diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/java/org/apache/cassandra/service/RepairCallback.java b/src/java/org/apache/cassandra/service/RepairCallback.java
index 6242b5a8..e1a925ef 100644
--- a/src/java/org/apache/cassandra/service/RepairCallback.java
+++ b/src/java/org/apache/cassandra/service/RepairCallback.java
@@ -1,83 +1,83 @@
package org.apache.cassandra.service;
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
import java.io.IOException;
import java.net.InetAddress;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.net.IAsyncCallback;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.utils.SimpleCondition;
public class RepairCallback<T> implements IAsyncCallback
{
private final IResponseResolver<T> resolver;
private final List<InetAddress> endpoints;
private final SimpleCondition condition = new SimpleCondition();
private final long startTime;
/**
* The main difference between this and ReadCallback is, ReadCallback has a ConsistencyLevel
* it needs to achieve. Repair on the other hand is happy to repair whoever replies within the timeout.
*
* (The other main difference of course is, this is only created once we know we have a digest
* mismatch, and we're going to do full-data reads from everyone -- that is, this is the final
* stage in the read process.)
*/
public RepairCallback(IResponseResolver<T> resolver, List<InetAddress> endpoints)
{
this.resolver = resolver;
this.endpoints = endpoints;
this.startTime = System.currentTimeMillis();
}
public T get() throws TimeoutException, DigestMismatchException, IOException
{
long timeout = DatabaseDescriptor.getRpcTimeout() - (System.currentTimeMillis() - startTime);
try
{
condition.await(timeout, TimeUnit.MILLISECONDS);
}
catch (InterruptedException ex)
{
throw new AssertionError(ex);
}
- return resolver.isDataPresent() ? resolver.resolve() : null;
+ return resolver.getMessageCount() > 0 ? resolver.resolve() : null;
}
public void response(Message message)
{
resolver.preprocess(message);
if (resolver.getMessageCount() == endpoints.size())
condition.signal();
}
public boolean isLatencyForSnitch()
{
return true;
}
}
| true | true | public T get() throws TimeoutException, DigestMismatchException, IOException
{
long timeout = DatabaseDescriptor.getRpcTimeout() - (System.currentTimeMillis() - startTime);
try
{
condition.await(timeout, TimeUnit.MILLISECONDS);
}
catch (InterruptedException ex)
{
throw new AssertionError(ex);
}
return resolver.isDataPresent() ? resolver.resolve() : null;
}
| public T get() throws TimeoutException, DigestMismatchException, IOException
{
long timeout = DatabaseDescriptor.getRpcTimeout() - (System.currentTimeMillis() - startTime);
try
{
condition.await(timeout, TimeUnit.MILLISECONDS);
}
catch (InterruptedException ex)
{
throw new AssertionError(ex);
}
return resolver.getMessageCount() > 0 ? resolver.resolve() : null;
}
|
diff --git a/src/org/ebookdroid/core/PageTreeNode.java b/src/org/ebookdroid/core/PageTreeNode.java
index 388d9758..bffd7c9f 100644
--- a/src/org/ebookdroid/core/PageTreeNode.java
+++ b/src/org/ebookdroid/core/PageTreeNode.java
@@ -1,515 +1,515 @@
package org.ebookdroid.core;
import org.ebookdroid.core.IDocumentViewController.InvalidateSizeReason;
import org.ebookdroid.core.bitmaps.BitmapManager;
import org.ebookdroid.core.bitmaps.BitmapRef;
import org.ebookdroid.core.codec.CodecPage;
import org.ebookdroid.core.crop.PageCropper;
import org.ebookdroid.core.models.DecodingProgressModel;
import org.ebookdroid.core.models.DocumentModel;
import org.ebookdroid.core.settings.SettingsManager;
import org.ebookdroid.utils.LengthUtils;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
public class PageTreeNode implements DecodeService.DecodeCallback {
// private static final LogContext LCTX = LogContext.ROOT.lctx("Imaging");
final Page page;
final PageTreeNode parent;
final long id;
final String shortId;
final AtomicBoolean decodingNow = new AtomicBoolean();
final BitmapHolder holder = new BitmapHolder();
final float childrenZoomThreshold;
final RectF pageSliceBounds;
final Matrix matrix = new Matrix();
float bitmapZoom = 1;
boolean hasChildren = false;
private boolean cropped;
RectF croppedBounds = null;
PageTreeNode(final Page page, final PageTreeNode parent, final long id, final RectF localPageSliceBounds,
final float childrenZoomThreshold) {
this.id = id;
this.shortId = page.index.viewIndex + ":" + id;
this.parent = parent;
this.pageSliceBounds = evaluatePageSliceBounds(localPageSliceBounds, parent);
this.croppedBounds = evaluateCroppedPageSliceBounds(localPageSliceBounds, parent);
this.page = page;
this.childrenZoomThreshold = childrenZoomThreshold;
}
public void recycle(final List<BitmapRef> bitmapsToRecycle) {
stopDecodingThisNode("node recycling");
holder.recycle(bitmapsToRecycle);
hasChildren = page.nodes.recycleChildren(this, bitmapsToRecycle);
}
public boolean onZoomChanged(final float oldZoom, final ViewState viewState, boolean committed,
final RectF pageBounds, final List<PageTreeNode> nodesToDecode, final List<BitmapRef> bitmapsToRecycle) {
if (!viewState.isNodeKeptInMemory(this, pageBounds)) {
recycle(bitmapsToRecycle);
return false;
}
final boolean childrenRequired = isChildrenRequired(viewState);
PageTreeNode[] children = page.nodes.getChildren(this);
if (viewState.zoom < oldZoom) {
if (!childrenRequired) {
if (LengthUtils.isNotEmpty(children)) {
hasChildren = page.nodes.recycleChildren(this, bitmapsToRecycle);
}
if (viewState.isNodeVisible(this, pageBounds) && getBitmap() == null) {
decodePageTreeNode(nodesToDecode, viewState);
}
}
return true;
}
if (childrenRequired) {
if (LengthUtils.isEmpty(children)) {
hasChildren = true;
if (id != 0 || viewState.decodeMode == DecodeMode.LOW_MEMORY) {
stopDecodingThisNode("children created");
}
children = page.nodes.createChildren(this, calculateChildThreshold());
}
for (final PageTreeNode child : children) {
child.onZoomChanged(oldZoom, viewState, committed, pageBounds, nodesToDecode, bitmapsToRecycle);
}
return true;
}
if (isReDecodingRequired(committed, viewState)) {
stopDecodingThisNode("Zoom changed");
decodePageTreeNode(nodesToDecode, viewState);
} else if (getBitmap() == null) {
decodePageTreeNode(nodesToDecode, viewState);
}
return true;
}
private boolean isReDecodingRequired(final boolean committed, final ViewState viewState) {
return (committed && viewState.zoom != bitmapZoom) || viewState.zoom > 1.2 * bitmapZoom;
}
protected float calculateChildThreshold() {
return childrenZoomThreshold * childrenZoomThreshold;
}
public boolean onPositionChanged(final ViewState viewState, final RectF pageBounds,
final List<PageTreeNode> nodesToDecode, final List<BitmapRef> bitmapsToRecycle) {
if (!viewState.isNodeKeptInMemory(this, pageBounds)) {
recycle(bitmapsToRecycle);
return false;
}
final boolean childrenRequired = isChildrenRequired(viewState);
PageTreeNode[] children = page.nodes.getChildren(this);
if (LengthUtils.isNotEmpty(children)) {
for (final PageTreeNode child : children) {
child.onPositionChanged(viewState, pageBounds, nodesToDecode, bitmapsToRecycle);
}
return true;
}
if (childrenRequired) {
hasChildren = true;
if (id != 0 || viewState.decodeMode == DecodeMode.LOW_MEMORY) {
stopDecodingThisNode("children created");
}
children = page.nodes.createChildren(this, calculateChildThreshold());
for (final PageTreeNode child : children) {
child.onPositionChanged(viewState, pageBounds, nodesToDecode, bitmapsToRecycle);
}
return true;
}
if (getBitmap() == null) {
decodePageTreeNode(nodesToDecode, viewState);
}
return true;
}
protected void onChildLoaded(final PageTreeNode child, final ViewState viewState, final RectF bounds,
final List<BitmapRef> bitmapsToRecycle) {
if (viewState.decodeMode == DecodeMode.LOW_MEMORY) {
if (page.nodes.isHiddenByChildren(this, viewState, bounds)) {
holder.clearDirectRef(bitmapsToRecycle);
}
}
}
protected boolean isChildrenRequired(final ViewState viewState) {
if (viewState.decodeMode == DecodeMode.NATIVE_RESOLUTION) {
return false;
}
if (viewState.decodeMode == DecodeMode.NORMAL) {
return viewState.zoom > childrenZoomThreshold;
}
final Rect rect = page.base.getDecodeService().getScaledSize(viewState.realRect.width(), page.bounds.width(),
page.bounds.height(), pageSliceBounds, viewState.zoom, page.getTargetRectScale());
final long size = BitmapManager.getBitmapBufferSize(getBitmap(), rect);
return size >= SettingsManager.getAppSettings().getMaxImageSize();
}
protected void decodePageTreeNode(final List<PageTreeNode> nodesToDecode, ViewState viewState) {
if (setDecodingNow(true)) {
bitmapZoom = viewState.zoom;
nodesToDecode.add(this);
}
}
@Override
public void decodeComplete(final CodecPage codecPage, final BitmapRef bitmap, final Rect bitmapBounds) {
if (bitmap == null || bitmapBounds == null) {
return;
}
if (SettingsManager.getBookSettings().cropPages) {
if (id == 0 && !cropped) {
croppedBounds = PageCropper.getCropBounds(bitmap, bitmapBounds, pageSliceBounds);
cropped = true;
System.out.println("Cropped bounds:" + croppedBounds);
BitmapManager.release(bitmap);
page.base.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
setDecodingNow(false);
page.base.getDecodeService().decodePage(new ViewState(PageTreeNode.this), PageTreeNode.this,
croppedBounds);
}
});
return;
}
}
page.base.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
holder.setBitmap(bitmap, bitmapBounds);
setDecodingNow(false);
final IDocumentViewController dc = page.base.getDocumentController();
final DocumentModel dm = page.base.getDocumentModel();
if (dc != null && dm != null) {
final boolean changed = page.setAspectRatio(bitmapBounds.width(), bitmapBounds.height());
ViewState viewState = new ViewState(dc);
if (changed) {
dc.invalidatePageSizes(InvalidateSizeReason.PAGE_LOADED, page);
- viewState = dc.updatePageVisibility(page.index.viewIndex, 0, viewState.zoom);
+ viewState = dc.updatePageVisibility(dm.getCurrentViewPageIndex(), 0, viewState.zoom);
}
final RectF bounds = viewState.getBounds(page);
if (parent != null) {
final List<BitmapRef> bitmapsToRecycle = new ArrayList<BitmapRef>(2);
parent.onChildLoaded(PageTreeNode.this, viewState, bounds, bitmapsToRecycle);
BitmapManager.release(bitmapsToRecycle);
}
if (viewState.isNodeVisible(PageTreeNode.this, bounds)) {
dc.redrawView(viewState);
}
}
}
});
}
private boolean setDecodingNow(final boolean decodingNow) {
if (this.decodingNow.compareAndSet(!decodingNow, decodingNow)) {
final DecodingProgressModel dpm = page.base.getDecodingProgressModel();
if (dpm != null) {
if (decodingNow) {
dpm.increase();
} else {
dpm.decrease();
}
}
return true;
}
return false;
}
private void stopDecodingThisNode(final String reason) {
if (setDecodingNow(false)) {
final DecodeService ds = page.base.getDecodeService();
if (ds != null) {
ds.stopDecoding(this, reason);
}
}
}
void draw(final Canvas canvas, final ViewState viewState, final RectF pageBounds, final PagePaint paint) {
final RectF tr = getTargetRect(viewState.viewRect, pageBounds);
if (!viewState.isNodeVisible(this, pageBounds)) {
return;
}
final Bitmap bitmap = viewState.nightMode ? holder.getNightBitmap(paint.nightBitmapPaint) : holder.getBitmap();
if (bitmap != null) {
canvas.drawBitmap(bitmap, holder.getBitmapBounds(), tr, paint.bitmapPaint);
}
drawBrightnessFilter(canvas, tr);
drawChildren(canvas, viewState, pageBounds, paint);
}
void drawBrightnessFilter(final Canvas canvas, final RectF tr) {
final int brightness = SettingsManager.getAppSettings().getBrightness();
if (brightness < 100) {
final Paint p = new Paint();
p.setColor(Color.BLACK);
p.setAlpha(255 - brightness * 255 / 100);
canvas.drawRect(tr, p);
}
}
void drawChildren(final Canvas canvas, final ViewState viewState, final RectF pageBounds, final PagePaint paint) {
for (final PageTreeNode child : page.nodes.getChildren(this)) {
child.draw(canvas, viewState, pageBounds, paint);
}
}
public RectF getTargetRect(final RectF viewRect, final RectF pageBounds) {
matrix.reset();
final RectF bounds = new RectF(pageBounds);
bounds.offset(-viewRect.left, -viewRect.top);
matrix.postScale(bounds.width() * page.getTargetRectScale(), bounds.height());
matrix.postTranslate(bounds.left - bounds.width() * page.getTargetTranslate(), bounds.top);
final RectF targetRectF = new RectF();
matrix.mapRect(targetRectF, pageSliceBounds);
return new RectF(targetRectF);
}
public RectF getTargetCroppedRect(final RectF viewRect, final RectF pageBounds) {
matrix.reset();
final RectF bounds = new RectF(pageBounds);
bounds.offset(-viewRect.left, -viewRect.top);
matrix.postScale(bounds.width() * page.getTargetRectScale(), bounds.height());
matrix.postTranslate(bounds.left - bounds.width() * page.getTargetTranslate(), bounds.top);
final RectF targetRectF = new RectF();
matrix.mapRect(targetRectF, croppedBounds);
return new RectF(targetRectF);
}
public IViewerActivity getBase() {
return page.base;
}
/**
* Gets the parent node.
*
* @return the parent node
*/
public PageTreeNode getParent() {
return parent;
}
public RectF getPageSliceBounds() {
return pageSliceBounds;
}
public int getPageIndex() {
return page.index.viewIndex;
}
public Bitmap getBitmap() {
return holder.getBitmap();
}
@Override
public int hashCode() {
return (page == null) ? 0 : page.index.viewIndex;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof PageTreeNode) {
final PageTreeNode that = (PageTreeNode) obj;
if (this.page == null) {
return that.page == null;
}
return this.page.index.viewIndex == that.page.index.viewIndex
&& this.pageSliceBounds.equals(that.pageSliceBounds);
}
return false;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder("PageTreeNode");
buf.append("[");
buf.append("id").append("=").append(page.index.viewIndex).append(":").append(id);
buf.append(", ");
buf.append("rect").append("=").append(this.pageSliceBounds);
buf.append(", ");
buf.append("hasBitmap").append("=").append(getBitmap() != null);
buf.append("]");
return buf.toString();
}
public String getFullId() {
return page.index + ":" + id;
}
public int getDocumentPageIndex() {
return page.index.docIndex;
}
private static RectF evaluatePageSliceBounds(final RectF localPageSliceBounds, final PageTreeNode parent) {
if (parent == null) {
return localPageSliceBounds;
}
final Matrix matrix = new Matrix();
matrix.postScale(parent.pageSliceBounds.width(), parent.pageSliceBounds.height());
matrix.postTranslate(parent.pageSliceBounds.left, parent.pageSliceBounds.top);
final RectF sliceBounds = new RectF();
matrix.mapRect(sliceBounds, localPageSliceBounds);
return sliceBounds;
}
private static RectF evaluateCroppedPageSliceBounds(final RectF localPageSliceBounds, final PageTreeNode parent) {
if (parent == null) {
return null;
}
if (parent.croppedBounds == null) {
return null;
}
final Matrix matrix = new Matrix();
matrix.postScale(parent.croppedBounds.width(), parent.croppedBounds.height());
matrix.postTranslate(parent.croppedBounds.left, parent.croppedBounds.top);
final RectF sliceBounds = new RectF();
matrix.mapRect(sliceBounds, localPageSliceBounds);
return sliceBounds;
}
class BitmapHolder {
BitmapRef bitmap;
BitmapRef night;
Rect bounds;
public synchronized Bitmap getBitmap() {
final Bitmap bmp = bitmap != null ? bitmap.getBitmap() : null;
if (bmp == null || bmp.isRecycled()) {
if (bitmap != null) {
BitmapManager.release(bitmap);
bitmap = null;
}
}
return bmp;
}
public synchronized Rect getBitmapBounds() {
return bounds;
}
public synchronized Bitmap getNightBitmap(final Paint paint) {
Bitmap bmp = null;
if (night != null) {
bmp = night.getBitmap();
if (bmp == null || bmp.isRecycled()) {
BitmapManager.release(night);
night = null;
}
return bmp;
}
bmp = getBitmap();
if (bmp == null || bmp.isRecycled()) {
return null;
}
this.night = BitmapManager.getBitmap(bmp.getWidth(), bmp.getHeight(), Bitmap.Config.RGB_565);
final Canvas c = new Canvas(night.getBitmap());
c.drawRect(0, 0, bmp.getWidth(), bmp.getHeight(), PagePaint.NIGHT.fillPaint);
c.drawBitmap(bmp, 0, 0, paint);
bitmap.clearDirectRef();
return night.getBitmap();
}
public synchronized void clearDirectRef(final List<BitmapRef> bitmapsToRecycle) {
if (bitmap != null) {
bitmap.clearDirectRef();
}
if (night != null) {
night.clearDirectRef();
}
}
public synchronized void recycle(final List<BitmapRef> bitmapsToRecycle) {
if (bitmap != null) {
if (bitmapsToRecycle != null) {
bitmapsToRecycle.add(bitmap);
} else {
BitmapManager.release(bitmap);
}
bitmap = null;
}
if (night != null) {
if (bitmapsToRecycle != null) {
bitmapsToRecycle.add(night);
} else {
BitmapManager.release(night);
}
night = null;
}
}
public synchronized void setBitmap(final BitmapRef ref, final Rect bitmapBounds) {
if (ref == null) {
return;
}
this.bounds = bitmapBounds;
final List<BitmapRef> bitmapsToRecycle = new ArrayList<BitmapRef>(2);
recycle(bitmapsToRecycle);
BitmapManager.release(bitmapsToRecycle);
this.bitmap = ref;
}
}
}
| true | true | public void decodeComplete(final CodecPage codecPage, final BitmapRef bitmap, final Rect bitmapBounds) {
if (bitmap == null || bitmapBounds == null) {
return;
}
if (SettingsManager.getBookSettings().cropPages) {
if (id == 0 && !cropped) {
croppedBounds = PageCropper.getCropBounds(bitmap, bitmapBounds, pageSliceBounds);
cropped = true;
System.out.println("Cropped bounds:" + croppedBounds);
BitmapManager.release(bitmap);
page.base.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
setDecodingNow(false);
page.base.getDecodeService().decodePage(new ViewState(PageTreeNode.this), PageTreeNode.this,
croppedBounds);
}
});
return;
}
}
page.base.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
holder.setBitmap(bitmap, bitmapBounds);
setDecodingNow(false);
final IDocumentViewController dc = page.base.getDocumentController();
final DocumentModel dm = page.base.getDocumentModel();
if (dc != null && dm != null) {
final boolean changed = page.setAspectRatio(bitmapBounds.width(), bitmapBounds.height());
ViewState viewState = new ViewState(dc);
if (changed) {
dc.invalidatePageSizes(InvalidateSizeReason.PAGE_LOADED, page);
viewState = dc.updatePageVisibility(page.index.viewIndex, 0, viewState.zoom);
}
final RectF bounds = viewState.getBounds(page);
if (parent != null) {
final List<BitmapRef> bitmapsToRecycle = new ArrayList<BitmapRef>(2);
parent.onChildLoaded(PageTreeNode.this, viewState, bounds, bitmapsToRecycle);
BitmapManager.release(bitmapsToRecycle);
}
if (viewState.isNodeVisible(PageTreeNode.this, bounds)) {
dc.redrawView(viewState);
}
}
}
});
}
| public void decodeComplete(final CodecPage codecPage, final BitmapRef bitmap, final Rect bitmapBounds) {
if (bitmap == null || bitmapBounds == null) {
return;
}
if (SettingsManager.getBookSettings().cropPages) {
if (id == 0 && !cropped) {
croppedBounds = PageCropper.getCropBounds(bitmap, bitmapBounds, pageSliceBounds);
cropped = true;
System.out.println("Cropped bounds:" + croppedBounds);
BitmapManager.release(bitmap);
page.base.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
setDecodingNow(false);
page.base.getDecodeService().decodePage(new ViewState(PageTreeNode.this), PageTreeNode.this,
croppedBounds);
}
});
return;
}
}
page.base.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
holder.setBitmap(bitmap, bitmapBounds);
setDecodingNow(false);
final IDocumentViewController dc = page.base.getDocumentController();
final DocumentModel dm = page.base.getDocumentModel();
if (dc != null && dm != null) {
final boolean changed = page.setAspectRatio(bitmapBounds.width(), bitmapBounds.height());
ViewState viewState = new ViewState(dc);
if (changed) {
dc.invalidatePageSizes(InvalidateSizeReason.PAGE_LOADED, page);
viewState = dc.updatePageVisibility(dm.getCurrentViewPageIndex(), 0, viewState.zoom);
}
final RectF bounds = viewState.getBounds(page);
if (parent != null) {
final List<BitmapRef> bitmapsToRecycle = new ArrayList<BitmapRef>(2);
parent.onChildLoaded(PageTreeNode.this, viewState, bounds, bitmapsToRecycle);
BitmapManager.release(bitmapsToRecycle);
}
if (viewState.isNodeVisible(PageTreeNode.this, bounds)) {
dc.redrawView(viewState);
}
}
}
});
}
|
diff --git a/conan-atlas-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/atlas/PerlExperimentEligibilityCheckingProcess.java b/conan-atlas-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/atlas/PerlExperimentEligibilityCheckingProcess.java
index 1e5a07e..cb9c2fe 100755
--- a/conan-atlas-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/atlas/PerlExperimentEligibilityCheckingProcess.java
+++ b/conan-atlas-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/atlas/PerlExperimentEligibilityCheckingProcess.java
@@ -1,100 +1,100 @@
package uk.ac.ebi.fgpt.conan.process.atlas;
import net.sourceforge.fluxion.spi.ServiceProvider;
import uk.ac.ebi.fgpt.conan.ae.AccessionParameter;
import uk.ac.ebi.fgpt.conan.lsf.AbstractLSFProcess;
import uk.ac.ebi.fgpt.conan.lsf.LSFProcess;
import uk.ac.ebi.fgpt.conan.model.ConanParameter;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
/**
* Conan process to check experiment for eligibility for
* the Expression Atlas.
*
* @author Amy Tang
* @date 25-Apr-2013
*/
@ServiceProvider
public class PerlExperimentEligibilityCheckingProcess extends AbstractLSFProcess {
private final Collection<ConanParameter> parameters;
private final AccessionParameter accessionParameter;
public PerlExperimentEligibilityCheckingProcess() {
parameters = new ArrayList<ConanParameter>();
accessionParameter = new AccessionParameter();
parameters.add(accessionParameter);
// setQueueName("production");
}
public String getName() {
return "atlas eligibility";
}
public Collection<ConanParameter> getParameters() {
return parameters;
}
protected String getComponentName() {
return LSFProcess.UNSPECIFIED_COMPONENT_NAME;
}
protected String getCommand(Map<ConanParameter, String> parameters) throws IllegalArgumentException {
getLog().debug("Executing " + getName() + " with the following parameters: " + parameters.toString());
// deal with parameters
AccessionParameter accession = new AccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
if (accession.getAccession() == null) {
throw new IllegalArgumentException("Accession cannot be null");
}
else {
if (accession.isExperiment()) {
// main command to execute perl script
// Writing back to production Subs Tracking database
String mainCommand = "cd " + accession.getFile().getParentFile().getAbsolutePath() + "; " +
- "perl /ebi/microarray/home/fgpt/sw/lib/perl/Red_Hat/check_atlas_eligibility.pl -w -a " +
+ "perl /ebi/microarray/home/fgpt/sw/lib/perl/FGPT_RH_prod/check_atlas_eligibility.pl -w -a " +
accession.getAccession();
// Testing script without writing anything back to production submissions tracking database
/*String mainCommand = "cd " + accession.getFile().getParentFile().getAbsolutePath() + "; " +
"perl /ebi/microarray/home/fgpt/sw/lib/perl/FGPT_RH_prod/check_atlas_eligibility.pl";
*/
// path to relevant file
String filePath = accession.getFile().getAbsolutePath();
// return command string
return mainCommand + " -i " + filePath;
}
else {
throw new IllegalArgumentException("Cannot run atlas eligibility checks for Arrays");
}
}
}
protected String getLSFOutputFilePath(Map<ConanParameter, String> parameters)
throws IllegalArgumentException {
// deal with parameters
AccessionParameter accession = new AccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
if (accession.getAccession() == null) {
throw new IllegalArgumentException("Accession cannot be null");
}
else {
// get the mageFile parent directory
final File parentDir = accession.getFile().getAbsoluteFile().getParentFile();
// files to write output to
final File outputDir = new File(parentDir, ".conan");
// lsf output file
return new File(outputDir, "atlas_eligibility.lsfoutput.txt").getAbsolutePath();
}
}
}
| true | true | protected String getCommand(Map<ConanParameter, String> parameters) throws IllegalArgumentException {
getLog().debug("Executing " + getName() + " with the following parameters: " + parameters.toString());
// deal with parameters
AccessionParameter accession = new AccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
if (accession.getAccession() == null) {
throw new IllegalArgumentException("Accession cannot be null");
}
else {
if (accession.isExperiment()) {
// main command to execute perl script
// Writing back to production Subs Tracking database
String mainCommand = "cd " + accession.getFile().getParentFile().getAbsolutePath() + "; " +
"perl /ebi/microarray/home/fgpt/sw/lib/perl/Red_Hat/check_atlas_eligibility.pl -w -a " +
accession.getAccession();
// Testing script without writing anything back to production submissions tracking database
/*String mainCommand = "cd " + accession.getFile().getParentFile().getAbsolutePath() + "; " +
"perl /ebi/microarray/home/fgpt/sw/lib/perl/FGPT_RH_prod/check_atlas_eligibility.pl";
*/
// path to relevant file
String filePath = accession.getFile().getAbsolutePath();
// return command string
return mainCommand + " -i " + filePath;
}
else {
throw new IllegalArgumentException("Cannot run atlas eligibility checks for Arrays");
}
}
}
| protected String getCommand(Map<ConanParameter, String> parameters) throws IllegalArgumentException {
getLog().debug("Executing " + getName() + " with the following parameters: " + parameters.toString());
// deal with parameters
AccessionParameter accession = new AccessionParameter();
accession.setAccession(parameters.get(accessionParameter));
if (accession.getAccession() == null) {
throw new IllegalArgumentException("Accession cannot be null");
}
else {
if (accession.isExperiment()) {
// main command to execute perl script
// Writing back to production Subs Tracking database
String mainCommand = "cd " + accession.getFile().getParentFile().getAbsolutePath() + "; " +
"perl /ebi/microarray/home/fgpt/sw/lib/perl/FGPT_RH_prod/check_atlas_eligibility.pl -w -a " +
accession.getAccession();
// Testing script without writing anything back to production submissions tracking database
/*String mainCommand = "cd " + accession.getFile().getParentFile().getAbsolutePath() + "; " +
"perl /ebi/microarray/home/fgpt/sw/lib/perl/FGPT_RH_prod/check_atlas_eligibility.pl";
*/
// path to relevant file
String filePath = accession.getFile().getAbsolutePath();
// return command string
return mainCommand + " -i " + filePath;
}
else {
throw new IllegalArgumentException("Cannot run atlas eligibility checks for Arrays");
}
}
}
|
diff --git a/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/plotting/SidePlotUtils.java b/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/plotting/SidePlotUtils.java
index 9fe1994..b99e7c5 100644
--- a/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/plotting/SidePlotUtils.java
+++ b/uk.ac.diamond.scisoft.analysis.rcp/src/uk/ac/diamond/scisoft/analysis/rcp/plotting/SidePlotUtils.java
@@ -1,91 +1,91 @@
/*
* Copyright 2012 Diamond Light Source Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.diamond.scisoft.analysis.rcp.plotting;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.diamond.scisoft.analysis.rcp.views.SidePlotView;
public class SidePlotUtils {
private static final Logger logger = LoggerFactory.getLogger(SidePlotUtils.class);
/**
* Attempts to find the side plot view and logs errors if not
* rather than throwing exceptions.
* @param page
* @param plotViewID
* @return SidePlotView
*/
public static SidePlotView getSidePlotView(final IWorkbenchPage page,
final String plotViewID) {
//if (PlatformUI.getWorkbench().isStarting()) throw new IllegalStateException("Workbench is starting!");
SidePlotView sidePlotView = null;
// necessary for multiple SPVs
try {
// Cannot use the findView(...) because of some side plot initiation madness.
//sidePlotView = (SidePlotView) page.findView("uk.ac.diamond.scisoft.analysis.rcp.views.SidePlotView");
//if (sidePlotView==null) {
sidePlotView = (SidePlotView) page.showView(SidePlotView.ID,
plotViewID, IWorkbenchPage.VIEW_CREATE);
//}
} catch (PartInitException e) {
logger.warn("Could not find side plot ",e);
}
if (sidePlotView == null) {
- logger.error("Cannot find side plot");
+// logger.error("Cannot find side plot");
throw new IllegalStateException("Cannot find side plot");
}
return sidePlotView;
}
public static void bringToTop(final IWorkbenchPage activePage, final IWorkbenchPart part) {
if (part.getSite().getShell().isDisposed()) return;
// activating the view stops the rogue toolbars appearing
// these could also be avoided by moving the toolbars to
// eclipse configured things.
try {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
activePage.bringToTop(part);
}
});
} catch (Exception ne) {
logger.error("Cannot acivate plot "+part.getTitle(), ne);
}
}
}
| true | true | public static SidePlotView getSidePlotView(final IWorkbenchPage page,
final String plotViewID) {
//if (PlatformUI.getWorkbench().isStarting()) throw new IllegalStateException("Workbench is starting!");
SidePlotView sidePlotView = null;
// necessary for multiple SPVs
try {
// Cannot use the findView(...) because of some side plot initiation madness.
//sidePlotView = (SidePlotView) page.findView("uk.ac.diamond.scisoft.analysis.rcp.views.SidePlotView");
//if (sidePlotView==null) {
sidePlotView = (SidePlotView) page.showView(SidePlotView.ID,
plotViewID, IWorkbenchPage.VIEW_CREATE);
//}
} catch (PartInitException e) {
logger.warn("Could not find side plot ",e);
}
if (sidePlotView == null) {
logger.error("Cannot find side plot");
throw new IllegalStateException("Cannot find side plot");
}
return sidePlotView;
}
| public static SidePlotView getSidePlotView(final IWorkbenchPage page,
final String plotViewID) {
//if (PlatformUI.getWorkbench().isStarting()) throw new IllegalStateException("Workbench is starting!");
SidePlotView sidePlotView = null;
// necessary for multiple SPVs
try {
// Cannot use the findView(...) because of some side plot initiation madness.
//sidePlotView = (SidePlotView) page.findView("uk.ac.diamond.scisoft.analysis.rcp.views.SidePlotView");
//if (sidePlotView==null) {
sidePlotView = (SidePlotView) page.showView(SidePlotView.ID,
plotViewID, IWorkbenchPage.VIEW_CREATE);
//}
} catch (PartInitException e) {
logger.warn("Could not find side plot ",e);
}
if (sidePlotView == null) {
// logger.error("Cannot find side plot");
throw new IllegalStateException("Cannot find side plot");
}
return sidePlotView;
}
|
diff --git a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/servlet/TestHostnameFilter.java b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/servlet/TestHostnameFilter.java
index f30ab0c0c..f3a2a5ad6 100644
--- a/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/servlet/TestHostnameFilter.java
+++ b/hadoop-hdfs-project/hadoop-hdfs-httpfs/src/test/java/org/apache/hadoop/lib/servlet/TestHostnameFilter.java
@@ -1,64 +1,64 @@
/**
* 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.hadoop.lib.servlet;
import junit.framework.Assert;
import org.apache.hadoop.test.HTestCase;
import org.junit.Test;
import org.mockito.Mockito;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
public class TestHostnameFilter extends HTestCase {
@Test
public void hostname() throws Exception {
ServletRequest request = Mockito.mock(ServletRequest.class);
Mockito.when(request.getRemoteAddr()).thenReturn("localhost");
ServletResponse response = Mockito.mock(ServletResponse.class);
final AtomicBoolean invoked = new AtomicBoolean();
FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
- Assert.assertEquals(HostnameFilter.get(), "localhost");
+ Assert.assertTrue(HostnameFilter.get().contains("localhost"));
invoked.set(true);
}
};
Filter filter = new HostnameFilter();
filter.init(null);
Assert.assertNull(HostnameFilter.get());
filter.doFilter(request, response, chain);
Assert.assertTrue(invoked.get());
Assert.assertNull(HostnameFilter.get());
filter.destroy();
}
}
| true | true | public void hostname() throws Exception {
ServletRequest request = Mockito.mock(ServletRequest.class);
Mockito.when(request.getRemoteAddr()).thenReturn("localhost");
ServletResponse response = Mockito.mock(ServletResponse.class);
final AtomicBoolean invoked = new AtomicBoolean();
FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
Assert.assertEquals(HostnameFilter.get(), "localhost");
invoked.set(true);
}
};
Filter filter = new HostnameFilter();
filter.init(null);
Assert.assertNull(HostnameFilter.get());
filter.doFilter(request, response, chain);
Assert.assertTrue(invoked.get());
Assert.assertNull(HostnameFilter.get());
filter.destroy();
}
| public void hostname() throws Exception {
ServletRequest request = Mockito.mock(ServletRequest.class);
Mockito.when(request.getRemoteAddr()).thenReturn("localhost");
ServletResponse response = Mockito.mock(ServletResponse.class);
final AtomicBoolean invoked = new AtomicBoolean();
FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
Assert.assertTrue(HostnameFilter.get().contains("localhost"));
invoked.set(true);
}
};
Filter filter = new HostnameFilter();
filter.init(null);
Assert.assertNull(HostnameFilter.get());
filter.doFilter(request, response, chain);
Assert.assertTrue(invoked.get());
Assert.assertNull(HostnameFilter.get());
filter.destroy();
}
|
diff --git a/src/edu/uc/cs/distsys/ui/NodeStatusViewThread.java b/src/edu/uc/cs/distsys/ui/NodeStatusViewThread.java
index f3da9f4..6958eea 100644
--- a/src/edu/uc/cs/distsys/ui/NodeStatusViewThread.java
+++ b/src/edu/uc/cs/distsys/ui/NodeStatusViewThread.java
@@ -1,90 +1,92 @@
package edu.uc.cs.distsys.ui;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import edu.uc.cs.distsys.Node;
public class NodeStatusViewThread implements Runnable {
private JFrame viewFrame;
private NodeStatusView nodeStatusView;
private Node node;
private String defaultTitle = "Node Status View - Node ID: ";
public NodeStatusViewThread(Node n) {
this.node = n;
this.defaultTitle += this.node.getId();
//Create and setup the windows
viewFrame = new JFrame(this.defaultTitle);
viewFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
nodeStatusView = new NodeStatusView();
//Force the first update
this.getNodeStatusView().getNodePropertiesTableStorage().setNode(this.node);
//Set the listener for when a user clicks a given node to update appropriately
this.getNodeStatusView().getNodeTable().addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent evnt) {
if (evnt.getClickCount() == 1) {
int row = getNodeStatusView().getNodeTable().getSelectedRow();
- Node clickedNode = getNodeStatusView().getNodeTableStorage().getNodeAtRow(row);
- System.out.println("Clicked node: " + clickedNode.toString());
- // set the new data
- getNodeStatusView().getClickedNodeTableStorage().setNode(clickedNode);
- // force the UI update
- getNodeStatusView().getClickedNodeTableStorage().fireTableDataChanged();
+ if (row != -1) {
+ Node clickedNode = getNodeStatusView().getNodeTableStorage().getNodeAtRow(row);
+ System.out.println("Clicked node: " + clickedNode.toString());
+ // set the new data
+ getNodeStatusView().getClickedNodeTableStorage().setNode(clickedNode);
+ // force the UI update
+ getNodeStatusView().getClickedNodeTableStorage().fireTableDataChanged();
+ }
}
}
});
}
@Override
public void run() {
//Create and setup the content pane
nodeStatusView.setOpaque(true); // apparently you always have to set this true
viewFrame.setContentPane(nodeStatusView);
// Display the window
viewFrame.pack();
viewFrame.setVisible(true);
}
public JFrame getViewFrame() {
return viewFrame;
}
public void setViewFrame(JFrame viewFrame) {
this.viewFrame = viewFrame;
}
public NodeStatusView getNodeStatusView() {
return nodeStatusView;
}
public void setNodeStatusView(NodeStatusView nodeStatusView) {
this.nodeStatusView = nodeStatusView;
}
public int getNodeID() {
return node.getId();
}
public void updateUI() {
this.getNodeStatusView().getNodeTableStorage().fireTableDataChanged();
this.getNodeStatusView().getNodePropertiesTableStorage().fireTableDataChanged();
}
public void addMonitoredNode(Node n) {
this.getNodeStatusView().getNodeTableStorage().addItem(n);
}
public void setUIMessage(String uiMessage) {
if (uiMessage != null) {
this.viewFrame.setTitle(this.defaultTitle + " [" + uiMessage + "]");
} else {
this.viewFrame.setTitle(this.defaultTitle);
}
}
}
| true | true | public NodeStatusViewThread(Node n) {
this.node = n;
this.defaultTitle += this.node.getId();
//Create and setup the windows
viewFrame = new JFrame(this.defaultTitle);
viewFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
nodeStatusView = new NodeStatusView();
//Force the first update
this.getNodeStatusView().getNodePropertiesTableStorage().setNode(this.node);
//Set the listener for when a user clicks a given node to update appropriately
this.getNodeStatusView().getNodeTable().addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent evnt) {
if (evnt.getClickCount() == 1) {
int row = getNodeStatusView().getNodeTable().getSelectedRow();
Node clickedNode = getNodeStatusView().getNodeTableStorage().getNodeAtRow(row);
System.out.println("Clicked node: " + clickedNode.toString());
// set the new data
getNodeStatusView().getClickedNodeTableStorage().setNode(clickedNode);
// force the UI update
getNodeStatusView().getClickedNodeTableStorage().fireTableDataChanged();
}
}
});
}
| public NodeStatusViewThread(Node n) {
this.node = n;
this.defaultTitle += this.node.getId();
//Create and setup the windows
viewFrame = new JFrame(this.defaultTitle);
viewFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
nodeStatusView = new NodeStatusView();
//Force the first update
this.getNodeStatusView().getNodePropertiesTableStorage().setNode(this.node);
//Set the listener for when a user clicks a given node to update appropriately
this.getNodeStatusView().getNodeTable().addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent evnt) {
if (evnt.getClickCount() == 1) {
int row = getNodeStatusView().getNodeTable().getSelectedRow();
if (row != -1) {
Node clickedNode = getNodeStatusView().getNodeTableStorage().getNodeAtRow(row);
System.out.println("Clicked node: " + clickedNode.toString());
// set the new data
getNodeStatusView().getClickedNodeTableStorage().setNode(clickedNode);
// force the UI update
getNodeStatusView().getClickedNodeTableStorage().fireTableDataChanged();
}
}
}
});
}
|
diff --git a/site/src/main/java/org/soluvas/web/site/BehaviorTenantInjector.java b/site/src/main/java/org/soluvas/web/site/BehaviorTenantInjector.java
index a656e905..59e6cef2 100644
--- a/site/src/main/java/org/soluvas/web/site/BehaviorTenantInjector.java
+++ b/site/src/main/java/org/soluvas/web/site/BehaviorTenantInjector.java
@@ -1,196 +1,201 @@
package org.soluvas.web.site;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import javax.inject.Inject;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.wicket.Application;
import org.apache.wicket.Component;
import org.apache.wicket.Page;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.application.IComponentInstantiationListener;
import org.apache.wicket.core.request.handler.ListenerInterfaceRequestHandler;
import org.apache.wicket.core.request.handler.RenderPageRequestHandler;
import org.apache.wicket.core.request.mapper.StalePageException;
import org.apache.wicket.request.IRequestHandler;
import org.apache.wicket.request.cycle.AbstractRequestCycleListener;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.util.visit.IVisit;
import org.apache.wicket.util.visit.IVisitor;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.soluvas.commons.ReflectionUtils;
import org.soluvas.commons.inject.Filter;
import org.soluvas.commons.inject.Namespace;
import org.soluvas.commons.inject.Supplied;
import org.soluvas.commons.tenant.TenantRef;
import org.soluvas.web.site.osgi.WebTenantUtils;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
/**
* Injects Wicket {@link Component}s using {@link TenantInjectionBehavior}.
*
* Supported annotations are: {@link Inject}, {@link Namespace}, {@link Filter}, {@link Supplied}.
*
* The Wicket app's {@link Application#getApplicationKey()} must be {tenantId}_{tenantEnv}.
*
* @deprecated Our homegrown multitenancy support for Pax Wicket is unstable and too problematic. :(
* @author ceefour
*/
@Deprecated
public class BehaviorTenantInjector extends AbstractRequestCycleListener implements IComponentInstantiationListener {
public static final class InjectVisitor implements
IVisitor<Component, Void> {
@Override
public void component(Component component, IVisit<Void> visit) {
TenantInjectionBehavior injectionBehavior = Iterables.getFirst(
component.getBehaviors(TenantInjectionBehavior.class), null);
if (injectionBehavior != null) {
injectionBehavior.inject(component, "ajaxRequestTarget");
}
}
}
private static Logger log = LoggerFactory.getLogger(BehaviorTenantInjector.class);
@SuppressWarnings("rawtypes")
@Override
public void onInstantiation(Component component) {
final TenantRef tenant = WebTenantUtils.getTenant();
final String tenantId = tenant.getTenantId();
final String tenantEnv = tenant.getTenantEnv();
final List<Field> fields = ReflectionUtils.getAllFields(component.getClass());
final String componentId = component instanceof org.apache.wicket.Page ? component.getClass().getName() : component.getId();
final BundleContext bundleContext = Preconditions.checkNotNull(FrameworkUtil.getBundle(component.getClass()).getBundleContext(),
"Cannot get BundleContext for Wicket component %s %s", component.getClass().getName(), componentId);
boolean needBehavior = false;
for (Field field : fields) {
final Inject injectAnn = field.getAnnotation(Inject.class);
if (injectAnn == null)
continue;
final Supplied supplied = field.getAnnotation(Supplied.class);
if (supplied == null) {
needBehavior = true;
} else {
final Namespace namespaced = field.getAnnotation(Namespace.class);
final String namespace = namespaced != null ? namespaced.value() : null;
final String namespaceFilter = namespace != null ? "(namespace=" + namespace + ")" : "";
final Filter filtered = field.getAnnotation(Filter.class);
final String additionalFilter = filtered != null ? filtered.value() : "";
final Class<?> suppliedClass = field.getType();
log.trace("Field {}#{} needs Supplier<{}> for tenantId={} tenantEnv={} namespace={} filter: {}", new Object[] {
componentId, field.getName(), suppliedClass.getName(), tenantId, tenantEnv, namespace, additionalFilter });
final String suppliedClassFilter = supplied != null ? "(suppliedClass=" + field.getType().getName() + ")(layer=application)" : "";
- final String filter = "(&" + String.format("(|(tenantId=%s)(tenantId=\\*))(|(tenantEnv=%s)(tenantEnv=\\*))", tenantId, tenantEnv)
- + namespaceFilter + suppliedClassFilter + additionalFilter + ")";
+ // single-tenant for now
+// final String filter = "(&" + String.format("(|(tenantId=%s)(tenantId=\\*))(|(tenantEnv=%s)(tenantEnv=\\*))", tenantId, tenantEnv)
+// + namespaceFilter + suppliedClassFilter + additionalFilter + ")";
+ String filter = "(&" + namespaceFilter + suppliedClassFilter + additionalFilter + ")";
+ if ("(&)".equals(filter)) {
+ filter = null;
+ }
final Collection<ServiceReference<Supplier>> serviceRefs;
try {
serviceRefs = bundleContext.getServiceReferences(Supplier.class, filter);
} catch (InvalidSyntaxException e) {
throw new SiteException("Cannot inject " + componentId + "#" + field.getName() + ", invalid " +
suppliedClass.getName() + " Supplier service with filter " + filter, e);
}
if (serviceRefs == null || serviceRefs.isEmpty()) {
throw new SiteException("Cannot find " + suppliedClass.getName() + " supplier for " + componentId + "#" + field.getName() + ", " +
"Supplier with " + filter + " not found");
}
final ServiceReference<Supplier> serviceRef = serviceRefs.iterator().next();
final Supplier supplier = bundleContext.getService(serviceRef);
try {
final Object suppliedObj = supplier.get();
log.trace("Injecting {}#{} as {}", componentId, field.getName(), suppliedObj);
FieldUtils.writeField(field, component, suppliedObj, true);
} catch (Exception e) {
log.error("Cannot inject " + componentId + "#" + field.getName() + " from " + supplier, e);
throw new SiteException("Cannot inject " + componentId + "#" + field.getName() + " from " + supplier, e);
} finally {
bundleContext.ungetService(serviceRef);
}
}
}
if (needBehavior) {
final TenantInjectionBehavior behavior = new TenantInjectionBehavior(bundleContext, tenantId, tenantEnv);
behavior.inject(component, "onInstantiation"); // perform first injection
component.add( behavior );
}
}
@Override
public void onRequestHandlerResolved(RequestCycle cycle,
IRequestHandler handler) {
log.trace("onRequestHandlerResolved {} {}", handler.getClass(), handler);
try {
if (handler instanceof RenderPageRequestHandler) {
final RenderPageRequestHandler renderPageHandler = (RenderPageRequestHandler) handler;
if (renderPageHandler.isPageInstanceCreated()) {
final Page page = (Page) renderPageHandler.getPage();
injectPage(page);
}
// sometimes (?) inject was not run yet before Wicket calls beforeRender...
// but I can't reproduce it again (huh!)
} else if (handler instanceof ListenerInterfaceRequestHandler) {
final ListenerInterfaceRequestHandler listenerInterfaceHandler = (ListenerInterfaceRequestHandler) handler;
log.trace("onRequestHandlerResolved {} {} isPageInstanceCreated={}",
handler.getClass(), handler, listenerInterfaceHandler.isPageInstanceCreated());
if (listenerInterfaceHandler.isPageInstanceCreated()) {
final Page page = (Page) listenerInterfaceHandler.getPage();
injectPage(page);
}
}
} catch (StalePageException e) {
log.debug("StalePageException during onRequestHandlerResolved " +
handler.getClass() + " " + handler, e);
}
super.onRequestHandlerResolved(cycle, handler);
}
@Override
public void onRequestHandlerScheduled(RequestCycle reqCycle,
IRequestHandler handler) {
log.trace("onRequestHandlerScheduled {} {}", handler.getClass(), handler);
try {
if (handler instanceof AjaxRequestTarget) {
final Page page = ((AjaxRequestTarget) handler).getPage();
injectPage(page);
} else if (handler instanceof RenderPageRequestHandler) {
final RenderPageRequestHandler renderPageHandler = (RenderPageRequestHandler) handler;
if (renderPageHandler.isPageInstanceCreated()) {
final Page page = (Page) renderPageHandler.getPage();
injectPage(page);
}
}
} catch (StalePageException e) {
log.debug("StalePageException during onRequestHandlerScheduled " +
handler.getClass() + " " + handler, e);
}
super.onRequestHandlerScheduled(reqCycle, handler);
}
/**
* @param page
*/
protected void injectPage(final Page page) {
final InjectVisitor injectVisitor = new InjectVisitor();
injectVisitor.component(page, null);
page.visitChildren(injectVisitor);
}
}
| true | true | public void onInstantiation(Component component) {
final TenantRef tenant = WebTenantUtils.getTenant();
final String tenantId = tenant.getTenantId();
final String tenantEnv = tenant.getTenantEnv();
final List<Field> fields = ReflectionUtils.getAllFields(component.getClass());
final String componentId = component instanceof org.apache.wicket.Page ? component.getClass().getName() : component.getId();
final BundleContext bundleContext = Preconditions.checkNotNull(FrameworkUtil.getBundle(component.getClass()).getBundleContext(),
"Cannot get BundleContext for Wicket component %s %s", component.getClass().getName(), componentId);
boolean needBehavior = false;
for (Field field : fields) {
final Inject injectAnn = field.getAnnotation(Inject.class);
if (injectAnn == null)
continue;
final Supplied supplied = field.getAnnotation(Supplied.class);
if (supplied == null) {
needBehavior = true;
} else {
final Namespace namespaced = field.getAnnotation(Namespace.class);
final String namespace = namespaced != null ? namespaced.value() : null;
final String namespaceFilter = namespace != null ? "(namespace=" + namespace + ")" : "";
final Filter filtered = field.getAnnotation(Filter.class);
final String additionalFilter = filtered != null ? filtered.value() : "";
final Class<?> suppliedClass = field.getType();
log.trace("Field {}#{} needs Supplier<{}> for tenantId={} tenantEnv={} namespace={} filter: {}", new Object[] {
componentId, field.getName(), suppliedClass.getName(), tenantId, tenantEnv, namespace, additionalFilter });
final String suppliedClassFilter = supplied != null ? "(suppliedClass=" + field.getType().getName() + ")(layer=application)" : "";
final String filter = "(&" + String.format("(|(tenantId=%s)(tenantId=\\*))(|(tenantEnv=%s)(tenantEnv=\\*))", tenantId, tenantEnv)
+ namespaceFilter + suppliedClassFilter + additionalFilter + ")";
final Collection<ServiceReference<Supplier>> serviceRefs;
try {
serviceRefs = bundleContext.getServiceReferences(Supplier.class, filter);
} catch (InvalidSyntaxException e) {
throw new SiteException("Cannot inject " + componentId + "#" + field.getName() + ", invalid " +
suppliedClass.getName() + " Supplier service with filter " + filter, e);
}
if (serviceRefs == null || serviceRefs.isEmpty()) {
throw new SiteException("Cannot find " + suppliedClass.getName() + " supplier for " + componentId + "#" + field.getName() + ", " +
"Supplier with " + filter + " not found");
}
final ServiceReference<Supplier> serviceRef = serviceRefs.iterator().next();
final Supplier supplier = bundleContext.getService(serviceRef);
try {
final Object suppliedObj = supplier.get();
log.trace("Injecting {}#{} as {}", componentId, field.getName(), suppliedObj);
FieldUtils.writeField(field, component, suppliedObj, true);
} catch (Exception e) {
log.error("Cannot inject " + componentId + "#" + field.getName() + " from " + supplier, e);
throw new SiteException("Cannot inject " + componentId + "#" + field.getName() + " from " + supplier, e);
} finally {
bundleContext.ungetService(serviceRef);
}
}
}
if (needBehavior) {
final TenantInjectionBehavior behavior = new TenantInjectionBehavior(bundleContext, tenantId, tenantEnv);
behavior.inject(component, "onInstantiation"); // perform first injection
component.add( behavior );
}
}
| public void onInstantiation(Component component) {
final TenantRef tenant = WebTenantUtils.getTenant();
final String tenantId = tenant.getTenantId();
final String tenantEnv = tenant.getTenantEnv();
final List<Field> fields = ReflectionUtils.getAllFields(component.getClass());
final String componentId = component instanceof org.apache.wicket.Page ? component.getClass().getName() : component.getId();
final BundleContext bundleContext = Preconditions.checkNotNull(FrameworkUtil.getBundle(component.getClass()).getBundleContext(),
"Cannot get BundleContext for Wicket component %s %s", component.getClass().getName(), componentId);
boolean needBehavior = false;
for (Field field : fields) {
final Inject injectAnn = field.getAnnotation(Inject.class);
if (injectAnn == null)
continue;
final Supplied supplied = field.getAnnotation(Supplied.class);
if (supplied == null) {
needBehavior = true;
} else {
final Namespace namespaced = field.getAnnotation(Namespace.class);
final String namespace = namespaced != null ? namespaced.value() : null;
final String namespaceFilter = namespace != null ? "(namespace=" + namespace + ")" : "";
final Filter filtered = field.getAnnotation(Filter.class);
final String additionalFilter = filtered != null ? filtered.value() : "";
final Class<?> suppliedClass = field.getType();
log.trace("Field {}#{} needs Supplier<{}> for tenantId={} tenantEnv={} namespace={} filter: {}", new Object[] {
componentId, field.getName(), suppliedClass.getName(), tenantId, tenantEnv, namespace, additionalFilter });
final String suppliedClassFilter = supplied != null ? "(suppliedClass=" + field.getType().getName() + ")(layer=application)" : "";
// single-tenant for now
// final String filter = "(&" + String.format("(|(tenantId=%s)(tenantId=\\*))(|(tenantEnv=%s)(tenantEnv=\\*))", tenantId, tenantEnv)
// + namespaceFilter + suppliedClassFilter + additionalFilter + ")";
String filter = "(&" + namespaceFilter + suppliedClassFilter + additionalFilter + ")";
if ("(&)".equals(filter)) {
filter = null;
}
final Collection<ServiceReference<Supplier>> serviceRefs;
try {
serviceRefs = bundleContext.getServiceReferences(Supplier.class, filter);
} catch (InvalidSyntaxException e) {
throw new SiteException("Cannot inject " + componentId + "#" + field.getName() + ", invalid " +
suppliedClass.getName() + " Supplier service with filter " + filter, e);
}
if (serviceRefs == null || serviceRefs.isEmpty()) {
throw new SiteException("Cannot find " + suppliedClass.getName() + " supplier for " + componentId + "#" + field.getName() + ", " +
"Supplier with " + filter + " not found");
}
final ServiceReference<Supplier> serviceRef = serviceRefs.iterator().next();
final Supplier supplier = bundleContext.getService(serviceRef);
try {
final Object suppliedObj = supplier.get();
log.trace("Injecting {}#{} as {}", componentId, field.getName(), suppliedObj);
FieldUtils.writeField(field, component, suppliedObj, true);
} catch (Exception e) {
log.error("Cannot inject " + componentId + "#" + field.getName() + " from " + supplier, e);
throw new SiteException("Cannot inject " + componentId + "#" + field.getName() + " from " + supplier, e);
} finally {
bundleContext.ungetService(serviceRef);
}
}
}
if (needBehavior) {
final TenantInjectionBehavior behavior = new TenantInjectionBehavior(bundleContext, tenantId, tenantEnv);
behavior.inject(component, "onInstantiation"); // perform first injection
component.add( behavior );
}
}
|
diff --git a/lexevs-dao/src/main/java/org/lexevs/dao/database/service/association/VersionableEventAssociationService.java b/lexevs-dao/src/main/java/org/lexevs/dao/database/service/association/VersionableEventAssociationService.java
index d5590c6f9..e109a19d3 100644
--- a/lexevs-dao/src/main/java/org/lexevs/dao/database/service/association/VersionableEventAssociationService.java
+++ b/lexevs-dao/src/main/java/org/lexevs/dao/database/service/association/VersionableEventAssociationService.java
@@ -1,137 +1,137 @@
/*
* Copyright: (c) 2004-2009 Mayo Foundation for Medical Education and
* Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the
* triple-shield Mayo logo are trademarks and service marks of MFMER.
*
* Except as contained in the copyright notice above, or as used to identify
* MFMER as the author of this software, the trade names, trademarks, service
* marks, or product names of the copyright holder shall not be used in
* advertising, promotion or otherwise in connection with this software without
* prior written authorization of the copyright holder.
*
* Licensed under the Eclipse 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://www.eclipse.org/legal/epl-v10.html
*
*/
package org.lexevs.dao.database.service.association;
import java.util.Arrays;
import java.util.List;
import org.LexGrid.relations.AssociationPredicate;
import org.LexGrid.relations.AssociationSource;
import org.LexGrid.relations.Relations;
import org.lexevs.dao.database.access.association.AssociationDao;
import org.lexevs.dao.database.service.AbstractDatabaseService;
import org.lexevs.dao.database.utility.DaoUtility;
import org.springframework.transaction.annotation.Transactional;
/**
* The Class VersionableEventAssociationService.
*
* @author <a href="mailto:[email protected]">Kevin Peterson</a>
*/
public class VersionableEventAssociationService extends AbstractDatabaseService implements AssociationService{
/* (non-Javadoc)
* @see org.lexevs.dao.database.service.association.AssociationService#insertAssociationSource(java.lang.String, java.lang.String, java.lang.String, java.lang.String, org.LexGrid.relations.AssociationSource)
*/
@Transactional
public void insertAssociationSource(String codingSchemeUri,
String version,
String relationContainerName,
String associationPredicateName,
AssociationSource source){
String codingSchemeId = this.getDaoManager().getCodingSchemeDao(codingSchemeUri, version).
getCodingSchemeIdByUriAndVersion(codingSchemeUri, version);
String associationPredicateId = this.getDaoManager().getAssociationDao(codingSchemeUri, version).
getAssociationPredicateId(codingSchemeId, relationContainerName, associationPredicateName);
- this.doInsertAssociationSource(codingSchemeUri, codingSchemeUri, codingSchemeId, associationPredicateId,
+ this.doInsertAssociationSource(codingSchemeUri, version, codingSchemeId, associationPredicateId,
DaoUtility.createList(AssociationSource.class, source));
}
/* (non-Javadoc)
* @see org.lexevs.dao.database.service.association.AssociationService#insertRelation(java.lang.String, java.lang.String, org.LexGrid.relations.Relations)
*/
@Transactional
public void insertRelation(String codingSchemeUri, String version,
Relations relation) {
String codingSchemeId = this.getDaoManager().getCodingSchemeDao(codingSchemeUri, version).
getCodingSchemeIdByUriAndVersion(codingSchemeUri, version);
this.doInsertRelation(codingSchemeUri, version, codingSchemeId, relation);
}
/**
* Insert association predicate.
*
* @param codingSchemeUri the coding scheme uri
* @param version the version
* @param relationsName the relations name
* @param predicate the predicate
*/
@Transactional
public void insertAssociationPredicate(
String codingSchemeUri, String version, String relationsName, AssociationPredicate predicate) {
String codingSchemeId = this.getDaoManager().getCodingSchemeDao(codingSchemeUri, version).
getCodingSchemeIdByUriAndVersion(codingSchemeUri, version);
AssociationDao associationDao = this.getDaoManager().getAssociationDao(codingSchemeUri, version);
String relationId = associationDao.getRelationsId(codingSchemeUri, relationsName);
this.doInsertAssociationPredicate(codingSchemeUri, codingSchemeUri, codingSchemeId, relationId, predicate);
}
/**
* Do insert relation.
*
* @param codingSchemeUri the coding scheme uri
* @param codingSchemeVersion the coding scheme version
* @param codingSchemeId the coding scheme id
* @param relations the relations
*/
protected void doInsertRelation(String codingSchemeUri,
String codingSchemeVersion, String codingSchemeId, Relations relations) {
this.getDaoManager().getAssociationDao(codingSchemeUri, codingSchemeVersion)
.insertRelations(codingSchemeId, relations);
}
/**
* Do insert association predicate.
*
* @param codingSchemeUri the coding scheme uri
* @param codingSchemeVersion the coding scheme version
* @param codingSchemeId the coding scheme id
* @param relationsId the relations id
* @param predicate the predicate
*/
protected void doInsertAssociationPredicate(String codingSchemeUri,
String codingSchemeVersion, String codingSchemeId, String relationsId, AssociationPredicate predicate) {
AssociationDao associationDao = this.getDaoManager().getAssociationDao(codingSchemeUri, codingSchemeVersion);
String predicateId = associationDao.insertAssociationPredicate(codingSchemeId, relationsId, predicate);
this.doInsertAssociationSource(codingSchemeUri, codingSchemeVersion, codingSchemeId, predicateId, Arrays.asList(predicate.getSource()));
}
/**
* Do insert association source.
*
* @param codingSchemeUri the coding scheme uri
* @param codingSchemeVersion the coding scheme version
* @param codingSchemeId the coding scheme id
* @param predicateId the predicate id
* @param sources the sources
*/
protected void doInsertAssociationSource(String codingSchemeUri,
String codingSchemeVersion, String codingSchemeId, String predicateId, List<AssociationSource> sources) {
AssociationDao associationDao = this.getDaoManager().getAssociationDao(codingSchemeUri, codingSchemeVersion);
associationDao.insertBatchAssociationSources(codingSchemeId, predicateId, sources);
}
}
| true | true | public void insertAssociationSource(String codingSchemeUri,
String version,
String relationContainerName,
String associationPredicateName,
AssociationSource source){
String codingSchemeId = this.getDaoManager().getCodingSchemeDao(codingSchemeUri, version).
getCodingSchemeIdByUriAndVersion(codingSchemeUri, version);
String associationPredicateId = this.getDaoManager().getAssociationDao(codingSchemeUri, version).
getAssociationPredicateId(codingSchemeId, relationContainerName, associationPredicateName);
this.doInsertAssociationSource(codingSchemeUri, codingSchemeUri, codingSchemeId, associationPredicateId,
DaoUtility.createList(AssociationSource.class, source));
}
| public void insertAssociationSource(String codingSchemeUri,
String version,
String relationContainerName,
String associationPredicateName,
AssociationSource source){
String codingSchemeId = this.getDaoManager().getCodingSchemeDao(codingSchemeUri, version).
getCodingSchemeIdByUriAndVersion(codingSchemeUri, version);
String associationPredicateId = this.getDaoManager().getAssociationDao(codingSchemeUri, version).
getAssociationPredicateId(codingSchemeId, relationContainerName, associationPredicateName);
this.doInsertAssociationSource(codingSchemeUri, version, codingSchemeId, associationPredicateId,
DaoUtility.createList(AssociationSource.class, source));
}
|
diff --git a/rms/org.eclipse.ptp.rm.ibm.platform.lsf.ui/src/org/eclipse/ptp/rm/ibm/lsf/ui/widgets/ApplicationQueryControl.java b/rms/org.eclipse.ptp.rm.ibm.platform.lsf.ui/src/org/eclipse/ptp/rm/ibm/lsf/ui/widgets/ApplicationQueryControl.java
index 66e64e1fb..902c00dbb 100644
--- a/rms/org.eclipse.ptp.rm.ibm.platform.lsf.ui/src/org/eclipse/ptp/rm/ibm/lsf/ui/widgets/ApplicationQueryControl.java
+++ b/rms/org.eclipse.ptp.rm.ibm.platform.lsf.ui/src/org/eclipse/ptp/rm/ibm/lsf/ui/widgets/ApplicationQueryControl.java
@@ -1,130 +1,130 @@
// Copyright (c) 2013 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.0s which accompanies this distribution,
// and is available at http://www.eclipse.org/legal/epl-v10.html
package org.eclipse.ptp.rm.ibm.lsf.ui.widgets;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ptp.remote.core.IRemoteConnection;
import org.eclipse.ptp.remote.core.IRemoteProcess;
import org.eclipse.ptp.remote.core.IRemoteProcessBuilder;
import org.eclipse.ptp.remote.core.IRemoteServices;
import org.eclipse.ptp.rm.jaxb.control.ui.IWidgetDescriptor;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
public class ApplicationQueryControl extends LSFQueryControl {
/**
* Create the custom widget for the JAXB ui. In this case the widget is a
* push button that pops up a dialog with a list of active applications when
* the button is pushed.
*
* @param parent
* : Container for the widget
* @param wd
* : Information about the custom widget
*/
public ApplicationQueryControl(Composite parent, final IWidgetDescriptor wd) {
super(parent, wd);
}
@Override
protected void configureQueryButton(Button button, final IRemoteConnection connection) {
button.addSelectionListener(new SelectionAdapter() {
@Override
/**
* Handle button press event. Pop up a dialog listing applications. If the user
* selects an application and clicks the ok button notify listeners that this
* widget has been modified.
*
* @param e: The selection event
*/
public void widgetSelected(SelectionEvent e) {
int selection;
if (getQueryResponse(connection)) {
dialog = new LSFQueryDialog(getShell(), Messages.ApplicationQueryControl_0, columnLabels, commandResponse);
dialog.setSelectedValue(selectedValue);
selection = dialog.open();
if (selection == 0) {
selectedValue = dialog.getSelectedValue();
notifyListeners();
}
}
}
});
}
/**
* Issue the 'bapp' command to query the application list and set up the
* column heading and application data arrays.
*
* @param connection
* : Connection to the remote system
*/
@Override
protected boolean getQueryResponse(IRemoteConnection connection) {
IRemoteServices remoteServices;
IRemoteProcessBuilder processBuilder;
IRemoteProcess process;
remoteServices = connection.getRemoteServices();
processBuilder = remoteServices.getProcessBuilder(connection, "bapp", "-w"); //$NON-NLS-1$ //$NON-NLS-2$
process = null;
try {
BufferedReader reader;
String data;
boolean headerLine;
process = processBuilder.start();
try {
process.waitFor();
} catch (InterruptedException e) {
// Do nothing
}
if (process.exitValue() == 0) {
String columnData[];
/*
* Read stdout and tokenize each line of data into an array of
* blank-delimited strings. The first line of output is the
* column headings. Subsequent lines are reservation data.
*/
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
data = reader.readLine();
headerLine = true;
commandResponse.clear();
while (data != null) {
if (headerLine) {
- if (data.equals("No application found")) { //$NON-NLS-1$
+ if (data.equals("No application profiles found")) { //$NON-NLS-1$
MessageDialog.openWarning(getShell(), Messages.ApplicationQueryControl_2,
Messages.ApplicationQueryControl_3);
reader.close();
return false;
}
columnLabels = data.split(" +"); //$NON-NLS-1$
headerLine = false;
} else {
columnData = data.split(" +"); //$NON-NLS-1$
commandResponse.add(columnData);
}
data = reader.readLine();
}
reader.close();
}
} catch (IOException e) {
MessageDialog.openError(getShell(), "Error", //$NON-NLS-1$
"Error querying reservations:\n" + e.getMessage()); //$NON-NLS-1$
return false;
}
return true;
}
}
| true | true | protected boolean getQueryResponse(IRemoteConnection connection) {
IRemoteServices remoteServices;
IRemoteProcessBuilder processBuilder;
IRemoteProcess process;
remoteServices = connection.getRemoteServices();
processBuilder = remoteServices.getProcessBuilder(connection, "bapp", "-w"); //$NON-NLS-1$ //$NON-NLS-2$
process = null;
try {
BufferedReader reader;
String data;
boolean headerLine;
process = processBuilder.start();
try {
process.waitFor();
} catch (InterruptedException e) {
// Do nothing
}
if (process.exitValue() == 0) {
String columnData[];
/*
* Read stdout and tokenize each line of data into an array of
* blank-delimited strings. The first line of output is the
* column headings. Subsequent lines are reservation data.
*/
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
data = reader.readLine();
headerLine = true;
commandResponse.clear();
while (data != null) {
if (headerLine) {
if (data.equals("No application found")) { //$NON-NLS-1$
MessageDialog.openWarning(getShell(), Messages.ApplicationQueryControl_2,
Messages.ApplicationQueryControl_3);
reader.close();
return false;
}
columnLabels = data.split(" +"); //$NON-NLS-1$
headerLine = false;
} else {
columnData = data.split(" +"); //$NON-NLS-1$
commandResponse.add(columnData);
}
data = reader.readLine();
}
reader.close();
}
} catch (IOException e) {
MessageDialog.openError(getShell(), "Error", //$NON-NLS-1$
"Error querying reservations:\n" + e.getMessage()); //$NON-NLS-1$
return false;
}
return true;
}
| protected boolean getQueryResponse(IRemoteConnection connection) {
IRemoteServices remoteServices;
IRemoteProcessBuilder processBuilder;
IRemoteProcess process;
remoteServices = connection.getRemoteServices();
processBuilder = remoteServices.getProcessBuilder(connection, "bapp", "-w"); //$NON-NLS-1$ //$NON-NLS-2$
process = null;
try {
BufferedReader reader;
String data;
boolean headerLine;
process = processBuilder.start();
try {
process.waitFor();
} catch (InterruptedException e) {
// Do nothing
}
if (process.exitValue() == 0) {
String columnData[];
/*
* Read stdout and tokenize each line of data into an array of
* blank-delimited strings. The first line of output is the
* column headings. Subsequent lines are reservation data.
*/
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
data = reader.readLine();
headerLine = true;
commandResponse.clear();
while (data != null) {
if (headerLine) {
if (data.equals("No application profiles found")) { //$NON-NLS-1$
MessageDialog.openWarning(getShell(), Messages.ApplicationQueryControl_2,
Messages.ApplicationQueryControl_3);
reader.close();
return false;
}
columnLabels = data.split(" +"); //$NON-NLS-1$
headerLine = false;
} else {
columnData = data.split(" +"); //$NON-NLS-1$
commandResponse.add(columnData);
}
data = reader.readLine();
}
reader.close();
}
} catch (IOException e) {
MessageDialog.openError(getShell(), "Error", //$NON-NLS-1$
"Error querying reservations:\n" + e.getMessage()); //$NON-NLS-1$
return false;
}
return true;
}
|
diff --git a/src/java/org/codehaus/groovy/grails/orm/hibernate/metaclass/AbstractSavePersistentMethod.java b/src/java/org/codehaus/groovy/grails/orm/hibernate/metaclass/AbstractSavePersistentMethod.java
index c4c4226e5..2c6773828 100644
--- a/src/java/org/codehaus/groovy/grails/orm/hibernate/metaclass/AbstractSavePersistentMethod.java
+++ b/src/java/org/codehaus/groovy/grails/orm/hibernate/metaclass/AbstractSavePersistentMethod.java
@@ -1,273 +1,273 @@
/*
* 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.metaclass;
import grails.validation.ValidationException;
import groovy.lang.GroovyObject;
import groovy.lang.GroovySystem;
import groovy.lang.MetaClass;
import org.codehaus.groovy.grails.commons.*;
import org.codehaus.groovy.grails.validation.CascadingValidator;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.InvalidPropertyException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Abstract class for different implementations that perform saving to implement
*
* @author Graeme Rocher
* @since 0.3
*
*/
public abstract class AbstractSavePersistentMethod extends
AbstractDynamicPersistentMethod {
private GrailsApplication application;
private static final String ARGUMENT_VALIDATE = "validate";
private static final String ARGUMENT_DEEP_VALIDATE = "deepValidate";
private static final String ARGUMENT_FLUSH = "flush";
private static final String ARGUMENT_INSERT = "insert";
private static final String ARGUMENT_FAIL_ON_ERROR = "failOnError";
private static final String FAIL_ON_ERROR_CONFIG_PROPERTY = "grails.gorm.failOnError";
private static final String AUTO_FLUSH_CONFIG_PROPERTY = "grails.gorm.autoFlush";
public AbstractSavePersistentMethod(Pattern pattern, SessionFactory sessionFactory, ClassLoader classLoader, GrailsApplication application) {
super(pattern, sessionFactory, classLoader);
if(application == null)
throw new IllegalArgumentException("Constructor argument 'application' cannot be null");
this.application = application;
}
/* (non-Javadoc)
* @see org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractDynamicPersistentMethod#doInvokeInternal(java.lang.Object, java.lang.Object[])
*/
protected Object doInvokeInternal(final Object target, Object[] arguments) {
GrailsDomainClass domainClass = (GrailsDomainClass) application.getArtefact(DomainClassArtefactHandler.TYPE,
target.getClass().getName() );
if(shouldValidate(arguments, domainClass)) {
Validator validator = domainClass.getValidator();
Errors errors = setupErrorsProperty(target);
if(validator != null) {
boolean deepValidate = true;
Map argsMap = null;
if(arguments.length > 0 && arguments[0] instanceof Map) {
argsMap = (Map) arguments[0];
}
if (argsMap != null && argsMap.containsKey(ARGUMENT_DEEP_VALIDATE)) {
deepValidate = GrailsClassUtils.getBooleanFromMap(ARGUMENT_DEEP_VALIDATE, argsMap);
}
if(deepValidate && (validator instanceof CascadingValidator)) {
((CascadingValidator)validator).validate(target, errors, deepValidate);
}
else {
validator.validate(target,errors);
}
if(errors.hasErrors()) {
handleValidationError(target,errors);
boolean shouldFail = false;
final Map config = ConfigurationHolder.getFlatConfig();
if(argsMap != null && argsMap.containsKey(ARGUMENT_FAIL_ON_ERROR)) {
shouldFail = GrailsClassUtils.getBooleanFromMap(ARGUMENT_FAIL_ON_ERROR, argsMap);
} else if(config.containsKey(FAIL_ON_ERROR_CONFIG_PROPERTY)) {
Object configProperty = config.get(FAIL_ON_ERROR_CONFIG_PROPERTY);
if (configProperty instanceof Boolean) {
shouldFail = Boolean.TRUE == configProperty;
}
else if (configProperty instanceof List) {
String domainClassName = domainClass.getClazz().getName();
List packageList = (List) configProperty;
for (Object packageName : packageList) {
if (domainClassName.startsWith(packageName.toString())) {
shouldFail = true;
break;
}
}
}
}
if(shouldFail) {
- throw new ValidationException("Validation Error(s) Occurred During Save");
+ throw new ValidationException("Validation Error(s) occurred during save()", errors);
}
return null;
}
else {
setObjectToReadWrite(target);
}
}
}
// this piece of code will retrieve a persistent instant
// of a domain class property is only the id is set thus
// relieving this burden off the developer
if(domainClass != null) {
autoRetrieveAssocations(domainClass, target);
}
if(shouldInsert(arguments)) {
return performInsert(target, shouldFlush(arguments));
}
else {
return performSave(target, shouldFlush(arguments));
}
}
private boolean shouldInsert(Object[] arguments) {
return arguments.length > 0 && arguments[0] instanceof Map && GrailsClassUtils.getBooleanFromMap(ARGUMENT_INSERT, (Map) arguments[0]);
}
private boolean shouldFlush(Object[] arguments) {
final boolean shouldFlush;
if (arguments.length > 0 && arguments[0] instanceof Boolean) {
shouldFlush = ((Boolean) arguments[0]).booleanValue();
}
else if (arguments.length > 0 && arguments[0] instanceof Map && ((Map) arguments[0]).containsKey(ARGUMENT_FLUSH)) {
shouldFlush = GrailsClassUtils.getBooleanFromMap(ARGUMENT_FLUSH, ((Map) arguments[0]));
}
else {
final Map config = ConfigurationHolder.getFlatConfig();
shouldFlush = Boolean.TRUE == config.get(AUTO_FLUSH_CONFIG_PROPERTY);
}
return shouldFlush;
}
/**
* Performs automatic association retrieval
* @param domainClass The domain class to retrieve associations for
* @param target The target object
*/
private void autoRetrieveAssocations(GrailsDomainClass domainClass, Object target) {
BeanWrapper bean = new BeanWrapperImpl(target);
HibernateTemplate t = getHibernateTemplate();
GrailsDomainClassProperty[] props = domainClass.getPersistentProperties();
for (int i = 0; i < props.length; i++) {
GrailsDomainClassProperty prop = props[i];
if(prop.isManyToOne() || prop.isOneToOne()) {
Object propValue = bean.getPropertyValue(prop.getName());
if(propValue != null && !t.contains(propValue)) {
GrailsDomainClass otherSide = (GrailsDomainClass) application.getArtefact(DomainClassArtefactHandler.TYPE,
prop.getType().getName());
if(otherSide != null) {
BeanWrapper propBean = new BeanWrapperImpl(propValue);
try {
Serializable id = (Serializable) propBean.getPropertyValue(otherSide.getIdentifier().getName());
if (id != null) {
bean.setPropertyValue(prop.getName(), t.get(prop.getType(), id));
}
} catch (InvalidPropertyException ipe) {
// property is not accessable
}
}
}
}
}
}
/**
* This method willl set the save() method will set the flush mode to manual. What this does
* is ensure that the database changes are not persisted to the database if a validation error occurs.
* If save() is called again and validation passes the code will check if there is a manual flush mode and
* flush manually if necessary
*
* @param target The target object that failed validation
* @param errors The Errors instance
* @return This method will return null signaling a validation failure
*/
protected Object handleValidationError(final Object target, Errors errors) {
// if a validation error occurs set the object to read-only to prevent a flush
setObjectToReadOnly(target);
setErrorsOnInstance(target, errors);
return null;
}
/**
* Associates the Errors object on the instance
*
* @param target The target instance
* @param errors The Errors object
*/
protected void setErrorsOnInstance(Object target, Errors errors) {
if(target instanceof GroovyObject) {
((GroovyObject)target).setProperty(ERRORS_PROPERTY,errors);
}
else {
MetaClass metaClass = GroovySystem.getMetaClassRegistry().getMetaClass(target.getClass());
metaClass.setProperty(target.getClass() ,target, ERRORS_PROPERTY,errors, false, false);
}
}
/**
* Checks whether validation should be performed
* @return True if the domain class should be validated
* @param arguments The arguments to the validate method
* @param domainClass The domain class
*/
private boolean shouldValidate(Object[] arguments, GrailsDomainClass domainClass) {
if(domainClass != null) {
if(arguments.length > 0) {
if(arguments[0] instanceof Boolean) {
return ((Boolean)arguments[0]).booleanValue();
}
else if(arguments[0] instanceof Map) {
Map argsMap = (Map)arguments[0];
if(argsMap.containsKey(ARGUMENT_VALIDATE)) {
return GrailsClassUtils.getBooleanFromMap(ARGUMENT_VALIDATE,argsMap);
}
else {
return true;
}
}
else {
return true;
}
}
else {
return true;
}
}
return false;
}
/**
* Subclasses should override and perform a save operation, flushing the session if the second argument is true
*
* @param target The target object to save
* @param shouldFlush Whether to flush
* @return The target object
*/
abstract protected Object performSave(Object target, boolean shouldFlush);
/**
* Subclasses should override and perform an insert operation, flushing the session if the second argument is true
*
* @param target The target object to save
* @param shouldFlush Whether to flush
* @return The target object
*/
protected abstract Object performInsert(Object target, boolean shouldFlush);
}
| true | true | protected Object doInvokeInternal(final Object target, Object[] arguments) {
GrailsDomainClass domainClass = (GrailsDomainClass) application.getArtefact(DomainClassArtefactHandler.TYPE,
target.getClass().getName() );
if(shouldValidate(arguments, domainClass)) {
Validator validator = domainClass.getValidator();
Errors errors = setupErrorsProperty(target);
if(validator != null) {
boolean deepValidate = true;
Map argsMap = null;
if(arguments.length > 0 && arguments[0] instanceof Map) {
argsMap = (Map) arguments[0];
}
if (argsMap != null && argsMap.containsKey(ARGUMENT_DEEP_VALIDATE)) {
deepValidate = GrailsClassUtils.getBooleanFromMap(ARGUMENT_DEEP_VALIDATE, argsMap);
}
if(deepValidate && (validator instanceof CascadingValidator)) {
((CascadingValidator)validator).validate(target, errors, deepValidate);
}
else {
validator.validate(target,errors);
}
if(errors.hasErrors()) {
handleValidationError(target,errors);
boolean shouldFail = false;
final Map config = ConfigurationHolder.getFlatConfig();
if(argsMap != null && argsMap.containsKey(ARGUMENT_FAIL_ON_ERROR)) {
shouldFail = GrailsClassUtils.getBooleanFromMap(ARGUMENT_FAIL_ON_ERROR, argsMap);
} else if(config.containsKey(FAIL_ON_ERROR_CONFIG_PROPERTY)) {
Object configProperty = config.get(FAIL_ON_ERROR_CONFIG_PROPERTY);
if (configProperty instanceof Boolean) {
shouldFail = Boolean.TRUE == configProperty;
}
else if (configProperty instanceof List) {
String domainClassName = domainClass.getClazz().getName();
List packageList = (List) configProperty;
for (Object packageName : packageList) {
if (domainClassName.startsWith(packageName.toString())) {
shouldFail = true;
break;
}
}
}
}
if(shouldFail) {
throw new ValidationException("Validation Error(s) Occurred During Save");
}
return null;
}
else {
setObjectToReadWrite(target);
}
}
}
// this piece of code will retrieve a persistent instant
// of a domain class property is only the id is set thus
// relieving this burden off the developer
if(domainClass != null) {
autoRetrieveAssocations(domainClass, target);
}
if(shouldInsert(arguments)) {
return performInsert(target, shouldFlush(arguments));
}
else {
return performSave(target, shouldFlush(arguments));
}
}
| protected Object doInvokeInternal(final Object target, Object[] arguments) {
GrailsDomainClass domainClass = (GrailsDomainClass) application.getArtefact(DomainClassArtefactHandler.TYPE,
target.getClass().getName() );
if(shouldValidate(arguments, domainClass)) {
Validator validator = domainClass.getValidator();
Errors errors = setupErrorsProperty(target);
if(validator != null) {
boolean deepValidate = true;
Map argsMap = null;
if(arguments.length > 0 && arguments[0] instanceof Map) {
argsMap = (Map) arguments[0];
}
if (argsMap != null && argsMap.containsKey(ARGUMENT_DEEP_VALIDATE)) {
deepValidate = GrailsClassUtils.getBooleanFromMap(ARGUMENT_DEEP_VALIDATE, argsMap);
}
if(deepValidate && (validator instanceof CascadingValidator)) {
((CascadingValidator)validator).validate(target, errors, deepValidate);
}
else {
validator.validate(target,errors);
}
if(errors.hasErrors()) {
handleValidationError(target,errors);
boolean shouldFail = false;
final Map config = ConfigurationHolder.getFlatConfig();
if(argsMap != null && argsMap.containsKey(ARGUMENT_FAIL_ON_ERROR)) {
shouldFail = GrailsClassUtils.getBooleanFromMap(ARGUMENT_FAIL_ON_ERROR, argsMap);
} else if(config.containsKey(FAIL_ON_ERROR_CONFIG_PROPERTY)) {
Object configProperty = config.get(FAIL_ON_ERROR_CONFIG_PROPERTY);
if (configProperty instanceof Boolean) {
shouldFail = Boolean.TRUE == configProperty;
}
else if (configProperty instanceof List) {
String domainClassName = domainClass.getClazz().getName();
List packageList = (List) configProperty;
for (Object packageName : packageList) {
if (domainClassName.startsWith(packageName.toString())) {
shouldFail = true;
break;
}
}
}
}
if(shouldFail) {
throw new ValidationException("Validation Error(s) occurred during save()", errors);
}
return null;
}
else {
setObjectToReadWrite(target);
}
}
}
// this piece of code will retrieve a persistent instant
// of a domain class property is only the id is set thus
// relieving this burden off the developer
if(domainClass != null) {
autoRetrieveAssocations(domainClass, target);
}
if(shouldInsert(arguments)) {
return performInsert(target, shouldFlush(arguments));
}
else {
return performSave(target, shouldFlush(arguments));
}
}
|
diff --git a/src/main/novelang/rendering/xslt/Numbering.java b/src/main/novelang/rendering/xslt/Numbering.java
index 3376d540..bdbfdb32 100644
--- a/src/main/novelang/rendering/xslt/Numbering.java
+++ b/src/main/novelang/rendering/xslt/Numbering.java
@@ -1,291 +1,291 @@
/*
* Copyright (C) 2008 Laurent Caillette
*
* 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 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package novelang.rendering.xslt;
import org.apache.commons.lang.ArrayUtils;
import org.joda.time.ReadableDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
/**
* @author Laurent Caillette
*/
public class Numbering {
private static final Logger LOGGER = LoggerFactory.getLogger( Numbering.class ) ;
private static final DateTimeFormatter DATE_TIME_FORMATTER_NOSEPARATOR = DateTimeFormat.forPattern( "yyyyMMddkkmm" );
/**
* Just to get an easy case.
* @return The constant String "{@code Hello!}".
*/
public static String hello() {
return "Hello!" ;
}
public static String asString( Object treeResultFragment ) {
return asString( "", treeResultFragment ) ;
}
public static String numberAsText(
Object numberObject,
Object localeNameObject,
Object caseObject
) {
final String numberAsString = asString( "number", numberObject ) ;
final String localeAsString = asString( "locale", localeNameObject ) ;
final String caseAsString = asString( "case", caseObject ) ;
final CaseType caseType ;
if( caseObject instanceof String ) {
CaseType possibleCaseType ;
try {
possibleCaseType = CaseType.valueOf( ( ( String ) caseObject ).toUpperCase() ) ;
} catch( IllegalArgumentException e ) {
LOGGER.warn(
"Not a supported case type: {} (supported: {})",
caseObject,
ArrayUtils.toString( CaseType.values() )
) ;
possibleCaseType = CaseType.LOWER ;
}
caseType = possibleCaseType ;
} else {
LOGGER.warn( "Case type is not a String: {}", caseAsString ) ;
caseType = CaseType.LOWER ;
}
final String numberAsText ;
if( numberObject instanceof Number ) {
final Number number = ( Number ) numberObject ;
if( "FR".equals( localeNameObject ) ) {
numberAsText = numberAsLocalizedText( number.intValue(), TO_FRENCH_TEXT, caseType ) ;
} else if( "EN".equals( localeNameObject ) ) {
numberAsText = numberAsLocalizedText( number.intValue(), TO_ENGLISH_TEXT, caseType ) ;
} else {
LOGGER.warn( "Locale not supported: " + localeAsString ) ;
numberAsText = number.toString() ;
}
return numberAsText ;
} else {
final String message = "!NAN! Cannot convert to number: " + numberAsString ;
LOGGER.error( message ) ;
return message ;
}
}
private enum CaseType {
LOWER, UPPER, CAPITAL ;
}
private static String numberAsLocalizedText(
int number,
Function< Number, String > textualizer,
CaseType caseType
) {
switch( caseType ) {
case CAPITAL:
final String s = textualizer.apply( number ) ;
return s.substring( 0, 1 ).toUpperCase() + s.substring( 1, s.length() ) ;
case LOWER:
return textualizer.apply( number ) ;
case UPPER:
return textualizer.apply( number ).toUpperCase() ;
default :
LOGGER.warn( "Unsupported case: {}", caseType ) ;
return textualizer.apply( number ) ;
}
}
private static final Function< Number, String > TO_FRENCH_TEXT =
new Function< Number, String >(){
public String apply( Number number ) {
switch( number.intValue() ) {
- case 0 : return "z�ro" ;
+ case 0 : return "z\u00e9ro" ;
case 1 : return "un" ;
case 2 : return "deux" ;
case 3 : return "trois" ;
case 4 : return "quatre" ;
case 5 : return "cinq" ;
case 6 : return "six" ;
case 7 : return "sept" ;
case 8 : return "huit" ;
case 9 : return "neuf" ;
case 10 : return "dix" ;
case 11 : return "onze" ;
case 12 : return "douze" ;
case 13 : return "treize" ;
case 14 : return "quatorze" ;
case 15 : return "quinze" ;
case 16 : return "seize" ;
case 17 : return "dix-sept" ;
case 18 : return "dix-huit" ;
case 19 : return "dix-neuf" ;
case 20 : return "vingt" ;
case 21 : return "vingt et un" ;
case 22 : return "vingt-deux" ;
case 23 : return "vingt-trois" ;
case 24 : return "vingt-quatre" ;
case 25 : return "vingt-cinq" ;
case 26 : return "vingt-six" ;
case 27 : return "vingt-sept" ;
case 28 : return "vingt-huit" ;
case 29 : return "vingt-neuf" ;
case 30 : return "trente" ;
case 31 : return "trente-et-un" ;
case 32 : return "trente-deux" ;
case 33 : return "trente-trois" ;
case 34 : return "trente-quatre" ;
case 35 : return "trente-cinq" ;
case 36 : return "trente-six" ;
case 37 : return "trente-sept" ;
case 38 : return "trente-huit" ;
case 39 : return "trente-neuf" ;
case 40 : return "quarante" ;
case 41 : return "quarante-et-un" ;
case 42 : return "quarante-deux" ;
case 43 : return "quarante-trois" ;
case 44 : return "quarante-quatre" ;
case 45 : return "quarante-cinq" ;
case 46 : return "quarante-six" ;
case 47 : return "quarante-sept" ;
case 48 : return "quarante-huit" ;
case 49 : return "quarante-neuf" ;
case 50 : return "cinquante" ;
default : throw new UnsupportedOperationException( "Not supported: " + number.intValue() ) ;
}
}
} ;
private static final Function< Number, String > TO_ENGLISH_TEXT =
new Function< Number, String >(){
public String apply( Number number ) {
switch( number.intValue() ) {
case 0 : return "zero" ;
case 1 : return "one" ;
case 2 : return "two" ;
case 3 : return "three" ;
case 4 : return "four" ;
case 5 : return "five" ;
case 6 : return "six" ;
case 7 : return "seven" ;
case 8 : return "eight" ;
case 9 : return "nine" ;
case 10 : return "ten" ;
case 11 : return "eleven" ;
case 12 : return "twelve" ;
case 13 : return "thirteen" ;
case 14 : return "fourteen" ;
case 15 : return "fifteen" ;
case 16 : return "sixteen" ;
case 17 : return "seventeen" ;
case 18 : return "eighteen" ;
case 19 : return "nineteen" ;
case 20 : return "twenty" ;
case 21 : return "twenty-one" ;
case 22 : return "twenty-two" ;
case 23 : return "twenty-three" ;
case 24 : return "twenty-four" ;
case 25 : return "twenty-five" ;
case 26 : return "twenty-six" ;
case 27 : return "twenty-seven" ;
case 28 : return "twenty-eight" ;
case 29 : return "twenty-nine" ;
case 30 : return "thirty" ;
case 31 : return "thirty-one" ;
case 32 : return "thirty-two" ;
case 33 : return "thirty-three" ;
case 34 : return "thirty-four" ;
case 35 : return "thirty-five" ;
case 36 : return "thirty-six" ;
case 37 : return "thirty-seven" ;
case 38 : return "thirty-eight" ;
case 39 : return "thirty-nine" ;
case 40 : return "fourty" ;
case 41 : return "fourty-one" ;
case 42 : return "fourty-two" ;
case 43 : return "fourty-three" ;
case 44 : return "fourty-four" ;
case 45 : return "fourty-five" ;
case 46 : return "fourty-six" ;
case 47 : return "fourty-seven" ;
case 48 : return "fourty-eight" ;
case 49 : return "fourty-nine" ;
case 50 : return "fifty" ;
default : throw new UnsupportedOperationException( "Not supported: " + number.intValue() ) ;
}
}
} ;
public static String asString( String name, Object object ) {
return
( null == name ? "" : name + ": " )
+ "'" + object + "' "
+ ( null == object ? "" : object.getClass().getName() )
;
}
public static String formatDateTime(
Object readableDateTimeObject,
Object formatDescriptionObject
) {
final ReadableDateTime readableDateTime = Preconditions.checkNotNull(
( ReadableDateTime ) readableDateTimeObject ) ;
final String formatDescription = Preconditions.checkNotNull(
( String ) formatDescriptionObject ) ;
if( "BASE36".equals( formatDescription ) ) {
final DateTimeFormatter format = DATE_TIME_FORMATTER_NOSEPARATOR ;
final String formattedString = format.print( readableDateTime ) ;
final long number = Long.parseLong( formattedString ) ;
return Long.toString( number, 36 ) ;
} else {
final DateTimeFormatter format = DateTimeFormat.forPattern( formatDescription ) ;
return format.print( readableDateTime ) ;
}
}
protected static ReadableDateTime unformatDateTime(
String formattedDateTime,
String formatDescription
) {
if( "BASE36".equals( formatDescription ) ) {
final Long decimalNumber = Long.parseLong( formattedDateTime, 36 ) ;
final String decimalNumberAsString = decimalNumber.toString() ;
return DATE_TIME_FORMATTER_NOSEPARATOR.parseDateTime( decimalNumberAsString ) ;
} else {
final DateTimeFormatter formatter = DateTimeFormat.forPattern( formatDescription ) ;
return formatter.parseDateTime( formattedDateTime ) ;
}
}
}
| true | true | public String apply( Number number ) {
switch( number.intValue() ) {
case 0 : return "z�ro" ;
case 1 : return "un" ;
case 2 : return "deux" ;
case 3 : return "trois" ;
case 4 : return "quatre" ;
case 5 : return "cinq" ;
case 6 : return "six" ;
case 7 : return "sept" ;
case 8 : return "huit" ;
case 9 : return "neuf" ;
case 10 : return "dix" ;
case 11 : return "onze" ;
case 12 : return "douze" ;
case 13 : return "treize" ;
case 14 : return "quatorze" ;
case 15 : return "quinze" ;
case 16 : return "seize" ;
case 17 : return "dix-sept" ;
case 18 : return "dix-huit" ;
case 19 : return "dix-neuf" ;
case 20 : return "vingt" ;
case 21 : return "vingt et un" ;
case 22 : return "vingt-deux" ;
case 23 : return "vingt-trois" ;
case 24 : return "vingt-quatre" ;
case 25 : return "vingt-cinq" ;
case 26 : return "vingt-six" ;
case 27 : return "vingt-sept" ;
case 28 : return "vingt-huit" ;
case 29 : return "vingt-neuf" ;
case 30 : return "trente" ;
case 31 : return "trente-et-un" ;
case 32 : return "trente-deux" ;
case 33 : return "trente-trois" ;
case 34 : return "trente-quatre" ;
case 35 : return "trente-cinq" ;
case 36 : return "trente-six" ;
case 37 : return "trente-sept" ;
case 38 : return "trente-huit" ;
case 39 : return "trente-neuf" ;
case 40 : return "quarante" ;
case 41 : return "quarante-et-un" ;
case 42 : return "quarante-deux" ;
case 43 : return "quarante-trois" ;
case 44 : return "quarante-quatre" ;
case 45 : return "quarante-cinq" ;
case 46 : return "quarante-six" ;
case 47 : return "quarante-sept" ;
case 48 : return "quarante-huit" ;
case 49 : return "quarante-neuf" ;
case 50 : return "cinquante" ;
default : throw new UnsupportedOperationException( "Not supported: " + number.intValue() ) ;
}
}
| public String apply( Number number ) {
switch( number.intValue() ) {
case 0 : return "z\u00e9ro" ;
case 1 : return "un" ;
case 2 : return "deux" ;
case 3 : return "trois" ;
case 4 : return "quatre" ;
case 5 : return "cinq" ;
case 6 : return "six" ;
case 7 : return "sept" ;
case 8 : return "huit" ;
case 9 : return "neuf" ;
case 10 : return "dix" ;
case 11 : return "onze" ;
case 12 : return "douze" ;
case 13 : return "treize" ;
case 14 : return "quatorze" ;
case 15 : return "quinze" ;
case 16 : return "seize" ;
case 17 : return "dix-sept" ;
case 18 : return "dix-huit" ;
case 19 : return "dix-neuf" ;
case 20 : return "vingt" ;
case 21 : return "vingt et un" ;
case 22 : return "vingt-deux" ;
case 23 : return "vingt-trois" ;
case 24 : return "vingt-quatre" ;
case 25 : return "vingt-cinq" ;
case 26 : return "vingt-six" ;
case 27 : return "vingt-sept" ;
case 28 : return "vingt-huit" ;
case 29 : return "vingt-neuf" ;
case 30 : return "trente" ;
case 31 : return "trente-et-un" ;
case 32 : return "trente-deux" ;
case 33 : return "trente-trois" ;
case 34 : return "trente-quatre" ;
case 35 : return "trente-cinq" ;
case 36 : return "trente-six" ;
case 37 : return "trente-sept" ;
case 38 : return "trente-huit" ;
case 39 : return "trente-neuf" ;
case 40 : return "quarante" ;
case 41 : return "quarante-et-un" ;
case 42 : return "quarante-deux" ;
case 43 : return "quarante-trois" ;
case 44 : return "quarante-quatre" ;
case 45 : return "quarante-cinq" ;
case 46 : return "quarante-six" ;
case 47 : return "quarante-sept" ;
case 48 : return "quarante-huit" ;
case 49 : return "quarante-neuf" ;
case 50 : return "cinquante" ;
default : throw new UnsupportedOperationException( "Not supported: " + number.intValue() ) ;
}
}
|
diff --git a/subsonic-android/src/net/sourceforge/subsonic/androidapp/util/EntryAdapter.java b/subsonic-android/src/net/sourceforge/subsonic/androidapp/util/EntryAdapter.java
index 66c019bf..1b4d72cf 100644
--- a/subsonic-android/src/net/sourceforge/subsonic/androidapp/util/EntryAdapter.java
+++ b/subsonic-android/src/net/sourceforge/subsonic/androidapp/util/EntryAdapter.java
@@ -1,70 +1,71 @@
/*
This file is part of Subsonic.
Subsonic 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.
Subsonic 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 Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2010 (C) Sindre Mehus
*/
package net.sourceforge.subsonic.androidapp.util;
import java.util.List;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import net.sourceforge.subsonic.androidapp.activity.SubsonicTabActivity;
import net.sourceforge.subsonic.androidapp.domain.MusicDirectory;
/**
* @author Sindre Mehus
*/
public class EntryAdapter extends ArrayAdapter<MusicDirectory.Entry> {
private final SubsonicTabActivity activity;
private final ImageLoader imageLoader;
private final boolean checkable;
public EntryAdapter(SubsonicTabActivity activity, ImageLoader imageLoader, List<MusicDirectory.Entry> entries, boolean checkable) {
super(activity, android.R.layout.simple_list_item_1, entries);
this.activity = activity;
this.imageLoader = imageLoader;
this.checkable = checkable;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MusicDirectory.Entry entry = getItem(position);
if (entry.isDirectory()) {
AlbumView view;
- if (convertView != null && convertView instanceof AlbumView) {
- view = (AlbumView) convertView;
- } else {
+ // TODO: Reuse AlbumView objects once cover art loading is working.
+// if (convertView != null && convertView instanceof AlbumView) {
+// view = (AlbumView) convertView;
+// } else {
view = new AlbumView(activity);
- }
+// }
view.setAlbum(entry, imageLoader);
return view;
} else {
SongView view;
if (convertView != null && convertView instanceof SongView) {
view = (SongView) convertView;
} else {
view = new SongView(activity);
}
view.setSong(entry, checkable);
return view;
}
}
}
| false | true | public View getView(int position, View convertView, ViewGroup parent) {
MusicDirectory.Entry entry = getItem(position);
if (entry.isDirectory()) {
AlbumView view;
if (convertView != null && convertView instanceof AlbumView) {
view = (AlbumView) convertView;
} else {
view = new AlbumView(activity);
}
view.setAlbum(entry, imageLoader);
return view;
} else {
SongView view;
if (convertView != null && convertView instanceof SongView) {
view = (SongView) convertView;
} else {
view = new SongView(activity);
}
view.setSong(entry, checkable);
return view;
}
}
| public View getView(int position, View convertView, ViewGroup parent) {
MusicDirectory.Entry entry = getItem(position);
if (entry.isDirectory()) {
AlbumView view;
// TODO: Reuse AlbumView objects once cover art loading is working.
// if (convertView != null && convertView instanceof AlbumView) {
// view = (AlbumView) convertView;
// } else {
view = new AlbumView(activity);
// }
view.setAlbum(entry, imageLoader);
return view;
} else {
SongView view;
if (convertView != null && convertView instanceof SongView) {
view = (SongView) convertView;
} else {
view = new SongView(activity);
}
view.setSong(entry, checkable);
return view;
}
}
|
diff --git a/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/utils/AcceleoDynamicTemplatesEclipseUtil.java b/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/utils/AcceleoDynamicTemplatesEclipseUtil.java
index 4331e181..bad2d13c 100644
--- a/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/utils/AcceleoDynamicTemplatesEclipseUtil.java
+++ b/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/utils/AcceleoDynamicTemplatesEclipseUtil.java
@@ -1,144 +1,149 @@
/*******************************************************************************
* Copyright (c) 2009 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.acceleo.engine.internal.utils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.acceleo.common.IAcceleoConstants;
import org.eclipse.acceleo.engine.AcceleoEngineMessages;
import org.eclipse.acceleo.engine.AcceleoEnginePlugin;
import org.eclipse.core.runtime.FileLocator;
import org.osgi.framework.Bundle;
/**
* Eclipse-specific utilities for Acceleo dynamic templates. It will be initialized with all dynamic templates
* that could be parsed from the extension point if Eclipse is running and won't be used when outside of
* Eclipse.
*
* @author <a href="mailto:[email protected]">Laurent Goubet</a>
*/
public final class AcceleoDynamicTemplatesEclipseUtil {
/** Keeps track of the bundles extending this extension point. */
protected static final Map<Bundle, List<String>> EXTENDING_BUNDLES = new HashMap<Bundle, List<String>>();
/** This will contain the modules contained by this registry. */
private static final Set<File> REGISTERED_MODULES = new LinkedHashSet<File>();
/**
* Utility classes don't need a default constructor.
*/
private AcceleoDynamicTemplatesEclipseUtil() {
// hides constructor
}
/**
* Adds a bundle in the extending bundles map.
*
* @param bundle
* The extending bundle.
* @param pathes
* Pathes where dynamic modules are located.
*/
public static void addExtendingBundle(Bundle bundle, List<String> pathes) {
List<String> currentPathes = EXTENDING_BUNDLES.get(bundle);
if (currentPathes == null) {
currentPathes = new ArrayList<String>();
}
currentPathes.addAll(pathes);
EXTENDING_BUNDLES.put(bundle, currentPathes);
}
/**
* Clears the registry from all registered bundles.
*/
public static void clearRegistry() {
EXTENDING_BUNDLES.clear();
REGISTERED_MODULES.clear();
}
/**
* Returns all registered modules. The returned set is a copy of this instance's.
*
* @return A copy of the registered modules set.
*/
public static Set<File> getRegisteredModules() {
refreshModules();
return new LinkedHashSet<File>(REGISTERED_MODULES);
}
/**
* Removes a bundle from the extending bundles map.
*
* @param bundle
* The bundle that is to be removed.
*/
public static void removeExtendingBundle(Bundle bundle) {
EXTENDING_BUNDLES.remove(bundle);
}
/**
* This will be called prior to all invocations of getRegisteredModules so as to be aware of new additions
* or removals of dynamic templates.
*/
@SuppressWarnings("unchecked")
private static void refreshModules() {
REGISTERED_MODULES.clear();
for (java.util.Map.Entry<Bundle, List<String>> entry : new LinkedHashSet<java.util.Map.Entry<Bundle, List<String>>>(
EXTENDING_BUNDLES.entrySet())) {
for (String path : entry.getValue()) {
String actualPath = path;
if (actualPath.charAt(0) != '/') {
actualPath = '/' + actualPath;
}
if (actualPath.charAt(actualPath.length() - 1) == '/') {
actualPath = actualPath.substring(0, actualPath.length() - 1);
}
if (actualPath.startsWith("/src") || actualPath.startsWith("/bin")) { //$NON-NLS-1$ //$NON-NLS-2$
- actualPath = actualPath.substring(actualPath.indexOf('/', 2));
+ int firstFragmentEnd = actualPath.indexOf('/', 2);
+ if (firstFragmentEnd > 0) {
+ actualPath = actualPath.substring(firstFragmentEnd);
+ } else {
+ actualPath = "/"; //$NON-NLS-1$
+ }
}
final String filePattern = "*." + IAcceleoConstants.EMTL_FILE_EXTENSION; //$NON-NLS-1$
Enumeration<URL> emtlFiles = entry.getKey().findEntries("/", //$NON-NLS-1$
filePattern, true);
// no dynamic templates in this bundle
if (emtlFiles == null) {
AcceleoEnginePlugin.log(AcceleoEngineMessages.getString(
"AcceleoDynamicTemplatesEclipseUtil.MissingDynamicTemplates", entry.getKey() //$NON-NLS-1$
.getSymbolicName(), path), false);
return;
}
try {
while (emtlFiles.hasMoreElements()) {
final URL next = emtlFiles.nextElement();
String emtlPath = next.getPath();
emtlPath.substring(0, emtlPath.lastIndexOf('/'));
if (emtlPath.endsWith(actualPath)) {
final File moduleFile = new File(FileLocator.toFileURL(next).getFile());
if (moduleFile.exists() && moduleFile.canRead()) {
REGISTERED_MODULES.add(moduleFile);
}
}
}
} catch (IOException e) {
AcceleoEnginePlugin.log(e, false);
}
}
}
}
}
| true | true | private static void refreshModules() {
REGISTERED_MODULES.clear();
for (java.util.Map.Entry<Bundle, List<String>> entry : new LinkedHashSet<java.util.Map.Entry<Bundle, List<String>>>(
EXTENDING_BUNDLES.entrySet())) {
for (String path : entry.getValue()) {
String actualPath = path;
if (actualPath.charAt(0) != '/') {
actualPath = '/' + actualPath;
}
if (actualPath.charAt(actualPath.length() - 1) == '/') {
actualPath = actualPath.substring(0, actualPath.length() - 1);
}
if (actualPath.startsWith("/src") || actualPath.startsWith("/bin")) { //$NON-NLS-1$ //$NON-NLS-2$
actualPath = actualPath.substring(actualPath.indexOf('/', 2));
}
final String filePattern = "*." + IAcceleoConstants.EMTL_FILE_EXTENSION; //$NON-NLS-1$
Enumeration<URL> emtlFiles = entry.getKey().findEntries("/", //$NON-NLS-1$
filePattern, true);
// no dynamic templates in this bundle
if (emtlFiles == null) {
AcceleoEnginePlugin.log(AcceleoEngineMessages.getString(
"AcceleoDynamicTemplatesEclipseUtil.MissingDynamicTemplates", entry.getKey() //$NON-NLS-1$
.getSymbolicName(), path), false);
return;
}
try {
while (emtlFiles.hasMoreElements()) {
final URL next = emtlFiles.nextElement();
String emtlPath = next.getPath();
emtlPath.substring(0, emtlPath.lastIndexOf('/'));
if (emtlPath.endsWith(actualPath)) {
final File moduleFile = new File(FileLocator.toFileURL(next).getFile());
if (moduleFile.exists() && moduleFile.canRead()) {
REGISTERED_MODULES.add(moduleFile);
}
}
}
} catch (IOException e) {
AcceleoEnginePlugin.log(e, false);
}
}
}
}
| private static void refreshModules() {
REGISTERED_MODULES.clear();
for (java.util.Map.Entry<Bundle, List<String>> entry : new LinkedHashSet<java.util.Map.Entry<Bundle, List<String>>>(
EXTENDING_BUNDLES.entrySet())) {
for (String path : entry.getValue()) {
String actualPath = path;
if (actualPath.charAt(0) != '/') {
actualPath = '/' + actualPath;
}
if (actualPath.charAt(actualPath.length() - 1) == '/') {
actualPath = actualPath.substring(0, actualPath.length() - 1);
}
if (actualPath.startsWith("/src") || actualPath.startsWith("/bin")) { //$NON-NLS-1$ //$NON-NLS-2$
int firstFragmentEnd = actualPath.indexOf('/', 2);
if (firstFragmentEnd > 0) {
actualPath = actualPath.substring(firstFragmentEnd);
} else {
actualPath = "/"; //$NON-NLS-1$
}
}
final String filePattern = "*." + IAcceleoConstants.EMTL_FILE_EXTENSION; //$NON-NLS-1$
Enumeration<URL> emtlFiles = entry.getKey().findEntries("/", //$NON-NLS-1$
filePattern, true);
// no dynamic templates in this bundle
if (emtlFiles == null) {
AcceleoEnginePlugin.log(AcceleoEngineMessages.getString(
"AcceleoDynamicTemplatesEclipseUtil.MissingDynamicTemplates", entry.getKey() //$NON-NLS-1$
.getSymbolicName(), path), false);
return;
}
try {
while (emtlFiles.hasMoreElements()) {
final URL next = emtlFiles.nextElement();
String emtlPath = next.getPath();
emtlPath.substring(0, emtlPath.lastIndexOf('/'));
if (emtlPath.endsWith(actualPath)) {
final File moduleFile = new File(FileLocator.toFileURL(next).getFile());
if (moduleFile.exists() && moduleFile.canRead()) {
REGISTERED_MODULES.add(moduleFile);
}
}
}
} catch (IOException e) {
AcceleoEnginePlugin.log(e, false);
}
}
}
}
|
diff --git a/src/main/java/pairs/ui/TextDisplayBox.java b/src/main/java/pairs/ui/TextDisplayBox.java
index b6112dc..e426d59 100644
--- a/src/main/java/pairs/ui/TextDisplayBox.java
+++ b/src/main/java/pairs/ui/TextDisplayBox.java
@@ -1,83 +1,83 @@
/*
Pairs, a concentration game with modular card packages.
Copyright © 2012 Alexander Klauer
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package pairs.ui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import org.apache.log4j.Logger;
import pairs.util.Resources;
import static pairs.util.Message._;
/**
* Box displaying text from a resource.
*/
class TextDisplayBox extends JDialog {
/**
* Logger for this class.
*/
private static final Logger logger = Logger.getLogger( TextDisplayBox.class );
/**
* Creates a new text display box.
*
* @param owner Owner of the display box.
* @param titleKey Title key for the dialog title.
* @param resourceName Resource name for the text to be displayed.
*/
TextDisplayBox( Dialog owner, String titleKey, String resourceName ) {
super( owner, _( titleKey ) );
/* Dispose on close */
setDefaultCloseOperation( DISPOSE_ON_CLOSE );
/* Load resource */
String text;
try {
text = Resources.loadResourceAsString( resourceName );
} catch ( Exception e ) {
String errorMsg = _( "error-loadingtext", resourceName );
logger.error( errorMsg, e );
JOptionPane.showMessageDialog( this, errorMsg, _( "error" ), JOptionPane.ERROR_MESSAGE );
dispose();
return;
}
/* Layout */
setLayout( new BorderLayout() );
JTextArea textArea = new JTextArea( text, 20, 0 );
textArea.setEditable( false );
JScrollPane scrollPane = new JScrollPane( textArea );
- add( scrollPane, BorderLayout.NORTH );
+ add( scrollPane, BorderLayout.CENTER );
add( new JButton( new ButtonAction( "button-close" ) {
public void actionPerformed( ActionEvent e ) {
TextDisplayBox.this.dispose();
}
} ), BorderLayout.SOUTH );
/* Display */
pack();
setLocationRelativeTo( null );
setVisible( true );
}
}
| true | true | TextDisplayBox( Dialog owner, String titleKey, String resourceName ) {
super( owner, _( titleKey ) );
/* Dispose on close */
setDefaultCloseOperation( DISPOSE_ON_CLOSE );
/* Load resource */
String text;
try {
text = Resources.loadResourceAsString( resourceName );
} catch ( Exception e ) {
String errorMsg = _( "error-loadingtext", resourceName );
logger.error( errorMsg, e );
JOptionPane.showMessageDialog( this, errorMsg, _( "error" ), JOptionPane.ERROR_MESSAGE );
dispose();
return;
}
/* Layout */
setLayout( new BorderLayout() );
JTextArea textArea = new JTextArea( text, 20, 0 );
textArea.setEditable( false );
JScrollPane scrollPane = new JScrollPane( textArea );
add( scrollPane, BorderLayout.NORTH );
add( new JButton( new ButtonAction( "button-close" ) {
public void actionPerformed( ActionEvent e ) {
TextDisplayBox.this.dispose();
}
} ), BorderLayout.SOUTH );
/* Display */
pack();
setLocationRelativeTo( null );
setVisible( true );
}
| TextDisplayBox( Dialog owner, String titleKey, String resourceName ) {
super( owner, _( titleKey ) );
/* Dispose on close */
setDefaultCloseOperation( DISPOSE_ON_CLOSE );
/* Load resource */
String text;
try {
text = Resources.loadResourceAsString( resourceName );
} catch ( Exception e ) {
String errorMsg = _( "error-loadingtext", resourceName );
logger.error( errorMsg, e );
JOptionPane.showMessageDialog( this, errorMsg, _( "error" ), JOptionPane.ERROR_MESSAGE );
dispose();
return;
}
/* Layout */
setLayout( new BorderLayout() );
JTextArea textArea = new JTextArea( text, 20, 0 );
textArea.setEditable( false );
JScrollPane scrollPane = new JScrollPane( textArea );
add( scrollPane, BorderLayout.CENTER );
add( new JButton( new ButtonAction( "button-close" ) {
public void actionPerformed( ActionEvent e ) {
TextDisplayBox.this.dispose();
}
} ), BorderLayout.SOUTH );
/* Display */
pack();
setLocationRelativeTo( null );
setVisible( true );
}
|
diff --git a/com.ifedorenko.m2e.mavendev/src/com/ifedorenko/m2e/mavendev/internal/launching/MavenITLaunchConfigurationTabGroup.java b/com.ifedorenko.m2e.mavendev/src/com/ifedorenko/m2e/mavendev/internal/launching/MavenITLaunchConfigurationTabGroup.java
index 1abd8a2..00f3df6 100644
--- a/com.ifedorenko.m2e.mavendev/src/com/ifedorenko/m2e/mavendev/internal/launching/MavenITLaunchConfigurationTabGroup.java
+++ b/com.ifedorenko.m2e.mavendev/src/com/ifedorenko/m2e/mavendev/internal/launching/MavenITLaunchConfigurationTabGroup.java
@@ -1,114 +1,114 @@
/*******************************************************************************
* Copyright (c) 2012 Igor Fedorenko
* 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:
* Igor Fedorenko - initial API and implementation
*******************************************************************************/
package com.ifedorenko.m2e.mavendev.internal.launching;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.ui.AbstractLaunchConfigurationTabGroup;
import org.eclipse.debug.ui.CommonTab;
import org.eclipse.debug.ui.EnvironmentTab;
import org.eclipse.debug.ui.ILaunchConfigurationDialog;
import org.eclipse.debug.ui.ILaunchConfigurationTab;
import org.eclipse.debug.ui.sourcelookup.SourceLookupTab;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.debug.ui.launchConfigurations.JavaArgumentsTab;
import org.eclipse.jdt.debug.ui.launchConfigurations.JavaClasspathTab;
import org.eclipse.jdt.debug.ui.launchConfigurations.JavaJRETab;
import org.eclipse.jdt.junit.launcher.JUnitLaunchConfigurationTab;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.m2e.actions.MavenLaunchConstants;
import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.project.IMavenProjectFacade;
import org.eclipse.m2e.core.project.ResolverConfiguration;
import org.eclipse.m2e.internal.launch.MavenLaunchParticipantInfo;
import org.eclipse.m2e.ui.internal.launch.MavenLaunchExtensionsTab;
@SuppressWarnings( "restriction" )
public class MavenITLaunchConfigurationTabGroup
extends AbstractLaunchConfigurationTabGroup
{
@Override
public void createTabs( ILaunchConfigurationDialog dialog, String mode )
{
List<ILaunchConfigurationTab> tabs = new ArrayList<ILaunchConfigurationTab>();
tabs.add( new JUnitLaunchConfigurationTab() );
tabs.add( new MavenITLaunchConfigurationTab() );
tabs.add( new JavaArgumentsTab() );
tabs.add( new JavaClasspathTab() );
tabs.add( new JavaJRETab() );
tabs.add( new SourceLookupTab() );
List<MavenLaunchParticipantInfo> participants = MavenLaunchParticipantInfo.readParticipantsInfo();
if ( !participants.isEmpty() )
{
tabs.add( new MavenLaunchExtensionsTab( participants ) );
}
tabs.add( new EnvironmentTab() );
tabs.add( new CommonTab() );
setTabs( tabs.toArray( new ILaunchConfigurationTab[tabs.size()] ) );
}
@Override
public void performApply( ILaunchConfigurationWorkingCopy configuration )
{
super.performApply( configuration );
String projectName;
try
{
projectName =
configuration.getAttribute( IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String) null );
}
catch ( CoreException e )
{
return;
}
- if ( projectName == null )
+ if ( projectName == null || projectName.trim().isEmpty() )
{
return;
}
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject( projectName );
if ( project == null || JavaCore.create( project ) == null )
{
return;
}
IMavenProjectFacade facade = //
MavenPlugin.getMavenProjectRegistry().create( project, new NullProgressMonitor() ); // XXX yikes
if ( facade == null )
{
return;
}
ResolverConfiguration resolverConfiguration = facade.getResolverConfiguration();
configuration.setAttribute( MavenLaunchConstants.ATTR_WORKSPACE_RESOLUTION,
resolverConfiguration.shouldResolveWorkspaceProjects() );
configuration.setAttribute( IJavaLaunchConfigurationConstants.ATTR_CLASSPATH_PROVIDER,
MavenITClasspathProvider.MAVENIT_CLASSPATH_PROVIDER );
configuration.setAttribute( IJavaLaunchConfigurationConstants.ATTR_SOURCE_PATH_PROVIDER,
MavenITSourcepathProvider.MAVENIT_SOURCEPATH_PROVIDER );
}
}
| true | true | public void performApply( ILaunchConfigurationWorkingCopy configuration )
{
super.performApply( configuration );
String projectName;
try
{
projectName =
configuration.getAttribute( IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String) null );
}
catch ( CoreException e )
{
return;
}
if ( projectName == null )
{
return;
}
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject( projectName );
if ( project == null || JavaCore.create( project ) == null )
{
return;
}
IMavenProjectFacade facade = //
MavenPlugin.getMavenProjectRegistry().create( project, new NullProgressMonitor() ); // XXX yikes
if ( facade == null )
{
return;
}
ResolverConfiguration resolverConfiguration = facade.getResolverConfiguration();
configuration.setAttribute( MavenLaunchConstants.ATTR_WORKSPACE_RESOLUTION,
resolverConfiguration.shouldResolveWorkspaceProjects() );
configuration.setAttribute( IJavaLaunchConfigurationConstants.ATTR_CLASSPATH_PROVIDER,
MavenITClasspathProvider.MAVENIT_CLASSPATH_PROVIDER );
configuration.setAttribute( IJavaLaunchConfigurationConstants.ATTR_SOURCE_PATH_PROVIDER,
MavenITSourcepathProvider.MAVENIT_SOURCEPATH_PROVIDER );
}
| public void performApply( ILaunchConfigurationWorkingCopy configuration )
{
super.performApply( configuration );
String projectName;
try
{
projectName =
configuration.getAttribute( IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, (String) null );
}
catch ( CoreException e )
{
return;
}
if ( projectName == null || projectName.trim().isEmpty() )
{
return;
}
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject( projectName );
if ( project == null || JavaCore.create( project ) == null )
{
return;
}
IMavenProjectFacade facade = //
MavenPlugin.getMavenProjectRegistry().create( project, new NullProgressMonitor() ); // XXX yikes
if ( facade == null )
{
return;
}
ResolverConfiguration resolverConfiguration = facade.getResolverConfiguration();
configuration.setAttribute( MavenLaunchConstants.ATTR_WORKSPACE_RESOLUTION,
resolverConfiguration.shouldResolveWorkspaceProjects() );
configuration.setAttribute( IJavaLaunchConfigurationConstants.ATTR_CLASSPATH_PROVIDER,
MavenITClasspathProvider.MAVENIT_CLASSPATH_PROVIDER );
configuration.setAttribute( IJavaLaunchConfigurationConstants.ATTR_SOURCE_PATH_PROVIDER,
MavenITSourcepathProvider.MAVENIT_SOURCEPATH_PROVIDER );
}
|
diff --git a/plugins/com.aptana.ide.core.io/src/com/aptana/ide/core/io/internal/DeleteResourceShortcutListener.java b/plugins/com.aptana.ide.core.io/src/com/aptana/ide/core/io/internal/DeleteResourceShortcutListener.java
index 8eb5164a..beb2e994 100644
--- a/plugins/com.aptana.ide.core.io/src/com/aptana/ide/core/io/internal/DeleteResourceShortcutListener.java
+++ b/plugins/com.aptana.ide.core.io/src/com/aptana/ide/core/io/internal/DeleteResourceShortcutListener.java
@@ -1,112 +1,117 @@
/**
* This file Copyright (c) 2005-2009 Aptana, Inc. This program is
* dual-licensed under both the Aptana Public License and the GNU General
* Public license. You may elect to use one or the other of these licenses.
*
* This program is distributed in the hope that it will be useful, but
* AS-IS and WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, TITLE, or
* NONINFRINGEMENT. Redistribution, except as permitted by whichever of
* the GPL or APL you select, is prohibited.
*
* 1. For the GPL license (GPL), you can redistribute and/or modify this
* program under the terms of the GNU General Public License,
* Version 3, as published by the Free Software Foundation. You should
* have received a copy of the GNU General Public License, Version 3 along
* with this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Aptana provides a special exception to allow redistribution of this file
* with certain other free and open source software ("FOSS") code and certain additional terms
* pursuant to Section 7 of the GPL. You may view the exception and these
* terms on the web at http://www.aptana.com/legal/gpl/.
*
* 2. For the Aptana Public License (APL), this program and the
* accompanying materials are made available under the terms of the APL
* v1.0 which accompanies this distribution, and is available at
* http://www.aptana.com/legal/apl/.
*
* You may view the GPL, Aptana's exception and additional terms, and the
* APL in the file titled license.html at the root of the corresponding
* plugin containing this source file.
*
* Any modifications to this file must keep this entire header intact.
*/
package com.aptana.ide.core.io.internal;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import com.aptana.ide.core.io.CoreIOPlugin;
import com.aptana.ide.core.io.IConnectionPoint;
import com.aptana.ide.core.io.IConnectionPointManager;
import com.aptana.ide.core.io.WorkspaceConnectionPoint;
/**
* Deletes its corresponding project shortcuts when a resource is deleted.
*
* @author Michael Xia ([email protected])
*/
public class DeleteResourceShortcutListener implements IResourceChangeListener {
private static final String CATEGORY_ID = "com.aptana.ide.core.io.projectShortcuts"; //$NON-NLS-1$
/**
* @see org.eclipse.core.resources.IResourceChangeListener#resourceChanged(org.eclipse.core.resources.IResourceChangeEvent)
*/
public void resourceChanged(IResourceChangeEvent event) {
IResourceDelta delta = event.getDelta();
switch (delta.getKind()) {
case IResourceDelta.REMOVED:
break;
case IResourceDelta.CHANGED:
List<IConnectionPoint> deleted = new ArrayList<IConnectionPoint>();
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IConnectionPointManager manager = CoreIOPlugin.getConnectionPointManager();
IConnectionPoint[] projectShortcuts = manager.getConnectionPointCategory(CATEGORY_ID)
.getConnectionPoints();
WorkspaceConnectionPoint connectionPoint;
for (IConnectionPoint shortcut : projectShortcuts) {
connectionPoint = (WorkspaceConnectionPoint) shortcut;
// see if the relative path matches the changed item
IResourceDelta d = delta.findMember(connectionPoint.getPath());
if (d != null && d.getKind() == IResourceDelta.REMOVED) {
if (d.getMovedToPath() == null) {
- // the original container was deleted
- deleted.add(shortcut);
+ IResource resource = d.getResource();
+ if (!(resource instanceof IProject) && resource.getProject().exists() && !resource.getProject().isOpen())
+ {
+ continue;
+ }
+ // the original container was deleted
+ deleted.add(shortcut);
} else {
// the original container was moved
IPath newPath = d.getMovedToPath();
IContainer newContainer;
if (d.getResource() instanceof IProject) {
newContainer = root.getProject(newPath.toString());
} else {
newContainer = root.getFolder(newPath);
}
connectionPoint.setResource(newContainer);
connectionPoint.setName(newContainer.getName());
}
}
}
// if the item was deleted, remove it
for (IConnectionPoint projectShortcut : deleted) {
manager.removeConnectionPoint(projectShortcut);
}
break;
}
}
}
| true | true | public void resourceChanged(IResourceChangeEvent event) {
IResourceDelta delta = event.getDelta();
switch (delta.getKind()) {
case IResourceDelta.REMOVED:
break;
case IResourceDelta.CHANGED:
List<IConnectionPoint> deleted = new ArrayList<IConnectionPoint>();
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IConnectionPointManager manager = CoreIOPlugin.getConnectionPointManager();
IConnectionPoint[] projectShortcuts = manager.getConnectionPointCategory(CATEGORY_ID)
.getConnectionPoints();
WorkspaceConnectionPoint connectionPoint;
for (IConnectionPoint shortcut : projectShortcuts) {
connectionPoint = (WorkspaceConnectionPoint) shortcut;
// see if the relative path matches the changed item
IResourceDelta d = delta.findMember(connectionPoint.getPath());
if (d != null && d.getKind() == IResourceDelta.REMOVED) {
if (d.getMovedToPath() == null) {
// the original container was deleted
deleted.add(shortcut);
} else {
// the original container was moved
IPath newPath = d.getMovedToPath();
IContainer newContainer;
if (d.getResource() instanceof IProject) {
newContainer = root.getProject(newPath.toString());
} else {
newContainer = root.getFolder(newPath);
}
connectionPoint.setResource(newContainer);
connectionPoint.setName(newContainer.getName());
}
}
}
// if the item was deleted, remove it
for (IConnectionPoint projectShortcut : deleted) {
manager.removeConnectionPoint(projectShortcut);
}
break;
}
}
| public void resourceChanged(IResourceChangeEvent event) {
IResourceDelta delta = event.getDelta();
switch (delta.getKind()) {
case IResourceDelta.REMOVED:
break;
case IResourceDelta.CHANGED:
List<IConnectionPoint> deleted = new ArrayList<IConnectionPoint>();
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IConnectionPointManager manager = CoreIOPlugin.getConnectionPointManager();
IConnectionPoint[] projectShortcuts = manager.getConnectionPointCategory(CATEGORY_ID)
.getConnectionPoints();
WorkspaceConnectionPoint connectionPoint;
for (IConnectionPoint shortcut : projectShortcuts) {
connectionPoint = (WorkspaceConnectionPoint) shortcut;
// see if the relative path matches the changed item
IResourceDelta d = delta.findMember(connectionPoint.getPath());
if (d != null && d.getKind() == IResourceDelta.REMOVED) {
if (d.getMovedToPath() == null) {
IResource resource = d.getResource();
if (!(resource instanceof IProject) && resource.getProject().exists() && !resource.getProject().isOpen())
{
continue;
}
// the original container was deleted
deleted.add(shortcut);
} else {
// the original container was moved
IPath newPath = d.getMovedToPath();
IContainer newContainer;
if (d.getResource() instanceof IProject) {
newContainer = root.getProject(newPath.toString());
} else {
newContainer = root.getFolder(newPath);
}
connectionPoint.setResource(newContainer);
connectionPoint.setName(newContainer.getName());
}
}
}
// if the item was deleted, remove it
for (IConnectionPoint projectShortcut : deleted) {
manager.removeConnectionPoint(projectShortcut);
}
break;
}
}
|
diff --git a/test/com/google/inject/PrivateModuleTest.java b/test/com/google/inject/PrivateModuleTest.java
index d3b29e30..3beca2a4 100644
--- a/test/com/google/inject/PrivateModuleTest.java
+++ b/test/com/google/inject/PrivateModuleTest.java
@@ -1,423 +1,423 @@
/**
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.inject;
import static com.google.inject.Asserts.assertContains;
import com.google.inject.binder.PrivateBinder;
import com.google.inject.name.Named;
import static com.google.inject.name.Names.named;
import junit.framework.TestCase;
/**
* @author [email protected] (Jesse Wilson)
*/
public class PrivateModuleTest extends TestCase {
public void testBasicUsage() {
Injector injector = Guice.createInjector(new AbstractModule() {
protected void configure() {
bind(String.class).annotatedWith(named("a")).toInstance("public");
install(new PrivateModule() {
public void configurePrivateBindings() {
bind(String.class).annotatedWith(named("b")).toInstance("i");
bind(AB.class).annotatedWith(named("one")).to(AB.class);
expose(AB.class).annotatedWith(named("one"));
}
});
install(new PrivateModule() {
public void configurePrivateBindings() {
bind(String.class).annotatedWith(named("b")).toInstance("ii");
bind(AB.class).annotatedWith(named("two")).to(AB.class);
expose(AB.class).annotatedWith(named("two"));
}
});
}
});
AB ab1 = injector.getInstance(Key.get(AB.class, named("one")));
assertEquals("public", ab1.a);
assertEquals("i", ab1.b);
AB ab2 = injector.getInstance(Key.get(AB.class, named("two")));
assertEquals("public", ab2.a);
assertEquals("ii", ab2.b);
}
public void testWithoutPrivateModules() {
Injector injector = Guice.createInjector(new AbstractModule() {
protected void configure() {
PrivateBinder bindA = binder().newPrivateBinder();
bindA.bind(String.class).annotatedWith(named("a")).toInstance("i");
bindA.expose(String.class).annotatedWith(named("a"));
bindA.bind(String.class).annotatedWith(named("c")).toInstance("private to A");
PrivateBinder bindB = binder().newPrivateBinder();
bindB.bind(String.class).annotatedWith(named("b")).toInstance("ii");
bindB.expose(String.class).annotatedWith(named("b"));
bindB.bind(String.class).annotatedWith(named("c")).toInstance("private to B");
}
});
assertEquals("i", injector.getInstance(Key.get(String.class, named("a"))));
assertEquals("ii", injector.getInstance(Key.get(String.class, named("b"))));
}
public void testMisplacedExposedAnnotation() {
try {
Guice.createInjector(new AbstractModule() {
protected void configure() {}
@Provides @Exposed
String provideString() {
return "i";
}
});
fail();
} catch (CreationException expected) {
assertContains(expected.getMessage(), "Cannot expose java.lang.String on a standard binder. ",
"Exposed bindings are only applicable to private binders.",
" at " + PrivateModuleTest.class.getName(), "provideString(PrivateModuleTest.java:");
}
}
public void testMisplacedExposeStatement() {
try {
Guice.createInjector(new AbstractModule() {
protected void configure() {
((PrivateBinder) binder()).expose(String.class).annotatedWith(named("a"));
}
});
fail();
} catch (CreationException expected) {
assertContains(expected.getMessage(), "Cannot expose java.lang.String on a standard binder. ",
"Exposed bindings are only applicable to private binders.",
" at " + PrivateModuleTest.class.getName(), "configure(PrivateModuleTest.java:");
}
}
public void testPrivateModulesAndProvidesMethods() {
Injector injector = Guice.createInjector(new AbstractModule() {
protected void configure() {
install(new PrivateModule() {
public void configurePrivateBindings() {
expose(String.class).annotatedWith(named("a"));
}
@Provides @Named("a") String providePublicA() {
return "i";
}
@Provides @Named("b") String providePrivateB() {
return "private";
}
});
install(new PrivateModule() {
public void configurePrivateBindings() {}
@Provides @Named("c") String providePrivateC() {
return "private";
}
@Provides @Exposed @Named("d") String providePublicD() {
return "ii";
}
});
}
});
assertEquals("i", injector.getInstance(Key.get(String.class, named("a"))));
try {
- injector.getInstance(Key.get(String.class, named("c")));
+ injector.getInstance(Key.get(String.class, named("b")));
fail();
} catch(ConfigurationException expected) {
}
try {
- injector.getInstance(Key.get(String.class, named("d")));
+ injector.getInstance(Key.get(String.class, named("c")));
fail();
} catch(ConfigurationException expected) {
}
assertEquals("ii", injector.getInstance(Key.get(String.class, named("d"))));
}
public void testCannotBindAKeyExportedByASibling() {
try {
Guice.createInjector(new AbstractModule() {
protected void configure() {
install(new PrivateModule() {
public void configurePrivateBindings() {
bind(String.class).toInstance("public");
expose(String.class);
}
});
install(new PrivateModule() {
public void configurePrivateBindings() {
bind(String.class).toInstance("private");
}
});
}
});
fail();
} catch (CreationException expected) {
assertContains(expected.getMessage(),
"A binding to java.lang.String was already configured at ",
getClass().getName(), ".configurePrivateBindings(PrivateModuleTest.java:",
" at " + getClass().getName(), ".configurePrivateBindings(PrivateModuleTest.java:");
}
}
public void testExposeButNoBind() {
try {
Guice.createInjector(new AbstractModule() {
protected void configure() {
bind(String.class).annotatedWith(named("a")).toInstance("a");
bind(String.class).annotatedWith(named("b")).toInstance("b");
install(new PrivateModule() {
public void configurePrivateBindings() {
expose(AB.class);
}
});
}
});
fail("AB was exposed but not bound");
} catch (CreationException expected) {
assertContains(expected.getMessage(),
"Could not expose() " + AB.class.getName() + ", it must be explicitly bound",
".configurePrivateBindings(PrivateModuleTest.java:");
}
}
/**
* Ensure that when we've got errors in different private modules, Guice presents all errors
* in a unified message.
*/
public void testMessagesFromPrivateModulesAreNicelyIntegrated() {
try {
Guice.createInjector(
new PrivateModule() {
public void configurePrivateBindings() {
bind(C.class);
}
},
new PrivateModule() {
public void configurePrivateBindings() {
bind(AB.class);
}
}
);
fail();
} catch (CreationException expected) {
assertContains(expected.getMessage(),
"1) No implementation for " + C.class.getName() + " was bound.",
"at " + getClass().getName(), ".configurePrivateBindings(PrivateModuleTest.java:",
"2) No implementation for " + String.class.getName(), "Named(value=a) was bound.",
"for field at " + AB.class.getName() + ".a(PrivateModuleTest.java:",
"3) No implementation for " + String.class.getName(), "Named(value=b) was bound.",
"for field at " + AB.class.getName() + ".b(PrivateModuleTest.java:",
"3 errors");
}
}
public void testNestedPrivateInjectors() {
Injector injector = Guice.createInjector(new PrivateModule() {
public void configurePrivateBindings() {
expose(String.class);
install(new PrivateModule() {
public void configurePrivateBindings() {
bind(String.class).toInstance("nested");
expose(String.class);
}
});
}
});
assertEquals("nested", injector.getInstance(String.class));
}
public void testInstallingRegularModulesFromPrivateModules() {
Injector injector = Guice.createInjector(new PrivateModule() {
public void configurePrivateBindings() {
expose(String.class);
install(new AbstractModule() {
protected void configure() {
bind(String.class).toInstance("nested");
}
});
}
});
assertEquals("nested", injector.getInstance(String.class));
}
public void testNestedPrivateModulesWithSomeKeysUnexposed() {
Injector injector = Guice.createInjector(new PrivateModule() {
public void configurePrivateBindings() {
bind(String.class).annotatedWith(named("bound outer, exposed outer")).toInstance("boeo");
expose(String.class).annotatedWith(named("bound outer, exposed outer"));
bind(String.class).annotatedWith(named("bound outer, exposed none")).toInstance("boen");
expose(String.class).annotatedWith(named("bound inner, exposed both"));
install(new PrivateModule() {
public void configurePrivateBindings() {
bind(String.class).annotatedWith(named("bound inner, exposed both")).toInstance("bieb");
expose(String.class).annotatedWith(named("bound inner, exposed both"));
bind(String.class).annotatedWith(named("bound inner, exposed none")).toInstance("bien");
}
});
}
});
assertEquals("boeo",
injector.getInstance(Key.get(String.class, named("bound outer, exposed outer"))));
assertEquals("bieb",
injector.getInstance(Key.get(String.class, named("bound inner, exposed both"))));
try {
injector.getInstance(Key.get(String.class, named("bound outer, exposed none")));
fail();
} catch (ConfigurationException expected) {
}
try {
injector.getInstance(Key.get(String.class, named("bound inner, exposed none")));
fail();
} catch (ConfigurationException expected) {
}
}
public void testDependenciesBetweenPrivateAndPublic() {
Injector injector = Guice.createInjector(
new PrivateModule() {
protected void configurePrivateBindings() {}
@Provides @Exposed @Named("a") String provideA() {
return "A";
}
@Provides @Exposed @Named("abc") String provideAbc(@Named("ab") String ab) {
return ab + "C";
}
},
new AbstractModule() {
protected void configure() {}
@Provides @Named("ab") String provideAb(@Named("a") String a) {
return a + "B";
}
@Provides @Named("abcd") String provideAbcd(@Named("abc") String abc) {
return abc + "D";
}
}
);
assertEquals("ABCD", injector.getInstance(Key.get(String.class, named("abcd"))));
}
public void testDependenciesBetweenPrivateAndPublicWithPublicEagerSingleton() {
Injector injector = Guice.createInjector(
new PrivateModule() {
protected void configurePrivateBindings() {}
@Provides @Exposed @Named("a") String provideA() {
return "A";
}
@Provides @Exposed @Named("abc") String provideAbc(@Named("ab") String ab) {
return ab + "C";
}
},
new AbstractModule() {
protected void configure() {
bind(String.class).annotatedWith(named("abcde")).toProvider(new Provider<String>() {
@Inject @Named("abcd") String abcd;
public String get() {
return abcd + "E";
}
}).asEagerSingleton();
}
@Provides @Named("ab") String provideAb(@Named("a") String a) {
return a + "B";
}
@Provides @Named("abcd") String provideAbcd(@Named("abc") String abc) {
return abc + "D";
}
}
);
assertEquals("ABCDE", injector.getInstance(Key.get(String.class, named("abcde"))));
}
public void testDependenciesBetweenPrivateAndPublicWithPrivateEagerSingleton() {
Injector injector = Guice.createInjector(
new AbstractModule() {
protected void configure() {}
@Provides @Named("ab") String provideAb(@Named("a") String a) {
return a + "B";
}
@Provides @Named("abcd") String provideAbcd(@Named("abc") String abc) {
return abc + "D";
}
},
new PrivateModule() {
protected void configurePrivateBindings() {
bind(String.class).annotatedWith(named("abcde")).toProvider(new Provider<String>() {
@Inject @Named("abcd") String abcd;
public String get() {
return abcd + "E";
}
}).asEagerSingleton();
expose(String.class).annotatedWith(named("abcde"));
}
@Provides @Exposed @Named("a") String provideA() {
return "A";
}
@Provides @Exposed @Named("abc") String provideAbc(@Named("ab") String ab) {
return ab + "C";
}
}
);
assertEquals("ABCDE", injector.getInstance(Key.get(String.class, named("abcde"))));
}
static class AB {
@Inject @Named("a") String a;
@Inject @Named("b") String b;
}
interface C {}
}
| false | true | public void testPrivateModulesAndProvidesMethods() {
Injector injector = Guice.createInjector(new AbstractModule() {
protected void configure() {
install(new PrivateModule() {
public void configurePrivateBindings() {
expose(String.class).annotatedWith(named("a"));
}
@Provides @Named("a") String providePublicA() {
return "i";
}
@Provides @Named("b") String providePrivateB() {
return "private";
}
});
install(new PrivateModule() {
public void configurePrivateBindings() {}
@Provides @Named("c") String providePrivateC() {
return "private";
}
@Provides @Exposed @Named("d") String providePublicD() {
return "ii";
}
});
}
});
assertEquals("i", injector.getInstance(Key.get(String.class, named("a"))));
try {
injector.getInstance(Key.get(String.class, named("c")));
fail();
} catch(ConfigurationException expected) {
}
try {
injector.getInstance(Key.get(String.class, named("d")));
fail();
} catch(ConfigurationException expected) {
}
assertEquals("ii", injector.getInstance(Key.get(String.class, named("d"))));
}
| public void testPrivateModulesAndProvidesMethods() {
Injector injector = Guice.createInjector(new AbstractModule() {
protected void configure() {
install(new PrivateModule() {
public void configurePrivateBindings() {
expose(String.class).annotatedWith(named("a"));
}
@Provides @Named("a") String providePublicA() {
return "i";
}
@Provides @Named("b") String providePrivateB() {
return "private";
}
});
install(new PrivateModule() {
public void configurePrivateBindings() {}
@Provides @Named("c") String providePrivateC() {
return "private";
}
@Provides @Exposed @Named("d") String providePublicD() {
return "ii";
}
});
}
});
assertEquals("i", injector.getInstance(Key.get(String.class, named("a"))));
try {
injector.getInstance(Key.get(String.class, named("b")));
fail();
} catch(ConfigurationException expected) {
}
try {
injector.getInstance(Key.get(String.class, named("c")));
fail();
} catch(ConfigurationException expected) {
}
assertEquals("ii", injector.getInstance(Key.get(String.class, named("d"))));
}
|
diff --git a/src/com/rabbitmq/client/impl/ChannelManager.java b/src/com/rabbitmq/client/impl/ChannelManager.java
index 72d6178d6..98e37b541 100644
--- a/src/com/rabbitmq/client/impl/ChannelManager.java
+++ b/src/com/rabbitmq/client/impl/ChannelManager.java
@@ -1,137 +1,137 @@
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (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.mozilla.org/MPL/
//
// 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.
//
// The Original Code is RabbitMQ.
//
// The Initial Developers of the Original Code are LShift Ltd,
// Cohesive Financial Technologies LLC, and Rabbit Technologies Ltd.
//
// Portions created before 22-Nov-2008 00:00:00 GMT by LShift Ltd,
// Cohesive Financial Technologies LLC, or Rabbit Technologies Ltd
// are Copyright (C) 2007-2008 LShift Ltd, Cohesive Financial
// Technologies LLC, and Rabbit Technologies Ltd.
//
// Portions created by LShift Ltd are Copyright (C) 2007-2010 LShift
// Ltd. Portions created by Cohesive Financial Technologies LLC are
// Copyright (C) 2007-2010 Cohesive Financial Technologies
// LLC. Portions created by Rabbit Technologies Ltd are Copyright
// (C) 2007-2010 Rabbit Technologies Ltd.
//
// All Rights Reserved.
//
// Contributor(s): ______________________________________.
//
package com.rabbitmq.client.impl;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.rabbitmq.client.ShutdownSignalException;
import com.rabbitmq.utility.IntAllocator;
/**
* Manages a set of channels, indexed by channel number.
*/
public class ChannelManager {
/** Mapping from channel number to AMQChannel instance */
private final Map<Integer, ChannelN> _channelMap = Collections.synchronizedMap(new HashMap<Integer, ChannelN>());
private final IntAllocator channelNumberAllocator;
/** Maximum channel number available on this connection. */
public final int _channelMax;
public int getChannelMax(){
return _channelMax;
}
public ChannelManager(int channelMax){
if(channelMax == 0){
// The framing encoding only allows for unsigned 16-bit integers for the channel number
channelMax = (1 << 16) - 1;
}
_channelMax = channelMax;
channelNumberAllocator = new IntAllocator(1, channelMax);
}
/**
* Public API - Looks up an existing channel associated with this connection.
* @param channelNumber the number of the required channel
* @return the relevant channel descriptor
* @throws UnknownChannelException if there is no Channel associated with the
* required channel number.
*/
public ChannelN getChannel(int channelNumber) {
ChannelN result = _channelMap.get(channelNumber);
if(result == null) throw new UnknownChannelException(channelNumber);
return result;
}
public void handleSignal(ShutdownSignalException signal) {
Set<ChannelN> channels;
synchronized(_channelMap) {
channels = new HashSet<ChannelN>(_channelMap.values());
}
for (AMQChannel channel : channels) {
disconnectChannel(channel.getChannelNumber());
channel.processShutdownSignal(signal, true, true);
}
}
public synchronized ChannelN createChannel(AMQConnection connection) throws IOException {
int channelNumber = channelNumberAllocator.allocate();
if (channelNumber == -1) {
return null;
}
return createChannelInternal(connection, channelNumber);
}
public synchronized ChannelN createChannel(AMQConnection connection, int channelNumber) throws IOException {
if(channelNumberAllocator.reserve(channelNumber))
return createChannelInternal(connection, channelNumber);
else
return null;
}
private synchronized ChannelN createChannelInternal(AMQConnection connection, int channelNumber) throws IOException {
if (_channelMap.containsKey(channelNumber)) {
// That number's already allocated! Can't do it
// This should never happen unless something has gone
// badly wrong with our implementation.
- throw new IllegalStateException("We have attempted to"
- + "create a channel with a number that is already in"
+ throw new IllegalStateException("We have attempted to "
+ + "create a channel with a number that is already in "
+ "use. This should never happen. Please report this as a bug.");
}
ChannelN ch = new ChannelN(connection, channelNumber);
addChannel(ch);
ch.open(); // now that it's been added to our internal tables
return ch;
}
private void addChannel(ChannelN chan) {
_channelMap.put(chan.getChannelNumber(), chan);
}
public synchronized void disconnectChannel(int channelNumber) {
if (_channelMap.remove(channelNumber) == null)
throw new IllegalStateException(
"We have attempted to "
+ "create a disconnect a channel that's no longer in "
+ "use. This should never happen. Please report this as a bug.");
System.err.println("DISCONN CH" + channelNumber);
channelNumberAllocator.free(channelNumber);
}
}
| true | true | private synchronized ChannelN createChannelInternal(AMQConnection connection, int channelNumber) throws IOException {
if (_channelMap.containsKey(channelNumber)) {
// That number's already allocated! Can't do it
// This should never happen unless something has gone
// badly wrong with our implementation.
throw new IllegalStateException("We have attempted to"
+ "create a channel with a number that is already in"
+ "use. This should never happen. Please report this as a bug.");
}
ChannelN ch = new ChannelN(connection, channelNumber);
addChannel(ch);
ch.open(); // now that it's been added to our internal tables
return ch;
}
| private synchronized ChannelN createChannelInternal(AMQConnection connection, int channelNumber) throws IOException {
if (_channelMap.containsKey(channelNumber)) {
// That number's already allocated! Can't do it
// This should never happen unless something has gone
// badly wrong with our implementation.
throw new IllegalStateException("We have attempted to "
+ "create a channel with a number that is already in "
+ "use. This should never happen. Please report this as a bug.");
}
ChannelN ch = new ChannelN(connection, channelNumber);
addChannel(ch);
ch.open(); // now that it's been added to our internal tables
return ch;
}
|
diff --git a/src/xmlvm/org/xmlvm/proc/out/ObjectiveCOutputProcess.java b/src/xmlvm/org/xmlvm/proc/out/ObjectiveCOutputProcess.java
index 4e0f796b..a309f8f6 100755
--- a/src/xmlvm/org/xmlvm/proc/out/ObjectiveCOutputProcess.java
+++ b/src/xmlvm/org/xmlvm/proc/out/ObjectiveCOutputProcess.java
@@ -1,164 +1,164 @@
/*
* Copyright (c) 2004-2009 XMLVM --- An XML-based Programming Language
*
* 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., 675 Mass
* Ave, Cambridge, MA 02139, USA.
*
* For more information, visit the XMLVM Home Page at http://www.xmlvm.org
*/
package org.xmlvm.proc.out;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.xmlvm.main.Arguments;
import org.xmlvm.proc.XmlvmResource;
import org.xmlvm.proc.XsltRunner;
import org.xmlvm.proc.in.InputProcess;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
public class ObjectiveCOutputProcess extends OutputProcess<InputProcess<?>> {
private static final String M_EXTENSION = ".m";
private static final String H_EXTENSION = ".h";
private List<OutputFile> result = new ArrayList<OutputFile>();
public ObjectiveCOutputProcess(Arguments arguments) {
super(arguments);
// We support any InputProcess as a valid input for JavaScript
// generation.
addSupportedInput(InputProcess.class);
}
@Override
public List<OutputFile> getOutputFiles() {
return result;
}
@Override
public boolean process() {
List<InputProcess<?>> preprocesses = preprocess();
for (InputProcess<?> process : preprocesses) {
XmlvmResource xmlvm = process.getXmlvm();
OutputFile[] files = genObjC(xmlvm);
for (OutputFile file : files) {
file.setLocation(arguments.option_out());
result.add(file);
}
}
return true;
}
/**
* From the given XmlvmResource creates a header as well as m-file.
*/
public OutputFile[] genObjC(XmlvmResource xmlvm) {
Document doc = xmlvm.getXmlvmDocument();
// The filename will be the name of the first class
Namespace nsXMLVM = Namespace.getNamespace("vm", "http://xmlvm.org");
Element clazz = doc.getRootElement().getChild("class", nsXMLVM);
String namespaceName = clazz.getAttributeValue("package");
- String inheritsFrom = clazz.getAttributeValue("extends").replace('.', '_');
+ String inheritsFrom = clazz.getAttributeValue("extends").replace('.', '_').replace('$', '_');
String className = clazz.getAttributeValue("name").replace('$', '_');
String fileNameStem = (namespaceName + "." + className).replace('.', '_');
String headerFileName = fileNameStem + H_EXTENSION;
String mFileName = fileNameStem + M_EXTENSION;
StringBuffer headerBuffer = new StringBuffer();
headerBuffer.append("#import \"xmlvm.h\"\n");
for (String i : getTypesForHeader(doc)) {
if (i.equals(inheritsFrom)) {
headerBuffer.append("#import \"" + i + ".h\"\n");
}
}
String interfaces = clazz.getAttributeValue("interfaces");
if (interfaces != null) {
for (String i : interfaces.split(",")) {
headerBuffer
.append("#import \"" + i.replace('.', '_').replace('$', '_') + ".h\"\n");
}
}
headerBuffer.append("\n// For circular include:\n");
for (String i : getTypesForHeader(doc)) {
headerBuffer.append("@class " + i + ";\n");
}
OutputFile headerFile = XsltRunner.runXSLT("xmlvm2objc.xsl", doc, new String[][] {
{ "pass", "emitHeader" }, { "header", headerFileName } });
headerFile.setData(headerBuffer.toString() + headerFile.getData());
headerFile.setFileName(headerFileName);
StringBuffer mBuffer = new StringBuffer();
for (String i : getTypesForHeader(doc)) {
String toIgnore = (namespaceName + "_" + className).replace('.', '_');
if (!i.equals(inheritsFrom) && !i.equals(toIgnore)) {
mBuffer.append("#import \"" + i + ".h\"\n");
}
}
OutputFile mFile = XsltRunner.runXSLT("xmlvm2objc.xsl", doc, new String[][] {
{ "pass", "emitImplementation" }, { "header", headerFileName } });
mFile.setData(mBuffer.toString() + mFile.getData());
mFile.setFileName(mFileName);
return new OutputFile[] { headerFile, mFile };
}
private List<String> getTypesForHeader(Document doc) {
HashSet<String> seen = new HashSet<String>();
@SuppressWarnings("unchecked")
Iterator i = doc.getDescendants();
while (i.hasNext()) {
Object cur = i.next();
if (cur instanceof Element) {
Attribute a = ((Element) cur).getAttribute("type");
if (a != null) {
seen.add(a.getValue());
}
a = ((Element) cur).getAttribute("extends");
if (a != null) {
seen.add(a.getValue());
}
a = ((Element) cur).getAttribute("interfaces");
if (a != null) {
for (String iface : a.getValue().split(",")) {
seen.add(iface);
}
}
a = ((Element) cur).getAttribute("class-type");
if (a != null) {
seen.add(a.getValue());
}
} else {
System.out.println(cur);
}
}
HashSet<String> bad = new HashSet<String>();
for (String t : new String[] { "char", "float", "double", "int", "void", "boolean",
"short", "byte", "float", "long" }) {
bad.add(t);
}
List<String> toRet = new ArrayList<String>();
for (String t : seen) {
if (!bad.contains(t) && t.indexOf("[]") == -1) {
toRet.add(t.replace('.', '_').replace('$', '_'));
}
}
return toRet;
}
}
| true | true | public OutputFile[] genObjC(XmlvmResource xmlvm) {
Document doc = xmlvm.getXmlvmDocument();
// The filename will be the name of the first class
Namespace nsXMLVM = Namespace.getNamespace("vm", "http://xmlvm.org");
Element clazz = doc.getRootElement().getChild("class", nsXMLVM);
String namespaceName = clazz.getAttributeValue("package");
String inheritsFrom = clazz.getAttributeValue("extends").replace('.', '_');
String className = clazz.getAttributeValue("name").replace('$', '_');
String fileNameStem = (namespaceName + "." + className).replace('.', '_');
String headerFileName = fileNameStem + H_EXTENSION;
String mFileName = fileNameStem + M_EXTENSION;
StringBuffer headerBuffer = new StringBuffer();
headerBuffer.append("#import \"xmlvm.h\"\n");
for (String i : getTypesForHeader(doc)) {
if (i.equals(inheritsFrom)) {
headerBuffer.append("#import \"" + i + ".h\"\n");
}
}
String interfaces = clazz.getAttributeValue("interfaces");
if (interfaces != null) {
for (String i : interfaces.split(",")) {
headerBuffer
.append("#import \"" + i.replace('.', '_').replace('$', '_') + ".h\"\n");
}
}
headerBuffer.append("\n// For circular include:\n");
for (String i : getTypesForHeader(doc)) {
headerBuffer.append("@class " + i + ";\n");
}
OutputFile headerFile = XsltRunner.runXSLT("xmlvm2objc.xsl", doc, new String[][] {
{ "pass", "emitHeader" }, { "header", headerFileName } });
headerFile.setData(headerBuffer.toString() + headerFile.getData());
headerFile.setFileName(headerFileName);
StringBuffer mBuffer = new StringBuffer();
for (String i : getTypesForHeader(doc)) {
String toIgnore = (namespaceName + "_" + className).replace('.', '_');
if (!i.equals(inheritsFrom) && !i.equals(toIgnore)) {
mBuffer.append("#import \"" + i + ".h\"\n");
}
}
OutputFile mFile = XsltRunner.runXSLT("xmlvm2objc.xsl", doc, new String[][] {
{ "pass", "emitImplementation" }, { "header", headerFileName } });
mFile.setData(mBuffer.toString() + mFile.getData());
mFile.setFileName(mFileName);
return new OutputFile[] { headerFile, mFile };
}
| public OutputFile[] genObjC(XmlvmResource xmlvm) {
Document doc = xmlvm.getXmlvmDocument();
// The filename will be the name of the first class
Namespace nsXMLVM = Namespace.getNamespace("vm", "http://xmlvm.org");
Element clazz = doc.getRootElement().getChild("class", nsXMLVM);
String namespaceName = clazz.getAttributeValue("package");
String inheritsFrom = clazz.getAttributeValue("extends").replace('.', '_').replace('$', '_');
String className = clazz.getAttributeValue("name").replace('$', '_');
String fileNameStem = (namespaceName + "." + className).replace('.', '_');
String headerFileName = fileNameStem + H_EXTENSION;
String mFileName = fileNameStem + M_EXTENSION;
StringBuffer headerBuffer = new StringBuffer();
headerBuffer.append("#import \"xmlvm.h\"\n");
for (String i : getTypesForHeader(doc)) {
if (i.equals(inheritsFrom)) {
headerBuffer.append("#import \"" + i + ".h\"\n");
}
}
String interfaces = clazz.getAttributeValue("interfaces");
if (interfaces != null) {
for (String i : interfaces.split(",")) {
headerBuffer
.append("#import \"" + i.replace('.', '_').replace('$', '_') + ".h\"\n");
}
}
headerBuffer.append("\n// For circular include:\n");
for (String i : getTypesForHeader(doc)) {
headerBuffer.append("@class " + i + ";\n");
}
OutputFile headerFile = XsltRunner.runXSLT("xmlvm2objc.xsl", doc, new String[][] {
{ "pass", "emitHeader" }, { "header", headerFileName } });
headerFile.setData(headerBuffer.toString() + headerFile.getData());
headerFile.setFileName(headerFileName);
StringBuffer mBuffer = new StringBuffer();
for (String i : getTypesForHeader(doc)) {
String toIgnore = (namespaceName + "_" + className).replace('.', '_');
if (!i.equals(inheritsFrom) && !i.equals(toIgnore)) {
mBuffer.append("#import \"" + i + ".h\"\n");
}
}
OutputFile mFile = XsltRunner.runXSLT("xmlvm2objc.xsl", doc, new String[][] {
{ "pass", "emitImplementation" }, { "header", headerFileName } });
mFile.setData(mBuffer.toString() + mFile.getData());
mFile.setFileName(mFileName);
return new OutputFile[] { headerFile, mFile };
}
|
diff --git a/server/src/main/java/nz/ac/vuw/ecs/rprofs/server/weaving/Weaver.java b/server/src/main/java/nz/ac/vuw/ecs/rprofs/server/weaving/Weaver.java
index a10771f..f5c1f87 100644
--- a/server/src/main/java/nz/ac/vuw/ecs/rprofs/server/weaving/Weaver.java
+++ b/server/src/main/java/nz/ac/vuw/ecs/rprofs/server/weaving/Weaver.java
@@ -1,116 +1,117 @@
package nz.ac.vuw.ecs.rprofs.server.weaving;
import nz.ac.vuw.ecs.rprof.HeapTracker;
import nz.ac.vuw.ecs.rprofs.server.domain.Class;
import nz.ac.vuw.ecs.rprofs.server.domain.id.ClassId;
import org.objectweb.asm.ClassAdapter;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
public class Weaver {
private ClassRecord cr;
private short lastMethodId = 0;
private short lastFieldId = 0;
public Weaver(ClassId classId) {
this.cr = new ClassRecord(this, classId);
}
public byte[] weave(byte[] classfile) {
ClassReader reader = new ClassReader(classfile);
ClassWriter writer = new ClassWriter(reader, ClassWriter.COMPUTE_MAXS);
reader.accept(new FieldReader(cr), ClassReader.SKIP_CODE);
reader.accept(new Dispatcher(writer, cr), 0); // ClassReader.EXPAND_FRAMES);
return writer.toByteArray();
}
public ClassRecord getClassRecord() {
return cr;
}
MethodRecord createMethodRecord(String name) {
MethodRecord mr = new MethodRecord(cr, ++lastMethodId, name);
cr.methods.put(mr.id, mr);
return mr;
}
FieldRecord createFieldRecord(String name) {
FieldRecord fr = new FieldRecord(cr, ++lastFieldId, name);
cr.fields.put(fr.id, fr);
return fr;
}
private static class Dispatcher extends ClassVisitorDispatcher {
private ClassVisitor cv;
private ClassRecord cr;
public Dispatcher(ClassVisitor cv, ClassRecord cr) {
this.cv = cv;
this.cr = cr;
}
@Override
public void visit(int version, int access, String name,
String signature, String superName, String[] interfaces) {
ClassVisitor cv = null;
String[] filters = new String[] {
"sun/reflect/.*", // jhotdraw crashes in this package
"java/awt/.*", // jhotdraw has font problems if this packages is included
"com/sun/.*",
"sun/.*",
"apple/.*",
"com/apple/.*", // might help jhotdraw?
"java/lang/IncompatibleClassChangeError", // gc blows up if this is woven
"java/lang/LinkageError", // gc blows up if this is woven
- "java/lang/NullPointerException" // something blows up - null pointers appear as runtime exceptions with this change
+ "java/lang/NullPointerException", // something blows up - null pointers appear as runtime exceptions with this change
+ "java/util/concurrent/.*" // SIGSEGV/SIGBUS in pmd
};
int flags = cr.properties;
if (Type.getInternalName(HeapTracker.class).equals(name)) {
flags |= Class.SPECIAL_CLASS_WEAVER;
cv = new TrackingClassWeaver(this.cv, cr);
}
else if (Type.getInternalName(Thread.class).equals(name)) {
flags |= Class.SPECIAL_CLASS_WEAVER;
cv = new ThreadClassWeaver(this.cv, cr);
}
else if (Type.getInternalName(Throwable.class).equals(name)) {
flags |= Class.SPECIAL_CLASS_WEAVER;
cv = new ThreadClassWeaver(this.cv, cr);
}
else if (Type.getInternalName(Object.class).equals(name)) {
flags |= Class.SPECIAL_CLASS_WEAVER;
cv = new ObjectClassWeaver(this.cv, cr);
}
else {
for (String filter: filters) {
if (name.matches(filter)) {
flags |= Class.CLASS_IGNORED_PACKAGE_FILTER;
cv = new ClassAdapter(this.cv);
}
}
}
cr.setProperties(flags);
if (cv == null) {
cv = new GenericClassWeaver(this.cv, cr);
}
setClassVisitor(cv);
cv.visit(version, access, name, signature, superName, interfaces);
}
}
}
| true | true | public void visit(int version, int access, String name,
String signature, String superName, String[] interfaces) {
ClassVisitor cv = null;
String[] filters = new String[] {
"sun/reflect/.*", // jhotdraw crashes in this package
"java/awt/.*", // jhotdraw has font problems if this packages is included
"com/sun/.*",
"sun/.*",
"apple/.*",
"com/apple/.*", // might help jhotdraw?
"java/lang/IncompatibleClassChangeError", // gc blows up if this is woven
"java/lang/LinkageError", // gc blows up if this is woven
"java/lang/NullPointerException" // something blows up - null pointers appear as runtime exceptions with this change
};
int flags = cr.properties;
if (Type.getInternalName(HeapTracker.class).equals(name)) {
flags |= Class.SPECIAL_CLASS_WEAVER;
cv = new TrackingClassWeaver(this.cv, cr);
}
else if (Type.getInternalName(Thread.class).equals(name)) {
flags |= Class.SPECIAL_CLASS_WEAVER;
cv = new ThreadClassWeaver(this.cv, cr);
}
else if (Type.getInternalName(Throwable.class).equals(name)) {
flags |= Class.SPECIAL_CLASS_WEAVER;
cv = new ThreadClassWeaver(this.cv, cr);
}
else if (Type.getInternalName(Object.class).equals(name)) {
flags |= Class.SPECIAL_CLASS_WEAVER;
cv = new ObjectClassWeaver(this.cv, cr);
}
else {
for (String filter: filters) {
if (name.matches(filter)) {
flags |= Class.CLASS_IGNORED_PACKAGE_FILTER;
cv = new ClassAdapter(this.cv);
}
}
}
cr.setProperties(flags);
if (cv == null) {
cv = new GenericClassWeaver(this.cv, cr);
}
setClassVisitor(cv);
cv.visit(version, access, name, signature, superName, interfaces);
}
| public void visit(int version, int access, String name,
String signature, String superName, String[] interfaces) {
ClassVisitor cv = null;
String[] filters = new String[] {
"sun/reflect/.*", // jhotdraw crashes in this package
"java/awt/.*", // jhotdraw has font problems if this packages is included
"com/sun/.*",
"sun/.*",
"apple/.*",
"com/apple/.*", // might help jhotdraw?
"java/lang/IncompatibleClassChangeError", // gc blows up if this is woven
"java/lang/LinkageError", // gc blows up if this is woven
"java/lang/NullPointerException", // something blows up - null pointers appear as runtime exceptions with this change
"java/util/concurrent/.*" // SIGSEGV/SIGBUS in pmd
};
int flags = cr.properties;
if (Type.getInternalName(HeapTracker.class).equals(name)) {
flags |= Class.SPECIAL_CLASS_WEAVER;
cv = new TrackingClassWeaver(this.cv, cr);
}
else if (Type.getInternalName(Thread.class).equals(name)) {
flags |= Class.SPECIAL_CLASS_WEAVER;
cv = new ThreadClassWeaver(this.cv, cr);
}
else if (Type.getInternalName(Throwable.class).equals(name)) {
flags |= Class.SPECIAL_CLASS_WEAVER;
cv = new ThreadClassWeaver(this.cv, cr);
}
else if (Type.getInternalName(Object.class).equals(name)) {
flags |= Class.SPECIAL_CLASS_WEAVER;
cv = new ObjectClassWeaver(this.cv, cr);
}
else {
for (String filter: filters) {
if (name.matches(filter)) {
flags |= Class.CLASS_IGNORED_PACKAGE_FILTER;
cv = new ClassAdapter(this.cv);
}
}
}
cr.setProperties(flags);
if (cv == null) {
cv = new GenericClassWeaver(this.cv, cr);
}
setClassVisitor(cv);
cv.visit(version, access, name, signature, superName, interfaces);
}
|
diff --git a/bundles/commons/mime/src/main/java/org/apache/sling/commons/mime/internal/MimeTypeWebConsolePlugin.java b/bundles/commons/mime/src/main/java/org/apache/sling/commons/mime/internal/MimeTypeWebConsolePlugin.java
index 2945f59872..432b275ea2 100644
--- a/bundles/commons/mime/src/main/java/org/apache/sling/commons/mime/internal/MimeTypeWebConsolePlugin.java
+++ b/bundles/commons/mime/src/main/java/org/apache/sling/commons/mime/internal/MimeTypeWebConsolePlugin.java
@@ -1,193 +1,193 @@
/*
* Copyright 1997-2009 Day Management AG
* Barfuesserplatz 6, 4001 Basel, Switzerland
* All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Day Management AG, ("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 Day.
*/
package org.apache.sling.commons.mime.internal;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.felix.webconsole.AbstractWebConsolePlugin;
class MimeTypeWebConsolePlugin extends AbstractWebConsolePlugin {
/** Serial Version */
private static final long serialVersionUID = -2025952303202431607L;
private static final String LABEL = "mimetypes";
private static final String TITLE = "MIME Types";
private final MimeTypeServiceImpl mimeTypeService;
MimeTypeWebConsolePlugin(MimeTypeServiceImpl mimeTypeService) {
this.mimeTypeService = mimeTypeService;
}
@Override
public String getLabel() {
return LABEL;
}
@Override
public String getTitle() {
return TITLE;
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (!spoolResource(request, response)) {
super.doGet(request, response);
}
}
@Override
protected void renderContent(HttpServletRequest req, HttpServletResponse res)
throws IOException {
Map<String, Set<String>> mimetab = new TreeMap<String, Set<String>>();
Map<String, String> extMap = mimeTypeService.getExtensionMap();
int numExt = 0;
for (Entry<String, String> entry : mimeTypeService.getMimeMap().entrySet()) {
String ext = entry.getKey();
String mime = entry.getValue();
Set<String> extList = mimetab.get(mime);
if (extList == null) {
extList = new HashSet<String>();
mimetab.put(mime, extList);
}
if (ext.equals(extMap.get(mime))) {
ext = "*" + ext + "*";
}
extList.add(ext);
numExt++;
}
PrintWriter pw = res.getWriter();
String resLoc = getLabel() + "/res";
pw.println("<link href='" + resLoc
+ "/jquery.treeTable.css' rel='stylesheet' type='text/css' />");
pw.println("<script type='text/javascript' src='" + resLoc
+ "/jquery.treeTable.min.js'></script>");
pw.println("<script type='text/javascript'>");
pw.println(" $(document).ready(function() {");
pw.println(" $('#mimetabtable').treeTable({ treeColumn: 1 });");
pw.println(" });");
pw.println("</script>");
pw.println("<div id='plugin_content'>");
pw.println("<div class='fullwidth'>");
pw.println("<div class='statusline'>Statistic: " + mimetab.size()
+ " MIME Types, " + numExt + " Extensions</div>");
pw.println("</div>");
pw.println("<div class='table'>");
pw.println("<table id='mimetabtable' class='tablelayout'>");
pw.println("<colgroup>");
pw.println("<col width='20px'>");
pw.println("<col width='50%'>");
pw.println("<col width='50%'>");
pw.println("</colgroup>");
pw.println("<thead>");
pw.println("<tr>");
pw.println("<th colspan='2'>Mime Type</th>");
- pw.println("<th'>Extensions</th>");
+ pw.println("<th>Extensions</th>");
pw.println("</tr>");
pw.println("</thead>");
pw.println("<tbody>");
String currentMajor = null;
for (Entry<String, Set<String>> entry : mimetab.entrySet()) {
String major = getMajorType(entry.getKey());
if (!major.equals(currentMajor)) {
currentMajor = major;
pw.println("<tr id='" + currentMajor + "'>");
pw.println("<td> </td>");
pw.println("<td>" + currentMajor + "</td>");
pw.println("<td>--</td>");
pw.println("</tr>");
}
pw.println("<tr id='" + entry.getKey().replace('/', '-')
+ "' class='child-of-" + currentMajor + "'>");
pw.println("<td> </td>");
pw.println("<td>" + entry.getKey() + "</td>");
pw.println("<td>" + entry.getValue() + "</td>");
pw.println("</tr>");
}
pw.println("</tbody>");
pw.println("</table>");
pw.println("</div>");
pw.println("</div>");
}
private String getMajorType(String type) {
int slash = type.indexOf('/');
return (slash > 0) ? type.substring(0, slash) : type;
}
private boolean spoolResource(HttpServletRequest request,
HttpServletResponse response) throws IOException {
String pi = request.getPathInfo();
int rPi = pi.indexOf("/res/");
if (rPi >= 0) {
pi = pi.substring(rPi);
InputStream ins = getClass().getResourceAsStream(pi);
if (ins != null) {
try {
response.setContentType(getServletContext().getMimeType(pi));
OutputStream out = response.getOutputStream();
byte[] buf = new byte[2048];
int rd;
while ((rd = ins.read(buf)) >= 0) {
out.write(buf, 0, rd);
}
return true;
} finally {
try {
ins.close();
} catch (IOException ignore) {
}
}
}
}
return false;
}
}
| true | true | protected void renderContent(HttpServletRequest req, HttpServletResponse res)
throws IOException {
Map<String, Set<String>> mimetab = new TreeMap<String, Set<String>>();
Map<String, String> extMap = mimeTypeService.getExtensionMap();
int numExt = 0;
for (Entry<String, String> entry : mimeTypeService.getMimeMap().entrySet()) {
String ext = entry.getKey();
String mime = entry.getValue();
Set<String> extList = mimetab.get(mime);
if (extList == null) {
extList = new HashSet<String>();
mimetab.put(mime, extList);
}
if (ext.equals(extMap.get(mime))) {
ext = "*" + ext + "*";
}
extList.add(ext);
numExt++;
}
PrintWriter pw = res.getWriter();
String resLoc = getLabel() + "/res";
pw.println("<link href='" + resLoc
+ "/jquery.treeTable.css' rel='stylesheet' type='text/css' />");
pw.println("<script type='text/javascript' src='" + resLoc
+ "/jquery.treeTable.min.js'></script>");
pw.println("<script type='text/javascript'>");
pw.println(" $(document).ready(function() {");
pw.println(" $('#mimetabtable').treeTable({ treeColumn: 1 });");
pw.println(" });");
pw.println("</script>");
pw.println("<div id='plugin_content'>");
pw.println("<div class='fullwidth'>");
pw.println("<div class='statusline'>Statistic: " + mimetab.size()
+ " MIME Types, " + numExt + " Extensions</div>");
pw.println("</div>");
pw.println("<div class='table'>");
pw.println("<table id='mimetabtable' class='tablelayout'>");
pw.println("<colgroup>");
pw.println("<col width='20px'>");
pw.println("<col width='50%'>");
pw.println("<col width='50%'>");
pw.println("</colgroup>");
pw.println("<thead>");
pw.println("<tr>");
pw.println("<th colspan='2'>Mime Type</th>");
pw.println("<th'>Extensions</th>");
pw.println("</tr>");
pw.println("</thead>");
pw.println("<tbody>");
String currentMajor = null;
for (Entry<String, Set<String>> entry : mimetab.entrySet()) {
String major = getMajorType(entry.getKey());
if (!major.equals(currentMajor)) {
currentMajor = major;
pw.println("<tr id='" + currentMajor + "'>");
pw.println("<td> </td>");
pw.println("<td>" + currentMajor + "</td>");
pw.println("<td>--</td>");
pw.println("</tr>");
}
pw.println("<tr id='" + entry.getKey().replace('/', '-')
+ "' class='child-of-" + currentMajor + "'>");
pw.println("<td> </td>");
pw.println("<td>" + entry.getKey() + "</td>");
pw.println("<td>" + entry.getValue() + "</td>");
pw.println("</tr>");
}
pw.println("</tbody>");
pw.println("</table>");
pw.println("</div>");
pw.println("</div>");
}
| protected void renderContent(HttpServletRequest req, HttpServletResponse res)
throws IOException {
Map<String, Set<String>> mimetab = new TreeMap<String, Set<String>>();
Map<String, String> extMap = mimeTypeService.getExtensionMap();
int numExt = 0;
for (Entry<String, String> entry : mimeTypeService.getMimeMap().entrySet()) {
String ext = entry.getKey();
String mime = entry.getValue();
Set<String> extList = mimetab.get(mime);
if (extList == null) {
extList = new HashSet<String>();
mimetab.put(mime, extList);
}
if (ext.equals(extMap.get(mime))) {
ext = "*" + ext + "*";
}
extList.add(ext);
numExt++;
}
PrintWriter pw = res.getWriter();
String resLoc = getLabel() + "/res";
pw.println("<link href='" + resLoc
+ "/jquery.treeTable.css' rel='stylesheet' type='text/css' />");
pw.println("<script type='text/javascript' src='" + resLoc
+ "/jquery.treeTable.min.js'></script>");
pw.println("<script type='text/javascript'>");
pw.println(" $(document).ready(function() {");
pw.println(" $('#mimetabtable').treeTable({ treeColumn: 1 });");
pw.println(" });");
pw.println("</script>");
pw.println("<div id='plugin_content'>");
pw.println("<div class='fullwidth'>");
pw.println("<div class='statusline'>Statistic: " + mimetab.size()
+ " MIME Types, " + numExt + " Extensions</div>");
pw.println("</div>");
pw.println("<div class='table'>");
pw.println("<table id='mimetabtable' class='tablelayout'>");
pw.println("<colgroup>");
pw.println("<col width='20px'>");
pw.println("<col width='50%'>");
pw.println("<col width='50%'>");
pw.println("</colgroup>");
pw.println("<thead>");
pw.println("<tr>");
pw.println("<th colspan='2'>Mime Type</th>");
pw.println("<th>Extensions</th>");
pw.println("</tr>");
pw.println("</thead>");
pw.println("<tbody>");
String currentMajor = null;
for (Entry<String, Set<String>> entry : mimetab.entrySet()) {
String major = getMajorType(entry.getKey());
if (!major.equals(currentMajor)) {
currentMajor = major;
pw.println("<tr id='" + currentMajor + "'>");
pw.println("<td> </td>");
pw.println("<td>" + currentMajor + "</td>");
pw.println("<td>--</td>");
pw.println("</tr>");
}
pw.println("<tr id='" + entry.getKey().replace('/', '-')
+ "' class='child-of-" + currentMajor + "'>");
pw.println("<td> </td>");
pw.println("<td>" + entry.getKey() + "</td>");
pw.println("<td>" + entry.getValue() + "</td>");
pw.println("</tr>");
}
pw.println("</tbody>");
pw.println("</table>");
pw.println("</div>");
pw.println("</div>");
}
|
diff --git a/fabric/fabric-agent/src/main/java/org/fusesource/fabric/agent/ObrResolver.java b/fabric/fabric-agent/src/main/java/org/fusesource/fabric/agent/ObrResolver.java
index c0f2fd8d4..136ce02a1 100644
--- a/fabric/fabric-agent/src/main/java/org/fusesource/fabric/agent/ObrResolver.java
+++ b/fabric/fabric-agent/src/main/java/org/fusesource/fabric/agent/ObrResolver.java
@@ -1,342 +1,343 @@
/**
* Copyright (C) FuseSource, Inc.
* http://fusesource.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fusesource.fabric.agent;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.felix.bundlerepository.Property;
import org.apache.felix.bundlerepository.Reason;
import org.apache.felix.bundlerepository.Repository;
import org.apache.felix.bundlerepository.RepositoryAdmin;
import org.apache.felix.bundlerepository.Requirement;
import org.apache.felix.bundlerepository.Resource;
import org.apache.felix.bundlerepository.impl.ResourceImpl;
import org.apache.karaf.features.BundleInfo;
import org.apache.karaf.features.Feature;
import org.fusesource.fabric.fab.DependencyTree;
import org.fusesource.fabric.fab.osgi.FabBundleInfo;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ObrResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(ObrResolver.class);
private RepositoryAdmin repositoryAdmin;
public ObrResolver() {
}
public ObrResolver(RepositoryAdmin repositoryAdmin) {
this.repositoryAdmin = repositoryAdmin;
}
public RepositoryAdmin getRepositoryAdmin() {
return repositoryAdmin;
}
public void setRepositoryAdmin(RepositoryAdmin repositoryAdmin) {
this.repositoryAdmin = repositoryAdmin;
}
public List<Resource> resolve(Set<Feature> features,
Set<String> bundles,
Map<String, FabBundleInfo> fabs,
Set<String> overrides,
Map<String, File> downloads) throws Exception {
List<Requirement> reqs = new ArrayList<Requirement>();
List<Resource> ress = new ArrayList<Resource>();
List<Resource> deploy = new ArrayList<Resource>();
Map<Object, BundleInfo> infos = new HashMap<Object, BundleInfo>();
for (Feature feature : features) {
for (BundleInfo bundleInfo : feature.getBundles()) {
try {
//We ignore Fabs completely as the are already been added to fabs set.
if (!bundleInfo.getLocation().startsWith(DeploymentAgent.FAB_PROTOCOL)) {
Resource res = createResource(bundleInfo.getLocation(), downloads, fabs);
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for bundle " + bundleInfo.getLocation());
}
ress.add(res);
infos.put(res, bundleInfo);
}
} catch (MalformedURLException e) {
Requirement req = parseRequirement(bundleInfo.getLocation());
reqs.add(req);
infos.put(req, bundleInfo);
}
}
}
for (String bundle : bundles) {
Resource res = createResource(bundle, downloads, fabs);
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for bundle " + bundle);
}
ress.add(res);
infos.put(res, new SimpleBundleInfo(bundle, false));
}
for (FabBundleInfo fab : fabs.values()) {
Resource res = repositoryAdmin.getHelper().createResource(fab.getManifest());
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for fab " + fab.getUrl());
}
((ResourceImpl) res).put(Resource.URI, DeploymentAgent.FAB_PROTOCOL + fab.getUrl(), Property.URI);
ress.add(res);
infos.put(res, new SimpleBundleInfo(fab.getUrl(), false));
for (DependencyTree dep : fab.getBundles()) {
if (dep.isBundle()) {
URL url = new URL(dep.getUrl());
Resource resDep = createResource(dep.getUrl(), downloads, fabs);
if (resDep == null) {
throw new IllegalArgumentException("Unable to build OBR representation for fab dependency " + url);
}
ress.add(resDep);
infos.put(resDep, new SimpleBundleInfo(dep.getUrl(), true));
}
}
}
for (String override : overrides) {
Resource over = createResource(override, downloads, fabs);
if (over == null) {
- throw new IllegalArgumentException("Unable to build OBR representation for bundle " + override);
+ // Artifacts may not be valid bundles, so just ignore those artifacts
+ continue;
}
boolean add = false;
boolean dependency = true;
for (Resource res : new ArrayList<Resource>(ress)) {
if (res.getSymbolicName().equals(over.getSymbolicName())) {
Version v1 = res.getVersion();
Version v2 = new Version(v1.getMajor(), v1.getMinor() + 1, 0);
if (compareFuseVersions(v1, over.getVersion()) < 0 && compareFuseVersions(over.getVersion(), v2) < 0) {
ress.remove(res);
dependency &= infos.remove(res).isDependency();
add = true;
}
}
}
if (add) {
ress.add(over);
infos.put(over, new SimpleBundleInfo(override, dependency));
}
}
Repository repository = repositoryAdmin.getHelper().repository(ress.toArray(new Resource[ress.size()]));
List<Repository> repos = new ArrayList<Repository>();
repos.add(repositoryAdmin.getSystemRepository());
repos.add(repository);
repos.addAll(Arrays.asList(repositoryAdmin.listRepositories()));
org.apache.felix.bundlerepository.Resolver resolver = repositoryAdmin.resolver(repos.toArray(new Repository[repos.size()]));
for (Resource res : ress) {
if (!infos.get(res).isDependency()) {
resolver.add(res);
}
}
for (Requirement req : reqs) {
resolver.add(req);
}
if (!resolver.resolve(org.apache.felix.bundlerepository.Resolver.NO_OPTIONAL_RESOURCES)) {
StringWriter w = new StringWriter();
PrintWriter out = new PrintWriter(w);
Reason[] failedReqs = resolver.getUnsatisfiedRequirements();
if ((failedReqs != null) && (failedReqs.length > 0)) {
out.println("Unsatisfied requirement(s):");
printUnderline(out, 27);
for (Reason r : failedReqs) {
out.println(" " + r.getRequirement().getName() + ":" + r.getRequirement().getFilter());
out.println(" " + r.getResource().getPresentationName());
}
} else {
out.println("Could not resolve targets.");
}
out.flush();
throw new Exception("Can not resolve feature:\n" + w.toString());
}
Collections.addAll(deploy, resolver.getAddedResources());
Collections.addAll(deploy, resolver.getRequiredResources());
return deploy;
}
private int compareFuseVersions(org.osgi.framework.Version v1, org.osgi.framework.Version v2) {
int c = v1.getMajor() - v2.getMajor();
if (c != 0) {
return c;
}
c = v1.getMinor() - v2.getMinor();
if (c != 0) {
return c;
}
c = v1.getMicro() - v2.getMicro();
if (c != 0) {
return c;
}
String q1 = v1.getQualifier();
String q2 = v2.getQualifier();
if (q1.startsWith("fuse-") && q2.startsWith("fuse-")) {
q1 = cleanQualifierForComparison(q1);
q2 = cleanQualifierForComparison(q2);
}
return q1.compareTo(q2);
}
private String cleanQualifierForComparison(String q) {
return q.replace("-alpha-", "-").replace("-beta-", "-")
.replace("-7-0-", "-70-")
.replace("-7-", "-70-");
}
protected Resource createResource(String uri, Map<String, File> urls, Map<String, FabBundleInfo> infos) throws Exception {
URL url = new URL(uri);
Attributes attributes = getAttributes(uri, urls, infos);
ResourceImpl resource = (ResourceImpl) repositoryAdmin.getHelper().createResource(attributes);
if (resource != null) {
if ("file".equals(url.getProtocol()))
{
try {
File f = new File(url.toURI());
resource.put(Resource.SIZE, Long.toString(f.length()), null);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
resource.put(Resource.URI, url.toExternalForm(), null);
}
return resource;
}
protected Attributes getAttributes(String uri, Map<String, File> urls, Map<String, FabBundleInfo> infos) throws Exception {
InputStream is = DeploymentAgent.getBundleInputStream(uri, urls, infos);
byte[] man = loadEntry(is, JarFile.MANIFEST_NAME);
if (man == null)
{
throw new IllegalArgumentException("The specified url is not a valid jar (can't read manifest): " + uri);
}
Manifest manifest = new Manifest(new ByteArrayInputStream(man));
return manifest.getMainAttributes();
}
private byte[] loadEntry(InputStream is, String name) throws IOException
{
try
{
ZipInputStream jis = new ZipInputStream(is);
for (ZipEntry e = jis.getNextEntry(); e != null; e = jis.getNextEntry())
{
if (name.equalsIgnoreCase(e.getName()))
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while ((n = jis.read(buf, 0, buf.length)) > 0)
{
baos.write(buf, 0, n);
}
return baos.toByteArray();
}
}
}
finally
{
is.close();
}
return null;
}
protected void printUnderline(PrintWriter out, int length) {
for (int i = 0; i < length; i++) {
out.print('-');
}
out.println("");
}
protected Requirement parseRequirement(String req) throws InvalidSyntaxException {
int p = req.indexOf(':');
String name;
String filter;
if (p > 0) {
name = req.substring(0, p);
filter = req.substring(p + 1);
} else {
if (req.contains("package")) {
name = "package";
} else if (req.contains("service")) {
name = "service";
} else {
name = "bundle";
}
filter = req;
}
if (!filter.startsWith("(")) {
filter = "(" + filter + ")";
}
return repositoryAdmin.getHelper().requirement(name, filter);
}
private static class SimpleBundleInfo implements BundleInfo {
private final String bundle;
private final boolean dependency;
public SimpleBundleInfo(String bundle, boolean dependency) {
this.bundle = bundle;
this.dependency = dependency;
}
@Override
public String getLocation() {
return bundle;
}
@Override
public int getStartLevel() {
return 0;
}
@Override
public boolean isStart() {
return true;
}
@Override
public boolean isDependency() {
return dependency;
}
}
}
| true | true | public List<Resource> resolve(Set<Feature> features,
Set<String> bundles,
Map<String, FabBundleInfo> fabs,
Set<String> overrides,
Map<String, File> downloads) throws Exception {
List<Requirement> reqs = new ArrayList<Requirement>();
List<Resource> ress = new ArrayList<Resource>();
List<Resource> deploy = new ArrayList<Resource>();
Map<Object, BundleInfo> infos = new HashMap<Object, BundleInfo>();
for (Feature feature : features) {
for (BundleInfo bundleInfo : feature.getBundles()) {
try {
//We ignore Fabs completely as the are already been added to fabs set.
if (!bundleInfo.getLocation().startsWith(DeploymentAgent.FAB_PROTOCOL)) {
Resource res = createResource(bundleInfo.getLocation(), downloads, fabs);
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for bundle " + bundleInfo.getLocation());
}
ress.add(res);
infos.put(res, bundleInfo);
}
} catch (MalformedURLException e) {
Requirement req = parseRequirement(bundleInfo.getLocation());
reqs.add(req);
infos.put(req, bundleInfo);
}
}
}
for (String bundle : bundles) {
Resource res = createResource(bundle, downloads, fabs);
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for bundle " + bundle);
}
ress.add(res);
infos.put(res, new SimpleBundleInfo(bundle, false));
}
for (FabBundleInfo fab : fabs.values()) {
Resource res = repositoryAdmin.getHelper().createResource(fab.getManifest());
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for fab " + fab.getUrl());
}
((ResourceImpl) res).put(Resource.URI, DeploymentAgent.FAB_PROTOCOL + fab.getUrl(), Property.URI);
ress.add(res);
infos.put(res, new SimpleBundleInfo(fab.getUrl(), false));
for (DependencyTree dep : fab.getBundles()) {
if (dep.isBundle()) {
URL url = new URL(dep.getUrl());
Resource resDep = createResource(dep.getUrl(), downloads, fabs);
if (resDep == null) {
throw new IllegalArgumentException("Unable to build OBR representation for fab dependency " + url);
}
ress.add(resDep);
infos.put(resDep, new SimpleBundleInfo(dep.getUrl(), true));
}
}
}
for (String override : overrides) {
Resource over = createResource(override, downloads, fabs);
if (over == null) {
throw new IllegalArgumentException("Unable to build OBR representation for bundle " + override);
}
boolean add = false;
boolean dependency = true;
for (Resource res : new ArrayList<Resource>(ress)) {
if (res.getSymbolicName().equals(over.getSymbolicName())) {
Version v1 = res.getVersion();
Version v2 = new Version(v1.getMajor(), v1.getMinor() + 1, 0);
if (compareFuseVersions(v1, over.getVersion()) < 0 && compareFuseVersions(over.getVersion(), v2) < 0) {
ress.remove(res);
dependency &= infos.remove(res).isDependency();
add = true;
}
}
}
if (add) {
ress.add(over);
infos.put(over, new SimpleBundleInfo(override, dependency));
}
}
Repository repository = repositoryAdmin.getHelper().repository(ress.toArray(new Resource[ress.size()]));
List<Repository> repos = new ArrayList<Repository>();
repos.add(repositoryAdmin.getSystemRepository());
repos.add(repository);
repos.addAll(Arrays.asList(repositoryAdmin.listRepositories()));
org.apache.felix.bundlerepository.Resolver resolver = repositoryAdmin.resolver(repos.toArray(new Repository[repos.size()]));
for (Resource res : ress) {
if (!infos.get(res).isDependency()) {
resolver.add(res);
}
}
for (Requirement req : reqs) {
resolver.add(req);
}
if (!resolver.resolve(org.apache.felix.bundlerepository.Resolver.NO_OPTIONAL_RESOURCES)) {
StringWriter w = new StringWriter();
PrintWriter out = new PrintWriter(w);
Reason[] failedReqs = resolver.getUnsatisfiedRequirements();
if ((failedReqs != null) && (failedReqs.length > 0)) {
out.println("Unsatisfied requirement(s):");
printUnderline(out, 27);
for (Reason r : failedReqs) {
out.println(" " + r.getRequirement().getName() + ":" + r.getRequirement().getFilter());
out.println(" " + r.getResource().getPresentationName());
}
} else {
out.println("Could not resolve targets.");
}
out.flush();
throw new Exception("Can not resolve feature:\n" + w.toString());
}
Collections.addAll(deploy, resolver.getAddedResources());
Collections.addAll(deploy, resolver.getRequiredResources());
return deploy;
}
| public List<Resource> resolve(Set<Feature> features,
Set<String> bundles,
Map<String, FabBundleInfo> fabs,
Set<String> overrides,
Map<String, File> downloads) throws Exception {
List<Requirement> reqs = new ArrayList<Requirement>();
List<Resource> ress = new ArrayList<Resource>();
List<Resource> deploy = new ArrayList<Resource>();
Map<Object, BundleInfo> infos = new HashMap<Object, BundleInfo>();
for (Feature feature : features) {
for (BundleInfo bundleInfo : feature.getBundles()) {
try {
//We ignore Fabs completely as the are already been added to fabs set.
if (!bundleInfo.getLocation().startsWith(DeploymentAgent.FAB_PROTOCOL)) {
Resource res = createResource(bundleInfo.getLocation(), downloads, fabs);
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for bundle " + bundleInfo.getLocation());
}
ress.add(res);
infos.put(res, bundleInfo);
}
} catch (MalformedURLException e) {
Requirement req = parseRequirement(bundleInfo.getLocation());
reqs.add(req);
infos.put(req, bundleInfo);
}
}
}
for (String bundle : bundles) {
Resource res = createResource(bundle, downloads, fabs);
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for bundle " + bundle);
}
ress.add(res);
infos.put(res, new SimpleBundleInfo(bundle, false));
}
for (FabBundleInfo fab : fabs.values()) {
Resource res = repositoryAdmin.getHelper().createResource(fab.getManifest());
if (res == null) {
throw new IllegalArgumentException("Unable to build OBR representation for fab " + fab.getUrl());
}
((ResourceImpl) res).put(Resource.URI, DeploymentAgent.FAB_PROTOCOL + fab.getUrl(), Property.URI);
ress.add(res);
infos.put(res, new SimpleBundleInfo(fab.getUrl(), false));
for (DependencyTree dep : fab.getBundles()) {
if (dep.isBundle()) {
URL url = new URL(dep.getUrl());
Resource resDep = createResource(dep.getUrl(), downloads, fabs);
if (resDep == null) {
throw new IllegalArgumentException("Unable to build OBR representation for fab dependency " + url);
}
ress.add(resDep);
infos.put(resDep, new SimpleBundleInfo(dep.getUrl(), true));
}
}
}
for (String override : overrides) {
Resource over = createResource(override, downloads, fabs);
if (over == null) {
// Artifacts may not be valid bundles, so just ignore those artifacts
continue;
}
boolean add = false;
boolean dependency = true;
for (Resource res : new ArrayList<Resource>(ress)) {
if (res.getSymbolicName().equals(over.getSymbolicName())) {
Version v1 = res.getVersion();
Version v2 = new Version(v1.getMajor(), v1.getMinor() + 1, 0);
if (compareFuseVersions(v1, over.getVersion()) < 0 && compareFuseVersions(over.getVersion(), v2) < 0) {
ress.remove(res);
dependency &= infos.remove(res).isDependency();
add = true;
}
}
}
if (add) {
ress.add(over);
infos.put(over, new SimpleBundleInfo(override, dependency));
}
}
Repository repository = repositoryAdmin.getHelper().repository(ress.toArray(new Resource[ress.size()]));
List<Repository> repos = new ArrayList<Repository>();
repos.add(repositoryAdmin.getSystemRepository());
repos.add(repository);
repos.addAll(Arrays.asList(repositoryAdmin.listRepositories()));
org.apache.felix.bundlerepository.Resolver resolver = repositoryAdmin.resolver(repos.toArray(new Repository[repos.size()]));
for (Resource res : ress) {
if (!infos.get(res).isDependency()) {
resolver.add(res);
}
}
for (Requirement req : reqs) {
resolver.add(req);
}
if (!resolver.resolve(org.apache.felix.bundlerepository.Resolver.NO_OPTIONAL_RESOURCES)) {
StringWriter w = new StringWriter();
PrintWriter out = new PrintWriter(w);
Reason[] failedReqs = resolver.getUnsatisfiedRequirements();
if ((failedReqs != null) && (failedReqs.length > 0)) {
out.println("Unsatisfied requirement(s):");
printUnderline(out, 27);
for (Reason r : failedReqs) {
out.println(" " + r.getRequirement().getName() + ":" + r.getRequirement().getFilter());
out.println(" " + r.getResource().getPresentationName());
}
} else {
out.println("Could not resolve targets.");
}
out.flush();
throw new Exception("Can not resolve feature:\n" + w.toString());
}
Collections.addAll(deploy, resolver.getAddedResources());
Collections.addAll(deploy, resolver.getRequiredResources());
return deploy;
}
|
diff --git a/src/com/sebrichard/mfgen/inspection/InspectingMetaFields.java b/src/com/sebrichard/mfgen/inspection/InspectingMetaFields.java
index ba3911f..f55c2b8 100644
--- a/src/com/sebrichard/mfgen/inspection/InspectingMetaFields.java
+++ b/src/com/sebrichard/mfgen/inspection/InspectingMetaFields.java
@@ -1,144 +1,144 @@
/*
* (C) Copyright 2013 Sébastien Richard
*
* 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.sebrichard.mfgen.inspection;
import com.google.common.collect.Sets;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.codeInspection.BaseJavaLocalInspectionTool;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.psi.*;
import com.intellij.psi.util.PropertyUtil;
import com.sebrichard.mfgen.MetaFieldUtil;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import java.util.Set;
public class InspectingMetaFields extends BaseJavaLocalInspectionTool {
@NotNull
public String getDisplayName() {
return "Meta-field validations";
}
@NotNull
public String getGroupDisplayName() {
return GroupNames.BUGS_GROUP_NAME;
}
@NotNull
public String getShortName() {
return "ValidatingMetaField";
}
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new JavaElementVisitor() {
@Override
public void visitClass(PsiClass psiClass) {
Set<String> acceptedMetaFieldNames = generateAcceptedMetaFieldNames(psiClass);
Set<PsiField> metaFields = findMetaFields(psiClass);
for (PsiField metaField : metaFields) {
if (!metaField.hasModifierProperty(PsiModifier.FINAL)) {
holder.registerProblem(metaField, "Meta-field not final");
continue;
}
if (!metaField.getType().equalsToText(CommonClassNames.JAVA_LANG_STRING)) {
// The field with the 'meta-field' name pattern does not have the String type!
holder.registerProblem(metaField, "Meta-field is not a String");
continue;
}
PsiExpression initializer = metaField.getInitializer();
if (initializer != null) {
if (initializer instanceof PsiLiteral) {
PsiLiteral literal = (PsiLiteral) initializer;
- if (literal.getValue() instanceof String) {
+ if (literal.getValue() != null && literal.getValue() instanceof String) {
String initializationValue = (String) literal.getValue();
if (!StringUtils.equals(metaField.getName(), MetaFieldUtil.generateMetaFieldName(initializationValue))) {
holder.registerProblem(metaField, "Meta-field name does not match its value");
continue;
}
} else {
holder.registerProblem(metaField, "Meta-field initializing value is not a String value");
continue;
}
} else {
holder.registerProblem(metaField, "Meta-field initializing value is not a String constant value");
continue;
}
} else {
holder.registerProblem(metaField, "Uninitialized Meta-field");
}
if (!acceptedMetaFieldNames.contains(metaField.getName())) {
// We didn't find any matching field!
holder.registerProblem(metaField, "Did not find any matching non-static field.");
continue;
}
}
}
};
}
private Set<String> generateAcceptedMetaFieldNames(PsiClass psiClass) {
Set<String> acceptedMetaFields = Sets.newHashSet();
for (PsiField field : psiClass.getAllFields()) {
if (!field.hasModifierProperty(PsiModifier.STATIC)) {
acceptedMetaFields.add(MetaFieldUtil.generateMetaFieldName(field.getName()));
}
}
for (PsiMethod method : psiClass.getAllMethods()) {
if (!method.hasModifierProperty(PsiModifier.STATIC) && PropertyUtil.isSimplePropertyGetter(method)) {
String propertyName = PropertyUtil.getPropertyNameByGetter(method);
acceptedMetaFields.add(MetaFieldUtil.generateMetaFieldName(propertyName));
}
}
return acceptedMetaFields;
}
private Set<PsiField> findMetaFields(PsiClass psiClass) {
Set<PsiField> metaFields = Sets.newHashSet();
for (PsiField metaField : psiClass.getAllFields()) {
if (MetaFieldUtil.isMetaField(metaField)) {
metaFields.add(metaField);
}
}
return metaFields;
}
public boolean isEnabledByDefault() {
return true;
}
@NotNull
@Override
public HighlightDisplayLevel getDefaultLevel() {
return HighlightDisplayLevel.ERROR;
}
}
| true | true | public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new JavaElementVisitor() {
@Override
public void visitClass(PsiClass psiClass) {
Set<String> acceptedMetaFieldNames = generateAcceptedMetaFieldNames(psiClass);
Set<PsiField> metaFields = findMetaFields(psiClass);
for (PsiField metaField : metaFields) {
if (!metaField.hasModifierProperty(PsiModifier.FINAL)) {
holder.registerProblem(metaField, "Meta-field not final");
continue;
}
if (!metaField.getType().equalsToText(CommonClassNames.JAVA_LANG_STRING)) {
// The field with the 'meta-field' name pattern does not have the String type!
holder.registerProblem(metaField, "Meta-field is not a String");
continue;
}
PsiExpression initializer = metaField.getInitializer();
if (initializer != null) {
if (initializer instanceof PsiLiteral) {
PsiLiteral literal = (PsiLiteral) initializer;
if (literal.getValue() instanceof String) {
String initializationValue = (String) literal.getValue();
if (!StringUtils.equals(metaField.getName(), MetaFieldUtil.generateMetaFieldName(initializationValue))) {
holder.registerProblem(metaField, "Meta-field name does not match its value");
continue;
}
} else {
holder.registerProblem(metaField, "Meta-field initializing value is not a String value");
continue;
}
} else {
holder.registerProblem(metaField, "Meta-field initializing value is not a String constant value");
continue;
}
} else {
holder.registerProblem(metaField, "Uninitialized Meta-field");
}
if (!acceptedMetaFieldNames.contains(metaField.getName())) {
// We didn't find any matching field!
holder.registerProblem(metaField, "Did not find any matching non-static field.");
continue;
}
}
}
};
}
| public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
return new JavaElementVisitor() {
@Override
public void visitClass(PsiClass psiClass) {
Set<String> acceptedMetaFieldNames = generateAcceptedMetaFieldNames(psiClass);
Set<PsiField> metaFields = findMetaFields(psiClass);
for (PsiField metaField : metaFields) {
if (!metaField.hasModifierProperty(PsiModifier.FINAL)) {
holder.registerProblem(metaField, "Meta-field not final");
continue;
}
if (!metaField.getType().equalsToText(CommonClassNames.JAVA_LANG_STRING)) {
// The field with the 'meta-field' name pattern does not have the String type!
holder.registerProblem(metaField, "Meta-field is not a String");
continue;
}
PsiExpression initializer = metaField.getInitializer();
if (initializer != null) {
if (initializer instanceof PsiLiteral) {
PsiLiteral literal = (PsiLiteral) initializer;
if (literal.getValue() != null && literal.getValue() instanceof String) {
String initializationValue = (String) literal.getValue();
if (!StringUtils.equals(metaField.getName(), MetaFieldUtil.generateMetaFieldName(initializationValue))) {
holder.registerProblem(metaField, "Meta-field name does not match its value");
continue;
}
} else {
holder.registerProblem(metaField, "Meta-field initializing value is not a String value");
continue;
}
} else {
holder.registerProblem(metaField, "Meta-field initializing value is not a String constant value");
continue;
}
} else {
holder.registerProblem(metaField, "Uninitialized Meta-field");
}
if (!acceptedMetaFieldNames.contains(metaField.getName())) {
// We didn't find any matching field!
holder.registerProblem(metaField, "Did not find any matching non-static field.");
continue;
}
}
}
};
}
|
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileObject.java
index 48e7b15..fca6736 100644
--- a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileObject.java
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileObject.java
@@ -1,117 +1,117 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.compressed;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileObject;
/**
* A compressed file.<br>
* Such a file do only have one child (the compressed filename with stripped last extension)
*/
public abstract class CompressedFileFileObject extends AbstractFileObject
{
private final FileObject container;
private final String[] children;
protected CompressedFileFileObject(AbstractFileName name, FileObject container, CompressedFileFileSystem fs)
{
super(name, fs);
this.container = container;
// todo, add getBaseName(String) to FileName
String basename = container.getName().getBaseName();
int pos = basename.lastIndexOf('.');
if (pos > 0)
{
basename = basename.substring(0, pos);
}
- children = new String[] { basename };
+ children = new String[]{ basename };
}
/**
* Determines if this file can be written to.
*
* @return <code>true</code> if this file is writeable, <code>false</code> if not.
* @throws FileSystemException if an error occurs.
*/
@Override
public boolean isWriteable() throws FileSystemException
{
return getFileSystem().hasCapability(Capability.WRITE_CONTENT);
}
/**
* Returns the file's type.
*/
@Override
protected FileType doGetType() throws FileSystemException
{
if (getName().getPath().endsWith("/"))
{
return FileType.FOLDER;
}
else
{
return FileType.FILE;
}
}
/**
* Lists the children of the file.
*/
@Override
protected String[] doListChildren()
{
return children;
}
/**
* Returns the size of the file content (in bytes). Is only called if
* {@link #doGetType} returns {@link FileType#FILE}.
*/
@Override
protected long doGetContentSize()
{
return -1;
}
/**
* Returns the last modified time of this file.
*/
@Override
protected long doGetLastModifiedTime() throws Exception
{
return container.getContent().getLastModifiedTime();
}
protected FileObject getContainer()
{
return container;
}
@Override
public void createFile() throws FileSystemException
{
container.createFile();
injectType(FileType.FILE);
}
}
| true | true | protected CompressedFileFileObject(AbstractFileName name, FileObject container, CompressedFileFileSystem fs)
{
super(name, fs);
this.container = container;
// todo, add getBaseName(String) to FileName
String basename = container.getName().getBaseName();
int pos = basename.lastIndexOf('.');
if (pos > 0)
{
basename = basename.substring(0, pos);
}
children = new String[] { basename };
}
| protected CompressedFileFileObject(AbstractFileName name, FileObject container, CompressedFileFileSystem fs)
{
super(name, fs);
this.container = container;
// todo, add getBaseName(String) to FileName
String basename = container.getName().getBaseName();
int pos = basename.lastIndexOf('.');
if (pos > 0)
{
basename = basename.substring(0, pos);
}
children = new String[]{ basename };
}
|
diff --git a/src/com/github/snowindy/getResourceAsStream/TestGetResourceAsStreamBug.java b/src/com/github/snowindy/getResourceAsStream/TestGetResourceAsStreamBug.java
index 32a264d..b4c2910 100644
--- a/src/com/github/snowindy/getResourceAsStream/TestGetResourceAsStreamBug.java
+++ b/src/com/github/snowindy/getResourceAsStream/TestGetResourceAsStreamBug.java
@@ -1,46 +1,46 @@
package com.github.snowindy.getResourceAsStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import org.apache.commons.io.FileUtils;
public class TestGetResourceAsStreamBug {
public static void main(String[] args) throws Exception {
byte[] fileBytes = FileUtils.readFileToByteArray(new File(
- "src/com/github/snowindy/getResourceAsStream/test-short-enc.xml"));
+ "resources/test/xml/test-short-enc.xml"));
printBytes(fileBytes);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
InputStream is = TestGetResourceAsStreamBug.class
- .getResourceAsStream("/com/github/snowindy/getResourceAsStream/test-short-enc.xml");
+ .getResourceAsStream("/test/xml/test-short-enc.xml");
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] bis = buffer.toByteArray();
printBytes(bis);
is.close();
}
public static void printBytes(byte[] bv) {
System.out.println();
for (byte b : bv) {
System.out.print(' ');
System.out.print(String.format("%02X", b));
}
}
}
| false | true | public static void main(String[] args) throws Exception {
byte[] fileBytes = FileUtils.readFileToByteArray(new File(
"src/com/github/snowindy/getResourceAsStream/test-short-enc.xml"));
printBytes(fileBytes);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
InputStream is = TestGetResourceAsStreamBug.class
.getResourceAsStream("/com/github/snowindy/getResourceAsStream/test-short-enc.xml");
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] bis = buffer.toByteArray();
printBytes(bis);
is.close();
}
| public static void main(String[] args) throws Exception {
byte[] fileBytes = FileUtils.readFileToByteArray(new File(
"resources/test/xml/test-short-enc.xml"));
printBytes(fileBytes);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
InputStream is = TestGetResourceAsStreamBug.class
.getResourceAsStream("/test/xml/test-short-enc.xml");
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] bis = buffer.toByteArray();
printBytes(bis);
is.close();
}
|
diff --git a/bridge-impl/src/main/java/com/liferay/faces/bridge/context/map/RequestParameterMapMultiPartImpl.java b/bridge-impl/src/main/java/com/liferay/faces/bridge/context/map/RequestParameterMapMultiPartImpl.java
index 75266eb87..28c118610 100644
--- a/bridge-impl/src/main/java/com/liferay/faces/bridge/context/map/RequestParameterMapMultiPartImpl.java
+++ b/bridge-impl/src/main/java/com/liferay/faces/bridge/context/map/RequestParameterMapMultiPartImpl.java
@@ -1,654 +1,656 @@
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.faces.bridge.context.map;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.faces.render.ResponseStateManager;
import javax.portlet.ActionRequest;
import javax.portlet.ClientDataRequest;
import javax.portlet.PortalContext;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletSession;
import javax.portlet.ResourceRequest;
import javax.portlet.WindowState;
import javax.servlet.http.Cookie;
import org.apache.commons.fileupload.FileItemHeaders;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.InvalidFileNameException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.portlet.PortletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FileUtils;
import com.liferay.faces.bridge.BridgeFactoryFinder;
import com.liferay.faces.bridge.config.BridgeConfigConstants;
import com.liferay.faces.bridge.container.PortletContainer;
import com.liferay.faces.bridge.context.BridgeContext;
import com.liferay.faces.bridge.model.UploadedFile;
import com.liferay.faces.bridge.model.UploadedFileFactory;
import com.liferay.faces.util.helper.BooleanHelper;
import com.liferay.faces.util.logging.Logger;
import com.liferay.faces.util.logging.LoggerFactory;
import com.liferay.faces.util.map.AbstractPropertyMapEntry;
import com.liferay.portal.kernel.util.StringPool;
/**
* @author Neil Griffin
*/
public class RequestParameterMapMultiPartImpl extends RequestParameterMap {
// Logger
private static final Logger logger = LoggerFactory.getLogger(RequestParameterMapMultiPartImpl.class);
// Private Constants
private static final String CONTEXT_PARAM_UPLOADED_FILES_DIR = "javax.faces.UPLOADED_FILES_DIR";
private static final String CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE = "javax.faces.UPLOADED_FILE_MAX_SIZE";
private static final String JAVA_IO_TMPDIR = "java.io.tmpdir";
private static final int DEFAULT_FILE_MAX_SIZE = 104857600; // 100MB
// Private Data Members
private Map<String, String> requestParameterMap;
private Map<String, List<UploadedFile>> requestParameterFileMap;
@SuppressWarnings("unchecked")
public RequestParameterMapMultiPartImpl(BridgeContext bridgeContext, ClientDataRequest clientDataRequest) {
try {
PortletSession portletSession = clientDataRequest.getPortletSession();
// Determine the uploaded files directory path according to the JSF 2.2 proposal:
// https://javaserverfaces-spec-public.dev.java.net/issues/show_bug.cgi?id=690
String uploadedFilesDir = bridgeContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILES_DIR);
if (uploadedFilesDir == null) {
uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);
if (logger.isDebugEnabled()) {
logger.debug(
"The web.xml context-param name=[{0}] not found, using default system property=[{1}] value=[{2}]",
new Object[] { CONTEXT_PARAM_UPLOADED_FILES_DIR, JAVA_IO_TMPDIR, uploadedFilesDir });
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Using web.xml context-param name=[{0}] value=[{1}]",
new Object[] { CONTEXT_PARAM_UPLOADED_FILES_DIR, uploadedFilesDir });
}
}
// Using the portlet sessionId, determine a unique folder path and create the path if it does not exist.
String sessionId = portletSession.getId();
// FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
// created properly.
sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK);
File uploadedFilesPath = new File(uploadedFilesDir, sessionId);
if (!uploadedFilesPath.exists()) {
try {
uploadedFilesPath.mkdirs();
}
catch (SecurityException e) {
uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);
logger.error(
"Security exception message=[{0}] when trying to create unique path=[{1}] so using default system property=[{2}] value=[{3}]",
new Object[] { e.getMessage(), uploadedFilesPath.toString(), JAVA_IO_TMPDIR, uploadedFilesDir });
uploadedFilesPath = new File(uploadedFilesDir, sessionId);
uploadedFilesPath.mkdirs();
}
}
// Initialize commons-fileupload with the file upload path.
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setRepository(uploadedFilesPath);
// Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
diskFileItemFactory.setFileCleaningTracker(null);
// Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
// instead of staying in memory.
diskFileItemFactory.setSizeThreshold(0);
// Determine the max file upload size threshold in bytes.
String uploadedFilesMaxSize = bridgeContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE);
int fileMaxSize = DEFAULT_FILE_MAX_SIZE;
if (uploadedFilesMaxSize == null) {
if (logger.isDebugEnabled()) {
logger.debug("The web.xml context-param name=[{0}] not found, using default=[{1}] bytes",
new Object[] { CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE });
}
}
else {
try {
fileMaxSize = Integer.parseInt(uploadedFilesMaxSize);
if (logger.isDebugEnabled()) {
logger.debug("Using web.xml context-param name=[{0}] value=[{1}] bytes",
new Object[] { CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, fileMaxSize });
}
}
catch (NumberFormatException e) {
logger.error("Invalid value=[{0}] for web.xml context-param name=[{1}] using default=[{2}] bytes.",
new Object[] {
uploadedFilesMaxSize, CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE
});
}
}
// Parse the request parameters and save all uploaded files in a map.
PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory);
portletFileUpload.setFileSizeMax(fileMaxSize);
requestParameterMap = new HashMap<String, String>();
requestParameterFileMap = new HashMap<String, List<UploadedFile>>();
// Get the namespace that might be found in request parameter names.
String namespace = bridgeContext.getPortletContainer().getResponseNamespace();
// FACES-271: Include name+value pairs found in the ActionRequest.
PortletContainer portletContainer = bridgeContext.getPortletContainer();
Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet();
for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {
String parameterName = mapEntry.getKey();
int pos = parameterName.indexOf(namespace);
if (pos >= 0) {
parameterName = parameterName.substring(pos + namespace.length());
}
String[] parameterValues = mapEntry.getValue();
if (parameterValues.length > 0) {
String fixedRequestParameterValue = portletContainer.fixRequestParameterValue(parameterValues[0]);
requestParameterMap.put(parameterName, fixedRequestParameterValue);
logger.debug("Found in ActionRequest: {0}=[{1}]", parameterName, fixedRequestParameterValue);
}
}
UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder.getFactory(
UploadedFileFactory.class);
// Begin parsing the request for file parts:
try {
FileItemIterator fileItemIterator = null;
if (clientDataRequest instanceof ResourceRequest) {
ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
}
else {
ActionRequest actionRequest = (ActionRequest) clientDataRequest;
fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
}
boolean optimizeNamespace = BooleanHelper.toBoolean(bridgeContext.getInitParameter(
BridgeConfigConstants.PARAM_OPTIMIZE_PORTLET_NAMESPACE1), true);
if (fileItemIterator != null) {
int totalFiles = 0;
// For each field found in the request:
while (fileItemIterator.hasNext()) {
try {
totalFiles++;
// Get the stream of field data from the request.
FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();
// Get field name from the field stream.
String fieldName = fieldStream.getFieldName();
// If namespace optimization is enabled and the namespace is present in the field name,
// then remove the portlet namespace from the field name.
if (optimizeNamespace) {
int pos = fieldName.indexOf(namespace);
if (pos >= 0) {
fieldName = fieldName.substring(pos + namespace.length());
}
}
// Get the content-type, and file-name from the field stream.
String contentType = fieldStream.getContentType();
boolean formField = fieldStream.isFormField();
String fileName = null;
try {
fileName = fieldStream.getName();
}
catch (InvalidFileNameException e) {
fileName = e.getName();
}
// Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
// current field is a simple form-field because the call below to diskFileItem.getString()
// will fail otherwise.
DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
contentType, formField, fileName);
Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);
// If the current field is a simple form-field, then save the form field value in the map.
if (diskFileItem.isFormField()) {
String characterEncoding = clientDataRequest.getCharacterEncoding();
String requestParameterValue = null;
if (characterEncoding == null) {
requestParameterValue = diskFileItem.getString();
}
else {
requestParameterValue = diskFileItem.getString(characterEncoding);
}
String fixedRequestParameterValue = portletContainer.fixRequestParameterValue(
requestParameterValue);
requestParameterMap.put(fieldName, fixedRequestParameterValue);
logger.debug("{0}=[{1}]", fieldName, fixedRequestParameterValue);
}
else {
File tempFile = diskFileItem.getStoreLocation();
// If the copy was successful, then
if (tempFile.exists()) {
// Copy the commons-fileupload temporary file to a file in the same temporary
// location, but with the filename provided by the user in the upload. This has two
// benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
// the file, the developer can have access to a semi-permanent file, because the
// commmons-fileupload DiskFileItem.finalize() method automatically deletes the
// temporary one.
String tempFileName = tempFile.getName();
String tempFileAbsolutePath = tempFile.getAbsolutePath();
String copiedFileName = stripIllegalCharacters(fileName);
String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
copiedFileName);
File copiedFile = new File(copiedFileAbsolutePath);
FileUtils.copyFile(tempFile, copiedFile);
// If present, build up a map of headers.
Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
FileItemHeaders fileItemHeaders = fieldStream.getHeaders();
if (fileItemHeaders != null) {
Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();
if (headerNameItr != null) {
while (headerNameItr.hasNext()) {
String headerName = headerNameItr.next();
Iterator<String> headerValuesItr = fileItemHeaders.getHeaders(
headerName);
List<String> headerValues = new ArrayList<String>();
if (headerValuesItr != null) {
while (headerValuesItr.hasNext()) {
String headerValue = headerValuesItr.next();
headerValues.add(headerValue);
}
}
headersMap.put(headerName, headerValues);
}
}
}
// Put a valid UploadedFile instance into the map that contains all of the
// uploaded file's attributes, along with a successful status.
Map<String, Object> attributeMap = new HashMap<String, Object>();
String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
String message = null;
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
diskFileItem.getContentType(), headersMap, id, message, fileName,
diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);
requestParameterMap.put(fieldName, copiedFileAbsolutePath);
addUploadedFile(fieldName, uploadedFile);
logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
fileName);
}
else {
- Exception e = new IOException(
- "Failed to copy the stream of file data to a temporary file");
- UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
- addUploadedFile(fieldName, uploadedFile);
+ if ((fileName != null) && (fileName.trim().length() > 0)) {
+ Exception e = new IOException(
+ "Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)");
+ UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
+ addUploadedFile(fieldName, uploadedFile);
+ }
}
}
}
catch (Exception e) {
logger.error(e);
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
String fieldName = Integer.toString(totalFiles);
addUploadedFile(fieldName, uploadedFile);
}
}
}
}
// If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
// the map so that the developer can have some idea that something went wrong.
catch (Exception e) {
logger.error(e);
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
addUploadedFile("unknown", uploadedFile);
}
clientDataRequest.setAttribute(PARAM_UPLOADED_FILES, requestParameterFileMap);
// If not found in the request, Section 6.9 of the Bridge spec requires that the value of the
// ResponseStateManager.RENDER_KIT_ID_PARAM request parameter be set to the value of the
// "javax.portlet.faces.<portletName>.defaultRenderKitId" PortletContext attribute.
String renderKitIdParam = requestParameterMap.get(ResponseStateManager.RENDER_KIT_ID_PARAM);
if (renderKitIdParam == null) {
renderKitIdParam = bridgeContext.getDefaultRenderKitId();
if (renderKitIdParam != null) {
requestParameterMap.put(ResponseStateManager.RENDER_KIT_ID_PARAM, renderKitIdParam);
}
}
}
catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
protected void addUploadedFile(String fieldName, UploadedFile uploadedFile) {
List<UploadedFile> uploadedFiles = requestParameterFileMap.get(fieldName);
if (uploadedFiles == null) {
uploadedFiles = new ArrayList<UploadedFile>();
requestParameterFileMap.put(fieldName, uploadedFiles);
}
uploadedFiles.add(uploadedFile);
}
@Override
protected AbstractPropertyMapEntry<String> createPropertyMapEntry(String name) {
return new RequestParameterMapEntryMultiPart(name, requestParameterMap);
}
@Override
protected void removeProperty(String name) {
throw new UnsupportedOperationException();
}
protected String stripIllegalCharacters(String fileName) {
// FACES-64: Need to strip out invalid characters.
// http://technet.microsoft.com/en-us/library/cc956689.aspx
String strippedFileName = fileName;
if (fileName != null) {
strippedFileName = fileName.replaceAll("[\\\\/\\[\\]:|<>+;=.?\"]", "-");
}
return strippedFileName;
}
@Override
protected String getProperty(String name) {
return requestParameterMap.get(name);
}
@Override
protected void setProperty(String name, String value) {
throw new UnsupportedOperationException();
}
@Override
protected Enumeration<String> getPropertyNames() {
// Note#1: Section 6.9 of the Bridge spec requires that a parameter name be added to the return value of
// ExternalContext.getRequestParameterNames() for ResponseStateManager.RENDER_KIT_ID_PARAM. This will
// automatically be the case because this class builds up its own internal requestParameterMap in the
// constructor that will contain the ResponseStateManager.RENDER_KIT_ID_PARAM if required.
// Note#2: This can't be cached because the caller basically wants a new enumeration to iterate over each time.
return Collections.enumeration(requestParameterMap.keySet());
}
/**
* Since {@link PortletFileUpload#parseRequest(ActionRequest)} only works with {@link ActionRequest}, this adapter
* class is necessary to force commons-fileupload to work with ResourceRequest (Ajax file upload).
*
* @author Neil Griffin
*/
protected class ActionRequestAdapter implements ActionRequest {
private ResourceRequest resourceRequest;
public ActionRequestAdapter(ResourceRequest resourceRequest) {
this.resourceRequest = resourceRequest;
}
public void removeAttribute(String name) {
resourceRequest.removeAttribute(name);
}
public Object getAttribute(String name) {
return resourceRequest.getAttribute(name);
}
public void setAttribute(String name, Object value) {
resourceRequest.setAttribute(name, value);
}
public Enumeration<String> getAttributeNames() {
return resourceRequest.getAttributeNames();
}
public String getAuthType() {
return resourceRequest.getAuthType();
}
public String getCharacterEncoding() {
return resourceRequest.getCharacterEncoding();
}
public void setCharacterEncoding(String enc) throws UnsupportedEncodingException {
resourceRequest.setCharacterEncoding(enc);
}
public int getContentLength() {
return resourceRequest.getContentLength();
}
public String getContentType() {
return resourceRequest.getContentType();
}
public String getContextPath() {
return resourceRequest.getContextPath();
}
public Cookie[] getCookies() {
return resourceRequest.getCookies();
}
public boolean isPortletModeAllowed(PortletMode mode) {
return resourceRequest.isPortletModeAllowed(mode);
}
public boolean isRequestedSessionIdValid() {
return resourceRequest.isRequestedSessionIdValid();
}
public boolean isWindowStateAllowed(WindowState state) {
return resourceRequest.isWindowStateAllowed(state);
}
public boolean isSecure() {
return resourceRequest.isSecure();
}
public boolean isUserInRole(String role) {
return resourceRequest.isUserInRole(role);
}
public Locale getLocale() {
return resourceRequest.getLocale();
}
public Enumeration<Locale> getLocales() {
return resourceRequest.getLocales();
}
public String getMethod() {
return resourceRequest.getMethod();
}
public String getParameter(String name) {
return resourceRequest.getParameter(name);
}
public Map<String, String[]> getParameterMap() {
return resourceRequest.getParameterMap();
}
public Enumeration<String> getParameterNames() {
return resourceRequest.getParameterNames();
}
public String[] getParameterValues(String name) {
return resourceRequest.getParameterValues(name);
}
public PortalContext getPortalContext() {
return resourceRequest.getPortalContext();
}
public InputStream getPortletInputStream() throws IOException {
return resourceRequest.getPortletInputStream();
}
public PortletMode getPortletMode() {
return resourceRequest.getPortletMode();
}
public PortletSession getPortletSession() {
return resourceRequest.getPortletSession();
}
public PortletSession getPortletSession(boolean create) {
return resourceRequest.getPortletSession();
}
public PortletPreferences getPreferences() {
return resourceRequest.getPreferences();
}
public Map<String, String[]> getPrivateParameterMap() {
return resourceRequest.getPrivateParameterMap();
}
public Enumeration<String> getProperties(String name) {
return resourceRequest.getProperties(name);
}
public String getProperty(String name) {
return resourceRequest.getProperty(name);
}
public Enumeration<String> getPropertyNames() {
return resourceRequest.getPropertyNames();
}
public Map<String, String[]> getPublicParameterMap() {
return resourceRequest.getPublicParameterMap();
}
public BufferedReader getReader() throws UnsupportedEncodingException, IOException {
return resourceRequest.getReader();
}
public String getRemoteUser() {
return resourceRequest.getRemoteUser();
}
public String getRequestedSessionId() {
return resourceRequest.getRequestedSessionId();
}
public String getResponseContentType() {
return resourceRequest.getResponseContentType();
}
public Enumeration<String> getResponseContentTypes() {
return resourceRequest.getResponseContentTypes();
}
public String getScheme() {
return resourceRequest.getScheme();
}
public String getServerName() {
return resourceRequest.getServerName();
}
public int getServerPort() {
return resourceRequest.getServerPort();
}
public Principal getUserPrincipal() {
return resourceRequest.getUserPrincipal();
}
public String getWindowID() {
return resourceRequest.getWindowID();
}
public WindowState getWindowState() {
return resourceRequest.getWindowState();
}
}
}
| true | true | public RequestParameterMapMultiPartImpl(BridgeContext bridgeContext, ClientDataRequest clientDataRequest) {
try {
PortletSession portletSession = clientDataRequest.getPortletSession();
// Determine the uploaded files directory path according to the JSF 2.2 proposal:
// https://javaserverfaces-spec-public.dev.java.net/issues/show_bug.cgi?id=690
String uploadedFilesDir = bridgeContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILES_DIR);
if (uploadedFilesDir == null) {
uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);
if (logger.isDebugEnabled()) {
logger.debug(
"The web.xml context-param name=[{0}] not found, using default system property=[{1}] value=[{2}]",
new Object[] { CONTEXT_PARAM_UPLOADED_FILES_DIR, JAVA_IO_TMPDIR, uploadedFilesDir });
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Using web.xml context-param name=[{0}] value=[{1}]",
new Object[] { CONTEXT_PARAM_UPLOADED_FILES_DIR, uploadedFilesDir });
}
}
// Using the portlet sessionId, determine a unique folder path and create the path if it does not exist.
String sessionId = portletSession.getId();
// FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
// created properly.
sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK);
File uploadedFilesPath = new File(uploadedFilesDir, sessionId);
if (!uploadedFilesPath.exists()) {
try {
uploadedFilesPath.mkdirs();
}
catch (SecurityException e) {
uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);
logger.error(
"Security exception message=[{0}] when trying to create unique path=[{1}] so using default system property=[{2}] value=[{3}]",
new Object[] { e.getMessage(), uploadedFilesPath.toString(), JAVA_IO_TMPDIR, uploadedFilesDir });
uploadedFilesPath = new File(uploadedFilesDir, sessionId);
uploadedFilesPath.mkdirs();
}
}
// Initialize commons-fileupload with the file upload path.
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setRepository(uploadedFilesPath);
// Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
diskFileItemFactory.setFileCleaningTracker(null);
// Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
// instead of staying in memory.
diskFileItemFactory.setSizeThreshold(0);
// Determine the max file upload size threshold in bytes.
String uploadedFilesMaxSize = bridgeContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE);
int fileMaxSize = DEFAULT_FILE_MAX_SIZE;
if (uploadedFilesMaxSize == null) {
if (logger.isDebugEnabled()) {
logger.debug("The web.xml context-param name=[{0}] not found, using default=[{1}] bytes",
new Object[] { CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE });
}
}
else {
try {
fileMaxSize = Integer.parseInt(uploadedFilesMaxSize);
if (logger.isDebugEnabled()) {
logger.debug("Using web.xml context-param name=[{0}] value=[{1}] bytes",
new Object[] { CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, fileMaxSize });
}
}
catch (NumberFormatException e) {
logger.error("Invalid value=[{0}] for web.xml context-param name=[{1}] using default=[{2}] bytes.",
new Object[] {
uploadedFilesMaxSize, CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE
});
}
}
// Parse the request parameters and save all uploaded files in a map.
PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory);
portletFileUpload.setFileSizeMax(fileMaxSize);
requestParameterMap = new HashMap<String, String>();
requestParameterFileMap = new HashMap<String, List<UploadedFile>>();
// Get the namespace that might be found in request parameter names.
String namespace = bridgeContext.getPortletContainer().getResponseNamespace();
// FACES-271: Include name+value pairs found in the ActionRequest.
PortletContainer portletContainer = bridgeContext.getPortletContainer();
Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet();
for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {
String parameterName = mapEntry.getKey();
int pos = parameterName.indexOf(namespace);
if (pos >= 0) {
parameterName = parameterName.substring(pos + namespace.length());
}
String[] parameterValues = mapEntry.getValue();
if (parameterValues.length > 0) {
String fixedRequestParameterValue = portletContainer.fixRequestParameterValue(parameterValues[0]);
requestParameterMap.put(parameterName, fixedRequestParameterValue);
logger.debug("Found in ActionRequest: {0}=[{1}]", parameterName, fixedRequestParameterValue);
}
}
UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder.getFactory(
UploadedFileFactory.class);
// Begin parsing the request for file parts:
try {
FileItemIterator fileItemIterator = null;
if (clientDataRequest instanceof ResourceRequest) {
ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
}
else {
ActionRequest actionRequest = (ActionRequest) clientDataRequest;
fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
}
boolean optimizeNamespace = BooleanHelper.toBoolean(bridgeContext.getInitParameter(
BridgeConfigConstants.PARAM_OPTIMIZE_PORTLET_NAMESPACE1), true);
if (fileItemIterator != null) {
int totalFiles = 0;
// For each field found in the request:
while (fileItemIterator.hasNext()) {
try {
totalFiles++;
// Get the stream of field data from the request.
FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();
// Get field name from the field stream.
String fieldName = fieldStream.getFieldName();
// If namespace optimization is enabled and the namespace is present in the field name,
// then remove the portlet namespace from the field name.
if (optimizeNamespace) {
int pos = fieldName.indexOf(namespace);
if (pos >= 0) {
fieldName = fieldName.substring(pos + namespace.length());
}
}
// Get the content-type, and file-name from the field stream.
String contentType = fieldStream.getContentType();
boolean formField = fieldStream.isFormField();
String fileName = null;
try {
fileName = fieldStream.getName();
}
catch (InvalidFileNameException e) {
fileName = e.getName();
}
// Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
// current field is a simple form-field because the call below to diskFileItem.getString()
// will fail otherwise.
DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
contentType, formField, fileName);
Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);
// If the current field is a simple form-field, then save the form field value in the map.
if (diskFileItem.isFormField()) {
String characterEncoding = clientDataRequest.getCharacterEncoding();
String requestParameterValue = null;
if (characterEncoding == null) {
requestParameterValue = diskFileItem.getString();
}
else {
requestParameterValue = diskFileItem.getString(characterEncoding);
}
String fixedRequestParameterValue = portletContainer.fixRequestParameterValue(
requestParameterValue);
requestParameterMap.put(fieldName, fixedRequestParameterValue);
logger.debug("{0}=[{1}]", fieldName, fixedRequestParameterValue);
}
else {
File tempFile = diskFileItem.getStoreLocation();
// If the copy was successful, then
if (tempFile.exists()) {
// Copy the commons-fileupload temporary file to a file in the same temporary
// location, but with the filename provided by the user in the upload. This has two
// benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
// the file, the developer can have access to a semi-permanent file, because the
// commmons-fileupload DiskFileItem.finalize() method automatically deletes the
// temporary one.
String tempFileName = tempFile.getName();
String tempFileAbsolutePath = tempFile.getAbsolutePath();
String copiedFileName = stripIllegalCharacters(fileName);
String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
copiedFileName);
File copiedFile = new File(copiedFileAbsolutePath);
FileUtils.copyFile(tempFile, copiedFile);
// If present, build up a map of headers.
Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
FileItemHeaders fileItemHeaders = fieldStream.getHeaders();
if (fileItemHeaders != null) {
Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();
if (headerNameItr != null) {
while (headerNameItr.hasNext()) {
String headerName = headerNameItr.next();
Iterator<String> headerValuesItr = fileItemHeaders.getHeaders(
headerName);
List<String> headerValues = new ArrayList<String>();
if (headerValuesItr != null) {
while (headerValuesItr.hasNext()) {
String headerValue = headerValuesItr.next();
headerValues.add(headerValue);
}
}
headersMap.put(headerName, headerValues);
}
}
}
// Put a valid UploadedFile instance into the map that contains all of the
// uploaded file's attributes, along with a successful status.
Map<String, Object> attributeMap = new HashMap<String, Object>();
String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
String message = null;
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
diskFileItem.getContentType(), headersMap, id, message, fileName,
diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);
requestParameterMap.put(fieldName, copiedFileAbsolutePath);
addUploadedFile(fieldName, uploadedFile);
logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
fileName);
}
else {
Exception e = new IOException(
"Failed to copy the stream of file data to a temporary file");
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
addUploadedFile(fieldName, uploadedFile);
}
}
}
catch (Exception e) {
logger.error(e);
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
String fieldName = Integer.toString(totalFiles);
addUploadedFile(fieldName, uploadedFile);
}
}
}
}
// If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
// the map so that the developer can have some idea that something went wrong.
catch (Exception e) {
logger.error(e);
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
addUploadedFile("unknown", uploadedFile);
}
clientDataRequest.setAttribute(PARAM_UPLOADED_FILES, requestParameterFileMap);
// If not found in the request, Section 6.9 of the Bridge spec requires that the value of the
// ResponseStateManager.RENDER_KIT_ID_PARAM request parameter be set to the value of the
// "javax.portlet.faces.<portletName>.defaultRenderKitId" PortletContext attribute.
String renderKitIdParam = requestParameterMap.get(ResponseStateManager.RENDER_KIT_ID_PARAM);
if (renderKitIdParam == null) {
renderKitIdParam = bridgeContext.getDefaultRenderKitId();
if (renderKitIdParam != null) {
requestParameterMap.put(ResponseStateManager.RENDER_KIT_ID_PARAM, renderKitIdParam);
}
}
}
catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
| public RequestParameterMapMultiPartImpl(BridgeContext bridgeContext, ClientDataRequest clientDataRequest) {
try {
PortletSession portletSession = clientDataRequest.getPortletSession();
// Determine the uploaded files directory path according to the JSF 2.2 proposal:
// https://javaserverfaces-spec-public.dev.java.net/issues/show_bug.cgi?id=690
String uploadedFilesDir = bridgeContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILES_DIR);
if (uploadedFilesDir == null) {
uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);
if (logger.isDebugEnabled()) {
logger.debug(
"The web.xml context-param name=[{0}] not found, using default system property=[{1}] value=[{2}]",
new Object[] { CONTEXT_PARAM_UPLOADED_FILES_DIR, JAVA_IO_TMPDIR, uploadedFilesDir });
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Using web.xml context-param name=[{0}] value=[{1}]",
new Object[] { CONTEXT_PARAM_UPLOADED_FILES_DIR, uploadedFilesDir });
}
}
// Using the portlet sessionId, determine a unique folder path and create the path if it does not exist.
String sessionId = portletSession.getId();
// FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
// created properly.
sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK);
File uploadedFilesPath = new File(uploadedFilesDir, sessionId);
if (!uploadedFilesPath.exists()) {
try {
uploadedFilesPath.mkdirs();
}
catch (SecurityException e) {
uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);
logger.error(
"Security exception message=[{0}] when trying to create unique path=[{1}] so using default system property=[{2}] value=[{3}]",
new Object[] { e.getMessage(), uploadedFilesPath.toString(), JAVA_IO_TMPDIR, uploadedFilesDir });
uploadedFilesPath = new File(uploadedFilesDir, sessionId);
uploadedFilesPath.mkdirs();
}
}
// Initialize commons-fileupload with the file upload path.
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setRepository(uploadedFilesPath);
// Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
diskFileItemFactory.setFileCleaningTracker(null);
// Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
// instead of staying in memory.
diskFileItemFactory.setSizeThreshold(0);
// Determine the max file upload size threshold in bytes.
String uploadedFilesMaxSize = bridgeContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE);
int fileMaxSize = DEFAULT_FILE_MAX_SIZE;
if (uploadedFilesMaxSize == null) {
if (logger.isDebugEnabled()) {
logger.debug("The web.xml context-param name=[{0}] not found, using default=[{1}] bytes",
new Object[] { CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE });
}
}
else {
try {
fileMaxSize = Integer.parseInt(uploadedFilesMaxSize);
if (logger.isDebugEnabled()) {
logger.debug("Using web.xml context-param name=[{0}] value=[{1}] bytes",
new Object[] { CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, fileMaxSize });
}
}
catch (NumberFormatException e) {
logger.error("Invalid value=[{0}] for web.xml context-param name=[{1}] using default=[{2}] bytes.",
new Object[] {
uploadedFilesMaxSize, CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE
});
}
}
// Parse the request parameters and save all uploaded files in a map.
PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory);
portletFileUpload.setFileSizeMax(fileMaxSize);
requestParameterMap = new HashMap<String, String>();
requestParameterFileMap = new HashMap<String, List<UploadedFile>>();
// Get the namespace that might be found in request parameter names.
String namespace = bridgeContext.getPortletContainer().getResponseNamespace();
// FACES-271: Include name+value pairs found in the ActionRequest.
PortletContainer portletContainer = bridgeContext.getPortletContainer();
Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet();
for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {
String parameterName = mapEntry.getKey();
int pos = parameterName.indexOf(namespace);
if (pos >= 0) {
parameterName = parameterName.substring(pos + namespace.length());
}
String[] parameterValues = mapEntry.getValue();
if (parameterValues.length > 0) {
String fixedRequestParameterValue = portletContainer.fixRequestParameterValue(parameterValues[0]);
requestParameterMap.put(parameterName, fixedRequestParameterValue);
logger.debug("Found in ActionRequest: {0}=[{1}]", parameterName, fixedRequestParameterValue);
}
}
UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder.getFactory(
UploadedFileFactory.class);
// Begin parsing the request for file parts:
try {
FileItemIterator fileItemIterator = null;
if (clientDataRequest instanceof ResourceRequest) {
ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
}
else {
ActionRequest actionRequest = (ActionRequest) clientDataRequest;
fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
}
boolean optimizeNamespace = BooleanHelper.toBoolean(bridgeContext.getInitParameter(
BridgeConfigConstants.PARAM_OPTIMIZE_PORTLET_NAMESPACE1), true);
if (fileItemIterator != null) {
int totalFiles = 0;
// For each field found in the request:
while (fileItemIterator.hasNext()) {
try {
totalFiles++;
// Get the stream of field data from the request.
FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();
// Get field name from the field stream.
String fieldName = fieldStream.getFieldName();
// If namespace optimization is enabled and the namespace is present in the field name,
// then remove the portlet namespace from the field name.
if (optimizeNamespace) {
int pos = fieldName.indexOf(namespace);
if (pos >= 0) {
fieldName = fieldName.substring(pos + namespace.length());
}
}
// Get the content-type, and file-name from the field stream.
String contentType = fieldStream.getContentType();
boolean formField = fieldStream.isFormField();
String fileName = null;
try {
fileName = fieldStream.getName();
}
catch (InvalidFileNameException e) {
fileName = e.getName();
}
// Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
// current field is a simple form-field because the call below to diskFileItem.getString()
// will fail otherwise.
DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
contentType, formField, fileName);
Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);
// If the current field is a simple form-field, then save the form field value in the map.
if (diskFileItem.isFormField()) {
String characterEncoding = clientDataRequest.getCharacterEncoding();
String requestParameterValue = null;
if (characterEncoding == null) {
requestParameterValue = diskFileItem.getString();
}
else {
requestParameterValue = diskFileItem.getString(characterEncoding);
}
String fixedRequestParameterValue = portletContainer.fixRequestParameterValue(
requestParameterValue);
requestParameterMap.put(fieldName, fixedRequestParameterValue);
logger.debug("{0}=[{1}]", fieldName, fixedRequestParameterValue);
}
else {
File tempFile = diskFileItem.getStoreLocation();
// If the copy was successful, then
if (tempFile.exists()) {
// Copy the commons-fileupload temporary file to a file in the same temporary
// location, but with the filename provided by the user in the upload. This has two
// benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
// the file, the developer can have access to a semi-permanent file, because the
// commmons-fileupload DiskFileItem.finalize() method automatically deletes the
// temporary one.
String tempFileName = tempFile.getName();
String tempFileAbsolutePath = tempFile.getAbsolutePath();
String copiedFileName = stripIllegalCharacters(fileName);
String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
copiedFileName);
File copiedFile = new File(copiedFileAbsolutePath);
FileUtils.copyFile(tempFile, copiedFile);
// If present, build up a map of headers.
Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
FileItemHeaders fileItemHeaders = fieldStream.getHeaders();
if (fileItemHeaders != null) {
Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();
if (headerNameItr != null) {
while (headerNameItr.hasNext()) {
String headerName = headerNameItr.next();
Iterator<String> headerValuesItr = fileItemHeaders.getHeaders(
headerName);
List<String> headerValues = new ArrayList<String>();
if (headerValuesItr != null) {
while (headerValuesItr.hasNext()) {
String headerValue = headerValuesItr.next();
headerValues.add(headerValue);
}
}
headersMap.put(headerName, headerValues);
}
}
}
// Put a valid UploadedFile instance into the map that contains all of the
// uploaded file's attributes, along with a successful status.
Map<String, Object> attributeMap = new HashMap<String, Object>();
String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
String message = null;
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
diskFileItem.getContentType(), headersMap, id, message, fileName,
diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);
requestParameterMap.put(fieldName, copiedFileAbsolutePath);
addUploadedFile(fieldName, uploadedFile);
logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
fileName);
}
else {
if ((fileName != null) && (fileName.trim().length() > 0)) {
Exception e = new IOException(
"Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)");
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
addUploadedFile(fieldName, uploadedFile);
}
}
}
}
catch (Exception e) {
logger.error(e);
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
String fieldName = Integer.toString(totalFiles);
addUploadedFile(fieldName, uploadedFile);
}
}
}
}
// If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
// the map so that the developer can have some idea that something went wrong.
catch (Exception e) {
logger.error(e);
UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
addUploadedFile("unknown", uploadedFile);
}
clientDataRequest.setAttribute(PARAM_UPLOADED_FILES, requestParameterFileMap);
// If not found in the request, Section 6.9 of the Bridge spec requires that the value of the
// ResponseStateManager.RENDER_KIT_ID_PARAM request parameter be set to the value of the
// "javax.portlet.faces.<portletName>.defaultRenderKitId" PortletContext attribute.
String renderKitIdParam = requestParameterMap.get(ResponseStateManager.RENDER_KIT_ID_PARAM);
if (renderKitIdParam == null) {
renderKitIdParam = bridgeContext.getDefaultRenderKitId();
if (renderKitIdParam != null) {
requestParameterMap.put(ResponseStateManager.RENDER_KIT_ID_PARAM, renderKitIdParam);
}
}
}
catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
|
diff --git a/splitString.java b/splitString.java
index 384c577..5b73c3d 100644
--- a/splitString.java
+++ b/splitString.java
@@ -1,29 +1,29 @@
/*
* Copyright (C) 2013
* 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, version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*/
public class splitString {
public static void main(String args[]){
String str = "2.2.0-10.0.59.20134.douglas.master.ev";
// dot is special code, require \\
String delimiter = "\\.";
String temp[] = str.split(delimiter);
- // Printing by delimiter
+ // Printing by delimiter
for(int i=0; i < temp.length; i++)
System.out.println(temp[i]);
if (temp[2].contains("-")) {
System.out.println(temp[2].split("-")[0]);
}
}
}
| true | true | public static void main(String args[]){
String str = "2.2.0-10.0.59.20134.douglas.master.ev";
// dot is special code, require \\
String delimiter = "\\.";
String temp[] = str.split(delimiter);
// Printing by delimiter
for(int i=0; i < temp.length; i++)
System.out.println(temp[i]);
if (temp[2].contains("-")) {
System.out.println(temp[2].split("-")[0]);
}
}
| public static void main(String args[]){
String str = "2.2.0-10.0.59.20134.douglas.master.ev";
// dot is special code, require \\
String delimiter = "\\.";
String temp[] = str.split(delimiter);
// Printing by delimiter
for(int i=0; i < temp.length; i++)
System.out.println(temp[i]);
if (temp[2].contains("-")) {
System.out.println(temp[2].split("-")[0]);
}
}
|
diff --git a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/ConfirmInvoice.java b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/ConfirmInvoice.java
index ea6721aa..4d988990 100644
--- a/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/ConfirmInvoice.java
+++ b/expenditure-tracking/src/pt/ist/expenditureTrackingSystem/domain/acquisitions/simplified/activities/ConfirmInvoice.java
@@ -1,88 +1,88 @@
package pt.ist.expenditureTrackingSystem.domain.acquisitions.simplified.activities;
import java.util.Set;
import module.workflow.activities.ActivityInformation;
import module.workflow.activities.WorkflowActivity;
import myorg.applicationTier.Authenticate.UserView;
import myorg.domain.User;
import myorg.util.BundleUtil;
import org.apache.commons.lang.StringUtils;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.AcquisitionInvoice;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.PaymentProcessInvoice;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.RegularAcquisitionProcess;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.RequestItem;
import pt.ist.expenditureTrackingSystem.domain.acquisitions.UnitItem;
import pt.ist.expenditureTrackingSystem.domain.organization.Person;
import pt.ist.expenditureTrackingSystem.domain.organization.Unit;
public class ConfirmInvoice extends WorkflowActivity<RegularAcquisitionProcess, ActivityInformation<RegularAcquisitionProcess>> {
@Override
public boolean isActive(RegularAcquisitionProcess process, User user) {
Person person = user.getExpenditurePerson();
return isUserProcessOwner(process, user) && person != null && process.isActive() && !process.isInvoiceReceived()
&& !process.getUnconfirmedInvoices(person).isEmpty() && process.isResponsibleForUnit(person);
}
@Override
protected void process(ActivityInformation<RegularAcquisitionProcess> activityInformation) {
activityInformation.getProcess().confirmInvoiceBy(UserView.getCurrentUser().getExpenditurePerson());
}
@Override
public String getLocalizedName() {
return BundleUtil.getStringFromResourceBundle(getUsedBundle(), "label." + getClass().getName());
}
@Override
public String getUsedBundle() {
return "resources/AcquisitionResources";
}
@Override
public boolean isConfirmationNeeded(RegularAcquisitionProcess process) {
User currentUser = UserView.getCurrentUser();
Set<AcquisitionInvoice> unconfirmedInvoices = process.getUnconfirmedInvoices(currentUser.getExpenditurePerson());
for (AcquisitionInvoice unconfirmedInvoice : unconfirmedInvoices) {
if (!StringUtils.isEmpty(unconfirmedInvoice.getConfirmationReport())) {
return true;
}
}
return false;
}
@Override
public String getLocalizedConfirmationMessage(RegularAcquisitionProcess process) {
StringBuilder builder = new StringBuilder();
User currentUser = UserView.getCurrentUser();
Set<AcquisitionInvoice> unconfirmedInvoices = process.getUnconfirmedInvoices(currentUser.getExpenditurePerson());
for (AcquisitionInvoice unconfirmedInvoice : unconfirmedInvoices) {
builder.append(BundleUtil.getFormattedStringFromResourceBundle(getUsedBundle(), "activity.confirmation."
+ getClass().getName(), unconfirmedInvoice.getInvoiceNumber(), unconfirmedInvoice.getConfirmationReport()));
}
return builder.toString();
}
@Override
public boolean isUserAwarenessNeeded(final RegularAcquisitionProcess process, final User user) {
final Person person = user.getExpenditurePerson();
if (person.hasAnyValidAuthorization()) {
for (final RequestItem requestItem : process.getRequest().getRequestItemsSet()) {
- for (PaymentProcessInvoice invoice : requestItem.getInvoicesFiles()) {
- for (final UnitItem unitItem : invoice.getUnitItemsSet()) {
- final Unit unit = unitItem.getUnit();
+ for (final UnitItem unitItem : requestItem.getUnitItemsSet()) {
+ final Unit unit = unitItem.getUnit();
+ for (final PaymentProcessInvoice invoice : requestItem.getInvoicesFilesSet()) {
if (!unitItem.getConfirmedInvoices().contains(invoice) && unit.isDirectResponsible(person)) {
return true;
}
}
}
}
}
return false;
}
}
| true | true | public boolean isUserAwarenessNeeded(final RegularAcquisitionProcess process, final User user) {
final Person person = user.getExpenditurePerson();
if (person.hasAnyValidAuthorization()) {
for (final RequestItem requestItem : process.getRequest().getRequestItemsSet()) {
for (PaymentProcessInvoice invoice : requestItem.getInvoicesFiles()) {
for (final UnitItem unitItem : invoice.getUnitItemsSet()) {
final Unit unit = unitItem.getUnit();
if (!unitItem.getConfirmedInvoices().contains(invoice) && unit.isDirectResponsible(person)) {
return true;
}
}
}
}
}
return false;
}
| public boolean isUserAwarenessNeeded(final RegularAcquisitionProcess process, final User user) {
final Person person = user.getExpenditurePerson();
if (person.hasAnyValidAuthorization()) {
for (final RequestItem requestItem : process.getRequest().getRequestItemsSet()) {
for (final UnitItem unitItem : requestItem.getUnitItemsSet()) {
final Unit unit = unitItem.getUnit();
for (final PaymentProcessInvoice invoice : requestItem.getInvoicesFilesSet()) {
if (!unitItem.getConfirmedInvoices().contains(invoice) && unit.isDirectResponsible(person)) {
return true;
}
}
}
}
}
return false;
}
|
diff --git a/dfpagent/src/com/github/veithen/dfpagent/protocol/connection/Connection.java b/dfpagent/src/com/github/veithen/dfpagent/protocol/connection/Connection.java
index e0f65a9..24b0d42 100644
--- a/dfpagent/src/com/github/veithen/dfpagent/protocol/connection/Connection.java
+++ b/dfpagent/src/com/github/veithen/dfpagent/protocol/connection/Connection.java
@@ -1,134 +1,134 @@
package com.github.veithen.dfpagent.protocol.connection;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.github.veithen.dfpagent.Constants;
import com.github.veithen.dfpagent.protocol.DFPConstants;
import com.github.veithen.dfpagent.protocol.message.Message;
import com.github.veithen.dfpagent.protocol.message.MessageType;
import com.github.veithen.dfpagent.protocol.tlv.TLV;
import com.github.veithen.dfpagent.protocol.tlv.Type;
import com.github.veithen.dfpagent.resources.Messages;
import com.ibm.ejs.ras.Tr;
import com.ibm.ejs.ras.TraceComponent;
/**
* Manages a DFP connection. This class may be used both for outgoing and incoming connections. Its
* primary responsibility is to deserialize incoming messages and to serialize outgoing messages. To
* use this class:
* <ol>
* <li>Create the underlying {@link Socket}.
* <li>Create a {@link Handler} instance that processes incoming messages.
* <li>Create an instance of this class.
* <li>Execute the {@link Connection#run()} method, potentially in a separate thread.
* </ol>
* To close the connection, call {@link Connection#stop()}. This will cause the
* {@link Connection#run()} method to exit.
* <p>
* This class is thread safe.
*/
public final class Connection implements Runnable {
private static final TraceComponent TC = Tr.register(Connection.class, Constants.TRACE_GROUP, Messages.class.getName());
private static final Map<Integer,MessageType> messageTypeByCode = new HashMap<Integer,MessageType>();
private static final Map<Integer,Type> typeByCode = new HashMap<Integer,Type>();
static {
for (MessageType messageType : MessageType.values()) {
messageTypeByCode.put(messageType.getCode(), messageType);
}
for (Type type : Type.values()) {
typeByCode.put(type.getCode(), type);
}
}
private final Socket socket;
private final Handler handler;
private final DataInputStream in;
private final DataOutputStream out;
public Connection(Socket socket, Handler handler) throws IOException {
this.socket = socket;
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
this.handler = handler;
}
public void run() {
try {
ml: while (true) {
int version = in.readUnsignedShort();
if (version != DFPConstants.VERSION) {
Tr.error(TC, Messages._0005E, new Object[] { DFPConstants.VERSION, version });
break;
}
int messageTypeCode = in.readUnsignedShort();
int messageLength = in.readInt();
int remaining = messageLength - 8;
List<TLV> tlvs = new ArrayList<TLV>();
while (remaining != 0) {
if (remaining < 4) {
Tr.error(TC, Messages._0006E);
break ml;
}
int typeCode = in.readUnsignedShort();
int length = in.readUnsignedShort();
if (remaining < length) {
Tr.error(TC, Messages._0006E);
break ml;
}
byte[] value = new byte[length-4];
in.readFully(value);
Type type = typeByCode.get(typeCode);
if (type == null) {
Tr.warning(TC, Messages._0010W, typeCode);
} else {
tlvs.add(new TLV(type, value));
}
remaining -= length;
}
- MessageType messageType = messageTypeByCode.get(messageTypeByCode);
+ MessageType messageType = messageTypeByCode.get(messageTypeCode);
if (messageType == null) {
Tr.warning(TC, Messages._0009W, messageTypeCode);
} else {
handler.processMessage(new Message(messageType, tlvs));
}
}
socket.close();
} catch (IOException ex) {
// TODO
}
}
/**
* Send a message to the peer.
*
* @param message the message to send
*/
public synchronized void sendMessage(Message message) throws IOException {
int length = 8;
for (TLV tlv : message) {
length += tlv.getDataLength() + 4;
}
out.writeShort(DFPConstants.VERSION);
out.writeShort(message.getType().getCode());
out.writeInt(length);
for (TLV tlv : message) {
out.writeShort(tlv.getType().getCode());
out.writeShort(tlv.getDataLength() + 4);
tlv.writeValue(out);
}
out.flush();
}
public void stop() {
// TODO
}
}
| true | true | public void run() {
try {
ml: while (true) {
int version = in.readUnsignedShort();
if (version != DFPConstants.VERSION) {
Tr.error(TC, Messages._0005E, new Object[] { DFPConstants.VERSION, version });
break;
}
int messageTypeCode = in.readUnsignedShort();
int messageLength = in.readInt();
int remaining = messageLength - 8;
List<TLV> tlvs = new ArrayList<TLV>();
while (remaining != 0) {
if (remaining < 4) {
Tr.error(TC, Messages._0006E);
break ml;
}
int typeCode = in.readUnsignedShort();
int length = in.readUnsignedShort();
if (remaining < length) {
Tr.error(TC, Messages._0006E);
break ml;
}
byte[] value = new byte[length-4];
in.readFully(value);
Type type = typeByCode.get(typeCode);
if (type == null) {
Tr.warning(TC, Messages._0010W, typeCode);
} else {
tlvs.add(new TLV(type, value));
}
remaining -= length;
}
MessageType messageType = messageTypeByCode.get(messageTypeByCode);
if (messageType == null) {
Tr.warning(TC, Messages._0009W, messageTypeCode);
} else {
handler.processMessage(new Message(messageType, tlvs));
}
}
socket.close();
} catch (IOException ex) {
// TODO
}
}
| public void run() {
try {
ml: while (true) {
int version = in.readUnsignedShort();
if (version != DFPConstants.VERSION) {
Tr.error(TC, Messages._0005E, new Object[] { DFPConstants.VERSION, version });
break;
}
int messageTypeCode = in.readUnsignedShort();
int messageLength = in.readInt();
int remaining = messageLength - 8;
List<TLV> tlvs = new ArrayList<TLV>();
while (remaining != 0) {
if (remaining < 4) {
Tr.error(TC, Messages._0006E);
break ml;
}
int typeCode = in.readUnsignedShort();
int length = in.readUnsignedShort();
if (remaining < length) {
Tr.error(TC, Messages._0006E);
break ml;
}
byte[] value = new byte[length-4];
in.readFully(value);
Type type = typeByCode.get(typeCode);
if (type == null) {
Tr.warning(TC, Messages._0010W, typeCode);
} else {
tlvs.add(new TLV(type, value));
}
remaining -= length;
}
MessageType messageType = messageTypeByCode.get(messageTypeCode);
if (messageType == null) {
Tr.warning(TC, Messages._0009W, messageTypeCode);
} else {
handler.processMessage(new Message(messageType, tlvs));
}
}
socket.close();
} catch (IOException ex) {
// TODO
}
}
|
diff --git a/src/main/java/com/github/kpacha/jkata/pokerhand/PokerCard.java b/src/main/java/com/github/kpacha/jkata/pokerhand/PokerCard.java
index 894038c..b94959f 100644
--- a/src/main/java/com/github/kpacha/jkata/pokerhand/PokerCard.java
+++ b/src/main/java/com/github/kpacha/jkata/pokerhand/PokerCard.java
@@ -1,17 +1,19 @@
package com.github.kpacha.jkata.pokerhand;
public class PokerCard {
private String card;
public PokerCard(String card) {
this.card = card;
}
public int getNumericValue() {
+ if (card.charAt(0) == 'J')
+ return 10;
if (card.charAt(0) == '9')
return 9;
return 5;
}
}
| true | true | public int getNumericValue() {
if (card.charAt(0) == '9')
return 9;
return 5;
}
| public int getNumericValue() {
if (card.charAt(0) == 'J')
return 10;
if (card.charAt(0) == '9')
return 9;
return 5;
}
|
diff --git a/src/DialogCharacters.java b/src/DialogCharacters.java
index 3f8ff54..7f68147 100644
--- a/src/DialogCharacters.java
+++ b/src/DialogCharacters.java
@@ -1,203 +1,202 @@
/*
Mafiamanager - a tool to support the referee of the parlor game "Mafia"
Copyright (C) 2011 Thomas Högner
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.SortedMap;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class DialogCharacters extends JDialog implements ActionListener{
private static final long serialVersionUID = -9021187337746013906L;
// general
private SortedMap<String, Player> playerlist;
private Board board;
private int counterCharacters;
private int counterPlayer;
// gui
private GridBagConstraints con;
private KeyListener keylistener;
private JLabel labelTxt;
private JLabel labelCounter;
private JPanel panelCharacters;
private ArrayList<JPanel> panelx;
private ArrayList<JLabel> labelx;
private ArrayList<JTextField> fieldx;
private JButton buttonAcc;
public DialogCharacters(SortedMap<String, Player> _playerlist, JFrame _frame, Board _board){
super(_frame, true);
// initializing
playerlist = _playerlist;
board = _board;
counterPlayer = playerlist.size();
panelx = new ArrayList<JPanel>();
labelx = new ArrayList<JLabel>();
fieldx = new ArrayList<JTextField>();
// gui
setLayout(new GridBagLayout());
con = new GridBagConstraints();
con.gridx = 0;
con.insets = new Insets(0,0,5,0);
// text
labelTxt = new JLabel(Messages.getString("gui.configureTxt"));
con.gridy = 0;
add(labelTxt, con);
// counter
labelCounter = new JLabel(Messages.getString("gui.leftPlayer")+" "+counterPlayer);
con.gridy = 1;
add(labelCounter, con);
// listener for checking textfields
keylistener = new KeyListener() {
public void keyPressed(KeyEvent event) {
}
public void keyReleased(KeyEvent event) {
int sum = 0;
boolean onlynumbers = true;
for (JTextField curField : fieldx){
String number = curField.getText();
if (!number.equals("")){
try {
sum += Integer.parseInt(number);
} catch (NumberFormatException e){
- System.err.println(Messages.getString("err.nonum"));
onlynumbers = false;
break;
}
}
}
counterPlayer = playerlist.size() - sum;
if (onlynumbers && counterPlayer >= 0){
labelCounter.setForeground(null);
buttonAcc.setEnabled(true);
labelCounter.setText(Messages.getString("gui.leftPlayer")+" "+counterPlayer);
}
else if (onlynumbers) {
labelCounter.setForeground(Color.red);
buttonAcc.setEnabled(false);
labelCounter.setText(Messages.getString("gui.leftPlayer")+" "+counterPlayer);
}
else {
labelCounter.setForeground(Color.red);
buttonAcc.setEnabled(false);
labelCounter.setText(Messages.getString("gui.leftPlayererr"));
}
}
public void keyTyped(KeyEvent event) {
}
};
// characters
panelCharacters = new JPanel(new GridLayout(0,1));
counterCharacters = 0;
addCharacter(2);
addCharacter(3);
addCharacter(4);
con.gridy = 2;
add(panelCharacters, con);
// button accept
buttonAcc = new JButton(Messages.getString("gui.acc"));
buttonAcc.addActionListener(this);
con.gridy = 3;
add(buttonAcc, con);
// dialog end
pack();
setLocationRelativeTo(null);
setVisible(true);
}
// add figure
public void addCharacter(int _fig){
panelx.add(new JPanel(new GridLayout(1,2)));
labelx.add(new JLabel(Keys.IntToFigure(_fig)+":"));
fieldx.add(new JTextField(5));
fieldx.get(counterCharacters).addKeyListener(keylistener);
panelx.get(counterCharacters).add(labelx.get(counterCharacters));
panelx.get(counterCharacters).add(fieldx.get(counterCharacters));
panelCharacters.add(panelx.get(counterCharacters));
counterCharacters++;
}
// button Accept pressed
public void actionPerformed(ActionEvent event) {
if (event.getSource() == buttonAcc){
Keys.villager = counterPlayer;
Keys.mafia = StringToInt(fieldx.get(0).getText());
Keys.detective = StringToInt(fieldx.get(1).getText());
Keys.doctor = StringToInt(fieldx.get(2).getText());
board.space();
board.line(Messages.getString("log.character"));
if (Keys.villager > 0) board.line(Messages.getString("villager")+"("+Keys.villager+")");
if (Keys.mafia > 0) board.line(Messages.getString("mafia")+"("+Keys.mafia+")");
if (Keys.detective > 0) board.line(Messages.getString("detective")+"("+Keys.detective+")");
if (Keys.doctor > 0) board.line(Messages.getString("doctor")+"("+Keys.doctor+")");
setVisible(false);
}
}
// convert string to integer
public int StringToInt(String _s){
int i = 0;
if (!_s.equals("")){
try { i = Integer.parseInt(_s); }
catch (NumberFormatException e){}
}
return i;
}
}
| true | true | public DialogCharacters(SortedMap<String, Player> _playerlist, JFrame _frame, Board _board){
super(_frame, true);
// initializing
playerlist = _playerlist;
board = _board;
counterPlayer = playerlist.size();
panelx = new ArrayList<JPanel>();
labelx = new ArrayList<JLabel>();
fieldx = new ArrayList<JTextField>();
// gui
setLayout(new GridBagLayout());
con = new GridBagConstraints();
con.gridx = 0;
con.insets = new Insets(0,0,5,0);
// text
labelTxt = new JLabel(Messages.getString("gui.configureTxt"));
con.gridy = 0;
add(labelTxt, con);
// counter
labelCounter = new JLabel(Messages.getString("gui.leftPlayer")+" "+counterPlayer);
con.gridy = 1;
add(labelCounter, con);
// listener for checking textfields
keylistener = new KeyListener() {
public void keyPressed(KeyEvent event) {
}
public void keyReleased(KeyEvent event) {
int sum = 0;
boolean onlynumbers = true;
for (JTextField curField : fieldx){
String number = curField.getText();
if (!number.equals("")){
try {
sum += Integer.parseInt(number);
} catch (NumberFormatException e){
System.err.println(Messages.getString("err.nonum"));
onlynumbers = false;
break;
}
}
}
counterPlayer = playerlist.size() - sum;
if (onlynumbers && counterPlayer >= 0){
labelCounter.setForeground(null);
buttonAcc.setEnabled(true);
labelCounter.setText(Messages.getString("gui.leftPlayer")+" "+counterPlayer);
}
else if (onlynumbers) {
labelCounter.setForeground(Color.red);
buttonAcc.setEnabled(false);
labelCounter.setText(Messages.getString("gui.leftPlayer")+" "+counterPlayer);
}
else {
labelCounter.setForeground(Color.red);
buttonAcc.setEnabled(false);
labelCounter.setText(Messages.getString("gui.leftPlayererr"));
}
}
public void keyTyped(KeyEvent event) {
}
};
// characters
panelCharacters = new JPanel(new GridLayout(0,1));
counterCharacters = 0;
addCharacter(2);
addCharacter(3);
addCharacter(4);
con.gridy = 2;
add(panelCharacters, con);
// button accept
buttonAcc = new JButton(Messages.getString("gui.acc"));
buttonAcc.addActionListener(this);
con.gridy = 3;
add(buttonAcc, con);
// dialog end
pack();
setLocationRelativeTo(null);
setVisible(true);
}
| public DialogCharacters(SortedMap<String, Player> _playerlist, JFrame _frame, Board _board){
super(_frame, true);
// initializing
playerlist = _playerlist;
board = _board;
counterPlayer = playerlist.size();
panelx = new ArrayList<JPanel>();
labelx = new ArrayList<JLabel>();
fieldx = new ArrayList<JTextField>();
// gui
setLayout(new GridBagLayout());
con = new GridBagConstraints();
con.gridx = 0;
con.insets = new Insets(0,0,5,0);
// text
labelTxt = new JLabel(Messages.getString("gui.configureTxt"));
con.gridy = 0;
add(labelTxt, con);
// counter
labelCounter = new JLabel(Messages.getString("gui.leftPlayer")+" "+counterPlayer);
con.gridy = 1;
add(labelCounter, con);
// listener for checking textfields
keylistener = new KeyListener() {
public void keyPressed(KeyEvent event) {
}
public void keyReleased(KeyEvent event) {
int sum = 0;
boolean onlynumbers = true;
for (JTextField curField : fieldx){
String number = curField.getText();
if (!number.equals("")){
try {
sum += Integer.parseInt(number);
} catch (NumberFormatException e){
onlynumbers = false;
break;
}
}
}
counterPlayer = playerlist.size() - sum;
if (onlynumbers && counterPlayer >= 0){
labelCounter.setForeground(null);
buttonAcc.setEnabled(true);
labelCounter.setText(Messages.getString("gui.leftPlayer")+" "+counterPlayer);
}
else if (onlynumbers) {
labelCounter.setForeground(Color.red);
buttonAcc.setEnabled(false);
labelCounter.setText(Messages.getString("gui.leftPlayer")+" "+counterPlayer);
}
else {
labelCounter.setForeground(Color.red);
buttonAcc.setEnabled(false);
labelCounter.setText(Messages.getString("gui.leftPlayererr"));
}
}
public void keyTyped(KeyEvent event) {
}
};
// characters
panelCharacters = new JPanel(new GridLayout(0,1));
counterCharacters = 0;
addCharacter(2);
addCharacter(3);
addCharacter(4);
con.gridy = 2;
add(panelCharacters, con);
// button accept
buttonAcc = new JButton(Messages.getString("gui.acc"));
buttonAcc.addActionListener(this);
con.gridy = 3;
add(buttonAcc, con);
// dialog end
pack();
setLocationRelativeTo(null);
setVisible(true);
}
|
diff --git a/src/coinFlipV1/gitmad/app/ResultActivity.java b/src/coinFlipV1/gitmad/app/ResultActivity.java
index 51aedc0..5805f74 100644
--- a/src/coinFlipV1/gitmad/app/ResultActivity.java
+++ b/src/coinFlipV1/gitmad/app/ResultActivity.java
@@ -1,232 +1,232 @@
package coinFlipV1.gitmad.app;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import coinFlipV1.gitmad.app.db.CoinFlipDbOpenHelper;
public class ResultActivity extends Activity implements OnClickListener {
public static final String PARAM_RESULT = "result";
private String result = "not set", name = "david";
private int resultImage = 0, retries = 0, currTotal = 0;
private HttpURLConnection connection;
private URL url;
public void connectionSetup() {
try {
url = new URL("http://gitmadleaderboard.herokuapp.com/scores");
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
String result = getIntent().getExtras().getString(ResultActivity.PARAM_RESULT);
setResult(result);
connectionSetup();
//open a writable database connection
CoinFlipDbOpenHelper dbHelper = new CoinFlipDbOpenHelper(this);
SQLiteDatabase database = dbHelper.getWritableDatabase();
try {
//record the flip and update the distribution
recordCoinFlip(database);
updateFlipDistribution(database);
// Spin off Async task
new postResultsTask().execute();
} finally {
database.close();
}
Log.d("Demo", getResult());
int images[] = {R.drawable.heads, R.drawable.tails};
ImageView resultImageView = (ImageView) this.findViewById(R.id.result_value_image);
resultImageView.setBackgroundResource(images[0]);
//TextView text = (TextView) this.findViewById(R.id.result_value_label);
//text.setText(getResult());
- if (getResult() == "heads")
+ if (getResult().equals("heads"))
{
resultImage = R.drawable.heads;
flipAnimate(resultImageView, images, 0, 9, true);
}
else
{
resultImage = R.drawable.tails;
flipAnimate(resultImageView, images, 0, 7, true);
}
View flipCoinButton = findViewById(R.id.back_to_menu_button);
flipCoinButton.setOnClickListener(this);
}
private class postResultsTask extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
Log.d("currTotal", String.valueOf(currTotal));
postScore(name, String.valueOf(currTotal));
return null;
}
protected void onPostExecute(Void result) {}
}
private void postScore(String name, String score) {
HttpURLConnection connection = null;
try {
String leaderboardEntry = new String("{\"score\": { \"name\": \"" + name + "\", \"score\": " + score + "}}");
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.getOutputStream().write(leaderboardEntry.getBytes());
connection.connect();
connection.getResponseCode();
Log.d("resp code", String.valueOf(connection.getResponseCode()));
this.retries = 0;
} catch (IOException e) {
this.retries++;
if(this.retries >= 5)
throw new RuntimeException(e);
} finally {
if(connection != null)
connection.disconnect();
}
}
private void updateFlipDistribution(SQLiteDatabase database) {
//process the counts
SparseIntArray spArray = new SparseIntArray();
spArray.put(0, 0);
spArray.put(1, 0);
int total = 0;
Cursor c = database.query(CoinFlipDbOpenHelper.FLIP_TABLE,
new String[] {CoinFlipDbOpenHelper.FLIP_TYPE, "count(*)"},
null, null, CoinFlipDbOpenHelper.FLIP_TYPE, null, null);
try {
//iterate thru the cursor...there should be 1 or 2 entries
//NOTE: first col of 0 indicates heads, 1 indicates tails
c.moveToFirst();
while(!c.isAfterLast()) {
int count = c.getInt(1);
spArray.put(c.getInt(0), count);
total += count;
c.moveToNext();
}
} finally {
c.close();
}
currTotal = total;
//format the text for the flip distribution
String text;
if (total > 0) {
text = String.format("%d flip%s, %2.0f%% heads, %2.0f%% tails", total, total != 1 ? "s" : "", spArray.get(0) * 100.0 / total, spArray.get(1) * 100.0 / total);
} else {
text = "0 flips.";
}
TextView textView = (TextView) this.findViewById(R.id.flip_distribution);
textView.setText(text);
}
private void recordCoinFlip(SQLiteDatabase database) {
ContentValues values = new ContentValues();
values.put(CoinFlipDbOpenHelper.FLIP_TYPE, getResult().equals("heads") ? 0 : 1);
database.insert(CoinFlipDbOpenHelper.FLIP_TABLE, null, values);
}
public void setResult(String result) {
this.result = result;
}
public String getResult() {
return result;
}
private void flipAnimate(final ImageView imageView, final int images[], final int imageIndex, final int iterations, final boolean isShrunk) {
if (iterations > 0) {
Animation curAnim = null;
ScaleAnimation shrink = new ScaleAnimation(1, 0, 1, 1, Animation.RELATIVE_TO_SELF, (float) 0.5, Animation.RELATIVE_TO_SELF, (float) .5);
ScaleAnimation expand = new ScaleAnimation(0, 1, 1, 1, Animation.RELATIVE_TO_SELF, (float) 0.5, Animation.RELATIVE_TO_SELF, (float) .5);
if (isShrunk)
{
curAnim = expand;
imageView.setBackgroundResource(images[imageIndex]);
}
else{
curAnim = shrink;
}
curAnim.setDuration(300);
imageView.setAnimation(curAnim);
curAnim.setAnimationListener(new AnimationListener() {
public void onAnimationEnd(Animation animation) {
int newIndex = imageIndex;
if (isShrunk)
{
if (imageIndex == 1)
{
newIndex = 0;
}
else
{
newIndex = 1;
}
}
flipAnimate(imageView, images, newIndex, iterations-1, !isShrunk);
}
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
});
}
}
@Override
public void onClick(View v) {
this.finish();
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
String result = getIntent().getExtras().getString(ResultActivity.PARAM_RESULT);
setResult(result);
connectionSetup();
//open a writable database connection
CoinFlipDbOpenHelper dbHelper = new CoinFlipDbOpenHelper(this);
SQLiteDatabase database = dbHelper.getWritableDatabase();
try {
//record the flip and update the distribution
recordCoinFlip(database);
updateFlipDistribution(database);
// Spin off Async task
new postResultsTask().execute();
} finally {
database.close();
}
Log.d("Demo", getResult());
int images[] = {R.drawable.heads, R.drawable.tails};
ImageView resultImageView = (ImageView) this.findViewById(R.id.result_value_image);
resultImageView.setBackgroundResource(images[0]);
//TextView text = (TextView) this.findViewById(R.id.result_value_label);
//text.setText(getResult());
if (getResult() == "heads")
{
resultImage = R.drawable.heads;
flipAnimate(resultImageView, images, 0, 9, true);
}
else
{
resultImage = R.drawable.tails;
flipAnimate(resultImageView, images, 0, 7, true);
}
View flipCoinButton = findViewById(R.id.back_to_menu_button);
flipCoinButton.setOnClickListener(this);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
String result = getIntent().getExtras().getString(ResultActivity.PARAM_RESULT);
setResult(result);
connectionSetup();
//open a writable database connection
CoinFlipDbOpenHelper dbHelper = new CoinFlipDbOpenHelper(this);
SQLiteDatabase database = dbHelper.getWritableDatabase();
try {
//record the flip and update the distribution
recordCoinFlip(database);
updateFlipDistribution(database);
// Spin off Async task
new postResultsTask().execute();
} finally {
database.close();
}
Log.d("Demo", getResult());
int images[] = {R.drawable.heads, R.drawable.tails};
ImageView resultImageView = (ImageView) this.findViewById(R.id.result_value_image);
resultImageView.setBackgroundResource(images[0]);
//TextView text = (TextView) this.findViewById(R.id.result_value_label);
//text.setText(getResult());
if (getResult().equals("heads"))
{
resultImage = R.drawable.heads;
flipAnimate(resultImageView, images, 0, 9, true);
}
else
{
resultImage = R.drawable.tails;
flipAnimate(resultImageView, images, 0, 7, true);
}
View flipCoinButton = findViewById(R.id.back_to_menu_button);
flipCoinButton.setOnClickListener(this);
}
|
diff --git a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIT.java b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIT.java
index c85905a1..53a068b1 100644
--- a/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIT.java
+++ b/surefire-integration-tests/src/test/java/org/apache/maven/surefire/its/WorkingDirectoryIT.java
@@ -1,137 +1,137 @@
package org.apache.maven.surefire.its;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import org.apache.commons.lang.SystemUtils;
import org.apache.maven.it.Verifier;
import org.apache.maven.it.util.ResourceExtractor;
/**
* Test working directory configuration, SUREFIRE-416
*
* @author <a href="mailto:[email protected]">Dan Fabulich</a>
*/
public class WorkingDirectoryIT
extends AbstractSurefireIntegrationTestClass
{
private File testDir;
private File childTestDir;
private File targetDir;
private File outFile;
public void setUp()
throws IOException
{
testDir = ResourceExtractor.simpleExtractResources( getClass(), "/working-directory" );
childTestDir = new File( testDir, "child" );
targetDir = new File( childTestDir, "target" );
outFile = new File( targetDir, "out.txt" );
outFile.delete();
}
public void testWorkingDirectory()
throws Exception
{
Verifier verifier = new Verifier( testDir.getAbsolutePath() );
this.executeGoal( verifier, "test" );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
HelperAssertions.assertTestSuiteResults( 1, 0, 0, 0, childTestDir );
verifyOutputDirectory( childTestDir );
}
public void verifyOutputDirectory( File childTestDir )
throws IOException
{
assertTrue( "out.txt doesn't exist: " + outFile.getAbsolutePath(), outFile.exists() );
Properties p = new Properties();
FileInputStream is = new FileInputStream( outFile );
p.load( is );
is.close();
String userDirPath = p.getProperty( "user.dir" );
assertNotNull( "user.dir was null in property file", userDirPath );
File userDir = new File( userDirPath );
// test if not a symlink
- String message = "canonicalFile " + userDir.getCanonicalPath() + SystemUtils.LINE_SEPARATOR
- + " absolutePath " + userDir.getAbsolutePath() + SystemUtils.LINE_SEPARATOR
- + " path " + userDir.getPath() + SystemUtils.LINE_SEPARATOR;
- if ( userDir.getCanonicalFile().equals(userDir.getAbsoluteFile()) )
+ String message = "canonicalFile " + childTestDir.getCanonicalPath() + SystemUtils.LINE_SEPARATOR
+ + " absolutePath " + childTestDir.getAbsolutePath() + SystemUtils.LINE_SEPARATOR
+ + " path " + childTestDir.getPath() + SystemUtils.LINE_SEPARATOR;
+ if ( childTestDir.getCanonicalFile().equals(childTestDir.getAbsoluteFile()) )
{
assertEquals( "wrong user.dir ! symlink " + message, childTestDir.getAbsolutePath(), userDir.getAbsolutePath() );
}
else
{
assertEquals( "wrong user.dir symlink " + message, childTestDir.getCanonicalPath(), userDir.getCanonicalPath() );
}
}
public void testWorkingDirectoryNoFork()
throws Exception
{
Verifier verifier = new Verifier( testDir.getAbsolutePath() );
List<String> goals = this.getInitialGoals();
goals.add( "test" );
goals.add( "-DforkMode=never" );
executeGoals( verifier, goals );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
HelperAssertions.assertTestSuiteResults( 1, 0, 0, 0, childTestDir );
verifyOutputDirectory( childTestDir );
}
public void testWorkingDirectoryChildOnly()
throws Exception
{
Verifier verifier = new Verifier( childTestDir.getAbsolutePath() );
this.executeGoal( verifier, "test" );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
HelperAssertions.assertTestSuiteResults( 1, 0, 0, 0, childTestDir );
verifyOutputDirectory( childTestDir );
}
public void testWorkingDirectoryChildOnlyNoFork()
throws Exception
{
Verifier verifier = new Verifier( childTestDir.getAbsolutePath() );
List<String> goals = this.getInitialGoals();
goals.add( "test" );
goals.add( "-DforkMode=never" );
executeGoals( verifier, goals );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
HelperAssertions.assertTestSuiteResults( 1, 0, 0, 0, childTestDir );
verifyOutputDirectory( childTestDir );
}
}
| true | true | public void verifyOutputDirectory( File childTestDir )
throws IOException
{
assertTrue( "out.txt doesn't exist: " + outFile.getAbsolutePath(), outFile.exists() );
Properties p = new Properties();
FileInputStream is = new FileInputStream( outFile );
p.load( is );
is.close();
String userDirPath = p.getProperty( "user.dir" );
assertNotNull( "user.dir was null in property file", userDirPath );
File userDir = new File( userDirPath );
// test if not a symlink
String message = "canonicalFile " + userDir.getCanonicalPath() + SystemUtils.LINE_SEPARATOR
+ " absolutePath " + userDir.getAbsolutePath() + SystemUtils.LINE_SEPARATOR
+ " path " + userDir.getPath() + SystemUtils.LINE_SEPARATOR;
if ( userDir.getCanonicalFile().equals(userDir.getAbsoluteFile()) )
{
assertEquals( "wrong user.dir ! symlink " + message, childTestDir.getAbsolutePath(), userDir.getAbsolutePath() );
}
else
{
assertEquals( "wrong user.dir symlink " + message, childTestDir.getCanonicalPath(), userDir.getCanonicalPath() );
}
}
| public void verifyOutputDirectory( File childTestDir )
throws IOException
{
assertTrue( "out.txt doesn't exist: " + outFile.getAbsolutePath(), outFile.exists() );
Properties p = new Properties();
FileInputStream is = new FileInputStream( outFile );
p.load( is );
is.close();
String userDirPath = p.getProperty( "user.dir" );
assertNotNull( "user.dir was null in property file", userDirPath );
File userDir = new File( userDirPath );
// test if not a symlink
String message = "canonicalFile " + childTestDir.getCanonicalPath() + SystemUtils.LINE_SEPARATOR
+ " absolutePath " + childTestDir.getAbsolutePath() + SystemUtils.LINE_SEPARATOR
+ " path " + childTestDir.getPath() + SystemUtils.LINE_SEPARATOR;
if ( childTestDir.getCanonicalFile().equals(childTestDir.getAbsoluteFile()) )
{
assertEquals( "wrong user.dir ! symlink " + message, childTestDir.getAbsolutePath(), userDir.getAbsolutePath() );
}
else
{
assertEquals( "wrong user.dir symlink " + message, childTestDir.getCanonicalPath(), userDir.getCanonicalPath() );
}
}
|
diff --git a/announcement-impl/impl/src/java/org/sakaiproject/announcement/impl/BaseAnnouncementService.java b/announcement-impl/impl/src/java/org/sakaiproject/announcement/impl/BaseAnnouncementService.java
index b318818..be62f65 100644
--- a/announcement-impl/impl/src/java/org/sakaiproject/announcement/impl/BaseAnnouncementService.java
+++ b/announcement-impl/impl/src/java/org/sakaiproject/announcement/impl/BaseAnnouncementService.java
@@ -1,1653 +1,1655 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 Sakai Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.announcement.impl;
import java.io.Writer;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import java.text.DateFormat;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.announcement.api.AnnouncementChannel;
import org.sakaiproject.announcement.api.AnnouncementChannelEdit;
import org.sakaiproject.announcement.api.AnnouncementMessage;
import org.sakaiproject.announcement.api.AnnouncementMessageEdit;
import org.sakaiproject.announcement.api.AnnouncementMessageHeader;
import org.sakaiproject.announcement.api.AnnouncementMessageHeaderEdit;
import org.sakaiproject.announcement.api.AnnouncementService;
import org.sakaiproject.authz.cover.FunctionManager;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.entity.api.ContextObserver;
import org.sakaiproject.entity.api.Edit;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.Summary;
import org.sakaiproject.entity.api.EntityAccessOverloadException;
import org.sakaiproject.entity.api.EntityCopyrightException;
import org.sakaiproject.entity.api.EntityNotDefinedException;
import org.sakaiproject.entity.api.EntityPermissionException;
import org.sakaiproject.entity.api.EntityTransferrer;
import org.sakaiproject.entity.api.HttpAccess;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.event.api.NotificationEdit;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.javax.Filter;
import org.sakaiproject.message.api.Message;
import org.sakaiproject.message.api.MessageChannel;
import org.sakaiproject.message.api.MessageHeader;
import org.sakaiproject.message.api.MessageHeaderEdit;
import org.sakaiproject.message.impl.BaseMessageService;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Placement;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
import org.sakaiproject.alias.api.Alias;
import org.sakaiproject.alias.cover.AliasService;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/**
* <p>
* BaseAnnouncementService extends the BaseMessageService for the specifics of Announcement.
* </p>
*/
public abstract class BaseAnnouncementService extends BaseMessageService implements AnnouncementService, ContextObserver,
EntityTransferrer
{
/** Our logger. */
private static Log M_log = LogFactory.getLog(BaseAnnouncementService.class);
/** Messages, for the http access. */
protected static ResourceLoader rb = new ResourceLoader("annc-access");
// XML DocumentBuilder and Transformer for RSS Feed
private DocumentBuilder docBuilder = null;
private Transformer docTransformer = null;
private ContentHostingService contentHostingService;
/**
* Dependency: contentHostingService.
*
* @param service
* The NotificationService.
*/
public void setContentHostingService(ContentHostingService service)
{
contentHostingService = service;
}
/**********************************************************************************************************************************************************************************************************************************************************
* Constructors, Dependencies and their setter methods
*********************************************************************************************************************************************************************************************************************************************************/
/** Dependency: NotificationService. */
protected NotificationService m_notificationService = null;
/**
* Dependency: NotificationService.
*
* @param service
* The NotificationService.
*/
public void setNotificationService(NotificationService service)
{
m_notificationService = service;
}
/**********************************************************************************************************************************************************************************************************************************************************
* Init and Destroy
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Final initialization, once all dependencies are set.
*/
public void init()
{
try
{
super.init();
// register a transient notification for announcements
NotificationEdit edit = m_notificationService.addTransientNotification();
// set functions
edit.setFunction(eventId(SECURE_ADD));
edit.addFunction(eventId(SECURE_UPDATE_OWN));
edit.addFunction(eventId(SECURE_UPDATE_ANY));
// set the filter to any announcement resource (see messageReference())
edit.setResourceFilter(getAccessPoint(true) + Entity.SEPARATOR + REF_TYPE_MESSAGE);
// set the action
edit.setAction(new SiteEmailNotificationAnnc());
// register functions
FunctionManager.registerFunction(eventId(SECURE_READ));
FunctionManager.registerFunction(eventId(SECURE_ADD));
FunctionManager.registerFunction(eventId(SECURE_REMOVE_ANY));
FunctionManager.registerFunction(eventId(SECURE_REMOVE_OWN));
FunctionManager.registerFunction(eventId(SECURE_UPDATE_ANY));
FunctionManager.registerFunction(eventId(SECURE_UPDATE_OWN));
FunctionManager.registerFunction(eventId(SECURE_ALL_GROUPS));
// Sakai v2.4: UI end says hidden, 'under the covers' says draft
// Done so import from old sites causes drafts to 'become' hidden in new sites
FunctionManager.registerFunction(eventId(SECURE_READ_DRAFT));
// entity producer registration
m_entityManager.registerEntityProducer(this, REFERENCE_ROOT);
// create DocumentBuilder for RSS Feed
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true); // ignore comments
factory.setNamespaceAware(true); // namespace aware should be true
factory.setValidating(false); // we're not validating
docBuilder = factory.newDocumentBuilder();
TransformerFactory tFactory = TransformerFactory.newInstance();
docTransformer = tFactory.newTransformer();
M_log.info("init()");
}
catch (Throwable t)
{
M_log.warn("init(): ", t);
}
} // init
/**********************************************************************************************************************************************************************************************************************************************************
* StorageUser implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Construct a new continer given just ids.
*
* @param ref
* The container reference.
* @return The new containe Resource.
*/
public Entity newContainer(String ref)
{
return new BaseAnnouncementChannelEdit(ref);
}
/**
* Construct a new container resource, from an XML element.
*
* @param element
* The XML.
* @return The new container resource.
*/
public Entity newContainer(Element element)
{
return new BaseAnnouncementChannelEdit(element);
}
/**
* Construct a new container resource, as a copy of another
*
* @param other
* The other contianer to copy.
* @return The new container resource.
*/
public Entity newContainer(Entity other)
{
return new BaseAnnouncementChannelEdit((MessageChannel) other);
}
/**
* Construct a new rsource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Entity newResource(Entity container, String id, Object[] others)
{
return new BaseAnnouncementMessageEdit((MessageChannel) container, id);
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Entity newResource(Entity container, Element element)
{
return new BaseAnnouncementMessageEdit((MessageChannel) container, element);
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Entity newResource(Entity container, Entity other)
{
return new BaseAnnouncementMessageEdit((MessageChannel) container, (Message) other);
}
/**
* Construct a new continer given just ids.
*
* @param ref
* The container reference.
* @return The new containe Resource.
*/
public Edit newContainerEdit(String ref)
{
BaseAnnouncementChannelEdit rv = new BaseAnnouncementChannelEdit(ref);
rv.activate();
return rv;
}
/**
* Construct a new container resource, from an XML element.
*
* @param element
* The XML.
* @return The new container resource.
*/
public Edit newContainerEdit(Element element)
{
BaseAnnouncementChannelEdit rv = new BaseAnnouncementChannelEdit(element);
rv.activate();
return rv;
}
/**
* Construct a new container resource, as a copy of another
*
* @param other
* The other contianer to copy.
* @return The new container resource.
*/
public Edit newContainerEdit(Entity other)
{
BaseAnnouncementChannelEdit rv = new BaseAnnouncementChannelEdit((MessageChannel) other);
rv.activate();
return rv;
}
/**
* Construct a new rsource given just an id.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param id
* The id for the new object.
* @param others
* (options) array of objects to load into the Resource's fields.
* @return The new resource.
*/
public Edit newResourceEdit(Entity container, String id, Object[] others)
{
BaseAnnouncementMessageEdit rv = new BaseAnnouncementMessageEdit((MessageChannel) container, id);
rv.activate();
return rv;
}
/**
* Construct a new resource, from an XML element.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param element
* The XML.
* @return The new resource from the XML.
*/
public Edit newResourceEdit(Entity container, Element element)
{
BaseAnnouncementMessageEdit rv = new BaseAnnouncementMessageEdit((MessageChannel) container, element);
rv.activate();
return rv;
}
/**
* Construct a new resource from another resource of the same type.
*
* @param container
* The Resource that is the container for the new resource (may be null).
* @param other
* The other resource.
* @return The new resource as a copy of the other.
*/
public Edit newResourceEdit(Entity container, Entity other)
{
BaseAnnouncementMessageEdit rv = new BaseAnnouncementMessageEdit((MessageChannel) container, (Message) other);
rv.activate();
return rv;
}
/**
* Collect the fields that need to be stored outside the XML (for the resource).
*
* @return An array of field values to store in the record outside the XML (for the resource).
*/
public Object[] storageFields(Entity r)
{
Object[] rv = new Object[4];
rv[0] = ((Message) r).getHeader().getDate();
rv[1] = ((Message) r).getHeader().getFrom().getId();
rv[2] = ((AnnouncementMessage) r).getAnnouncementHeader().getDraft() ? "1" : "0";
rv[3] = r.getProperties().getProperty(ResourceProperties.PROP_PUBVIEW) == null ? "0" : "1";
// rv[3] = ((AnnouncementMessage) r).getAnnouncementHeader().getAccess() == MessageHeader.MessageAccess.PUBLIC ? "1" : "0";
return rv;
}
/**
* Check if this resource is in draft mode.
*
* @param r
* The resource.
* @return true if the resource is in draft mode, false if not.
*/
public boolean isDraft(Entity r)
{
return ((AnnouncementMessage) r).getAnnouncementHeader().getDraft();
}
/**
* Access the resource owner user id.
*
* @param r
* The resource.
* @return The resource owner user id.
*/
public String getOwnerId(Entity r)
{
return ((Message) r).getHeader().getFrom().getId();
}
/**
* Access the resource date.
*
* @param r
* The resource.
* @return The resource date.
*/
public Time getDate(Entity r)
{
return ((Message) r).getHeader().getDate();
}
/**********************************************************************************************************************************************************************************************************************************************************
* Abstractions, etc. satisfied
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Report the Service API name being implemented.
*/
protected String serviceName()
{
return AnnouncementService.class.getName();
}
/**
* Construct a new message header from XML in a DOM element.
*
* @param id
* The message Id.
* @return The new message header.
*/
protected MessageHeaderEdit newMessageHeader(Message msg, String id)
{
return new BaseAnnouncementMessageHeaderEdit(msg, id);
} // newMessageHeader
/**
* Construct a new message header from XML in a DOM element.
*
* @param el
* The XML DOM element that has the header information.
* @return The new message header.
*/
protected MessageHeaderEdit newMessageHeader(Message msg, Element el)
{
return new BaseAnnouncementMessageHeaderEdit(msg, el);
} // newMessageHeader
/**
* Construct a new message header as a copy of another.
*
* @param other
* The other header to copy.
* @return The new message header.
*/
protected MessageHeaderEdit newMessageHeader(Message msg, MessageHeader other)
{
return new BaseAnnouncementMessageHeaderEdit(msg, other);
} // newMessageHeader
/**
* Form a tracking event string based on a security function string.
*
* @param secure
* The security function string.
* @return The event tracking string.
*/
protected String eventId(String secure)
{
return SECURE_ANNC_ROOT + secure;
} // eventId
/**
* Return the reference rooot for use in resource references and urls.
*
* @return The reference rooot for use in resource references and urls.
*/
protected String getReferenceRoot()
{
return REFERENCE_ROOT;
} // getReferenceRoot
/**
* {@inheritDoc}
*/
public boolean parseEntityReference(String reference, Reference ref)
{
if (reference.startsWith(REFERENCE_ROOT))
{
String[] parts = StringUtil.split(reference, Entity.SEPARATOR);
String id = null;
String subType = null;
String context = null;
String container = null;
// the first part will be null, then next the service, the third will be: "msg", "channel", "announcement" or "rss"
if (parts.length > 2)
{
subType = parts[2];
if (REF_TYPE_CHANNEL.equals(subType))
{
// next is the context id
if (parts.length > 3)
{
context = parts[3];
// next is the channel id
if (parts.length > 4)
{
id = parts[4];
}
}
}
else if (REF_TYPE_MESSAGE.equals(subType))
{
// next three parts are context, channel (container) and mesage id
if (parts.length > 5)
{
context = parts[3];
container = parts[4];
id = parts[5];
}
}
else if (REF_TYPE_ANNOUNCEMENT_RSS.equals(subType) || REF_TYPE_ANNOUNCEMENT.equals(subType))
{
// next is the context id
if (parts.length > 3)
context = parts[3];
}
else
M_log.warn("parse(): unknown message subtype: " + subType + " in ref: " + reference);
}
// Translate context alias into site id (only for rss) if necessary
if (REF_TYPE_ANNOUNCEMENT_RSS.equals(subType) &&(context != null) && (context.length() > 0))
{
if (!m_siteService.siteExists(context))
{
try
{
String aliasTarget = AliasService.getTarget(context);
if (aliasTarget.startsWith(REFERENCE_ROOT)) // only support announcement aliases
{
parts = StringUtil.split(aliasTarget, Entity.SEPARATOR);
if (parts.length > 3)
context = parts[3];
}
}
catch (Exception e)
{
M_log.debug(this+".parseEntityReference(): "+e.toString());
return false;
}
}
// if context still isn't valid, then no valid alias or site was specified
if (!m_siteService.siteExists(context))
{
M_log.warn(this+".parseEntityReference() no valid site or alias: " + context);
return false;
}
}
ref.set(APPLICATION_ID, subType, id, container, context);
return true;
}
return false;
}
/**
* @inheritDoc
*/
public Reference getAnnouncementReference(String context)
{
StringBuilder refString = new StringBuilder();
refString.append(getAccessPoint(true));
refString.append(Entity.SEPARATOR);
refString.append(REF_TYPE_ANNOUNCEMENT);
refString.append(Entity.SEPARATOR);
refString.append(context);
return m_entityManager.newReference( refString.toString() );
}
/**
* @inheritDoc
*/
public String getRssUrl(Reference ref)
{
String alias = null;
List aliasList = AliasService.getAliases( ref.getReference() );
if ( ! aliasList.isEmpty() )
alias = ((Alias)aliasList.get(0)).getId();
StringBuilder rssUrlString = new StringBuilder();
rssUrlString.append( m_serverConfigurationService.getAccessUrl() );
rssUrlString.append(getAccessPoint(true));
rssUrlString.append(Entity.SEPARATOR);
rssUrlString.append(REF_TYPE_ANNOUNCEMENT_RSS);
rssUrlString.append(Entity.SEPARATOR);
if ( alias != null)
rssUrlString.append(alias);
else
rssUrlString.append(ref.getContext());
return rssUrlString.toString();
}
/**
* {@inheritDoc}
*/
public boolean isMessageViewable(AnnouncementMessage message)
{
final ResourceProperties messageProps = message.getProperties();
final Time now = TimeService.newTime();
try
{
final Time releaseDate = message.getProperties().getTimeProperty(RELEASE_DATE);
if (now.before(releaseDate))
{
return false;
}
}
catch (Exception e)
{
// Just not using/set Release Date
}
try
{
final Time retractDate = message.getProperties().getTimeProperty(RETRACT_DATE);
if (now.after(retractDate))
{
return false;
}
}
catch (Exception e)
{
// Just not using/set Retract Date
}
return true;
}
/**
* {@inheritDoc}
*/
public void contextCreated(String context, boolean toolPlacement)
{
if (toolPlacement) enableMessageChannel(context);
}
/**
* {@inheritDoc}
*/
public void contextUpdated(String context, boolean toolPlacement)
{
if (toolPlacement) enableMessageChannel(context);
}
/**
* {@inheritDoc}
*/
public void contextDeleted(String context, boolean toolPlacement)
{
disableMessageChannel(context);
}
/**
* {@inheritDoc}
*/
public String[] myToolIds()
{
String[] toolIds = { "sakai.announcements" };
return toolIds;
}
/**
** Generate RSS Item element for specified assignment
**/
protected Element generateItemElement( Document doc, AnnouncementMessage msg, Reference msgRef )
{
Element item = doc.createElement("item");
Element el = doc.createElement("title");
el.appendChild(doc.createTextNode( msg.getAnnouncementHeader().getSubject() ));
item.appendChild(el);
el = doc.createElement("author");
el.appendChild(doc.createTextNode( msg.getHeader().getFrom().getEmail() ));
item.appendChild(el);
el = doc.createElement("link");
el.appendChild(doc.createTextNode( msgRef.getUrl() ));
item.appendChild(el);
el = doc.createElement("description");
el.appendChild(doc.createTextNode( msg.getBody()) );
item.appendChild(el);
el = doc.createElement("pubDate");
el.appendChild(doc.createTextNode( msg.getHeader().getDate().toStringLocalFullZ() ));
item.appendChild(el);
// attachments
List attachments = msg.getAnnouncementHeader().getAttachments();
if (attachments.size() > 0)
{
for (Iterator iAttachments = attachments.iterator(); iAttachments.hasNext();)
{
Reference attachment = (Reference) iAttachments.next();
el = doc.createElement("enclosure");
el.setAttribute("url",attachment.getUrl());
el.setAttribute("type",attachment.getType());
item.appendChild(el);
}
}
return item;
}
/**
** Print all Announcements as RSS Feed
**/
protected void printAnnouncementRss( OutputStream out, Reference rssRef )
{
try
{
Site site = m_siteService.getSite(rssRef.getContext());
Document doc = docBuilder.newDocument();
Element root = doc.createElement("rss");
root.setAttribute("version","2.0");
doc.appendChild(root);
Element channel = doc.createElement("channel");
root.appendChild(channel);
// add title
Element el = doc.createElement("title");
el.appendChild(doc.createTextNode("Announcements for "+site.getTitle()));
channel.appendChild(el);
// add description
el = doc.createElement("description");
String desc = (site.getDescription()!=null)?site.getDescription():site.getTitle();
el.appendChild(doc.createTextNode(desc));
channel.appendChild(el);
// add link
el = doc.createElement("link");
String siteUrl = m_serverConfigurationService.getPortalUrl() + site.getReference();
el.appendChild(doc.createTextNode(siteUrl));
channel.appendChild(el);
// add lastBuildDate
el = doc.createElement("lastBuildDate");
String now = DateFormat.getDateInstance(DateFormat.FULL).format( new Date() );
el.appendChild(doc.createTextNode( now ));
channel.appendChild(el);
// add generator
el = doc.createElement("generator");
el.appendChild(doc.createTextNode("Sakai Announcements RSS Generator"));
channel.appendChild(el);
// get list of public announcements
AnnouncementChannel anncChan = (AnnouncementChannel)getChannelPublic( channelReference(rssRef.getContext(), SiteService.MAIN_CONTAINER) );
List anncList = anncChan.getMessagesPublic(null,false);
for ( Iterator it=anncList.iterator(); it.hasNext(); )
{
AnnouncementMessage msg = (AnnouncementMessage)it.next();
if ( isMessageViewable(msg) )
{
Reference msgRef = m_entityManager.newReference( msg.getReference() );
Element item = generateItemElement( doc, msg, msgRef );
channel.appendChild(item);
}
}
docTransformer.transform( new DOMSource(doc), new StreamResult(out) );
}
catch (Exception e)
{
M_log.warn(this+"printAnnouncementRss ", e);
}
}
/**
** Print specified Announcement as HTML Page
**/
protected void printAnnouncementHtml( PrintWriter out, Reference ref )
throws EntityPermissionException, EntityNotDefinedException
{
try
{
// check security on the message, if not a public message (throws if not permitted)
if ( ref.getProperties().getProperty(ResourceProperties.PROP_PUBVIEW) == null ||
!ref.getProperties().getProperty(ResourceProperties.PROP_PUBVIEW).equals(Boolean.TRUE.toString()) )
{
unlock(SECURE_READ, ref.getReference());
}
AnnouncementMessage msg = (AnnouncementMessage) ref.getEntity();
AnnouncementMessageHeader hdr = (AnnouncementMessageHeader) msg.getAnnouncementHeader();
out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n"
+ "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"
+ "<style type=\"text/css\">body{margin:0px;padding:1em;font-family:Verdana,Arial,Helvetica,sans-serif;font-size:80%;}</style>\n"
+ "<title>"
+ rb.getString("announcement")
+ ": "
+ Validator.escapeHtml(hdr.getSubject())
+ "</title>" + "</head>\n<body>");
out.println("<h1>" + rb.getString("announcement") + "</h1>");
// header
out.println("<table><tr><td><b>" + rb.getString("from") + ":</b></td><td>"
+ Validator.escapeHtml(hdr.getFrom().getDisplayName()) + "</td></tr>");
out.println("<tr><td><b>" + rb.getString("date") + ":</b></td><td>" + Validator.escapeHtml(hdr.getDate().toStringLocalFull())
+ "</td></tr>");
out.println("<tr><td><b>" + rb.getString("subject") + ":</b></td><td>" + Validator.escapeHtml(hdr.getSubject()) + "</td></tr></table>");
// body
out.println("<p>" + Validator.escapeHtmlFormattedText(msg.getBody()) + "</p>");
// attachments
List attachments = hdr.getAttachments();
if (attachments.size() > 0)
{
out.println("<p><b>" + rb.getString("attachments") + ":</b></p><p>");
for (Iterator iAttachments = attachments.iterator(); iAttachments.hasNext();)
{
Reference attachment = (Reference) iAttachments.next();
out.println("<a href=\"" + Validator.escapeHtml(attachment.getUrl()) + "\">"
+ Validator.escapeHtml(attachment.getUrl()) + "</a><br />");
}
out.println("</p>");
}
out.println("</body></html>");
}
catch (PermissionException e)
{
throw new EntityPermissionException(e.getUser(), e.getLock(), e.getResource());
}
}
/**
* {@inheritDoc}
*/
public HttpAccess getHttpAccess()
{
return new HttpAccess()
{
public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref, Collection copyrightAcceptedRefs)
throws EntityPermissionException, EntityNotDefinedException //, EntityAccessOverloadException, EntityCopyrightException
{
// we only access the msg & rss reference
if ( !REF_TYPE_MESSAGE.equals(ref.getSubType()) &&
!REF_TYPE_ANNOUNCEMENT_RSS.equals(ref.getSubType()) )
throw new EntityNotDefinedException(ref.getReference());
try
{
if ( REF_TYPE_MESSAGE.equals(ref.getSubType()) )
{
res.setContentType("text/html; charset=UTF-8");
printAnnouncementHtml( res.getWriter(), ref );
}
else
{
res.setContentType("application/xml");
res.setCharacterEncoding("UTF-8");
printAnnouncementRss( res.getOutputStream(), ref );
}
}
catch ( IOException e )
{
throw new EntityNotDefinedException(ref.getReference());
}
}
};
}
/**********************************************************************************************************************************************************************************************************************************************************
* AnnouncementService implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* Return a specific announcement channel.
*
* @param ref
* The channel reference.
* @return the AnnouncementChannel that has the specified name.
* @exception IdUnusedException
* If this name is not defined for a announcement channel.
* @exception PermissionException
* If the user does not have any permissions to the channel.
*/
public AnnouncementChannel getAnnouncementChannel(String ref) throws IdUnusedException, PermissionException
{
return (AnnouncementChannel) getChannel(ref);
} // getAnnouncementChannel
/**
* Add a new announcement channel.
*
* @param ref
* The channel reference.
* @return The newly created channel.
* @exception IdUsedException
* if the id is not unique.
* @exception IdInvalidException
* if the id is not made up of valid characters.
* @exception PermissionException
* if the user does not have permission to add a channel.
*/
public AnnouncementChannelEdit addAnnouncementChannel(String ref) throws IdUsedException, IdInvalidException,
PermissionException
{
return (AnnouncementChannelEdit) addChannel(ref);
} // addAnnouncementChannel
/**********************************************************************************************************************************************************************************************************************************************************
* ResourceService implementation
*********************************************************************************************************************************************************************************************************************************************************/
/**
* {@inheritDoc}
*/
public String getLabel()
{
return "announcement";
}
/**********************************************************************************************************************************************************************************************************************************************************
* getSummaryFromHeader implementation
*********************************************************************************************************************************************************************************************************************************************************/
protected String getSummaryFromHeader(Message item, MessageHeader header)
{
String newText;
if ( header instanceof AnnouncementMessageHeader) {
AnnouncementMessageHeader hdr = (AnnouncementMessageHeader) header;
newText = hdr.getSubject();
} else {
newText = item.getBody();
if ( newText.length() > 50 ) newText = newText.substring(1,49);
}
newText = newText + ", " + header.getFrom().getDisplayName() + ", " + header.getDate().toStringLocalFull();
return newText;
}
/**
* {@inheritDoc}
*/
public void transferCopyEntities(String fromContext, String toContext, List resourceIds)
{
// get the channel associated with this site
String oChannelRef = channelReference(fromContext, SiteService.MAIN_CONTAINER);
AnnouncementChannel oChannel = null;
try
{
oChannel = (AnnouncementChannel) getChannel(oChannelRef);
// the "to" message channel
String nChannelRef = channelReference(toContext, SiteService.MAIN_CONTAINER);
AnnouncementChannel nChannel = null;
try
{
nChannel = (AnnouncementChannel) getChannel(nChannelRef);
}
catch (IdUnusedException e)
{
try
{
commitChannel(addChannel(nChannelRef));
try
{
nChannel = (AnnouncementChannel) getChannel(nChannelRef);
}
catch (Exception eee)
{
// ignore
}
}
catch (Exception ee)
{
// ignore
}
}
if (nChannel != null)
{
// pass the DOM to get new message ids, record the mapping from old to new, and adjust attachments
List oMessageList = oChannel.getMessages(null, true);
AnnouncementMessage oMessage = null;
AnnouncementMessageHeader oMessageHeader = null;
AnnouncementMessageEdit nMessage = null;
for (int i = 0; i < oMessageList.size(); i++)
{
// the "from" message
oMessage = (AnnouncementMessage) oMessageList.get(i);
String oMessageId = oMessage.getId();
boolean toBeImported = true;
if (resourceIds != null && resourceIds.size() > 0)
{
// if there is a list for import assignments, only import those assignments and relative submissions
toBeImported = false;
for (int m = 0; m < resourceIds.size() && !toBeImported; m++)
{
if (((String) resourceIds.get(m)).equals(oMessageId))
{
toBeImported = true;
}
}
}
if (toBeImported)
{
oMessageHeader = (AnnouncementMessageHeaderEdit) oMessage.getHeader();
ResourceProperties oProperties = oMessage.getProperties();
// the "to" message
nMessage = (AnnouncementMessageEdit) nChannel.addMessage();
nMessage.setBody(oMessage.getBody());
// message header
AnnouncementMessageHeaderEdit nMessageHeader = (AnnouncementMessageHeaderEdit) nMessage.getHeaderEdit();
nMessageHeader.setDate(oMessageHeader.getDate());
// when importing, refer to property to determine draft status
if ("false".equalsIgnoreCase(m_serverConfigurationService.getString("import.importAsDraft")))
{
nMessageHeader.setDraft(oMessageHeader.getDraft());
}
else
{
nMessageHeader.setDraft(true);
}
nMessageHeader.setFrom(oMessageHeader.getFrom());
nMessageHeader.setSubject(oMessageHeader.getSubject());
// attachment
List oAttachments = oMessageHeader.getAttachments();
List nAttachments = m_entityManager.newReferenceList();
for (int n = 0; n < oAttachments.size(); n++)
{
Reference oAttachmentRef = (Reference) oAttachments.get(n);
String oAttachmentId = ((Reference) oAttachments.get(n)).getId();
if (oAttachmentId.indexOf(fromContext) != -1)
{
// replace old site id with new site id in attachments
String nAttachmentId = oAttachmentId.replaceAll(fromContext, toContext);
try
{
ContentResource attachment = contentHostingService.getResource(nAttachmentId);
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
catch (IdUnusedException e)
{
try
{
ContentResource oAttachment = contentHostingService.getResource(oAttachmentId);
try
{
if (contentHostingService.isAttachmentResource(nAttachmentId))
{
// add the new resource into attachment collection area
ContentResource attachment = contentHostingService.addAttachmentResource(
Validator.escapeResourceName(oAttachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)),
- ToolManager.getCurrentPlacement().getContext(),
+ //ToolManager.getCurrentPlacement().getContext(),
+ toContext, //don't use ToolManager.getCurrentPlacement()!
ToolManager.getTool("sakai.announcements").getTitle(),
oAttachment.getContentType(),
oAttachment.getContent(),
oAttachment.getProperties());
// add to attachment list
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
else
{
// add the new resource into resource area
ContentResource attachment = contentHostingService.addResource(
Validator.escapeResourceName(oAttachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)),
- ToolManager.getCurrentPlacement().getContext(),
+ //ToolManager.getCurrentPlacement().getContext(),
+ toContext, //don't use ToolManager.getCurrentPlacement()!
1,
oAttachment.getContentType(),
oAttachment.getContent(),
oAttachment.getProperties(),
NotificationService.NOTI_NONE);
// add to attachment list
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
}
catch (Exception eeAny)
{
// if the new resource cannot be added
M_log.warn(" cannot add new attachment with id=" + nAttachmentId);
}
}
catch (Exception eAny)
{
// if cannot find the original attachment, do nothing.
M_log.warn(" cannot find the original attachment with id=" + oAttachmentId);
}
}
catch (Exception any)
{
M_log.info(any.getMessage());
}
}
else
{
nAttachments.add(oAttachmentRef);
}
}
nMessageHeader.replaceAttachments(nAttachments);
// properties
ResourcePropertiesEdit p = nMessage.getPropertiesEdit();
p.clear();
p.addAll(oProperties);
// complete the edit
nChannel.commitMessage(nMessage, NotificationService.NOTI_NONE);
}
}
} // if
transferSynopticOptions(fromContext, toContext);
}
catch (IdUnusedException e)
{
M_log.warn(" MessageChannel " + fromContext + " cannot be found. ");
}
catch (Exception any)
{
M_log.warn(".importResources(): exception in handling " + serviceName() + " : ", any);
}
}
/**********************************************************************************************************************************************************************************************************************************************************
* AnnouncementChannel implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseAnnouncementChannelEdit extends BaseMessageChannelEdit implements AnnouncementChannelEdit
{
/**
* Construct with a reference.
*
* @param ref
* The channel reference.
*/
public BaseAnnouncementChannelEdit(String ref)
{
super(ref);
} // BaseAnnouncementChannelEdit
/**
* Construct as a copy of another message.
*
* @param other
* The other message to copy.
*/
public BaseAnnouncementChannelEdit(MessageChannel other)
{
super(other);
} // BaseAnnouncementChannelEdit
/**
* Construct from a channel (and possibly messages) already defined in XML in a DOM tree. The Channel is added to storage.
*
* @param el
* The XML DOM element defining the channel.
*/
public BaseAnnouncementChannelEdit(Element el)
{
super(el);
} // BaseAnnouncementChannelEdit
/**
* Return a specific announcement channel message, as specified by message name.
*
* @param messageId
* The id of the message to get.
* @return the AnnouncementMessage that has the specified id.
* @exception IdUnusedException
* If this name is not a defined message in this announcement channel.
* @exception PermissionException
* If the user does not have any permissions to read the message.
*/
public AnnouncementMessage getAnnouncementMessage(String messageId) throws IdUnusedException, PermissionException
{
AnnouncementMessage msg = (AnnouncementMessage) getMessage(messageId);
// filter out drafts not by this user (unless this user is a super user or has access_draft ability)
if ((msg.getAnnouncementHeader()).getDraft() && (!SecurityService.isSuperUser())
&& (!msg.getHeader().getFrom().getId().equals(SessionManager.getCurrentSessionUserId()))
&& (!unlockCheck(SECURE_READ_DRAFT, msg.getReference())))
{
throw new PermissionException(SessionManager.getCurrentSessionUserId(), SECURE_READ, msg.getReference());
}
return msg;
} // getAnnouncementMessage
/**
* Return a list of all or filtered messages in the channel. The order in which the messages will be found in the iteration is by date, oldest first if ascending is true, newest first if ascending is false.
*
* @param filter
* A filtering object to accept messages, or null if no filtering is desired.
* @param ascending
* Order of messages, ascending if true, descending if false
* @return a list on channel Message objects or specializations of Message objects (may be empty).
* @exception PermissionException
* if the user does not have read permission to the channel.
*/
public List getMessages(Filter filter, boolean ascending) throws PermissionException
{
// filter out drafts this user cannot see
filter = new PrivacyFilter(filter);
return super.getMessages(filter, ascending);
} // getMessages
/**
* A (AnnouncementMessageEdit) cover for editMessage. Return a specific channel message, as specified by message name, locked for update. Must commitEdit() to make official, or cancelEdit() when done!
*
* @param messageId
* The id of the message to get.
* @return the Message that has the specified id.
* @exception IdUnusedException
* If this name is not a defined message in this channel.
* @exception PermissionException
* If the user does not have any permissions to read the message.
* @exception InUseException
* if the current user does not have permission to mess with this user.
*/
public AnnouncementMessageEdit editAnnouncementMessage(String messageId) throws IdUnusedException, PermissionException,
InUseException
{
return (AnnouncementMessageEdit) editMessage(messageId);
} // editAnnouncementMessage
/**
* A cover for removeMessage. Deletes the messages specified by the message id.
*
* @param messageId
* The id of the message to get.
* @exception PermissionException
* If the user does not have any permissions to delete the message.
*/
public void removeAnnouncementMessage(String messageId) throws PermissionException
{
removeMessage(messageId);
//return (AnnouncementMessageEdit) removeMessage(messageId);
} // editAnnouncementMessage
/**
* A (AnnouncementMessageEdit) cover for addMessage. Add a new message to this channel. Must commitEdit() to make official, or cancelEdit() when done!
*
* @return The newly added message, locked for update.
* @exception PermissionException
* If the user does not have write permission to the channel.
*/
public AnnouncementMessageEdit addAnnouncementMessage() throws PermissionException
{
return (AnnouncementMessageEdit) addMessage();
} // addAnnouncementMessage
/**
* a (AnnouncementMessage) cover for addMessage to add a new message to this channel.
*
* @param subject
* The message header subject.
* @param draft
* The message header draft indication.
* @param attachments
* The message header attachments, a vector of Reference objects.
* @param body
* The message body.
* @return The newly added message.
* @exception PermissionException
* If the user does not have write permission to the channel.
*/
public AnnouncementMessage addAnnouncementMessage(String subject, boolean draft, List attachments, String body)
throws PermissionException
{
AnnouncementMessageEdit edit = (AnnouncementMessageEdit) addMessage();
AnnouncementMessageHeaderEdit header = edit.getAnnouncementHeaderEdit();
edit.setBody(body);
header.replaceAttachments(attachments);
header.setSubject(subject);
header.setDraft(draft);
commitMessage(edit);
return edit;
} // addAnnouncementMessage
} // class BaseAnnouncementChannelEdit
/**********************************************************************************************************************************************************************************************************************************************************
* AnnouncementMessage implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseAnnouncementMessageEdit extends BaseMessageEdit implements AnnouncementMessageEdit
{
/**
* Construct.
*
* @param channel
* The channel in which this message lives.
* @param id
* The message id.
*/
public BaseAnnouncementMessageEdit(MessageChannel channel, String id)
{
super(channel, id);
} // BaseAnnouncementMessageEdit
/**
* Construct as a copy of another message.
*
* @param other
* The other message to copy.
*/
public BaseAnnouncementMessageEdit(MessageChannel channel, Message other)
{
super(channel, other);
} // BaseAnnouncementMessageEdit
/**
* Construct from an existing definition, in xml.
*
* @param channel
* The channel in which this message lives.
* @param el
* The message in XML in a DOM element.
*/
public BaseAnnouncementMessageEdit(MessageChannel channel, Element el)
{
super(channel, el);
} // BaseAnnouncementMessageEdit
/**
* Access the announcement message header.
*
* @return The announcement message header.
*/
public AnnouncementMessageHeader getAnnouncementHeader()
{
return (AnnouncementMessageHeader) getHeader();
} // getAnnouncementHeader
/**
* Access the announcement message header.
*
* @return The announcement message header.
*/
public AnnouncementMessageHeaderEdit getAnnouncementHeaderEdit()
{
return (AnnouncementMessageHeaderEdit) getHeader();
} // getAnnouncementHeaderEdit
} // class BasicAnnouncementMessageEdit
/**********************************************************************************************************************************************************************************************************************************************************
* AnnouncementMessageHeaderEdit implementation
*********************************************************************************************************************************************************************************************************************************************************/
public class BaseAnnouncementMessageHeaderEdit extends BaseMessageHeaderEdit implements AnnouncementMessageHeaderEdit
{
/** The subject for the announcement. */
protected String m_subject = null;
/**
* Construct.
*
* @param id
* The unique (within the channel) message id.
* @param from
* The User who sent the message to the channel.
* @param attachments
* The message header attachments, a vector of Reference objects.
*/
public BaseAnnouncementMessageHeaderEdit(Message msg, String id)
{
super(msg, id);
} // BaseAnnouncementMessageHeaderEdit
/**
* Construct, from an already existing XML DOM element.
*
* @param el
* The header in XML in a DOM element.
*/
public BaseAnnouncementMessageHeaderEdit(Message msg, Element el)
{
super(msg, el);
// extract the subject
m_subject = el.getAttribute("subject");
} // BaseAnnouncementMessageHeaderEdit
/**
* Construct as a copy of another header.
*
* @param other
* The other message header to copy.
*/
public BaseAnnouncementMessageHeaderEdit(Message msg, MessageHeader other)
{
super(msg, other);
m_subject = ((AnnouncementMessageHeader) other).getSubject();
} // BaseAnnouncementMessageHeaderEdit
/**
* Access the subject of the announcement.
*
* @return The subject of the announcement.
*/
public String getSubject()
{
return ((m_subject == null) ? "" : m_subject);
} // getSubject
/**
* Set the subject of the announcement.
*
* @param subject
* The subject of the announcement.
*/
public void setSubject(String subject)
{
if (StringUtil.different(subject, m_subject))
{
m_subject = subject;
}
} // setSubject
/**
* Serialize the resource into XML, adding an element to the doc under the top of the stack element.
*
* @param doc
* The DOM doc to contain the XML (or null for a string return).
* @param stack
* The DOM elements, the top of which is the containing element of the new "resource" element.
* @return The newly added element.
*/
public Element toXml(Document doc, Stack stack)
{
// get the basic work done
Element header = super.toXml(doc, stack);
// add draft, subject
header.setAttribute("subject", getSubject());
header.setAttribute("draft", new Boolean(getDraft()).toString());
return header;
} // toXml
} // BaseAnnouncementMessageHeader
/**
* A filter that will reject announcement message drafts not from the current user, and otherwise use another filter, if defined, for acceptance.
*/
protected class PrivacyFilter implements Filter
{
/** The other filter to check with. May be null. */
protected Filter m_filter = null;
/**
* Construct
*
* @param filter
* The other filter we check with.
*/
public PrivacyFilter(Filter filter)
{
m_filter = filter;
} // PrivacyFilter
/**
* Does this object satisfy the criteria of the filter?
*
* @return true if the object is accepted by the filter, false if not.
*/
public boolean accept(Object o)
{
// first if o is a announcement message that's a draft from another user, reject it
if (o instanceof AnnouncementMessage)
{
AnnouncementMessage msg = (AnnouncementMessage) o;
if ((msg.getAnnouncementHeader()).getDraft() && (!SecurityService.isSuperUser())
&& (!msg.getHeader().getFrom().getId().equals(SessionManager.getCurrentSessionUserId()))
&& (!unlockCheck(SECURE_READ_DRAFT, msg.getReference())))
{
return false;
}
}
// now, use the real filter, if present
if (m_filter != null) return m_filter.accept(o);
return true;
} // accept
} // PrivacyFilter
/* (non-Javadoc)
* @see org.sakaiproject.entity.api.EntitySummary#summarizableToolIds()
*/
public String[] summarizableToolIds()
{
return new String[] {
"sakai.announcements",
"sakai.motd"
};
}
public String getSummarizableReference(String siteId, String toolIdentifier)
{
if ( "sakai.motd".equals(toolIdentifier) ) {
return "/announcement/channel/!site/motd";
} else {
return super.getSummarizableReference(siteId, toolIdentifier);
}
}
public void transferCopyEntities(String fromContext, String toContext, List ids, boolean cleanup)
{
try
{
if(cleanup == true)
{
String channelId = ServerConfigurationService.getString("channel", null);
String toSiteId = toContext;
if (channelId == null)
{
channelId = channelReference(toSiteId, SiteService.MAIN_CONTAINER);
try
{
AnnouncementChannel aChannel = getAnnouncementChannel(channelId);
List mList = aChannel.getMessages(null, true);
for(Iterator iter = mList.iterator(); iter.hasNext();)
{
AnnouncementMessage msg = (AnnouncementMessage) iter.next();
aChannel.removeMessage(msg.getId());
}
}
catch(Exception e)
{
M_log.debug("Unable to remove Announcements " + e);
}
}
}
}
catch (Exception e)
{
M_log.debug("transferCopyEntities: End removing Announcement data");
}
transferCopyEntities(fromContext, toContext, ids);
}
}
| false | true | public void transferCopyEntities(String fromContext, String toContext, List resourceIds)
{
// get the channel associated with this site
String oChannelRef = channelReference(fromContext, SiteService.MAIN_CONTAINER);
AnnouncementChannel oChannel = null;
try
{
oChannel = (AnnouncementChannel) getChannel(oChannelRef);
// the "to" message channel
String nChannelRef = channelReference(toContext, SiteService.MAIN_CONTAINER);
AnnouncementChannel nChannel = null;
try
{
nChannel = (AnnouncementChannel) getChannel(nChannelRef);
}
catch (IdUnusedException e)
{
try
{
commitChannel(addChannel(nChannelRef));
try
{
nChannel = (AnnouncementChannel) getChannel(nChannelRef);
}
catch (Exception eee)
{
// ignore
}
}
catch (Exception ee)
{
// ignore
}
}
if (nChannel != null)
{
// pass the DOM to get new message ids, record the mapping from old to new, and adjust attachments
List oMessageList = oChannel.getMessages(null, true);
AnnouncementMessage oMessage = null;
AnnouncementMessageHeader oMessageHeader = null;
AnnouncementMessageEdit nMessage = null;
for (int i = 0; i < oMessageList.size(); i++)
{
// the "from" message
oMessage = (AnnouncementMessage) oMessageList.get(i);
String oMessageId = oMessage.getId();
boolean toBeImported = true;
if (resourceIds != null && resourceIds.size() > 0)
{
// if there is a list for import assignments, only import those assignments and relative submissions
toBeImported = false;
for (int m = 0; m < resourceIds.size() && !toBeImported; m++)
{
if (((String) resourceIds.get(m)).equals(oMessageId))
{
toBeImported = true;
}
}
}
if (toBeImported)
{
oMessageHeader = (AnnouncementMessageHeaderEdit) oMessage.getHeader();
ResourceProperties oProperties = oMessage.getProperties();
// the "to" message
nMessage = (AnnouncementMessageEdit) nChannel.addMessage();
nMessage.setBody(oMessage.getBody());
// message header
AnnouncementMessageHeaderEdit nMessageHeader = (AnnouncementMessageHeaderEdit) nMessage.getHeaderEdit();
nMessageHeader.setDate(oMessageHeader.getDate());
// when importing, refer to property to determine draft status
if ("false".equalsIgnoreCase(m_serverConfigurationService.getString("import.importAsDraft")))
{
nMessageHeader.setDraft(oMessageHeader.getDraft());
}
else
{
nMessageHeader.setDraft(true);
}
nMessageHeader.setFrom(oMessageHeader.getFrom());
nMessageHeader.setSubject(oMessageHeader.getSubject());
// attachment
List oAttachments = oMessageHeader.getAttachments();
List nAttachments = m_entityManager.newReferenceList();
for (int n = 0; n < oAttachments.size(); n++)
{
Reference oAttachmentRef = (Reference) oAttachments.get(n);
String oAttachmentId = ((Reference) oAttachments.get(n)).getId();
if (oAttachmentId.indexOf(fromContext) != -1)
{
// replace old site id with new site id in attachments
String nAttachmentId = oAttachmentId.replaceAll(fromContext, toContext);
try
{
ContentResource attachment = contentHostingService.getResource(nAttachmentId);
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
catch (IdUnusedException e)
{
try
{
ContentResource oAttachment = contentHostingService.getResource(oAttachmentId);
try
{
if (contentHostingService.isAttachmentResource(nAttachmentId))
{
// add the new resource into attachment collection area
ContentResource attachment = contentHostingService.addAttachmentResource(
Validator.escapeResourceName(oAttachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)),
ToolManager.getCurrentPlacement().getContext(),
ToolManager.getTool("sakai.announcements").getTitle(),
oAttachment.getContentType(),
oAttachment.getContent(),
oAttachment.getProperties());
// add to attachment list
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
else
{
// add the new resource into resource area
ContentResource attachment = contentHostingService.addResource(
Validator.escapeResourceName(oAttachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)),
ToolManager.getCurrentPlacement().getContext(),
1,
oAttachment.getContentType(),
oAttachment.getContent(),
oAttachment.getProperties(),
NotificationService.NOTI_NONE);
// add to attachment list
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
}
catch (Exception eeAny)
{
// if the new resource cannot be added
M_log.warn(" cannot add new attachment with id=" + nAttachmentId);
}
}
catch (Exception eAny)
{
// if cannot find the original attachment, do nothing.
M_log.warn(" cannot find the original attachment with id=" + oAttachmentId);
}
}
catch (Exception any)
{
M_log.info(any.getMessage());
}
}
else
{
nAttachments.add(oAttachmentRef);
}
}
nMessageHeader.replaceAttachments(nAttachments);
// properties
ResourcePropertiesEdit p = nMessage.getPropertiesEdit();
p.clear();
p.addAll(oProperties);
// complete the edit
nChannel.commitMessage(nMessage, NotificationService.NOTI_NONE);
}
}
} // if
transferSynopticOptions(fromContext, toContext);
}
catch (IdUnusedException e)
{
M_log.warn(" MessageChannel " + fromContext + " cannot be found. ");
}
catch (Exception any)
{
M_log.warn(".importResources(): exception in handling " + serviceName() + " : ", any);
}
}
| public void transferCopyEntities(String fromContext, String toContext, List resourceIds)
{
// get the channel associated with this site
String oChannelRef = channelReference(fromContext, SiteService.MAIN_CONTAINER);
AnnouncementChannel oChannel = null;
try
{
oChannel = (AnnouncementChannel) getChannel(oChannelRef);
// the "to" message channel
String nChannelRef = channelReference(toContext, SiteService.MAIN_CONTAINER);
AnnouncementChannel nChannel = null;
try
{
nChannel = (AnnouncementChannel) getChannel(nChannelRef);
}
catch (IdUnusedException e)
{
try
{
commitChannel(addChannel(nChannelRef));
try
{
nChannel = (AnnouncementChannel) getChannel(nChannelRef);
}
catch (Exception eee)
{
// ignore
}
}
catch (Exception ee)
{
// ignore
}
}
if (nChannel != null)
{
// pass the DOM to get new message ids, record the mapping from old to new, and adjust attachments
List oMessageList = oChannel.getMessages(null, true);
AnnouncementMessage oMessage = null;
AnnouncementMessageHeader oMessageHeader = null;
AnnouncementMessageEdit nMessage = null;
for (int i = 0; i < oMessageList.size(); i++)
{
// the "from" message
oMessage = (AnnouncementMessage) oMessageList.get(i);
String oMessageId = oMessage.getId();
boolean toBeImported = true;
if (resourceIds != null && resourceIds.size() > 0)
{
// if there is a list for import assignments, only import those assignments and relative submissions
toBeImported = false;
for (int m = 0; m < resourceIds.size() && !toBeImported; m++)
{
if (((String) resourceIds.get(m)).equals(oMessageId))
{
toBeImported = true;
}
}
}
if (toBeImported)
{
oMessageHeader = (AnnouncementMessageHeaderEdit) oMessage.getHeader();
ResourceProperties oProperties = oMessage.getProperties();
// the "to" message
nMessage = (AnnouncementMessageEdit) nChannel.addMessage();
nMessage.setBody(oMessage.getBody());
// message header
AnnouncementMessageHeaderEdit nMessageHeader = (AnnouncementMessageHeaderEdit) nMessage.getHeaderEdit();
nMessageHeader.setDate(oMessageHeader.getDate());
// when importing, refer to property to determine draft status
if ("false".equalsIgnoreCase(m_serverConfigurationService.getString("import.importAsDraft")))
{
nMessageHeader.setDraft(oMessageHeader.getDraft());
}
else
{
nMessageHeader.setDraft(true);
}
nMessageHeader.setFrom(oMessageHeader.getFrom());
nMessageHeader.setSubject(oMessageHeader.getSubject());
// attachment
List oAttachments = oMessageHeader.getAttachments();
List nAttachments = m_entityManager.newReferenceList();
for (int n = 0; n < oAttachments.size(); n++)
{
Reference oAttachmentRef = (Reference) oAttachments.get(n);
String oAttachmentId = ((Reference) oAttachments.get(n)).getId();
if (oAttachmentId.indexOf(fromContext) != -1)
{
// replace old site id with new site id in attachments
String nAttachmentId = oAttachmentId.replaceAll(fromContext, toContext);
try
{
ContentResource attachment = contentHostingService.getResource(nAttachmentId);
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
catch (IdUnusedException e)
{
try
{
ContentResource oAttachment = contentHostingService.getResource(oAttachmentId);
try
{
if (contentHostingService.isAttachmentResource(nAttachmentId))
{
// add the new resource into attachment collection area
ContentResource attachment = contentHostingService.addAttachmentResource(
Validator.escapeResourceName(oAttachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)),
//ToolManager.getCurrentPlacement().getContext(),
toContext, //don't use ToolManager.getCurrentPlacement()!
ToolManager.getTool("sakai.announcements").getTitle(),
oAttachment.getContentType(),
oAttachment.getContent(),
oAttachment.getProperties());
// add to attachment list
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
else
{
// add the new resource into resource area
ContentResource attachment = contentHostingService.addResource(
Validator.escapeResourceName(oAttachment.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME)),
//ToolManager.getCurrentPlacement().getContext(),
toContext, //don't use ToolManager.getCurrentPlacement()!
1,
oAttachment.getContentType(),
oAttachment.getContent(),
oAttachment.getProperties(),
NotificationService.NOTI_NONE);
// add to attachment list
nAttachments.add(m_entityManager.newReference(attachment.getReference()));
}
}
catch (Exception eeAny)
{
// if the new resource cannot be added
M_log.warn(" cannot add new attachment with id=" + nAttachmentId);
}
}
catch (Exception eAny)
{
// if cannot find the original attachment, do nothing.
M_log.warn(" cannot find the original attachment with id=" + oAttachmentId);
}
}
catch (Exception any)
{
M_log.info(any.getMessage());
}
}
else
{
nAttachments.add(oAttachmentRef);
}
}
nMessageHeader.replaceAttachments(nAttachments);
// properties
ResourcePropertiesEdit p = nMessage.getPropertiesEdit();
p.clear();
p.addAll(oProperties);
// complete the edit
nChannel.commitMessage(nMessage, NotificationService.NOTI_NONE);
}
}
} // if
transferSynopticOptions(fromContext, toContext);
}
catch (IdUnusedException e)
{
M_log.warn(" MessageChannel " + fromContext + " cannot be found. ");
}
catch (Exception any)
{
M_log.warn(".importResources(): exception in handling " + serviceName() + " : ", any);
}
}
|
diff --git a/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/environment/DynamicModulesURIConverter.java b/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/environment/DynamicModulesURIConverter.java
index 297f34ee..f9109d95 100644
--- a/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/environment/DynamicModulesURIConverter.java
+++ b/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/environment/DynamicModulesURIConverter.java
@@ -1,428 +1,430 @@
/*******************************************************************************
* Copyright (c) 2010, 2011 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.acceleo.engine.internal.environment;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.acceleo.common.IAcceleoConstants;
import org.eclipse.acceleo.common.internal.utils.workspace.AcceleoWorkspaceUtil;
import org.eclipse.acceleo.common.internal.utils.workspace.BundleURLConverter;
import org.eclipse.acceleo.common.utils.CompactLinkedHashSet;
import org.eclipse.acceleo.model.mtl.Module;
import org.eclipse.emf.common.EMFPlugin;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.ContentHandler;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.URIConverter;
import org.eclipse.emf.ecore.resource.URIHandler;
import org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl;
/**
* This will allow us to handle references to file scheme URIs within the resource set containing the
* generation modules and their dynamic overrides. We need this since the dynamic overrides are loaded with
* file scheme URIs whereas the generation module can be loaded through platform scheme URIs and we need
* references to be resolved anyway.
*
* @author <a href="mailto:[email protected]">Laurent Goubet</a>
*/
final class DynamicModulesURIConverter extends ExtensibleURIConverterImpl {
/** The parent URIConverted if any. */
private URIConverter parent;
/** This will be initialized with the environment that asked for the construction of a converter. */
private final AcceleoEvaluationEnvironment parentEnvironment;
/**
* This is only meant to be instantiated once for each generation, from the
* {@link AcceleoEvaluationEnvironment} only.
*
* @param parent
* The parent URIConverter. Can be <code>null</code>.
* @param parentEnvironment
* Environment that asked for this URI converter instance.
*/
DynamicModulesURIConverter(URIConverter parent, AcceleoEvaluationEnvironment parentEnvironment) {
this.parent = parent;
this.parentEnvironment = parentEnvironment;
}
/**
* {@inheritDoc}
*
* @see ExtensibleURIConverterImpl#normalize(URI)
*/
@Override
public URI normalize(URI uri) {
URI normalized = normalizeWithParent(uri);
if (normalized == null || normalized.equals(uri)) {
normalized = dynamicNormalize(uri);
}
return normalized;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#getURIMap()
*/
@Override
public Map<URI, URI> getURIMap() {
if (parent != null) {
return parent.getURIMap();
}
return super.getURIMap();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#getURIHandlers()
*/
@Override
public EList<URIHandler> getURIHandlers() {
if (parent != null) {
return parent.getURIHandlers();
}
return super.getURIHandlers();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#getURIHandler(org.eclipse.emf.common.util.URI)
*/
@Override
public URIHandler getURIHandler(URI uri) {
if (parent != null) {
return parent.getURIHandler(uri);
}
return super.getURIHandler(uri);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#getContentHandlers()
*/
@Override
public EList<ContentHandler> getContentHandlers() {
if (parent != null) {
return parent.getContentHandlers();
}
return super.getContentHandlers();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#createInputStream(org.eclipse.emf.common.util.URI)
*/
@Override
public InputStream createInputStream(URI uri) throws IOException {
if (parent != null) {
return parent.createInputStream(uri);
}
return super.createInputStream(uri);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#createInputStream(org.eclipse.emf.common.util.URI,
* java.util.Map)
*/
@Override
public InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException {
if (parent != null) {
return parent.createInputStream(uri, options);
}
return super.createInputStream(uri, options);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#createOutputStream(org.eclipse.emf.common.util.URI)
*/
@Override
public OutputStream createOutputStream(URI uri) throws IOException {
if (parent != null) {
return parent.createOutputStream(uri);
}
return super.createOutputStream(uri);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#createOutputStream(org.eclipse.emf.common.util.URI,
* java.util.Map)
*/
@Override
public OutputStream createOutputStream(URI uri, Map<?, ?> options) throws IOException {
if (parent != null) {
return parent.createOutputStream(uri, options);
}
return super.createOutputStream(uri, options);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#delete(org.eclipse.emf.common.util.URI,
* java.util.Map)
*/
@Override
public void delete(URI uri, Map<?, ?> options) throws IOException {
if (parent != null) {
parent.delete(uri, options);
}
super.delete(uri, options);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#contentDescription(org.eclipse.emf.common.util.URI,
* java.util.Map)
*/
@Override
public Map<String, ?> contentDescription(URI uri, Map<?, ?> options) throws IOException {
if (parent != null) {
return parent.contentDescription(uri, options);
}
return super.contentDescription(uri, options);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#exists(org.eclipse.emf.common.util.URI,
* java.util.Map)
*/
@Override
public boolean exists(URI uri, Map<?, ?> options) {
if (parent != null) {
return parent.exists(uri, options);
}
return super.exists(uri, options);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#getAttributes(org.eclipse.emf.common.util.URI,
* java.util.Map)
*/
@Override
public Map<String, ?> getAttributes(URI uri, Map<?, ?> options) {
if (parent != null) {
return parent.getAttributes(uri, options);
}
return super.getAttributes(uri, options);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#setAttributes(org.eclipse.emf.common.util.URI,
* java.util.Map, java.util.Map)
*/
@Override
public void setAttributes(URI uri, Map<String, ?> attributes, Map<?, ?> options) throws IOException {
if (parent != null) {
parent.setAttributes(uri, attributes, options);
}
super.setAttributes(uri, attributes, options);
}
/**
* Normalizes the given URI using the parent environment.
*
* @param uri
* The uri we are to normalize.
* @return The normalized form of <code>uri</code>.
*/
private URI normalizeWithParent(URI uri) {
if (parent != null) {
return parent.normalize(uri);
}
return uri;
}
/**
* This will be called if the parent {@link URIConverter} didn't know how to convert the given URI.
*
* @param uri
* The uri we are to normalize.
* @return The normalized form of <code>uri</code>.
*/
private URI dynamicNormalize(URI uri) {
URI normalized = getURIMap().get(uri);
if (normalized == null) {
BundleURLConverter conv = new BundleURLConverter(uri.toString());
if (conv.resolveBundle() != null) {
normalized = URI.createURI(conv.resolveAsPlatformPlugin());
}
}
if (normalized == null
&& (!IAcceleoConstants.EMTL_FILE_EXTENSION.equals(uri.fileExtension()) || !"file".equals(uri.scheme()))) { //$NON-NLS-1$
normalized = super.normalize(uri);
}
if (normalized != null) {
getURIMap().put(uri, normalized);
return normalized;
}
String moduleName = uri.lastSegment();
moduleName = moduleName.substring(0, moduleName.lastIndexOf('.'));
Set<URI> candidateURIs = new CompactLinkedHashSet<URI>();
// Search matching module in the current generation context
Set<Module> candidateModules = searchCurrentModuleForCandidateMatches(moduleName);
for (Module candidateModule : candidateModules) {
- candidateURIs.add(candidateModule.eResource().getURI());
+ if (candidateModule.eResource() != null) {
+ candidateURIs.add(candidateModule.eResource().getURI());
+ }
}
// If there were no matching module, search in their ResourceSet(s)
if (candidateURIs.size() == 0) {
candidateURIs.addAll(searchResourceSetForMatches(moduleName));
}
if (candidateURIs.size() == 1) {
normalized = candidateURIs.iterator().next();
} else if (candidateURIs.size() > 0) {
normalized = findBestMatchFor(uri, candidateURIs);
}
// There is a chance that our match should itself be normalized
if ((normalized == null || "file".equals(normalized.scheme())) //$NON-NLS-1$
&& EMFPlugin.IS_ECLIPSE_RUNNING) {
BundleURLConverter conv = new BundleURLConverter(uri.toString());
if (conv.resolveBundle() != null) {
normalized = URI.createURI(conv.resolveAsPlatformPlugin());
} else {
String uriToString = uri.toString();
if (uriToString.indexOf('#') > 0) {
uriToString = uriToString.substring(0, uriToString.indexOf('#'));
}
String resolvedPath = AcceleoWorkspaceUtil.resolveInBundles(uriToString);
if (resolvedPath != null) {
normalized = URI.createURI(resolvedPath);
}
}
}
if (normalized == null) {
normalized = super.normalize(uri);
}
if (!uri.equals(normalized)) {
getURIMap().put(uri, normalized);
}
return normalized;
}
/**
* Returns the normalized form of the URI, using the given multiple candidates (this means that more than
* 2 modules had a matching name).
*
* @param uri
* The URI that is to be normalized.
* @param candidateURIs
* URIs of the modules that can potentially be a match for <code>uri</code>.
* @return the normalized form
*/
private URI findBestMatchFor(URI uri, Set<URI> candidateURIs) {
URI normalized = null;
final Iterator<URI> candidatesIterator = candidateURIs.iterator();
final List<String> referenceSegments = Arrays.asList(uri.segments());
Collections.reverse(referenceSegments);
int highestEqualFragments = 0;
while (candidatesIterator.hasNext()) {
final URI next = candidatesIterator.next();
int equalFragments = 0;
final List<String> candidateSegments = Arrays.asList(next.segments());
Collections.reverse(candidateSegments);
for (int i = 0; i < Math.min(candidateSegments.size(), referenceSegments.size()); i++) {
if (candidateSegments.get(i) == referenceSegments.get(i)) {
equalFragments++;
} else {
break;
}
}
if (equalFragments > highestEqualFragments) {
highestEqualFragments = equalFragments;
normalized = next;
}
}
return normalized;
}
/**
* This will search the current generation context for a loaded module matching the given
* <code>moduleName</code>.
*
* @param moduleName
* Name of the module we seek.
* @return The Set of all modules currently loaded for generation going by the name
* <code>moduleName</code>.
*/
private Set<Module> searchCurrentModuleForCandidateMatches(String moduleName) {
Set<Module> candidates = new CompactLinkedHashSet<Module>();
for (Module module : parentEnvironment.getCurrentModules()) {
if (moduleName.equals(module.getName())) {
candidates.add(module);
}
}
return candidates;
}
/**
* This will search throughout the resourceSet(s) containing the loaded modules for modules going by name
* <code>moduleName</code>.
*
* @param moduleName
* Name of the module we seek.
* @return The Set of all modules loaded within the generation ResourceSet going by the name
* <code>moduleName</code>.
*/
private Set<URI> searchResourceSetForMatches(String moduleName) {
final Set<URI> candidates = new CompactLinkedHashSet<URI>();
final List<ResourceSet> resourceSets = new ArrayList<ResourceSet>();
for (Module module : parentEnvironment.getCurrentModules()) {
if (module != null && module.eResource() != null) {
final ResourceSet resourceSet = module.eResource().getResourceSet();
if (!resourceSets.contains(resourceSet)) {
resourceSets.add(resourceSet);
}
}
}
for (ResourceSet resourceSet : resourceSets) {
for (Resource resource : resourceSet.getResources()) {
if (IAcceleoConstants.EMTL_FILE_EXTENSION.equals(resource.getURI().fileExtension())) {
String candidateName = resource.getURI().lastSegment();
candidateName = candidateName.substring(0, candidateName.lastIndexOf('.'));
if (moduleName.equals(candidateName)) {
candidates.add(resource.getURI());
}
}
}
}
return candidates;
}
}
| true | true | private URI dynamicNormalize(URI uri) {
URI normalized = getURIMap().get(uri);
if (normalized == null) {
BundleURLConverter conv = new BundleURLConverter(uri.toString());
if (conv.resolveBundle() != null) {
normalized = URI.createURI(conv.resolveAsPlatformPlugin());
}
}
if (normalized == null
&& (!IAcceleoConstants.EMTL_FILE_EXTENSION.equals(uri.fileExtension()) || !"file".equals(uri.scheme()))) { //$NON-NLS-1$
normalized = super.normalize(uri);
}
if (normalized != null) {
getURIMap().put(uri, normalized);
return normalized;
}
String moduleName = uri.lastSegment();
moduleName = moduleName.substring(0, moduleName.lastIndexOf('.'));
Set<URI> candidateURIs = new CompactLinkedHashSet<URI>();
// Search matching module in the current generation context
Set<Module> candidateModules = searchCurrentModuleForCandidateMatches(moduleName);
for (Module candidateModule : candidateModules) {
candidateURIs.add(candidateModule.eResource().getURI());
}
// If there were no matching module, search in their ResourceSet(s)
if (candidateURIs.size() == 0) {
candidateURIs.addAll(searchResourceSetForMatches(moduleName));
}
if (candidateURIs.size() == 1) {
normalized = candidateURIs.iterator().next();
} else if (candidateURIs.size() > 0) {
normalized = findBestMatchFor(uri, candidateURIs);
}
// There is a chance that our match should itself be normalized
if ((normalized == null || "file".equals(normalized.scheme())) //$NON-NLS-1$
&& EMFPlugin.IS_ECLIPSE_RUNNING) {
BundleURLConverter conv = new BundleURLConverter(uri.toString());
if (conv.resolveBundle() != null) {
normalized = URI.createURI(conv.resolveAsPlatformPlugin());
} else {
String uriToString = uri.toString();
if (uriToString.indexOf('#') > 0) {
uriToString = uriToString.substring(0, uriToString.indexOf('#'));
}
String resolvedPath = AcceleoWorkspaceUtil.resolveInBundles(uriToString);
if (resolvedPath != null) {
normalized = URI.createURI(resolvedPath);
}
}
}
if (normalized == null) {
normalized = super.normalize(uri);
}
if (!uri.equals(normalized)) {
getURIMap().put(uri, normalized);
}
return normalized;
}
| private URI dynamicNormalize(URI uri) {
URI normalized = getURIMap().get(uri);
if (normalized == null) {
BundleURLConverter conv = new BundleURLConverter(uri.toString());
if (conv.resolveBundle() != null) {
normalized = URI.createURI(conv.resolveAsPlatformPlugin());
}
}
if (normalized == null
&& (!IAcceleoConstants.EMTL_FILE_EXTENSION.equals(uri.fileExtension()) || !"file".equals(uri.scheme()))) { //$NON-NLS-1$
normalized = super.normalize(uri);
}
if (normalized != null) {
getURIMap().put(uri, normalized);
return normalized;
}
String moduleName = uri.lastSegment();
moduleName = moduleName.substring(0, moduleName.lastIndexOf('.'));
Set<URI> candidateURIs = new CompactLinkedHashSet<URI>();
// Search matching module in the current generation context
Set<Module> candidateModules = searchCurrentModuleForCandidateMatches(moduleName);
for (Module candidateModule : candidateModules) {
if (candidateModule.eResource() != null) {
candidateURIs.add(candidateModule.eResource().getURI());
}
}
// If there were no matching module, search in their ResourceSet(s)
if (candidateURIs.size() == 0) {
candidateURIs.addAll(searchResourceSetForMatches(moduleName));
}
if (candidateURIs.size() == 1) {
normalized = candidateURIs.iterator().next();
} else if (candidateURIs.size() > 0) {
normalized = findBestMatchFor(uri, candidateURIs);
}
// There is a chance that our match should itself be normalized
if ((normalized == null || "file".equals(normalized.scheme())) //$NON-NLS-1$
&& EMFPlugin.IS_ECLIPSE_RUNNING) {
BundleURLConverter conv = new BundleURLConverter(uri.toString());
if (conv.resolveBundle() != null) {
normalized = URI.createURI(conv.resolveAsPlatformPlugin());
} else {
String uriToString = uri.toString();
if (uriToString.indexOf('#') > 0) {
uriToString = uriToString.substring(0, uriToString.indexOf('#'));
}
String resolvedPath = AcceleoWorkspaceUtil.resolveInBundles(uriToString);
if (resolvedPath != null) {
normalized = URI.createURI(resolvedPath);
}
}
}
if (normalized == null) {
normalized = super.normalize(uri);
}
if (!uri.equals(normalized)) {
getURIMap().put(uri, normalized);
}
return normalized;
}
|
diff --git a/src/org/opensolaris/opengrok/configuration/Configuration.java b/src/org/opensolaris/opengrok/configuration/Configuration.java
index bda5ea3..68a7224 100644
--- a/src/org/opensolaris/opengrok/configuration/Configuration.java
+++ b/src/org/opensolaris/opengrok/configuration/Configuration.java
@@ -1,662 +1,662 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
*/
package org.opensolaris.opengrok.configuration;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.logging.Logger;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.opensolaris.opengrok.history.RepositoryInfo;
import org.opensolaris.opengrok.index.Filter;
import org.opensolaris.opengrok.index.IgnoredNames;
import org.opensolaris.opengrok.util.IOUtils;
/**
* Placeholder class for all configuration variables. Due to the multithreaded
* nature of the web application, each thread will use the same instance of the
* configuration object for each page request. Class and methods should have
* package scope, but that didn't work with the XMLDecoder/XMLEncoder.
*/
public final class Configuration {
private String ctags;
/** Should the history log be cached? */
private boolean historyCache;
/**
* The maximum time in milliseconds {@code HistoryCache.get()} can take
* before its result is cached.
*/
private int historyCacheTime;
/** Should the history cache be stored in a database? */
private boolean historyCacheInDB;
private List<Project> projects;
private String sourceRoot;
private String dataRoot;
private List<RepositoryInfo> repositories;
private String urlPrefix;
private boolean generateHtml;
/** Default project will be used, when no project is selected and no project is in cookie, so basically only the first time you open the first page, or when you clear your web cookies */
private Project defaultProject;
private int indexWordLimit;
private boolean verbose;
//if below is set, then we count how many files per project we need to process and print percentage of completion per project
private boolean printProgress;
private boolean allowLeadingWildcard;
private IgnoredNames ignoredNames;
private Filter includedNames;
private String userPage;
private String userPageSuffix;
private String bugPage;
private String bugPattern;
private String reviewPage;
private String reviewPattern;
private String webappLAF;
private boolean remoteScmSupported;
private boolean optimizeDatabase;
private boolean useLuceneLocking;
private boolean compressXref;
private boolean indexVersionedFilesOnly;
private int hitsPerPage;
private int cachePages;
private String databaseDriver;
private String databaseUrl;
private int scanningDepth;
private Set<String> allowedSymlinks;
private boolean obfuscatingEMailAddresses;
private boolean chattyStatusPage;
private final Map<String,String> cmds;
private int tabSize;
private static final Logger logger = Logger.getLogger("org.opensolaris.opengrok");
/**
* Get the default tab size (number of space characters per tab character)
* to use for each project. If {@code <= 0} tabs are read/write as is.
* @return current tab size set.
* @see Project#getTabSize()
* @see org.opensolaris.opengrok.analysis.ExpandTabsReader
*/
public int getTabSize() {
return tabSize;
}
/**
* Set the default tab size (number of space characters per tab character)
* to use for each project. If {@code <= 0} tabs are read/write as is.
* @param tabSize tabsize to set.
* @see Project#setTabSize(int)
* @see org.opensolaris.opengrok.analysis.ExpandTabsReader
*/
public void setTabSize(int tabSize) {
this.tabSize = tabSize;
}
public int getScanningDepth() {
return scanningDepth;
}
public void setScanningDepth(int scanningDepth) {
this.scanningDepth = scanningDepth;
}
/** Creates a new instance of Configuration */
public Configuration() {
//defaults for an opengrok instance configuration
setHistoryCache(true);
setHistoryCacheTime(30);
setHistoryCacheInDB(false);
setProjects(new ArrayList<Project>());
setRepositories(new ArrayList<RepositoryInfo>());
setUrlPrefix("/source/s?");
//setUrlPrefix("../s?"); // TODO generate relative search paths, get rid of -w <webapp> option to indexer !
setCtags(System.getProperty("org.opensolaris.opengrok.analysis.Ctags", "ctags"));
//below can cause an outofmemory error, since it is defaulting to NO LIMIT
setIndexWordLimit(Integer.MAX_VALUE);
setVerbose(false);
setPrintProgress(false);
setGenerateHtml(true);
setQuickContextScan(true);
setIgnoredNames(new IgnoredNames());
setIncludedNames(new Filter());
setUserPage("http://www.opensolaris.org/viewProfile.jspa?username=");
setBugPage("http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=");
setBugPattern("\\b([12456789][0-9]{6})\\b");
setReviewPage("http://arc.opensolaris.org/caselog/PSARC/");
setReviewPattern("\\b(\\d{4}/\\d{3})\\b"); // in form e.g. PSARC 2008/305
setWebappLAF("default");
setRemoteScmSupported(false);
setOptimizeDatabase(true);
setUsingLuceneLocking(false);
setCompressXref(true);
setIndexVersionedFilesOnly(false);
setHitsPerPage(25);
setCachePages(5);
setScanningDepth(3); // default depth of scanning for repositories
setAllowedSymlinks(new HashSet<String>());
- setTabSize(4);
+ //setTabSize(4);
cmds = new HashMap<String, String>();
}
public String getRepoCmd(String clazzName) {
return cmds.get(clazzName);
}
public String setRepoCmd(String clazzName, String cmd) {
if (clazzName == null) {
return null;
}
if (cmd == null || cmd.length() == 0) {
return cmds.remove(clazzName);
}
return cmds.put(clazzName, cmd);
}
// just to satisfy bean/de|encoder stuff
public Map<String, String> getCmds() {
return Collections.unmodifiableMap(cmds);
}
public void setCmds(Map<String, String> cmds) {
this.cmds.clear();
this.cmds.putAll(cmds);
}
public String getCtags() {
return ctags;
}
public void setCtags(String ctags) {
this.ctags = ctags;
}
public int getCachePages() {
return cachePages;
}
public void setCachePages(int cachePages) {
this.cachePages = cachePages;
}
public int getHitsPerPage() {
return hitsPerPage;
}
public void setHitsPerPage(int hitsPerPage) {
this.hitsPerPage = hitsPerPage;
}
/**
* Should the history log be cached?
* @return {@code true} if a {@code HistoryCache} implementation should
* be used, {@code false} otherwise
*/
public boolean isHistoryCache() {
return historyCache;
}
/**
* Set whether history should be cached.
* @param historyCache if {@code true} enable history cache
*/
public void setHistoryCache(boolean historyCache) {
this.historyCache = historyCache;
}
/**
* How long can a history request take before it's cached? If the time
* is exceeded, the result is cached. This setting only affects
* {@code FileHistoryCache}.
*
* @return the maximum time in milliseconds a history request can take
* before it's cached
*/
public int getHistoryCacheTime() {
return historyCacheTime;
}
/**
* Set the maximum time a history request can take before it's cached.
* This setting is only respected if {@code FileHistoryCache} is used.
*
* @param historyCacheTime maximum time in milliseconds
*/
public void setHistoryCacheTime(int historyCacheTime) {
this.historyCacheTime = historyCacheTime;
}
/**
* Should the history cache be stored in a database? If yes,
* {@code JDBCHistoryCache} will be used to cache the history; otherwise,
* {@code FileHistoryCache} is used.
*
* @return whether the history cache should be stored in a database
*/
public boolean isHistoryCacheInDB() {
return historyCacheInDB;
}
/**
* Set whether the history cache should be stored in a database, and
* {@code JDBCHistoryCache} should be used instead of {@code
* FileHistoryCache}.
*
* @param historyCacheInDB whether the history cached should be stored in
* a database
*/
public void setHistoryCacheInDB(boolean historyCacheInDB) {
this.historyCacheInDB = historyCacheInDB;
}
public List<Project> getProjects() {
return projects;
}
public void setProjects(List<Project> projects) {
this.projects = projects;
}
public String getSourceRoot() {
return sourceRoot;
}
public void setSourceRoot(String sourceRoot) {
this.sourceRoot = sourceRoot;
}
public String getDataRoot() {
return dataRoot;
}
public void setDataRoot(String dataRoot) {
this.dataRoot = dataRoot;
}
public List<RepositoryInfo> getRepositories() {
return repositories;
}
public void setRepositories(List<RepositoryInfo> repositories) {
this.repositories = repositories;
}
public String getUrlPrefix() {
return urlPrefix;
}
/**
* Set the URL prefix to be used by the {@link
* org.opensolaris.opengrok.analysis.executables.JavaClassAnalyzer} as well
* as lexers (see {@link org.opensolaris.opengrok.analysis.JFlexXref})
* when they create output with html links.
* @param urlPrefix prefix to use.
*/
public void setUrlPrefix(String urlPrefix) {
this.urlPrefix = urlPrefix;
}
public void setGenerateHtml(boolean generateHtml) {
this.generateHtml = generateHtml;
}
public boolean isGenerateHtml() {
return generateHtml;
}
public void setDefaultProject(Project defaultProject) {
this.defaultProject = defaultProject;
}
public Project getDefaultProject() {
return defaultProject;
}
public int getIndexWordLimit() {
return indexWordLimit;
}
public void setIndexWordLimit(int indexWordLimit) {
this.indexWordLimit = indexWordLimit;
}
public boolean isVerbose() {
return verbose;
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public boolean isPrintProgress() {
return printProgress;
}
public void setPrintProgress(boolean printProgress) {
this.printProgress = printProgress;
}
public void setAllowLeadingWildcard(boolean allowLeadingWildcard) {
this.allowLeadingWildcard = allowLeadingWildcard;
}
public boolean isAllowLeadingWildcard() {
return allowLeadingWildcard;
}
private boolean quickContextScan;
public boolean isQuickContextScan() {
return quickContextScan;
}
public void setQuickContextScan(boolean quickContextScan) {
this.quickContextScan = quickContextScan;
}
public void setIgnoredNames(IgnoredNames ignoredNames) {
this.ignoredNames = ignoredNames;
}
public IgnoredNames getIgnoredNames() {
return ignoredNames;
}
public void setIncludedNames(Filter includedNames) {
this.includedNames = includedNames;
}
public Filter getIncludedNames() {
return includedNames;
}
public void setUserPage(String userPage) {
this.userPage = userPage;
}
public String getUserPage() {
return userPage;
}
public void setUserPageSuffix(String userPageSuffix) {
this.userPageSuffix = userPageSuffix;
}
public String getUserPageSuffix() {
return userPageSuffix;
}
public void setBugPage(String bugPage) {
this.bugPage = bugPage;
}
public String getBugPage() {
return bugPage;
}
public void setBugPattern(String bugPattern) {
this.bugPattern = bugPattern;
}
public String getBugPattern() {
return bugPattern;
}
public String getReviewPage() {
return reviewPage;
}
public void setReviewPage(String reviewPage) {
this.reviewPage = reviewPage;
}
public String getReviewPattern() {
return reviewPattern;
}
public void setReviewPattern(String reviewPattern) {
this.reviewPattern = reviewPattern;
}
public String getWebappLAF() {
return webappLAF;
}
public void setWebappLAF(String webappLAF) {
this.webappLAF = webappLAF;
}
public boolean isRemoteScmSupported() {
return remoteScmSupported;
}
public void setRemoteScmSupported(boolean remoteScmSupported) {
this.remoteScmSupported = remoteScmSupported;
}
public boolean isOptimizeDatabase() {
return optimizeDatabase;
}
public void setOptimizeDatabase(boolean optimizeDatabase) {
this.optimizeDatabase = optimizeDatabase;
}
public boolean isUsingLuceneLocking() {
return useLuceneLocking;
}
public void setUsingLuceneLocking(boolean useLuceneLocking) {
this.useLuceneLocking = useLuceneLocking;
}
public void setCompressXref(boolean compressXref) {
this.compressXref = compressXref;
}
public boolean isCompressXref() {
return compressXref;
}
public boolean isIndexVersionedFilesOnly() {
return indexVersionedFilesOnly;
}
public void setIndexVersionedFilesOnly(boolean indexVersionedFilesOnly) {
this.indexVersionedFilesOnly = indexVersionedFilesOnly;
}
public Date getDateForLastIndexRun() {
File timestamp = new File(getDataRoot(), "timestamp");
return new Date(timestamp.lastModified());
}
/**
* Return contents of a file or empty string if the file cannot be read.
*/
private String getFileContent(File file) {
StringBuilder contents = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(file));
try {
String line = null;
while (( line = input.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
catch (java.io.IOException e) {
logger.warning("failed to read header include file: " + e);
return "";
}
finally {
try {
input.close();
}
catch (java.io.IOException e) {
logger.info("failed to close header include file: " + e);
}
}
}
catch (java.io.FileNotFoundException e) {
return "";
}
return contents.toString();
}
/**
* Return string from the header include file so it can be embedded into
* page footer.
*/
public String getFooterIncludeFileContent() {
File hdrfile = new File(getDataRoot(), "footer_include");
return getFileContent(hdrfile);
}
/**
* Return string from the header include file so it can be embedded into
* page header.
*/
public String getHeaderIncludeFileContent() {
File hdrfile = new File(getDataRoot(), "header_include");
return getFileContent(hdrfile);
}
public String getDatabaseDriver() {
return databaseDriver;
}
public void setDatabaseDriver(String databaseDriver) {
this.databaseDriver = databaseDriver;
}
public String getDatabaseUrl() {
return databaseUrl;
}
public void setDatabaseUrl(String databaseUrl) {
this.databaseUrl = databaseUrl;
}
public Set<String> getAllowedSymlinks() {
return allowedSymlinks;
}
public void setAllowedSymlinks(Set<String> allowedSymlinks) {
this.allowedSymlinks = allowedSymlinks;
}
public boolean isObfuscatingEMailAddresses() {
return obfuscatingEMailAddresses;
}
public void setObfuscatingEMailAddresses(boolean obfuscate) {
this.obfuscatingEMailAddresses = obfuscate;
}
public boolean isChattyStatusPage() {
return chattyStatusPage;
}
public void setChattyStatusPage(boolean chattyStatusPage) {
this.chattyStatusPage = chattyStatusPage;
}
/**
* Write the current configuration to a file
* @param file the file to write the configuration into
* @throws IOException if an error occurs
*/
public void write(File file) throws IOException {
final FileOutputStream out = new FileOutputStream(file);
try {
this.encodeObject(out);
} finally {
IOUtils.close(out);
}
}
public String getXMLRepresentationAsString() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
this.encodeObject(bos);
return bos.toString();
}
private void encodeObject(OutputStream out) {
XMLEncoder e = new XMLEncoder(new BufferedOutputStream(out));
e.writeObject(this);
e.close();
}
public static Configuration read(File file) throws IOException {
final FileInputStream in = new FileInputStream(file);
try {
return decodeObject(in);
} finally {
IOUtils.close(in);
}
}
public static Configuration makeXMLStringAsConfiguration(String xmlconfig) throws IOException {
final Configuration ret;
final ByteArrayInputStream in = new ByteArrayInputStream(xmlconfig.getBytes());
ret = decodeObject(in);
return ret;
}
private static Configuration decodeObject(InputStream in) throws IOException {
XMLDecoder d = new XMLDecoder(new BufferedInputStream(in));
final Object ret = d.readObject();
d.close();
if (!(ret instanceof Configuration)) {
throw new IOException("Not a valid config file");
}
return (Configuration)ret;
}
}
| true | true | public Configuration() {
//defaults for an opengrok instance configuration
setHistoryCache(true);
setHistoryCacheTime(30);
setHistoryCacheInDB(false);
setProjects(new ArrayList<Project>());
setRepositories(new ArrayList<RepositoryInfo>());
setUrlPrefix("/source/s?");
//setUrlPrefix("../s?"); // TODO generate relative search paths, get rid of -w <webapp> option to indexer !
setCtags(System.getProperty("org.opensolaris.opengrok.analysis.Ctags", "ctags"));
//below can cause an outofmemory error, since it is defaulting to NO LIMIT
setIndexWordLimit(Integer.MAX_VALUE);
setVerbose(false);
setPrintProgress(false);
setGenerateHtml(true);
setQuickContextScan(true);
setIgnoredNames(new IgnoredNames());
setIncludedNames(new Filter());
setUserPage("http://www.opensolaris.org/viewProfile.jspa?username=");
setBugPage("http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=");
setBugPattern("\\b([12456789][0-9]{6})\\b");
setReviewPage("http://arc.opensolaris.org/caselog/PSARC/");
setReviewPattern("\\b(\\d{4}/\\d{3})\\b"); // in form e.g. PSARC 2008/305
setWebappLAF("default");
setRemoteScmSupported(false);
setOptimizeDatabase(true);
setUsingLuceneLocking(false);
setCompressXref(true);
setIndexVersionedFilesOnly(false);
setHitsPerPage(25);
setCachePages(5);
setScanningDepth(3); // default depth of scanning for repositories
setAllowedSymlinks(new HashSet<String>());
setTabSize(4);
cmds = new HashMap<String, String>();
}
| public Configuration() {
//defaults for an opengrok instance configuration
setHistoryCache(true);
setHistoryCacheTime(30);
setHistoryCacheInDB(false);
setProjects(new ArrayList<Project>());
setRepositories(new ArrayList<RepositoryInfo>());
setUrlPrefix("/source/s?");
//setUrlPrefix("../s?"); // TODO generate relative search paths, get rid of -w <webapp> option to indexer !
setCtags(System.getProperty("org.opensolaris.opengrok.analysis.Ctags", "ctags"));
//below can cause an outofmemory error, since it is defaulting to NO LIMIT
setIndexWordLimit(Integer.MAX_VALUE);
setVerbose(false);
setPrintProgress(false);
setGenerateHtml(true);
setQuickContextScan(true);
setIgnoredNames(new IgnoredNames());
setIncludedNames(new Filter());
setUserPage("http://www.opensolaris.org/viewProfile.jspa?username=");
setBugPage("http://bugs.opensolaris.org/bugdatabase/view_bug.do?bug_id=");
setBugPattern("\\b([12456789][0-9]{6})\\b");
setReviewPage("http://arc.opensolaris.org/caselog/PSARC/");
setReviewPattern("\\b(\\d{4}/\\d{3})\\b"); // in form e.g. PSARC 2008/305
setWebappLAF("default");
setRemoteScmSupported(false);
setOptimizeDatabase(true);
setUsingLuceneLocking(false);
setCompressXref(true);
setIndexVersionedFilesOnly(false);
setHitsPerPage(25);
setCachePages(5);
setScanningDepth(3); // default depth of scanning for repositories
setAllowedSymlinks(new HashSet<String>());
//setTabSize(4);
cmds = new HashMap<String, String>();
}
|
diff --git a/src/share/classes/com/sun/tools/javafx/comp/JavafxDecompose.java b/src/share/classes/com/sun/tools/javafx/comp/JavafxDecompose.java
index 7367b9ee0..a7d89ff6e 100644
--- a/src/share/classes/com/sun/tools/javafx/comp/JavafxDecompose.java
+++ b/src/share/classes/com/sun/tools/javafx/comp/JavafxDecompose.java
@@ -1,1120 +1,1120 @@
/*
* Copyright 2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.tools.javafx.comp;
import com.sun.javafx.api.JavafxBindStatus;
import com.sun.tools.javafx.code.JavafxFlags;
import com.sun.tools.javafx.code.JavafxSymtab;
import com.sun.tools.javafx.code.JavafxTypes;
import com.sun.tools.javafx.code.JavafxVarSymbol;
import com.sun.tools.javafx.comp.JavafxTranslationSupport.NotYetImplementedException;
import com.sun.tools.javafx.tree.*;
import com.sun.tools.mjavac.code.Flags;
import com.sun.tools.mjavac.code.Kinds;
import com.sun.tools.mjavac.code.Symbol;
import com.sun.tools.mjavac.code.Symbol.ClassSymbol;
import com.sun.tools.mjavac.code.Symbol.MethodSymbol;
import com.sun.tools.mjavac.code.Symbol.VarSymbol;
import com.sun.tools.mjavac.code.Type;
import com.sun.tools.mjavac.code.Type.MethodType;
import com.sun.tools.mjavac.code.TypeTags;
import com.sun.tools.mjavac.jvm.ClassReader;
import com.sun.tools.mjavac.util.List;
import com.sun.tools.mjavac.util.ListBuffer;
import com.sun.tools.mjavac.util.Name;
import com.sun.tools.mjavac.util.Context;
import com.sun.tools.mjavac.util.JCDiagnostic.DiagnosticPosition;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
/**
* Decompose bind expressions into easily translated expressions
*
* @author Robert Field
*/
public class JavafxDecompose implements JavafxVisitor {
protected static final Context.Key<JavafxDecompose> decomposeKey =
new Context.Key<JavafxDecompose>();
private JFXTree result;
private JavafxBindStatus bindStatus = JavafxBindStatus.UNBOUND;
private ListBuffer<JFXTree> lbVar;
private Set<String> synthNames;
private Symbol varOwner = null;
private Symbol currentVarSymbol;
private Symbol currentClass = null;
private boolean inScriptLevel = true;
// Map of shreded (Ident) selectors in bound select expressions.
// Used in shred optimization.
private Map<Symbol, JFXExpression> shrededSelectors;
protected final JavafxTreeMaker fxmake;
protected final JavafxPreTranslationSupport preTrans;
protected final JavafxDefs defs;
protected final Name.Table names;
protected final JavafxResolve rs;
protected final JavafxSymtab syms;
protected final JavafxTypes types;
protected final ClassReader reader;
public static JavafxDecompose instance(Context context) {
JavafxDecompose instance = context.get(decomposeKey);
if (instance == null)
instance = new JavafxDecompose(context);
return instance;
}
JavafxDecompose(Context context) {
context.put(decomposeKey, this);
fxmake = JavafxTreeMaker.instance(context);
preTrans = JavafxPreTranslationSupport.instance(context);
names = Name.Table.instance(context);
types = JavafxTypes.instance(context);
syms = (JavafxSymtab)JavafxSymtab.instance(context);
rs = JavafxResolve.instance(context);
defs = JavafxDefs.instance(context);
reader = ClassReader.instance(context);
}
/**
* External access: overwrite the top-level tree with the translated tree
*/
public void decompose(JavafxEnv<JavafxAttrContext> attrEnv) {
bindStatus = JavafxBindStatus.UNBOUND;
lbVar = null;
synthNames = new HashSet<String>();
attrEnv.toplevel = decompose(attrEnv.toplevel);
synthNames = null;
lbVar = null;
}
void TODO(String msg) {
throw new NotYetImplementedException("Not yet implemented: " + msg);
}
@SuppressWarnings("unchecked")
private <T extends JFXTree> T decompose(T tree) {
if (tree == null)
return null;
tree.accept(this);
result.type = tree.type;
return (T)result;
}
private <T extends JFXTree> List<T> decompose(List<T> trees) {
if (trees == null)
return null;
ListBuffer<T> lb = new ListBuffer<T>();
for (T tree: trees)
lb.append(decompose(tree));
return lb.toList();
}
private boolean requiresShred(JFXExpression tree) {
if (tree==null) {
return false;
}
switch (tree.getFXTag()) {
case APPLY:
case SEQUENCE_EXPLICIT:
case SEQUENCE_RANGE:
case FOR_EXPRESSION:
return true;
case CONDEXPR:
return types.isSequence(tree.type);
}
return false;
}
private JFXExpression decomposeComponent(JFXExpression tree) {
if (requiresShred(tree))
return shred(tree);
else
return decompose(tree);
}
private List<JFXExpression> decomposeComponents(List<JFXExpression> trees) {
if (trees == null)
return null;
ListBuffer<JFXExpression> lb = new ListBuffer<JFXExpression>();
for (JFXExpression tree: trees)
lb.append(decomposeComponent(tree));
return lb.toList();
}
private JFXVar makeVar(DiagnosticPosition diagPos, String label, JFXExpression pose, JavafxBindStatus bindStatus, Type type) {
Name vName = tempName(label);
return makeVar(diagPos, vName, pose, bindStatus, type);
}
private JFXVar makeVar(DiagnosticPosition diagPos, Name vName, JFXExpression pose, JavafxBindStatus bindStatus, Type type) {
long flags = JavafxFlags.SCRIPT_PRIVATE | (inScriptLevel ? Flags.STATIC | JavafxFlags.SCRIPT_LEVEL_SYNTH_STATIC : 0L);
JavafxVarSymbol sym = new JavafxVarSymbol(types, names, flags, vName, types.normalize(type), varOwner);
varOwner.members().enter(sym);
JFXModifiers mod = fxmake.at(diagPos).Modifiers(flags);
JFXType fxType = preTrans.makeTypeTree(sym.type);
JFXVar v = fxmake.at(diagPos).Var(vName, fxType, mod, pose, bindStatus, null, null);
v.sym = sym;
v.type = sym.type;
lbVar.append(v);
return v;
}
private JFXVar shredVar(String label, JFXExpression pose, Type type) {
return shredVar(label, pose, type, JavafxBindStatus.UNIDIBIND);
}
private JFXVar shredVar(String label, JFXExpression pose, Type type, JavafxBindStatus bindStatus) {
Name tmpName = tempName(label);
// If this shred var initialized with a call to a bound function?
JFXVar ptrVar = makeTempBoundResultName(tmpName, pose);
if (ptrVar != null) {
return makeVar(pose.pos(), tmpName, id(ptrVar), bindStatus, type);
} else {
return makeVar(pose.pos(), tmpName, pose, bindStatus, type);
}
}
private JFXIdent id(JFXVar v) {
JFXIdent id = fxmake.at(v.pos).Ident(v.getName());
id.sym = v.sym;
id.type = v.type;
return id;
}
/**
* If we are in a bound expression, break this expression out into a separate synthetic bound variable.
*/
private JFXExpression shred(JFXExpression tree, Type contextType) {
if (tree == null) {
return null;
}
if (bindStatus.isBound()) {
return unconditionalShred(tree, contextType);
} else {
return decompose(tree);
}
}
private JFXIdent unconditionalShred(JFXExpression tree, Type contextType) {
JFXExpression pose = decompose(tree);
Type varType = tree.type;
if (tree.type == syms.botType && contextType != null) {
// If the tree type is bottom, try to use contextType
varType = contextType;
}
JFXVar v = shredVar("", pose, varType, bindStatus);
return id(v);
}
private JFXExpression shred(JFXExpression tree) {
return shred(tree, null);
}
private JFXExpression shredUnlessIdent(JFXExpression tree) {
if (tree instanceof JFXIdent) {
return decompose(tree);
}
return shred(tree);
}
private List<JFXExpression> shred(List<JFXExpression> trees, List<Type> paramTypes) {
if (trees == null)
return null;
ListBuffer<JFXExpression> lb = new ListBuffer<JFXExpression>();
Type paramType = paramTypes != null? paramTypes.head : null;
for (JFXExpression tree: trees) {
lb.append(shred(tree, paramType));
if (paramTypes != null) {
paramTypes = paramTypes.tail;
paramType = paramTypes.head;
}
}
return lb.toList();
}
private Name tempName(String label) {
String name = currentVarSymbol != null ? currentVarSymbol.toString() : "";
name += "$" + label + "$";
if (synthNames.contains(name)) {
for (int i = 0; true; i++) {
String numbered = name + i;
if (!synthNames.contains(numbered)) {
name = numbered;
break;
}
}
}
// name += defs.internalNameMarker;
synthNames.add(name);
return names.fromString(name);
}
private Name tempBoundResultName(Name name) {
return names.fromString(JavafxDefs.boundFunctionResult + name);
}
//TODO: clean-up this whole mess
private boolean isBoundFunctionResult(JFXExpression initExpr) {
if (initExpr instanceof JFXFunctionInvocation) {
Symbol meth = JavafxTreeInfo.symbol(((JFXFunctionInvocation)initExpr).meth);
return meth != null && (meth.flags() & JavafxFlags.BOUND) != 0L;
} else {
return false;
}
}
private JFXVar makeTempBoundResultName(Name varName, JFXExpression initExpr) {
JFXVar ptrVar = null;
if (isBoundFunctionResult(initExpr)) {
Name tmpBoundResName = tempBoundResultName(varName);
/*
* Introduce a Pointer synthetic variable which will be used to cache
* bound function's return value. The name of the sythetic Pointer
* variable is derived from the given varName.
*/
ptrVar = makeVar(initExpr.pos(), tmpBoundResName, initExpr, JavafxBindStatus.UNIDIBIND, syms.javafx_PointerType);
ptrVar.sym.flags_field |= Flags.SYNTHETIC | JavafxFlags.VARUSE_BIND_ACCESS;
}
return ptrVar;
}
private <T extends JFXTree> List<T> decomposeContainer(List<T> trees) {
if (trees == null)
return null;
ListBuffer<T> lb = new ListBuffer<T>();
for (T tree: trees)
lb.append(decompose(tree));
return lb.toList();
}
public void visitScript(JFXScript tree) {
bindStatus = JavafxBindStatus.UNBOUND;
tree.defs = decomposeContainer(tree.defs);
result = tree;
}
public void visitImport(JFXImport tree) {
result = tree;
}
public void visitSkip(JFXSkip tree) {
result = tree;
}
public void visitWhileLoop(JFXWhileLoop tree) {
JFXExpression cond = decompose(tree.cond);
JFXExpression body = decompose(tree.body);
result = fxmake.at(tree.pos).WhileLoop(cond, body);
}
public void visitTry(JFXTry tree) {
JFXBlock body = decompose(tree.body);
List<JFXCatch> catchers = decompose(tree.catchers);
JFXBlock finalizer = decompose(tree.finalizer);
result = fxmake.at(tree.pos).Try(body, catchers, finalizer);
}
public void visitCatch(JFXCatch tree) {
JFXVar param = decompose(tree.param);
JFXBlock body = decompose(tree.body);
result = fxmake.at(tree.pos).Catch(param, body);
}
public void visitIfExpression(JFXIfExpression tree) {
JFXExpression cond = decomposeComponent(tree.cond);
JFXExpression truepart = decomposeComponent(tree.truepart);
JFXExpression falsepart = decomposeComponent(tree.falsepart);
JFXIfExpression res = fxmake.at(tree.pos).Conditional(cond, truepart, falsepart);
if (bindStatus.isBound() && types.isSequence(tree.type)) {
res.boundCondVar = synthVar("cond", cond, cond.type, false);
res.boundThenVar = synthVar("then", truepart, truepart.type, false);
res.boundElseVar = synthVar("else", falsepart, falsepart.type, false);
// Add a size field to hold the previous size on condition switch
JFXVar v = makeSizeVar(tree.pos(), JavafxDefs.UNDEFINED_MARKER_INT);
v.sym.flags_field |= JavafxFlags.VARMARK_BARE_SYNTH;
res.boundSizeVar = v;
}
result = res;
}
public void visitBreak(JFXBreak tree) {
if (tree.nonLocalBreak) {
// A non-local break gets turned into an exception
JFXIdent nonLocalExceptionClass = fxmake.Ident(names.fromString(JavafxDefs.cNonLocalBreakException));
nonLocalExceptionClass.sym = syms.javafx_NonLocalBreakExceptionType.tsym;
nonLocalExceptionClass.type = syms.javafx_NonLocalBreakExceptionType;
JFXInstanciate expInst = fxmake.InstanciateNew(nonLocalExceptionClass, List.<JFXExpression>nil());
expInst.sym = (ClassSymbol)syms.javafx_NonLocalBreakExceptionType.tsym;
expInst.type = syms.javafx_NonLocalBreakExceptionType;
result = fxmake.Throw(expInst).setType(syms.unreachableType);
} else {
result = tree;
}
}
public void visitContinue(JFXContinue tree) {
if (tree.nonLocalContinue) {
// A non-local continue gets turned into an exception
JFXIdent nonLocalExceptionClass = fxmake.Ident(names.fromString(JavafxDefs.cNonLocalContinueException));
nonLocalExceptionClass.sym = syms.javafx_NonLocalContinueExceptionType.tsym;
nonLocalExceptionClass.type = syms.javafx_NonLocalContinueExceptionType;
JFXInstanciate expInst = fxmake.InstanciateNew(nonLocalExceptionClass, List.<JFXExpression>nil());
expInst.sym = (ClassSymbol)syms.javafx_NonLocalContinueExceptionType.tsym;
expInst.type = syms.javafx_NonLocalContinueExceptionType;
result = fxmake.Throw(expInst).setType(syms.unreachableType);
} else {
result = tree;
}
}
public void visitReturn(JFXReturn tree) {
tree.expr = decompose(tree.expr);
if (tree.nonLocalReturn) {
// A non-local return gets turned into an exception
JFXIdent nonLocalExceptionClass = fxmake.Ident(names.fromString(JavafxDefs.cNonLocalReturnException));
nonLocalExceptionClass.sym = syms.javafx_NonLocalReturnExceptionType.tsym;
nonLocalExceptionClass.type = syms.javafx_NonLocalReturnExceptionType;
List<JFXExpression> valueArg = tree.expr==null? List.<JFXExpression>nil() : List.of(tree.expr);
JFXInstanciate expInst = fxmake.InstanciateNew(
nonLocalExceptionClass,
valueArg);
expInst.sym = (ClassSymbol)syms.javafx_NonLocalReturnExceptionType.tsym;
expInst.type = syms.javafx_NonLocalReturnExceptionType;
result = fxmake.Throw(expInst);
} else {
result = tree;
}
}
public void visitThrow(JFXThrow tree) {
result = tree;
}
public void visitFunctionInvocation(JFXFunctionInvocation tree) {
JFXExpression fn = decompose(tree.meth);
Symbol msym = JavafxTreeInfo.symbol(tree.meth);
/*
* Do *not* shred select expression if it is passed to intrinsic function
* Pointer.make(Object). Shred only the "selected" portion of it. If
* we shred the whole select expr, then a temporary shred variable will
* be used to create Pointer. That temporary is a bound variable and so
* Pointer.set() on that would throw assign-to-bind-variable exception.
*/
List<JFXExpression> args;
if (types.isSyntheticPointerFunction(msym)) {
JFXVarRef varRef = (JFXVarRef)tree.args.head;
if (varRef.getReceiver() != null) {
varRef.setReceiver(shred(varRef.getReceiver()));
}
args = tree.args;
} else {
List<Type> paramTypes = tree.meth.type.getParameterTypes();
Symbol sym = JavafxTreeInfo.symbolFor(tree.meth);
if (sym instanceof MethodSymbol &&
((MethodSymbol)sym).isVarArgs()) {
Type varargType = paramTypes.reverse().head;
paramTypes = paramTypes.reverse().tail.reverse(); //remove last formal
while (paramTypes.size() < tree.args.size()) {
paramTypes = paramTypes.append(types.elemtype(varargType));
}
}
args = shred(tree.args, paramTypes);
}
JFXExpression res = fxmake.at(tree.pos).Apply(tree.typeargs, fn, args);
res.type = tree.type;
if (bindStatus.isBound() && types.isSequence(tree.type) && !isBoundFunctionResult(tree)) {
JFXVar v = shredVar("sii", res, tree.type);
JFXVar sz = makeSizeVar(v.pos(), JavafxDefs.UNDEFINED_MARKER_INT, JavafxBindStatus.UNBOUND);
res = fxmake.IdentSequenceProxy(v.name, v.sym, sz.sym);
}
result = res;
}
public void visitParens(JFXParens tree) {
JFXExpression expr = decomposeComponent(tree.expr);
result = fxmake.at(tree.pos).Parens(expr);
}
public void visitAssign(JFXAssign tree) {
JFXExpression lhs = decompose(tree.lhs);
JFXExpression rhs = decompose(tree.rhs);
result = fxmake.at(tree.pos).Assign(lhs, rhs);
}
public void visitAssignop(JFXAssignOp tree) {
JFXExpression lhs = decompose(tree.lhs);
JFXExpression rhs = decompose(tree.rhs);
JavafxTag tag = tree.getFXTag();
JFXAssignOp res = fxmake.at(tree.pos).Assignop(tag, lhs, rhs);
res.operator = tree.operator;
result = res;
}
public void visitUnary(JFXUnary tree) {
JFXExpression arg = tree.getFXTag() == JavafxTag.REVERSE?
shredUnlessIdent(tree.arg) :
decomposeComponent(tree.arg);
JavafxTag tag = tree.getFXTag();
JFXUnary res = fxmake.at(tree.pos).Unary(tag, arg);
res.operator = tree.operator;
result = res;
}
public void visitBinary(JFXBinary tree) {
JavafxTag tag = tree.getFXTag();
boolean cutOff = tag==JavafxTag.AND || tag==JavafxTag.OR;
JFXExpression lhs = decomposeComponent(tree.lhs);
JFXExpression rhs = cutOff?
shredUnlessIdent(tree.rhs) : // If cut-off operation, preface code must be evaluated separately
decomposeComponent(tree.rhs);
JFXBinary res = fxmake.at(tree.pos).Binary(tag, lhs, rhs);
res.operator = tree.operator;
result = res;
}
public void visitTypeCast(JFXTypeCast tree) {
JFXTree clazz = decompose(tree.clazz);
JFXExpression expr = (bindStatus.isBound() && types.isSequence(tree.type))?
shredUnlessIdent(tree.expr) :
decomposeComponent(tree.expr);
result = fxmake.at(tree.pos).TypeCast(clazz, expr);
}
public void visitInstanceOf(JFXInstanceOf tree) {
JFXExpression expr = decomposeComponent(tree.expr);
JFXTree clazz = decompose(tree.clazz);
result = fxmake.at(tree.pos).TypeTest(expr, clazz);
}
public void visitSelect(JFXSelect tree) {
DiagnosticPosition diagPos = tree.pos();
Symbol sym = tree.sym;
Symbol selectSym = JavafxTreeInfo.symbolFor(tree.selected);
if (selectSym != null
&& ((selectSym.kind == Kinds.TYP && sym.kind != Kinds.MTH)
|| selectSym.name == names._this)) {
// Select is just via "this" -- make it a simple Ident
//TODO: move this to lower
JFXIdent res = fxmake.at(diagPos).Ident(sym.name);
res.sym = sym;
result = res;
} else {
JFXExpression selected;
if ((selectSym != null && (selectSym.kind == Kinds.TYP || selectSym.name == names._super || selectSym.name == names._class))) {
// Referenced is static, or qualified super access
// then selected is a class reference
selected = decompose(tree.selected);
} else {
JavafxBindStatus oldBindStatus = bindStatus;
if (bindStatus == JavafxBindStatus.BIDIBIND) bindStatus = JavafxBindStatus.UNIDIBIND;
/**
* Avoding shreding as an optimization: if the select expression's selected part
* is a JFXIdent and that identifier is an instance var of current class, then we
* don't have to shred it.
*
* Example:
*
* class Person {
* var name : String;
* var age: Integer;
* }
*
* class Test {
* var p : Person;
* var name = bind p.name; // instance var "p" in bind-select
* var age = bind p.age; // same instance var "p" in bind-select
* }
*
* In this case we can avoid shreding and generating two synthetic variables for
* bind select expressions p.name, p.age.
*
* Special cases:
*
* (1) sequences are always shreded
* (2) non-variable access (eg. select expression selects method)
*
* TODO: for some reason this optimization does not work if the same selected part is
* used by a unidirectional and bidirectional bind expressions. For now, filtering out
* bidirectional cases. We need to revisit that mystery. Also. I've to oldBindStatus
* because bindStatus has been set to UNIDIBIND in the previous statement.
*/
- if (oldBindStatus == JavafxBindStatus.UNIDIBIND &&
+ if (false && oldBindStatus == JavafxBindStatus.UNIDIBIND &&
tree.selected instanceof JFXIdent &&
!types.isSequence(tree.type) &&
sym instanceof VarSymbol) {
if (selectSym.owner == currentClass && !(selectSym.isStatic() ^ inScriptLevel)) {
selected = tree.selected;
} else if (shrededSelectors.containsKey(selectSym)) {
selected = shrededSelectors.get(selectSym);
} else {
selected = shred(tree.selected);
shrededSelectors.put(selectSym, selected);
}
} else {
selected = shred(tree.selected);
}
bindStatus = oldBindStatus;
}
JFXSelect res = fxmake.at(diagPos).Select(selected, sym.name);
res.sym = sym;
if (bindStatus.isBound() && types.isSequence(tree.type)) {
// Add a size field to hold the previous size on selector switch
JFXVar v = makeSizeVar(diagPos, 0);
v.sym.flags_field |= JavafxFlags.VARMARK_BARE_SYNTH | Flags.PRIVATE;
res.boundSize = v;
}
result = res;
}
}
public void visitIdent(JFXIdent tree) {
JFXIdent res = fxmake.at(tree.pos).Ident(tree.getName());
res.sym = tree.sym;
result = res;
}
public void visitLiteral(JFXLiteral tree) {
result = tree;
}
public void visitModifiers(JFXModifiers tree) {
result = tree;
}
public void visitErroneous(JFXErroneous tree) {
result = tree;
}
public void visitClassDeclaration(JFXClassDeclaration tree) {
JavafxBindStatus prevBindStatus = bindStatus;
bindStatus = JavafxBindStatus.UNBOUND;
Symbol prevVarOwner = varOwner;
Symbol prevClass = currentClass;
Map<Symbol, JFXExpression> prevShredExprs = shrededSelectors;
shrededSelectors = new HashMap<Symbol, JFXExpression>();
currentClass = varOwner = tree.sym;
ListBuffer<JFXTree> prevLbVar = lbVar;
lbVar = ListBuffer.<JFXTree>lb();
for (JFXTree mem : tree.getMembers()) {
lbVar.append(decompose(mem));
}
tree.setMembers(lbVar.toList());
lbVar = prevLbVar;
varOwner = prevVarOwner;
currentClass = prevClass;
shrededSelectors = prevShredExprs;
result = tree;
bindStatus = prevBindStatus;
}
public void visitFunctionDefinition(JFXFunctionDefinition tree) {
boolean wasInScriptLevel = inScriptLevel;
// Bound functions are handled by local variable bind facility.
// The return value is transformed already in JavafxLocalToClass.
// So, we are not changing bind state "inBind".
JavafxBindStatus prevBindStatus = bindStatus;
bindStatus = JavafxBindStatus.UNBOUND;
inScriptLevel = tree.isStatic();
Symbol prevVarOwner = varOwner;
varOwner = null;
JFXModifiers mods = tree.mods;
Name name = tree.getName();
JFXType restype = tree.getJFXReturnType();
List<JFXVar> params = decompose(tree.getParams());
JFXBlock bodyExpression = decompose(tree.getBodyExpression());
JFXFunctionDefinition res = fxmake.at(tree.pos).FunctionDefinition(mods, name, restype, params, bodyExpression);
res.sym = tree.sym;
result = res;
bindStatus = prevBindStatus;
inScriptLevel = wasInScriptLevel;
varOwner = prevVarOwner;
}
public void visitInitDefinition(JFXInitDefinition tree) {
boolean wasInScriptLevel = inScriptLevel;
inScriptLevel = tree.sym.isStatic();
JFXBlock body = decompose(tree.body);
JFXInitDefinition res = fxmake.at(tree.pos).InitDefinition(body);
res.sym = tree.sym;
result = res;
inScriptLevel = wasInScriptLevel;
}
public void visitPostInitDefinition(JFXPostInitDefinition tree) {
boolean wasInScriptLevel = inScriptLevel;
inScriptLevel = tree.sym.isStatic();
JFXBlock body = decompose(tree.body);
JFXPostInitDefinition res = fxmake.at(tree.pos).PostInitDefinition(body);
res.sym = tree.sym;
result = res;
inScriptLevel = wasInScriptLevel;
}
public void visitStringExpression(JFXStringExpression tree) {
List<JFXExpression> parts = decomposeComponents(tree.parts);
result = fxmake.at(tree.pos).StringExpression(parts, tree.translationKey);
}
public void visitInstanciate(JFXInstanciate tree) {
JFXExpression klassExpr = tree.getIdentifier();
List<JFXObjectLiteralPart> dparts = decompose(tree.getParts());
JFXClassDeclaration dcdel = decompose(tree.getClassBody());
List<JFXExpression> dargs = decomposeComponents(tree.getArgs());
JFXInstanciate res = fxmake.at(tree.pos).Instanciate(tree.getJavaFXKind(), klassExpr, dcdel, dargs, dparts, tree.getLocalvars());
res.sym = tree.sym;
res.constructor = tree.constructor;
res.varDefinedByThis = tree.varDefinedByThis;
long anonTestFlags = Flags.SYNTHETIC | Flags.FINAL;
if (dcdel != null && (dcdel.sym.flags_field & anonTestFlags) == anonTestFlags) {
ListBuffer<JavafxVarSymbol> objInitSyms = ListBuffer.lb();
for (JFXObjectLiteralPart olp : dparts) {
objInitSyms.append((JavafxVarSymbol)olp.sym);
}
if (objInitSyms.size() > 1) {
dcdel.setObjInitSyms(objInitSyms.toList());
}
}
result = res;
}
public void visitObjectLiteralPart(JFXObjectLiteralPart tree) {
Symbol prevVarSymbol = currentVarSymbol;
currentVarSymbol = tree.sym;
if (tree.isExplicitlyBound())
throw new AssertionError("bound parts should have been converted to overrides");
JFXExpression expr = shred(tree.getExpression(), tree.sym.type);
JFXObjectLiteralPart res = fxmake.at(tree.pos).ObjectLiteralPart(tree.name, expr, tree.getExplicitBindStatus());
res.markBound(bindStatus);
res.sym = tree.sym;
currentVarSymbol = prevVarSymbol;
result = res;
}
public void visitTypeAny(JFXTypeAny tree) {
result = tree;
}
public void visitTypeClass(JFXTypeClass tree) {
result = tree;
}
public void visitTypeFunctional(JFXTypeFunctional tree) {
result = tree;
}
public void visitTypeArray(JFXTypeArray tree) {
result = tree;
}
public void visitTypeUnknown(JFXTypeUnknown tree) {
result = tree;
}
public void visitVarInit(JFXVarInit tree) {
// Handled in visitVar
result = tree;
}
public void visitVarRef(JFXVarRef tree) {
result = tree;
}
public void visitVar(JFXVar tree) {
boolean wasInScriptLevel = inScriptLevel;
inScriptLevel = tree.isStatic();
Symbol prevVarSymbol = currentVarSymbol;
currentVarSymbol = tree.sym;
JavafxBindStatus prevBindStatus = bindStatus;
// for on-replace, decompose as unbound
bindStatus = JavafxBindStatus.UNBOUND;
JFXOnReplace onReplace = decompose(tree.getOnReplace());
JFXOnReplace onInvalidate = decompose(tree.getOnInvalidate());
// bound if was bind context or is bound variable
bindStatus = tree.isBound()?
tree.getBindStatus() :
prevBindStatus;
JFXExpression initExpr = decompose(tree.getInitializer());
// Is this a bound var and initialized with a Pointer result
// from a bound function call? If so, we need to create Pointer
// synthetic var here.
JFXVar ptrVar = bindStatus.isBound()? makeTempBoundResultName(tree.name, initExpr) : null;
JFXVar res = fxmake.at(tree.pos).Var(
tree.name,
tree.getJFXType(),
tree.getModifiers(),
(ptrVar != null)? id(ptrVar) : initExpr,
tree.getBindStatus(),
onReplace,
onInvalidate);
res.sym = tree.sym;
res.type = tree.type;
JFXVarInit vsi = tree.getVarInit();
if (vsi != null) {
// update the var in the var-init
vsi.resetVar(res);
}
bindStatus = prevBindStatus;
inScriptLevel = wasInScriptLevel;
currentVarSymbol = prevVarSymbol;
result = res;
}
public void visitOnReplace(JFXOnReplace tree) {
JFXVar oldValue = tree.getOldValue();
JFXVar firstIndex = tree.getFirstIndex();
JFXVar lastIndex = tree.getLastIndex();
JFXVar newElements = tree.getNewElements();
JFXVar saveVar = oldValue != null && types.isSequence(oldValue.type) ? makeSaveVar(tree.pos(), oldValue.type) : null;
JFXBlock body = decompose(tree.getBody());
result = fxmake.at(tree.pos).OnReplace(oldValue, firstIndex, lastIndex, tree.getEndKind(), newElements, saveVar, body);
}
/**
* Block-expressions
*
* For bound sequence block-expressions, get the initialization right by
* The block vars have already been made into VarInits.
* Making block value into a synthetic var, and add a VarInit for it
* to the block vars
*/
public void visitBlockExpression(JFXBlock tree) {
List<JFXExpression> stats;
JFXExpression value;
if (bindStatus.isBound() && types.isSequence(tree.type)) {
for (JFXExpression stat : tree.stats) {
if (!(stat instanceof JFXVarInit)) {
throw new AssertionError("the statements in a bound block should already be just VarInit");
}
}
JFXVar v = shredVar("value", decompose(tree.value), tree.type);
JFXVarInit vi = fxmake.at(tree.value.pos()).VarInit(v);
vi.type = tree.type;
stats = tree.stats.append(vi);
JFXIdent val = id(v);
val.sym = v.sym;
val.type = tree.type;
value = val;
} else {
stats = decomposeContainer(tree.stats);
value = decompose(tree.value);
}
result = fxmake.at(tree.pos()).Block(tree.flags, stats, value);
}
public void visitFunctionValue(JFXFunctionValue tree) {
JavafxBindStatus prevBindStatus = bindStatus;
bindStatus = JavafxBindStatus.UNBOUND;
tree.bodyExpression = decompose(tree.bodyExpression);
result = tree;
bindStatus = prevBindStatus;
}
public void visitSequenceEmpty(JFXSequenceEmpty tree) {
result = tree;
}
private JFXVar synthVar(String label, JFXExpression tree, Type type) {
return synthVar(label, tree, type, true);
}
private JFXVar synthVar(String label, JFXExpression tree, Type type, boolean decompose) {
if (tree == null) {
return null;
}
JFXExpression expr = decompose ? decompose(tree) : tree;
fxmake.at(tree.pos()); // set position
if (!types.isSameType(tree.type, type)) {
// cast to desired type
JFXIdent tp = (JFXIdent) fxmake.Type(type);
tp.sym = type.tsym;
expr = fxmake.TypeCast(tp, expr);
}
JFXVar v = shredVar(label, expr, type);
v.sym.flags_field |= JavafxFlags.VARMARK_BARE_SYNTH;
return v;
}
private JFXVar makeSizeVar(DiagnosticPosition diagPos, int initial) {
return makeSizeVar( diagPos, initial, JavafxBindStatus.UNIDIBIND);
}
private JFXVar makeSizeVar(DiagnosticPosition diagPos, int initial, JavafxBindStatus bindStatus) {
JFXExpression initialSize = fxmake.at(diagPos).Literal(initial);
initialSize.type = syms.intType;
JFXVar v = makeVar(diagPos, "size", initialSize, bindStatus, syms.intType);
return v;
}
private JFXVar makeSaveVar(DiagnosticPosition diagPos, Type type) {
JFXVar v = makeVar(diagPos, "save", null, JavafxBindStatus.UNBOUND, type);
v.sym.flags_field |= JavafxFlags.VARMARK_BARE_SYNTH;
return v;
}
/**
* Add synthetic variables, and attach them to the reconstituted range.
* def range = bind [rb .. re step st]
* adds:
*
* def lower = bind rb; // marked BARE_SYNTH
* def upper = bind re; // marked BARE_SYNTH
* def step = bind st; // marked BARE_SYNTH
* def size = bind -99;
*/
public void visitSequenceRange(JFXSequenceRange tree) {
JFXExpression lower;
JFXExpression upper;
JFXExpression stepOrNull;
if (bindStatus.isBound()) {
Type elemType = types.elementType(tree.type);
lower = synthVar("lower", tree.getLower(), elemType);
upper = synthVar("upper", tree.getUpper(), elemType);
stepOrNull = synthVar("step", tree.getStepOrNull(), elemType);
} else {
lower = decomposeComponent(tree.getLower());
upper = decomposeComponent(tree.getUpper());
stepOrNull = decomposeComponent(tree.getStepOrNull());
}
JFXSequenceRange res = fxmake.at(tree.pos).RangeSequence(lower, upper, stepOrNull, tree.isExclusive());
res.type = tree.type;
if (bindStatus.isBound()) {
// now add a size temp var
res.boundSizeVar = makeSizeVar(tree.pos(), JavafxDefs.UNDEFINED_MARKER_INT);
res.boundSizeVar.sym.flags_field |= JavafxFlags.VARMARK_BARE_SYNTH;
}
result = res;
}
public void visitSequenceExplicit(JFXSequenceExplicit tree) {
List<JFXExpression> items;
if (bindStatus.isBound()) {
items = List.nil(); // bound should not use items - non-null for pretty-printing
} else {
items = decomposeComponents(tree.getItems());
}
JFXSequenceExplicit res = fxmake.at(tree.pos).ExplicitSequence(items);
res.type = tree.type;
if (bindStatus.isBound()) {
ListBuffer<JFXVar> vb = ListBuffer.lb();
for (JFXExpression item : tree.getItems()) {
vb.append(shredVar("item", decompose(item), item.type));
}
res.boundItemsVars = vb.toList();
}
result = res;
}
public void visitSequenceIndexed(JFXSequenceIndexed tree) {
JFXExpression sequence = null;
if (bindStatus.isBound()) {
sequence = shredUnlessIdent(tree.getSequence());
} else {
sequence = decomposeComponent(tree.getSequence());
}
JFXExpression index = decomposeComponent(tree.getIndex());
result = fxmake.at(tree.pos).SequenceIndexed(sequence, index);
}
public void visitSequenceSlice(JFXSequenceSlice tree) {
JFXExpression sequence = shred(tree.getSequence());
JFXExpression firstIndex = shred(tree.getFirstIndex());
JFXExpression lastIndex = shred(tree.getLastIndex());
result = fxmake.at(tree.pos).SequenceSlice(sequence, firstIndex, lastIndex, tree.getEndKind());
}
public void visitSequenceInsert(JFXSequenceInsert tree) {
JFXExpression sequence = decompose(tree.getSequence());
JFXExpression element = decompose(tree.getElement());
JFXExpression position = decompose(tree.getPosition());
result = fxmake.at(tree.pos).SequenceInsert(sequence, element, position, tree.shouldInsertAfter());
}
public void visitSequenceDelete(JFXSequenceDelete tree) {
JFXExpression sequence = decompose(tree.getSequence());
JFXExpression element = decompose(tree.getElement());
result = fxmake.at(tree.pos).SequenceDelete(sequence, element);
}
public void visitInvalidate(JFXInvalidate tree) {
JFXExpression variable = decompose(tree.getVariable());
result = fxmake.at(tree.pos).Invalidate(variable);
}
public void visitForExpression(JFXForExpression tree) {
if (bindStatus.isBound()) {
JFXForExpressionInClause clause = tree.inClauses.head;
clause.seqExpr = shred(clause.seqExpr, null);
// clause.whereExpr = decompose(clause.whereExpr);
// Create the BoundForHelper variable:
Type inductionType = types.boxedTypeOrType(clause.inductionVarSym.type);
JFXBlock body = (JFXBlock) tree.getBodyExpression();
Type helperType = types.applySimpleGenericType(
types.isSequence(body.type)?
syms.javafx_BoundForOverSequenceType :
(preTrans.isNullable(body) || clause.hasWhereExpression())?
syms.javafx_BoundForOverNullableSingletonType :
syms.javafx_BoundForOverSingletonType,
types.boxedElementType(tree.type),
inductionType);
JFXExpression init = fxmake.Literal(TypeTags.BOT, null);
init.type = helperType;
Name helperName = preTrans.makeUniqueVarNameIn(names.fromString("helper$"+currentVarSymbol.name), varOwner);
JFXVar helper = makeVar(tree, helperName, init, JavafxBindStatus.UNBOUND, helperType);
//helper.sym.flags_field |= JavafxFlags.VARMARK_BARE_SYNTH;
clause.boundHelper = helper;
// Fix up the class
JFXClassDeclaration cdecl = (JFXClassDeclaration) decompose(body.stats.head);
body.stats.head = cdecl;
// Patch the type of the doit function
patchDoitFunction(cdecl);
// Patch the type of the anon{}.doit() call
body.value.type = cdecl.type; //TODO: probably need to go deeper
// Add FXForPart as implemented interface -- FXForPart<T>
Type intfc = types.applySimpleGenericType(types.erasure(syms.javafx_FXForPartInterfaceType), inductionType);
cdecl.setDifferentiatedExtendingImplementingMixing(
List.<JFXExpression>nil(),
List.<JFXExpression>of(fxmake.Type(intfc)), // implement interface
List.<JFXExpression>nil());
result = fxmake.at(tree.pos).ForExpression(List.of(clause), body);
} else {
List<JFXForExpressionInClause> inClauses = decompose(tree.inClauses);
JFXExpression bodyExpr = decompose(tree.bodyExpr);
result = fxmake.at(tree.pos).ForExpression(inClauses, bodyExpr);
}
}
private void patchDoitFunction(JFXClassDeclaration cdecl) {
Type ctype = cdecl.type;
for (JFXTree mem : cdecl.getMembers()) {
if (mem.getFXTag() == JavafxTag.FUNCTION_DEF) {
JFXFunctionDefinition func = (JFXFunctionDefinition) mem;
if ((func.sym.flags() & JavafxFlags.FUNC_SYNTH_LOCAL_DOIT) != 0L) {
// Change the value to be "this"
JFXBlock body = func.getBodyExpression();
body.value = fxmake.This(ctype);
body.type = ctype;
// Adjust function to return class type
final MethodType funcType = new MethodType(
List.<Type>nil(), // arg types
ctype, // return type
List.<Type>nil(), // Throws type
syms.methodClass); // TypeSymbol
func.sym.type = funcType;
func.type = funcType;
}
}
}
}
public void visitForExpressionInClause(JFXForExpressionInClause tree) {
tree.seqExpr = decompose(tree.seqExpr);
tree.setWhereExpr(decompose(tree.getWhereExpression()));
result = tree;
}
public void visitIndexof(JFXIndexof tree) {
result = tree.clause.indexVarSym == null ? tree : fxmake.Ident(tree.clause.indexVarSym);
}
public void visitTimeLiteral(JFXTimeLiteral tree) {
result = tree;
}
public void visitOverrideClassVar(JFXOverrideClassVar tree) {
boolean wasInScriptLevel = inScriptLevel;
inScriptLevel = tree.isStatic();
JavafxBindStatus prevBindStatus = bindStatus;
Symbol prevVarSymbol = currentVarSymbol;
currentVarSymbol = tree.sym;
// on-replace is always unbound
bindStatus = JavafxBindStatus.UNBOUND;
JFXOnReplace onReplace = decompose(tree.getOnReplace());
JFXOnReplace onInvalidate = decompose(tree.getOnInvalidate());
// bound if was bind context or is bound variable
bindStatus = tree.isBound()?
tree.getBindStatus() :
prevBindStatus;
JFXExpression initializer = shredUnlessIdent(tree.getInitializer());
JFXOverrideClassVar res = fxmake.at(tree.pos).OverrideClassVar(tree.getName(),
tree.getJFXType(),
tree.getModifiers(),
tree.getId(),
initializer,
tree.getBindStatus(),
onReplace,
onInvalidate);
res.sym = tree.sym;
bindStatus = prevBindStatus;
currentVarSymbol = prevVarSymbol;
inScriptLevel = wasInScriptLevel;
result = res;
}
public void visitInterpolateValue(JFXInterpolateValue tree) {
JavafxBindStatus prevBindStatus = bindStatus;
bindStatus = JavafxBindStatus.UNBOUND;
JFXExpression attr = decompose(tree.attribute);
JFXExpression funcValue = decompose(tree.funcValue);
JFXExpression interpolation = decompose(tree.interpolation);
// Note: funcValue takes the place of value
JFXInterpolateValue res = fxmake.at(tree.pos).InterpolateValue(attr, funcValue, interpolation);
res.sym = tree.sym;
result = res;
bindStatus = prevBindStatus;
}
public void visitKeyFrameLiteral(JFXKeyFrameLiteral tree) {
JFXExpression start = decompose(tree.start);
List<JFXExpression> values = decomposeComponents(tree.values);
JFXExpression trigger = decompose(tree.trigger);
result = fxmake.at(tree.pos).KeyFrameLiteral(start, values, trigger);
}
}
| true | true | public void visitSelect(JFXSelect tree) {
DiagnosticPosition diagPos = tree.pos();
Symbol sym = tree.sym;
Symbol selectSym = JavafxTreeInfo.symbolFor(tree.selected);
if (selectSym != null
&& ((selectSym.kind == Kinds.TYP && sym.kind != Kinds.MTH)
|| selectSym.name == names._this)) {
// Select is just via "this" -- make it a simple Ident
//TODO: move this to lower
JFXIdent res = fxmake.at(diagPos).Ident(sym.name);
res.sym = sym;
result = res;
} else {
JFXExpression selected;
if ((selectSym != null && (selectSym.kind == Kinds.TYP || selectSym.name == names._super || selectSym.name == names._class))) {
// Referenced is static, or qualified super access
// then selected is a class reference
selected = decompose(tree.selected);
} else {
JavafxBindStatus oldBindStatus = bindStatus;
if (bindStatus == JavafxBindStatus.BIDIBIND) bindStatus = JavafxBindStatus.UNIDIBIND;
/**
* Avoding shreding as an optimization: if the select expression's selected part
* is a JFXIdent and that identifier is an instance var of current class, then we
* don't have to shred it.
*
* Example:
*
* class Person {
* var name : String;
* var age: Integer;
* }
*
* class Test {
* var p : Person;
* var name = bind p.name; // instance var "p" in bind-select
* var age = bind p.age; // same instance var "p" in bind-select
* }
*
* In this case we can avoid shreding and generating two synthetic variables for
* bind select expressions p.name, p.age.
*
* Special cases:
*
* (1) sequences are always shreded
* (2) non-variable access (eg. select expression selects method)
*
* TODO: for some reason this optimization does not work if the same selected part is
* used by a unidirectional and bidirectional bind expressions. For now, filtering out
* bidirectional cases. We need to revisit that mystery. Also. I've to oldBindStatus
* because bindStatus has been set to UNIDIBIND in the previous statement.
*/
if (oldBindStatus == JavafxBindStatus.UNIDIBIND &&
tree.selected instanceof JFXIdent &&
!types.isSequence(tree.type) &&
sym instanceof VarSymbol) {
if (selectSym.owner == currentClass && !(selectSym.isStatic() ^ inScriptLevel)) {
selected = tree.selected;
} else if (shrededSelectors.containsKey(selectSym)) {
selected = shrededSelectors.get(selectSym);
} else {
selected = shred(tree.selected);
shrededSelectors.put(selectSym, selected);
}
} else {
selected = shred(tree.selected);
}
bindStatus = oldBindStatus;
}
JFXSelect res = fxmake.at(diagPos).Select(selected, sym.name);
res.sym = sym;
if (bindStatus.isBound() && types.isSequence(tree.type)) {
// Add a size field to hold the previous size on selector switch
JFXVar v = makeSizeVar(diagPos, 0);
v.sym.flags_field |= JavafxFlags.VARMARK_BARE_SYNTH | Flags.PRIVATE;
res.boundSize = v;
}
result = res;
}
}
| public void visitSelect(JFXSelect tree) {
DiagnosticPosition diagPos = tree.pos();
Symbol sym = tree.sym;
Symbol selectSym = JavafxTreeInfo.symbolFor(tree.selected);
if (selectSym != null
&& ((selectSym.kind == Kinds.TYP && sym.kind != Kinds.MTH)
|| selectSym.name == names._this)) {
// Select is just via "this" -- make it a simple Ident
//TODO: move this to lower
JFXIdent res = fxmake.at(diagPos).Ident(sym.name);
res.sym = sym;
result = res;
} else {
JFXExpression selected;
if ((selectSym != null && (selectSym.kind == Kinds.TYP || selectSym.name == names._super || selectSym.name == names._class))) {
// Referenced is static, or qualified super access
// then selected is a class reference
selected = decompose(tree.selected);
} else {
JavafxBindStatus oldBindStatus = bindStatus;
if (bindStatus == JavafxBindStatus.BIDIBIND) bindStatus = JavafxBindStatus.UNIDIBIND;
/**
* Avoding shreding as an optimization: if the select expression's selected part
* is a JFXIdent and that identifier is an instance var of current class, then we
* don't have to shred it.
*
* Example:
*
* class Person {
* var name : String;
* var age: Integer;
* }
*
* class Test {
* var p : Person;
* var name = bind p.name; // instance var "p" in bind-select
* var age = bind p.age; // same instance var "p" in bind-select
* }
*
* In this case we can avoid shreding and generating two synthetic variables for
* bind select expressions p.name, p.age.
*
* Special cases:
*
* (1) sequences are always shreded
* (2) non-variable access (eg. select expression selects method)
*
* TODO: for some reason this optimization does not work if the same selected part is
* used by a unidirectional and bidirectional bind expressions. For now, filtering out
* bidirectional cases. We need to revisit that mystery. Also. I've to oldBindStatus
* because bindStatus has been set to UNIDIBIND in the previous statement.
*/
if (false && oldBindStatus == JavafxBindStatus.UNIDIBIND &&
tree.selected instanceof JFXIdent &&
!types.isSequence(tree.type) &&
sym instanceof VarSymbol) {
if (selectSym.owner == currentClass && !(selectSym.isStatic() ^ inScriptLevel)) {
selected = tree.selected;
} else if (shrededSelectors.containsKey(selectSym)) {
selected = shrededSelectors.get(selectSym);
} else {
selected = shred(tree.selected);
shrededSelectors.put(selectSym, selected);
}
} else {
selected = shred(tree.selected);
}
bindStatus = oldBindStatus;
}
JFXSelect res = fxmake.at(diagPos).Select(selected, sym.name);
res.sym = sym;
if (bindStatus.isBound() && types.isSequence(tree.type)) {
// Add a size field to hold the previous size on selector switch
JFXVar v = makeSizeVar(diagPos, 0);
v.sym.flags_field |= JavafxFlags.VARMARK_BARE_SYNTH | Flags.PRIVATE;
res.boundSize = v;
}
result = res;
}
}
|
diff --git a/java/com/abreen/dungeon/worker/DungeonProtocol.java b/java/com/abreen/dungeon/worker/DungeonProtocol.java
index 2b1483b..096bc62 100644
--- a/java/com/abreen/dungeon/worker/DungeonProtocol.java
+++ b/java/com/abreen/dungeon/worker/DungeonProtocol.java
@@ -1,326 +1,327 @@
package com.abreen.dungeon.worker;
import java.util.*;
import com.abreen.dungeon.exceptions.*;
import com.abreen.dungeon.model.*;
import com.abreen.dungeon.DungeonServer;
public class DungeonProtocol {
public static final double VERSION = 0.1;
private static final String CHEVRONS = ">>> ";
private static final String BANGS = "!!! ";
private static enum Action {
/**
* The action a player issues to move from one room to another.
*/
MOVE("m", "move", "go", "walk"),
/**
* The action a player issues to take an item from the room. The item
* is then removed from the room and placed in the player's inventory.
*/
TAKE("t", "take", "get"),
/**
* The action a player issues to drop an item from the player's inventory.
* The item is then placed in the room.
*/
DROP("d", "drop"),
/**
* The action a player issues to give an item to another player. The
* two players must be in the same room. The item is removed from the
* giving player's inventory and then placed in the receiving player's
* inventory.
*/
GIVE("g", "give"),
/**
* The action a player issues to be sent a description of the current
* room or an item in the room or the player's inventory.
*/
LOOK("l", "look", "describe"),
/**
* The action a player issues to be sent a list of items currently in
* the player's inventory.
*/
INVENTORY("i", "inventory"),
/**
* The action a player issues to be sent a list of exits out of the
* current room.
*/
EXITS("e", "exits"),
/**
* The action a player issues to speak. The message is then sent to
* other players in the current room.
*/
SAY("s", "say", "talk"),
/**
* The action a player issues to yell. The message is sent to players
* in the current room and adjacent rooms.
*/
YELL("y", "yell", "shout"),
/**
* The action a player issues to whisper to another player. The other
* player must be in the same room. The message is only seen by the
* receiving player.
*/
WHISPER("w", "whisper"),
/**
* The action a player issues to use an item in the room or in the
* player's inventory. The item must be a UseableItem.
*
* @see UseableItem
*/
USE("u", "use"),
/**
* The command a player issues to get a listing of acceptable commands.
*/
HELP("help"),
/**
* The command a player issues to get a listing of currently connected
* players.
*/
WHO("who"),
/**
* The command a player issues to disconnect.
*/
QUIT("quit");
private String[] keys;
Action(String... keys) {
this.keys = keys;
}
public boolean isAction(String str) {
for(String key : keys) {
if(key.equalsIgnoreCase(str)) {
return true;
}
}
return false;
}
}
private static DungeonUniverse u = DungeonServer.universe;
private static DungeonDispatcher d = DungeonServer.events;
private static DungeonNarrator n = DungeonServer.narrator;
/**
* Processes the supplied input from the supplied player's point of
* view. This method calls mutating methods in the DungeonUniverse
* class. It is the way connection threads attempt to modify or
* otherwise access the universe.
*
* @param p The player object who sent the input string
* @param input The input string received from the connected player
* @throws PlayerIsQuittingException
* @see DungeonUniverse
*/
public static void process(Player p, String input)
throws PlayerIsQuittingException {
if (input.isEmpty()) return;
String[] tokens = input.split("\\s");
Action action = null;
for (Action a : Action.values()) {
if (a.isAction(tokens[0])) {
action = a;
break;
}
}
if (action == null) {
String unsure = "Unsure what is meant by '" + tokens[0] + "'. Try " +
"'help' to get a list of valid actions.";
d.addNotificationEvent(p.getWriter(), unsure);
+ return;
}
switch (action) {
case QUIT: throw new PlayerIsQuittingException();
case MOVE: processMove(p, tokens); return;
case TAKE: processTake(p, tokens); return;
case DROP: processDrop(p, tokens); return;
case GIVE: processGive(p, tokens); return;
case LOOK: processLook(p, tokens); return;
case INVENTORY: processInventory(p, tokens); return;
case EXITS: processExits(p, tokens); return;
case SAY: processSay(p, tokens); return;
case YELL: processYell(p, tokens); return;
case WHISPER: processWhisper(p, tokens); return;
case USE: processUse(p, tokens); return;
case WHO: processWho(p, tokens); return;
case HELP:
default:
for (String s : usage())
d.addNotificationEvent(p.getWriter(), s);
return;
}
}
private static void processDrop(Player p, String[] tokens) {
}
private static void processExits(Player p, String[] tokens) {
}
private static void processGive(Player p, String[] tokens) {
}
private static void processInventory(Player p, String[] tokens) {
}
private static void processLook(Player p, String[] tokens) {
String tokensAfter = getTokensAfterAction(tokens);
try {
if (tokensAfter == null) {
u.look(p, "here");
} else {
u.look(p, tokensAfter);
}
} catch (NoSuchItemException e) {
String oops = "There's no such item by the name '" + tokensAfter
+ "' in the room or your inventory.";
d.addNotificationEvent(p.getWriter(), oops);
}
}
private static void processMove(Player p, String[] tokens) {
try {
Room here = p.here();
Room there = u.movePlayer(p, tokens[1]);
/*
* Do narration for players watching this player leave.
* Because getPlayersInRoom would include the moving player if it
* were called before the player moves, we send the narration here.
*/
Iterator<Player> playersHere = u.getPlayersInRoom(here);
int numPlayersHere = u.getNumberOfPlayersInRoom(here);
String moveTo = n.narrateMoveToRoom(p.toString(), there.toString());
d.addNarrationEvent(
DungeonDispatcher.playerIteratorToWriterArray(playersHere,
numPlayersHere), moveTo);
} catch (NoSuchDirectionException e) {
String oops = "Unsure which direction is meant "
+ "by '" + tokens[1] + "'. The following directions "
+ "are recognized: " + Space.listValidDirections();
d.addNotificationEvent(p.getWriter(), oops);
} catch (NoSuchExitException e) {
String oops = "That's not an exit. Try 'exits' for a list of ways "
+ "out.";
d.addNotificationEvent(p.getWriter(), oops);
} catch (LockedDoorException e) {
String oops = "The door is locked, and you don't have the key.";
d.addNotificationEvent(p.getWriter(), oops);
} catch (ArrayIndexOutOfBoundsException e) {
String oops = "Specify a direction in which to move.";
d.addNotificationEvent(p.getWriter(), oops);
}
}
private static void processSay(Player p, String[] tokens) {
String tokensAfter = getTokensAfterAction(tokens);
u.say(p, tokensAfter);
}
private static void processTake(Player p, String[] tokens) {
}
private static void processUse(Player p, String[] tokens) {
}
private static void processWhisper(Player p, String[] tokens) {
}
private static void processWho(Player p, String[] tokens) {
}
private static void processYell(Player p, String[] tokens) {
String tokensAfter = getTokensAfterAction(tokens);
if (tokensAfter == null) {
String oops = "Supply something to yell.";
d.addNotificationEvent(p.getWriter(), oops);
return;
}
u.yell(p, tokensAfter);
}
/*
* Returns all the tokens after the action as a space-separated
* string. Returns null if there are no tokens after the action.
*/
private static String getTokensAfterAction(String[] tokens) {
if (tokens.length < 2)
return null;
int i;
if (tokens[1].equalsIgnoreCase("the"))
i = 2;
else
i = 1;
String obj = "";
for ( ; i < tokens.length; i++) {
obj += tokens[i];
if (i != (tokens.length - 1))
obj += " ";
}
return obj;
}
private static String[] usage() {
String[] z =
{ "ACTION OBJECT INDIRECT OBJECT",
"[{m,move,go,walk}] <direction>",
"{t,take,get} <object>",
"{d,drop}",
"{g,give} <object> to <player>",
"{l,look,describe} [<object>]",
"{i,inventory}",
"{e,exits}",
"{s,say,talk} [<string>]",
"{y,yell,shout} <string>",
"{w,whisper} <string> to <player>",
"{u,use} <object in inventory>",
"SERVER ACTION",
"help",
"who",
"quit" };
return z;
}
}
| true | true | public static void process(Player p, String input)
throws PlayerIsQuittingException {
if (input.isEmpty()) return;
String[] tokens = input.split("\\s");
Action action = null;
for (Action a : Action.values()) {
if (a.isAction(tokens[0])) {
action = a;
break;
}
}
if (action == null) {
String unsure = "Unsure what is meant by '" + tokens[0] + "'. Try " +
"'help' to get a list of valid actions.";
d.addNotificationEvent(p.getWriter(), unsure);
}
switch (action) {
case QUIT: throw new PlayerIsQuittingException();
case MOVE: processMove(p, tokens); return;
case TAKE: processTake(p, tokens); return;
case DROP: processDrop(p, tokens); return;
case GIVE: processGive(p, tokens); return;
case LOOK: processLook(p, tokens); return;
case INVENTORY: processInventory(p, tokens); return;
case EXITS: processExits(p, tokens); return;
case SAY: processSay(p, tokens); return;
case YELL: processYell(p, tokens); return;
case WHISPER: processWhisper(p, tokens); return;
case USE: processUse(p, tokens); return;
case WHO: processWho(p, tokens); return;
case HELP:
default:
for (String s : usage())
d.addNotificationEvent(p.getWriter(), s);
return;
}
}
| public static void process(Player p, String input)
throws PlayerIsQuittingException {
if (input.isEmpty()) return;
String[] tokens = input.split("\\s");
Action action = null;
for (Action a : Action.values()) {
if (a.isAction(tokens[0])) {
action = a;
break;
}
}
if (action == null) {
String unsure = "Unsure what is meant by '" + tokens[0] + "'. Try " +
"'help' to get a list of valid actions.";
d.addNotificationEvent(p.getWriter(), unsure);
return;
}
switch (action) {
case QUIT: throw new PlayerIsQuittingException();
case MOVE: processMove(p, tokens); return;
case TAKE: processTake(p, tokens); return;
case DROP: processDrop(p, tokens); return;
case GIVE: processGive(p, tokens); return;
case LOOK: processLook(p, tokens); return;
case INVENTORY: processInventory(p, tokens); return;
case EXITS: processExits(p, tokens); return;
case SAY: processSay(p, tokens); return;
case YELL: processYell(p, tokens); return;
case WHISPER: processWhisper(p, tokens); return;
case USE: processUse(p, tokens); return;
case WHO: processWho(p, tokens); return;
case HELP:
default:
for (String s : usage())
d.addNotificationEvent(p.getWriter(), s);
return;
}
}
|
diff --git a/src/main/java/archimulator/sim/uncore/cache/replacement/partitioned/SimpleStaticPartitionedLRUPolicy.java b/src/main/java/archimulator/sim/uncore/cache/replacement/partitioned/SimpleStaticPartitionedLRUPolicy.java
index 272c07fa..62c3e3f6 100644
--- a/src/main/java/archimulator/sim/uncore/cache/replacement/partitioned/SimpleStaticPartitionedLRUPolicy.java
+++ b/src/main/java/archimulator/sim/uncore/cache/replacement/partitioned/SimpleStaticPartitionedLRUPolicy.java
@@ -1,131 +1,131 @@
/*******************************************************************************
* Copyright (c) 2010-2013 by Min Cai ([email protected]).
*
* This file is part of the Archimulator multicore architectural simulator.
*
* Archimulator 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.
*
* Archimulator 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 Archimulator. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package archimulator.sim.uncore.cache.replacement.partitioned;
import archimulator.sim.uncore.MemoryHierarchyAccess;
import archimulator.sim.uncore.cache.CacheAccess;
import archimulator.sim.uncore.cache.CacheLine;
import archimulator.sim.uncore.cache.EvictableCache;
import archimulator.sim.uncore.cache.partitioning.Partitioner;
import archimulator.sim.uncore.cache.replacement.LRUPolicy;
import net.pickapack.action.Predicate;
import net.pickapack.util.Pair;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import static archimulator.sim.uncore.cache.partitioning.mlpAware.MLPAwareCachePartitioningHelper.getThreadIdentifier;
/**
* Simple static partitioned least recently used (LRU) policy.
*
* @param <StateT> the state type of the parent evictable cache
* @author Min Cai
*/
public class SimpleStaticPartitionedLRUPolicy<StateT extends Serializable> extends LRUPolicy<StateT> implements Partitioner {
private List<Integer> partitions;
private List<Pair<Integer,Integer>> partitionBoundaries;
/**
* Create a simple static partitioned least recently used (LRU) policy for the specified evictable cache.
*
* @param cache the parent evictable cache
*/
public SimpleStaticPartitionedLRUPolicy(EvictableCache<StateT> cache) {
this(cache, cache.getExperiment().getArchitecture().getNumMainThreadWaysInStaticPartitionedLRUPolicy());
}
/**
* Create a simple static partitioned least recently used (LRU) policy for the specified evictable cache.
*
* @param cache the parent evictable cache
*/
public SimpleStaticPartitionedLRUPolicy(EvictableCache<StateT> cache, final int numMainThreadWays) {
super(cache);
this.partitions = new ArrayList<Integer>() {{
add(numMainThreadWays);
add(getCache().getAssociativity() - numMainThreadWays);
}};
this.partitionBoundaries = new ArrayList<Pair<Integer, Integer>>();
int previousWay = 0;
int currentWay = 0;
for (Integer partition : this.partitions) {
- previousWay = currentWay + 1;
+ previousWay = currentWay;
currentWay += partition;
- this.partitionBoundaries.add(new Pair<Integer, Integer>(previousWay, currentWay));
+ this.partitionBoundaries.add(new Pair<Integer, Integer>(previousWay, currentWay - 1));
}
}
@Override
public CacheAccess<StateT> newMiss(MemoryHierarchyAccess access, int set, int address) {
int tag = this.getCache().getTag(address);
Pair<Integer, Integer> partitionBoundary = doGetPartitionBoundary(getThreadIdentifier(access.getThread()));
for(int way = partitionBoundary.getFirst(); way <= partitionBoundary.getSecond(); way++) {
CacheLine<StateT> line = this.getCache().getLine(set, way);
if (line.getState() == line.getInitialState()) {
return new CacheAccess<StateT>(this.getCache(), access, set, way, tag);
}
}
return this.handleReplacement(access, set, tag);
}
/**
* Handle a cache replacement.
*
* @param access the memory hierarchy access
* @param set the set index
* @param tag the tag
* @return the newly created cache access object
*/
@Override
public CacheAccess<StateT> handleReplacement(MemoryHierarchyAccess access, int set, int tag) {
Pair<Integer, Integer> partitionBoundary = doGetPartitionBoundary(getThreadIdentifier(access.getThread()));
for (int stackPosition = this.getCache().getAssociativity() - 1; stackPosition >= 0; stackPosition--) {
int way = this.getWayInStackPosition(set, stackPosition);
if(way >= partitionBoundary.getFirst() && way <= partitionBoundary.getSecond()) {
return new CacheAccess<StateT>(this.getCache(), access, set, way, tag);
}
}
throw new IllegalArgumentException();
}
private Pair<Integer, Integer> doGetPartitionBoundary(int set) {
return partitionBoundaries.get(set);
}
@Override
public List<Integer> getPartition() {
return partitions;
}
@Override
public void setShouldIncludePredicate(Predicate<Integer> shouldIncludePredicate) {
}
}
| false | true | public SimpleStaticPartitionedLRUPolicy(EvictableCache<StateT> cache, final int numMainThreadWays) {
super(cache);
this.partitions = new ArrayList<Integer>() {{
add(numMainThreadWays);
add(getCache().getAssociativity() - numMainThreadWays);
}};
this.partitionBoundaries = new ArrayList<Pair<Integer, Integer>>();
int previousWay = 0;
int currentWay = 0;
for (Integer partition : this.partitions) {
previousWay = currentWay + 1;
currentWay += partition;
this.partitionBoundaries.add(new Pair<Integer, Integer>(previousWay, currentWay));
}
}
| public SimpleStaticPartitionedLRUPolicy(EvictableCache<StateT> cache, final int numMainThreadWays) {
super(cache);
this.partitions = new ArrayList<Integer>() {{
add(numMainThreadWays);
add(getCache().getAssociativity() - numMainThreadWays);
}};
this.partitionBoundaries = new ArrayList<Pair<Integer, Integer>>();
int previousWay = 0;
int currentWay = 0;
for (Integer partition : this.partitions) {
previousWay = currentWay;
currentWay += partition;
this.partitionBoundaries.add(new Pair<Integer, Integer>(previousWay, currentWay - 1));
}
}
|
diff --git a/src/simpleserver/Player.java b/src/simpleserver/Player.java
index 6196c7a..3766cf6 100644
--- a/src/simpleserver/Player.java
+++ b/src/simpleserver/Player.java
@@ -1,992 +1,998 @@
/*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* 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 simpleserver;
import static simpleserver.lang.Translations.t;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.Socket;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.xml.sax.SAXException;
import simpleserver.Coordinate.Dimension;
import simpleserver.bot.BotController.ConnectException;
import simpleserver.bot.Giver;
import simpleserver.bot.Teleporter;
import simpleserver.command.ExternalCommand;
import simpleserver.command.PlayerCommand;
import simpleserver.config.KitList.Kit;
import simpleserver.config.data.Stats.StatField;
import simpleserver.config.xml.Area;
import simpleserver.config.xml.CommandConfig;
import simpleserver.config.xml.CommandConfig.Forwarding;
import simpleserver.config.xml.Event;
import simpleserver.config.xml.Group;
import simpleserver.config.xml.Permission;
import simpleserver.message.AbstractChat;
import simpleserver.message.Chat;
import simpleserver.message.GlobalChat;
import simpleserver.stream.Encryption;
import simpleserver.stream.Encryption.ClientEncryption;
import simpleserver.stream.Encryption.ServerEncryption;
import simpleserver.stream.StreamTunnel;
public class Player {
private final long connected;
private final Socket extsocket;
private final Server server;
private Socket intsocket;
private StreamTunnel serverToClient;
private StreamTunnel clientToServer;
private Watchdog watchdog;
public ServerEncryption serverEncryption = new Encryption.ServerEncryption();
public ClientEncryption clientEncryption = new Encryption.ClientEncryption();
private String name = null;
private String renameName = null;
private String connectionHash;
private boolean closed = false;
private boolean isKicked = false;
private Action attemptedAction;
private boolean instantDestroy = false;
private boolean godMode = false;
private String kickMsg = null;
public Position position;
private Position deathPlace;
private short health = 0;
private short experience = 0;
private int group = 0;
private int entityId = 0;
private Group groupObject = null;
private boolean isRobot = false;
// player is not authenticated with minecraft.net:
private boolean guest = false;
private boolean usedAuthenticator = false;
private int blocksPlaced = 0;
private int blocksDestroyed = 0;
private Player reply = null;
private String lastCommand = "";
private AbstractChat chatType;
private Queue<String> messages = new ConcurrentLinkedQueue<String>();
private Queue<String> forwardMessages = new ConcurrentLinkedQueue<String>();
private Queue<PlayerVisitRequest> visitreqs = new ConcurrentLinkedQueue<PlayerVisitRequest>();
private Coordinate chestPlaced;
private Coordinate chestOpened;
private String nextChestName;
// temporary coordinate storage for /myarea command
public Coordinate areastart;
public Coordinate areaend;
private long lastTeleport;
private short experienceLevel;
public ConcurrentHashMap<String, String> vars; // temporary player-scope
// Script variables
private long lastEvent;
private HashSet<Area> currentAreas = new HashSet<Area>();
public Player(Socket inc, Server parent) {
connected = System.currentTimeMillis();
position = new Position();
server = parent;
chatType = new GlobalChat(this);
extsocket = inc;
vars = new ConcurrentHashMap<String, String>();
if (server.isRobot(getIPAddress())) {
System.out.println("[SimpleServer] Robot Heartbeat: " + getIPAddress()
+ ".");
isRobot = true;
} else {
System.out.println("[SimpleServer] IP Connection from " + getIPAddress()
+ "!");
}
if (server.isIPBanned(getIPAddress())) {
System.out.println("[SimpleServer] IP " + getIPAddress() + " is banned!");
cleanup();
return;
}
server.requestTracker.addRequest(getIPAddress());
try {
InetAddress localAddress = InetAddress.getByName(Server.addressFactory.getNextAddress());
intsocket = new Socket(InetAddress.getByName(null),
server.options.getInt("internalPort"),
localAddress, 0);
} catch (Exception e) {
try {
intsocket = new Socket(InetAddress.getByName(null), server.options.getInt("internalPort"));
} catch (Exception E) {
e.printStackTrace();
if (server.config.properties.getBoolean("exitOnFailure")) {
server.stop();
} else {
server.restart();
}
cleanup();
return;
}
}
watchdog = new Watchdog();
try {
serverToClient = new StreamTunnel(intsocket.getInputStream(),
extsocket.getOutputStream(), true, this);
clientToServer = new StreamTunnel(extsocket.getInputStream(),
intsocket.getOutputStream(), false,
this);
} catch (IOException e) {
e.printStackTrace();
cleanup();
return;
}
if (isRobot) {
server.addRobotPort(intsocket.getLocalPort());
}
watchdog.start();
}
public boolean setName(String name) {
renameName = server.data.players.getRenameName(name);
name = name.trim();
if (name.length() == 0 || this.name != null) {
kick(t("Invalid Name!"));
return false;
}
if (name == "Player") {
kick(t("Too many guests in server!"));
return false;
}
if (!guest && server.config.properties.getBoolean("useWhitelist")
&& !server.whitelist.isWhitelisted(name)) {
kick(t("You are not whitelisted!"));
return false;
}
if (server.playerList.findPlayerExact(name) != null) {
kick(t("Player already in server!"));
return false;
}
this.name = name;
updateGroup();
watchdog.setName("PlayerWatchdog-" + name);
server.connectionLog("player", extsocket, name);
if (server.numPlayers() == 0) {
server.time.set();
}
server.playerList.addPlayer(this);
return true;
}
public String getName() {
return renameName;
}
public String getName(boolean original) {
return (original) ? name : renameName;
}
public String getRealName() {
return server.data.players.getRealName(name);
}
public void updateRealName(String name) {
server.data.players.setRealName(name);
}
public String getConnectionHash() {
if (connectionHash == null) {
connectionHash = server.nextHash();
}
return connectionHash;
}
public String getLoginHash() throws NoSuchAlgorithmException, UnsupportedEncodingException {
return clientEncryption.getLoginHash(getConnectionHash());
}
public double distanceTo(Player player) {
return Math.sqrt(Math.pow(x() - player.x(), 2) + Math.pow(y() - player.y(), 2) + Math.pow(z() - player.z(), 2));
}
public long getConnectedAt() {
return connected;
}
public boolean isAttemptLock() {
return attemptedAction == Action.Lock;
}
public void setAttemptedAction(Action action) {
attemptedAction = action;
}
public boolean instantDestroyEnabled() {
return instantDestroy;
}
public void toggleInstantDestroy() {
instantDestroy = !instantDestroy;
}
public Server getServer() {
return server;
}
public void setChat(AbstractChat chat) {
chatType = chat;
}
public String getChatRoom() {
return chatType.toString();
}
public void sendMessage(String message) {
sendMessage(chatType, message);
}
public void sendMessage(String message, boolean build) {
sendMessage(chatType, message, build);
}
public void sendMessage(Chat messageType, String message) {
server.getMessager().propagate(messageType, message);
}
public void sendMessage(Chat messageType, String message, boolean build) {
server.getMessager().propagate(messageType, message, build);
}
public void forwardMessage(String message) {
forwardMessages.add(message);
}
public boolean hasForwardMessages() {
return !forwardMessages.isEmpty();
}
public boolean hasMessages() {
return !messages.isEmpty();
}
public void addMessage(Color color, String format, Object... args) {
addMessage(color, String.format(format, args));
}
public void addMessage(Color color, String message) {
addMessage(color + message);
}
public void addMessage(String format, Object... args) {
addMessage(String.format(format, args));
}
public void addCaptionedMessage(String caption, String format, Object... args) {
addMessage("%s%s: %s%s", Color.GRAY, caption, Color.WHITE, String.format(format, args));
}
public void addMessage(String msg) {
messages.add(msg);
}
public void addTMessage(Color color, String format, Object... args) {
addMessage(color + t(format, args));
}
public void addTMessage(Color color, String message) {
addMessage(color + t(message));
}
public void addTMessage(String msg) {
addMessage(t(msg));
}
public void addTCaptionedTMessage(String caption, String format, Object... args) {
addMessage("%s%s: %s%s", Color.GRAY, t(caption), Color.WHITE, t(format, args));
}
public void addTCaptionedMessage(String caption, String format, Object... args) {
addMessage("%s%s: %s%s", Color.GRAY, t(caption),
Color.WHITE, String.format(format, args));
}
public String getForwardMessage() {
return forwardMessages.remove();
}
public String getMessage() {
return messages.remove();
}
public void addVisitRequest(Player source) {
visitreqs.add(new PlayerVisitRequest(source));
}
public void handleVisitRequests() {
while (visitreqs.size() > 0) {
PlayerVisitRequest req = visitreqs.remove();
if (System.currentTimeMillis() < req.timestamp + 10000 && server.findPlayerExact(req.source.getName()) != null) {
req.source.addTMessage(Color.GRAY, "Request accepted!");
req.source.teleportTo(this);
}
}
}
public void kick(String reason) {
kickMsg = reason;
isKicked = true;
serverToClient.stop();
clientToServer.stop();
}
public boolean isKicked() {
return isKicked;
}
public void setKicked(boolean b) {
isKicked = b;
}
public String getKickMsg() {
return kickMsg;
}
public boolean isMuted() {
return server.mutelist.isMuted(name);
}
public boolean isRobot() {
return isRobot;
}
public boolean godModeEnabled() {
return godMode;
}
public void toggleGodMode() {
godMode = !godMode;
}
public int getEntityId() {
return entityId;
}
public void setEntityId(int readInt) {
entityId = readInt;
}
public int getGroupId() {
return group;
}
public Group getGroup() {
return groupObject;
}
public void setGuest(boolean guest) {
this.guest = guest;
}
public boolean isGuest() {
return guest;
}
public void setUsedAuthenticator(boolean usedAuthenticator) {
this.usedAuthenticator = usedAuthenticator;
}
public boolean usedAuthenticator() {
return usedAuthenticator;
}
public String getIPAddress() {
return extsocket.getInetAddress().getHostAddress();
}
public InetAddress getInetAddress() {
return extsocket.getInetAddress();
}
public boolean ignoresChestLocks() {
return groupObject.ignoreChestLocks;
}
private void setDeathPlace(Position deathPosition) {
deathPlace = deathPosition;
}
public Position getDeathPlace() {
return deathPlace;
}
public short getHealth() {
return health;
}
public void updateHealth(short health) {
this.health = health;
if (health <= 0) {
setDeathPlace(new Position(position()));
}
}
public short getExperience() {
return experience;
}
public short getExperienceLevel() {
return experienceLevel;
}
public void updateExperience(float bar, short level, short experience) {
experienceLevel = level;
this.experience = experience;
}
public double x() {
return position.x;
}
public double y() {
return position.y;
}
public double z() {
return position.z;
}
public Coordinate position() {
return position.coordinate();
}
public float yaw() {
return position.yaw;
}
public float pitch() {
return position.pitch;
}
public String parseCommand(String message, boolean overridePermissions) {
// TODO: Handle aliases of external commands
if (closed) {
return null;
}
// Repeat last command
if (message.equals(server.getCommandParser().commandPrefix() + "!")) {
message = lastCommand;
} else {
lastCommand = message;
}
String commandName = message.split(" ")[0].substring(1).toLowerCase();
String args = commandName.length() + 1 >= message.length() ? "" : message.substring(commandName.length() + 2);
CommandConfig config = server.config.commands.getTopConfig(commandName);
String originalName = config == null ? commandName : config.originalName;
PlayerCommand command;
if (config == null) {
command = server.getCommandParser().getPlayerCommand(commandName);
if (command != null && !command.hidden()) {
command = null;
}
} else {
command = server.getCommandParser().getPlayerCommand(originalName);
}
if (command == null) {
if (groupObject.forwardUnknownCommands || config != null) {
command = new ExternalCommand(commandName);
} else {
command = server.getCommandParser().getPlayerCommand((String) null);
}
}
if (config != null && !overridePermissions) {
Permission permission = server.config.getCommandPermission(config.name, args, position.coordinate());
if (!permission.contains(this)) {
addTMessage(Color.RED, "Insufficient permission.");
return null;
}
}
try {
if (server.options.getBoolean("enableEvents") && config.event != null) {
Event e = server.eventhost.findEvent(config.event);
if (e != null) {
ArrayList<String> arguments = new ArrayList<String>();
if (!args.equals("")) {
arguments = new ArrayList<String>(java.util.Arrays.asList(args.split("\\s+")));
}
server.eventhost.execute(e, this, true, arguments);
} else {
System.out.println("Error in player command " + originalName + ": Event " + config.event + " not found!");
}
}
} catch (NullPointerException e) {
System.out.println("Error evaluating player command: " + originalName);
}
if (!(command instanceof ExternalCommand) && (config == null || config.forwarding != Forwarding.ONLY)) {
command.execute(this, message);
}
if (command instanceof ExternalCommand) {
- return "/" + originalName + " " + args;
+ // commands with bound events have to be forwarded explicitly
+ // (to prevent unknown command error by server)
+ if (config.event != null && config.forwarding == Forwarding.NONE) {
+ return null;
+ } else {
+ return "/" + originalName + " " + args;
+ }
} else if ((config != null && config.forwarding != Forwarding.NONE) || server.config.properties.getBoolean("forwardAllCommands")) {
return message;
} else {
return null;
}
}
public void execute(Class<? extends PlayerCommand> c) {
execute(c, "");
}
public void execute(Class<? extends PlayerCommand> c, String arguments) {
server.getCommandParser().getPlayerCommand(c).execute(this, "a " + arguments);
}
public void teleportTo(Player target) {
server.runCommand("tp", getName() + " " + target.getName());
}
public void sendMOTD() {
String[] lines = server.motd.getMOTD().split("\\r?\\n");
for (String line : lines) {
addMessage(line);
}
}
public void give(int id, int amount) {
String baseCommand = getName() + " " + id + " ";
for (int c = 0; c < amount / 64; ++c) {
server.runCommand("give", baseCommand + 64);
}
if (amount % 64 != 0) {
server.runCommand("give", baseCommand + amount % 64);
}
}
public void give(int id, short damage, int amount) throws ConnectException {
if (damage == 0) {
give(id, amount);
} else {
Giver giver = new Giver(this);
for (int c = 0; c < amount / 64; ++c) {
giver.add(id, 64, damage);
}
if (amount % 64 != 0) {
giver.add(id, amount % 64, damage);
}
server.bots.connect(giver);
}
}
public void give(Kit kit) throws ConnectException {
Giver giver = new Giver(this);
int invSize = 45;
int slot = invSize;
for (Kit.Entry e : kit.items) {
if (e.damage() == 0) {
give(e.item(), e.amount());
} else {
int restAmount = e.amount();
while (restAmount > 0 && --slot >= 0) {
giver.add(e.item(), Math.min(restAmount, 64), e.damage());
restAmount -= 64;
if (slot == 0) {
slot = invSize;
server.bots.connect(giver);
giver = new Giver(this);
}
}
}
}
if (slot != invSize) {
server.bots.connect(giver);
}
}
public void updateGroup() {
try {
groupObject = server.config.getGroup(this);
} catch (SAXException e) {
System.out.println("[SimpleServer] A player could not be assigned to any group. (" + e + ")");
kick("You could not be asigned to any group.");
return;
}
group = groupObject.id;
}
public void placedBlock() {
blocksPlaced += 1;
}
public void destroyedBlock() {
blocksDestroyed += 1;
}
public Integer[] stats() {
Integer[] stats = new Integer[4];
stats[0] = (int) (System.currentTimeMillis() - connected) / 1000 / 60;
stats[1] = server.data.players.stats.get(this, StatField.PLAY_TIME) + stats[0];
stats[2] = server.data.players.stats.add(this, StatField.BLOCKS_PLACED, blocksPlaced);
stats[3] = server.data.players.stats.add(this, StatField.BLOCKS_DESTROYED, blocksDestroyed);
blocksPlaced = 0;
blocksDestroyed = 0;
server.data.save();
return stats;
}
public void setReply(Player answer) {
// set Player to reply with !reply command
reply = answer;
}
public Player getReply() {
return reply;
}
public void close() {
if (serverToClient != null) {
serverToClient.stop();
}
if (clientToServer != null) {
clientToServer.stop();
}
if (name != null) {
server.authenticator.unbanLogin(this);
if (usedAuthenticator) {
if (guest) {
server.authenticator.releaseGuestName(name);
} else {
server.authenticator.rememberAuthentication(name, getIPAddress());
}
} else if (guest) {
if (isKicked) {
server.authenticator.releaseGuestName(name);
} else {
server.authenticator.rememberGuest(name, getIPAddress());
}
}
server.data.players.stats.add(this, StatField.PLAY_TIME, (int) (System.currentTimeMillis() - connected) / 1000 / 60);
server.data.players.stats.add(this, StatField.BLOCKS_DESTROYED, blocksDestroyed);
server.data.players.stats.add(this, StatField.BLOCKS_PLACED, blocksPlaced);
server.data.save();
server.playerList.removePlayer(this);
name = renameName = null;
}
}
private void cleanup() {
if (!closed) {
closed = true;
entityId = 0;
close();
try {
extsocket.close();
} catch (Exception e) {
}
try {
intsocket.close();
} catch (Exception e) {
}
if (!isRobot) {
System.out.println("[SimpleServer] Socket Closed: "
+ extsocket.getInetAddress().getHostAddress());
}
}
}
private class PlayerVisitRequest {
public Player source;
public long timestamp;
public PlayerVisitRequest(Player source) {
timestamp = System.currentTimeMillis();
this.source = source;
}
}
private final class Watchdog extends Thread {
@Override
public void run() {
while (serverToClient.isAlive() || clientToServer.isAlive()) {
if (!serverToClient.isActive() || !clientToServer.isActive()) {
System.out.println("[SimpleServer] Disconnecting " + getIPAddress()
+ " due to inactivity.");
close();
break;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
}
cleanup();
}
}
public void placingChest(Coordinate coord) {
chestPlaced = coord;
}
public boolean placedChest(Coordinate coordinate) {
return chestPlaced != null && chestPlaced.equals(coordinate);
}
public void openingChest(Coordinate coordinate) {
chestOpened = coordinate;
}
public Coordinate openedChest() {
return chestOpened;
}
public void setChestName(String name) {
nextChestName = name;
}
public String nextChestName() {
return nextChestName;
}
public enum Action {
Lock, Unlock, Rename;
}
public boolean isAttemptingUnlock() {
return attemptedAction == Action.Unlock;
}
public void setDimension(Dimension dimension) {
position.updateDimension(dimension);
}
public Dimension getDimension() {
return position.dimension();
}
public void teleport(Coordinate coordinate) throws ConnectException, IOException {
teleport(new Position(coordinate));
}
public void teleport(Position position) throws ConnectException, IOException {
if (position.dimension() == getDimension()) {
server.bots.connect(new Teleporter(this, position));
} else {
addTMessage(Color.RED, "You're not in the same dimension as the specified warppoint.");
}
}
public void teleportSelf(Coordinate coordinate) {
teleportSelf(new Position(coordinate));
}
public void teleportSelf(Position position) {
try {
teleport(position);
} catch (Exception e) {
addTMessage(Color.RED, "Teleporting failed.");
return;
}
lastTeleport = System.currentTimeMillis();
}
private int cooldownLeft() {
int cooldown = getGroup().cooldown();
if (lastTeleport > System.currentTimeMillis() - cooldown) {
return (int) (cooldown - System.currentTimeMillis() + lastTeleport);
} else {
return 0;
}
}
public synchronized void teleportWithWarmup(Coordinate coordinate) {
teleportWithWarmup(new Position(coordinate));
}
public synchronized void teleportWithWarmup(Position position) {
int cooldown = cooldownLeft();
if (lastTeleport < 0) {
addTMessage(Color.RED, "You are already waiting for a teleport.");
} else if (cooldown > 0) {
addTMessage(Color.RED, "You have to wait %d seconds before you can teleport again.", cooldown / 1000);
} else {
int warmup = getGroup().warmup();
if (warmup > 0) {
lastTeleport = -1;
Timer timer = new Timer();
timer.schedule(new Warmup(position), warmup);
addTMessage(Color.GRAY, "You will be teleported in %s seconds.", warmup / 1000);
} else {
teleportSelf(position);
}
}
}
public void checkAreaEvents() {
HashSet<Area> areas = new HashSet<Area>(server.config.dimensions.areas(position()));
HashSet<Area> areasCopy = new HashSet<Area>(areas);
HashSet<Area> oldAreas = currentAreas;
areasCopy.removeAll(oldAreas); // -> now contains only newly entered areas
oldAreas.removeAll(areas); // -> now contains only areas not present anymore
for (Area a : areasCopy) { // run area onenter events
if (a.event == null) {
continue;
}
Event e = server.eventhost.findEvent(a.event);
if (e != null) {
ArrayList<String> args = new ArrayList<String>();
args.add("enter");
args.add(a.name);
server.eventhost.execute(e, this, true, args);
} else {
System.out.println("Error in area " + a.name + "/event: Event " + a.event + " not found!");
}
}
for (Area a : oldAreas) { // run area onleave events
if (a.event == null) {
continue;
}
Event e = server.eventhost.findEvent(a.event);
if (e != null) {
ArrayList<String> args = new ArrayList<String>();
args.add("leave");
args.add(a.name);
server.eventhost.execute(e, this, true, args);
} else {
System.out.println("Error in area " + a.name + "/event: Event " + a.event + " not found!");
}
}
currentAreas = areas;
}
public void checkLocationEvents() {
checkAreaEvents();
long currtime = System.currentTimeMillis();
if (currtime < lastEvent + 500) {
return;
}
Iterator<Event> it = server.eventhost.events.keySet().iterator();
while (it.hasNext()) {
Event ev = it.next();
if (!ev.type.equals("plate") || ev.coordinate == null) {
continue;
}
if (position.coordinate().equals(ev.coordinate)) { // matching -> execute
server.eventhost.execute(ev, this, false, null);
lastEvent = currtime;
}
}
}
public void checkButtonEvents(Coordinate c) {
long currtime = System.currentTimeMillis();
if (currtime < lastEvent + 500) {
return;
}
Iterator<Event> it = server.eventhost.events.keySet().iterator();
while (it.hasNext()) {
Event ev = it.next();
if (!ev.type.equals("button") || ev.coordinate == null) {
continue;
}
if ((new Coordinate(c.x(), c.y(), c.z(), position.dimension())).equals(ev.coordinate)) { // matching
// ->
// execute
server.eventhost.execute(ev, this, false, null);
lastEvent = currtime;
}
}
}
private final class Warmup extends TimerTask {
private final Position position;
private Warmup(Position position) {
super();
this.position = position;
}
@Override
public void run() {
teleportSelf(position);
}
}
}
| true | true | public String parseCommand(String message, boolean overridePermissions) {
// TODO: Handle aliases of external commands
if (closed) {
return null;
}
// Repeat last command
if (message.equals(server.getCommandParser().commandPrefix() + "!")) {
message = lastCommand;
} else {
lastCommand = message;
}
String commandName = message.split(" ")[0].substring(1).toLowerCase();
String args = commandName.length() + 1 >= message.length() ? "" : message.substring(commandName.length() + 2);
CommandConfig config = server.config.commands.getTopConfig(commandName);
String originalName = config == null ? commandName : config.originalName;
PlayerCommand command;
if (config == null) {
command = server.getCommandParser().getPlayerCommand(commandName);
if (command != null && !command.hidden()) {
command = null;
}
} else {
command = server.getCommandParser().getPlayerCommand(originalName);
}
if (command == null) {
if (groupObject.forwardUnknownCommands || config != null) {
command = new ExternalCommand(commandName);
} else {
command = server.getCommandParser().getPlayerCommand((String) null);
}
}
if (config != null && !overridePermissions) {
Permission permission = server.config.getCommandPermission(config.name, args, position.coordinate());
if (!permission.contains(this)) {
addTMessage(Color.RED, "Insufficient permission.");
return null;
}
}
try {
if (server.options.getBoolean("enableEvents") && config.event != null) {
Event e = server.eventhost.findEvent(config.event);
if (e != null) {
ArrayList<String> arguments = new ArrayList<String>();
if (!args.equals("")) {
arguments = new ArrayList<String>(java.util.Arrays.asList(args.split("\\s+")));
}
server.eventhost.execute(e, this, true, arguments);
} else {
System.out.println("Error in player command " + originalName + ": Event " + config.event + " not found!");
}
}
} catch (NullPointerException e) {
System.out.println("Error evaluating player command: " + originalName);
}
if (!(command instanceof ExternalCommand) && (config == null || config.forwarding != Forwarding.ONLY)) {
command.execute(this, message);
}
if (command instanceof ExternalCommand) {
return "/" + originalName + " " + args;
} else if ((config != null && config.forwarding != Forwarding.NONE) || server.config.properties.getBoolean("forwardAllCommands")) {
return message;
} else {
return null;
}
}
| public String parseCommand(String message, boolean overridePermissions) {
// TODO: Handle aliases of external commands
if (closed) {
return null;
}
// Repeat last command
if (message.equals(server.getCommandParser().commandPrefix() + "!")) {
message = lastCommand;
} else {
lastCommand = message;
}
String commandName = message.split(" ")[0].substring(1).toLowerCase();
String args = commandName.length() + 1 >= message.length() ? "" : message.substring(commandName.length() + 2);
CommandConfig config = server.config.commands.getTopConfig(commandName);
String originalName = config == null ? commandName : config.originalName;
PlayerCommand command;
if (config == null) {
command = server.getCommandParser().getPlayerCommand(commandName);
if (command != null && !command.hidden()) {
command = null;
}
} else {
command = server.getCommandParser().getPlayerCommand(originalName);
}
if (command == null) {
if (groupObject.forwardUnknownCommands || config != null) {
command = new ExternalCommand(commandName);
} else {
command = server.getCommandParser().getPlayerCommand((String) null);
}
}
if (config != null && !overridePermissions) {
Permission permission = server.config.getCommandPermission(config.name, args, position.coordinate());
if (!permission.contains(this)) {
addTMessage(Color.RED, "Insufficient permission.");
return null;
}
}
try {
if (server.options.getBoolean("enableEvents") && config.event != null) {
Event e = server.eventhost.findEvent(config.event);
if (e != null) {
ArrayList<String> arguments = new ArrayList<String>();
if (!args.equals("")) {
arguments = new ArrayList<String>(java.util.Arrays.asList(args.split("\\s+")));
}
server.eventhost.execute(e, this, true, arguments);
} else {
System.out.println("Error in player command " + originalName + ": Event " + config.event + " not found!");
}
}
} catch (NullPointerException e) {
System.out.println("Error evaluating player command: " + originalName);
}
if (!(command instanceof ExternalCommand) && (config == null || config.forwarding != Forwarding.ONLY)) {
command.execute(this, message);
}
if (command instanceof ExternalCommand) {
// commands with bound events have to be forwarded explicitly
// (to prevent unknown command error by server)
if (config.event != null && config.forwarding == Forwarding.NONE) {
return null;
} else {
return "/" + originalName + " " + args;
}
} else if ((config != null && config.forwarding != Forwarding.NONE) || server.config.properties.getBoolean("forwardAllCommands")) {
return message;
} else {
return null;
}
}
|
diff --git a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/AbstractConnectionFactory.java b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/AbstractConnectionFactory.java
index 4c6c62c9aa..2d4a8a1387 100644
--- a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/AbstractConnectionFactory.java
+++ b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/AbstractConnectionFactory.java
@@ -1,455 +1,455 @@
/*
* Copyright 2002-2010 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.springframework.integration.ip.tcp.connection;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.SmartLifecycle;
import org.springframework.core.serializer.Deserializer;
import org.springframework.core.serializer.Serializer;
import org.springframework.integration.ip.tcp.serializer.ByteArrayCrLfSerializer;
import org.springframework.util.Assert;
/**
* Base class for all connection factories.
*
* @author Gary Russell
* @since 2.0
*
*/
public abstract class AbstractConnectionFactory
implements ConnectionFactory, Runnable, SmartLifecycle {
protected Log logger = LogFactory.getLog(this.getClass());
protected final static int DEFAULT_REPLY_TIMEOUT = 10000;
protected String host;
protected int port;
protected TcpListener listener;
protected TcpSender sender;
protected int soTimeout;
private int soSendBufferSize;
private int soReceiveBufferSize;
private boolean soTcpNoDelay;
private int soLinger = -1; // don't set by default
private boolean soKeepAlive;
private int soTrafficClass = -1; // don't set by default
protected Executor taskExecutor;
protected Deserializer<?> deserializer = new ByteArrayCrLfSerializer();
protected Serializer<?> serializer = new ByteArrayCrLfSerializer();
protected TcpMessageMapper mapper = new TcpMessageMapper();
protected boolean singleUse;
protected int poolSize = 5;
protected boolean active;
protected TcpConnectionInterceptorFactoryChain interceptorFactoryChain;
/**
* Sets socket attributes on the socket.
* @param socket The socket.
* @throws SocketException
*/
protected void setSocketAttributes(Socket socket) throws SocketException {
if (this.soTimeout >= 0) {
socket.setSoTimeout(this.soTimeout);
}
if (this.soSendBufferSize > 0) {
socket.setSendBufferSize(this.soSendBufferSize);
}
if (this.soReceiveBufferSize > 0) {
socket.setReceiveBufferSize(this.soReceiveBufferSize);
}
socket.setTcpNoDelay(this.soTcpNoDelay);
if (this.soLinger >= 0) {
socket.setSoLinger(true, this.soLinger);
}
if (this.soTrafficClass >= 0) {
socket.setTrafficClass(this.soTrafficClass);
}
socket.setKeepAlive(this.soKeepAlive);
}
/**
* @return the soTimeout
*/
public int getSoTimeout() {
return soTimeout;
}
/**
* @param soTimeout the soTimeout to set
*/
public void setSoTimeout(int soTimeout) {
this.soTimeout = soTimeout;
}
/**
* @return the soReceiveBufferSize
*/
public int getSoReceiveBufferSize() {
return soReceiveBufferSize;
}
/**
* @param soReceiveBufferSize the soReceiveBufferSize to set
*/
public void setSoReceiveBufferSize(int soReceiveBufferSize) {
this.soReceiveBufferSize = soReceiveBufferSize;
}
/**
* @return the soSendBufferSize
*/
public int getSoSendBufferSize() {
return soSendBufferSize;
}
/**
* @param soSendBufferSize the soSendBufferSize to set
*/
public void setSoSendBufferSize(int soSendBufferSize) {
this.soSendBufferSize = soSendBufferSize;
}
/**
* @return the soTcpNoDelay
*/
public boolean isSoTcpNoDelay() {
return soTcpNoDelay;
}
/**
* @param soTcpNoDelay the soTcpNoDelay to set
*/
public void setSoTcpNoDelay(boolean soTcpNoDelay) {
this.soTcpNoDelay = soTcpNoDelay;
}
/**
* @return the soLinger
*/
public int getSoLinger() {
return soLinger;
}
/**
* @param soLinger the soLinger to set
*/
public void setSoLinger(int soLinger) {
this.soLinger = soLinger;
}
/**
* @return the soKeepAlive
*/
public boolean isSoKeepAlive() {
return soKeepAlive;
}
/**
* @param soKeepAlive the soKeepAlive to set
*/
public void setSoKeepAlive(boolean soKeepAlive) {
this.soKeepAlive = soKeepAlive;
}
/**
* @return the soTrafficClass
*/
public int getSoTrafficClass() {
return soTrafficClass;
}
/**
* @param soTrafficClass the soTrafficClass to set
*/
public void setSoTrafficClass(int soTrafficClass) {
this.soTrafficClass = soTrafficClass;
}
/**
* @return the host
*/
public String getHost() {
return host;
}
/**
* @return the port
*/
public int getPort() {
return port;
}
/**
* Registers a TcpListener to receive messages after
* the payload has been converted from the input data.
* @param listener the TcpListener.
*/
public void registerListener(TcpListener listener) {
Assert.isNull(this.listener, this.getClass().getName() +
" may only be used by one inbound adapter");
this.listener = listener;
}
/**
* Registers a TcpSender; for server sockets, used to
* provide connection information so a sender can be used
* to reply to incoming messages.
* @param sender The sender
*/
public void registerSender(TcpSender sender) {
Assert.isNull(this.sender, this.getClass().getName() +
" may only be used by one outbound adapter");
this.sender = sender;
}
/**
* @param taskExecutor the taskExecutor to set
*/
public void setTaskExecutor(Executor taskExecutor) {
this.taskExecutor = taskExecutor;
}
/**
*
* @param deserializer the deserializer to set
*/
public void setDeserializer(Deserializer<?> deserializer) {
this.deserializer = deserializer;
}
/**
*
* @param serializer the serializer to set
*/
public void setSerializer(Serializer<?> serializer) {
this.serializer = serializer;
}
/**
*
* @param mapper the mapper to set; defaults to a {@link TcpMessageMapper}
*/
public void setMapper(TcpMessageMapper mapper) {
this.mapper = mapper;
}
/**
* @return the singleUse
*/
public boolean isSingleUse() {
return singleUse;
}
/**
* If true, sockets created by this factory will be used once.
* @param singleUse
*/
public void setSingleUse(boolean singleUse) {
this.singleUse = singleUse;
}
public void setPoolSize(int poolSize) {
this.poolSize = poolSize;
}
public void setInterceptorFactoryChain(TcpConnectionInterceptorFactoryChain interceptorFactoryChain) {
this.interceptorFactoryChain = interceptorFactoryChain;
}
/**
* Closes the server.
*/
public abstract void close();
/**
* Creates a taskExecutor (if one was not provided) and starts
* the listening process on one of its threads.
*/
public void start() {
if (this.taskExecutor == null) {
this.taskExecutor = Executors.newFixedThreadPool(this.poolSize);
}
this.active = true;
this.taskExecutor.execute(this);
}
/**
* Stops the server.
*/
public void stop() {
this.active = false;
this.close();
}
protected TcpConnection wrapConnection(TcpConnection connection) throws Exception {
if (this.interceptorFactoryChain == null) {
return connection;
}
TcpConnectionInterceptorFactory[] interceptorFactories =
this.interceptorFactoryChain.getInterceptorFactories();
if (interceptorFactories == null) {
return connection;
}
for (TcpConnectionInterceptorFactory factory : interceptorFactories) {
TcpConnectionInterceptor wrapper = factory.getInterceptor();
wrapper.setTheConnection(connection);
// if no ultimate listener or sender, register each wrapper in turn
if (this.listener == null) {
connection.registerListener(wrapper);
}
if (this.sender == null) {
connection.registerSender(wrapper);
}
connection = wrapper;
}
return connection;
}
/**
*
* Times out any expired connections then, if selectionCount > 0, processes the selected keys.
*
* @param selectionCount
* @param selector
* @param connections
* @throws IOException
*/
protected void processNioSelections(int selectionCount, final Selector selector, ServerSocketChannel server,
Map<SocketChannel, TcpNioConnection> connections) throws IOException {
long now = 0;
if (this.soTimeout > 0) {
Iterator<SocketChannel> it = connections.keySet().iterator();
now = System.currentTimeMillis();
while (it.hasNext()) {
SocketChannel channel = it.next();
if (!channel.isOpen()) {
logger.debug("Removing closed channel");
it.remove();
} else {
TcpNioConnection connection = connections.get(channel);
if (now - connection.getLastRead() > this.soTimeout) {
logger.warn("Timing out TcpNioConnection " +
this.port + " : " +
connection.getConnectionId());
connection.timeout();
}
}
}
}
if (logger.isTraceEnabled())
- logger.trace("Host" + this.host + " port " + this.port + " SelectionCount: " + selectionCount);
+ logger.trace("Host " + this.host + " port " + this.port + " SelectionCount: " + selectionCount);
if (selectionCount > 0) {
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
final SelectionKey key = iterator.next();
iterator.remove();
if (!key.isValid()) {
logger.debug("Selection key no longer valid");
}
else if (key.isReadable()) {
key.interestOps(key.interestOps() - key.readyOps());
final TcpNioConnection connection;
connection = (TcpNioConnection) key.attachment();
connection.setLastRead(System.currentTimeMillis());
this.taskExecutor.execute(new Runnable() {
public void run() {
try {
connection.readPacket();
} catch (Exception e) {
if (connection.isOpen()) {
logger.error("Exception on read " +
connection.getConnectionId() + " " +
e.getMessage());
connection.close();
} else {
logger.debug("Connection closed");
}
}
if (key.channel().isOpen()) {
key.interestOps(SelectionKey.OP_READ);
selector.wakeup();
}
}});
}
else if (key.isAcceptable()) {
doAccept(selector, server, now);
}
else {
logger.error("Unexpected key: " + key);
}
}
}
}
/**
* @param selector
* @param now
* @throws IOException
*/
protected void doAccept(final Selector selector, ServerSocketChannel server, long now) throws IOException {
throw new UnsupportedOperationException("Nio server factory must override this method");
}
public int getPhase() {
return 0;
}
public boolean isAutoStartup() {
return true;
}
public void stop(Runnable callback) {
stop();
callback.run();
}
}
| true | true | protected void processNioSelections(int selectionCount, final Selector selector, ServerSocketChannel server,
Map<SocketChannel, TcpNioConnection> connections) throws IOException {
long now = 0;
if (this.soTimeout > 0) {
Iterator<SocketChannel> it = connections.keySet().iterator();
now = System.currentTimeMillis();
while (it.hasNext()) {
SocketChannel channel = it.next();
if (!channel.isOpen()) {
logger.debug("Removing closed channel");
it.remove();
} else {
TcpNioConnection connection = connections.get(channel);
if (now - connection.getLastRead() > this.soTimeout) {
logger.warn("Timing out TcpNioConnection " +
this.port + " : " +
connection.getConnectionId());
connection.timeout();
}
}
}
}
if (logger.isTraceEnabled())
logger.trace("Host" + this.host + " port " + this.port + " SelectionCount: " + selectionCount);
if (selectionCount > 0) {
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
final SelectionKey key = iterator.next();
iterator.remove();
if (!key.isValid()) {
logger.debug("Selection key no longer valid");
}
else if (key.isReadable()) {
key.interestOps(key.interestOps() - key.readyOps());
final TcpNioConnection connection;
connection = (TcpNioConnection) key.attachment();
connection.setLastRead(System.currentTimeMillis());
this.taskExecutor.execute(new Runnable() {
public void run() {
try {
connection.readPacket();
} catch (Exception e) {
if (connection.isOpen()) {
logger.error("Exception on read " +
connection.getConnectionId() + " " +
e.getMessage());
connection.close();
} else {
logger.debug("Connection closed");
}
}
if (key.channel().isOpen()) {
key.interestOps(SelectionKey.OP_READ);
selector.wakeup();
}
}});
}
else if (key.isAcceptable()) {
doAccept(selector, server, now);
}
else {
logger.error("Unexpected key: " + key);
}
}
}
}
| protected void processNioSelections(int selectionCount, final Selector selector, ServerSocketChannel server,
Map<SocketChannel, TcpNioConnection> connections) throws IOException {
long now = 0;
if (this.soTimeout > 0) {
Iterator<SocketChannel> it = connections.keySet().iterator();
now = System.currentTimeMillis();
while (it.hasNext()) {
SocketChannel channel = it.next();
if (!channel.isOpen()) {
logger.debug("Removing closed channel");
it.remove();
} else {
TcpNioConnection connection = connections.get(channel);
if (now - connection.getLastRead() > this.soTimeout) {
logger.warn("Timing out TcpNioConnection " +
this.port + " : " +
connection.getConnectionId());
connection.timeout();
}
}
}
}
if (logger.isTraceEnabled())
logger.trace("Host " + this.host + " port " + this.port + " SelectionCount: " + selectionCount);
if (selectionCount > 0) {
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()) {
final SelectionKey key = iterator.next();
iterator.remove();
if (!key.isValid()) {
logger.debug("Selection key no longer valid");
}
else if (key.isReadable()) {
key.interestOps(key.interestOps() - key.readyOps());
final TcpNioConnection connection;
connection = (TcpNioConnection) key.attachment();
connection.setLastRead(System.currentTimeMillis());
this.taskExecutor.execute(new Runnable() {
public void run() {
try {
connection.readPacket();
} catch (Exception e) {
if (connection.isOpen()) {
logger.error("Exception on read " +
connection.getConnectionId() + " " +
e.getMessage());
connection.close();
} else {
logger.debug("Connection closed");
}
}
if (key.channel().isOpen()) {
key.interestOps(SelectionKey.OP_READ);
selector.wakeup();
}
}});
}
else if (key.isAcceptable()) {
doAccept(selector, server, now);
}
else {
logger.error("Unexpected key: " + key);
}
}
}
}
|
diff --git a/access-tests/src/test/java/org/apache/access/tests/e2e/TestMovingToProduction.java b/access-tests/src/test/java/org/apache/access/tests/e2e/TestMovingToProduction.java
index a05881618..20d9ec796 100644
--- a/access-tests/src/test/java/org/apache/access/tests/e2e/TestMovingToProduction.java
+++ b/access-tests/src/test/java/org/apache/access/tests/e2e/TestMovingToProduction.java
@@ -1,220 +1,224 @@
/*
* 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.access.tests.e2e;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.Statement;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.common.io.Resources;
public class TestMovingToProduction extends AbstractTestWithStaticHiveServer {
private Context context;
private final String SINGLE_TYPE_DATA_FILE_NAME = "kv1.dat";
@Before
public void setUp() throws Exception {
context = createContext();
File dataFile = new File(dataDir, SINGLE_TYPE_DATA_FILE_NAME);
FileOutputStream to = new FileOutputStream(dataFile);
Resources.copy(Resources.getResource(SINGLE_TYPE_DATA_FILE_NAME), to);
to.close();
}
@After
public void tearDown() throws Exception {
if (context != null) {
context.close();
}
}
/**
* Steps:
* 1. admin create DB_1, admin create GROUP_1, GROUP_2
* 2. admin grant all to GROUP_1 on DB_1
* 3. user in GROUP_1 create table tb_1 and load data into
* 4. admin create table production.tb_1.
* 5. admin grant all to GROUP_1 on production.tb_1.
* positive test cases:
* a)verify user in GROUP_1 can load data from DB_1.tb_1 to production.tb_1
* b)verify user in GROUP_1 has proper privilege on production.tb_1
* (read and insert)
* negative test cases:
* c)verify user in GROUP_2 cannot load data from DB_1.tb_1
* to production.tb_1
* d)verify user in GROUP_1 cannot drop production.tb_1
*/
@Test
public void testMovingTable1() throws Exception {
File policyFile = context.getPolicyFile();
Assert.assertTrue(policyFile.delete() && policyFile.createNewFile());
PolicyFileEditor editor = new PolicyFileEditor(policyFile);
editor.addPolicy("admin = admin", "groups");
editor.addPolicy("group1 = all_db1, load_data, select_proddb_tbl1, insert_proddb_tbl1", "groups");
editor.addPolicy("all_db1 = server=server1->db=db_1", "roles");
editor.addPolicy("load_data = server=server1->uri=file:" + dataDir.getPath(), "roles");
editor.addPolicy("admin = server=server1", "roles");
editor.addPolicy("admin1 = admin", "users");
editor.addPolicy("user1 = group1", "users");
editor.addPolicy("user2 = group2", "users");
String dbName1 = "db_1";
String dbName2 = "proddb";
String tableName1 = "tb_1";
Connection connection = context.createConnection("admin1", "foo");
Statement statement = context.createStatement(connection);
statement.execute("DROP DATABASE IF EXISTS " + dbName1 + " CASCADE");
statement.execute("DROP DATABASE IF EXISTS " + dbName2 + " CASCADE");
statement.execute("CREATE DATABASE " + dbName1);
statement.execute("CREATE DATABASE " + dbName2);
statement.execute("DROP TABLE IF EXISTS " + dbName2 + "." + tableName1);
statement.execute("create table " + dbName2 + "." + tableName1
+ " (under_col int comment 'the under column', value string)");
statement.close();
connection.close();
// a
connection = context.createConnection("user1", "foo");
statement = context.createStatement(connection);
statement.execute("USE " + dbName1);
statement.execute("DROP TABLE IF EXISTS " + tableName1);
statement.execute("create table " + tableName1
+ " (under_col int comment 'the under column', value string)");
statement.execute("LOAD DATA INPATH 'file:" + dataDir.getPath()
+ "' INTO TABLE " + tableName1);
editor.addPolicy("insert_proddb_tbl1 = server=server1->db=proddb->table=tb_1->action=insert", "roles");
statement.execute("USE " + dbName2);
statement.execute("INSERT OVERWRITE TABLE "
+ tableName1 + " SELECT * FROM " + dbName1
+ "." + tableName1);
// b
editor.addPolicy("select_proddb_tbl1 = server=server1->db=proddb->table=tb_1->action=select", "roles");
- statement.execute("SELECT * FROM " + tableName1 + " LIMIT 10");
- assertTrue("user1 should be able to describe table " + tableName1,
- statement.execute("DESCRIBE " + tableName1));
+ ResultSet resultSet = statement.executeQuery("SELECT * FROM " + tableName1 + " LIMIT 10");
+ int count = 0;
+ while(resultSet.next()) {
+ count++;
+ }
+ assertEquals(10, count);
+ statement.execute("DESCRIBE " + tableName1);
// c
connection = context.createConnection("user2", "foo");
statement = context.createStatement(connection);
context.assertAuthzException(statement, "USE " + dbName2);
context.assertAuthzException(statement, "INSERT OVERWRITE TABLE "
+ dbName2 + "." + tableName1 + " SELECT * FROM " + dbName1
+ "." + tableName1);
context.assertAuthzException(statement, "SELECT * FROM " + dbName2 + "." + tableName1 + " LIMIT 10");
statement.close();
connection.close();
// d
connection = context.createConnection("user1", "foo");
statement = context.createStatement(connection);
statement.execute("USE " + dbName2);
context.assertAuthzException(statement, "DROP TABLE " + tableName1);
statement.close();
connection.close();
}
/**
* repeat above tests, only difference is don't do 'USE <database>'
* in this test. Instead, access table objects across database by
* database.table
* @throws Exception
*/
@Test
public void testMovingTable2() throws Exception {
File policyFile = context.getPolicyFile();
PolicyFileEditor editor = new PolicyFileEditor(policyFile);
editor.addPolicy("admin = admin", "groups");
editor.addPolicy("group1 = all_db1, load_data, select_proddb_tbl1, insert_proddb_tbl1", "groups");
editor.addPolicy("all_db1 = server=server1->db=db_1", "roles");
editor.addPolicy("load_data = server=server1->uri=file:" + dataDir.getPath(), "roles");
editor.addPolicy("admin = server=server1", "roles");
editor.addPolicy("admin1 = admin", "users");
editor.addPolicy("user1 = group1", "users");
editor.addPolicy("user2 = group2", "users");
String dbName1 = "db_1";
String dbName2 = "proddb";
String tableName1 = "tb_1";
Connection connection = context.createConnection("admin1", "foo");
Statement statement = context.createStatement(connection);
statement.execute("DROP DATABASE IF EXISTS " + dbName1 + " CASCADE");
statement.execute("DROP DATABASE IF EXISTS " + dbName2 + " CASCADE");
statement.execute("CREATE DATABASE " + dbName1);
statement.execute("CREATE DATABASE " + dbName2);
statement.execute("DROP TABLE IF EXISTS " + dbName2 + "." + tableName1);
statement.execute("create table " + dbName2 + "." + tableName1
+ " (under_col int comment 'the under column', value string)");
statement.close();
connection.close();
// a
connection = context.createConnection("user1", "foo");
statement = context.createStatement(connection);
statement.execute("DROP TABLE IF EXISTS " + dbName1 + "." + tableName1);
statement.execute("create table " + dbName1 + "." + tableName1
+ " (under_col int comment 'the under column', value string)");
statement.execute("LOAD DATA INPATH 'file:" + dataDir.getPath()
+ "' INTO TABLE " + dbName1 + "." + tableName1);
editor.addPolicy("insert_proddb_tbl1 = server=server1->db=proddb->table=tb_1->action=insert", "roles");
statement.execute("INSERT OVERWRITE TABLE "
+ dbName2 + "." + tableName1 + " SELECT * FROM " + dbName1
+ "." + tableName1);
// b
editor.addPolicy("select_proddb_tbl1 = server=server1->db=proddb->table=tb_1->action=select", "roles");
assertTrue("user1 should be able to select data from "
+ dbName2 + "." + dbName2 + "." + tableName1, statement.execute("SELECT * FROM "
+ dbName2 + "." + tableName1 + " LIMIT 10"));
assertTrue("user1 should be able to describe table " + dbName2 + "." + tableName1,
statement.execute("DESCRIBE " + dbName2 + "." + tableName1));
// c
connection = context.createConnection("user2", "foo");
statement = context.createStatement(connection);
context.assertAuthzException(statement, "INSERT OVERWRITE TABLE "
+ dbName2 + "." + tableName1 + " SELECT * FROM " + dbName1
+ "." + tableName1);
context.assertAuthzException(statement, "SELECT * FROM "
+ dbName2 + "." + tableName1 + " LIMIT 10");
statement.close();
connection.close();
// d
connection = context.createConnection("user1", "foo");
statement = context.createStatement(connection);
statement.execute("USE " + dbName2);
context.assertAuthzException(statement, "DROP TABLE " + tableName1);
statement.close();
connection.close();
}
}
| true | true | public void testMovingTable1() throws Exception {
File policyFile = context.getPolicyFile();
Assert.assertTrue(policyFile.delete() && policyFile.createNewFile());
PolicyFileEditor editor = new PolicyFileEditor(policyFile);
editor.addPolicy("admin = admin", "groups");
editor.addPolicy("group1 = all_db1, load_data, select_proddb_tbl1, insert_proddb_tbl1", "groups");
editor.addPolicy("all_db1 = server=server1->db=db_1", "roles");
editor.addPolicy("load_data = server=server1->uri=file:" + dataDir.getPath(), "roles");
editor.addPolicy("admin = server=server1", "roles");
editor.addPolicy("admin1 = admin", "users");
editor.addPolicy("user1 = group1", "users");
editor.addPolicy("user2 = group2", "users");
String dbName1 = "db_1";
String dbName2 = "proddb";
String tableName1 = "tb_1";
Connection connection = context.createConnection("admin1", "foo");
Statement statement = context.createStatement(connection);
statement.execute("DROP DATABASE IF EXISTS " + dbName1 + " CASCADE");
statement.execute("DROP DATABASE IF EXISTS " + dbName2 + " CASCADE");
statement.execute("CREATE DATABASE " + dbName1);
statement.execute("CREATE DATABASE " + dbName2);
statement.execute("DROP TABLE IF EXISTS " + dbName2 + "." + tableName1);
statement.execute("create table " + dbName2 + "." + tableName1
+ " (under_col int comment 'the under column', value string)");
statement.close();
connection.close();
// a
connection = context.createConnection("user1", "foo");
statement = context.createStatement(connection);
statement.execute("USE " + dbName1);
statement.execute("DROP TABLE IF EXISTS " + tableName1);
statement.execute("create table " + tableName1
+ " (under_col int comment 'the under column', value string)");
statement.execute("LOAD DATA INPATH 'file:" + dataDir.getPath()
+ "' INTO TABLE " + tableName1);
editor.addPolicy("insert_proddb_tbl1 = server=server1->db=proddb->table=tb_1->action=insert", "roles");
statement.execute("USE " + dbName2);
statement.execute("INSERT OVERWRITE TABLE "
+ tableName1 + " SELECT * FROM " + dbName1
+ "." + tableName1);
// b
editor.addPolicy("select_proddb_tbl1 = server=server1->db=proddb->table=tb_1->action=select", "roles");
statement.execute("SELECT * FROM " + tableName1 + " LIMIT 10");
assertTrue("user1 should be able to describe table " + tableName1,
statement.execute("DESCRIBE " + tableName1));
// c
connection = context.createConnection("user2", "foo");
statement = context.createStatement(connection);
context.assertAuthzException(statement, "USE " + dbName2);
context.assertAuthzException(statement, "INSERT OVERWRITE TABLE "
+ dbName2 + "." + tableName1 + " SELECT * FROM " + dbName1
+ "." + tableName1);
context.assertAuthzException(statement, "SELECT * FROM " + dbName2 + "." + tableName1 + " LIMIT 10");
statement.close();
connection.close();
// d
connection = context.createConnection("user1", "foo");
statement = context.createStatement(connection);
statement.execute("USE " + dbName2);
context.assertAuthzException(statement, "DROP TABLE " + tableName1);
statement.close();
connection.close();
}
| public void testMovingTable1() throws Exception {
File policyFile = context.getPolicyFile();
Assert.assertTrue(policyFile.delete() && policyFile.createNewFile());
PolicyFileEditor editor = new PolicyFileEditor(policyFile);
editor.addPolicy("admin = admin", "groups");
editor.addPolicy("group1 = all_db1, load_data, select_proddb_tbl1, insert_proddb_tbl1", "groups");
editor.addPolicy("all_db1 = server=server1->db=db_1", "roles");
editor.addPolicy("load_data = server=server1->uri=file:" + dataDir.getPath(), "roles");
editor.addPolicy("admin = server=server1", "roles");
editor.addPolicy("admin1 = admin", "users");
editor.addPolicy("user1 = group1", "users");
editor.addPolicy("user2 = group2", "users");
String dbName1 = "db_1";
String dbName2 = "proddb";
String tableName1 = "tb_1";
Connection connection = context.createConnection("admin1", "foo");
Statement statement = context.createStatement(connection);
statement.execute("DROP DATABASE IF EXISTS " + dbName1 + " CASCADE");
statement.execute("DROP DATABASE IF EXISTS " + dbName2 + " CASCADE");
statement.execute("CREATE DATABASE " + dbName1);
statement.execute("CREATE DATABASE " + dbName2);
statement.execute("DROP TABLE IF EXISTS " + dbName2 + "." + tableName1);
statement.execute("create table " + dbName2 + "." + tableName1
+ " (under_col int comment 'the under column', value string)");
statement.close();
connection.close();
// a
connection = context.createConnection("user1", "foo");
statement = context.createStatement(connection);
statement.execute("USE " + dbName1);
statement.execute("DROP TABLE IF EXISTS " + tableName1);
statement.execute("create table " + tableName1
+ " (under_col int comment 'the under column', value string)");
statement.execute("LOAD DATA INPATH 'file:" + dataDir.getPath()
+ "' INTO TABLE " + tableName1);
editor.addPolicy("insert_proddb_tbl1 = server=server1->db=proddb->table=tb_1->action=insert", "roles");
statement.execute("USE " + dbName2);
statement.execute("INSERT OVERWRITE TABLE "
+ tableName1 + " SELECT * FROM " + dbName1
+ "." + tableName1);
// b
editor.addPolicy("select_proddb_tbl1 = server=server1->db=proddb->table=tb_1->action=select", "roles");
ResultSet resultSet = statement.executeQuery("SELECT * FROM " + tableName1 + " LIMIT 10");
int count = 0;
while(resultSet.next()) {
count++;
}
assertEquals(10, count);
statement.execute("DESCRIBE " + tableName1);
// c
connection = context.createConnection("user2", "foo");
statement = context.createStatement(connection);
context.assertAuthzException(statement, "USE " + dbName2);
context.assertAuthzException(statement, "INSERT OVERWRITE TABLE "
+ dbName2 + "." + tableName1 + " SELECT * FROM " + dbName1
+ "." + tableName1);
context.assertAuthzException(statement, "SELECT * FROM " + dbName2 + "." + tableName1 + " LIMIT 10");
statement.close();
connection.close();
// d
connection = context.createConnection("user1", "foo");
statement = context.createStatement(connection);
statement.execute("USE " + dbName2);
context.assertAuthzException(statement, "DROP TABLE " + tableName1);
statement.close();
connection.close();
}
|
diff --git a/contrib/Karma.java b/contrib/Karma.java
index b160f08..aeb9f18 100644
--- a/contrib/Karma.java
+++ b/contrib/Karma.java
@@ -1,930 +1,930 @@
import uk.co.uwcs.choob.*;
import uk.co.uwcs.choob.modules.*;
import uk.co.uwcs.choob.support.*;
import uk.co.uwcs.choob.support.events.*;
import java.sql.*;
import java.util.*;
import java.util.regex.*;
import java.io.*;
public class KarmaObject
{
public int id;
public String string;
public int up;
public int down;
public int value;
boolean increase;
String instName;
}
public class KarmaReasonObject
{
public int id;
public String string;
public int direction;
public String reason;
}
class KarmaSortByAbsValue implements Comparator<KarmaObject>
{
public int compare(KarmaObject o1, KarmaObject o2) {
if (Math.abs(o1.value) > Math.abs(o2.value)) {
return -1;
}
if (Math.abs(o1.value) < Math.abs(o2.value)) {
return 1;
}
if (o1.up > o2.up) {
return -1;
}
if (o1.up < o2.up) {
return 1;
}
if (o1.down > o2.down) {
return -1;
}
if (o1.down < o2.down) {
return 1;
}
return 0;
}
public boolean equals(Object obj) {
return false;
}
}
public class Karma
{
// Non-null == ignore.
private final static Set<String> exceptions = new HashSet<String>();
private final static Set<String> reasonExceptions = new HashSet<String>();
static
{
exceptions.add("c");
exceptions.add("dc");
exceptions.add("visualj");
exceptions.add("vc");
reasonExceptions.add("for that");
reasonExceptions.add("because of that");
}
static final int FLOOD_RATE = 15 * 60 * 1000;
static final String FLOOD_RATE_STR = "15 minutes";
public String[] info()
{
return new String[] {
"Plugin to keep track of the \"karma\" of stuff.",
"The Choob Team",
"[email protected]",
"$Rev$$Date$"
};
}
private Modules mods;
private IRCInterface irc;
public Karma (Modules mods, IRCInterface irc)
{
this.mods = mods;
this.irc = irc;
}
public String[] apiReason()
{
List<KarmaReasonObject> results;
results = mods.odb.retrieve(KarmaReasonObject.class, "ORDER BY RAND() LIMIT 1");
if (results.size() == 0)
return null;
else
return new String[] {
results.get(0).string,
results.get(0).reason,
results.get(0).direction == 1 ? "gained" : "lost"
};
}
public String[] apiReason(boolean up)
{
List<KarmaReasonObject> results;
results = mods.odb.retrieve(KarmaReasonObject.class, "WHERE direction = '" + (up ? 1 : -1) + "' ORDER BY RAND() LIMIT 1");
if (results.size() == 0)
return null;
else
return new String[] {
results.get(0).string,
results.get(0).reason,
up ? "gained" : "lost"
};
}
public String[] apiReason(String name)
{
List<KarmaReasonObject> results;
results = mods.odb.retrieve(KarmaReasonObject.class, "WHERE string = \"" + mods.odb.escapeString(name) + "\" ORDER BY RAND() LIMIT 1");
if (results.size() == 0)
return null;
else
return new String[] {
name,
results.get(0).reason,
results.get(0).direction == 1 ? "gained" : "lost"
};
}
public String[] apiReason(String name, boolean up)
{
List<KarmaReasonObject> results;
results = mods.odb.retrieve(KarmaReasonObject.class, "WHERE string = \"" + mods.odb.escapeString(name) + "\" AND direction = '" + (up ? 1 : -1) + "' ORDER BY RAND() LIMIT 1");
if (results.size() == 0)
return null;
else
return new String[] {
name,
results.get(0).reason,
up ? "gained" : "lost"
};
}
public String[] helpCommandReason = {
"Find out why something rocks or sucks.",
"[<Object>]",
"<Object> is the optional thing to ask about."
};
public void commandReason( Message mes )
{
String name = mods.util.getParamString(mes);
String[] reason;
if (name.equals(""))
{
reason = apiReason();
if (reason != null)
name = reason[0];
}
else
{
Matcher ma = karmaItemPattern.matcher(name);
if (ma.find())
{
reason = apiReason(getName(ma));
if (reason != null)
name = reason[0];
}
else
{
if (name.startsWith("\""))
{
irc.sendContextReply(mes, "Unable to match your query to a valid karma string.");
return;
}
// Value wasn't quoted, so try it again, but quoted.
ma = karmaItemPattern.matcher("\"" + name + "\"");
if (!ma.find())
{
irc.sendContextReply(mes, "Unable to match your query to a valid karma string.");
return;
}
reason = apiReason(getName(ma));
if (reason != null)
name = reason[0];
}
}
if (reason != null)
irc.sendContextReply(mes, name + " has " + reason[2] + " karma " + reason[1]);
else
irc.sendContextReply(mes, "Nobody has ever told me why " + name + " has changed karma. :(");
}
private void nullReason(Message mes, boolean direction)
{
String[] reason;
String name;
reason = apiReason(direction);
if (reason != null)
name = reason[0];
else
{
irc.sendContextReply(mes, "No karma reasons.");
return;
}
irc.sendContextReply(mes, name + " has " + (direction ? "gained" : "lost") + " karma " + reason[1]);
}
public String[] helpCommandReasonUp = {
"Find out why something rocks.",
"[<Object>]",
"<Object> is the optional thing to ask about."
};
public void commandReasonUp( Message mes )
{
String name = mods.util.getParamString(mes);
String[] reason;
if (name.equals(""))
{
nullReason(mes, true);
return;
}
else
{
Matcher ma=karmaItemPattern.matcher(name);
if (ma.find())
{
reason = apiReason(getName(ma), true);
if (reason !=null)
name = reason[0];
}
else
{
nullReason(mes, true);
return;
}
}
if (reason != null)
irc.sendContextReply(mes, name + " has gained karma " + reason[1]);
else
irc.sendContextReply(mes, "Nobody has ever told me why " + name + " has gained karma. :(");
}
public String[] helpCommandReasonDown = {
"Find out why something sucks.",
"[<Object>]",
"<Object> is the optional thing to ask about."
};
public void commandReasonDown( Message mes )
{
String name = mods.util.getParamString(mes);
String[] reason;
if (name.equals(""))
{
reason = apiReason(false);
if (reason != null)
name = reason[0];
}
else
{
Matcher ma=karmaItemPattern.matcher(name);
if (ma.find())
{
reason = apiReason(getName(ma), false);
if (reason != null)
name = reason[0];
}
else
{
nullReason(mes, false);
return;
}
}
if (reason != null)
irc.sendContextReply(mes, name + " has lost karma " + reason[1]);
else
irc.sendContextReply(mes, "Nobody has ever told me why " + name + " has lost karma. :(");
}
public String[] helpTopics = { "Using" };
public String[] helpUsing = {
"To change the karma of something, simply send the message"
+ " 'something--' or 'something++'. You can also specify a reason, by"
+ " sending a line starting with a karma change then giving a reason,"
+ " like: 'ntl-- because they suck' or 'ntl-- for sucking teh c0k'.",
"For strings shorter than 3 chars, or spaced strings or whatever,"
+ " you can use quotes, like this: '\"a\"--' or '\"big bananas\"++'."
+ " You can't yet Set these types of string."
};
// Let's just do a simple filter to pick up karma. This is lightweight and
// picks up anything that /could/ be karma (though not necessarily only
// karma)
// ++ or --:
final private static String plusplus_or_minusminus = "(\\+\\+|\\-\\-)";
// Quoted string:
final private static String c_style_quoted_string = "(?:"
+ "\""
+ "("
+ "(?:\\\\.|[^\"\\\\])+" // C-style quoting
+ ")"
+ "\""
+ ")";
// Plain string of >=2 chars.
final private static String plain_karma = "("
+ "[a-zA-Z0-9_]{2,}"
+ ")";
// Either a quoted or a valid plain karmaitem.
final private static String karma_item = "(?x:" + c_style_quoted_string + "|" + plain_karma + ")";
final private static Pattern karmaItemPattern = Pattern.compile(karma_item);
// If you change this, change reasonPattern too.
final private static Pattern karmaPattern = Pattern.compile(
"(?x:"
+ "(?: ^ | (?<=[\\s\\(]) )" // Anchor at start of string, whitespace or open bracket.
+ karma_item
+ plusplus_or_minusminus
+ "[\\)\\.,]?" // Allowed to terminate with full stop/close bracket etc.
+ "(?: (?=\\s) | $ )" // Need either whitespace or end-of-string now.
+ ")"
);
// If you change the first part of this, change karmaPattern too.
final private static Pattern reasonPattern = Pattern.compile(
"(?x:"
+ "^" // Anchor at start of string...
+ karma_item
+ plusplus_or_minusminus
+ "\\s+"
+ "("
// A "natural English" reason
+ "(?i: because | for)\\s" // Must start sensibly
+ ".+?" // Rest of reason
+ "|"
// A bracketted reason
+ "\\("
+ ".+?" // Contains any text.
+ "\\)"
+ ")"
+ "\\s*$" // Chew up all trailing whitespace.
+ ")"
);
public final String filterKarmaRegex = plusplus_or_minusminus + "\\B";
public synchronized void filterKarma( Message mes, Modules mods, IRCInterface irc )
{
// Ignore lines that look like commands.
if (Pattern.compile(irc.getTriggerRegex()).matcher(mes.getMessage()).find())
return;
Matcher reasonMatch = reasonPattern.matcher(mes.getMessage());
boolean hasReason = false;
String karmaReasonFloodCheck = "";
if (reasonMatch.matches())
{
// Find out which holds our name.
String name;
boolean skip = false;
// Group 1: quoted karma item
// Group 2: raw karma item
// Group 3: "++" or "--"
// Group 4: reason
if (reasonMatch.group(1) != null)
name = reasonMatch.group(1).replaceAll("\\\\(.)", "$1");
else
{
// need verification on this one.
name = reasonMatch.group(2);
if (exceptions.contains(name.toLowerCase()))
skip = true;
}
if (!skip)
{
// Wait until we know there's a real karma change going on.
if (mes instanceof PrivateEvent)
{
irc.sendContextReply(mes, "I'm sure other people want to hear what you have to think!");
return;
}
// Karma flood check.
karmaReasonFloodCheck = name;
try
{
// 15 minute block for each karma item, irespective of who or direction.
- int ret = (Integer)mods.plugin.callAPI("Flood", "IsFlooding", "Karma:" + name, FLOOD_RATE, 2);
+ int ret = (Integer)mods.plugin.callAPI("Flood", "IsFlooding", "Karma:" + name.replaceAll(" ", "_"), FLOOD_RATE, 2);
if (ret != 0)
{
if (ret == 1)
irc.sendContextReply(mes, "Denied change to '" + name + "'! Karma changes limited to one change per item per " + FLOOD_RATE_STR + ".");
return;
}
}
catch (ChoobNoSuchCallException e)
{ } // ignore
catch (Throwable e)
{
System.err.println("Couldn't do antiflood call: " + e);
}
boolean increase = reasonMatch.group(3).equals("++");
final String sreason = reasonMatch.group(4);
if (!reasonExceptions.contains(sreason))
{
// Store the reason too.
KarmaReasonObject reason = new KarmaReasonObject();
reason.string = name;
reason.reason = sreason;
reason.direction = increase ? 1 : -1;
mods.odb.save(reason);
hasReason = true;
}
}
}
// Not a reasoned match, then.
Matcher karmaMatch = karmaPattern.matcher(mes.getMessage());
String nick = mods.nick.getBestPrimaryNick(mes.getNick());
HashSet used = new HashSet();
List<String> names = new ArrayList<String>();
List<KarmaObject> karmaObjs = new ArrayList<KarmaObject>();
while (karmaMatch.find() && karmaObjs.size() < 5)
{
String name;
boolean skip = false;
// Group 1: quoted karma item
// Group 2: raw karma item
// Group 3: "++" or "--"
if (karmaMatch.group(1) != null)
name = karmaMatch.group(1).replaceAll("\\\\(.)", "$1");
else
{
// need verification on this one.
name = karmaMatch.group(2);
if (exceptions.contains(name.toLowerCase()))
skip = true;
}
if (skip)
continue;
// Wait until we know there's a real karma change going on.
if (mes instanceof PrivateEvent)
{
irc.sendContextReply(mes, "I'm sure other people want to hear what you have to think!");
return;
}
if (name.equals/*NOT IgnoreCase*/("me"))
name=nick;
// Have we already done this?
if (used.contains(name.toLowerCase()))
continue;
used.add(name.toLowerCase());
boolean increase = karmaMatch.group(3).equals("++");
if (name.equalsIgnoreCase(nick))
increase = false;
// Karma flood check (skip if we checked this item with the reason earlier).
if (!name.equalsIgnoreCase(karmaReasonFloodCheck))
{
try
{
// 15 minute block for each karma item, irespective of who or direction.
- int ret = (Integer)mods.plugin.callAPI("Flood", "IsFlooding", "Karma:" + name, FLOOD_RATE, 2);
+ int ret = (Integer)mods.plugin.callAPI("Flood", "IsFlooding", "Karma:" + name.replaceAll(" ", "_"), FLOOD_RATE, 2);
if (ret != 0)
{
if (ret == 1)
irc.sendContextReply(mes, "Denied change to '" + name + "'! Karma changes limited to one change per item per " + FLOOD_RATE_STR + ".");
return;
}
}
catch (ChoobNoSuchCallException e)
{ } // ignore
catch (Throwable e)
{
System.err.println("Couldn't do antiflood call: " + e);
}
}
KarmaObject karmaObj = retrieveKarmaObject(name);
if (increase)
{
karmaObj.up++;
karmaObj.value++;
}
else
{
karmaObj.down++;
karmaObj.value--;
}
karmaObj.instName = name;
karmaObj.increase = increase;
karmaObjs.add(karmaObj);
}
saveKarmaObjects(karmaObjs);
// No actual karma changes. Maybe someone said "c++" or something.
if (karmaObjs.size() == 0)
return;
// Generate a pretty reply, all actual processing is done now:
if (karmaObjs.size() == 1)
{
KarmaObject info = karmaObjs.get(0);
if (info.string.equalsIgnoreCase(nick))
// This doesn't mention if there was a reason..
irc.sendContextReply(mes, "Fool, that's less karma to you! That leaves you with " + info.value + ".");
else
{
if (hasReason)
irc.sendContextReply(mes, "Given " + (info.increase ? "karma" : "less karma") + " to " + info.instName + ", and understood your reasons. New karma is " + info.value + ".");
else
irc.sendContextReply(mes, "Given " + (info.increase ? "karma" : "less karma") + " to " + info.instName + ". New karma is " + info.value + ".");
}
return;
}
StringBuffer output = new StringBuffer("Karma adjustments: ");
for (int i=0; i<karmaObjs.size(); i++)
{
KarmaObject info = karmaObjs.get(i);
output.append(info.instName);
output.append(info.increase ? " up" : " down");
if (i == 0 && hasReason)
output.append(", with reason");
output.append(" (now " + info.value + ")");
if (i != karmaObjs.size() - 1)
{
if (i == karmaObjs.size() - 2)
output.append(" and ");
else
output.append(", ");
}
}
output.append(".");
irc.sendContextReply( mes, output.toString());
}
private String postfix(int n)
{
if (n % 100 >= 11 && n % 100 <= 13)
return "th";
switch (n % 10)
{
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
}
return "th";
}
private void commandScores(Message mes, Modules mods, IRCInterface irc, boolean asc)
{
List<KarmaObject> karmaObjs = retrieveKarmaObjects("SORT " + (asc ? "ASC" : "DESC") + " INTEGER value LIMIT (5)");
StringBuffer output = new StringBuffer((asc ? "Low" : "High" ) + " Scores: ");
for (int i=0; i<karmaObjs.size(); i++)
{
output.append(String.valueOf(i+1) + postfix(i+1));
output.append(": ");
output.append(karmaObjs.get(i).string);
output.append(" (with " + karmaObjs.get(i).value + ")");
if (i != karmaObjs.size() - 1)
{
if (i == karmaObjs.size() - 2)
output.append(" and ");
else
output.append(", ");
}
}
output.append(".");
irc.sendContextReply( mes, output.toString());
}
public String[] helpCommandHighScores = {
"Find out what has the highest karma"
};
public void commandHighScores(Message mes)
{
commandScores(mes, mods, irc, false);
}
public String[] helpCommandLowScores = {
"Find out what has the lowest karma"
};
public void commandLowScores(Message mes)
{
commandScores(mes, mods, irc, true);
}
private void saveKarmaObjects(List<KarmaObject> karmaObjs)
{
for (KarmaObject karmaObj: karmaObjs)
mods.odb.update(karmaObj);
}
private KarmaObject retrieveKarmaObject(String name)
{
name = name.replaceAll(" ", "_");
List<KarmaObject> results = mods.odb.retrieve(KarmaObject.class, "WHERE string = \"" + mods.odb.escapeString(name) + "\"");
if (results.size() == 0)
{
KarmaObject newObj = new KarmaObject();
newObj.string = name;
mods.odb.save(newObj);
return newObj;
}
else
return results.get(0);
}
private List<KarmaObject> retrieveKarmaObjects(String clause)
{
return mods.odb.retrieve(KarmaObject.class, clause);
}
public String[] helpCommandGet = {
"Find out the karma of some object or other.",
"<Object> [<Object> ...]",
"<Object> is the name of something to get the karma of"
};
public void commandGet (Message mes, Modules mods, IRCInterface irc)
{
List<String> params = new ArrayList<String>();
Matcher ma=karmaItemPattern.matcher(mods.util.getParamString(mes));
while (ma.find())
params.add(getName(ma));
List<KarmaObject> karmaObjs = new ArrayList<KarmaObject>();
List<String> names = new ArrayList<String>();
if (params.size() > 0)
for (int i=0; i<params.size(); i++)
{
String name = params.get(i);
if (name!=null)
{
KarmaObject karmaObj = retrieveKarmaObject(name);
karmaObj.instName = name;
karmaObjs.add(karmaObj);
}
}
if (karmaObjs.size() == 1)
{
irc.sendContextReply(mes, karmaObjs.get(0).instName + " has a karma of " + karmaObjs.get(0).value + " (" + karmaObjs.get(0).up + " up, " + karmaObjs.get(0).down + " down).");
return;
}
StringBuffer output = new StringBuffer("Karmas: ");
if (karmaObjs.size()!=0)
{
for (int i=0; i<karmaObjs.size(); i++)
{
output.append(karmaObjs.get(i).instName);
output.append(": " + karmaObjs.get(i).value);
if (i != karmaObjs.size() - 1)
{
if (i == karmaObjs.size() - 2)
output.append(" and ");
else
output.append(", ");
}
}
output.append(".");
irc.sendContextReply( mes, output.toString());
}
else
irc.sendContextReply( mes, "Check the karma of what?");
}
public String[] helpCommandSet = {
"Set out the karma of some object or other.",
"<Object>=<Value> [<Object>=<Value> ...]",
"<Object> is the name of something to set the karma of",
"<Value> is the value to set the karma to"
};
public synchronized void commandSet( Message mes, Modules mods, IRCInterface irc )
{
mods.security.checkNickPerm(new ChoobPermission("plugins.karma.set"), mes);
List<String> params = mods.util.getParams( mes );
List<KarmaObject> karmaObjs = new ArrayList<KarmaObject>();
List<String> names = new ArrayList<String>();
for (int i=1; i<params.size(); i++)
{
String param = params.get(i);
String[] items = param.split("=");
if (items.length != 2)
{
irc.sendContextReply(mes, "Bad syntax: Use <Object>=<Value> [<Object>=<Value> ...]");
return;
}
String name = items[0].trim();
int val;
try
{
val = Integer.parseInt(items[1]);
}
catch (NumberFormatException e)
{
irc.sendContextReply(mes, "Bad syntax: Karma value " + items[1] + " is not a valid integer.");
return;
}
KarmaObject karmaObj = retrieveKarmaObject(name);
karmaObj.instName = name;
karmaObj.value = val;
karmaObjs.add(karmaObj);
}
if (karmaObjs.size()==0)
{
irc.sendContextReply(mes, "You need to specify some bobdamn karma to set!");
return;
}
saveKarmaObjects(karmaObjs);
StringBuffer output = new StringBuffer("Karma adjustment");
output.append(karmaObjs.size() == 1 ? "" : "s");
output.append(": ");
for (int i=0; i<karmaObjs.size(); i++)
{
output.append(karmaObjs.get(i).instName);
output.append(": now ");
output.append(karmaObjs.get(i).value);
if (i != karmaObjs.size() - 1)
{
if (i == karmaObjs.size() - 2)
output.append(" and ");
else
output.append(", ");
}
}
output.append(".");
irc.sendContextReply( mes, output.toString());
}
final private static String slashed_regex_string = "(?:"
+ "/"
+ "("
+ "(?:\\\\.|[^/\\\\])+" // C-style quoting
+ ")"
+ "/"
+ ")";
class KarmaSearchItem
{
KarmaSearchItem(String name, boolean regex)
{
this.name = name;
this.regex = regex;
}
String name;
boolean regex;
}
public String[] helpCommandSearch = {
"Finds existing karma items.",
"<Query> [<Query> ...]",
"<Query> is some text or a regular expression (in /.../) to find"
};
public void commandSearch(Message mes, Modules mods, IRCInterface irc)
{
final List<KarmaSearchItem> params = new ArrayList<KarmaSearchItem>();
final Matcher ma = Pattern.compile(karma_item + "|" + slashed_regex_string).matcher(mods.util.getParamString(mes));
while (ma.find())
{
final String name = getName(ma);
params.add(
name == null ?
new KarmaSearchItem(ma.group(3).replaceAll(" ", "_"), true) :
new KarmaSearchItem(name.replaceAll(" ", "_"), false)
);
}
if (params.size() == 0)
irc.sendContextReply(mes, "Please specify at least one valid karma item, or a regex.");
// Only 3 items please!
while (params.size() > 3)
params.remove(params.size() - 1);
for (KarmaSearchItem item : params)
{
String odbQuery;
final String andNotZero = " AND NOT (up = 0 AND down = 0 AND value = 0)";
if (item.regex) {
// Regexp
odbQuery = "WHERE string RLIKE \"" + mods.odb.escapeString(item.name) + "\"" + andNotZero;
} else {
// Substring
odbQuery = "WHERE string LIKE \"%" + mods.odb.escapeString(item.name) + "%\"" + andNotZero;
}
final List<KarmaObject> odbItems = (List<KarmaObject>)mods.odb.retrieve(KarmaObject.class, odbQuery);
if (odbItems.size() == 0) {
irc.sendContextReply(mes, "No karma items matched " + (item.regex ? "/" : "'") + item.name + (item.regex ? "/" : "'") + ".");
} else {
Collections.sort(odbItems, new KarmaSortByAbsValue());
String rpl = "Karma items matching " + (item.regex ? "/" : "'") + item.name + (item.regex ? "/" : "'") + ": ";
boolean cutOff = false;
for (int j = 0; j < odbItems.size(); j++) {
KarmaObject ko = odbItems.get(j);
if (rpl.length() + ko.string.length() > 350) {
cutOff = true;
break;
}
if (j > 0) {
rpl += ", ";
}
rpl += ko.string + " (" + ko.value + ")";
}
if (cutOff) {
rpl += ", ...";
} else {
rpl += ".";
}
irc.sendContextReply(mes, rpl);
}
}
//List<KarmaObject> karmaObjs = new ArrayList<KarmaObject>();
//List<String> names = new ArrayList<String>();
//if (params.size() > 0)
// for (int i=0; i<params.size(); i++)
// {
// }
}
public String[] helpCommandList = {
"Get a list of all karma objects.",
};
public void commandList (Message mes, Modules mods, IRCInterface irc)
{
irc.sendContextReply(mes, "No chance, matey.");
}
public void webList(PrintWriter out, String params, String[] user)
{
out.println("HTTP/1.0 200 OK");
out.println("Content-Type: text/html");
out.println();
List<KarmaObject> res = retrieveKarmaObjects("WHERE 1 SORT INTEGER value");
out.println("Item count: " + res.size() + "<br/>");
for(KarmaObject karmaObject: res)
{
if (karmaObject == null)
out.println("NULL.<br/>");
else
out.println("" + karmaObject.id + ": " + karmaObject.string + " => " + karmaObject.value + ".<br/>");
}
}
private String getName (Matcher ma)
{
if (ma.group(1) != null)
return ma.group(1).replaceAll("\\\\(.)", "$1");
else
return ma.group(2);
}
}
| false | true | public synchronized void filterKarma( Message mes, Modules mods, IRCInterface irc )
{
// Ignore lines that look like commands.
if (Pattern.compile(irc.getTriggerRegex()).matcher(mes.getMessage()).find())
return;
Matcher reasonMatch = reasonPattern.matcher(mes.getMessage());
boolean hasReason = false;
String karmaReasonFloodCheck = "";
if (reasonMatch.matches())
{
// Find out which holds our name.
String name;
boolean skip = false;
// Group 1: quoted karma item
// Group 2: raw karma item
// Group 3: "++" or "--"
// Group 4: reason
if (reasonMatch.group(1) != null)
name = reasonMatch.group(1).replaceAll("\\\\(.)", "$1");
else
{
// need verification on this one.
name = reasonMatch.group(2);
if (exceptions.contains(name.toLowerCase()))
skip = true;
}
if (!skip)
{
// Wait until we know there's a real karma change going on.
if (mes instanceof PrivateEvent)
{
irc.sendContextReply(mes, "I'm sure other people want to hear what you have to think!");
return;
}
// Karma flood check.
karmaReasonFloodCheck = name;
try
{
// 15 minute block for each karma item, irespective of who or direction.
int ret = (Integer)mods.plugin.callAPI("Flood", "IsFlooding", "Karma:" + name, FLOOD_RATE, 2);
if (ret != 0)
{
if (ret == 1)
irc.sendContextReply(mes, "Denied change to '" + name + "'! Karma changes limited to one change per item per " + FLOOD_RATE_STR + ".");
return;
}
}
catch (ChoobNoSuchCallException e)
{ } // ignore
catch (Throwable e)
{
System.err.println("Couldn't do antiflood call: " + e);
}
boolean increase = reasonMatch.group(3).equals("++");
final String sreason = reasonMatch.group(4);
if (!reasonExceptions.contains(sreason))
{
// Store the reason too.
KarmaReasonObject reason = new KarmaReasonObject();
reason.string = name;
reason.reason = sreason;
reason.direction = increase ? 1 : -1;
mods.odb.save(reason);
hasReason = true;
}
}
}
// Not a reasoned match, then.
Matcher karmaMatch = karmaPattern.matcher(mes.getMessage());
String nick = mods.nick.getBestPrimaryNick(mes.getNick());
HashSet used = new HashSet();
List<String> names = new ArrayList<String>();
List<KarmaObject> karmaObjs = new ArrayList<KarmaObject>();
while (karmaMatch.find() && karmaObjs.size() < 5)
{
String name;
boolean skip = false;
// Group 1: quoted karma item
// Group 2: raw karma item
// Group 3: "++" or "--"
if (karmaMatch.group(1) != null)
name = karmaMatch.group(1).replaceAll("\\\\(.)", "$1");
else
{
// need verification on this one.
name = karmaMatch.group(2);
if (exceptions.contains(name.toLowerCase()))
skip = true;
}
if (skip)
continue;
// Wait until we know there's a real karma change going on.
if (mes instanceof PrivateEvent)
{
irc.sendContextReply(mes, "I'm sure other people want to hear what you have to think!");
return;
}
if (name.equals/*NOT IgnoreCase*/("me"))
name=nick;
// Have we already done this?
if (used.contains(name.toLowerCase()))
continue;
used.add(name.toLowerCase());
boolean increase = karmaMatch.group(3).equals("++");
if (name.equalsIgnoreCase(nick))
increase = false;
// Karma flood check (skip if we checked this item with the reason earlier).
if (!name.equalsIgnoreCase(karmaReasonFloodCheck))
{
try
{
// 15 minute block for each karma item, irespective of who or direction.
int ret = (Integer)mods.plugin.callAPI("Flood", "IsFlooding", "Karma:" + name, FLOOD_RATE, 2);
if (ret != 0)
{
if (ret == 1)
irc.sendContextReply(mes, "Denied change to '" + name + "'! Karma changes limited to one change per item per " + FLOOD_RATE_STR + ".");
return;
}
}
catch (ChoobNoSuchCallException e)
{ } // ignore
catch (Throwable e)
{
System.err.println("Couldn't do antiflood call: " + e);
}
}
KarmaObject karmaObj = retrieveKarmaObject(name);
if (increase)
{
karmaObj.up++;
karmaObj.value++;
}
else
{
karmaObj.down++;
karmaObj.value--;
}
karmaObj.instName = name;
karmaObj.increase = increase;
karmaObjs.add(karmaObj);
}
saveKarmaObjects(karmaObjs);
// No actual karma changes. Maybe someone said "c++" or something.
if (karmaObjs.size() == 0)
return;
// Generate a pretty reply, all actual processing is done now:
if (karmaObjs.size() == 1)
{
KarmaObject info = karmaObjs.get(0);
if (info.string.equalsIgnoreCase(nick))
// This doesn't mention if there was a reason..
irc.sendContextReply(mes, "Fool, that's less karma to you! That leaves you with " + info.value + ".");
else
{
if (hasReason)
irc.sendContextReply(mes, "Given " + (info.increase ? "karma" : "less karma") + " to " + info.instName + ", and understood your reasons. New karma is " + info.value + ".");
else
irc.sendContextReply(mes, "Given " + (info.increase ? "karma" : "less karma") + " to " + info.instName + ". New karma is " + info.value + ".");
}
return;
}
StringBuffer output = new StringBuffer("Karma adjustments: ");
for (int i=0; i<karmaObjs.size(); i++)
{
KarmaObject info = karmaObjs.get(i);
output.append(info.instName);
output.append(info.increase ? " up" : " down");
if (i == 0 && hasReason)
output.append(", with reason");
output.append(" (now " + info.value + ")");
if (i != karmaObjs.size() - 1)
{
if (i == karmaObjs.size() - 2)
output.append(" and ");
else
output.append(", ");
}
}
output.append(".");
irc.sendContextReply( mes, output.toString());
}
| public synchronized void filterKarma( Message mes, Modules mods, IRCInterface irc )
{
// Ignore lines that look like commands.
if (Pattern.compile(irc.getTriggerRegex()).matcher(mes.getMessage()).find())
return;
Matcher reasonMatch = reasonPattern.matcher(mes.getMessage());
boolean hasReason = false;
String karmaReasonFloodCheck = "";
if (reasonMatch.matches())
{
// Find out which holds our name.
String name;
boolean skip = false;
// Group 1: quoted karma item
// Group 2: raw karma item
// Group 3: "++" or "--"
// Group 4: reason
if (reasonMatch.group(1) != null)
name = reasonMatch.group(1).replaceAll("\\\\(.)", "$1");
else
{
// need verification on this one.
name = reasonMatch.group(2);
if (exceptions.contains(name.toLowerCase()))
skip = true;
}
if (!skip)
{
// Wait until we know there's a real karma change going on.
if (mes instanceof PrivateEvent)
{
irc.sendContextReply(mes, "I'm sure other people want to hear what you have to think!");
return;
}
// Karma flood check.
karmaReasonFloodCheck = name;
try
{
// 15 minute block for each karma item, irespective of who or direction.
int ret = (Integer)mods.plugin.callAPI("Flood", "IsFlooding", "Karma:" + name.replaceAll(" ", "_"), FLOOD_RATE, 2);
if (ret != 0)
{
if (ret == 1)
irc.sendContextReply(mes, "Denied change to '" + name + "'! Karma changes limited to one change per item per " + FLOOD_RATE_STR + ".");
return;
}
}
catch (ChoobNoSuchCallException e)
{ } // ignore
catch (Throwable e)
{
System.err.println("Couldn't do antiflood call: " + e);
}
boolean increase = reasonMatch.group(3).equals("++");
final String sreason = reasonMatch.group(4);
if (!reasonExceptions.contains(sreason))
{
// Store the reason too.
KarmaReasonObject reason = new KarmaReasonObject();
reason.string = name;
reason.reason = sreason;
reason.direction = increase ? 1 : -1;
mods.odb.save(reason);
hasReason = true;
}
}
}
// Not a reasoned match, then.
Matcher karmaMatch = karmaPattern.matcher(mes.getMessage());
String nick = mods.nick.getBestPrimaryNick(mes.getNick());
HashSet used = new HashSet();
List<String> names = new ArrayList<String>();
List<KarmaObject> karmaObjs = new ArrayList<KarmaObject>();
while (karmaMatch.find() && karmaObjs.size() < 5)
{
String name;
boolean skip = false;
// Group 1: quoted karma item
// Group 2: raw karma item
// Group 3: "++" or "--"
if (karmaMatch.group(1) != null)
name = karmaMatch.group(1).replaceAll("\\\\(.)", "$1");
else
{
// need verification on this one.
name = karmaMatch.group(2);
if (exceptions.contains(name.toLowerCase()))
skip = true;
}
if (skip)
continue;
// Wait until we know there's a real karma change going on.
if (mes instanceof PrivateEvent)
{
irc.sendContextReply(mes, "I'm sure other people want to hear what you have to think!");
return;
}
if (name.equals/*NOT IgnoreCase*/("me"))
name=nick;
// Have we already done this?
if (used.contains(name.toLowerCase()))
continue;
used.add(name.toLowerCase());
boolean increase = karmaMatch.group(3).equals("++");
if (name.equalsIgnoreCase(nick))
increase = false;
// Karma flood check (skip if we checked this item with the reason earlier).
if (!name.equalsIgnoreCase(karmaReasonFloodCheck))
{
try
{
// 15 minute block for each karma item, irespective of who or direction.
int ret = (Integer)mods.plugin.callAPI("Flood", "IsFlooding", "Karma:" + name.replaceAll(" ", "_"), FLOOD_RATE, 2);
if (ret != 0)
{
if (ret == 1)
irc.sendContextReply(mes, "Denied change to '" + name + "'! Karma changes limited to one change per item per " + FLOOD_RATE_STR + ".");
return;
}
}
catch (ChoobNoSuchCallException e)
{ } // ignore
catch (Throwable e)
{
System.err.println("Couldn't do antiflood call: " + e);
}
}
KarmaObject karmaObj = retrieveKarmaObject(name);
if (increase)
{
karmaObj.up++;
karmaObj.value++;
}
else
{
karmaObj.down++;
karmaObj.value--;
}
karmaObj.instName = name;
karmaObj.increase = increase;
karmaObjs.add(karmaObj);
}
saveKarmaObjects(karmaObjs);
// No actual karma changes. Maybe someone said "c++" or something.
if (karmaObjs.size() == 0)
return;
// Generate a pretty reply, all actual processing is done now:
if (karmaObjs.size() == 1)
{
KarmaObject info = karmaObjs.get(0);
if (info.string.equalsIgnoreCase(nick))
// This doesn't mention if there was a reason..
irc.sendContextReply(mes, "Fool, that's less karma to you! That leaves you with " + info.value + ".");
else
{
if (hasReason)
irc.sendContextReply(mes, "Given " + (info.increase ? "karma" : "less karma") + " to " + info.instName + ", and understood your reasons. New karma is " + info.value + ".");
else
irc.sendContextReply(mes, "Given " + (info.increase ? "karma" : "less karma") + " to " + info.instName + ". New karma is " + info.value + ".");
}
return;
}
StringBuffer output = new StringBuffer("Karma adjustments: ");
for (int i=0; i<karmaObjs.size(); i++)
{
KarmaObject info = karmaObjs.get(i);
output.append(info.instName);
output.append(info.increase ? " up" : " down");
if (i == 0 && hasReason)
output.append(", with reason");
output.append(" (now " + info.value + ")");
if (i != karmaObjs.size() - 1)
{
if (i == karmaObjs.size() - 2)
output.append(" and ");
else
output.append(", ");
}
}
output.append(".");
irc.sendContextReply( mes, output.toString());
}
|
diff --git a/src/main/java/org/jinglenodes/sip/processor/SipProcessor.java b/src/main/java/org/jinglenodes/sip/processor/SipProcessor.java
index f93bd35..6c012d5 100644
--- a/src/main/java/org/jinglenodes/sip/processor/SipProcessor.java
+++ b/src/main/java/org/jinglenodes/sip/processor/SipProcessor.java
@@ -1,1040 +1,1036 @@
/*
* Copyright (C) 2011 - Jingle Nodes - Yuilop - Neppo
*
* This file is part of Switji (http://jinglenodes.org)
*
* Switji 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.
*
* Switji 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 MjSip; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author(s):
* Benhur Langoni ([email protected])
* Thiago Camargo ([email protected])
*/
package org.jinglenodes.sip.processor;
import org.apache.log4j.Logger;
import org.jinglenodes.jingle.Info;
import org.jinglenodes.jingle.Jingle;
import org.jinglenodes.jingle.Reason;
import org.jinglenodes.jingle.content.Content;
import org.jinglenodes.jingle.description.Description;
import org.jinglenodes.jingle.description.Payload;
import org.jinglenodes.jingle.processor.JingleException;
import org.jinglenodes.jingle.processor.JingleProcessor;
import org.jinglenodes.jingle.processor.JingleSipException;
import org.jinglenodes.jingle.transport.Candidate;
import org.jinglenodes.jingle.transport.RawUdpTransport;
import org.jinglenodes.prepare.CallPreparation;
import org.jinglenodes.prepare.PrepareStatesManager;
import org.jinglenodes.session.CallSession;
import org.jinglenodes.session.CallSessionMapper;
import org.jinglenodes.sip.GatewayRouter;
import org.jinglenodes.sip.SipPacketProcessor;
import org.jinglenodes.sip.SipToJingleBind;
import org.xmpp.packet.JID;
import org.xmpp.tinder.JingleIQ;
import org.zoolu.sip.address.NameAddress;
import org.zoolu.sip.address.SipURL;
import org.zoolu.sip.header.CSeqHeader;
import org.zoolu.sip.header.ContactHeader;
import org.zoolu.sip.header.ToHeader;
import org.zoolu.sip.message.*;
import org.zoolu.sip.provider.SipProviderInfoInterface;
import javax.sdp.*;
import javax.sdp.fields.AttributeField;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class SipProcessor implements SipPacketProcessor, PrepareStatesManager {
private static final Logger log = Logger.getLogger(SipProcessor.class);
public static final String emptyAddress = "0.0.0.0";
private SipProviderInfoInterface sipProviderInfo;
private GatewayRouter gatewayRouter;
private CallSessionMapper callSessions;
private JingleProcessor jingleProcessor;
private SipToJingleBind sipToJingleBind;
private boolean forceMapper = false;
private List<CallPreparation> preparations = new ArrayList<CallPreparation>();
public void processSip(final org.zoolu.sip.message.Message msg, final SipChannel sipChannel) {
log.debug("Processing SIP: " + msg.toString());
try {
final CallSession callSession = msg.isRequest() ? callSessions.addReceivedRequest(msg) : callSessions.addReceivedResponse(msg);
if (msg.isInvite() && msg.isRequest()) {
if (!isReInvite(msg)) {
for (final CallPreparation p : preparations) {
callSession.addCallPreparation(p);
}
prepareCall(msg, callSession, sipChannel);
return;
}
}
proceedCall(msg, callSession, sipChannel);
} catch (JingleException e) {
log.error("Could not Process Packet", e);
}
}
@Override
public void prepareCall(final Message msg, CallSession session, final SipChannel sipChannel) {
for (CallPreparation preparation = session.popCallPreparation(); preparation != null; preparation = session.popCallPreparation()) {
session.addCallProceed(preparation);
if (!preparation.prepareInitiate(msg, session, sipChannel)) return;
}
proceedCall(msg, session, sipChannel);
}
@Override
public void proceedCall(Message msg, CallSession session, final SipChannel sipChannel) {
try {
log.debug("Proceeding SIP: " + msg.toString());
final CSeqHeader ch = msg.getCSeqHeader();
if (msg.isRegister() || (ch != null && ch.getMethod().equals(SipMethods.REGISTER))) {
return;
}
final int statusLineCode = msg.getStatusLine() != null ? msg.getStatusLine().getCode() : -1;
// 200 OK
if (statusLineCode >= 200 && statusLineCode < 300 && ch != null && ch.getMethod() != null) {
if (ch.getMethod().equals(SipMethods.INVITE)) {
process2xxSip(msg);
}
}
// Bye Request
else if (msg.isBye()) {
processByeSip(msg, sipChannel);
}
// CANCEL Request
else if (msg.isCancel()) {
processCancelSip(msg, sipChannel);
}
// Invite Request
else if (msg.isInvite() && msg.isRequest()) {
if (isReInvite(msg)) {
processReInviteSip(msg, sipChannel);
} else {
processInviteSip(msg, sipChannel);
}
}
// Ringing
else if (msg.isRinging()) {
processRingingSip(msg);
}
// Ack
else if (msg.isAck()) {
processAckSip(msg);
}
// 486 BUSY, 408 TIMEOUT, 483 MANY HOPS
else if (statusLineCode > -1) {
processFailSip(msg, sipChannel);
} else if (msg.isOption()) {
processSipOption(msg);
}
} catch (JingleException e) {
log.error("Could not Parse Packet", e);
} catch (Throwable e) {
log.error("Severe Error Processing SIP Packet: " + msg, e);
}
}
@Override
public void prepareCall(JingleIQ iq, CallSession session) {
}
@Override
public void proceedCall(JingleIQ iq, CallSession session) {
}
public SipProviderInfoInterface getSipProviderInfo() {
return sipProviderInfo;
}
public void setSipProviderInfo(final SipProviderInfoInterface sipProviderInfo) {
this.sipProviderInfo = sipProviderInfo;
}
public GatewayRouter getGatewayRouter() {
return gatewayRouter;
}
public void setGatewayRouter(GatewayRouter gatewayRouter) {
this.gatewayRouter = gatewayRouter;
}
public boolean isForceMapper() {
return forceMapper;
}
public void setForceMapper(boolean forceMapper) {
this.forceMapper = forceMapper;
}
public CallSessionMapper getCallSessions() {
return callSessions;
}
public void setCallSessions(CallSessionMapper callSessions) {
this.callSessions = callSessions;
}
public JingleProcessor getJingleProcessor() {
return jingleProcessor;
}
public void setJingleProcessor(JingleProcessor jingleProcessor) {
this.jingleProcessor = jingleProcessor;
}
public boolean isReInvite(final org.zoolu.sip.message.Message msg) throws JingleException {
final CallSession callSession = callSessions.getSession(msg);
if (callSession == null) {
return false;
}
final org.zoolu.sip.message.Message lastResponse = callSession.getLastReceivedResponse();
if (lastResponse == null) {
return false;
}
final int statusLineCode = lastResponse.getStatusLine() != null ? lastResponse.getStatusLine().getCode() : -1;
final CSeqHeader ch = msg.getCSeqHeader();
return statusLineCode >= 200 && statusLineCode < 300 && ch != null && ch.getMethod() != null;
}
protected void process2xxSip(final org.zoolu.sip.message.Message msg) throws JingleException {
sendJingleAccepted(msg);
sendSipAck(msg);
}
protected void processByeSip(final org.zoolu.sip.message.Message msg, final SipChannel sipChannel) throws JingleException {
sendJingleTerminate(msg, sipChannel);
sendSipOk(msg);
callSessions.removeSession(callSessions.getSession(msg));
}
protected void processCancelSip(final org.zoolu.sip.message.Message msg, final SipChannel sipChannel) throws JingleException {
sendJingleTerminate(msg, sipChannel);
sendSipOk(msg);
callSessions.removeSession(callSessions.getSession(msg));
}
protected void processInviteSip(final org.zoolu.sip.message.Message msg, final SipChannel sipChannel) throws JingleException {
sendSipTrying(msg);
sendJingleInitialization(msg, sipChannel);
}
protected void processReInviteSip(final org.zoolu.sip.message.Message msg, final SipChannel sipChannel) throws JingleException {
final CallSession callSession = callSessions.getSession(msg);
JingleIQ iq = callSession.getLastSentJingle();
jingleProcessor.sendSipInviteOk(iq);
}
protected void processRingingSip(final org.zoolu.sip.message.Message msg) throws JingleException {
final int statusLineCode = msg.getStatusLine() != null ? msg.getStatusLine().getCode() : -1;
// if (statusLineCode == 183) {
// sendJingleEarlyMedia(msg);
// } else {
sendJingleRinging(msg);
// }
}
protected void processAckSip(final org.zoolu.sip.message.Message msg) throws JingleException {
// Fix Contact Address Update
if (msg.getContactHeader() != null) {
Participants p = null;
try {
p = msg.getParticipants();
} catch (SipParsingException e) {
log.error("Error Processing ACK.", e);
}
final CallSession t = callSessions.getSession(msg);
if (p != null && p.getInitiator() != null) {
t.addContact(p.getInitiator().toBareJID(), msg.getContactHeader());
}
}
}
protected void process100Sip(final org.zoolu.sip.message.Message msg) throws JingleException {
}
protected void processFailSip(final org.zoolu.sip.message.Message msg, final SipChannel sipChannel) throws JingleException {
final int statusLineCode = msg.getStatusLine() != null ? msg.getStatusLine().getCode() : -1;
boolean matches = false;
for (final int c : SipResponses.ackRequiredCodes) {
if (statusLineCode == c) {
matches = true;
break;
}
}
if (matches) {
if (msg.isInvite() || (msg.getCSeqHeader() != null && SipMethods.INVITE.equals(msg.getCSeqHeader().getMethod()))) {
sendJingleTerminate(msg, sipChannel);
}
sendSipAck(msg);
callSessions.removeSession(callSessions.getSession(msg));
}
}
protected void processSipOption(final org.zoolu.sip.message.Message msg) throws JingleException {
sendSipOk(msg);
}
public final void sendSipTrying(final Message msg) {
try {
final Message ringing = createSipTrying(msg, null);
callSessions.addSentResponse(ringing);
ringing.setSendTo(msg.getSendTo());
ringing.setArrivedAt(msg.getArrivedAt());
gatewayRouter.routeSIP(ringing, null);
} catch (JingleSipException e) {
log.error("Error Sending Trying", e);
} catch (JingleException e) {
log.error("Error Sending Trying", e);
}
}
public final void sendJingleRinging(final Message msg) {
final Participants participants;
try {
participants = msg.getParticipants();
final JID initiator = participants.getInitiator();
final JID responder = participants.getResponder();
JID to = initiator;
final CallSession callSession = callSessions.getSession(msg);
if (callSession != null) {
if (sipToJingleBind != null) {
to = sipToJingleBind.getXmppTo(initiator, callSession.getLastReceivedJingle());
}
for (final JID usr : callSession.getUsers()) {
if (to.toBareJID().equals(usr.toBareJID())) {
to = usr;
}
}
}
final JingleIQ iq = JingleProcessor.createJingleSessionInfo(initiator, responder, to.toString(), msg.getCallIdHeader().getCallId(), Info.Type.ringing);
callSessions.addSentJingle(iq);
gatewayRouter.send(iq);
} catch (JingleException e) {
log.error("Error Creating Ring Packet", e);
} catch (SipParsingException e) {
log.error("Error Sending Trying", e);
} catch (JingleSipException e) {
log.error("Error Creating Ring Packet", e);
}
}
public final void sendJingleAccepted(final Message msg) {
final Participants participants;
try {
try {
participants = msg.getParticipants();
} catch (SipParsingException e) {
log.error("Error Processing 200OK.", e);
return;
}
final JID initiator = participants.getInitiator();
JID responder = participants.getResponder();
JID to = initiator;
final CallSession callSession = callSessions.getSession(msg);
if (callSession != null) {
if (sipToJingleBind != null) {
to = sipToJingleBind.getXmppTo(initiator, callSession.getLastReceivedJingle());
}
for (final JID usr : callSession.getUsers()) {
if (to.toBareJID().equals(usr.toBareJID())) {
to = usr;
}
}
if (callSession.getLastReceivedJingle() != null) {
//TODO Dynamic Configure XMPP Route
responder = new JID(callSession.getLastReceivedJingle().getJingle().getResponder().split("@")[0] + "@sip.yuilop.tv");
}
}
final Content content = getContent(msg.getBody());
JingleIQ iq = JingleProcessor.createJingleAccept(initiator, responder, to.toString(), content, msg.getCallIdHeader().getCallId());
if (callSession != null) {
for (final CallPreparation preparation : callSession.getProceeds()) {
iq = preparation.proceedSIPAccept(iq, callSession, null);
}
}
callSessions.addSentJingle(iq);
gatewayRouter.send(iq);
} catch (JingleSipException e) {
log.error("Error creating Session-accept packet", e);
} catch (JingleException e) {
log.error("Error Sending Trying", e);
}
}
public final void sendJingleTerminate(final Message msg, final SipChannel sipChannel) {
try {
final CallSession callSession = callSessions.getSession(msg);
Participants mainParticipants;
try {
mainParticipants = msg.getParticipants();
} catch (SipParsingException e) {
log.debug("Error Processing BYE.", e);
return;
}
if (callSession == null) {
log.debug("CallSession not found for packet: " + msg.toString());
return;
}
JID initiator;
JID responder;
JID to;
if (callSession.getLastSentJingle() != null) {
initiator = new JID(callSession.getLastSentJingle().getJingle().getInitiator());
responder = new JID(callSession.getLastSentJingle().getJingle().getResponder());
} else if (callSession.getLastReceivedJingle() != null) {
initiator = new JID(callSession.getLastReceivedJingle().getJingle().getInitiator());
responder = new JID(callSession.getLastReceivedJingle().getJingle().getResponder());
} else {
log.info("Invalid CallSession to Terminate.");
return;
}
if (msg.isRequest()) {
to = mainParticipants.getResponder();
} else {
to = mainParticipants.getInitiator();
}
if (initiator.getResource() == null) {
if (initiator.toBareJID().equals(mainParticipants.getInitiator().toBareJID())) {
initiator = mainParticipants.getInitiator();
} else {
initiator = mainParticipants.getResponder();
}
} else if (responder.getResource() == null) {
if (responder.toBareJID().equals(mainParticipants.getResponder().toBareJID())) {
responder = mainParticipants.getResponder();
} else {
responder = mainParticipants.getInitiator();
}
}
// Try last Message as a last resort.
final Message lastMsg = callSession.getLastMessage();
if (lastMsg != null) {
mainParticipants = lastMsg.getParticipants();
}
if (mainParticipants == null) {
log.info("Invalid Participants on Message: " + msg);
return;
}
if (initiator.getResource() == null) {
if (initiator.toBareJID().equals(mainParticipants.getInitiator().toBareJID())) {
initiator = mainParticipants.getInitiator();
} else {
initiator = mainParticipants.getResponder();
}
} else if (responder.getResource() == null) {
if (responder.toBareJID().equals(mainParticipants.getResponder().toBareJID())) {
responder = mainParticipants.getResponder();
} else {
responder = mainParticipants.getInitiator();
}
}
- if (sipChannel != null && sipChannel.getId() != null) {
- to = JIDFactory.getInstance().getJID(sipChannel.getId());
- } else {
- if (sipToJingleBind != null) {
- to = sipToJingleBind.getXmppTo(to, callSession.getLastReceivedJingle());
- }
+ if (sipToJingleBind != null) {
+ to = sipToJingleBind.getXmppTo(to, callSession.getLastReceivedJingle());
}
for (final JID usr : callSession.getUsers()) {
if (to.toBareJID().equals(usr.toBareJID())) {
to = usr;
}
}
if (to.getResource() == null) {
if (to.toBareJID().equals(mainParticipants.getInitiator().toBareJID())) {
to = mainParticipants.getInitiator();
} else if (to.toBareJID().equals(mainParticipants.getResponder().toBareJID())) {
to = mainParticipants.getResponder();
}
}
final int code = getCode(msg);
final Reason reason = getReason(msg, code);
final JingleIQ terminate = JingleProcessor.createJingleTermination(initiator, responder, to.toString(), reason, msg.getCallIdHeader().getCallId());
for (final CallPreparation preparation : callSession.getProceeds()) {
preparation.proceedSIPTerminate(terminate, callSession, null);
}
callSessions.addSentJingle(terminate);
gatewayRouter.send(terminate);
} catch (JingleException e) {
log.debug("Error Processing BYE.", e);
} catch (SipParsingException e) {
log.debug("Error Processing BYE.", e);
}
}
public static int getCode(final Message msg) {
return msg.getStatusLine() != null ? msg.getStatusLine().getCode() : -1;
}
public static Reason getReason(final Message msg) {
final int code = getCode(msg);
return getReason(msg, code);
}
public static Reason getReason(final Message msg, final int code) {
final Reason reason;
switch (code) {
case 602:
reason = new Reason(code + " - " + msg.getStatusLine().getReason(), Reason.Type.decline);
break;
case 402:
reason = new Reason((code) + " - " + msg.getStatusLine().getReason(), Reason.Type.general_error);
break;
case 483:
case 404:
case 420:
case 405:
case 414:
case 484:
case 485:
reason = new Reason((code) + " - " + msg.getStatusLine().getReason(), Reason.Type.connectivity_error);
break;
case 486:
case 480:
reason = new Reason((code) + " - " + msg.getStatusLine().getReason(), Reason.Type.busy);
break;
case 415:
reason = new Reason((code) + " - " + msg.getStatusLine().getReason(), Reason.Type.media_error);
break;
case 403:
reason = new Reason((code) + " - " + msg.getStatusLine().getReason(), Reason.Type.security_error);
break;
case 487:
case -1:
reason = new Reason(Reason.Type.no_error);
break;
default:
reason = new Reason(code > 0 ? (code) + " - " + msg.getStatusLine().getReason() : String.valueOf(code), Reason.Type.no_error);
}
return reason;
}
public final void sendJingleInitialization(final Message msg, final SipChannel sipChannel) {
try {
//TODO Query and Inject Relay
final Participants participants = msg.getParticipants();
if (participants == null) {
log.info("Invalid Participants on Message: " + msg);
return;
}
JID initiator = participants.getInitiator();
final JID responder = participants.getResponder();
JID to = responder;
if (sipChannel != null && sipChannel.getId() != null && !isForceMapper()) {
to = JIDFactory.getInstance().getJID(sipChannel.getId());
} else {
if (sipToJingleBind != null) {
to = sipToJingleBind.getXmppTo(responder, null);
}
}
final Content content = getContent(msg.getBody());
// Added to Support Display Name Translation
final String display = msg.getFromHeader().getNameAddress().getDisplayName();
if (display != null && !display.trim().equals("")) {
content.setName(display.trim());
}
final JingleIQ initialization = JingleProcessor.createJingleInitialization(initiator, responder, to.toString(), content, msg.getCallIdHeader().getCallId());
initialization.setTo(to);
final CallSession callSession = callSessions.addSentJingle(initialization);
callSession.setInitiateIQ(initialization);
callSession.addContact(initiator.toBareJID(), msg.getContactHeader());
for (final CallPreparation preparation : callSession.getProceeds()) {
preparation.proceedSIPInitiate(initialization, callSession, null);
}
gatewayRouter.send(initialization);
} catch (JingleSipException e) {
log.error("Error Processing INVITE.", e);
} catch (SipParsingException e) {
log.debug("Error Processing INVITE.", e);
} catch (Throwable e) {
log.debug("SEVERE - Error Processing INVITE.", e);
}
}
public final void sendJingleEarlyMedia(final Message msg) {
try {
final Participants participants;
participants = msg.getParticipants();
final JID initiator = participants.getInitiator();
final JID responder = participants.getResponder();
JID to = initiator;
final CallSession callSession = callSessions.getSession(msg);
if (callSession != null) {
if (sipToJingleBind != null) {
to = sipToJingleBind.getXmppTo(initiator, callSession.getLastReceivedJingle());
}
for (final JID usr : callSession.getUsers()) {
if (to.toBareJID().equals(usr.toBareJID())) {
to = usr;
}
}
}
final Content content = getContent(msg.getBody());
JingleIQ iq = JingleProcessor.createJingleEarlyMedia(initiator, responder, to.toString(), content, msg.getCallIdHeader().getCallId());
if (callSession != null) {
for (final CallPreparation preparation : callSession.getProceeds()) {
iq = preparation.proceedSIPEarlyMedia(iq, callSession, null);
}
}
callSessions.addSentJingle(iq);
gatewayRouter.send(iq);
} catch (JingleSipException e) {
log.error("Error Creating Ring Packet", e);
} catch (JingleException e) {
log.error("Error Sending Trying", e);
} catch (SipParsingException e) {
log.error("Error Sending Trying", e);
}
}
public final void sendSipOk(final Message msg) {
try {
final Message response = createSipOk(msg, sipProviderInfo);
response.setSendTo(msg.getSendTo());
response.setArrivedAt(msg.getArrivedAt());
gatewayRouter.routeSIP(response, null);
} catch (JingleSipException e) {
log.error("Error Creating SIP OK", e);
}
}
public final void sendSipAck(final Message msg) {
final Message ack = createSipAck(msg, sipProviderInfo);
ack.setSendTo(msg.getSendTo());
ack.setArrivedAt(msg.getArrivedAt());
gatewayRouter.routeSIP(ack, null);
}
public final void sendSipNon2xxAck(final Message msg) {
final Message ack = createSipNon2xxAck(msg, sipProviderInfo);
ack.setSendTo(msg.getSendTo());
ack.setArrivedAt(msg.getArrivedAt());
gatewayRouter.routeSIP(ack, null);
}
public void setSipToJingleBind(SipToJingleBind sipToJingleBind) {
this.sipToJingleBind = sipToJingleBind;
}
public void processSipPacket(ByteBuffer byteBuffer, SocketAddress address, SipChannel channel) {
try {
byteBuffer.rewind();
final byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes);
if (bytes.length < 40) {
return;
}
final Message message = new Message(bytes, 0, bytes.length);
message.setArrivedAt(channel);
message.setSendTo(address);
message.setArrivedAt(channel);
processSip(message, channel);
} catch (Throwable e) {
log.error("Severe Error Parsing SIP Message.", e);
}
}
public static enum MediaDirection {
both,
sendonly,
recvonly,
none
}
public static Message createSipInvite(final JID initiator, final JID responder, final String sid, final SipProviderInfoInterface sipProvider, final Description rtpDescription, final RawUdpTransport transport) throws SdpException {
final String contact = getContact(initiator.getNode(), sipProvider);
final SessionDescription description = createSipSDP(rtpDescription, transport, sipProvider);
final String to = responder.toBareJID();
final String from = initiator.toBareJID();
return MessageFactory.createInviteRequest(sipProvider, new SipURL(to), new NameAddress(to.split("@")[0], new SipURL(to)), new NameAddress(from, new SipURL(from)), new NameAddress(new SipURL(contact)), description.toString(), sid, initiator.getResource());
}
public static Message createSipOnHold(final JID initiator, final JID responder, final String sid, final SipProviderInfoInterface sipProvider, final Description rtpDescription, final RawUdpTransport transport) throws SdpException {
final String contact = getContact(initiator.getNode(), sipProvider);
final SessionDescription description = createSipSDP(rtpDescription, transport, sipProvider);
description.setAttribute("c", emptyAddress);
description.setAttribute("s", "");
final String to = responder.toBareJID();
final String from = initiator.toBareJID();
return MessageFactory.createInviteRequest(sipProvider, new SipURL(to), new NameAddress(to.split("@")[0], new SipURL(to)), new NameAddress(from, new SipURL(from)), new NameAddress(new SipURL(contact)), description.toString(), sid, initiator.getResource());
}
public static String getContact(final String node, final SipProviderInfoInterface sipProvider) {
return node + "@" + sipProvider.getIP() + ":" + sipProvider.getPort() + ";transport=udp";
}
public static SessionDescription createSipSDP(final Description rtpDescription, final RawUdpTransport transport, final SipProviderInfoInterface sipProvider) throws SdpException {
return createSipSDP(rtpDescription, transport, sipProvider, MediaDirection.both);
}
public static SessionDescription createSipSDP(final Description rtpDescription, final RawUdpTransport transport, final SipProviderInfoInterface sipProvider, final MediaDirection mediaDirection) throws SdpException {
final SessionDescription description = SdpFactory.getInstance().createSessionDescription(sipProvider);
final int[] ids = new int[rtpDescription.getPayloads().size()];
int i = 0;
final List<String> names = new ArrayList<String>();
final List<String> values = new ArrayList<String>();
for (final Payload payload : rtpDescription.getPayloads()) {
ids[i++] = Integer.parseInt(payload.getId());
names.add("rtpmap");
values.add(payload.getId() + " " + payload.getName() + (payload.getClockrate() > -1 ? "/" + payload.getClockrate() : "") + (payload.getChannels() > -1 ? "/" + payload.getChannels() : ""));
// Fix for G729 prevent VAD support
if (payload.equals(Payload.G729)) {
names.add("fmtp");
values.add(String.valueOf(payload.getId()) + " annexb=no");
}
}
if (transport.getCandidates().size() < 1) {
throw new SdpException("No Transports Found in Jingle Packet.");
}
final MediaDescription md = SdpFactory.getInstance().createMediaDescription(rtpDescription.getMedia(), Integer.parseInt(transport.getCandidates().get(0).getPort()), 1, "RTP/AVP", ids);
md.addDynamicPayloads(names, values);
final AttributeField af = new AttributeField();
if (!MediaDirection.both.equals(mediaDirection)) {
af.setValueAllowNull(mediaDirection.toString());
md.addAttribute(af);
} else {
af.setValueAllowNull("sendrecv");
md.addAttribute(af);
}
final List<MediaDescription> mv = new ArrayList<MediaDescription>();
mv.add(md);
description.setMediaDescriptions(mv);
String ip = transport.getCandidates().get(0).getIp();
ip = ip == null || ip.trim().length() < 7 ? sipProvider.getIP() : ip;
final Origin origin = SdpFactory.getInstance().createOrigin("J2S", ip);
origin.setSessionId(3);
origin.setSessionVersion(1);
description.setOrigin(origin);
description.setConnection(SdpFactory.getInstance().createConnection(ip));
return description;
}
public static Message createSipAck(final Message response, final SipProviderInfoInterface sipProvider) {
return MessageFactory.create2xxAckRequest(sipProvider, response, null);
}
public static Message createSipNon2xxAck(final Message response, final SipProviderInfoInterface sipProvider) {
SipURL requestUri = response.getContactHeader() != null ? response.getContactHeader().getNameAddress().getAddress() : response.getFromHeader().getNameAddress().getAddress();
return MessageFactory.createNon2xxAckRequest(sipProvider, response, requestUri);
}
public static Message createSipOk(final Message request, final String fromTag, final SipProviderInfoInterface sipProvider) throws JingleSipException {
final String contact = getContact(request.getToHeader().getNameAddress().getAddress().getUserName(), sipProvider);
return MessageFactory.createResponse(request, 200, SipResponses.reasonOf(200), fromTag, new NameAddress(contact), "audio", "");
}
public static Message createSipOk(final Message request, final SipProviderInfoInterface sipProvider) throws JingleSipException {
final ToHeader toHeader = request.getToHeader();
if (toHeader != null) {
final NameAddress nameAddress = toHeader.getNameAddress();
if (nameAddress != null) {
final SipURL address = nameAddress.getAddress();
if (address != null) {
final String contact = getContact(address.getUserName(), sipProvider);
return MessageFactory.createResponse(request, 200, SipResponses.reasonOf(200), toHeader.getTag(), new NameAddress(contact), "audio", "");
}
throw new JingleSipException("Could NOT get Address for: " + request);
}
throw new JingleSipException("Could NOT get NameAddress for: " + request);
}
throw new JingleSipException("Could NOT get ToHeader for: " + request);
}
public static Message createSipBye(final JID initiator, final JID responder, final String sid, final SipProviderInfoInterface sipProvider, final Message lastMessage, final NameAddress requestURI) {
return MessageFactory.createByeRequest(sipProvider, new NameAddress(new SipURL(responder.toBareJID())), new NameAddress(new SipURL(initiator.toBareJID())), sid, initiator.getResource(), responder.getResource(), lastMessage, requestURI);
}
public static Message createSipCancel(final Message lastMessage) throws JingleSipException {
if (lastMessage == null) {
throw new JingleSipException("Failed to create CANCEL Request. No arguments.");
}
final Message cancel = MessageFactory.createCancelRequest(lastMessage);
if (cancel == null) {
throw new JingleSipException("Failed to create CANCEL Request. Null return.");
}
return cancel;
}
public static Message createSipInvite(final Jingle iq, final SipProviderInfoInterface sipProvider) throws JingleSipException, SdpException {
// Checks to verify if the conversion is supported
if (!iq.getAction().equals(Jingle.SESSION_INITIATE)) {
throw new JingleSipException("The IQ MUST have a session-initiate action.");
}
if (iq.getContent() == null) {
throw new JingleSipException("Session Description Required.");
}
final Content content = iq.getContent();
// Checks to verify if the conversion is supported
if (!(content.getDescription() instanceof Description)) {
throw new JingleSipException("Only RTP Session Description Supported.");
}
final Description description = content.getDescription();
// Checks to verify if the conversion is supported
if (!(content.getTransport() instanceof RawUdpTransport)) {
throw new JingleSipException("Only RAW Transport Supported.");
}
final RawUdpTransport transport = content.getTransport();
return createSipInvite(JIDFactory.getInstance().getJID(iq.getInitiator()), JIDFactory.getInstance().getJID(iq.getResponder()), iq.getSid(), sipProvider, description, transport);
}
public static Message createSipBye(final JingleIQ iq, final SipProviderInfoInterface sipProvider, final Message lastResponse, final CallSession callSession) throws JingleSipException, SipParsingException {
// Checks to verify if the conversion is supported
// if (!iq.getJingle().getAction().equals(Jingle.SESSION_TERMINATE)) {
// throw new JingleSipException("The IQ MUST have a session-terminate action.");
// }
if (lastResponse == null) {
throw new JingleSipException("No related Message Found.");
}
final Participants p;
p = Participants.getParticipants(lastResponse);
final JID from;
final JID to;
if (iq.getFrom().toBareJID().equals(p.getResponder().toBareJID())) {
from = p.getResponder();
to = p.getInitiator();
} else {
from = p.getInitiator();
to = p.getResponder();
}
final ContactHeader contactHeader = callSession.getContactHeader(to.toBareJID());
NameAddress requestURI = null;
if (contactHeader != null) {
requestURI = contactHeader.getNameAddress();
}
final Message bye = createSipBye(from, to, iq.getJingle().getSid(), sipProvider, lastResponse, requestURI);
if (bye == null) {
throw new JingleSipException("Failed to create BYE Request.");
}
return bye;
}
public static Message createSipRinging(final Message req, final JID from, final String fromTag, final SipProviderInfoInterface sipProvider) throws JingleSipException {
final NameAddress contact = new NameAddress(getContact(from.getNode(), sipProvider));
return MessageFactory.createResponse(req, 180, BaseSipResponses.reasonOf(180), fromTag, contact, "audio", "");
}
public static Message createSipTrying(final Message req, final String fromTag) throws JingleSipException {
return MessageFactory.createResponse(req, 100, BaseSipResponses.reasonOf(100), fromTag, null, "audio", "");
}
public static Content getContent(final String sdpDescription) throws JingleSipException {
final Description rtpDescription;
final RawUdpTransport rawTransport;
if (sdpDescription == null) {
throw new JingleSipException("SDP Parsing Error. SDP Missing.");
}
try {
final SessionDescription sdp = SdpFactory.getInstance().createSessionDescription(sdpDescription);
final List m = sdp.getMediaDescriptions(true);
final List<Payload> sdpPayloads = new ArrayList<Payload>();
// Ignore Extra Contents
final MediaDescription md = (MediaDescription) m.get(0);
final HashMap<Integer, Payload> payloads = new HashMap<Integer, Payload>();
final List atbs = md.getAttributes(false);
for (final Object atb : atbs) {
if (atb instanceof AttributeField) {
final AttributeField codec = (AttributeField) atb;
final String key = codec.getName();
final String value = codec.getValue();
if ("rtpmap".equals(key)) {
try {
String c[] = value.split(" ");
final int id = Integer.valueOf(c[0]);
c = c[1].split("/");
final String name = c[0];
int rate = -1;
int channels = 1;
if (c.length > 1) {
rate = Integer.valueOf(c[1]);
if (c.length > 2) {
channels = Integer.valueOf(c[2]);
}
}
final Payload p = new Payload(c[0], name, rate, channels);
payloads.put(id, p);
} catch (Exception e) {
// Ignore Payload
}
}
}
}
final List p = md.getMedia().getMediaFormats(false);
if (p == null) {
throw new JingleSipException("SDP Parsing Error.");
}
// Calculate Payloads that Matches with Supported Payloads
for (final Object aP : p) {
final String mm = (String) aP;
final int id = Integer.valueOf(mm);
Payload payload = Payload.getPayload(id);
if (payload != null)
sdpPayloads.add(payload);
}
final String type = md.getMedia().getMediaType();
rtpDescription = new Description(type);
rtpDescription.addPayload(sdpPayloads);
rawTransport = new RawUdpTransport(new Candidate(sdp.getConnection().getAddress(), String.valueOf(md.getMedia().getMediaPort()), "0"));
return new Content("initiator", sdp.getOrigin().getUsername(), "both", rtpDescription, rawTransport);
} catch (SdpParseException e) {
throw new JingleSipException("SDP Parsing Error.");
} catch (SdpException e) {
throw new JingleSipException("SDP Parsing Error.");
} catch (Throwable e) {
throw new JingleSipException("Critical SDP Parsing Error:" + sdpDescription);
}
}
public void setPreparations(List<CallPreparation> preparations) {
this.preparations = preparations;
}
}
| true | true | public final void sendJingleTerminate(final Message msg, final SipChannel sipChannel) {
try {
final CallSession callSession = callSessions.getSession(msg);
Participants mainParticipants;
try {
mainParticipants = msg.getParticipants();
} catch (SipParsingException e) {
log.debug("Error Processing BYE.", e);
return;
}
if (callSession == null) {
log.debug("CallSession not found for packet: " + msg.toString());
return;
}
JID initiator;
JID responder;
JID to;
if (callSession.getLastSentJingle() != null) {
initiator = new JID(callSession.getLastSentJingle().getJingle().getInitiator());
responder = new JID(callSession.getLastSentJingle().getJingle().getResponder());
} else if (callSession.getLastReceivedJingle() != null) {
initiator = new JID(callSession.getLastReceivedJingle().getJingle().getInitiator());
responder = new JID(callSession.getLastReceivedJingle().getJingle().getResponder());
} else {
log.info("Invalid CallSession to Terminate.");
return;
}
if (msg.isRequest()) {
to = mainParticipants.getResponder();
} else {
to = mainParticipants.getInitiator();
}
if (initiator.getResource() == null) {
if (initiator.toBareJID().equals(mainParticipants.getInitiator().toBareJID())) {
initiator = mainParticipants.getInitiator();
} else {
initiator = mainParticipants.getResponder();
}
} else if (responder.getResource() == null) {
if (responder.toBareJID().equals(mainParticipants.getResponder().toBareJID())) {
responder = mainParticipants.getResponder();
} else {
responder = mainParticipants.getInitiator();
}
}
// Try last Message as a last resort.
final Message lastMsg = callSession.getLastMessage();
if (lastMsg != null) {
mainParticipants = lastMsg.getParticipants();
}
if (mainParticipants == null) {
log.info("Invalid Participants on Message: " + msg);
return;
}
if (initiator.getResource() == null) {
if (initiator.toBareJID().equals(mainParticipants.getInitiator().toBareJID())) {
initiator = mainParticipants.getInitiator();
} else {
initiator = mainParticipants.getResponder();
}
} else if (responder.getResource() == null) {
if (responder.toBareJID().equals(mainParticipants.getResponder().toBareJID())) {
responder = mainParticipants.getResponder();
} else {
responder = mainParticipants.getInitiator();
}
}
if (sipChannel != null && sipChannel.getId() != null) {
to = JIDFactory.getInstance().getJID(sipChannel.getId());
} else {
if (sipToJingleBind != null) {
to = sipToJingleBind.getXmppTo(to, callSession.getLastReceivedJingle());
}
}
for (final JID usr : callSession.getUsers()) {
if (to.toBareJID().equals(usr.toBareJID())) {
to = usr;
}
}
if (to.getResource() == null) {
if (to.toBareJID().equals(mainParticipants.getInitiator().toBareJID())) {
to = mainParticipants.getInitiator();
} else if (to.toBareJID().equals(mainParticipants.getResponder().toBareJID())) {
to = mainParticipants.getResponder();
}
}
final int code = getCode(msg);
final Reason reason = getReason(msg, code);
final JingleIQ terminate = JingleProcessor.createJingleTermination(initiator, responder, to.toString(), reason, msg.getCallIdHeader().getCallId());
for (final CallPreparation preparation : callSession.getProceeds()) {
preparation.proceedSIPTerminate(terminate, callSession, null);
}
callSessions.addSentJingle(terminate);
gatewayRouter.send(terminate);
} catch (JingleException e) {
log.debug("Error Processing BYE.", e);
} catch (SipParsingException e) {
log.debug("Error Processing BYE.", e);
}
}
| public final void sendJingleTerminate(final Message msg, final SipChannel sipChannel) {
try {
final CallSession callSession = callSessions.getSession(msg);
Participants mainParticipants;
try {
mainParticipants = msg.getParticipants();
} catch (SipParsingException e) {
log.debug("Error Processing BYE.", e);
return;
}
if (callSession == null) {
log.debug("CallSession not found for packet: " + msg.toString());
return;
}
JID initiator;
JID responder;
JID to;
if (callSession.getLastSentJingle() != null) {
initiator = new JID(callSession.getLastSentJingle().getJingle().getInitiator());
responder = new JID(callSession.getLastSentJingle().getJingle().getResponder());
} else if (callSession.getLastReceivedJingle() != null) {
initiator = new JID(callSession.getLastReceivedJingle().getJingle().getInitiator());
responder = new JID(callSession.getLastReceivedJingle().getJingle().getResponder());
} else {
log.info("Invalid CallSession to Terminate.");
return;
}
if (msg.isRequest()) {
to = mainParticipants.getResponder();
} else {
to = mainParticipants.getInitiator();
}
if (initiator.getResource() == null) {
if (initiator.toBareJID().equals(mainParticipants.getInitiator().toBareJID())) {
initiator = mainParticipants.getInitiator();
} else {
initiator = mainParticipants.getResponder();
}
} else if (responder.getResource() == null) {
if (responder.toBareJID().equals(mainParticipants.getResponder().toBareJID())) {
responder = mainParticipants.getResponder();
} else {
responder = mainParticipants.getInitiator();
}
}
// Try last Message as a last resort.
final Message lastMsg = callSession.getLastMessage();
if (lastMsg != null) {
mainParticipants = lastMsg.getParticipants();
}
if (mainParticipants == null) {
log.info("Invalid Participants on Message: " + msg);
return;
}
if (initiator.getResource() == null) {
if (initiator.toBareJID().equals(mainParticipants.getInitiator().toBareJID())) {
initiator = mainParticipants.getInitiator();
} else {
initiator = mainParticipants.getResponder();
}
} else if (responder.getResource() == null) {
if (responder.toBareJID().equals(mainParticipants.getResponder().toBareJID())) {
responder = mainParticipants.getResponder();
} else {
responder = mainParticipants.getInitiator();
}
}
if (sipToJingleBind != null) {
to = sipToJingleBind.getXmppTo(to, callSession.getLastReceivedJingle());
}
for (final JID usr : callSession.getUsers()) {
if (to.toBareJID().equals(usr.toBareJID())) {
to = usr;
}
}
if (to.getResource() == null) {
if (to.toBareJID().equals(mainParticipants.getInitiator().toBareJID())) {
to = mainParticipants.getInitiator();
} else if (to.toBareJID().equals(mainParticipants.getResponder().toBareJID())) {
to = mainParticipants.getResponder();
}
}
final int code = getCode(msg);
final Reason reason = getReason(msg, code);
final JingleIQ terminate = JingleProcessor.createJingleTermination(initiator, responder, to.toString(), reason, msg.getCallIdHeader().getCallId());
for (final CallPreparation preparation : callSession.getProceeds()) {
preparation.proceedSIPTerminate(terminate, callSession, null);
}
callSessions.addSentJingle(terminate);
gatewayRouter.send(terminate);
} catch (JingleException e) {
log.debug("Error Processing BYE.", e);
} catch (SipParsingException e) {
log.debug("Error Processing BYE.", e);
}
}
|
diff --git a/sopc2dts/sopc2dts/lib/AvalonSystem.java b/sopc2dts/sopc2dts/lib/AvalonSystem.java
index 13a3194..4ac3bdb 100644
--- a/sopc2dts/sopc2dts/lib/AvalonSystem.java
+++ b/sopc2dts/sopc2dts/lib/AvalonSystem.java
@@ -1,96 +1,99 @@
/*
sopc2dts - Devicetree generation for Altera systems
Copyright (C) 2011 Walter Goossens <[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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package sopc2dts.lib;
import java.io.File;
import java.util.Vector;
import sopc2dts.lib.components.BasicComponent;
public class AvalonSystem extends BasicElement {
private static final long serialVersionUID = -4412823810569371574L;
public enum SystemDataType { MEMORY_MAPPED, STREAMING, INTERRUPT, CLOCK,
CUSTOM_INSTRUCTION, RESET, CONDUIT };
protected String versionStr = "";
protected File sourceFile;
private String systemName;
protected Vector<BasicComponent> vSystemComponents = new Vector<BasicComponent>();
public AvalonSystem(String name, String version, File f) {
versionStr = version;
sourceFile = f;
systemName = name;
}
public BasicComponent getComponentByName(String name)
{
for(BasicComponent c : getSystemComponents())
{
if(c.getInstanceName().equalsIgnoreCase(name))
{
return c;
}
}
return null;
}
public Vector<BasicComponent> getMasterComponents() {
Vector<BasicComponent> vRes = new Vector<BasicComponent>();
for(BasicComponent comp : vSystemComponents)
{
if(comp.hasMemoryMaster())
{
vRes.add(comp);
}
}
return vRes;
}
public File getSourceFile()
{
return sourceFile;
}
public Vector<BasicComponent> getSystemComponents() {
return vSystemComponents;
}
public String getSystemName() {
return systemName;
}
public void setVersion(String string) {
versionStr = string;
}
public void recheckComponents()
{
for(BasicComponent comp : vSystemComponents)
{
SopcComponentLib.getInstance().finalCheckOnComponent(comp);
}
/*
* Now remove tristate (and other unneeded) bridges. If any.
* Also flatten hierarchical qsys designs.
*/
for(int i=0; i<vSystemComponents.size();)
{
int oldSize = vSystemComponents.size();
BasicComponent c = vSystemComponents.get(i);
c.removeFromSystemIfPossible(this);
+ //Move back the number of components removed, or advance
i+= (vSystemComponents.size() - oldSize) + 1;
+ //Don't move back beyond the beginning.
+ if(i<0) i=0;
}
}
}
| false | true | public void recheckComponents()
{
for(BasicComponent comp : vSystemComponents)
{
SopcComponentLib.getInstance().finalCheckOnComponent(comp);
}
/*
* Now remove tristate (and other unneeded) bridges. If any.
* Also flatten hierarchical qsys designs.
*/
for(int i=0; i<vSystemComponents.size();)
{
int oldSize = vSystemComponents.size();
BasicComponent c = vSystemComponents.get(i);
c.removeFromSystemIfPossible(this);
i+= (vSystemComponents.size() - oldSize) + 1;
}
}
| public void recheckComponents()
{
for(BasicComponent comp : vSystemComponents)
{
SopcComponentLib.getInstance().finalCheckOnComponent(comp);
}
/*
* Now remove tristate (and other unneeded) bridges. If any.
* Also flatten hierarchical qsys designs.
*/
for(int i=0; i<vSystemComponents.size();)
{
int oldSize = vSystemComponents.size();
BasicComponent c = vSystemComponents.get(i);
c.removeFromSystemIfPossible(this);
//Move back the number of components removed, or advance
i+= (vSystemComponents.size() - oldSize) + 1;
//Don't move back beyond the beginning.
if(i<0) i=0;
}
}
|
diff --git a/src/test/java/ar/edu/utn/tacs/group5/controller/LoginControllerTest.java b/src/test/java/ar/edu/utn/tacs/group5/controller/LoginControllerTest.java
index 0e72240..91b528d 100644
--- a/src/test/java/ar/edu/utn/tacs/group5/controller/LoginControllerTest.java
+++ b/src/test/java/ar/edu/utn/tacs/group5/controller/LoginControllerTest.java
@@ -1,18 +1,19 @@
package ar.edu.utn.tacs.group5.controller;
import org.slim3.tester.ControllerTestCase;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
public class LoginControllerTest extends ControllerTestCase {
@Test
public void run() throws Exception {
- tester.start("/Login");
+ tester.param(Constants.USER_ID, "123456789");
+ tester.start("/login");
LoginController controller = tester.getController();
assertThat(controller, is(notNullValue()));
assertThat(tester.isRedirect(), is(false));
assertThat(tester.getDestinationPath(), is(nullValue()));
}
}
| true | true | public void run() throws Exception {
tester.start("/Login");
LoginController controller = tester.getController();
assertThat(controller, is(notNullValue()));
assertThat(tester.isRedirect(), is(false));
assertThat(tester.getDestinationPath(), is(nullValue()));
}
| public void run() throws Exception {
tester.param(Constants.USER_ID, "123456789");
tester.start("/login");
LoginController controller = tester.getController();
assertThat(controller, is(notNullValue()));
assertThat(tester.isRedirect(), is(false));
assertThat(tester.getDestinationPath(), is(nullValue()));
}
|
diff --git a/src/marrc/Driver.java b/src/marrc/Driver.java
index efae9f3..4038680 100644
--- a/src/marrc/Driver.java
+++ b/src/marrc/Driver.java
@@ -1,171 +1,173 @@
package marrc;
import java.util.Random;
import vision.*;
import mobile.*;
public class Driver implements Runnable{
final int SPEED = 200; // mm/s
Capture camera;
Detect detector;
Manager m;
Mover mv;
boolean qrDetected, bumped, locked, auto;
private String qrSeen; // should be a set of strings for multiple qr codes, but...
Thread photographer, detective;
private long nextMove;
Driver(Manager m) {
this.m = m;
m.registerDriver(this);
mv = m.getMover();
nextMove = 0;
qrDetected = false;
bumped = false;
locked = false;
auto = false;
camera = new Capture(m);
if(camera.success()) {
photographer = new Thread(camera);
photographer.start();
m.registerCapture(camera);
} else {
m.registerCapture(null);
}
}
public boolean isLocked() { return locked; }
public void run() {
driveRandomly();
// int[] qrLoc;
// while(true) {
// while ((qrLoc = detector.detect("img/0.jpg")) == null) {
// driveRandomly();
// //Thread.sleep(500);
// }
//
// driveTowards(qrLoc);
// }
}
public boolean hasQR() {
return qrSeen.equals("yes");
}
private void slightRight(int time) {
mv.right(SPEED);
}
private void slightLeft(int time) {
mv.left(SPEED);
}
private void driveWait(int time) {
boolean localLock = !locked; // if its not locked, lock locally
locked = true;
long waitTime = System.currentTimeMillis() + time;
nextMove = waitTime + 10;
while (waitTime > System.currentTimeMillis()) { Thread.yield(); }
if (localLock) { locked = false; } // don't release if it wasn't locked locally
}
private void driveWaitWithInterrupt (int time) {
int count = 0;
while(count < time && (!qrDetected && !bumped)) {
driveWait(10);
count += 10;
}
}
public void setAutomatic() {
auto = true;
}
public void eventOccured(String event) {
if(event.contains("QR")) {
if(qrDetected || qrSeen.equals("yes")) { return; }
qrDetected = true;
qrSeen = "yes";
System.out.println("Saw something!!");
driveTowardsQR();
qrDetected = false;
} else if (event.contains("bump")) {
+ System.out.print("Trying bump...");
if(bumped) { return; }
+ System.out.println("\tbumping");
bumped = true;
locked = true;
mv.stop();
mv.reverse(SPEED);
driveWait(200);
mv.stop();
if(event.contains("center")) {
if(Math.random() > 0.5) {
slightRight(500);
} else {
slightLeft(500);
}
} else {
if(event.contains("left")) {
slightRight(200);
} else if (event.contains("right")) {
slightLeft(200);
}
}
mv.stop();
driveWait(500);
bumped = false;
locked = false;
if(auto) { driveRandomly(); }
}
}
private void driveRandomly() {
// System.out.println("New call to driveRandomly");
Random r = new Random();
while(!qrDetected && !bumped) {
if ((bumped || qrDetected) || (locked || nextMove > System.currentTimeMillis())) { Thread.yield(); continue; }
// makes sure driving is mostly forward
switch(r.nextInt(5)) {
case 1: // turn left
mv.left(SPEED);
driveWaitWithInterrupt(250 + r.nextInt(250)); // turn this direction for up to a half second
break;
case 2: // turn right
mv.right(SPEED);
driveWaitWithInterrupt(250 + r.nextInt(250)); // turn this direction for up to a half second
break;
default: // forward
mv.forward(SPEED);
driveWaitWithInterrupt(500 + r.nextInt(500)); // drive this direction for up to a second
}
}
}
private void driveTowardsQR() {
while (!bumped) {
driveTowards(m.getQRX());
}
}
private void driveTowards(int i) {
if (i < 0) { return; }
// loc[0] is x coordinate, disregard y
if (i < (Capture.imageWidth / 3)) {
slightRight(50);
// System.out.println("Right");
} else if (i > (2*Capture.imageWidth / 3)) {
slightLeft(50);
// System.out.println("Left");
} else {
// System.out.println("Forward");
mv.forward(SPEED);
driveWaitWithInterrupt(50);
}
}
}
| false | true | public void eventOccured(String event) {
if(event.contains("QR")) {
if(qrDetected || qrSeen.equals("yes")) { return; }
qrDetected = true;
qrSeen = "yes";
System.out.println("Saw something!!");
driveTowardsQR();
qrDetected = false;
} else if (event.contains("bump")) {
if(bumped) { return; }
bumped = true;
locked = true;
mv.stop();
mv.reverse(SPEED);
driveWait(200);
mv.stop();
if(event.contains("center")) {
if(Math.random() > 0.5) {
slightRight(500);
} else {
slightLeft(500);
}
} else {
if(event.contains("left")) {
slightRight(200);
} else if (event.contains("right")) {
slightLeft(200);
}
}
mv.stop();
driveWait(500);
bumped = false;
locked = false;
if(auto) { driveRandomly(); }
}
}
| public void eventOccured(String event) {
if(event.contains("QR")) {
if(qrDetected || qrSeen.equals("yes")) { return; }
qrDetected = true;
qrSeen = "yes";
System.out.println("Saw something!!");
driveTowardsQR();
qrDetected = false;
} else if (event.contains("bump")) {
System.out.print("Trying bump...");
if(bumped) { return; }
System.out.println("\tbumping");
bumped = true;
locked = true;
mv.stop();
mv.reverse(SPEED);
driveWait(200);
mv.stop();
if(event.contains("center")) {
if(Math.random() > 0.5) {
slightRight(500);
} else {
slightLeft(500);
}
} else {
if(event.contains("left")) {
slightRight(200);
} else if (event.contains("right")) {
slightLeft(200);
}
}
mv.stop();
driveWait(500);
bumped = false;
locked = false;
if(auto) { driveRandomly(); }
}
}
|
diff --git a/src/net/dmcloud/cloudkey/Helpers.java b/src/net/dmcloud/cloudkey/Helpers.java
index 1dcd07d..57932b1 100644
--- a/src/net/dmcloud/cloudkey/Helpers.java
+++ b/src/net/dmcloud/cloudkey/Helpers.java
@@ -1,319 +1,319 @@
package net.dmcloud.cloudkey;
import java.io.*;
import java.net.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.zip.Deflater;
public class Helpers
{
static public String curl(String targetURL, String urlParameters)
{
URL url;
HttpURLConnection connection = null;
try
{
// Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes (urlParameters);
wr.flush();
wr.close();
// Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null)
{
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
finally
{
if (connection != null)
{
connection.disconnect();
}
}
}
static public String normalize(Map data)
{
String normalize = "";
data = new TreeMap(data);
Iterator iter = data.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry entry = (Map.Entry)iter.next();
normalize += entry.getKey();
normalize += normalizing(entry.getValue());
}
return normalize;
}
static public String normalize(ArrayList data)
{
String normalize = "";
for (int i=0; i<data.size(); i++)
{
normalize += normalizing(data.get(i));
}
return normalize;
}
static private String normalizing(Object o)
{
String normalize = "";
if (o instanceof Map)
{
normalize = normalize((Map)o);
}
else if (o instanceof ArrayList)
{
normalize = normalize((ArrayList)o);
}
else
{
normalize = o.toString();
}
return normalize;
}
static public String sign_url(String url, String secret) throws DCException
{
return sign_url(url, secret, CloudKey.SECLEVEL_NONE, "", "", "", null, null, 0);
}
static public String sign_url(String url, String secret, int seclevel, String asnum, String ip, String useragent, String[] countries, String[] referers, int expires) throws DCException
{
- expires = (expires == 0) ? (int)(new Date().getTime() + 7200) : expires;
+ expires = (expires == 0) ? (int)((new Date().getTime() / 1000) + 7200) : expires;
// Compute digest
String[] tokens = url.split("\\?");
String query = "";
if (tokens.length > 1)
{
url = tokens[0];
query = tokens[1];
}
String secparams = "";
ArrayList<String> public_secparams = new ArrayList<String>();
if ((seclevel & CloudKey.SECLEVEL_DELEGATE) == 0)
{
if ((seclevel & CloudKey.SECLEVEL_ASNUM) > 0)
{
if (asnum == "")
{
throw new DCException("IP security level required and no IP address provided.");
}
secparams += asnum;
}
if ((seclevel & CloudKey.SECLEVEL_IP) > 0)
{
if (asnum == "")
{
throw new DCException("IP security level required and no IP address provided.");
}
secparams += ip;
}
if ((seclevel & CloudKey.SECLEVEL_USERAGENT) > 0)
{
if (asnum == "")
{
throw new DCException("USERAGENT security level required and no user-agent provided.");
}
secparams += useragent;
}
if ((seclevel & CloudKey.SECLEVEL_COUNTRY) > 0)
{
if (countries == null || countries.length == 0)
{
throw new DCException("COUNTRY security level required and no country list provided.");
}
public_secparams.add("cc=" + implode(",", countries).toLowerCase());
}
if ((seclevel & CloudKey.SECLEVEL_REFERER) > 0)
{
if (referers == null || referers.length == 0)
{
throw new DCException("REFERER security level required and no referer list provided.");
}
try
{
StringBuffer ref = new StringBuffer();
for (int i=0; i<referers.length; i++)
{
if (i > 0)
ref.append(" ");
ref.append(referers[i].replace(" ", "%20"));
}
public_secparams.add("rf=" + URLEncoder.encode(ref.toString(), "UTF-8"));
}
catch (Exception e)
{
throw new DCException(e.getMessage());
}
}
}
String public_secparams_encoded = "";
if (public_secparams.size() > 0)
{
try
{
public_secparams_encoded = Base64.encode(gzcompress(implode("&", public_secparams)));
}
catch (Exception e)
{
throw new DCException(e.getMessage());
}
}
String rand = "";
String letters = "abcdefghijklmnopqrstuvwxyz0123456789";
for (int i=0; i<8; i++)
{
int index = (int)Math.round(Math.random() * 35);
rand += letters.substring(index, index + 1);
}
String digest = md5(seclevel + url + expires + rand + secret + secparams + public_secparams_encoded);
return url + "?" + (query != "" ? query + '&' : "") + "auth=" + expires + "-" + seclevel + "-" + rand + "-" + digest + (public_secparams_encoded != "" ? "-" + public_secparams_encoded : "");
}
private static String implode(String delim, String[] args)
{
StringBuffer sb = new StringBuffer();
for (int i=0; i<args.length; i++)
{
if (i > 0)
{
sb.append(delim);
}
sb.append(args[i]);
}
return sb.toString();
}
private static String implode(String delim, ArrayList<String> args)
{
StringBuffer sb = new StringBuffer();
for (int i=0; i<args.size(); i++)
{
if (i > 0)
{
sb.append(delim);
}
sb.append(args.get(i));
}
return sb.toString();
}
public static String md5(String password)
{
byte[] uniqueKey = password.getBytes();
byte[] hash = null;
try
{
hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
}
catch (NoSuchAlgorithmException e)
{
throw new Error("No MD5 support in this VM.");
}
StringBuilder hashString = new StringBuilder();
for (int i=0; i<hash.length; i++)
{
String hex = Integer.toHexString(hash[i]);
if (hex.length() == 1)
{
hashString.append('0');
hashString.append(hex.charAt(hex.length() - 1));
}
else
{
hashString.append(hex.substring(hex.length() - 2));
}
}
return hashString.toString();
}
private static byte[] gzcompress(String inputString) throws Exception
{
byte[] input = inputString.getBytes("UTF-8");
Deflater compresser = new Deflater();
compresser.setInput(input);
compresser.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
byte[] buf = new byte[1024];
while (!compresser.finished())
{
int count = compresser.deflate(buf);
bos.write(buf, 0, count);
}
bos.close();
return bos.toByteArray();
}
}
class Base64
{
private static final String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789" + "+/";
public static byte[] zeroPad(int length, byte[] bytes)
{
byte[] padded = new byte[length]; // initialized to zero by JVM
System.arraycopy(bytes, 0, padded, 0, bytes.length);
return padded;
}
public static String encode(byte[] stringArray)
{
String encoded = "";
// determine how many padding bytes to add to the output
int paddingCount = (3 - (stringArray.length % 3)) % 3;
// add any necessary padding to the input
stringArray = zeroPad(stringArray.length + paddingCount, stringArray);
// process 3 bytes at a time, churning out 4 output bytes
// worry about CRLF insertions later
for (int i = 0; i < stringArray.length; i += 3)
{
int j = ((stringArray[i] & 0xff) << 16) +
((stringArray[i + 1] & 0xff) << 8) +
(stringArray[i + 2] & 0xff);
encoded = encoded + base64code.charAt((j >> 18) & 0x3f) +
base64code.charAt((j >> 12) & 0x3f) +
base64code.charAt((j >> 6) & 0x3f) +
base64code.charAt(j & 0x3f);
}
// replace encoded padding nulls with "="
return encoded.substring(0, encoded.length() -
paddingCount) + "==".substring(0, paddingCount);
}
}
| true | true | static public String sign_url(String url, String secret, int seclevel, String asnum, String ip, String useragent, String[] countries, String[] referers, int expires) throws DCException
{
expires = (expires == 0) ? (int)(new Date().getTime() + 7200) : expires;
// Compute digest
String[] tokens = url.split("\\?");
String query = "";
if (tokens.length > 1)
{
url = tokens[0];
query = tokens[1];
}
String secparams = "";
ArrayList<String> public_secparams = new ArrayList<String>();
if ((seclevel & CloudKey.SECLEVEL_DELEGATE) == 0)
{
if ((seclevel & CloudKey.SECLEVEL_ASNUM) > 0)
{
if (asnum == "")
{
throw new DCException("IP security level required and no IP address provided.");
}
secparams += asnum;
}
if ((seclevel & CloudKey.SECLEVEL_IP) > 0)
{
if (asnum == "")
{
throw new DCException("IP security level required and no IP address provided.");
}
secparams += ip;
}
if ((seclevel & CloudKey.SECLEVEL_USERAGENT) > 0)
{
if (asnum == "")
{
throw new DCException("USERAGENT security level required and no user-agent provided.");
}
secparams += useragent;
}
if ((seclevel & CloudKey.SECLEVEL_COUNTRY) > 0)
{
if (countries == null || countries.length == 0)
{
throw new DCException("COUNTRY security level required and no country list provided.");
}
public_secparams.add("cc=" + implode(",", countries).toLowerCase());
}
if ((seclevel & CloudKey.SECLEVEL_REFERER) > 0)
{
if (referers == null || referers.length == 0)
{
throw new DCException("REFERER security level required and no referer list provided.");
}
try
{
StringBuffer ref = new StringBuffer();
for (int i=0; i<referers.length; i++)
{
if (i > 0)
ref.append(" ");
ref.append(referers[i].replace(" ", "%20"));
}
public_secparams.add("rf=" + URLEncoder.encode(ref.toString(), "UTF-8"));
}
catch (Exception e)
{
throw new DCException(e.getMessage());
}
}
}
String public_secparams_encoded = "";
if (public_secparams.size() > 0)
{
try
{
public_secparams_encoded = Base64.encode(gzcompress(implode("&", public_secparams)));
}
catch (Exception e)
{
throw new DCException(e.getMessage());
}
}
String rand = "";
String letters = "abcdefghijklmnopqrstuvwxyz0123456789";
for (int i=0; i<8; i++)
{
int index = (int)Math.round(Math.random() * 35);
rand += letters.substring(index, index + 1);
}
String digest = md5(seclevel + url + expires + rand + secret + secparams + public_secparams_encoded);
return url + "?" + (query != "" ? query + '&' : "") + "auth=" + expires + "-" + seclevel + "-" + rand + "-" + digest + (public_secparams_encoded != "" ? "-" + public_secparams_encoded : "");
}
| static public String sign_url(String url, String secret, int seclevel, String asnum, String ip, String useragent, String[] countries, String[] referers, int expires) throws DCException
{
expires = (expires == 0) ? (int)((new Date().getTime() / 1000) + 7200) : expires;
// Compute digest
String[] tokens = url.split("\\?");
String query = "";
if (tokens.length > 1)
{
url = tokens[0];
query = tokens[1];
}
String secparams = "";
ArrayList<String> public_secparams = new ArrayList<String>();
if ((seclevel & CloudKey.SECLEVEL_DELEGATE) == 0)
{
if ((seclevel & CloudKey.SECLEVEL_ASNUM) > 0)
{
if (asnum == "")
{
throw new DCException("IP security level required and no IP address provided.");
}
secparams += asnum;
}
if ((seclevel & CloudKey.SECLEVEL_IP) > 0)
{
if (asnum == "")
{
throw new DCException("IP security level required and no IP address provided.");
}
secparams += ip;
}
if ((seclevel & CloudKey.SECLEVEL_USERAGENT) > 0)
{
if (asnum == "")
{
throw new DCException("USERAGENT security level required and no user-agent provided.");
}
secparams += useragent;
}
if ((seclevel & CloudKey.SECLEVEL_COUNTRY) > 0)
{
if (countries == null || countries.length == 0)
{
throw new DCException("COUNTRY security level required and no country list provided.");
}
public_secparams.add("cc=" + implode(",", countries).toLowerCase());
}
if ((seclevel & CloudKey.SECLEVEL_REFERER) > 0)
{
if (referers == null || referers.length == 0)
{
throw new DCException("REFERER security level required and no referer list provided.");
}
try
{
StringBuffer ref = new StringBuffer();
for (int i=0; i<referers.length; i++)
{
if (i > 0)
ref.append(" ");
ref.append(referers[i].replace(" ", "%20"));
}
public_secparams.add("rf=" + URLEncoder.encode(ref.toString(), "UTF-8"));
}
catch (Exception e)
{
throw new DCException(e.getMessage());
}
}
}
String public_secparams_encoded = "";
if (public_secparams.size() > 0)
{
try
{
public_secparams_encoded = Base64.encode(gzcompress(implode("&", public_secparams)));
}
catch (Exception e)
{
throw new DCException(e.getMessage());
}
}
String rand = "";
String letters = "abcdefghijklmnopqrstuvwxyz0123456789";
for (int i=0; i<8; i++)
{
int index = (int)Math.round(Math.random() * 35);
rand += letters.substring(index, index + 1);
}
String digest = md5(seclevel + url + expires + rand + secret + secparams + public_secparams_encoded);
return url + "?" + (query != "" ? query + '&' : "") + "auth=" + expires + "-" + seclevel + "-" + rand + "-" + digest + (public_secparams_encoded != "" ? "-" + public_secparams_encoded : "");
}
|
diff --git a/brix-plugin-menu/src/main/java/brix/plugin/menu/tile/MenuTileEditor.java b/brix-plugin-menu/src/main/java/brix/plugin/menu/tile/MenuTileEditor.java
index 1da8803..73b17fa 100644
--- a/brix-plugin-menu/src/main/java/brix/plugin/menu/tile/MenuTileEditor.java
+++ b/brix-plugin-menu/src/main/java/brix/plugin/menu/tile/MenuTileEditor.java
@@ -1,128 +1,128 @@
package brix.plugin.menu.tile;
import java.util.List;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.ComponentFeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;
import brix.BrixNodeModel;
import brix.jcr.wrapper.BrixNode;
import brix.plugin.menu.Menu;
import brix.plugin.menu.MenuPlugin;
import brix.plugin.site.page.tile.admin.GenericTileEditorPanel;
import brix.web.util.AbstractModel;
public class MenuTileEditor extends GenericTileEditorPanel<BrixNode>
{
public MenuTileEditor(String id, IModel<BrixNode> containerNode)
{
super(id, containerNode);
IModel<List<BrixNode>> listViewModel = new LoadableDetachableModel<List<BrixNode>>()
{
@Override
protected List<BrixNode> load()
{
return MenuPlugin.get().getMenuNodes(
MenuTileEditor.this.getModelObject().getSession().getWorkspace().getName());
}
};
add(new MenuListView("listView", listViewModel));
Form<MenuContainer> form;
add(form = new Form<MenuContainer>("form", new CompoundPropertyModel<MenuContainer>(
new PropertyModel<MenuContainer>(this, "currentEntry"))));
form.add(new TextField<String>("outerContainerStyleClass"));
form.add(new TextField<String>("innerContainerStyleClass"));
form.add(new TextField<String>("selectedItemStyleClass"));
form.add(new TextField<String>("itemWithSelectedChildStyleClass"));
form.add(new TextField<Integer>("startAtLevel"));
form.add(new TextField<Integer>("renderLevels"));
}
@Override
public void load(BrixNode node)
{
currentEntry = new MenuContainer();
currentEntry.load(node);
}
@Override
public void save(BrixNode node)
{
currentEntry.save(node);
}
private MenuContainer currentEntry = new MenuContainer();
private class MenuListView extends ListView<BrixNode>
{
public MenuListView(String id, IModel<List<BrixNode>> model)
{
super(id, model);
}
@Override
protected void populateItem(final ListItem<BrixNode> item)
{
Link<Object> select = new Link<Object>("select")
{
@Override
public void onClick()
{
currentEntry.setMenuNode(item.getModelObject());
}
@Override
public boolean isEnabled()
{
BrixNode current = currentEntry.getMenuNode();
- return current == null || !item.getModelObject().equals(current);
+ return current == null || !item.getModelObject().isSame(current);
}
};
IModel<String> labelModel = new AbstractModel<String>()
{
@Override
public String getObject()
{
BrixNode node = item.getModelObject();
Menu menu = new Menu();
menu.loadName(node);
return menu.getName();
}
};
select.add(new Label("label", labelModel));
item.add(select);
}
@Override
protected IModel<BrixNode> getListItemModel(IModel<List<BrixNode>> listViewModel, int index)
{
List<BrixNode> nodes = listViewModel.getObject();
return new BrixNodeModel(nodes.get(index));
}
};
@Override
protected void onDetach()
{
if (currentEntry != null)
{
currentEntry.detach();
}
super.onDetach();
}
}
| true | true | protected void populateItem(final ListItem<BrixNode> item)
{
Link<Object> select = new Link<Object>("select")
{
@Override
public void onClick()
{
currentEntry.setMenuNode(item.getModelObject());
}
@Override
public boolean isEnabled()
{
BrixNode current = currentEntry.getMenuNode();
return current == null || !item.getModelObject().equals(current);
}
};
IModel<String> labelModel = new AbstractModel<String>()
{
@Override
public String getObject()
{
BrixNode node = item.getModelObject();
Menu menu = new Menu();
menu.loadName(node);
return menu.getName();
}
};
select.add(new Label("label", labelModel));
item.add(select);
}
| protected void populateItem(final ListItem<BrixNode> item)
{
Link<Object> select = new Link<Object>("select")
{
@Override
public void onClick()
{
currentEntry.setMenuNode(item.getModelObject());
}
@Override
public boolean isEnabled()
{
BrixNode current = currentEntry.getMenuNode();
return current == null || !item.getModelObject().isSame(current);
}
};
IModel<String> labelModel = new AbstractModel<String>()
{
@Override
public String getObject()
{
BrixNode node = item.getModelObject();
Menu menu = new Menu();
menu.loadName(node);
return menu.getName();
}
};
select.add(new Label("label", labelModel));
item.add(select);
}
|
diff --git a/maven-gae-plugin/src/main/java/net/kindleit/gae/runner/BackgroundKickStartRunner.java b/maven-gae-plugin/src/main/java/net/kindleit/gae/runner/BackgroundKickStartRunner.java
index 0264192..e3a724f 100644
--- a/maven-gae-plugin/src/main/java/net/kindleit/gae/runner/BackgroundKickStartRunner.java
+++ b/maven-gae-plugin/src/main/java/net/kindleit/gae/runner/BackgroundKickStartRunner.java
@@ -1,168 +1,170 @@
/* Copyright 2009 Kindleit.net Software Development
*
* 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.kindleit.gae.runner;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.logging.Log;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import org.codehaus.plexus.util.cli.StreamConsumer;
/**
* An implementation of {@code KickStartRunner} that asynchronously invokes {@link com.google.appengine.tools.KickStart}
* in a forked process.
*
* @author [email protected]
* @since 0.5.8
*/
final class BackgroundKickStartRunner extends KickStartRunner {
private final String pluginPath;
private final Log log;
private Thread thread;
private volatile Exception thrown;
/**
* Creates a new {@code BackgroundKickStartRunner}.
*
* @param artifacts The Maven Project.
* @param gaeProperties Properties with the plugin's groupId, and artifactId.
* @param log The Maven plugin logger to direct output to.
* @throws KickStartExecutionException if the plugin cannot be found.
*/
public BackgroundKickStartRunner(final Set<Artifact> artifacts,
final Properties gaeProperties, final Log log)
throws KickStartExecutionException {
this.log = log;
pluginPath = getPluginPath(artifacts, gaeProperties);
}
/**
* Asynchronously starts a {@code KickStart} instance with the specified arguments.
* This method method will block until the server starts up, and then allows the current thread to continue while
* the server runs in the background.
*
* @param args the arguments to pass to {@code KickStart}
*/
@Override
public synchronized void start(final int monitorPort, final String monitorKey,
final List<String> args) throws KickStartExecutionException {
if (thread != null) {
throw new IllegalStateException("Already started");
}
thread = setupCommandLine(monitorPort, monitorKey, args);
thread.start();
try {
wait();
} catch (final InterruptedException e) {
thrown = e;
}
if (thrown != null) {
throw new KickStartExecutionException(thrown);
}
}
- private Thread setupCommandLine(final int monitorPort, final String monitorKey,
- final List<String> args) {
- final Commandline commandline = new Commandline("java");
+ private Thread setupCommandLine(final int monitorPort,
+ final String monitorKey, final List<String> args) {
+ final String javaExe = System.getProperty("java.home") + File.separator
+ + "bin" + File.separator + "java";
+ final Commandline commandline = new Commandline(javaExe);
final String classPath =
System.getProperty("java.class.path") + File.pathSeparator + pluginPath;
commandline.createArg().setValue("-ea");
commandline.createArg().setValue("-cp");
commandline.createArg().setValue(classPath);
commandline.createArg().setValue("-Dmonitor.port=" + monitorPort);
commandline.createArg().setValue("-Dmonitor.key=" + monitorKey);
commandline.createArg().setValue("-Dappengine.sdk.root=" + System.getProperty("appengine.sdk.root"));
commandline.createArg().setValue(AppEnginePluginMonitor.class.getName());
commandline.addArguments(args.toArray(new String[args.size()]));
final StreamConsumer outConsumer = new StreamConsumer() {
public void consumeLine(final String line) {
consumeOutputLine(line);
}
};
final StreamConsumer errConsumer = new StreamConsumer() {
public void consumeLine(final String line) {
consumeErrorLine(line);
}
};
if (log.isDebugEnabled()) {
log.debug("Forking executable: " + commandline.getExecutable());
log.debug("Command line: " + commandline.toString());
}
return new Thread(new Runnable() {
public void run() {
try {
CommandLineUtils.executeCommandLine(commandline, outConsumer, errConsumer);
} catch (final Exception e) {
setThrown(e);
}
}
});
}
private synchronized void consumeOutputLine(final String line) {
System.out.println(line);
if (line.contains("The server is running")) {
notify();
}
}
private synchronized void consumeErrorLine(final String line) {
System.err.println(line);
if (line.contains("The server is running")) {
notify();
}
}
private synchronized void setThrown(final Exception thrown) {
this.thrown = thrown;
notify();
}
private String getPluginPath(final Set<Artifact> artifacts,
final Properties gaeProperties) throws KickStartExecutionException {
final String groupId = gaeProperties.getProperty("plugin.groupId");
final String artifactId = gaeProperties.getProperty("plugin.artifactId");
for (final Artifact a : artifacts) {
if (groupId.equals(a.getGroupId())
&& artifactId.equals(a.getArtifactId())) {
try {
return a.getFile().getCanonicalPath();
} catch (final IOException e) {
log.error(e);
throw new KickStartExecutionException(e);
}
}
}
throw new KickStartExecutionException("Plugin not found");
}
}
| true | true | private Thread setupCommandLine(final int monitorPort, final String monitorKey,
final List<String> args) {
final Commandline commandline = new Commandline("java");
final String classPath =
System.getProperty("java.class.path") + File.pathSeparator + pluginPath;
commandline.createArg().setValue("-ea");
commandline.createArg().setValue("-cp");
commandline.createArg().setValue(classPath);
commandline.createArg().setValue("-Dmonitor.port=" + monitorPort);
commandline.createArg().setValue("-Dmonitor.key=" + monitorKey);
commandline.createArg().setValue("-Dappengine.sdk.root=" + System.getProperty("appengine.sdk.root"));
commandline.createArg().setValue(AppEnginePluginMonitor.class.getName());
commandline.addArguments(args.toArray(new String[args.size()]));
final StreamConsumer outConsumer = new StreamConsumer() {
public void consumeLine(final String line) {
consumeOutputLine(line);
}
};
final StreamConsumer errConsumer = new StreamConsumer() {
public void consumeLine(final String line) {
consumeErrorLine(line);
}
};
if (log.isDebugEnabled()) {
log.debug("Forking executable: " + commandline.getExecutable());
log.debug("Command line: " + commandline.toString());
}
return new Thread(new Runnable() {
public void run() {
try {
CommandLineUtils.executeCommandLine(commandline, outConsumer, errConsumer);
} catch (final Exception e) {
setThrown(e);
}
}
});
}
| private Thread setupCommandLine(final int monitorPort,
final String monitorKey, final List<String> args) {
final String javaExe = System.getProperty("java.home") + File.separator
+ "bin" + File.separator + "java";
final Commandline commandline = new Commandline(javaExe);
final String classPath =
System.getProperty("java.class.path") + File.pathSeparator + pluginPath;
commandline.createArg().setValue("-ea");
commandline.createArg().setValue("-cp");
commandline.createArg().setValue(classPath);
commandline.createArg().setValue("-Dmonitor.port=" + monitorPort);
commandline.createArg().setValue("-Dmonitor.key=" + monitorKey);
commandline.createArg().setValue("-Dappengine.sdk.root=" + System.getProperty("appengine.sdk.root"));
commandline.createArg().setValue(AppEnginePluginMonitor.class.getName());
commandline.addArguments(args.toArray(new String[args.size()]));
final StreamConsumer outConsumer = new StreamConsumer() {
public void consumeLine(final String line) {
consumeOutputLine(line);
}
};
final StreamConsumer errConsumer = new StreamConsumer() {
public void consumeLine(final String line) {
consumeErrorLine(line);
}
};
if (log.isDebugEnabled()) {
log.debug("Forking executable: " + commandline.getExecutable());
log.debug("Command line: " + commandline.toString());
}
return new Thread(new Runnable() {
public void run() {
try {
CommandLineUtils.executeCommandLine(commandline, outConsumer, errConsumer);
} catch (final Exception e) {
setThrown(e);
}
}
});
}
|
diff --git a/src/me/neatmonster/spacertk/PingListener.java b/src/me/neatmonster/spacertk/PingListener.java
index 4766c9a..d6d6255 100644
--- a/src/me/neatmonster/spacertk/PingListener.java
+++ b/src/me/neatmonster/spacertk/PingListener.java
@@ -1,131 +1,132 @@
/*
* This file is part of SpaceRTK (http://spacebukkit.xereo.net/).
*
* SpaceRTK 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.
*
* SpaceRTK 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.spacertk;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Pings the Module to ensure it is functioning correctly
*/
public class PingListener extends Thread {
public static final int REQUEST_THRESHOLD = 60000; // Sixty seconds
public static final int SLEEP_TIME = 30000; // Thirty seconds
private boolean lostModule;
private DatagramSocket socket;
private AtomicBoolean running = new AtomicBoolean(false);
private InetAddress localHost;
/**
* Creates a new PingListener
*/
public PingListener() {
super("Ping Listener Main Thread");
try {
this.localHost = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
handleException(e, "Unable to get the Local Host!");
}
this.lostModule = false;
try {
this.socket = new DatagramSocket();
} catch (IOException e) {
handleException(e, "Unable to start the PingListener!");
}
}
/**
* Starts the Ping Listener
*/
public void startup() {
this.running.set(true);
this.start();
}
@Override
public void run() {
try {
socket.setSoTimeout(REQUEST_THRESHOLD);
} catch (SocketException e) {
handleException(e, "Error setting the So Timeout!");
}
while (running.get()) {
System.out.println("Run");
byte[] buffer = new byte[512];
+ buffer[0] = 1;
try {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, localHost, SpaceRTK.getInstance().rPingPort);
socket.send(packet);
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
handleException(e, "Error sleeping in the run() loop!");
}
socket.receive(packet);
} catch (SocketTimeoutException e) {
onModuleNotFound();
} catch (IOException e) {
handleException(e, "Error sending and receiving the RTK packet!");
}
}
}
/**
* Shuts down the Ping Listener
*/
public void shutdown() {
this.running.set(false);
}
/**
* Called when an exception is thrown
*
* @param e
* Exception thrown
*/
public void handleException(Exception e, String reason) {
shutdown();
System.err.println("[SpaceBukkit] Ping Listener Error!");
System.err.println(reason);
System.err.println("Error message:");
e.printStackTrace();
}
/**
* Called when the Module can't be found
*/
public void onModuleNotFound() {
if (lostModule) {
return;
}
shutdown();
System.err.println("[SpaceBukkit] Unable to ping the Module!");
System.err
.println("[SpaceBukkit] Please insure the correct ports are open");
System.err
.println("[SpaceBukkit] Please contact the forums (http://forums.xereo.net/) or IRC (#SpaceBukkit on irc.esper.net)");
lostModule = true;
}
}
| true | true | public void run() {
try {
socket.setSoTimeout(REQUEST_THRESHOLD);
} catch (SocketException e) {
handleException(e, "Error setting the So Timeout!");
}
while (running.get()) {
System.out.println("Run");
byte[] buffer = new byte[512];
try {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, localHost, SpaceRTK.getInstance().rPingPort);
socket.send(packet);
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
handleException(e, "Error sleeping in the run() loop!");
}
socket.receive(packet);
} catch (SocketTimeoutException e) {
onModuleNotFound();
} catch (IOException e) {
handleException(e, "Error sending and receiving the RTK packet!");
}
}
}
| public void run() {
try {
socket.setSoTimeout(REQUEST_THRESHOLD);
} catch (SocketException e) {
handleException(e, "Error setting the So Timeout!");
}
while (running.get()) {
System.out.println("Run");
byte[] buffer = new byte[512];
buffer[0] = 1;
try {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, localHost, SpaceRTK.getInstance().rPingPort);
socket.send(packet);
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
handleException(e, "Error sleeping in the run() loop!");
}
socket.receive(packet);
} catch (SocketTimeoutException e) {
onModuleNotFound();
} catch (IOException e) {
handleException(e, "Error sending and receiving the RTK packet!");
}
}
}
|
diff --git a/core/src/main/java/hudson/tasks/Ant.java b/core/src/main/java/hudson/tasks/Ant.java
index 4e15b13..8ddce53 100644
--- a/core/src/main/java/hudson/tasks/Ant.java
+++ b/core/src/main/java/hudson/tasks/Ant.java
@@ -1,428 +1,427 @@
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Tom Huybrechts
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.tasks;
import hudson.CopyOnWrite;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.EnvironmentSpecific;
import hudson.model.Hudson;
import hudson.model.Node;
import hudson.model.TaskListener;
import hudson.remoting.Callable;
import hudson.slaves.NodeSpecific;
import hudson.tools.ToolDescriptor;
import hudson.tools.ToolInstallation;
import hudson.tools.ToolLocationNodeProperty;
import hudson.util.ArgumentListBuilder;
import hudson.util.FormFieldValidator;
import hudson.util.VariableResolver;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
/**
* Ant launcher.
*
* @author Kohsuke Kawaguchi
*/
public class Ant extends Builder {
/**
* The targets, properties, and other Ant options.
* Either separated by whitespace or newline.
*/
private final String targets;
/**
* Identifies {@link AntInstallation} to be used.
*/
private final String antName;
/**
* ANT_OPTS if not null.
*/
private final String antOpts;
/**
* Optional build script path relative to the workspace.
* Used for the Ant '-f' option.
*/
private final String buildFile;
/**
* Optional properties to be passed to Ant. Follows {@link Properties} syntax.
*/
private final String properties;
@DataBoundConstructor
public Ant(String targets,String antName, String antOpts, String buildFile, String properties) {
this.targets = targets;
this.antName = antName;
this.antOpts = Util.fixEmptyAndTrim(antOpts);
this.buildFile = Util.fixEmptyAndTrim(buildFile);
this.properties = Util.fixEmptyAndTrim(properties);
}
public String getBuildFile() {
return buildFile;
}
public String getProperties() {
return properties;
}
public String getTargets() {
return targets;
}
/**
* Gets the Ant to invoke,
* or null to invoke the default one.
*/
public AntInstallation getAnt() {
for( AntInstallation i : getDescriptor().getInstallations() ) {
if(antName!=null && i.getName().equals(antName))
return i;
}
return null;
}
/**
* Gets the ANT_OPTS parameter, or null.
*/
public String getAntOpts() {
return antOpts;
}
public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
AbstractProject proj = build.getProject();
ArgumentListBuilder args = new ArgumentListBuilder();
- Map<String,String> slaveEnv = EnvVars.getRemote(launcher.getChannel());
- EnvVars env = new EnvVars(slaveEnv);
- env.overrideAll(build.getEnvVars());
+ EnvVars env = EnvVars.getRemote(launcher.getChannel());
+ env.overrideAll(build.getEnvironment());
AntInstallation ai = getAnt();
if (ai != null) {
ai = ai.forNode(Computer.currentComputer().getNode());
}
if(ai==null) {
args.add(launcher.isUnix() ? "ant" : "ant.bat");
} else {
ai = ai.forEnvironment(env);
String exe = ai.getExecutable(launcher);
if (exe==null) {
listener.fatalError(Messages.Ant_ExecutableNotFound(ai.getName()));
return false;
}
args.add(exe);
}
VariableResolver<String> vr = build.getBuildVariableResolver();
String buildFile = env.expand(this.buildFile);
String targets = Util.replaceMacro(env.expand(this.targets), vr);
FilePath buildFilePath = buildFilePath(proj.getModuleRoot(), buildFile, targets);
if(!buildFilePath.exists()) {
// because of the poor choice of getModuleRoot() with CVS/Subversion, people often get confused
// with where the build file path is relative to. Now it's too late to change this behavior
// due to compatibility issue, but at least we can make this less painful by looking for errors
// and diagnosing it nicely. See HUDSON-1782
// first check if this appears to be a valid relative path from workspace root
FilePath buildFilePath2 = buildFilePath(proj.getWorkspace(), buildFile, targets);
if(buildFilePath2.exists()) {
// This must be what the user meant. Let it continue.
buildFilePath = buildFilePath2;
} else {
// neither file exists. So this now really does look like an error.
listener.fatalError("Unable to find build script at "+buildFilePath);
return false;
}
}
if(buildFile!=null) {
args.add("-file", buildFilePath.getName());
}
args.addKeyValuePairs("-D",build.getBuildVariables());
args.addKeyValuePairsFromPropertyString("-D",properties,vr);
args.addTokenized(targets.replaceAll("[\t\r\n]+"," "));
if(ai!=null)
env.put("ANT_HOME",ai.getAntHome());
if(antOpts!=null)
env.put("ANT_OPTS",env.expand(antOpts));
if(!launcher.isUnix()) {
// on Windows, executing batch file can't return the correct error code,
// so we need to wrap it into cmd.exe.
// double %% is needed because we want ERRORLEVEL to be expanded after
// batch file executed, not before. This alone shows how broken Windows is...
args.add("&&","exit","%%ERRORLEVEL%%");
// on Windows, proper double quote handling requires extra surrounding quote.
// so we need to convert the entire argument list once into a string,
// then build the new list so that by the time JVM invokes CreateProcess win32 API,
// it puts additional double-quote. See issue #1007
// the 'addQuoted' is necessary because Process implementation for Windows (at least in Sun JVM)
// is too clever to avoid putting a quote around it if the argument begins with "
// see "cmd /?" for more about how cmd.exe handles quotation.
args = new ArgumentListBuilder().add("cmd.exe","/C").addQuoted(args.toStringWithQuote());
}
long startTime = System.currentTimeMillis();
try {
int r = launcher.launch(args.toCommandArray(),env,listener.getLogger(),buildFilePath.getParent()).join();
return r==0;
} catch (IOException e) {
Util.displayIOException(e,listener);
String errorMessage = Messages.Ant_ExecFailed();
if(ai==null && (System.currentTimeMillis()-startTime)<1000) {
if(getDescriptor().getInstallations()==null)
// looks like the user didn't configure any Ant installation
errorMessage += Messages.Ant_GlobalConfigNeeded();
else
// There are Ant installations configured but the project didn't pick it
errorMessage += Messages.Ant_ProjectConfigNeeded();
}
e.printStackTrace( listener.fatalError(errorMessage) );
return false;
}
}
private static FilePath buildFilePath(FilePath base, String buildFile, String targets) {
if(buildFile!=null) return base.child(buildFile);
// some users specify the -f option in the targets field, so take that into account as well.
// see
String[] tokens = Util.tokenize(targets);
for (int i = 0; i<tokens.length-1; i++) {
String a = tokens[i];
if(a.equals("-f") || a.equals("-file") || a.equals("-buildfile"))
return base.child(tokens[i+1]);
}
return base.child("build.xml");
}
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
@Extension
public static class DescriptorImpl extends Descriptor<Builder> {
@CopyOnWrite
private volatile AntInstallation[] installations = new AntInstallation[0];
public DescriptorImpl() {
load();
}
protected DescriptorImpl(Class<? extends Ant> clazz) {
super(clazz);
}
protected void convert(Map<String,Object> oldPropertyBag) {
if(oldPropertyBag.containsKey("installations"))
installations = (AntInstallation[]) oldPropertyBag.get("installations");
}
public String getHelpFile() {
return "/help/project-config/ant.html";
}
public String getDisplayName() {
return Messages.Ant_DisplayName();
}
public AntInstallation[] getInstallations() {
return installations;
}
@Override
public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
installations = req.bindJSONToList(
AntInstallation.class, json.get("ant")).toArray(new AntInstallation[0]);
save();
return true;
}
public Ant newInstance(StaplerRequest req, JSONObject formData) throws FormException {
return (Ant)req.bindJSON(clazz,formData);
}
//
// web methods
//
/**
* Checks if the ANT_HOME is valid.
*/
public void doCheckAntHome( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
// this can be used to check the existence of a file on the server, so needs to be protected
new FormFieldValidator(req,rsp,true) {
public void check() throws IOException, ServletException {
File f = getFileParameter("value");
if(!f.isDirectory()) {
error(Messages.Ant_NotADirectory(f));
return;
}
File antJar = new File(f,"lib/ant.jar");
if(!antJar.exists()) {
error(Messages.Ant_NotAntDirectory(f));
return;
}
ok();
}
}.process();
}
public void setInstallations(AntInstallation... antInstallations) {
this.installations = antInstallations;
}
}
public static final class AntInstallation extends ToolInstallation implements
EnvironmentSpecific<AntInstallation>, NodeSpecific<AntInstallation> {
private final String antHome;
@DataBoundConstructor
public AntInstallation(String name, String home) {
super(name, launderHome(home));
if(home.endsWith("/") || home.endsWith("\\"))
// see https://issues.apache.org/bugzilla/show_bug.cgi?id=26947
// Ant doesn't like the trailing slash, especially on Windows
home = home.substring(0,home.length()-1);
this.antHome = home;
}
private static String launderHome(String home) {
if(home.endsWith("/") || home.endsWith("\\")) {
// see https://issues.apache.org/bugzilla/show_bug.cgi?id=26947
// Ant doesn't like the trailing slash, especially on Windows
return home.substring(0,home.length()-1);
} else {
return home;
}
}
/**
* install directory.
*/
public String getAntHome() {
return getHome();
}
public String getHome() {
if (antHome != null) return antHome;
return super.getHome();
}
/**
* Gets the executable path of this Ant on the given target system.
*/
public String getExecutable(Launcher launcher) throws IOException, InterruptedException {
final boolean isUnix = launcher.isUnix();
return launcher.getChannel().call(new Callable<String,IOException>() {
public String call() throws IOException {
File exe = getExeFile(isUnix);
if(exe.exists())
return exe.getPath();
return null;
}
});
}
private File getExeFile(boolean isUnix) {
String execName;
if(isUnix)
execName = "ant";
else
execName = "ant.bat";
String antHome = Util.replaceMacro(getAntHome(),EnvVars.masterEnvVars);
return new File(antHome,"bin/"+execName);
}
/**
* Returns true if the executable exists.
*/
public boolean getExists() throws IOException, InterruptedException {
return getExecutable(new Launcher.LocalLauncher(TaskListener.NULL))!=null;
}
private static final long serialVersionUID = 1L;
public AntInstallation forEnvironment(EnvVars environment) {
return new AntInstallation(getName(), environment.expand(antHome));
}
public AntInstallation forNode(Node node) {
return new AntInstallation(getName(),ToolLocationNodeProperty.getToolHome(node, this));
}
@Extension
public static class DescriptorImpl extends ToolDescriptor<AntInstallation> {
@Override
public String getDisplayName() {
return "Ant";
}
@Override
public AntInstallation[] getInstallations() {
return Hudson.getInstance().getDescriptorByType(Ant.DescriptorImpl.class).getInstallations();
}
@Override
public void setInstallations(AntInstallation... installations) {
Hudson.getInstance().getDescriptorByType(Ant.DescriptorImpl.class).setInstallations(installations);
}
}
}
}
| true | true | public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
AbstractProject proj = build.getProject();
ArgumentListBuilder args = new ArgumentListBuilder();
Map<String,String> slaveEnv = EnvVars.getRemote(launcher.getChannel());
EnvVars env = new EnvVars(slaveEnv);
env.overrideAll(build.getEnvVars());
AntInstallation ai = getAnt();
if (ai != null) {
ai = ai.forNode(Computer.currentComputer().getNode());
}
if(ai==null) {
args.add(launcher.isUnix() ? "ant" : "ant.bat");
} else {
ai = ai.forEnvironment(env);
String exe = ai.getExecutable(launcher);
if (exe==null) {
listener.fatalError(Messages.Ant_ExecutableNotFound(ai.getName()));
return false;
}
args.add(exe);
}
VariableResolver<String> vr = build.getBuildVariableResolver();
String buildFile = env.expand(this.buildFile);
String targets = Util.replaceMacro(env.expand(this.targets), vr);
FilePath buildFilePath = buildFilePath(proj.getModuleRoot(), buildFile, targets);
if(!buildFilePath.exists()) {
// because of the poor choice of getModuleRoot() with CVS/Subversion, people often get confused
// with where the build file path is relative to. Now it's too late to change this behavior
// due to compatibility issue, but at least we can make this less painful by looking for errors
// and diagnosing it nicely. See HUDSON-1782
// first check if this appears to be a valid relative path from workspace root
FilePath buildFilePath2 = buildFilePath(proj.getWorkspace(), buildFile, targets);
if(buildFilePath2.exists()) {
// This must be what the user meant. Let it continue.
buildFilePath = buildFilePath2;
} else {
// neither file exists. So this now really does look like an error.
listener.fatalError("Unable to find build script at "+buildFilePath);
return false;
}
}
if(buildFile!=null) {
args.add("-file", buildFilePath.getName());
}
args.addKeyValuePairs("-D",build.getBuildVariables());
args.addKeyValuePairsFromPropertyString("-D",properties,vr);
args.addTokenized(targets.replaceAll("[\t\r\n]+"," "));
if(ai!=null)
env.put("ANT_HOME",ai.getAntHome());
if(antOpts!=null)
env.put("ANT_OPTS",env.expand(antOpts));
if(!launcher.isUnix()) {
// on Windows, executing batch file can't return the correct error code,
// so we need to wrap it into cmd.exe.
// double %% is needed because we want ERRORLEVEL to be expanded after
// batch file executed, not before. This alone shows how broken Windows is...
args.add("&&","exit","%%ERRORLEVEL%%");
// on Windows, proper double quote handling requires extra surrounding quote.
// so we need to convert the entire argument list once into a string,
// then build the new list so that by the time JVM invokes CreateProcess win32 API,
// it puts additional double-quote. See issue #1007
// the 'addQuoted' is necessary because Process implementation for Windows (at least in Sun JVM)
// is too clever to avoid putting a quote around it if the argument begins with "
// see "cmd /?" for more about how cmd.exe handles quotation.
args = new ArgumentListBuilder().add("cmd.exe","/C").addQuoted(args.toStringWithQuote());
}
long startTime = System.currentTimeMillis();
try {
int r = launcher.launch(args.toCommandArray(),env,listener.getLogger(),buildFilePath.getParent()).join();
return r==0;
} catch (IOException e) {
Util.displayIOException(e,listener);
String errorMessage = Messages.Ant_ExecFailed();
if(ai==null && (System.currentTimeMillis()-startTime)<1000) {
if(getDescriptor().getInstallations()==null)
// looks like the user didn't configure any Ant installation
errorMessage += Messages.Ant_GlobalConfigNeeded();
else
// There are Ant installations configured but the project didn't pick it
errorMessage += Messages.Ant_ProjectConfigNeeded();
}
e.printStackTrace( listener.fatalError(errorMessage) );
return false;
}
}
| public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
AbstractProject proj = build.getProject();
ArgumentListBuilder args = new ArgumentListBuilder();
EnvVars env = EnvVars.getRemote(launcher.getChannel());
env.overrideAll(build.getEnvironment());
AntInstallation ai = getAnt();
if (ai != null) {
ai = ai.forNode(Computer.currentComputer().getNode());
}
if(ai==null) {
args.add(launcher.isUnix() ? "ant" : "ant.bat");
} else {
ai = ai.forEnvironment(env);
String exe = ai.getExecutable(launcher);
if (exe==null) {
listener.fatalError(Messages.Ant_ExecutableNotFound(ai.getName()));
return false;
}
args.add(exe);
}
VariableResolver<String> vr = build.getBuildVariableResolver();
String buildFile = env.expand(this.buildFile);
String targets = Util.replaceMacro(env.expand(this.targets), vr);
FilePath buildFilePath = buildFilePath(proj.getModuleRoot(), buildFile, targets);
if(!buildFilePath.exists()) {
// because of the poor choice of getModuleRoot() with CVS/Subversion, people often get confused
// with where the build file path is relative to. Now it's too late to change this behavior
// due to compatibility issue, but at least we can make this less painful by looking for errors
// and diagnosing it nicely. See HUDSON-1782
// first check if this appears to be a valid relative path from workspace root
FilePath buildFilePath2 = buildFilePath(proj.getWorkspace(), buildFile, targets);
if(buildFilePath2.exists()) {
// This must be what the user meant. Let it continue.
buildFilePath = buildFilePath2;
} else {
// neither file exists. So this now really does look like an error.
listener.fatalError("Unable to find build script at "+buildFilePath);
return false;
}
}
if(buildFile!=null) {
args.add("-file", buildFilePath.getName());
}
args.addKeyValuePairs("-D",build.getBuildVariables());
args.addKeyValuePairsFromPropertyString("-D",properties,vr);
args.addTokenized(targets.replaceAll("[\t\r\n]+"," "));
if(ai!=null)
env.put("ANT_HOME",ai.getAntHome());
if(antOpts!=null)
env.put("ANT_OPTS",env.expand(antOpts));
if(!launcher.isUnix()) {
// on Windows, executing batch file can't return the correct error code,
// so we need to wrap it into cmd.exe.
// double %% is needed because we want ERRORLEVEL to be expanded after
// batch file executed, not before. This alone shows how broken Windows is...
args.add("&&","exit","%%ERRORLEVEL%%");
// on Windows, proper double quote handling requires extra surrounding quote.
// so we need to convert the entire argument list once into a string,
// then build the new list so that by the time JVM invokes CreateProcess win32 API,
// it puts additional double-quote. See issue #1007
// the 'addQuoted' is necessary because Process implementation for Windows (at least in Sun JVM)
// is too clever to avoid putting a quote around it if the argument begins with "
// see "cmd /?" for more about how cmd.exe handles quotation.
args = new ArgumentListBuilder().add("cmd.exe","/C").addQuoted(args.toStringWithQuote());
}
long startTime = System.currentTimeMillis();
try {
int r = launcher.launch(args.toCommandArray(),env,listener.getLogger(),buildFilePath.getParent()).join();
return r==0;
} catch (IOException e) {
Util.displayIOException(e,listener);
String errorMessage = Messages.Ant_ExecFailed();
if(ai==null && (System.currentTimeMillis()-startTime)<1000) {
if(getDescriptor().getInstallations()==null)
// looks like the user didn't configure any Ant installation
errorMessage += Messages.Ant_GlobalConfigNeeded();
else
// There are Ant installations configured but the project didn't pick it
errorMessage += Messages.Ant_ProjectConfigNeeded();
}
e.printStackTrace( listener.fatalError(errorMessage) );
return false;
}
}
|
diff --git a/src/test/java/org/atlasapi/remotesite/itv/ItvMercuryBrandAdapterTest.java b/src/test/java/org/atlasapi/remotesite/itv/ItvMercuryBrandAdapterTest.java
index 4c789d2dc..20a6e2fb5 100644
--- a/src/test/java/org/atlasapi/remotesite/itv/ItvMercuryBrandAdapterTest.java
+++ b/src/test/java/org/atlasapi/remotesite/itv/ItvMercuryBrandAdapterTest.java
@@ -1,62 +1,62 @@
package org.atlasapi.remotesite.itv;
import junit.framework.TestCase;
import org.atlasapi.media.TransportType;
import org.atlasapi.media.entity.Brand;
import org.atlasapi.media.entity.Broadcast;
import org.atlasapi.media.entity.Encoding;
import org.atlasapi.media.entity.Item;
import org.atlasapi.media.entity.Location;
import org.atlasapi.media.entity.Version;
import org.atlasapi.remotesite.SiteSpecificAdapter;
public class ItvMercuryBrandAdapterTest extends TestCase {
private final SiteSpecificAdapter<Brand> adapter = new ItvMercuryBrandAdapter();
public void testShouldGetBrand() throws Exception {
String uri = "http://www.itv.com/itvplayer/video/?Filter=Emmerdale";
Brand brand = adapter.fetch(uri);
assertNotNull(brand);
assertEquals(uri, brand.getCanonicalUri());
assertEquals("itv:Emmerdale", brand.getCurie());
assertFalse(brand.getGenres().isEmpty());
assertNotNull(brand.getTitle());
assertNotNull(brand.getDescription());
assertFalse(brand.getItems().isEmpty());
for (Item item: brand.getItems()) {
assertNotNull(item.getTitle());
assertNotNull(item.getDescription());
- assertFalse(item.getGenres().isEmpty());
+ //assertFalse(item.getGenres().isEmpty());
assertFalse(item.getVersions().isEmpty());
for (Version version: item.getVersions()) {
assertFalse(version.getBroadcasts().isEmpty());
assertFalse(version.getManifestedAs().isEmpty());
for (Broadcast broadcast: version.getBroadcasts()) {
assertNotNull(broadcast.getBroadcastOn());
assertNotNull(broadcast.getTransmissionTime());
assertNotNull(broadcast.getTransmissionEndTime());
}
for (Encoding encoding: version.getManifestedAs()) {
assertFalse(encoding.getAvailableAt().isEmpty());
for (Location location: encoding.getAvailableAt()) {
assertNotNull(location.getUri());
assertNotNull(location.getPolicy());
assertEquals(TransportType.LINK, location.getTransportType());
}
}
}
}
}
public void testShouldBeAbleToFetch() {
assertTrue(adapter.canFetch("http://www.itv.com/itvplayer/video/?Filter=...Do%20the%20Funniest%20Things"));
assertFalse(adapter.canFetch("http://www.itv.com/itvplayer/video/?Filter=1234"));
}
}
| true | true | public void testShouldGetBrand() throws Exception {
String uri = "http://www.itv.com/itvplayer/video/?Filter=Emmerdale";
Brand brand = adapter.fetch(uri);
assertNotNull(brand);
assertEquals(uri, brand.getCanonicalUri());
assertEquals("itv:Emmerdale", brand.getCurie());
assertFalse(brand.getGenres().isEmpty());
assertNotNull(brand.getTitle());
assertNotNull(brand.getDescription());
assertFalse(brand.getItems().isEmpty());
for (Item item: brand.getItems()) {
assertNotNull(item.getTitle());
assertNotNull(item.getDescription());
assertFalse(item.getGenres().isEmpty());
assertFalse(item.getVersions().isEmpty());
for (Version version: item.getVersions()) {
assertFalse(version.getBroadcasts().isEmpty());
assertFalse(version.getManifestedAs().isEmpty());
for (Broadcast broadcast: version.getBroadcasts()) {
assertNotNull(broadcast.getBroadcastOn());
assertNotNull(broadcast.getTransmissionTime());
assertNotNull(broadcast.getTransmissionEndTime());
}
for (Encoding encoding: version.getManifestedAs()) {
assertFalse(encoding.getAvailableAt().isEmpty());
for (Location location: encoding.getAvailableAt()) {
assertNotNull(location.getUri());
assertNotNull(location.getPolicy());
assertEquals(TransportType.LINK, location.getTransportType());
}
}
}
}
}
| public void testShouldGetBrand() throws Exception {
String uri = "http://www.itv.com/itvplayer/video/?Filter=Emmerdale";
Brand brand = adapter.fetch(uri);
assertNotNull(brand);
assertEquals(uri, brand.getCanonicalUri());
assertEquals("itv:Emmerdale", brand.getCurie());
assertFalse(brand.getGenres().isEmpty());
assertNotNull(brand.getTitle());
assertNotNull(brand.getDescription());
assertFalse(brand.getItems().isEmpty());
for (Item item: brand.getItems()) {
assertNotNull(item.getTitle());
assertNotNull(item.getDescription());
//assertFalse(item.getGenres().isEmpty());
assertFalse(item.getVersions().isEmpty());
for (Version version: item.getVersions()) {
assertFalse(version.getBroadcasts().isEmpty());
assertFalse(version.getManifestedAs().isEmpty());
for (Broadcast broadcast: version.getBroadcasts()) {
assertNotNull(broadcast.getBroadcastOn());
assertNotNull(broadcast.getTransmissionTime());
assertNotNull(broadcast.getTransmissionEndTime());
}
for (Encoding encoding: version.getManifestedAs()) {
assertFalse(encoding.getAvailableAt().isEmpty());
for (Location location: encoding.getAvailableAt()) {
assertNotNull(location.getUri());
assertNotNull(location.getPolicy());
assertEquals(TransportType.LINK, location.getTransportType());
}
}
}
}
}
|
diff --git a/examples/stanfordBlacklight/test/src/edu/stanford/ItemsSplitTests.java b/examples/stanfordBlacklight/test/src/edu/stanford/ItemsSplitTests.java
index 767227c..3c10849 100644
--- a/examples/stanfordBlacklight/test/src/edu/stanford/ItemsSplitTests.java
+++ b/examples/stanfordBlacklight/test/src/edu/stanford/ItemsSplitTests.java
@@ -1,250 +1,250 @@
package edu.stanford;
import java.io.*;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.*;
import org.xml.sax.SAXException;
import edu.stanford.enumValues.CallNumberType;
/**
* tests for records that have so many items that the sirsi dump splits them
* into multiple records to avoid a 5000 character limit for each record. Each
* of the records has the same bib portion except for the 999s
* @author naomi
*
*/
public class ItemsSplitTests extends AbstractStanfordBlacklightTest {
static String fldName = "item_display";
static String SEP = " -|- ";
String testFilePath = testDataParentPath + File.separator + "splitItemsTest.mrc";
static boolean isSerial = true;
@Before
public final void setup()
{
mappingTestInit();
}
/**
* test when the first record in the file is split into multiple records.
*/
@Test
public void testFirstRecordSplit()
{
solrFldMapTest.assertSolrFldValue(testFilePath, "notSplit1", "id", "notSplit1");
solrFldMapTest.assertSolrFldValue(testFilePath, "notSplit2", "id", "notSplit2");
String id = "split1";
solrFldMapTest.assertSolrFldHasNumValues(testFilePath, id, fldName, 5);
String lopped = "A1 .B2 ...";
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped, CallNumberType.LC, id).toLowerCase();
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey).toLowerCase();
String barcode = "101";
String callnum = "A1 .B2 V.1";
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, isSerial, id);
String fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal.trim());
barcode = "102";
callnum = "A1 .B2 V.2";
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, isSerial, id);
fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal);
barcode = "103";
callnum = "A1 .B2 V.3";
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, isSerial, id);
fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal);
barcode = "104";
callnum = "A1 .B2 V.4";
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, isSerial, id);
fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal);
barcode = "105";
callnum = "A1 .B2 V.5";
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, isSerial, id);
fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal);
}
/**
* test when a middle record in the file is split into multiple records.
*/
@Test
public void testMiddleRecordSplit()
{
String id = "split2";
solrFldMapTest.assertSolrFldHasNumValues(testFilePath, id, fldName, 5);
String lopped = "A3 .B4 ...";
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped, CallNumberType.LC, id).toLowerCase();
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey).toLowerCase();
String barcode = "201";
String callnum = "A3 .B4 V.1";
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, isSerial, id);
String fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal);
barcode = "202";
callnum = "A3 .B4 V.2";
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, isSerial, id);
fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal);
barcode = "203";
callnum = "A3 .B4 V.3";
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, isSerial, id);
fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal);
barcode = "204";
callnum = "A3 .B4 V.4";
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, isSerial, id);
fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal);
barcode = "205";
callnum = "A3 .B4 V.5";
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, isSerial, id);
fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal);
}
/**
* test when the last record in the file is split into multiple records.
*/
@Test
public void testLastRecordSplit()
{
String id = "split3";
solrFldMapTest.assertSolrFldHasNumValues(testFilePath, id, fldName, 5);
String lopped = "A5 .B6 ...";
String shelfkey = edu.stanford.CallNumUtils.getShelfKey(lopped, CallNumberType.LC, id).toLowerCase();
String reversekey = org.solrmarc.tools.CallNumUtils.getReverseShelfKey(shelfkey).toLowerCase();
String barcode = "301";
String callnum = "A5 .B6 V.1";
String volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, !isSerial, id);
String fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal);
barcode = "302";
callnum = "A5 .B6 V.2";
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, !isSerial, id);
fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal);
barcode = "303";
callnum = "A5 .B6 V.3";
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, !isSerial, id);
fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal);
barcode = "304";
callnum = "A5 .B6 V.4";
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, !isSerial, id);
fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal);
barcode = "305";
callnum = "A5 .B6 V.5";
volSort = edu.stanford.CallNumUtils.getVolumeSortCallnum(callnum, lopped, shelfkey, CallNumberType.LC, !isSerial, id);
fldVal = barcode + SEP + "GREEN -|- STACKS" + SEP + SEP + SEP + lopped + SEP +
shelfkey + SEP + reversekey + SEP + callnum + SEP + volSort;
solrFldMapTest.assertSolrFldValue(testFilePath, id, fldName, fldVal);
}
/**
* assert the non-split records are present.
*/
@Test
public void testNonSplitRecords()
{
solrFldMapTest.assertSolrFldValue(testFilePath, "notSplit1", "id", "notSplit1");
solrFldMapTest.assertSolrFldValue(testFilePath, "notSplit2", "id", "notSplit2");
}
/**
* assert all items are present and not garbled (via sampling)
* (turns out problem is in the marc directory ... the ruby marc gem
* can read these records correctly if it uses the "forgiving" reader.
* but the REAL solution is to switch to marcxml.
*/
//@Test
public void testAllItemsPresent()
throws ParserConfigurationException, IOException, SAXException
{
String barcodeFldName = "barcode_search";
// 3195846 is a giant record for "Science"
createIxInitVars("3195846.mrc");
// createIxInitVars("100817_uni_increment.marc");
assertDocPresent("3195846");
// first barcode
assertSingleResult("3195846", barcodeFldName, "36105016962404");
// last "good" 999 in UI
assertSingleResult("3195846", barcodeFldName, "36105019891873");
// first "bad" 999 in UI
assertSingleResult("3195846", barcodeFldName, "36105018074463");
// last barcode
assertSingleResult("3195846", barcodeFldName, "36105123124971");
- // 3195846 is a giant record for Buckminster Fuller
+ // 4332640 is a giant record for Buckminster Fuller
createIxInitVars("4332640.mrc");
// createIxInitVars("100813_uni_increment.marc");
assertDocPresent("4332640");
// first barcode
assertSingleResult("4332640", barcodeFldName, "36105116017505");
// last "good" 999 in UI
assertSingleResult("4332640", barcodeFldName, "36105116028791");
// first "bad" 999 in UI
assertSingleResult("4332640", barcodeFldName, "36105116028809");
// last barcode
assertSingleResult("4332640", barcodeFldName, "36105115865367");
// 7621542 is a moderately large record for Southern Pacific Railroad Group 2
createIxInitVars("7621542.mrc");
assertDocPresent("7621542");
// first barcode
assertSingleResult("7621542", barcodeFldName, "36105115582079");
// last "good" 999 in UI
assertSingleResult("7621542", barcodeFldName, "36105116127981");
// first "bad" 999 in UI
assertSingleResult("7621542", barcodeFldName, "36105116127999");
// last barcode
assertSingleResult("7621542", barcodeFldName, "36105115641370");
}
}
| true | true | public void testAllItemsPresent()
throws ParserConfigurationException, IOException, SAXException
{
String barcodeFldName = "barcode_search";
// 3195846 is a giant record for "Science"
createIxInitVars("3195846.mrc");
// createIxInitVars("100817_uni_increment.marc");
assertDocPresent("3195846");
// first barcode
assertSingleResult("3195846", barcodeFldName, "36105016962404");
// last "good" 999 in UI
assertSingleResult("3195846", barcodeFldName, "36105019891873");
// first "bad" 999 in UI
assertSingleResult("3195846", barcodeFldName, "36105018074463");
// last barcode
assertSingleResult("3195846", barcodeFldName, "36105123124971");
// 3195846 is a giant record for Buckminster Fuller
createIxInitVars("4332640.mrc");
// createIxInitVars("100813_uni_increment.marc");
assertDocPresent("4332640");
// first barcode
assertSingleResult("4332640", barcodeFldName, "36105116017505");
// last "good" 999 in UI
assertSingleResult("4332640", barcodeFldName, "36105116028791");
// first "bad" 999 in UI
assertSingleResult("4332640", barcodeFldName, "36105116028809");
// last barcode
assertSingleResult("4332640", barcodeFldName, "36105115865367");
// 7621542 is a moderately large record for Southern Pacific Railroad Group 2
createIxInitVars("7621542.mrc");
assertDocPresent("7621542");
// first barcode
assertSingleResult("7621542", barcodeFldName, "36105115582079");
// last "good" 999 in UI
assertSingleResult("7621542", barcodeFldName, "36105116127981");
// first "bad" 999 in UI
assertSingleResult("7621542", barcodeFldName, "36105116127999");
// last barcode
assertSingleResult("7621542", barcodeFldName, "36105115641370");
}
| public void testAllItemsPresent()
throws ParserConfigurationException, IOException, SAXException
{
String barcodeFldName = "barcode_search";
// 3195846 is a giant record for "Science"
createIxInitVars("3195846.mrc");
// createIxInitVars("100817_uni_increment.marc");
assertDocPresent("3195846");
// first barcode
assertSingleResult("3195846", barcodeFldName, "36105016962404");
// last "good" 999 in UI
assertSingleResult("3195846", barcodeFldName, "36105019891873");
// first "bad" 999 in UI
assertSingleResult("3195846", barcodeFldName, "36105018074463");
// last barcode
assertSingleResult("3195846", barcodeFldName, "36105123124971");
// 4332640 is a giant record for Buckminster Fuller
createIxInitVars("4332640.mrc");
// createIxInitVars("100813_uni_increment.marc");
assertDocPresent("4332640");
// first barcode
assertSingleResult("4332640", barcodeFldName, "36105116017505");
// last "good" 999 in UI
assertSingleResult("4332640", barcodeFldName, "36105116028791");
// first "bad" 999 in UI
assertSingleResult("4332640", barcodeFldName, "36105116028809");
// last barcode
assertSingleResult("4332640", barcodeFldName, "36105115865367");
// 7621542 is a moderately large record for Southern Pacific Railroad Group 2
createIxInitVars("7621542.mrc");
assertDocPresent("7621542");
// first barcode
assertSingleResult("7621542", barcodeFldName, "36105115582079");
// last "good" 999 in UI
assertSingleResult("7621542", barcodeFldName, "36105116127981");
// first "bad" 999 in UI
assertSingleResult("7621542", barcodeFldName, "36105116127999");
// last barcode
assertSingleResult("7621542", barcodeFldName, "36105115641370");
}
|
diff --git a/mailarchive-tool/tool/src/java/org/sakaiproject/mailarchive/tool/MailboxAction.java b/mailarchive-tool/tool/src/java/org/sakaiproject/mailarchive/tool/MailboxAction.java
index df0da2e..6783b85 100644
--- a/mailarchive-tool/tool/src/java/org/sakaiproject/mailarchive/tool/MailboxAction.java
+++ b/mailarchive-tool/tool/src/java/org/sakaiproject/mailarchive/tool/MailboxAction.java
@@ -1,1145 +1,1148 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.mailarchive.tool;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.sakaiproject.alias.api.Alias;
import org.sakaiproject.alias.cover.AliasService;
import org.sakaiproject.authz.api.PermissionsHelper;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.PagedResourceActionII;
import org.sakaiproject.cheftool.PortletConfig;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.api.Menu;
import org.sakaiproject.cheftool.menu.MenuDivider;
import org.sakaiproject.cheftool.menu.MenuEntry;
import org.sakaiproject.cheftool.menu.MenuImpl;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.cover.ContentTypeImageService;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.javax.PagingPosition;
import org.sakaiproject.mailarchive.api.MailArchiveChannel;
import org.sakaiproject.mailarchive.api.MailArchiveChannelEdit;
import org.sakaiproject.mailarchive.api.MailArchiveMessage;
import org.sakaiproject.mailarchive.cover.MailArchiveService;
import org.sakaiproject.message.api.Message;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
import org.sakaiproject.javax.Filter;
import org.sakaiproject.javax.SearchFilter;
import org.sakaiproject.javax.Search;
import org.sakaiproject.javax.Restriction;
import org.sakaiproject.javax.Order;
/**
* <p>
* MailboxAction is a the Sakai mailbox tool.
* </p>
*/
public class MailboxAction extends PagedResourceActionII
{
private static ResourceLoader rb = new ResourceLoader("email");
/** portlet configuration parameter names. */
private static final String PARAM_CHANNEL = "channel";
private static final String PARAM_SITE = "site";
private static final String PARAM_SHOW_NON_ALIAS = "showNonAlias";
/** Configure form field names. */
private static final String FORM_CHANNEL = "channel";
private static final String FORM_PAGESIZE = "pagesize";
private static final String FORM_OPEN = "open";
private static final String FORM_REPLY = "reply";
private static final String FORM_ALIAS = "alias";
private static final String FORM_ITEM_NUMBER = "item_number";
/** List request parameters. */
private static final String VIEW_ID = "view-id";
/** state attribute names. */
private static final String STATE_CHANNEL_REF = "channelId";
private static final String STATE_ASCENDING = "ascending";
private static final String STATE_SORT = "sort";
private static final String STATE_VIEW_HEADERS = "view-headers";
private static final String STATE_OPTION_PAGESIZE = "optSize";
private static final String STATE_OPTION_OPEN = "optOpen";
private static final String STATE_OPTION_REPLY = "optReply";
private static final String STATE_OPTION_ALIAS = "optAlias";
private static final String STATE_SHOW_NON_ALIAS = "showNonAlias";
private static final String STATE_ALERT_MESSAGE = "alertMessage";
private static final String STATE_DELETE_CONFIRM_ID = "confirmDeleteId";
/** Sort codes. */
private static final int SORT_FROM = 0;
private static final int SORT_DATE = 1;
private static final int SORT_SUBJECT = 2;
/** paging */
private static final String STATE_MSG_VIEW_ID = "msg-id";
/** State to cache the count of messages */
private static final String STATE_COUNT = "state-cached-count";
private static final String STATE_COUNT_SEARCH = "state-cached-count-search";
/** Default for search suppression threshold */
private final int MESSAGE_THRESHOLD_DEFAULT = 2500;
/** paging */
/*
* (non-Javadoc)
*
* @see org.sakaiproject.cheftool.PagedResourceActionII#sizeResources(org.sakaiproject.service.framework.session.SessionState)
*/
protected int sizeResources(SessionState state)
{
String search = (String) state.getAttribute(STATE_SEARCH);
// We cache the count at the tool level because it is not done perfectly
// at the lower layer
Integer lastCount = (Integer) state.getAttribute(STATE_COUNT);
String countSearch = (String) state.getAttribute(STATE_COUNT_SEARCH);
if ( search == null && countSearch == null && lastCount != null )
{
return lastCount.intValue();
}
if ( countSearch != null && countSearch.equals(search))
{
return lastCount.intValue();
}
// We must talk to the Storage to count the messages
try
{
MailArchiveChannel channel = MailArchiveService.getMailArchiveChannel((String) state.getAttribute(STATE_CHANNEL_REF));
int cCount = channel.getCount((Filter) getSearchFilter(search, 0, 0));
lastCount = new Integer(cCount);
state.setAttribute(STATE_COUNT, lastCount);
state.setAttribute(STATE_COUNT_SEARCH, search);
return cCount;
}
catch (Exception e)
{
Log.warn("sakai", "sizeResources failed search="+search+" exeption="+e);
}
return 0;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.cheftool.PagedResourceActionII#readResourcesPage(org.sakaiproject.service.framework.session.SessionState, int, int)
*/
protected List readResourcesPage(SessionState state, int first, int last)
{
// read all channel messages
List allMessages = null;
boolean ascending = ((Boolean) state.getAttribute(STATE_ASCENDING)).booleanValue();
int sort = ((Integer) state.getAttribute(STATE_SORT)).intValue();
String search = (String) state.getAttribute(STATE_SEARCH);
PagingPosition pages = new PagingPosition(first, last);
try
{
MailArchiveChannel channel = MailArchiveService.getMailArchiveChannel((String) state.getAttribute(STATE_CHANNEL_REF));
Search f = getSearchFilter(search, first, last);
if ( sort == SORT_FROM )
{
f.setOrders(new Order[] { new Order("OWNER",ascending) } );
}
else if ( sort == SORT_SUBJECT )
{
f.setOrders(new Order[] { new Order("SUBJECT",ascending) } );
}
allMessages = channel.getMessages((Filter) f, ascending, null);
}
catch (Exception e)
{
Log.warn("sakai", "readResourcesPage not able to retrieve messages sort ="+
sort+" search = "+search+" first="+first+" last="+last);
}
// deal with no messages
if (allMessages == null) return new Vector();
return allMessages;
} // readPagedResources
/**
* Populate the state object, if needed.
*/
protected void initState(SessionState state, VelocityPortlet portlet, JetspeedRunData rundata)
{
super.initState(state, portlet, rundata);
if (state.getAttribute(STATE_CHANNEL_REF) == null)
{
PortletConfig config = portlet.getPortletConfig();
// start in list mode
state.setAttribute(STATE_MODE, "list");
// read the channel from configuration, or, if not specified, use the default for the request
String channel = StringUtil.trimToNull(config.getInitParameter(PARAM_CHANNEL));
if (channel == null)
{
channel = MailArchiveService.channelReference(ToolManager.getCurrentPlacement().getContext(),
SiteService.MAIN_CONTAINER);
}
state.setAttribute(STATE_CHANNEL_REF, channel);
if (state.getAttribute(STATE_SHOW_NON_ALIAS) == null)
{
Boolean showNonAlias = Boolean.parseBoolean(config.getInitParameter(PARAM_SHOW_NON_ALIAS, "false"));
state.setAttribute(STATE_SHOW_NON_ALIAS, showNonAlias);
}
if (state.getAttribute(STATE_ASCENDING) == null)
{
state.setAttribute(STATE_ASCENDING, new Boolean(false));
}
if (state.getAttribute(STATE_SORT) == null)
{
state.setAttribute(STATE_SORT, new Integer(SORT_DATE));
}
if (state.getAttribute(STATE_VIEW_HEADERS) == null)
{
state.setAttribute(STATE_VIEW_HEADERS, new Boolean(false));
}
}
} // initState
/**
* build the context for the main panel
*
* @return (optional) template name for this panel
*/
public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
String mode = (String) state.getAttribute(STATE_MODE);
context.put(Menu.CONTEXT_ACTION, state.getAttribute(STATE_ACTION));
String search = (String) state.getAttribute(STATE_SEARCH);
String alertMessage = (String) state.getAttribute(STATE_ALERT_MESSAGE);
if ( alertMessage != null )
{
state.setAttribute(STATE_ALERT_MESSAGE, null);
context.put(STATE_ALERT_MESSAGE, alertMessage);
}
// Put this back only for Confirm
String deleteConfirm = (String) state.getAttribute(STATE_DELETE_CONFIRM_ID);
state.removeAttribute(STATE_DELETE_CONFIRM_ID);
if ("list".equals(mode))
{
return buildListModeContext(portlet, context, rundata, state);
}
else if ("confirm-remove".equals(mode))
{
if ( deleteConfirm != null && deleteConfirm.length() > 0 )
{
state.setAttribute(STATE_DELETE_CONFIRM_ID,deleteConfirm);
}
return buildConfirmModeContext(portlet, context, rundata, state);
}
else if ("view".equals(mode))
{
return buildViewModeContext(portlet, context, rundata, state);
}
else if (MODE_OPTIONS.equals(mode))
{
return buildOptionsPanelContext(portlet, context, rundata, state);
}
else
{
Log.warn("sakai", this + ".buildMainPanelContext: invalid mode: " + mode);
return null;
}
} // buildMainPanelContext
/**
* build the context for the View mode (in the Main panel)
*
* @return (optional) template name for this panel
*/
private String buildViewModeContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
boolean allowDelete = false;
int viewPos = ((Integer) state.getAttribute(FORM_ITEM_NUMBER)).intValue();
int numMessages = sizeResources(state);
int prevPos = viewPos - 1;
int nextPos = viewPos + 1;
state.setAttribute(STATE_PREV_EXISTS, "");
state.setAttribute(STATE_NEXT_EXISTS, "");
// Message numbers are one-based
boolean goPrev = (prevPos > 0);
boolean goNext = (nextPos <= numMessages);
context.put("viewPos",viewPos);
context.put("nextPos",nextPos);
context.put("goNPButton", new Boolean(goNext));
context.put("prevPos",prevPos);
context.put("goPPButton", new Boolean(goPrev));
System.out.println("Hello buildViewMode viewPos="+viewPos+" max="+numMessages);
// prepare the sort of messages
context.put("tlang", rb);
String channelRef = (String) state.getAttribute(STATE_CHANNEL_REF);
MailArchiveChannel channel = null;
try
{
channel = MailArchiveService.getMailArchiveChannel(channelRef);
}
catch (Exception e)
{
Log.warn("sakai", "Cannot find channel "+channelRef);
}
// Read a single message
List messagePage = readResourcesPage(state, viewPos, viewPos);
if ( messagePage != null ) {
Message msg = (Message) messagePage.get(0);
context.put("email",msg);
allowDelete = channel.allowRemoveMessage(msg);
// Sadly this is the only way to send this to a menu pick :(
state.setAttribute(STATE_DELETE_CONFIRM_ID, msg.getId());
} else {
Log.warn("sakai", "Could not retrieve message "+channelRef);
context.put("message", rb.getString("thiemames1"));
}
context.put("viewheaders", state.getAttribute(STATE_VIEW_HEADERS));
context.put("contentTypeImageService", ContentTypeImageService.getInstance());
// build the menu
Menu bar = new MenuImpl(portlet, rundata, (String) state.getAttribute(STATE_ACTION));
// bar.add( new MenuEntry(rb.getString("listall"), "doList"));
// addViewPagingMenus(bar, state);
if (((Boolean) state.getAttribute(STATE_VIEW_HEADERS)).booleanValue())
{
bar.add(new MenuEntry(rb.getString("hidehead"), "doHide_headers"));
}
else
{
bar.add(new MenuEntry(rb.getString("viehea"), "doView_headers"));
}
if (allowDelete) bar.add(new MenuEntry(rb.getString("del"), "doRemove"));
// make sure there's not leading or trailing dividers
bar.adjustDividers();
context.put(Menu.CONTEXT_MENU, bar);
return (String) getContext(rundata).get("template") + "-view";
} // buildViewModeContext
/**
* Build the context for the confirm remove mode (in the Main panel).
*/
private String buildConfirmModeContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
// get the message
context.put("tlang", rb);
String id = (String) state.getAttribute(STATE_DELETE_CONFIRM_ID);
System.out.println("buildConfirmModeContext id="+id);
MailArchiveMessage message = null;
try
{
MailArchiveChannel channel = MailArchiveService.getMailArchiveChannel((String) state.getAttribute(STATE_CHANNEL_REF));
message = channel.getMailArchiveMessage(id);
context.put("email", message);
context.put(STATE_DELETE_CONFIRM_ID, message.getId());
}
catch (IdUnusedException e)
{
}
catch (PermissionException e)
{
}
if (message == null)
{
context.put("message", rb.getString("thiemames1"));
}
context.put("viewheaders", state.getAttribute(STATE_VIEW_HEADERS));
return (String) getContext(rundata).get("template") + "-confirm_remove";
} // buildConfirmModeContext
/**
* build the context for the list mode (in the Main panel).
*/
private String buildListModeContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
// prepare the page of messages
context.put("tlang", rb);
List messages = prepPage(state);
context.put("messages", messages);
// build the menu
Menu bar = new MenuImpl(portlet, rundata, (String) state.getAttribute(STATE_ACTION));
if (SiteService.allowUpdateSite(ToolManager.getCurrentPlacement().getContext()))
{
bar.add(new MenuDivider());
// add options if allowed
addOptionsMenu(bar, (JetspeedRunData) rundata);
bar.add(new MenuEntry(rb.getString("perm"), "doPermissions"));
}
// make sure there's not leading or trailing dividers
bar.adjustDividers();
context.put(Menu.CONTEXT_MENU, bar);
// Decide if we are going to allow searching...
int numMessages = sizeResources(state);
int messageLimit = getMessageThreshold();
context.put("allow-search",new Boolean(numMessages <= messageLimit));
// output the search field
context.put(STATE_SEARCH, state.getAttribute(STATE_SEARCH));
// eventSubmit value and id field for drill down
context.put("view-id", VIEW_ID);
context.put(Menu.CONTEXT_ACTION, state.getAttribute(STATE_ACTION));
context.put("sort-by", state.getAttribute(STATE_SORT));
context.put("sort-order", state.getAttribute(STATE_ASCENDING));
pagingInfoToContext(state, context);
// the aliases for the channel
List all = AliasService.getAliases((String) state.getAttribute(STATE_CHANNEL_REF));
// and the aliases for the site (context)
Reference channelRef = EntityManager.newReference((String) state.getAttribute(STATE_CHANNEL_REF));
String siteRef = SiteService.siteReference(channelRef.getContext());
all.addAll(AliasService.getAliases(siteRef));
context.put("aliases", all);
if (all.size() == 0 || (Boolean)state.getAttribute(STATE_SHOW_NON_ALIAS))
{
context.put("nonAlias", channelRef.getContext());
}
context.put("serverName", ServerConfigurationService.getServerName());
// if the user has permission to send mail, drop in the email address
try
{
MailArchiveChannel channel = MailArchiveService.getMailArchiveChannel((String) state.getAttribute(STATE_CHANNEL_REF));
if (channel.getEnabled())
{
if (channel.getOpen())
{
// if open, mail from anywhere
context.put("validFrom", "*");
}
else if (channel.allowAddMessage())
{
User user = UserDirectoryService.getCurrentUser();
String email = user.getEmail();
context.put("validFrom", email);
}
}
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("thismaiis"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youdonot1"));
}
catch (Exception e)
{
}
// inform the observing courier that we just updated the page...
// if there are pending requests to do so they can be cleared
justDelivered(state);
return (String) getContext(rundata).get("template") + "-List";
} // buildListModeContext
/**
* Handle a user drill down request.
*/
public void doView(RunData runData, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData) runData).getJs_peid();
SessionState state = ((JetspeedRunData) runData).getPortletSessionState(peid);
// switch to view mode
state.setAttribute(STATE_MODE, "view");
String id = runData.getParameters().getString(VIEW_ID);
state.setAttribute(STATE_MSG_VIEW_ID, id);
String position = runData.getParameters().getString(FORM_ITEM_NUMBER);
state.setAttribute(FORM_ITEM_NUMBER, Integer.valueOf(position));
// disable auto-updates while in view mode
disableObservers(state);
} // doView
/**
* Handle a return-to-list-view request.
*/
public void doList(RunData runData, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData) runData).getJs_peid();
SessionState state = ((JetspeedRunData) runData).getPortletSessionState(peid);
// switch to view mode
state.setAttribute(STATE_MODE, "list");
// make sure auto-updates are enabled
enableObserver(state);
state.removeAttribute(STATE_MSG_VIEW_ID);
} // doList
/**
* Handle a view headers request.
*/
public void doView_headers(RunData runData, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData) runData).getJs_peid();
SessionState state = ((JetspeedRunData) runData).getPortletSessionState(peid);
// switch to view mode
state.setAttribute(STATE_VIEW_HEADERS, new Boolean(true));
} // doView_headers
/**
* Handle a hide headers request.
*/
public void doHide_headers(RunData runData, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData) runData).getJs_peid();
SessionState state = ((JetspeedRunData) runData).getPortletSessionState(peid);
// switch to view mode
state.setAttribute(STATE_VIEW_HEADERS, new Boolean(false));
} // doHide_headers
/**
* Handle a user request to change the sort to "from"
*/
public void doSort_from(RunData runData, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData) runData).getJs_peid();
SessionState state = ((JetspeedRunData) runData).getPortletSessionState(peid);
// we are changing the sort, so start from the first page again
resetPaging(state);
// if already from, swap the order
if (((Integer) state.getAttribute(STATE_SORT)).intValue() == SORT_FROM)
{
boolean order = !((Boolean) state.getAttribute(STATE_ASCENDING)).booleanValue();
state.setAttribute(STATE_ASCENDING, new Boolean(order));
}
// set state
else
{
state.setAttribute(STATE_SORT, new Integer(SORT_FROM));
}
} // doSort_from
/**
* Handle a user request to change the sort to "date"
*/
public void doSort_date(RunData runData, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData) runData).getJs_peid();
SessionState state = ((JetspeedRunData) runData).getPortletSessionState(peid);
// we are changing the sort, so start from the first page again
resetPaging(state);
// if already date, swap the order
if (((Integer) state.getAttribute(STATE_SORT)).intValue() == SORT_DATE)
{
boolean order = !((Boolean) state.getAttribute(STATE_ASCENDING)).booleanValue();
state.setAttribute(STATE_ASCENDING, new Boolean(order));
}
// set state
else
{
state.setAttribute(STATE_SORT, new Integer(SORT_DATE));
}
} // doSort_date
/**
* Handle a user request to change the sort to "subject"
*/
public void doSort_subject(RunData runData, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData) runData).getJs_peid();
SessionState state = ((JetspeedRunData) runData).getPortletSessionState(peid);
// we are changing the sort, so start from the first page again
resetPaging(state);
// if already subject, swap the order
if (((Integer) state.getAttribute(STATE_SORT)).intValue() == SORT_SUBJECT)
{
boolean order = !((Boolean) state.getAttribute(STATE_ASCENDING)).booleanValue();
state.setAttribute(STATE_ASCENDING, new Boolean(order));
}
// set state
else
{
state.setAttribute(STATE_SORT, new Integer(SORT_SUBJECT));
}
} // doSort_subject
/**
* doRemove called when "eventSubmit_doRemove" is in the request parameters to confirm removal of the group
*/
public void doRemove(RunData data, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData) data).getJs_peid();
SessionState state = ((JetspeedRunData) data).getPortletSessionState(peid);
// go to remove confirm mode
state.setAttribute(STATE_MODE, "confirm-remove");
// disable auto-updates while in confirm mode
disableObservers(state);
} // doRemove
/**
* doRemove_confirmed called when "eventSubmit_doRemove_confirmed" is in the request parameters to remove the group
*/
public void doRemove_confirmed(RunData data, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData) data).getJs_peid();
SessionState state = ((JetspeedRunData) data).getPortletSessionState(peid);
// Grab and remove immedaitely
String msgId = (String) state.getAttribute(STATE_DELETE_CONFIRM_ID);
System.out.println("doRemove_confirmed id="+msgId);
state.removeAttribute(STATE_DELETE_CONFIRM_ID);
state.removeAttribute(STATE_COUNT);
state.removeAttribute(STATE_COUNT_SEARCH);
// remove
try
{
MailArchiveChannel channel = MailArchiveService.getMailArchiveChannel((String) state.getAttribute(STATE_CHANNEL_REF));
if (msgId != null)
channel.removeMessage(msgId);
else
addAlert(state, rb.getString("thimeshas"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("youdonot3"));
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("thimeshas"));
}
// go to list mode
doList(data, context);
} // doRemove_confirmed
/**
* doCancel_remove called when "eventSubmit_doCancel_remove" is in the request parameters to cancel group removal
*/
public void doRemove_cancel(RunData data, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData) data).getJs_peid();
SessionState state = ((JetspeedRunData) data).getPortletSessionState(peid);
// Clean up state
state.removeAttribute(STATE_MSG_VIEW_ID);
// return to view mode
state.setAttribute(STATE_MODE, "view");
// disable auto-updates while in view mode
disableObservers(state);
} // doRemove_cancel
/**
* Handle a request to set options.
*/
public void doOptions(RunData runData, Context context)
{
super.doOptions(runData, context);
// access the portlet element id to find our state
String peid = ((JetspeedRunData) runData).getJs_peid();
SessionState state = ((JetspeedRunData) runData).getPortletSessionState(peid);
// if we ended up in options mode, do whatever else ...
if (!MODE_OPTIONS.equals(state.getAttribute(STATE_MODE))) return;
} // doOptions
/**
* Setup for options.
*/
public String buildOptionsPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("tlang", rb);
// provide "pagesize" with the current page size setting
context.put("pagesize", ((Integer) state.getAttribute(STATE_PAGESIZE)).toString());
// provide form names
context.put("form-pagesize", FORM_PAGESIZE);
context.put("form-open", FORM_OPEN);
context.put("form-reply", FORM_REPLY);
context.put("form-alias", FORM_ALIAS);
context.put("form-submit", BUTTON + "doUpdate");
context.put("form-cancel", BUTTON + "doCancel");
// in progress values
if (state.getAttribute(STATE_OPTION_PAGESIZE) != null)
context.put(STATE_OPTION_PAGESIZE, state.getAttribute(STATE_OPTION_PAGESIZE));
if (state.getAttribute(STATE_OPTION_OPEN) != null)
context.put(STATE_OPTION_OPEN, state.getAttribute(STATE_OPTION_OPEN));
if (state.getAttribute(STATE_OPTION_REPLY) != null)
context.put(STATE_OPTION_REPLY, state.getAttribute(STATE_OPTION_REPLY));
if (state.getAttribute(STATE_OPTION_ALIAS) != null)
context.put(STATE_OPTION_ALIAS, state.getAttribute(STATE_OPTION_ALIAS));
// provide the channel
try
{
MailArchiveChannel channel = MailArchiveService.getMailArchiveChannel((String) state.getAttribute(STATE_CHANNEL_REF));
context.put("channel", channel);
}
catch (Exception ignore)
{
}
// place the current alias, if any, in to context
List all = AliasService.getAliases((String) state.getAttribute(STATE_CHANNEL_REF), 1, 1);
if (!all.isEmpty()) context.put("alias", ((Alias) all.get(0)).getId());
context.put("serverName", ServerConfigurationService.getServerName());
// pick the "-customize" template based on the standard template name
String template = (String) getContext(rundata).get("template");
return template + "-customize";
} // buildOptionsPanelContext
/**
* doUpdate called for form input tags type="submit" named="eventSubmit_doUpdate" update/save from the options process
*/
public void doUpdate(RunData data, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData) data).getJs_peid();
SessionState state = ((JetspeedRunData) data).getPortletSessionState(peid);
// collect & save in state (for possible form re-draw)
// String pagesize = StringUtil.trimToZero(data.getParameters().getString(FORM_PAGESIZE));
// state.setAttribute(STATE_OPTION_PAGESIZE, pagesize);
String open = data.getParameters().getString(FORM_OPEN);
state.setAttribute(STATE_OPTION_OPEN, open);
String replyToList = data.getParameters().getString(FORM_REPLY);
state.setAttribute(STATE_OPTION_REPLY, replyToList);
String alias = StringUtil.trimToNull(data.getParameters().getString(FORM_ALIAS));
state.setAttribute(STATE_OPTION_ALIAS, alias);
MailArchiveChannel channel = null;
try
{
channel = MailArchiveService.getMailArchiveChannel((String) state.getAttribute(STATE_CHANNEL_REF));
}
catch (Exception e)
{
addAlert(state, rb.getString("cannot1"));
+ // FIXME confusing code: this exception will cause a NPE below
+ channel = null;
}
// first validate - page size
// int size = 0;
// try
// {
// size = Integer.parseInt(pagesize);
// if (size <= 0)
// {
// addAlert(state,rb.getString("pagsiz"));
// }
// }
// catch (Exception any)
// {
// addAlert(state, rb.getString("pagsiz"));
// }
// validate the email alias
if (alias != null)
{
if (!Validator.checkEmailLocal(alias))
{
addAlert(state, rb.getString("theemaali"));
}
}
// make sure we can get to the channel
MailArchiveChannelEdit edit = null;
try
{
- edit = (MailArchiveChannelEdit) MailArchiveService.editChannel(channel.getReference());
+ // FIXME if channel is null then this causes a NPE, if this is desired it should be moved up nearer to the other code
+ edit = (MailArchiveChannelEdit) MailArchiveService.editChannel(channel.getReference());
}
catch (Exception any)
{
addAlert(state, rb.getString("theemaarc"));
}
// if all is well, save
if (state.getAttribute(STATE_MESSAGE) == null)
{
// get any current alias for this channel
List all = AliasService.getAliases((String) state.getAttribute(STATE_CHANNEL_REF), 1, 1);
String curAlias = null;
if (!all.isEmpty()) curAlias = ((Alias) all.get(0)).getId();
// alias from the form
if (StringUtil.different(curAlias, alias))
{
boolean ok = false;
// see if this alias exists
if (alias != null)
{
try
{
String target = AliasService.getTarget(alias);
// if so, is it this channel?
ok = target.equals(channel.getReference());
}
catch (IdUnusedException e)
{
// not in use
ok = true;
}
}
else
{
// no alias is desired
ok = true;
}
if (ok)
{
try
{
// first, clear any alias set to this channel
AliasService.removeTargetAliases(channel.getReference());
// then add the desired alias
if (alias != null)
{
AliasService.setAlias(alias, channel.getReference());
}
}
catch (Exception any)
{
addAlert(state, rb.getString("theemaali2"));
}
}
else
{
addAlert(state, rb.getString("theemaali3"));
}
}
// if the alias saving went well, go on to the rest
if (state.getAttribute(STATE_MESSAGE) == null)
{
boolean modified = false;
// update the channel for open (if changed)
boolean ss = new Boolean(open).booleanValue();
if (channel.getOpen() != ss)
{
edit.setOpen(ss);
modified = true;
}
ss = new Boolean(replyToList).booleanValue();
if (channel.getReplyToList() != ss)
{
edit.setReplyToList(ss);
modified = true;
}
if (modified)
{
MailArchiveService.commitChannel(edit);
}
else
{
MailArchiveService.cancelChannel(edit);
}
edit = null;
// we are done with customization... back to the main (list) mode
state.setAttribute(STATE_MODE, "list");
// clear state temps.
state.removeAttribute(STATE_OPTION_PAGESIZE);
state.removeAttribute(STATE_OPTION_OPEN);
state.removeAttribute(STATE_OPTION_REPLY);
state.removeAttribute(STATE_OPTION_ALIAS);
// re-enable auto-updates when going back to list mode
enableObserver(state);
}
}
// before leaving, make sure the edit was cleared
if (edit != null)
{
MailArchiveService.cancelChannel(edit);
edit = null;
}
} // doUpdate
/**
* doCancel called for form input tags type="submit" named="eventSubmit_doCancel" cancel the options process
*/
public void doCancel(RunData data, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData) data).getJs_peid();
SessionState state = ((JetspeedRunData) data).getPortletSessionState(peid);
// cancel the options
cancelOptions();
// we are done with customization... back to the main (list) mode
state.setAttribute(STATE_MODE, "list");
// clear state temps.
state.removeAttribute(STATE_OPTION_PAGESIZE);
state.removeAttribute(STATE_OPTION_OPEN);
state.removeAttribute(STATE_OPTION_REPLY);
state.removeAttribute(STATE_OPTION_ALIAS);
// re-enable auto-updates when going back to list mode
enableObserver(state);
} // doCancel
/**
* Fire up the permissions editor
*/
public void doPermissions(RunData data, Context context)
{
// get into helper mode with this helper tool
startHelper(data.getRequest(), "sakai.permissions.helper");
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
String channelRefStr = (String) state.getAttribute(STATE_CHANNEL_REF);
Reference channelRef = EntityManager.newReference(channelRefStr);
String siteRef = SiteService.siteReference(channelRef.getContext());
// setup for editing the permissions of the site for this tool, using the roles of this site, too
state.setAttribute(PermissionsHelper.TARGET_REF, siteRef);
// ... with this description
state.setAttribute(PermissionsHelper.DESCRIPTION, rb.getString("setperm")
+ SiteService.getSiteDisplay(channelRef.getContext()));
// ... showing only locks that are prpefixed with this
state.setAttribute(PermissionsHelper.PREFIX, "mail.");
} // doPermissions
private Search getSearchFilter(String search, int first, int last)
{
return new MailMessageSearchFilter(search, first, last);
}
protected class MailMessageSearchFilter extends Search implements SearchFilter
{
public MailMessageSearchFilter(String searchString, int first, int last)
{
super(searchString);
this.setStart(first);
this.setLimit(last);
}
// Deal with the name mis-match
public String getSearchString()
{
return this.getQueryString();
}
/**
* Does this object satisfy the criteria of the filter?
*
* @param o
* The object to test.
* @return true if the object is accepted by the filter, false if not.
*/
public boolean accept(Object o)
{
// we want to test only messages
if (!(o instanceof MailArchiveMessage))
{
return false;
}
String searchStr = getSearchString();
if ( searchStr != null )
{
MailArchiveMessage msg = (MailArchiveMessage) o;
if (StringUtil.containsIgnoreCase(msg.getMailArchiveHeader().getSubject(), searchStr)
|| StringUtil.containsIgnoreCase(msg.getMailArchiveHeader().getFromAddress(), searchStr)
|| StringUtil.containsIgnoreCase(FormattedText.convertFormattedTextToPlaintext(msg.getBody()), searchStr))
{
return false;
}
}
return true;
}
}
/**
* get the Message Threshold - above which searching is disabled
*/
private int getMessageThreshold()
{
return ServerConfigurationService.getInt("sakai.mailbox.search-threshold",
MESSAGE_THRESHOLD_DEFAULT);
}
} // MailboxAction
| false | true | public void doUpdate(RunData data, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData) data).getJs_peid();
SessionState state = ((JetspeedRunData) data).getPortletSessionState(peid);
// collect & save in state (for possible form re-draw)
// String pagesize = StringUtil.trimToZero(data.getParameters().getString(FORM_PAGESIZE));
// state.setAttribute(STATE_OPTION_PAGESIZE, pagesize);
String open = data.getParameters().getString(FORM_OPEN);
state.setAttribute(STATE_OPTION_OPEN, open);
String replyToList = data.getParameters().getString(FORM_REPLY);
state.setAttribute(STATE_OPTION_REPLY, replyToList);
String alias = StringUtil.trimToNull(data.getParameters().getString(FORM_ALIAS));
state.setAttribute(STATE_OPTION_ALIAS, alias);
MailArchiveChannel channel = null;
try
{
channel = MailArchiveService.getMailArchiveChannel((String) state.getAttribute(STATE_CHANNEL_REF));
}
catch (Exception e)
{
addAlert(state, rb.getString("cannot1"));
}
// first validate - page size
// int size = 0;
// try
// {
// size = Integer.parseInt(pagesize);
// if (size <= 0)
// {
// addAlert(state,rb.getString("pagsiz"));
// }
// }
// catch (Exception any)
// {
// addAlert(state, rb.getString("pagsiz"));
// }
// validate the email alias
if (alias != null)
{
if (!Validator.checkEmailLocal(alias))
{
addAlert(state, rb.getString("theemaali"));
}
}
// make sure we can get to the channel
MailArchiveChannelEdit edit = null;
try
{
edit = (MailArchiveChannelEdit) MailArchiveService.editChannel(channel.getReference());
}
catch (Exception any)
{
addAlert(state, rb.getString("theemaarc"));
}
// if all is well, save
if (state.getAttribute(STATE_MESSAGE) == null)
{
// get any current alias for this channel
List all = AliasService.getAliases((String) state.getAttribute(STATE_CHANNEL_REF), 1, 1);
String curAlias = null;
if (!all.isEmpty()) curAlias = ((Alias) all.get(0)).getId();
// alias from the form
if (StringUtil.different(curAlias, alias))
{
boolean ok = false;
// see if this alias exists
if (alias != null)
{
try
{
String target = AliasService.getTarget(alias);
// if so, is it this channel?
ok = target.equals(channel.getReference());
}
catch (IdUnusedException e)
{
// not in use
ok = true;
}
}
else
{
// no alias is desired
ok = true;
}
if (ok)
{
try
{
// first, clear any alias set to this channel
AliasService.removeTargetAliases(channel.getReference());
// then add the desired alias
if (alias != null)
{
AliasService.setAlias(alias, channel.getReference());
}
}
catch (Exception any)
{
addAlert(state, rb.getString("theemaali2"));
}
}
else
{
addAlert(state, rb.getString("theemaali3"));
}
}
// if the alias saving went well, go on to the rest
if (state.getAttribute(STATE_MESSAGE) == null)
{
boolean modified = false;
// update the channel for open (if changed)
boolean ss = new Boolean(open).booleanValue();
if (channel.getOpen() != ss)
{
edit.setOpen(ss);
modified = true;
}
ss = new Boolean(replyToList).booleanValue();
if (channel.getReplyToList() != ss)
{
edit.setReplyToList(ss);
modified = true;
}
if (modified)
{
MailArchiveService.commitChannel(edit);
}
else
{
MailArchiveService.cancelChannel(edit);
}
edit = null;
// we are done with customization... back to the main (list) mode
state.setAttribute(STATE_MODE, "list");
// clear state temps.
state.removeAttribute(STATE_OPTION_PAGESIZE);
state.removeAttribute(STATE_OPTION_OPEN);
state.removeAttribute(STATE_OPTION_REPLY);
state.removeAttribute(STATE_OPTION_ALIAS);
// re-enable auto-updates when going back to list mode
enableObserver(state);
}
}
// before leaving, make sure the edit was cleared
if (edit != null)
{
MailArchiveService.cancelChannel(edit);
edit = null;
}
} // doUpdate
| public void doUpdate(RunData data, Context context)
{
// access the portlet element id to find our state
String peid = ((JetspeedRunData) data).getJs_peid();
SessionState state = ((JetspeedRunData) data).getPortletSessionState(peid);
// collect & save in state (for possible form re-draw)
// String pagesize = StringUtil.trimToZero(data.getParameters().getString(FORM_PAGESIZE));
// state.setAttribute(STATE_OPTION_PAGESIZE, pagesize);
String open = data.getParameters().getString(FORM_OPEN);
state.setAttribute(STATE_OPTION_OPEN, open);
String replyToList = data.getParameters().getString(FORM_REPLY);
state.setAttribute(STATE_OPTION_REPLY, replyToList);
String alias = StringUtil.trimToNull(data.getParameters().getString(FORM_ALIAS));
state.setAttribute(STATE_OPTION_ALIAS, alias);
MailArchiveChannel channel = null;
try
{
channel = MailArchiveService.getMailArchiveChannel((String) state.getAttribute(STATE_CHANNEL_REF));
}
catch (Exception e)
{
addAlert(state, rb.getString("cannot1"));
// FIXME confusing code: this exception will cause a NPE below
channel = null;
}
// first validate - page size
// int size = 0;
// try
// {
// size = Integer.parseInt(pagesize);
// if (size <= 0)
// {
// addAlert(state,rb.getString("pagsiz"));
// }
// }
// catch (Exception any)
// {
// addAlert(state, rb.getString("pagsiz"));
// }
// validate the email alias
if (alias != null)
{
if (!Validator.checkEmailLocal(alias))
{
addAlert(state, rb.getString("theemaali"));
}
}
// make sure we can get to the channel
MailArchiveChannelEdit edit = null;
try
{
// FIXME if channel is null then this causes a NPE, if this is desired it should be moved up nearer to the other code
edit = (MailArchiveChannelEdit) MailArchiveService.editChannel(channel.getReference());
}
catch (Exception any)
{
addAlert(state, rb.getString("theemaarc"));
}
// if all is well, save
if (state.getAttribute(STATE_MESSAGE) == null)
{
// get any current alias for this channel
List all = AliasService.getAliases((String) state.getAttribute(STATE_CHANNEL_REF), 1, 1);
String curAlias = null;
if (!all.isEmpty()) curAlias = ((Alias) all.get(0)).getId();
// alias from the form
if (StringUtil.different(curAlias, alias))
{
boolean ok = false;
// see if this alias exists
if (alias != null)
{
try
{
String target = AliasService.getTarget(alias);
// if so, is it this channel?
ok = target.equals(channel.getReference());
}
catch (IdUnusedException e)
{
// not in use
ok = true;
}
}
else
{
// no alias is desired
ok = true;
}
if (ok)
{
try
{
// first, clear any alias set to this channel
AliasService.removeTargetAliases(channel.getReference());
// then add the desired alias
if (alias != null)
{
AliasService.setAlias(alias, channel.getReference());
}
}
catch (Exception any)
{
addAlert(state, rb.getString("theemaali2"));
}
}
else
{
addAlert(state, rb.getString("theemaali3"));
}
}
// if the alias saving went well, go on to the rest
if (state.getAttribute(STATE_MESSAGE) == null)
{
boolean modified = false;
// update the channel for open (if changed)
boolean ss = new Boolean(open).booleanValue();
if (channel.getOpen() != ss)
{
edit.setOpen(ss);
modified = true;
}
ss = new Boolean(replyToList).booleanValue();
if (channel.getReplyToList() != ss)
{
edit.setReplyToList(ss);
modified = true;
}
if (modified)
{
MailArchiveService.commitChannel(edit);
}
else
{
MailArchiveService.cancelChannel(edit);
}
edit = null;
// we are done with customization... back to the main (list) mode
state.setAttribute(STATE_MODE, "list");
// clear state temps.
state.removeAttribute(STATE_OPTION_PAGESIZE);
state.removeAttribute(STATE_OPTION_OPEN);
state.removeAttribute(STATE_OPTION_REPLY);
state.removeAttribute(STATE_OPTION_ALIAS);
// re-enable auto-updates when going back to list mode
enableObserver(state);
}
}
// before leaving, make sure the edit was cleared
if (edit != null)
{
MailArchiveService.cancelChannel(edit);
edit = null;
}
} // doUpdate
|
diff --git a/Algorithms/AdvancedGraph.java b/Algorithms/AdvancedGraph.java
index b1df2a5..a32e335 100644
--- a/Algorithms/AdvancedGraph.java
+++ b/Algorithms/AdvancedGraph.java
@@ -1,82 +1,82 @@
package Algorithms;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import Graphs.Edge;
import Graphs.Graph;
import Graphs.Vertex;
/**
* Advanced Graph Algorithms
* @author RDrapeau
*
*/
public class AdvancedGraph {
/**
* Random variable for algorithms.
*/
private static final Random r = new Random();
/**
* Returns a Minimum Spanning Tree as a graph using Prim's algorithm.
*
* @param g - The connected undirected acyclic graph
* @return The minimum spanning tree for the graph
*/
public Graph minSpanTree(Graph g) {
Graph result = new Graph();
if (g.numberOfVertices() > 0) {
Map<Vertex, Vertex> convert = new HashMap<Vertex, Vertex>();
Queue<Edge> q = new PriorityQueue<Edge>();
Vertex s = g.getVertex(r.nextInt(g.numberOfVertices()) + 1); // Numbered 1 to N
convert.put(s, new Vertex(s.getID()));
q.addAll(s.getEdges());
result.addVertex(convert.get(s));
- while (result.numberOfVertices() != g.numberOfEdges() && !q.isEmpty()) {
+ while (result.numberOfVertices() != g.numberOfVertices()) {
Edge e = q.remove();
if (!convert.containsKey(e.getHead()) || !convert.containsKey(e.getTail())) { // New Vertex Discovered
Vertex tail = e.getTail();
Vertex head = e.getHead();
update(convert, q, result, tail, head);
tail = convert.get(tail); // Grab new Tail
head = convert.get(head); // Grab new Head
Edge shortest = new Edge(tail, head, e.getWeight());
tail.addEdge(shortest);
head.addEdge(shortest);
result.addEdge(shortest);
}
}
}
return result;
}
/**
* Updates the Map, Heap, and the result so far to contain the newly discovered Vertex.
*
* @param convert - Conversion from the old vertices to the new ones in the tree
* @param q - The Heap of edges
* @param result - The minimum spanning tree so far
* @param tail - The tail of the edge
* @param head - The head of the edge
*/
private void update(Map<Vertex, Vertex> convert, Queue<Edge> q, Graph result, Vertex tail, Vertex head) {
if (!convert.containsKey(tail)) { /// Doesn't contain tail
q.addAll(tail.getEdges());
convert.put(tail, new Vertex(tail.getID()));
result.addVertex(convert.get(tail));
} else { // Doesn't contain head
q.addAll(head.getEdges());
convert.put(head, new Vertex(head.getID()));
result.addVertex(convert.get(head));
}
}
}
| true | true | public Graph minSpanTree(Graph g) {
Graph result = new Graph();
if (g.numberOfVertices() > 0) {
Map<Vertex, Vertex> convert = new HashMap<Vertex, Vertex>();
Queue<Edge> q = new PriorityQueue<Edge>();
Vertex s = g.getVertex(r.nextInt(g.numberOfVertices()) + 1); // Numbered 1 to N
convert.put(s, new Vertex(s.getID()));
q.addAll(s.getEdges());
result.addVertex(convert.get(s));
while (result.numberOfVertices() != g.numberOfEdges() && !q.isEmpty()) {
Edge e = q.remove();
if (!convert.containsKey(e.getHead()) || !convert.containsKey(e.getTail())) { // New Vertex Discovered
Vertex tail = e.getTail();
Vertex head = e.getHead();
update(convert, q, result, tail, head);
tail = convert.get(tail); // Grab new Tail
head = convert.get(head); // Grab new Head
Edge shortest = new Edge(tail, head, e.getWeight());
tail.addEdge(shortest);
head.addEdge(shortest);
result.addEdge(shortest);
}
}
}
return result;
}
| public Graph minSpanTree(Graph g) {
Graph result = new Graph();
if (g.numberOfVertices() > 0) {
Map<Vertex, Vertex> convert = new HashMap<Vertex, Vertex>();
Queue<Edge> q = new PriorityQueue<Edge>();
Vertex s = g.getVertex(r.nextInt(g.numberOfVertices()) + 1); // Numbered 1 to N
convert.put(s, new Vertex(s.getID()));
q.addAll(s.getEdges());
result.addVertex(convert.get(s));
while (result.numberOfVertices() != g.numberOfVertices()) {
Edge e = q.remove();
if (!convert.containsKey(e.getHead()) || !convert.containsKey(e.getTail())) { // New Vertex Discovered
Vertex tail = e.getTail();
Vertex head = e.getHead();
update(convert, q, result, tail, head);
tail = convert.get(tail); // Grab new Tail
head = convert.get(head); // Grab new Head
Edge shortest = new Edge(tail, head, e.getWeight());
tail.addEdge(shortest);
head.addEdge(shortest);
result.addEdge(shortest);
}
}
}
return result;
}
|
diff --git a/src/api/org/openmrs/validator/ObsValidator.java b/src/api/org/openmrs/validator/ObsValidator.java
index bb982916..4284ba2c 100644
--- a/src/api/org/openmrs/validator/ObsValidator.java
+++ b/src/api/org/openmrs/validator/ObsValidator.java
@@ -1,168 +1,167 @@
/**
* 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.validator;
import java.util.ArrayList;
import java.util.List;
import org.openmrs.Concept;
import org.openmrs.ConceptDatatype;
import org.openmrs.ConceptNumeric;
import org.openmrs.Obs;
import org.openmrs.annotation.Handler;
import org.openmrs.api.context.Context;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
/**
* Validator for the Obs class. This class checks for anything set on the Obs object that will cause
* errors or is incorrect. Things checked are similar to:
* <ul>
* <li>all required properties are filled in on the Obs object.
* <li>checks for no recursion in the obs grouping.
* <li>Makes sure the obs has at least one value (if not an obs grouping)</li>
*
* @see org.openmrs.Obs
*/
@Handler(supports = { Obs.class }, order = 50)
public class ObsValidator implements Validator {
public final static int VALUE_TEXT_MAX_LENGTH = 50;
/**
* @see org.springframework.validation.Validator#supports(java.lang.Class)
*/
@SuppressWarnings("unchecked")
public boolean supports(Class c) {
return Obs.class.isAssignableFrom(c);
}
/**
* @see org.springframework.validation.Validator#validate(java.lang.Object,
* org.springframework.validation.Errors)
* @should fail validation if personId is null
* @should fail validation if obsDatetime is null
* @should fail validation if concept is null
* @should fail validation if concept datatype is boolean and valueBoolean is null
* @should fail validation if concept datatype is coded and valueCoded is null
* @should fail validation if concept datatype is date and valueDatetime is null
* @should fail validation if concept datatype is numeric and valueNumeric is null
* @should fail validation if concept datatype is text and valueText is null
* @should fail validation if obs ancestors contains obs
* @should pass validation if all values present
*/
public void validate(Object obj, Errors errors) {
Obs obs = (Obs) obj;
List<Obs> ancestors = new ArrayList<Obs>();
//ancestors.add(obs);
validateHelper(obs, errors, ancestors, true);
}
/**
* Checks whether obs has all required values, and also checks to make sure that no obs group
* contains any of its ancestors
*
* @param obs
* @param errors
* @param ancestors
* @param atRootNode whether or not this is the obs that validate() was originally called on. If
* not then we shouldn't reject fields by name.
*/
private void validateHelper(Obs obs, Errors errors, List<Obs> ancestors, boolean atRootNode) {
if (obs.getPersonId() == null)
errors.rejectValue("person", "error.null");
if (obs.getObsDatetime() == null)
errors.rejectValue("obsDatetime", "error.null");
Concept c = obs.getConcept();
if (c == null) {
errors.rejectValue("concept", "error.null");
} else {
ConceptDatatype dt = c.getDatatype();
if (dt.isBoolean() && obs.getValueAsBoolean() == null) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isCoded() && obs.getValueCoded() == null) {
if (atRootNode)
errors.rejectValue("valueCoded", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
- } else if (dt.isDate() && obs.getValueDatetime() == null) {
+ } else if (dt.isDateTime() && obs.getValueDatetime() == null) {
if (atRootNode)
errors.rejectValue("valueDatetime", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isNumeric() && obs.getValueNumeric() == null) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isNumeric()) {
ConceptNumeric cn = Context.getConceptService().getConceptNumeric(c.getConceptId());
// If the concept numeric is not precise, the value cannot be a float, so raise an error
if (!cn.isPrecise() && Math.ceil(obs.getValueNumeric()) != obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.precision");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
// If the number is higher than the absolute range, raise an error
if (cn.getHiAbsolute() != null && cn.getHiAbsolute() < obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.outOfRange.high");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
// If the number is lower than the absolute range, raise an error as well
if (cn.getLowAbsolute() != null && cn.getLowAbsolute() > obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.outOfRange.low");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
} else if (dt.isText() && obs.getValueText() == null) {
if (atRootNode)
errors.rejectValue("valueText", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
//If valueText is longer than the maxlength, raise an error as well.
- if (dt.isText() && obs.getValueText() != null
- && obs.getValueText().length() > VALUE_TEXT_MAX_LENGTH) {
+ if (dt.isText() && obs.getValueText() != null && obs.getValueText().length() > VALUE_TEXT_MAX_LENGTH) {
if (atRootNode)
errors.rejectValue("valueText", "error.exceededMaxLengthOfField");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
}
// If an obs fails validation, don't bother checking its children
if (errors.hasErrors())
return;
if (ancestors.contains(obs))
errors.rejectValue("groupMembers", "Obs.error.groupContainsItself");
if (obs.isObsGrouping()) {
ancestors.add(obs);
for (Obs child : obs.getGroupMembers()) {
validateHelper(child, errors, ancestors, false);
}
ancestors.remove(ancestors.size() - 1);
}
}
}
| false | true | private void validateHelper(Obs obs, Errors errors, List<Obs> ancestors, boolean atRootNode) {
if (obs.getPersonId() == null)
errors.rejectValue("person", "error.null");
if (obs.getObsDatetime() == null)
errors.rejectValue("obsDatetime", "error.null");
Concept c = obs.getConcept();
if (c == null) {
errors.rejectValue("concept", "error.null");
} else {
ConceptDatatype dt = c.getDatatype();
if (dt.isBoolean() && obs.getValueAsBoolean() == null) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isCoded() && obs.getValueCoded() == null) {
if (atRootNode)
errors.rejectValue("valueCoded", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isDate() && obs.getValueDatetime() == null) {
if (atRootNode)
errors.rejectValue("valueDatetime", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isNumeric() && obs.getValueNumeric() == null) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isNumeric()) {
ConceptNumeric cn = Context.getConceptService().getConceptNumeric(c.getConceptId());
// If the concept numeric is not precise, the value cannot be a float, so raise an error
if (!cn.isPrecise() && Math.ceil(obs.getValueNumeric()) != obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.precision");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
// If the number is higher than the absolute range, raise an error
if (cn.getHiAbsolute() != null && cn.getHiAbsolute() < obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.outOfRange.high");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
// If the number is lower than the absolute range, raise an error as well
if (cn.getLowAbsolute() != null && cn.getLowAbsolute() > obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.outOfRange.low");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
} else if (dt.isText() && obs.getValueText() == null) {
if (atRootNode)
errors.rejectValue("valueText", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
//If valueText is longer than the maxlength, raise an error as well.
if (dt.isText() && obs.getValueText() != null
&& obs.getValueText().length() > VALUE_TEXT_MAX_LENGTH) {
if (atRootNode)
errors.rejectValue("valueText", "error.exceededMaxLengthOfField");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
}
// If an obs fails validation, don't bother checking its children
if (errors.hasErrors())
return;
if (ancestors.contains(obs))
errors.rejectValue("groupMembers", "Obs.error.groupContainsItself");
if (obs.isObsGrouping()) {
ancestors.add(obs);
for (Obs child : obs.getGroupMembers()) {
validateHelper(child, errors, ancestors, false);
}
ancestors.remove(ancestors.size() - 1);
}
}
| private void validateHelper(Obs obs, Errors errors, List<Obs> ancestors, boolean atRootNode) {
if (obs.getPersonId() == null)
errors.rejectValue("person", "error.null");
if (obs.getObsDatetime() == null)
errors.rejectValue("obsDatetime", "error.null");
Concept c = obs.getConcept();
if (c == null) {
errors.rejectValue("concept", "error.null");
} else {
ConceptDatatype dt = c.getDatatype();
if (dt.isBoolean() && obs.getValueAsBoolean() == null) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isCoded() && obs.getValueCoded() == null) {
if (atRootNode)
errors.rejectValue("valueCoded", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isDateTime() && obs.getValueDatetime() == null) {
if (atRootNode)
errors.rejectValue("valueDatetime", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isNumeric() && obs.getValueNumeric() == null) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
} else if (dt.isNumeric()) {
ConceptNumeric cn = Context.getConceptService().getConceptNumeric(c.getConceptId());
// If the concept numeric is not precise, the value cannot be a float, so raise an error
if (!cn.isPrecise() && Math.ceil(obs.getValueNumeric()) != obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.precision");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
// If the number is higher than the absolute range, raise an error
if (cn.getHiAbsolute() != null && cn.getHiAbsolute() < obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.outOfRange.high");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
// If the number is lower than the absolute range, raise an error as well
if (cn.getLowAbsolute() != null && cn.getLowAbsolute() > obs.getValueNumeric()) {
if (atRootNode)
errors.rejectValue("valueNumeric", "error.outOfRange.low");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
} else if (dt.isText() && obs.getValueText() == null) {
if (atRootNode)
errors.rejectValue("valueText", "error.null");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
//If valueText is longer than the maxlength, raise an error as well.
if (dt.isText() && obs.getValueText() != null && obs.getValueText().length() > VALUE_TEXT_MAX_LENGTH) {
if (atRootNode)
errors.rejectValue("valueText", "error.exceededMaxLengthOfField");
else
errors.rejectValue("groupMembers", "Obs.error.inGroupMember");
}
}
// If an obs fails validation, don't bother checking its children
if (errors.hasErrors())
return;
if (ancestors.contains(obs))
errors.rejectValue("groupMembers", "Obs.error.groupContainsItself");
if (obs.isObsGrouping()) {
ancestors.add(obs);
for (Obs child : obs.getGroupMembers()) {
validateHelper(child, errors, ancestors, false);
}
ancestors.remove(ancestors.size() - 1);
}
}
|
diff --git a/src/net/cscott/sdr/calls/GeneralFormationMatcher.java b/src/net/cscott/sdr/calls/GeneralFormationMatcher.java
index ff712ca..6dcc313 100644
--- a/src/net/cscott/sdr/calls/GeneralFormationMatcher.java
+++ b/src/net/cscott/sdr/calls/GeneralFormationMatcher.java
@@ -1,657 +1,660 @@
package net.cscott.sdr.calls;
import static net.cscott.sdr.util.Tools.m;
import static net.cscott.sdr.util.Tools.p;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.cscott.jdoctest.JDoctestRunner;
import net.cscott.jutil.BitSetFactory;
import net.cscott.jutil.GenericMultiMap;
import net.cscott.jutil.Indexer;
import net.cscott.jutil.MultiMap;
import net.cscott.jutil.PersistentSet;
import net.cscott.jutil.SetFactory;
import net.cscott.sdr.calls.Breather.FormationPiece;
import net.cscott.sdr.calls.Position.Flag;
import net.cscott.sdr.calls.TaggedFormation.Tag;
import net.cscott.sdr.calls.TaggedFormation.TaggedDancerInfo;
import net.cscott.sdr.util.Fraction;
import org.junit.runner.RunWith;
/**
* {@link GeneralFormationMatcher} produces a {@link FormationMatch}
* given an input {@link Formation} and a goal {@link TaggedFormation}.
* This can be used to make {@link Matcher}s out of {@link TaggedFormation}s,
* via the {@link #makeMatcher} method.
*
* @author C. Scott Ananian
*/
@RunWith(value=JDoctestRunner.class)
public class GeneralFormationMatcher {
private GeneralFormationMatcher() {}
// currying, oh, my
public static Matcher makeMatcher(TaggedFormation... goals) {
return makeMatcher(Arrays.asList(goals));
}
public static Matcher makeMatcher(List<TaggedFormation> goals) {
String name = targetName(goals);
return makeMatcher(name, goals);
}
public static Matcher makeMatcher(final String name, final List<TaggedFormation> goals) {
return new Matcher() {
@Override
public FormationMatch match(Formation f) throws NoMatchException {
return doMatch(f, goals, false, false);
}
@Override
public String getName() { return name; }
};
}
/**
* Attempt to match the input formation against the goal formation; you can
* have multiple rotated copies of the goal formation in the input.
* Allow dancers who are not part of copies of the goal formation if
* allowUnmatchedDancers is true; allow copies of the goal formation
* with phantoms in them if usePhantoms is true. Returns the best
* such match (ie, most copies of the goal formation).
* @param input An untagged formation to match against.
* @param goal A tagged goal formation
* @param allowUnmatchedDancers allow dancers in the input formation not to
* match dancers in (copies of) the goal
* @param usePhantoms allow dancers in the goal formation not to match
* dancers in the input
* @return the match result
* @throws NoMatchException if there is no way to match the goal formation
* with the given input
* @doc.test A successful match with no phantoms or unmatched dancers:
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> GeneralFormationMatcher.doMatch(Formation.SQUARED_SET,
* > FormationList.COUPLE,
* > false, false)
* AAv
*
* BB> CC<
*
* DD^
* AA:
* 3B^ 3G^
* [3B: BEAU; 3G: BELLE]
* BB:
* 4B^ 4G^
* [4B: BEAU; 4G: BELLE]
* CC:
* 2B^ 2G^
* [2B: BEAU; 2G: BELLE]
* DD:
* 1B^ 1G^
* [1B: BEAU; 1G: BELLE]
* @doc.test A successful match with some unmatched dancers:
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> GeneralFormationMatcher.doMatch(FormationList.RH_TWIN_DIAMONDS,
* > FormationList.RH_MINIWAVE,
* > true, false)
* AA> BB>
*
* CC^ DDv
*
* EE< FF<
* AA: (unmatched)
* ^
* BB: (unmatched)
* ^
* CC:
* ^ v
* [ph: BEAU; ph: BEAU]
* DD:
* ^ v
* [ph: BEAU; ph: BEAU]
* EE: (unmatched)
* ^
* FF: (unmatched)
* ^
* @doc.test When possible, symmetry is preserved in the result:
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> GeneralFormationMatcher.doMatch(FormationList.PARALLEL_RH_WAVES,
* > FormationList.RH_MINIWAVE,
* > false, false)
* AA^ BBv
*
* CC^ DDv
* AA:
* ^ v
* [ph: BEAU; ph: BEAU]
* BB:
* ^ v
* [ph: BEAU; ph: BEAU]
* CC:
* ^ v
* [ph: BEAU; ph: BEAU]
* DD:
* ^ v
* [ph: BEAU; ph: BEAU]
*/
// booleans for 'allow unmatched dancers' and
// 'use phantoms' allow dancers in the input and result formations,
// respectively, not to match up.
// XXX: implement usePhantoms
// NOTE THAT result will include 1-dancer formations if
// allowUnmatchedDancers is true; see the contract of FormationMatch.
public static FormationMatch doMatch(
final Formation input,
final TaggedFormation goal,
boolean allowUnmatchedDancers,
boolean usePhantoms)
throws NoMatchException {
return doMatch(input, Collections.singletonList(goal),
allowUnmatchedDancers, usePhantoms);
}
private static String targetName(List<TaggedFormation> goals) {
StringBuilder sb = new StringBuilder();
assert goals.size() > 0;
for (TaggedFormation goal : goals) {
String name = (goal instanceof NamedTaggedFormation) ?
((NamedTaggedFormation) goal).getName() : goal.toString();
if (sb.length()>0) sb.append(',');
sb.append(name);
}
if (goals.size()>1)
return "MIXED("+sb.toString()+")";
return sb.toString();
}
/** sort so that first dancers' target rotations are most constrained,
* for efficiency. (ie largest rotation moduli are first) */
private static Comparator<Position> PCOMP = new Comparator<Position>() {
public int compare(Position p1, Position p2) {
int c = -p1.facing.modulus.compareTo(p2.facing.modulus);
if (c!=0) return c;
return p1.compareTo(p2);
}
};
/** Allow multiple simultaneous goal formations.
* @doc.test A successful match on a Siamese Diamond.
* js> importPackage(net.cscott.sdr.util); // for Fraction
* js> FormationList = FormationListJS.initJS(this); undefined;
* js> f = Formation.SQUARED_SET; undefined
* js> for each (d in StandardDancer.values()) {
* > if (d.isHead()) continue;
* > p = f.location(d).forwardStep(Fraction.valueOf(2), true).
* > turn(Fraction.valueOf(1,4), false);
* > f = f.move(d, p);
* > }; f.toStringDiagram('|');
* |3Gv 3Bv
* |
* |4Bv 2G^
* |
* |4Gv 2B^
* |
* |1B^ 1G^
* js> goals = java.util.Arrays.asList(FormationList.TANDEM,
* > FormationList.COUPLE); undefined
* js> GeneralFormationMatcher.doMatch(f, goals, false, false)
* AAv
*
* BBv CC^
*
* DD^
* AA:
* 3B^ 3G^
* [3B: BEAU; 3G: BELLE]
* BB:
* 4G^
*
* 4B^
* [4G: LEADER; 4B: TRAILER]
* CC:
* 2G^
*
* 2B^
* [2G: LEADER; 2B: TRAILER]
* DD:
* 1B^ 1G^
* [1B: BEAU; 1G: BELLE]
*/
public static FormationMatch doMatch(
final Formation input,
final List<TaggedFormation> goals,
boolean allowUnmatchedDancers,
boolean usePhantoms)
throws NoMatchException {
assert !usePhantoms : "matching with phantoms is not implemented";
// get an appropriate formation name
String target = targetName(goals);
// okay, try to perform match by trying to use each dancer in turn
// as dancer #1 in the goal formation. We then validate the match:
// make sure that there is a dancer in each position, that no dancer
// in the match is already in another match, and that the state isn't
// redundant due to symmetry. (To determine this last, we identify
// those 'other dancers' in the goal formation which are rotationally
// symmetric to dancer #1, and make sure that the proposed match
// doesn't assign any of these positions to dancers we've already
// tried as #1.) Finally, we'll have a list of matches. We
// identify the ones with a maximum number of the goal formation,
// and assert that this maximal match is unique; otherwise the
// match is ambiguous and we throw NoMatchException.
// (note that we ignore unselected dancers in formation f)
// (note that 'dancer #1' is really 'dancer #0' below)
assert goals.size() > 0;
int minGoalDancers = goals.get(0).dancers().size();
List<GoalInfo> goalInfo = new ArrayList<GoalInfo>(goals.size());
for (TaggedFormation goal : goals) {
// create GoalInfo
goalInfo.add(new GoalInfo(goal));
minGoalDancers = Math.min(minGoalDancers, goal.dancers().size());
}
if (minGoalDancers > input.dancers().size())
throw new NoMatchException(target, "goal is too large");
// sort the input dancers the same as the goal dancers: real dancers
// before phantoms.
// there must be at least one non-phantom dancer in the formation.
// in addition, group symmetric dancers together in the order, so
// that the resulting matches tend to symmetry.
final List<Dancer> inputDancers=new ArrayList<Dancer>(input.dancers());
Collections.sort(inputDancers, new Comparator<Dancer>() {
/** minimum of position rotated through 4 quarter rotations */
private Position qtrMin(Position p) {
if (!qtrMinCache.containsKey(p))
qtrMinCache.put(p, Collections.min(rotated(p), PCOMP));
return qtrMinCache.get(p);
}
/** minimum of position rotated by 180 degrees */
private Position halfMin(Position p) {
if (!halfMinCache.containsKey(p)) {
Position pprime = p.rotateAroundOrigin(ExactRotation.ONE_HALF);
Position r = Collections.min(Arrays.asList(p,pprime), PCOMP);
halfMinCache.put(p, r);
}
return halfMinCache.get(p);
}
public int compare(Dancer d1, Dancer d2) {
Position p1 = input.location(d1), p2 = input.location(d2);
// first comparison is against min of quarter-rotated versions
int c = PCOMP.compare(qtrMin(p1), qtrMin(p2));
if (c!=0) return c;
// now, compare against min of half-rotated versions
c = PCOMP.compare(halfMin(p1), halfMin(p2));
if (c!=0) return c;
// finally, break ties by comparing against "real" position
return PCOMP.compare(p1, p2);
}
private Map<Position,Position> halfMinCache = new HashMap<Position,Position>();
private Map<Position,Position> qtrMinCache = new HashMap<Position,Position>();
});
final Indexer<Dancer> inputIndex = new Indexer<Dancer>() {
Map<Dancer,Integer> index = new HashMap<Dancer,Integer>();
{ int i=0; for (Dancer d: inputDancers) index.put(d, i++); }
@Override
public int getID(Dancer d) { return index.get(d); }
@Override
public Dancer getByID(int id) { return inputDancers.get(id); }
@Override
public boolean implementsReverseMapping() { return true; }
};
final PersistentSet<Dancer> inputEmpty = new PersistentSet<Dancer>
(new Comparator<Dancer>() {
public int compare(Dancer d1, Dancer d2) {
return inputIndex.getID(d1) - inputIndex.getID(d2);
}
});
// now try setting each dancer in 'f' to d0 in the goal formation.
// Construct MatchInfo & initial (empty) assignment
MatchInfo mi = new MatchInfo(input, goalInfo, minGoalDancers,
inputDancers, inputIndex, inputEmpty);
PersistentSet<OneMatch> initialAssignment = new PersistentSet<OneMatch>
(new Comparator<OneMatch>(){
public int compare(OneMatch o1, OneMatch o2) {
int c=inputIndex.getID(o1.dancer)-inputIndex.getID(o2.dancer);
if (c!=0) return c;
return o1.extraRot.compareTo(o2.extraRot);
}
});
// Do the match
tryOne(mi, 0, initialAssignment, inputEmpty, allowUnmatchedDancers);
if (mi.matches.isEmpty())
throw new NoMatchException(target, "no matches");
// Filter out the max
int max = 0;
for (PersistentSet<OneMatch> match: mi.matches)
max = Math.max(max,match.size());
assert max > 0;
// Is it unique?
PersistentSet<OneMatch> bestMatch=null; boolean found = false;
for (PersistentSet<OneMatch> match: mi.matches)
if (match.size()==max)
if (found) // ambiguous match.
throw new NoMatchException(target, "ambiguous");
else {
bestMatch = match;
found = true;
}
assert found;
// track the input dancers who aren't involved in matches
Set<Dancer> unmappedInputDancers = new LinkedHashSet<Dancer>(inputDancers);
// Create a FormationMatch object from FormationPieces.
List<FormationPiece> pieces = new ArrayList<FormationPiece>(max);
Map<Dancer,TaggedFormation> canonical=new LinkedHashMap<Dancer,TaggedFormation>();
for (OneMatch om : bestMatch) {
Dancer id0 = om.dancer;//input dancer who's #1 in the goal formation
int dn0 = inputIndex.getID(id0);
Position inP = mi.inputPositions.get(dn0);
assert inP.facing instanceof ExactRotation :
"at least one real dancer must be in formation";
// make an ExactRotation for pGoal, given the extraRot
Position goP = makeExact(om.gi.goalPositions.get(0), om.extraRot);
Warp warpF = Warp.rotateAndMove(goP, inP);
Warp warpB = Warp.rotateAndMove(inP, goP);
ExactRotation rr = (ExactRotation) inP.facing.subtract(goP.facing.amount);
Map<Dancer,Position> subPos = new LinkedHashMap<Dancer,Position>();
MultiMap<Dancer,Tag> subTag = new GenericMultiMap<Dancer,Tag>();
for (Dancer goD : om.gi.goalDancers) {
goP = om.gi.goal.location(goD);
// warp to find which input dancer corresponds to this one
inP = warpF.warp(goP, Fraction.ZERO);
Dancer inD = mi.inputPositionMap.get(zeroRotation(inP));
// warp back to get an exact rotation for this version of goal
- goP = warpB.warp(input.location(inD), Fraction.ZERO);
+ Position goPr = warpB.warp(input.location(inD), Fraction.ZERO);
+ // to avoid distortion for 1/8 off formations, take only the
+ // rotation (and flags) from this new goP
+ goP = goPr.relocate(goP.x, goP.y, goPr.facing);
// add to this subformation.
subPos.put(inD, goP);
subTag.addAll(inD, om.gi.goal.tags(goD));
unmappedInputDancers.remove(inD);
}
TaggedFormation tf =
new TaggedFormation(new Formation(subPos), subTag);
Dancer dd = new PhantomDancer();
canonical.put(dd, tf);
Formation pieceI = input.select(tf.dancers()).onlySelected();
Formation pieceO = new Formation(m(p(dd, new Position(0,0,rr))));
pieces.add(new FormationPiece(pieceI, pieceO));
}
// add pieces for unmapped dancers (see spec for FormationMatch.meta)
Set<Dancer> unmatchedMetaDancers = new LinkedHashSet<Dancer>();
for (Dancer d : unmappedInputDancers) {
// these clauses are parallel to the ones above for matched dancers
Position inP = input.location(d);
Position goP = Position.getGrid(0,0,"n");
ExactRotation rr = (ExactRotation) // i know this is a no-op.
inP.facing.subtract(goP.facing.amount);
Dancer dd = new PhantomDancer();
TaggedFormation tf = new TaggedFormation
(new TaggedDancerInfo(d, goP));
canonical.put(dd, tf);
unmatchedMetaDancers.add(dd);
Formation pieceI = input.select(tf.dancers()).onlySelected();
Formation pieceO = new Formation(m(p(dd, new Position(0,0,rr))));
pieces.add(new FormationPiece(pieceI, pieceO));
}
// the components formations are the warped & rotated version.
// the rotation in 'components' tells how much they were rotated.
// the canonical formations have the input dancers, and the formations
// are unwarped and unrotated. The key dancers in the canonical map
// are the phantoms from the meta formation.
return new FormationMatch(Breather.breathe(pieces), canonical,
unmatchedMetaDancers);
}
private static class OneMatch {
/** Which goal formation. */
public final GoalInfo gi;
/** This input dancer is #1 in the goal formation. */
public final Dancer dancer;
/** This is the 'extra rotation' needed to align the goal formation,
* if dancer #1 in the goal formation allows multiple orientations. */
public final Fraction extraRot;
OneMatch(GoalInfo gi, Dancer dancer, Fraction extraRot) {
this.gi = gi; this.dancer = dancer; this.extraRot = extraRot;
}
}
private static class GoalInfo {
final List<Dancer> goalDancers;
final List<Position> goalPositions;
final TaggedFormation goal;
final Set<Dancer> eq0; // goal dancers who are symmetric to goal dancer #0
final int numExtra; // number of 'extra' rotations we'll try to match
GoalInfo(final TaggedFormation goal) {
this.goal = goal;
// make a canonical ordering for the goal dancers
this.goalDancers=new ArrayList<Dancer>(goal.dancers());
Collections.sort(this.goalDancers, new Comparator<Dancer>() {
public int compare(Dancer d1, Dancer d2) {
return PCOMP.compare(goal.location(d1), goal.location(d2));
}
});
SetFactory<Dancer> gsf = new BitSetFactory<Dancer>(goalDancers);
// Identify dancers who are symmetric to dancer #0
assert goal.isCentered(); // Assumes center of goal formation is 0,0
Dancer gd0 = goalDancers.get(0);
this.eq0 = gsf.makeSet();
Position p0 = goal.location(gd0).normalize(); // remember p0.facing is most exact
for (Dancer gd : goalDancers)
for (Position rp: rotated(goal.location(gd)))
if (rp.x.equals(p0.x) && rp.y.equals(p0.y)&&
rp.facing.includes(p0.facing))
eq0.add(gd);
assert eq0.contains(gd0);//at the very least, gd0 is symmetric to itself
// map dancer # to position
this.goalPositions = new ArrayList<Position>(goalDancers.size());
for (Dancer d : goalDancers) {
Position p = goal.location(d);
this.goalPositions.add(p);
}
// first goal dancer has a rotation modulus which is 1/N for some
// N. This means we need to try N other rotations for matches.
this.numExtra = goal.location
(goalDancers.get(0)).facing.modulus.getDenominator();
}
}
private static class MatchInfo {
final List<PersistentSet<OneMatch>> matches = new ArrayList<PersistentSet<OneMatch>>();
final Indexer<Dancer> inputIndex;
final Map<Position,Dancer> inputPositionMap = new HashMap<Position,Dancer>();
final List<Position> inputPositions = new ArrayList<Position>();
final List<GoalInfo> goals;
final int minGoalDancers;
final int numInput;
final Set<Dancer> sel; // input dancers who are selected
// these next one is used to pass info into validate & back:
/** Input dancers who are already assigned to a formation. */
PersistentSet<Dancer> inFormation;
/** Size of the current best match. */
int bestMatchSize = 0;
MatchInfo(Formation f, List<GoalInfo> goals, int minGoalDancers,
List<Dancer> inputDancers, Indexer<Dancer> inputIndex,
PersistentSet<Dancer> inputEmpty) {
for (Dancer d : inputDancers) {
Position p = f.location(d);
this.inputPositions.add(p);
this.inputPositionMap.put(zeroRotation(p), d);
}
this.numInput = inputDancers.size();
this.inputIndex = inputIndex;
this.sel = f.selected;
this.inFormation = inputEmpty;
this.goals = goals;
this.minGoalDancers = minGoalDancers;
}
}
private static boolean validate(MatchInfo mi, GoalInfo goal, int dancerNum, Fraction extraRot) {
PersistentSet<Dancer> inFormation = mi.inFormation;
Set<Dancer> eq0 = goal.eq0;
// find some Dancer in the input formation to correspond to each
// Dancer in the goal formation. Each such dancer must not already
// be assigned.
Position pIn = mi.inputPositions.get(dancerNum);
assert pIn.facing instanceof ExactRotation :
"at least one dancer in the input formation must be non-phantom";
Position pGoal = makeExact(goal.goalPositions.get(0), extraRot);
Warp warp = Warp.rotateAndMove(pGoal, pIn);
int gNum = 0;
for (Position gp : goal.goalPositions) {
// compute warped position.
gp = warp.warp(gp, Fraction.ZERO);
Position key = zeroRotation(gp);
if (!mi.inputPositionMap.containsKey(key))
return false; // no input dancer at this goal position.
// okay, there is an input dancer:
Dancer iDan = mi.inputPositionMap.get(key);
int iNum = mi.inputIndex.getID(iDan);
// if this dancer selected?
if (!mi.sel.contains(iDan))
return false; // this dancer isn't selected.
// is he free to be assigned to this formation?
if (inFormation.contains(iDan))
return false; // this dancer is already in some match
// is his facing direction consistent?
Position ip = mi.inputPositions.get(iNum);
assert ip.x.equals(gp.x) && ip.y.equals(gp.y);
if (!gp.facing.includes(ip.facing))
return false; // rotations aren't correct.
// check for symmetry: if this goal position is 'eq0' (ie,
// symmetric with the 0 dancer's position), then this dancer #
// must be >= the 0 dancer's input # (ie, dancerNum)
if (eq0.contains(goal.goalDancers.get(gNum)))
if (iNum < dancerNum) {
// check that our matching rotation is really symmetric,
// since the goal dancer may have a vague direction which
// includes an asymmetric alternative (ie, "n|" as a target)
for (Position gp0 : rotated(goal.goalPositions.get(0))) {
gp0 = warp.warp(gp0, Fraction.ZERO);
if (ip.x.equals(gp0.x) &&
ip.y.equals(gp0.y) &&
gp0.facing.includes(ip.facing))
return false; // symmetric to some other canonical formation
}
}
// update 'in formation' and 'gNum'
inFormation = inFormation.add(iDan);
gNum++;
}
// return updates to inFormation
mi.inFormation = inFormation;
return true; // this is a valid match.
}
private static void tryOne(MatchInfo mi, int dancerNum,
PersistentSet<OneMatch> currentAssignment,
PersistentSet<Dancer> inFormation,
boolean allowUnmatchedDancers) {
if (dancerNum >= mi.numInput) {
if (inFormation.size() != mi.numInput)
if (!allowUnmatchedDancers)
return; // not a good assignment
// we've got a complete assignment; save it.
if (!currentAssignment.isEmpty() &&
currentAssignment.size() >= mi.bestMatchSize) {
mi.bestMatchSize = currentAssignment.size();
mi.matches.add(currentAssignment);
}
return;
}
// is there any way we can still match the bestMatchSize?
int dancer0sLeftToAssign = mi.numInput - dancerNum;
if (currentAssignment.size() + dancer0sLeftToAssign < mi.bestMatchSize)
return; // not enough dancer 0's to beat the current best match
int dancersLeftToAssign = mi.numInput - inFormation.size();
int goalsLeftToAssign = mi.bestMatchSize - currentAssignment.size();
if (mi.minGoalDancers*goalsLeftToAssign > dancersLeftToAssign)
return; // not enough unassigned dancers to beat the best match
// is this dancer available to be assigned?
Dancer thisDancer = mi.inputIndex.getByID(dancerNum);
if (!inFormation.contains(thisDancer)) {
// okay, try to assign the thisDancer, possibly w/ some extra rotation
for (GoalInfo gi : mi.goals) {
for (int i=0; i < gi.numExtra; i++) {
Fraction extraRot = Fraction.valueOf(i, gi.numExtra);
PersistentSet<OneMatch> newAssignment =
currentAssignment.add(new OneMatch(gi, thisDancer, extraRot));
mi.inFormation = inFormation;
if (validate(mi, gi, dancerNum, extraRot)) // sets mi.inFormation
// try to extend this match!
tryOne(mi, dancerNum+1, newAssignment, mi.inFormation,
allowUnmatchedDancers);
}
}
}
// try NOT assigning this dancer
tryOne(mi, dancerNum+1, currentAssignment, inFormation,
allowUnmatchedDancers);
}
/** Make a position with an ExactRotation from the given position with a
* general rotation and an 'extra rotation' amount. */
private static Position makeExact(Position p, Fraction extraRot) {
return new Position(p.x, p.y,
new ExactRotation(p.facing.amount.add(extraRot)));
}
/** Make a position with exact zero rotation from the given position. */
private static Position zeroRotation(Position p) {
return new Position(p.x, p.y, ExactRotation.ZERO);
}
private static Set<Position> rotated(Position p) {
Set<Position> s = new LinkedHashSet<Position>(4);
for (int i=0; i<4; i++) {
s.add(p);
p = p.rotateAroundOrigin(ExactRotation.ONE_QUARTER);
}
return s;
}
/** @deprecated XXX: rewrite to remove dependency on old Warp class */
private static abstract class Warp {
public abstract Position warp(Position p, Fraction time);
/** A <code>Warp</code> which returns points unchanged. */
public static final Warp NONE = new Warp() {
public Position warp(Position p, Fraction time) { return p; }
};
/** Returns a <code>Warp</code> which will rotate and translate
* points such that <code>from</code> is warped to <code>to</code>.
* Requires that both {@code from.facing} and {@code to.facing} are
* {@link ExactRotation}s.
*/
// XXX is this the right spec? Should we allow general Rotations?
public static Warp rotateAndMove(Position from, Position to) {
assert from.facing instanceof ExactRotation;
assert to.facing instanceof ExactRotation;
if (from.equals(to)) return NONE;
ExactRotation rot = (ExactRotation) to.facing.add(from.facing.amount.negate());
Position nFrom = rotateCWAroundOrigin(from,rot);
final Position warp = new Position
(to.x.subtract(nFrom.x), to.y.subtract(nFrom.y),
rot);
Warp w = new Warp() {
public Position warp(Position p, Fraction time) {
p = rotateCWAroundOrigin(p, (ExactRotation) warp.facing);
return p.relocate
(p.x.add(warp.x), p.y.add(warp.y), p.facing);
}
};
assert to.setFlags(from.flags.toArray(new Flag[0])).equals(w.warp(from,Fraction.ZERO)) : "bad warp "+to+" vs "+w.warp(from, Fraction.ZERO);
return w;
}
// helper method for rotateAndMove
private static Position rotateCWAroundOrigin(Position p, ExactRotation amt) {
Fraction x = p.x.multiply(amt.toY()).add(p.y.multiply(amt.toX()));
Fraction y = p.y.multiply(amt.toY()).subtract(p.x.multiply(amt.toX()));
return p.relocate(x, y, p.facing.add(amt.amount));
}
}
}
| true | true | public static FormationMatch doMatch(
final Formation input,
final List<TaggedFormation> goals,
boolean allowUnmatchedDancers,
boolean usePhantoms)
throws NoMatchException {
assert !usePhantoms : "matching with phantoms is not implemented";
// get an appropriate formation name
String target = targetName(goals);
// okay, try to perform match by trying to use each dancer in turn
// as dancer #1 in the goal formation. We then validate the match:
// make sure that there is a dancer in each position, that no dancer
// in the match is already in another match, and that the state isn't
// redundant due to symmetry. (To determine this last, we identify
// those 'other dancers' in the goal formation which are rotationally
// symmetric to dancer #1, and make sure that the proposed match
// doesn't assign any of these positions to dancers we've already
// tried as #1.) Finally, we'll have a list of matches. We
// identify the ones with a maximum number of the goal formation,
// and assert that this maximal match is unique; otherwise the
// match is ambiguous and we throw NoMatchException.
// (note that we ignore unselected dancers in formation f)
// (note that 'dancer #1' is really 'dancer #0' below)
assert goals.size() > 0;
int minGoalDancers = goals.get(0).dancers().size();
List<GoalInfo> goalInfo = new ArrayList<GoalInfo>(goals.size());
for (TaggedFormation goal : goals) {
// create GoalInfo
goalInfo.add(new GoalInfo(goal));
minGoalDancers = Math.min(minGoalDancers, goal.dancers().size());
}
if (minGoalDancers > input.dancers().size())
throw new NoMatchException(target, "goal is too large");
// sort the input dancers the same as the goal dancers: real dancers
// before phantoms.
// there must be at least one non-phantom dancer in the formation.
// in addition, group symmetric dancers together in the order, so
// that the resulting matches tend to symmetry.
final List<Dancer> inputDancers=new ArrayList<Dancer>(input.dancers());
Collections.sort(inputDancers, new Comparator<Dancer>() {
/** minimum of position rotated through 4 quarter rotations */
private Position qtrMin(Position p) {
if (!qtrMinCache.containsKey(p))
qtrMinCache.put(p, Collections.min(rotated(p), PCOMP));
return qtrMinCache.get(p);
}
/** minimum of position rotated by 180 degrees */
private Position halfMin(Position p) {
if (!halfMinCache.containsKey(p)) {
Position pprime = p.rotateAroundOrigin(ExactRotation.ONE_HALF);
Position r = Collections.min(Arrays.asList(p,pprime), PCOMP);
halfMinCache.put(p, r);
}
return halfMinCache.get(p);
}
public int compare(Dancer d1, Dancer d2) {
Position p1 = input.location(d1), p2 = input.location(d2);
// first comparison is against min of quarter-rotated versions
int c = PCOMP.compare(qtrMin(p1), qtrMin(p2));
if (c!=0) return c;
// now, compare against min of half-rotated versions
c = PCOMP.compare(halfMin(p1), halfMin(p2));
if (c!=0) return c;
// finally, break ties by comparing against "real" position
return PCOMP.compare(p1, p2);
}
private Map<Position,Position> halfMinCache = new HashMap<Position,Position>();
private Map<Position,Position> qtrMinCache = new HashMap<Position,Position>();
});
final Indexer<Dancer> inputIndex = new Indexer<Dancer>() {
Map<Dancer,Integer> index = new HashMap<Dancer,Integer>();
{ int i=0; for (Dancer d: inputDancers) index.put(d, i++); }
@Override
public int getID(Dancer d) { return index.get(d); }
@Override
public Dancer getByID(int id) { return inputDancers.get(id); }
@Override
public boolean implementsReverseMapping() { return true; }
};
final PersistentSet<Dancer> inputEmpty = new PersistentSet<Dancer>
(new Comparator<Dancer>() {
public int compare(Dancer d1, Dancer d2) {
return inputIndex.getID(d1) - inputIndex.getID(d2);
}
});
// now try setting each dancer in 'f' to d0 in the goal formation.
// Construct MatchInfo & initial (empty) assignment
MatchInfo mi = new MatchInfo(input, goalInfo, minGoalDancers,
inputDancers, inputIndex, inputEmpty);
PersistentSet<OneMatch> initialAssignment = new PersistentSet<OneMatch>
(new Comparator<OneMatch>(){
public int compare(OneMatch o1, OneMatch o2) {
int c=inputIndex.getID(o1.dancer)-inputIndex.getID(o2.dancer);
if (c!=0) return c;
return o1.extraRot.compareTo(o2.extraRot);
}
});
// Do the match
tryOne(mi, 0, initialAssignment, inputEmpty, allowUnmatchedDancers);
if (mi.matches.isEmpty())
throw new NoMatchException(target, "no matches");
// Filter out the max
int max = 0;
for (PersistentSet<OneMatch> match: mi.matches)
max = Math.max(max,match.size());
assert max > 0;
// Is it unique?
PersistentSet<OneMatch> bestMatch=null; boolean found = false;
for (PersistentSet<OneMatch> match: mi.matches)
if (match.size()==max)
if (found) // ambiguous match.
throw new NoMatchException(target, "ambiguous");
else {
bestMatch = match;
found = true;
}
assert found;
// track the input dancers who aren't involved in matches
Set<Dancer> unmappedInputDancers = new LinkedHashSet<Dancer>(inputDancers);
// Create a FormationMatch object from FormationPieces.
List<FormationPiece> pieces = new ArrayList<FormationPiece>(max);
Map<Dancer,TaggedFormation> canonical=new LinkedHashMap<Dancer,TaggedFormation>();
for (OneMatch om : bestMatch) {
Dancer id0 = om.dancer;//input dancer who's #1 in the goal formation
int dn0 = inputIndex.getID(id0);
Position inP = mi.inputPositions.get(dn0);
assert inP.facing instanceof ExactRotation :
"at least one real dancer must be in formation";
// make an ExactRotation for pGoal, given the extraRot
Position goP = makeExact(om.gi.goalPositions.get(0), om.extraRot);
Warp warpF = Warp.rotateAndMove(goP, inP);
Warp warpB = Warp.rotateAndMove(inP, goP);
ExactRotation rr = (ExactRotation) inP.facing.subtract(goP.facing.amount);
Map<Dancer,Position> subPos = new LinkedHashMap<Dancer,Position>();
MultiMap<Dancer,Tag> subTag = new GenericMultiMap<Dancer,Tag>();
for (Dancer goD : om.gi.goalDancers) {
goP = om.gi.goal.location(goD);
// warp to find which input dancer corresponds to this one
inP = warpF.warp(goP, Fraction.ZERO);
Dancer inD = mi.inputPositionMap.get(zeroRotation(inP));
// warp back to get an exact rotation for this version of goal
goP = warpB.warp(input.location(inD), Fraction.ZERO);
// add to this subformation.
subPos.put(inD, goP);
subTag.addAll(inD, om.gi.goal.tags(goD));
unmappedInputDancers.remove(inD);
}
TaggedFormation tf =
new TaggedFormation(new Formation(subPos), subTag);
Dancer dd = new PhantomDancer();
canonical.put(dd, tf);
Formation pieceI = input.select(tf.dancers()).onlySelected();
Formation pieceO = new Formation(m(p(dd, new Position(0,0,rr))));
pieces.add(new FormationPiece(pieceI, pieceO));
}
// add pieces for unmapped dancers (see spec for FormationMatch.meta)
Set<Dancer> unmatchedMetaDancers = new LinkedHashSet<Dancer>();
for (Dancer d : unmappedInputDancers) {
// these clauses are parallel to the ones above for matched dancers
Position inP = input.location(d);
Position goP = Position.getGrid(0,0,"n");
ExactRotation rr = (ExactRotation) // i know this is a no-op.
inP.facing.subtract(goP.facing.amount);
Dancer dd = new PhantomDancer();
TaggedFormation tf = new TaggedFormation
(new TaggedDancerInfo(d, goP));
canonical.put(dd, tf);
unmatchedMetaDancers.add(dd);
Formation pieceI = input.select(tf.dancers()).onlySelected();
Formation pieceO = new Formation(m(p(dd, new Position(0,0,rr))));
pieces.add(new FormationPiece(pieceI, pieceO));
}
// the components formations are the warped & rotated version.
// the rotation in 'components' tells how much they were rotated.
// the canonical formations have the input dancers, and the formations
// are unwarped and unrotated. The key dancers in the canonical map
// are the phantoms from the meta formation.
return new FormationMatch(Breather.breathe(pieces), canonical,
unmatchedMetaDancers);
}
| public static FormationMatch doMatch(
final Formation input,
final List<TaggedFormation> goals,
boolean allowUnmatchedDancers,
boolean usePhantoms)
throws NoMatchException {
assert !usePhantoms : "matching with phantoms is not implemented";
// get an appropriate formation name
String target = targetName(goals);
// okay, try to perform match by trying to use each dancer in turn
// as dancer #1 in the goal formation. We then validate the match:
// make sure that there is a dancer in each position, that no dancer
// in the match is already in another match, and that the state isn't
// redundant due to symmetry. (To determine this last, we identify
// those 'other dancers' in the goal formation which are rotationally
// symmetric to dancer #1, and make sure that the proposed match
// doesn't assign any of these positions to dancers we've already
// tried as #1.) Finally, we'll have a list of matches. We
// identify the ones with a maximum number of the goal formation,
// and assert that this maximal match is unique; otherwise the
// match is ambiguous and we throw NoMatchException.
// (note that we ignore unselected dancers in formation f)
// (note that 'dancer #1' is really 'dancer #0' below)
assert goals.size() > 0;
int minGoalDancers = goals.get(0).dancers().size();
List<GoalInfo> goalInfo = new ArrayList<GoalInfo>(goals.size());
for (TaggedFormation goal : goals) {
// create GoalInfo
goalInfo.add(new GoalInfo(goal));
minGoalDancers = Math.min(minGoalDancers, goal.dancers().size());
}
if (minGoalDancers > input.dancers().size())
throw new NoMatchException(target, "goal is too large");
// sort the input dancers the same as the goal dancers: real dancers
// before phantoms.
// there must be at least one non-phantom dancer in the formation.
// in addition, group symmetric dancers together in the order, so
// that the resulting matches tend to symmetry.
final List<Dancer> inputDancers=new ArrayList<Dancer>(input.dancers());
Collections.sort(inputDancers, new Comparator<Dancer>() {
/** minimum of position rotated through 4 quarter rotations */
private Position qtrMin(Position p) {
if (!qtrMinCache.containsKey(p))
qtrMinCache.put(p, Collections.min(rotated(p), PCOMP));
return qtrMinCache.get(p);
}
/** minimum of position rotated by 180 degrees */
private Position halfMin(Position p) {
if (!halfMinCache.containsKey(p)) {
Position pprime = p.rotateAroundOrigin(ExactRotation.ONE_HALF);
Position r = Collections.min(Arrays.asList(p,pprime), PCOMP);
halfMinCache.put(p, r);
}
return halfMinCache.get(p);
}
public int compare(Dancer d1, Dancer d2) {
Position p1 = input.location(d1), p2 = input.location(d2);
// first comparison is against min of quarter-rotated versions
int c = PCOMP.compare(qtrMin(p1), qtrMin(p2));
if (c!=0) return c;
// now, compare against min of half-rotated versions
c = PCOMP.compare(halfMin(p1), halfMin(p2));
if (c!=0) return c;
// finally, break ties by comparing against "real" position
return PCOMP.compare(p1, p2);
}
private Map<Position,Position> halfMinCache = new HashMap<Position,Position>();
private Map<Position,Position> qtrMinCache = new HashMap<Position,Position>();
});
final Indexer<Dancer> inputIndex = new Indexer<Dancer>() {
Map<Dancer,Integer> index = new HashMap<Dancer,Integer>();
{ int i=0; for (Dancer d: inputDancers) index.put(d, i++); }
@Override
public int getID(Dancer d) { return index.get(d); }
@Override
public Dancer getByID(int id) { return inputDancers.get(id); }
@Override
public boolean implementsReverseMapping() { return true; }
};
final PersistentSet<Dancer> inputEmpty = new PersistentSet<Dancer>
(new Comparator<Dancer>() {
public int compare(Dancer d1, Dancer d2) {
return inputIndex.getID(d1) - inputIndex.getID(d2);
}
});
// now try setting each dancer in 'f' to d0 in the goal formation.
// Construct MatchInfo & initial (empty) assignment
MatchInfo mi = new MatchInfo(input, goalInfo, minGoalDancers,
inputDancers, inputIndex, inputEmpty);
PersistentSet<OneMatch> initialAssignment = new PersistentSet<OneMatch>
(new Comparator<OneMatch>(){
public int compare(OneMatch o1, OneMatch o2) {
int c=inputIndex.getID(o1.dancer)-inputIndex.getID(o2.dancer);
if (c!=0) return c;
return o1.extraRot.compareTo(o2.extraRot);
}
});
// Do the match
tryOne(mi, 0, initialAssignment, inputEmpty, allowUnmatchedDancers);
if (mi.matches.isEmpty())
throw new NoMatchException(target, "no matches");
// Filter out the max
int max = 0;
for (PersistentSet<OneMatch> match: mi.matches)
max = Math.max(max,match.size());
assert max > 0;
// Is it unique?
PersistentSet<OneMatch> bestMatch=null; boolean found = false;
for (PersistentSet<OneMatch> match: mi.matches)
if (match.size()==max)
if (found) // ambiguous match.
throw new NoMatchException(target, "ambiguous");
else {
bestMatch = match;
found = true;
}
assert found;
// track the input dancers who aren't involved in matches
Set<Dancer> unmappedInputDancers = new LinkedHashSet<Dancer>(inputDancers);
// Create a FormationMatch object from FormationPieces.
List<FormationPiece> pieces = new ArrayList<FormationPiece>(max);
Map<Dancer,TaggedFormation> canonical=new LinkedHashMap<Dancer,TaggedFormation>();
for (OneMatch om : bestMatch) {
Dancer id0 = om.dancer;//input dancer who's #1 in the goal formation
int dn0 = inputIndex.getID(id0);
Position inP = mi.inputPositions.get(dn0);
assert inP.facing instanceof ExactRotation :
"at least one real dancer must be in formation";
// make an ExactRotation for pGoal, given the extraRot
Position goP = makeExact(om.gi.goalPositions.get(0), om.extraRot);
Warp warpF = Warp.rotateAndMove(goP, inP);
Warp warpB = Warp.rotateAndMove(inP, goP);
ExactRotation rr = (ExactRotation) inP.facing.subtract(goP.facing.amount);
Map<Dancer,Position> subPos = new LinkedHashMap<Dancer,Position>();
MultiMap<Dancer,Tag> subTag = new GenericMultiMap<Dancer,Tag>();
for (Dancer goD : om.gi.goalDancers) {
goP = om.gi.goal.location(goD);
// warp to find which input dancer corresponds to this one
inP = warpF.warp(goP, Fraction.ZERO);
Dancer inD = mi.inputPositionMap.get(zeroRotation(inP));
// warp back to get an exact rotation for this version of goal
Position goPr = warpB.warp(input.location(inD), Fraction.ZERO);
// to avoid distortion for 1/8 off formations, take only the
// rotation (and flags) from this new goP
goP = goPr.relocate(goP.x, goP.y, goPr.facing);
// add to this subformation.
subPos.put(inD, goP);
subTag.addAll(inD, om.gi.goal.tags(goD));
unmappedInputDancers.remove(inD);
}
TaggedFormation tf =
new TaggedFormation(new Formation(subPos), subTag);
Dancer dd = new PhantomDancer();
canonical.put(dd, tf);
Formation pieceI = input.select(tf.dancers()).onlySelected();
Formation pieceO = new Formation(m(p(dd, new Position(0,0,rr))));
pieces.add(new FormationPiece(pieceI, pieceO));
}
// add pieces for unmapped dancers (see spec for FormationMatch.meta)
Set<Dancer> unmatchedMetaDancers = new LinkedHashSet<Dancer>();
for (Dancer d : unmappedInputDancers) {
// these clauses are parallel to the ones above for matched dancers
Position inP = input.location(d);
Position goP = Position.getGrid(0,0,"n");
ExactRotation rr = (ExactRotation) // i know this is a no-op.
inP.facing.subtract(goP.facing.amount);
Dancer dd = new PhantomDancer();
TaggedFormation tf = new TaggedFormation
(new TaggedDancerInfo(d, goP));
canonical.put(dd, tf);
unmatchedMetaDancers.add(dd);
Formation pieceI = input.select(tf.dancers()).onlySelected();
Formation pieceO = new Formation(m(p(dd, new Position(0,0,rr))));
pieces.add(new FormationPiece(pieceI, pieceO));
}
// the components formations are the warped & rotated version.
// the rotation in 'components' tells how much they were rotated.
// the canonical formations have the input dancers, and the formations
// are unwarped and unrotated. The key dancers in the canonical map
// are the phantoms from the meta formation.
return new FormationMatch(Breather.breathe(pieces), canonical,
unmatchedMetaDancers);
}
|
diff --git a/AndroidExtensions_Native/src/com/ssd/android/ane/functions/SMSFunction.java b/AndroidExtensions_Native/src/com/ssd/android/ane/functions/SMSFunction.java
index a6bc1af..a3b7406 100644
--- a/AndroidExtensions_Native/src/com/ssd/android/ane/functions/SMSFunction.java
+++ b/AndroidExtensions_Native/src/com/ssd/android/ane/functions/SMSFunction.java
@@ -1,49 +1,49 @@
package com.ssd.android.ane.functions;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;
import com.ssd.android.ane.AndroidExtensions;
/**
* <p>
* This function exposes the Android SMS facility. In order to use this function
* you have to provide:
*
* <li> the text for the SMS</li>
* <li> the telephone number of the recipient (optional)</li>
* </p>
* @author mr_archano (twitter: @mr_archano)
*
*/
public class SMSFunction implements FREFunction {
@Override
public FREObject call(FREContext context, FREObject[] args) {
if(args == null || args.length < 1) {
Log.e(AndroidExtensions.TAG, "Invalid arguments number for SMSFunction! (requested: text, optional: recipient)");
return null;
}
try{
String text = args[0].getAsString();
String recipient = "";
- if(args.length == 2) recipient = args[1].getAsString();
+ if(args.length == 2 && args[1] != null) recipient = args[1].getAsString();
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"+recipient));
sendIntent.putExtra("sms_body", text);
context.getActivity().startActivity(sendIntent);
}
catch(Exception e) {
Log.e(AndroidExtensions.TAG, "Error: "+e.getMessage(), e);
}
return null;
}
}
| true | true | public FREObject call(FREContext context, FREObject[] args) {
if(args == null || args.length < 1) {
Log.e(AndroidExtensions.TAG, "Invalid arguments number for SMSFunction! (requested: text, optional: recipient)");
return null;
}
try{
String text = args[0].getAsString();
String recipient = "";
if(args.length == 2) recipient = args[1].getAsString();
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"+recipient));
sendIntent.putExtra("sms_body", text);
context.getActivity().startActivity(sendIntent);
}
catch(Exception e) {
Log.e(AndroidExtensions.TAG, "Error: "+e.getMessage(), e);
}
return null;
}
| public FREObject call(FREContext context, FREObject[] args) {
if(args == null || args.length < 1) {
Log.e(AndroidExtensions.TAG, "Invalid arguments number for SMSFunction! (requested: text, optional: recipient)");
return null;
}
try{
String text = args[0].getAsString();
String recipient = "";
if(args.length == 2 && args[1] != null) recipient = args[1].getAsString();
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:"+recipient));
sendIntent.putExtra("sms_body", text);
context.getActivity().startActivity(sendIntent);
}
catch(Exception e) {
Log.e(AndroidExtensions.TAG, "Error: "+e.getMessage(), e);
}
return null;
}
|
diff --git a/bInfoBooks/src/uk/codingbadgers/binfobooks/commands/CommandBook.java b/bInfoBooks/src/uk/codingbadgers/binfobooks/commands/CommandBook.java
index adca16e..4f41af5 100644
--- a/bInfoBooks/src/uk/codingbadgers/binfobooks/commands/CommandBook.java
+++ b/bInfoBooks/src/uk/codingbadgers/binfobooks/commands/CommandBook.java
@@ -1,94 +1,94 @@
package uk.codingbadgers.binfobooks.commands;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import uk.codingbadgers.bFundamentals.commands.ModuleCommand;
import uk.codingbadgers.bFundamentals.module.Module;
import uk.codingbadgers.binfobooks.InfoBook;
import uk.codingbadgers.binfobooks.bInfoBooks;
public class CommandBook extends ModuleCommand {
private final bInfoBooks m_module;
/**
* Command constructor.
*/
public CommandBook(bInfoBooks intance) {
super("book", "book | book <name>");
m_module = intance;
}
/**
* Called when the 'book' command is executed.
*/
public boolean onCommand(CommandSender sender, String label, String[] args) {
if (!(sender instanceof Player)) {
System.out.println("Book commands must be used in game");
return true;
}
Player player = (Player)sender;
// List books
if (args.length == 0) {
if (Module.hasPermission(player, "binfobooks.list")) {
Module.sendMessage("bInfoBooks", player, "The following books are avaliable...");
m_module.listBooks(player);
} else {
Module.sendMessage("bInfoBooks", player, "You do not have permission to list books. [binfobooks.list]");
}
return true;
}
if (!Module.hasPermission(player, "binfobooks.get")) {
Module.sendMessage("bInfoBooks", player, "You do not have permission to get books. [binfobooks.get]");
return true;
}
// Get the name of the requested book
String bookName = "";
for (String arg : args) {
bookName = bookName + arg + " ";
}
bookName = bookName.substring(0, bookName.length() - 1);
boolean silent = false;
- if (bookName.substring(bookName.length() - 2).equalsIgnoreCase("-s")) {
+ if (bookName.length() > 1 && bookName.substring(bookName.length() - 2).equalsIgnoreCase("-s")) {
silent = true;
bookName = bookName.substring(0, bookName.length() - 3);
}
// See if the book exists
InfoBook book = m_module.bookExists(bookName);
if (book == null) {
if (!silent) {
Module.sendMessage("bInfoBooks", player, "No book by the name '" + bookName + "' exists.");
}
return true;
}
// See if player already has the same book
if (m_module.playerHasBook(player, book)) {
if (!silent) {
Module.sendMessage("bInfoBooks", player, "You already have a copy of the book '" + book.getName() + "' in your inventory.");
}
return true;
}
// Try and give the player the book
if (m_module.givePlayerBook(player, book)) {
if (!silent) {
Module.sendMessage("bInfoBooks", player, "You have been given the book '" + book.getName() + "'.");
}
}
return true;
}
}
| true | true | public boolean onCommand(CommandSender sender, String label, String[] args) {
if (!(sender instanceof Player)) {
System.out.println("Book commands must be used in game");
return true;
}
Player player = (Player)sender;
// List books
if (args.length == 0) {
if (Module.hasPermission(player, "binfobooks.list")) {
Module.sendMessage("bInfoBooks", player, "The following books are avaliable...");
m_module.listBooks(player);
} else {
Module.sendMessage("bInfoBooks", player, "You do not have permission to list books. [binfobooks.list]");
}
return true;
}
if (!Module.hasPermission(player, "binfobooks.get")) {
Module.sendMessage("bInfoBooks", player, "You do not have permission to get books. [binfobooks.get]");
return true;
}
// Get the name of the requested book
String bookName = "";
for (String arg : args) {
bookName = bookName + arg + " ";
}
bookName = bookName.substring(0, bookName.length() - 1);
boolean silent = false;
if (bookName.substring(bookName.length() - 2).equalsIgnoreCase("-s")) {
silent = true;
bookName = bookName.substring(0, bookName.length() - 3);
}
// See if the book exists
InfoBook book = m_module.bookExists(bookName);
if (book == null) {
if (!silent) {
Module.sendMessage("bInfoBooks", player, "No book by the name '" + bookName + "' exists.");
}
return true;
}
// See if player already has the same book
if (m_module.playerHasBook(player, book)) {
if (!silent) {
Module.sendMessage("bInfoBooks", player, "You already have a copy of the book '" + book.getName() + "' in your inventory.");
}
return true;
}
// Try and give the player the book
if (m_module.givePlayerBook(player, book)) {
if (!silent) {
Module.sendMessage("bInfoBooks", player, "You have been given the book '" + book.getName() + "'.");
}
}
return true;
}
| public boolean onCommand(CommandSender sender, String label, String[] args) {
if (!(sender instanceof Player)) {
System.out.println("Book commands must be used in game");
return true;
}
Player player = (Player)sender;
// List books
if (args.length == 0) {
if (Module.hasPermission(player, "binfobooks.list")) {
Module.sendMessage("bInfoBooks", player, "The following books are avaliable...");
m_module.listBooks(player);
} else {
Module.sendMessage("bInfoBooks", player, "You do not have permission to list books. [binfobooks.list]");
}
return true;
}
if (!Module.hasPermission(player, "binfobooks.get")) {
Module.sendMessage("bInfoBooks", player, "You do not have permission to get books. [binfobooks.get]");
return true;
}
// Get the name of the requested book
String bookName = "";
for (String arg : args) {
bookName = bookName + arg + " ";
}
bookName = bookName.substring(0, bookName.length() - 1);
boolean silent = false;
if (bookName.length() > 1 && bookName.substring(bookName.length() - 2).equalsIgnoreCase("-s")) {
silent = true;
bookName = bookName.substring(0, bookName.length() - 3);
}
// See if the book exists
InfoBook book = m_module.bookExists(bookName);
if (book == null) {
if (!silent) {
Module.sendMessage("bInfoBooks", player, "No book by the name '" + bookName + "' exists.");
}
return true;
}
// See if player already has the same book
if (m_module.playerHasBook(player, book)) {
if (!silent) {
Module.sendMessage("bInfoBooks", player, "You already have a copy of the book '" + book.getName() + "' in your inventory.");
}
return true;
}
// Try and give the player the book
if (m_module.givePlayerBook(player, book)) {
if (!silent) {
Module.sendMessage("bInfoBooks", player, "You have been given the book '" + book.getName() + "'.");
}
}
return true;
}
|
diff --git a/test/com/eteks/sweethome3d/junit/HomeCameraTest.java b/test/com/eteks/sweethome3d/junit/HomeCameraTest.java
index ed30077f..b428987e 100644
--- a/test/com/eteks/sweethome3d/junit/HomeCameraTest.java
+++ b/test/com/eteks/sweethome3d/junit/HomeCameraTest.java
@@ -1,493 +1,493 @@
/*
* HomeCameraTest.java 21 juin 2007
*
* Copyright (c) 2007 Emmanuel PUYBARET / eTeks <[email protected]>. All Rights Reserved.
*
* 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 com.eteks.sweethome3d.junit;
import java.awt.Point;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.lang.reflect.InvocationTargetException;
import java.util.Locale;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import junit.extensions.abbot.ComponentTestFixture;
import abbot.finder.AWTHierarchy;
import abbot.finder.BasicFinder;
import abbot.finder.ComponentSearchException;
import abbot.finder.matchers.ClassMatcher;
import abbot.finder.matchers.WindowMatcher;
import abbot.tester.ComponentLocation;
import abbot.tester.JComponentTester;
import com.eteks.sweethome3d.io.DefaultUserPreferences;
import com.eteks.sweethome3d.model.Camera;
import com.eteks.sweethome3d.model.CatalogTexture;
import com.eteks.sweethome3d.model.Home;
import com.eteks.sweethome3d.model.HomeEnvironment;
import com.eteks.sweethome3d.model.ObserverCamera;
import com.eteks.sweethome3d.model.TextureImage;
import com.eteks.sweethome3d.model.UserPreferences;
import com.eteks.sweethome3d.model.Wall;
import com.eteks.sweethome3d.swing.ColorButton;
import com.eteks.sweethome3d.swing.Home3DAttributesPanel;
import com.eteks.sweethome3d.swing.HomeComponent3D;
import com.eteks.sweethome3d.swing.HomePane;
import com.eteks.sweethome3d.swing.ObserverCameraPanel;
import com.eteks.sweethome3d.swing.PlanComponent;
import com.eteks.sweethome3d.swing.SwingViewFactory;
import com.eteks.sweethome3d.swing.TextureChoiceComponent;
import com.eteks.sweethome3d.tools.OperatingSystem;
import com.eteks.sweethome3d.viewcontroller.Home3DAttributesController;
import com.eteks.sweethome3d.viewcontroller.HomeController;
/**
* Tests camera changes in home.
* @author Emmanuel Puybaret
*/
public class HomeCameraTest extends ComponentTestFixture {
public void testHomeCamera() throws ComponentSearchException, InterruptedException,
NoSuchFieldException, IllegalAccessException, InvocationTargetException {
Locale.setDefault(Locale.FRANCE);
UserPreferences preferences = new DefaultUserPreferences();
Home home = new Home();
home.getCompass().setVisible(false);
final HomeController controller =
new HomeController(home, preferences, new SwingViewFactory());
JComponent homeView = (JComponent)controller.getView();
PlanComponent planComponent = (PlanComponent)TestUtilities.findComponent(
homeView, PlanComponent.class);
HomeComponent3D component3D = (HomeComponent3D)TestUtilities.findComponent(
homeView, HomeComponent3D.class);
// 1. Create a frame that displays a home view
JFrame frame = new JFrame("Home Camera Test");
frame.add(homeView);
frame.pack();
// Show home plan frame
showWindow(frame);
JComponentTester tester = new JComponentTester();
tester.waitForIdle();
// Transfer focus to plan view
planComponent.requestFocusInWindow();
tester.waitForIdle();
// Check plan view has focus
assertTrue("Plan component doesn't have the focus", planComponent.isFocusOwner());
// Check default camera is the top camera
assertSame("Default camera isn't top camera",
home.getTopCamera(), home.getCamera());
// Check default camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(500, 1500, 1010,
(float)Math.PI, (float)Math.PI / 4, home.getCamera());
// 2. Create one wall between points (50, 50) and (150, 50) at a bigger scale
runAction(controller, HomePane.ActionType.CREATE_WALLS, tester);
runAction(controller, HomePane.ActionType.ZOOM_IN, tester);
tester.actionKeyPress(TestUtilities.getMagnetismToggleKey());
tester.actionClick(planComponent, 50, 50);
tester.actionClick(planComponent, 150, 50, InputEvent.BUTTON1_MASK, 2);
tester.actionKeyRelease(TestUtilities.getMagnetismToggleKey());
// Check wall length is 100 * plan scale
Wall wall = home.getWalls().iterator().next();
assertTrue("Incorrect wall length " + 100 / planComponent.getScale()
+ " " + (wall.getXEnd() - wall.getXStart()),
Math.abs(wall.getXEnd() - wall.getXStart() - 100 / planComponent.getScale()) < 1E-3);
float xWallMiddle = (wall.getXEnd() + wall.getXStart()) / 2;
float yWallMiddle = (wall.getYEnd() + wall.getYStart()) / 2;
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(xWallMiddle, yWallMiddle + 1000, 1125,
(float)Math.PI, (float)Math.PI / 4, home.getCamera());
// 3. Transfer focus to 3D view with TAB key
tester.actionKeyStroke(KeyEvent.VK_TAB);
// Check 3D view has focus
assertTrue("3D component doesn't have the focus", component3D.isFocusOwner());
// Add 1� to camera pitch
tester.actionKeyStroke(KeyEvent.VK_PAGE_UP);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(xWallMiddle, 1052.5009f, 1098.4805f,
(float)Math.PI, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
- // 4. Remove 10� from camera yaw
+ // 4. Remove 1� from camera yaw
tester.actionKeyStroke(KeyEvent.VK_LEFT);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(147.02121f, 1051.095f, 1098.4805f,
(float)Math.PI - (float)Math.PI / 60, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
- // Add 1� to camera yaw
+ // Add 10� to camera yaw
tester.actionKeyPress(KeyEvent.VK_SHIFT);
tester.actionKeyStroke(KeyEvent.VK_RIGHT);
tester.actionKeyRelease(KeyEvent.VK_SHIFT);
// Check camera location and angles
- assertCoordinatesAndAnglesEqualCameraLocationAndAngles(-119.9497f, 1030.084f, 1098.4805f,
+ assertCoordinatesAndAnglesEqualCameraLocationAndAngles(-119.94972f, 1030.084f, 1098.4805f,
(float)Math.PI - (float)Math.PI / 60 + (float)Math.PI / 12, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
- // 5. Move camera 1cm forward
+ // 5. Move camera 10cm forward
tester.actionKeyPress(KeyEvent.VK_SHIFT);
tester.actionKeyStroke(KeyEvent.VK_UP);
tester.actionKeyRelease(KeyEvent.VK_SHIFT);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(-95.4424f, 914.7864f, 986.62274f,
(float)Math.PI - (float)Math.PI / 60 + (float)Math.PI / 12, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
- // Move camera 10 backward
+ // Move camera 1 backward
tester.actionKeyStroke(KeyEvent.VK_DOWN);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(-100.3438f, 937.8459f, 1008.99426f,
(float)Math.PI - (float)Math.PI / 60 + (float)Math.PI / 12, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
// 6. View from observer
runAction(controller, HomePane.ActionType.VIEW_FROM_OBSERVER, tester);
tester.waitForIdle();
ObserverCamera observerCamera = home.getObserverCamera();
// Check camera is the observer camera
assertSame("Camera isn't observer camera", observerCamera, home.getCamera());
// Check default camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(50, 50, 170,
7 * (float)Math.PI / 4, (float)Math.PI / 16, home.getCamera());
// Change camera location and angles
observerCamera.setX(100);
observerCamera.setY(100);
observerCamera.setYaw(3 * (float)Math.PI / 4);
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(100, 100, 170,
3 * (float)Math.PI / 4, (float)Math.PI / 16, home.getCamera());
// Check observer camera is selected
assertEquals("Wrong selected items count", 1, home.getSelectedItems().size());
assertTrue("Camera isn't selected", home.getSelectedItems().contains(home.getCamera()));
// Try to select wall and observer camera
runAction(controller, HomePane.ActionType.SELECT, tester);
tester.actionClick(planComponent, 50, 50);
tester.actionKeyPress(KeyEvent.VK_SHIFT);
tester.actionClick(planComponent, (int)(140 * planComponent.getScale()),
(int)(140 * planComponent.getScale()));
tester.actionKeyRelease(KeyEvent.VK_SHIFT);
// Check selected items contains only wall
assertEquals("Wrong selected items count", 1, home.getSelectedItems().size());
assertTrue("Wall isn't selected", home.getSelectedItems().contains(wall));
// Select observer camera
Thread.sleep(1000); // Wait 1s to avoid double click
tester.actionClick(planComponent, (int)(140 * planComponent.getScale()),
(int)(140 * planComponent.getScale()));
// Check observer camera is selected
assertEquals("Wrong selected items count", 1, home.getSelectedItems().size());
assertTrue("Camera isn't selected", home.getSelectedItems().contains(home.getCamera()));
// 7. Move observer camera at right and down
tester.actionKeyStroke(KeyEvent.VK_RIGHT);
tester.actionKeyStroke(KeyEvent.VK_DOWN);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(100 + 1 / planComponent.getScale(),
100 + 1 / planComponent.getScale(), 170,
3 * (float)Math.PI / 4, (float)Math.PI / 16, home.getCamera());
// 8. Change observer camera yaw by moving its yaw indicator
float [][] cameraPoints = observerCamera.getPoints();
int xYawIndicator = (int)(((40 + (cameraPoints[0][0] + cameraPoints[3][0]) / 2)) * planComponent.getScale());
int yYawIndicator = (int)(((40 + (cameraPoints[0][1] + cameraPoints[3][1]) / 2)) * planComponent.getScale());
tester.actionMousePress(planComponent, new ComponentLocation(
new Point(xYawIndicator, yYawIndicator)));
tester.actionMouseMove(planComponent, new ComponentLocation(
new Point(xYawIndicator + 2, yYawIndicator + 2)));
tester.actionMouseRelease();
// Check camera yaw angle changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(100 + 1 / planComponent.getScale(),
100 + 1 / planComponent.getScale(), 170,
2.5156f, (float)Math.PI / 16, home.getCamera());
// Change observer camera pitch by moving its pitch indicator
cameraPoints = observerCamera.getPoints();
int xPitchIndicator = (int)(((40 + (cameraPoints[1][0] + cameraPoints[2][0]) / 2)) * planComponent.getScale());
int yPitchIndicator = (int)(((40 + (cameraPoints[1][1] + cameraPoints[2][1]) / 2)) * planComponent.getScale());
tester.actionMousePress(planComponent, new ComponentLocation(
new Point(xPitchIndicator, yPitchIndicator)));
tester.actionMouseMove(planComponent, new ComponentLocation(
new Point(xPitchIndicator + 2, yPitchIndicator + 2)));
tester.actionMouseRelease();
// Check camera pitch angle changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(100 + 1 / planComponent.getScale(),
100 + 1 / planComponent.getScale(), 170,
2.5156f, 0.1639f, home.getCamera());
// 9. Change observer camera location with mouse in 3D view
tester.actionMousePress(component3D, new ComponentLocation(new Point(10, 10)));
tester.actionKeyPress(KeyEvent.VK_ALT);
tester.actionMouseMove(component3D, new ComponentLocation(new Point(10, 20)));
tester.actionKeyRelease(KeyEvent.VK_ALT);
tester.actionMouseRelease();
// Check camera location changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(108.657f, 111.4631f, 170,
2.5156f, 0.1639f, home.getCamera());
// 10. Change observer camera yaw with mouse in 3D view
tester.actionMousePress(component3D, new ComponentLocation(new Point(10, 20)));
tester.actionMouseMove(component3D, new ComponentLocation(new Point(20, 20)));
tester.actionMouseRelease();
// Check camera yaw changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(108.657f, 111.4631f, 170,
2.5656f, 0.1639f, home.getCamera());
// Change camera pitch with mouse in 3D view
tester.actionMousePress(component3D, new ComponentLocation(new Point(20, 20)));
tester.actionMouseMove(component3D, new ComponentLocation(new Point(20, 30)));
tester.actionMouseRelease();
// Check camera yaw changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(108.657f, 111.4631f, 170,
2.5656f, 0.2139f, home.getCamera());
// 11. Edit 3D view modal dialog box
JDialog attributesDialog = showHome3DAttributesPanel(preferences, controller, frame, tester);
// Retrieve Home3DAttributesPanel components
Home3DAttributesPanel panel = (Home3DAttributesPanel)TestUtilities.findComponent(
attributesDialog, Home3DAttributesPanel.class);
Home3DAttributesController panelController =
(Home3DAttributesController)TestUtilities.getField(panel, "controller");
ColorButton groundColorButton =
(ColorButton)TestUtilities.getField(panel, "groundColorButton");
ColorButton skyColorButton =
(ColorButton)TestUtilities.getField(panel, "skyColorButton");
JSlider brightnessSlider =
(JSlider)TestUtilities.getField(panel, "brightnessSlider");
JSlider wallsTransparencySlider =
(JSlider)TestUtilities.getField(panel, "wallsTransparencySlider");
// Check edited values
int oldGroundColor = home.getEnvironment().getGroundColor();
TextureImage oldGroundTexture = home.getEnvironment().getGroundTexture();
int oldSkyColor = home.getEnvironment().getSkyColor();
int oldLightColor = home.getEnvironment().getLightColor();
float oldWallsAlpha = home.getEnvironment().getWallsAlpha();
assertEquals("Wrong ground color", oldGroundColor,
groundColorButton.getColor().intValue());
assertEquals("Wrong ground texture", oldGroundTexture,
panelController.getGroundTextureController().getTexture());
assertEquals("Wrong sky color", oldSkyColor,
skyColorButton.getColor().intValue());
assertEquals("Wrong brightness", oldLightColor & 0xFF,
brightnessSlider.getValue());
assertEquals("Wrong transparency", (int)(oldWallsAlpha * 255),
wallsTransparencySlider.getValue());
// 12. Change dialog box values
groundColorButton.setColor(0xFFFFFF);
skyColorButton.setColor(0x000000);
brightnessSlider.setValue(128);
wallsTransparencySlider.setValue(128);
// Click on Ok in dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check home attributes are modified accordingly
assert3DAttributesEqualHomeAttributes(0xFFFFFF, null,
0x000000, 0x808080, 1 / 255f * 128f, home);
// 13. Undo changes
runAction(controller, HomePane.ActionType.UNDO, tester);
// Check home attributes have previous values
assert3DAttributesEqualHomeAttributes(oldGroundColor, null,
oldSkyColor, oldLightColor, oldWallsAlpha, home);
// Redo
runAction(controller, HomePane.ActionType.REDO, tester);
// Check home attributes are modified accordingly
assert3DAttributesEqualHomeAttributes(0xFFFFFF, null,
0x000000, 0x808080, 1 / 255f * 128f, home);
// 14. Edit 3D view modal dialog box to change ground texture
attributesDialog = showHome3DAttributesPanel(preferences, controller, frame, tester);
panel = (Home3DAttributesPanel)TestUtilities.findComponent(
attributesDialog, Home3DAttributesPanel.class);
panelController = (Home3DAttributesController)TestUtilities.getField(panel, "controller");
JRadioButton groundColorRadioButton =
(JRadioButton)TestUtilities.getField(panel, "groundColorRadioButton");
final TextureChoiceComponent groundTextureButton =
(TextureChoiceComponent)panelController.getGroundTextureController().getView();
JRadioButton groundTextureRadioButton =
(JRadioButton)TestUtilities.getField(panel, "groundTextureRadioButton");
// Check color and texture radio buttons
assertTrue("Ground color radio button isn't checked",
groundColorRadioButton.isSelected());
assertFalse("Ground texture radio button is checked",
groundTextureRadioButton.isSelected());
// Click on ground texture button
tester.invokeLater(new Runnable() {
public void run() {
// Display texture dialog later in Event Dispatch Thread to avoid blocking test thread
groundTextureButton.doClick();
}
});
// Wait for 3D view to be shown
String groundTextureTitle = preferences.getLocalizedString(
Home3DAttributesController.class, "groundTextureTitle");
tester.waitForFrameShowing(new AWTHierarchy(), groundTextureTitle);
// Check texture dialog box is displayed
JDialog textureDialog = (JDialog)new BasicFinder().find(attributesDialog,
new WindowMatcher(groundTextureTitle));
assertTrue("Texture dialog not showing", textureDialog.isShowing());
JList availableTexturesList = (JList)new BasicFinder().find(textureDialog,
new ClassMatcher(JList.class, true));
availableTexturesList.setSelectedIndex(0);
CatalogTexture firstTexture = preferences.getTexturesCatalog().getCategories().get(0).getTexture(0);
assertEquals("Wrong first texture in list", firstTexture,
availableTexturesList.getSelectedValue());
// Click on OK in texture dialog box
doClickOnOkInDialog(textureDialog, tester);
// Check color and texture radio buttons
assertFalse("Ground color radio button is checked",
groundColorRadioButton.isSelected());
assertTrue("Ground texture radio button isn't checked",
groundTextureRadioButton.isSelected());
// Click on OK in 3D attributes dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check home attributes are modified accordingly
assert3DAttributesEqualHomeAttributes(0xFFFFFF, firstTexture,
0x000000, 0x808080, 1 / 255f * 128f, home);
// 15. Edit observer camera attributes
tester.actionClick(planComponent, new ComponentLocation(new Point(115, 115)), InputEvent.BUTTON1_MASK, 2);
String observerCameraTitle = preferences.getLocalizedString(
ObserverCameraPanel.class, "observerCamera.title");
tester.waitForFrameShowing(new AWTHierarchy(), observerCameraTitle);
// Check observer camera dialog box is displayed
JDialog observerCameraDialog = (JDialog)new BasicFinder().find(frame,
new WindowMatcher(observerCameraTitle));
assertTrue("Observer camera dialog not showing", observerCameraDialog.isShowing());
ObserverCameraPanel observerCameraPanel = (ObserverCameraPanel)TestUtilities.findComponent(
observerCameraDialog, ObserverCameraPanel.class);
JSpinner fieldOfViewSpinner =
(JSpinner)TestUtilities.getField(observerCameraPanel, "fieldOfViewSpinner");
JSpinner elevationSpinner =
(JSpinner)TestUtilities.getField(observerCameraPanel, "elevationSpinner");
assertEquals("Wrong field of view", (int)Math.round(Math.toDegrees(observerCamera.getFieldOfView())),
fieldOfViewSpinner.getValue());
assertEquals("Wrong elevation", (float)Math.round(observerCamera.getZ() * 100) / 100,
elevationSpinner.getValue());
fieldOfViewSpinner.setValue(90);
elevationSpinner.setValue(300f);
// Click on OK in observer camera dialog box
doClickOnOkInDialog(observerCameraDialog, tester);
assertEquals("Wrong field of view", (float)Math.toRadians(90), observerCamera.getFieldOfView());
assertEquals("Wrong elevation", 300f, observerCamera.getZ());
}
/**
* Returns the dialog that displays home 3D attributes.
*/
private JDialog showHome3DAttributesPanel(UserPreferences preferences,
final HomeController controller,
JFrame parent, JComponentTester tester)
throws ComponentSearchException {
tester.invokeLater(new Runnable() {
public void run() {
// Display dialog box later in Event Dispatch Thread to avoid blocking test thread
((JComponent)controller.getView()).getActionMap().get(HomePane.ActionType.MODIFY_3D_ATTRIBUTES).actionPerformed(null);
}
});
// Wait for 3D view to be shown
tester.waitForFrameShowing(new AWTHierarchy(), preferences.getLocalizedString(
Home3DAttributesPanel.class, "home3DAttributes.title"));
// Check dialog box is displayed
JDialog attributesDialog = (JDialog)new BasicFinder().find(parent,
new ClassMatcher (JDialog.class, true));
assertTrue("3D view dialog not showing", attributesDialog.isShowing());
return attributesDialog;
}
/**
* Clicks on OK in dialog to close it.
*/
private void doClickOnOkInDialog(JDialog dialog, JComponentTester tester)
throws ComponentSearchException {
final JOptionPane attributesOptionPane = (JOptionPane)TestUtilities.findComponent(
dialog, JOptionPane.class);
tester.invokeAndWait(new Runnable() {
public void run() {
// Select Ok option to hide dialog box in Event Dispatch Thread
attributesOptionPane.setValue(JOptionPane.OK_OPTION);
}
});
assertFalse("Dialog still showing", dialog.isShowing());
}
/**
* Runs <code>actionPerformed</code> method matching <code>actionType</code>
* in <code>controller</code> view.
*/
private void runAction(final HomeController controller,
final HomePane.ActionType actionType,
JComponentTester tester) {
tester.invokeAndWait(new Runnable() {
public void run() {
((JComponent)controller.getView()).getActionMap().get(actionType).actionPerformed(null);
}
});
}
/**
* Asserts the location and angles of <code>camera</code> are the point
* at (<code>x</code>, <code>y</code>, <code>z</code>) and the angles
* <code>yaw</code> and <code>pitch</code>.
*/
private void assertCoordinatesAndAnglesEqualCameraLocationAndAngles(float x, float y,
float z, float yaw, float pitch,
Camera camera) {
assertTrue("Incorrect X " + camera.getX() + ", should be " + x,
Math.abs(x - camera.getX()) < 1E-3);
assertTrue("Incorrect Y " + camera.getY() + ", should be " + y,
Math.abs(y - camera.getY()) < 1E-3);
assertTrue("Incorrect Z " + camera.getZ() + ", should be " + z,
Math.abs(z - camera.getZ()) < 1E-3);
assertTrue("Incorrect yaw " + camera.getYaw() + ", should be " + yaw,
Math.abs(yaw - camera.getYaw()) < 1E-3);
assertTrue("Incorrect pitch " + camera.getPitch() + ", should be " + pitch,
Math.abs(pitch - camera.getPitch()) < 1E-3);
}
/**
* Asserts the 3D attributes given in parameter match <code>home</code> 3D attributes.
*/
private void assert3DAttributesEqualHomeAttributes(int groundColor,
TextureImage groundTexture,
int skyColor,
int lightColor,
float wallsAlpha,
Home home) {
HomeEnvironment homeEnvironment = home.getEnvironment();
assertEquals("Wrong ground color", groundColor, homeEnvironment.getGroundColor());
if (groundTexture == null) {
assertEquals("Wrong ground texture", groundTexture, homeEnvironment.getGroundTexture());
} else {
assertEquals("Wrong ground texture", groundTexture.getName(), homeEnvironment.getGroundTexture().getName());
}
assertEquals("Wrong sky color", skyColor, homeEnvironment.getSkyColor());
assertEquals("Wrong brightness", lightColor, homeEnvironment.getLightColor());
assertEquals("Wrong transparency", wallsAlpha, home.getEnvironment().getWallsAlpha());
}
}
| false | true | public void testHomeCamera() throws ComponentSearchException, InterruptedException,
NoSuchFieldException, IllegalAccessException, InvocationTargetException {
Locale.setDefault(Locale.FRANCE);
UserPreferences preferences = new DefaultUserPreferences();
Home home = new Home();
home.getCompass().setVisible(false);
final HomeController controller =
new HomeController(home, preferences, new SwingViewFactory());
JComponent homeView = (JComponent)controller.getView();
PlanComponent planComponent = (PlanComponent)TestUtilities.findComponent(
homeView, PlanComponent.class);
HomeComponent3D component3D = (HomeComponent3D)TestUtilities.findComponent(
homeView, HomeComponent3D.class);
// 1. Create a frame that displays a home view
JFrame frame = new JFrame("Home Camera Test");
frame.add(homeView);
frame.pack();
// Show home plan frame
showWindow(frame);
JComponentTester tester = new JComponentTester();
tester.waitForIdle();
// Transfer focus to plan view
planComponent.requestFocusInWindow();
tester.waitForIdle();
// Check plan view has focus
assertTrue("Plan component doesn't have the focus", planComponent.isFocusOwner());
// Check default camera is the top camera
assertSame("Default camera isn't top camera",
home.getTopCamera(), home.getCamera());
// Check default camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(500, 1500, 1010,
(float)Math.PI, (float)Math.PI / 4, home.getCamera());
// 2. Create one wall between points (50, 50) and (150, 50) at a bigger scale
runAction(controller, HomePane.ActionType.CREATE_WALLS, tester);
runAction(controller, HomePane.ActionType.ZOOM_IN, tester);
tester.actionKeyPress(TestUtilities.getMagnetismToggleKey());
tester.actionClick(planComponent, 50, 50);
tester.actionClick(planComponent, 150, 50, InputEvent.BUTTON1_MASK, 2);
tester.actionKeyRelease(TestUtilities.getMagnetismToggleKey());
// Check wall length is 100 * plan scale
Wall wall = home.getWalls().iterator().next();
assertTrue("Incorrect wall length " + 100 / planComponent.getScale()
+ " " + (wall.getXEnd() - wall.getXStart()),
Math.abs(wall.getXEnd() - wall.getXStart() - 100 / planComponent.getScale()) < 1E-3);
float xWallMiddle = (wall.getXEnd() + wall.getXStart()) / 2;
float yWallMiddle = (wall.getYEnd() + wall.getYStart()) / 2;
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(xWallMiddle, yWallMiddle + 1000, 1125,
(float)Math.PI, (float)Math.PI / 4, home.getCamera());
// 3. Transfer focus to 3D view with TAB key
tester.actionKeyStroke(KeyEvent.VK_TAB);
// Check 3D view has focus
assertTrue("3D component doesn't have the focus", component3D.isFocusOwner());
// Add 1� to camera pitch
tester.actionKeyStroke(KeyEvent.VK_PAGE_UP);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(xWallMiddle, 1052.5009f, 1098.4805f,
(float)Math.PI, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
// 4. Remove 10� from camera yaw
tester.actionKeyStroke(KeyEvent.VK_LEFT);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(147.02121f, 1051.095f, 1098.4805f,
(float)Math.PI - (float)Math.PI / 60, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
// Add 1� to camera yaw
tester.actionKeyPress(KeyEvent.VK_SHIFT);
tester.actionKeyStroke(KeyEvent.VK_RIGHT);
tester.actionKeyRelease(KeyEvent.VK_SHIFT);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(-119.9497f, 1030.084f, 1098.4805f,
(float)Math.PI - (float)Math.PI / 60 + (float)Math.PI / 12, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
// 5. Move camera 1cm forward
tester.actionKeyPress(KeyEvent.VK_SHIFT);
tester.actionKeyStroke(KeyEvent.VK_UP);
tester.actionKeyRelease(KeyEvent.VK_SHIFT);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(-95.4424f, 914.7864f, 986.62274f,
(float)Math.PI - (float)Math.PI / 60 + (float)Math.PI / 12, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
// Move camera 10 backward
tester.actionKeyStroke(KeyEvent.VK_DOWN);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(-100.3438f, 937.8459f, 1008.99426f,
(float)Math.PI - (float)Math.PI / 60 + (float)Math.PI / 12, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
// 6. View from observer
runAction(controller, HomePane.ActionType.VIEW_FROM_OBSERVER, tester);
tester.waitForIdle();
ObserverCamera observerCamera = home.getObserverCamera();
// Check camera is the observer camera
assertSame("Camera isn't observer camera", observerCamera, home.getCamera());
// Check default camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(50, 50, 170,
7 * (float)Math.PI / 4, (float)Math.PI / 16, home.getCamera());
// Change camera location and angles
observerCamera.setX(100);
observerCamera.setY(100);
observerCamera.setYaw(3 * (float)Math.PI / 4);
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(100, 100, 170,
3 * (float)Math.PI / 4, (float)Math.PI / 16, home.getCamera());
// Check observer camera is selected
assertEquals("Wrong selected items count", 1, home.getSelectedItems().size());
assertTrue("Camera isn't selected", home.getSelectedItems().contains(home.getCamera()));
// Try to select wall and observer camera
runAction(controller, HomePane.ActionType.SELECT, tester);
tester.actionClick(planComponent, 50, 50);
tester.actionKeyPress(KeyEvent.VK_SHIFT);
tester.actionClick(planComponent, (int)(140 * planComponent.getScale()),
(int)(140 * planComponent.getScale()));
tester.actionKeyRelease(KeyEvent.VK_SHIFT);
// Check selected items contains only wall
assertEquals("Wrong selected items count", 1, home.getSelectedItems().size());
assertTrue("Wall isn't selected", home.getSelectedItems().contains(wall));
// Select observer camera
Thread.sleep(1000); // Wait 1s to avoid double click
tester.actionClick(planComponent, (int)(140 * planComponent.getScale()),
(int)(140 * planComponent.getScale()));
// Check observer camera is selected
assertEquals("Wrong selected items count", 1, home.getSelectedItems().size());
assertTrue("Camera isn't selected", home.getSelectedItems().contains(home.getCamera()));
// 7. Move observer camera at right and down
tester.actionKeyStroke(KeyEvent.VK_RIGHT);
tester.actionKeyStroke(KeyEvent.VK_DOWN);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(100 + 1 / planComponent.getScale(),
100 + 1 / planComponent.getScale(), 170,
3 * (float)Math.PI / 4, (float)Math.PI / 16, home.getCamera());
// 8. Change observer camera yaw by moving its yaw indicator
float [][] cameraPoints = observerCamera.getPoints();
int xYawIndicator = (int)(((40 + (cameraPoints[0][0] + cameraPoints[3][0]) / 2)) * planComponent.getScale());
int yYawIndicator = (int)(((40 + (cameraPoints[0][1] + cameraPoints[3][1]) / 2)) * planComponent.getScale());
tester.actionMousePress(planComponent, new ComponentLocation(
new Point(xYawIndicator, yYawIndicator)));
tester.actionMouseMove(planComponent, new ComponentLocation(
new Point(xYawIndicator + 2, yYawIndicator + 2)));
tester.actionMouseRelease();
// Check camera yaw angle changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(100 + 1 / planComponent.getScale(),
100 + 1 / planComponent.getScale(), 170,
2.5156f, (float)Math.PI / 16, home.getCamera());
// Change observer camera pitch by moving its pitch indicator
cameraPoints = observerCamera.getPoints();
int xPitchIndicator = (int)(((40 + (cameraPoints[1][0] + cameraPoints[2][0]) / 2)) * planComponent.getScale());
int yPitchIndicator = (int)(((40 + (cameraPoints[1][1] + cameraPoints[2][1]) / 2)) * planComponent.getScale());
tester.actionMousePress(planComponent, new ComponentLocation(
new Point(xPitchIndicator, yPitchIndicator)));
tester.actionMouseMove(planComponent, new ComponentLocation(
new Point(xPitchIndicator + 2, yPitchIndicator + 2)));
tester.actionMouseRelease();
// Check camera pitch angle changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(100 + 1 / planComponent.getScale(),
100 + 1 / planComponent.getScale(), 170,
2.5156f, 0.1639f, home.getCamera());
// 9. Change observer camera location with mouse in 3D view
tester.actionMousePress(component3D, new ComponentLocation(new Point(10, 10)));
tester.actionKeyPress(KeyEvent.VK_ALT);
tester.actionMouseMove(component3D, new ComponentLocation(new Point(10, 20)));
tester.actionKeyRelease(KeyEvent.VK_ALT);
tester.actionMouseRelease();
// Check camera location changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(108.657f, 111.4631f, 170,
2.5156f, 0.1639f, home.getCamera());
// 10. Change observer camera yaw with mouse in 3D view
tester.actionMousePress(component3D, new ComponentLocation(new Point(10, 20)));
tester.actionMouseMove(component3D, new ComponentLocation(new Point(20, 20)));
tester.actionMouseRelease();
// Check camera yaw changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(108.657f, 111.4631f, 170,
2.5656f, 0.1639f, home.getCamera());
// Change camera pitch with mouse in 3D view
tester.actionMousePress(component3D, new ComponentLocation(new Point(20, 20)));
tester.actionMouseMove(component3D, new ComponentLocation(new Point(20, 30)));
tester.actionMouseRelease();
// Check camera yaw changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(108.657f, 111.4631f, 170,
2.5656f, 0.2139f, home.getCamera());
// 11. Edit 3D view modal dialog box
JDialog attributesDialog = showHome3DAttributesPanel(preferences, controller, frame, tester);
// Retrieve Home3DAttributesPanel components
Home3DAttributesPanel panel = (Home3DAttributesPanel)TestUtilities.findComponent(
attributesDialog, Home3DAttributesPanel.class);
Home3DAttributesController panelController =
(Home3DAttributesController)TestUtilities.getField(panel, "controller");
ColorButton groundColorButton =
(ColorButton)TestUtilities.getField(panel, "groundColorButton");
ColorButton skyColorButton =
(ColorButton)TestUtilities.getField(panel, "skyColorButton");
JSlider brightnessSlider =
(JSlider)TestUtilities.getField(panel, "brightnessSlider");
JSlider wallsTransparencySlider =
(JSlider)TestUtilities.getField(panel, "wallsTransparencySlider");
// Check edited values
int oldGroundColor = home.getEnvironment().getGroundColor();
TextureImage oldGroundTexture = home.getEnvironment().getGroundTexture();
int oldSkyColor = home.getEnvironment().getSkyColor();
int oldLightColor = home.getEnvironment().getLightColor();
float oldWallsAlpha = home.getEnvironment().getWallsAlpha();
assertEquals("Wrong ground color", oldGroundColor,
groundColorButton.getColor().intValue());
assertEquals("Wrong ground texture", oldGroundTexture,
panelController.getGroundTextureController().getTexture());
assertEquals("Wrong sky color", oldSkyColor,
skyColorButton.getColor().intValue());
assertEquals("Wrong brightness", oldLightColor & 0xFF,
brightnessSlider.getValue());
assertEquals("Wrong transparency", (int)(oldWallsAlpha * 255),
wallsTransparencySlider.getValue());
// 12. Change dialog box values
groundColorButton.setColor(0xFFFFFF);
skyColorButton.setColor(0x000000);
brightnessSlider.setValue(128);
wallsTransparencySlider.setValue(128);
// Click on Ok in dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check home attributes are modified accordingly
assert3DAttributesEqualHomeAttributes(0xFFFFFF, null,
0x000000, 0x808080, 1 / 255f * 128f, home);
// 13. Undo changes
runAction(controller, HomePane.ActionType.UNDO, tester);
// Check home attributes have previous values
assert3DAttributesEqualHomeAttributes(oldGroundColor, null,
oldSkyColor, oldLightColor, oldWallsAlpha, home);
// Redo
runAction(controller, HomePane.ActionType.REDO, tester);
// Check home attributes are modified accordingly
assert3DAttributesEqualHomeAttributes(0xFFFFFF, null,
0x000000, 0x808080, 1 / 255f * 128f, home);
// 14. Edit 3D view modal dialog box to change ground texture
attributesDialog = showHome3DAttributesPanel(preferences, controller, frame, tester);
panel = (Home3DAttributesPanel)TestUtilities.findComponent(
attributesDialog, Home3DAttributesPanel.class);
panelController = (Home3DAttributesController)TestUtilities.getField(panel, "controller");
JRadioButton groundColorRadioButton =
(JRadioButton)TestUtilities.getField(panel, "groundColorRadioButton");
final TextureChoiceComponent groundTextureButton =
(TextureChoiceComponent)panelController.getGroundTextureController().getView();
JRadioButton groundTextureRadioButton =
(JRadioButton)TestUtilities.getField(panel, "groundTextureRadioButton");
// Check color and texture radio buttons
assertTrue("Ground color radio button isn't checked",
groundColorRadioButton.isSelected());
assertFalse("Ground texture radio button is checked",
groundTextureRadioButton.isSelected());
// Click on ground texture button
tester.invokeLater(new Runnable() {
public void run() {
// Display texture dialog later in Event Dispatch Thread to avoid blocking test thread
groundTextureButton.doClick();
}
});
// Wait for 3D view to be shown
String groundTextureTitle = preferences.getLocalizedString(
Home3DAttributesController.class, "groundTextureTitle");
tester.waitForFrameShowing(new AWTHierarchy(), groundTextureTitle);
// Check texture dialog box is displayed
JDialog textureDialog = (JDialog)new BasicFinder().find(attributesDialog,
new WindowMatcher(groundTextureTitle));
assertTrue("Texture dialog not showing", textureDialog.isShowing());
JList availableTexturesList = (JList)new BasicFinder().find(textureDialog,
new ClassMatcher(JList.class, true));
availableTexturesList.setSelectedIndex(0);
CatalogTexture firstTexture = preferences.getTexturesCatalog().getCategories().get(0).getTexture(0);
assertEquals("Wrong first texture in list", firstTexture,
availableTexturesList.getSelectedValue());
// Click on OK in texture dialog box
doClickOnOkInDialog(textureDialog, tester);
// Check color and texture radio buttons
assertFalse("Ground color radio button is checked",
groundColorRadioButton.isSelected());
assertTrue("Ground texture radio button isn't checked",
groundTextureRadioButton.isSelected());
// Click on OK in 3D attributes dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check home attributes are modified accordingly
assert3DAttributesEqualHomeAttributes(0xFFFFFF, firstTexture,
0x000000, 0x808080, 1 / 255f * 128f, home);
// 15. Edit observer camera attributes
tester.actionClick(planComponent, new ComponentLocation(new Point(115, 115)), InputEvent.BUTTON1_MASK, 2);
String observerCameraTitle = preferences.getLocalizedString(
ObserverCameraPanel.class, "observerCamera.title");
tester.waitForFrameShowing(new AWTHierarchy(), observerCameraTitle);
// Check observer camera dialog box is displayed
JDialog observerCameraDialog = (JDialog)new BasicFinder().find(frame,
new WindowMatcher(observerCameraTitle));
assertTrue("Observer camera dialog not showing", observerCameraDialog.isShowing());
ObserverCameraPanel observerCameraPanel = (ObserverCameraPanel)TestUtilities.findComponent(
observerCameraDialog, ObserverCameraPanel.class);
JSpinner fieldOfViewSpinner =
(JSpinner)TestUtilities.getField(observerCameraPanel, "fieldOfViewSpinner");
JSpinner elevationSpinner =
(JSpinner)TestUtilities.getField(observerCameraPanel, "elevationSpinner");
assertEquals("Wrong field of view", (int)Math.round(Math.toDegrees(observerCamera.getFieldOfView())),
fieldOfViewSpinner.getValue());
assertEquals("Wrong elevation", (float)Math.round(observerCamera.getZ() * 100) / 100,
elevationSpinner.getValue());
fieldOfViewSpinner.setValue(90);
elevationSpinner.setValue(300f);
// Click on OK in observer camera dialog box
doClickOnOkInDialog(observerCameraDialog, tester);
assertEquals("Wrong field of view", (float)Math.toRadians(90), observerCamera.getFieldOfView());
assertEquals("Wrong elevation", 300f, observerCamera.getZ());
}
| public void testHomeCamera() throws ComponentSearchException, InterruptedException,
NoSuchFieldException, IllegalAccessException, InvocationTargetException {
Locale.setDefault(Locale.FRANCE);
UserPreferences preferences = new DefaultUserPreferences();
Home home = new Home();
home.getCompass().setVisible(false);
final HomeController controller =
new HomeController(home, preferences, new SwingViewFactory());
JComponent homeView = (JComponent)controller.getView();
PlanComponent planComponent = (PlanComponent)TestUtilities.findComponent(
homeView, PlanComponent.class);
HomeComponent3D component3D = (HomeComponent3D)TestUtilities.findComponent(
homeView, HomeComponent3D.class);
// 1. Create a frame that displays a home view
JFrame frame = new JFrame("Home Camera Test");
frame.add(homeView);
frame.pack();
// Show home plan frame
showWindow(frame);
JComponentTester tester = new JComponentTester();
tester.waitForIdle();
// Transfer focus to plan view
planComponent.requestFocusInWindow();
tester.waitForIdle();
// Check plan view has focus
assertTrue("Plan component doesn't have the focus", planComponent.isFocusOwner());
// Check default camera is the top camera
assertSame("Default camera isn't top camera",
home.getTopCamera(), home.getCamera());
// Check default camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(500, 1500, 1010,
(float)Math.PI, (float)Math.PI / 4, home.getCamera());
// 2. Create one wall between points (50, 50) and (150, 50) at a bigger scale
runAction(controller, HomePane.ActionType.CREATE_WALLS, tester);
runAction(controller, HomePane.ActionType.ZOOM_IN, tester);
tester.actionKeyPress(TestUtilities.getMagnetismToggleKey());
tester.actionClick(planComponent, 50, 50);
tester.actionClick(planComponent, 150, 50, InputEvent.BUTTON1_MASK, 2);
tester.actionKeyRelease(TestUtilities.getMagnetismToggleKey());
// Check wall length is 100 * plan scale
Wall wall = home.getWalls().iterator().next();
assertTrue("Incorrect wall length " + 100 / planComponent.getScale()
+ " " + (wall.getXEnd() - wall.getXStart()),
Math.abs(wall.getXEnd() - wall.getXStart() - 100 / planComponent.getScale()) < 1E-3);
float xWallMiddle = (wall.getXEnd() + wall.getXStart()) / 2;
float yWallMiddle = (wall.getYEnd() + wall.getYStart()) / 2;
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(xWallMiddle, yWallMiddle + 1000, 1125,
(float)Math.PI, (float)Math.PI / 4, home.getCamera());
// 3. Transfer focus to 3D view with TAB key
tester.actionKeyStroke(KeyEvent.VK_TAB);
// Check 3D view has focus
assertTrue("3D component doesn't have the focus", component3D.isFocusOwner());
// Add 1� to camera pitch
tester.actionKeyStroke(KeyEvent.VK_PAGE_UP);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(xWallMiddle, 1052.5009f, 1098.4805f,
(float)Math.PI, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
// 4. Remove 1� from camera yaw
tester.actionKeyStroke(KeyEvent.VK_LEFT);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(147.02121f, 1051.095f, 1098.4805f,
(float)Math.PI - (float)Math.PI / 60, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
// Add 10� to camera yaw
tester.actionKeyPress(KeyEvent.VK_SHIFT);
tester.actionKeyStroke(KeyEvent.VK_RIGHT);
tester.actionKeyRelease(KeyEvent.VK_SHIFT);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(-119.94972f, 1030.084f, 1098.4805f,
(float)Math.PI - (float)Math.PI / 60 + (float)Math.PI / 12, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
// 5. Move camera 10cm forward
tester.actionKeyPress(KeyEvent.VK_SHIFT);
tester.actionKeyStroke(KeyEvent.VK_UP);
tester.actionKeyRelease(KeyEvent.VK_SHIFT);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(-95.4424f, 914.7864f, 986.62274f,
(float)Math.PI - (float)Math.PI / 60 + (float)Math.PI / 12, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
// Move camera 1 backward
tester.actionKeyStroke(KeyEvent.VK_DOWN);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(-100.3438f, 937.8459f, 1008.99426f,
(float)Math.PI - (float)Math.PI / 60 + (float)Math.PI / 12, (float)Math.PI / 4 - (float)Math.PI / 120, home.getCamera());
// 6. View from observer
runAction(controller, HomePane.ActionType.VIEW_FROM_OBSERVER, tester);
tester.waitForIdle();
ObserverCamera observerCamera = home.getObserverCamera();
// Check camera is the observer camera
assertSame("Camera isn't observer camera", observerCamera, home.getCamera());
// Check default camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(50, 50, 170,
7 * (float)Math.PI / 4, (float)Math.PI / 16, home.getCamera());
// Change camera location and angles
observerCamera.setX(100);
observerCamera.setY(100);
observerCamera.setYaw(3 * (float)Math.PI / 4);
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(100, 100, 170,
3 * (float)Math.PI / 4, (float)Math.PI / 16, home.getCamera());
// Check observer camera is selected
assertEquals("Wrong selected items count", 1, home.getSelectedItems().size());
assertTrue("Camera isn't selected", home.getSelectedItems().contains(home.getCamera()));
// Try to select wall and observer camera
runAction(controller, HomePane.ActionType.SELECT, tester);
tester.actionClick(planComponent, 50, 50);
tester.actionKeyPress(KeyEvent.VK_SHIFT);
tester.actionClick(planComponent, (int)(140 * planComponent.getScale()),
(int)(140 * planComponent.getScale()));
tester.actionKeyRelease(KeyEvent.VK_SHIFT);
// Check selected items contains only wall
assertEquals("Wrong selected items count", 1, home.getSelectedItems().size());
assertTrue("Wall isn't selected", home.getSelectedItems().contains(wall));
// Select observer camera
Thread.sleep(1000); // Wait 1s to avoid double click
tester.actionClick(planComponent, (int)(140 * planComponent.getScale()),
(int)(140 * planComponent.getScale()));
// Check observer camera is selected
assertEquals("Wrong selected items count", 1, home.getSelectedItems().size());
assertTrue("Camera isn't selected", home.getSelectedItems().contains(home.getCamera()));
// 7. Move observer camera at right and down
tester.actionKeyStroke(KeyEvent.VK_RIGHT);
tester.actionKeyStroke(KeyEvent.VK_DOWN);
// Check camera location and angles
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(100 + 1 / planComponent.getScale(),
100 + 1 / planComponent.getScale(), 170,
3 * (float)Math.PI / 4, (float)Math.PI / 16, home.getCamera());
// 8. Change observer camera yaw by moving its yaw indicator
float [][] cameraPoints = observerCamera.getPoints();
int xYawIndicator = (int)(((40 + (cameraPoints[0][0] + cameraPoints[3][0]) / 2)) * planComponent.getScale());
int yYawIndicator = (int)(((40 + (cameraPoints[0][1] + cameraPoints[3][1]) / 2)) * planComponent.getScale());
tester.actionMousePress(planComponent, new ComponentLocation(
new Point(xYawIndicator, yYawIndicator)));
tester.actionMouseMove(planComponent, new ComponentLocation(
new Point(xYawIndicator + 2, yYawIndicator + 2)));
tester.actionMouseRelease();
// Check camera yaw angle changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(100 + 1 / planComponent.getScale(),
100 + 1 / planComponent.getScale(), 170,
2.5156f, (float)Math.PI / 16, home.getCamera());
// Change observer camera pitch by moving its pitch indicator
cameraPoints = observerCamera.getPoints();
int xPitchIndicator = (int)(((40 + (cameraPoints[1][0] + cameraPoints[2][0]) / 2)) * planComponent.getScale());
int yPitchIndicator = (int)(((40 + (cameraPoints[1][1] + cameraPoints[2][1]) / 2)) * planComponent.getScale());
tester.actionMousePress(planComponent, new ComponentLocation(
new Point(xPitchIndicator, yPitchIndicator)));
tester.actionMouseMove(planComponent, new ComponentLocation(
new Point(xPitchIndicator + 2, yPitchIndicator + 2)));
tester.actionMouseRelease();
// Check camera pitch angle changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(100 + 1 / planComponent.getScale(),
100 + 1 / planComponent.getScale(), 170,
2.5156f, 0.1639f, home.getCamera());
// 9. Change observer camera location with mouse in 3D view
tester.actionMousePress(component3D, new ComponentLocation(new Point(10, 10)));
tester.actionKeyPress(KeyEvent.VK_ALT);
tester.actionMouseMove(component3D, new ComponentLocation(new Point(10, 20)));
tester.actionKeyRelease(KeyEvent.VK_ALT);
tester.actionMouseRelease();
// Check camera location changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(108.657f, 111.4631f, 170,
2.5156f, 0.1639f, home.getCamera());
// 10. Change observer camera yaw with mouse in 3D view
tester.actionMousePress(component3D, new ComponentLocation(new Point(10, 20)));
tester.actionMouseMove(component3D, new ComponentLocation(new Point(20, 20)));
tester.actionMouseRelease();
// Check camera yaw changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(108.657f, 111.4631f, 170,
2.5656f, 0.1639f, home.getCamera());
// Change camera pitch with mouse in 3D view
tester.actionMousePress(component3D, new ComponentLocation(new Point(20, 20)));
tester.actionMouseMove(component3D, new ComponentLocation(new Point(20, 30)));
tester.actionMouseRelease();
// Check camera yaw changed
assertCoordinatesAndAnglesEqualCameraLocationAndAngles(108.657f, 111.4631f, 170,
2.5656f, 0.2139f, home.getCamera());
// 11. Edit 3D view modal dialog box
JDialog attributesDialog = showHome3DAttributesPanel(preferences, controller, frame, tester);
// Retrieve Home3DAttributesPanel components
Home3DAttributesPanel panel = (Home3DAttributesPanel)TestUtilities.findComponent(
attributesDialog, Home3DAttributesPanel.class);
Home3DAttributesController panelController =
(Home3DAttributesController)TestUtilities.getField(panel, "controller");
ColorButton groundColorButton =
(ColorButton)TestUtilities.getField(panel, "groundColorButton");
ColorButton skyColorButton =
(ColorButton)TestUtilities.getField(panel, "skyColorButton");
JSlider brightnessSlider =
(JSlider)TestUtilities.getField(panel, "brightnessSlider");
JSlider wallsTransparencySlider =
(JSlider)TestUtilities.getField(panel, "wallsTransparencySlider");
// Check edited values
int oldGroundColor = home.getEnvironment().getGroundColor();
TextureImage oldGroundTexture = home.getEnvironment().getGroundTexture();
int oldSkyColor = home.getEnvironment().getSkyColor();
int oldLightColor = home.getEnvironment().getLightColor();
float oldWallsAlpha = home.getEnvironment().getWallsAlpha();
assertEquals("Wrong ground color", oldGroundColor,
groundColorButton.getColor().intValue());
assertEquals("Wrong ground texture", oldGroundTexture,
panelController.getGroundTextureController().getTexture());
assertEquals("Wrong sky color", oldSkyColor,
skyColorButton.getColor().intValue());
assertEquals("Wrong brightness", oldLightColor & 0xFF,
brightnessSlider.getValue());
assertEquals("Wrong transparency", (int)(oldWallsAlpha * 255),
wallsTransparencySlider.getValue());
// 12. Change dialog box values
groundColorButton.setColor(0xFFFFFF);
skyColorButton.setColor(0x000000);
brightnessSlider.setValue(128);
wallsTransparencySlider.setValue(128);
// Click on Ok in dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check home attributes are modified accordingly
assert3DAttributesEqualHomeAttributes(0xFFFFFF, null,
0x000000, 0x808080, 1 / 255f * 128f, home);
// 13. Undo changes
runAction(controller, HomePane.ActionType.UNDO, tester);
// Check home attributes have previous values
assert3DAttributesEqualHomeAttributes(oldGroundColor, null,
oldSkyColor, oldLightColor, oldWallsAlpha, home);
// Redo
runAction(controller, HomePane.ActionType.REDO, tester);
// Check home attributes are modified accordingly
assert3DAttributesEqualHomeAttributes(0xFFFFFF, null,
0x000000, 0x808080, 1 / 255f * 128f, home);
// 14. Edit 3D view modal dialog box to change ground texture
attributesDialog = showHome3DAttributesPanel(preferences, controller, frame, tester);
panel = (Home3DAttributesPanel)TestUtilities.findComponent(
attributesDialog, Home3DAttributesPanel.class);
panelController = (Home3DAttributesController)TestUtilities.getField(panel, "controller");
JRadioButton groundColorRadioButton =
(JRadioButton)TestUtilities.getField(panel, "groundColorRadioButton");
final TextureChoiceComponent groundTextureButton =
(TextureChoiceComponent)panelController.getGroundTextureController().getView();
JRadioButton groundTextureRadioButton =
(JRadioButton)TestUtilities.getField(panel, "groundTextureRadioButton");
// Check color and texture radio buttons
assertTrue("Ground color radio button isn't checked",
groundColorRadioButton.isSelected());
assertFalse("Ground texture radio button is checked",
groundTextureRadioButton.isSelected());
// Click on ground texture button
tester.invokeLater(new Runnable() {
public void run() {
// Display texture dialog later in Event Dispatch Thread to avoid blocking test thread
groundTextureButton.doClick();
}
});
// Wait for 3D view to be shown
String groundTextureTitle = preferences.getLocalizedString(
Home3DAttributesController.class, "groundTextureTitle");
tester.waitForFrameShowing(new AWTHierarchy(), groundTextureTitle);
// Check texture dialog box is displayed
JDialog textureDialog = (JDialog)new BasicFinder().find(attributesDialog,
new WindowMatcher(groundTextureTitle));
assertTrue("Texture dialog not showing", textureDialog.isShowing());
JList availableTexturesList = (JList)new BasicFinder().find(textureDialog,
new ClassMatcher(JList.class, true));
availableTexturesList.setSelectedIndex(0);
CatalogTexture firstTexture = preferences.getTexturesCatalog().getCategories().get(0).getTexture(0);
assertEquals("Wrong first texture in list", firstTexture,
availableTexturesList.getSelectedValue());
// Click on OK in texture dialog box
doClickOnOkInDialog(textureDialog, tester);
// Check color and texture radio buttons
assertFalse("Ground color radio button is checked",
groundColorRadioButton.isSelected());
assertTrue("Ground texture radio button isn't checked",
groundTextureRadioButton.isSelected());
// Click on OK in 3D attributes dialog box
doClickOnOkInDialog(attributesDialog, tester);
// Check home attributes are modified accordingly
assert3DAttributesEqualHomeAttributes(0xFFFFFF, firstTexture,
0x000000, 0x808080, 1 / 255f * 128f, home);
// 15. Edit observer camera attributes
tester.actionClick(planComponent, new ComponentLocation(new Point(115, 115)), InputEvent.BUTTON1_MASK, 2);
String observerCameraTitle = preferences.getLocalizedString(
ObserverCameraPanel.class, "observerCamera.title");
tester.waitForFrameShowing(new AWTHierarchy(), observerCameraTitle);
// Check observer camera dialog box is displayed
JDialog observerCameraDialog = (JDialog)new BasicFinder().find(frame,
new WindowMatcher(observerCameraTitle));
assertTrue("Observer camera dialog not showing", observerCameraDialog.isShowing());
ObserverCameraPanel observerCameraPanel = (ObserverCameraPanel)TestUtilities.findComponent(
observerCameraDialog, ObserverCameraPanel.class);
JSpinner fieldOfViewSpinner =
(JSpinner)TestUtilities.getField(observerCameraPanel, "fieldOfViewSpinner");
JSpinner elevationSpinner =
(JSpinner)TestUtilities.getField(observerCameraPanel, "elevationSpinner");
assertEquals("Wrong field of view", (int)Math.round(Math.toDegrees(observerCamera.getFieldOfView())),
fieldOfViewSpinner.getValue());
assertEquals("Wrong elevation", (float)Math.round(observerCamera.getZ() * 100) / 100,
elevationSpinner.getValue());
fieldOfViewSpinner.setValue(90);
elevationSpinner.setValue(300f);
// Click on OK in observer camera dialog box
doClickOnOkInDialog(observerCameraDialog, tester);
assertEquals("Wrong field of view", (float)Math.toRadians(90), observerCamera.getFieldOfView());
assertEquals("Wrong elevation", 300f, observerCamera.getZ());
}
|
diff --git a/src/main/java/net/pterodactylus/sone/web/CreateSonePage.java b/src/main/java/net/pterodactylus/sone/web/CreateSonePage.java
index f9775560..dfd37609 100644
--- a/src/main/java/net/pterodactylus/sone/web/CreateSonePage.java
+++ b/src/main/java/net/pterodactylus/sone/web/CreateSonePage.java
@@ -1,101 +1,101 @@
/*
* FreenetSone - CreateSonePage.java - Copyright © 2010 David Roden
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.pterodactylus.sone.web;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.pterodactylus.sone.core.SoneException;
import net.pterodactylus.sone.core.SoneException.Type;
import net.pterodactylus.sone.data.Sone;
import net.pterodactylus.sone.web.page.Page.Request.Method;
import net.pterodactylus.util.logging.Logging;
import net.pterodactylus.util.template.Template;
import freenet.clients.http.ToadletContext;
/**
* The “create Sone” page lets the user create a new Sone.
*
* @author <a href="mailto:[email protected]">David ‘Bombe’ Roden</a>
*/
public class CreateSonePage extends SoneTemplatePage {
/** The logger. */
private static final Logger logger = Logging.getLogger(CreateSonePage.class);
/**
* Creates a new “create Sone” page.
*
* @param template
* The template to render
* @param webInterface
* The Sone web interface
*/
public CreateSonePage(Template template, WebInterface webInterface) {
super("createSone.html", template, "Page.CreateSone.Title", webInterface, false);
}
//
// TEMPLATEPAGE METHODS
//
/**
* {@inheritDoc}
*/
@Override
protected void processTemplate(Request request, Template template) throws RedirectException {
super.processTemplate(request, template);
String name = "";
String requestUri = null;
String insertUri = null;
if (request.getMethod() == Method.POST) {
name = request.getHttpRequest().getPartAsStringFailsafe("name", 100);
- if (request.getHttpRequest().getParam("create-from-uri").length() > 0) {
+ if (request.getHttpRequest().isPartSet("create-from-uri")) {
requestUri = request.getHttpRequest().getPartAsStringFailsafe("request-uri", 256);
insertUri = request.getHttpRequest().getPartAsStringFailsafe("insert-uri", 256);
}
try {
/* create Sone. */
Sone sone = webInterface.core().createSone(name, "Sone", requestUri, insertUri);
/* log in the new Sone. */
setCurrentSone(request.getToadletContext(), sone);
throw new RedirectException("index.html");
} catch (SoneException se1) {
logger.log(Level.FINE, "Could not create Sone “%s” at (“%s”, “%s”), %s!", new Object[] { name, requestUri, insertUri, se1.getType() });
if (se1.getType() == Type.INVALID_SONE_NAME) {
template.set("errorName", true);
} else if (se1.getType() == Type.INVALID_URI) {
template.set("errorUri", true);
}
}
}
template.set("name", name);
template.set("requestUri", requestUri);
template.set("insertUri", insertUri);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isEnabled(ToadletContext toadletContext) {
return getCurrentSone(toadletContext) == null;
}
}
| true | true | protected void processTemplate(Request request, Template template) throws RedirectException {
super.processTemplate(request, template);
String name = "";
String requestUri = null;
String insertUri = null;
if (request.getMethod() == Method.POST) {
name = request.getHttpRequest().getPartAsStringFailsafe("name", 100);
if (request.getHttpRequest().getParam("create-from-uri").length() > 0) {
requestUri = request.getHttpRequest().getPartAsStringFailsafe("request-uri", 256);
insertUri = request.getHttpRequest().getPartAsStringFailsafe("insert-uri", 256);
}
try {
/* create Sone. */
Sone sone = webInterface.core().createSone(name, "Sone", requestUri, insertUri);
/* log in the new Sone. */
setCurrentSone(request.getToadletContext(), sone);
throw new RedirectException("index.html");
} catch (SoneException se1) {
logger.log(Level.FINE, "Could not create Sone “%s” at (“%s”, “%s”), %s!", new Object[] { name, requestUri, insertUri, se1.getType() });
if (se1.getType() == Type.INVALID_SONE_NAME) {
template.set("errorName", true);
} else if (se1.getType() == Type.INVALID_URI) {
template.set("errorUri", true);
}
}
}
template.set("name", name);
template.set("requestUri", requestUri);
template.set("insertUri", insertUri);
}
| protected void processTemplate(Request request, Template template) throws RedirectException {
super.processTemplate(request, template);
String name = "";
String requestUri = null;
String insertUri = null;
if (request.getMethod() == Method.POST) {
name = request.getHttpRequest().getPartAsStringFailsafe("name", 100);
if (request.getHttpRequest().isPartSet("create-from-uri")) {
requestUri = request.getHttpRequest().getPartAsStringFailsafe("request-uri", 256);
insertUri = request.getHttpRequest().getPartAsStringFailsafe("insert-uri", 256);
}
try {
/* create Sone. */
Sone sone = webInterface.core().createSone(name, "Sone", requestUri, insertUri);
/* log in the new Sone. */
setCurrentSone(request.getToadletContext(), sone);
throw new RedirectException("index.html");
} catch (SoneException se1) {
logger.log(Level.FINE, "Could not create Sone “%s” at (“%s”, “%s”), %s!", new Object[] { name, requestUri, insertUri, se1.getType() });
if (se1.getType() == Type.INVALID_SONE_NAME) {
template.set("errorName", true);
} else if (se1.getType() == Type.INVALID_URI) {
template.set("errorUri", true);
}
}
}
template.set("name", name);
template.set("requestUri", requestUri);
template.set("insertUri", insertUri);
}
|
diff --git a/src/com/owncloud/android/operations/SynchronizeFileOperation.java b/src/com/owncloud/android/operations/SynchronizeFileOperation.java
index 6a79e751b..ec51392db 100644
--- a/src/com/owncloud/android/operations/SynchronizeFileOperation.java
+++ b/src/com/owncloud/android/operations/SynchronizeFileOperation.java
@@ -1,198 +1,198 @@
/* ownCloud Android client application
* Copyright (C) 2012 Bartek Przybylski
* Copyright (C) 2012-2013 ownCloud Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.owncloud.android.operations;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.files.services.FileDownloader;
import com.owncloud.android.files.services.FileUploader;
import com.owncloud.android.lib.network.OwnCloudClient;
import com.owncloud.android.lib.operations.common.RemoteOperation;
import com.owncloud.android.lib.operations.common.RemoteOperationResult;
import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode;
import com.owncloud.android.lib.operations.remote.ReadRemoteFileOperation;
import com.owncloud.android.utils.FileStorageUtils;
import com.owncloud.android.utils.Log_OC;
import android.accounts.Account;
import android.content.Context;
import android.content.Intent;
/**
* Remote operation performing the read of remote file in the ownCloud server.
*
* @author David A. Velasco
* @author masensio
*/
public class SynchronizeFileOperation extends RemoteOperation {
private String TAG = SynchronizeFileOperation.class.getSimpleName();
private OCFile mLocalFile;
private OCFile mServerFile;
private FileDataStorageManager mStorageManager;
private Account mAccount;
private boolean mSyncFileContents;
private Context mContext;
private boolean mTransferWasRequested = false;
public SynchronizeFileOperation(
OCFile localFile,
OCFile serverFile, // make this null to let the operation checks the server; added to reuse info from SynchronizeFolderOperation
FileDataStorageManager storageManager,
Account account,
boolean syncFileContents,
Context context) {
mLocalFile = localFile;
mServerFile = serverFile;
mStorageManager = storageManager;
mAccount = account;
mSyncFileContents = syncFileContents;
mContext = context;
}
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result = null;
mTransferWasRequested = false;
if (!mLocalFile.isDown()) {
/// easy decision
requestForDownload(mLocalFile);
result = new RemoteOperationResult(ResultCode.OK);
} else {
/// local copy in the device -> need to think a bit more before do anything
if (mServerFile == null) {
String remotePath = mLocalFile.getRemotePath();
ReadRemoteFileOperation operation = new ReadRemoteFileOperation(remotePath);
result = operation.execute(client);
if (result.isSuccess()){
mServerFile = FileStorageUtils.fillOCFile(result.getData().get(0));
mServerFile.setLastSyncDateForProperties(System.currentTimeMillis());
}
}
- if (result.isSuccess()) {
+ if (mServerFile != null) {
/// check changes in server and local file
boolean serverChanged = false;
/* time for eTag is coming, but not yet
if (mServerFile.getEtag() != null) {
serverChanged = (!mServerFile.getEtag().equals(mLocalFile.getEtag())); // TODO could this be dangerous when the user upgrades the server from non-tagged to tagged?
} else { */
// server without etags
serverChanged = (mServerFile.getModificationTimestamp() != mLocalFile.getModificationTimestampAtLastSyncForData());
//}
boolean localChanged = (mLocalFile.getLocalModificationTimestamp() > mLocalFile.getLastSyncDateForData());
// TODO this will be always true after the app is upgraded to database version 2; will result in unnecessary uploads
/// decide action to perform depending upon changes
//if (!mLocalFile.getEtag().isEmpty() && localChanged && serverChanged) {
if (localChanged && serverChanged) {
result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
} else if (localChanged) {
if (mSyncFileContents) {
requestForUpload(mLocalFile);
// the local update of file properties will be done by the FileUploader service when the upload finishes
} else {
// NOTHING TO DO HERE: updating the properties of the file in the server without uploading the contents would be stupid;
// So, an instance of SynchronizeFileOperation created with syncFileContents == false is completely useless when we suspect
// that an upload is necessary (for instance, in FileObserverService).
}
result = new RemoteOperationResult(ResultCode.OK);
} else if (serverChanged) {
if (mSyncFileContents) {
requestForDownload(mLocalFile); // local, not server; we won't to keep the value of keepInSync!
// the update of local data will be done later by the FileUploader service when the upload finishes
} else {
// TODO CHECK: is this really useful in some point in the code?
mServerFile.setKeepInSync(mLocalFile.keepInSync());
mServerFile.setLastSyncDateForData(mLocalFile.getLastSyncDateForData());
mServerFile.setStoragePath(mLocalFile.getStoragePath());
mServerFile.setParentId(mLocalFile.getParentId());
mStorageManager.saveFile(mServerFile);
}
result = new RemoteOperationResult(ResultCode.OK);
} else {
// nothing changed, nothing to do
result = new RemoteOperationResult(ResultCode.OK);
}
}
}
Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", file " + mLocalFile.getRemotePath() + ": " + result.getLogMessage());
return result;
}
/**
* Requests for an upload to the FileUploader service
*
* @param file OCFile object representing the file to upload
*/
private void requestForUpload(OCFile file) {
Intent i = new Intent(mContext, FileUploader.class);
i.putExtra(FileUploader.KEY_ACCOUNT, mAccount);
i.putExtra(FileUploader.KEY_FILE, file);
/*i.putExtra(FileUploader.KEY_REMOTE_FILE, mRemotePath); // doing this we would lose the value of keepInSync in the road, and maybe it's not updated in the database when the FileUploader service gets it!
i.putExtra(FileUploader.KEY_LOCAL_FILE, localFile.getStoragePath());*/
i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
i.putExtra(FileUploader.KEY_FORCE_OVERWRITE, true);
mContext.startService(i);
mTransferWasRequested = true;
}
/**
* Requests for a download to the FileDownloader service
*
* @param file OCFile object representing the file to download
*/
private void requestForDownload(OCFile file) {
Intent i = new Intent(mContext, FileDownloader.class);
i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
i.putExtra(FileDownloader.EXTRA_FILE, file);
mContext.startService(i);
mTransferWasRequested = true;
}
public boolean transferWasRequested() {
return mTransferWasRequested;
}
public OCFile getLocalFile() {
return mLocalFile;
}
}
| true | true | protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result = null;
mTransferWasRequested = false;
if (!mLocalFile.isDown()) {
/// easy decision
requestForDownload(mLocalFile);
result = new RemoteOperationResult(ResultCode.OK);
} else {
/// local copy in the device -> need to think a bit more before do anything
if (mServerFile == null) {
String remotePath = mLocalFile.getRemotePath();
ReadRemoteFileOperation operation = new ReadRemoteFileOperation(remotePath);
result = operation.execute(client);
if (result.isSuccess()){
mServerFile = FileStorageUtils.fillOCFile(result.getData().get(0));
mServerFile.setLastSyncDateForProperties(System.currentTimeMillis());
}
}
if (result.isSuccess()) {
/// check changes in server and local file
boolean serverChanged = false;
/* time for eTag is coming, but not yet
if (mServerFile.getEtag() != null) {
serverChanged = (!mServerFile.getEtag().equals(mLocalFile.getEtag())); // TODO could this be dangerous when the user upgrades the server from non-tagged to tagged?
} else { */
// server without etags
serverChanged = (mServerFile.getModificationTimestamp() != mLocalFile.getModificationTimestampAtLastSyncForData());
//}
boolean localChanged = (mLocalFile.getLocalModificationTimestamp() > mLocalFile.getLastSyncDateForData());
// TODO this will be always true after the app is upgraded to database version 2; will result in unnecessary uploads
/// decide action to perform depending upon changes
//if (!mLocalFile.getEtag().isEmpty() && localChanged && serverChanged) {
if (localChanged && serverChanged) {
result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
} else if (localChanged) {
if (mSyncFileContents) {
requestForUpload(mLocalFile);
// the local update of file properties will be done by the FileUploader service when the upload finishes
} else {
// NOTHING TO DO HERE: updating the properties of the file in the server without uploading the contents would be stupid;
// So, an instance of SynchronizeFileOperation created with syncFileContents == false is completely useless when we suspect
// that an upload is necessary (for instance, in FileObserverService).
}
result = new RemoteOperationResult(ResultCode.OK);
} else if (serverChanged) {
if (mSyncFileContents) {
requestForDownload(mLocalFile); // local, not server; we won't to keep the value of keepInSync!
// the update of local data will be done later by the FileUploader service when the upload finishes
} else {
// TODO CHECK: is this really useful in some point in the code?
mServerFile.setKeepInSync(mLocalFile.keepInSync());
mServerFile.setLastSyncDateForData(mLocalFile.getLastSyncDateForData());
mServerFile.setStoragePath(mLocalFile.getStoragePath());
mServerFile.setParentId(mLocalFile.getParentId());
mStorageManager.saveFile(mServerFile);
}
result = new RemoteOperationResult(ResultCode.OK);
} else {
// nothing changed, nothing to do
result = new RemoteOperationResult(ResultCode.OK);
}
}
}
Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", file " + mLocalFile.getRemotePath() + ": " + result.getLogMessage());
return result;
}
/**
* Requests for an upload to the FileUploader service
*
* @param file OCFile object representing the file to upload
*/
private void requestForUpload(OCFile file) {
Intent i = new Intent(mContext, FileUploader.class);
i.putExtra(FileUploader.KEY_ACCOUNT, mAccount);
i.putExtra(FileUploader.KEY_FILE, file);
/*i.putExtra(FileUploader.KEY_REMOTE_FILE, mRemotePath); // doing this we would lose the value of keepInSync in the road, and maybe it's not updated in the database when the FileUploader service gets it!
i.putExtra(FileUploader.KEY_LOCAL_FILE, localFile.getStoragePath());*/
i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
i.putExtra(FileUploader.KEY_FORCE_OVERWRITE, true);
mContext.startService(i);
mTransferWasRequested = true;
}
/**
* Requests for a download to the FileDownloader service
*
* @param file OCFile object representing the file to download
*/
private void requestForDownload(OCFile file) {
Intent i = new Intent(mContext, FileDownloader.class);
i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
i.putExtra(FileDownloader.EXTRA_FILE, file);
mContext.startService(i);
mTransferWasRequested = true;
}
public boolean transferWasRequested() {
return mTransferWasRequested;
}
public OCFile getLocalFile() {
return mLocalFile;
}
}
| protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result = null;
mTransferWasRequested = false;
if (!mLocalFile.isDown()) {
/// easy decision
requestForDownload(mLocalFile);
result = new RemoteOperationResult(ResultCode.OK);
} else {
/// local copy in the device -> need to think a bit more before do anything
if (mServerFile == null) {
String remotePath = mLocalFile.getRemotePath();
ReadRemoteFileOperation operation = new ReadRemoteFileOperation(remotePath);
result = operation.execute(client);
if (result.isSuccess()){
mServerFile = FileStorageUtils.fillOCFile(result.getData().get(0));
mServerFile.setLastSyncDateForProperties(System.currentTimeMillis());
}
}
if (mServerFile != null) {
/// check changes in server and local file
boolean serverChanged = false;
/* time for eTag is coming, but not yet
if (mServerFile.getEtag() != null) {
serverChanged = (!mServerFile.getEtag().equals(mLocalFile.getEtag())); // TODO could this be dangerous when the user upgrades the server from non-tagged to tagged?
} else { */
// server without etags
serverChanged = (mServerFile.getModificationTimestamp() != mLocalFile.getModificationTimestampAtLastSyncForData());
//}
boolean localChanged = (mLocalFile.getLocalModificationTimestamp() > mLocalFile.getLastSyncDateForData());
// TODO this will be always true after the app is upgraded to database version 2; will result in unnecessary uploads
/// decide action to perform depending upon changes
//if (!mLocalFile.getEtag().isEmpty() && localChanged && serverChanged) {
if (localChanged && serverChanged) {
result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
} else if (localChanged) {
if (mSyncFileContents) {
requestForUpload(mLocalFile);
// the local update of file properties will be done by the FileUploader service when the upload finishes
} else {
// NOTHING TO DO HERE: updating the properties of the file in the server without uploading the contents would be stupid;
// So, an instance of SynchronizeFileOperation created with syncFileContents == false is completely useless when we suspect
// that an upload is necessary (for instance, in FileObserverService).
}
result = new RemoteOperationResult(ResultCode.OK);
} else if (serverChanged) {
if (mSyncFileContents) {
requestForDownload(mLocalFile); // local, not server; we won't to keep the value of keepInSync!
// the update of local data will be done later by the FileUploader service when the upload finishes
} else {
// TODO CHECK: is this really useful in some point in the code?
mServerFile.setKeepInSync(mLocalFile.keepInSync());
mServerFile.setLastSyncDateForData(mLocalFile.getLastSyncDateForData());
mServerFile.setStoragePath(mLocalFile.getStoragePath());
mServerFile.setParentId(mLocalFile.getParentId());
mStorageManager.saveFile(mServerFile);
}
result = new RemoteOperationResult(ResultCode.OK);
} else {
// nothing changed, nothing to do
result = new RemoteOperationResult(ResultCode.OK);
}
}
}
Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", file " + mLocalFile.getRemotePath() + ": " + result.getLogMessage());
return result;
}
/**
* Requests for an upload to the FileUploader service
*
* @param file OCFile object representing the file to upload
*/
private void requestForUpload(OCFile file) {
Intent i = new Intent(mContext, FileUploader.class);
i.putExtra(FileUploader.KEY_ACCOUNT, mAccount);
i.putExtra(FileUploader.KEY_FILE, file);
/*i.putExtra(FileUploader.KEY_REMOTE_FILE, mRemotePath); // doing this we would lose the value of keepInSync in the road, and maybe it's not updated in the database when the FileUploader service gets it!
i.putExtra(FileUploader.KEY_LOCAL_FILE, localFile.getStoragePath());*/
i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
i.putExtra(FileUploader.KEY_FORCE_OVERWRITE, true);
mContext.startService(i);
mTransferWasRequested = true;
}
/**
* Requests for a download to the FileDownloader service
*
* @param file OCFile object representing the file to download
*/
private void requestForDownload(OCFile file) {
Intent i = new Intent(mContext, FileDownloader.class);
i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
i.putExtra(FileDownloader.EXTRA_FILE, file);
mContext.startService(i);
mTransferWasRequested = true;
}
public boolean transferWasRequested() {
return mTransferWasRequested;
}
public OCFile getLocalFile() {
return mLocalFile;
}
}
|
diff --git a/modules/weblounge-taglib/src/main/java/ch/entwine/weblounge/taglib/resource/ResourceIteratorTag.java b/modules/weblounge-taglib/src/main/java/ch/entwine/weblounge/taglib/resource/ResourceIteratorTag.java
index e30bd9bca..497a2ae70 100644
--- a/modules/weblounge-taglib/src/main/java/ch/entwine/weblounge/taglib/resource/ResourceIteratorTag.java
+++ b/modules/weblounge-taglib/src/main/java/ch/entwine/weblounge/taglib/resource/ResourceIteratorTag.java
@@ -1,361 +1,361 @@
/*
* Weblounge: Web Content Management System
* Copyright (c) 2003 - 2011 The Weblounge Team
* http://entwinemedia.com/weblounge
*
* 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
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ch.entwine.weblounge.taglib.resource;
import ch.entwine.weblounge.common.content.Resource;
import ch.entwine.weblounge.common.content.ResourceContent;
import ch.entwine.weblounge.common.content.ResourceSearchResultItem;
import ch.entwine.weblounge.common.content.ResourceURI;
import ch.entwine.weblounge.common.content.SearchQuery;
import ch.entwine.weblounge.common.content.SearchQuery.Order;
import ch.entwine.weblounge.common.content.SearchResult;
import ch.entwine.weblounge.common.impl.content.SearchQueryImpl;
import ch.entwine.weblounge.common.impl.util.WebloungeDateFormat;
import ch.entwine.weblounge.common.repository.ContentRepository;
import ch.entwine.weblounge.common.repository.ContentRepositoryException;
import ch.entwine.weblounge.common.request.CacheTag;
import ch.entwine.weblounge.common.site.Site;
import ch.entwine.weblounge.taglib.WebloungeTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.jsp.JspException;
public class ResourceIteratorTag extends WebloungeTag {
/** Serial version UID */
private static final long serialVersionUID = 3626449066999007138L;
/** Logging facility */
private static final Logger logger = LoggerFactory.getLogger(ResourceIteratorTag.class);
/** The subjects */
private List<String> resourceSubjects = null;
/** The series */
private List<String> resourceSeries = null;
/** The types to include */
private List<String> includeTypes = null;
/** The types to exclude */
private List<String> excludeTypes = null;
/** The resource id */
private List<String> resourceId = null;
/** The minimum creation start date */
private Date creatorStartDate = null;
/** The iteration index */
protected int index = 0;
/** The number of iterations */
protected long iterations = -1;
/** The search result */
private SearchResult searchResult = null;
/** The content repository */
private ContentRepository repository = null;
/** The result order */
private Order order = null;
/**
* Sets the subjects for the search.
*
* @param subjects
* the subjects to search
*/
public void setSubjects(String subjects) {
if (resourceSubjects == null)
resourceSubjects = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(subjects, ",;");
while (st.hasMoreTokens()) {
resourceSubjects.add(st.nextToken());
}
}
/**
* Sets the resource identifier for the search.
*
* @param id
* the resource identifier to search
*/
public void setUuid(String id) {
if (resourceId == null)
resourceId = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(id, ",;");
while (st.hasMoreTokens()) {
resourceId.add(st.nextToken());
}
}
/**
* Sets the series for the search.
*
* @param series
* the series to search
*/
public void setSeries(String series) {
if (resourceSeries == null)
resourceSeries = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(series, ",;");
while (st.hasMoreTokens()) {
resourceSeries.add(st.nextToken());
}
}
/**
* Sets the types to search for.
*
* @param types
* the types
*/
public void setIncludetypes(String types) {
if (includeTypes == null)
includeTypes = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(types, ",;");
while (st.hasMoreTokens()) {
includeTypes.add(st.nextToken());
}
}
/**
* Sets the types to exclude in the serach.
*
* @param types
* the types to exlude
*/
public void setExcludetypes(String types) {
if (excludeTypes == null)
excludeTypes = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(types, ",;");
while (st.hasMoreTokens()) {
excludeTypes.add(st.nextToken());
}
}
/**
* Set the minimum creation date to search from
*
* @param startDate
* the creator date
*/
public void setStartdate(String startDate) {
try {
creatorStartDate = WebloungeDateFormat.parseStatic(startDate);
} catch (ParseException e) {
logger.debug("Unable to parse date '{}'", startDate);
}
}
/**
* Set the sort order for the search
*
* @param order
* the sort order
*/
public void setOrder(String order) {
try {
this.order = Order.valueOf(order);
} catch (Exception e) {
logger.debug("Unable to parse order '{}'", order);
}
}
/**
* {@inheritDoc}
*
* @see javax.servlet.jsp.tagext.BodyTagSupport#doStartTag()
*/
@Override
public int doStartTag() throws JspException {
Site site = request.getSite();
repository = site.getContentRepository();
if (repository == null) {
logger.debug("Unable to load content repository for site '{}'", site);
response.invalidate();
return SKIP_BODY;
}
// First time search resources
if (searchResult == null) {
SearchQuery q = new SearchQueryImpl(site);
if (includeTypes != null)
q.withTypes(includeTypes.toArray(new String[includeTypes.size()]));
if (excludeTypes != null)
q.withoutTypes(excludeTypes.toArray(new String[excludeTypes.size()]));
if (order != null)
q.sortByCreationDate(order);
if (resourceId != null) {
for (String id : resourceId)
q.withIdentifier(id);
} else {
if (resourceSubjects != null) {
for (String subject : resourceSubjects) {
q.withSubject(subject);
}
}
if (resourceSeries != null) {
for (String series : resourceSeries) {
q.withSeries(series);
}
}
if (creatorStartDate != null)
q.withCreationDateBetween(creatorStartDate);
}
try {
searchResult = repository.find(q);
} catch (ContentRepositoryException e) {
logger.error("Error searching for resources with given subjects.");
return SKIP_BODY;
}
index = 0;
- iterations = searchResult.getHitCount();
+ iterations = searchResult.getDocumentCount();
}
if (iterations < 1)
return SKIP_BODY;
stashAndSetAttribute(ResourceIteratorTagExtraInfo.INDEX, index);
stashAndSetAttribute(ResourceIteratorTagExtraInfo.ITERATIONS, iterations);
ResourceSearchResultItem searchResultItem = (ResourceSearchResultItem) searchResult.getItems()[index];
return setResource(searchResultItem, EVAL_BODY_INCLUDE);
}
/**
* Get the search result item from the repository and set it to the page
* context.
*
* @param searchResultItem
* the search result item
* @param resultCode
* the success code
* @return the <code>resultCode</code> if success else <code>SKIP_BODY</code>
*/
private int setResource(ResourceSearchResultItem searchResultItem,
int resultCode) {
ResourceURI uri = searchResultItem.getResourceURI();
// Try to load the resource from the content repository
try {
if (!repository.exists(uri)) {
logger.warn("Non existing resource {} requested on {}", uri, request.getUrl());
return SKIP_BODY;
}
} catch (ContentRepositoryException e) {
logger.error("Error trying to look up resource {} from {}", searchResultItem.getId(), repository);
return SKIP_BODY;
}
Resource<?> resource = null;
ResourceContent resourceContent = null;
try {
resource = repository.get(uri);
resource.switchTo(request.getLanguage());
resourceContent = resource.getContent(request.getLanguage());
if (resourceContent == null)
resourceContent = resource.getOriginalContent();
} catch (ContentRepositoryException e) {
logger.warn("Error trying to load resource " + uri + ": " + e.getMessage(), e);
return SKIP_BODY;
}
// TODO: Check the permissions
// Store the resource and the resource content in the request
stashAndSetAttribute(ResourceIteratorTagExtraInfo.RESOURCE, resource);
stashAndSetAttribute(ResourceIteratorTagExtraInfo.RESOURCE_CONTENT, resourceContent);
// Add cache tags to the response
response.addTag(CacheTag.Resource, resource.getURI().getIdentifier());
response.addTag(CacheTag.Url, resource.getURI().getPath());
return resultCode;
}
/**
* {@inheritDoc}
*
* @see javax.servlet.jsp.tagext.BodyTagSupport#doAfterBody()
*/
@Override
public int doAfterBody() throws JspException {
index++;
if (index >= iterations)
return SKIP_BODY;
pageContext.setAttribute(ResourceIteratorTagExtraInfo.INDEX, index);
ResourceSearchResultItem searchResultItem = (ResourceSearchResultItem) searchResult.getItems()[index];
return setResource(searchResultItem, EVAL_BODY_AGAIN);
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.taglib.WebloungeTag#doEndTag()
*/
@Override
public int doEndTag() throws JspException {
removeAndUnstashAttributes();
return super.doEndTag();
}
/**
* {@inheritDoc}
*
* @see ch.entwine.weblounge.taglib.WebloungeTag#reset()
*/
@Override
protected void reset() {
super.reset();
index = 0;
iterations = -1;
searchResult = null;
resourceSubjects = null;
repository = null;
creatorStartDate = null;
resourceId = null;
order = null;
resourceSeries = null;
excludeTypes = null;
includeTypes = null;
}
}
| true | true | public int doStartTag() throws JspException {
Site site = request.getSite();
repository = site.getContentRepository();
if (repository == null) {
logger.debug("Unable to load content repository for site '{}'", site);
response.invalidate();
return SKIP_BODY;
}
// First time search resources
if (searchResult == null) {
SearchQuery q = new SearchQueryImpl(site);
if (includeTypes != null)
q.withTypes(includeTypes.toArray(new String[includeTypes.size()]));
if (excludeTypes != null)
q.withoutTypes(excludeTypes.toArray(new String[excludeTypes.size()]));
if (order != null)
q.sortByCreationDate(order);
if (resourceId != null) {
for (String id : resourceId)
q.withIdentifier(id);
} else {
if (resourceSubjects != null) {
for (String subject : resourceSubjects) {
q.withSubject(subject);
}
}
if (resourceSeries != null) {
for (String series : resourceSeries) {
q.withSeries(series);
}
}
if (creatorStartDate != null)
q.withCreationDateBetween(creatorStartDate);
}
try {
searchResult = repository.find(q);
} catch (ContentRepositoryException e) {
logger.error("Error searching for resources with given subjects.");
return SKIP_BODY;
}
index = 0;
iterations = searchResult.getHitCount();
}
if (iterations < 1)
return SKIP_BODY;
stashAndSetAttribute(ResourceIteratorTagExtraInfo.INDEX, index);
stashAndSetAttribute(ResourceIteratorTagExtraInfo.ITERATIONS, iterations);
ResourceSearchResultItem searchResultItem = (ResourceSearchResultItem) searchResult.getItems()[index];
return setResource(searchResultItem, EVAL_BODY_INCLUDE);
}
| public int doStartTag() throws JspException {
Site site = request.getSite();
repository = site.getContentRepository();
if (repository == null) {
logger.debug("Unable to load content repository for site '{}'", site);
response.invalidate();
return SKIP_BODY;
}
// First time search resources
if (searchResult == null) {
SearchQuery q = new SearchQueryImpl(site);
if (includeTypes != null)
q.withTypes(includeTypes.toArray(new String[includeTypes.size()]));
if (excludeTypes != null)
q.withoutTypes(excludeTypes.toArray(new String[excludeTypes.size()]));
if (order != null)
q.sortByCreationDate(order);
if (resourceId != null) {
for (String id : resourceId)
q.withIdentifier(id);
} else {
if (resourceSubjects != null) {
for (String subject : resourceSubjects) {
q.withSubject(subject);
}
}
if (resourceSeries != null) {
for (String series : resourceSeries) {
q.withSeries(series);
}
}
if (creatorStartDate != null)
q.withCreationDateBetween(creatorStartDate);
}
try {
searchResult = repository.find(q);
} catch (ContentRepositoryException e) {
logger.error("Error searching for resources with given subjects.");
return SKIP_BODY;
}
index = 0;
iterations = searchResult.getDocumentCount();
}
if (iterations < 1)
return SKIP_BODY;
stashAndSetAttribute(ResourceIteratorTagExtraInfo.INDEX, index);
stashAndSetAttribute(ResourceIteratorTagExtraInfo.ITERATIONS, iterations);
ResourceSearchResultItem searchResultItem = (ResourceSearchResultItem) searchResult.getItems()[index];
return setResource(searchResultItem, EVAL_BODY_INCLUDE);
}
|
diff --git a/modules/cpr/src/test/java/org/atmosphere/cpr/BroadcasterTest.java b/modules/cpr/src/test/java/org/atmosphere/cpr/BroadcasterTest.java
index 9be2e5986..d96704669 100644
--- a/modules/cpr/src/test/java/org/atmosphere/cpr/BroadcasterTest.java
+++ b/modules/cpr/src/test/java/org/atmosphere/cpr/BroadcasterTest.java
@@ -1,222 +1,222 @@
/*
* Copyright 2012 Jean-Francois Arcand
*
* 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.atmosphere.cpr;
import org.atmosphere.container.BlockingIOCometSupport;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import static org.mockito.Mockito.mock;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class BroadcasterTest {
private AtmosphereResource ar;
private Broadcaster broadcaster;
private AR atmosphereHandler;
@BeforeMethod
public void setUp() throws Exception {
AtmosphereConfig config = new AtmosphereFramework().getAtmosphereConfig();
DefaultBroadcasterFactory factory = new DefaultBroadcasterFactory(DefaultBroadcaster.class, "NEVER", config);
broadcaster = factory.get(DefaultBroadcaster.class, "test");
atmosphereHandler = new AR();
ar = new AtmosphereResourceImpl(config,
broadcaster,
mock(AtmosphereRequest.class),
AtmosphereResponse.create(),
mock(BlockingIOCometSupport.class),
atmosphereHandler);
broadcaster.addAtmosphereResource(ar);
}
@AfterMethod
public void unSetUp() throws Exception {
broadcaster.removeAtmosphereResource(ar);
atmosphereHandler.value.set(new HashSet());
}
@Test
public void testDirectBroadcastMethod() throws ExecutionException, InterruptedException, ServletException {
broadcaster.broadcast("foo", ar).get();
assertEquals(atmosphereHandler.value.get().toArray()[0], ar);
}
@Test
public void testEmptyBroadcastMethod() throws ExecutionException, InterruptedException, ServletException {
broadcaster.resumeAll();
broadcaster.broadcast("foo").get();
assertEquals(atmosphereHandler.value.get(), new HashSet());
}
@Test
public void testSetBroadcastMethod() throws ExecutionException, InterruptedException, ServletException {
AtmosphereConfig config = new AtmosphereFramework()
.setAsyncSupport(mock(BlockingIOCometSupport.class))
.init(new ServletConfig() {
@Override
public String getServletName() {
return "void";
}
@Override
public ServletContext getServletContext() {
return mock(ServletContext.class);
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Enumeration<String> getInitParameterNames() {
return null;
}
})
.getAtmosphereConfig();
DefaultBroadcasterFactory factory = new DefaultBroadcasterFactory(DefaultBroadcaster.class, "NEVER", config);
broadcaster = factory.get(DefaultBroadcaster.class, "test");
atmosphereHandler = new AR();
ar = new AtmosphereResourceImpl(config,
broadcaster,
mock(AtmosphereRequest.class),
AtmosphereResponse.create(),
mock(BlockingIOCometSupport.class),
atmosphereHandler);
AtmosphereResource ar2 = new AtmosphereResourceImpl(config,
broadcaster,
mock(AtmosphereRequest.class),
AtmosphereResponse.create(),
mock(BlockingIOCometSupport.class),
atmosphereHandler);
AtmosphereResource ar3 = new AtmosphereResourceImpl(config,
broadcaster,
mock(AtmosphereRequest.class),
AtmosphereResponse.create(),
mock(BlockingIOCometSupport.class),
atmosphereHandler);
broadcaster.addAtmosphereResource(ar).addAtmosphereResource(ar2).addAtmosphereResource(ar3);
Set<AtmosphereResource> set = new HashSet<AtmosphereResource>();
set.add(ar);
set.add(ar2);
broadcaster.broadcast("foo", set).get();
- assertEquals(atmosphereHandler.value.get(), new HashSet());
+ assertEquals(atmosphereHandler.value.get(), set);
}
public final static class AR implements AtmosphereHandler {
public AtomicReference<Set> value = new AtomicReference<Set>(new HashSet());
@Override
public void onRequest(AtmosphereResource e) throws IOException {
}
@Override
public void onStateChange(AtmosphereResourceEvent e) throws IOException {
value.get().add(e.getResource());
}
@Override
public void destroy() {
}
}
@Test
public void testBroadcasterListenerOnPostCreate() {
final AtomicReference<Boolean> create = new AtomicReference<Boolean>();
BroadcasterListener l = new BroadcasterListener() {
@Override
public void onPostCreate(Broadcaster b) {
create.set(Boolean.TRUE);
}
@Override
public void onComplete(Broadcaster b) {
}
@Override
public void onPreDestroy(Broadcaster b) {
}
};
BroadcasterFactory.getDefault().addBroadcasterListener(l).get("/a1");
assertTrue(create.get());
}
@Test
public void testBroadcasterListenerOnPreDestroy() {
final AtomicReference<Boolean> deleted = new AtomicReference<Boolean>();
BroadcasterListener l = new BroadcasterListener() {
@Override
public void onPostCreate(Broadcaster b) {
}
@Override
public void onComplete(Broadcaster b) {
}
@Override
public void onPreDestroy(Broadcaster b) {
deleted.set(Boolean.TRUE);
}
};
BroadcasterFactory.getDefault().addBroadcasterListener(l).get("/b1").destroy();
assertTrue(deleted.get());
}
@Test
public void testBroadcasterOnComplete() throws ExecutionException, InterruptedException {
final AtomicReference<Boolean> complete = new AtomicReference<Boolean>(false);
BroadcasterListener l = new BroadcasterListener() {
@Override
public void onPostCreate(Broadcaster b) {
}
@Override
public void onComplete(Broadcaster b) {
complete.set(Boolean.TRUE);
}
@Override
public void onPreDestroy(Broadcaster b) {
}
};
BroadcasterFactory.getDefault().addBroadcasterListener(l).get("/c1").broadcast("").get();
assertTrue(complete.get());
}
}
| true | true | public void testSetBroadcastMethod() throws ExecutionException, InterruptedException, ServletException {
AtmosphereConfig config = new AtmosphereFramework()
.setAsyncSupport(mock(BlockingIOCometSupport.class))
.init(new ServletConfig() {
@Override
public String getServletName() {
return "void";
}
@Override
public ServletContext getServletContext() {
return mock(ServletContext.class);
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Enumeration<String> getInitParameterNames() {
return null;
}
})
.getAtmosphereConfig();
DefaultBroadcasterFactory factory = new DefaultBroadcasterFactory(DefaultBroadcaster.class, "NEVER", config);
broadcaster = factory.get(DefaultBroadcaster.class, "test");
atmosphereHandler = new AR();
ar = new AtmosphereResourceImpl(config,
broadcaster,
mock(AtmosphereRequest.class),
AtmosphereResponse.create(),
mock(BlockingIOCometSupport.class),
atmosphereHandler);
AtmosphereResource ar2 = new AtmosphereResourceImpl(config,
broadcaster,
mock(AtmosphereRequest.class),
AtmosphereResponse.create(),
mock(BlockingIOCometSupport.class),
atmosphereHandler);
AtmosphereResource ar3 = new AtmosphereResourceImpl(config,
broadcaster,
mock(AtmosphereRequest.class),
AtmosphereResponse.create(),
mock(BlockingIOCometSupport.class),
atmosphereHandler);
broadcaster.addAtmosphereResource(ar).addAtmosphereResource(ar2).addAtmosphereResource(ar3);
Set<AtmosphereResource> set = new HashSet<AtmosphereResource>();
set.add(ar);
set.add(ar2);
broadcaster.broadcast("foo", set).get();
assertEquals(atmosphereHandler.value.get(), new HashSet());
}
| public void testSetBroadcastMethod() throws ExecutionException, InterruptedException, ServletException {
AtmosphereConfig config = new AtmosphereFramework()
.setAsyncSupport(mock(BlockingIOCometSupport.class))
.init(new ServletConfig() {
@Override
public String getServletName() {
return "void";
}
@Override
public ServletContext getServletContext() {
return mock(ServletContext.class);
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Enumeration<String> getInitParameterNames() {
return null;
}
})
.getAtmosphereConfig();
DefaultBroadcasterFactory factory = new DefaultBroadcasterFactory(DefaultBroadcaster.class, "NEVER", config);
broadcaster = factory.get(DefaultBroadcaster.class, "test");
atmosphereHandler = new AR();
ar = new AtmosphereResourceImpl(config,
broadcaster,
mock(AtmosphereRequest.class),
AtmosphereResponse.create(),
mock(BlockingIOCometSupport.class),
atmosphereHandler);
AtmosphereResource ar2 = new AtmosphereResourceImpl(config,
broadcaster,
mock(AtmosphereRequest.class),
AtmosphereResponse.create(),
mock(BlockingIOCometSupport.class),
atmosphereHandler);
AtmosphereResource ar3 = new AtmosphereResourceImpl(config,
broadcaster,
mock(AtmosphereRequest.class),
AtmosphereResponse.create(),
mock(BlockingIOCometSupport.class),
atmosphereHandler);
broadcaster.addAtmosphereResource(ar).addAtmosphereResource(ar2).addAtmosphereResource(ar3);
Set<AtmosphereResource> set = new HashSet<AtmosphereResource>();
set.add(ar);
set.add(ar2);
broadcaster.broadcast("foo", set).get();
assertEquals(atmosphereHandler.value.get(), set);
}
|
diff --git a/src/LocationMapper/SQLConnection.java b/src/LocationMapper/SQLConnection.java
index efd806a..bc4e4c0 100755
--- a/src/LocationMapper/SQLConnection.java
+++ b/src/LocationMapper/SQLConnection.java
@@ -1,236 +1,236 @@
package LocationMapper;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import LocationMapper.LocationMapper;
import LocationMapper.Log;
import LocationMapper.Record;
public class SQLConnection
{
public final int timeout = 5;
public final int batchCount = 5000;
public final int fetchSize = 20000;
public int parseCount = 0;
Connection connection = null;
ResultSet results = null;
public final String statement = "" +
"SELECT id, interaction_geo_latitude, interaction_geo_longitude, twitter_user_location, twitter_user_lang " +
"FROM datasift_results " +
"WHERE id > 33900000 " +
//"WHERE country is null " +
"AND (twitter_user_location is not null or interaction_geo_latitude is not null)";
// final String statement = "" +
// "SELECT id, interaction_geo_latitude, interaction_geo_longitude, twitter_user_location, twitter_user_lang " + //"WHERE id > 33980000 " + // AND id < 33100000 " + //" + // id > 25800000 " + //
// "from datasift_results " +
// "WHERE interaction_created_at > '2013-04-01 00:00:00' " +
// "AND datasift_stream_id in (78, 88) " +
// "AND (twitter_user_location is not null or interaction_geo_latitude is not null)";
public String address = null;
public String tableName = null;
public String port = null;
public String userName = null;
public String password = null;
ArrayList<String> sendStrings = new ArrayList<String>();
public SQLConnection(String address, String tableName, String port, String userName, String password)
{
this.address = address;
this.tableName = tableName;
this.port = port;
this.userName = userName;
this.password = password;
}
public boolean updateRecord(Record record)
{
String tempString = record.getUpdateStatement();
sendStrings.add(tempString);
parseCount++;
if(parseCount % this.batchCount == 0)
{
flush(sendStrings);
Log.log("ParseCount = " + parseCount);
sendStrings.clear();
}
return true;
}
public String printString()
{
String sendString = "";
for(String string : sendStrings)
sendString += string + "\n";
return sendString;
}
public void flush(List<String> stringsToBeSent)// throws SQLException
{
if(stringsToBeSent == null || stringsToBeSent.size() == 0)
{
- Log.log("Error in flush: if(stringsToBeSent == null || stringsToBeSent.size() == 0) evaluated to true..." + stringsToBeSent);
+ //Log.log("Error in flush: if(stringsToBeSent == null || stringsToBeSent.size() == 0) evaluated to true..." + stringsToBeSent);
return;
}
Statement stmt = null;
try {
stmt = connection.createStatement();
} catch (SQLException e1) {
// TODO Auto-generated catch block
Log.log("error: stmt = connection.createStatement();", e1);
LocationMapper.Exit(5);
}
String sendString = "";
for(String string : stringsToBeSent)
sendString += string;
try
{
stmt.executeUpdate(sendString);
}
catch (SQLException e)
{
if(stringsToBeSent.size() == 1)
{
Log.log("ERRROR: bad send String: " + stringsToBeSent.get(0));
stringsToBeSent.clear();
return;
}
List<String> list1 = new ArrayList<String>(stringsToBeSent.subList(0, stringsToBeSent.size() / 2));
List<String> list2 = new ArrayList<String>(stringsToBeSent.subList(stringsToBeSent.size() / 2, stringsToBeSent.size()));
flush(list1);
flush(list2);
}
stringsToBeSent.clear();
}
public void close() throws SQLException
{
flush(sendStrings);
connection.close();
}
public boolean isConnected()
{
boolean data = false;
if(connection == null)
return data;
try
{
data = connection.isValid(timeout);
}
catch (SQLException e)
{
Log.log("", e);
}
return data;
}
public ResultSet getData()
{
results = null;
if(this.Connect() == false)
{
Log.log("ERROR: unable to get data from server");
LocationMapper.Exit(4);
}
try
{
Statement stmt = connection.createStatement();
stmt.setFetchSize(fetchSize);
Log.log("Querying Server: " + statement);
results = stmt.executeQuery(statement);
}
catch (Exception e)
{
Log.log("ERROR: Query Failed: " + e.getMessage());
return null;
}
return results;
}
public boolean Connect()
{
if(isConnected())
return true;
try
{
Class.forName("org.postgresql.Driver");
}
catch (ClassNotFoundException cnfe)
{
Log.log("ERROR: Could not find the JDBC driver!");
return false;
}
String connectionString = "jdbc:postgresql://" + address +":" + port + "/" + tableName;
Log.log("Connecting to " + connectionString);
try
{
connection = DriverManager.getConnection(connectionString, userName, password);
Log.log("Connection is full of success!");
}
catch (SQLException e)
{
Log.log("ERROR: Could not connect: " + e.getMessage());
return false;
}
if (connection == null) //this should never happen
{
Log.log("ERROR: Could not connect: LocationMapper.getDataFromServer.sqlConnection == null...hmmmm this should never happen");
return false;
}
return isConnected();
}
}
| true | true | public void flush(List<String> stringsToBeSent)// throws SQLException
{
if(stringsToBeSent == null || stringsToBeSent.size() == 0)
{
Log.log("Error in flush: if(stringsToBeSent == null || stringsToBeSent.size() == 0) evaluated to true..." + stringsToBeSent);
return;
}
Statement stmt = null;
try {
stmt = connection.createStatement();
} catch (SQLException e1) {
// TODO Auto-generated catch block
Log.log("error: stmt = connection.createStatement();", e1);
LocationMapper.Exit(5);
}
String sendString = "";
for(String string : stringsToBeSent)
sendString += string;
try
{
stmt.executeUpdate(sendString);
}
catch (SQLException e)
{
if(stringsToBeSent.size() == 1)
{
Log.log("ERRROR: bad send String: " + stringsToBeSent.get(0));
stringsToBeSent.clear();
return;
}
List<String> list1 = new ArrayList<String>(stringsToBeSent.subList(0, stringsToBeSent.size() / 2));
List<String> list2 = new ArrayList<String>(stringsToBeSent.subList(stringsToBeSent.size() / 2, stringsToBeSent.size()));
flush(list1);
flush(list2);
}
stringsToBeSent.clear();
}
| public void flush(List<String> stringsToBeSent)// throws SQLException
{
if(stringsToBeSent == null || stringsToBeSent.size() == 0)
{
//Log.log("Error in flush: if(stringsToBeSent == null || stringsToBeSent.size() == 0) evaluated to true..." + stringsToBeSent);
return;
}
Statement stmt = null;
try {
stmt = connection.createStatement();
} catch (SQLException e1) {
// TODO Auto-generated catch block
Log.log("error: stmt = connection.createStatement();", e1);
LocationMapper.Exit(5);
}
String sendString = "";
for(String string : stringsToBeSent)
sendString += string;
try
{
stmt.executeUpdate(sendString);
}
catch (SQLException e)
{
if(stringsToBeSent.size() == 1)
{
Log.log("ERRROR: bad send String: " + stringsToBeSent.get(0));
stringsToBeSent.clear();
return;
}
List<String> list1 = new ArrayList<String>(stringsToBeSent.subList(0, stringsToBeSent.size() / 2));
List<String> list2 = new ArrayList<String>(stringsToBeSent.subList(stringsToBeSent.size() / 2, stringsToBeSent.size()));
flush(list1);
flush(list2);
}
stringsToBeSent.clear();
}
|
diff --git a/arena/easc/java/src/net/xp_framework/easc/protocol/standard/Serializer.java b/arena/easc/java/src/net/xp_framework/easc/protocol/standard/Serializer.java
index 4175af6ba..64b41b4e9 100644
--- a/arena/easc/java/src/net/xp_framework/easc/protocol/standard/Serializer.java
+++ b/arena/easc/java/src/net/xp_framework/easc/protocol/standard/Serializer.java
@@ -1,617 +1,618 @@
/* This class is part of the XP framework's EAS connectivity
*
* $Id$
*/
package net.xp_framework.easc.protocol.standard;
import java.lang.reflect.Proxy;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationHandler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.AbstractCollection;
import java.util.Date;
import java.util.Iterator;
import net.xp_framework.easc.protocol.standard.Handler;
import net.xp_framework.easc.protocol.standard.ArraySerializer;
import net.xp_framework.easc.protocol.standard.Invokeable;
import net.xp_framework.easc.protocol.standard.SerializationException;
/**
* Serializer / unserializer for PHP serialized data
*
* Usage example:
* <code>
* Object o= Serializer.valueOf("s:11:\"Hello World\";");
* System.out.println(o);
* </code>
*
* Usage example:
* <code>
* String s= Serializer.representationOf("Hello");
* System.out.println(s);
* </code>
*
* @see http://php.net/unserialize
* @see http://php.net/serialize
*/
public class Serializer {
private static class MethodTarget<Return, Parameter> implements Invokeable<Return, Parameter> {
private Method method = null;
MethodTarget(Method m) {
this.method= m;
}
public Return invoke(Parameter p) throws Exception {
return (Return)this.method.invoke(null, new Object[] { p });
}
}
private static class Length {
public int value = 0;
public Length(int initial) {
this.value = initial;
}
@Override public String toString() {
return "Length(" + this.value + ")";
}
}
private static enum Token {
T_NULL {
public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
length.value= 2;
return null;
}
},
T_BOOLEAN {
public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
length.value= 4;
return ('1' == serialized.charAt(2));
}
},
T_INTEGER {
public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
String value= serialized.substring(2, serialized.indexOf(';', 2));
length.value= value.length() + 3;
return Integer.parseInt(value);
}
},
T_LONG {
public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
String value= serialized.substring(2, serialized.indexOf(';', 2));
length.value= value.length() + 3;
return Long.parseLong(value);
}
},
T_FLOAT {
public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
String value= serialized.substring(2, serialized.indexOf(';', 2));
length.value= value.length() + 3;
return Float.parseFloat(value);
}
},
T_DOUBLE {
public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
String value= serialized.substring(2, serialized.indexOf(';', 2));
length.value= value.length() + 3;
return Double.parseDouble(value);
}
},
T_STRING {
public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
String strlength= serialized.substring(2, serialized.indexOf(':', 2));
int offset= 2 + strlength.length() + 2;
int parsed= Integer.parseInt(strlength);
length.value= offset + parsed + 2;
return serialized.substring(offset, parsed+ offset);
}
},
T_HASH {
public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
String arraylength= serialized.substring(2, serialized.indexOf(':', 2));
int parsed= Integer.parseInt(arraylength);
int offset= arraylength.length() + 2 + 2;
HashMap h= new HashMap(parsed);
for (int i= 0; i < parsed; i++) {
Object key= Serializer.valueOf(serialized.substring(offset), length, loader);
offset+= length.value;
Object value= Serializer.valueOf(serialized.substring(offset), length, loader);
offset+= length.value;
h.put(key, value);
}
length.value= offset + 1;
return h;
}
},
T_ARRAY {
public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
String arraylength= serialized.substring(2, serialized.indexOf(':', 2));
int parsed= Integer.parseInt(arraylength);
int offset= arraylength.length() + 2 + 2;
Object[] array= new Object[parsed];
for (int i= 0; i < parsed; i++) {
array[i]= Serializer.valueOf(serialized.substring(offset), length, loader);
offset+= length.value;
}
length.value= offset + 1;
return array;
}
},
T_OBJECT {
public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
String classnamelength= serialized.substring(2, serialized.indexOf(':', 2));
int offset= classnamelength.length() + 2 + 2;
int parsed= Integer.parseInt(classnamelength);
Class c= null;
Object instance= null;
// Load class
try {
c= loader.loadClass(serialized.substring(offset, parsed+ offset));
} catch (ClassNotFoundException e) {
throw new SerializationException(loader + ": " + e.getMessage());
}
// Instanciate
instance= c.newInstance();
String objectlength= serialized.substring(parsed+ offset+ 2, serialized.indexOf(':', parsed+ offset+ 2));
offset+= parsed+ 2 + objectlength.length() + 2;
// Set field values
for (int i= 0; i < Integer.parseInt(objectlength); i++) {
Field f= c.getDeclaredField((String)Serializer.valueOf(serialized.substring(offset), length, loader));
offset+= length.value;
Object value= Serializer.valueOf(serialized.substring(offset), length, loader);
offset+= length.value;
f.setAccessible(true);
if (f.getType() == char.class) {
f.setChar(instance, ((String)value).charAt(0));
} else if (f.getType() == byte.class) {
f.setByte(instance, ((Byte)value).byteValue());
} else if (f.getType() == short.class) {
f.setShort(instance, ((Short)value).shortValue());
} else if (f.getType() == int.class) {
f.setInt(instance, ((Integer)value).intValue());
} else if (f.getType() == long.class) {
f.setLong(instance, ((Long)value).longValue());
} else if (f.getType() == double.class) {
f.setDouble(instance, ((Double)value).doubleValue());
} else if (f.getType() == float.class) {
f.setFloat(instance, ((Float)value).floatValue());
} else if (f.getType() == boolean.class) {
f.setBoolean(instance, ((Boolean)value).booleanValue());
} else {
f.set(instance, value);
}
}
+ length.value= offset + 1;
return instance;
}
},
T_DATE {
public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
String value= serialized.substring(2, serialized.indexOf(';', 2));
length.value= value.length() + 3;
return new Date(Long.parseLong(value) * 1000);
}
},
T_BYTE {
public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
String value= serialized.substring(2, serialized.indexOf(';', 2));
length.value= value.length() + 3;
return Byte.parseByte(value);
}
},
T_SHORT {
public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
String value= serialized.substring(2, serialized.indexOf(';', 2));
length.value= value.length() + 3;
return Short.parseShort(value);
}
};
private static HashMap<Character, Token> map= new HashMap<Character, Token>();
static {
map.put('N', T_NULL);
map.put('b', T_BOOLEAN);
map.put('i', T_INTEGER);
map.put('l', T_LONG);
map.put('f', T_FLOAT);
map.put('d', T_DOUBLE);
map.put('s', T_STRING);
map.put('a', T_HASH);
map.put('A', T_ARRAY);
map.put('O', T_OBJECT);
map.put('T', T_DATE);
map.put('B', T_BYTE);
map.put('S', T_SHORT);
}
public static Token valueOf(char c) throws Exception {
if (!map.containsKey(c)) {
throw new SerializationException("Unknown type '" + c + "'");
}
return map.get(c);
}
abstract public Object handle(String serialized, Length length, ClassLoader loader) throws Exception;
}
private static HashMap<Class, Invokeable<?, ?>> typeMap= new HashMap<Class, Invokeable<?, ?>>();
private static HashMap<Class, String> exceptionMap= new HashMap<Class, String>();
static {
// Set up typeMap by inspecting all class methods with @Handler annotation
for (Method m : Serializer.class.getDeclaredMethods()) {
if (!m.isAnnotationPresent(Handler.class)) continue;
registerMapping(m.getParameterTypes()[0], new MethodTarget<String, Object>(m));
}
registerExceptionName(IllegalArgumentException.class, "IllegalArgument");
registerExceptionName(IllegalAccessException.class, "IllegalAccess");
registerExceptionName(ClassNotFoundException.class, "ClassNotFound");
registerExceptionName(NullPointerException.class, "NullPointer");
}
public static void registerExceptionName(Class c, String name) {
exceptionMap.put(c, name);
}
public static void registerMapping(Class c, Invokeable<?, ?> i) {
typeMap.put(c, i);
}
public static Invokeable<?, ?> invokeableFor(Class c) {
Invokeable<?, ?> i= null;
if (null != (i= typeMap.get(c))) return i; // Direct hit
// Search for classes the specified class is assignable from
for (Class key: typeMap.keySet()) {
if (!key.isAssignableFrom(c)) continue;
// Cache results. Next time around, we'll have a direct hit
i= typeMap.get(key);
typeMap.put(c, i);
return i;
}
// Nothing found, return NULL. This will make representationOf()
// use the default object serialization mechanism (field-based)
return null;
}
private static ArrayList<Field> classFields(Class c) {
ArrayList<Field> list= new ArrayList<Field>();
for (Field f : c.getDeclaredFields()) {
if (Modifier.isTransient(f.getModifiers())) continue;
list.add(f);
}
return list;
}
private static String representationOf(Object o, Invokeable i) throws Exception {
if (i != null) return (String)i.invoke(o);
if (null == o) return "N;";
// Default object serialization
StringBuffer buffer= new StringBuffer();
Class c= o.getClass();
long numFields = 0;
for (Field f : classFields(c)) {
buffer.append("s:");
buffer.append(f.getName().length());
buffer.append(":\"");
buffer.append(f.getName());
buffer.append("\";");
f.setAccessible(true);
buffer.append(representationOf(f.get(o), invokeableFor(f.getType())));
numFields++;
}
buffer.append("}");
buffer.insert(0, "O:" + c.getName().length() + ":\"" + c.getName() + "\":" + numFields + ":{");
return buffer.toString();
}
@Handler public static String representationOf(String s) {
if (null == s) return "N;";
return "s:" + s.length() + ":\"" + s + "\";";
}
@Handler public static String representationOf(char c) {
return "s:1:\"" + c + "\";";
}
@Handler public static String representationOf(final char[] array) throws Exception {
return new ArraySerializer() {
public void yield(int i) {
this.buffer.append(representationOf(array[i]));
}
}.run(array.length);
}
@Handler public static String representationOf(Character c) {
if (null == c) return "N;";
return "s:1:\"" + c + "\";";
}
@Handler public static String representationOf(byte b) {
return "B:" + b + ";";
}
@Handler public static String representationOf(final byte[] array) throws Exception {
return new ArraySerializer() {
public void yield(int i) {
this.buffer.append(representationOf(array[i]));
}
}.run(array.length);
}
@Handler public static String representationOf(Byte b) {
if (null == b) return "N;";
return "B:" + b + ";";
}
@Handler public static String representationOf(short s) {
return "S:" + s + ";";
}
@Handler public static String representationOf(final short[] array) throws Exception {
return new ArraySerializer() {
public void yield(int i) {
this.buffer.append(representationOf(array[i]));
}
}.run(array.length);
}
@Handler public static String representationOf(Short s) {
if (null == s) return "N;";
return "S:" + s + ";";
}
@Handler public static String representationOf(int i) {
return "i:" + i + ";";
}
@Handler public static String representationOf(final int[] array) throws Exception {
return new ArraySerializer() {
public void yield(int i) {
this.buffer.append(representationOf(array[i]));
}
}.run(array.length);
}
@Handler public static String representationOf(Integer i) {
if (null == i) return "N;";
return "i:" + i + ";";
}
@Handler public static String representationOf(long l) {
return "l:" + l + ";";
}
@Handler public static String representationOf(final long[] array) throws Exception {
return new ArraySerializer() {
public void yield(int i) {
this.buffer.append(representationOf(array[i]));
}
}.run(array.length);
}
@Handler public static String representationOf(Long l) {
if (null == l) return "N;";
return "l:" + l + ";";
}
@Handler public static String representationOf(double d) {
return "d:" + d + ";";
}
@Handler public static String representationOf(final double[] array) throws Exception {
return new ArraySerializer() {
public void yield(int i) {
this.buffer.append(representationOf(array[i]));
}
}.run(array.length);
}
@Handler public static String representationOf(Double d) {
if (null == d) return "N;";
return "d:" + d + ";";
}
@Handler public static String representationOf(float f) {
return "f:" + f + ";";
}
@Handler public static String representationOf(final float[] array) throws Exception {
return new ArraySerializer() {
public void yield(int i) {
this.buffer.append(representationOf(array[i]));
}
}.run(array.length);
}
@Handler public static String representationOf(Float f) {
if (null == f) return "N;";
return "f:" + f + ";";
}
@Handler public static String representationOf(boolean b) {
return "b:" + (b ? 1 : 0) + ";";
}
@Handler public static String representationOf(final boolean[] array) throws Exception {
return new ArraySerializer() {
public void yield(int i) {
this.buffer.append(representationOf(array[i]));
}
}.run(array.length);
}
@Handler public static String representationOf(Boolean b) {
if (null == b) return "N;";
return "b:" + (b ? 1 : 0) + ";";
}
@Handler public static String representationOf(HashMap h) throws Exception {
if (null == h) return "N;";
StringBuffer buffer= new StringBuffer("a:" + h.size() + ":{");
for (Iterator it= h.keySet().iterator(); it.hasNext(); ) {
Object key= it.next();
Object value= h.get(key);
buffer.append(representationOf(key, invokeableFor(key.getClass())));
buffer.append(representationOf(value, invokeableFor(value.getClass())));
}
buffer.append("}");
return buffer.toString();
}
@Handler public static String representationOf(AbstractCollection c) throws Exception {
if (null == c) return "N;";
return representationOf(c.toArray());
}
@Handler public static String representationOf(Date d) throws Exception {
if (null == d) return "N;";
return "T:" + d.getTime() / 1000 + ";"; // getTime() returns *milliseconds*
}
@Handler public static String representationOf(Object[] a) throws Exception {
StringBuffer buffer= new StringBuffer("a:" + a.length + ":{");
for (int i= 0; i < a.length; i++) {
buffer.append("i:" + i + ";");
buffer.append(representationOf(a[i], invokeableFor(a[i].getClass())));
}
buffer.append("}");
return buffer.toString();
}
@Handler public static String representationOf(StackTraceElement e) throws Exception {
if (null == e) return "N;";
StringBuffer buffer= new StringBuffer();
Class c= e.getClass();
String name;
buffer.append("t:4:{");
buffer.append("s:4:\"file\";").append(representationOf(e.getFileName()));
buffer.append("s:5:\"class\";").append(representationOf(e.getClassName()));
buffer.append("s:6:\"method\";").append(representationOf(e.getMethodName()));
buffer.append("s:4:\"line\";").append(representationOf(e.getLineNumber()));
buffer.append("}");
return buffer.toString();
}
@Handler public static String representationOf(Throwable e) throws Exception {
if (null == e) return "N;";
StringBuffer buffer= new StringBuffer();
Class c= e.getClass();
StackTraceElement[] trace= e.getStackTrace();
String alias= null;
if (null != (alias= exceptionMap.get(c))) {
buffer.append("e:").append(alias.length()).append(":\"").append(alias);
} else {
buffer.append("E:").append(c.getName().length()).append(":\"").append(c.getName());
}
buffer.append("\":2:{s:7:\"message\";");
buffer.append(representationOf(e.getMessage()));
buffer.append("s:5:\"trace\";a:").append(trace.length).append(":{");
int offset= 0;
for (StackTraceElement element: trace) {
buffer.append("i:").append(offset++).append(';').append(representationOf(element));
}
buffer.append("}}");
return buffer.toString();
}
/**
* Fall-back method for default serialization. Not a handler since this
* would lead to an infinite loop in the invokeableFor() method.
*
* @static
* @access public
* @param java.lang.Object o
* @return java.lang.String
*/
public static String representationOf(Object o) throws Exception {
if (null == o) return "N;";
return representationOf(o, invokeableFor(o.getClass()));
}
/**
* Private helper method for public valueOf()
*
* @access private
* @param java.lang.String serialized
* @param Length length
* @return java.lang.Object
*/
private static Object valueOf(String serialized, Length length, ClassLoader loader) throws Exception {
return Token.valueOf(serialized.charAt(0)).handle(serialized, length, loader);
}
private static Object valueOf(String serialized, Length length) throws Exception {
return Token.valueOf(serialized.charAt(0)).handle(serialized, length, Serializer.class.getClassLoader());
}
public static Object valueOf(String serialized) throws Exception {
return valueOf(serialized, new Length(0));
}
public static Object valueOf(String serialized, ClassLoader loader) throws Exception {
return valueOf(serialized, new Length(0), loader);
}
}
| true | true | public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
String classnamelength= serialized.substring(2, serialized.indexOf(':', 2));
int offset= classnamelength.length() + 2 + 2;
int parsed= Integer.parseInt(classnamelength);
Class c= null;
Object instance= null;
// Load class
try {
c= loader.loadClass(serialized.substring(offset, parsed+ offset));
} catch (ClassNotFoundException e) {
throw new SerializationException(loader + ": " + e.getMessage());
}
// Instanciate
instance= c.newInstance();
String objectlength= serialized.substring(parsed+ offset+ 2, serialized.indexOf(':', parsed+ offset+ 2));
offset+= parsed+ 2 + objectlength.length() + 2;
// Set field values
for (int i= 0; i < Integer.parseInt(objectlength); i++) {
Field f= c.getDeclaredField((String)Serializer.valueOf(serialized.substring(offset), length, loader));
offset+= length.value;
Object value= Serializer.valueOf(serialized.substring(offset), length, loader);
offset+= length.value;
f.setAccessible(true);
if (f.getType() == char.class) {
f.setChar(instance, ((String)value).charAt(0));
} else if (f.getType() == byte.class) {
f.setByte(instance, ((Byte)value).byteValue());
} else if (f.getType() == short.class) {
f.setShort(instance, ((Short)value).shortValue());
} else if (f.getType() == int.class) {
f.setInt(instance, ((Integer)value).intValue());
} else if (f.getType() == long.class) {
f.setLong(instance, ((Long)value).longValue());
} else if (f.getType() == double.class) {
f.setDouble(instance, ((Double)value).doubleValue());
} else if (f.getType() == float.class) {
f.setFloat(instance, ((Float)value).floatValue());
} else if (f.getType() == boolean.class) {
f.setBoolean(instance, ((Boolean)value).booleanValue());
} else {
f.set(instance, value);
}
}
return instance;
}
| public Object handle(String serialized, Length length, ClassLoader loader) throws Exception {
String classnamelength= serialized.substring(2, serialized.indexOf(':', 2));
int offset= classnamelength.length() + 2 + 2;
int parsed= Integer.parseInt(classnamelength);
Class c= null;
Object instance= null;
// Load class
try {
c= loader.loadClass(serialized.substring(offset, parsed+ offset));
} catch (ClassNotFoundException e) {
throw new SerializationException(loader + ": " + e.getMessage());
}
// Instanciate
instance= c.newInstance();
String objectlength= serialized.substring(parsed+ offset+ 2, serialized.indexOf(':', parsed+ offset+ 2));
offset+= parsed+ 2 + objectlength.length() + 2;
// Set field values
for (int i= 0; i < Integer.parseInt(objectlength); i++) {
Field f= c.getDeclaredField((String)Serializer.valueOf(serialized.substring(offset), length, loader));
offset+= length.value;
Object value= Serializer.valueOf(serialized.substring(offset), length, loader);
offset+= length.value;
f.setAccessible(true);
if (f.getType() == char.class) {
f.setChar(instance, ((String)value).charAt(0));
} else if (f.getType() == byte.class) {
f.setByte(instance, ((Byte)value).byteValue());
} else if (f.getType() == short.class) {
f.setShort(instance, ((Short)value).shortValue());
} else if (f.getType() == int.class) {
f.setInt(instance, ((Integer)value).intValue());
} else if (f.getType() == long.class) {
f.setLong(instance, ((Long)value).longValue());
} else if (f.getType() == double.class) {
f.setDouble(instance, ((Double)value).doubleValue());
} else if (f.getType() == float.class) {
f.setFloat(instance, ((Float)value).floatValue());
} else if (f.getType() == boolean.class) {
f.setBoolean(instance, ((Boolean)value).booleanValue());
} else {
f.set(instance, value);
}
}
length.value= offset + 1;
return instance;
}
|
diff --git a/grisu-client/src/main/java/grisu/frontend/control/JaxWsServiceInterfaceCreator.java b/grisu-client/src/main/java/grisu/frontend/control/JaxWsServiceInterfaceCreator.java
index 57c228b5..6c419ebc 100644
--- a/grisu-client/src/main/java/grisu/frontend/control/JaxWsServiceInterfaceCreator.java
+++ b/grisu-client/src/main/java/grisu/frontend/control/JaxWsServiceInterfaceCreator.java
@@ -1,230 +1,230 @@
package grisu.frontend.control;
import grisu.control.ServiceInterface;
import grisu.control.ServiceInterfaceCreator;
import grisu.control.exceptions.ServiceInterfaceException;
import grisu.settings.Environment;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.soap.MTOMFeature;
import javax.xml.ws.soap.SOAPBinding;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.sun.xml.ws.developer.JAXWSProperties;
public class JaxWsServiceInterfaceCreator implements ServiceInterfaceCreator {
static final Logger myLogger = Logger
.getLogger(JaxWsServiceInterfaceCreator.class.getName());
public static String TRUST_FILE_NAME = Environment
.getGrisuClientDirectory().getPath()
+ File.separator
+ "truststore.jks";
/**
* configures secure connection parameters.
**/
public JaxWsServiceInterfaceCreator() throws ServiceInterfaceException {
try {
if (!(new File(Environment.getGrisuClientDirectory(),
"truststore.jks").exists())) {
final InputStream ts = JaxWsServiceInterfaceCreator.class
.getResourceAsStream("/truststore.jks");
IOUtils.copy(ts, new FileOutputStream(TRUST_FILE_NAME));
}
} catch (final IOException ex) {
throw new ServiceInterfaceException(
"cannot copy SSL certificate store into grisu home directory. Does "
+ Environment.getGrisuClientDirectory().getPath()
+ " exist?", ex);
}
System.setProperty("javax.net.ssl.trustStore", TRUST_FILE_NAME);
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
}
public boolean canHandleUrl(String url) {
if (StringUtils.isNotBlank(url) && url.startsWith("http")) {
return true;
} else {
return false;
}
}
public ServiceInterface create(String interfaceUrl, String username,
char[] password, String myProxyServer, String myProxyPort,
Object[] otherOptions) throws ServiceInterfaceException {
try {
final QName serviceName = new QName(
"http://api.grisu.arcs.org.au/", "GrisuService");
final QName portName = new QName("http://api.grisu.arcs.org.au/",
// "ServiceInterfaceSOAPPort");
"ServiceInterfacePort");
Service s;
try {
s = Service.create(
new URL(interfaceUrl.replace("soap/GrisuService",
"api.wsdl")), serviceName);
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
}
final MTOMFeature mtom = new MTOMFeature();
try {
s.getPort(portName, ServiceInterface.class, mtom);
} catch (Error e) {
// throw new ServiceInterfaceException(
// "Could not connect to backend, probably because of frontend/backend incompatibility (Underlying cause: \""
// + e.getLocalizedMessage()
// +
// "\"). Before reporting a bug, please try latest client from: http://code.ceres.auckland.ac.nz/stable-downloads.");
throw new ServiceInterfaceException(
- "Sorry, could not login. Most likely your client version is incompatible with the server.\n"
- + "Please download the latest version from:\nhttp://code.ceres.auckland.ac.nz/stable-downloads\n"
- + "If you have the latest version and are still experiencing this problem please contact\n"
- + "[email protected]\n"
+ "Sorry, could not login. Most likely your client version is incompatible with the server.\n\n"
+ + "Please download the latest version from:\n\nhttp://code.ceres.auckland.ac.nz/stable-downloads\n\n"
+ + "If you have the latest version and are still experiencing this problem please contact\n\n"
+ + "[email protected]\n\n"
+ "with a description of the issue.\n\nUnderlying cause: "
+ e.getLocalizedMessage());
}
final ServiceInterface service = s.getPort(portName,
ServiceInterface.class);
final BindingProvider bp = (javax.xml.ws.BindingProvider) service;
bp.getRequestContext().put(
javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
interfaceUrl);
bp.getRequestContext().put(
JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 4096);
// just to be sure, I'll keep that in there as well...
bp.getRequestContext()
.put("com.sun.xml.internal.ws.transport.http.client.streaming.chunk.size",
new Integer(4096));
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY,
username);
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,
new String(password));
bp.getRequestContext().put(
BindingProvider.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE);
final SOAPBinding binding = (SOAPBinding) bp.getBinding();
binding.setMTOMEnabled(true);
return service;
} catch (final Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
throw new ServiceInterfaceException(
"Could not create JaxwsServiceInterface: "
+ e.getLocalizedMessage(), e);
}
}
// private SSLSocketFactory createSocketFactory(String interfaceUrl)
// throws ServiceInterfaceException {
// // Technique similar to
// // http://juliusdavies.ca/commons-ssl/TrustExample.java.html
// HttpSecureProtocol protocolSocketFactory;
// try {
// protocolSocketFactory = new HttpSecureProtocol();
//
// TrustMaterial trustMaterial = null;
//
// // "/thecertificate.cer" can be PEM or DER (raw ASN.1). Can even
// // be several PEM certificates in one file.
//
// String cacertFilename = System.getProperty("grisu.cacert");
// URL cacertURL = null;
//
// try {
// if (cacertFilename != null && !"".equals(cacertFilename)) {
// cacertURL = JaxWsServiceInterfaceCreator.class
// .getResource("/" + cacertFilename);
// if (cacertURL != null) {
// myLogger.debug("Using cacert " + cacertFilename
// + " as configured in the -D option.");
// }
// }
// } catch (Exception e) {
// // doesn't matter
// myLogger
// .debug("Couldn't find specified cacert. Using default one.");
// }
//
// if (cacertURL == null) {
//
// cacertFilename = new CaCertManager()
// .getCaCertNameForServiceInterfaceUrl(interfaceUrl);
// if (cacertFilename != null && cacertFilename.length() > 0) {
// myLogger
// .debug("Found url in map. Trying to use this cacert file: "
// + cacertFilename);
// cacertURL = JaxWsServiceInterfaceCreator.class
// .getResource("/" + cacertFilename);
// if (cacertURL == null) {
// myLogger
// .debug("Didn't find cacert. Using the default one.");
// // use the default one
// cacertURL = JaxWsServiceInterfaceCreator.class
// .getResource("/cacert.pem");
// } else {
// myLogger.debug("Found cacert. Using it. Good.");
// }
// } else {
// myLogger
// .debug("Didn't find any configuration for a special cacert. Using the default one.");
// // use the default one
// cacertURL = JaxWsServiceInterfaceCreator.class
// .getResource("/cacert.pem");
// }
//
// }
//
// trustMaterial = new TrustMaterial(cacertURL);
//
// // We can use setTrustMaterial() instead of addTrustMaterial()
// // if we want to remove
// // HttpSecureProtocol's default trust of TrustMaterial.CACERTS.
// protocolSocketFactory.addTrustMaterial(trustMaterial);
//
// // Maybe we want to turn off CN validation (not recommended!):
// protocolSocketFactory.setCheckHostname(false);
//
// Protocol protocol = new Protocol("https",
// (ProtocolSocketFactory) protocolSocketFactory, 443);
// Protocol.registerProtocol("https", protocol);
//
// return protocolSocketFactory;
// } catch (Exception e1) {
// // TODO Auto-generated catch block
// // e1.printStackTrace();
// throw new ServiceInterfaceException(
// "Unspecified error while trying to establish secure connection.",
// e1);
// }
// }
}
| true | true | public ServiceInterface create(String interfaceUrl, String username,
char[] password, String myProxyServer, String myProxyPort,
Object[] otherOptions) throws ServiceInterfaceException {
try {
final QName serviceName = new QName(
"http://api.grisu.arcs.org.au/", "GrisuService");
final QName portName = new QName("http://api.grisu.arcs.org.au/",
// "ServiceInterfaceSOAPPort");
"ServiceInterfacePort");
Service s;
try {
s = Service.create(
new URL(interfaceUrl.replace("soap/GrisuService",
"api.wsdl")), serviceName);
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
}
final MTOMFeature mtom = new MTOMFeature();
try {
s.getPort(portName, ServiceInterface.class, mtom);
} catch (Error e) {
// throw new ServiceInterfaceException(
// "Could not connect to backend, probably because of frontend/backend incompatibility (Underlying cause: \""
// + e.getLocalizedMessage()
// +
// "\"). Before reporting a bug, please try latest client from: http://code.ceres.auckland.ac.nz/stable-downloads.");
throw new ServiceInterfaceException(
"Sorry, could not login. Most likely your client version is incompatible with the server.\n"
+ "Please download the latest version from:\nhttp://code.ceres.auckland.ac.nz/stable-downloads\n"
+ "If you have the latest version and are still experiencing this problem please contact\n"
+ "[email protected]\n"
+ "with a description of the issue.\n\nUnderlying cause: "
+ e.getLocalizedMessage());
}
final ServiceInterface service = s.getPort(portName,
ServiceInterface.class);
final BindingProvider bp = (javax.xml.ws.BindingProvider) service;
bp.getRequestContext().put(
javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
interfaceUrl);
bp.getRequestContext().put(
JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 4096);
// just to be sure, I'll keep that in there as well...
bp.getRequestContext()
.put("com.sun.xml.internal.ws.transport.http.client.streaming.chunk.size",
new Integer(4096));
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY,
username);
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,
new String(password));
bp.getRequestContext().put(
BindingProvider.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE);
final SOAPBinding binding = (SOAPBinding) bp.getBinding();
binding.setMTOMEnabled(true);
return service;
} catch (final Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
throw new ServiceInterfaceException(
"Could not create JaxwsServiceInterface: "
+ e.getLocalizedMessage(), e);
}
}
| public ServiceInterface create(String interfaceUrl, String username,
char[] password, String myProxyServer, String myProxyPort,
Object[] otherOptions) throws ServiceInterfaceException {
try {
final QName serviceName = new QName(
"http://api.grisu.arcs.org.au/", "GrisuService");
final QName portName = new QName("http://api.grisu.arcs.org.au/",
// "ServiceInterfaceSOAPPort");
"ServiceInterfacePort");
Service s;
try {
s = Service.create(
new URL(interfaceUrl.replace("soap/GrisuService",
"api.wsdl")), serviceName);
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
}
final MTOMFeature mtom = new MTOMFeature();
try {
s.getPort(portName, ServiceInterface.class, mtom);
} catch (Error e) {
// throw new ServiceInterfaceException(
// "Could not connect to backend, probably because of frontend/backend incompatibility (Underlying cause: \""
// + e.getLocalizedMessage()
// +
// "\"). Before reporting a bug, please try latest client from: http://code.ceres.auckland.ac.nz/stable-downloads.");
throw new ServiceInterfaceException(
"Sorry, could not login. Most likely your client version is incompatible with the server.\n\n"
+ "Please download the latest version from:\n\nhttp://code.ceres.auckland.ac.nz/stable-downloads\n\n"
+ "If you have the latest version and are still experiencing this problem please contact\n\n"
+ "[email protected]\n\n"
+ "with a description of the issue.\n\nUnderlying cause: "
+ e.getLocalizedMessage());
}
final ServiceInterface service = s.getPort(portName,
ServiceInterface.class);
final BindingProvider bp = (javax.xml.ws.BindingProvider) service;
bp.getRequestContext().put(
javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
interfaceUrl);
bp.getRequestContext().put(
JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 4096);
// just to be sure, I'll keep that in there as well...
bp.getRequestContext()
.put("com.sun.xml.internal.ws.transport.http.client.streaming.chunk.size",
new Integer(4096));
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY,
username);
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY,
new String(password));
bp.getRequestContext().put(
BindingProvider.SESSION_MAINTAIN_PROPERTY, Boolean.TRUE);
final SOAPBinding binding = (SOAPBinding) bp.getBinding();
binding.setMTOMEnabled(true);
return service;
} catch (final Exception e) {
// TODO Auto-generated catch block
// e.printStackTrace();
throw new ServiceInterfaceException(
"Could not create JaxwsServiceInterface: "
+ e.getLocalizedMessage(), e);
}
}
|
diff --git a/commons/src/main/java/org/wikimedia/commons/contributions/ContributionsSyncAdapter.java b/commons/src/main/java/org/wikimedia/commons/contributions/ContributionsSyncAdapter.java
index ec133e3d..61ca6bf7 100644
--- a/commons/src/main/java/org/wikimedia/commons/contributions/ContributionsSyncAdapter.java
+++ b/commons/src/main/java/org/wikimedia/commons/contributions/ContributionsSyncAdapter.java
@@ -1,121 +1,125 @@
package org.wikimedia.commons.contributions;
import android.content.*;
import android.database.Cursor;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.accounts.Account;
import android.os.Bundle;
import org.apache.commons.codec.digest.DigestUtils;
import org.wikimedia.commons.CommonsApplication;
import org.mediawiki.api.*;
import org.wikimedia.commons.Utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class ContributionsSyncAdapter extends AbstractThreadedSyncAdapter {
private static int COMMIT_THRESHOLD = 10;
public ContributionsSyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
}
private int getLimit() {
return 500; // FIXME: Parameterize!
}
private static final String[] existsQuery = { Contribution.Table.COLUMN_FILENAME };
private static final String existsSelection = Contribution.Table.COLUMN_FILENAME + " = ?";
private boolean fileExists(ContentProviderClient client, String filename) {
Cursor cursor = null;
try {
cursor = client.query(ContributionsContentProvider.BASE_URI,
existsQuery,
existsSelection,
new String[] { filename },
""
);
} catch (RemoteException e) {
throw new RuntimeException(e);
}
return cursor != null && cursor.getCount() != 0;
}
@Override
public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient, SyncResult syncResult) {
// This code is fraught with possibilities of race conditions, but lalalalala I can't hear you!
String user = account.name;
MWApi api = CommonsApplication.createMWApi();
SharedPreferences prefs = this.getContext().getSharedPreferences("prefs", Context.MODE_PRIVATE);
String lastModified = prefs.getString("lastSyncTimestamp", "");
Date curTime = new Date();
ApiResult result;
Boolean done = false;
String queryContinue = null;
while(!done) {
try {
MWApi.RequestBuilder builder = api.action("query")
.param("list", "logevents")
.param("leaction", "upload/upload")
.param("leprop", "title|timestamp")
.param("leuser", user)
.param("lelimit", getLimit());
if(!TextUtils.isEmpty(lastModified)) {
builder.param("leend", lastModified);
}
if(!TextUtils.isEmpty(queryContinue)) {
builder.param("lestart", queryContinue);
}
result = builder.get();
} catch (IOException e) {
- throw new RuntimeException(e); // FIXME: Maybe something else?
+ // There isn't really much we can do, eh?
+ // FIXME: Perhaps add EventLogging?
+ syncResult.stats.numIoExceptions += 1; // Not sure if this does anything. Shitty docs
+ Log.d("Commons", "Syncing failed due to " + e.toString());
+ return;
}
Log.d("Commons", "Last modified at " + lastModified);
ArrayList<ApiResult> uploads = result.getNodes("/api/query/logevents/item");
Log.d("Commons", uploads.size() + " results!");
ArrayList<ContentValues> imageValues = new ArrayList<ContentValues>();
for(ApiResult image: uploads) {
String filename = image.getString("@title");
if(fileExists(contentProviderClient, filename)) {
Log.d("Commons", "Skipping " + filename);
continue;
}
String thumbUrl = Utils.makeThumbBaseUrl(filename);
Date dateUpdated = Utils.parseMWDate(image.getString("@timestamp"));
Contribution contrib = new Contribution(null, thumbUrl, filename, "", -1, dateUpdated, dateUpdated, user, "");
contrib.setState(Contribution.STATE_COMPLETED);
imageValues.add(contrib.toContentValues());
if(imageValues.size() % COMMIT_THRESHOLD == 0) {
try {
contentProviderClient.bulkInsert(ContributionsContentProvider.BASE_URI, imageValues.toArray(new ContentValues[]{}));
} catch (RemoteException e) {
throw new RuntimeException(e);
}
imageValues.clear();
}
}
if(imageValues.size() != 0) {
try {
contentProviderClient.bulkInsert(ContributionsContentProvider.BASE_URI, imageValues.toArray(new ContentValues[]{}));
} catch (RemoteException e) {
throw new RuntimeException(e);
}
}
queryContinue = result.getString("/api/query-continue/logevents/@lestart");
if(TextUtils.isEmpty(queryContinue)) {
done = true;
}
}
prefs.edit().putString("lastSyncTimestamp", Utils.toMWDate(curTime)).apply();
Log.d("Commons", "Oh hai, everyone! Look, a kitty!");
}
}
| true | true | public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient, SyncResult syncResult) {
// This code is fraught with possibilities of race conditions, but lalalalala I can't hear you!
String user = account.name;
MWApi api = CommonsApplication.createMWApi();
SharedPreferences prefs = this.getContext().getSharedPreferences("prefs", Context.MODE_PRIVATE);
String lastModified = prefs.getString("lastSyncTimestamp", "");
Date curTime = new Date();
ApiResult result;
Boolean done = false;
String queryContinue = null;
while(!done) {
try {
MWApi.RequestBuilder builder = api.action("query")
.param("list", "logevents")
.param("leaction", "upload/upload")
.param("leprop", "title|timestamp")
.param("leuser", user)
.param("lelimit", getLimit());
if(!TextUtils.isEmpty(lastModified)) {
builder.param("leend", lastModified);
}
if(!TextUtils.isEmpty(queryContinue)) {
builder.param("lestart", queryContinue);
}
result = builder.get();
} catch (IOException e) {
throw new RuntimeException(e); // FIXME: Maybe something else?
}
Log.d("Commons", "Last modified at " + lastModified);
ArrayList<ApiResult> uploads = result.getNodes("/api/query/logevents/item");
Log.d("Commons", uploads.size() + " results!");
ArrayList<ContentValues> imageValues = new ArrayList<ContentValues>();
for(ApiResult image: uploads) {
String filename = image.getString("@title");
if(fileExists(contentProviderClient, filename)) {
Log.d("Commons", "Skipping " + filename);
continue;
}
String thumbUrl = Utils.makeThumbBaseUrl(filename);
Date dateUpdated = Utils.parseMWDate(image.getString("@timestamp"));
Contribution contrib = new Contribution(null, thumbUrl, filename, "", -1, dateUpdated, dateUpdated, user, "");
contrib.setState(Contribution.STATE_COMPLETED);
imageValues.add(contrib.toContentValues());
if(imageValues.size() % COMMIT_THRESHOLD == 0) {
try {
contentProviderClient.bulkInsert(ContributionsContentProvider.BASE_URI, imageValues.toArray(new ContentValues[]{}));
} catch (RemoteException e) {
throw new RuntimeException(e);
}
imageValues.clear();
}
}
if(imageValues.size() != 0) {
try {
contentProviderClient.bulkInsert(ContributionsContentProvider.BASE_URI, imageValues.toArray(new ContentValues[]{}));
} catch (RemoteException e) {
throw new RuntimeException(e);
}
}
queryContinue = result.getString("/api/query-continue/logevents/@lestart");
if(TextUtils.isEmpty(queryContinue)) {
done = true;
}
}
prefs.edit().putString("lastSyncTimestamp", Utils.toMWDate(curTime)).apply();
Log.d("Commons", "Oh hai, everyone! Look, a kitty!");
}
| public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient, SyncResult syncResult) {
// This code is fraught with possibilities of race conditions, but lalalalala I can't hear you!
String user = account.name;
MWApi api = CommonsApplication.createMWApi();
SharedPreferences prefs = this.getContext().getSharedPreferences("prefs", Context.MODE_PRIVATE);
String lastModified = prefs.getString("lastSyncTimestamp", "");
Date curTime = new Date();
ApiResult result;
Boolean done = false;
String queryContinue = null;
while(!done) {
try {
MWApi.RequestBuilder builder = api.action("query")
.param("list", "logevents")
.param("leaction", "upload/upload")
.param("leprop", "title|timestamp")
.param("leuser", user)
.param("lelimit", getLimit());
if(!TextUtils.isEmpty(lastModified)) {
builder.param("leend", lastModified);
}
if(!TextUtils.isEmpty(queryContinue)) {
builder.param("lestart", queryContinue);
}
result = builder.get();
} catch (IOException e) {
// There isn't really much we can do, eh?
// FIXME: Perhaps add EventLogging?
syncResult.stats.numIoExceptions += 1; // Not sure if this does anything. Shitty docs
Log.d("Commons", "Syncing failed due to " + e.toString());
return;
}
Log.d("Commons", "Last modified at " + lastModified);
ArrayList<ApiResult> uploads = result.getNodes("/api/query/logevents/item");
Log.d("Commons", uploads.size() + " results!");
ArrayList<ContentValues> imageValues = new ArrayList<ContentValues>();
for(ApiResult image: uploads) {
String filename = image.getString("@title");
if(fileExists(contentProviderClient, filename)) {
Log.d("Commons", "Skipping " + filename);
continue;
}
String thumbUrl = Utils.makeThumbBaseUrl(filename);
Date dateUpdated = Utils.parseMWDate(image.getString("@timestamp"));
Contribution contrib = new Contribution(null, thumbUrl, filename, "", -1, dateUpdated, dateUpdated, user, "");
contrib.setState(Contribution.STATE_COMPLETED);
imageValues.add(contrib.toContentValues());
if(imageValues.size() % COMMIT_THRESHOLD == 0) {
try {
contentProviderClient.bulkInsert(ContributionsContentProvider.BASE_URI, imageValues.toArray(new ContentValues[]{}));
} catch (RemoteException e) {
throw new RuntimeException(e);
}
imageValues.clear();
}
}
if(imageValues.size() != 0) {
try {
contentProviderClient.bulkInsert(ContributionsContentProvider.BASE_URI, imageValues.toArray(new ContentValues[]{}));
} catch (RemoteException e) {
throw new RuntimeException(e);
}
}
queryContinue = result.getString("/api/query-continue/logevents/@lestart");
if(TextUtils.isEmpty(queryContinue)) {
done = true;
}
}
prefs.edit().putString("lastSyncTimestamp", Utils.toMWDate(curTime)).apply();
Log.d("Commons", "Oh hai, everyone! Look, a kitty!");
}
|
diff --git a/jnalib/test/com/sun/jna/examples/FileMonitorTest.java b/jnalib/test/com/sun/jna/examples/FileMonitorTest.java
index 19b62a52..95d02bbc 100644
--- a/jnalib/test/com/sun/jna/examples/FileMonitorTest.java
+++ b/jnalib/test/com/sun/jna/examples/FileMonitorTest.java
@@ -1,202 +1,204 @@
/* Copyright (c) 2007 Timothy Wall, All Rights Reserved
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* <p/>
* 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.
*/
package com.sun.jna.examples;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
import com.sun.jna.Platform;
import com.sun.jna.examples.FileMonitor.FileEvent;
import com.sun.jna.examples.FileMonitor.FileListener;
import com.sun.jna.examples.win32.Kernel32;
import com.sun.jna.ptr.PointerByReference;
public class FileMonitorTest extends TestCase {
Map events;
FileListener listener;
FileMonitor monitor;
File tmpdir;
protected void setUp() throws Exception {
if (!Platform.isWindows()) return;
events = new HashMap();
listener = new FileListener() {
public void fileChanged(FileEvent e) {
events.put(new Integer(e.getType()), e);
}
};
monitor = FileMonitor.getInstance();
monitor.addFileListener(listener);
tmpdir = new File(System.getProperty("java.io.tmpdir"));
}
protected void tearDown() {
if (monitor != null) {
monitor.dispose();
}
}
public void testNotifyOnFileCreation() throws Exception {
if (!Platform.isWindows()) return;
monitor.addWatch(tmpdir);
File file = File.createTempFile(getName(), ".tmp", tmpdir);
file.deleteOnExit();
FileEvent event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 5000 && event == null) {
Thread.sleep(10);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
}
assertTrue("No events sent", events.size() != 0);
assertNotNull("No creation event: " + events, event);
assertEquals("Wrong target file for event", file, event.getFile());
}
public void testNotifyOnFileDelete() throws Exception {
if (!Platform.isWindows()) return;
monitor.addWatch(tmpdir);
File file = File.createTempFile(getName(), ".tmp", tmpdir);
file.delete();
FileEvent event = (FileEvent)events.get(new Integer(FileMonitor.FILE_DELETED));
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 5000 && event == null) {
Thread.sleep(10);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_DELETED));
}
assertTrue("No events sent", events.size() != 0);
assertNotNull("No delete event: " + events, event);
assertEquals("Wrong target file for event", file, event.getFile());
}
public void testNotifyOnFileRename() throws Exception {
if (!Platform.isWindows()) return;
monitor.addWatch(tmpdir);
File file = File.createTempFile(getName(), ".tmp", tmpdir);
File newFile = new File(file.getParentFile(), "newfile");
newFile.deleteOnExit();
file.deleteOnExit();
file.renameTo(newFile);
FileEvent e1 = (FileEvent)events.get(new Integer(FileMonitor.FILE_NAME_CHANGED_OLD));
FileEvent e2 = (FileEvent)events.get(new Integer(FileMonitor.FILE_NAME_CHANGED_NEW));
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 5000 && e1 == null && e2 == null) {
Thread.sleep(10);
e1 = (FileEvent)events.get(new Integer(FileMonitor.FILE_NAME_CHANGED_OLD));
e2 = (FileEvent)events.get(new Integer(FileMonitor.FILE_NAME_CHANGED_NEW));
}
assertTrue("No events sent", events.size() != 0);
assertNotNull("No rename event (old): " + events, e1);
assertNotNull("No rename event (new): " + events, e2);
assertEquals("Wrong target file for event (old)", file, e1.getFile());
assertEquals("Wrong target file for event (new)", newFile, e2.getFile());
}
public void testNotifyOnFileModification() throws Exception {
if (!Platform.isWindows()) return;
monitor.addWatch(tmpdir);
File file = File.createTempFile(getName(), ".tmp", tmpdir);
file.deleteOnExit();
FileOutputStream os = new FileOutputStream(file);
os.write(getName().getBytes());
os.close();
FileEvent event = (FileEvent)events.get(new Integer(FileMonitor.FILE_MODIFIED));
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 5000 && event == null) {
Thread.sleep(10);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_MODIFIED));
}
assertTrue("No events sent", events.size() != 0);
assertNotNull("No file modified event: " + events, event);
assertEquals("Wrong target file for event (old)", file, event.getFile());
}
private void delete(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i=0;i < files.length;i++) {
delete(files[i]);
}
}
file.delete();
}
private File createSubdir(File dir, String name) throws IOException {
File f = File.createTempFile(name, ".tmp", dir);
f.delete();
f.mkdirs();
return f;
}
public void testMultipleWatches() throws Exception {
if (!Platform.isWindows()) return;
File subdir1 = createSubdir(tmpdir, "sub1");
File subdir2 = createSubdir(tmpdir, "sub2");
try {
monitor.addWatch(subdir1);
monitor.addWatch(subdir2);
// trigger change in dir 1
File file = File.createTempFile(getName(), ".tmp", subdir1);
FileEvent event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 5000 && event == null) {
Thread.sleep(10);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
}
assertTrue("No events sent", events.size() != 0);
assertNotNull("No creation event: " + events, event);
assertEquals("Wrong target file for event", file, event.getFile());
events.clear();
// trigger change in dir 2
file = File.createTempFile(getName(), ".tmp", subdir2);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 5000 && event == null) {
Thread.sleep(10);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
}
assertTrue("No events sent", events.size() != 0);
assertNotNull("No creation event: " + events, event);
assertEquals("Wrong target file for event", file, event.getFile());
+ events.clear();
// trigger change in dir 1
file = File.createTempFile(getName(), ".tmp", subdir1);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 5000 && event == null) {
Thread.sleep(10);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
}
assertTrue("No events sent", events.size() != 0);
assertNotNull("No creation event: " + events, event);
assertEquals("Wrong target file for event", file, event.getFile());
+ events.clear();
}
finally {
delete(subdir1);
delete(subdir2);
}
}
public static void main(String[] args) {
junit.textui.TestRunner.run(FileMonitorTest.class);
}
}
| false | true | public void testMultipleWatches() throws Exception {
if (!Platform.isWindows()) return;
File subdir1 = createSubdir(tmpdir, "sub1");
File subdir2 = createSubdir(tmpdir, "sub2");
try {
monitor.addWatch(subdir1);
monitor.addWatch(subdir2);
// trigger change in dir 1
File file = File.createTempFile(getName(), ".tmp", subdir1);
FileEvent event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 5000 && event == null) {
Thread.sleep(10);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
}
assertTrue("No events sent", events.size() != 0);
assertNotNull("No creation event: " + events, event);
assertEquals("Wrong target file for event", file, event.getFile());
events.clear();
// trigger change in dir 2
file = File.createTempFile(getName(), ".tmp", subdir2);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 5000 && event == null) {
Thread.sleep(10);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
}
assertTrue("No events sent", events.size() != 0);
assertNotNull("No creation event: " + events, event);
assertEquals("Wrong target file for event", file, event.getFile());
// trigger change in dir 1
file = File.createTempFile(getName(), ".tmp", subdir1);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 5000 && event == null) {
Thread.sleep(10);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
}
assertTrue("No events sent", events.size() != 0);
assertNotNull("No creation event: " + events, event);
assertEquals("Wrong target file for event", file, event.getFile());
}
finally {
delete(subdir1);
delete(subdir2);
}
}
| public void testMultipleWatches() throws Exception {
if (!Platform.isWindows()) return;
File subdir1 = createSubdir(tmpdir, "sub1");
File subdir2 = createSubdir(tmpdir, "sub2");
try {
monitor.addWatch(subdir1);
monitor.addWatch(subdir2);
// trigger change in dir 1
File file = File.createTempFile(getName(), ".tmp", subdir1);
FileEvent event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 5000 && event == null) {
Thread.sleep(10);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
}
assertTrue("No events sent", events.size() != 0);
assertNotNull("No creation event: " + events, event);
assertEquals("Wrong target file for event", file, event.getFile());
events.clear();
// trigger change in dir 2
file = File.createTempFile(getName(), ".tmp", subdir2);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 5000 && event == null) {
Thread.sleep(10);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
}
assertTrue("No events sent", events.size() != 0);
assertNotNull("No creation event: " + events, event);
assertEquals("Wrong target file for event", file, event.getFile());
events.clear();
// trigger change in dir 1
file = File.createTempFile(getName(), ".tmp", subdir1);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 5000 && event == null) {
Thread.sleep(10);
event = (FileEvent)events.get(new Integer(FileMonitor.FILE_CREATED));
}
assertTrue("No events sent", events.size() != 0);
assertNotNull("No creation event: " + events, event);
assertEquals("Wrong target file for event", file, event.getFile());
events.clear();
}
finally {
delete(subdir1);
delete(subdir2);
}
}
|
diff --git a/src/org/proofpad/IdeDocument.java b/src/org/proofpad/IdeDocument.java
index 59c62b6..f2caec1 100755
--- a/src/org/proofpad/IdeDocument.java
+++ b/src/org/proofpad/IdeDocument.java
@@ -1,148 +1,148 @@
package org.proofpad;
import java.util.Stack;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import org.fife.ui.rsyntaxtextarea.RSyntaxDocument;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rsyntaxtextarea.Token;
public class IdeDocument extends RSyntaxDocument implements Document {
private static final long serialVersionUID = 7048788640273203918L;
private ProofBar pb;
class IndentToken {
public final String name;
public final int offset;
public final int type;
public int params = 0;
public IndentToken parent;
public IndentToken(String name, int offset, int type, IndentToken parent) {
this.name = name;
this.offset = offset;
this.type = type;
this.parent = parent;
}
@Override
public String toString() {
return "<" + name + ", " + offset + ", " + params + ">";
}
}
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
// Auto indentation
if (str.endsWith("\n")) {
boolean waitingForName = false;
Stack<IndentToken> s = new Stack<IndentToken>();
int lineBeginOffset = 0;
Token token = null;
int lineIndentLevel = -1;
IndentToken top = null;
for (int i = 0; i < lineCount(); i++) {
token = getTokenListForLine(i);
lineBeginOffset = token.offset;
while (token != null && token.offset != -1 && offs > token.offset) {
top = s.empty() ? null : s.peek();
if (token.offset == lineBeginOffset && token.isWhitespace()) {
lineIndentLevel = token.textCount;
}
if (token.isSingleChar('(')) {
if (waitingForName) {
s.push(new IndentToken(null, token.offset - lineBeginOffset, -1, top));
}
waitingForName = true;
} else if (token.isSingleChar(')')) {
if (!s.empty()) s.pop();
if (s.size() > 0) s.peek().params++;
} else if (!token.isWhitespace() && !token.isComment()) {
if (s.size() > 0) s.peek().params++;
}
if (waitingForName && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2)) {
s.push(new IndentToken(token.getLexeme(), token.offset - lineBeginOffset, token.type, top));
waitingForName = false;
lineIndentLevel = -1;
}
token = token.getNextToken();
}
}
if (waitingForName && token != null) {
s.push(new IndentToken(null, token.offset - lineBeginOffset, -1, top));
}
if (s.size() > 0) {
IndentToken it = s.peek();
int offset = it.offset;
int indentLevel;
boolean important = false;
if (it.type == -1) {
// Last token is open parenthesis
if (it.params == 0 || waitingForName) {
indentLevel = offset + 1;
} else {
indentLevel = offset - 1;
}
} else if (it.name.equalsIgnoreCase("let") || it.name.equalsIgnoreCase("let*")) {
if (it.params >= 2) {
indentLevel = offset + 1;
} else {
indentLevel = offset + it.name.length();
}
} else if (it.name.equalsIgnoreCase("mv-let")) {
if (it.params >= 3) { // FIXME: parenthesized param getting double counted?
indentLevel = offset + 1;
} else {
indentLevel = offset + it.name.length();
}
- } else if (it.parent != null && it.parent.name.equalsIgnoreCase("defproperty") &&
+ } else if (it.parent != null && it.parent.name != null && it.parent.name.equalsIgnoreCase("defproperty") &&
it.parent.params == 2) {
indentLevel = offset - 1;
} else if (it.name.equalsIgnoreCase("defproperty")) {
if (it.params == 3) {
important = true;
}
indentLevel = offset + 1;
} else if (it.type == Token.RESERVED_WORD_2) {
// Events
indentLevel = offset + 1;
} else if (it.params == 0) {
indentLevel = offset - 1;
} else {
// Regular functions
indentLevel = offset + it.name.length();
}
if (lineIndentLevel != -1 && !important) {
indentLevel = lineIndentLevel - 1;
}
for (int j = 0; j < indentLevel + 1; j++) {
str += " ";
}
}
}
if (pb == null || offs > pb.getReadOnlyIndex()) {
if (pb != null && pb.getReadOnlyIndex() >= 0 && offs == pb.getReadOnlyIndex() + 1 && !str.startsWith("\n")) {
str = '\n' + str;
}
super.insertString(offs, str, a);
} else {
if (pb != null) pb.flashAt(offs);
}
}
@Override
public void remove(int offs, int len) throws BadLocationException {
if (pb == null || offs > pb.getReadOnlyIndex()) {
super.remove(offs, len);
} else {
if (pb != null) pb.flashAt(offs);
}
}
public IdeDocument(ProofBar pb) {
super(SyntaxConstants.SYNTAX_STYLE_LISP);
this.pb = pb;
setSyntaxStyle(new Acl2TokenMaker());
}
public int lineCount() {
return getDefaultRootElement().getElementCount();
}
}
| true | true | public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
// Auto indentation
if (str.endsWith("\n")) {
boolean waitingForName = false;
Stack<IndentToken> s = new Stack<IndentToken>();
int lineBeginOffset = 0;
Token token = null;
int lineIndentLevel = -1;
IndentToken top = null;
for (int i = 0; i < lineCount(); i++) {
token = getTokenListForLine(i);
lineBeginOffset = token.offset;
while (token != null && token.offset != -1 && offs > token.offset) {
top = s.empty() ? null : s.peek();
if (token.offset == lineBeginOffset && token.isWhitespace()) {
lineIndentLevel = token.textCount;
}
if (token.isSingleChar('(')) {
if (waitingForName) {
s.push(new IndentToken(null, token.offset - lineBeginOffset, -1, top));
}
waitingForName = true;
} else if (token.isSingleChar(')')) {
if (!s.empty()) s.pop();
if (s.size() > 0) s.peek().params++;
} else if (!token.isWhitespace() && !token.isComment()) {
if (s.size() > 0) s.peek().params++;
}
if (waitingForName && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2)) {
s.push(new IndentToken(token.getLexeme(), token.offset - lineBeginOffset, token.type, top));
waitingForName = false;
lineIndentLevel = -1;
}
token = token.getNextToken();
}
}
if (waitingForName && token != null) {
s.push(new IndentToken(null, token.offset - lineBeginOffset, -1, top));
}
if (s.size() > 0) {
IndentToken it = s.peek();
int offset = it.offset;
int indentLevel;
boolean important = false;
if (it.type == -1) {
// Last token is open parenthesis
if (it.params == 0 || waitingForName) {
indentLevel = offset + 1;
} else {
indentLevel = offset - 1;
}
} else if (it.name.equalsIgnoreCase("let") || it.name.equalsIgnoreCase("let*")) {
if (it.params >= 2) {
indentLevel = offset + 1;
} else {
indentLevel = offset + it.name.length();
}
} else if (it.name.equalsIgnoreCase("mv-let")) {
if (it.params >= 3) { // FIXME: parenthesized param getting double counted?
indentLevel = offset + 1;
} else {
indentLevel = offset + it.name.length();
}
} else if (it.parent != null && it.parent.name.equalsIgnoreCase("defproperty") &&
it.parent.params == 2) {
indentLevel = offset - 1;
} else if (it.name.equalsIgnoreCase("defproperty")) {
if (it.params == 3) {
important = true;
}
indentLevel = offset + 1;
} else if (it.type == Token.RESERVED_WORD_2) {
// Events
indentLevel = offset + 1;
} else if (it.params == 0) {
indentLevel = offset - 1;
} else {
// Regular functions
indentLevel = offset + it.name.length();
}
if (lineIndentLevel != -1 && !important) {
indentLevel = lineIndentLevel - 1;
}
for (int j = 0; j < indentLevel + 1; j++) {
str += " ";
}
}
}
if (pb == null || offs > pb.getReadOnlyIndex()) {
if (pb != null && pb.getReadOnlyIndex() >= 0 && offs == pb.getReadOnlyIndex() + 1 && !str.startsWith("\n")) {
str = '\n' + str;
}
super.insertString(offs, str, a);
} else {
if (pb != null) pb.flashAt(offs);
}
}
| public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
// Auto indentation
if (str.endsWith("\n")) {
boolean waitingForName = false;
Stack<IndentToken> s = new Stack<IndentToken>();
int lineBeginOffset = 0;
Token token = null;
int lineIndentLevel = -1;
IndentToken top = null;
for (int i = 0; i < lineCount(); i++) {
token = getTokenListForLine(i);
lineBeginOffset = token.offset;
while (token != null && token.offset != -1 && offs > token.offset) {
top = s.empty() ? null : s.peek();
if (token.offset == lineBeginOffset && token.isWhitespace()) {
lineIndentLevel = token.textCount;
}
if (token.isSingleChar('(')) {
if (waitingForName) {
s.push(new IndentToken(null, token.offset - lineBeginOffset, -1, top));
}
waitingForName = true;
} else if (token.isSingleChar(')')) {
if (!s.empty()) s.pop();
if (s.size() > 0) s.peek().params++;
} else if (!token.isWhitespace() && !token.isComment()) {
if (s.size() > 0) s.peek().params++;
}
if (waitingForName && (token.type == Token.IDENTIFIER ||
token.type == Token.RESERVED_WORD ||
token.type == Token.RESERVED_WORD_2)) {
s.push(new IndentToken(token.getLexeme(), token.offset - lineBeginOffset, token.type, top));
waitingForName = false;
lineIndentLevel = -1;
}
token = token.getNextToken();
}
}
if (waitingForName && token != null) {
s.push(new IndentToken(null, token.offset - lineBeginOffset, -1, top));
}
if (s.size() > 0) {
IndentToken it = s.peek();
int offset = it.offset;
int indentLevel;
boolean important = false;
if (it.type == -1) {
// Last token is open parenthesis
if (it.params == 0 || waitingForName) {
indentLevel = offset + 1;
} else {
indentLevel = offset - 1;
}
} else if (it.name.equalsIgnoreCase("let") || it.name.equalsIgnoreCase("let*")) {
if (it.params >= 2) {
indentLevel = offset + 1;
} else {
indentLevel = offset + it.name.length();
}
} else if (it.name.equalsIgnoreCase("mv-let")) {
if (it.params >= 3) { // FIXME: parenthesized param getting double counted?
indentLevel = offset + 1;
} else {
indentLevel = offset + it.name.length();
}
} else if (it.parent != null && it.parent.name != null && it.parent.name.equalsIgnoreCase("defproperty") &&
it.parent.params == 2) {
indentLevel = offset - 1;
} else if (it.name.equalsIgnoreCase("defproperty")) {
if (it.params == 3) {
important = true;
}
indentLevel = offset + 1;
} else if (it.type == Token.RESERVED_WORD_2) {
// Events
indentLevel = offset + 1;
} else if (it.params == 0) {
indentLevel = offset - 1;
} else {
// Regular functions
indentLevel = offset + it.name.length();
}
if (lineIndentLevel != -1 && !important) {
indentLevel = lineIndentLevel - 1;
}
for (int j = 0; j < indentLevel + 1; j++) {
str += " ";
}
}
}
if (pb == null || offs > pb.getReadOnlyIndex()) {
if (pb != null && pb.getReadOnlyIndex() >= 0 && offs == pb.getReadOnlyIndex() + 1 && !str.startsWith("\n")) {
str = '\n' + str;
}
super.insertString(offs, str, a);
} else {
if (pb != null) pb.flashAt(offs);
}
}
|
diff --git a/src/de/bdh/ks/KrimBlockName.java b/src/de/bdh/ks/KrimBlockName.java
index c3a0706..409d85c 100644
--- a/src/de/bdh/ks/KrimBlockName.java
+++ b/src/de/bdh/ks/KrimBlockName.java
@@ -1,669 +1,669 @@
package de.bdh.ks;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.inventory.ItemStack;
public class KrimBlockName
{
public static HashMap<String,String> names = new HashMap<String,String>();
public KrimBlockName()
{
//INIT VALUES
KrimBlockName.put("air", "0");
KrimBlockName.put("stone","1");
KrimBlockName.put("grassblock","2");
KrimBlockName.put("dirt","3");
KrimBlockName.put("cobblestone","4");
KrimBlockName.put("woodenplanks","5");
KrimBlockName.put("pinewoodenplanks","5:1");
KrimBlockName.put("birchwoodenplanks","5:2");
KrimBlockName.put("djunglewoodenplanks","5:3");
KrimBlockName.put("sapling","6");
- KrimBlockName.put("birchsapling","6:1");
- KrimBlockName.put("pinesapling","6:2");
+ KrimBlockName.put("birchsapling","6:2");
+ KrimBlockName.put("pinesapling","6:1");
KrimBlockName.put("djunglesapling","6:3");
KrimBlockName.put("bedrock","7");
KrimBlockName.put("watersource","8");
KrimBlockName.put("waterstill","9");
KrimBlockName.put("lavasource","10");
KrimBlockName.put("lavastill","11");
KrimBlockName.put("sand","12");
KrimBlockName.put("gravel","13");
KrimBlockName.put("goldore","14");
KrimBlockName.put("ironore","15");
KrimBlockName.put("coalore","16");
KrimBlockName.put("wood","17");
- KrimBlockName.put("birchwood","17:1");
- KrimBlockName.put("pinewood","17:2");
+ KrimBlockName.put("birchwood","17:2");
+ KrimBlockName.put("pinewood","17:1");
KrimBlockName.put("djunglewood","17:3");
KrimBlockName.put("leaves","18");
- KrimBlockName.put("birchleaves","18:6");
+ KrimBlockName.put("birchleaves","18:5");
KrimBlockName.put("oakleaves","18:4");
- KrimBlockName.put("spruceleaves","18:5");
+ KrimBlockName.put("spruceleaves","18:6");
KrimBlockName.put("djungleleaves","18:7");
KrimBlockName.put("sponge","19");
KrimBlockName.put("glass","20");
KrimBlockName.put("lapislazuliore","21");
KrimBlockName.put("lapislazuliblock","22");
KrimBlockName.put("dispenser","23");
KrimBlockName.put("sandstone","24");
KrimBlockName.put("chiseledsandstone","24:1");
KrimBlockName.put("smoothsandstone","24:2");
KrimBlockName.put("noteblock","25");
KrimBlockName.put("poweredtrack","27");
KrimBlockName.put("detectortrack","28");
KrimBlockName.put("stickypiston","29");
KrimBlockName.put("cobweb","30");
KrimBlockName.put("grass","31:1");
KrimBlockName.put("fern","31:2");
KrimBlockName.put("deadbush","32");
KrimBlockName.put("piston","33");
KrimBlockName.put("wool","35");
KrimBlockName.put("orangewool","35:1");
KrimBlockName.put("magentawool","35:2");
KrimBlockName.put("lightbluewool","35:3");
KrimBlockName.put("yellowwool","35:4");
KrimBlockName.put("limewool","35:5");
KrimBlockName.put("pinkwool","35:6");
KrimBlockName.put("graywool","35:7");
KrimBlockName.put("lightgraywool","35:8");
KrimBlockName.put("cyanwool","35:9");
KrimBlockName.put("purplewool","35:10");
KrimBlockName.put("bluewool","35:11");
KrimBlockName.put("brownwool","35:12");
KrimBlockName.put("greenwool","35:13");
KrimBlockName.put("redwool","35:14");
KrimBlockName.put("blackwool","35:15");
KrimBlockName.put("flower","37");
KrimBlockName.put("rose","38");
KrimBlockName.put("brownmushroom","39");
KrimBlockName.put("redmushroom","40");
KrimBlockName.put("blockofgold","41");
KrimBlockName.put("goldblock","41");
KrimBlockName.put("blockofiron","42");
KrimBlockName.put("ironblock","42");
KrimBlockName.put("doubleslab","43");
KrimBlockName.put("doublesandstoneslab","43:1");
KrimBlockName.put("doublewoodenslab","43:2");
KrimBlockName.put("doublecobbelstoneslab","43:3");
KrimBlockName.put("doublebricksslab","43:4");
KrimBlockName.put("doublestonebricksslab","43:5");
KrimBlockName.put("stoneslab","44");
KrimBlockName.put("sandstoneslab","44:1");
KrimBlockName.put("woodenslab","44:2");
KrimBlockName.put("coobelstoneslab","44:3");
KrimBlockName.put("bricksslab","44:4");
KrimBlockName.put("stonebricksslab","44:5");
KrimBlockName.put("bricks","45");
KrimBlockName.put("tnt","46");
KrimBlockName.put("bookshelf","47");
KrimBlockName.put("mossstone","48");
KrimBlockName.put("obsidian","49");
KrimBlockName.put("torch","50");
KrimBlockName.put("fire","51");
KrimBlockName.put("monsterspawner(creeper)","52:50");
KrimBlockName.put("monsterspawner(skeleton)","52:51");
KrimBlockName.put("monsterspawner(spider)","52:52");
KrimBlockName.put("monsterspawner(giant)","52:53");
KrimBlockName.put("monsterspawner(zombie)","52:54");
KrimBlockName.put("monsterspawner(slime)","52:55");
KrimBlockName.put("monsterspawner(ghast)","52:56");
KrimBlockName.put("monsterspawner(pigzombie)","52:57");
KrimBlockName.put("monsterspawner(enderman)","52:58");
KrimBlockName.put("monsterspawner(cavespider)","52:59");
KrimBlockName.put("monsterspawner(silverfish)","52:60");
KrimBlockName.put("monsterspawner(blaze)","52:61");
KrimBlockName.put("monsterspawner(lavaslime)","52:62");
KrimBlockName.put("monsterspawner(pig)","52:90");
KrimBlockName.put("monsterspawner(sheep)","52:91");
KrimBlockName.put("monsterspawner(cow)","52:92");
KrimBlockName.put("monsterspawner(chicken)","52:93");
KrimBlockName.put("monsterspawner(squid)","52:94");
KrimBlockName.put("monsterspawner(wolf)","52:95");
KrimBlockName.put("monsterspawner(mushroomcow)","52:96");
KrimBlockName.put("monsterspawner(snowman)","52:97");
KrimBlockName.put("monsterspawner(ozelot)","52:98");
KrimBlockName.put("monsterspawner(irongolem)","52:99");
KrimBlockName.put("monsterspawner(villager)","52:120");
KrimBlockName.put("monsterspawner(horse)","52:220");
KrimBlockName.put("monsterspawner(ogre)","52:221");
KrimBlockName.put("monsterspawner(fireogre)","52:222");
KrimBlockName.put("monsterspawner(caveogre)","52:223");
KrimBlockName.put("monsterspawner(boar)","52:224");
KrimBlockName.put("monsterspawner(bear)","52:225");
KrimBlockName.put("monsterspawner(duck)","52:226");
KrimBlockName.put("monsterspawner(bigcat)","52:227");
KrimBlockName.put("monsterspawner(deer)","52:228");
KrimBlockName.put("monsterspawner(wildwolf)","52:229");
KrimBlockName.put("monsterspawner(polarbear)","52:230");
KrimBlockName.put("monsterspawner(wraith)","52:231");
KrimBlockName.put("monsterspawner(flamewraith)","52:232");
KrimBlockName.put("monsterspawner(bunny)","52:233");
KrimBlockName.put("monsterspawner(bird)","52:234");
KrimBlockName.put("monsterspawner(fox)","52:235");
KrimBlockName.put("monsterspawner(werewolf)","52:236");
KrimBlockName.put("monsterspawner(shark)","52:237");
KrimBlockName.put("monsterspawner(dolphin)","52:238");
KrimBlockName.put("monsterspawner(fishy)","52:239");
KrimBlockName.put("monsterspawner(kitty)","52:240");
KrimBlockName.put("monsterspawner(kittybed)","52:241");
KrimBlockName.put("monsterspawner(litterbox)","52:242");
KrimBlockName.put("monsterspawner(rat)","52:243");
KrimBlockName.put("monsterspawner(mouse)","52:244");
KrimBlockName.put("monsterspawner(hellrat)","52:245");
KrimBlockName.put("monsterspawner(scorpion)","52:246");
KrimBlockName.put("monsterspawner(turtle)","52:247");
KrimBlockName.put("monsterspawner(crocodile)","52:248");
KrimBlockName.put("monsterspawner(ray)","52:249");
KrimBlockName.put("monsterspawner(jellyfish)","52:250");
KrimBlockName.put("monsterspawner(goat)","52:251");
KrimBlockName.put("monsterspawner(snake)","52:252");
KrimBlockName.put("monsterspawner(mocegg)","52:253");
KrimBlockName.put("monsterspawner(fishbowl)","52:254");
KrimBlockName.put("monsterspawner(ostrich)","52:255");
KrimBlockName.put("woodenstairs","53");
KrimBlockName.put("chest","54");
KrimBlockName.put("diamondore","56");
KrimBlockName.put("blockofdiamond","57");
KrimBlockName.put("diamondblock","57");
KrimBlockName.put("craftingtable","58");
KrimBlockName.put("farmland","60");
KrimBlockName.put("furnace","61");
KrimBlockName.put("furnace_on","62");
KrimBlockName.put("ladder","65");
KrimBlockName.put("track","66");
KrimBlockName.put("cobblestonestairs","67");
KrimBlockName.put("lever","69");
KrimBlockName.put("pressureplate","70");
KrimBlockName.put("irondoorblock","71");
KrimBlockName.put("woodenpressureplate","72");
KrimBlockName.put("redstoneore","73");
KrimBlockName.put("redstonetorch_glow","74");
KrimBlockName.put("redstonetorch_off","75");
KrimBlockName.put("redstonetorch","76");
KrimBlockName.put("button","77");
KrimBlockName.put("snow","78");
KrimBlockName.put("ice","79");
KrimBlockName.put("snow","80");
KrimBlockName.put("cactus","81");
KrimBlockName.put("clay","82");
KrimBlockName.put("jukebox","84");
KrimBlockName.put("fence","85");
KrimBlockName.put("pumpkin","86");
KrimBlockName.put("netherrack","87");
KrimBlockName.put("soulsand","88");
KrimBlockName.put("glowstone","89");
KrimBlockName.put("portal","90");
KrimBlockName.put("jackolantern","91");
KrimBlockName.put("cake","92");
KrimBlockName.put("lockedchest","95");
KrimBlockName.put("trapdoor","96");
KrimBlockName.put("silverfishstone","97");
KrimBlockName.put("stonebricks","98");
KrimBlockName.put("mossystonebricks","98:1");
KrimBlockName.put("crackedstonebricks","98:2");
KrimBlockName.put("chiseledstonebricks","98:3");
KrimBlockName.put("hugebrownmushroom","99");
KrimBlockName.put("hugeredmushroom","100");
KrimBlockName.put("ironbars","101");
KrimBlockName.put("glasspanel","102");
KrimBlockName.put("melon","103");
KrimBlockName.put("vines","106");
KrimBlockName.put("fencegate","107");
KrimBlockName.put("brickstairs","108");
KrimBlockName.put("stonebricksatirs","109");
KrimBlockName.put("mycelium","110");
KrimBlockName.put("lilypad","111");
KrimBlockName.put("netherbrick","112");
KrimBlockName.put("netherbrickfence","113");
KrimBlockName.put("netherbrickstairs","114");
KrimBlockName.put("netherwart","115");
KrimBlockName.put("enchantmenttable","116");
KrimBlockName.put("endportal","119");
KrimBlockName.put("endportalframe","120");
KrimBlockName.put("whitestone","121");
KrimBlockName.put("endstone","121:1");
KrimBlockName.put("dragonegg","122");
KrimBlockName.put("redstonelamp_off","123");
KrimBlockName.put("redstonelamp","124");
KrimBlockName.put("Oakwoodslab","126");
KrimBlockName.put("Sprucewoodslab","126:1");
KrimBlockName.put("Birchwoodslab","126:2");
KrimBlockName.put("Junglewoodslab","126:3");
KrimBlockName.put("Sandstonestairs","128");
KrimBlockName.put("Emeraldore","129");
KrimBlockName.put("Tripwirehook","131");
KrimBlockName.put("emeraldblock","133");
KrimBlockName.put("Sprucewoodstairs","134");
KrimBlockName.put("Birchwoodstairs","135");
KrimBlockName.put("Junglewoodstairs","136");
KrimBlockName.put("Beacon","138");
KrimBlockName.put("Cobblestonewall","139");
KrimBlockName.put("Mossycobblestonewall","139:1");
KrimBlockName.put("Woodenbutton","143");
KrimBlockName.put("Anvil","145");
KrimBlockName.put("Anvil(Damaged)","145:1");
KrimBlockName.put("Anvil(VeryDamaged)","145:2");
KrimBlockName.put("TrappedChest","146");
KrimBlockName.put("WeightedPressurePlate(Light)","147");
KrimBlockName.put("WeightedPressurePlate(Heavy)","148");
KrimBlockName.put("RedstoneComparator(Dis)","149");
KrimBlockName.put("RedstoneComparator(Act)","150");
KrimBlockName.put("DaylightSensor","151");
KrimBlockName.put("BlockofRedstone","152");
KrimBlockName.put("Redstoneblock","152");
KrimBlockName.put("Netherquartzore","153");
KrimBlockName.put("Hopper","154");
KrimBlockName.put("BlockofQuartz","155");
KrimBlockName.put("Quartzstairs","156");
KrimBlockName.put("ActivatorRail","157");
KrimBlockName.put("Dropper","158");
KrimBlockName.put("ironpickaxe","257");
KrimBlockName.put("ironaxe","258");
KrimBlockName.put("flintandsteel","259");
KrimBlockName.put("apple","260");
KrimBlockName.put("bow","261");
KrimBlockName.put("arrow","262");
KrimBlockName.put("coal","263");
KrimBlockName.put("charcoal","263:1");
KrimBlockName.put("diamond","264");
KrimBlockName.put("ironingot","265");
KrimBlockName.put("goldingot","266");
KrimBlockName.put("ironsword","267");
KrimBlockName.put("woodensword","268");
KrimBlockName.put("woodenshovel","269");
KrimBlockName.put("woodenpickaxe","270");
KrimBlockName.put("woodenaxe","271");
KrimBlockName.put("stonesword","272");
KrimBlockName.put("stoneshovel","273");
KrimBlockName.put("stonepickaxe","274");
KrimBlockName.put("stoneaxe","275");
KrimBlockName.put("diamondsword","276");
KrimBlockName.put("diamondspade","277");
KrimBlockName.put("diamondpickaxe","278");
KrimBlockName.put("diamondaxe","279");
KrimBlockName.put("stick","280");
KrimBlockName.put("bowl","281");
KrimBlockName.put("mushroomsoup","282");
KrimBlockName.put("goldensword","283");
KrimBlockName.put("goldenspade","284");
KrimBlockName.put("goldenpickaxe","285");
KrimBlockName.put("goldenaxe","286");
KrimBlockName.put("string","287");
KrimBlockName.put("feather","288");
KrimBlockName.put("gunpowder","289");
KrimBlockName.put("woodenhoe","290");
KrimBlockName.put("stonehoe","291");
KrimBlockName.put("ironhoe","292");
KrimBlockName.put("diamondhoe","293");
KrimBlockName.put("goldenmhoe","294");
KrimBlockName.put("seeds","295");
KrimBlockName.put("wheat","296");
KrimBlockName.put("bread","297");
KrimBlockName.put("leathercap","298");
KrimBlockName.put("leathertunic","299");
KrimBlockName.put("leathertrousers","300");
KrimBlockName.put("leatherboots","301");
KrimBlockName.put("chainmailhelmet","302");
KrimBlockName.put("chainchestplate","303");
KrimBlockName.put("chainmailleggings","304");
KrimBlockName.put("chainmailboots","305");
KrimBlockName.put("ironhelmet","306");
KrimBlockName.put("ironchestplate","307");
KrimBlockName.put("ironleggings","308");
KrimBlockName.put("ironboots","309");
KrimBlockName.put("diamondhelmet","310");
KrimBlockName.put("diamondchestplate","311");
KrimBlockName.put("diamondleggings","312");
KrimBlockName.put("industrialdiamond","313");
KrimBlockName.put("goldenhelmet","314");
KrimBlockName.put("goldenchestplate","315");
KrimBlockName.put("goldenleggings","316");
KrimBlockName.put("goldenboots","317");
KrimBlockName.put("flint","318");
KrimBlockName.put("rawporkchop","319");
KrimBlockName.put("cookedporkchop","320");
KrimBlockName.put("painting","321");
KrimBlockName.put("goldenapple","322");
KrimBlockName.put("sign","323");
KrimBlockName.put("woodendoor","324");
KrimBlockName.put("bucket","325");
KrimBlockName.put("bucketofwater","326");
KrimBlockName.put("bucketoflava","327");
KrimBlockName.put("minecart","328");
KrimBlockName.put("saddle","329");
KrimBlockName.put("irondoor","330");
KrimBlockName.put("redstone","331");
KrimBlockName.put("snowball","332");
KrimBlockName.put("boat","333");
KrimBlockName.put("leather","334");
KrimBlockName.put("bucketofmilk","335");
KrimBlockName.put("brick","336");
KrimBlockName.put("clay","337");
KrimBlockName.put("sugarcanes","338");
KrimBlockName.put("paper","339");
KrimBlockName.put("book","340");
KrimBlockName.put("slimeball","341");
KrimBlockName.put("chestcart","342");
KrimBlockName.put("furnacecart","343");
KrimBlockName.put("egg","344");
KrimBlockName.put("compass","345");
KrimBlockName.put("fishingrod","346");
KrimBlockName.put("watch","347");
KrimBlockName.put("glowstonedust","348");
KrimBlockName.put("rawfish","349");
KrimBlockName.put("cookedfish","350");
KrimBlockName.put("inksac","351");
KrimBlockName.put("rosered","351:1");
KrimBlockName.put("cactusgreen","351:2");
KrimBlockName.put("cocoabeans","351:3");
KrimBlockName.put("lapislazuli","351:4");
KrimBlockName.put("purpledye","351:5");
KrimBlockName.put("cyandye","351:6");
KrimBlockName.put("lightgreydye","351:7");
KrimBlockName.put("greydye","351:8");
KrimBlockName.put("pinkdye","351:9");
KrimBlockName.put("limegreendye","351:10");
KrimBlockName.put("dandelionyellow","351:11");
KrimBlockName.put("lightbluedye","351:12");
KrimBlockName.put("magentadye","351:13");
KrimBlockName.put("orangedye","351:14");
KrimBlockName.put("bonemeal","351:15");
KrimBlockName.put("bone","352");
KrimBlockName.put("sugar","353");
KrimBlockName.put("cake","354");
KrimBlockName.put("bed","355");
KrimBlockName.put("redstonerepeater","356");
KrimBlockName.put("cookie","357");
KrimBlockName.put("map","358");
KrimBlockName.put("shears","359");
KrimBlockName.put("melon","360");
KrimBlockName.put("pumpkinseeds","361");
KrimBlockName.put("melonseeds","362");
KrimBlockName.put("rawbeef","363");
KrimBlockName.put("steak","364");
KrimBlockName.put("rawchicken","365");
KrimBlockName.put("cookedchicken","366");
KrimBlockName.put("rottenflesh","367");
KrimBlockName.put("ender pearl","368");
KrimBlockName.put("blazerod","369");
KrimBlockName.put("ghasttear","370");
KrimBlockName.put("goldennugget","371");
KrimBlockName.put("netherwart","372");
KrimBlockName.put("waterbottle","373");
KrimBlockName.put("awkwardpotion","373:16");
KrimBlockName.put("thickpotion","373:32");
KrimBlockName.put("mundanepotion","373:64");
KrimBlockName.put("Regeneration Potion (0:45)","373:8193");
KrimBlockName.put("Swiftness Potion (3:00)","373:8194");
KrimBlockName.put("Fire Resistance Potion (3:00)","373:8195");
KrimBlockName.put("Poison Potion (0:45)","373:8196");
KrimBlockName.put("Healing Potion","373:8197");
KrimBlockName.put("Weakness Potion (1:30)","373:8200");
KrimBlockName.put("Strength Potion (3:00)","373:8201");
KrimBlockName.put("Slowness Potion (1:30)","373:8202");
KrimBlockName.put("Harming Potion","373:8204");
KrimBlockName.put("Regeneration Potion II (0:22)","373:8225");
KrimBlockName.put("Swiftness Potion II (1:30)","373:8226");
KrimBlockName.put("Poison Potion II (0:22)","373:8228");
KrimBlockName.put("Healing Potion II","373:8229");
KrimBlockName.put("Strength Potion II (1:30)","373:8233");
KrimBlockName.put("Harming Potion II","373:8236");
KrimBlockName.put("Regeneration Potion (2:00)","373:8257");
KrimBlockName.put("Swiftness Potion (8:00)","373:8258");
KrimBlockName.put("Fire Resistance Potion (8:00)","373:8259");
KrimBlockName.put("Poison Potion (2:00)","373:8260");
KrimBlockName.put("Weakness Potion (4:00)","373:8264");
KrimBlockName.put("Strength Potion (8:00)","373:8265");
KrimBlockName.put("Slowness Potion (4:00)","373:8266");
KrimBlockName.put("Fire Resistance Splash (2:15)","373:16378");
KrimBlockName.put("Regeneration Splash (0:33)","373:16385");
KrimBlockName.put("Swiftness Splash (2:15)","373:16386");
KrimBlockName.put("Poison Splash (0:33)","373:16388");
KrimBlockName.put("Healing Splash","373:16389");
KrimBlockName.put("Weakness Splash (1:07)","373:16392");
KrimBlockName.put("Strength Splash (2:15)","373:16393");
KrimBlockName.put("Slowness Splash (1:07)","373:16394");
KrimBlockName.put("Harming Splash","373:16396");
KrimBlockName.put("Swiftness Splash II (1:07)","373:16418");
KrimBlockName.put("Poison Splash II (0:16)","373:16420");
KrimBlockName.put("Healing Splash II","373:16421");
KrimBlockName.put("Strength Splash II (1:07)","373:16425");
KrimBlockName.put("Harming Splash II","373:16428");
KrimBlockName.put("Regeneration Splash (1:30)","373:16449");
KrimBlockName.put("Swiftness Splash (6:00)","373:16450");
KrimBlockName.put("Fire Resistance Splash (6:00)","373:16451");
KrimBlockName.put("Poison Splash (1:30)","373:16452");
KrimBlockName.put("Weakness Splash (3:00)","373:16456");
KrimBlockName.put("Strength Splash (6:00)","373:16457");
KrimBlockName.put("Slowness Splash (3:00)","373:16458");
KrimBlockName.put("Regeneration Splash II (0:16)","373:16471");
KrimBlockName.put("glassbottle","374");
KrimBlockName.put("spidereye","375");
KrimBlockName.put("fermentedspidereye","376");
KrimBlockName.put("blazepowder","377");
KrimBlockName.put("magmacream","378");
KrimBlockName.put("brewingstand","379");
KrimBlockName.put("cauldron","380");
KrimBlockName.put("eyeofender","381");
KrimBlockName.put("glisteringmelon","382");
KrimBlockName.put("spawncreeper","383:50");
KrimBlockName.put("spawnskeleton","383:51");
KrimBlockName.put("spawnspider","383:52");
KrimBlockName.put("spawnzombie","383:54");
KrimBlockName.put("spawnslime","383:55");
KrimBlockName.put("spawnghast","383:56");
KrimBlockName.put("spawnpigzombie","383:57");
KrimBlockName.put("spawnenderman","383:58");
KrimBlockName.put("spawncavespider","383:59");
KrimBlockName.put("spawnsilverfish","383:60");
KrimBlockName.put("spawnblaze","383:61");
KrimBlockName.put("spawnmagmacube","383:62");
KrimBlockName.put("spawnpig","383:90");
KrimBlockName.put("spawnsheep","383:91");
KrimBlockName.put("spawncow","383:92");
KrimBlockName.put("spawnchicken","383:93");
KrimBlockName.put("spawnsquid","383:94");
KrimBlockName.put("spawnwolf","383:95");
KrimBlockName.put("spawnmooshroom","383:96");
KrimBlockName.put("spawnsnowgolem","383:97");
KrimBlockName.put("spawnocelot","383:98");
KrimBlockName.put("spawnirongolem","383:99");
KrimBlockName.put("spawnvillager","383:120");
KrimBlockName.put("bottleo´enchanting","384");
KrimBlockName.put("firecharge","385");
KrimBlockName.put("bookandquill","386");
KrimBlockName.put("writtenbook","387");
KrimBlockName.put("Emerald","388");
KrimBlockName.put("Itemframe","389");
KrimBlockName.put("Flowerpot","390");
KrimBlockName.put("Carrot","391");
KrimBlockName.put("Potatoe","392");
KrimBlockName.put("Bakedpotatoe","393");
KrimBlockName.put("Poisonedpotatoe","394");
KrimBlockName.put("Emptymap","395");
KrimBlockName.put("Goldencarrot","396");
KrimBlockName.put("SkelletonSkull","397");
KrimBlockName.put("Witherhead","397:1");
KrimBlockName.put("Zombiehead","397:2");
KrimBlockName.put("Head","397:3");
KrimBlockName.put("Creeperhead","397:4");
KrimBlockName.put("Carrotonastick","398");
KrimBlockName.put("Netherstar","399");
KrimBlockName.put("Pumpkinpie","400");
KrimBlockName.put("FireRocket","401");
KrimBlockName.put("Firestar","402");
KrimBlockName.put("Enchantedbook","403");
KrimBlockName.put("RedstoneComparator","404");
KrimBlockName.put("Netherbrick","405");
KrimBlockName.put("Netherquartz","406");
KrimBlockName.put("TNTCart","407");
KrimBlockName.put("HopperCart","408");
KrimBlockName.put("Disk C418-13","2256");
KrimBlockName.put("Disk C418-Cat","2257");
KrimBlockName.put("Disk C418-Blocks","2258");
KrimBlockName.put("Disk C418-Chirp","2259");
KrimBlockName.put("Disk C418-Far","2260");
KrimBlockName.put("Disk C418-Mall","2261");
KrimBlockName.put("Disk C418-Mellohi","2262");
KrimBlockName.put("Disk C418-Stall","2263");
KrimBlockName.put("Disk C418-Strad","2264");
KrimBlockName.put("Disk C418-Ward","2265");
KrimBlockName.put("Disk 11","2266");
KrimBlockName.put("Disk C418-Wait","2267");
}
public static void put(String a,String b)
{
names.put(a.toLowerCase().trim().replace(" ", "_"), b);
}
public static void loadNames(Map<String,String> m)
{
for(Entry<?, ?> i : m.entrySet())
{
KrimBlockName.names.put(i.getKey().toString().toLowerCase().trim().replace(" ","_"),(String)i.getValue());
}
}
public static String searchName(String name)
{
name = name.toLowerCase();
for (Map.Entry<String,String> entry : KrimBlockName.names.entrySet())
{
if(entry.getKey().toLowerCase().contains(name))
return entry.getKey();
}
return "null";
}
public static String getIdByName(String name)
{
name = name.trim().toLowerCase();
if(KrimBlockName.names.get(name) != null)
return KrimBlockName.names.get(name);
else
return "-1";
}
public static String getNameById(int type, int typeid)
{
String strg = "";
strg += type;
if(typeid > 0)
strg += ":"+typeid;
return getNameById(strg);
}
public static String getNameById(String id)
{
for (Map.Entry<String,String> entry : KrimBlockName.names.entrySet())
{
if(entry.getValue().trim().equalsIgnoreCase(id.trim()))
return entry.getKey();
}
//Suche Master Block
String[] subidTmp = id.split(":");
String nid = "";
if(subidTmp.length > 1)
{
nid = subidTmp[0];
for (Map.Entry<String,String> entry : KrimBlockName.names.entrySet())
{
if(entry.getValue().trim().equalsIgnoreCase(nid.trim()))
return entry.getKey();
}
}
return ""+id;
}
public static String getNameByItemStack(ItemStack i)
{
String str = getIdByItemStack(i);
return getNameById(str);
}
public static String getIdByItemStack(ItemStack i)
{
String str = "";
str += i.getTypeId();
if(i.getDurability() > 0 && i.getType().getMaxDurability() == 0)
str += ":"+i.getDurability();
return str;
}
public static ItemStack parseName(String nam)
{
ItemStack i = new ItemStack(Material.AIR);
int n = 0;
try
{
n = Integer.parseInt(nam);
i.setTypeId(n);
} catch(NumberFormatException e)
{
}
if(n == 0)
{
try
{
if(nam.split(":").length > 1)
{
String[] sp = nam.split(":");
//Block mit ID
i.setTypeId(Integer.parseInt(sp[0]));
i.setDurability((short) Integer.parseInt(sp[1]));
} else
{
nam = KrimBlockName.getIdByName(nam);
if(nam.split(":").length > 1)
{
String[] sp = nam.split(":");
//Block mit ID
i.setTypeId(Integer.parseInt(sp[0]));
i.setDurability((short) Integer.parseInt(sp[1]));
} else
{
i.setTypeId(Integer.parseInt(nam));
}
}
} catch(Exception e)
{
return null;
}
}
return i;
}
public static String getIdByBlock(Block i)
{
String str = "";
str += i.getTypeId();
if(i.getData() > 0 && i.getType().getMaxDurability() == 0)
str += ":"+i.getData();
return str;
}
public static ItemStack getStackByBlock(Block i)
{
ItemStack s = new ItemStack(Material.AIR);
s.setType(i.getType());
if(i.getData() > 0 && i.getType().getMaxDurability() == 0)
s.setDurability(i.getData());
return s;
}
}
| false | true | public KrimBlockName()
{
//INIT VALUES
KrimBlockName.put("air", "0");
KrimBlockName.put("stone","1");
KrimBlockName.put("grassblock","2");
KrimBlockName.put("dirt","3");
KrimBlockName.put("cobblestone","4");
KrimBlockName.put("woodenplanks","5");
KrimBlockName.put("pinewoodenplanks","5:1");
KrimBlockName.put("birchwoodenplanks","5:2");
KrimBlockName.put("djunglewoodenplanks","5:3");
KrimBlockName.put("sapling","6");
KrimBlockName.put("birchsapling","6:1");
KrimBlockName.put("pinesapling","6:2");
KrimBlockName.put("djunglesapling","6:3");
KrimBlockName.put("bedrock","7");
KrimBlockName.put("watersource","8");
KrimBlockName.put("waterstill","9");
KrimBlockName.put("lavasource","10");
KrimBlockName.put("lavastill","11");
KrimBlockName.put("sand","12");
KrimBlockName.put("gravel","13");
KrimBlockName.put("goldore","14");
KrimBlockName.put("ironore","15");
KrimBlockName.put("coalore","16");
KrimBlockName.put("wood","17");
KrimBlockName.put("birchwood","17:1");
KrimBlockName.put("pinewood","17:2");
KrimBlockName.put("djunglewood","17:3");
KrimBlockName.put("leaves","18");
KrimBlockName.put("birchleaves","18:6");
KrimBlockName.put("oakleaves","18:4");
KrimBlockName.put("spruceleaves","18:5");
KrimBlockName.put("djungleleaves","18:7");
KrimBlockName.put("sponge","19");
KrimBlockName.put("glass","20");
KrimBlockName.put("lapislazuliore","21");
KrimBlockName.put("lapislazuliblock","22");
KrimBlockName.put("dispenser","23");
KrimBlockName.put("sandstone","24");
KrimBlockName.put("chiseledsandstone","24:1");
KrimBlockName.put("smoothsandstone","24:2");
KrimBlockName.put("noteblock","25");
KrimBlockName.put("poweredtrack","27");
KrimBlockName.put("detectortrack","28");
KrimBlockName.put("stickypiston","29");
KrimBlockName.put("cobweb","30");
KrimBlockName.put("grass","31:1");
KrimBlockName.put("fern","31:2");
KrimBlockName.put("deadbush","32");
KrimBlockName.put("piston","33");
KrimBlockName.put("wool","35");
KrimBlockName.put("orangewool","35:1");
KrimBlockName.put("magentawool","35:2");
KrimBlockName.put("lightbluewool","35:3");
KrimBlockName.put("yellowwool","35:4");
KrimBlockName.put("limewool","35:5");
KrimBlockName.put("pinkwool","35:6");
KrimBlockName.put("graywool","35:7");
KrimBlockName.put("lightgraywool","35:8");
KrimBlockName.put("cyanwool","35:9");
KrimBlockName.put("purplewool","35:10");
KrimBlockName.put("bluewool","35:11");
KrimBlockName.put("brownwool","35:12");
KrimBlockName.put("greenwool","35:13");
KrimBlockName.put("redwool","35:14");
KrimBlockName.put("blackwool","35:15");
KrimBlockName.put("flower","37");
KrimBlockName.put("rose","38");
KrimBlockName.put("brownmushroom","39");
KrimBlockName.put("redmushroom","40");
KrimBlockName.put("blockofgold","41");
KrimBlockName.put("goldblock","41");
KrimBlockName.put("blockofiron","42");
KrimBlockName.put("ironblock","42");
KrimBlockName.put("doubleslab","43");
KrimBlockName.put("doublesandstoneslab","43:1");
KrimBlockName.put("doublewoodenslab","43:2");
KrimBlockName.put("doublecobbelstoneslab","43:3");
KrimBlockName.put("doublebricksslab","43:4");
KrimBlockName.put("doublestonebricksslab","43:5");
KrimBlockName.put("stoneslab","44");
KrimBlockName.put("sandstoneslab","44:1");
KrimBlockName.put("woodenslab","44:2");
KrimBlockName.put("coobelstoneslab","44:3");
KrimBlockName.put("bricksslab","44:4");
KrimBlockName.put("stonebricksslab","44:5");
KrimBlockName.put("bricks","45");
KrimBlockName.put("tnt","46");
KrimBlockName.put("bookshelf","47");
KrimBlockName.put("mossstone","48");
KrimBlockName.put("obsidian","49");
KrimBlockName.put("torch","50");
KrimBlockName.put("fire","51");
KrimBlockName.put("monsterspawner(creeper)","52:50");
KrimBlockName.put("monsterspawner(skeleton)","52:51");
KrimBlockName.put("monsterspawner(spider)","52:52");
KrimBlockName.put("monsterspawner(giant)","52:53");
KrimBlockName.put("monsterspawner(zombie)","52:54");
KrimBlockName.put("monsterspawner(slime)","52:55");
KrimBlockName.put("monsterspawner(ghast)","52:56");
KrimBlockName.put("monsterspawner(pigzombie)","52:57");
KrimBlockName.put("monsterspawner(enderman)","52:58");
KrimBlockName.put("monsterspawner(cavespider)","52:59");
KrimBlockName.put("monsterspawner(silverfish)","52:60");
KrimBlockName.put("monsterspawner(blaze)","52:61");
KrimBlockName.put("monsterspawner(lavaslime)","52:62");
KrimBlockName.put("monsterspawner(pig)","52:90");
KrimBlockName.put("monsterspawner(sheep)","52:91");
KrimBlockName.put("monsterspawner(cow)","52:92");
KrimBlockName.put("monsterspawner(chicken)","52:93");
KrimBlockName.put("monsterspawner(squid)","52:94");
KrimBlockName.put("monsterspawner(wolf)","52:95");
KrimBlockName.put("monsterspawner(mushroomcow)","52:96");
KrimBlockName.put("monsterspawner(snowman)","52:97");
KrimBlockName.put("monsterspawner(ozelot)","52:98");
KrimBlockName.put("monsterspawner(irongolem)","52:99");
KrimBlockName.put("monsterspawner(villager)","52:120");
KrimBlockName.put("monsterspawner(horse)","52:220");
KrimBlockName.put("monsterspawner(ogre)","52:221");
KrimBlockName.put("monsterspawner(fireogre)","52:222");
KrimBlockName.put("monsterspawner(caveogre)","52:223");
KrimBlockName.put("monsterspawner(boar)","52:224");
KrimBlockName.put("monsterspawner(bear)","52:225");
KrimBlockName.put("monsterspawner(duck)","52:226");
KrimBlockName.put("monsterspawner(bigcat)","52:227");
KrimBlockName.put("monsterspawner(deer)","52:228");
KrimBlockName.put("monsterspawner(wildwolf)","52:229");
KrimBlockName.put("monsterspawner(polarbear)","52:230");
KrimBlockName.put("monsterspawner(wraith)","52:231");
KrimBlockName.put("monsterspawner(flamewraith)","52:232");
KrimBlockName.put("monsterspawner(bunny)","52:233");
KrimBlockName.put("monsterspawner(bird)","52:234");
KrimBlockName.put("monsterspawner(fox)","52:235");
KrimBlockName.put("monsterspawner(werewolf)","52:236");
KrimBlockName.put("monsterspawner(shark)","52:237");
KrimBlockName.put("monsterspawner(dolphin)","52:238");
KrimBlockName.put("monsterspawner(fishy)","52:239");
KrimBlockName.put("monsterspawner(kitty)","52:240");
KrimBlockName.put("monsterspawner(kittybed)","52:241");
KrimBlockName.put("monsterspawner(litterbox)","52:242");
KrimBlockName.put("monsterspawner(rat)","52:243");
KrimBlockName.put("monsterspawner(mouse)","52:244");
KrimBlockName.put("monsterspawner(hellrat)","52:245");
KrimBlockName.put("monsterspawner(scorpion)","52:246");
KrimBlockName.put("monsterspawner(turtle)","52:247");
KrimBlockName.put("monsterspawner(crocodile)","52:248");
KrimBlockName.put("monsterspawner(ray)","52:249");
KrimBlockName.put("monsterspawner(jellyfish)","52:250");
KrimBlockName.put("monsterspawner(goat)","52:251");
KrimBlockName.put("monsterspawner(snake)","52:252");
KrimBlockName.put("monsterspawner(mocegg)","52:253");
KrimBlockName.put("monsterspawner(fishbowl)","52:254");
KrimBlockName.put("monsterspawner(ostrich)","52:255");
KrimBlockName.put("woodenstairs","53");
KrimBlockName.put("chest","54");
KrimBlockName.put("diamondore","56");
KrimBlockName.put("blockofdiamond","57");
KrimBlockName.put("diamondblock","57");
KrimBlockName.put("craftingtable","58");
KrimBlockName.put("farmland","60");
KrimBlockName.put("furnace","61");
KrimBlockName.put("furnace_on","62");
KrimBlockName.put("ladder","65");
KrimBlockName.put("track","66");
KrimBlockName.put("cobblestonestairs","67");
KrimBlockName.put("lever","69");
KrimBlockName.put("pressureplate","70");
KrimBlockName.put("irondoorblock","71");
KrimBlockName.put("woodenpressureplate","72");
KrimBlockName.put("redstoneore","73");
KrimBlockName.put("redstonetorch_glow","74");
KrimBlockName.put("redstonetorch_off","75");
KrimBlockName.put("redstonetorch","76");
KrimBlockName.put("button","77");
KrimBlockName.put("snow","78");
KrimBlockName.put("ice","79");
KrimBlockName.put("snow","80");
KrimBlockName.put("cactus","81");
KrimBlockName.put("clay","82");
KrimBlockName.put("jukebox","84");
KrimBlockName.put("fence","85");
KrimBlockName.put("pumpkin","86");
KrimBlockName.put("netherrack","87");
KrimBlockName.put("soulsand","88");
KrimBlockName.put("glowstone","89");
KrimBlockName.put("portal","90");
KrimBlockName.put("jackolantern","91");
KrimBlockName.put("cake","92");
KrimBlockName.put("lockedchest","95");
KrimBlockName.put("trapdoor","96");
KrimBlockName.put("silverfishstone","97");
KrimBlockName.put("stonebricks","98");
KrimBlockName.put("mossystonebricks","98:1");
KrimBlockName.put("crackedstonebricks","98:2");
KrimBlockName.put("chiseledstonebricks","98:3");
KrimBlockName.put("hugebrownmushroom","99");
KrimBlockName.put("hugeredmushroom","100");
KrimBlockName.put("ironbars","101");
KrimBlockName.put("glasspanel","102");
KrimBlockName.put("melon","103");
KrimBlockName.put("vines","106");
KrimBlockName.put("fencegate","107");
KrimBlockName.put("brickstairs","108");
KrimBlockName.put("stonebricksatirs","109");
KrimBlockName.put("mycelium","110");
KrimBlockName.put("lilypad","111");
KrimBlockName.put("netherbrick","112");
KrimBlockName.put("netherbrickfence","113");
KrimBlockName.put("netherbrickstairs","114");
KrimBlockName.put("netherwart","115");
KrimBlockName.put("enchantmenttable","116");
KrimBlockName.put("endportal","119");
KrimBlockName.put("endportalframe","120");
KrimBlockName.put("whitestone","121");
KrimBlockName.put("endstone","121:1");
KrimBlockName.put("dragonegg","122");
KrimBlockName.put("redstonelamp_off","123");
KrimBlockName.put("redstonelamp","124");
KrimBlockName.put("Oakwoodslab","126");
KrimBlockName.put("Sprucewoodslab","126:1");
KrimBlockName.put("Birchwoodslab","126:2");
KrimBlockName.put("Junglewoodslab","126:3");
KrimBlockName.put("Sandstonestairs","128");
KrimBlockName.put("Emeraldore","129");
KrimBlockName.put("Tripwirehook","131");
KrimBlockName.put("emeraldblock","133");
KrimBlockName.put("Sprucewoodstairs","134");
KrimBlockName.put("Birchwoodstairs","135");
KrimBlockName.put("Junglewoodstairs","136");
KrimBlockName.put("Beacon","138");
KrimBlockName.put("Cobblestonewall","139");
KrimBlockName.put("Mossycobblestonewall","139:1");
KrimBlockName.put("Woodenbutton","143");
KrimBlockName.put("Anvil","145");
KrimBlockName.put("Anvil(Damaged)","145:1");
KrimBlockName.put("Anvil(VeryDamaged)","145:2");
KrimBlockName.put("TrappedChest","146");
KrimBlockName.put("WeightedPressurePlate(Light)","147");
KrimBlockName.put("WeightedPressurePlate(Heavy)","148");
KrimBlockName.put("RedstoneComparator(Dis)","149");
KrimBlockName.put("RedstoneComparator(Act)","150");
KrimBlockName.put("DaylightSensor","151");
KrimBlockName.put("BlockofRedstone","152");
KrimBlockName.put("Redstoneblock","152");
KrimBlockName.put("Netherquartzore","153");
KrimBlockName.put("Hopper","154");
KrimBlockName.put("BlockofQuartz","155");
KrimBlockName.put("Quartzstairs","156");
KrimBlockName.put("ActivatorRail","157");
KrimBlockName.put("Dropper","158");
KrimBlockName.put("ironpickaxe","257");
KrimBlockName.put("ironaxe","258");
KrimBlockName.put("flintandsteel","259");
KrimBlockName.put("apple","260");
KrimBlockName.put("bow","261");
KrimBlockName.put("arrow","262");
KrimBlockName.put("coal","263");
KrimBlockName.put("charcoal","263:1");
KrimBlockName.put("diamond","264");
KrimBlockName.put("ironingot","265");
KrimBlockName.put("goldingot","266");
KrimBlockName.put("ironsword","267");
KrimBlockName.put("woodensword","268");
KrimBlockName.put("woodenshovel","269");
KrimBlockName.put("woodenpickaxe","270");
KrimBlockName.put("woodenaxe","271");
KrimBlockName.put("stonesword","272");
KrimBlockName.put("stoneshovel","273");
KrimBlockName.put("stonepickaxe","274");
KrimBlockName.put("stoneaxe","275");
KrimBlockName.put("diamondsword","276");
KrimBlockName.put("diamondspade","277");
KrimBlockName.put("diamondpickaxe","278");
KrimBlockName.put("diamondaxe","279");
KrimBlockName.put("stick","280");
KrimBlockName.put("bowl","281");
KrimBlockName.put("mushroomsoup","282");
KrimBlockName.put("goldensword","283");
KrimBlockName.put("goldenspade","284");
KrimBlockName.put("goldenpickaxe","285");
KrimBlockName.put("goldenaxe","286");
KrimBlockName.put("string","287");
KrimBlockName.put("feather","288");
KrimBlockName.put("gunpowder","289");
KrimBlockName.put("woodenhoe","290");
KrimBlockName.put("stonehoe","291");
KrimBlockName.put("ironhoe","292");
KrimBlockName.put("diamondhoe","293");
KrimBlockName.put("goldenmhoe","294");
KrimBlockName.put("seeds","295");
KrimBlockName.put("wheat","296");
KrimBlockName.put("bread","297");
KrimBlockName.put("leathercap","298");
KrimBlockName.put("leathertunic","299");
KrimBlockName.put("leathertrousers","300");
KrimBlockName.put("leatherboots","301");
KrimBlockName.put("chainmailhelmet","302");
KrimBlockName.put("chainchestplate","303");
KrimBlockName.put("chainmailleggings","304");
KrimBlockName.put("chainmailboots","305");
KrimBlockName.put("ironhelmet","306");
KrimBlockName.put("ironchestplate","307");
KrimBlockName.put("ironleggings","308");
KrimBlockName.put("ironboots","309");
KrimBlockName.put("diamondhelmet","310");
KrimBlockName.put("diamondchestplate","311");
KrimBlockName.put("diamondleggings","312");
KrimBlockName.put("industrialdiamond","313");
KrimBlockName.put("goldenhelmet","314");
KrimBlockName.put("goldenchestplate","315");
KrimBlockName.put("goldenleggings","316");
KrimBlockName.put("goldenboots","317");
KrimBlockName.put("flint","318");
KrimBlockName.put("rawporkchop","319");
KrimBlockName.put("cookedporkchop","320");
KrimBlockName.put("painting","321");
KrimBlockName.put("goldenapple","322");
KrimBlockName.put("sign","323");
KrimBlockName.put("woodendoor","324");
KrimBlockName.put("bucket","325");
KrimBlockName.put("bucketofwater","326");
KrimBlockName.put("bucketoflava","327");
KrimBlockName.put("minecart","328");
KrimBlockName.put("saddle","329");
KrimBlockName.put("irondoor","330");
KrimBlockName.put("redstone","331");
KrimBlockName.put("snowball","332");
KrimBlockName.put("boat","333");
KrimBlockName.put("leather","334");
KrimBlockName.put("bucketofmilk","335");
KrimBlockName.put("brick","336");
KrimBlockName.put("clay","337");
KrimBlockName.put("sugarcanes","338");
KrimBlockName.put("paper","339");
KrimBlockName.put("book","340");
KrimBlockName.put("slimeball","341");
KrimBlockName.put("chestcart","342");
KrimBlockName.put("furnacecart","343");
KrimBlockName.put("egg","344");
KrimBlockName.put("compass","345");
KrimBlockName.put("fishingrod","346");
KrimBlockName.put("watch","347");
KrimBlockName.put("glowstonedust","348");
KrimBlockName.put("rawfish","349");
KrimBlockName.put("cookedfish","350");
KrimBlockName.put("inksac","351");
KrimBlockName.put("rosered","351:1");
KrimBlockName.put("cactusgreen","351:2");
KrimBlockName.put("cocoabeans","351:3");
KrimBlockName.put("lapislazuli","351:4");
KrimBlockName.put("purpledye","351:5");
KrimBlockName.put("cyandye","351:6");
KrimBlockName.put("lightgreydye","351:7");
KrimBlockName.put("greydye","351:8");
KrimBlockName.put("pinkdye","351:9");
KrimBlockName.put("limegreendye","351:10");
KrimBlockName.put("dandelionyellow","351:11");
KrimBlockName.put("lightbluedye","351:12");
KrimBlockName.put("magentadye","351:13");
KrimBlockName.put("orangedye","351:14");
KrimBlockName.put("bonemeal","351:15");
KrimBlockName.put("bone","352");
KrimBlockName.put("sugar","353");
KrimBlockName.put("cake","354");
KrimBlockName.put("bed","355");
KrimBlockName.put("redstonerepeater","356");
KrimBlockName.put("cookie","357");
KrimBlockName.put("map","358");
KrimBlockName.put("shears","359");
KrimBlockName.put("melon","360");
KrimBlockName.put("pumpkinseeds","361");
KrimBlockName.put("melonseeds","362");
KrimBlockName.put("rawbeef","363");
KrimBlockName.put("steak","364");
KrimBlockName.put("rawchicken","365");
KrimBlockName.put("cookedchicken","366");
KrimBlockName.put("rottenflesh","367");
KrimBlockName.put("ender pearl","368");
KrimBlockName.put("blazerod","369");
KrimBlockName.put("ghasttear","370");
KrimBlockName.put("goldennugget","371");
KrimBlockName.put("netherwart","372");
KrimBlockName.put("waterbottle","373");
KrimBlockName.put("awkwardpotion","373:16");
KrimBlockName.put("thickpotion","373:32");
KrimBlockName.put("mundanepotion","373:64");
KrimBlockName.put("Regeneration Potion (0:45)","373:8193");
KrimBlockName.put("Swiftness Potion (3:00)","373:8194");
KrimBlockName.put("Fire Resistance Potion (3:00)","373:8195");
KrimBlockName.put("Poison Potion (0:45)","373:8196");
KrimBlockName.put("Healing Potion","373:8197");
KrimBlockName.put("Weakness Potion (1:30)","373:8200");
KrimBlockName.put("Strength Potion (3:00)","373:8201");
KrimBlockName.put("Slowness Potion (1:30)","373:8202");
KrimBlockName.put("Harming Potion","373:8204");
KrimBlockName.put("Regeneration Potion II (0:22)","373:8225");
KrimBlockName.put("Swiftness Potion II (1:30)","373:8226");
KrimBlockName.put("Poison Potion II (0:22)","373:8228");
KrimBlockName.put("Healing Potion II","373:8229");
KrimBlockName.put("Strength Potion II (1:30)","373:8233");
KrimBlockName.put("Harming Potion II","373:8236");
KrimBlockName.put("Regeneration Potion (2:00)","373:8257");
KrimBlockName.put("Swiftness Potion (8:00)","373:8258");
KrimBlockName.put("Fire Resistance Potion (8:00)","373:8259");
KrimBlockName.put("Poison Potion (2:00)","373:8260");
KrimBlockName.put("Weakness Potion (4:00)","373:8264");
KrimBlockName.put("Strength Potion (8:00)","373:8265");
KrimBlockName.put("Slowness Potion (4:00)","373:8266");
KrimBlockName.put("Fire Resistance Splash (2:15)","373:16378");
KrimBlockName.put("Regeneration Splash (0:33)","373:16385");
KrimBlockName.put("Swiftness Splash (2:15)","373:16386");
KrimBlockName.put("Poison Splash (0:33)","373:16388");
KrimBlockName.put("Healing Splash","373:16389");
KrimBlockName.put("Weakness Splash (1:07)","373:16392");
KrimBlockName.put("Strength Splash (2:15)","373:16393");
KrimBlockName.put("Slowness Splash (1:07)","373:16394");
KrimBlockName.put("Harming Splash","373:16396");
KrimBlockName.put("Swiftness Splash II (1:07)","373:16418");
KrimBlockName.put("Poison Splash II (0:16)","373:16420");
KrimBlockName.put("Healing Splash II","373:16421");
KrimBlockName.put("Strength Splash II (1:07)","373:16425");
KrimBlockName.put("Harming Splash II","373:16428");
KrimBlockName.put("Regeneration Splash (1:30)","373:16449");
KrimBlockName.put("Swiftness Splash (6:00)","373:16450");
KrimBlockName.put("Fire Resistance Splash (6:00)","373:16451");
KrimBlockName.put("Poison Splash (1:30)","373:16452");
KrimBlockName.put("Weakness Splash (3:00)","373:16456");
KrimBlockName.put("Strength Splash (6:00)","373:16457");
KrimBlockName.put("Slowness Splash (3:00)","373:16458");
KrimBlockName.put("Regeneration Splash II (0:16)","373:16471");
KrimBlockName.put("glassbottle","374");
KrimBlockName.put("spidereye","375");
KrimBlockName.put("fermentedspidereye","376");
KrimBlockName.put("blazepowder","377");
KrimBlockName.put("magmacream","378");
KrimBlockName.put("brewingstand","379");
KrimBlockName.put("cauldron","380");
KrimBlockName.put("eyeofender","381");
KrimBlockName.put("glisteringmelon","382");
KrimBlockName.put("spawncreeper","383:50");
KrimBlockName.put("spawnskeleton","383:51");
KrimBlockName.put("spawnspider","383:52");
KrimBlockName.put("spawnzombie","383:54");
KrimBlockName.put("spawnslime","383:55");
KrimBlockName.put("spawnghast","383:56");
KrimBlockName.put("spawnpigzombie","383:57");
KrimBlockName.put("spawnenderman","383:58");
KrimBlockName.put("spawncavespider","383:59");
KrimBlockName.put("spawnsilverfish","383:60");
KrimBlockName.put("spawnblaze","383:61");
KrimBlockName.put("spawnmagmacube","383:62");
KrimBlockName.put("spawnpig","383:90");
KrimBlockName.put("spawnsheep","383:91");
KrimBlockName.put("spawncow","383:92");
KrimBlockName.put("spawnchicken","383:93");
KrimBlockName.put("spawnsquid","383:94");
KrimBlockName.put("spawnwolf","383:95");
KrimBlockName.put("spawnmooshroom","383:96");
KrimBlockName.put("spawnsnowgolem","383:97");
KrimBlockName.put("spawnocelot","383:98");
KrimBlockName.put("spawnirongolem","383:99");
KrimBlockName.put("spawnvillager","383:120");
KrimBlockName.put("bottleo´enchanting","384");
KrimBlockName.put("firecharge","385");
KrimBlockName.put("bookandquill","386");
KrimBlockName.put("writtenbook","387");
KrimBlockName.put("Emerald","388");
KrimBlockName.put("Itemframe","389");
KrimBlockName.put("Flowerpot","390");
KrimBlockName.put("Carrot","391");
KrimBlockName.put("Potatoe","392");
KrimBlockName.put("Bakedpotatoe","393");
KrimBlockName.put("Poisonedpotatoe","394");
KrimBlockName.put("Emptymap","395");
KrimBlockName.put("Goldencarrot","396");
KrimBlockName.put("SkelletonSkull","397");
KrimBlockName.put("Witherhead","397:1");
KrimBlockName.put("Zombiehead","397:2");
KrimBlockName.put("Head","397:3");
KrimBlockName.put("Creeperhead","397:4");
KrimBlockName.put("Carrotonastick","398");
KrimBlockName.put("Netherstar","399");
KrimBlockName.put("Pumpkinpie","400");
KrimBlockName.put("FireRocket","401");
KrimBlockName.put("Firestar","402");
KrimBlockName.put("Enchantedbook","403");
KrimBlockName.put("RedstoneComparator","404");
KrimBlockName.put("Netherbrick","405");
KrimBlockName.put("Netherquartz","406");
KrimBlockName.put("TNTCart","407");
KrimBlockName.put("HopperCart","408");
KrimBlockName.put("Disk C418-13","2256");
KrimBlockName.put("Disk C418-Cat","2257");
KrimBlockName.put("Disk C418-Blocks","2258");
KrimBlockName.put("Disk C418-Chirp","2259");
KrimBlockName.put("Disk C418-Far","2260");
KrimBlockName.put("Disk C418-Mall","2261");
KrimBlockName.put("Disk C418-Mellohi","2262");
KrimBlockName.put("Disk C418-Stall","2263");
KrimBlockName.put("Disk C418-Strad","2264");
KrimBlockName.put("Disk C418-Ward","2265");
KrimBlockName.put("Disk 11","2266");
KrimBlockName.put("Disk C418-Wait","2267");
}
| public KrimBlockName()
{
//INIT VALUES
KrimBlockName.put("air", "0");
KrimBlockName.put("stone","1");
KrimBlockName.put("grassblock","2");
KrimBlockName.put("dirt","3");
KrimBlockName.put("cobblestone","4");
KrimBlockName.put("woodenplanks","5");
KrimBlockName.put("pinewoodenplanks","5:1");
KrimBlockName.put("birchwoodenplanks","5:2");
KrimBlockName.put("djunglewoodenplanks","5:3");
KrimBlockName.put("sapling","6");
KrimBlockName.put("birchsapling","6:2");
KrimBlockName.put("pinesapling","6:1");
KrimBlockName.put("djunglesapling","6:3");
KrimBlockName.put("bedrock","7");
KrimBlockName.put("watersource","8");
KrimBlockName.put("waterstill","9");
KrimBlockName.put("lavasource","10");
KrimBlockName.put("lavastill","11");
KrimBlockName.put("sand","12");
KrimBlockName.put("gravel","13");
KrimBlockName.put("goldore","14");
KrimBlockName.put("ironore","15");
KrimBlockName.put("coalore","16");
KrimBlockName.put("wood","17");
KrimBlockName.put("birchwood","17:2");
KrimBlockName.put("pinewood","17:1");
KrimBlockName.put("djunglewood","17:3");
KrimBlockName.put("leaves","18");
KrimBlockName.put("birchleaves","18:5");
KrimBlockName.put("oakleaves","18:4");
KrimBlockName.put("spruceleaves","18:6");
KrimBlockName.put("djungleleaves","18:7");
KrimBlockName.put("sponge","19");
KrimBlockName.put("glass","20");
KrimBlockName.put("lapislazuliore","21");
KrimBlockName.put("lapislazuliblock","22");
KrimBlockName.put("dispenser","23");
KrimBlockName.put("sandstone","24");
KrimBlockName.put("chiseledsandstone","24:1");
KrimBlockName.put("smoothsandstone","24:2");
KrimBlockName.put("noteblock","25");
KrimBlockName.put("poweredtrack","27");
KrimBlockName.put("detectortrack","28");
KrimBlockName.put("stickypiston","29");
KrimBlockName.put("cobweb","30");
KrimBlockName.put("grass","31:1");
KrimBlockName.put("fern","31:2");
KrimBlockName.put("deadbush","32");
KrimBlockName.put("piston","33");
KrimBlockName.put("wool","35");
KrimBlockName.put("orangewool","35:1");
KrimBlockName.put("magentawool","35:2");
KrimBlockName.put("lightbluewool","35:3");
KrimBlockName.put("yellowwool","35:4");
KrimBlockName.put("limewool","35:5");
KrimBlockName.put("pinkwool","35:6");
KrimBlockName.put("graywool","35:7");
KrimBlockName.put("lightgraywool","35:8");
KrimBlockName.put("cyanwool","35:9");
KrimBlockName.put("purplewool","35:10");
KrimBlockName.put("bluewool","35:11");
KrimBlockName.put("brownwool","35:12");
KrimBlockName.put("greenwool","35:13");
KrimBlockName.put("redwool","35:14");
KrimBlockName.put("blackwool","35:15");
KrimBlockName.put("flower","37");
KrimBlockName.put("rose","38");
KrimBlockName.put("brownmushroom","39");
KrimBlockName.put("redmushroom","40");
KrimBlockName.put("blockofgold","41");
KrimBlockName.put("goldblock","41");
KrimBlockName.put("blockofiron","42");
KrimBlockName.put("ironblock","42");
KrimBlockName.put("doubleslab","43");
KrimBlockName.put("doublesandstoneslab","43:1");
KrimBlockName.put("doublewoodenslab","43:2");
KrimBlockName.put("doublecobbelstoneslab","43:3");
KrimBlockName.put("doublebricksslab","43:4");
KrimBlockName.put("doublestonebricksslab","43:5");
KrimBlockName.put("stoneslab","44");
KrimBlockName.put("sandstoneslab","44:1");
KrimBlockName.put("woodenslab","44:2");
KrimBlockName.put("coobelstoneslab","44:3");
KrimBlockName.put("bricksslab","44:4");
KrimBlockName.put("stonebricksslab","44:5");
KrimBlockName.put("bricks","45");
KrimBlockName.put("tnt","46");
KrimBlockName.put("bookshelf","47");
KrimBlockName.put("mossstone","48");
KrimBlockName.put("obsidian","49");
KrimBlockName.put("torch","50");
KrimBlockName.put("fire","51");
KrimBlockName.put("monsterspawner(creeper)","52:50");
KrimBlockName.put("monsterspawner(skeleton)","52:51");
KrimBlockName.put("monsterspawner(spider)","52:52");
KrimBlockName.put("monsterspawner(giant)","52:53");
KrimBlockName.put("monsterspawner(zombie)","52:54");
KrimBlockName.put("monsterspawner(slime)","52:55");
KrimBlockName.put("monsterspawner(ghast)","52:56");
KrimBlockName.put("monsterspawner(pigzombie)","52:57");
KrimBlockName.put("monsterspawner(enderman)","52:58");
KrimBlockName.put("monsterspawner(cavespider)","52:59");
KrimBlockName.put("monsterspawner(silverfish)","52:60");
KrimBlockName.put("monsterspawner(blaze)","52:61");
KrimBlockName.put("monsterspawner(lavaslime)","52:62");
KrimBlockName.put("monsterspawner(pig)","52:90");
KrimBlockName.put("monsterspawner(sheep)","52:91");
KrimBlockName.put("monsterspawner(cow)","52:92");
KrimBlockName.put("monsterspawner(chicken)","52:93");
KrimBlockName.put("monsterspawner(squid)","52:94");
KrimBlockName.put("monsterspawner(wolf)","52:95");
KrimBlockName.put("monsterspawner(mushroomcow)","52:96");
KrimBlockName.put("monsterspawner(snowman)","52:97");
KrimBlockName.put("monsterspawner(ozelot)","52:98");
KrimBlockName.put("monsterspawner(irongolem)","52:99");
KrimBlockName.put("monsterspawner(villager)","52:120");
KrimBlockName.put("monsterspawner(horse)","52:220");
KrimBlockName.put("monsterspawner(ogre)","52:221");
KrimBlockName.put("monsterspawner(fireogre)","52:222");
KrimBlockName.put("monsterspawner(caveogre)","52:223");
KrimBlockName.put("monsterspawner(boar)","52:224");
KrimBlockName.put("monsterspawner(bear)","52:225");
KrimBlockName.put("monsterspawner(duck)","52:226");
KrimBlockName.put("monsterspawner(bigcat)","52:227");
KrimBlockName.put("monsterspawner(deer)","52:228");
KrimBlockName.put("monsterspawner(wildwolf)","52:229");
KrimBlockName.put("monsterspawner(polarbear)","52:230");
KrimBlockName.put("monsterspawner(wraith)","52:231");
KrimBlockName.put("monsterspawner(flamewraith)","52:232");
KrimBlockName.put("monsterspawner(bunny)","52:233");
KrimBlockName.put("monsterspawner(bird)","52:234");
KrimBlockName.put("monsterspawner(fox)","52:235");
KrimBlockName.put("monsterspawner(werewolf)","52:236");
KrimBlockName.put("monsterspawner(shark)","52:237");
KrimBlockName.put("monsterspawner(dolphin)","52:238");
KrimBlockName.put("monsterspawner(fishy)","52:239");
KrimBlockName.put("monsterspawner(kitty)","52:240");
KrimBlockName.put("monsterspawner(kittybed)","52:241");
KrimBlockName.put("monsterspawner(litterbox)","52:242");
KrimBlockName.put("monsterspawner(rat)","52:243");
KrimBlockName.put("monsterspawner(mouse)","52:244");
KrimBlockName.put("monsterspawner(hellrat)","52:245");
KrimBlockName.put("monsterspawner(scorpion)","52:246");
KrimBlockName.put("monsterspawner(turtle)","52:247");
KrimBlockName.put("monsterspawner(crocodile)","52:248");
KrimBlockName.put("monsterspawner(ray)","52:249");
KrimBlockName.put("monsterspawner(jellyfish)","52:250");
KrimBlockName.put("monsterspawner(goat)","52:251");
KrimBlockName.put("monsterspawner(snake)","52:252");
KrimBlockName.put("monsterspawner(mocegg)","52:253");
KrimBlockName.put("monsterspawner(fishbowl)","52:254");
KrimBlockName.put("monsterspawner(ostrich)","52:255");
KrimBlockName.put("woodenstairs","53");
KrimBlockName.put("chest","54");
KrimBlockName.put("diamondore","56");
KrimBlockName.put("blockofdiamond","57");
KrimBlockName.put("diamondblock","57");
KrimBlockName.put("craftingtable","58");
KrimBlockName.put("farmland","60");
KrimBlockName.put("furnace","61");
KrimBlockName.put("furnace_on","62");
KrimBlockName.put("ladder","65");
KrimBlockName.put("track","66");
KrimBlockName.put("cobblestonestairs","67");
KrimBlockName.put("lever","69");
KrimBlockName.put("pressureplate","70");
KrimBlockName.put("irondoorblock","71");
KrimBlockName.put("woodenpressureplate","72");
KrimBlockName.put("redstoneore","73");
KrimBlockName.put("redstonetorch_glow","74");
KrimBlockName.put("redstonetorch_off","75");
KrimBlockName.put("redstonetorch","76");
KrimBlockName.put("button","77");
KrimBlockName.put("snow","78");
KrimBlockName.put("ice","79");
KrimBlockName.put("snow","80");
KrimBlockName.put("cactus","81");
KrimBlockName.put("clay","82");
KrimBlockName.put("jukebox","84");
KrimBlockName.put("fence","85");
KrimBlockName.put("pumpkin","86");
KrimBlockName.put("netherrack","87");
KrimBlockName.put("soulsand","88");
KrimBlockName.put("glowstone","89");
KrimBlockName.put("portal","90");
KrimBlockName.put("jackolantern","91");
KrimBlockName.put("cake","92");
KrimBlockName.put("lockedchest","95");
KrimBlockName.put("trapdoor","96");
KrimBlockName.put("silverfishstone","97");
KrimBlockName.put("stonebricks","98");
KrimBlockName.put("mossystonebricks","98:1");
KrimBlockName.put("crackedstonebricks","98:2");
KrimBlockName.put("chiseledstonebricks","98:3");
KrimBlockName.put("hugebrownmushroom","99");
KrimBlockName.put("hugeredmushroom","100");
KrimBlockName.put("ironbars","101");
KrimBlockName.put("glasspanel","102");
KrimBlockName.put("melon","103");
KrimBlockName.put("vines","106");
KrimBlockName.put("fencegate","107");
KrimBlockName.put("brickstairs","108");
KrimBlockName.put("stonebricksatirs","109");
KrimBlockName.put("mycelium","110");
KrimBlockName.put("lilypad","111");
KrimBlockName.put("netherbrick","112");
KrimBlockName.put("netherbrickfence","113");
KrimBlockName.put("netherbrickstairs","114");
KrimBlockName.put("netherwart","115");
KrimBlockName.put("enchantmenttable","116");
KrimBlockName.put("endportal","119");
KrimBlockName.put("endportalframe","120");
KrimBlockName.put("whitestone","121");
KrimBlockName.put("endstone","121:1");
KrimBlockName.put("dragonegg","122");
KrimBlockName.put("redstonelamp_off","123");
KrimBlockName.put("redstonelamp","124");
KrimBlockName.put("Oakwoodslab","126");
KrimBlockName.put("Sprucewoodslab","126:1");
KrimBlockName.put("Birchwoodslab","126:2");
KrimBlockName.put("Junglewoodslab","126:3");
KrimBlockName.put("Sandstonestairs","128");
KrimBlockName.put("Emeraldore","129");
KrimBlockName.put("Tripwirehook","131");
KrimBlockName.put("emeraldblock","133");
KrimBlockName.put("Sprucewoodstairs","134");
KrimBlockName.put("Birchwoodstairs","135");
KrimBlockName.put("Junglewoodstairs","136");
KrimBlockName.put("Beacon","138");
KrimBlockName.put("Cobblestonewall","139");
KrimBlockName.put("Mossycobblestonewall","139:1");
KrimBlockName.put("Woodenbutton","143");
KrimBlockName.put("Anvil","145");
KrimBlockName.put("Anvil(Damaged)","145:1");
KrimBlockName.put("Anvil(VeryDamaged)","145:2");
KrimBlockName.put("TrappedChest","146");
KrimBlockName.put("WeightedPressurePlate(Light)","147");
KrimBlockName.put("WeightedPressurePlate(Heavy)","148");
KrimBlockName.put("RedstoneComparator(Dis)","149");
KrimBlockName.put("RedstoneComparator(Act)","150");
KrimBlockName.put("DaylightSensor","151");
KrimBlockName.put("BlockofRedstone","152");
KrimBlockName.put("Redstoneblock","152");
KrimBlockName.put("Netherquartzore","153");
KrimBlockName.put("Hopper","154");
KrimBlockName.put("BlockofQuartz","155");
KrimBlockName.put("Quartzstairs","156");
KrimBlockName.put("ActivatorRail","157");
KrimBlockName.put("Dropper","158");
KrimBlockName.put("ironpickaxe","257");
KrimBlockName.put("ironaxe","258");
KrimBlockName.put("flintandsteel","259");
KrimBlockName.put("apple","260");
KrimBlockName.put("bow","261");
KrimBlockName.put("arrow","262");
KrimBlockName.put("coal","263");
KrimBlockName.put("charcoal","263:1");
KrimBlockName.put("diamond","264");
KrimBlockName.put("ironingot","265");
KrimBlockName.put("goldingot","266");
KrimBlockName.put("ironsword","267");
KrimBlockName.put("woodensword","268");
KrimBlockName.put("woodenshovel","269");
KrimBlockName.put("woodenpickaxe","270");
KrimBlockName.put("woodenaxe","271");
KrimBlockName.put("stonesword","272");
KrimBlockName.put("stoneshovel","273");
KrimBlockName.put("stonepickaxe","274");
KrimBlockName.put("stoneaxe","275");
KrimBlockName.put("diamondsword","276");
KrimBlockName.put("diamondspade","277");
KrimBlockName.put("diamondpickaxe","278");
KrimBlockName.put("diamondaxe","279");
KrimBlockName.put("stick","280");
KrimBlockName.put("bowl","281");
KrimBlockName.put("mushroomsoup","282");
KrimBlockName.put("goldensword","283");
KrimBlockName.put("goldenspade","284");
KrimBlockName.put("goldenpickaxe","285");
KrimBlockName.put("goldenaxe","286");
KrimBlockName.put("string","287");
KrimBlockName.put("feather","288");
KrimBlockName.put("gunpowder","289");
KrimBlockName.put("woodenhoe","290");
KrimBlockName.put("stonehoe","291");
KrimBlockName.put("ironhoe","292");
KrimBlockName.put("diamondhoe","293");
KrimBlockName.put("goldenmhoe","294");
KrimBlockName.put("seeds","295");
KrimBlockName.put("wheat","296");
KrimBlockName.put("bread","297");
KrimBlockName.put("leathercap","298");
KrimBlockName.put("leathertunic","299");
KrimBlockName.put("leathertrousers","300");
KrimBlockName.put("leatherboots","301");
KrimBlockName.put("chainmailhelmet","302");
KrimBlockName.put("chainchestplate","303");
KrimBlockName.put("chainmailleggings","304");
KrimBlockName.put("chainmailboots","305");
KrimBlockName.put("ironhelmet","306");
KrimBlockName.put("ironchestplate","307");
KrimBlockName.put("ironleggings","308");
KrimBlockName.put("ironboots","309");
KrimBlockName.put("diamondhelmet","310");
KrimBlockName.put("diamondchestplate","311");
KrimBlockName.put("diamondleggings","312");
KrimBlockName.put("industrialdiamond","313");
KrimBlockName.put("goldenhelmet","314");
KrimBlockName.put("goldenchestplate","315");
KrimBlockName.put("goldenleggings","316");
KrimBlockName.put("goldenboots","317");
KrimBlockName.put("flint","318");
KrimBlockName.put("rawporkchop","319");
KrimBlockName.put("cookedporkchop","320");
KrimBlockName.put("painting","321");
KrimBlockName.put("goldenapple","322");
KrimBlockName.put("sign","323");
KrimBlockName.put("woodendoor","324");
KrimBlockName.put("bucket","325");
KrimBlockName.put("bucketofwater","326");
KrimBlockName.put("bucketoflava","327");
KrimBlockName.put("minecart","328");
KrimBlockName.put("saddle","329");
KrimBlockName.put("irondoor","330");
KrimBlockName.put("redstone","331");
KrimBlockName.put("snowball","332");
KrimBlockName.put("boat","333");
KrimBlockName.put("leather","334");
KrimBlockName.put("bucketofmilk","335");
KrimBlockName.put("brick","336");
KrimBlockName.put("clay","337");
KrimBlockName.put("sugarcanes","338");
KrimBlockName.put("paper","339");
KrimBlockName.put("book","340");
KrimBlockName.put("slimeball","341");
KrimBlockName.put("chestcart","342");
KrimBlockName.put("furnacecart","343");
KrimBlockName.put("egg","344");
KrimBlockName.put("compass","345");
KrimBlockName.put("fishingrod","346");
KrimBlockName.put("watch","347");
KrimBlockName.put("glowstonedust","348");
KrimBlockName.put("rawfish","349");
KrimBlockName.put("cookedfish","350");
KrimBlockName.put("inksac","351");
KrimBlockName.put("rosered","351:1");
KrimBlockName.put("cactusgreen","351:2");
KrimBlockName.put("cocoabeans","351:3");
KrimBlockName.put("lapislazuli","351:4");
KrimBlockName.put("purpledye","351:5");
KrimBlockName.put("cyandye","351:6");
KrimBlockName.put("lightgreydye","351:7");
KrimBlockName.put("greydye","351:8");
KrimBlockName.put("pinkdye","351:9");
KrimBlockName.put("limegreendye","351:10");
KrimBlockName.put("dandelionyellow","351:11");
KrimBlockName.put("lightbluedye","351:12");
KrimBlockName.put("magentadye","351:13");
KrimBlockName.put("orangedye","351:14");
KrimBlockName.put("bonemeal","351:15");
KrimBlockName.put("bone","352");
KrimBlockName.put("sugar","353");
KrimBlockName.put("cake","354");
KrimBlockName.put("bed","355");
KrimBlockName.put("redstonerepeater","356");
KrimBlockName.put("cookie","357");
KrimBlockName.put("map","358");
KrimBlockName.put("shears","359");
KrimBlockName.put("melon","360");
KrimBlockName.put("pumpkinseeds","361");
KrimBlockName.put("melonseeds","362");
KrimBlockName.put("rawbeef","363");
KrimBlockName.put("steak","364");
KrimBlockName.put("rawchicken","365");
KrimBlockName.put("cookedchicken","366");
KrimBlockName.put("rottenflesh","367");
KrimBlockName.put("ender pearl","368");
KrimBlockName.put("blazerod","369");
KrimBlockName.put("ghasttear","370");
KrimBlockName.put("goldennugget","371");
KrimBlockName.put("netherwart","372");
KrimBlockName.put("waterbottle","373");
KrimBlockName.put("awkwardpotion","373:16");
KrimBlockName.put("thickpotion","373:32");
KrimBlockName.put("mundanepotion","373:64");
KrimBlockName.put("Regeneration Potion (0:45)","373:8193");
KrimBlockName.put("Swiftness Potion (3:00)","373:8194");
KrimBlockName.put("Fire Resistance Potion (3:00)","373:8195");
KrimBlockName.put("Poison Potion (0:45)","373:8196");
KrimBlockName.put("Healing Potion","373:8197");
KrimBlockName.put("Weakness Potion (1:30)","373:8200");
KrimBlockName.put("Strength Potion (3:00)","373:8201");
KrimBlockName.put("Slowness Potion (1:30)","373:8202");
KrimBlockName.put("Harming Potion","373:8204");
KrimBlockName.put("Regeneration Potion II (0:22)","373:8225");
KrimBlockName.put("Swiftness Potion II (1:30)","373:8226");
KrimBlockName.put("Poison Potion II (0:22)","373:8228");
KrimBlockName.put("Healing Potion II","373:8229");
KrimBlockName.put("Strength Potion II (1:30)","373:8233");
KrimBlockName.put("Harming Potion II","373:8236");
KrimBlockName.put("Regeneration Potion (2:00)","373:8257");
KrimBlockName.put("Swiftness Potion (8:00)","373:8258");
KrimBlockName.put("Fire Resistance Potion (8:00)","373:8259");
KrimBlockName.put("Poison Potion (2:00)","373:8260");
KrimBlockName.put("Weakness Potion (4:00)","373:8264");
KrimBlockName.put("Strength Potion (8:00)","373:8265");
KrimBlockName.put("Slowness Potion (4:00)","373:8266");
KrimBlockName.put("Fire Resistance Splash (2:15)","373:16378");
KrimBlockName.put("Regeneration Splash (0:33)","373:16385");
KrimBlockName.put("Swiftness Splash (2:15)","373:16386");
KrimBlockName.put("Poison Splash (0:33)","373:16388");
KrimBlockName.put("Healing Splash","373:16389");
KrimBlockName.put("Weakness Splash (1:07)","373:16392");
KrimBlockName.put("Strength Splash (2:15)","373:16393");
KrimBlockName.put("Slowness Splash (1:07)","373:16394");
KrimBlockName.put("Harming Splash","373:16396");
KrimBlockName.put("Swiftness Splash II (1:07)","373:16418");
KrimBlockName.put("Poison Splash II (0:16)","373:16420");
KrimBlockName.put("Healing Splash II","373:16421");
KrimBlockName.put("Strength Splash II (1:07)","373:16425");
KrimBlockName.put("Harming Splash II","373:16428");
KrimBlockName.put("Regeneration Splash (1:30)","373:16449");
KrimBlockName.put("Swiftness Splash (6:00)","373:16450");
KrimBlockName.put("Fire Resistance Splash (6:00)","373:16451");
KrimBlockName.put("Poison Splash (1:30)","373:16452");
KrimBlockName.put("Weakness Splash (3:00)","373:16456");
KrimBlockName.put("Strength Splash (6:00)","373:16457");
KrimBlockName.put("Slowness Splash (3:00)","373:16458");
KrimBlockName.put("Regeneration Splash II (0:16)","373:16471");
KrimBlockName.put("glassbottle","374");
KrimBlockName.put("spidereye","375");
KrimBlockName.put("fermentedspidereye","376");
KrimBlockName.put("blazepowder","377");
KrimBlockName.put("magmacream","378");
KrimBlockName.put("brewingstand","379");
KrimBlockName.put("cauldron","380");
KrimBlockName.put("eyeofender","381");
KrimBlockName.put("glisteringmelon","382");
KrimBlockName.put("spawncreeper","383:50");
KrimBlockName.put("spawnskeleton","383:51");
KrimBlockName.put("spawnspider","383:52");
KrimBlockName.put("spawnzombie","383:54");
KrimBlockName.put("spawnslime","383:55");
KrimBlockName.put("spawnghast","383:56");
KrimBlockName.put("spawnpigzombie","383:57");
KrimBlockName.put("spawnenderman","383:58");
KrimBlockName.put("spawncavespider","383:59");
KrimBlockName.put("spawnsilverfish","383:60");
KrimBlockName.put("spawnblaze","383:61");
KrimBlockName.put("spawnmagmacube","383:62");
KrimBlockName.put("spawnpig","383:90");
KrimBlockName.put("spawnsheep","383:91");
KrimBlockName.put("spawncow","383:92");
KrimBlockName.put("spawnchicken","383:93");
KrimBlockName.put("spawnsquid","383:94");
KrimBlockName.put("spawnwolf","383:95");
KrimBlockName.put("spawnmooshroom","383:96");
KrimBlockName.put("spawnsnowgolem","383:97");
KrimBlockName.put("spawnocelot","383:98");
KrimBlockName.put("spawnirongolem","383:99");
KrimBlockName.put("spawnvillager","383:120");
KrimBlockName.put("bottleo´enchanting","384");
KrimBlockName.put("firecharge","385");
KrimBlockName.put("bookandquill","386");
KrimBlockName.put("writtenbook","387");
KrimBlockName.put("Emerald","388");
KrimBlockName.put("Itemframe","389");
KrimBlockName.put("Flowerpot","390");
KrimBlockName.put("Carrot","391");
KrimBlockName.put("Potatoe","392");
KrimBlockName.put("Bakedpotatoe","393");
KrimBlockName.put("Poisonedpotatoe","394");
KrimBlockName.put("Emptymap","395");
KrimBlockName.put("Goldencarrot","396");
KrimBlockName.put("SkelletonSkull","397");
KrimBlockName.put("Witherhead","397:1");
KrimBlockName.put("Zombiehead","397:2");
KrimBlockName.put("Head","397:3");
KrimBlockName.put("Creeperhead","397:4");
KrimBlockName.put("Carrotonastick","398");
KrimBlockName.put("Netherstar","399");
KrimBlockName.put("Pumpkinpie","400");
KrimBlockName.put("FireRocket","401");
KrimBlockName.put("Firestar","402");
KrimBlockName.put("Enchantedbook","403");
KrimBlockName.put("RedstoneComparator","404");
KrimBlockName.put("Netherbrick","405");
KrimBlockName.put("Netherquartz","406");
KrimBlockName.put("TNTCart","407");
KrimBlockName.put("HopperCart","408");
KrimBlockName.put("Disk C418-13","2256");
KrimBlockName.put("Disk C418-Cat","2257");
KrimBlockName.put("Disk C418-Blocks","2258");
KrimBlockName.put("Disk C418-Chirp","2259");
KrimBlockName.put("Disk C418-Far","2260");
KrimBlockName.put("Disk C418-Mall","2261");
KrimBlockName.put("Disk C418-Mellohi","2262");
KrimBlockName.put("Disk C418-Stall","2263");
KrimBlockName.put("Disk C418-Strad","2264");
KrimBlockName.put("Disk C418-Ward","2265");
KrimBlockName.put("Disk 11","2266");
KrimBlockName.put("Disk C418-Wait","2267");
}
|
diff --git a/contrib/src/main/java/com/datatorrent/contrib/adsdimension/Application.java b/contrib/src/main/java/com/datatorrent/contrib/adsdimension/Application.java
index d1b9a86bb..27081aab5 100644
--- a/contrib/src/main/java/com/datatorrent/contrib/adsdimension/Application.java
+++ b/contrib/src/main/java/com/datatorrent/contrib/adsdimension/Application.java
@@ -1,64 +1,64 @@
/*
* Copyright (c) 2013 DataTorrent, 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.datatorrent.contrib.adsdimension;
import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.api.Context.PortContext;
import com.datatorrent.api.DAG;
import com.datatorrent.api.DAG.Locality;
import com.datatorrent.api.StreamingApplication;
import com.datatorrent.contrib.redis.RedisNumberAggregateOutputOperator;
import java.util.Map;
import org.apache.commons.lang.mutable.MutableDouble;
import org.apache.hadoop.conf.Configuration;
/**
* <p>Application class.</p>
*
* @since 0.3.2
*/
public class Application implements StreamingApplication
{
@Override
public void populateDAG(DAG dag, Configuration conf)
{
dag.setAttribute(DAG.APPLICATION_NAME, "AdsDimensionDemoApplication");
- InputItemGenerator input = dag.addOperator("input", InputItemGenerator.class);
+ InputItemGenerator input = dag.addOperator("InputGenerator", InputItemGenerator.class);
dag.setOutputPortAttribute(input.outputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setAttribute(input, OperatorContext.INITIAL_PARTITION_COUNT, 8);
- InputDimensionGenerator inputDimension = dag.addOperator("inputDimension", InputDimensionGenerator.class);
+ InputDimensionGenerator inputDimension = dag.addOperator("DimensionalDataGenerator", InputDimensionGenerator.class);
dag.setInputPortAttribute(inputDimension.inputPort, PortContext.PARTITION_PARALLEL, true);
dag.setInputPortAttribute(inputDimension.inputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setOutputPortAttribute(inputDimension.outputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
- BucketOperator bucket = dag.addOperator("bucket", BucketOperator.class);
+ BucketOperator bucket = dag.addOperator("MinuteBucketAggregator", BucketOperator.class);
dag.setInputPortAttribute(bucket.inputPort, PortContext.PARTITION_PARALLEL, true);
dag.setInputPortAttribute(bucket.inputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setOutputPortAttribute(bucket.outputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setAttribute(bucket, OperatorContext.APPLICATION_WINDOW_COUNT, 10);
- RedisNumberAggregateOutputOperator<AggrKey, Map<String, MutableDouble>> redis = dag.addOperator("redis", new RedisNumberAggregateOutputOperator<AggrKey, Map<String, MutableDouble>>());
+ RedisNumberAggregateOutputOperator<AggrKey, Map<String, MutableDouble>> redis = dag.addOperator("RedisAdapter", new RedisNumberAggregateOutputOperator<AggrKey, Map<String, MutableDouble>>());
dag.setInputPortAttribute(redis.input, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setAttribute(redis, OperatorContext.INITIAL_PARTITION_COUNT, 2);
- dag.addStream("ingen", input.outputPort, inputDimension.inputPort).setLocality(Locality.CONTAINER_LOCAL);
- dag.addStream("indimgen", inputDimension.outputPort, bucket.inputPort).setLocality(Locality.CONTAINER_LOCAL);
- dag.addStream("store", bucket.outputPort, redis.inputInd);
+ dag.addStream("InputStream", input.outputPort, inputDimension.inputPort).setLocality(Locality.CONTAINER_LOCAL);
+ dag.addStream("DimensionalData", inputDimension.outputPort, bucket.inputPort).setLocality(Locality.CONTAINER_LOCAL);
+ dag.addStream("AggregateData", bucket.outputPort, redis.inputInd);
}
}
| false | true | public void populateDAG(DAG dag, Configuration conf)
{
dag.setAttribute(DAG.APPLICATION_NAME, "AdsDimensionDemoApplication");
InputItemGenerator input = dag.addOperator("input", InputItemGenerator.class);
dag.setOutputPortAttribute(input.outputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setAttribute(input, OperatorContext.INITIAL_PARTITION_COUNT, 8);
InputDimensionGenerator inputDimension = dag.addOperator("inputDimension", InputDimensionGenerator.class);
dag.setInputPortAttribute(inputDimension.inputPort, PortContext.PARTITION_PARALLEL, true);
dag.setInputPortAttribute(inputDimension.inputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setOutputPortAttribute(inputDimension.outputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
BucketOperator bucket = dag.addOperator("bucket", BucketOperator.class);
dag.setInputPortAttribute(bucket.inputPort, PortContext.PARTITION_PARALLEL, true);
dag.setInputPortAttribute(bucket.inputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setOutputPortAttribute(bucket.outputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setAttribute(bucket, OperatorContext.APPLICATION_WINDOW_COUNT, 10);
RedisNumberAggregateOutputOperator<AggrKey, Map<String, MutableDouble>> redis = dag.addOperator("redis", new RedisNumberAggregateOutputOperator<AggrKey, Map<String, MutableDouble>>());
dag.setInputPortAttribute(redis.input, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setAttribute(redis, OperatorContext.INITIAL_PARTITION_COUNT, 2);
dag.addStream("ingen", input.outputPort, inputDimension.inputPort).setLocality(Locality.CONTAINER_LOCAL);
dag.addStream("indimgen", inputDimension.outputPort, bucket.inputPort).setLocality(Locality.CONTAINER_LOCAL);
dag.addStream("store", bucket.outputPort, redis.inputInd);
}
| public void populateDAG(DAG dag, Configuration conf)
{
dag.setAttribute(DAG.APPLICATION_NAME, "AdsDimensionDemoApplication");
InputItemGenerator input = dag.addOperator("InputGenerator", InputItemGenerator.class);
dag.setOutputPortAttribute(input.outputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setAttribute(input, OperatorContext.INITIAL_PARTITION_COUNT, 8);
InputDimensionGenerator inputDimension = dag.addOperator("DimensionalDataGenerator", InputDimensionGenerator.class);
dag.setInputPortAttribute(inputDimension.inputPort, PortContext.PARTITION_PARALLEL, true);
dag.setInputPortAttribute(inputDimension.inputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setOutputPortAttribute(inputDimension.outputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
BucketOperator bucket = dag.addOperator("MinuteBucketAggregator", BucketOperator.class);
dag.setInputPortAttribute(bucket.inputPort, PortContext.PARTITION_PARALLEL, true);
dag.setInputPortAttribute(bucket.inputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setOutputPortAttribute(bucket.outputPort, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setAttribute(bucket, OperatorContext.APPLICATION_WINDOW_COUNT, 10);
RedisNumberAggregateOutputOperator<AggrKey, Map<String, MutableDouble>> redis = dag.addOperator("RedisAdapter", new RedisNumberAggregateOutputOperator<AggrKey, Map<String, MutableDouble>>());
dag.setInputPortAttribute(redis.input, PortContext.QUEUE_CAPACITY, 32 * 1024);
dag.setAttribute(redis, OperatorContext.INITIAL_PARTITION_COUNT, 2);
dag.addStream("InputStream", input.outputPort, inputDimension.inputPort).setLocality(Locality.CONTAINER_LOCAL);
dag.addStream("DimensionalData", inputDimension.outputPort, bucket.inputPort).setLocality(Locality.CONTAINER_LOCAL);
dag.addStream("AggregateData", bucket.outputPort, redis.inputInd);
}
|
diff --git a/src/main/java/mx/edu/um/academia/dao/impl/CursoDaoHibernate.java b/src/main/java/mx/edu/um/academia/dao/impl/CursoDaoHibernate.java
index 6d07fe1..a6ca6bf 100644
--- a/src/main/java/mx/edu/um/academia/dao/impl/CursoDaoHibernate.java
+++ b/src/main/java/mx/edu/um/academia/dao/impl/CursoDaoHibernate.java
@@ -1,1335 +1,1335 @@
/*
* The MIT License
*
* Copyright 2012 Universidad de Montemorelos A. C.
*
* 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 mx.edu.um.academia.dao.impl;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.model.User;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil;
import com.liferay.portlet.journal.model.JournalArticle;
import com.liferay.portlet.journal.service.JournalArticleLocalServiceUtil;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.*;
import mx.edu.um.academia.dao.CursoDao;
import mx.edu.um.academia.dao.ExamenDao;
import mx.edu.um.academia.model.*;
import mx.edu.um.academia.utils.Constantes;
import net.sf.jasperreports.engine.JasperReport;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.*;
import static org.hibernate.type.StandardBasicTypes.STRING;
import static org.hibernate.type.StandardBasicTypes.TIMESTAMP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author J. David Mendoza <[email protected]>
*/
@Repository
@Transactional
public class CursoDaoHibernate implements CursoDao {
private static final Logger log = LoggerFactory.getLogger(CursoDaoHibernate.class);
@Autowired
private SessionFactory sessionFactory;
@Autowired
private ExamenDao examenDao;
@Autowired
private ResourceBundleMessageSource messages;
public CursoDaoHibernate() {
log.info("Nueva instancia del dao de cursos");
}
private Session currentSession() {
return sessionFactory.getCurrentSession();
}
@Override
public Map<String, Object> lista(Map<String, Object> params) {
log.debug("Buscando lista de cursos con params {}", params);
if (params == null) {
params = new HashMap<>();
}
if (!params.containsKey("max") || params.get("max") == null) {
params.put("max", 5);
} else {
params.put("max", Math.min((Integer) params.get("max"), 100));
}
if (params.containsKey("pagina") && params.get("pagina") != null) {
Long pagina = (Long) params.get("pagina");
Long offset = (pagina - 1) * (Integer) params.get("max");
params.put("offset", offset.intValue());
}
if (!params.containsKey("offset") || params.get("offset") == null) {
params.put("offset", 0);
}
Criteria criteria = currentSession().createCriteria(Curso.class);
Criteria countCriteria = currentSession().createCriteria(Curso.class);
if (params.containsKey("comunidades")) {
criteria.add(Restrictions.in("comunidadId", (Set<Integer>) params.get("comunidades")));
countCriteria.add(Restrictions.in("comunidadId", (Set<Integer>) params.get("comunidades")));
}
if (params.containsKey("filtro")) {
String filtro = (String) params.get("filtro");
Disjunction propiedades = Restrictions.disjunction();
propiedades.add(Restrictions.ilike("codigo", filtro, MatchMode.ANYWHERE));
propiedades.add(Restrictions.ilike("nombre", filtro, MatchMode.ANYWHERE));
criteria.add(propiedades);
countCriteria.add(propiedades);
}
if (params.containsKey("order")) {
String campo = (String) params.get("order");
if (params.get("sort").equals("desc")) {
criteria.addOrder(Order.desc(campo));
} else {
criteria.addOrder(Order.asc(campo));
}
}
criteria.addOrder(Order.desc("fechaModificacion"));
criteria.setFirstResult((Integer) params.get("offset"));
criteria.setMaxResults((Integer) params.get("max"));
params.put("cursos", criteria.list());
countCriteria.setProjection(Projections.rowCount());
List cantidades = countCriteria.list();
if (cantidades != null) {
params.put("cantidad", (Long) cantidades.get(0));
} else {
params.put("cantidad", 0L);
}
return params;
}
@Override
public Curso obtiene(Long cursoId) {
log.debug("Obteniendo curso {}", cursoId);
return (Curso) currentSession().get(Curso.class, cursoId);
}
@Override
public Curso obtiene(String codigo, Long comunidadId) {
log.debug("Obteniendo curso por codigo {} y comunidad {}", codigo, comunidadId);
Query query = currentSession().createQuery("select c from Curso c where c.codigo = :codigo and c.comunidadId = :comunidadId");
query.setString("codigo", codigo);
query.setLong("comunidadId", comunidadId);
return (Curso) query.uniqueResult();
}
@Override
public Curso crea(Curso curso, User creador) {
log.debug("Creando curso {} por usuario", curso, creador);
Date fecha = new Date();
curso.setFechaCreacion(fecha);
curso.setFechaModificacion(fecha);
if (creador != null) {
curso.setCreador(creador.getScreenName());
} else {
curso.setCreador("admin");
}
currentSession().save(curso);
currentSession().flush();
Reporte reporte = curso.getReporte();
if (reporte != null) {
this.asignaReporte(reporte, curso);
}
currentSession().flush();
return curso;
}
@Override
public Curso actualiza(Curso otro, User creador) {
log.debug("Actualizando curso {} por usuario {}", otro, creador);
Curso curso = (Curso) currentSession().get(Curso.class, otro.getId());
currentSession().refresh(curso);
Long intro = curso.getIntro();
log.debug("CursoIntro:", curso.getIntro());
BeanUtils.copyProperties(otro, curso, new String[]{"id", "version", "fechaCreacion", "objetos", "intro", "correoId"});
log.debug("CursoIntro:", curso.getIntro());
curso.setIntro(intro);
curso.setFechaModificacion(new Date());
if (creador != null) {
curso.setCreador(creador.getScreenName());
} else {
curso.setCreador("admin");
}
currentSession().update(curso);
currentSession().flush();
Reporte reporte = curso.getReporte();
if (reporte != null) {
this.modificaReporte(reporte, curso);
}
currentSession().flush();
return curso;
}
@Override
public void asignaIntro(Curso curso) {
Query query = currentSession().createQuery("update Curso set intro = :intro where id = :id and version = :version");
query.setLong("intro", curso.getIntro());
query.setLong("id", curso.getId());
query.setLong("version", curso.getVersion());
query.executeUpdate();
}
@Override
public String elimina(Long cursoId, User creador) {
log.debug("Eliminando curso {} por usuario {}", cursoId, creador);
// Dando de baja alumnos
Query query = currentSession().createQuery("delete from AlumnoCurso where id.curso.id = :cursoId");
query.setLong("cursoId", cursoId);
query.executeUpdate();
query = currentSession().createQuery("delete from Reporte where curso.id = :cursoId");
query.setLong("cursoId", cursoId);
query.executeUpdate();
query = currentSession().createQuery("delete from PortletCurso where curso.id = :cursoId");
query.setLong("cursoId", cursoId);
query.executeUpdate();
// Dando de baja los objetos
Curso curso = (Curso) currentSession().get(Curso.class, cursoId);
curso.getObjetos().clear();
currentSession().update(curso);
if (curso.getIntro() != null) {
try {
JournalArticleLocalServiceUtil.deleteJournalArticle(curso.getIntro());
} catch (PortalException | SystemException ex) {
log.error("No se pudo eliminar el articulo de introduccion", ex);
}
}
if (curso.getCorreoId() != null) {
try {
JournalArticleLocalServiceUtil.deleteJournalArticle(curso.getCorreoId());
} catch (PortalException | SystemException ex) {
log.error("No se pudo eliminar el articulo de correo", ex);
}
}
String nombre = curso.getNombre();
currentSession().delete(curso);
return nombre;
}
@Override
public Map<String, Object> objetos(Long id, Set<Long> comunidades) {
log.debug("Buscando los objetos del curso {}", id);
Curso curso = (Curso) currentSession().get(Curso.class, id);
List<ObjetoAprendizaje> objetos = curso.getObjetos();
log.debug("Lista de seleccionados");
for (ObjetoAprendizaje objeto : objetos) {
log.debug("Seleccionado: " + objeto.getNombre());
}
Map<String, Object> resultado = new HashMap<>();
resultado.put("seleccionados", objetos);
Criteria criteria = currentSession().createCriteria(ObjetoAprendizaje.class);
criteria.add(Restrictions.in("comunidadId", (Set<Long>) comunidades));
criteria.addOrder(Order.asc("codigo"));
log.debug("Lista de disponibles");
List<ObjetoAprendizaje> disponibles = criteria.list();
disponibles.removeAll(objetos);
for (ObjetoAprendizaje objeto : disponibles) {
log.debug("Disponible: " + objeto.getNombre());
}
resultado.put("disponibles", disponibles);
log.debug("regresando {}", resultado);
return resultado;
}
@Override
public List<ObjetoAprendizaje> objetos(Long id) {
log.debug("Buscando los objetos del curso {}", id);
Curso curso = (Curso) currentSession().get(Curso.class, id);
List<ObjetoAprendizaje> objetos = curso.getObjetos();
for (ObjetoAprendizaje objeto : objetos) {
log.debug("Seleccionado: " + objeto.getNombre());
}
return objetos;
}
@Override
public void agregaObjetos(Long cursoId, Long[] objetosArray) {
log.debug("Agregando objetos {} a curso {}", objetosArray, cursoId);
Curso curso = (Curso) currentSession().get(Curso.class, cursoId);
curso.getObjetos().clear();
for (Long objetoId : objetosArray) {
curso.getObjetos().add((ObjetoAprendizaje) currentSession().load(ObjetoAprendizaje.class, objetoId));
}
log.debug("Actualizando curso {}", curso);
currentSession().update(curso);
currentSession().flush();
}
@Override
public Map<String, Object> verContenido(Long cursoId) {
Curso curso = (Curso) currentSession().get(Curso.class, cursoId);
List<ObjetoAprendizaje> objetos = curso.getObjetos();
for (ObjetoAprendizaje objeto : objetos) {
for (Contenido contenido : objeto.getContenidos()) {
log.debug("{} : {} : {}", new Object[]{curso.getCodigo(), objeto.getCodigo(), contenido.getCodigo()});
}
}
Map<String, Object> resultado = new HashMap<>();
resultado.put("objetos", objetos);
return resultado;
}
@Override
public List<Curso> todos(Set<Long> comunidades) {
log.debug("Buscando lista de cursos en las comunidades {}", comunidades);
Criteria criteria = currentSession().createCriteria(Curso.class);
criteria.add(Restrictions.in("comunidadId", comunidades));
criteria.addOrder(Order.desc("codigo"));
return criteria.list();
}
@Override
public PortletCurso guardaPortlet(Long cursoId, String portletId) {
Curso curso = (Curso) currentSession().get(Curso.class, cursoId);
PortletCurso portlet = (PortletCurso) currentSession().get(PortletCurso.class, portletId);
if (portlet == null) {
portlet = new PortletCurso(portletId, curso);
currentSession().save(portlet);
} else {
portlet.setCurso(curso);
currentSession().update(portlet);
}
return portlet;
}
@Override
public PortletCurso obtienePortlet(String portletId) {
return (PortletCurso) currentSession().get(PortletCurso.class, portletId);
}
@Override
public Alumno obtieneAlumno(Long id) {
return (Alumno) currentSession().get(Alumno.class, id);
}
@Override
public void inscribe(Curso curso, Alumno alumno, Boolean creaUsuario, String estatus) {
log.debug("Inscribiendo a alumno {} en curso {}", alumno, curso);
if (creaUsuario) {
log.debug("Creando alumno primero");
alumno.setComunidad(curso.getComunidadId());
currentSession().save(alumno);
}
log.debug("Inscribiendo...");
AlumnoCursoPK pk = new AlumnoCursoPK(alumno, curso);
AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().get(AlumnoCurso.class, pk);
if (alumnoCurso == null) {
alumnoCurso = new AlumnoCurso(alumno, curso, estatus);
currentSession().save(alumnoCurso);
} else {
alumnoCurso.setEstatus(estatus);
currentSession().update(alumnoCurso);
}
currentSession().flush();
}
@Override
public Boolean estaInscrito(Long cursoId, Long alumnoId) {
log.debug("Validando si el alumno {} esta inscrito en {}", alumnoId, cursoId);
Curso curso = (Curso) currentSession().load(Curso.class, cursoId);
Alumno alumno = (Alumno) currentSession().load(Alumno.class, alumnoId);
AlumnoCursoPK pk = new AlumnoCursoPK(alumno, curso);
AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().get(AlumnoCurso.class, pk);
boolean resultado = false;
if (alumnoCurso != null && (Constantes.INSCRITO.equals(alumnoCurso.getEstatus()) || Constantes.CONCLUIDO.equals(alumnoCurso.getEstatus()))) {
resultado = true;
}
return resultado;
}
@Override
public List<ObjetoAprendizaje> objetosAlumno(Long cursoId, Long alumnoId, ThemeDisplay themeDisplay) {
log.debug("Obteniendo objetos de aprendizaje del curso {} para el alumno {}", cursoId, alumnoId);
Curso curso = (Curso) currentSession().get(Curso.class, cursoId);
log.debug("{}", curso);
Alumno alumno = (Alumno) currentSession().load(Alumno.class, alumnoId);
log.debug("{}", alumno);
AlumnoCursoPK alumnoCursoPK = new AlumnoCursoPK(alumno, curso);
AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().get(AlumnoCurso.class, alumnoCursoPK);
alumnoCurso.setUltimoAcceso(new Date());
currentSession().update(alumnoCurso);
currentSession().flush();
List<ObjetoAprendizaje> objetos = curso.getObjetos();
boolean noAsignado = true;
boolean activo = false;
Date fecha = new Date();
for (ObjetoAprendizaje objeto : objetos) {
boolean bandera = true;
AlumnoObjetoAprendizajePK pk2 = new AlumnoObjetoAprendizajePK(alumno, objeto);
AlumnoObjetoAprendizaje alumnoObjeto = (AlumnoObjetoAprendizaje) currentSession().get(AlumnoObjetoAprendizaje.class, pk2);
if (alumnoObjeto == null) {
alumnoObjeto = new AlumnoObjetoAprendizaje(alumno, objeto);
currentSession().save(alumnoObjeto);
currentSession().flush();
}
for (Contenido contenido : objeto.getContenidos()) {
log.debug("Cargando contenido {} del objeto {} : activo : {}", new Object[]{contenido, objeto, contenido.getActivo()});
AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido);
AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk);
if (alumnoContenido == null) {
alumnoContenido = new AlumnoContenido(alumno, contenido);
currentSession().save(alumnoContenido);
currentSession().flush();
}
log.debug("Buscando {} : {}", bandera, alumnoContenido.getTerminado());
if (bandera && alumnoContenido.getTerminado() == null && !activo) {
this.asignaContenido(cursoId, alumnoContenido, contenido, themeDisplay);
log.debug("Activando a {}", contenido.getNombre());
contenido.setActivo(bandera);
activo = true;
alumnoContenido.setIniciado(fecha);
currentSession().update(alumnoContenido);
if (alumnoObjeto.getIniciado() == null) {
alumnoObjeto.setIniciado(fecha);
currentSession().update(alumnoObjeto);
}
currentSession().flush();
bandera = false;
noAsignado = false;
}
log.debug("Asignando el contenido {} : activo : {}", contenido.getNombre(), contenido.getActivo());
contenido.setAlumno(alumnoContenido);
}
}
if (noAsignado) {
log.debug("No asignado >> asignando");
for (ObjetoAprendizaje objeto : objetos) {
boolean bandera = true;
AlumnoObjetoAprendizajePK pk2 = new AlumnoObjetoAprendizajePK(alumno, objeto);
AlumnoObjetoAprendizaje alumnoObjeto = (AlumnoObjetoAprendizaje) currentSession().get(AlumnoObjetoAprendizaje.class, pk2);
if (alumnoObjeto == null) {
alumnoObjeto = new AlumnoObjetoAprendizaje(alumno, objeto);
currentSession().save(alumnoObjeto);
currentSession().flush();
}
for (Contenido contenido : objeto.getContenidos()) {
log.debug("Cargando contenido {} del objeto {}", contenido, objeto);
AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido);
AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk);
if (alumnoContenido == null) {
alumnoContenido = new AlumnoContenido(alumno, contenido);
currentSession().save(alumnoContenido);
currentSession().flush();
}
if (bandera && !activo) {
this.asignaContenido(cursoId, alumnoContenido, contenido, themeDisplay);
log.debug("Activando a {}", contenido.getNombre());
contenido.setActivo(true);
activo = true;
alumnoContenido.setIniciado(fecha);
currentSession().update(alumnoContenido);
if (alumnoObjeto.getIniciado() == null) {
alumnoObjeto.setIniciado(fecha);
currentSession().update(alumnoObjeto);
}
currentSession().flush();
bandera = false;
}
contenido.setAlumno(alumnoContenido);
}
}
}
return objetos;
}
@Override
public List<ObjetoAprendizaje> objetosAlumno(Long cursoId, Long contenidoId, Long alumnoId, ThemeDisplay themeDisplay) {
log.debug("Obteniendo objetos de aprendizaje del curso {} para el alumno {}", cursoId, alumnoId);
Curso curso = (Curso) currentSession().get(Curso.class, cursoId);
log.debug("{}", curso);
Alumno alumno = (Alumno) currentSession().load(Alumno.class, alumnoId);
log.debug("{}", alumno);
AlumnoCursoPK alumnoCursoPK = new AlumnoCursoPK(alumno, curso);
AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().get(AlumnoCurso.class, alumnoCursoPK);
alumnoCurso.setUltimoAcceso(new Date());
currentSession().update(alumnoCurso);
currentSession().flush();
List<ObjetoAprendizaje> objetos = curso.getObjetos();
boolean terminado = true;
boolean noAsignado = true;
boolean activo = false;
Date fecha = new Date();
for (ObjetoAprendizaje objeto : objetos) {
AlumnoObjetoAprendizajePK pk2 = new AlumnoObjetoAprendizajePK(alumno, objeto);
AlumnoObjetoAprendizaje alumnoObjeto = (AlumnoObjetoAprendizaje) currentSession().get(AlumnoObjetoAprendizaje.class, pk2);
if (alumnoObjeto == null) {
alumnoObjeto = new AlumnoObjetoAprendizaje(alumno, objeto);
currentSession().save(alumnoObjeto);
currentSession().flush();
}
for (Contenido contenido : objeto.getContenidos()) {
log.debug("Cargando contenido {} del objeto {}", contenido, objeto);
AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido);
AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk);
if (alumnoContenido == null) {
alumnoContenido = new AlumnoContenido(alumno, contenido);
currentSession().save(alumnoContenido);
currentSession().flush();
}
if (contenidoId == contenido.getId() && terminado) {
this.asignaContenido(cursoId, alumnoContenido, contenido, themeDisplay);
contenido.setActivo(true);
noAsignado = false;
activo = true;
log.debug("Validando si ha sido iniciado {}", alumnoContenido.getIniciado());
if (alumnoContenido.getIniciado() == null) {
alumnoContenido.setIniciado(fecha);
currentSession().update(alumnoContenido);
if (alumnoObjeto.getIniciado() == null) {
alumnoObjeto.setIniciado(fecha);
currentSession().update(alumnoObjeto);
}
currentSession().flush();
}
}
if (alumnoContenido.getTerminado() == null) {
terminado = false;
}
contenido.setAlumno(alumnoContenido);
}
}
if (noAsignado) {
for (ObjetoAprendizaje objeto : objetos) {
boolean bandera = true;
AlumnoObjetoAprendizajePK pk2 = new AlumnoObjetoAprendizajePK(alumno, objeto);
AlumnoObjetoAprendizaje alumnoObjeto = (AlumnoObjetoAprendizaje) currentSession().get(AlumnoObjetoAprendizaje.class, pk2);
if (alumnoObjeto == null) {
alumnoObjeto = new AlumnoObjetoAprendizaje(alumno, objeto);
currentSession().save(alumnoObjeto);
currentSession().flush();
}
for (Contenido contenido : objeto.getContenidos()) {
AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido);
AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk);
if (alumnoContenido == null) {
alumnoContenido = new AlumnoContenido(alumno, contenido);
currentSession().save(alumnoContenido);
currentSession().flush();
}
if (bandera && alumnoContenido.getTerminado() == null && !activo) {
this.asignaContenido(cursoId, alumnoContenido, contenido, themeDisplay);
contenido.setActivo(bandera);
bandera = false;
activo = true;
noAsignado = false;
if (alumnoContenido.getIniciado() == null) {
alumnoContenido.setIniciado(fecha);
currentSession().update(alumnoContenido);
if (alumnoObjeto.getIniciado() == null) {
alumnoObjeto.setIniciado(fecha);
currentSession().update(alumnoObjeto);
}
currentSession().flush();
}
}
contenido.setAlumno(alumnoContenido);
}
}
}
if (noAsignado) {
for (ObjetoAprendizaje objeto : objetos) {
boolean bandera = true;
AlumnoObjetoAprendizajePK pk2 = new AlumnoObjetoAprendizajePK(alumno, objeto);
AlumnoObjetoAprendizaje alumnoObjeto = (AlumnoObjetoAprendizaje) currentSession().get(AlumnoObjetoAprendizaje.class, pk2);
if (alumnoObjeto == null) {
alumnoObjeto = new AlumnoObjetoAprendizaje(alumno, objeto);
currentSession().save(alumnoObjeto);
currentSession().flush();
}
for (Contenido contenido : objeto.getContenidos()) {
AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido);
AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk);
if (alumnoContenido == null) {
alumnoContenido = new AlumnoContenido(alumno, contenido);
currentSession().save(alumnoContenido);
currentSession().flush();
}
if (bandera && !activo) {
this.asignaContenido(cursoId, alumnoContenido, contenido, themeDisplay);
contenido.setActivo(bandera);
alumnoContenido.setIniciado(fecha);
currentSession().update(alumnoContenido);
if (alumnoObjeto.getIniciado() == null) {
alumnoObjeto.setIniciado(fecha);
currentSession().update(alumnoObjeto);
}
currentSession().flush();
bandera = false;
activo = true;
}
contenido.setAlumno(alumnoContenido);
}
}
}
return objetos;
}
@Override
public List<ObjetoAprendizaje> objetosAlumnoSiguiente(Long cursoId, Long alumnoId, ThemeDisplay themeDisplay) {
log.debug("Obteniendo siguiente contenido curso {} para el alumno {}", cursoId, alumnoId);
Curso curso = (Curso) currentSession().get(Curso.class, cursoId);
log.debug("{}", curso);
Alumno alumno = (Alumno) currentSession().load(Alumno.class, alumnoId);
log.debug("{}", alumno);
AlumnoCursoPK alumnoCursoPK = new AlumnoCursoPK(alumno, curso);
AlumnoCurso ac = (AlumnoCurso) currentSession().get(AlumnoCurso.class, alumnoCursoPK);
ac.setUltimoAcceso(new Date());
currentSession().update(ac);
currentSession().flush();
List<ObjetoAprendizaje> objetos = curso.getObjetos();
boolean noAsignado = true;
boolean activo = false;
Date fecha = new Date();
for (ObjetoAprendizaje objeto : objetos) {
boolean bandera = true;
AlumnoObjetoAprendizajePK pk2 = new AlumnoObjetoAprendizajePK(alumno, objeto);
AlumnoObjetoAprendizaje alumnoObjeto = (AlumnoObjetoAprendizaje) currentSession().get(AlumnoObjetoAprendizaje.class, pk2);
if (alumnoObjeto == null) {
alumnoObjeto = new AlumnoObjetoAprendizaje(alumno, objeto);
currentSession().save(alumnoObjeto);
currentSession().flush();
}
for (Contenido contenido : objeto.getContenidos()) {
log.debug("Cargando contenido {} del objeto {}", contenido, objeto);
AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido);
AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk);
if (alumnoContenido == null) {
alumnoContenido = new AlumnoContenido(alumno, contenido);
currentSession().save(alumnoContenido);
currentSession().flush();
}
if (bandera && alumnoContenido.getTerminado() == null && !activo) {
if (alumnoContenido.getIniciado() == null) {
this.asignaContenido(cursoId, alumnoContenido, contenido, themeDisplay);
contenido.setActivo(bandera);
activo = true;
alumnoContenido.setIniciado(fecha);
currentSession().update(alumnoContenido);
if (alumnoObjeto.getIniciado() == null) {
alumnoObjeto.setIniciado(fecha);
currentSession().update(alumnoObjeto);
}
currentSession().flush();
bandera = false;
noAsignado = false;
} else {
alumnoContenido.setTerminado(fecha);
currentSession().update(alumnoContenido);
currentSession().flush();
}
}
contenido.setAlumno(alumnoContenido);
}
if (!activo) {
alumnoObjeto.setTerminado(fecha);
currentSession().update(alumnoObjeto);
}
}
if (noAsignado) {
log.debug("Asignando contenido");
for (ObjetoAprendizaje objeto : objetos) {
boolean bandera = true;
for (Contenido contenido : objeto.getContenidos()) {
AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido);
AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk);
if (alumnoContenido == null) {
alumnoContenido = new AlumnoContenido(alumno, contenido);
currentSession().save(alumnoContenido);
currentSession().flush();
}
if (bandera && !activo) {
this.asignaContenido(cursoId, alumnoContenido, contenido, themeDisplay);
contenido.setActivo(bandera);
activo = true;
if (alumnoContenido.getIniciado() == null) {
alumnoContenido.setIniciado(fecha);
} else {
AlumnoCursoPK pk2 = new AlumnoCursoPK(alumno, curso);
AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().get(AlumnoCurso.class, pk2);
alumnoCurso.setEstatus(Constantes.CONCLUIDO);
alumnoCurso.setFechaConclusion(fecha);
currentSession().update(alumnoCurso);
AlumnoObjetoAprendizajePK pk3 = new AlumnoObjetoAprendizajePK(alumno, objeto);
AlumnoObjetoAprendizaje alumnoObjeto = (AlumnoObjetoAprendizaje) currentSession().get(AlumnoObjetoAprendizaje.class, pk3);
alumnoObjeto.setTerminado(fecha);
currentSession().update(alumnoObjeto);
currentSession().flush();
}
currentSession().update(alumnoContenido);
currentSession().flush();
bandera = false;
}
contenido.setAlumno(alumnoContenido);
}
}
}
return objetos;
}
@Override
public List<AlumnoCurso> alumnos(Long cursoId) {
log.debug("Lista de alumnos del curso {}", cursoId);
Query query = currentSession().createQuery("select a from AlumnoCurso a where a.id.curso.id = :cursoId");
query.setLong("cursoId", cursoId);
return query.list();
}
@Override
public void inscribe(Long cursoId, Long alumnoId) {
log.debug("Inscribe alumno {} a curso {}", alumnoId, cursoId);
Curso curso = (Curso) currentSession().get(Curso.class, cursoId);
Alumno alumno = (Alumno) currentSession().get(Alumno.class, alumnoId);
if (alumno == null) {
try {
User usuario = UserLocalServiceUtil.getUser(alumnoId);
alumno = new Alumno(usuario);
alumno.setComunidad(curso.getComunidadId());
currentSession().save(alumno);
currentSession().flush();
} catch (PortalException | SystemException ex) {
log.error("No se pudo obtener el usuario", ex);
}
}
AlumnoCursoPK pk = new AlumnoCursoPK(alumno, curso);
AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().get(AlumnoCurso.class, pk);
if (alumnoCurso == null) {
alumnoCurso = new AlumnoCurso(pk, Constantes.INSCRITO);
currentSession().save(alumnoCurso);
} else {
alumnoCurso.setEstatus(Constantes.INSCRITO);
alumnoCurso.setFecha(new Date());
currentSession().update(alumnoCurso);
}
}
@Override
public Map<String, Object> alumnos(Map<String, Object> params) {
Long cursoId = (Long) params.get("cursoId");
Query query = currentSession().createQuery("select a from AlumnoCurso a join fetch a.id.curso where a.id.curso.id = :cursoId");
query.setLong("cursoId", cursoId);
List<AlumnoCurso> alumnos = query.list();
for (AlumnoCurso alumnoCurso : alumnos) {
alumnoCurso.setSaldo(alumnoCurso.getId().getCurso().getPrecio());
}
params.put("alumnos", alumnos);
Curso curso = (Curso) currentSession().get(Curso.class, cursoId);
params.put("curso", curso);
try {
log.debug("Buscando usuarios en la empresa {}", params.get("companyId"));
List<User> usuarios = UserLocalServiceUtil.getCompanyUsers((Long) params.get("companyId"), QueryUtil.ALL_POS, QueryUtil.ALL_POS);
List<User> lista = new ArrayList<>();
for (User user : usuarios) {
if (!user.isDefaultUser()) {
lista.add(user);
}
}
params.put("disponibles", lista);
} catch (SystemException e) {
log.error("No se pudo obtener lista de usuarios", e);
}
return params;
}
private void asignaContenido(Long cursoId, AlumnoContenido alumnoContenido, Contenido contenido, ThemeDisplay themeDisplay) {
try {
StringBuilder sb2 = new StringBuilder();
sb2.append("admin");
sb2.append(cursoId);
sb2.append(contenido.getId());
sb2.append(Constantes.SALT);
JournalArticle ja;
switch (contenido.getTipo()) {
case Constantes.ARTICULATE:
StringBuilder sb = new StringBuilder();
sb.append("<iframe src='/academia-portlet");
sb.append("/conteni2");
sb.append("/admin");
sb.append("/").append(cursoId);
sb.append("/").append(contenido.getId());
sb.append("/").append(DigestUtils.shaHex(sb2.toString()));
sb.append("/player.html");
sb.append("' style='width:100%;height:600px;'></iframe>");
contenido.setTexto(sb.toString());
break;
case Constantes.STORYLINE:
sb = new StringBuilder();
sb.append("<iframe src='/academia-portlet");
sb.append("/conteni2");
sb.append("/admin");
sb.append("/").append(cursoId);
sb.append("/").append(contenido.getId());
sb.append("/").append(DigestUtils.shaHex(sb2.toString()));
sb.append("/story.html");
sb.append("' style='width:100%;height:650px;'></iframe>");
contenido.setTexto(sb.toString());
break;
case Constantes.TEXTO:
ja = JournalArticleLocalServiceUtil.getArticle(contenido.getContenidoId());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
contenido.setTexto(texto);
}
break;
case Constantes.VIDEO:
log.debug("Buscando el video con el id {}", contenido.getContenidoId());
DLFileEntry fileEntry = DLFileEntryLocalServiceUtil.getDLFileEntry(contenido.getContenidoId());
if (fileEntry != null) {
StringBuilder videoLink = new StringBuilder();
videoLink.append("/documents/");
videoLink.append(fileEntry.getGroupId());
videoLink.append("/");
videoLink.append(fileEntry.getFolderId());
videoLink.append("/");
videoLink.append(fileEntry.getTitle());
contenido.setTexto(videoLink.toString());
}
break;
case Constantes.EXAMEN:
Examen examen = contenido.getExamen();
if (examen.getContenido() != null) {
ja = JournalArticleLocalServiceUtil.getArticle(examen.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
contenido.setTexto(texto);
}
}
List<Pregunta> preguntas = new ArrayList<>();
for (Pregunta pregunta : examenDao.preguntas(examen.getId())) {
for (Respuesta respuesta : pregunta.getRespuestas()) {
if (respuesta.getContenido() != null) {
ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
respuesta.setTexto(texto);
}
} else {
String texto = messages.getMessage("respuesta.requiere.texto", new String[]{respuesta.getNombre()}, themeDisplay.getLocale());
respuesta.setTexto(texto);
}
}
if (pregunta.getContenido() != null) {
ja = JournalArticleLocalServiceUtil.getArticle(pregunta.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
pregunta.setTexto(texto);
}
} else {
String texto = messages.getMessage("pregunta.requiere.texto", new String[]{pregunta.getNombre()}, themeDisplay.getLocale());
pregunta.setTexto(texto);
}
preguntas.add(pregunta);
}
if (preguntas.size() > 0) {
for (Pregunta pregunta : preguntas) {
log.debug("{} ||| {}", pregunta, pregunta.getTexto());
}
examen.setOtrasPreguntas(preguntas);
}
break;
}
log.debug("Validando si ha sido iniciado {}", alumnoContenido.getIniciado());
if (alumnoContenido.getIniciado() == null) {
alumnoContenido.setIniciado(new Date());
currentSession().update(alumnoContenido);
currentSession().flush();
}
} catch (PortalException | SystemException e) {
log.error("No se pudo obtener el texto del contenido", e);
}
}
@Override
public Examen obtieneExamen(Long examenId) {
Examen examen = (Examen) currentSession().get(Examen.class, examenId);
return examen;
}
@Override
public Map<String, Object> califica(Map<String, String[]> params, ThemeDisplay themeDisplay, User usuario) {
try {
Examen examen = (Examen) currentSession().get(Examen.class, new Long(params.get("examenId")[0]));
Integer totalExamen = 0;
Integer totalUsuario = 0;
Set<Pregunta> incorrectas = new LinkedHashSet<>();
for (ExamenPregunta examenPregunta : examen.getPreguntas()) {
Pregunta pregunta = examenPregunta.getId().getPregunta();
log.debug("{}({}:{}) > Multiple : {} || Por pregunta : {}", new Object[]{pregunta.getNombre(), pregunta.getId(), examen.getId(), pregunta.getEsMultiple(), examenPregunta.getPorPregunta()});
if (pregunta.getEsMultiple() && examenPregunta.getPorPregunta()) {
// Cuando puede tener muchas respuestas y los puntos son por pregunta
log.debug("ENTRO 1");
totalExamen += examenPregunta.getPuntos();
String[] respuestas = params.get(pregunta.getId().toString());
List<String> correctas = new ArrayList<>();
if (respuestas.length == pregunta.getCorrectas().size()) {
boolean vaBien = true;
for (Respuesta correcta : pregunta.getCorrectas()) {
boolean encontre = false;
for (String respuesta : respuestas) {
if (respuesta.equals(correcta.getId().toString())) {
encontre = true;
correctas.add(respuesta);
break;
}
}
if (!encontre) {
vaBien = false;
}
}
if (vaBien) {
totalUsuario += examenPregunta.getPuntos();
} else {
// pon respuesta incorrecta
for (String respuestaId : respuestas) {
if (!correctas.contains(respuestaId)) {
Respuesta respuesta = (Respuesta) currentSession().get(Respuesta.class, new Long(respuestaId));
JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
respuesta.setTexto(texto);
}
pregunta.getRespuestas().add(respuesta);
}
}
JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(pregunta.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
pregunta.setTexto(texto);
}
incorrectas.add(pregunta);
}
}
} else {
// Cuando puede tener muchas respuestas pero los puntos son por respuesta
// Tambien cuando es una sola respuesta la correcta
log.debug("ENTRO 2");
String[] respuestas = params.get(pregunta.getId().toString());
List<String> correctas = new ArrayList<>();
if (respuestas.length <= pregunta.getCorrectas().size()) {
log.debug("ENTRO 3");
respuestasLoop:
for (Respuesta correcta : pregunta.getCorrectas()) {
- log.debug("Sumando {} a {} para el total de puntos del examen", examenPregunta.getPuntos(), totalExamen);
+ log.debug("Pregunta: {} | Examen: {} | Alumno: {}", new Object[] {examenPregunta.getPuntos(), totalExamen, totalUsuario});
totalExamen += examenPregunta.getPuntos();
for (String respuesta : respuestas) {
if (respuesta.equals(correcta.getId().toString())) {
totalUsuario += examenPregunta.getPuntos();
correctas.add(respuesta);
continue respuestasLoop;
}
}
}
if (correctas.size() < pregunta.getCorrectas().size()) {
// pon respuesta incorrecta
for (String respuestaId : respuestas) {
if (!correctas.contains(respuestaId)) {
Respuesta respuesta = (Respuesta) currentSession().get(Respuesta.class, new Long(respuestaId));
JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
respuesta.setTexto(texto);
}
pregunta.getRespuestas().add(respuesta);
}
}
JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(pregunta.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
pregunta.setTexto(texto);
}
incorrectas.add(pregunta);
}
}
}
log.debug("Pregunta {} : Respuesta {} : Usuario {}", new Object[]{pregunta.getId(), pregunta.getCorrectas(), params.get(pregunta.getId().toString())});
}
Map<String, Object> resultados = new HashMap<>();
resultados.put("examen", examen);
resultados.put("totalExamen", totalExamen);
resultados.put("totalUsuario", totalUsuario);
resultados.put("totales", new String[]{totalUsuario.toString(), totalExamen.toString(), examen.getPuntos().toString()});
if (examen.getPuntos() != null && totalUsuario < examen.getPuntos()) {
resultados.put("messageTitle", "desaprobado");
resultados.put("messageType", "alert-error");
Long contenidoId = new Long(params.get("contenidoId")[0]);
Alumno alumno = (Alumno) currentSession().load(Alumno.class, usuario.getUserId());
Contenido contenido = (Contenido) currentSession().load(Contenido.class, contenidoId);
AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido);
AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk);
if (alumnoContenido != null && alumnoContenido.getTerminado() != null) {
alumnoContenido.setTerminado(null);
currentSession().update(alumnoContenido);
currentSession().flush();
}
} else {
resultados.put("messageTitle", "aprobado");
resultados.put("messageType", "alert-success");
for (String key : params.keySet()) {
log.debug("{} : {}", key, params.get(key));
}
Long contenidoId = new Long(params.get("contenidoId")[0]);
Alumno alumno = (Alumno) currentSession().load(Alumno.class, usuario.getUserId());
Contenido contenido = (Contenido) currentSession().load(Contenido.class, contenidoId);
AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido);
AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk);
if (alumnoContenido != null) {
alumnoContenido.setTerminado(new Date());
currentSession().update(alumnoContenido);
currentSession().flush();
}
}
if (incorrectas.size() > 0) {
resultados.put("incorrectas", incorrectas);
}
return resultados;
} catch (PortalException | SystemException e) {
log.error("No se pudo calificar el examen", e);
}
return null;
}
@Override
public Boolean haConcluido(Long alumnoId, Long cursoId) {
Curso curso = (Curso) currentSession().load(Curso.class, cursoId);
Alumno alumno = (Alumno) currentSession().load(Alumno.class, alumnoId);
AlumnoCursoPK pk = new AlumnoCursoPK(alumno, curso);
AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().get(AlumnoCurso.class, pk);
boolean resultado = false;
if (alumnoCurso.getEstatus().equals(Constantes.CONCLUIDO)) {
resultado = true;
}
return resultado;
}
@Override
public List<AlumnoCurso> obtieneCursos(Long alumnoId) {
log.debug("Buscando los cursos del alumno {}", alumnoId);
Query query = currentSession().createQuery("select ac from AlumnoCurso ac "
+ "join fetch ac.id.curso "
+ "where ac.id.alumno.id = :alumnoId "
+ "order by fecha desc");
query.setLong("alumnoId", alumnoId);
return query.list();
}
@Override
public AlumnoCurso obtieneAlumnoCurso(Long alumnoId, Long cursoId) {
log.debug("Buscando el curso con {} y {}", alumnoId, cursoId);
Query query = currentSession().createQuery("select ac from AlumnoCurso ac "
+ "join fetch ac.id.alumno "
+ "join fetch ac.id.curso "
+ "where ac.id.alumno.id = :alumnoId "
+ "and ac.id.curso.id = :cursoId");
query.setLong("alumnoId", alumnoId);
query.setLong("cursoId", cursoId);
AlumnoCurso alumnoCurso = (AlumnoCurso) query.uniqueResult();
if (alumnoCurso != null) {
alumnoCurso.setUltimoAcceso(new Date());
currentSession().save(alumnoCurso);
currentSession().flush();
}
log.debug("Regresando el alumnoCurso {}", alumnoCurso);
return alumnoCurso;
}
public void asignaReporte(Reporte reporte, Curso curso) {
reporte.setNombre(curso.getCodigo());
reporte.setCurso(curso);
Date fecha = new Date();
reporte.setFechaModificacion(fecha);
reporte.setFechaCreacion(fecha);
currentSession().save(reporte);
}
public void modificaReporte(Reporte reporte, Curso curso) {
Query query = currentSession().createQuery("select r from Reporte r where r.curso.id = :cursoId");
query.setLong("cursoId", curso.getId());
Reporte otro = (Reporte) query.uniqueResult();
if (otro != null) {
otro.setCompilado(reporte.getCompilado());
otro.setNombre(curso.getCodigo());
Date fecha = new Date();
otro.setFechaModificacion(fecha);
currentSession().update(otro);
} else {
this.asignaReporte(reporte, curso);
}
}
@Override
public JasperReport obtieneReporte(Long cursoId) {
Query query = currentSession().createQuery("select r from Reporte r where r.curso.id = :cursoId");
query.setLong("cursoId", cursoId);
Reporte reporte = (Reporte) query.uniqueResult();
JasperReport jr = reporte.getReporte();
return jr;
}
@Override
public Map<String, Object> todosAlumnos(Map<String, Object> params) {
MathContext mc = new MathContext(16, RoundingMode.HALF_UP);
Long comunidadId = (Long) params.get("comunidadId");
Query query = currentSession().createQuery("select a from AlumnoCurso a "
+ "join fetch a.id.alumno "
+ "join fetch a.id.curso "
+ "where a.id.curso.comunidadId = :comunidadId");
query.setLong("comunidadId", comunidadId);
List<AlumnoCurso> lista = query.list();
Map<String, AlumnoCurso> map = new TreeMap<>();
for (AlumnoCurso alumnoCurso : lista) {
AlumnoCurso a = map.get(alumnoCurso.getAlumno().getUsuario());
if (a == null) {
a = alumnoCurso;
try {
boolean cambio = false;
User user = UserLocalServiceUtil.getUser(alumnoCurso.getId().getAlumno().getId());
Alumno alumno = a.getAlumno();
if (!alumno.getCorreo().equals(user.getEmailAddress())) {
alumno.setCorreo(user.getEmailAddress());
cambio = true;
}
if (!alumno.getNombreCompleto().equals(user.getFullName())) {
alumno.setNombreCompleto(user.getFullName());
cambio = true;
}
if (!alumno.getUsuario().equals(user.getScreenName())) {
alumno.setUsuario(user.getScreenName());
cambio = true;
}
if (cambio) {
currentSession().update(alumno);
}
} catch (PortalException | SystemException ex) {
log.error("No se pudo obtener al usuario", ex);
}
}
StringBuilder sb = new StringBuilder();
if (StringUtils.isNotBlank(a.getCursos())) {
sb.append(a.getCursos());
sb.append(", ");
}
sb.append(alumnoCurso.getCurso().getCodigo());
a.setCursos(sb.toString());
a.setSaldo(a.getSaldo().add(alumnoCurso.getCurso().getPrecio(), mc).setScale(2, RoundingMode.HALF_UP));
map.put(alumnoCurso.getAlumno().getUsuario(), a);
}
params.put("alumnos", map.values());
return params;
}
@Override
public void bajaAlumno(Long alumnoId, Long cursoId) {
log.debug("Baja a alumno {} de curso {}", alumnoId, cursoId);
Curso curso = (Curso) currentSession().load(Curso.class, cursoId);
Alumno alumno = (Alumno) currentSession().load(Alumno.class, alumnoId);
AlumnoCursoPK pk = new AlumnoCursoPK(alumno, curso);
AlumnoCurso alumnoCurso = (AlumnoCurso) currentSession().load(AlumnoCurso.class, pk);
currentSession().delete(alumnoCurso);
}
@Override
public void asignaCorreo(Curso curso) {
Query query = currentSession().createQuery("update Curso set correoId = :correoId where id = :id and version = :version");
query.setLong("correoId", curso.getCorreoId());
query.setLong("id", curso.getId());
query.setLong("version", curso.getVersion());
query.executeUpdate();
}
@Override
public Salon obtieneSalon(Long cursoId) {
log.debug("Obtiene salon por el curso {}", cursoId);
Query query = currentSession().createQuery("select s from Salon s where s.curso.id = :cursoId");
query.setLong("cursoId", cursoId);
return (Salon) query.uniqueResult();
}
@Override
public Salon creaSalon(Salon salon) {
log.debug("Creando salon {}", salon);
currentSession().save(salon);
return salon;
}
@Override
public Salon obtieneSalonPorId(Long salonId) {
log.debug("Obtiene salon por su id {}", salonId);
Salon salon = (Salon) currentSession().get(Salon.class, salonId);
return salon;
}
@Override
public Salon actualizaSalon(Salon salon) {
log.debug("Actualizando el salon {}", salon);
currentSession().update(salon);
return salon;
}
@Override
public void eliminaSalon(Salon salon) {
log.debug("Eliminando salon {}", salon);
currentSession().delete(salon);
}
@Override
public void actualizaObjetos(Long cursoId, Long[] objetos) {
log.debug("Actualizando objetos {} del curso {}", objetos, cursoId);
Curso curso = (Curso) currentSession().get(Curso.class, cursoId);
curso.getObjetos().clear();
currentSession().update(curso);
currentSession().flush();
if (objetos != null) {
for (Long objetoId : objetos) {
curso.getObjetos().add((ObjetoAprendizaje) currentSession().load(ObjetoAprendizaje.class, objetoId));
}
currentSession().update(curso);
currentSession().flush();
}
}
@Override
public List<ObjetoAprendizaje> buscaObjetos(Long cursoId, String filtro) {
Query query = currentSession().createQuery("select comunidadId from Curso where id = :cursoId");
query.setLong("cursoId", cursoId);
Long comunidadId = (Long) query.uniqueResult();
query = currentSession().createQuery("select o.id from Curso c inner join c.objetos as o where c.id = :cursoId");
query.setLong("cursoId", cursoId);
List<Long> ids = query.list();
Criteria criteria = currentSession().createCriteria(ObjetoAprendizaje.class);
if (comunidadId != 23461L) {
criteria.add(Restrictions.eq("comunidadId", comunidadId));
}
if (ids != null && ids.size() > 0) {
criteria.add(Restrictions.not(Restrictions.in("id", ids)));
}
Disjunction propiedades = Restrictions.disjunction();
propiedades.add(Restrictions.ilike("codigo", filtro, MatchMode.ANYWHERE));
propiedades.add(Restrictions.ilike("nombre", filtro, MatchMode.ANYWHERE));
criteria.add(propiedades);
criteria.addOrder(Order.asc("codigo"));
return criteria.list();
}
@Override
public List<Map> contenidos(Long alumnoId, Long cursoId) {
String s = "SELECT o.nombre as objetoNombre, ao.iniciado as objetoIniciado, ao.terminado as objetoTerminado, c.nombre as contenidoNombre, ac.iniciado as contenidoIniciado, ac.terminado as contenidoTerminado "
+ "FROM aca_cursos_aca_objetos co, aca_objetos_aca_contenidos oc, aca_alumno_objeto ao, aca_alumno_contenido ac, aca_objetos o, aca_contenidos c "
+ "where co.cursos_id = :cursoId "
+ "and co.objetos_id = oc.objetos_id "
+ "and co.objetos_id = ao.objeto_id "
+ "and ao.alumno_id = ac.alumno_id "
+ "and oc.contenidos_id = ac.contenido_id "
+ "and co.objetos_id = o.id "
+ "and ac.contenido_id = c.id "
+ "and ao.alumno_id = :alumnoId "
+ "order by co.orden, oc.orden";
SQLQuery query = currentSession().createSQLQuery(s);
query.setLong("cursoId", cursoId);
query.setLong("alumnoId", alumnoId);
query.addScalar("objetoNombre", STRING);
query.addScalar("objetoIniciado", TIMESTAMP);
query.addScalar("objetoTerminado", TIMESTAMP);
query.addScalar("contenidoNombre", STRING);
query.addScalar("contenidoIniciado", TIMESTAMP);
query.addScalar("contenidoTerminado", TIMESTAMP);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
return query.list();
}
}
| true | true | public Map<String, Object> califica(Map<String, String[]> params, ThemeDisplay themeDisplay, User usuario) {
try {
Examen examen = (Examen) currentSession().get(Examen.class, new Long(params.get("examenId")[0]));
Integer totalExamen = 0;
Integer totalUsuario = 0;
Set<Pregunta> incorrectas = new LinkedHashSet<>();
for (ExamenPregunta examenPregunta : examen.getPreguntas()) {
Pregunta pregunta = examenPregunta.getId().getPregunta();
log.debug("{}({}:{}) > Multiple : {} || Por pregunta : {}", new Object[]{pregunta.getNombre(), pregunta.getId(), examen.getId(), pregunta.getEsMultiple(), examenPregunta.getPorPregunta()});
if (pregunta.getEsMultiple() && examenPregunta.getPorPregunta()) {
// Cuando puede tener muchas respuestas y los puntos son por pregunta
log.debug("ENTRO 1");
totalExamen += examenPregunta.getPuntos();
String[] respuestas = params.get(pregunta.getId().toString());
List<String> correctas = new ArrayList<>();
if (respuestas.length == pregunta.getCorrectas().size()) {
boolean vaBien = true;
for (Respuesta correcta : pregunta.getCorrectas()) {
boolean encontre = false;
for (String respuesta : respuestas) {
if (respuesta.equals(correcta.getId().toString())) {
encontre = true;
correctas.add(respuesta);
break;
}
}
if (!encontre) {
vaBien = false;
}
}
if (vaBien) {
totalUsuario += examenPregunta.getPuntos();
} else {
// pon respuesta incorrecta
for (String respuestaId : respuestas) {
if (!correctas.contains(respuestaId)) {
Respuesta respuesta = (Respuesta) currentSession().get(Respuesta.class, new Long(respuestaId));
JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
respuesta.setTexto(texto);
}
pregunta.getRespuestas().add(respuesta);
}
}
JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(pregunta.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
pregunta.setTexto(texto);
}
incorrectas.add(pregunta);
}
}
} else {
// Cuando puede tener muchas respuestas pero los puntos son por respuesta
// Tambien cuando es una sola respuesta la correcta
log.debug("ENTRO 2");
String[] respuestas = params.get(pregunta.getId().toString());
List<String> correctas = new ArrayList<>();
if (respuestas.length <= pregunta.getCorrectas().size()) {
log.debug("ENTRO 3");
respuestasLoop:
for (Respuesta correcta : pregunta.getCorrectas()) {
log.debug("Sumando {} a {} para el total de puntos del examen", examenPregunta.getPuntos(), totalExamen);
totalExamen += examenPregunta.getPuntos();
for (String respuesta : respuestas) {
if (respuesta.equals(correcta.getId().toString())) {
totalUsuario += examenPregunta.getPuntos();
correctas.add(respuesta);
continue respuestasLoop;
}
}
}
if (correctas.size() < pregunta.getCorrectas().size()) {
// pon respuesta incorrecta
for (String respuestaId : respuestas) {
if (!correctas.contains(respuestaId)) {
Respuesta respuesta = (Respuesta) currentSession().get(Respuesta.class, new Long(respuestaId));
JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
respuesta.setTexto(texto);
}
pregunta.getRespuestas().add(respuesta);
}
}
JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(pregunta.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
pregunta.setTexto(texto);
}
incorrectas.add(pregunta);
}
}
}
log.debug("Pregunta {} : Respuesta {} : Usuario {}", new Object[]{pregunta.getId(), pregunta.getCorrectas(), params.get(pregunta.getId().toString())});
}
Map<String, Object> resultados = new HashMap<>();
resultados.put("examen", examen);
resultados.put("totalExamen", totalExamen);
resultados.put("totalUsuario", totalUsuario);
resultados.put("totales", new String[]{totalUsuario.toString(), totalExamen.toString(), examen.getPuntos().toString()});
if (examen.getPuntos() != null && totalUsuario < examen.getPuntos()) {
resultados.put("messageTitle", "desaprobado");
resultados.put("messageType", "alert-error");
Long contenidoId = new Long(params.get("contenidoId")[0]);
Alumno alumno = (Alumno) currentSession().load(Alumno.class, usuario.getUserId());
Contenido contenido = (Contenido) currentSession().load(Contenido.class, contenidoId);
AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido);
AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk);
if (alumnoContenido != null && alumnoContenido.getTerminado() != null) {
alumnoContenido.setTerminado(null);
currentSession().update(alumnoContenido);
currentSession().flush();
}
} else {
resultados.put("messageTitle", "aprobado");
resultados.put("messageType", "alert-success");
for (String key : params.keySet()) {
log.debug("{} : {}", key, params.get(key));
}
Long contenidoId = new Long(params.get("contenidoId")[0]);
Alumno alumno = (Alumno) currentSession().load(Alumno.class, usuario.getUserId());
Contenido contenido = (Contenido) currentSession().load(Contenido.class, contenidoId);
AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido);
AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk);
if (alumnoContenido != null) {
alumnoContenido.setTerminado(new Date());
currentSession().update(alumnoContenido);
currentSession().flush();
}
}
if (incorrectas.size() > 0) {
resultados.put("incorrectas", incorrectas);
}
return resultados;
} catch (PortalException | SystemException e) {
log.error("No se pudo calificar el examen", e);
}
return null;
}
| public Map<String, Object> califica(Map<String, String[]> params, ThemeDisplay themeDisplay, User usuario) {
try {
Examen examen = (Examen) currentSession().get(Examen.class, new Long(params.get("examenId")[0]));
Integer totalExamen = 0;
Integer totalUsuario = 0;
Set<Pregunta> incorrectas = new LinkedHashSet<>();
for (ExamenPregunta examenPregunta : examen.getPreguntas()) {
Pregunta pregunta = examenPregunta.getId().getPregunta();
log.debug("{}({}:{}) > Multiple : {} || Por pregunta : {}", new Object[]{pregunta.getNombre(), pregunta.getId(), examen.getId(), pregunta.getEsMultiple(), examenPregunta.getPorPregunta()});
if (pregunta.getEsMultiple() && examenPregunta.getPorPregunta()) {
// Cuando puede tener muchas respuestas y los puntos son por pregunta
log.debug("ENTRO 1");
totalExamen += examenPregunta.getPuntos();
String[] respuestas = params.get(pregunta.getId().toString());
List<String> correctas = new ArrayList<>();
if (respuestas.length == pregunta.getCorrectas().size()) {
boolean vaBien = true;
for (Respuesta correcta : pregunta.getCorrectas()) {
boolean encontre = false;
for (String respuesta : respuestas) {
if (respuesta.equals(correcta.getId().toString())) {
encontre = true;
correctas.add(respuesta);
break;
}
}
if (!encontre) {
vaBien = false;
}
}
if (vaBien) {
totalUsuario += examenPregunta.getPuntos();
} else {
// pon respuesta incorrecta
for (String respuestaId : respuestas) {
if (!correctas.contains(respuestaId)) {
Respuesta respuesta = (Respuesta) currentSession().get(Respuesta.class, new Long(respuestaId));
JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
respuesta.setTexto(texto);
}
pregunta.getRespuestas().add(respuesta);
}
}
JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(pregunta.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
pregunta.setTexto(texto);
}
incorrectas.add(pregunta);
}
}
} else {
// Cuando puede tener muchas respuestas pero los puntos son por respuesta
// Tambien cuando es una sola respuesta la correcta
log.debug("ENTRO 2");
String[] respuestas = params.get(pregunta.getId().toString());
List<String> correctas = new ArrayList<>();
if (respuestas.length <= pregunta.getCorrectas().size()) {
log.debug("ENTRO 3");
respuestasLoop:
for (Respuesta correcta : pregunta.getCorrectas()) {
log.debug("Pregunta: {} | Examen: {} | Alumno: {}", new Object[] {examenPregunta.getPuntos(), totalExamen, totalUsuario});
totalExamen += examenPregunta.getPuntos();
for (String respuesta : respuestas) {
if (respuesta.equals(correcta.getId().toString())) {
totalUsuario += examenPregunta.getPuntos();
correctas.add(respuesta);
continue respuestasLoop;
}
}
}
if (correctas.size() < pregunta.getCorrectas().size()) {
// pon respuesta incorrecta
for (String respuestaId : respuestas) {
if (!correctas.contains(respuestaId)) {
Respuesta respuesta = (Respuesta) currentSession().get(Respuesta.class, new Long(respuestaId));
JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
respuesta.setTexto(texto);
}
pregunta.getRespuestas().add(respuesta);
}
}
JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(pregunta.getContenido());
if (ja != null) {
String texto = JournalArticleLocalServiceUtil.getArticleContent(ja.getGroupId(), ja.getArticleId(), "view", "" + themeDisplay.getLocale(), themeDisplay);
pregunta.setTexto(texto);
}
incorrectas.add(pregunta);
}
}
}
log.debug("Pregunta {} : Respuesta {} : Usuario {}", new Object[]{pregunta.getId(), pregunta.getCorrectas(), params.get(pregunta.getId().toString())});
}
Map<String, Object> resultados = new HashMap<>();
resultados.put("examen", examen);
resultados.put("totalExamen", totalExamen);
resultados.put("totalUsuario", totalUsuario);
resultados.put("totales", new String[]{totalUsuario.toString(), totalExamen.toString(), examen.getPuntos().toString()});
if (examen.getPuntos() != null && totalUsuario < examen.getPuntos()) {
resultados.put("messageTitle", "desaprobado");
resultados.put("messageType", "alert-error");
Long contenidoId = new Long(params.get("contenidoId")[0]);
Alumno alumno = (Alumno) currentSession().load(Alumno.class, usuario.getUserId());
Contenido contenido = (Contenido) currentSession().load(Contenido.class, contenidoId);
AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido);
AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk);
if (alumnoContenido != null && alumnoContenido.getTerminado() != null) {
alumnoContenido.setTerminado(null);
currentSession().update(alumnoContenido);
currentSession().flush();
}
} else {
resultados.put("messageTitle", "aprobado");
resultados.put("messageType", "alert-success");
for (String key : params.keySet()) {
log.debug("{} : {}", key, params.get(key));
}
Long contenidoId = new Long(params.get("contenidoId")[0]);
Alumno alumno = (Alumno) currentSession().load(Alumno.class, usuario.getUserId());
Contenido contenido = (Contenido) currentSession().load(Contenido.class, contenidoId);
AlumnoContenidoPK pk = new AlumnoContenidoPK(alumno, contenido);
AlumnoContenido alumnoContenido = (AlumnoContenido) currentSession().get(AlumnoContenido.class, pk);
if (alumnoContenido != null) {
alumnoContenido.setTerminado(new Date());
currentSession().update(alumnoContenido);
currentSession().flush();
}
}
if (incorrectas.size() > 0) {
resultados.put("incorrectas", incorrectas);
}
return resultados;
} catch (PortalException | SystemException e) {
log.error("No se pudo calificar el examen", e);
}
return null;
}
|
diff --git a/tree/google_quadtree.java b/tree/google_quadtree.java
index 7ddecfc..f23274b 100644
--- a/tree/google_quadtree.java
+++ b/tree/google_quadtree.java
@@ -1,103 +1,103 @@
/*Quadtree
google
Given a two-dimension image, each pixel is either black or white. If all pixels
are black, then this image is black; if all pixels are white, when this image
is white. If this image contains both white pixels and black pixels, divide it
into four parts.
__________ __________
| | divided into 4 parts | | |
| | |____|___|
| | | | |
|________| |____|___|
Each small part is a sub-quadtree
Q1: Design the data strcuture for each node of quadtree.
Q2: Describe intersection of two quadtree.
Q3: Write a function to return the intersection of two quadtree.
http://en.wikipedia.org/wiki/Quadtree
intersection of black and white is 1 && 0 = 0
*/
public class google_Quadtree{
final int WHITE = 0;
final int BLACK = 1;
final int GREY = 2;
public static void main(String[] args) {
// Test case.
}
public static QTNode cloneQT(QTNode root) {
if (root == null) {
return null;
}
QTNode newNode = new QTNode(root.color);
for (int i = 0; i < 4; ++i) {
newNode.kids[i] = cloneQT(root.kids[i]);
}
return newNode;
}
public static QTNode intersection(QTNode rootOne, QTNode rootTwo) {
if (rootOne.color == GREY && rootTwo.color == GREY) {
// Both contain black & white.
QTNode newNode = new QTNode(GREY);
for (int i = 0; i < 4; ++i) {
newNode.kids[i] = intersection(rootOne.kids[i], rootTwo.kids[i]);
}
// Trick here:
if (newNode.isAllKidsWhite()) {
// If Intersection of two grey area is white, it should have no kids and
// its color should be set to 0(white).
return new QTNode(WHITE);
} else {
return newNode;
}
- } else if (rootOne.color == WHITE && rootTwo.color == WHITE) {
- // Both are white.
+ } else if (rootOne.color == WHITE || rootTwo.color == WHITE) {
+ // Either is white.
return new QTNode(WHITE);
} else if (rootOne.color == BLACK) {
// allBlack && pixels = pixels
return cloneQT(rootTwo);
} else {
// rootTwo.color == 1
return cloneQT(rootOne);
}
}
static class QTNode {
private int color;
private final int WHITE = 0;
private final int BLACK = 1;
private final int GREY = 2;
// Children.
QTNode[] kids = new QTNode[4];
QTNode(int x) {
if (!(x == this.BLACK || x == this.WHITE || x == this.GREY)) {
throw new IllegalArgumentException("Invalid color.");
}
color = x;
for (QTNode kid : kids) {
kid = null;
}
}
public boolean isAllKidsWhite() {
for (QTNode kid : kids) {
if (kid == null) {
return false;
} else if (kid.color != this.WHITE) {
return false;
}
}
return true;
}
}
}
| true | true | public static QTNode intersection(QTNode rootOne, QTNode rootTwo) {
if (rootOne.color == GREY && rootTwo.color == GREY) {
// Both contain black & white.
QTNode newNode = new QTNode(GREY);
for (int i = 0; i < 4; ++i) {
newNode.kids[i] = intersection(rootOne.kids[i], rootTwo.kids[i]);
}
// Trick here:
if (newNode.isAllKidsWhite()) {
// If Intersection of two grey area is white, it should have no kids and
// its color should be set to 0(white).
return new QTNode(WHITE);
} else {
return newNode;
}
} else if (rootOne.color == WHITE && rootTwo.color == WHITE) {
// Both are white.
return new QTNode(WHITE);
} else if (rootOne.color == BLACK) {
// allBlack && pixels = pixels
return cloneQT(rootTwo);
} else {
// rootTwo.color == 1
return cloneQT(rootOne);
}
}
| public static QTNode intersection(QTNode rootOne, QTNode rootTwo) {
if (rootOne.color == GREY && rootTwo.color == GREY) {
// Both contain black & white.
QTNode newNode = new QTNode(GREY);
for (int i = 0; i < 4; ++i) {
newNode.kids[i] = intersection(rootOne.kids[i], rootTwo.kids[i]);
}
// Trick here:
if (newNode.isAllKidsWhite()) {
// If Intersection of two grey area is white, it should have no kids and
// its color should be set to 0(white).
return new QTNode(WHITE);
} else {
return newNode;
}
} else if (rootOne.color == WHITE || rootTwo.color == WHITE) {
// Either is white.
return new QTNode(WHITE);
} else if (rootOne.color == BLACK) {
// allBlack && pixels = pixels
return cloneQT(rootTwo);
} else {
// rootTwo.color == 1
return cloneQT(rootOne);
}
}
|
diff --git a/orion-viewer/orion_viewer/src/universe/constellation/orion/viewer/OrionViewerActivity.java b/orion-viewer/orion_viewer/src/universe/constellation/orion/viewer/OrionViewerActivity.java
index ce40382..3bdfe6d 100644
--- a/orion-viewer/orion_viewer/src/universe/constellation/orion/viewer/OrionViewerActivity.java
+++ b/orion-viewer/orion_viewer/src/universe/constellation/orion/viewer/OrionViewerActivity.java
@@ -1,1523 +1,1529 @@
/*
* Orion Viewer - pdf, djvu, xps and cbz file viewer for android devices
*
* Copyright (C) 2011-2012 Michael Bogdanov
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package universe.constellation.orion.viewer;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Debug;
import android.os.SystemClock;
import android.util.Log;
import android.view.*;
import android.widget.*;
import android.widget.ImageButton;
import android.widget.RadioButton;
import universe.constellation.orion.viewer.djvu.DjvuDocument;
import universe.constellation.orion.viewer.pdf.PdfDocument;
import universe.constellation.orion.viewer.prefs.GlobalOptions;
import universe.constellation.orion.viewer.prefs.OrionPreferenceActivity;
import pl.polidea.customwidget.TheMissingTabHost;
import universe.constellation.orion.viewer.selection.SelectedTextActions;
import universe.constellation.orion.viewer.selection.SelectionAutomata;
import java.io.*;
public class OrionViewerActivity extends OrionBaseActivity {
private Dialog dialog;
public static final int OPEN_BOOKMARK_ACTIVITY_RESULT = 1;
public static final int ROTATION_SCREEN = 0;
public static final int MAIN_SCREEN = 0;
public static final int PAGE_SCREEN = 1;
public static final int ZOOM_SCREEN = 2;
public static final int CROP_SCREEN = 3;
public static final int PAGE_LAYOUT_SCREEN = 4;
public static final int ADD_BOOKMARK_SCREEN = 5;
public static final int REFLOW_SCREEN = 6;
public static final int HELP_SCREEN = 100;
public static final int CROP_RESTRICTION_MIN = -10;
private static final int CROP_DELTA = 10;
public static final int CROP_RESTRICTION_MAX = 40;
private final SubscriptionManager manager = new SubscriptionManager();
private OrionView view;
private ViewAnimator animator;
private LastPageInfo lastPageInfo;
//left, right, top, bottom
private int [] cropBorders = new int[6];
private Controller controller;
private OperationHolder operation = new OperationHolder();
private GlobalOptions globalOptions;
private Intent myIntent;
public boolean isResumed;
private boolean selectionMode = false;
private SelectionAutomata textSelection;
private SelectedTextActions selectedTextActions;
@Override
public void onCreate(Bundle savedInstanceState) {
loadGlobalOptions();
getOrionContext().setViewActivity(this);
OptionActions.FULL_SCREEN.doAction(this, !globalOptions.isFullScreen(), globalOptions.isFullScreen());
super.onCreate(savedInstanceState);
setContentView(device.getLayoutId());
view = (OrionView) findViewById(R.id.view);
String mode = getOrionContext().getOptions().getStringProperty(GlobalOptions.DAY_NIGHT_MODE, "DAY");
view.setNightMode("NIGHT".equals(mode));
if (!device.optionViaDialog()) {
initAnimator();
initMainScreen();
//initHelpScreen();
} else {
initOptionDialog();
initRotationScreen();
}
//page chooser
initPagePeekerScreen();
initZoomScreen();
initCropScreen();
initReflowScreen();
initPageLayoutScreen();
initAddBookmarkScreen();
myIntent = getIntent();
}
protected void initHelpScreen() {
TheMissingTabHost host = (TheMissingTabHost) findMyViewById(R.id.helptab);
host.setup();
TheMissingTabHost.TheMissingTabSpec spec = host.newTabSpec("general_help");
spec.setContent(R.id.general_help);
spec.setIndicator("", getResources().getDrawable(R.drawable.help));
host.addTab(spec);
TheMissingTabHost.TheMissingTabSpec recent = host.newTabSpec("app_info");
recent.setContent(R.id.app_info);
recent.setIndicator("", getResources().getDrawable(R.drawable.info));
host.addTab(recent);
host.setCurrentTab(0);
ImageButton btn = (ImageButton) findMyViewById(R.id.help_close);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//animator.setDisplayedChild(MAIN_SCREEN);
onAnimatorCancel();
}
});
btn = (ImageButton) findMyViewById(R.id.info_close);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onAnimatorCancel();
//animator.setDisplayedChild(MAIN_SCREEN);
}
});
}
public void updateCrops() {
controller.getMargins(cropBorders);
TableLayout cropTable = (TableLayout) findMyViewById(R.id.crop_borders);
for (int i = 0; i < cropTable.getChildCount(); i++) {
TableRow row = (TableRow) cropTable.getChildAt(i);
TextView valueView = (TextView) row.findViewById(R.id.crop_value);
valueView.setText(cropBorders[i] + "%");
}
TableLayout cropTable2 = (TableLayout) findMyViewById(R.id.crop_borders_even);
int index = 4;
for (int i = 0; i < cropTable2.getChildCount(); i++) {
if (cropTable2.getChildAt(i) instanceof TableRow) {
TableRow row = (TableRow) cropTable2.getChildAt(i);
TextView valueView = (TextView) row.findViewById(R.id.crop_value);
valueView.setText(cropBorders[index] + "%");
index++;
}
}
((CheckBox)findMyViewById(R.id.crop_even_flag)).setChecked(controller.isEvenCropEnabled());
}
public void updatePageLayout() {
String walkOrder = controller.getDirection();
int lid = controller.getLayout();
((RadioGroup) findMyViewById(R.id.layoutGroup)).check(lid == 0 ? R.id.layout1 : lid == 1 ? R.id.layout2 : R.id.layout3);
//((RadioGroup) findMyViewById(R.id.directionGroup)).check(did == 0 ? R.id.direction1 : did == 1 ? R.id.direction2 : R.id.direction3);
RadioGroup group = (RadioGroup) findMyViewById(R.id.directionGroup);
for (int i = 0; i < group.getChildCount(); i++) {
View child = group.getChildAt(i);
if (child instanceof universe.constellation.orion.viewer.android.RadioButton) {
universe.constellation.orion.viewer.android.RadioButton button = (universe.constellation.orion.viewer.android.RadioButton) child;
if (walkOrder.equals(button.getWalkOrder())) {
group.check(button.getId());
}
}
}
}
protected void onNewIntent(Intent intent) {
Common.d("Runtime.getRuntime().totalMemory() = " + Runtime.getRuntime().totalMemory());
Common.d("Debug.getNativeHeapSize() = " + Debug.getNativeHeapSize());
Uri uri = intent.getData();
Common.d("File URI = " + uri.toString());
String file = uri.getPath();
if (controller != null) {
if (lastPageInfo!= null) {
if (lastPageInfo.openingFileName.equals(file)) {
//keep controller
controller.drawPage();
return;
}
}
controller.destroy();
controller = null;
}
if (intent.getData() != null) {
Common.stopLogger();
openFile(file);
} else /*if (intent.getAction().endsWith("MAIN"))*/ {
//TODO error
}
}
public void openFile(String filePath) {
DocumentWrapper doc = null;
Common.d("File URI = " + filePath);
getOrionContext().onNewBook(filePath);
try {
String filePAthLowCase = filePath.toLowerCase();
if (filePAthLowCase.endsWith("pdf") || filePAthLowCase.endsWith("xps") || filePAthLowCase.endsWith("cbz")) {
doc = new PdfDocument(filePath);
} else {
doc = new DjvuDocument(filePath);
}
LayoutStrategy str = new SimpleLayoutStrategy(doc, device.getDeviceSize());
int idx = filePath.lastIndexOf('/');
lastPageInfo = LastPageInfo.loadBookParameters(this, filePath);
getOrionContext().setCurrentBookParameters(lastPageInfo);
OptionActions.DEBUG.doAction(this, false, getGlobalOptions().getBooleanProperty("DEBUG", false));
controller = new Controller(this, doc, str, view);
// controller.setReflowParameters(1, 167, 2, lastPageInfo.screenWidth, lastPageInfo.screenHeight,
// -1, -1, -1, -1);
controller.changeOrinatation(lastPageInfo.screenOrientation);
controller.init(lastPageInfo);
getSubscriptionManager().sendDocOpenedNotification(controller);
getView().setController(controller);
controller.drawPage();
String title = doc.getTitle();
if (title == null || "".equals(title)) {
title = filePath.substring(idx + 1);
title = title.substring(0, title.lastIndexOf("."));
}
device.updateTitle(title);
globalOptions.addRecentEntry(new GlobalOptions.RecentEntry(new File(filePath).getAbsolutePath()));
} catch (Exception e) {
Common.d(e);
if (doc != null) {
doc.destroy();
}
finish();
}
}
public void onPause() {
isResumed = false;
super.onPause();
if (controller != null) {
controller.onPause();
saveData();
}
}
public void initPagePeekerScreen() {
final SeekBar pageSeek = (SeekBar) findMyViewById(R.id.page_picker_seeker);
getSubscriptionManager().addDocListeners(new DocumentViewAdapter() {
@Override
public void documentOpened(Controller controller) {
pageSeek.setMax(controller.getPageCount() - 1);
pageSeek.setProgress(controller.getCurrentPage());
}
@Override
public void pageChanged(int newPage, int pageCount) {
pageSeek.setProgress(newPage);
}
});
final TextView pageNumberText = (TextView) findMyViewById(R.id.page_picker_message);
//initial state
pageNumberText.setText("" + 1);
pageSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
pageNumberText.setText("" + (progress + 1));
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
ImageButton closePagePeeker = (ImageButton) findMyViewById(R.id.page_picker_close);
ImageButton plus = (ImageButton) findMyViewById(R.id.page_picker_plus);
plus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pageSeek.incrementProgressBy(1);
}
});
ImageButton minus = (ImageButton) findMyViewById(R.id.page_picker_minus);
minus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (pageSeek.getProgress() != 0) {
pageSeek.incrementProgressBy(-1);
}
}
});
closePagePeeker.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//controller.drawPage(Integer.valueOf(pageNumberText.getText().toString()) - 1);
//main menu
onAnimatorCancel();
updatePageSeeker();
//animator.setDisplayedChild(MAIN_SCREEN);
}
});
ImageButton page_preview = (ImageButton) findMyViewById(R.id.page_preview);
page_preview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onApplyAction();
if (!"".equals(pageNumberText.getText())) {
try {
int parsedInput = Integer.valueOf(pageNumberText.getText().toString());
controller.drawPage(parsedInput -1);
} catch (NumberFormatException ex) {
showError("Couldn't parse " + pageNumberText.getText(), ex);
}
}
}
});
}
public void updatePageSeeker() {
SeekBar pageSeek = (SeekBar) findMyViewById(R.id.page_picker_seeker);
pageSeek.setProgress(controller.getCurrentPage());
TextView view = (TextView) findMyViewById(R.id.page_picker_message);
view.setText("" + (controller.getCurrentPage() + 1));
view.clearFocus();
view.requestFocus();
}
public void initZoomScreen() {
//zoom screen
final Spinner sp = (Spinner) findMyViewById(R.id.zoom_spinner);
final TextView zoomText = (TextView) findMyViewById(R.id.zoom_picker_message);
final SeekBar zoomSeek = (SeekBar) findMyViewById(R.id.zoom_picker_seeker);
if (zoomSeek != null) {
zoomSeek.setMax(300);
zoomSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (zoomInternal != 1) {
zoomText.setText("" + progress);
if (sp.getSelectedItemPosition() != 0) {
int oldInternal = zoomInternal;
zoomInternal = 2;
sp.setSelection(0);
zoomInternal = oldInternal;
}
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
getSubscriptionManager().addDocListeners(new DocumentViewAdapter(){
@Override
public void documentOpened(Controller controller) {
updateZoom();
}
});
final ImageButton zplus = (ImageButton) findMyViewById(R.id.zoom_picker_plus);
zplus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
zoomSeek.incrementProgressBy(1);
}
});
final ImageButton zminus = (ImageButton) findMyViewById(R.id.zoom_picker_minus);
zminus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (zoomSeek.getProgress() != 0) {
zoomSeek.incrementProgressBy(-1);
}
}
});
ImageButton closeZoomPeeker = (ImageButton) findMyViewById(R.id.zoom_picker_close);
closeZoomPeeker.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//main menu
onAnimatorCancel();
//updateZoom();
}
});
ImageButton zoom_preview = (ImageButton) findMyViewById(R.id.zoom_preview);
zoom_preview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onApplyAction();
int index = sp.getSelectedItemPosition();
controller.changeZoom(index == 0 ? (int)(Float.parseFloat(zoomText.getText().toString()) * 100) : -1 *(index-1));
updateZoom();
}
});
//sp.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, getResources().getTextArray(R.array.fits)));
sp.setAdapter(new MyArrayAdapter());
// sp.setAdapter(new MyArrayAdapter(this, R.layout.zoom_spinner, R.id.spinner_text, getResources().getTextArray(R.array.fits)));
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
boolean disable = position != 0;
int oldZoomInternal = zoomInternal;
if (zoomInternal != 2) {
zoomInternal = 1;
if (disable) {
zoomText.setText((String)parent.getAdapter().getItem(position));
} else {
zoomText.setText("" + ((int) (controller.getCurrentPageZoom() * 10000)) / 100f);
zoomSeek.setProgress((int) (controller.getCurrentPageZoom() * 100));
}
zoomInternal = oldZoomInternal;
}
zminus.setVisibility(disable ? View.GONE : View.VISIBLE);
zplus.setVisibility(disable ? View.GONE : View.VISIBLE);
zoomText.setFocusable(!disable);
zoomText.setFocusableInTouchMode(!disable);
}
public void onNothingSelected(AdapterView<?> parent) {
//To change body of implemented methods use File | Settings | File Templates.
}
});
//by width
sp.setSelection(1);
}
private int zoomInternal = 0;
public void updateZoom() {
SeekBar zoomSeek = (SeekBar) findMyViewById(R.id.zoom_picker_seeker);
TextView textView = (TextView) findMyViewById(R.id.zoom_picker_message);
Spinner sp = (Spinner) findMyViewById(R.id.zoom_spinner);
int spinnerIndex = sp.getSelectedItemPosition();
zoomInternal = 1;
try {
int zoom = controller.getZoom10000Factor();
if (zoom <= 0) {
spinnerIndex = -zoom + 1;
zoom = (int) (10000 * controller.getCurrentPageZoom());
} else {
spinnerIndex = 0;
textView.setText("" + (zoom /100f));
}
zoomSeek.setProgress(zoom / 100);
sp.setSelection(spinnerIndex);
} finally {
zoomInternal = 0;
}
}
public void initPageLayoutScreen() {
ImageButton close = (ImageButton) findMyViewById(R.id.options_close);
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// int did = ((RadioGroup) findMyViewById(R.id.directionGroup)).getCheckedRadioButtonId();
// int lid = ((RadioGroup) findMyViewById(R.id.layoutGroup)).getCheckedRadioButtonId();
// controller.setDirectionAndLayout(did == R.id.direction1 ? 0 : 1, lid == R.id.layout1 ? 0 : lid == R.id.layout2 ? 1 : 2);
//main menu
onAnimatorCancel();
updatePageLayout();
//animator.setDisplayedChild(MAIN_SCREEN);
}
});
ImageButton view = (ImageButton) findMyViewById(R.id.options_apply);
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onApplyAction();
RadioGroup group = ((RadioGroup) findMyViewById(R.id.directionGroup));
int walkOrderButtonId = group.getCheckedRadioButtonId();
universe.constellation.orion.viewer.android.RadioButton button = (universe.constellation.orion.viewer.android.RadioButton) group.findViewById(walkOrderButtonId);
int lid = ((RadioGroup) findMyViewById(R.id.layoutGroup)).getCheckedRadioButtonId();
controller.setDirectionAndLayout(button.getWalkOrder(), lid == R.id.layout1 ? 0 : lid == R.id.layout2 ? 1 : 2);
}
});
getSubscriptionManager().addDocListeners(new DocumentViewAdapter() {
public void documentOpened(Controller controller) {
updatePageLayout();
}
});
}
public void initAddBookmarkScreen() {
ImageButton close = (ImageButton) findMyViewById(R.id.add_bookmark_close);
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//main menu
onAnimatorCancel();
}
});
ImageButton view = (ImageButton) findMyViewById(R.id.add_bookmark_apply);
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText text = (EditText) findMyViewById(R.id.add_bookmark_text);
insertBookmark(controller.getCurrentPage(), text.getText().toString());
onApplyAction(true);
}
});
}
public void initCropScreen() {
TableLayout cropTable = (TableLayout) findMyViewById(R.id.crop_borders);
getSubscriptionManager().addDocListeners(new DocumentViewAdapter(){
@Override
public void documentOpened(Controller controller) {
updateCrops();
}
});
for (int i = 0; i < cropTable.getChildCount(); i++) {
TableRow row = (TableRow) cropTable.getChildAt(i);
row.findViewById(R.id.crop_plus);
TextView valueView = (TextView) row.findViewById(R.id.crop_value);
ImageButton plus = (ImageButton) row.findViewById(R.id.crop_plus);
ImageButton minus = (ImageButton) row.findViewById(R.id.crop_minus);
linkCropButtonsAndText(minus, plus, valueView, i);
}
//even cropping
int index = 4;
final TableLayout cropTable2 = (TableLayout) findMyViewById(R.id.crop_borders_even);
for (int i = 0; i < cropTable2.getChildCount(); i++) {
View child = cropTable2.getChildAt(i);
if (child instanceof TableRow) {
TableRow row = (TableRow) child;
row.findViewById(R.id.crop_plus);
TextView valueView = (TextView) row.findViewById(R.id.crop_value);
ImageButton plus = (ImageButton) row.findViewById(R.id.crop_plus);
ImageButton minus = (ImageButton) row.findViewById(R.id.crop_minus);
linkCropButtonsAndText(minus, plus, valueView, index);
index++;
for (int j = 0; j < row.getChildCount(); j++) {
View v = row.getChildAt(j);
v.setEnabled(false);
}
}
}
final ImageButton switchEven = (ImageButton) findMyViewById(R.id.crop_even_button);
if (switchEven != null) {
final ViewAnimator cropAnim = (ViewAnimator) findMyViewById(R.id.crop_animator);
switchEven.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cropAnim.setDisplayedChild((cropAnim.getDisplayedChild() + 1) % 2);
switchEven.setImageResource(cropAnim.getDisplayedChild() == 0 ? R.drawable.next : R.drawable.prev);
}
});
}
final CheckBox checkBox = (CheckBox) findMyViewById(R.id.crop_even_flag);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
for (int i = 0; i < cropTable2.getChildCount(); i++) {
View child = cropTable2.getChildAt(i);
if (child instanceof TableRow) {
TableRow row = (TableRow) child;
for (int j = 0; j < row.getChildCount(); j++) {
View rowChild = row.getChildAt(j);
rowChild.setEnabled(isChecked);
}
}
}
}
});
ImageButton preview = (ImageButton) findMyViewById(R.id.crop_preview);
preview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onApplyAction();
controller.changeMargins(cropBorders[0], cropBorders[2], cropBorders[1], cropBorders[3], checkBox.isChecked(), cropBorders[4], cropBorders[5]);
}
});
ImageButton close = (ImageButton) findMyViewById(R.id.crop_close);
close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//main menu
onAnimatorCancel();
//reset if canceled
updateCrops();
}
});
}
public void linkCropButtonsAndText(final ImageButton minus, final ImageButton plus, final TextView text, final int cropIndex) {
minus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//main menu
if (cropBorders[cropIndex] != CROP_RESTRICTION_MIN) {
cropBorders[cropIndex] = cropBorders[cropIndex] - 1;
text.setText(cropBorders[cropIndex] + "%");
}
}
});
minus.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
cropBorders[cropIndex] = cropBorders[cropIndex] - CROP_DELTA;
if (cropBorders[cropIndex] < CROP_RESTRICTION_MIN) {
cropBorders[cropIndex] = CROP_RESTRICTION_MIN;
}
text.setText(cropBorders[cropIndex] + "%");
return true;
}
});
plus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//main menu
//int value = Integer.valueOf(text.getText().toString());
cropBorders[cropIndex] = cropBorders[cropIndex] + 1;
if (cropBorders[cropIndex] > CROP_RESTRICTION_MAX) {
cropBorders[cropIndex] = CROP_RESTRICTION_MAX;
}
text.setText(cropBorders[cropIndex] + "%");
}
});
plus.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
cropBorders[cropIndex] = cropBorders[cropIndex] + CROP_DELTA;
if (cropBorders[cropIndex] > CROP_RESTRICTION_MAX) {
cropBorders[cropIndex] = CROP_RESTRICTION_MAX;
}
text.setText(cropBorders[cropIndex] + "%");
return true;
}
});
}
private void initMainScreen() {
ImageButton btn = (ImageButton) findMyViewById(R.id.menu);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
openOptionsMenu();
}
});
btn = (ImageButton) findMyViewById(R.id.prev_page);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
changePage(-1);
}
});
btn.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
//page seeker
animator.setDisplayedChild(PAGE_SCREEN);
return true;
}
});
btn = (ImageButton) findMyViewById(R.id.next_page);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
changePage(1);
}
});
btn.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
//page seeker
Action.OPEN_BOOKMARKS.doAction(controller, OrionViewerActivity.this, null);
//animator.setDisplayedChild(PAGE_SCREEN);
return true;
}
});
btn = (ImageButton) findMyViewById(R.id.switch_page);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
controller.setRotation((controller.getRotation() - 1) % 2);
}
});
btn.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
controller.setRotation((controller.getRotation() + 1) % 2);
return true;
}
});
btn = (ImageButton) findMyViewById(R.id.zoom);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showOrionDialog(ZOOM_SCREEN, null, null);
}
});
btn = (ImageButton) findMyViewById(R.id.crop_menu);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
updateCrops();
animator.setDisplayedChild(CROP_SCREEN);
}
});
btn = (ImageButton) findMyViewById(R.id.help);
if (btn != null) {
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//animator.setDisplayedChild(HELP_SCREEN);
Intent intent = new Intent();
intent.setClass(OrionViewerActivity.this, OrionHelpActivity.class);
startActivity(intent);
}
});
}
btn = (ImageButton) findMyViewById(R.id.navigation);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
updatePageLayout();
animator.setDisplayedChild(PAGE_LAYOUT_SCREEN);
}
});
btn = (ImageButton) findMyViewById(R.id.options);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent in = new Intent(OrionViewerActivity.this, OrionPreferenceActivity.class);
startActivity(in);
}
});
}
protected void onResume() {
isResumed = true;
super.onResume();
updateBrightness();
Common.d("onResume");
if (myIntent != null) {
//starting creation intent
onNewIntent(myIntent);
myIntent = null;
} else {
if (controller != null) {
controller.processPendingEvents();
//controller.startRenderer();
controller.drawPage();
}
}
}
protected void onDestroy() {
super.onDestroy();
Common.d("onDestroy");
Common.stopLogger();
if (controller != null) {
controller.destroy();
}
if (dialog != null) {
dialog.dismiss();
}
getOrionContext().destroyDb();
//globalOptions.onDestroy(this);
}
private void saveData() {
if (controller != null) {
try {
controller.serialize(lastPageInfo);
lastPageInfo.save(this);
} catch (Exception ex) {
Log.e(Common.LOGTAG, ex.getMessage(), ex);
}
}
saveGlobalOptions();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
System.out.println("key " + keyCode);
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (!device.optionViaDialog() && animator.getDisplayedChild() != MAIN_SCREEN) {
onAnimatorCancel();
return true;
}
}
int actionCode = getOrionContext().getKeyBinding().getInt("" + keyCode, -1);
if (actionCode != -1) {
Action action = Action.getAction(actionCode);
switch (action) {
case PREV: case NEXT: changePage(action == Action.PREV ? Device.PREV : Device.NEXT); return true;
case NONE: break;
default: doAction(action); return true;
}
}
if (device.onKeyDown(keyCode, event, operation)) {
changePage(operation.value);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void changePage(int operation) {
boolean swapKeys = globalOptions.isSwapKeys();
int width = getView().getWidth();
int height = getView().getHeight();
boolean landscape = width > height || controller.getRotation() != 0; /*second condition for nook and alex*/
if (controller != null) {
if (operation == Device.NEXT && (!landscape || !swapKeys) || swapKeys && operation == Device.PREV && landscape) {
controller.drawNext();
} else {
controller.drawPrev();
}
}
}
public void loadGlobalOptions() {
globalOptions = getOrionContext().getOptions();
}
public void saveGlobalOptions() {
Common.d("Saving global options...");
globalOptions.saveRecents();
Common.d("Done!");
}
public OrionView getView() {
return view;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
if (result) {
getMenuInflater().inflate(Device.Info.NOOK_CLASSIC ? R.menu.nook_menu : R.menu.menu, menu);
}
return result;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Action action = Action.NONE; //will open help
switch (item.getItemId()) {
case R.id.exit_menu_item:
finish();
return true;
case R.id.crop_menu_item: action = Action.CROP; break;
case R.id.zoom_menu_item: action = Action.ZOOM; break;
case R.id.add_bookmark_menu_item: action = Action.ADD_BOOKMARK; break;
case R.id.goto_menu_item: action = Action.GOTO; break;
case R.id.select_text_menu_item: action = Action.SELECT_TEXT; break;
// case R.id.navigation_menu_item: showOrionDialog(PAGE_LAYOUT_SCREEN, null, null);
// return true;
// case R.id.rotation_menu_item: action = Action.ROTATION; break;
case R.id.options_menu_item: action = Action.OPTIONS; break;
case R.id.book_options_menu_item: action = Action.BOOK_OPTIONS; break;
// case R.id.tap_menu_item:
// Intent tap = new Intent(this, OrionTapActivity.class);
// startActivity(tap);
// return true;
case R.id.outline_menu_item: action = Action.SHOW_OUTLINE; break;
case R.id.open_menu_item: action = Action.OPEN_BOOK; break;
case R.id.open_dictionary_menu_item: action = Action.DICTIONARY; break;
case R.id.day_night_menu_item: action = Action.DAY_NIGHT; break;
case R.id.reflow_menu_item: action = Action.REFLOW; break;
case R.id.bookmarks_menu_item: action = Action.OPEN_BOOKMARKS; break;
}
if (Action.NONE != action) {
doAction(action);
} else {
Intent intent = new Intent();
intent.setClass(this, OrionHelpActivity.class);
startActivity(intent);
}
return true;
}
public void initAnimator() {
animator = (ViewAnimator) findMyViewById(R.id.viewanim);
getSubscriptionManager().addDocListeners(new DocumentViewAdapter() {
@Override
public void documentOpened(Controller controller) {
animator.setDisplayedChild(MAIN_SCREEN);
}
public void pageChanged(final int newPage, final int pageCount) {
TextView tv = (TextView) findMyViewById(R.id.page_number_view);
tv.setText(newPage + 1 + "/" + pageCount);
device.updatePageNumber(newPage + 1, pageCount);
}
});
}
public SubscriptionManager getSubscriptionManager() {
return manager;
}
public void initOptionDialog() {
dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.android_dialog);
animator = ((ViewAnimator)dialog.findViewById(R.id.viewanim));
getView().setOnTouchListener(new View.OnTouchListener() {
private int lastX = -1;
private int lastY = -1;
long startTime = 0;
private static final long TIME_DELTA = 600;
public boolean onTouch(View v, MotionEvent event) {
//Common.d("Event " + event.getAction() + ": " + (SystemClock.uptimeMillis() - startTime));
if (!selectionMode) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//Common.d("DOWN " + event.getAction());
startTime = SystemClock.uptimeMillis();
lastX = (int) event.getX();
lastY = (int) event.getY();
return true;
} else {
// Common.d("ev " + event.getAction());
boolean doAction = false;
if (event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
if (event.getAction() == MotionEvent.ACTION_UP) {
Common.d("UP " + event.getAction());
doAction = true;
} else {
if (lastX != -1 && lastY != -1) {
boolean isLongClick = (SystemClock.uptimeMillis() - startTime) > TIME_DELTA;
doAction = isLongClick;
}
}
if (doAction) {
Common.d("Check event action " + event.getAction());
boolean isLongClick = (SystemClock.uptimeMillis() - startTime) > TIME_DELTA;
if (lastX != -1 && lastY != -1) {
int width = getView().getWidth();
int height = getView().getHeight();
int i = 3 * lastY / height;
int j = 3 * lastX / width;
int code = globalOptions.getActionCode(i, j, isLongClick);
doAction(code);
startTime = 0;
lastX = -1;
lastY = -1;
}
}
return true;
} else if (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_OUTSIDE) {
startTime = 0;
lastX = -1;
lastY = -1;
}
}
return true;
} else {
boolean result = textSelection.onTouch(event);
if (textSelection.isSuccessful()) {
selectionMode = false;
String text = controller.selectText(textSelection.getStartX(), textSelection.getStartY(), textSelection.getWidth(), textSelection.getHeight());
if (text != null) {
if (selectedTextActions == null) {
selectedTextActions = new SelectedTextActions(OrionViewerActivity.this);
}
selectedTextActions.show(text);
} else {
}
}
return result;
}
}
});
// getView().setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
// v.get
// globalOptions.getActionCode()
// controller.drawNext();
// }
// });
//
// getView().setOnLongClickListener(new View.OnLongClickListener(){
// public boolean onLongClick(View v) {
// controller.drawPrev();
// return true;
// }
// });
// getView().setOnTouchListener(new View.OnTouchListener() {
// public boolean onTouch(View v, MotionEvent event) {
//
// }
// });
}
private void doAction(int code) {
Action action = Action.getAction(code);
doAction(action);
Common.d("Code action " + code);
}
public void doAction(Action action) {
action.doAction(controller, this, null);
}
protected View findMyViewById(int id) {
if (device.optionViaDialog()) {
return dialog.findViewById(id);
} else {
return findViewById(id);
}
}
public void onAnimatorCancel() {
if (!device.optionViaDialog()){
animator.setDisplayedChild(MAIN_SCREEN);
} else {
dialog.cancel();
}
}
@Override
protected void onApplyAction() {
onApplyAction(false);
}
protected void onApplyAction(boolean close) {
if (close || globalOptions.isApplyAndClose()) {
onAnimatorCancel();
}
}
public void initRotationScreen() {
//if (getDevice() instanceof EdgeDevice) {
if (false) {
final RadioGroup rotationGroup = (RadioGroup) findMyViewById(R.id.rotationGroup);
rotationGroup.check(R.id.rotate0);
if (Device.Info.NOOK2) {
RadioButton r0 = (RadioButton) rotationGroup.findViewById(R.id.rotate0);
RadioButton r90 = (RadioButton) rotationGroup.findViewById(R.id.rotate90);
RadioButton r270 = (RadioButton) rotationGroup.findViewById(R.id.rotate270);
TextView tv = (TextView) findMyViewById(R.id.navigation_title);
int color = tv.getTextColors().getDefaultColor();
r0.setTextColor(color);
r90.setTextColor(color);
r270.setTextColor(color);
}
getSubscriptionManager().addDocListeners(new DocumentViewAdapter() {
@Override
public void documentOpened(Controller controller) {
updateRotation();
}
});
ImageButton apply = (ImageButton) findMyViewById(R.id.rotation_apply);
apply.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onApplyAction(true);
int id = rotationGroup.getCheckedRadioButtonId();
controller.setRotation(id == R.id.rotate0 ? 0 : id == R.id.rotate90 ? -1 : 1);
}
});
ListView list = (ListView) findMyViewById(R.id.rotationList);
list.setVisibility(View.GONE);
} else {
RadioGroup rotationGroup = (RadioGroup) findMyViewById(R.id.rotationGroup);
rotationGroup.setVisibility(View.GONE);
final ListView list = (ListView) findMyViewById(R.id.rotationList);
//set choices and replace 0 one with Application Default
boolean isLevel9 = getOrionContext().getSdkVersion() >= 9;
CharSequence[] values = getResources().getTextArray(isLevel9 ? R.array.screen_orientation_full_desc : R.array.screen_orientation_desc);
CharSequence[] newValues = new CharSequence[values.length];
for (int i = 0; i < values.length; i++) {
newValues[i] = values[i];
}
newValues[0] = getResources().getString(R.string.orientation_default_rotation);
list.setAdapter(Device.Info.NOOK2 ?
new Nook2ListAdapter(this, android.R.layout.simple_list_item_single_choice, newValues, (TextView) findMyViewById(R.id.navigation_title)) :
new ArrayAdapter(this, android.R.layout.simple_list_item_single_choice, newValues));
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setItemChecked(0, true);
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckedTextView check = (CheckedTextView)view;
check.setChecked(!check.isChecked());
}
});
final CharSequence[] ORIENTATION_ARRAY = getResources().getTextArray(R.array.screen_orientation_full);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
onApplyAction(true);
String orientation = ORIENTATION_ARRAY[position].toString();
controller.changeOrinatation(orientation);
}
});
ImageButton apply = (ImageButton) findMyViewById(R.id.rotation_apply);
apply.setVisibility(View.GONE);
// apply.setOnClickListener(new View.OnClickListener() {
// public void onClick(View view) {
// onApplyAction(true);
// }
// });
}
ImageButton cancel = (ImageButton) findMyViewById(R.id.rotation_close);
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onAnimatorCancel();
updateRotation();
}
});
}
void initReflowScreen() {
final SeekBar reflowSeek = (SeekBar)findMyViewById(R.id.reflow_margin_seeker);
reflowSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
TextView seekDisplay = (TextView) findMyViewById(R.id.reflow_margin_display);
seekDisplay.setText(String.format("%.2f", progress * 0.02));
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
final SeekBar reflowWsSeek = (SeekBar)findMyViewById(R.id.reflow_word_space_seeker);
reflowWsSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
TextView seekWsDisplay = (TextView) findMyViewById(R.id.reflow_word_space_display);
seekWsDisplay.setText(String.format("%.2f", progress * 0.05));
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
final SeekBar reflowQlSeek = (SeekBar)findMyViewById(R.id.reflow_quality_seeker);
reflowQlSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
TextView seekQlDisplay = (TextView) findMyViewById(R.id.reflow_quality_display);
seekQlDisplay.setText(String.format("%.2f", progress * 0.05));
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
ImageButton apply = (ImageButton) findMyViewById(R.id.reflow_apply);
apply.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final Spinner zsp = (Spinner) findMyViewById(R.id.reflow_zoom_spinner);
final Spinner dsp = (Spinner) findMyViewById(R.id.reflow_dpi_spinner);
final EditText edit = (EditText) findMyViewById(R.id.reflow_columns_edit);
float zoom = Float.parseFloat(zsp.getSelectedItem().toString());
int dpi = Integer.parseInt(dsp.getSelectedItem().toString());
int columns = Integer.parseInt(edit.getText().toString());
int[] m = new int[6];
controller.getMargins(m);
int m_left = m[0];
int m_right = m[1];
int m_top = m[2];
int m_bottom = m[3];
cropBorders[0] = 0;
cropBorders[1] = 0;
cropBorders[2] = 0;
cropBorders[3] = 0;
cropBorders[4] = 0;
cropBorders[5] = 0;
CheckBox cb = (CheckBox) findMyViewById(R.id.reflow_default_crop_box);
int default_trim = (cb.isChecked()) ? 1 : 0;
cb = (CheckBox) findMyViewById(R.id.reflow_preserve_indent_box);
int indent = (cb.isChecked()) ? 1 : 0;
cb = (CheckBox) findMyViewById(R.id.reflow_wrap_text_box);
int wrap_text = (cb.isChecked()) ? 1 : 0;
Spinner sp_rot = (Spinner) findMyViewById(R.id.reflow_rotation_spinner);
int rotation = Integer.parseInt(sp_rot.getSelectedItem().toString());
TextView mg = (TextView) findMyViewById(R.id.reflow_margin_display);
TextView ws = (TextView) findMyViewById(R.id.reflow_word_space_display);
TextView ql = (TextView) findMyViewById(R.id.reflow_quality_display);
float margin = Float.parseFloat(mg.getText().toString());
float word_space = Float.parseFloat(ws.getText().toString());
float quality = Float.parseFloat(ql.getText().toString());
- controller.setReflowParameters(zoom, dpi, columns, lastPageInfo.screenWidth,
- lastPageInfo.screenHeight, m_top,
+ Display ds = getWindowManager().getDefaultDisplay();
+ Common.d("X: " + ds.getWidth() + " Y: " + ds.getHeight());
+ controller.setReflowParameters(zoom,
+ dpi,
+ columns,
+ ds.getWidth(),
+ ds.getHeight(),
+ m_top,
m_bottom, m_left, m_right,
default_trim,
wrap_text,
indent,
rotation,
margin,
word_space,
quality);
changeReflowMode();
controller.changeMargins(cropBorders[0], cropBorders[2], cropBorders[1],
cropBorders[3], false, cropBorders[4], cropBorders[5]);
onAnimatorCancel();
}
});
ImageButton cancel = (ImageButton) findMyViewById(R.id.reflow_close);
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onAnimatorCancel();
}
});
}
void updateRotation() {
RadioGroup rotationGroup = (RadioGroup) findMyViewById(R.id.rotationGroup);
if (rotationGroup != null) { //nook case
rotationGroup.check(controller.getRotation() == 0 ? R.id.rotate0 : controller.getRotation() == -1 ? R.id.rotate90 : R.id.rotate270);
}
ListView list = (ListView) findMyViewById(R.id.rotationList);
if (list != null) {
int index = getScreenOrientationItemPos(controller.getScreenOrientation());
list.setItemChecked(index, true);
list.setSelection(index);
}
}
@Override
public int getViewerType() {
return Device.VIEWER_ACTIVITY;
}
public GlobalOptions getGlobalOptions() {
return globalOptions;
}
public Controller getController() {
return controller;
}
public void updateBrightness() {
WindowManager.LayoutParams params = getWindow().getAttributes();
float oldBrightness = params.screenBrightness;
if (globalOptions.isCustomBrightness()) {
params.screenBrightness = (float)globalOptions.getBrightness() / 100;
getWindow().setAttributes(params);
} else {
if (oldBrightness >= 0) {
params.screenBrightness = -1;
getWindow().setAttributes(params);
}
}
}
public long insertOrGetBookId() {
LastPageInfo info = lastPageInfo;
Long bookId = getOrionContext().getTempOptions().bookId;
if (bookId == null || bookId == -1) {
bookId = getOrionContext().getBookmarkAccessor().insertOrUpdate(info.simpleFileName, info.fileSize);
getOrionContext().getTempOptions().bookId = bookId;
}
return bookId.intValue();
}
public boolean insertBookmark(int page, String text) {
long id = insertOrGetBookId();
if (id != -1) {
long bokmarkId = getOrionContext().getBookmarkAccessor().insertOrUpdateBookmark(id, page, text);
return bokmarkId != -1;
}
return false;
}
public long getBookId() {
Common.d("Selecting book id...");
LastPageInfo info = lastPageInfo;
Long bookId = getOrionContext().getTempOptions().bookId;
if (bookId == null) {
bookId = getOrionContext().getBookmarkAccessor().selectBookId(info.simpleFileName, info.fileSize);
getOrionContext().getTempOptions().bookId = bookId;
}
Common.d("...book id = " + bookId.longValue());
return bookId.longValue();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == OPEN_BOOKMARK_ACTIVITY_RESULT && resultCode == Activity.RESULT_OK) {
if (controller != null) {
int page = data.getIntExtra(OrionBookmarkActivity.OPEN_PAGE, -1);
if (page != -1) {
controller.drawPage(page);
} else {
doAction(Action.GOTO);
}
}
}
}
public void showOrionDialog(int screenId, Action action, Object parameter) {
if (screenId != -1) {
switch (screenId) {
case ROTATION_SCREEN: updateRotation(); break;
case CROP_SCREEN: updateCrops(); break;
case PAGE_LAYOUT_SCREEN: updatePageLayout();
case PAGE_SCREEN: updatePageSeeker(); break;
case ZOOM_SCREEN: updateZoom(); break;
// case REFLOW_SCREEN: updateReflow(); break;
}
if (action == Action.ADD_BOOKMARK) {
String parameterText = (String) parameter;
int page = controller.getCurrentPage();
String newText = getOrionContext().getBookmarkAccessor().selectExistingBookmark(getBookId(), page, parameterText);
boolean notOverride = parameterText == null || parameterText == newText;
findMyViewById(R.id.warn_text_override).setVisibility(notOverride ? View.GONE : View.VISIBLE);
((EditText)findMyViewById(R.id.add_bookmark_text)).setText(notOverride ? newText : parameterText);
}
animator.setDisplayedChild(screenId);
if (device.optionViaDialog()) {
dialog.show();
}
}
}
public void textSelectionMode() {
//selectionMode = true;
if (textSelection == null) {
textSelection = new SelectionAutomata(this);
}
textSelection.startSelection();
}
public void changeReflowMode() {
int reflow = controller.getReflow() ^ 1;
Common.d("REFLOW IS !!!!: " + reflow);
controller.setReflow(reflow);
}
public void changeDayNightMode() {
boolean newMode = !getView().isNightMode();
getOrionContext().getOptions().saveProperty(GlobalOptions.DAY_NIGHT_MODE, newMode ? "NIGHT" : "DAY");
getView().setNightMode(newMode);
getView().invalidate();
}
public class MyArrayAdapter extends ArrayAdapter implements SpinnerAdapter {
public MyArrayAdapter() {
super(OrionViewerActivity.this, android.R.layout.simple_spinner_dropdown_item, OrionViewerActivity.this.getResources().getTextArray(R.array.fits));
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView != null) {
return convertView;
} else {
TextView view = null;
view = new TextView(OrionViewerActivity.this);
view.setText("%");
return view;
}
}
}
public static class Nook2ListAdapter extends ArrayAdapter {
private int color;
public Nook2ListAdapter(Context context, int textViewResourceId, Object[] objects, TextView view) {
super(context, textViewResourceId, objects);
this.color = view.getTextColors().getDefaultColor();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
((CheckedTextView)view).setTextColor(color);
return view;
}
}
}
| true | true | void initReflowScreen() {
final SeekBar reflowSeek = (SeekBar)findMyViewById(R.id.reflow_margin_seeker);
reflowSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
TextView seekDisplay = (TextView) findMyViewById(R.id.reflow_margin_display);
seekDisplay.setText(String.format("%.2f", progress * 0.02));
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
final SeekBar reflowWsSeek = (SeekBar)findMyViewById(R.id.reflow_word_space_seeker);
reflowWsSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
TextView seekWsDisplay = (TextView) findMyViewById(R.id.reflow_word_space_display);
seekWsDisplay.setText(String.format("%.2f", progress * 0.05));
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
final SeekBar reflowQlSeek = (SeekBar)findMyViewById(R.id.reflow_quality_seeker);
reflowQlSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
TextView seekQlDisplay = (TextView) findMyViewById(R.id.reflow_quality_display);
seekQlDisplay.setText(String.format("%.2f", progress * 0.05));
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
ImageButton apply = (ImageButton) findMyViewById(R.id.reflow_apply);
apply.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final Spinner zsp = (Spinner) findMyViewById(R.id.reflow_zoom_spinner);
final Spinner dsp = (Spinner) findMyViewById(R.id.reflow_dpi_spinner);
final EditText edit = (EditText) findMyViewById(R.id.reflow_columns_edit);
float zoom = Float.parseFloat(zsp.getSelectedItem().toString());
int dpi = Integer.parseInt(dsp.getSelectedItem().toString());
int columns = Integer.parseInt(edit.getText().toString());
int[] m = new int[6];
controller.getMargins(m);
int m_left = m[0];
int m_right = m[1];
int m_top = m[2];
int m_bottom = m[3];
cropBorders[0] = 0;
cropBorders[1] = 0;
cropBorders[2] = 0;
cropBorders[3] = 0;
cropBorders[4] = 0;
cropBorders[5] = 0;
CheckBox cb = (CheckBox) findMyViewById(R.id.reflow_default_crop_box);
int default_trim = (cb.isChecked()) ? 1 : 0;
cb = (CheckBox) findMyViewById(R.id.reflow_preserve_indent_box);
int indent = (cb.isChecked()) ? 1 : 0;
cb = (CheckBox) findMyViewById(R.id.reflow_wrap_text_box);
int wrap_text = (cb.isChecked()) ? 1 : 0;
Spinner sp_rot = (Spinner) findMyViewById(R.id.reflow_rotation_spinner);
int rotation = Integer.parseInt(sp_rot.getSelectedItem().toString());
TextView mg = (TextView) findMyViewById(R.id.reflow_margin_display);
TextView ws = (TextView) findMyViewById(R.id.reflow_word_space_display);
TextView ql = (TextView) findMyViewById(R.id.reflow_quality_display);
float margin = Float.parseFloat(mg.getText().toString());
float word_space = Float.parseFloat(ws.getText().toString());
float quality = Float.parseFloat(ql.getText().toString());
controller.setReflowParameters(zoom, dpi, columns, lastPageInfo.screenWidth,
lastPageInfo.screenHeight, m_top,
m_bottom, m_left, m_right,
default_trim,
wrap_text,
indent,
rotation,
margin,
word_space,
quality);
changeReflowMode();
controller.changeMargins(cropBorders[0], cropBorders[2], cropBorders[1],
cropBorders[3], false, cropBorders[4], cropBorders[5]);
onAnimatorCancel();
}
});
ImageButton cancel = (ImageButton) findMyViewById(R.id.reflow_close);
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onAnimatorCancel();
}
});
}
| void initReflowScreen() {
final SeekBar reflowSeek = (SeekBar)findMyViewById(R.id.reflow_margin_seeker);
reflowSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
TextView seekDisplay = (TextView) findMyViewById(R.id.reflow_margin_display);
seekDisplay.setText(String.format("%.2f", progress * 0.02));
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
final SeekBar reflowWsSeek = (SeekBar)findMyViewById(R.id.reflow_word_space_seeker);
reflowWsSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
TextView seekWsDisplay = (TextView) findMyViewById(R.id.reflow_word_space_display);
seekWsDisplay.setText(String.format("%.2f", progress * 0.05));
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
final SeekBar reflowQlSeek = (SeekBar)findMyViewById(R.id.reflow_quality_seeker);
reflowQlSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
TextView seekQlDisplay = (TextView) findMyViewById(R.id.reflow_quality_display);
seekQlDisplay.setText(String.format("%.2f", progress * 0.05));
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
ImageButton apply = (ImageButton) findMyViewById(R.id.reflow_apply);
apply.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final Spinner zsp = (Spinner) findMyViewById(R.id.reflow_zoom_spinner);
final Spinner dsp = (Spinner) findMyViewById(R.id.reflow_dpi_spinner);
final EditText edit = (EditText) findMyViewById(R.id.reflow_columns_edit);
float zoom = Float.parseFloat(zsp.getSelectedItem().toString());
int dpi = Integer.parseInt(dsp.getSelectedItem().toString());
int columns = Integer.parseInt(edit.getText().toString());
int[] m = new int[6];
controller.getMargins(m);
int m_left = m[0];
int m_right = m[1];
int m_top = m[2];
int m_bottom = m[3];
cropBorders[0] = 0;
cropBorders[1] = 0;
cropBorders[2] = 0;
cropBorders[3] = 0;
cropBorders[4] = 0;
cropBorders[5] = 0;
CheckBox cb = (CheckBox) findMyViewById(R.id.reflow_default_crop_box);
int default_trim = (cb.isChecked()) ? 1 : 0;
cb = (CheckBox) findMyViewById(R.id.reflow_preserve_indent_box);
int indent = (cb.isChecked()) ? 1 : 0;
cb = (CheckBox) findMyViewById(R.id.reflow_wrap_text_box);
int wrap_text = (cb.isChecked()) ? 1 : 0;
Spinner sp_rot = (Spinner) findMyViewById(R.id.reflow_rotation_spinner);
int rotation = Integer.parseInt(sp_rot.getSelectedItem().toString());
TextView mg = (TextView) findMyViewById(R.id.reflow_margin_display);
TextView ws = (TextView) findMyViewById(R.id.reflow_word_space_display);
TextView ql = (TextView) findMyViewById(R.id.reflow_quality_display);
float margin = Float.parseFloat(mg.getText().toString());
float word_space = Float.parseFloat(ws.getText().toString());
float quality = Float.parseFloat(ql.getText().toString());
Display ds = getWindowManager().getDefaultDisplay();
Common.d("X: " + ds.getWidth() + " Y: " + ds.getHeight());
controller.setReflowParameters(zoom,
dpi,
columns,
ds.getWidth(),
ds.getHeight(),
m_top,
m_bottom, m_left, m_right,
default_trim,
wrap_text,
indent,
rotation,
margin,
word_space,
quality);
changeReflowMode();
controller.changeMargins(cropBorders[0], cropBorders[2], cropBorders[1],
cropBorders[3], false, cropBorders[4], cropBorders[5]);
onAnimatorCancel();
}
});
ImageButton cancel = (ImageButton) findMyViewById(R.id.reflow_close);
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onAnimatorCancel();
}
});
}
|
diff --git a/drools-analytics/src/test/java/org/drools/analytics/redundancy/NotesTest.java b/drools-analytics/src/test/java/org/drools/analytics/redundancy/NotesTest.java
index 5e83d7f51..1fa48ea42 100644
--- a/drools-analytics/src/test/java/org/drools/analytics/redundancy/NotesTest.java
+++ b/drools-analytics/src/test/java/org/drools/analytics/redundancy/NotesTest.java
@@ -1,58 +1,59 @@
package org.drools.analytics.redundancy;
import java.util.ArrayList;
import java.util.Collection;
import org.drools.StatelessSession;
import org.drools.analytics.TestBase;
import org.drools.analytics.components.LiteralRestriction;
import org.drools.analytics.components.PatternPossibility;
import org.drools.analytics.dao.AnalyticsDataFactory;
import org.drools.analytics.dao.AnalyticsResult;
import org.drools.analytics.report.components.AnalyticsMessage;
import org.drools.analytics.report.components.AnalyticsMessageBase;
import org.drools.analytics.report.components.Redundancy;
import org.drools.base.RuleNameMatchesAgendaFilter;
public class NotesTest extends TestBase {
public void testRedundantRestrictionsInPatternPossibilities()
throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Notes.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"Find redundant restrictions from pattern possibilities"));
Collection<Object> objects = new ArrayList<Object>();
LiteralRestriction left = new LiteralRestriction();
LiteralRestriction right = new LiteralRestriction();
Redundancy redundancy = new Redundancy(
Redundancy.RedundancyType.STRONG, left, right);
PatternPossibility possibility = new PatternPossibility();
possibility.add(left);
possibility.add(right);
objects.add(left);
objects.add(right);
objects.add(redundancy);
objects.add(possibility);
+ AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(objects);
Collection<AnalyticsMessageBase> notes = result
.getBySeverity(AnalyticsMessage.Severity.NOTE);
// Has at least one item.
assertEquals(1, notes.size());
AnalyticsMessageBase note = notes.iterator().next();
assertTrue(note.getFaulty().equals(redundancy));
}
}
| true | true | public void testRedundantRestrictionsInPatternPossibilities()
throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Notes.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"Find redundant restrictions from pattern possibilities"));
Collection<Object> objects = new ArrayList<Object>();
LiteralRestriction left = new LiteralRestriction();
LiteralRestriction right = new LiteralRestriction();
Redundancy redundancy = new Redundancy(
Redundancy.RedundancyType.STRONG, left, right);
PatternPossibility possibility = new PatternPossibility();
possibility.add(left);
possibility.add(right);
objects.add(left);
objects.add(right);
objects.add(redundancy);
objects.add(possibility);
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(objects);
Collection<AnalyticsMessageBase> notes = result
.getBySeverity(AnalyticsMessage.Severity.NOTE);
// Has at least one item.
assertEquals(1, notes.size());
AnalyticsMessageBase note = notes.iterator().next();
assertTrue(note.getFaulty().equals(redundancy));
}
| public void testRedundantRestrictionsInPatternPossibilities()
throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Notes.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"Find redundant restrictions from pattern possibilities"));
Collection<Object> objects = new ArrayList<Object>();
LiteralRestriction left = new LiteralRestriction();
LiteralRestriction right = new LiteralRestriction();
Redundancy redundancy = new Redundancy(
Redundancy.RedundancyType.STRONG, left, right);
PatternPossibility possibility = new PatternPossibility();
possibility.add(left);
possibility.add(right);
objects.add(left);
objects.add(right);
objects.add(redundancy);
objects.add(possibility);
AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(objects);
Collection<AnalyticsMessageBase> notes = result
.getBySeverity(AnalyticsMessage.Severity.NOTE);
// Has at least one item.
assertEquals(1, notes.size());
AnalyticsMessageBase note = notes.iterator().next();
assertTrue(note.getFaulty().equals(redundancy));
}
|
diff --git a/software/ncireportwriter/test/src/java/gov/nih/nci/evs/reportwriter/test/lexevs/DataUtilsTest.java b/software/ncireportwriter/test/src/java/gov/nih/nci/evs/reportwriter/test/lexevs/DataUtilsTest.java
index 409d569..ad890e2 100644
--- a/software/ncireportwriter/test/src/java/gov/nih/nci/evs/reportwriter/test/lexevs/DataUtilsTest.java
+++ b/software/ncireportwriter/test/src/java/gov/nih/nci/evs/reportwriter/test/lexevs/DataUtilsTest.java
@@ -1,74 +1,74 @@
package gov.nih.nci.evs.reportwriter.test.lexevs;
import java.util.*;
import gov.nih.nci.evs.reportwriter.service.*;
import gov.nih.nci.evs.reportwriter.test.utils.*;
import gov.nih.nci.evs.reportwriter.utils.*;
import gov.nih.nci.evs.utils.*;
import org.LexGrid.concepts.*;
import org.apache.log4j.*;
public class DataUtilsTest {
private static Logger _logger = Logger.getLogger(DataUtilsTest.class);
public static void main(String[] args) {
args = SetupEnv.getInstance().parse(args);
DataUtilsTest test = new DataUtilsTest();
test.getAssociations();
//test.generateStandardReport();
}
public void getAssociations() {
String scheme = "NCI Thesaurus";
String version = "09.12d";
String code = "C74456"; // CDISC SDTM Anatomical Location Terminology
code = "C63923"; // FDA Established Names and Unique Ingredient Identifier Codes Terminology
String assocName = "A8";
boolean retrieveTargets = false;
boolean showAll = true;
_logger.info(StringUtils.SEPARATOR);
_logger.info("Calling: getAssociations");
_logger.info(" * retrieveTargets: " + retrieveTargets);
_logger.info(" * scheme: " + scheme);
_logger.info(" * version: " + version);
_logger.info(" * code: " + code);
_logger.info(" * assocName: " + assocName);
- Vector<Concept> v = DataUtils.getAssociations(
+ Vector<Entity> v = DataUtils.getAssociations(
retrieveTargets, scheme, version, code, assocName);
int i=0, n=v.size();
- Iterator<Concept> iterator = v.iterator();
+ Iterator<Entity> iterator = v.iterator();
_logger.info("Results: (size=" + n + ")");
while (iterator.hasNext()) {
- Concept concept = iterator.next();
+ Entity concept = iterator.next();
if (showAll || i%100 == 0 || i+1 == n) {
String c_code = concept.getEntityCode();
String description = concept.getEntityDescription().getContent();
_logger.info(" " + i + ") " + c_code + ": " + description);
}
++i;
}
}
public void generateStandardReport() {
String outputDir = "c:/apps/evs/ncireportwriter-webapp/downloads";
String standardReportLabel = "FDA-UNII Subset REPORT Test";
String uid = "rwadmin";
String emailAddress = "[email protected]";
_logger.info("Calling: generateStandardReport");
_logger.info(" * outputDir: " + outputDir);
_logger.info(" * standardReportLabel: " + standardReportLabel);
_logger.info(" * uid: " + uid);
StringBuffer warningMsg = new StringBuffer();
ReportGenerationThread thread = new ReportGenerationThread(
outputDir, standardReportLabel, uid, emailAddress);
Boolean successful = thread.generateStandardReport(outputDir,
standardReportLabel, uid, warningMsg);
_logger.info(" * successful: " + successful);
_logger.info(" * warningMsg: " + warningMsg.toString());
}
}
| false | true | public void getAssociations() {
String scheme = "NCI Thesaurus";
String version = "09.12d";
String code = "C74456"; // CDISC SDTM Anatomical Location Terminology
code = "C63923"; // FDA Established Names and Unique Ingredient Identifier Codes Terminology
String assocName = "A8";
boolean retrieveTargets = false;
boolean showAll = true;
_logger.info(StringUtils.SEPARATOR);
_logger.info("Calling: getAssociations");
_logger.info(" * retrieveTargets: " + retrieveTargets);
_logger.info(" * scheme: " + scheme);
_logger.info(" * version: " + version);
_logger.info(" * code: " + code);
_logger.info(" * assocName: " + assocName);
Vector<Concept> v = DataUtils.getAssociations(
retrieveTargets, scheme, version, code, assocName);
int i=0, n=v.size();
Iterator<Concept> iterator = v.iterator();
_logger.info("Results: (size=" + n + ")");
while (iterator.hasNext()) {
Concept concept = iterator.next();
if (showAll || i%100 == 0 || i+1 == n) {
String c_code = concept.getEntityCode();
String description = concept.getEntityDescription().getContent();
_logger.info(" " + i + ") " + c_code + ": " + description);
}
++i;
}
}
| public void getAssociations() {
String scheme = "NCI Thesaurus";
String version = "09.12d";
String code = "C74456"; // CDISC SDTM Anatomical Location Terminology
code = "C63923"; // FDA Established Names and Unique Ingredient Identifier Codes Terminology
String assocName = "A8";
boolean retrieveTargets = false;
boolean showAll = true;
_logger.info(StringUtils.SEPARATOR);
_logger.info("Calling: getAssociations");
_logger.info(" * retrieveTargets: " + retrieveTargets);
_logger.info(" * scheme: " + scheme);
_logger.info(" * version: " + version);
_logger.info(" * code: " + code);
_logger.info(" * assocName: " + assocName);
Vector<Entity> v = DataUtils.getAssociations(
retrieveTargets, scheme, version, code, assocName);
int i=0, n=v.size();
Iterator<Entity> iterator = v.iterator();
_logger.info("Results: (size=" + n + ")");
while (iterator.hasNext()) {
Entity concept = iterator.next();
if (showAll || i%100 == 0 || i+1 == n) {
String c_code = concept.getEntityCode();
String description = concept.getEntityDescription().getContent();
_logger.info(" " + i + ") " + c_code + ": " + description);
}
++i;
}
}
|
diff --git a/samples/src/main/java/de/agilecoders/wicket/samples/WicketApplication.java b/samples/src/main/java/de/agilecoders/wicket/samples/WicketApplication.java
index 130b98e5..f9a378ad 100644
--- a/samples/src/main/java/de/agilecoders/wicket/samples/WicketApplication.java
+++ b/samples/src/main/java/de/agilecoders/wicket/samples/WicketApplication.java
@@ -1,99 +1,99 @@
package de.agilecoders.wicket.samples;
import de.agilecoders.wicket.Bootstrap;
import de.agilecoders.wicket.samples.pages.HomePage;
import de.agilecoders.wicket.settings.BootstrapSettings;
import org.apache.wicket.Application;
import org.apache.wicket.Page;
import org.apache.wicket.RuntimeConfigurationType;
import org.apache.wicket.markup.html.IPackageResourceGuard;
import org.apache.wicket.markup.html.SecurePackageResourceGuard;
import org.apache.wicket.protocol.http.WebApplication;
import org.wicketstuff.annotation.scan.AnnotatedMountScanner;
import java.io.IOException;
import java.util.Properties;
/**
* Demo Application instance.
*/
public class WicketApplication extends WebApplication {
private Properties properties;
/**
* Get Application for current thread.
*
* @return The current thread's Application
*/
public static WicketApplication get() {
return (WicketApplication) Application.get();
}
/**
* Constructor.
*/
public WicketApplication() {
super();
properties = loadProperties();
setConfigurationType(RuntimeConfigurationType.valueOf(properties.getProperty("configuration.type")));
}
/**
* @see org.apache.wicket.Application#getHomePage()
*/
@Override
public Class<? extends Page> getHomePage() {
return HomePage.class;
}
/**
* @see org.apache.wicket.Application#init()
*/
@Override
public void init() {
super.init();
// wicket markup leads to strange ui problems because css selectors
// won't match anymore.
getMarkupSettings().setStripWicketTags(true);
// Allow fonts.
IPackageResourceGuard packageResourceGuard = getResourceSettings().getPackageResourceGuard();
if (packageResourceGuard instanceof SecurePackageResourceGuard) {
SecurePackageResourceGuard guard = (SecurePackageResourceGuard) packageResourceGuard;
guard.addPattern("+*.woff");
guard.addPattern("+*.ttf");
guard.addPattern("+*.svg");
}
configureBootstrap();
- new AnnotatedMountScanner().scanPackage("de.agilecoders.wicket.demo").mount(this);
+ new AnnotatedMountScanner().scanPackage("de.agilecoders.wicket.samples.pages").mount(this);
}
private void configureBootstrap() {
BootstrapSettings settings = new BootstrapSettings();
settings.minify(true); // use minimized version of all bootstrap references
settings.useJqueryPP(true);
settings.useModernizr(true);
settings.useResponsiveCss(true);
settings.getBootstrapLessCompilerSettings().setUseLessCompiler(true);
Bootstrap.install(this, settings);
}
public Properties getProperties() {
return properties;
}
private Properties loadProperties() {
Properties properties = new Properties();
try {
properties.load(getClass().getResourceAsStream("/config.properties"));
} catch (IOException e) {
throw new RuntimeException(e);
}
return properties;
}
}
| true | true | public void init() {
super.init();
// wicket markup leads to strange ui problems because css selectors
// won't match anymore.
getMarkupSettings().setStripWicketTags(true);
// Allow fonts.
IPackageResourceGuard packageResourceGuard = getResourceSettings().getPackageResourceGuard();
if (packageResourceGuard instanceof SecurePackageResourceGuard) {
SecurePackageResourceGuard guard = (SecurePackageResourceGuard) packageResourceGuard;
guard.addPattern("+*.woff");
guard.addPattern("+*.ttf");
guard.addPattern("+*.svg");
}
configureBootstrap();
new AnnotatedMountScanner().scanPackage("de.agilecoders.wicket.demo").mount(this);
}
| public void init() {
super.init();
// wicket markup leads to strange ui problems because css selectors
// won't match anymore.
getMarkupSettings().setStripWicketTags(true);
// Allow fonts.
IPackageResourceGuard packageResourceGuard = getResourceSettings().getPackageResourceGuard();
if (packageResourceGuard instanceof SecurePackageResourceGuard) {
SecurePackageResourceGuard guard = (SecurePackageResourceGuard) packageResourceGuard;
guard.addPattern("+*.woff");
guard.addPattern("+*.ttf");
guard.addPattern("+*.svg");
}
configureBootstrap();
new AnnotatedMountScanner().scanPackage("de.agilecoders.wicket.samples.pages").mount(this);
}
|
diff --git a/src/org/jaudiotagger/tag/TagOptionSingleton.java b/src/org/jaudiotagger/tag/TagOptionSingleton.java
index 9f58ddb3..7d50ac76 100644
--- a/src/org/jaudiotagger/tag/TagOptionSingleton.java
+++ b/src/org/jaudiotagger/tag/TagOptionSingleton.java
@@ -1,1375 +1,1376 @@
/**
* @author : Paul Taylor
* @author : Eric Farng
*
* Version @version:$Id$
*
* MusicTag Copyright (C)2003,2004
*
* 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,
* you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Description:
* Options that are used for every datatype and class in this library.
*
*/
package org.jaudiotagger.tag;
import org.jaudiotagger.tag.id3.framebody.AbstractID3v2FrameBody;
import org.jaudiotagger.tag.id3.framebody.FrameBodyCOMM;
import org.jaudiotagger.tag.id3.framebody.FrameBodyTIPL;
import org.jaudiotagger.tag.id3.valuepair.Languages;
import org.jaudiotagger.tag.id3.valuepair.GenreTypes;
import org.jaudiotagger.tag.lyrics3.Lyrics3v2Fields;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
public class TagOptionSingleton
{
/**
*
*/
private static HashMap tagOptionTable = new HashMap();
/**
*
*/
private static String DEFAULT = "default";
/**
*
*/
private static Object defaultOptions = DEFAULT;
/**
*
*/
private HashMap keywordMap = new HashMap();
/**
* Map of lyric ID's to Boolean objects if we should or should not save the
* specific Kyrics3 field. Defaults to true.
*/
private HashMap lyrics3SaveFieldMap = new HashMap();
/**
* parenthesis map stuff
*/
private HashMap parenthesisMap = new HashMap();
/**
* <code>HashMap</code> listing words to be replaced if found
*/
private HashMap replaceWordMap = new HashMap();
/**
*
*/
private LinkedList endWordDelimiterList = new LinkedList();
/**
* delimiters within a file name
*/
private LinkedList filenameDelimiterList = new LinkedList();
/**
*
*/
private LinkedList startWordDelimiterList = new LinkedList();
/**
* words to always set the case as upper or lower case
*/
private LinkedList upperLowerCaseWordList = new LinkedList();
/**
* default language for any ID3v2 tags frameswhich require it. This string
* is in the [ISO-639-2] ISO/FDIS 639-2 definition
*/
private String language = "eng";
/**
*
*/
private boolean compositeMatchOverwrite = false;
/**
*
*/
private boolean filenameTagSave = false;
/**
* if we should save any fields of the ID3v1 tag or not. Defaults to true.
*/
private boolean id3v1Save = true;
/**
* if we should save the album field of the ID3v1 tag or not. Defaults to
* true.
*/
private boolean id3v1SaveAlbum = true;
/**
* if we should save the artist field of the ID3v1 tag or not. Defaults to
* true.
*/
private boolean id3v1SaveArtist = true;
/**
* if we should save the comment field of the ID3v1 tag or not. Defaults to
* true.
*/
private boolean id3v1SaveComment = true;
/**
* if we should save the genre field of the ID3v1 tag or not. Defaults to
* true.
*/
private boolean id3v1SaveGenre = true;
/**
* if we should save the title field of the ID3v1 tag or not. Defaults to
* true.
*/
private boolean id3v1SaveTitle = true;
/**
* if we should save the track field of the ID3v1 tag or not. Defaults to
* true.
*/
private boolean id3v1SaveTrack = true;
/**
* if we should save the year field of the ID3v1 tag or not. Defaults to
* true.
*/
private boolean id3v1SaveYear = true;
/**
* if we should keep an empty ID3v2 frame while we're reading. This is
* different from a string of white space. Defaults to false.
*
* @todo I don't think I'm checking this right now
*/
private boolean id3v2KeepEmptyFrameIfRead = false;
/**
* When adjusting the ID3v2 padding, if should we copy the current ID3v2
* tag to the new MP3 file. Defaults to true.
*/
private boolean id3v2PaddingCopyTag = true;
/**
* When adjusting the ID3v2 padding, if we should shorten the length of the
* ID3v2 tag padding. Defaults to false.
*/
private boolean id3v2PaddingWillShorten = false;
/**
* if we should save any fields of the ID3v2 tag or not. Defaults to true.
*/
private boolean id3v2Save = true;
/**
* if we should save empty ID3v2 frames or not. Defaults to false.
*
* @todo I don't think this is implemented yet.
*/
private boolean id3v2SaveEmptyFrame = false;
/**
* if we should save the ID3v2 extended header or not. Defaults to false.
*
* @todo Not implemented yet
*/
private boolean id3v2SaveExtendedHeader = false;
/**
* if we should keep an empty Lyrics3 field while we're reading. This is
* different from a string of white space. Defaults to false.
*/
private boolean lyrics3KeepEmptyFieldIfRead = false;
/**
* if we should save any fields of the Lyrics3 tag or not. Defaults to
* true.
*/
private boolean lyrics3Save = true;
/**
* if we should save empty Lyrics3 field or not. Defaults to false.
*
* @todo I don't think this is implemented yet.
*/
private boolean lyrics3SaveEmptyField = false;
/**
*
*/
private boolean originalSavedAfterAdjustingID3v2Padding = true;
/**
* default play counter size in bytes for the ID3v2 Tag.
*
* @todo implement this.
*/
private byte playCounterSize = 4;
/**
* default text encoding for any ID3v2 tag frames which require it.
*/
private byte textEncoding = 0;
/**
* default time stamp format for any ID3v2 tag frames which require it.
*/
private byte timeStampFormat = 2;
/**
* factor to increase the id3v2 padding size. When the ID3v2 tag padding
* length is calculated and is not large enough to fit the current ID3v2
* tag, the padding length will be multiplied by this number until it is
* large enough.
*/
private float id3v2PaddingMultiplier = 2;
/**
* padding length of the ID3v2 tag.
*/
private int id3v2PaddingSize = 2048;
/**
* number of frames to sync when trying to find the start of the MP3 frame
* data. The start of the MP3 frame data is the start of the music and is
* different from the ID3v2 frame data.
*/
private int numberMP3SyncFrame = 3;
private boolean unsyncTags = false;
/**
* Creates a new TagOptions datatype. All Options are set to their default
* values
*/
private TagOptionSingleton()
{
setToDefault();
}
/**
*
*
* @return
*/
public static TagOptionSingleton getInstance()
{
return getInstance(defaultOptions);
}
/**
*
*
* @param instanceKey
* @return
*/
public static TagOptionSingleton getInstance(Object instanceKey)
{
TagOptionSingleton tagOptions = (TagOptionSingleton) tagOptionTable.get(instanceKey);
if (tagOptions == null)
{
tagOptions = new TagOptionSingleton();
tagOptionTable.put(instanceKey, tagOptions);
}
return tagOptions;
}
/**
*
*
* @param open
* @return
*/
public String getCloseParenthesis(String open)
{
return (String) parenthesisMap.get(open);
}
/**
*
*
* @param close
* @return
*/
public boolean isCloseParenthesis(String close)
{
return parenthesisMap.containsValue(close);
}
/**
*
*
* @param compositeMatchOverwrite
*/
public void setCompositeMatchOverwrite(boolean compositeMatchOverwrite)
{
this.compositeMatchOverwrite = compositeMatchOverwrite;
}
/**
*
*
* @return
*/
public boolean isCompositeMatchOverwrite()
{
return compositeMatchOverwrite;
}
/**
*
*
* @param filenameTagSave
*/
public void setFilenameTagSave(boolean filenameTagSave)
{
this.filenameTagSave = filenameTagSave;
}
/**
*
*
* @return
*/
public boolean isFilenameTagSave()
{
return filenameTagSave;
}
/**
*
*
* @return
*/
public boolean isId3v2SaveExtendedHeader()
{
return id3v2SaveExtendedHeader;
}
/**
*
*
* @param instanceKey
*/
public void setInstanceKey(Object instanceKey)
{
TagOptionSingleton.defaultOptions = instanceKey;
}
/**
*
*
* @return
*/
public static Object getInstanceKey()
{
return defaultOptions;
}
/**
*
*
* @return
*/
public Iterator getEndWordDelimiterIterator()
{
return endWordDelimiterList.iterator();
}
/**
*
*
* @return
*/
public Iterator getFilenameDelimiterIterator()
{
return filenameDelimiterList.iterator();
}
/**
*
*
* @param id3v1Save
*/
public void setId3v1Save(boolean id3v1Save)
{
this.id3v1Save = id3v1Save;
}
/**
*
*
* @return
*/
public boolean isId3v1Save()
{
return id3v1Save;
}
/**
*
*
* @param id3v1SaveAlbum
*/
public void setId3v1SaveAlbum(boolean id3v1SaveAlbum)
{
this.id3v1SaveAlbum = id3v1SaveAlbum;
}
/**
*
*
* @return
*/
public boolean isId3v1SaveAlbum()
{
return id3v1SaveAlbum;
}
/**
*
*
* @param id3v1SaveArtist
*/
public void setId3v1SaveArtist(boolean id3v1SaveArtist)
{
this.id3v1SaveArtist = id3v1SaveArtist;
}
/**
*
*
* @return
*/
public boolean isId3v1SaveArtist()
{
return id3v1SaveArtist;
}
/**
*
*
* @param id3v1SaveComment
*/
public void setId3v1SaveComment(boolean id3v1SaveComment)
{
this.id3v1SaveComment = id3v1SaveComment;
}
/**
*
*
* @return
*/
public boolean isId3v1SaveComment()
{
return id3v1SaveComment;
}
/**
*
*
* @param id3v1SaveGenre
*/
public void setId3v1SaveGenre(boolean id3v1SaveGenre)
{
this.id3v1SaveGenre = id3v1SaveGenre;
}
/**
*
*
* @return
*/
public boolean isId3v1SaveGenre()
{
return id3v1SaveGenre;
}
/**
*
*
* @param id3v1SaveTitle
*/
public void setId3v1SaveTitle(boolean id3v1SaveTitle)
{
this.id3v1SaveTitle = id3v1SaveTitle;
}
/**
*
*
* @return
*/
public boolean isId3v1SaveTitle()
{
return id3v1SaveTitle;
}
/**
*
*
* @param id3v1SaveTrack
*/
public void setId3v1SaveTrack(boolean id3v1SaveTrack)
{
this.id3v1SaveTrack = id3v1SaveTrack;
}
/**
*
*
* @return
*/
public boolean isId3v1SaveTrack()
{
return id3v1SaveTrack;
}
/**
*
*
* @param id3v1SaveYear
*/
public void setId3v1SaveYear(boolean id3v1SaveYear)
{
this.id3v1SaveYear = id3v1SaveYear;
}
/**
*
*
* @return
*/
public boolean isId3v1SaveYear()
{
return id3v1SaveYear;
}
/**
*
*
* @param id3v2KeepEmptyFrameIfRead
*/
public void setId3v2KeepEmptyFrameIfRead(boolean id3v2KeepEmptyFrameIfRead)
{
this.id3v2KeepEmptyFrameIfRead = id3v2KeepEmptyFrameIfRead;
}
/**
*
*
* @return
*/
public boolean isId3v2KeepEmptyFrameIfRead()
{
return id3v2KeepEmptyFrameIfRead;
}
/**
*
*
* @param id3v2PaddingCopyTag
*/
public void setId3v2PaddingCopyTag(boolean id3v2PaddingCopyTag)
{
this.id3v2PaddingCopyTag = id3v2PaddingCopyTag;
}
/**
*
*
* @return
*/
public boolean isId3v2PaddingCopyTag()
{
return id3v2PaddingCopyTag;
}
/**
* Sets the factor to increase the id3v2 padding size. When the ID3v2 tag
* padding length is calculated and is not large enough to fit the current
* ID3v2 tag, the padding length will be multiplied by this number until
* it is large enough.
*
* @param mult new factor to increase the id3v2 padding size.
*/
public void setId3v2PaddingMultiplier(float mult)
{
if (mult > 1)
{
id3v2PaddingMultiplier = mult;
}
}
/**
* Returns the factor to increase the id3v2 padding size. When the ID3v2
* tag padding length is calculated and is not large enough to fit the
* current ID3v2 tag, the padding length will be multiplied by this number
* until it is large enough.
*
* @return the factor to increase the id3v2 padding size
*/
public float getId3v2PaddingMultiplier()
{
return id3v2PaddingMultiplier;
}
/**
* Sets the initial ID3v2 padding length. This will be the minimum padding
* length of the ID3v2 tag. The <code>willShorten</code> setting will not
* make the length shorter than this value.
*
* @param size the new initial ID3v2 padding length
*/
public void setId3v2PaddingSize(int size)
{
if (size >= 0)
{
id3v2PaddingSize = size;
}
}
/**
* Returns the initial ID3v2 padding length. This will be the minimum
* padding length of the ID3v2 tag. The <code>willShorten</code> setting
* will not make the length shorter than this value.
*
* @return the initial ID3v2 padding length
*/
public int getId3v2PaddingSize()
{
return id3v2PaddingSize;
}
/**
*
*
* @param id3v2PaddingWillShorten
*/
public void setId3v2PaddingWillShorten(boolean id3v2PaddingWillShorten)
{
this.id3v2PaddingWillShorten = id3v2PaddingWillShorten;
}
/**
*
*
* @return
*/
public boolean isId3v2PaddingWillShorten()
{
return id3v2PaddingWillShorten;
}
/**
*
*
* @param id3v2Save
*/
public void setId3v2Save(boolean id3v2Save)
{
this.id3v2Save = id3v2Save;
}
/**
*
*
* @return
*/
public boolean isId3v2Save()
{
return id3v2Save;
}
/**
*
*
* @param id3v2SaveEmptyFrame
*/
public void setId3v2SaveEmptyFrame(boolean id3v2SaveEmptyFrame)
{
this.id3v2SaveEmptyFrame = id3v2SaveEmptyFrame;
}
/**
*
*
* @return
*/
public boolean isId3v2SaveEmptyFrame()
{
return id3v2SaveEmptyFrame;
}
/**
*
*
* @param id3v2SaveExtendedHeader
*/
public void setId3v2SaveExtendedHeader(boolean id3v2SaveExtendedHeader)
{
this.id3v2SaveExtendedHeader = id3v2SaveExtendedHeader;
}
/**
*
*
* @return
*/
public Iterator getKeywordIterator()
{
return keywordMap.keySet().iterator();
}
/**
*
*
* @param id3v2_4FrameBody
* @return
*/
public Iterator getKeywordListIterator(Class id3v2_4FrameBody)
{
return ((LinkedList) keywordMap.get(id3v2_4FrameBody)).iterator();
}
/**
* Sets the default language for any ID3v2 tag frames which require it.
* While the value will already exist when reading from a file, this value
* will be used when a new ID3v2 Frame is created from scratch.
*
* @param lang language ID, [ISO-639-2] ISO/FDIS 639-2 definition
*/
public void setLanguage(String lang)
{
if (Languages.getInstanceOf().getIdToValueMap().containsKey(lang))
{
language = lang;
}
}
/**
* Returns the default language for any ID3v2 tag frames which require it.
*
* @return language ID, [ISO-639-2] ISO/FDIS 639-2 definition
*/
public String getLanguage()
{
return language;
}
/**
*
*
* @param lyrics3KeepEmptyFieldIfRead
*/
public void setLyrics3KeepEmptyFieldIfRead(boolean lyrics3KeepEmptyFieldIfRead)
{
this.lyrics3KeepEmptyFieldIfRead = lyrics3KeepEmptyFieldIfRead;
}
/**
*
*
* @return
*/
public boolean isLyrics3KeepEmptyFieldIfRead()
{
return lyrics3KeepEmptyFieldIfRead;
}
/**
*
*
* @param lyrics3Save
*/
public void setLyrics3Save(boolean lyrics3Save)
{
this.lyrics3Save = lyrics3Save;
}
/**
*
*
* @return
*/
public boolean isLyrics3Save()
{
return lyrics3Save;
}
/**
*
*
* @param lyrics3SaveEmptyField
*/
public void setLyrics3SaveEmptyField(boolean lyrics3SaveEmptyField)
{
this.lyrics3SaveEmptyField = lyrics3SaveEmptyField;
}
/**
*
*
* @return
*/
public boolean isLyrics3SaveEmptyField()
{
return lyrics3SaveEmptyField;
}
/**
* Sets if we should save the Lyrics3 field. Defaults to true.
*
* @param id Lyrics3 id string
* @param save true if you want to save this specific Lyrics3 field.
*/
public void setLyrics3SaveField(String id, boolean save)
{
this.lyrics3SaveFieldMap.put(id, new Boolean(save));
}
/**
* Returns true if we should save the Lyrics3 field asked for in the
* argument. Defaults to true.
*
* @param id Lyrics3 id string
* @return true if we should save the Lyrics3 field.
*/
public boolean getLyrics3SaveField(String id)
{
return ((Boolean) lyrics3SaveFieldMap.get(id)).booleanValue();
}
/**
*
*
* @return
*/
public HashMap getLyrics3SaveFieldMap()
{
return lyrics3SaveFieldMap;
}
/**
*
*
* @param oldWord
* @return
*/
public String getNewReplaceWord(String oldWord)
{
return (String) replaceWordMap.get(oldWord);
}
/**
* Sets the number of MP3 frames to sync when trying to find the start of
* the MP3 frame data. The start of the MP3 frame data is the start of the
* music and is different from the ID3v2 frame data. WinAmp 2.8 seems to
* sync 3 frames. Default is 5.
*
* @param numberMP3SyncFrame number of MP3 frames to sync
*/
public void setNumberMP3SyncFrame(int numberMP3SyncFrame)
{
this.numberMP3SyncFrame = numberMP3SyncFrame;
}
/**
* Returns the number of MP3 frames to sync when trying to find the start
* of the MP3 frame data. The start of the MP3 frame data is the start of
* the music and is different from the ID3v2 frame data. WinAmp 2.8 seems
* to sync 3 frames. Default is 5.
*
* @return number of MP3 frames to sync
*/
public int getNumberMP3SyncFrame()
{
return numberMP3SyncFrame;
}
/**
*
*
* @return
*/
public Iterator getOldReplaceWordIterator()
{
return replaceWordMap.keySet().iterator();
}
/**
*
*
* @param open
* @return
*/
public boolean isOpenParenthesis(String open)
{
return parenthesisMap.containsKey(open);
}
/**
*
*
* @return
*/
public Iterator getOpenParenthesisIterator()
{
return parenthesisMap.keySet().iterator();
}
/**
*
*
* @param originalSavedAfterAdjustingID3v2Padding
*
*/
public void setOriginalSavedAfterAdjustingID3v2Padding(boolean originalSavedAfterAdjustingID3v2Padding)
{
this.originalSavedAfterAdjustingID3v2Padding = originalSavedAfterAdjustingID3v2Padding;
}
/**
*
*
* @return
*/
public boolean isOriginalSavedAfterAdjustingID3v2Padding()
{
return originalSavedAfterAdjustingID3v2Padding;
}
/**
* Sets the default play counter size for the PCNT ID3v2 frame. While the
* value will already exist when reading from a file, this value will be
* used when a new ID3v2 Frame is created from scratch.
*
* @param size the default play counter size for the PCNT ID3v2 frame
*/
public void setPlayCounterSize(byte size)
{
if (size > 0)
{
playCounterSize = size;
}
}
/**
* Returns the default play counter size for the PCNT ID3v2 frame.
*
* @return the default play counter size for the PCNT ID3v2 frame
*/
public byte getPlayCounterSize()
{
return playCounterSize;
}
/**
*
*
* @return
*/
public Iterator getStartWordDelimiterIterator()
{
return startWordDelimiterList.iterator();
}
/**
* Sets the default text encoding for any ID3v2 tag frames which require
* it. While the value will already exist when reading from a file, this
* value will be used when a new ID3v2 Frame is created from scratch.
* <p/>
* <P>
* $00 ISO-8859-1 [ISO-8859-1]. Terminated with $00.<BR> $01 UTF-16
* [UTF-16] encoded Unicode [UNICODE] with BOM. All strings in the same
* frame SHALL have the same byteorder. Terminated with $00 00.<BR> $02
* UTF-16BE [UTF-16] encoded Unicode [UNICODE] without BOM. Terminated
* with $00 00.<BR> $03 UTF-8 [UTF-8] encoded Unicode [UNICODE].
* Terminated with $00.<BR>
* </p>
*
* @param enc new default text encoding
*/
public void setTextEncoding(byte enc)
{
if ((enc >= 0) && (enc <= 3))
{
textEncoding = enc;
}
}
/**
* Returns the default text encoding format for ID3v2 tags which require
* it.
* <p/>
* <P>
* $00 ISO-8859-1 [ISO-8859-1]. Terminated with $00.<BR> $01 UTF-16
* [UTF-16] encoded Unicode [UNICODE] with BOM. All strings in the same
* frame SHALL have the same byteorder. Terminated with $00 00.<BR> $02
* UTF-16BE [UTF-16] encoded Unicode [UNICODE] without BOM. Terminated
* with $00 00.<BR> $03 UTF-8 [UTF-8] encoded Unicode [UNICODE].
* Terminated with $00.<BR>
* </p>
*
* @return the default text encoding
*/
public byte getTextEncoding()
{
return textEncoding;
}
/**
* Sets the default time stamp format for ID3v2 tags which require it.
* While the value will already exist when reading from a file, this value
* will be used when a new ID3v2 Frame is created from scratch.
* <p/>
* <P>
* $01 Absolute time, 32 bit sized, using MPEG frames as unit<br>
* $02 Absolute time, 32 bit sized, using milliseconds as unit<br>
* </p>
*
* @param tsf the new default time stamp format
*/
public void setTimeStampFormat(byte tsf)
{
if ((tsf == 1) || (tsf == 2))
{
timeStampFormat = tsf;
}
}
/**
* Returns the default time stamp format for ID3v2 tags which require it.
* <p/>
* <P>
* $01 Absolute time, 32 bit sized, using MPEG frames as unit<br>
* $02 Absolute time, 32 bit sized, using milliseconds as unit<br>
* </p>
*
* @return the default time stamp format
*/
public byte getTimeStampFormat()
{
return timeStampFormat;
}
/**
*
*/
public void setToDefault()
{
keywordMap = new HashMap();
compositeMatchOverwrite = false;
endWordDelimiterList = new LinkedList();
filenameDelimiterList = new LinkedList();
filenameTagSave = false;
id3v1Save = true;
id3v1SaveAlbum = true;
id3v1SaveArtist = true;
id3v1SaveComment = true;
id3v1SaveGenre = true;
id3v1SaveTitle = true;
id3v1SaveTrack = true;
id3v1SaveYear = true;
id3v2KeepEmptyFrameIfRead = false;
id3v2PaddingCopyTag = true;
id3v2PaddingWillShorten = false;
id3v2Save = true;
id3v2SaveEmptyFrame = false;
id3v2SaveExtendedHeader = false;
id3v2PaddingMultiplier = 2;
id3v2PaddingSize = 2048;
language = "eng";
lyrics3KeepEmptyFieldIfRead = false;
lyrics3Save = true;
lyrics3SaveEmptyField = false;
lyrics3SaveFieldMap = new HashMap();
numberMP3SyncFrame = 3;
parenthesisMap = new HashMap();
playCounterSize = 4;
replaceWordMap = new HashMap();
startWordDelimiterList = new LinkedList();
textEncoding = 0;
timeStampFormat = 2;
upperLowerCaseWordList = new LinkedList();
+ unsyncTags = false;
/**
* default all lyrics3 fields to save. id3v1 fields are individual
* settings. id3v2 fields are always looked at to save.
*/
Iterator iterator = Lyrics3v2Fields.getInstanceOf().getIdToValueMap().keySet().iterator();
String fieldId;
while (iterator.hasNext())
{
fieldId = (String) iterator.next();
lyrics3SaveFieldMap.put(fieldId, new Boolean(true));
}
try
{
addKeyword(FrameBodyCOMM.class, "ultimix");
addKeyword(FrameBodyCOMM.class, "dance");
addKeyword(FrameBodyCOMM.class, "mix");
addKeyword(FrameBodyCOMM.class, "remix");
addKeyword(FrameBodyCOMM.class, "rmx");
addKeyword(FrameBodyCOMM.class, "live");
addKeyword(FrameBodyCOMM.class, "cover");
addKeyword(FrameBodyCOMM.class, "soundtrack");
addKeyword(FrameBodyCOMM.class, "version");
addKeyword(FrameBodyCOMM.class, "acoustic");
addKeyword(FrameBodyCOMM.class, "original");
addKeyword(FrameBodyCOMM.class, "cd");
addKeyword(FrameBodyCOMM.class, "extended");
addKeyword(FrameBodyCOMM.class, "vocal");
addKeyword(FrameBodyCOMM.class, "unplugged");
addKeyword(FrameBodyCOMM.class, "acapella");
addKeyword(FrameBodyCOMM.class, "edit");
addKeyword(FrameBodyCOMM.class, "radio");
addKeyword(FrameBodyCOMM.class, "original");
addKeyword(FrameBodyCOMM.class, "album");
addKeyword(FrameBodyCOMM.class, "studio");
addKeyword(FrameBodyCOMM.class, "instrumental");
addKeyword(FrameBodyCOMM.class, "unedited");
addKeyword(FrameBodyCOMM.class, "karoke");
addKeyword(FrameBodyCOMM.class, "quality");
addKeyword(FrameBodyCOMM.class, "uncensored");
addKeyword(FrameBodyCOMM.class, "clean");
addKeyword(FrameBodyCOMM.class, "dirty");
addKeyword(FrameBodyTIPL.class, "f.");
addKeyword(FrameBodyTIPL.class, "feat");
addKeyword(FrameBodyTIPL.class, "feat.");
addKeyword(FrameBodyTIPL.class, "featuring");
addKeyword(FrameBodyTIPL.class, "ftng");
addKeyword(FrameBodyTIPL.class, "ftng.");
addKeyword(FrameBodyTIPL.class, "ft.");
addKeyword(FrameBodyTIPL.class, "ft");
iterator = GenreTypes.getInstanceOf().getValueToIdMap().keySet().iterator();
while (iterator.hasNext())
{
addKeyword(FrameBodyCOMM.class, (String) iterator.next());
}
}
catch (TagException ex)
{
// this shouldn't happen, indicates coding error
throw new RuntimeException(ex);
}
addUpperLowerCaseWord("a");
addUpperLowerCaseWord("in");
addUpperLowerCaseWord("of");
addUpperLowerCaseWord("the");
addUpperLowerCaseWord("on");
addUpperLowerCaseWord("is");
addUpperLowerCaseWord("it");
addUpperLowerCaseWord("to");
addUpperLowerCaseWord("at");
addUpperLowerCaseWord("an");
addUpperLowerCaseWord("and");
addUpperLowerCaseWord("but");
addUpperLowerCaseWord("or");
addUpperLowerCaseWord("for");
addUpperLowerCaseWord("nor");
addUpperLowerCaseWord("not");
addUpperLowerCaseWord("so");
addUpperLowerCaseWord("yet");
addUpperLowerCaseWord("with");
addUpperLowerCaseWord("into");
addUpperLowerCaseWord("by");
addUpperLowerCaseWord("up");
addUpperLowerCaseWord("as");
addUpperLowerCaseWord("if");
addUpperLowerCaseWord("feat.");
addUpperLowerCaseWord("vs.");
addUpperLowerCaseWord("I'm");
addUpperLowerCaseWord("I");
addUpperLowerCaseWord("I've");
addUpperLowerCaseWord("I'll");
addReplaceWord("v.", "vs.");
addReplaceWord("vs.", "vs.");
addReplaceWord("versus", "vs.");
addReplaceWord("f.", "feat.");
addReplaceWord("feat", "feat.");
addReplaceWord("featuring", "feat.");
addReplaceWord("ftng.", "feat.");
addReplaceWord("ftng", "feat.");
addReplaceWord("ft.", "feat.");
addReplaceWord("ft", "feat.");
addFilenameDelimiter("/");
addFilenameDelimiter("\\");
addFilenameDelimiter(" -");
addFilenameDelimiter(";");
addFilenameDelimiter("|");
addFilenameDelimiter(":");
iterator = this.getKeywordListIterator(FrameBodyTIPL.class);
while (iterator.hasNext())
{
addStartWordDelimiter((String) iterator.next());
}
addParenthesis("(", ")");
addParenthesis("[", "]");
addParenthesis("{", "}");
addParenthesis("<", ">");
}
/**
*
*
* @return
*/
public Iterator getUpperLowerCaseWordListIterator()
{
return upperLowerCaseWordList.iterator();
}
/**
*
*
* @param wordDelimiter
*/
public void addEndWordDelimiter(String wordDelimiter)
{
endWordDelimiterList.add(wordDelimiter);
}
/**
*
*
* @param delimiter
*/
public void addFilenameDelimiter(String delimiter)
{
filenameDelimiterList.add(delimiter);
}
/**
*
*
* @param id3v2FrameBodyClass
* @param keyword
* @throws TagException
*/
public void addKeyword(Class id3v2FrameBodyClass, String keyword)
throws TagException
{
if (AbstractID3v2FrameBody.class.isAssignableFrom(id3v2FrameBodyClass) == false)
{
throw new TagException("Invalid class type. Must be AbstractId3v2FrameBody " + id3v2FrameBodyClass);
}
if ((keyword != null) && (keyword.length() > 0))
{
LinkedList keywordList;
if (keywordMap.containsKey(id3v2FrameBodyClass) == false)
{
keywordList = new LinkedList();
keywordMap.put(id3v2FrameBodyClass, keywordList);
}
else
{
keywordList = (LinkedList) keywordMap.get(id3v2FrameBodyClass);
}
keywordList.add(keyword);
}
}
/**
*
*
* @param open
* @param close
*/
public void addParenthesis(String open, String close)
{
parenthesisMap.put(open, close);
}
/**
*
*
* @param oldWord
* @param newWord
*/
public void addReplaceWord(String oldWord, String newWord)
{
replaceWordMap.put(oldWord, newWord);
}
/**
*
*
* @param wordDelimiter
*/
public void addStartWordDelimiter(String wordDelimiter)
{
startWordDelimiterList.add(wordDelimiter);
}
/**
*
*
* @param word
*/
public void addUpperLowerCaseWord(String word)
{
upperLowerCaseWordList.add(word);
}
/**
*
* @return are tags unsynchronized when written if contain bit pattern that could be mistaken for audio marker
*/
public boolean isUnsyncTags()
{
return unsyncTags;
}
/**
* Unsync tag where neccessary, currently only applies to IDv23
*
* @param unsyncTags set whether tags are unsynchronized when written if contain bit pattern that could
* be mistaken for audio marker
*/
public void setUnsyncTags(boolean unsyncTags)
{
this.unsyncTags = unsyncTags;
}
}
| true | true | public void setToDefault()
{
keywordMap = new HashMap();
compositeMatchOverwrite = false;
endWordDelimiterList = new LinkedList();
filenameDelimiterList = new LinkedList();
filenameTagSave = false;
id3v1Save = true;
id3v1SaveAlbum = true;
id3v1SaveArtist = true;
id3v1SaveComment = true;
id3v1SaveGenre = true;
id3v1SaveTitle = true;
id3v1SaveTrack = true;
id3v1SaveYear = true;
id3v2KeepEmptyFrameIfRead = false;
id3v2PaddingCopyTag = true;
id3v2PaddingWillShorten = false;
id3v2Save = true;
id3v2SaveEmptyFrame = false;
id3v2SaveExtendedHeader = false;
id3v2PaddingMultiplier = 2;
id3v2PaddingSize = 2048;
language = "eng";
lyrics3KeepEmptyFieldIfRead = false;
lyrics3Save = true;
lyrics3SaveEmptyField = false;
lyrics3SaveFieldMap = new HashMap();
numberMP3SyncFrame = 3;
parenthesisMap = new HashMap();
playCounterSize = 4;
replaceWordMap = new HashMap();
startWordDelimiterList = new LinkedList();
textEncoding = 0;
timeStampFormat = 2;
upperLowerCaseWordList = new LinkedList();
/**
* default all lyrics3 fields to save. id3v1 fields are individual
* settings. id3v2 fields are always looked at to save.
*/
Iterator iterator = Lyrics3v2Fields.getInstanceOf().getIdToValueMap().keySet().iterator();
String fieldId;
while (iterator.hasNext())
{
fieldId = (String) iterator.next();
lyrics3SaveFieldMap.put(fieldId, new Boolean(true));
}
try
{
addKeyword(FrameBodyCOMM.class, "ultimix");
addKeyword(FrameBodyCOMM.class, "dance");
addKeyword(FrameBodyCOMM.class, "mix");
addKeyword(FrameBodyCOMM.class, "remix");
addKeyword(FrameBodyCOMM.class, "rmx");
addKeyword(FrameBodyCOMM.class, "live");
addKeyword(FrameBodyCOMM.class, "cover");
addKeyword(FrameBodyCOMM.class, "soundtrack");
addKeyword(FrameBodyCOMM.class, "version");
addKeyword(FrameBodyCOMM.class, "acoustic");
addKeyword(FrameBodyCOMM.class, "original");
addKeyword(FrameBodyCOMM.class, "cd");
addKeyword(FrameBodyCOMM.class, "extended");
addKeyword(FrameBodyCOMM.class, "vocal");
addKeyword(FrameBodyCOMM.class, "unplugged");
addKeyword(FrameBodyCOMM.class, "acapella");
addKeyword(FrameBodyCOMM.class, "edit");
addKeyword(FrameBodyCOMM.class, "radio");
addKeyword(FrameBodyCOMM.class, "original");
addKeyword(FrameBodyCOMM.class, "album");
addKeyword(FrameBodyCOMM.class, "studio");
addKeyword(FrameBodyCOMM.class, "instrumental");
addKeyword(FrameBodyCOMM.class, "unedited");
addKeyword(FrameBodyCOMM.class, "karoke");
addKeyword(FrameBodyCOMM.class, "quality");
addKeyword(FrameBodyCOMM.class, "uncensored");
addKeyword(FrameBodyCOMM.class, "clean");
addKeyword(FrameBodyCOMM.class, "dirty");
addKeyword(FrameBodyTIPL.class, "f.");
addKeyword(FrameBodyTIPL.class, "feat");
addKeyword(FrameBodyTIPL.class, "feat.");
addKeyword(FrameBodyTIPL.class, "featuring");
addKeyword(FrameBodyTIPL.class, "ftng");
addKeyword(FrameBodyTIPL.class, "ftng.");
addKeyword(FrameBodyTIPL.class, "ft.");
addKeyword(FrameBodyTIPL.class, "ft");
iterator = GenreTypes.getInstanceOf().getValueToIdMap().keySet().iterator();
while (iterator.hasNext())
{
addKeyword(FrameBodyCOMM.class, (String) iterator.next());
}
}
catch (TagException ex)
{
// this shouldn't happen, indicates coding error
throw new RuntimeException(ex);
}
addUpperLowerCaseWord("a");
addUpperLowerCaseWord("in");
addUpperLowerCaseWord("of");
addUpperLowerCaseWord("the");
addUpperLowerCaseWord("on");
addUpperLowerCaseWord("is");
addUpperLowerCaseWord("it");
addUpperLowerCaseWord("to");
addUpperLowerCaseWord("at");
addUpperLowerCaseWord("an");
addUpperLowerCaseWord("and");
addUpperLowerCaseWord("but");
addUpperLowerCaseWord("or");
addUpperLowerCaseWord("for");
addUpperLowerCaseWord("nor");
addUpperLowerCaseWord("not");
addUpperLowerCaseWord("so");
addUpperLowerCaseWord("yet");
addUpperLowerCaseWord("with");
addUpperLowerCaseWord("into");
addUpperLowerCaseWord("by");
addUpperLowerCaseWord("up");
addUpperLowerCaseWord("as");
addUpperLowerCaseWord("if");
addUpperLowerCaseWord("feat.");
addUpperLowerCaseWord("vs.");
addUpperLowerCaseWord("I'm");
addUpperLowerCaseWord("I");
addUpperLowerCaseWord("I've");
addUpperLowerCaseWord("I'll");
addReplaceWord("v.", "vs.");
addReplaceWord("vs.", "vs.");
addReplaceWord("versus", "vs.");
addReplaceWord("f.", "feat.");
addReplaceWord("feat", "feat.");
addReplaceWord("featuring", "feat.");
addReplaceWord("ftng.", "feat.");
addReplaceWord("ftng", "feat.");
addReplaceWord("ft.", "feat.");
addReplaceWord("ft", "feat.");
addFilenameDelimiter("/");
addFilenameDelimiter("\\");
addFilenameDelimiter(" -");
addFilenameDelimiter(";");
addFilenameDelimiter("|");
addFilenameDelimiter(":");
iterator = this.getKeywordListIterator(FrameBodyTIPL.class);
while (iterator.hasNext())
{
addStartWordDelimiter((String) iterator.next());
}
addParenthesis("(", ")");
addParenthesis("[", "]");
addParenthesis("{", "}");
addParenthesis("<", ">");
}
| public void setToDefault()
{
keywordMap = new HashMap();
compositeMatchOverwrite = false;
endWordDelimiterList = new LinkedList();
filenameDelimiterList = new LinkedList();
filenameTagSave = false;
id3v1Save = true;
id3v1SaveAlbum = true;
id3v1SaveArtist = true;
id3v1SaveComment = true;
id3v1SaveGenre = true;
id3v1SaveTitle = true;
id3v1SaveTrack = true;
id3v1SaveYear = true;
id3v2KeepEmptyFrameIfRead = false;
id3v2PaddingCopyTag = true;
id3v2PaddingWillShorten = false;
id3v2Save = true;
id3v2SaveEmptyFrame = false;
id3v2SaveExtendedHeader = false;
id3v2PaddingMultiplier = 2;
id3v2PaddingSize = 2048;
language = "eng";
lyrics3KeepEmptyFieldIfRead = false;
lyrics3Save = true;
lyrics3SaveEmptyField = false;
lyrics3SaveFieldMap = new HashMap();
numberMP3SyncFrame = 3;
parenthesisMap = new HashMap();
playCounterSize = 4;
replaceWordMap = new HashMap();
startWordDelimiterList = new LinkedList();
textEncoding = 0;
timeStampFormat = 2;
upperLowerCaseWordList = new LinkedList();
unsyncTags = false;
/**
* default all lyrics3 fields to save. id3v1 fields are individual
* settings. id3v2 fields are always looked at to save.
*/
Iterator iterator = Lyrics3v2Fields.getInstanceOf().getIdToValueMap().keySet().iterator();
String fieldId;
while (iterator.hasNext())
{
fieldId = (String) iterator.next();
lyrics3SaveFieldMap.put(fieldId, new Boolean(true));
}
try
{
addKeyword(FrameBodyCOMM.class, "ultimix");
addKeyword(FrameBodyCOMM.class, "dance");
addKeyword(FrameBodyCOMM.class, "mix");
addKeyword(FrameBodyCOMM.class, "remix");
addKeyword(FrameBodyCOMM.class, "rmx");
addKeyword(FrameBodyCOMM.class, "live");
addKeyword(FrameBodyCOMM.class, "cover");
addKeyword(FrameBodyCOMM.class, "soundtrack");
addKeyword(FrameBodyCOMM.class, "version");
addKeyword(FrameBodyCOMM.class, "acoustic");
addKeyword(FrameBodyCOMM.class, "original");
addKeyword(FrameBodyCOMM.class, "cd");
addKeyword(FrameBodyCOMM.class, "extended");
addKeyword(FrameBodyCOMM.class, "vocal");
addKeyword(FrameBodyCOMM.class, "unplugged");
addKeyword(FrameBodyCOMM.class, "acapella");
addKeyword(FrameBodyCOMM.class, "edit");
addKeyword(FrameBodyCOMM.class, "radio");
addKeyword(FrameBodyCOMM.class, "original");
addKeyword(FrameBodyCOMM.class, "album");
addKeyword(FrameBodyCOMM.class, "studio");
addKeyword(FrameBodyCOMM.class, "instrumental");
addKeyword(FrameBodyCOMM.class, "unedited");
addKeyword(FrameBodyCOMM.class, "karoke");
addKeyword(FrameBodyCOMM.class, "quality");
addKeyword(FrameBodyCOMM.class, "uncensored");
addKeyword(FrameBodyCOMM.class, "clean");
addKeyword(FrameBodyCOMM.class, "dirty");
addKeyword(FrameBodyTIPL.class, "f.");
addKeyword(FrameBodyTIPL.class, "feat");
addKeyword(FrameBodyTIPL.class, "feat.");
addKeyword(FrameBodyTIPL.class, "featuring");
addKeyword(FrameBodyTIPL.class, "ftng");
addKeyword(FrameBodyTIPL.class, "ftng.");
addKeyword(FrameBodyTIPL.class, "ft.");
addKeyword(FrameBodyTIPL.class, "ft");
iterator = GenreTypes.getInstanceOf().getValueToIdMap().keySet().iterator();
while (iterator.hasNext())
{
addKeyword(FrameBodyCOMM.class, (String) iterator.next());
}
}
catch (TagException ex)
{
// this shouldn't happen, indicates coding error
throw new RuntimeException(ex);
}
addUpperLowerCaseWord("a");
addUpperLowerCaseWord("in");
addUpperLowerCaseWord("of");
addUpperLowerCaseWord("the");
addUpperLowerCaseWord("on");
addUpperLowerCaseWord("is");
addUpperLowerCaseWord("it");
addUpperLowerCaseWord("to");
addUpperLowerCaseWord("at");
addUpperLowerCaseWord("an");
addUpperLowerCaseWord("and");
addUpperLowerCaseWord("but");
addUpperLowerCaseWord("or");
addUpperLowerCaseWord("for");
addUpperLowerCaseWord("nor");
addUpperLowerCaseWord("not");
addUpperLowerCaseWord("so");
addUpperLowerCaseWord("yet");
addUpperLowerCaseWord("with");
addUpperLowerCaseWord("into");
addUpperLowerCaseWord("by");
addUpperLowerCaseWord("up");
addUpperLowerCaseWord("as");
addUpperLowerCaseWord("if");
addUpperLowerCaseWord("feat.");
addUpperLowerCaseWord("vs.");
addUpperLowerCaseWord("I'm");
addUpperLowerCaseWord("I");
addUpperLowerCaseWord("I've");
addUpperLowerCaseWord("I'll");
addReplaceWord("v.", "vs.");
addReplaceWord("vs.", "vs.");
addReplaceWord("versus", "vs.");
addReplaceWord("f.", "feat.");
addReplaceWord("feat", "feat.");
addReplaceWord("featuring", "feat.");
addReplaceWord("ftng.", "feat.");
addReplaceWord("ftng", "feat.");
addReplaceWord("ft.", "feat.");
addReplaceWord("ft", "feat.");
addFilenameDelimiter("/");
addFilenameDelimiter("\\");
addFilenameDelimiter(" -");
addFilenameDelimiter(";");
addFilenameDelimiter("|");
addFilenameDelimiter(":");
iterator = this.getKeywordListIterator(FrameBodyTIPL.class);
while (iterator.hasNext())
{
addStartWordDelimiter((String) iterator.next());
}
addParenthesis("(", ")");
addParenthesis("[", "]");
addParenthesis("{", "}");
addParenthesis("<", ">");
}
|
diff --git a/src/main/java/com/ixonos/cimd/simulator/CIMDCodecFactory.java b/src/main/java/com/ixonos/cimd/simulator/CIMDCodecFactory.java
index 1125fe1..48ba37d 100644
--- a/src/main/java/com/ixonos/cimd/simulator/CIMDCodecFactory.java
+++ b/src/main/java/com/ixonos/cimd/simulator/CIMDCodecFactory.java
@@ -1,49 +1,49 @@
/*
* Copyright 2012 Ixonos Plc, Finland. All rights reserved.
*
* This file is part of Ixonos MISP CIMD Simulator.
*
* This file is licensed under GNU LGPL version 3.
* Please see the 'license.txt' file in the root directory of the package you received.
* If you did not receive a license, please contact the copyright holder
* ([email protected]).
*
*/
package com.ixonos.cimd.simulator;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolEncoder;
import com.googlecode.jcimd.PacketSequenceNumberGenerator;
import com.googlecode.jcimd.PacketSerializer;
import com.googlecode.jcimd.SmsCenterPacketSequenceNumberGenerator;
/**
* A ProtocolCodecFactory implementation that serializes and deserializes CIMD
* protocol packets.
*
* @author Ixonos / Marko Asplund
*/
public class CIMDCodecFactory implements ProtocolCodecFactory {
private CIMDPacketDecoder decoder;
private CIMDPacketEncoder encoder;
public CIMDCodecFactory() {
PacketSequenceNumberGenerator gen = new SmsCenterPacketSequenceNumberGenerator();
- PacketSerializer serializer = new PacketSerializer();
+ PacketSerializer serializer = new PacketSerializer("ser", false);
serializer.setSequenceNumberGenerator(gen);
decoder = new CIMDPacketDecoder(serializer);
encoder = new CIMDPacketEncoder(serializer);
}
public ProtocolDecoder getDecoder(IoSession session) throws Exception {
return decoder;
}
public ProtocolEncoder getEncoder(IoSession session) throws Exception {
return encoder;
}
}
| true | true | public CIMDCodecFactory() {
PacketSequenceNumberGenerator gen = new SmsCenterPacketSequenceNumberGenerator();
PacketSerializer serializer = new PacketSerializer();
serializer.setSequenceNumberGenerator(gen);
decoder = new CIMDPacketDecoder(serializer);
encoder = new CIMDPacketEncoder(serializer);
}
| public CIMDCodecFactory() {
PacketSequenceNumberGenerator gen = new SmsCenterPacketSequenceNumberGenerator();
PacketSerializer serializer = new PacketSerializer("ser", false);
serializer.setSequenceNumberGenerator(gen);
decoder = new CIMDPacketDecoder(serializer);
encoder = new CIMDPacketEncoder(serializer);
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java b/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java
index c8bbaf24d..10110f186 100644
--- a/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java
+++ b/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java
@@ -1,518 +1,518 @@
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(Player 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 String getName() {
return player_name;
}
public dLocation getLocation() {
if (isOnline()) return new dLocation(getPlayerEntity().getLocation());
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";
if (attribute.startsWith("entity"))
return new dEntity(getPlayerEntity())
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("has_played_before"))
return new Element(String.valueOf(getOfflinePlayer().hasPlayedBefore()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_op"))
return new Element(String.valueOf(getOfflinePlayer().isOp()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("first_played"))
return new Element(String.valueOf(getOfflinePlayer().getFirstPlayed()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("last_played"))
return new Element(String.valueOf(getOfflinePlayer().getLastPlayed()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_banned"))
return new Element(String.valueOf(getOfflinePlayer().isBanned()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_whitelisted"))
return new Element(String.valueOf(getOfflinePlayer().isWhitelisted()))
.getAttribute(attribute.fulfill(1));
// This can be parsed later with more detail if the player is online, so only check for offline.
if (attribute.startsWith("name") && !isOnline())
return new Element(player_name).getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_online"))
return new Element(String.valueOf(isOnline())).getAttribute(attribute.fulfill(1));
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));
}
}
if (attribute.startsWith("chat_history_list"))
return new dList(PlayerTags.playerChatHistory.get(player_name))
.getAttribute(attribute.fulfill(1));
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));
}
if (attribute.startsWith("location.bed_spawn"))
return new dLocation(getOfflinePlayer().getBedSpawnLocation())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("money")) {
if(Depends.economy != null) {
if (attribute.startsWith("money.currency_singular"))
return new Element(Depends.economy.currencyNameSingular())
.getAttribute(attribute.fulfill(2));
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...
if (attribute.startsWith("xp.to_next_level"))
return new Element(String.valueOf(getPlayerEntity().getExpToLevel()))
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("xp.total"))
return new Element(String.valueOf(getPlayerEntity().getTotalExperience()))
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("xp.level"))
return new Element(getPlayerEntity().getLevel())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("xp"))
return new Element(String.valueOf(getPlayerEntity().getExp() * 100))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("equipment.boots"))
return new dItem(getPlayerEntity().getInventory().getBoots())
- .getAttribute(attribute.fulfill(1));
+ .getAttribute(attribute.fulfill(2));
if (attribute.startsWith("equipment.chestplate"))
return new dItem(getPlayerEntity().getInventory().getChestplate())
- .getAttribute(attribute.fulfill(1));
+ .getAttribute(attribute.fulfill(2));
if (attribute.startsWith("equipment.helmet"))
return new dItem(getPlayerEntity().getInventory().getHelmet())
- .getAttribute(attribute.fulfill(1));
+ .getAttribute(attribute.fulfill(2));
if (attribute.startsWith("equipment.leggings"))
return new dItem(getPlayerEntity().getInventory().getLeggings())
- .getAttribute(attribute.fulfill(1));
+ .getAttribute(attribute.fulfill(2));
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));
if (attribute.startsWith("inventory"))
return new dInventory(getPlayerEntity().getInventory())
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("item_in_hand"))
return new dItem(getPlayerEntity().getItemInHand())
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("name.display"))
return new Element(getPlayerEntity().getDisplayName())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("name.list"))
return new Element(getPlayerEntity().getPlayerListName())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("name"))
return new Element(player_name).getAttribute(attribute.fulfill(1));
if (attribute.startsWith("location.compass_target"))
return new dLocation(getPlayerEntity().getCompassTarget())
.getAttribute(attribute.fulfill(2));
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));
}
if (attribute.startsWith("food_level"))
return new Element(String.valueOf(getPlayerEntity().getFoodLevel()))
.getAttribute(attribute.fulfill(1));
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);
// 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));
// Permission in current world
return new Element(String.valueOf(Depends.permissions.has(getPlayerEntity(), permission)))
.getAttribute(attribute.fulfill(1));
}
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";
}
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);
// 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));
// Permission in current world
return new Element(String.valueOf(Depends.permissions.playerInGroup(getPlayerEntity(), group)))
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("is_flying"))
return new Element(String.valueOf(getPlayerEntity().isFlying()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_sneaking"))
return new Element(String.valueOf(getPlayerEntity().isSneaking()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_blocking"))
return new Element(String.valueOf(getPlayerEntity().isBlocking()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_sleeping"))
return new Element(String.valueOf(getPlayerEntity().isSleeping()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_sprinting"))
return new Element(String.valueOf(getPlayerEntity().isSprinting()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("gamemode.id"))
return new Element(String.valueOf(getPlayerEntity().getGameMode().getValue()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("gamemode"))
return new Element(String.valueOf(getPlayerEntity().getGameMode().toString()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("item_on_cursor"))
return new dItem(getPlayerEntity().getItemOnCursor())
.getAttribute(attribute.fulfill(1));
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";
}
if (attribute.startsWith("allowed_flight"))
return new Element(String.valueOf(getPlayerEntity().getAllowFlight()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("host_name"))
return new Element(String.valueOf(getPlayerEntity().getAddress().getHostName()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("time_asleep"))
return new Duration(getPlayerEntity().getSleepTicks() / 20)
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("player_time"))
return new Element(String.valueOf(getPlayerEntity().getPlayerTime()))
.getAttribute(attribute.fulfill(1));
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));
}
}
| false | true | public String getAttribute(Attribute attribute) {
if (attribute == null) return "null";
if (player_name == null) return "null";
if (attribute.startsWith("entity"))
return new dEntity(getPlayerEntity())
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("has_played_before"))
return new Element(String.valueOf(getOfflinePlayer().hasPlayedBefore()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_op"))
return new Element(String.valueOf(getOfflinePlayer().isOp()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("first_played"))
return new Element(String.valueOf(getOfflinePlayer().getFirstPlayed()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("last_played"))
return new Element(String.valueOf(getOfflinePlayer().getLastPlayed()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_banned"))
return new Element(String.valueOf(getOfflinePlayer().isBanned()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_whitelisted"))
return new Element(String.valueOf(getOfflinePlayer().isWhitelisted()))
.getAttribute(attribute.fulfill(1));
// This can be parsed later with more detail if the player is online, so only check for offline.
if (attribute.startsWith("name") && !isOnline())
return new Element(player_name).getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_online"))
return new Element(String.valueOf(isOnline())).getAttribute(attribute.fulfill(1));
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));
}
}
if (attribute.startsWith("chat_history_list"))
return new dList(PlayerTags.playerChatHistory.get(player_name))
.getAttribute(attribute.fulfill(1));
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));
}
if (attribute.startsWith("location.bed_spawn"))
return new dLocation(getOfflinePlayer().getBedSpawnLocation())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("money")) {
if(Depends.economy != null) {
if (attribute.startsWith("money.currency_singular"))
return new Element(Depends.economy.currencyNameSingular())
.getAttribute(attribute.fulfill(2));
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...
if (attribute.startsWith("xp.to_next_level"))
return new Element(String.valueOf(getPlayerEntity().getExpToLevel()))
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("xp.total"))
return new Element(String.valueOf(getPlayerEntity().getTotalExperience()))
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("xp.level"))
return new Element(getPlayerEntity().getLevel())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("xp"))
return new Element(String.valueOf(getPlayerEntity().getExp() * 100))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("equipment.boots"))
return new dItem(getPlayerEntity().getInventory().getBoots())
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("equipment.chestplate"))
return new dItem(getPlayerEntity().getInventory().getChestplate())
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("equipment.helmet"))
return new dItem(getPlayerEntity().getInventory().getHelmet())
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("equipment.leggings"))
return new dItem(getPlayerEntity().getInventory().getLeggings())
.getAttribute(attribute.fulfill(1));
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));
if (attribute.startsWith("inventory"))
return new dInventory(getPlayerEntity().getInventory())
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("item_in_hand"))
return new dItem(getPlayerEntity().getItemInHand())
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("name.display"))
return new Element(getPlayerEntity().getDisplayName())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("name.list"))
return new Element(getPlayerEntity().getPlayerListName())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("name"))
return new Element(player_name).getAttribute(attribute.fulfill(1));
if (attribute.startsWith("location.compass_target"))
return new dLocation(getPlayerEntity().getCompassTarget())
.getAttribute(attribute.fulfill(2));
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));
}
if (attribute.startsWith("food_level"))
return new Element(String.valueOf(getPlayerEntity().getFoodLevel()))
.getAttribute(attribute.fulfill(1));
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);
// 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));
// Permission in current world
return new Element(String.valueOf(Depends.permissions.has(getPlayerEntity(), permission)))
.getAttribute(attribute.fulfill(1));
}
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";
}
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);
// 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));
// Permission in current world
return new Element(String.valueOf(Depends.permissions.playerInGroup(getPlayerEntity(), group)))
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("is_flying"))
return new Element(String.valueOf(getPlayerEntity().isFlying()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_sneaking"))
return new Element(String.valueOf(getPlayerEntity().isSneaking()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_blocking"))
return new Element(String.valueOf(getPlayerEntity().isBlocking()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_sleeping"))
return new Element(String.valueOf(getPlayerEntity().isSleeping()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_sprinting"))
return new Element(String.valueOf(getPlayerEntity().isSprinting()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("gamemode.id"))
return new Element(String.valueOf(getPlayerEntity().getGameMode().getValue()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("gamemode"))
return new Element(String.valueOf(getPlayerEntity().getGameMode().toString()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("item_on_cursor"))
return new dItem(getPlayerEntity().getItemOnCursor())
.getAttribute(attribute.fulfill(1));
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";
}
if (attribute.startsWith("allowed_flight"))
return new Element(String.valueOf(getPlayerEntity().getAllowFlight()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("host_name"))
return new Element(String.valueOf(getPlayerEntity().getAddress().getHostName()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("time_asleep"))
return new Duration(getPlayerEntity().getSleepTicks() / 20)
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("player_time"))
return new Element(String.valueOf(getPlayerEntity().getPlayerTime()))
.getAttribute(attribute.fulfill(1));
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));
}
| public String getAttribute(Attribute attribute) {
if (attribute == null) return "null";
if (player_name == null) return "null";
if (attribute.startsWith("entity"))
return new dEntity(getPlayerEntity())
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("has_played_before"))
return new Element(String.valueOf(getOfflinePlayer().hasPlayedBefore()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_op"))
return new Element(String.valueOf(getOfflinePlayer().isOp()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("first_played"))
return new Element(String.valueOf(getOfflinePlayer().getFirstPlayed()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("last_played"))
return new Element(String.valueOf(getOfflinePlayer().getLastPlayed()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_banned"))
return new Element(String.valueOf(getOfflinePlayer().isBanned()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_whitelisted"))
return new Element(String.valueOf(getOfflinePlayer().isWhitelisted()))
.getAttribute(attribute.fulfill(1));
// This can be parsed later with more detail if the player is online, so only check for offline.
if (attribute.startsWith("name") && !isOnline())
return new Element(player_name).getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_online"))
return new Element(String.valueOf(isOnline())).getAttribute(attribute.fulfill(1));
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));
}
}
if (attribute.startsWith("chat_history_list"))
return new dList(PlayerTags.playerChatHistory.get(player_name))
.getAttribute(attribute.fulfill(1));
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));
}
if (attribute.startsWith("location.bed_spawn"))
return new dLocation(getOfflinePlayer().getBedSpawnLocation())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("money")) {
if(Depends.economy != null) {
if (attribute.startsWith("money.currency_singular"))
return new Element(Depends.economy.currencyNameSingular())
.getAttribute(attribute.fulfill(2));
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...
if (attribute.startsWith("xp.to_next_level"))
return new Element(String.valueOf(getPlayerEntity().getExpToLevel()))
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("xp.total"))
return new Element(String.valueOf(getPlayerEntity().getTotalExperience()))
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("xp.level"))
return new Element(getPlayerEntity().getLevel())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("xp"))
return new Element(String.valueOf(getPlayerEntity().getExp() * 100))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("equipment.boots"))
return new dItem(getPlayerEntity().getInventory().getBoots())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("equipment.chestplate"))
return new dItem(getPlayerEntity().getInventory().getChestplate())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("equipment.helmet"))
return new dItem(getPlayerEntity().getInventory().getHelmet())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("equipment.leggings"))
return new dItem(getPlayerEntity().getInventory().getLeggings())
.getAttribute(attribute.fulfill(2));
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));
if (attribute.startsWith("inventory"))
return new dInventory(getPlayerEntity().getInventory())
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("item_in_hand"))
return new dItem(getPlayerEntity().getItemInHand())
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("name.display"))
return new Element(getPlayerEntity().getDisplayName())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("name.list"))
return new Element(getPlayerEntity().getPlayerListName())
.getAttribute(attribute.fulfill(2));
if (attribute.startsWith("name"))
return new Element(player_name).getAttribute(attribute.fulfill(1));
if (attribute.startsWith("location.compass_target"))
return new dLocation(getPlayerEntity().getCompassTarget())
.getAttribute(attribute.fulfill(2));
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));
}
if (attribute.startsWith("food_level"))
return new Element(String.valueOf(getPlayerEntity().getFoodLevel()))
.getAttribute(attribute.fulfill(1));
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);
// 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));
// Permission in current world
return new Element(String.valueOf(Depends.permissions.has(getPlayerEntity(), permission)))
.getAttribute(attribute.fulfill(1));
}
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";
}
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);
// 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));
// Permission in current world
return new Element(String.valueOf(Depends.permissions.playerInGroup(getPlayerEntity(), group)))
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("is_flying"))
return new Element(String.valueOf(getPlayerEntity().isFlying()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_sneaking"))
return new Element(String.valueOf(getPlayerEntity().isSneaking()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_blocking"))
return new Element(String.valueOf(getPlayerEntity().isBlocking()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_sleeping"))
return new Element(String.valueOf(getPlayerEntity().isSleeping()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("is_sprinting"))
return new Element(String.valueOf(getPlayerEntity().isSprinting()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("gamemode.id"))
return new Element(String.valueOf(getPlayerEntity().getGameMode().getValue()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("gamemode"))
return new Element(String.valueOf(getPlayerEntity().getGameMode().toString()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("item_on_cursor"))
return new dItem(getPlayerEntity().getItemOnCursor())
.getAttribute(attribute.fulfill(1));
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";
}
if (attribute.startsWith("allowed_flight"))
return new Element(String.valueOf(getPlayerEntity().getAllowFlight()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("host_name"))
return new Element(String.valueOf(getPlayerEntity().getAddress().getHostName()))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("time_asleep"))
return new Duration(getPlayerEntity().getSleepTicks() / 20)
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("player_time"))
return new Element(String.valueOf(getPlayerEntity().getPlayerTime()))
.getAttribute(attribute.fulfill(1));
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));
}
|
diff --git a/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentWebService.java b/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentWebService.java
index 8c257797..8b5abe80 100644
--- a/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentWebService.java
+++ b/axis2/src/main/java/org/apache/ode/axis2/service/DeploymentWebService.java
@@ -1,292 +1,292 @@
/*
* 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.ode.axis2.service;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMText;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFactory;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.engine.AxisEngine;
import org.apache.axis2.receivers.AbstractMessageReceiver;
import org.apache.axis2.util.Utils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.axis2.OdeFault;
import org.apache.ode.axis2.deploy.DeploymentPoller;
import org.apache.ode.axis2.hooks.ODEAxisService;
import org.apache.ode.axis2.util.OMUtils;
import org.apache.ode.bpel.iapi.BpelServer;
import org.apache.ode.bpel.iapi.ProcessConf;
import org.apache.ode.bpel.iapi.ProcessStore;
import org.apache.ode.utils.fs.FileUtils;
import javax.activation.DataHandler;
import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.namespace.QName;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Axis wrapper for process deployment.
*/
public class DeploymentWebService {
private static final Log __log = LogFactory.getLog(DeploymentWebService.class);
private final OMNamespace _pmapi;
private File _deployPath;
private DeploymentPoller _poller;
private ProcessStore _store;
public DeploymentWebService() {
_pmapi = OMAbstractFactory.getOMFactory().createOMNamespace("http://www.apache.org/ode/pmapi","pmapi");
}
public void enableService(AxisConfiguration axisConfig, BpelServer server, ProcessStore store,
DeploymentPoller poller, String rootpath, String workPath) {
_deployPath = new File(workPath, "processes");
_store = store;
Definition def;
try {
WSDLReader wsdlReader = WSDLFactory.newInstance().newWSDLReader();
wsdlReader.setFeature("javax.wsdl.verbose", false);
File wsdlFile = new File(rootpath + "/deploy.wsdl");
def = wsdlReader.readWSDL(wsdlFile.toURI().getPath());
AxisService deployService = ODEAxisService.createService(
axisConfig, new QName("http://www.apache.org/ode/deployapi", "DeploymentService"),
"DeploymentPort", "DeploymentService", def, new DeploymentMessageReceiver());
axisConfig.addService(deployService);
_poller = poller;
} catch (WSDLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
class DeploymentMessageReceiver extends AbstractMessageReceiver {
public void invokeBusinessLogic(MessageContext messageContext) throws AxisFault {
String operation = messageContext.getAxisOperation().getName().getLocalPart();
SOAPFactory factory = getSOAPFactory(messageContext);
boolean unknown = false;
try {
if (operation.equals("deploy")) {
OMElement namePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
OMElement zipPart = (OMElement) namePart.getNextOMSibling();
- OMElement zip = zipPart.getFirstElement();
- if (!zipPart.getQName().getLocalPart().equals("package") ||
- !zip.getQName().getLocalPart().equals("zip"))
- throw new OdeFault("Your message should contain a part named 'package' with a zip element");
+ OMElement zip = (zipPart == null) ? null : zipPart.getFirstElement();
+ if (zip == null || !zipPart.getQName().getLocalPart().equals("package")
+ || !zip.getQName().getLocalPart().equals("zip"))
+ throw new OdeFault("Your message should contain an element named 'package' with a 'zip' element");
OMText binaryNode = (OMText) zip.getFirstOMChild();
if (binaryNode == null) {
throw new OdeFault("Empty binary node under <zip> element");
}
binaryNode.setOptimize(true);
try {
// We're going to create a directory under the deployment root and put
// files in there. The poller shouldn't pick them up so we're asking
// it to hold on for a while.
_poller.hold();
File dest = new File(_deployPath, namePart.getText() + "-" + _store.getCurrentVersion());
dest.mkdir();
unzip(dest, (DataHandler) binaryNode.getDataHandler());
// Check that we have a deploy.xml
File deployXml = new File(dest, "deploy.xml");
if (!deployXml.exists())
throw new OdeFault("The deployment doesn't appear to contain a deployment " +
"descriptor in its root directory named deploy.xml, aborting.");
Collection<QName> deployed = _store.deploy(dest);
File deployedMarker = new File(_deployPath, dest.getName() + ".deployed");
deployedMarker.createNewFile();
// Telling the poller what we deployed so that it doesn't try to deploy it again
_poller.markAsDeployed(dest);
__log.info("Deployment of artifact " + dest.getName() + " successful.");
OMElement response = factory.createOMElement("response", null);
if (__log.isDebugEnabled()) __log.debug("Deployed package: "+dest.getName());
OMElement d = factory.createOMElement("name", null);
d.setText(dest.getName());
response.addChild(d);
for (QName pid : deployed) {
if (__log.isDebugEnabled()) __log.debug("Deployed PID: "+pid);
d = factory.createOMElement("id", null);
d.setText(pid);
response.addChild(d);
}
sendResponse(factory, messageContext, "deployResponse", response);
} finally {
_poller.release();
}
} else if (operation.equals("undeploy")) {
OMElement part = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
String pkg = part.getText();
File deploymentDir = new File(_deployPath, pkg);
if (!deploymentDir.exists())
throw new OdeFault("Couldn't find deployment package " + pkg + " in directory " + _deployPath);
try {
// We're going to create a directory under the deployment root and put
// files in there. The poller shouldn't pick them up so we're asking
// it to hold on for a while.
_poller.hold();
Collection<QName> undeployed = _store.undeploy(deploymentDir);
File deployedMarker = new File(_deployPath, pkg + ".deployed");
deployedMarker.delete();
FileUtils.deepDelete(new File(_deployPath, pkg));
OMElement response = factory.createOMElement("response", null);
response.setText("" + (undeployed.size() > 0));
sendResponse(factory, messageContext, "undeployResponse", response);
_poller.markAsUndeployed(deploymentDir);
} finally {
_poller.release();
}
} else if (operation.equals("listDeployedPackages")) {
Collection<String> packageNames = _store.getPackages();
OMElement response = factory.createOMElement("deployedPackages", null);
for (String name : packageNames) {
OMElement nameElmt = factory.createOMElement("name", null);
nameElmt.setText(name);
response.addChild(nameElmt);
}
sendResponse(factory, messageContext, "listDeployedPackagesResponse", response);
} else if (operation.equals("listProcesses")) {
OMElement namePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
List<QName> processIds = _store.listProcesses(namePart.getText());
OMElement response = factory.createOMElement("processIds", null);
for (QName qname : processIds) {
OMElement nameElmt = factory.createOMElement("id", null);
nameElmt.setText(qname);
response.addChild(nameElmt);
}
sendResponse(factory, messageContext, "listProcessResponse", response);
} else if (operation.equals("getProcessPackage")) {
OMElement qnamePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
ProcessConf process = _store.getProcessConfiguration(OMUtils.getTextAsQName(qnamePart));
if (process == null) {
throw new OdeFault("Could not find process: " + qnamePart.getTextAsQName());
}
String packageName = _store.getProcessConfiguration(OMUtils.getTextAsQName(qnamePart)).getPackage();
OMElement response = factory.createOMElement("packageName", null);
response.setText(packageName);
sendResponse(factory, messageContext, "getProcessPackageResponse", response);
} else unknown = true;
} catch (Throwable t) {
// Trying to extract a meaningful message
Throwable source = t;
while (source.getCause() != null && source.getCause() != source) source = source.getCause();
__log.warn("Invocation of operation " + operation + " failed", t);
throw new OdeFault("Invocation of operation " + operation + " failed: " + source.toString(), t);
}
if (unknown) throw new OdeFault("Unknown operation: '"
+ messageContext.getAxisOperation().getName() + "'");
}
private File buildUnusedDir(File deployPath, String dirName) {
int v = 1;
while (new File(deployPath, dirName + "-" + v).exists()) v++;
return new File(deployPath, dirName + "-" + v);
}
private void unzip(File dest, DataHandler dataHandler) throws AxisFault {
try {
ZipInputStream zis = new ZipInputStream(dataHandler.getDataSource().getInputStream());
ZipEntry entry;
// Processing the package
while((entry = zis.getNextEntry()) != null) {
if(entry.isDirectory()) {
__log.debug("Extracting directory: " + entry.getName());
new File(dest, entry.getName()).mkdir();
continue;
}
__log.debug("Extracting file: " + entry.getName());
File destFile = new File(dest, entry.getName());
if (!destFile.getParentFile().exists()) destFile.getParentFile().mkdirs();
copyInputStream(zis, new BufferedOutputStream(
new FileOutputStream(destFile)));
}
zis.close();
} catch (IOException e) {
throw new OdeFault("An error occured on deployment.", e);
}
}
private void sendResponse(SOAPFactory factory, MessageContext messageContext, String op,
OMElement response) throws AxisFault {
MessageContext outMsgContext = Utils.createOutMessageContext(messageContext);
outMsgContext.getOperationContext().addMessageContext(outMsgContext);
SOAPEnvelope envelope = factory.getDefaultEnvelope();
outMsgContext.setEnvelope(envelope);
OMElement responseOp = factory.createOMElement(op, _pmapi);
responseOp.addChild(response);
envelope.getBody().addChild(response);
AxisEngine engine = new AxisEngine(
messageContext.getOperationContext().getServiceContext().getConfigurationContext());
engine.send(outMsgContext);
}
}
private static void copyInputStream(InputStream in, OutputStream out)
throws IOException {
byte[] buffer = new byte[1024];
int len;
while((len = in.read(buffer)) >= 0)
out.write(buffer, 0, len);
out.close();
}
}
| true | true | public void invokeBusinessLogic(MessageContext messageContext) throws AxisFault {
String operation = messageContext.getAxisOperation().getName().getLocalPart();
SOAPFactory factory = getSOAPFactory(messageContext);
boolean unknown = false;
try {
if (operation.equals("deploy")) {
OMElement namePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
OMElement zipPart = (OMElement) namePart.getNextOMSibling();
OMElement zip = zipPart.getFirstElement();
if (!zipPart.getQName().getLocalPart().equals("package") ||
!zip.getQName().getLocalPart().equals("zip"))
throw new OdeFault("Your message should contain a part named 'package' with a zip element");
OMText binaryNode = (OMText) zip.getFirstOMChild();
if (binaryNode == null) {
throw new OdeFault("Empty binary node under <zip> element");
}
binaryNode.setOptimize(true);
try {
// We're going to create a directory under the deployment root and put
// files in there. The poller shouldn't pick them up so we're asking
// it to hold on for a while.
_poller.hold();
File dest = new File(_deployPath, namePart.getText() + "-" + _store.getCurrentVersion());
dest.mkdir();
unzip(dest, (DataHandler) binaryNode.getDataHandler());
// Check that we have a deploy.xml
File deployXml = new File(dest, "deploy.xml");
if (!deployXml.exists())
throw new OdeFault("The deployment doesn't appear to contain a deployment " +
"descriptor in its root directory named deploy.xml, aborting.");
Collection<QName> deployed = _store.deploy(dest);
File deployedMarker = new File(_deployPath, dest.getName() + ".deployed");
deployedMarker.createNewFile();
// Telling the poller what we deployed so that it doesn't try to deploy it again
_poller.markAsDeployed(dest);
__log.info("Deployment of artifact " + dest.getName() + " successful.");
OMElement response = factory.createOMElement("response", null);
if (__log.isDebugEnabled()) __log.debug("Deployed package: "+dest.getName());
OMElement d = factory.createOMElement("name", null);
d.setText(dest.getName());
response.addChild(d);
for (QName pid : deployed) {
if (__log.isDebugEnabled()) __log.debug("Deployed PID: "+pid);
d = factory.createOMElement("id", null);
d.setText(pid);
response.addChild(d);
}
sendResponse(factory, messageContext, "deployResponse", response);
} finally {
_poller.release();
}
} else if (operation.equals("undeploy")) {
OMElement part = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
String pkg = part.getText();
File deploymentDir = new File(_deployPath, pkg);
if (!deploymentDir.exists())
throw new OdeFault("Couldn't find deployment package " + pkg + " in directory " + _deployPath);
try {
// We're going to create a directory under the deployment root and put
// files in there. The poller shouldn't pick them up so we're asking
// it to hold on for a while.
_poller.hold();
Collection<QName> undeployed = _store.undeploy(deploymentDir);
File deployedMarker = new File(_deployPath, pkg + ".deployed");
deployedMarker.delete();
FileUtils.deepDelete(new File(_deployPath, pkg));
OMElement response = factory.createOMElement("response", null);
response.setText("" + (undeployed.size() > 0));
sendResponse(factory, messageContext, "undeployResponse", response);
_poller.markAsUndeployed(deploymentDir);
} finally {
_poller.release();
}
} else if (operation.equals("listDeployedPackages")) {
Collection<String> packageNames = _store.getPackages();
OMElement response = factory.createOMElement("deployedPackages", null);
for (String name : packageNames) {
OMElement nameElmt = factory.createOMElement("name", null);
nameElmt.setText(name);
response.addChild(nameElmt);
}
sendResponse(factory, messageContext, "listDeployedPackagesResponse", response);
} else if (operation.equals("listProcesses")) {
OMElement namePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
List<QName> processIds = _store.listProcesses(namePart.getText());
OMElement response = factory.createOMElement("processIds", null);
for (QName qname : processIds) {
OMElement nameElmt = factory.createOMElement("id", null);
nameElmt.setText(qname);
response.addChild(nameElmt);
}
sendResponse(factory, messageContext, "listProcessResponse", response);
} else if (operation.equals("getProcessPackage")) {
OMElement qnamePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
ProcessConf process = _store.getProcessConfiguration(OMUtils.getTextAsQName(qnamePart));
if (process == null) {
throw new OdeFault("Could not find process: " + qnamePart.getTextAsQName());
}
String packageName = _store.getProcessConfiguration(OMUtils.getTextAsQName(qnamePart)).getPackage();
OMElement response = factory.createOMElement("packageName", null);
response.setText(packageName);
sendResponse(factory, messageContext, "getProcessPackageResponse", response);
} else unknown = true;
} catch (Throwable t) {
// Trying to extract a meaningful message
Throwable source = t;
while (source.getCause() != null && source.getCause() != source) source = source.getCause();
__log.warn("Invocation of operation " + operation + " failed", t);
throw new OdeFault("Invocation of operation " + operation + " failed: " + source.toString(), t);
}
if (unknown) throw new OdeFault("Unknown operation: '"
+ messageContext.getAxisOperation().getName() + "'");
}
| public void invokeBusinessLogic(MessageContext messageContext) throws AxisFault {
String operation = messageContext.getAxisOperation().getName().getLocalPart();
SOAPFactory factory = getSOAPFactory(messageContext);
boolean unknown = false;
try {
if (operation.equals("deploy")) {
OMElement namePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
OMElement zipPart = (OMElement) namePart.getNextOMSibling();
OMElement zip = (zipPart == null) ? null : zipPart.getFirstElement();
if (zip == null || !zipPart.getQName().getLocalPart().equals("package")
|| !zip.getQName().getLocalPart().equals("zip"))
throw new OdeFault("Your message should contain an element named 'package' with a 'zip' element");
OMText binaryNode = (OMText) zip.getFirstOMChild();
if (binaryNode == null) {
throw new OdeFault("Empty binary node under <zip> element");
}
binaryNode.setOptimize(true);
try {
// We're going to create a directory under the deployment root and put
// files in there. The poller shouldn't pick them up so we're asking
// it to hold on for a while.
_poller.hold();
File dest = new File(_deployPath, namePart.getText() + "-" + _store.getCurrentVersion());
dest.mkdir();
unzip(dest, (DataHandler) binaryNode.getDataHandler());
// Check that we have a deploy.xml
File deployXml = new File(dest, "deploy.xml");
if (!deployXml.exists())
throw new OdeFault("The deployment doesn't appear to contain a deployment " +
"descriptor in its root directory named deploy.xml, aborting.");
Collection<QName> deployed = _store.deploy(dest);
File deployedMarker = new File(_deployPath, dest.getName() + ".deployed");
deployedMarker.createNewFile();
// Telling the poller what we deployed so that it doesn't try to deploy it again
_poller.markAsDeployed(dest);
__log.info("Deployment of artifact " + dest.getName() + " successful.");
OMElement response = factory.createOMElement("response", null);
if (__log.isDebugEnabled()) __log.debug("Deployed package: "+dest.getName());
OMElement d = factory.createOMElement("name", null);
d.setText(dest.getName());
response.addChild(d);
for (QName pid : deployed) {
if (__log.isDebugEnabled()) __log.debug("Deployed PID: "+pid);
d = factory.createOMElement("id", null);
d.setText(pid);
response.addChild(d);
}
sendResponse(factory, messageContext, "deployResponse", response);
} finally {
_poller.release();
}
} else if (operation.equals("undeploy")) {
OMElement part = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
String pkg = part.getText();
File deploymentDir = new File(_deployPath, pkg);
if (!deploymentDir.exists())
throw new OdeFault("Couldn't find deployment package " + pkg + " in directory " + _deployPath);
try {
// We're going to create a directory under the deployment root and put
// files in there. The poller shouldn't pick them up so we're asking
// it to hold on for a while.
_poller.hold();
Collection<QName> undeployed = _store.undeploy(deploymentDir);
File deployedMarker = new File(_deployPath, pkg + ".deployed");
deployedMarker.delete();
FileUtils.deepDelete(new File(_deployPath, pkg));
OMElement response = factory.createOMElement("response", null);
response.setText("" + (undeployed.size() > 0));
sendResponse(factory, messageContext, "undeployResponse", response);
_poller.markAsUndeployed(deploymentDir);
} finally {
_poller.release();
}
} else if (operation.equals("listDeployedPackages")) {
Collection<String> packageNames = _store.getPackages();
OMElement response = factory.createOMElement("deployedPackages", null);
for (String name : packageNames) {
OMElement nameElmt = factory.createOMElement("name", null);
nameElmt.setText(name);
response.addChild(nameElmt);
}
sendResponse(factory, messageContext, "listDeployedPackagesResponse", response);
} else if (operation.equals("listProcesses")) {
OMElement namePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
List<QName> processIds = _store.listProcesses(namePart.getText());
OMElement response = factory.createOMElement("processIds", null);
for (QName qname : processIds) {
OMElement nameElmt = factory.createOMElement("id", null);
nameElmt.setText(qname);
response.addChild(nameElmt);
}
sendResponse(factory, messageContext, "listProcessResponse", response);
} else if (operation.equals("getProcessPackage")) {
OMElement qnamePart = messageContext.getEnvelope().getBody().getFirstElement().getFirstElement();
ProcessConf process = _store.getProcessConfiguration(OMUtils.getTextAsQName(qnamePart));
if (process == null) {
throw new OdeFault("Could not find process: " + qnamePart.getTextAsQName());
}
String packageName = _store.getProcessConfiguration(OMUtils.getTextAsQName(qnamePart)).getPackage();
OMElement response = factory.createOMElement("packageName", null);
response.setText(packageName);
sendResponse(factory, messageContext, "getProcessPackageResponse", response);
} else unknown = true;
} catch (Throwable t) {
// Trying to extract a meaningful message
Throwable source = t;
while (source.getCause() != null && source.getCause() != source) source = source.getCause();
__log.warn("Invocation of operation " + operation + " failed", t);
throw new OdeFault("Invocation of operation " + operation + " failed: " + source.toString(), t);
}
if (unknown) throw new OdeFault("Unknown operation: '"
+ messageContext.getAxisOperation().getName() + "'");
}
|
diff --git a/src/individual/Individual.java b/src/individual/Individual.java
index 82b2a0f..393cd30 100644
--- a/src/individual/Individual.java
+++ b/src/individual/Individual.java
@@ -1,144 +1,145 @@
package individual;
import genotype.Genome;
import genotype.Genotype;
import jade.core.AID;
import jade.core.Agent;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.FailureException;
import jade.domain.FIPAAgentManagement.NotUnderstoodException;
import jade.domain.FIPAAgentManagement.SearchConstraints;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;
import java.io.NotActiveException;
import java.io.Serializable;
import java.util.ArrayList;
import settings.ViabilityPair;
public class Individual extends Agent implements Serializable{
private static final long serialVersionUID = 1L;
private Genotype myGenotype;
protected int age;
protected AID myZone;
private final static int maxDFRequests = 20;
ArrayList<ViabilityPair> uSettings;
@Override
protected void setup() {
Object[] args = getArguments();
if (args.length < 3)
return;
myGenotype = (Genotype) args[0];
age = (Integer) args[1];
myZone = (AID) args[2];
GetSettings();
BehaviourRegister();
}
public AID getAID_Zone(){
return myZone;
}
@SuppressWarnings("unchecked")
private void GetSettings() {
DFAgentDescription template = new DFAgentDescription();
ServiceDescription templateSd = new ServiceDescription();
templateSd.setType("Settings");
template.addServices(templateSd);
SearchConstraints sc = new SearchConstraints();
// We want to receive 1 result
sc.setMaxResults(new Long(1));
try {
DFAgentDescription[] results = null;
int DFRequestsCounter = 0;
while(results == null || results.length < 1) {
try {
results = DFService.search(this, template, sc);
}
catch(FailureException e) {
DFRequestsCounter++;
if(DFRequestsCounter > maxDFRequests) {
e.printStackTrace();
throw new NotActiveException("Cannot get DF service, " + maxDFRequests + " attempts");
}
//System.err.println("DF search exception #" + DFRequestsCounter);
if (results == null || results.length < 1)
doWait(1000);
}
}
DFAgentDescription dfd = results[0];
AID provider = dfd.getName();
ACLMessage msg = new ACLMessage(ACLMessage.QUERY_REF);
msg.addReceiver(provider);
try {
msg.setContentObject(myGenotype);
}
catch (Exception ex) { ex.printStackTrace(); }
- send(msg);
+ ACLMessage response = null;
int DFMsgResponses = 0;
do {
DFMsgResponses++;
if(DFMsgResponses > maxDFRequests)
throw new NotActiveException("Unexpected behaviour of DF, " + maxDFRequests + " attempts");
- msg = blockingReceive(MessageTemplate.MatchSender( provider ));
+ send(msg);
+ response = blockingReceive(MessageTemplate.MatchSender( provider ));
}
- while(msg.getPerformative() == ACLMessage.FAILURE);
+ while(response.getPerformative() == ACLMessage.FAILURE);
- if(msg.getPerformative() != ACLMessage.CONFIRM) {
+ if(response.getPerformative() != ACLMessage.CONFIRM) {
throw new NotUnderstoodException("Not understood");
}
- uSettings = (ArrayList<ViabilityPair>) msg.getContentObject();
+ uSettings = (ArrayList<ViabilityPair>) response.getContentObject();
} catch (FIPAException e) {
e.printStackTrace();
} catch (UnreadableException e) {
e.printStackTrace();
} catch(NotActiveException e) {
e.printStackTrace();
}
}
protected Float getSetting(settings.Vocabulary.Param param) {
for(settings.ViabilityPair pair : uSettings) {
if(pair.getParam() == param) return pair.getValue();
}
return 0f;
}
private void BehaviourRegister() {
if (myGenotype.getGender() == Genome.X)
addBehaviour(new FemaleBehaviour());
else addBehaviour(new MaleBehaviour());
}
public void changeZone(AID aid){
myZone = aid;
}
public Genotype getGenotype(){
return myGenotype;
}
public int getAge(){
return age;
}
}
| false | true | private void GetSettings() {
DFAgentDescription template = new DFAgentDescription();
ServiceDescription templateSd = new ServiceDescription();
templateSd.setType("Settings");
template.addServices(templateSd);
SearchConstraints sc = new SearchConstraints();
// We want to receive 1 result
sc.setMaxResults(new Long(1));
try {
DFAgentDescription[] results = null;
int DFRequestsCounter = 0;
while(results == null || results.length < 1) {
try {
results = DFService.search(this, template, sc);
}
catch(FailureException e) {
DFRequestsCounter++;
if(DFRequestsCounter > maxDFRequests) {
e.printStackTrace();
throw new NotActiveException("Cannot get DF service, " + maxDFRequests + " attempts");
}
//System.err.println("DF search exception #" + DFRequestsCounter);
if (results == null || results.length < 1)
doWait(1000);
}
}
DFAgentDescription dfd = results[0];
AID provider = dfd.getName();
ACLMessage msg = new ACLMessage(ACLMessage.QUERY_REF);
msg.addReceiver(provider);
try {
msg.setContentObject(myGenotype);
}
catch (Exception ex) { ex.printStackTrace(); }
send(msg);
int DFMsgResponses = 0;
do {
DFMsgResponses++;
if(DFMsgResponses > maxDFRequests)
throw new NotActiveException("Unexpected behaviour of DF, " + maxDFRequests + " attempts");
msg = blockingReceive(MessageTemplate.MatchSender( provider ));
}
while(msg.getPerformative() == ACLMessage.FAILURE);
if(msg.getPerformative() != ACLMessage.CONFIRM) {
throw new NotUnderstoodException("Not understood");
}
uSettings = (ArrayList<ViabilityPair>) msg.getContentObject();
} catch (FIPAException e) {
e.printStackTrace();
} catch (UnreadableException e) {
e.printStackTrace();
} catch(NotActiveException e) {
e.printStackTrace();
}
}
| private void GetSettings() {
DFAgentDescription template = new DFAgentDescription();
ServiceDescription templateSd = new ServiceDescription();
templateSd.setType("Settings");
template.addServices(templateSd);
SearchConstraints sc = new SearchConstraints();
// We want to receive 1 result
sc.setMaxResults(new Long(1));
try {
DFAgentDescription[] results = null;
int DFRequestsCounter = 0;
while(results == null || results.length < 1) {
try {
results = DFService.search(this, template, sc);
}
catch(FailureException e) {
DFRequestsCounter++;
if(DFRequestsCounter > maxDFRequests) {
e.printStackTrace();
throw new NotActiveException("Cannot get DF service, " + maxDFRequests + " attempts");
}
//System.err.println("DF search exception #" + DFRequestsCounter);
if (results == null || results.length < 1)
doWait(1000);
}
}
DFAgentDescription dfd = results[0];
AID provider = dfd.getName();
ACLMessage msg = new ACLMessage(ACLMessage.QUERY_REF);
msg.addReceiver(provider);
try {
msg.setContentObject(myGenotype);
}
catch (Exception ex) { ex.printStackTrace(); }
ACLMessage response = null;
int DFMsgResponses = 0;
do {
DFMsgResponses++;
if(DFMsgResponses > maxDFRequests)
throw new NotActiveException("Unexpected behaviour of DF, " + maxDFRequests + " attempts");
send(msg);
response = blockingReceive(MessageTemplate.MatchSender( provider ));
}
while(response.getPerformative() == ACLMessage.FAILURE);
if(response.getPerformative() != ACLMessage.CONFIRM) {
throw new NotUnderstoodException("Not understood");
}
uSettings = (ArrayList<ViabilityPair>) response.getContentObject();
} catch (FIPAException e) {
e.printStackTrace();
} catch (UnreadableException e) {
e.printStackTrace();
} catch(NotActiveException e) {
e.printStackTrace();
}
}
|
diff --git a/focusns-web/src/main/java/org/focusns/web/modules/profile/ProjectHistoryWidget.java b/focusns-web/src/main/java/org/focusns/web/modules/profile/ProjectHistoryWidget.java
index b6957cf..af8a286 100644
--- a/focusns-web/src/main/java/org/focusns/web/modules/profile/ProjectHistoryWidget.java
+++ b/focusns-web/src/main/java/org/focusns/web/modules/profile/ProjectHistoryWidget.java
@@ -1,88 +1,88 @@
package org.focusns.web.modules.profile;
/*
* #%L
* FocusSNS Web
* %%
* Copyright (C) 2011 - 2013 FocusSNS
* %%
* 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 General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import org.focusns.model.common.Page;
import org.focusns.model.core.Project;
import org.focusns.model.core.ProjectHistory;
import org.focusns.model.core.ProjectUser;
import org.focusns.service.core.ProjectHistoryService;
import org.focusns.web.widget.Constraint;
import org.focusns.web.widget.annotation.Constraints;
import org.focusns.web.widget.annotation.WidgetAttribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/project")
public class ProjectHistoryWidget {
@Autowired
private ProjectHistoryService historyService;
@RequestMapping("/history-create")
public void doCreate(ProjectHistory history) {
historyService.createProjectHistory(history);
}
@RequestMapping("/history-edit")
@Constraints({Constraint.PROJECT_REQUIRED, Constraint.PROJECT_USER_REQUIRED})
public String doEdit(@WidgetAttribute Project project,
@WidgetAttribute ProjectUser user, Model model) {
//
ProjectHistory template = createTemplate(user, project);
model.addAttribute("template", template);
//
return "modules/profile/history-edit";
}
@RequestMapping("/history-list")
@Constraints({Constraint.PAGE_NOT_EMPTY})
- public String doList(@WidgetAttribute Project project,
- @WidgetAttribute ProjectUser user, Model model) {
+ public String doList(@WidgetAttribute(required = false) ProjectUser user,
+ @WidgetAttribute Project project, Model model) {
//
if(user!=null) {
ProjectHistory template = createTemplate(user, project);
model.addAttribute("template", template);
}
//
Page<ProjectHistory> page = new Page<ProjectHistory>(20);
page = historyService.fetchPage(page, project.getId());
model.addAttribute("page", page);
//
return "modules/profile/history-list";
}
private ProjectHistory createTemplate(ProjectUser user, Project project) {
ProjectHistory template = new ProjectHistory();
template.setProjectId(project.getId());
template.setTargetId(project.getId());
template.setTargetType("project");
template.setCreateById(user.getId());
return template;
}
}
| true | true | public String doList(@WidgetAttribute Project project,
@WidgetAttribute ProjectUser user, Model model) {
//
if(user!=null) {
ProjectHistory template = createTemplate(user, project);
model.addAttribute("template", template);
}
//
Page<ProjectHistory> page = new Page<ProjectHistory>(20);
page = historyService.fetchPage(page, project.getId());
model.addAttribute("page", page);
//
return "modules/profile/history-list";
}
| public String doList(@WidgetAttribute(required = false) ProjectUser user,
@WidgetAttribute Project project, Model model) {
//
if(user!=null) {
ProjectHistory template = createTemplate(user, project);
model.addAttribute("template", template);
}
//
Page<ProjectHistory> page = new Page<ProjectHistory>(20);
page = historyService.fetchPage(page, project.getId());
model.addAttribute("page", page);
//
return "modules/profile/history-list";
}
|
diff --git a/src/minecraft/co/uk/flansmods/client/RenderVehicle.java b/src/minecraft/co/uk/flansmods/client/RenderVehicle.java
index e143e34d..a0eb5380 100644
--- a/src/minecraft/co/uk/flansmods/client/RenderVehicle.java
+++ b/src/minecraft/co/uk/flansmods/client/RenderVehicle.java
@@ -1,119 +1,118 @@
package co.uk.flansmods.client;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.entity.Entity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import co.uk.flansmods.client.model.ModelVehicle;
import co.uk.flansmods.common.FlansMod;
import co.uk.flansmods.common.driveables.DriveablePart;
import co.uk.flansmods.common.driveables.EntityVehicle;
import co.uk.flansmods.common.driveables.EnumDriveablePart;
import co.uk.flansmods.common.driveables.PilotGun;
import co.uk.flansmods.common.driveables.VehicleType;
public class RenderVehicle extends Render
{
public RenderVehicle()
{
shadowSize = 0.5F;
}
public void render(EntityVehicle vehicle, double d, double d1, double d2, float f, float f1)
{
bindEntityTexture(vehicle);
VehicleType type = vehicle.getVehicleType();
GL11.glPushMatrix();
GL11.glTranslatef((float)d, (float)d1, (float)d2);
float dYaw = (vehicle.axes.getYaw() - vehicle.prevRotationYaw);
for(; dYaw > 180F; dYaw -= 360F) {}
for(; dYaw <= -180F; dYaw += 360F) {}
float dPitch = (vehicle.axes.getPitch() - vehicle.prevRotationPitch);
for(; dPitch > 180F; dPitch -= 360F) {}
for(; dPitch <= -180F; dPitch += 360F) {}
float dRoll = (vehicle.axes.getRoll() - vehicle.prevRotationRoll);
for(; dRoll > 180F; dRoll -= 360F) {}
for(; dRoll <= -180F; dRoll += 360F) {}
GL11.glRotatef(180F - vehicle.prevRotationYaw - dYaw * f1, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(vehicle.prevRotationPitch + dPitch * f1, 0.0F, 0.0F, 1.0F);
GL11.glRotatef(vehicle.prevRotationRoll + dRoll * f1, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(180F, 0.0F, 1.0F, 0.0F);
float modelScale = type.modelScale;
- GL11.glPushMatrix();
GL11.glScalef(modelScale, modelScale, modelScale);
ModelVehicle modVehicle = (ModelVehicle)type.model;
if(modVehicle != null)
modVehicle.render(vehicle, f1);
GL11.glPushMatrix();
if(type.barrelPosition != null && vehicle.isPartIntact(EnumDriveablePart.turret) && vehicle.seats != null && vehicle.seats[0] != null)
{
float yaw = vehicle.seats[0].prevLooking.getYaw() + (vehicle.seats[0].looking.getYaw() - vehicle.seats[0].prevLooking.getYaw()) * f1;
GL11.glTranslatef(type.barrelPosition.x, type.barrelPosition.y, type.barrelPosition.z);
GL11.glRotatef(-yaw, 0.0F, 1.0F, 0.0F);
GL11.glTranslatef(-type.barrelPosition.x, -type.barrelPosition.y, -type.barrelPosition.z);
if(modVehicle != null)
modVehicle.renderTurret(0.0F, 0.0F, -0.1F, 0.0F, 0.0F, 0.0625F, vehicle);
if(FlansMod.DEBUG)
{
GL11.glColor4f(0F, 0F, 1F, 0.3F);
for(PilotGun gun : type.guns)
{
if(gun.driveablePart == EnumDriveablePart.turret)
renderAABB(AxisAlignedBB.getBoundingBox(gun.position.x - 0.25F, gun.position.y - 0.25F, gun.position.z - 0.25F, gun.position.x + 0.25F, gun.position.y + 0.25F, gun.position.z + 0.25F));
}
}
}
GL11.glPopMatrix();
if(FlansMod.DEBUG)
{
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glColor4f(1F, 0F, 0F, 0.3F);
GL11.glScalef(1F, 1F, 1F);
for(DriveablePart part : vehicle.getDriveableData().parts.values())
{
if(part.box == null)
continue;
renderAABB(AxisAlignedBB.getBoundingBox(part.box.x / 16F, part.box.y / 16F, part.box.z / 16F, (part.box.x + part.box.w) / 16F, (part.box.y + part.box.h) / 16F, (part.box.z + part.box.d) / 16F));
}
GL11.glColor4f(0F, 1F, 0F, 0.3F);
if(type.barrelPosition != null)
renderAABB(AxisAlignedBB.getBoundingBox(type.barrelPosition.x - 0.25F, type.barrelPosition.y - 0.25F, type.barrelPosition.z - 0.25F, type.barrelPosition.x + 0.25F, type.barrelPosition.y + 0.25F, type.barrelPosition.z + 0.25F));
GL11.glColor4f(0F, 0F, 1F, 0.3F);
for(PilotGun gun : type.guns)
{
if(gun.driveablePart != EnumDriveablePart.turret)
renderAABB(AxisAlignedBB.getBoundingBox(gun.position.x - 0.25F, gun.position.y - 0.25F, gun.position.z - 0.25F, gun.position.x + 0.25F, gun.position.y + 0.25F, gun.position.z + 0.25F));
}
GL11.glColor4f(0F, 0F, 0F, 0.3F);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1F, 1F, 1F, 1F);
}
GL11.glPopMatrix();
}
@Override
public void doRender(Entity entity, double d, double d1, double d2, float f, float f1)
{
render((EntityVehicle)entity, d, d1, d2, f, f1);
}
@Override
protected ResourceLocation getEntityTexture(Entity entity)
{
return FlansModResourceHandler.getTexture(((EntityVehicle)entity).getVehicleType());
}
}
| true | true | public void render(EntityVehicle vehicle, double d, double d1, double d2, float f, float f1)
{
bindEntityTexture(vehicle);
VehicleType type = vehicle.getVehicleType();
GL11.glPushMatrix();
GL11.glTranslatef((float)d, (float)d1, (float)d2);
float dYaw = (vehicle.axes.getYaw() - vehicle.prevRotationYaw);
for(; dYaw > 180F; dYaw -= 360F) {}
for(; dYaw <= -180F; dYaw += 360F) {}
float dPitch = (vehicle.axes.getPitch() - vehicle.prevRotationPitch);
for(; dPitch > 180F; dPitch -= 360F) {}
for(; dPitch <= -180F; dPitch += 360F) {}
float dRoll = (vehicle.axes.getRoll() - vehicle.prevRotationRoll);
for(; dRoll > 180F; dRoll -= 360F) {}
for(; dRoll <= -180F; dRoll += 360F) {}
GL11.glRotatef(180F - vehicle.prevRotationYaw - dYaw * f1, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(vehicle.prevRotationPitch + dPitch * f1, 0.0F, 0.0F, 1.0F);
GL11.glRotatef(vehicle.prevRotationRoll + dRoll * f1, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(180F, 0.0F, 1.0F, 0.0F);
float modelScale = type.modelScale;
GL11.glPushMatrix();
GL11.glScalef(modelScale, modelScale, modelScale);
ModelVehicle modVehicle = (ModelVehicle)type.model;
if(modVehicle != null)
modVehicle.render(vehicle, f1);
GL11.glPushMatrix();
if(type.barrelPosition != null && vehicle.isPartIntact(EnumDriveablePart.turret) && vehicle.seats != null && vehicle.seats[0] != null)
{
float yaw = vehicle.seats[0].prevLooking.getYaw() + (vehicle.seats[0].looking.getYaw() - vehicle.seats[0].prevLooking.getYaw()) * f1;
GL11.glTranslatef(type.barrelPosition.x, type.barrelPosition.y, type.barrelPosition.z);
GL11.glRotatef(-yaw, 0.0F, 1.0F, 0.0F);
GL11.glTranslatef(-type.barrelPosition.x, -type.barrelPosition.y, -type.barrelPosition.z);
if(modVehicle != null)
modVehicle.renderTurret(0.0F, 0.0F, -0.1F, 0.0F, 0.0F, 0.0625F, vehicle);
if(FlansMod.DEBUG)
{
GL11.glColor4f(0F, 0F, 1F, 0.3F);
for(PilotGun gun : type.guns)
{
if(gun.driveablePart == EnumDriveablePart.turret)
renderAABB(AxisAlignedBB.getBoundingBox(gun.position.x - 0.25F, gun.position.y - 0.25F, gun.position.z - 0.25F, gun.position.x + 0.25F, gun.position.y + 0.25F, gun.position.z + 0.25F));
}
}
}
GL11.glPopMatrix();
if(FlansMod.DEBUG)
{
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glColor4f(1F, 0F, 0F, 0.3F);
GL11.glScalef(1F, 1F, 1F);
for(DriveablePart part : vehicle.getDriveableData().parts.values())
{
if(part.box == null)
continue;
renderAABB(AxisAlignedBB.getBoundingBox(part.box.x / 16F, part.box.y / 16F, part.box.z / 16F, (part.box.x + part.box.w) / 16F, (part.box.y + part.box.h) / 16F, (part.box.z + part.box.d) / 16F));
}
GL11.glColor4f(0F, 1F, 0F, 0.3F);
if(type.barrelPosition != null)
renderAABB(AxisAlignedBB.getBoundingBox(type.barrelPosition.x - 0.25F, type.barrelPosition.y - 0.25F, type.barrelPosition.z - 0.25F, type.barrelPosition.x + 0.25F, type.barrelPosition.y + 0.25F, type.barrelPosition.z + 0.25F));
GL11.glColor4f(0F, 0F, 1F, 0.3F);
for(PilotGun gun : type.guns)
{
if(gun.driveablePart != EnumDriveablePart.turret)
renderAABB(AxisAlignedBB.getBoundingBox(gun.position.x - 0.25F, gun.position.y - 0.25F, gun.position.z - 0.25F, gun.position.x + 0.25F, gun.position.y + 0.25F, gun.position.z + 0.25F));
}
GL11.glColor4f(0F, 0F, 0F, 0.3F);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1F, 1F, 1F, 1F);
}
GL11.glPopMatrix();
}
| public void render(EntityVehicle vehicle, double d, double d1, double d2, float f, float f1)
{
bindEntityTexture(vehicle);
VehicleType type = vehicle.getVehicleType();
GL11.glPushMatrix();
GL11.glTranslatef((float)d, (float)d1, (float)d2);
float dYaw = (vehicle.axes.getYaw() - vehicle.prevRotationYaw);
for(; dYaw > 180F; dYaw -= 360F) {}
for(; dYaw <= -180F; dYaw += 360F) {}
float dPitch = (vehicle.axes.getPitch() - vehicle.prevRotationPitch);
for(; dPitch > 180F; dPitch -= 360F) {}
for(; dPitch <= -180F; dPitch += 360F) {}
float dRoll = (vehicle.axes.getRoll() - vehicle.prevRotationRoll);
for(; dRoll > 180F; dRoll -= 360F) {}
for(; dRoll <= -180F; dRoll += 360F) {}
GL11.glRotatef(180F - vehicle.prevRotationYaw - dYaw * f1, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(vehicle.prevRotationPitch + dPitch * f1, 0.0F, 0.0F, 1.0F);
GL11.glRotatef(vehicle.prevRotationRoll + dRoll * f1, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(180F, 0.0F, 1.0F, 0.0F);
float modelScale = type.modelScale;
GL11.glScalef(modelScale, modelScale, modelScale);
ModelVehicle modVehicle = (ModelVehicle)type.model;
if(modVehicle != null)
modVehicle.render(vehicle, f1);
GL11.glPushMatrix();
if(type.barrelPosition != null && vehicle.isPartIntact(EnumDriveablePart.turret) && vehicle.seats != null && vehicle.seats[0] != null)
{
float yaw = vehicle.seats[0].prevLooking.getYaw() + (vehicle.seats[0].looking.getYaw() - vehicle.seats[0].prevLooking.getYaw()) * f1;
GL11.glTranslatef(type.barrelPosition.x, type.barrelPosition.y, type.barrelPosition.z);
GL11.glRotatef(-yaw, 0.0F, 1.0F, 0.0F);
GL11.glTranslatef(-type.barrelPosition.x, -type.barrelPosition.y, -type.barrelPosition.z);
if(modVehicle != null)
modVehicle.renderTurret(0.0F, 0.0F, -0.1F, 0.0F, 0.0F, 0.0625F, vehicle);
if(FlansMod.DEBUG)
{
GL11.glColor4f(0F, 0F, 1F, 0.3F);
for(PilotGun gun : type.guns)
{
if(gun.driveablePart == EnumDriveablePart.turret)
renderAABB(AxisAlignedBB.getBoundingBox(gun.position.x - 0.25F, gun.position.y - 0.25F, gun.position.z - 0.25F, gun.position.x + 0.25F, gun.position.y + 0.25F, gun.position.z + 0.25F));
}
}
}
GL11.glPopMatrix();
if(FlansMod.DEBUG)
{
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glColor4f(1F, 0F, 0F, 0.3F);
GL11.glScalef(1F, 1F, 1F);
for(DriveablePart part : vehicle.getDriveableData().parts.values())
{
if(part.box == null)
continue;
renderAABB(AxisAlignedBB.getBoundingBox(part.box.x / 16F, part.box.y / 16F, part.box.z / 16F, (part.box.x + part.box.w) / 16F, (part.box.y + part.box.h) / 16F, (part.box.z + part.box.d) / 16F));
}
GL11.glColor4f(0F, 1F, 0F, 0.3F);
if(type.barrelPosition != null)
renderAABB(AxisAlignedBB.getBoundingBox(type.barrelPosition.x - 0.25F, type.barrelPosition.y - 0.25F, type.barrelPosition.z - 0.25F, type.barrelPosition.x + 0.25F, type.barrelPosition.y + 0.25F, type.barrelPosition.z + 0.25F));
GL11.glColor4f(0F, 0F, 1F, 0.3F);
for(PilotGun gun : type.guns)
{
if(gun.driveablePart != EnumDriveablePart.turret)
renderAABB(AxisAlignedBB.getBoundingBox(gun.position.x - 0.25F, gun.position.y - 0.25F, gun.position.z - 0.25F, gun.position.x + 0.25F, gun.position.y + 0.25F, gun.position.z + 0.25F));
}
GL11.glColor4f(0F, 0F, 0F, 0.3F);
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDisable(GL11.GL_BLEND);
GL11.glColor4f(1F, 1F, 1F, 1F);
}
GL11.glPopMatrix();
}
|
diff --git a/Java_practice/src/jp/yahei/lwjgl/SimpleObject.java b/Java_practice/src/jp/yahei/lwjgl/SimpleObject.java
index af389ca..ab03dbe 100644
--- a/Java_practice/src/jp/yahei/lwjgl/SimpleObject.java
+++ b/Java_practice/src/jp/yahei/lwjgl/SimpleObject.java
@@ -1,77 +1,77 @@
package jp.yahei.lwjgl;
import static org.lwjgl.opengl.GL11.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
/**
* �P���ȕ`��\�I�u�W�F�N�g�̒��ۃN���X<br>
* �ʒu�ƌ����̂���3�����`��̕`��Ɋւ��@�\������<br>
* @author Yahei
*
*/
public abstract class SimpleObject implements Drawable {
// �`��ɕK�v�Ȉʒu�Ǝp���̏��
double x,y,z;
float[] rotMatrix;
// ��]�s��̓_�C���N�g�o�b�t�@�ɓ���ēn���K�v�����邽�߁A�����p�ӂ��Ă���
FloatBuffer fb;
{
ByteBuffer bb = ByteBuffer.allocateDirect(16*4);
bb.order(ByteOrder.nativeOrder());
fb = bb.asFloatBuffer();
}
/**
* �`����s��<br>
* �����ł͉�]�E���s�ړ��̏���������S�����A
* ��̓I�ȕ`��`��́A�T�u�N���X�Œ�`�����drawGeometry()�Ō��肳���<br>
*/
@Override
public void draw(){
+ glMatrixMode(GL_MODELVIEW);
glPushMatrix(); {
- glMatrixMode(GL_MODELVIEW);
glTranslated(x, y, z);
fb.put(rotMatrix);
fb.flip();
glMultMatrix(fb);
drawGeometry();
} glPopMatrix();
}
/**
* ���̕��̂̍��W��ݒ�<br>
*/
public void setCoordinate(double x, double y, double z){
this.x = x;
this.y = y;
this.z = z;
}
/**
* ���̕��̂̌�����ݒ�<br>
*/
public void setAngle(float[] rotMatrix){
this.rotMatrix = rotMatrix;
}
/**
* ���_��z�u���Ď��ۂɕ`�悵�Ă�������<br>
* �T�u�N���X�ŃI�[�o�[���C�h�����<br>
*/
abstract protected void drawGeometry();
}
| false | true | public void draw(){
glPushMatrix(); {
glMatrixMode(GL_MODELVIEW);
glTranslated(x, y, z);
fb.put(rotMatrix);
fb.flip();
glMultMatrix(fb);
drawGeometry();
} glPopMatrix();
}
| public void draw(){
glMatrixMode(GL_MODELVIEW);
glPushMatrix(); {
glTranslated(x, y, z);
fb.put(rotMatrix);
fb.flip();
glMultMatrix(fb);
drawGeometry();
} glPopMatrix();
}
|
diff --git a/src/jMyCTCM/JMyCTCM.java b/src/jMyCTCM/JMyCTCM.java
index a483402..49c49c5 100644
--- a/src/jMyCTCM/JMyCTCM.java
+++ b/src/jMyCTCM/JMyCTCM.java
@@ -1,46 +1,46 @@
package jMyCTCM;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import boccaccio.andrea.ctmc.ICTCM;
import boccaccio.andrea.filesystem.DirectoryFactory;
import boccaccio.andrea.filesystem.FileFilterFactory;
import boccaccio.andrea.inputFiles.FileLoaderFactory;
import boccaccio.andrea.outputFiles.FileWriterFactory;
public class JMyCTCM {
/**
* @param args
*/
public static void main(String[] args) {
List<String> ff = new ArrayList<>();
List<File> lf;
ICTCM tmpCTCM;
String inputFilename;
String outputFilename;
int i = -1;
int max = -1;
ff.add("ctmc");
lf = DirectoryFactory.getInstance().getDirectory(".").getFiles(FileFilterFactory.getInstance().getFileFilter(ff));
max = lf.size();
for(i=0;i<max;++i) {
try {
inputFilename = lf.get(i).getAbsolutePath();
- outputFilename = inputFilename.substring(0,inputFilename.lastIndexOf("ctmc")) + "output.ctmc";
+ outputFilename = inputFilename.substring(0,inputFilename.lastIndexOf("ctmc")) + "ctmc.output.txt";
tmpCTCM = FileLoaderFactory.getInstance().getFileLoader().load(inputFilename);
FileWriterFactory.getInstance().getFileWriter().write(tmpCTCM, outputFilename);
System.out.println(inputFilename + " correttamente elaborato risultati nel file " + outputFilename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
| true | true | public static void main(String[] args) {
List<String> ff = new ArrayList<>();
List<File> lf;
ICTCM tmpCTCM;
String inputFilename;
String outputFilename;
int i = -1;
int max = -1;
ff.add("ctmc");
lf = DirectoryFactory.getInstance().getDirectory(".").getFiles(FileFilterFactory.getInstance().getFileFilter(ff));
max = lf.size();
for(i=0;i<max;++i) {
try {
inputFilename = lf.get(i).getAbsolutePath();
outputFilename = inputFilename.substring(0,inputFilename.lastIndexOf("ctmc")) + "output.ctmc";
tmpCTCM = FileLoaderFactory.getInstance().getFileLoader().load(inputFilename);
FileWriterFactory.getInstance().getFileWriter().write(tmpCTCM, outputFilename);
System.out.println(inputFilename + " correttamente elaborato risultati nel file " + outputFilename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| public static void main(String[] args) {
List<String> ff = new ArrayList<>();
List<File> lf;
ICTCM tmpCTCM;
String inputFilename;
String outputFilename;
int i = -1;
int max = -1;
ff.add("ctmc");
lf = DirectoryFactory.getInstance().getDirectory(".").getFiles(FileFilterFactory.getInstance().getFileFilter(ff));
max = lf.size();
for(i=0;i<max;++i) {
try {
inputFilename = lf.get(i).getAbsolutePath();
outputFilename = inputFilename.substring(0,inputFilename.lastIndexOf("ctmc")) + "ctmc.output.txt";
tmpCTCM = FileLoaderFactory.getInstance().getFileLoader().load(inputFilename);
FileWriterFactory.getInstance().getFileWriter().write(tmpCTCM, outputFilename);
System.out.println(inputFilename + " correttamente elaborato risultati nel file " + outputFilename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
diff --git a/MyTinyProjects/Snake/src/com/az/Egg.java b/MyTinyProjects/Snake/src/com/az/Egg.java
index c62c737..1192c31 100644
--- a/MyTinyProjects/Snake/src/com/az/Egg.java
+++ b/MyTinyProjects/Snake/src/com/az/Egg.java
@@ -1,74 +1,75 @@
package com.az;
import java.awt.*;
import java.util.Random;
public class Egg {
private Point p = new Point();
private static int w = Yard.CELL_SIZE;
private static int h = w;
private static Random r = new Random();
Egg(Point p) {
this.p = p;
}
Egg() {
this(nextPos());
}
static int x, y;
private static Point nextPos() {
x = r.nextInt(Yard.COLS-1);
y = r.nextInt(Yard.ROWS-1);
while(x <1 || y*Yard.CELL_SIZE < 30) {
+ x = r.nextInt(Yard.COLS-1);
y = r.nextInt(Yard.ROWS-1);
}
return new Point(x, y);
}
public void draw(Graphics g) {
Color c = g.getColor();
g.setColor(Color.ORANGE);
g.fillOval(Yard.CELL_SIZE*p.x, Yard.CELL_SIZE*p.y, w, h);
g.setColor(c);
}
public Rectangle getRect() {
return new Rectangle(Yard.CELL_SIZE*p.x, Yard.CELL_SIZE*p.y, w, h);
}
public void reset() {
p = nextPos();
}
}
| true | true | private static Point nextPos() {
x = r.nextInt(Yard.COLS-1);
y = r.nextInt(Yard.ROWS-1);
while(x <1 || y*Yard.CELL_SIZE < 30) {
y = r.nextInt(Yard.ROWS-1);
}
return new Point(x, y);
}
| private static Point nextPos() {
x = r.nextInt(Yard.COLS-1);
y = r.nextInt(Yard.ROWS-1);
while(x <1 || y*Yard.CELL_SIZE < 30) {
x = r.nextInt(Yard.COLS-1);
y = r.nextInt(Yard.ROWS-1);
}
return new Point(x, y);
}
|
diff --git a/zssapp/test/SS_169_Test.java b/zssapp/test/SS_169_Test.java
index 252e900..7417a2a 100644
--- a/zssapp/test/SS_169_Test.java
+++ b/zssapp/test/SS_169_Test.java
@@ -1,18 +1,20 @@
public class SS_169_Test extends SSAbstractTestCase {
@Override
protected void executeTest() {
verifyFalse(isWidgetVisible("$_openFileDialog"));
click("jq('$fileMenu button.z-menu-btn')");
waitResponse();
click("jq('$openFile a.z-menu-item-cnt')");
waitResponse();
verifyTrue(isWidgetVisible("$_openFileDialog"));
- //TODO: need to open a excel file and verify
+ doubleClick(jq("$_openFileDialog $filesListbox .z-listcell").first());
+ String text = getSpecifiedCell(0, 3).text();
+ verifyEquals(text, "Collaboration");
}
}
| true | true | protected void executeTest() {
verifyFalse(isWidgetVisible("$_openFileDialog"));
click("jq('$fileMenu button.z-menu-btn')");
waitResponse();
click("jq('$openFile a.z-menu-item-cnt')");
waitResponse();
verifyTrue(isWidgetVisible("$_openFileDialog"));
//TODO: need to open a excel file and verify
}
| protected void executeTest() {
verifyFalse(isWidgetVisible("$_openFileDialog"));
click("jq('$fileMenu button.z-menu-btn')");
waitResponse();
click("jq('$openFile a.z-menu-item-cnt')");
waitResponse();
verifyTrue(isWidgetVisible("$_openFileDialog"));
doubleClick(jq("$_openFileDialog $filesListbox .z-listcell").first());
String text = getSpecifiedCell(0, 3).text();
verifyEquals(text, "Collaboration");
}
|
diff --git a/org.eclipse.virgo.kernel.deployer.test/src/test/java/org/eclipse/virgo/kernel/deployer/test/ImportPromotionTests.java b/org.eclipse.virgo.kernel.deployer.test/src/test/java/org/eclipse/virgo/kernel/deployer/test/ImportPromotionTests.java
index 189be03a..232ebcb6 100644
--- a/org.eclipse.virgo.kernel.deployer.test/src/test/java/org/eclipse/virgo/kernel/deployer/test/ImportPromotionTests.java
+++ b/org.eclipse.virgo.kernel.deployer.test/src/test/java/org/eclipse/virgo/kernel/deployer/test/ImportPromotionTests.java
@@ -1,44 +1,45 @@
/*******************************************************************************
* Copyright (c) 2008, 2010 VMware Inc.
* 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:
* VMware Inc. - initial contribution
*******************************************************************************/
package org.eclipse.virgo.kernel.deployer.test;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import org.junit.Test;
/**
* Test the promotion of a bundle import across the bundles of a PAR file.
*
*/
public class ImportPromotionTests extends AbstractParTests {
private static final String BUNDLE_SYMBOLIC_NAME = "ImportPromotion-1-ImporterA";
private static final String BUNDLE_SYMBOLIC_NAME_2 = "ImportPromotionViaLibrary-1-ImporterA";
@Test
public void testImportPromotion() throws Throwable {
File par = new File("src/test/resources/ImportPromotion.par");
deploy(par);
assertNotNull(ApplicationContextUtils.getApplicationContext(this.context, BUNDLE_SYMBOLIC_NAME));
this.deployer.refresh(par.toURI(), "ImporterA");
+ Thread.sleep(100);
assertNotNull(ApplicationContextUtils.getApplicationContext(this.context, BUNDLE_SYMBOLIC_NAME));
}
@Test
public void testImportPromotionViaLibrary() throws Throwable {
deploy(new File("src/test/resources/ImportPromotionViaLibrary.par"));
assertNotNull(ApplicationContextUtils.getApplicationContext(this.context, BUNDLE_SYMBOLIC_NAME_2));
}
}
| true | true | public void testImportPromotion() throws Throwable {
File par = new File("src/test/resources/ImportPromotion.par");
deploy(par);
assertNotNull(ApplicationContextUtils.getApplicationContext(this.context, BUNDLE_SYMBOLIC_NAME));
this.deployer.refresh(par.toURI(), "ImporterA");
assertNotNull(ApplicationContextUtils.getApplicationContext(this.context, BUNDLE_SYMBOLIC_NAME));
}
| public void testImportPromotion() throws Throwable {
File par = new File("src/test/resources/ImportPromotion.par");
deploy(par);
assertNotNull(ApplicationContextUtils.getApplicationContext(this.context, BUNDLE_SYMBOLIC_NAME));
this.deployer.refresh(par.toURI(), "ImporterA");
Thread.sleep(100);
assertNotNull(ApplicationContextUtils.getApplicationContext(this.context, BUNDLE_SYMBOLIC_NAME));
}
|
diff --git a/src/main/java/org/weather/weatherman/activity/ForecastActivity.java b/src/main/java/org/weather/weatherman/activity/ForecastActivity.java
index 9500bac..91d3201 100644
--- a/src/main/java/org/weather/weatherman/activity/ForecastActivity.java
+++ b/src/main/java/org/weather/weatherman/activity/ForecastActivity.java
@@ -1,170 +1,159 @@
package org.weather.weatherman.activity;
import org.weather.weatherman.R;
import org.weather.weatherman.WeatherApplication;
import org.weather.weatherman.content.Weather;
import org.weather.weatherman.content.WeatherService;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.baidu.mobstat.StatService;
/**
* @since 2012-5-18
* @author gmz
*
*/
public class ForecastActivity extends Activity {
private static final String tag = ForecastTask.class.getSimpleName();
private WeatherApplication app;
private WeatherService weatherService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.forecast);
app = (WeatherApplication) getApplication();
weatherService = new WeatherService(this);
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
ProgressBar progressBar = (ProgressBar) getParent().findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
this.refreshData();
// stats
StatService.onResume(this);
}
/**
* @author gengmaozhang01
* @since 2014-1-25 下午6:06:02
*/
public void refreshData() {
String city = (app.getCity() != null ? app.getCity().getId() : null);
new ForecastTask().execute(city);
}
class ForecastTask extends AsyncTask<String, Integer, Weather.ForecastWeather> {
public ForecastTask() {
}
@Override
protected void onPreExecute() {
super.onPreExecute();
// updateTime
TextView view = (TextView) findViewById(R.id.updateTime);
view.setText("--");
// clear
TableLayout layout = (TableLayout) view.getParent().getParent();
layout.removeViews(1, layout.getChildCount() - 1);
}
@Override
protected Weather.ForecastWeather doInBackground(String... params) {
onProgressUpdate(0);
String city = (params != null && params.length > 0 ? params[0] : null);
if (city == null || city.length() == 0) {
return null;
}
onProgressUpdate(20);
Weather.ForecastWeather forecast = weatherService.findForecastWeather(city);
onProgressUpdate(60);
return forecast;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
int progress = (values != null && values.length > 0 ? values[0] : 0);
ProgressBar progressBar = (ProgressBar) getParent().findViewById(R.id.progressBar);
if (progressBar != null) {
Log.i(tag, progress + "/" + progressBar.getMax());
progressBar.setProgress(progress);
if (progress >= progressBar.getMax()) {
progressBar.setVisibility(View.GONE);
}
}
}
@Override
protected void onPostExecute(Weather.ForecastWeather forecast) {
this.onPreExecute();
super.onPostExecute(forecast);
onProgressUpdate(80);
if (forecast != null) {
// update time
TextView uptimeView = (TextView) findViewById(R.id.updateTime);
uptimeView.setText(forecast.getTime() + "更新");
// add row
TableLayout layout = (TableLayout) uptimeView.getParent().getParent();
for (int i = 0; i < forecast.getForecastSize(); i++) {
TableRow row = new TableRow(layout.getContext());
// date
TextView view = new TextView(layout.getContext());
- view.setText(forecast.getForecastTime(i).substring(5));
+ final String time = forecast.getForecastTime(i).substring(5);
+ view.setText(time + ":");
row.addView(view);
- // image
- // view = new TextView(this);
- // view.setPadding(3, 3, 3, 3);
- // view.setTextSize(14);
- // view.setText(cursor.getString(cursor.getColumnIndex(Weather.ForecastWeather.IMAGE)));
- // row.addView(view);
// weather
view = new TextView(layout.getContext());
- view.setText(forecast.getForecastWeather(i));
- row.addView(view);
- // temperature
- view = new TextView(layout.getContext());
- view.setText(forecast.getForecastTemperature(i));
- row.addView(view);
- // wind
- view = new TextView(layout.getContext());
- view.setText(forecast.getForecastWind(i) + "," + forecast.getForecastWindForce(i));
+ view.setText(forecast.getForecastWeather(i) + "。" + (time.contains("夜") ? "低温" : "高温")
+ + forecast.getForecastTemperature(i) + "。" + forecast.getForecastWind(i) + ","
+ + forecast.getForecastWindForce(i));
row.addView(view);
layout.addView(row);
}
} else {
ToastService.toastLong(getApplicationContext(), getResources().getString(R.string.connect_failed));
Log.e(tag, "can't get forecast weather");
}
onProgressUpdate(100);
}
}
@Override
protected void onPause() {
super.onPause();
// stats
StatService.onPause(this);
}
@Override
public void onBackPressed() {
Activity parent = getParent();
if (parent != null) {
parent.onBackPressed();
} else {
super.onBackPressed();
}
}
}
| false | true | protected void onPostExecute(Weather.ForecastWeather forecast) {
this.onPreExecute();
super.onPostExecute(forecast);
onProgressUpdate(80);
if (forecast != null) {
// update time
TextView uptimeView = (TextView) findViewById(R.id.updateTime);
uptimeView.setText(forecast.getTime() + "更新");
// add row
TableLayout layout = (TableLayout) uptimeView.getParent().getParent();
for (int i = 0; i < forecast.getForecastSize(); i++) {
TableRow row = new TableRow(layout.getContext());
// date
TextView view = new TextView(layout.getContext());
view.setText(forecast.getForecastTime(i).substring(5));
row.addView(view);
// image
// view = new TextView(this);
// view.setPadding(3, 3, 3, 3);
// view.setTextSize(14);
// view.setText(cursor.getString(cursor.getColumnIndex(Weather.ForecastWeather.IMAGE)));
// row.addView(view);
// weather
view = new TextView(layout.getContext());
view.setText(forecast.getForecastWeather(i));
row.addView(view);
// temperature
view = new TextView(layout.getContext());
view.setText(forecast.getForecastTemperature(i));
row.addView(view);
// wind
view = new TextView(layout.getContext());
view.setText(forecast.getForecastWind(i) + "," + forecast.getForecastWindForce(i));
row.addView(view);
layout.addView(row);
}
} else {
ToastService.toastLong(getApplicationContext(), getResources().getString(R.string.connect_failed));
Log.e(tag, "can't get forecast weather");
}
onProgressUpdate(100);
}
| protected void onPostExecute(Weather.ForecastWeather forecast) {
this.onPreExecute();
super.onPostExecute(forecast);
onProgressUpdate(80);
if (forecast != null) {
// update time
TextView uptimeView = (TextView) findViewById(R.id.updateTime);
uptimeView.setText(forecast.getTime() + "更新");
// add row
TableLayout layout = (TableLayout) uptimeView.getParent().getParent();
for (int i = 0; i < forecast.getForecastSize(); i++) {
TableRow row = new TableRow(layout.getContext());
// date
TextView view = new TextView(layout.getContext());
final String time = forecast.getForecastTime(i).substring(5);
view.setText(time + ":");
row.addView(view);
// weather
view = new TextView(layout.getContext());
view.setText(forecast.getForecastWeather(i) + "。" + (time.contains("夜") ? "低温" : "高温")
+ forecast.getForecastTemperature(i) + "。" + forecast.getForecastWind(i) + ","
+ forecast.getForecastWindForce(i));
row.addView(view);
layout.addView(row);
}
} else {
ToastService.toastLong(getApplicationContext(), getResources().getString(R.string.connect_failed));
Log.e(tag, "can't get forecast weather");
}
onProgressUpdate(100);
}
|
diff --git a/src/net/ST392/ChangeHorse/CHCommandExecutor.java b/src/net/ST392/ChangeHorse/CHCommandExecutor.java
index 5a7e730..d318e44 100644
--- a/src/net/ST392/ChangeHorse/CHCommandExecutor.java
+++ b/src/net/ST392/ChangeHorse/CHCommandExecutor.java
@@ -1,268 +1,268 @@
package net.ST392.ChangeHorse;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Horse;
import org.bukkit.entity.Player;
public class CHCommandExecutor implements CommandExecutor {
String mainArgs = ChatColor.GREEN + "/ChangeHorse (set/get)";
String getArgs = ChatColor.YELLOW + "A valid property to get is required. " + ChatColor.GREEN + " Options are: Type, Color, Style, JumpStrength";
String setArgs = ChatColor.YELLOW + "A valid property to set is required. " + ChatColor.GREEN + " Options are: Type, Color, Style, JumpStrength, MaxHealth";
//Class that handles slash commands from user
//=============================================
private ChangeHorse plugin;
public CHCommandExecutor(ChangeHorse plugin) {
this.plugin = plugin;
}
//=============================================
@SuppressWarnings("deprecation")
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
//Make sure command was not sent from console
if (sender instanceof Player == false){
plugin.getLog().info("/ChangeHorse is only available in game.");
return true;
}
//Convert sender to Player
Player player = (Player) sender;
if (!player.isInsideVehicle() || !(player.getVehicle() instanceof Horse)) {
player.sendMessage(ChatColor.YELLOW + "Must have argument and must be riding a horse.");
- return false;
+ return true;
}
if(args.length == 0){
player.sendMessage(mainArgs);
return true;
}
//Get the Horse
Horse horse = (Horse) player.getVehicle();
String property = null;
try { property = args[0].toLowerCase(); } catch(NumberFormatException e) {}
if(property == null){
player.sendMessage("Invalid argument");
return true;
}
if(args.length > 3){
- args[2] = args[2] + args[3];
+ args[2] += args[3];
}
if(property.equals("get")){
if(args.length < 2){ //ADD NEW PROPERTIES HERE
player.sendMessage(getArgs);
return true;
}
String option = args[1].toLowerCase();
if(option.equals("type") || option.equals("t")){
if(!player.hasPermission("changehorse.get.type")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
- return false;
+ return true;
}
player.sendMessage(ChatColor.GREEN + "Horse type is: " + horse.getType());
return true;
}
if(option.equals("color") || option.equals("c")){
if(!player.hasPermission("changehorse.get.color")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
- return false;
+ return true;
}
player.sendMessage(ChatColor.GREEN + "Horse color is: " + horse.getColor());
return true;
}
if(option.equals("style") || option.equals("st")){
if(!player.hasPermission("changehorse.get.style")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
- return false;
+ return true;
}
player.sendMessage(ChatColor.GREEN + "Horse style is: " + horse.getStyle());
return true;
}
if(option.equals("jumpstrength") || option.equals("js")){
if(!player.hasPermission("changehorse.get.jumpstrength")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
- return false;
+ return true;
}
player.sendMessage(ChatColor.GREEN + "Horse type is: " + horse.getJumpStrength()*50);
return true;
}
player.sendMessage(getArgs);
return true;
}else if(property.equals("set")){
if(args.length < 2){ //ADD NEW PROPERTIES HERE
player.sendMessage(ChatColor.YELLOW + setArgs);
return true;
}
String option = args[1].toLowerCase();
if(option.equals("type") || option.equals("t")){
if(!player.hasPermission("changehorse.set.type")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
- return false;
+ return true;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Type options are:");
for(Horse.Variant variant: Horse.Variant.values()){
player.sendMessage(ChatColor.GREEN + " " + variant.toString().toLowerCase());
}
return true;
}else{
for(Horse.Variant variant: Horse.Variant.values()){
if(variant.toString().toLowerCase().replaceAll("_", "").replaceAll("horse", "").equals(args[2].toLowerCase().replaceAll("_", "").replaceAll("horse", ""))){
if(variant != Horse.Variant.HORSE && horse.getInventory().getArmor() != null){
player.sendMessage(ChatColor.RED + "Please remove horse armor before changing horse type.");
return true;
}
horse.setVariant(variant);
player.sendMessage(ChatColor.GREEN + "Horse type set to " + variant.toString());
return true;
}
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguement. For list of Types: /ChangeHorse Type");
return true;
}
}
if(option.equals("color") || option.equals("c")){
if(!player.hasPermission("changehorse.set.color")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
- return false;
+ return true;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Color options are:");
for(Horse.Color color: Horse.Color.values()){
player.sendMessage(ChatColor.GREEN + " " + color.toString().toLowerCase().replaceAll("_", ""));
}
return true;
}else{
if(horse.getVariant() == Horse.Variant.HORSE){
for(Horse.Color color: Horse.Color.values()){
if(color.toString().toLowerCase().replaceAll("_", "").equals(args[2].toLowerCase())){
horse.setColor(color);
player.sendMessage(ChatColor.GREEN + "Horse color set to " + color.toString());
return true;
}
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguement. For list of Colors: /ChangeHorse Color");
return true;
}else{
player.sendMessage(ChatColor.YELLOW + "Horse colors only apply to normal horses. Change horse to type \"Horse\"");
return true;
}
}
}
if(option.equals("style") || option.equals("st")){
if(!player.hasPermission("changehorse.set.style")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
- return false;
+ return true;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Style options are:");
for(Horse.Style style: Horse.Style.values()){
player.sendMessage(ChatColor.GREEN + " " + style.toString().toLowerCase());
}
return true;
}else{
if(horse.getVariant() == Horse.Variant.HORSE){
for(Horse.Style style: Horse.Style.values()){
- if(style.toString().toLowerCase().replaceAll("_", "").equals(args[1].toLowerCase().replaceAll("_", ""))){
+ if(style.toString().toLowerCase().replaceAll("_", "").equals(args[2].toLowerCase().replaceAll("_", ""))){
horse.setStyle(style);
player.sendMessage(ChatColor.GREEN + "Horse style set to " + style.toString());
return true;
}
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguement. For list of Styles: /ChangeHorse Style");
return true;
}else{
player.sendMessage(ChatColor.YELLOW + "Horse styles only apply to normal horses. Change horse to type \"Horse\"");
return true;
}
}
}
if(option.equals("jumpstrength") || option.equals("js")){
if(!player.hasPermission("changehorse.set.jumpstrength")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
- return false;
+ return true;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Valid range for Jump Strength is: 0-100");
return true;
}else{
int num = -1;
try{
num = Integer.parseInt(args[2]);
} catch(NumberFormatException e) {
player.sendMessage(ChatColor.YELLOW + "Invalid number given. " + ChatColor.GREEN + "Valid range for Jump Strength is: 0-100");
return true;
}
if(num > 0 && num <= 100){
double js = (double) num/50;
horse.setJumpStrength(js);
player.sendMessage(ChatColor.GREEN + "Horse jump strength set to " + num);
return true;
}else{
player.sendMessage(ChatColor.YELLOW + "Invalid number given, go get the correct range use /ChangeHorse set JumpStrength");
return true;
}
}
}
if(option.equals("maxhealth") || option.equals("mh")){
if(!player.hasPermission("changehorse.set.maxhealth")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
- return false;
+ return true;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Valid range for Max Health is: 0-60");
return true;
}else{
int num = -1;
try{
num = Integer.parseInt(args[2]);
} catch(NumberFormatException e) {
player.sendMessage(ChatColor.YELLOW + "Invalid number given." + ChatColor.GREEN +" Valid range for Max Health is: 0-60");
return true;
}
if(num > 0 && num <= 100){
horse.setMaxHealth(num);
player.sendMessage(ChatColor.GREEN + "Horse jump strength set to " + num);
return true;
}else{
player.sendMessage(ChatColor.YELLOW + "Invalid number given, go get the correct range use /ChangeHorse set MaxHealth");
return true;
}
}
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguement. " + ChatColor.GREEN + setArgs);
return true;
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguments. " + mainArgs);
return true;
//end new code
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
//Make sure command was not sent from console
if (sender instanceof Player == false){
plugin.getLog().info("/ChangeHorse is only available in game.");
return true;
}
//Convert sender to Player
Player player = (Player) sender;
if (!player.isInsideVehicle() || !(player.getVehicle() instanceof Horse)) {
player.sendMessage(ChatColor.YELLOW + "Must have argument and must be riding a horse.");
return false;
}
if(args.length == 0){
player.sendMessage(mainArgs);
return true;
}
//Get the Horse
Horse horse = (Horse) player.getVehicle();
String property = null;
try { property = args[0].toLowerCase(); } catch(NumberFormatException e) {}
if(property == null){
player.sendMessage("Invalid argument");
return true;
}
if(args.length > 3){
args[2] = args[2] + args[3];
}
if(property.equals("get")){
if(args.length < 2){ //ADD NEW PROPERTIES HERE
player.sendMessage(getArgs);
return true;
}
String option = args[1].toLowerCase();
if(option.equals("type") || option.equals("t")){
if(!player.hasPermission("changehorse.get.type")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return false;
}
player.sendMessage(ChatColor.GREEN + "Horse type is: " + horse.getType());
return true;
}
if(option.equals("color") || option.equals("c")){
if(!player.hasPermission("changehorse.get.color")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return false;
}
player.sendMessage(ChatColor.GREEN + "Horse color is: " + horse.getColor());
return true;
}
if(option.equals("style") || option.equals("st")){
if(!player.hasPermission("changehorse.get.style")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return false;
}
player.sendMessage(ChatColor.GREEN + "Horse style is: " + horse.getStyle());
return true;
}
if(option.equals("jumpstrength") || option.equals("js")){
if(!player.hasPermission("changehorse.get.jumpstrength")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return false;
}
player.sendMessage(ChatColor.GREEN + "Horse type is: " + horse.getJumpStrength()*50);
return true;
}
player.sendMessage(getArgs);
return true;
}else if(property.equals("set")){
if(args.length < 2){ //ADD NEW PROPERTIES HERE
player.sendMessage(ChatColor.YELLOW + setArgs);
return true;
}
String option = args[1].toLowerCase();
if(option.equals("type") || option.equals("t")){
if(!player.hasPermission("changehorse.set.type")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return false;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Type options are:");
for(Horse.Variant variant: Horse.Variant.values()){
player.sendMessage(ChatColor.GREEN + " " + variant.toString().toLowerCase());
}
return true;
}else{
for(Horse.Variant variant: Horse.Variant.values()){
if(variant.toString().toLowerCase().replaceAll("_", "").replaceAll("horse", "").equals(args[2].toLowerCase().replaceAll("_", "").replaceAll("horse", ""))){
if(variant != Horse.Variant.HORSE && horse.getInventory().getArmor() != null){
player.sendMessage(ChatColor.RED + "Please remove horse armor before changing horse type.");
return true;
}
horse.setVariant(variant);
player.sendMessage(ChatColor.GREEN + "Horse type set to " + variant.toString());
return true;
}
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguement. For list of Types: /ChangeHorse Type");
return true;
}
}
if(option.equals("color") || option.equals("c")){
if(!player.hasPermission("changehorse.set.color")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return false;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Color options are:");
for(Horse.Color color: Horse.Color.values()){
player.sendMessage(ChatColor.GREEN + " " + color.toString().toLowerCase().replaceAll("_", ""));
}
return true;
}else{
if(horse.getVariant() == Horse.Variant.HORSE){
for(Horse.Color color: Horse.Color.values()){
if(color.toString().toLowerCase().replaceAll("_", "").equals(args[2].toLowerCase())){
horse.setColor(color);
player.sendMessage(ChatColor.GREEN + "Horse color set to " + color.toString());
return true;
}
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguement. For list of Colors: /ChangeHorse Color");
return true;
}else{
player.sendMessage(ChatColor.YELLOW + "Horse colors only apply to normal horses. Change horse to type \"Horse\"");
return true;
}
}
}
if(option.equals("style") || option.equals("st")){
if(!player.hasPermission("changehorse.set.style")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return false;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Style options are:");
for(Horse.Style style: Horse.Style.values()){
player.sendMessage(ChatColor.GREEN + " " + style.toString().toLowerCase());
}
return true;
}else{
if(horse.getVariant() == Horse.Variant.HORSE){
for(Horse.Style style: Horse.Style.values()){
if(style.toString().toLowerCase().replaceAll("_", "").equals(args[1].toLowerCase().replaceAll("_", ""))){
horse.setStyle(style);
player.sendMessage(ChatColor.GREEN + "Horse style set to " + style.toString());
return true;
}
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguement. For list of Styles: /ChangeHorse Style");
return true;
}else{
player.sendMessage(ChatColor.YELLOW + "Horse styles only apply to normal horses. Change horse to type \"Horse\"");
return true;
}
}
}
if(option.equals("jumpstrength") || option.equals("js")){
if(!player.hasPermission("changehorse.set.jumpstrength")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return false;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Valid range for Jump Strength is: 0-100");
return true;
}else{
int num = -1;
try{
num = Integer.parseInt(args[2]);
} catch(NumberFormatException e) {
player.sendMessage(ChatColor.YELLOW + "Invalid number given. " + ChatColor.GREEN + "Valid range for Jump Strength is: 0-100");
return true;
}
if(num > 0 && num <= 100){
double js = (double) num/50;
horse.setJumpStrength(js);
player.sendMessage(ChatColor.GREEN + "Horse jump strength set to " + num);
return true;
}else{
player.sendMessage(ChatColor.YELLOW + "Invalid number given, go get the correct range use /ChangeHorse set JumpStrength");
return true;
}
}
}
if(option.equals("maxhealth") || option.equals("mh")){
if(!player.hasPermission("changehorse.set.maxhealth")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return false;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Valid range for Max Health is: 0-60");
return true;
}else{
int num = -1;
try{
num = Integer.parseInt(args[2]);
} catch(NumberFormatException e) {
player.sendMessage(ChatColor.YELLOW + "Invalid number given." + ChatColor.GREEN +" Valid range for Max Health is: 0-60");
return true;
}
if(num > 0 && num <= 100){
horse.setMaxHealth(num);
player.sendMessage(ChatColor.GREEN + "Horse jump strength set to " + num);
return true;
}else{
player.sendMessage(ChatColor.YELLOW + "Invalid number given, go get the correct range use /ChangeHorse set MaxHealth");
return true;
}
}
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguement. " + ChatColor.GREEN + setArgs);
return true;
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguments. " + mainArgs);
return true;
//end new code
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
//Make sure command was not sent from console
if (sender instanceof Player == false){
plugin.getLog().info("/ChangeHorse is only available in game.");
return true;
}
//Convert sender to Player
Player player = (Player) sender;
if (!player.isInsideVehicle() || !(player.getVehicle() instanceof Horse)) {
player.sendMessage(ChatColor.YELLOW + "Must have argument and must be riding a horse.");
return true;
}
if(args.length == 0){
player.sendMessage(mainArgs);
return true;
}
//Get the Horse
Horse horse = (Horse) player.getVehicle();
String property = null;
try { property = args[0].toLowerCase(); } catch(NumberFormatException e) {}
if(property == null){
player.sendMessage("Invalid argument");
return true;
}
if(args.length > 3){
args[2] += args[3];
}
if(property.equals("get")){
if(args.length < 2){ //ADD NEW PROPERTIES HERE
player.sendMessage(getArgs);
return true;
}
String option = args[1].toLowerCase();
if(option.equals("type") || option.equals("t")){
if(!player.hasPermission("changehorse.get.type")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return true;
}
player.sendMessage(ChatColor.GREEN + "Horse type is: " + horse.getType());
return true;
}
if(option.equals("color") || option.equals("c")){
if(!player.hasPermission("changehorse.get.color")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return true;
}
player.sendMessage(ChatColor.GREEN + "Horse color is: " + horse.getColor());
return true;
}
if(option.equals("style") || option.equals("st")){
if(!player.hasPermission("changehorse.get.style")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return true;
}
player.sendMessage(ChatColor.GREEN + "Horse style is: " + horse.getStyle());
return true;
}
if(option.equals("jumpstrength") || option.equals("js")){
if(!player.hasPermission("changehorse.get.jumpstrength")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return true;
}
player.sendMessage(ChatColor.GREEN + "Horse type is: " + horse.getJumpStrength()*50);
return true;
}
player.sendMessage(getArgs);
return true;
}else if(property.equals("set")){
if(args.length < 2){ //ADD NEW PROPERTIES HERE
player.sendMessage(ChatColor.YELLOW + setArgs);
return true;
}
String option = args[1].toLowerCase();
if(option.equals("type") || option.equals("t")){
if(!player.hasPermission("changehorse.set.type")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return true;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Type options are:");
for(Horse.Variant variant: Horse.Variant.values()){
player.sendMessage(ChatColor.GREEN + " " + variant.toString().toLowerCase());
}
return true;
}else{
for(Horse.Variant variant: Horse.Variant.values()){
if(variant.toString().toLowerCase().replaceAll("_", "").replaceAll("horse", "").equals(args[2].toLowerCase().replaceAll("_", "").replaceAll("horse", ""))){
if(variant != Horse.Variant.HORSE && horse.getInventory().getArmor() != null){
player.sendMessage(ChatColor.RED + "Please remove horse armor before changing horse type.");
return true;
}
horse.setVariant(variant);
player.sendMessage(ChatColor.GREEN + "Horse type set to " + variant.toString());
return true;
}
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguement. For list of Types: /ChangeHorse Type");
return true;
}
}
if(option.equals("color") || option.equals("c")){
if(!player.hasPermission("changehorse.set.color")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return true;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Color options are:");
for(Horse.Color color: Horse.Color.values()){
player.sendMessage(ChatColor.GREEN + " " + color.toString().toLowerCase().replaceAll("_", ""));
}
return true;
}else{
if(horse.getVariant() == Horse.Variant.HORSE){
for(Horse.Color color: Horse.Color.values()){
if(color.toString().toLowerCase().replaceAll("_", "").equals(args[2].toLowerCase())){
horse.setColor(color);
player.sendMessage(ChatColor.GREEN + "Horse color set to " + color.toString());
return true;
}
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguement. For list of Colors: /ChangeHorse Color");
return true;
}else{
player.sendMessage(ChatColor.YELLOW + "Horse colors only apply to normal horses. Change horse to type \"Horse\"");
return true;
}
}
}
if(option.equals("style") || option.equals("st")){
if(!player.hasPermission("changehorse.set.style")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return true;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Style options are:");
for(Horse.Style style: Horse.Style.values()){
player.sendMessage(ChatColor.GREEN + " " + style.toString().toLowerCase());
}
return true;
}else{
if(horse.getVariant() == Horse.Variant.HORSE){
for(Horse.Style style: Horse.Style.values()){
if(style.toString().toLowerCase().replaceAll("_", "").equals(args[2].toLowerCase().replaceAll("_", ""))){
horse.setStyle(style);
player.sendMessage(ChatColor.GREEN + "Horse style set to " + style.toString());
return true;
}
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguement. For list of Styles: /ChangeHorse Style");
return true;
}else{
player.sendMessage(ChatColor.YELLOW + "Horse styles only apply to normal horses. Change horse to type \"Horse\"");
return true;
}
}
}
if(option.equals("jumpstrength") || option.equals("js")){
if(!player.hasPermission("changehorse.set.jumpstrength")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return true;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Valid range for Jump Strength is: 0-100");
return true;
}else{
int num = -1;
try{
num = Integer.parseInt(args[2]);
} catch(NumberFormatException e) {
player.sendMessage(ChatColor.YELLOW + "Invalid number given. " + ChatColor.GREEN + "Valid range for Jump Strength is: 0-100");
return true;
}
if(num > 0 && num <= 100){
double js = (double) num/50;
horse.setJumpStrength(js);
player.sendMessage(ChatColor.GREEN + "Horse jump strength set to " + num);
return true;
}else{
player.sendMessage(ChatColor.YELLOW + "Invalid number given, go get the correct range use /ChangeHorse set JumpStrength");
return true;
}
}
}
if(option.equals("maxhealth") || option.equals("mh")){
if(!player.hasPermission("changehorse.set.maxhealth")){
player.sendMessage(ChatColor.RED + "You don't have permission!");
return true;
}
if(args.length == 2){
player.sendMessage(ChatColor.GREEN + "Valid range for Max Health is: 0-60");
return true;
}else{
int num = -1;
try{
num = Integer.parseInt(args[2]);
} catch(NumberFormatException e) {
player.sendMessage(ChatColor.YELLOW + "Invalid number given." + ChatColor.GREEN +" Valid range for Max Health is: 0-60");
return true;
}
if(num > 0 && num <= 100){
horse.setMaxHealth(num);
player.sendMessage(ChatColor.GREEN + "Horse jump strength set to " + num);
return true;
}else{
player.sendMessage(ChatColor.YELLOW + "Invalid number given, go get the correct range use /ChangeHorse set MaxHealth");
return true;
}
}
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguement. " + ChatColor.GREEN + setArgs);
return true;
}
player.sendMessage(ChatColor.YELLOW + "Invalid arguments. " + mainArgs);
return true;
//end new code
}
|
diff --git a/src/se/team05/view/EditRouteMapView.java b/src/se/team05/view/EditRouteMapView.java
index 363ccc9..c1e34fc 100644
--- a/src/se/team05/view/EditRouteMapView.java
+++ b/src/se/team05/view/EditRouteMapView.java
@@ -1,97 +1,94 @@
package se.team05.view;
import se.team05.R;
import se.team05.overlay.CheckPoint;
import se.team05.overlay.CheckPointOverlay;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
public class EditRouteMapView extends MapView {
private int minTimeForLongClick = 800;
private long timerIfLongClick = 0;
private float xScreenCoordinateForLongClick;
private float yScreenCoordinateForLongClick;
private float tolerance=10;//pixels that your finger can move but still be a long press
private MapActivity mapActivity;
Drawable drawable = this.getResources().getDrawable(R.drawable.green_markerc);
CheckPointOverlay checkPointOverlay;
public EditRouteMapView(Context arg0, String arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public EditRouteMapView(Context arg0, AttributeSet arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public EditRouteMapView(Context arg0, AttributeSet arg1, int arg2) {
super(arg0, arg1, arg2);
// TODO Auto-generated constructor stub
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
timerIfLongClick=event.getEventTime();
xScreenCoordinateForLongClick=event.getX();
yScreenCoordinateForLongClick=event.getY();
break;
case MotionEvent.ACTION_MOVE:
- float dY = event.getY()-yScreenCoordinateForLongClick;
- float dX = event.getX()-xScreenCoordinateForLongClick;
- if(dY<tolerance || dX<tolerance){
+ float dY = Math.abs(event.getY()-yScreenCoordinateForLongClick);
+ float dX = Math.abs(event.getX()-xScreenCoordinateForLongClick);
+ if(dY>tolerance || dX>tolerance){
timerIfLongClick=0;
}
break;
case MotionEvent.ACTION_UP:
long eventTime = event.getEventTime();
long downTime = event.getDownTime();
if (timerIfLongClick==downTime){
if ((eventTime-timerIfLongClick)>minTimeForLongClick){
GeoPoint p = this.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(mapActivity.getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
setCheckPoint(p);
-// CheckPoint checkPoint = new CheckPoint(p, "CheckPoint", 30);
-// checkPointOverlay.addCheckPoint(checkPoint);
-// postInvalidate();
}
break;
}
}
return super.onTouchEvent(event);
}
public void setMapActivity(MapActivity mapActivity) {
this.mapActivity = mapActivity;
checkPointOverlay = new CheckPointOverlay(drawable, mapActivity);
this.getOverlays().add(checkPointOverlay);
}
public void setCheckPoint(GeoPoint geoPoint)
{
CheckPoint checkPoint = new CheckPoint(geoPoint, "CheckPoint", 30);
checkPointOverlay.addCheckPoint(checkPoint);
postInvalidate();
}
}
| false | true | public boolean onTouchEvent(MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
timerIfLongClick=event.getEventTime();
xScreenCoordinateForLongClick=event.getX();
yScreenCoordinateForLongClick=event.getY();
break;
case MotionEvent.ACTION_MOVE:
float dY = event.getY()-yScreenCoordinateForLongClick;
float dX = event.getX()-xScreenCoordinateForLongClick;
if(dY<tolerance || dX<tolerance){
timerIfLongClick=0;
}
break;
case MotionEvent.ACTION_UP:
long eventTime = event.getEventTime();
long downTime = event.getDownTime();
if (timerIfLongClick==downTime){
if ((eventTime-timerIfLongClick)>minTimeForLongClick){
GeoPoint p = this.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(mapActivity.getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
setCheckPoint(p);
// CheckPoint checkPoint = new CheckPoint(p, "CheckPoint", 30);
// checkPointOverlay.addCheckPoint(checkPoint);
// postInvalidate();
}
break;
}
}
return super.onTouchEvent(event);
}
| public boolean onTouchEvent(MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
timerIfLongClick=event.getEventTime();
xScreenCoordinateForLongClick=event.getX();
yScreenCoordinateForLongClick=event.getY();
break;
case MotionEvent.ACTION_MOVE:
float dY = Math.abs(event.getY()-yScreenCoordinateForLongClick);
float dX = Math.abs(event.getX()-xScreenCoordinateForLongClick);
if(dY>tolerance || dX>tolerance){
timerIfLongClick=0;
}
break;
case MotionEvent.ACTION_UP:
long eventTime = event.getEventTime();
long downTime = event.getDownTime();
if (timerIfLongClick==downTime){
if ((eventTime-timerIfLongClick)>minTimeForLongClick){
GeoPoint p = this.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(mapActivity.getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
setCheckPoint(p);
}
break;
}
}
return super.onTouchEvent(event);
}
|
diff --git a/trunk/src/edu/umich/lsa/cscs/gridsweeper/DateUtils.java b/trunk/src/edu/umich/lsa/cscs/gridsweeper/DateUtils.java
index 357ef66..f56e52a 100644
--- a/trunk/src/edu/umich/lsa/cscs/gridsweeper/DateUtils.java
+++ b/trunk/src/edu/umich/lsa/cscs/gridsweeper/DateUtils.java
@@ -1,43 +1,43 @@
package edu.umich.lsa.cscs.gridsweeper;
import java.util.Calendar;
import static java.lang.String.format;
/**
* A utility class with methods for converting date objects
* into strings for use in directory names, etc.
* @author Ed Baskerville
*
*/
public class DateUtils
{
/**
* Converts a {@code java.util.Calendar} object to a string representation
* of the date represented, in the format YYYY-MM-DD.
* @param cal The {@code Calendar} object representing the date.
* @return The string representation of the date.
*/
public static String getDateString(Calendar cal)
{
int year = cal.get(Calendar.YEAR);
- int month = cal.get(Calendar.MONTH);
- int day = cal.get(Calendar.DAY_OF_MONTH) + 1;
+ int month = cal.get(Calendar.MONTH) + 1;
+ int day = cal.get(Calendar.DAY_OF_MONTH);
return format("%d-%02d-%02d", year, month, day);
}
/**
* Converts a @{code java.util.Calendar} object to a string representation
* of the time represented, in the format HH-MM-SS.
* @param cal
* @return The string representation of the time.
*/
public static String getTimeString(Calendar cal)
{
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
return format("%02d-%02d-%02d", hour, minute, second);
}
}
| true | true | public static String getDateString(Calendar cal)
{
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH) + 1;
return format("%d-%02d-%02d", year, month, day);
}
| public static String getDateString(Calendar cal)
{
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
return format("%d-%02d-%02d", year, month, day);
}
|
diff --git a/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/sample/SampleWSBase.java b/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/sample/SampleWSBase.java
index 0d9fdc4e..3bd324e4 100644
--- a/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/sample/SampleWSBase.java
+++ b/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/sample/SampleWSBase.java
@@ -1,122 +1,123 @@
/*******************************************************************************
* Copyright (c) 2010 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
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.ws.ui.bot.test.sample;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.logging.Level;
import javax.xml.namespace.QName;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor;
import org.jboss.tools.ws.ui.bot.test.WSTestBase;
import org.jboss.tools.ws.ui.bot.test.uiutils.actions.NewSampleWSWizardAction;
import org.jboss.tools.ws.ui.bot.test.uiutils.actions.NewSimpleWSWizardAction;
import org.jboss.tools.ws.ui.bot.test.uiutils.wizards.SampleWSWizard;
import org.jboss.tools.ws.ui.bot.test.uiutils.wizards.SimpleWSWizard;
import org.jboss.tools.ws.ui.bot.test.uiutils.wizards.Type;
import org.jboss.tools.ws.ui.bot.test.wsclient.WSClient;
/**
* Test base for all sample Web Services bot tests
* @author jjankovi
*
*/
public class SampleWSBase extends WSTestBase {
protected static final String SOAP_REQUEST = getSoapRequest("<ns1:sayHello xmlns:ns1=\"http://{0}/\"><arg0>{1}</arg0></ns1:sayHello>");
protected static final String SERVER_URL = "localhost:8080";
protected IProject getProject(String project) {
return ResourcesPlugin.getWorkspace().getRoot().getProject(project);
}
protected IFile getDD(String project) {
return getProject(project).getFile("WebContent/WEB-INF/web.xml");
}
protected SWTBotEditor createSampleService(Type type, String project, String name, String pkg, String cls, String appCls) {
SampleWSWizard w = new NewSampleWSWizardAction(type).run();
w.setProjectName(project).setServiceName(name);
w.setPackageName(pkg).setClassName(cls);
if (type == Type.REST) {
w.setApplicationClassName(appCls);
w.addRESTEasyLibraryFromRuntime();
}
w.finish();
util.waitForNonIgnoredJobs();
return bot.editorByTitle(cls + ".java");
}
protected SWTBotEditor createSimpleService(Type type, String project, String name, String pkg, String cls, String appCls) {
SimpleWSWizard w = new NewSimpleWSWizardAction(type).run();
w.setProjectName(project).setServiceName(name);
w.setPackageName(pkg).setClassName(cls);
if (type == Type.REST) {
w.addRESTEasyLibraryFromRuntime();
w.setApplicationClassName(appCls);
}
w.finish();
util.waitForNonIgnoredJobs();
return bot.editorByTitle(cls + ".java");
}
protected void checkService(Type type, String project, String svcName, String svcPkg, String svcClass, String msgContent, String appCls) {
SWTBotEditor ed = bot.editorByTitle(svcClass + ".java");
ed.show();
String code = ed.toTextEditor().getText();
assertContains("package " + svcPkg + ";", code);
String dd = resourceHelper.readFile(getDD(project));
switch (type) {
case REST:
assertContains("@Path(\"/" + svcName + "\")", code);
assertContains("@GET()", code);
assertContains("@Produces(\"text/plain\")", code);
assertContains("<servlet-name>Resteasy</servlet-name>", dd);
assertContains("<param-value>" + svcPkg + "." + appCls + "</param-value>", dd);
break;
case SOAP:
assertContains("<servlet-name>" + svcName + "</servlet-name>", dd);
break;
}
+ deploymentHelper.removeProjectFromServer(project);
deploymentHelper.runProject(project);
switch (type) {
case REST:
try {
URL u = new URL("http://" + SERVER_URL + "/" + project + "/" + svcName);
String s = resourceHelper.readStream(u.openConnection().getInputStream());
assertEquals(msgContent, s);
} catch (MalformedURLException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
}
break;
case SOAP:
try {
WSClient c = new WSClient(new URL("http://" + SERVER_URL + "/" + project + "/" + svcName),
new QName("http://" + svcPkg + "/", svcClass + "Service"),
new QName("http://" + svcPkg + "/", svcClass + "Port"));
assertContains("Hello " + msgContent + "!", c.callService(MessageFormat.format(SOAP_REQUEST, svcPkg, msgContent)));
} catch (MalformedURLException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
}
break;
}
}
}
| true | true | protected void checkService(Type type, String project, String svcName, String svcPkg, String svcClass, String msgContent, String appCls) {
SWTBotEditor ed = bot.editorByTitle(svcClass + ".java");
ed.show();
String code = ed.toTextEditor().getText();
assertContains("package " + svcPkg + ";", code);
String dd = resourceHelper.readFile(getDD(project));
switch (type) {
case REST:
assertContains("@Path(\"/" + svcName + "\")", code);
assertContains("@GET()", code);
assertContains("@Produces(\"text/plain\")", code);
assertContains("<servlet-name>Resteasy</servlet-name>", dd);
assertContains("<param-value>" + svcPkg + "." + appCls + "</param-value>", dd);
break;
case SOAP:
assertContains("<servlet-name>" + svcName + "</servlet-name>", dd);
break;
}
deploymentHelper.runProject(project);
switch (type) {
case REST:
try {
URL u = new URL("http://" + SERVER_URL + "/" + project + "/" + svcName);
String s = resourceHelper.readStream(u.openConnection().getInputStream());
assertEquals(msgContent, s);
} catch (MalformedURLException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
}
break;
case SOAP:
try {
WSClient c = new WSClient(new URL("http://" + SERVER_URL + "/" + project + "/" + svcName),
new QName("http://" + svcPkg + "/", svcClass + "Service"),
new QName("http://" + svcPkg + "/", svcClass + "Port"));
assertContains("Hello " + msgContent + "!", c.callService(MessageFormat.format(SOAP_REQUEST, svcPkg, msgContent)));
} catch (MalformedURLException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
}
break;
}
}
| protected void checkService(Type type, String project, String svcName, String svcPkg, String svcClass, String msgContent, String appCls) {
SWTBotEditor ed = bot.editorByTitle(svcClass + ".java");
ed.show();
String code = ed.toTextEditor().getText();
assertContains("package " + svcPkg + ";", code);
String dd = resourceHelper.readFile(getDD(project));
switch (type) {
case REST:
assertContains("@Path(\"/" + svcName + "\")", code);
assertContains("@GET()", code);
assertContains("@Produces(\"text/plain\")", code);
assertContains("<servlet-name>Resteasy</servlet-name>", dd);
assertContains("<param-value>" + svcPkg + "." + appCls + "</param-value>", dd);
break;
case SOAP:
assertContains("<servlet-name>" + svcName + "</servlet-name>", dd);
break;
}
deploymentHelper.removeProjectFromServer(project);
deploymentHelper.runProject(project);
switch (type) {
case REST:
try {
URL u = new URL("http://" + SERVER_URL + "/" + project + "/" + svcName);
String s = resourceHelper.readStream(u.openConnection().getInputStream());
assertEquals(msgContent, s);
} catch (MalformedURLException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
} catch (IOException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
}
break;
case SOAP:
try {
WSClient c = new WSClient(new URL("http://" + SERVER_URL + "/" + project + "/" + svcName),
new QName("http://" + svcPkg + "/", svcClass + "Service"),
new QName("http://" + svcPkg + "/", svcClass + "Port"));
assertContains("Hello " + msgContent + "!", c.callService(MessageFormat.format(SOAP_REQUEST, svcPkg, msgContent)));
} catch (MalformedURLException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
}
break;
}
}
|
diff --git a/src/com/github/andlyticsproject/DetailsActivity.java b/src/com/github/andlyticsproject/DetailsActivity.java
index 1b63b78..8fc1f30 100755
--- a/src/com/github/andlyticsproject/DetailsActivity.java
+++ b/src/com/github/andlyticsproject/DetailsActivity.java
@@ -1,295 +1,299 @@
package com.github.andlyticsproject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.view.MenuItem;
import com.github.andlyticsproject.console.v2.DevConsoleRegistry;
import com.github.andlyticsproject.console.v2.DevConsoleV2;
import com.github.andlyticsproject.db.AndlyticsDb;
import com.github.andlyticsproject.model.Comment;
import com.github.andlyticsproject.util.DetachableAsyncTask;
import com.github.andlyticsproject.util.Utils;
public class DetailsActivity extends BaseActivity implements DetailedStatsActivity, CommentReplier,
ChartSwitcher {
private static final String TAG = DetailsActivity.class.getSimpleName();
public static final String EXTRA_CHART_SET = "com.github.andlyticsproject.chartset";
public static final String EXTRA_CHART_NAME = "com.github.andlyticsproject.chartname";
private static final String REPLY_DIALOG_FRAGMENT = "reply_dialog_fragment";
private static final String[] TAB_TAGS = { "comments_tab", "ratings_tab", "downloads_tab",
"revenue_tab", "admob_tab" };
public static String EXTRA_SELECTED_TAB_IDX = "selectedTabIdx";
public static int TAB_IDX_COMMENTS = 0;
public static int TAB_IDX_RATINGS = 1;
public static int TAB_IDX_DOWNLOADS = 2;
public static int TAB_IDX_REVENUE = 3;
public static int TAB_IDX_ADMOB = 4;
public static String EXTRA_HAS_REVENUE = "com.github.andlyticsproject.hasRevenue";
private String appName;
private boolean hasRevenue;
public static class TabListener<T extends StatsView<?>> implements ActionBar.TabListener {
private Fragment fragment;
private DetailsActivity activity;
private String tag;
private Class<T> clazz;
public TabListener(DetailsActivity activity, String tag, Class<T> clz) {
this.activity = activity;
this.tag = tag;
this.clazz = clz;
fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (fragment == null) {
fragment = Fragment.instantiate(activity, clazz.getName());
ft.add(android.R.id.content, fragment, tag);
} else {
ft.attach(fragment);
}
activity.setTitle(((StatsView<?>) fragment).getTitle());
if (activity.appName != null) {
activity.getSupportActionBar().setSubtitle(activity.appName);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (fragment != null) {
ft.detach(fragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate()");
// FragmentManager.enableDebugLogging(true);
super.onCreate(savedInstanceState);
appName = getDbAdapter().getAppName(packageName);
hasRevenue = getIntent().getBooleanExtra(EXTRA_HAS_REVENUE, true);
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab = actionBar
.newTab()
.setText(R.string.comments)
.setTabListener(
new TabListener<CommentsFragment>(this, "comments_tab",
CommentsFragment.class));
actionBar.addTab(tab);
tab = actionBar
.newTab()
.setText(R.string.ratings)
.setTabListener(
new TabListener<RatingsFragment>(this, "ratings_tab", RatingsFragment.class));
actionBar.addTab(tab);
tab = actionBar
.newTab()
.setText(R.string.downloads)
.setTabListener(
new TabListener<DownloadsFragment>(this, "downloads_tab",
DownloadsFragment.class));
actionBar.addTab(tab);
if (hasRevenue) {
tab = actionBar
.newTab()
.setText(R.string.revenue)
.setTabListener(
new TabListener<RevenueFragment>(this, "revenue_tab",
RevenueFragment.class));
actionBar.addTab(tab);
}
// Check if AdMob is configured for this app
String[] admobDetails = AndlyticsDb.getInstance(this).getAdmobDetails(packageName);
boolean admobConfigured = admobDetails != null;
if (admobConfigured || !Preferences.getHideAdmobForUnconfiguredApps(this)) {
tab = actionBar
.newTab()
.setText(R.string.admob)
.setTabListener(
new TabListener<AdmobFragment>(this, "admob_tab", AdmobFragment.class));
actionBar.addTab(tab);
}
int selectedTabIdx = getIntent().getExtras().getInt(EXTRA_SELECTED_TAB_IDX, 0);
+ // FIXME This is a hack to select AdMob in the case that the revenue tab isn't enabled
+ if (!hasRevenue && selectedTabIdx == TAB_IDX_ADMOB) {
+ selectedTabIdx = TAB_IDX_REVENUE;
+ }
if (savedInstanceState != null) {
selectedTabIdx = savedInstanceState.getInt(EXTRA_SELECTED_TAB_IDX, 0);
}
if (selectedTabIdx < actionBar.getTabCount()) {
actionBar.setSelectedNavigationItem(selectedTabIdx);
} else {
actionBar.setSelectedNavigationItem(0);
}
}
@Override
protected void onResume() {
super.onResume();
}
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putInt(EXTRA_SELECTED_TAB_IDX, getSupportActionBar().getSelectedNavigationIndex());
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// XXX finish?!
finish();
overridePendingTransition(R.anim.activity_prev_in, R.anim.activity_prev_out);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void showReplyDialog(Comment comment) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag(REPLY_DIALOG_FRAGMENT);
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
ReplyDialog replyDialog = new ReplyDialog();
Bundle args = new Bundle();
args.putString(ReplyDialog.ARG_UNIQUE_ID, comment.getUniqueId());
args.putString(ReplyDialog.ARG_REPLY, comment.getReply() == null ? "" : comment.getReply()
.getText());
replyDialog.setArguments(args);
replyDialog.show(ft, REPLY_DIALOG_FRAGMENT);
}
public void hideReplyDialog() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment dialog = getSupportFragmentManager().findFragmentByTag(REPLY_DIALOG_FRAGMENT);
if (dialog != null) {
ft.remove(dialog);
ft.commit();
}
}
public void replyToComment(final String commentUniqueId, final String replyText) {
Utils.execute(new DetachableAsyncTask<Void, Void, Comment, DetailsActivity>(this) {
Exception error;
@Override
protected void onPreExecute() {
if (activity == null) {
return;
}
activity.refreshStarted();
}
@Override
protected Comment doInBackground(Void... arg0) {
if (activity == null) {
return null;
}
try {
DevConsoleV2 devConsole = DevConsoleRegistry.getInstance().get(accountName);
return devConsole.replyToComment(DetailsActivity.this, packageName,
developerId, commentUniqueId, replyText);
} catch (Exception e) {
error = e;
return null;
}
}
@Override
protected void onPostExecute(Comment reply) {
if (activity == null) {
return;
}
activity.refreshFinished();
if (error != null) {
Log.e(TAG, "Error replying to comment: " + error.getMessage(), error);
activity.hideReplyDialog();
activity.handleUserVisibleException(error);
return;
}
Toast.makeText(activity, R.string.reply_sent, Toast.LENGTH_LONG).show();
CommentsFragment commentsFargment = (CommentsFragment) getSupportFragmentManager()
.findFragmentByTag("comments_tab");
if (commentsFargment != null) {
commentsFargment.refreshComments();
}
}
});
}
@Override
public void setCurrentChart(int currentPage, int column) {
String tabTag = TAB_TAGS[getSupportActionBar().getSelectedNavigationIndex()];
StatsView<?> chartFargment = (StatsView<?>) getSupportFragmentManager().findFragmentByTag(
tabTag);
if (chartFargment != null) {
chartFargment.setCurrentChart(currentPage, column);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GOOGLE_PLAY_SERVICES) {
if (resultCode != Activity.RESULT_OK) {
checkGooglePlayServicesAvailable();
}
} else if (requestCode == REQUEST_AUTHORIZATION) {
if (resultCode == Activity.RESULT_OK) {
if (getSupportActionBar().getSelectedNavigationIndex() == TAB_IDX_ADMOB) {
String tabTag = TAB_TAGS[getSupportActionBar().getSelectedNavigationIndex()];
AdmobFragment admobFragment = (AdmobFragment) getSupportFragmentManager()
.findFragmentByTag(tabTag);
admobFragment.loadAdUnits();
}
} else {
Toast.makeText(this, getString(R.string.account_authorization_denied, accountName),
Toast.LENGTH_LONG).show();
}
}
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate()");
// FragmentManager.enableDebugLogging(true);
super.onCreate(savedInstanceState);
appName = getDbAdapter().getAppName(packageName);
hasRevenue = getIntent().getBooleanExtra(EXTRA_HAS_REVENUE, true);
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab = actionBar
.newTab()
.setText(R.string.comments)
.setTabListener(
new TabListener<CommentsFragment>(this, "comments_tab",
CommentsFragment.class));
actionBar.addTab(tab);
tab = actionBar
.newTab()
.setText(R.string.ratings)
.setTabListener(
new TabListener<RatingsFragment>(this, "ratings_tab", RatingsFragment.class));
actionBar.addTab(tab);
tab = actionBar
.newTab()
.setText(R.string.downloads)
.setTabListener(
new TabListener<DownloadsFragment>(this, "downloads_tab",
DownloadsFragment.class));
actionBar.addTab(tab);
if (hasRevenue) {
tab = actionBar
.newTab()
.setText(R.string.revenue)
.setTabListener(
new TabListener<RevenueFragment>(this, "revenue_tab",
RevenueFragment.class));
actionBar.addTab(tab);
}
// Check if AdMob is configured for this app
String[] admobDetails = AndlyticsDb.getInstance(this).getAdmobDetails(packageName);
boolean admobConfigured = admobDetails != null;
if (admobConfigured || !Preferences.getHideAdmobForUnconfiguredApps(this)) {
tab = actionBar
.newTab()
.setText(R.string.admob)
.setTabListener(
new TabListener<AdmobFragment>(this, "admob_tab", AdmobFragment.class));
actionBar.addTab(tab);
}
int selectedTabIdx = getIntent().getExtras().getInt(EXTRA_SELECTED_TAB_IDX, 0);
if (savedInstanceState != null) {
selectedTabIdx = savedInstanceState.getInt(EXTRA_SELECTED_TAB_IDX, 0);
}
if (selectedTabIdx < actionBar.getTabCount()) {
actionBar.setSelectedNavigationItem(selectedTabIdx);
} else {
actionBar.setSelectedNavigationItem(0);
}
}
| protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate()");
// FragmentManager.enableDebugLogging(true);
super.onCreate(savedInstanceState);
appName = getDbAdapter().getAppName(packageName);
hasRevenue = getIntent().getBooleanExtra(EXTRA_HAS_REVENUE, true);
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab = actionBar
.newTab()
.setText(R.string.comments)
.setTabListener(
new TabListener<CommentsFragment>(this, "comments_tab",
CommentsFragment.class));
actionBar.addTab(tab);
tab = actionBar
.newTab()
.setText(R.string.ratings)
.setTabListener(
new TabListener<RatingsFragment>(this, "ratings_tab", RatingsFragment.class));
actionBar.addTab(tab);
tab = actionBar
.newTab()
.setText(R.string.downloads)
.setTabListener(
new TabListener<DownloadsFragment>(this, "downloads_tab",
DownloadsFragment.class));
actionBar.addTab(tab);
if (hasRevenue) {
tab = actionBar
.newTab()
.setText(R.string.revenue)
.setTabListener(
new TabListener<RevenueFragment>(this, "revenue_tab",
RevenueFragment.class));
actionBar.addTab(tab);
}
// Check if AdMob is configured for this app
String[] admobDetails = AndlyticsDb.getInstance(this).getAdmobDetails(packageName);
boolean admobConfigured = admobDetails != null;
if (admobConfigured || !Preferences.getHideAdmobForUnconfiguredApps(this)) {
tab = actionBar
.newTab()
.setText(R.string.admob)
.setTabListener(
new TabListener<AdmobFragment>(this, "admob_tab", AdmobFragment.class));
actionBar.addTab(tab);
}
int selectedTabIdx = getIntent().getExtras().getInt(EXTRA_SELECTED_TAB_IDX, 0);
// FIXME This is a hack to select AdMob in the case that the revenue tab isn't enabled
if (!hasRevenue && selectedTabIdx == TAB_IDX_ADMOB) {
selectedTabIdx = TAB_IDX_REVENUE;
}
if (savedInstanceState != null) {
selectedTabIdx = savedInstanceState.getInt(EXTRA_SELECTED_TAB_IDX, 0);
}
if (selectedTabIdx < actionBar.getTabCount()) {
actionBar.setSelectedNavigationItem(selectedTabIdx);
} else {
actionBar.setSelectedNavigationItem(0);
}
}
|
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgGetProperties.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgGetProperties.java
index 46bdb8331..098b3bb0d 100644
--- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgGetProperties.java
+++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/wc2/ng/SvnNgGetProperties.java
@@ -1,68 +1,68 @@
package org.tmatesoft.svn.core.internal.wc2.ng;
import org.tmatesoft.svn.core.SVNDepth;
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.internal.wc.SVNErrorManager;
import org.tmatesoft.svn.core.internal.wc17.SVNWCContext;
import org.tmatesoft.svn.core.internal.wc17.db.SVNWCDb;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc2.SvnGetProperties;
import org.tmatesoft.svn.util.SVNLogType;
public class SvnNgGetProperties extends SvnNgOperationRunner<SVNProperties, SvnGetProperties> {
@Override
protected SVNProperties run(SVNWCContext context) throws SVNException {
boolean pristine = getOperation().getRevision() == SVNRevision.COMMITTED || getOperation().getRevision() == SVNRevision.BASE;
SVNNodeKind kind = context.readKind(getFirstTarget(), false);
if (kind == SVNNodeKind.UNKNOWN || kind == SVNNodeKind.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNVERSIONED_RESOURCE, "''{0}'' is not under version control", getFirstTarget());
SVNErrorManager.error(err, SVNLogType.WC);
}
if (kind == SVNNodeKind.DIR) {
if (getOperation().getDepth() == SVNDepth.EMPTY) {
- if (matchesChangelist(getFirstTarget())) {
+ if (!matchesChangelist(getFirstTarget())) {
return getOperation().first();
}
SVNProperties properties = null;
if (pristine) {
properties = context.getDb().readPristineProperties(getFirstTarget());
} else {
properties = context.getDb().readProperties(getFirstTarget());
}
if (properties != null && !properties.isEmpty()) {
getOperation().receive(getOperation().getFirstTarget(), properties);
}
} else if (matchesChangelist(getFirstTarget())) {
SVNWCDb db = (SVNWCDb) context.getDb();
db.readPropertiesRecursively(
getFirstTarget(),
getOperation().getDepth(),
false,
pristine,
getOperation().getApplicableChangelists(),
getOperation());
}
} else {
SVNProperties properties = null;
if (pristine) {
properties = context.getDb().readPristineProperties(getFirstTarget());
} else {
if (!context.isNodeStatusDeleted(getFirstTarget())) {
properties = context.getDb().readProperties(getFirstTarget());
}
}
if (properties != null && !properties.isEmpty()) {
getOperation().receive(getOperation().getFirstTarget(), properties);
}
}
return getOperation().first();
}
}
| true | true | protected SVNProperties run(SVNWCContext context) throws SVNException {
boolean pristine = getOperation().getRevision() == SVNRevision.COMMITTED || getOperation().getRevision() == SVNRevision.BASE;
SVNNodeKind kind = context.readKind(getFirstTarget(), false);
if (kind == SVNNodeKind.UNKNOWN || kind == SVNNodeKind.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNVERSIONED_RESOURCE, "''{0}'' is not under version control", getFirstTarget());
SVNErrorManager.error(err, SVNLogType.WC);
}
if (kind == SVNNodeKind.DIR) {
if (getOperation().getDepth() == SVNDepth.EMPTY) {
if (matchesChangelist(getFirstTarget())) {
return getOperation().first();
}
SVNProperties properties = null;
if (pristine) {
properties = context.getDb().readPristineProperties(getFirstTarget());
} else {
properties = context.getDb().readProperties(getFirstTarget());
}
if (properties != null && !properties.isEmpty()) {
getOperation().receive(getOperation().getFirstTarget(), properties);
}
} else if (matchesChangelist(getFirstTarget())) {
SVNWCDb db = (SVNWCDb) context.getDb();
db.readPropertiesRecursively(
getFirstTarget(),
getOperation().getDepth(),
false,
pristine,
getOperation().getApplicableChangelists(),
getOperation());
}
} else {
SVNProperties properties = null;
if (pristine) {
properties = context.getDb().readPristineProperties(getFirstTarget());
} else {
if (!context.isNodeStatusDeleted(getFirstTarget())) {
properties = context.getDb().readProperties(getFirstTarget());
}
}
if (properties != null && !properties.isEmpty()) {
getOperation().receive(getOperation().getFirstTarget(), properties);
}
}
return getOperation().first();
}
| protected SVNProperties run(SVNWCContext context) throws SVNException {
boolean pristine = getOperation().getRevision() == SVNRevision.COMMITTED || getOperation().getRevision() == SVNRevision.BASE;
SVNNodeKind kind = context.readKind(getFirstTarget(), false);
if (kind == SVNNodeKind.UNKNOWN || kind == SVNNodeKind.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.UNVERSIONED_RESOURCE, "''{0}'' is not under version control", getFirstTarget());
SVNErrorManager.error(err, SVNLogType.WC);
}
if (kind == SVNNodeKind.DIR) {
if (getOperation().getDepth() == SVNDepth.EMPTY) {
if (!matchesChangelist(getFirstTarget())) {
return getOperation().first();
}
SVNProperties properties = null;
if (pristine) {
properties = context.getDb().readPristineProperties(getFirstTarget());
} else {
properties = context.getDb().readProperties(getFirstTarget());
}
if (properties != null && !properties.isEmpty()) {
getOperation().receive(getOperation().getFirstTarget(), properties);
}
} else if (matchesChangelist(getFirstTarget())) {
SVNWCDb db = (SVNWCDb) context.getDb();
db.readPropertiesRecursively(
getFirstTarget(),
getOperation().getDepth(),
false,
pristine,
getOperation().getApplicableChangelists(),
getOperation());
}
} else {
SVNProperties properties = null;
if (pristine) {
properties = context.getDb().readPristineProperties(getFirstTarget());
} else {
if (!context.isNodeStatusDeleted(getFirstTarget())) {
properties = context.getDb().readProperties(getFirstTarget());
}
}
if (properties != null && !properties.isEmpty()) {
getOperation().receive(getOperation().getFirstTarget(), properties);
}
}
return getOperation().first();
}
|
diff --git a/src/com/android/gallery3d/filtershow/FilterShowActivity.java b/src/com/android/gallery3d/filtershow/FilterShowActivity.java
index 6e88d8639..d482d16ed 100644
--- a/src/com/android/gallery3d/filtershow/FilterShowActivity.java
+++ b/src/com/android/gallery3d/filtershow/FilterShowActivity.java
@@ -1,1057 +1,1058 @@
/*
* 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.gallery3d.filtershow;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ShareActionProvider;
import android.widget.ShareActionProvider.OnShareTargetSelectedListener;
import android.widget.Toast;
import com.android.gallery3d.R;
import com.android.gallery3d.data.LocalAlbum;
import com.android.gallery3d.filtershow.cache.CachingPipeline;
import com.android.gallery3d.filtershow.cache.FilteringPipeline;
import com.android.gallery3d.filtershow.cache.ImageLoader;
import com.android.gallery3d.filtershow.category.*;
import com.android.gallery3d.filtershow.crop.CropExtras;
import com.android.gallery3d.filtershow.editors.*;
import com.android.gallery3d.filtershow.filters.*;
import com.android.gallery3d.filtershow.imageshow.GeometryMetadata;
import com.android.gallery3d.filtershow.imageshow.ImageCrop;
import com.android.gallery3d.filtershow.imageshow.ImageShow;
import com.android.gallery3d.filtershow.imageshow.MasterImage;
import com.android.gallery3d.filtershow.presets.ImagePreset;
import com.android.gallery3d.filtershow.provider.SharedImageProvider;
import com.android.gallery3d.filtershow.state.StateAdapter;
import com.android.gallery3d.filtershow.tools.BitmapTask;
import com.android.gallery3d.filtershow.tools.SaveCopyTask;
import com.android.gallery3d.filtershow.ui.FramedTextButton;
import com.android.gallery3d.filtershow.ui.Spline;
import com.android.gallery3d.util.GalleryUtils;
import com.android.photos.data.GalleryBitmapPool;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Vector;
public class FilterShowActivity extends FragmentActivity implements OnItemClickListener,
OnShareTargetSelectedListener {
// fields for supporting crop action
public static final String CROP_ACTION = "com.android.camera.action.CROP";
private CropExtras mCropExtras = null;
private String mAction = "";
MasterImage mMasterImage = null;
private static final long LIMIT_SUPPORTS_HIGHRES = 134217728; // 128Mb
public static final String TINY_PLANET_ACTION = "com.android.camera.action.TINY_PLANET";
public static final String LAUNCH_FULLSCREEN = "launch-fullscreen";
public static final int MAX_BMAP_IN_INTENT = 990000;
private ImageLoader mImageLoader = null;
private ImageShow mImageShow = null;
private View mSaveButton = null;
private EditorPlaceHolder mEditorPlaceHolder = new EditorPlaceHolder(this);
private static final int SELECT_PICTURE = 1;
private static final String LOGTAG = "FilterShowActivity";
protected static final boolean ANIMATE_PANELS = true;
private boolean mShowingTinyPlanet = false;
private boolean mShowingImageStatePanel = false;
private final Vector<ImageShow> mImageViews = new Vector<ImageShow>();
private ShareActionProvider mShareActionProvider;
private File mSharedOutputFile = null;
private boolean mSharingImage = false;
private WeakReference<ProgressDialog> mSavingProgressDialog;
private LoadBitmapTask mLoadBitmapTask;
private boolean mLoading = true;
private CategoryAdapter mCategoryLooksAdapter = null;
private CategoryAdapter mCategoryBordersAdapter = null;
private CategoryAdapter mCategoryGeometryAdapter = null;
private CategoryAdapter mCategoryFiltersAdapter = null;
private int mCurrentPanel = MainPanel.LOOKS;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean onlyUsePortrait = getResources().getBoolean(R.bool.only_use_portrait);
if (onlyUsePortrait) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
MasterImage.setMaster(mMasterImage);
clearGalleryBitmapPool();
CachingPipeline.createRenderscriptContext(this);
setupMasterImage();
setDefaultValues();
fillEditors();
loadXML();
loadMainPanel();
setDefaultPreset();
processIntent();
}
public boolean isShowingImageStatePanel() {
return mShowingImageStatePanel;
}
public void loadMainPanel() {
if (findViewById(R.id.main_panel_container) == null) {
return;
}
MainPanel panel = new MainPanel();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.main_panel_container, panel, MainPanel.FRAGMENT_TAG);
transaction.commit();
}
public void loadEditorPanel(FilterRepresentation representation,
final Editor currentEditor) {
if (representation.getEditorId() == ImageOnlyEditor.ID) {
currentEditor.getImageShow().select();
currentEditor.reflectCurrentFilter();
return;
}
final int currentId = currentEditor.getID();
Runnable showEditor = new Runnable() {
@Override
public void run() {
EditorPanel panel = new EditorPanel();
panel.setEditor(currentId);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.remove(getSupportFragmentManager().findFragmentByTag(MainPanel.FRAGMENT_TAG));
transaction.replace(R.id.main_panel_container, panel, MainPanel.FRAGMENT_TAG);
transaction.commit();
}
};
Fragment main = getSupportFragmentManager().findFragmentByTag(MainPanel.FRAGMENT_TAG);
boolean doAnimation = false;
if (mShowingImageStatePanel
&& getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
doAnimation = true;
}
if (doAnimation && main != null && main instanceof MainPanel) {
MainPanel mainPanel = (MainPanel) main;
View container = mainPanel.getView().findViewById(R.id.category_panel_container);
View bottom = mainPanel.getView().findViewById(R.id.bottom_panel);
int panelHeight = container.getHeight() + bottom.getHeight();
mainPanel.getView().animate().translationY(panelHeight).withEndAction(showEditor).start();
} else {
showEditor.run();
}
}
private void loadXML() {
setContentView(R.layout.filtershow_activity);
ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setCustomView(R.layout.filtershow_actionbar);
mSaveButton = actionBar.getCustomView();
mSaveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
saveImage();
}
});
mImageShow = (ImageShow) findViewById(R.id.imageShow);
mImageViews.add(mImageShow);
setupEditors();
mEditorPlaceHolder.hide();
mImageShow.setImageLoader(mImageLoader);
fillFx();
fillBorders();
fillGeometry();
fillFilters();
setupStatePanel();
}
public void setupStatePanel() {
mImageLoader.setAdapter(mMasterImage.getHistory());
}
private void fillFilters() {
Vector<FilterRepresentation> filtersRepresentations = new Vector<FilterRepresentation>();
FiltersManager filtersManager = FiltersManager.getManager();
filtersManager.addEffects(filtersRepresentations);
mCategoryFiltersAdapter = new CategoryAdapter(this);
for (FilterRepresentation representation : filtersRepresentations) {
if (representation.getTextId() != 0) {
representation.setName(getString(representation.getTextId()));
}
mCategoryFiltersAdapter.add(new Action(this, representation));
}
}
private void fillGeometry() {
Vector<FilterRepresentation> filtersRepresentations = new Vector<FilterRepresentation>();
FiltersManager filtersManager = FiltersManager.getManager();
GeometryMetadata geo = new GeometryMetadata();
int[] editorsId = geo.getEditorIds();
for (int i = 0; i < editorsId.length; i++) {
int editorId = editorsId[i];
GeometryMetadata geometry = new GeometryMetadata(geo);
geometry.setEditorId(editorId);
EditorInfo editorInfo = (EditorInfo) mEditorPlaceHolder.getEditor(editorId);
geometry.setTextId(editorInfo.getTextId());
geometry.setOverlayId(editorInfo.getOverlayId());
geometry.setOverlayOnly(editorInfo.getOverlayOnly());
if (geometry.getTextId() != 0) {
geometry.setName(getString(geometry.getTextId()));
}
filtersRepresentations.add(geometry);
}
filtersManager.addTools(filtersRepresentations);
mCategoryGeometryAdapter = new CategoryAdapter(this);
for (FilterRepresentation representation : filtersRepresentations) {
mCategoryGeometryAdapter.add(new Action(this, representation));
}
}
private void processIntent() {
Intent intent = getIntent();
if (intent.getBooleanExtra(LAUNCH_FULLSCREEN, false)) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
mAction = intent.getAction();
if (intent.getData() != null) {
startLoadBitmap(intent.getData());
} else {
pickImage();
}
}
private void setupEditors() {
mEditorPlaceHolder.setContainer((FrameLayout) findViewById(R.id.editorContainer));
EditorManager.addEditors(mEditorPlaceHolder);
mEditorPlaceHolder.setOldViews(mImageViews);
mEditorPlaceHolder.setImageLoader(mImageLoader);
}
private void fillEditors() {
mEditorPlaceHolder.addEditor(new EditorDraw());
mEditorPlaceHolder.addEditor(new BasicEditor());
mEditorPlaceHolder.addEditor(new ImageOnlyEditor());
mEditorPlaceHolder.addEditor(new EditorTinyPlanet());
mEditorPlaceHolder.addEditor(new EditorRedEye());
mEditorPlaceHolder.addEditor(new EditorCrop());
mEditorPlaceHolder.addEditor(new EditorFlip());
mEditorPlaceHolder.addEditor(new EditorRotate());
mEditorPlaceHolder.addEditor(new EditorStraighten());
}
private void setDefaultValues() {
ImageFilter.setActivityForMemoryToasts(this);
Resources res = getResources();
FiltersManager.setResources(res);
CategoryView.setMargin((int) getPixelsFromDip(8));
CategoryView.setTextSize((int) getPixelsFromDip(16));
ImageShow.setDefaultBackgroundColor(res.getColor(R.color.background_screen));
// TODO: get those values from XML.
FramedTextButton.setTextSize((int) getPixelsFromDip(14));
FramedTextButton.setTrianglePadding((int) getPixelsFromDip(4));
FramedTextButton.setTriangleSize((int) getPixelsFromDip(10));
ImageShow.setTextSize((int) getPixelsFromDip(12));
ImageShow.setTextPadding((int) getPixelsFromDip(10));
ImageShow.setOriginalTextMargin((int) getPixelsFromDip(4));
ImageShow.setOriginalTextSize((int) getPixelsFromDip(18));
ImageShow.setOriginalText(res.getString(R.string.original_picture_text));
Drawable curveHandle = res.getDrawable(R.drawable.camera_crop);
int curveHandleSize = (int) res.getDimension(R.dimen.crop_indicator_size);
Spline.setCurveHandle(curveHandle, curveHandleSize);
Spline.setCurveWidth((int) getPixelsFromDip(3));
ImageCrop.setAspectTextSize((int) getPixelsFromDip(18));
ImageCrop.setTouchTolerance((int) getPixelsFromDip(25));
ImageCrop.setMinCropSize((int) getPixelsFromDip(55));
}
private void startLoadBitmap(Uri uri) {
mLoading = true;
final View loading = findViewById(R.id.loading);
final View imageShow = findViewById(R.id.imageShow);
imageShow.setVisibility(View.INVISIBLE);
loading.setVisibility(View.VISIBLE);
mShowingTinyPlanet = false;
mLoadBitmapTask = new LoadBitmapTask();
mLoadBitmapTask.execute(uri);
}
private void fillBorders() {
Vector<FilterRepresentation> borders = new Vector<FilterRepresentation>();
// The "no border" implementation
borders.add(new FilterImageBorderRepresentation(0));
// Google-build borders
FiltersManager.getManager().addBorders(this, borders);
for (int i = 0; i < borders.size(); i++) {
FilterRepresentation filter = borders.elementAt(i);
if (i == 0) {
filter.setName(getString(R.string.none));
}
}
mCategoryBordersAdapter = new CategoryAdapter(this);
for (FilterRepresentation representation : borders) {
if (representation.getTextId() != 0) {
representation.setName(getString(representation.getTextId()));
}
mCategoryBordersAdapter.add(new Action(this, representation, Action.FULL_VIEW));
}
}
public CategoryAdapter getCategoryLooksAdapter() {
return mCategoryLooksAdapter;
}
public CategoryAdapter getCategoryBordersAdapter() {
return mCategoryBordersAdapter;
}
public CategoryAdapter getCategoryGeometryAdapter() {
return mCategoryGeometryAdapter;
}
public CategoryAdapter getCategoryFiltersAdapter() {
return mCategoryFiltersAdapter;
}
public void removeFilterRepresentation(FilterRepresentation filterRepresentation) {
if (filterRepresentation == null) {
return;
}
ImagePreset oldPreset = MasterImage.getImage().getPreset();
ImagePreset copy = new ImagePreset(oldPreset);
copy.removeFilter(filterRepresentation);
MasterImage.getImage().setPreset(copy, true);
if (MasterImage.getImage().getCurrentFilterRepresentation() == filterRepresentation) {
FilterRepresentation lastRepresentation = copy.getLastRepresentation();
MasterImage.getImage().setCurrentFilterRepresentation(lastRepresentation);
}
}
public void useFilterRepresentation(FilterRepresentation filterRepresentation) {
if (filterRepresentation == null) {
return;
}
if (MasterImage.getImage().getCurrentFilterRepresentation() == filterRepresentation) {
return;
}
ImagePreset oldPreset = MasterImage.getImage().getPreset();
ImagePreset copy = new ImagePreset(oldPreset);
FilterRepresentation representation = copy.getRepresentation(filterRepresentation);
if (representation == null) {
copy.addFilter(filterRepresentation);
} else {
if (filterRepresentation.allowsMultipleInstances()) {
representation.updateTempParametersFrom(filterRepresentation);
copy.setHistoryName(filterRepresentation.getName());
representation.synchronizeRepresentation();
}
filterRepresentation = representation;
}
MasterImage.getImage().setPreset(copy, true);
MasterImage.getImage().setCurrentFilterRepresentation(filterRepresentation);
}
public void showRepresentation(FilterRepresentation representation) {
if (representation == null) {
return;
}
useFilterRepresentation(representation);
// show representation
Editor mCurrentEditor = mEditorPlaceHolder.showEditor(representation.getEditorId());
loadEditorPanel(representation, mCurrentEditor);
}
public Editor getEditor(int editorID) {
return mEditorPlaceHolder.getEditor(editorID);
}
public void setCurrentPanel(int currentPanel) {
mCurrentPanel = currentPanel;
}
public int getCurrentPanel() {
return mCurrentPanel;
}
private class LoadBitmapTask extends AsyncTask<Uri, Boolean, Boolean> {
int mBitmapSize;
public LoadBitmapTask() {
mBitmapSize = getScreenImageSize();
}
@Override
protected Boolean doInBackground(Uri... params) {
if (!mImageLoader.loadBitmap(params[0], mBitmapSize)) {
return false;
}
publishProgress(mImageLoader.queryLightCycle360());
return true;
}
@Override
protected void onProgressUpdate(Boolean... values) {
super.onProgressUpdate(values);
if (isCancelled()) {
return;
}
if (values[0]) {
mShowingTinyPlanet = true;
}
}
@Override
protected void onPostExecute(Boolean result) {
MasterImage.setMaster(mMasterImage);
if (isCancelled()) {
return;
}
if (!result) {
cannotLoadImage();
+ return;
}
final View loading = findViewById(R.id.loading);
loading.setVisibility(View.GONE);
final View imageShow = findViewById(R.id.imageShow);
imageShow.setVisibility(View.VISIBLE);
Bitmap largeBitmap = mImageLoader.getOriginalBitmapLarge();
FilteringPipeline pipeline = FilteringPipeline.getPipeline();
pipeline.setOriginal(largeBitmap);
float previewScale = (float) largeBitmap.getWidth() / (float) mImageLoader.getOriginalBounds().width();
pipeline.setPreviewScaleFactor(previewScale);
Bitmap highresBitmap = mImageLoader.getOriginalBitmapHighres();
if (highresBitmap != null) {
float highResPreviewScale = (float) highresBitmap.getWidth() / (float) mImageLoader.getOriginalBounds().width();
pipeline.setHighResPreviewScaleFactor(highResPreviewScale);
}
if (!mShowingTinyPlanet) {
mCategoryFiltersAdapter.removeTinyPlanet();
}
pipeline.turnOnPipeline(true);
MasterImage.getImage().setOriginalGeometry(largeBitmap);
mCategoryLooksAdapter.imageLoaded();
mCategoryBordersAdapter.imageLoaded();
mCategoryGeometryAdapter.imageLoaded();
mCategoryFiltersAdapter.imageLoaded();
mLoadBitmapTask = null;
if (mAction == TINY_PLANET_ACTION) {
showRepresentation(mCategoryFiltersAdapter.getTinyPlanet());
}
mLoading = false;
super.onPostExecute(result);
}
}
private void clearGalleryBitmapPool() {
(new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
// Free memory held in Gallery's Bitmap pool. May be O(n) for n bitmaps.
GalleryBitmapPool.getInstance().clear();
return null;
}
}).execute();
}
@Override
protected void onDestroy() {
if (mLoadBitmapTask != null) {
mLoadBitmapTask.cancel(false);
}
// TODO: refactor, don't use so many singletons.
FilteringPipeline.getPipeline().turnOnPipeline(false);
MasterImage.reset();
FilteringPipeline.reset();
ImageFilter.resetStatics();
FiltersManager.getPreviewManager().freeRSFilterScripts();
FiltersManager.getManager().freeRSFilterScripts();
FiltersManager.getHighresManager().freeRSFilterScripts();
FiltersManager.reset();
CachingPipeline.destroyRenderScriptContext();
super.onDestroy();
}
private int getScreenImageSize() {
DisplayMetrics metrics = new DisplayMetrics();
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
display.getMetrics(metrics);
int msize = Math.min(size.x, size.y);
return (133 * msize) / metrics.densityDpi;
}
private void showSavingProgress(String albumName) {
ProgressDialog progress;
if (mSavingProgressDialog != null) {
progress = mSavingProgressDialog.get();
if (progress != null) {
progress.show();
return;
}
}
// TODO: Allow cancellation of the saving process
String progressText;
if (albumName == null) {
progressText = getString(R.string.saving_image);
} else {
progressText = getString(R.string.filtershow_saving_image, albumName);
}
progress = ProgressDialog.show(this, "", progressText, true, false);
mSavingProgressDialog = new WeakReference<ProgressDialog>(progress);
}
private void hideSavingProgress() {
if (mSavingProgressDialog != null) {
ProgressDialog progress = mSavingProgressDialog.get();
if (progress != null)
progress.dismiss();
}
}
public void completeSaveImage(Uri saveUri) {
if (mSharingImage && mSharedOutputFile != null) {
// Image saved, we unblock the content provider
Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI,
Uri.encode(mSharedOutputFile.getAbsolutePath()));
ContentValues values = new ContentValues();
values.put(SharedImageProvider.PREPARE, false);
getContentResolver().insert(uri, values);
}
setResult(RESULT_OK, new Intent().setData(saveUri));
hideSavingProgress();
finish();
}
@Override
public boolean onShareTargetSelected(ShareActionProvider arg0, Intent arg1) {
// First, let's tell the SharedImageProvider that it will need to wait
// for the image
Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI,
Uri.encode(mSharedOutputFile.getAbsolutePath()));
ContentValues values = new ContentValues();
values.put(SharedImageProvider.PREPARE, true);
getContentResolver().insert(uri, values);
mSharingImage = true;
// Process and save the image in the background.
showSavingProgress(null);
mImageShow.saveImage(this, mSharedOutputFile);
return true;
}
private Intent getDefaultShareIntent() {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType(SharedImageProvider.MIME_TYPE);
mSharedOutputFile = SaveCopyTask.getNewFile(this, mImageLoader.getUri());
Uri uri = Uri.withAppendedPath(SharedImageProvider.CONTENT_URI,
Uri.encode(mSharedOutputFile.getAbsolutePath()));
intent.putExtra(Intent.EXTRA_STREAM, uri);
return intent;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.filtershow_activity_menu, menu);
MenuItem showState = menu.findItem(R.id.showImageStateButton);
if (mShowingImageStatePanel) {
showState.setTitle(R.string.hide_imagestate_panel);
} else {
showState.setTitle(R.string.show_imagestate_panel);
}
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.menu_share)
.getActionProvider();
mShareActionProvider.setShareIntent(getDefaultShareIntent());
mShareActionProvider.setOnShareTargetSelectedListener(this);
MenuItem undoItem = menu.findItem(R.id.undoButton);
MenuItem redoItem = menu.findItem(R.id.redoButton);
MenuItem resetItem = menu.findItem(R.id.resetHistoryButton);
mMasterImage.getHistory().setMenuItems(undoItem, redoItem, resetItem);
return true;
}
@Override
public void onPause() {
super.onPause();
rsPause();
if (mShareActionProvider != null) {
mShareActionProvider.setOnShareTargetSelectedListener(null);
}
}
@Override
public void onResume() {
super.onResume();
rsResume();
if (mShareActionProvider != null) {
mShareActionProvider.setOnShareTargetSelectedListener(this);
}
}
private void rsResume() {
ImageFilter.setActivityForMemoryToasts(this);
MasterImage.setMaster(mMasterImage);
if (CachingPipeline.getRenderScriptContext() == null) {
CachingPipeline.createRenderscriptContext(this);
}
FiltersManager.setResources(getResources());
if (!mLoading) {
Bitmap largeBitmap = mImageLoader.getOriginalBitmapLarge();
FilteringPipeline pipeline = FilteringPipeline.getPipeline();
pipeline.setOriginal(largeBitmap);
float previewScale = (float) largeBitmap.getWidth() /
(float) mImageLoader.getOriginalBounds().width();
pipeline.setPreviewScaleFactor(previewScale);
Bitmap highresBitmap = mImageLoader.getOriginalBitmapHighres();
if (highresBitmap != null) {
float highResPreviewScale = (float) highresBitmap.getWidth() /
(float) mImageLoader.getOriginalBounds().width();
pipeline.setHighResPreviewScaleFactor(highResPreviewScale);
}
pipeline.turnOnPipeline(true);
MasterImage.getImage().setOriginalGeometry(largeBitmap);
}
}
private void rsPause() {
FilteringPipeline.getPipeline().turnOnPipeline(false);
FilteringPipeline.reset();
ImageFilter.resetStatics();
FiltersManager.getPreviewManager().freeRSFilterScripts();
FiltersManager.getManager().freeRSFilterScripts();
FiltersManager.getHighresManager().freeRSFilterScripts();
FiltersManager.reset();
CachingPipeline.destroyRenderScriptContext();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.undoButton: {
HistoryAdapter adapter = mMasterImage.getHistory();
int position = adapter.undo();
mMasterImage.onHistoryItemClick(position);
mImageShow.showToast(getString(R.string.filtershow_undo_toast));
backToMain();
invalidateViews();
return true;
}
case R.id.redoButton: {
HistoryAdapter adapter = mMasterImage.getHistory();
int position = adapter.redo();
mMasterImage.onHistoryItemClick(position);
mImageShow.showToast(getString(R.string.filtershow_redo_toast));
invalidateViews();
return true;
}
case R.id.resetHistoryButton: {
resetHistory();
return true;
}
case R.id.showImageStateButton: {
toggleImageStatePanel();
return true;
}
case android.R.id.home: {
saveImage();
return true;
}
}
return false;
}
public void enableSave(boolean enable) {
if (mSaveButton != null)
mSaveButton.setEnabled(enable);
}
private void fillFx() {
FilterFxRepresentation nullFx =
new FilterFxRepresentation(getString(R.string.none), 0, R.string.none);
Vector<FilterRepresentation> filtersRepresentations = new Vector<FilterRepresentation>();
FiltersManager.getManager().addLooks(this, filtersRepresentations);
mCategoryLooksAdapter = new CategoryAdapter(this);
int verticalItemHeight = (int) getResources().getDimension(R.dimen.action_item_height);
mCategoryLooksAdapter.setItemHeight(verticalItemHeight);
mCategoryLooksAdapter.add(new Action(this, nullFx, Action.FULL_VIEW));
for (FilterRepresentation representation : filtersRepresentations) {
mCategoryLooksAdapter.add(new Action(this, representation, Action.FULL_VIEW));
}
}
public void setDefaultPreset() {
// Default preset (original)
ImagePreset preset = new ImagePreset(getString(R.string.history_original)); // empty
preset.setImageLoader(mImageLoader);
mMasterImage.setPreset(preset, true);
}
// //////////////////////////////////////////////////////////////////////////////
// Some utility functions
// TODO: finish the cleanup.
public void invalidateViews() {
for (ImageShow views : mImageViews) {
views.invalidate();
views.updateImage();
}
}
public void hideImageViews() {
for (View view : mImageViews) {
view.setVisibility(View.GONE);
}
mEditorPlaceHolder.hide();
}
// //////////////////////////////////////////////////////////////////////////////
// imageState panel...
public void toggleImageStatePanel() {
invalidateOptionsMenu();
mShowingImageStatePanel = !mShowingImageStatePanel;
Fragment panel = getSupportFragmentManager().findFragmentByTag(MainPanel.FRAGMENT_TAG);
if (panel != null) {
if (panel instanceof EditorPanel) {
EditorPanel editorPanel = (EditorPanel) panel;
editorPanel.showImageStatePanel(mShowingImageStatePanel);
} else if (panel instanceof MainPanel) {
MainPanel mainPanel = (MainPanel) panel;
mainPanel.showImageStatePanel(mShowingImageStatePanel);
}
}
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setDefaultValues();
loadXML();
loadMainPanel();
// mLoadBitmapTask==null implies you have looked at the intent
if (!mShowingTinyPlanet && (mLoadBitmapTask == null)) {
mCategoryFiltersAdapter.removeTinyPlanet();
}
final View loading = findViewById(R.id.loading);
loading.setVisibility(View.GONE);
}
public void setupMasterImage() {
mImageLoader = new ImageLoader(this, getApplicationContext());
HistoryAdapter mHistoryAdapter = new HistoryAdapter(
this, R.layout.filtershow_history_operation_row,
R.id.rowTextView);
StateAdapter mImageStateAdapter = new StateAdapter(this, 0);
MasterImage.reset();
mMasterImage = MasterImage.getImage();
mMasterImage.setHistoryAdapter(mHistoryAdapter);
mMasterImage.setStateAdapter(mImageStateAdapter);
mMasterImage.setActivity(this);
mMasterImage.setImageLoader(mImageLoader);
if (Runtime.getRuntime().maxMemory() > LIMIT_SUPPORTS_HIGHRES) {
mMasterImage.setSupportsHighRes(true);
} else {
mMasterImage.setSupportsHighRes(false);
}
}
void resetHistory() {
HistoryAdapter adapter = mMasterImage.getHistory();
adapter.reset();
ImagePreset original = new ImagePreset(adapter.getItem(0));
mMasterImage.setPreset(original, true);
invalidateViews();
backToMain();
}
public void showDefaultImageView() {
mEditorPlaceHolder.hide();
mImageShow.setVisibility(View.VISIBLE);
MasterImage.getImage().setCurrentFilter(null);
MasterImage.getImage().setCurrentFilterRepresentation(null);
}
public void backToMain() {
Fragment currentPanel = getSupportFragmentManager().findFragmentByTag(MainPanel.FRAGMENT_TAG);
if (currentPanel instanceof MainPanel) {
return;
}
loadMainPanel();
showDefaultImageView();
}
@Override
public void onBackPressed() {
Fragment currentPanel = getSupportFragmentManager().findFragmentByTag(MainPanel.FRAGMENT_TAG);
if (currentPanel instanceof MainPanel) {
if (!mImageShow.hasModifications()) {
done();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.unsaved).setTitle(R.string.save_before_exit);
builder.setPositiveButton(R.string.save_and_exit, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
saveImage();
}
});
builder.setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
done();
}
});
builder.show();
}
} else {
backToMain();
}
}
public void cannotLoadImage() {
CharSequence text = getString(R.string.cannot_load_image);
Toast toast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
toast.show();
finish();
}
// //////////////////////////////////////////////////////////////////////////////
public float getPixelsFromDip(float value) {
Resources r = getResources();
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value,
r.getDisplayMetrics());
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mMasterImage.onHistoryItemClick(position);
invalidateViews();
}
public void pickImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_image)),
SELECT_PICTURE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
startLoadBitmap(selectedImageUri);
}
}
}
private boolean mSaveToExtraUri = false;
private boolean mSaveAsWallpaper = false;
private boolean mReturnAsExtra = false;
private boolean mOutputted = false;
public void saveImage() {
handleSpecialExitCases();
if (!mOutputted) {
if (mImageShow.hasModifications()) {
// Get the name of the album, to which the image will be saved
File saveDir = SaveCopyTask.getFinalSaveDirectory(this, mImageLoader.getUri());
int bucketId = GalleryUtils.getBucketId(saveDir.getPath());
String albumName = LocalAlbum.getLocalizedName(getResources(), bucketId, null);
showSavingProgress(albumName);
mImageShow.saveImage(this, null);
} else {
done();
}
}
}
public boolean detectSpecialExitCases() {
return mCropExtras != null && (mCropExtras.getExtraOutput() != null
|| mCropExtras.getSetAsWallpaper() || mCropExtras.getReturnData());
}
public void handleSpecialExitCases() {
if (mCropExtras != null) {
if (mCropExtras.getExtraOutput() != null) {
mSaveToExtraUri = true;
mOutputted = true;
}
if (mCropExtras.getSetAsWallpaper()) {
mSaveAsWallpaper = true;
mOutputted = true;
}
if (mCropExtras.getReturnData()) {
mReturnAsExtra = true;
mOutputted = true;
}
if (mOutputted) {
mImageShow.getImagePreset().mGeoData.setUseCropExtrasFlag(true);
showSavingProgress(null);
mImageShow.returnFilteredResult(this);
}
}
}
public void onFilteredResult(Bitmap filtered) {
Intent intent = new Intent();
intent.putExtra(CropExtras.KEY_CROPPED_RECT, mImageShow.getImageCropBounds());
if (mSaveToExtraUri) {
mImageShow.saveToUri(filtered, mCropExtras.getExtraOutput(),
mCropExtras.getOutputFormat(), this);
}
if (mSaveAsWallpaper) {
setWallpaperInBackground(filtered);
}
if (mReturnAsExtra) {
if (filtered != null) {
int bmapSize = filtered.getRowBytes() * filtered.getHeight();
/*
* Max size of Binder transaction buffer is 1Mb, so constrain
* Bitmap to be somewhat less than this, otherwise we get
* TransactionTooLargeExceptions.
*/
if (bmapSize > MAX_BMAP_IN_INTENT) {
Log.w(LOGTAG, "Bitmap too large to be returned via intent");
} else {
intent.putExtra(CropExtras.KEY_DATA, filtered);
}
}
}
setResult(RESULT_OK, intent);
if (!mSaveToExtraUri) {
done();
}
}
void setWallpaperInBackground(final Bitmap bmap) {
Toast.makeText(this, R.string.setting_wallpaper, Toast.LENGTH_LONG).show();
BitmapTask.Callbacks<FilterShowActivity> cb = new BitmapTask.Callbacks<FilterShowActivity>() {
@Override
public void onComplete(Bitmap result) {}
@Override
public void onCancel() {}
@Override
public Bitmap onExecute(FilterShowActivity param) {
try {
WallpaperManager.getInstance(param).setBitmap(bmap);
} catch (IOException e) {
Log.w(LOGTAG, "fail to set wall paper", e);
}
return null;
}
};
(new BitmapTask<FilterShowActivity>(cb)).execute(this);
}
public void done() {
if (mOutputted) {
hideSavingProgress();
}
finish();
}
static {
System.loadLibrary("jni_filtershow_filters");
}
}
| true | true | protected void onPostExecute(Boolean result) {
MasterImage.setMaster(mMasterImage);
if (isCancelled()) {
return;
}
if (!result) {
cannotLoadImage();
}
final View loading = findViewById(R.id.loading);
loading.setVisibility(View.GONE);
final View imageShow = findViewById(R.id.imageShow);
imageShow.setVisibility(View.VISIBLE);
Bitmap largeBitmap = mImageLoader.getOriginalBitmapLarge();
FilteringPipeline pipeline = FilteringPipeline.getPipeline();
pipeline.setOriginal(largeBitmap);
float previewScale = (float) largeBitmap.getWidth() / (float) mImageLoader.getOriginalBounds().width();
pipeline.setPreviewScaleFactor(previewScale);
Bitmap highresBitmap = mImageLoader.getOriginalBitmapHighres();
if (highresBitmap != null) {
float highResPreviewScale = (float) highresBitmap.getWidth() / (float) mImageLoader.getOriginalBounds().width();
pipeline.setHighResPreviewScaleFactor(highResPreviewScale);
}
if (!mShowingTinyPlanet) {
mCategoryFiltersAdapter.removeTinyPlanet();
}
pipeline.turnOnPipeline(true);
MasterImage.getImage().setOriginalGeometry(largeBitmap);
mCategoryLooksAdapter.imageLoaded();
mCategoryBordersAdapter.imageLoaded();
mCategoryGeometryAdapter.imageLoaded();
mCategoryFiltersAdapter.imageLoaded();
mLoadBitmapTask = null;
if (mAction == TINY_PLANET_ACTION) {
showRepresentation(mCategoryFiltersAdapter.getTinyPlanet());
}
mLoading = false;
super.onPostExecute(result);
}
| protected void onPostExecute(Boolean result) {
MasterImage.setMaster(mMasterImage);
if (isCancelled()) {
return;
}
if (!result) {
cannotLoadImage();
return;
}
final View loading = findViewById(R.id.loading);
loading.setVisibility(View.GONE);
final View imageShow = findViewById(R.id.imageShow);
imageShow.setVisibility(View.VISIBLE);
Bitmap largeBitmap = mImageLoader.getOriginalBitmapLarge();
FilteringPipeline pipeline = FilteringPipeline.getPipeline();
pipeline.setOriginal(largeBitmap);
float previewScale = (float) largeBitmap.getWidth() / (float) mImageLoader.getOriginalBounds().width();
pipeline.setPreviewScaleFactor(previewScale);
Bitmap highresBitmap = mImageLoader.getOriginalBitmapHighres();
if (highresBitmap != null) {
float highResPreviewScale = (float) highresBitmap.getWidth() / (float) mImageLoader.getOriginalBounds().width();
pipeline.setHighResPreviewScaleFactor(highResPreviewScale);
}
if (!mShowingTinyPlanet) {
mCategoryFiltersAdapter.removeTinyPlanet();
}
pipeline.turnOnPipeline(true);
MasterImage.getImage().setOriginalGeometry(largeBitmap);
mCategoryLooksAdapter.imageLoaded();
mCategoryBordersAdapter.imageLoaded();
mCategoryGeometryAdapter.imageLoaded();
mCategoryFiltersAdapter.imageLoaded();
mLoadBitmapTask = null;
if (mAction == TINY_PLANET_ACTION) {
showRepresentation(mCategoryFiltersAdapter.getTinyPlanet());
}
mLoading = false;
super.onPostExecute(result);
}
|
diff --git a/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/src/org/eclipse/equinox/p2/examples/rcp/prestartupdate/P2Util.java b/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/src/org/eclipse/equinox/p2/examples/rcp/prestartupdate/P2Util.java
index 81ee3e9f0..2ade309a9 100644
--- a/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/src/org/eclipse/equinox/p2/examples/rcp/prestartupdate/P2Util.java
+++ b/examples/org.eclipse.equinox.p2.examples.rcp.prestartupdate/src/org/eclipse/equinox/p2/examples/rcp/prestartupdate/P2Util.java
@@ -1,193 +1,193 @@
/*******************************************************************************
* Copyright (c) 2009 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.equinox.p2.examples.rcp.prestartupdate;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper;
import org.eclipse.equinox.internal.provisional.p2.artifact.repository.IArtifactRepositoryManager;
import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException;
import org.eclipse.equinox.internal.provisional.p2.director.IPlanner;
import org.eclipse.equinox.internal.provisional.p2.director.ProfileChangeRequest;
import org.eclipse.equinox.internal.provisional.p2.director.ProvisioningPlan;
import org.eclipse.equinox.internal.provisional.p2.engine.DefaultPhaseSet;
import org.eclipse.equinox.internal.provisional.p2.engine.IEngine;
import org.eclipse.equinox.internal.provisional.p2.engine.IProfile;
import org.eclipse.equinox.internal.provisional.p2.engine.IProfileRegistry;
import org.eclipse.equinox.internal.provisional.p2.engine.ProvisioningContext;
import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.internal.provisional.p2.metadata.query.InstallableUnitQuery;
import org.eclipse.equinox.internal.provisional.p2.metadata.repository.IMetadataRepositoryManager;
import org.eclipse.equinox.internal.provisional.p2.query.Collector;
import org.eclipse.equinox.internal.provisional.p2.repository.IRepositoryManager;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
public class P2Util {
// XXX Check for updates to this application and return true if
// we have installed updates and need a restart.
// This method is intentionally long and ugly in order to provide
// "one-stop-shopping" for how to check for and perform an update.
static boolean checkForUpdates() {
// Before we show a progress dialog, at least find out that we have
// installed content and repos to check.
final IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper
.getService(Activator.bundleContext, IProfileRegistry.class
.getName());
if (profileRegistry == null)
return false;
final IProfile profile = profileRegistry
.getProfile(IProfileRegistry.SELF);
if (profile == null)
return false;
// We are going to look for updates to all IU's in the profile. A
// different query could be used if we are looking for updates to
// a subset. For example, the p2 UI only looks for updates to those
// IU's marked with a special property.
final Collector collector = profile.query(InstallableUnitQuery.ANY,
new Collector(), null);
if (collector.isEmpty())
return false;
final IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper
.getService(Activator.bundleContext,
IMetadataRepositoryManager.class.getName());
if (manager == null)
return false;
final URI[] reposToSearch = manager
.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL);
if (reposToSearch.length == 0)
return false;
final IPlanner planner = (IPlanner) ServiceHelper.getService(
Activator.bundleContext, IPlanner.class.getName());
if (planner == null)
return false;
// Looking in all known repositories for updates for each IU in the profile
final boolean[] didWeUpdate = new boolean[1];
didWeUpdate[0] = false;
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
// We'll break progress up into 4 steps.
// 1. Load repos - it is not strictly necessary to do this.
// The planner will do it for us. However, burying this
// in the planner's progress reporting will not
// show enough progress initially, so we do it manually.
// 2. Get update list
// 3. Build a profile change request and get a provisioning plan
// 4. Perform the provisioning plan.
SubMonitor sub = SubMonitor.convert(monitor,
"Checking for application updates...", 400);
// 1. Load repos
SubMonitor loadMonitor = sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS);
for (int i=0; i<reposToSearch.length; i++)
try {
if (loadMonitor.isCanceled())
throw new InterruptedException();
manager.loadRepository(reposToSearch[i], loadMonitor.newChild(100/reposToSearch.length));
} catch (ProvisionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loadMonitor.done();
// 2. Get update list.
// First we look for replacement IU's for each IU
ArrayList iusWithUpdates = new ArrayList();
ArrayList replacementIUs = new ArrayList();
Iterator iter = collector.iterator();
ProvisioningContext pc = new ProvisioningContext(reposToSearch);
SubMonitor updateSearchMonitor = sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS);
while (iter.hasNext()) {
if (updateSearchMonitor.isCanceled())
throw new InterruptedException();
IInstallableUnit iu = (IInstallableUnit) iter.next();
IInstallableUnit[] replacements = planner.updatesFor(iu,
pc, updateSearchMonitor.newChild(100/collector.size()));
if (replacements.length > 0) {
iusWithUpdates.add(iu);
if (replacements.length == 1)
replacementIUs.add(replacements[0]);
else {
IInstallableUnit repl = replacements[0];
for (int i = 1; i < replacements.length; i++)
if (replacements[i].getVersion().compareTo(
repl.getVersion()) > 0)
repl = replacements[i];
replacementIUs.add(repl);
}
}
}
// Did we find any updates?
if (iusWithUpdates.size() == 0) {
sub.done();
} else {
if (sub.isCanceled())
throw new InterruptedException();
// 3. Build a profile change request and get a provisioning plan
ProfileChangeRequest changeRequest = new ProfileChangeRequest(
profile);
changeRequest
.removeInstallableUnits((IInstallableUnit[]) iusWithUpdates
.toArray(new IInstallableUnit[iusWithUpdates
.size()]));
changeRequest
- .addInstallableUnits((IInstallableUnit[]) iusWithUpdates
- .toArray(new IInstallableUnit[iusWithUpdates
+ .addInstallableUnits((IInstallableUnit[]) replacementIUs
+ .toArray(new IInstallableUnit[replacementIUs
.size()]));
ProvisioningPlan plan = planner.getProvisioningPlan(
changeRequest, pc, sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS));
if (plan.getStatus().getSeverity() == IStatus.CANCEL)
throw new InterruptedException();
if (plan.getStatus().getSeverity() != IStatus.ERROR) {
IEngine engine = (IEngine) ServiceHelper.getService(
Activator.bundleContext, IEngine.class
.getName());
IArtifactRepositoryManager artifactMgr = (IArtifactRepositoryManager) ServiceHelper
.getService(Activator.bundleContext,
IArtifactRepositoryManager.class
.getName());
if (engine != null && artifactMgr != null) {
// 4. Perform the provisioning plan
pc
.setArtifactRepositories(artifactMgr
.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL));
IStatus status = engine.perform(profile,
new DefaultPhaseSet(), plan.getOperands(),
pc, sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS));
if (status.getSeverity() == IStatus.CANCEL)
throw new InterruptedException();
if (status.getSeverity() != IStatus.ERROR) {
didWeUpdate[0] = true;
}
}
}
}
}
};
try {
new ProgressMonitorDialog(null).run(true, true, runnable);
} catch (InvocationTargetException e) {
e.printStackTrace();
return false;
} catch (InterruptedException e) {
return false;
}
return didWeUpdate[0];
}
}
| true | true | static boolean checkForUpdates() {
// Before we show a progress dialog, at least find out that we have
// installed content and repos to check.
final IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper
.getService(Activator.bundleContext, IProfileRegistry.class
.getName());
if (profileRegistry == null)
return false;
final IProfile profile = profileRegistry
.getProfile(IProfileRegistry.SELF);
if (profile == null)
return false;
// We are going to look for updates to all IU's in the profile. A
// different query could be used if we are looking for updates to
// a subset. For example, the p2 UI only looks for updates to those
// IU's marked with a special property.
final Collector collector = profile.query(InstallableUnitQuery.ANY,
new Collector(), null);
if (collector.isEmpty())
return false;
final IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper
.getService(Activator.bundleContext,
IMetadataRepositoryManager.class.getName());
if (manager == null)
return false;
final URI[] reposToSearch = manager
.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL);
if (reposToSearch.length == 0)
return false;
final IPlanner planner = (IPlanner) ServiceHelper.getService(
Activator.bundleContext, IPlanner.class.getName());
if (planner == null)
return false;
// Looking in all known repositories for updates for each IU in the profile
final boolean[] didWeUpdate = new boolean[1];
didWeUpdate[0] = false;
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
// We'll break progress up into 4 steps.
// 1. Load repos - it is not strictly necessary to do this.
// The planner will do it for us. However, burying this
// in the planner's progress reporting will not
// show enough progress initially, so we do it manually.
// 2. Get update list
// 3. Build a profile change request and get a provisioning plan
// 4. Perform the provisioning plan.
SubMonitor sub = SubMonitor.convert(monitor,
"Checking for application updates...", 400);
// 1. Load repos
SubMonitor loadMonitor = sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS);
for (int i=0; i<reposToSearch.length; i++)
try {
if (loadMonitor.isCanceled())
throw new InterruptedException();
manager.loadRepository(reposToSearch[i], loadMonitor.newChild(100/reposToSearch.length));
} catch (ProvisionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loadMonitor.done();
// 2. Get update list.
// First we look for replacement IU's for each IU
ArrayList iusWithUpdates = new ArrayList();
ArrayList replacementIUs = new ArrayList();
Iterator iter = collector.iterator();
ProvisioningContext pc = new ProvisioningContext(reposToSearch);
SubMonitor updateSearchMonitor = sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS);
while (iter.hasNext()) {
if (updateSearchMonitor.isCanceled())
throw new InterruptedException();
IInstallableUnit iu = (IInstallableUnit) iter.next();
IInstallableUnit[] replacements = planner.updatesFor(iu,
pc, updateSearchMonitor.newChild(100/collector.size()));
if (replacements.length > 0) {
iusWithUpdates.add(iu);
if (replacements.length == 1)
replacementIUs.add(replacements[0]);
else {
IInstallableUnit repl = replacements[0];
for (int i = 1; i < replacements.length; i++)
if (replacements[i].getVersion().compareTo(
repl.getVersion()) > 0)
repl = replacements[i];
replacementIUs.add(repl);
}
}
}
// Did we find any updates?
if (iusWithUpdates.size() == 0) {
sub.done();
} else {
if (sub.isCanceled())
throw new InterruptedException();
// 3. Build a profile change request and get a provisioning plan
ProfileChangeRequest changeRequest = new ProfileChangeRequest(
profile);
changeRequest
.removeInstallableUnits((IInstallableUnit[]) iusWithUpdates
.toArray(new IInstallableUnit[iusWithUpdates
.size()]));
changeRequest
.addInstallableUnits((IInstallableUnit[]) iusWithUpdates
.toArray(new IInstallableUnit[iusWithUpdates
.size()]));
ProvisioningPlan plan = planner.getProvisioningPlan(
changeRequest, pc, sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS));
if (plan.getStatus().getSeverity() == IStatus.CANCEL)
throw new InterruptedException();
if (plan.getStatus().getSeverity() != IStatus.ERROR) {
IEngine engine = (IEngine) ServiceHelper.getService(
Activator.bundleContext, IEngine.class
.getName());
IArtifactRepositoryManager artifactMgr = (IArtifactRepositoryManager) ServiceHelper
.getService(Activator.bundleContext,
IArtifactRepositoryManager.class
.getName());
if (engine != null && artifactMgr != null) {
// 4. Perform the provisioning plan
pc
.setArtifactRepositories(artifactMgr
.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL));
IStatus status = engine.perform(profile,
new DefaultPhaseSet(), plan.getOperands(),
pc, sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS));
if (status.getSeverity() == IStatus.CANCEL)
throw new InterruptedException();
if (status.getSeverity() != IStatus.ERROR) {
didWeUpdate[0] = true;
}
}
}
}
}
};
try {
new ProgressMonitorDialog(null).run(true, true, runnable);
} catch (InvocationTargetException e) {
e.printStackTrace();
return false;
} catch (InterruptedException e) {
return false;
}
return didWeUpdate[0];
}
| static boolean checkForUpdates() {
// Before we show a progress dialog, at least find out that we have
// installed content and repos to check.
final IProfileRegistry profileRegistry = (IProfileRegistry) ServiceHelper
.getService(Activator.bundleContext, IProfileRegistry.class
.getName());
if (profileRegistry == null)
return false;
final IProfile profile = profileRegistry
.getProfile(IProfileRegistry.SELF);
if (profile == null)
return false;
// We are going to look for updates to all IU's in the profile. A
// different query could be used if we are looking for updates to
// a subset. For example, the p2 UI only looks for updates to those
// IU's marked with a special property.
final Collector collector = profile.query(InstallableUnitQuery.ANY,
new Collector(), null);
if (collector.isEmpty())
return false;
final IMetadataRepositoryManager manager = (IMetadataRepositoryManager) ServiceHelper
.getService(Activator.bundleContext,
IMetadataRepositoryManager.class.getName());
if (manager == null)
return false;
final URI[] reposToSearch = manager
.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL);
if (reposToSearch.length == 0)
return false;
final IPlanner planner = (IPlanner) ServiceHelper.getService(
Activator.bundleContext, IPlanner.class.getName());
if (planner == null)
return false;
// Looking in all known repositories for updates for each IU in the profile
final boolean[] didWeUpdate = new boolean[1];
didWeUpdate[0] = false;
IRunnableWithProgress runnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
// We'll break progress up into 4 steps.
// 1. Load repos - it is not strictly necessary to do this.
// The planner will do it for us. However, burying this
// in the planner's progress reporting will not
// show enough progress initially, so we do it manually.
// 2. Get update list
// 3. Build a profile change request and get a provisioning plan
// 4. Perform the provisioning plan.
SubMonitor sub = SubMonitor.convert(monitor,
"Checking for application updates...", 400);
// 1. Load repos
SubMonitor loadMonitor = sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS);
for (int i=0; i<reposToSearch.length; i++)
try {
if (loadMonitor.isCanceled())
throw new InterruptedException();
manager.loadRepository(reposToSearch[i], loadMonitor.newChild(100/reposToSearch.length));
} catch (ProvisionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
loadMonitor.done();
// 2. Get update list.
// First we look for replacement IU's for each IU
ArrayList iusWithUpdates = new ArrayList();
ArrayList replacementIUs = new ArrayList();
Iterator iter = collector.iterator();
ProvisioningContext pc = new ProvisioningContext(reposToSearch);
SubMonitor updateSearchMonitor = sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS);
while (iter.hasNext()) {
if (updateSearchMonitor.isCanceled())
throw new InterruptedException();
IInstallableUnit iu = (IInstallableUnit) iter.next();
IInstallableUnit[] replacements = planner.updatesFor(iu,
pc, updateSearchMonitor.newChild(100/collector.size()));
if (replacements.length > 0) {
iusWithUpdates.add(iu);
if (replacements.length == 1)
replacementIUs.add(replacements[0]);
else {
IInstallableUnit repl = replacements[0];
for (int i = 1; i < replacements.length; i++)
if (replacements[i].getVersion().compareTo(
repl.getVersion()) > 0)
repl = replacements[i];
replacementIUs.add(repl);
}
}
}
// Did we find any updates?
if (iusWithUpdates.size() == 0) {
sub.done();
} else {
if (sub.isCanceled())
throw new InterruptedException();
// 3. Build a profile change request and get a provisioning plan
ProfileChangeRequest changeRequest = new ProfileChangeRequest(
profile);
changeRequest
.removeInstallableUnits((IInstallableUnit[]) iusWithUpdates
.toArray(new IInstallableUnit[iusWithUpdates
.size()]));
changeRequest
.addInstallableUnits((IInstallableUnit[]) replacementIUs
.toArray(new IInstallableUnit[replacementIUs
.size()]));
ProvisioningPlan plan = planner.getProvisioningPlan(
changeRequest, pc, sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS));
if (plan.getStatus().getSeverity() == IStatus.CANCEL)
throw new InterruptedException();
if (plan.getStatus().getSeverity() != IStatus.ERROR) {
IEngine engine = (IEngine) ServiceHelper.getService(
Activator.bundleContext, IEngine.class
.getName());
IArtifactRepositoryManager artifactMgr = (IArtifactRepositoryManager) ServiceHelper
.getService(Activator.bundleContext,
IArtifactRepositoryManager.class
.getName());
if (engine != null && artifactMgr != null) {
// 4. Perform the provisioning plan
pc
.setArtifactRepositories(artifactMgr
.getKnownRepositories(IRepositoryManager.REPOSITORIES_ALL));
IStatus status = engine.perform(profile,
new DefaultPhaseSet(), plan.getOperands(),
pc, sub.newChild(100, SubMonitor.SUPPRESS_ALL_LABELS));
if (status.getSeverity() == IStatus.CANCEL)
throw new InterruptedException();
if (status.getSeverity() != IStatus.ERROR) {
didWeUpdate[0] = true;
}
}
}
}
}
};
try {
new ProgressMonitorDialog(null).run(true, true, runnable);
} catch (InvocationTargetException e) {
e.printStackTrace();
return false;
} catch (InterruptedException e) {
return false;
}
return didWeUpdate[0];
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.