answer
stringlengths 17
10.2M
|
|---|
package org.zanata.webtrans.client.presenter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.zanata.webtrans.client.events.KeyShortcutEvent;
import org.zanata.webtrans.client.events.KeyShortcutEventHandler;
import org.zanata.webtrans.client.keys.KeyShortcut;
import org.zanata.webtrans.client.keys.ShortcutContext;
import org.zanata.webtrans.client.resources.WebTransMessages;
import com.allen_sauer.gwt.log.client.Log;
import com.google.common.base.Strings;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.inject.Inject;
import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.widget.WidgetDisplay;
import net.customware.gwt.presenter.client.widget.WidgetPresenter;
/**
* Detects shortcut key combinations such as Alt+KEY and Shift+Alt+KEY and
* broadcasts corresponding {@link KeyShortcutEvent}s.
*
* Handlers are registered directly with this presenter to avoid excessive
* traffic on the main event bus and to make handling of events simpler.
*
* Only key-down events are processed.
*
* @author David Mason, <a
* href="mailto:damason@redhat.com">damason@redhat.com</a> *
*/
public class KeyShortcutPresenter extends WidgetPresenter<KeyShortcutPresenter.Display>
{
public interface Display extends WidgetDisplay
{
void addContext(String title, List<String> shortcuts);
void showPanel();
public void clearPanel();
// hide method not provided as auto-hide is enabled
}
/**
* Key uses {@link KeyShortcut#keysHash()}
*/
private Map<Integer, Set<KeyShortcut>> shortcutMap;
private Map<Integer, String> keyDisplayMap;
private Set<ShortcutContext> activeContexts;
private WebTransMessages messages;
@Inject
public KeyShortcutPresenter(Display display, EventBus eventBus, final WebTransMessages webTransMessages)
{
super(display, eventBus);
this.messages = webTransMessages;
keyDisplayMap = new HashMap<Integer, String>();
keyDisplayMap.put(KeyShortcut.ALT_KEY, "Alt");
keyDisplayMap.put(KeyShortcut.SHIFT_KEY, "Shift");
keyDisplayMap.put(KeyShortcut.META_KEY, "Meta");
keyDisplayMap.put(KeyShortcut.CTRL_KEY, "Ctrl");
keyDisplayMap.put(KeyCodes.KEY_DOWN, "Down Arrow");
keyDisplayMap.put(KeyCodes.KEY_UP, "Up Arrow");
keyDisplayMap.put(KeyCodes.KEY_ENTER, "Enter");
}
@Override
protected void onBind()
{
ensureActiveContexts().add(ShortcutContext.Application);
Event.addNativePreviewHandler(new NativePreviewHandler()
{
@Override
public void onPreviewNativeEvent(NativePreviewEvent event)
{
NativeEvent evt = event.getNativeEvent();
if ((event.getTypeInt() & (Event.ONKEYDOWN | Event.ONKEYUP)) != 0)
{
processKeyEvent(evt);
// Log.debug("Key event. Stopping propagation.");
// evt.stopPropagation();
// evt.preventDefault();
}
}
});
// could try to use ?, although this is not as simple as passing character
registerKeyShortcut(new KeyShortcut(KeyShortcut.ALT_KEY, 'Y', ShortcutContext.Application, messages.showAvailableKeyShortcuts(), new KeyShortcutEventHandler()
{
@Override
public void onKeyShortcut(KeyShortcutEvent event)
{
display.clearPanel();
for (ShortcutContext context : ensureActiveContexts())
{
ArrayList<String> shortcutStrings = new ArrayList<String>();
for (Set<KeyShortcut> shortcutSet : ensureShortcutMap().values())
{
for (KeyShortcut shortcut : shortcutSet)
{
if (shortcut.getContext() == context && shortcut.isDisplayInView())
{
StringBuilder sb = new StringBuilder();
if ((shortcut.getModifiers() & KeyShortcut.CTRL_KEY) != 0)
{
sb.append(keyDisplayMap.get(KeyShortcut.CTRL_KEY));
sb.append("+");
}
if ((shortcut.getModifiers() & KeyShortcut.SHIFT_KEY) != 0)
{
sb.append(keyDisplayMap.get(KeyShortcut.SHIFT_KEY));
sb.append("+");
}
if ((shortcut.getModifiers() & KeyShortcut.META_KEY) != 0)
{
sb.append(keyDisplayMap.get(KeyShortcut.META_KEY));
sb.append("+");
}
if ((shortcut.getModifiers() & KeyShortcut.ALT_KEY) != 0)
{
sb.append(keyDisplayMap.get(KeyShortcut.ALT_KEY));
sb.append("+");
}
if (!Strings.isNullOrEmpty(keyDisplayMap.get(shortcut.getKeyCode())))
{
sb.append(keyDisplayMap.get(shortcut.getKeyCode()));
}
else
{
sb.append((char) shortcut.getKeyCode());
}
sb.append(" : ");
sb.append(shortcut.getDescription());
shortcutStrings.add(sb.toString());
}
}
}
Collections.sort(shortcutStrings);
String contextName = "";
switch (context)
{
case Application:
contextName = messages.applicationScope();
break;
case ProjectWideSearch:
contextName = messages.projectWideSearchAndReplace();
break;
case Edit:
contextName = messages.editScope();
break;
case Navigation:
contextName = messages.navigationScope();
break;
}
display.addContext(contextName, shortcutStrings);
}
display.showPanel();
}
}));
}
@Override
protected void onUnbind()
{
// TODO Auto-generated method stub
}
@Override
protected void onRevealDisplay()
{
// TODO Auto-generated method stub
}
public void setContextActive(ShortcutContext context, boolean active)
{
if (active)
{
ensureActiveContexts().add(context);
}
else
{
if (context == ShortcutContext.Application)
{
// TODO throw exception? Remove this check? Just warn but still
// remove context?
Log.warn("Tried to set global shortcut context inactive. Ignoring.");
}
else
{
ensureActiveContexts().remove(context);
}
}
}
public HandlerRegistration registerKeyShortcut(KeyShortcut shortcut)
{
Log.debug("registering key shortcut. key: " + shortcut.getKeyCode() + " modifier: " + shortcut.getModifiers() + " keyhash: " + shortcut.keysHash());
Set<KeyShortcut> shortcuts = ensureShortcutMap().get(shortcut.keysHash());
if (shortcuts == null)
{
shortcuts = new HashSet<KeyShortcut>();
ensureShortcutMap().put(shortcut.keysHash(), shortcuts);
}
shortcuts.add(shortcut);
return new KeyShortcutHandlerRegistration(shortcut);
}
private void processKeyEvent(NativeEvent evt)
{
int modifiers = calculateModifiers(evt);
int keyHash = calculateKeyHash(modifiers, evt.getKeyCode());
Log.debug("processing key shortcut for key" + evt.getKeyCode() + " with hash " + keyHash);
Set<KeyShortcut> shortcuts = ensureShortcutMap().get(keyHash);
if (shortcuts != null)
{
KeyShortcutEvent shortcutEvent = new KeyShortcutEvent(modifiers, evt.getKeyCode());
for (KeyShortcut shortcut : shortcuts)
{
if (ensureActiveContexts().contains(shortcut.getContext()) && shortcut.getKeyAction().equals(evt.getType()))
{
if (shortcut.isStopPropagation())
{
evt.stopPropagation();
}
if (shortcut.isPreventDefault())
{
evt.preventDefault();
}
shortcut.getHandler().onKeyShortcut(shortcutEvent);
}
}
}
}
/**
* Calculate a hash that should match {@link KeyShortcut#keysHash()}.
*
* @param evt
* @return
* @see KeyShortcut#keysHash()
*/
private int calculateKeyHash(int modifiers, int keyCode)
{
int keyHash = keyCode * 8;
keyHash |= modifiers;
return keyHash;
}
private int calculateModifiers(NativeEvent evt)
{
int modifiers = 0;
modifiers |= evt.getAltKey() ? KeyShortcut.ALT_KEY : 0;
modifiers |= evt.getShiftKey() ? KeyShortcut.SHIFT_KEY : 0;
modifiers |= evt.getCtrlKey() ? KeyShortcut.CTRL_KEY : 0;
modifiers |= evt.getMetaKey() ? KeyShortcut.META_KEY : 0;
return modifiers;
}
private Set<ShortcutContext> ensureActiveContexts()
{
if (activeContexts == null)
{
activeContexts = new HashSet<ShortcutContext>();
}
return activeContexts;
}
private Map<Integer, Set<KeyShortcut>> ensureShortcutMap()
{
if (shortcutMap == null)
{
shortcutMap = new HashMap<Integer, Set<KeyShortcut>>();
}
return shortcutMap;
}
private class KeyShortcutHandlerRegistration implements HandlerRegistration
{
private KeyShortcut shortcut;
public KeyShortcutHandlerRegistration(KeyShortcut shortcut)
{
this.shortcut = shortcut;
}
@Override
public void removeHandler()
{
Set<KeyShortcut> shortcuts = ensureShortcutMap().get(shortcut.keysHash());
if (shortcuts != null)
{
shortcuts.remove(shortcut);
}
}
}
}
|
package edu.arizona.kfs.module.purap.document.authorization;
import java.util.Set;
import org.kuali.kfs.module.purap.PurapParameterConstants;
import org.kuali.kfs.module.purap.PurapAuthorizationConstants.PurchaseOrderEditMode;
import org.kuali.kfs.module.purap.PurapAuthorizationConstants.RequisitionEditMode;
import org.kuali.kfs.module.purap.PurapConstants.PurchaseOrderStatuses;
import org.kuali.kfs.module.purap.document.PurchaseOrderDocument;
import org.kuali.kfs.module.purap.document.PurchasingAccountsPayableDocument;
import org.kuali.kfs.module.purap.document.service.PurapService;
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.sys.service.impl.KfsParameterConstants;
import org.kuali.rice.krad.document.Document;
import org.kuali.rice.coreservice.framework.parameter.ParameterService;
import org.kuali.rice.kew.api.WorkflowDocument;
public class PurchaseOrderAmendmentDocumentPresentationController extends org.kuali.kfs.module.purap.document.authorization.PurchaseOrderAmendmentDocumentPresentationController {
@Override
public Set<String> getEditModes(Document document) {
Set<String> editModes = super.getEditModes(document);
PurchaseOrderDocument poDocument = (PurchaseOrderDocument) document;
if (PurchaseOrderStatuses.APPDOC_CHANGE_IN_PROCESS.equals(poDocument.getApplicationDocumentStatus())) {
WorkflowDocument workflowDocument = poDocument.getFinancialSystemDocumentHeader().getWorkflowDocument();
// PRE_ROUTE_CHANGEABLE mode is used for fields that are editable only before POA is routed, for ex, contract manager
if (workflowDocument.isInitiated() || workflowDocument.isSaved() || workflowDocument.isCompletionRequested()) {
editModes.add(PurchaseOrderEditMode.PRE_ROUTE_CHANGEABLE);
}
}
//make clear tax button always available like REQS
boolean salesTaxInd = SpringContext.getBean(ParameterService.class).getParameterValueAsBoolean(KfsParameterConstants.PURCHASING_DOCUMENT.class, PurapParameterConstants.ENABLE_SALES_TAX_IND);
if (salesTaxInd) {
editModes.add(PurchaseOrderEditMode.CLEAR_ALL_TAXES);
}
if (isAccountNode(document)) {
editModes.add(RequisitionEditMode.RESTRICT_FISCAL_ENTRY);
}
return editModes;
}
/**
* determine whether the current route node is account
*
* @param document the given POA document
* @return true if the current route node is account
*/
protected boolean isAccountNode(Document document) {
WorkflowDocument workflowDocument = document.getDocumentHeader().getWorkflowDocument();
Set<String> currentRouteLevels = workflowDocument.getNodeNames();
return workflowDocument.isEnroute() && currentRouteLevels.contains(KFSConstants.RouteLevelNames.ACCOUNT);
}
}
|
package net.imagej.ops.math;
import java.util.Random;
import net.imagej.ops.AbstractNamespace;
import net.imagej.ops.MathOps;
import net.imagej.ops.OpMethod;
import net.imglib2.IterableInterval;
import net.imglib2.IterableRealInterval;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.img.array.ArrayImg;
import net.imglib2.img.basictypeaccess.array.ByteArray;
import net.imglib2.img.basictypeaccess.array.DoubleArray;
import net.imglib2.img.planar.PlanarImg;
import net.imglib2.type.numeric.NumericType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.ByteType;
import net.imglib2.type.numeric.real.DoubleType;
/**
* The math namespace contains arithmetic operations.
*
* @author Curtis Rueden
*/
public class MathNamespace extends AbstractNamespace {
// -- Math namespace ops --
@OpMethod(op = net.imagej.ops.MathOps.Abs.class)
public Object abs(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Abs.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerAbs.class)
public int abs(final int a) {
final int result =
(Integer) ops()
.run(net.imagej.ops.math.PrimitiveMath.IntegerAbs.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongAbs.class)
public long abs(final long a) {
final long result =
(Long) ops().run(net.imagej.ops.math.PrimitiveMath.LongAbs.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.FloatAbs.class)
public float abs(final float a) {
final float result =
(Float) ops().run(net.imagej.ops.math.PrimitiveMath.FloatAbs.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleAbs.class)
public double abs(final double a) {
final double result =
(Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleAbs.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealAbs.class)
public <I extends RealType<I>, O extends RealType<O>> O abs(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealAbs.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Add.class)
public Object add(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Add.class, args);
}
@OpMethod(ops = {
net.imagej.ops.arithmetic.add.parallel.AddConstantToArrayByteImageP.class,
net.imagej.ops.arithmetic.add.AddConstantToArrayByteImage.class })
public ArrayImg<ByteType, ByteArray> add(
final ArrayImg<ByteType, ByteArray> image, final byte value)
{
@SuppressWarnings("unchecked")
final ArrayImg<ByteType, ByteArray> result =
(ArrayImg<ByteType, ByteArray>) ops().run(MathOps.Add.NAME, image, value);
return result;
}
@OpMethod(
ops = {
net.imagej.ops.arithmetic.add.parallel.AddConstantToArrayDoubleImageP.class,
net.imagej.ops.arithmetic.add.AddConstantToArrayDoubleImage.class })
public
ArrayImg<DoubleType, DoubleArray> add(
final ArrayImg<DoubleType, DoubleArray> image, final double value)
{
@SuppressWarnings("unchecked")
final ArrayImg<DoubleType, DoubleArray> result =
(ArrayImg<DoubleType, DoubleArray>) ops().run(MathOps.Add.NAME, image,
value);
return result;
}
@OpMethod(op = net.imagej.ops.onthefly.ArithmeticOp.AddOp.class)
public Object add(final Object result, final Object a, final Object b) {
final Object result_op =
ops().run(net.imagej.ops.onthefly.ArithmeticOp.AddOp.class, result, a, b);
return result_op;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerAdd.class)
public int add(final int a, final int b) {
final int result =
(Integer) ops().run(net.imagej.ops.math.PrimitiveMath.IntegerAdd.class,
a, b);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongAdd.class)
public long add(final long a, final long b) {
final long result =
(Long) ops().run(net.imagej.ops.math.PrimitiveMath.LongAdd.class, a, b);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.FloatAdd.class)
public float add(final float a, final float b) {
final float result =
(Float) ops().run(net.imagej.ops.math.PrimitiveMath.FloatAdd.class, a, b);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleAdd.class)
public double add(final double a, final double b) {
final double result =
(Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleAdd.class, a,
b);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealAdd.class)
public <I extends RealType<I>, O extends RealType<O>> RealType<O> add(
final RealType<O> out, final RealType<I> in, final double constant)
{
@SuppressWarnings("unchecked")
final RealType<O> result =
(RealType<O>) ops().run(net.imagej.ops.arithmetic.real.RealAdd.class,
out, in, constant);
return result;
}
@OpMethod(
op = net.imagej.ops.arithmetic.add.AddRandomAccessibleIntervalToIterableInterval.class)
public
<T extends NumericType<T>> IterableInterval<T> add(
final IterableInterval<T> a, final RandomAccessibleInterval<T> b)
{
@SuppressWarnings("unchecked")
final IterableInterval<T> result =
(IterableInterval<T>) ops()
.run(
net.imagej.ops.arithmetic.add.AddRandomAccessibleIntervalToIterableInterval.class,
a, b);
return result;
}
@OpMethod(
op = net.imagej.ops.arithmetic.add.AddConstantToPlanarDoubleImage.class)
public PlanarImg<DoubleType, DoubleArray> add(
final PlanarImg<DoubleType, DoubleArray> image, final double value)
{
@SuppressWarnings("unchecked")
final PlanarImg<DoubleType, DoubleArray> result =
(PlanarImg<DoubleType, DoubleArray>) ops().run(
net.imagej.ops.arithmetic.add.AddConstantToPlanarDoubleImage.class,
image, value);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.add.AddConstantToImageInPlace.class)
public <T extends NumericType<T>> IterableRealInterval<T> add(
final IterableRealInterval<T> image, final T value)
{
@SuppressWarnings("unchecked")
final IterableRealInterval<T> result =
(IterableRealInterval<T>) ops().run(
net.imagej.ops.arithmetic.add.AddConstantToImageInPlace.class, image,
value);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.add.AddConstantToNumericType.class)
public <T extends NumericType<T>> T add(final T in, final T value) {
@SuppressWarnings("unchecked")
final T result =
(T) ops()
.run(net.imagej.ops.arithmetic.add.AddConstantToNumericType.class, in,
value);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.add.AddConstantToNumericType.class)
public <T extends NumericType<T>> T
add(final T out, final T in, final T value)
{
@SuppressWarnings("unchecked")
final T result =
(T) ops().run(
net.imagej.ops.arithmetic.add.AddConstantToNumericType.class, out, in,
value);
return result;
}
@OpMethod(
op = net.imagej.ops.arithmetic.add.AddConstantToImageFunctional.class)
public <T extends NumericType<T>> RandomAccessibleInterval<T> add(
final RandomAccessibleInterval<T> out, final IterableInterval<T> in,
final T value)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.arithmetic.add.AddConstantToImageFunctional.class, out,
in, value);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.AddNoise.class)
public Object addnoise(final Object... args) {
return ops().run(net.imagej.ops.MathOps.AddNoise.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealAddNoise.class)
public <I extends RealType<I>, O extends RealType<O>> O addnoise(final O out,
final I in, final double rangeMin, final double rangeMax,
final double rangeStdDev, final Random rng)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealAddNoise.class, out, in,
rangeMin, rangeMax, rangeStdDev, rng);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.And.class)
public Object and(final Object... args) {
return ops().run(net.imagej.ops.MathOps.And.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerAnd.class)
public int and(final int a, final int b) {
final int result =
(Integer) ops().run(net.imagej.ops.math.PrimitiveMath.IntegerAnd.class,
a, b);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongAnd.class)
public long and(final long a, final long b) {
final long result =
(Long) ops().run(net.imagej.ops.math.PrimitiveMath.LongAnd.class, a, b);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealAndConstant.class)
public <I extends RealType<I>, O extends RealType<O>> O and(final O out,
final I in, final long constant)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealAndConstant.class, out,
in, constant);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arccos.class)
public Object arccos(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arccos.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleArccos.class)
public double arccos(final double a) {
final double result =
(Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleArccos.class,
a);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealArccos.class)
public <I extends RealType<I>, O extends RealType<O>> O arccos(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealArccos.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arccosh.class)
public Object arccosh(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arccosh.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealArccosh.class)
public <I extends RealType<I>, O extends RealType<O>> O arccosh(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealArccosh.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arccot.class)
public Object arccot(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arccot.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealArccot.class)
public <I extends RealType<I>, O extends RealType<O>> O arccot(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealArccot.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arccoth.class)
public Object arccoth(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arccoth.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealArccoth.class)
public <I extends RealType<I>, O extends RealType<O>> O arccoth(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealArccoth.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arccsc.class)
public Object arccsc(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arccsc.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealArccsc.class)
public <I extends RealType<I>, O extends RealType<O>> O arccsc(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealArccsc.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arccsch.class)
public Object arccsch(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arccsch.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealArccsch.class)
public <I extends RealType<I>, O extends RealType<O>> O arccsch(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealArccsch.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arcsec.class)
public Object arcsec(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arcsec.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealArcsec.class)
public <I extends RealType<I>, O extends RealType<O>> O arcsec(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealArcsec.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arcsech.class)
public Object arcsech(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arcsech.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealArcsech.class)
public <I extends RealType<I>, O extends RealType<O>> O arcsech(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealArcsech.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arcsin.class)
public Object arcsin(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arcsin.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleArcsin.class)
public double arcsin(final double a) {
final double result =
(Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleArcsin.class,
a);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealArcsin.class)
public <I extends RealType<I>, O extends RealType<O>> O arcsin(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealArcsin.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arcsinh.class)
public Object arcsinh(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arcsinh.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealArcsinh.class)
public <I extends RealType<I>, O extends RealType<O>> O arcsinh(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealArcsinh.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arctan.class)
public Object arctan(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arctan.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleArctan.class)
public double arctan(final double a) {
final double result =
(Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleArctan.class,
a);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealArctan.class)
public <I extends RealType<I>, O extends RealType<O>> O arctan(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealArctan.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Arctanh.class)
public Object arctanh(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Arctanh.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealArctanh.class)
public <I extends RealType<I>, O extends RealType<O>> O arctanh(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealArctanh.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Ceil.class)
public Object ceil(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Ceil.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleCeil.class)
public double ceil(final double a) {
final double result =
(Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleCeil.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealCeil.class)
public <I extends RealType<I>, O extends RealType<O>> O ceil(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealCeil.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Complement.class)
public Object complement(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Complement.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerComplement.class)
public int complement(final int a) {
final int result =
(Integer) ops().run(
net.imagej.ops.math.PrimitiveMath.IntegerComplement.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongComplement.class)
public long complement(final long a) {
final long result =
(Long) ops().run(net.imagej.ops.math.PrimitiveMath.LongComplement.class,
a);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Copy.class)
public Object copy(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Copy.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealCopy.class)
public <I extends RealType<I>, O extends RealType<O>> O copy(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealCopy.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Cos.class)
public Object cos(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Cos.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleCos.class)
public double cos(final double a) {
final double result =
(Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleCos.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealCos.class)
public <I extends RealType<I>, O extends RealType<O>> O cos(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealCos.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Cosh.class)
public Object cosh(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Cosh.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleCosh.class)
public double cosh(final double a) {
final double result =
(Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleCosh.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealCosh.class)
public <I extends RealType<I>, O extends RealType<O>> O cosh(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealCosh.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Cot.class)
public Object cot(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Cot.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealCot.class)
public <I extends RealType<I>, O extends RealType<O>> O cot(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealCot.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Coth.class)
public Object coth(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Coth.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealCoth.class)
public <I extends RealType<I>, O extends RealType<O>> O coth(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealCoth.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Csc.class)
public Object csc(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Csc.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealCsc.class)
public <I extends RealType<I>, O extends RealType<O>> O csc(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealCsc.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Csch.class)
public Object csch(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Csch.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealCsch.class)
public <I extends RealType<I>, O extends RealType<O>> O csch(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealCsch.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.CubeRoot.class)
public Object cuberoot(final Object... args) {
return ops().run(net.imagej.ops.MathOps.CubeRoot.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleCubeRoot.class)
public double cuberoot(final double a) {
final double result =
(Double) ops().run(
net.imagej.ops.math.PrimitiveMath.DoubleCubeRoot.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealCubeRoot.class)
public <I extends RealType<I>, O extends RealType<O>> O cuberoot(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealCubeRoot.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Divide.class)
public Object divide(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Divide.class, args);
}
@OpMethod(op = net.imagej.ops.onthefly.ArithmeticOp.DivideOp.class)
public Object divide(final Object result, final Object a, final Object b) {
final Object result_op =
ops().run(net.imagej.ops.onthefly.ArithmeticOp.DivideOp.class, result, a,
b);
return result_op;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.IntegerDivide.class)
public int divide(final int a, final int b) {
final int result =
(Integer) ops().run(
net.imagej.ops.math.PrimitiveMath.IntegerDivide.class, a, b);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.LongDivide.class)
public long divide(final long a, final long b) {
final long result =
(Long) ops()
.run(net.imagej.ops.math.PrimitiveMath.LongDivide.class, a, b);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.FloatDivide.class)
public float divide(final float a, final float b) {
final float result =
(Float) ops().run(net.imagej.ops.math.PrimitiveMath.FloatDivide.class, a,
b);
return result;
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleDivide.class)
public double divide(final double a, final double b) {
final double result =
(Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleDivide.class,
a, b);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealDivide.class)
public <I extends RealType<I>, O extends RealType<O>> O divide(final O out,
final I in, final double constant, final double dbzVal)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealDivide.class, out, in,
constant, dbzVal);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Exp.class)
public Object exp(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Exp.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleExp.class)
public double exp(final double a) {
final double result =
(Double) ops().run(net.imagej.ops.math.PrimitiveMath.DoubleExp.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealExp.class)
public <I extends RealType<I>, O extends RealType<O>> O exp(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealExp.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.ExpMinusOne.class)
public Object expminusone(final Object... args) {
return ops().run(net.imagej.ops.MathOps.ExpMinusOne.class, args);
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealExpMinusOne.class)
public <I extends RealType<I>, O extends RealType<O>> O expminusone(
final O out, final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealExpMinusOne.class, out,
in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Floor.class)
public Object floor(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Floor.class, args);
}
@OpMethod(op = net.imagej.ops.math.PrimitiveMath.DoubleFloor.class)
public double floor(final double a) {
final double result =
(Double) ops()
.run(net.imagej.ops.math.PrimitiveMath.DoubleFloor.class, a);
return result;
}
@OpMethod(op = net.imagej.ops.arithmetic.real.RealFloor.class)
public <I extends RealType<I>, O extends RealType<O>> O floor(final O out,
final I in)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.arithmetic.real.RealFloor.class, out, in);
return result;
}
@OpMethod(op = net.imagej.ops.MathOps.Gamma.class)
public Object gamma(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Gamma.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.GaussianRandom.class)
public Object gaussianrandom(final Object... args) {
return ops().run(net.imagej.ops.MathOps.GaussianRandom.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Invert.class)
public Object invert(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Invert.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.LeftShift.class)
public Object leftshift(final Object... args) {
return ops().run(net.imagej.ops.MathOps.LeftShift.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Log.class)
public Object log(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Log.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Log2.class)
public Object log2(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Log2.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Log10.class)
public Object log10(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Log10.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.LogOnePlusX.class)
public Object logoneplusx(final Object... args) {
return ops().run(net.imagej.ops.MathOps.LogOnePlusX.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Max.class)
public Object max(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Max.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Min.class)
public Object min(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Min.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Multiply.class)
public Object multiply(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Multiply.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.NearestInt.class)
public Object nearestint(final Object... args) {
return ops().run(net.imagej.ops.MathOps.NearestInt.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Negate.class)
public Object negate(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Negate.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Or.class)
public Object or(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Or.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Power.class)
public Object power(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Power.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Reciprocal.class)
public Object reciprocal(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Reciprocal.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Remainder.class)
public Object remainder(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Remainder.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.RightShift.class)
public Object rightshift(final Object... args) {
return ops().run(net.imagej.ops.MathOps.RightShift.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Round.class)
public Object round(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Round.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Sec.class)
public Object sec(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Sec.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Sech.class)
public Object sech(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Sech.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Signum.class)
public Object signum(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Signum.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Sin.class)
public Object sin(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Sin.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Sinc.class)
public Object sinc(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Sinc.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.SincPi.class)
public Object sincpi(final Object... args) {
return ops().run(net.imagej.ops.MathOps.SincPi.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Sinh.class)
public Object sinh(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Sinh.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Sqr.class)
public Object sqr(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Sqr.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Sqrt.class)
public Object sqrt(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Sqrt.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Step.class)
public Object step(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Step.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Subtract.class)
public Object subtract(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Subtract.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Tan.class)
public Object tan(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Tan.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Tanh.class)
public Object tanh(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Tanh.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Ulp.class)
public Object ulp(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Ulp.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.UniformRandom.class)
public Object uniformrandom(final Object... args) {
return ops().run(net.imagej.ops.MathOps.UniformRandom.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.UnsignedRightShift.class)
public Object unsignedrightshift(final Object... args) {
return ops().run(net.imagej.ops.MathOps.UnsignedRightShift.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Xor.class)
public Object xor(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Xor.class, args);
}
@OpMethod(op = net.imagej.ops.MathOps.Zero.class)
public Object zero(final Object... args) {
return ops().run(net.imagej.ops.MathOps.Zero.class, args);
}
// -- Named methods --
@Override
public String getName() {
return "math";
}
}
|
package com.braintreepayments.api.models;
import android.content.Context;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Contains the remote Android Pay configuration for the Braintree SDK.
*/
public class AndroidPayConfiguration {
private static final String ENABLED_KEY = "enabled";
private static final String GOOGLE_AUTHORIZATION_FINGERPRINT_KEY = "googleAuthorizationFingerprint";
private static final String ENVIRONMENT_KEY = "environment";
private static final String DISPLAY_NAME_KEY = "displayName";
private static final String SUPPORTED_NETWORKS_KEY = "supportedNetworks";
private boolean mEnabled;
private String mGoogleAuthorizationFingerprint;
private String mEnvironment;
private String mDisplayName;
private String[] mSupportedNetworks;
/**
* Parse an {@link AndroidPayConfiguration} from json.
*
* @param json The {@link JSONObject} to parse.
* @return An {@link AndroidPayConfiguration} instance with data that was able to be parsed from
* the {@link JSONObject}.
*/
public static AndroidPayConfiguration fromJson(JSONObject json) {
if (json == null) {
json = new JSONObject();
}
AndroidPayConfiguration androidPayConfiguration = new AndroidPayConfiguration();
androidPayConfiguration.mEnabled = json.optBoolean(ENABLED_KEY, false);
androidPayConfiguration.mGoogleAuthorizationFingerprint = json.optString(
GOOGLE_AUTHORIZATION_FINGERPRINT_KEY, null);
androidPayConfiguration.mEnvironment = json.optString(ENVIRONMENT_KEY, null);
androidPayConfiguration.mDisplayName = json.optString(DISPLAY_NAME_KEY, null);
JSONArray supportedNetworks = json.optJSONArray(SUPPORTED_NETWORKS_KEY);
if (supportedNetworks != null) {
androidPayConfiguration.mSupportedNetworks = new String[supportedNetworks.length()];
for (int i = 0; i < supportedNetworks.length(); i++) {
try {
androidPayConfiguration.mSupportedNetworks[i] = supportedNetworks.getString(i);
} catch (JSONException ignored) {}
}
} else {
androidPayConfiguration.mSupportedNetworks = new String[0];
}
return androidPayConfiguration;
}
/**
* @return {@code true} if Android Pay is enabled and supported in the current environment,
* {@code false} otherwise.
*/
public boolean isEnabled(Context context) {
try {
return mEnabled &&
GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context) ==
ConnectionResult.SUCCESS;
} catch (NoClassDefFoundError e) {
return false;
}
}
/**
* @return the authorization fingerprint to use for Android Pay, only allows tokenizing Android Pay cards.
*/
public String getGoogleAuthorizationFingerprint() {
return mGoogleAuthorizationFingerprint;
}
/**
* @return the current Android Pay environment.
*/
public String getEnvironment() {
return mEnvironment;
}
/**
* @return the display name to show to the user.
*/
public String getDisplayName() {
return mDisplayName;
}
/**
* @return a string array of supported card networks for Android Pay.
*/
public String[] getSupportedNetworks() {
return mSupportedNetworks;
}
}
|
package io.kortex.aes;
public class CipherBlock {
private byte[] salt;
private byte[] iv;
private byte[] cipherText;
public CipherBlock(byte[] salt, byte[] iv, byte[] cipherText) {
super();
this.salt = salt.clone();
this.iv = iv.clone();
this.cipherText = cipherText.clone();
}
public byte[] getSalt() {
return salt.clone();
}
public byte[] getIv() {
return iv.clone();
}
public byte[] getCipherText() {
return cipherText.clone();
}
@override
public int hashCode(){
return 1;
}
}
|
package net.openhft.chronicle.bytes;
import net.openhft.chronicle.core.util.StringUtils;
import org.jetbrains.annotations.NotNull;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
public interface Bytes<Underlying> extends BytesStore<Bytes<Underlying>, Underlying>,
StreamingDataInput<Bytes<Underlying>>,
StreamingDataOutput<Bytes<Underlying>>,
ByteStringParser<Bytes<Underlying>>,
ByteStringAppender<Bytes<Underlying>> {
long MAX_CAPACITY = Long.MAX_VALUE; // 8 EiB - 1
static Bytes<ByteBuffer> elasticByteBuffer() {
return NativeBytesStore.elasticByteBuffer().bytesForWrite();
}
static Bytes<ByteBuffer> wrapForRead(ByteBuffer byteBuffer) {
return BytesStore.wrap(byteBuffer).bytesForRead();
}
static Bytes<ByteBuffer> wrapForWrite(ByteBuffer byteBuffer) {
return BytesStore.wrap(byteBuffer).bytesForWrite();
}
@NotNull
static Bytes<byte[]> expect(@NotNull String text) {
return expect(wrapForRead(text.getBytes(StandardCharsets.ISO_8859_1)));
}
@NotNull
static <B extends BytesStore<B, Underlying>, Underlying> Bytes<Underlying> expect(BytesStore<B, Underlying> bytesStore) {
return new VanillaBytes<>(new ExpectedBytesStore<>(bytesStore));
}
static Bytes<byte[]> wrapForRead(byte[] byteArray) {
return BytesStore.<byte[]>wrap(byteArray).bytesForRead();
}
static Bytes<byte[]> wrapForWrite(byte[] byteArray) {
return BytesStore.<byte[]>wrap(byteArray).bytesForWrite();
}
static Bytes<byte[]> wrapForRead(@NotNull CharSequence text) {
return wrapForRead(text.toString().getBytes(StandardCharsets.ISO_8859_1));
}
static VanillaBytes<Void> allocateDirect(long capacity) {
return NativeBytesStore.nativeStoreWithFixedCapacity(capacity).bytesForWrite();
}
static NativeBytes<Void> allocateElasticDirect() {
return NativeBytes.nativeBytes();
}
static NativeBytes<Void> allocateElasticDirect(long initialCapacity) {
return NativeBytes.nativeBytes(initialCapacity);
}
@Deprecated
static Bytes from(String s) {
return BytesStore.wrap(s).bytesForRead();
}
/**
* Creates a string from the {@code position} to the {@code limit}, The buffer is not modified
* by this call
*
* @param buffer the buffer to use
* @return a string contain the text from the {@code position} to the {@code limit}
*/
static String toString(@NotNull final Bytes<?> buffer) {
if (buffer.readRemaining() == 0)
return "";
return buffer.parseWithLength(buffer.readRemaining(), b -> {
final StringBuilder builder = new StringBuilder();
while (buffer.readRemaining() > 0) {
builder.append((char) buffer.readByte());
}
// remove the last comma
return builder.toString();
});
}
static String toString(@NotNull final Bytes buffer, long position, long len) {
final long pos = buffer.readPosition();
final long limit = buffer.readLimit();
buffer.readPosition(position);
buffer.readLimit(position + len);
try {
final StringBuilder builder = new StringBuilder();
while (buffer.readRemaining() > 0) {
builder.append((char) buffer.readByte());
}
// remove the last comma
return builder.toString();
} finally {
buffer.readLimit(limit);
buffer.readPosition(pos);
}
}
static BytesStore empty() {
return NoBytesStore.noBytesStore();
}
default Bytes<Underlying> unchecked(boolean unchecked) {
return unchecked ?
start() == 0 && bytesStore() instanceof NativeBytesStore ?
new UncheckedNativeBytes<Underlying>(this) :
new UncheckedBytes<>(this) :
this;
}
default long safeLimit() {
return bytesStore().safeLimit();
}
default boolean isClear() {
return start() == readPosition() && writeLimit() == capacity();
}
default long realCapacity() {
return BytesStore.super.realCapacity();
}
/**
* @return a copy of this Bytes from position() to limit().
*/
BytesStore<Bytes<Underlying>, Underlying> copy();
/**
* display the hex data of {@link Bytes} from the position() to the limit()
*
* @return hex representation of the buffer, from example [0D ,OA, FF]
*/
@NotNull
default String toHexString() {
return BytesUtil.toHexString(this);
}
@NotNull
default String toHexString(long maxLength) {
if (readRemaining() < maxLength) return toHexString();
return BytesUtil.toHexString(this, readPosition(), maxLength) + ".... truncated";
}
/**
* @return can the Bytes resize when more data is written than it's realCapacity()
*/
boolean isElastic();
/**
* grow the buffer if the buffer is elastic, if the buffer is not elastic and there is not enough capacity then this
* method will throws {@link java.nio.BufferOverflowException}
*
* @param size the capacity that you required
* @throws java.nio.BufferOverflowException if the buffer is not elastic and there is not enough space
*/
default void ensureCapacity(long size) {
if (size > capacity())
throw new UnsupportedOperationException(isElastic() ? "todo" : "not elastic");
}
/**
* Creates a slice of the current Bytes based on its position() and limit(). As a sub-section of a Bytes it cannot
* be elastic.
*
* @return a slice of the existing Bytes where the start is moved to the position and the current limit determines
* the capacity.
*/
@Override
default Bytes<Underlying> bytesForRead() {
return isClear() ? BytesStore.super.bytesForRead() : new SubBytes<>(this, readPosition(), readLimit() + start());
}
/**
* @return the ByteStore this Bytes wraps.
*/
BytesStore bytesStore();
default boolean isEqual(String s) {
return StringUtils.isEqual(this, s);
}
/**
* copies the contents of bytes into a direct byte buffer
*
* @param bytes the bytes to wrap
* @return a direct byte buffer contain the {@code bytes}
*/
static Bytes allocateDirect(@NotNull byte[] bytes) {
VanillaBytes<Void> result = allocateDirect(bytes.length);
result.write(bytes);
return result;
}
}
|
package org.opendaylight.controller.md.sal.common.impl.service;
import java.util.concurrent.Future;
import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
import org.opendaylight.controller.md.sal.common.impl.AbstractDataModification;
import org.opendaylight.yangtools.concepts.Path;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractDataTransaction<P extends Path<P>, D extends Object> extends
AbstractDataModification<P, D> {
private final static Logger LOG = LoggerFactory.getLogger(AbstractDataTransaction.class);
private final Object identifier;
@Override
public Object getIdentifier() {
return this.identifier;
}
private TransactionStatus status;
private final AbstractDataBroker<P, D, ? extends Object> broker;
protected AbstractDataTransaction(final Object identifier,
final AbstractDataBroker<P, D, ? extends Object> dataBroker) {
super(dataBroker);
this.identifier = identifier;
this.broker = dataBroker;
this.status = TransactionStatus.NEW;
AbstractDataTransaction.LOG.debug("Transaction {} Allocated.", identifier);
}
@Override
public Future<RpcResult<TransactionStatus>> commit() {
return this.broker.commit(this);
}
@Override
public D readConfigurationData(final P path) {
final D local = getUpdatedConfigurationData().get(path);
if (local != null) {
return local;
}
return this.broker.readConfigurationData(path);
}
@Override
public D readOperationalData(final P path) {
final D local = this.getUpdatedOperationalData().get(path);
if (local != null) {
return local;
}
return this.broker.readOperationalData(path);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((identifier == null) ? 0 : identifier.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AbstractDataTransaction<?, ?> other = (AbstractDataTransaction<?, ?>) obj;
if (identifier == null) {
if (other.identifier != null)
return false;
} else if (!identifier.equals(other.identifier))
return false;
return true;
}
@Override
public TransactionStatus getStatus() {
return this.status;
}
protected abstract void onStatusChange(final TransactionStatus status);
public void changeStatus(final TransactionStatus status) {
Object _identifier = this.getIdentifier();
AbstractDataTransaction.LOG
.debug("Transaction {} transitioned from {} to {}", _identifier, this.status, status);
this.status = status;
this.onStatusChange(status);
}
}
|
package net.spy.memcached.auth;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import net.spy.memcached.KeyUtil;
import net.spy.memcached.MemcachedConnection;
import net.spy.memcached.MemcachedNode;
import net.spy.memcached.OperationFactory;
import net.spy.memcached.compat.SpyThread;
import net.spy.memcached.ops.Operation;
import net.spy.memcached.ops.OperationCallback;
import net.spy.memcached.ops.OperationStatus;
/**
* A thread that does SASL authentication.
*/
public class AuthThread extends SpyThread {
public static final String MECH_SEPARATOR = " ";
private final MemcachedConnection conn;
private final AuthDescriptor authDescriptor;
private final OperationFactory opFact;
private final MemcachedNode node;
public AuthThread(MemcachedConnection c, OperationFactory o,
AuthDescriptor a, MemcachedNode n) {
conn = c;
opFact = o;
authDescriptor = a;
node = n;
start();
}
private String[] listSupportedSASLMechanisms(AtomicBoolean done) {
final CountDownLatch listMechsLatch = new CountDownLatch(1);
final AtomicReference<String> supportedMechs =
new AtomicReference<String>();
Operation listMechsOp = opFact.saslMechs(new OperationCallback() {
@Override
public void receivedStatus(OperationStatus status) {
if(status.isSuccess()) {
supportedMechs.set(status.getMessage());
getLogger().debug("Received SASL supported mechs: "
+ status.getMessage());
}
}
@Override
public void complete() {
listMechsLatch.countDown();
}
});
conn.insertOperation(node, listMechsOp);
try {
listMechsLatch.await();
} catch(InterruptedException ex) {
// we can be interrupted if we were in the
// process of auth'ing and the connection is
// lost or dropped due to bad auth
Thread.currentThread().interrupt();
if (listMechsOp != null) {
listMechsOp.cancel();
}
done.set(true); // If we were interrupted, tear down.
}
String supported = supportedMechs.get();
if (supported == null || supported.isEmpty()) {
throw new IllegalStateException("Got empty SASL auth mech list.");
}
return supported.split(MECH_SEPARATOR);
}
@Override
public void run() {
final AtomicBoolean done = new AtomicBoolean();
String[] supportedMechs;
if (authDescriptor.getMechs() == null
|| authDescriptor.getMechs().length == 0) {
supportedMechs = listSupportedSASLMechanisms(done);
} else {
supportedMechs = authDescriptor.getMechs();
}
OperationStatus priorStatus = null;
while (!done.get()) {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<OperationStatus> foundStatus =
new AtomicReference<OperationStatus>();
final OperationCallback cb = new OperationCallback() {
@Override
public void receivedStatus(OperationStatus val) {
// If the status we found was null, we're done.
if (val.getMessage().length() == 0) {
done.set(true);
node.authComplete();
getLogger().info("Authenticated to " + node.getSocketAddress());
} else {
foundStatus.set(val);
}
}
@Override
public void complete() {
latch.countDown();
}
};
// Get the prior status to create the correct operation.
final Operation op = buildOperation(priorStatus, cb, supportedMechs);
conn.insertOperation(node, op);
try {
latch.await();
Thread.sleep(100);
} catch (InterruptedException e) {
// we can be interrupted if we were in the
// process of auth'ing and the connection is
// lost or dropped due to bad auth
Thread.currentThread().interrupt();
if (op != null) {
op.cancel();
}
done.set(true); // If we were interrupted, tear down.
}
// Get the new status to inspect it.
priorStatus = foundStatus.get();
if (priorStatus != null) {
if (!priorStatus.isSuccess()) {
getLogger().warn(
"Authentication failed to " + node.getSocketAddress());
}
}
}
}
private Operation buildOperation(OperationStatus st, OperationCallback cb,
final String [] supportedMechs) {
if (st == null) {
return opFact.saslAuth(supportedMechs,
node.getSocketAddress().toString(), null,
authDescriptor.getCallback(), cb);
} else {
return opFact.saslStep(supportedMechs, KeyUtil.getKeyBytes(
st.getMessage()), node.getSocketAddress().toString(), null,
authDescriptor.getCallback(), cb);
}
}
}
|
package org.opendaylight.controller.cluster.datastore;
import akka.actor.ActorRef;
import akka.actor.Status.Failure;
import akka.serialization.Serialization;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.primitives.UnsignedLong;
import com.google.common.util.concurrent.FutureCallback;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import javax.annotation.Nonnull;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
import org.opendaylight.controller.cluster.datastore.messages.VersionedExternalizableMessage;
import org.opendaylight.controller.cluster.datastore.utils.AbstractBatchedModificationsCursor;
import org.opendaylight.yangtools.concepts.Identifier;
import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
import org.slf4j.Logger;
/**
* Coordinates commits for a shard ensuring only one concurrent 3-phase commit.
*
* @author Thomas Pantelis
*/
final class ShardCommitCoordinator {
// Interface hook for unit tests to replace or decorate the ShardDataTreeCohorts.
@VisibleForTesting
public interface CohortDecorator {
ShardDataTreeCohort decorate(Identifier transactionID, ShardDataTreeCohort actual);
}
private final Map<Identifier, CohortEntry> cohortCache = new HashMap<>();
private final ShardDataTree dataTree;
private final Logger log;
private final String name;
// This is a hook for unit tests to replace or decorate the ShardDataTreeCohorts.
@VisibleForTesting
private CohortDecorator cohortDecorator;
private ReadyTransactionReply readyTransactionReply;
ShardCommitCoordinator(final ShardDataTree dataTree, final Logger log, final String name) {
this.log = log;
this.name = name;
this.dataTree = Preconditions.checkNotNull(dataTree);
}
int getCohortCacheSize() {
return cohortCache.size();
}
private String persistenceId() {
return dataTree.logContext();
}
private ReadyTransactionReply readyTransactionReply(final ActorRef cohort) {
if (readyTransactionReply == null) {
readyTransactionReply = new ReadyTransactionReply(Serialization.serializedActorPath(cohort));
}
return readyTransactionReply;
}
/**
* This method is called to ready a transaction that was prepared by ShardTransaction actor. It caches
* the prepared cohort entry for the given transactions ID in preparation for the subsequent 3-phase commit.
*
* @param ready the ForwardedReadyTransaction message to process
* @param sender the sender of the message
* @param shard the transaction's shard actor
*/
void handleForwardedReadyTransaction(final ForwardedReadyTransaction ready, final ActorRef sender,
final Shard shard) {
log.debug("{}: Readying transaction {}, client version {}", name,
ready.getTransactionId(), ready.getTxnClientVersion());
final ShardDataTreeCohort cohort = ready.getTransaction().ready();
final CohortEntry cohortEntry = CohortEntry.createReady(cohort, ready.getTxnClientVersion());
cohortCache.put(cohortEntry.getTransactionId(), cohortEntry);
if (ready.isDoImmediateCommit()) {
cohortEntry.setDoImmediateCommit(true);
cohortEntry.setReplySender(sender);
cohortEntry.setShard(shard);
handleCanCommit(cohortEntry);
} else {
// The caller does not want immediate commit - the 3-phase commit will be coordinated by the
// front-end so send back a ReadyTransactionReply with our actor path.
sender.tell(readyTransactionReply(shard.self()), shard.self());
}
}
/**
* This method handles a BatchedModifications message for a transaction being prepared directly on the
* Shard actor instead of via a ShardTransaction actor. If there's no currently cached
* DOMStoreWriteTransaction, one is created. The batched modifications are applied to the write Tx. If
* the BatchedModifications is ready to commit then a DOMStoreThreePhaseCommitCohort is created.
*
* @param batched the BatchedModifications message to process
* @param sender the sender of the message
*/
void handleBatchedModifications(final BatchedModifications batched, final ActorRef sender, final Shard shard) {
CohortEntry cohortEntry = cohortCache.get(batched.getTransactionId());
if (cohortEntry == null) {
cohortEntry = CohortEntry.createOpen(dataTree.newReadWriteTransaction(batched.getTransactionId()),
batched.getVersion());
cohortCache.put(cohortEntry.getTransactionId(), cohortEntry);
}
if (log.isDebugEnabled()) {
log.debug("{}: Applying {} batched modifications for Tx {}", name,
batched.getModifications().size(), batched.getTransactionId());
}
cohortEntry.applyModifications(batched.getModifications());
if (batched.isReady()) {
if (cohortEntry.getLastBatchedModificationsException() != null) {
cohortCache.remove(cohortEntry.getTransactionId());
throw cohortEntry.getLastBatchedModificationsException();
}
if (cohortEntry.getTotalBatchedModificationsReceived() != batched.getTotalMessagesSent()) {
cohortCache.remove(cohortEntry.getTransactionId());
throw new IllegalStateException(String.format(
"The total number of batched messages received %d does not match the number sent %d",
cohortEntry.getTotalBatchedModificationsReceived(), batched.getTotalMessagesSent()));
}
if (log.isDebugEnabled()) {
log.debug("{}: Readying Tx {}, client version {}", name,
batched.getTransactionId(), batched.getVersion());
}
cohortEntry.setDoImmediateCommit(batched.isDoCommitOnReady());
cohortEntry.ready(cohortDecorator);
if (batched.isDoCommitOnReady()) {
cohortEntry.setReplySender(sender);
cohortEntry.setShard(shard);
handleCanCommit(cohortEntry);
} else {
sender.tell(readyTransactionReply(shard.self()), shard.self());
}
} else {
sender.tell(new BatchedModificationsReply(batched.getModifications().size()), shard.self());
}
}
/**
* This method handles {@link ReadyLocalTransaction} message. All transaction modifications have
* been prepared beforehand by the sender and we just need to drive them through into the
* dataTree.
*
* @param message the ReadyLocalTransaction message to process
* @param sender the sender of the message
* @param shard the transaction's shard actor
*/
void handleReadyLocalTransaction(final ReadyLocalTransaction message, final ActorRef sender, final Shard shard) {
final ShardDataTreeCohort cohort = dataTree.createReadyCohort(message.getTransactionId(),
message.getModification());
final CohortEntry cohortEntry = CohortEntry.createReady(cohort, DataStoreVersions.CURRENT_VERSION);
cohortCache.put(cohortEntry.getTransactionId(), cohortEntry);
cohortEntry.setDoImmediateCommit(message.isDoCommitOnReady());
log.debug("{}: Applying local modifications for Tx {}", name, message.getTransactionId());
if (message.isDoCommitOnReady()) {
cohortEntry.setReplySender(sender);
cohortEntry.setShard(shard);
handleCanCommit(cohortEntry);
} else {
sender.tell(readyTransactionReply(shard.self()), shard.self());
}
}
Collection<BatchedModifications> createForwardedBatchedModifications(final BatchedModifications from,
final int maxModificationsPerBatch) {
CohortEntry cohortEntry = cohortCache.remove(from.getTransactionId());
if (cohortEntry == null || cohortEntry.getTransaction() == null) {
return Collections.singletonList(from);
}
cohortEntry.applyModifications(from.getModifications());
final LinkedList<BatchedModifications> newModifications = new LinkedList<>();
cohortEntry.getTransaction().getSnapshot().applyToCursor(new AbstractBatchedModificationsCursor() {
@Override
protected BatchedModifications getModifications() {
if (newModifications.isEmpty()
|| newModifications.getLast().getModifications().size() >= maxModificationsPerBatch) {
newModifications.add(new BatchedModifications(from.getTransactionId(), from.getVersion()));
}
return newModifications.getLast();
}
});
BatchedModifications last = newModifications.getLast();
last.setDoCommitOnReady(from.isDoCommitOnReady());
last.setReady(from.isReady());
last.setTotalMessagesSent(newModifications.size());
return newModifications;
}
private void handleCanCommit(final CohortEntry cohortEntry) {
cohortEntry.canCommit(new FutureCallback<Void>() {
@Override
public void onSuccess(final Void result) {
log.debug("{}: canCommit for {}: success", name, cohortEntry.getTransactionId());
if (cohortEntry.isDoImmediateCommit()) {
doCommit(cohortEntry);
} else {
cohortEntry.getReplySender().tell(
CanCommitTransactionReply.yes(cohortEntry.getClientVersion()).toSerializable(),
cohortEntry.getShard().self());
}
}
@Override
public void onFailure(final Throwable failure) {
log.debug("{}: An exception occurred during canCommit for {}: {}", name,
cohortEntry.getTransactionId(), failure);
cohortCache.remove(cohortEntry.getTransactionId());
cohortEntry.getReplySender().tell(new Failure(failure), cohortEntry.getShard().self());
}
});
}
/**
* This method handles the canCommit phase for a transaction.
*
* @param transactionID the ID of the transaction to canCommit
* @param sender the actor to which to send the response
* @param shard the transaction's shard actor
*/
void handleCanCommit(final Identifier transactionID, final ActorRef sender, final Shard shard) {
// Lookup the cohort entry that was cached previously (or should have been) by
// transactionReady (via the ForwardedReadyTransaction message).
final CohortEntry cohortEntry = cohortCache.get(transactionID);
if (cohortEntry == null) {
// Either canCommit was invoked before ready (shouldn't happen) or a long time passed
// between canCommit and ready and the entry was expired from the cache or it was aborted.
IllegalStateException ex = new IllegalStateException(
String.format("%s: Cannot canCommit transaction %s - no cohort entry found", name, transactionID));
log.error(ex.getMessage());
sender.tell(new Failure(ex), shard.self());
return;
}
cohortEntry.setReplySender(sender);
cohortEntry.setShard(shard);
handleCanCommit(cohortEntry);
}
void doCommit(final CohortEntry cohortEntry) {
log.debug("{}: Committing transaction {}", name, cohortEntry.getTransactionId());
// We perform the preCommit phase here atomically with the commit phase. This is an
// optimization to eliminate the overhead of an extra preCommit message. We lose front-end
// coordination of preCommit across shards in case of failure but preCommit should not
// normally fail since we ensure only one concurrent 3-phase commit.
cohortEntry.preCommit(new FutureCallback<DataTreeCandidate>() {
@Override
public void onSuccess(final DataTreeCandidate candidate) {
finishCommit(cohortEntry.getReplySender(), cohortEntry);
}
@Override
public void onFailure(final Throwable failure) {
log.error("{} An exception occurred while preCommitting transaction {}", name,
cohortEntry.getTransactionId(), failure);
cohortCache.remove(cohortEntry.getTransactionId());
cohortEntry.getReplySender().tell(new Failure(failure), cohortEntry.getShard().self());
}
});
}
void finishCommit(@Nonnull final ActorRef sender, @Nonnull final CohortEntry cohortEntry) {
log.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionId());
cohortEntry.commit(new FutureCallback<UnsignedLong>() {
@Override
public void onSuccess(final UnsignedLong result) {
final TransactionIdentifier txId = cohortEntry.getTransactionId();
log.debug("{}: Transaction {} committed as {}, sending response to {}", persistenceId(), txId, result,
sender);
cohortCache.remove(cohortEntry.getTransactionId());
sender.tell(CommitTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(),
cohortEntry.getShard().self());
}
@Override
public void onFailure(final Throwable failure) {
log.error("{}, An exception occurred while committing transaction {}", persistenceId(),
cohortEntry.getTransactionId(), failure);
cohortCache.remove(cohortEntry.getTransactionId());
sender.tell(new Failure(failure), cohortEntry.getShard().self());
}
});
}
/**
* This method handles the preCommit and commit phases for a transaction.
*
* @param transactionID the ID of the transaction to commit
* @param sender the actor to which to send the response
* @param shard the transaction's shard actor
*/
void handleCommit(final Identifier transactionID, final ActorRef sender, final Shard shard) {
final CohortEntry cohortEntry = cohortCache.get(transactionID);
if (cohortEntry == null) {
// Either a long time passed between canCommit and commit and the entry was expired from the cache
// or it was aborted.
IllegalStateException ex = new IllegalStateException(
String.format("%s: Cannot commit transaction %s - no cohort entry found", name, transactionID));
log.error(ex.getMessage());
sender.tell(new Failure(ex), shard.self());
return;
}
cohortEntry.setReplySender(sender);
doCommit(cohortEntry);
}
@SuppressWarnings("checkstyle:IllegalCatch")
void handleAbort(final Identifier transactionID, final ActorRef sender, final Shard shard) {
CohortEntry cohortEntry = cohortCache.remove(transactionID);
if (cohortEntry == null) {
return;
}
log.debug("{}: Aborting transaction {}", name, transactionID);
final ActorRef self = shard.getSelf();
cohortEntry.abort(new FutureCallback<Void>() {
@Override
public void onSuccess(final Void result) {
if (sender != null) {
sender.tell(AbortTransactionReply.instance(cohortEntry.getClientVersion()).toSerializable(), self);
}
}
@Override
public void onFailure(final Throwable failure) {
log.error("{}: An exception happened during abort", name, failure);
if (sender != null) {
sender.tell(new Failure(failure), self);
}
}
});
shard.getShardMBean().incrementAbortTransactionsCount();
}
void checkForExpiredTransactions(final long timeout, final Shard shard) {
Iterator<CohortEntry> iter = cohortCache.values().iterator();
while (iter.hasNext()) {
CohortEntry cohortEntry = iter.next();
if (cohortEntry.isFailed()) {
iter.remove();
}
}
}
void abortPendingTransactions(final String reason, final Shard shard) {
final Failure failure = new Failure(new RuntimeException(reason));
Collection<ShardDataTreeCohort> pending = dataTree.getAndClearPendingTransactions();
log.debug("{}: Aborting {} pending queued transactions", name, pending.size());
for (ShardDataTreeCohort cohort : pending) {
CohortEntry cohortEntry = cohortCache.remove(cohort.getIdentifier());
if (cohortEntry == null) {
continue;
}
if (cohortEntry.getReplySender() != null) {
cohortEntry.getReplySender().tell(failure, shard.self());
}
}
cohortCache.clear();
}
Collection<?> convertPendingTransactionsToMessages(final int maxModificationsPerBatch) {
final Collection<VersionedExternalizableMessage> messages = new ArrayList<>();
for (ShardDataTreeCohort cohort : dataTree.getAndClearPendingTransactions()) {
CohortEntry cohortEntry = cohortCache.remove(cohort.getIdentifier());
if (cohortEntry == null) {
continue;
}
final Deque<BatchedModifications> newMessages = new ArrayDeque<>();
cohortEntry.getDataTreeModification().applyToCursor(new AbstractBatchedModificationsCursor() {
@Override
protected BatchedModifications getModifications() {
final BatchedModifications lastBatch = newMessages.peekLast();
if (lastBatch != null && lastBatch.getModifications().size() >= maxModificationsPerBatch) {
return lastBatch;
}
// Allocate a new message
final BatchedModifications ret = new BatchedModifications(cohortEntry.getTransactionId(),
cohortEntry.getClientVersion());
newMessages.add(ret);
return ret;
}
});
final BatchedModifications last = newMessages.peekLast();
if (last != null) {
final boolean immediate = cohortEntry.isDoImmediateCommit();
last.setDoCommitOnReady(immediate);
last.setReady(true);
last.setTotalMessagesSent(newMessages.size());
messages.addAll(newMessages);
if (!immediate) {
switch (cohort.getState()) {
case CAN_COMMIT_COMPLETE:
case CAN_COMMIT_PENDING:
messages.add(new CanCommitTransaction(cohortEntry.getTransactionId(),
cohortEntry.getClientVersion()));
break;
case PRE_COMMIT_COMPLETE:
case PRE_COMMIT_PENDING:
messages.add(new CommitTransaction(cohortEntry.getTransactionId(),
cohortEntry.getClientVersion()));
break;
default:
break;
}
}
}
}
return messages;
}
@VisibleForTesting
void setCohortDecorator(final CohortDecorator cohortDecorator) {
this.cohortDecorator = cohortDecorator;
}
}
|
package de.uka.ipd.sdq.beagle.core.pcmconnection;
import de.uka.ipd.sdq.beagle.core.CodeSection;
import de.uka.ipd.sdq.beagle.core.facade.SourceCodeFileProvider;
import de.uka.ipd.sdq.beagle.core.pcmsourcestatementlink.PcmSourceStatementLink;
import de.uka.ipd.sdq.beagle.core.pcmsourcestatementlink.PcmSourceStatementLinkRepository;
import de.uka.ipd.sdq.beagle.core.pcmsourcestatementlink.SourceCodePosition;
import org.apache.commons.lang3.Validate;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
/**
* This class manages the creation of the {@link CodeSection} for a given ID using the
* {@link PcmSourceStatementLinkRepository}.
*
* @author Ansgar Spiegler
*/
public class PcmCodeSectionGenerator {
/**
* This map simplifies and speed-ups the access to IDs.
*/
private Map<String, PcmSourceStatementLink> mapIdToStatementLink;
/**
* The {@link PcmSourceStatementLinkRepository} the searching of IDs is based on.
*/
private final PcmSourceStatementLinkRepository sourceStateLinkRepository;
/**
* The {@link SourceCodeFileProvider} for the project under analysis.
*/
private final SourceCodeFileProvider sourceCodeFileProvider;
/**
* Adapting the given SourceStateLinkRepository to the searching of IDs.
*
* @param sourceStateLinkRepository The {@link PcmSourceStatementLinkRepository}
* containing the linking of Ids to SourceCodeFiles
* @param sourceCodeFileProvider The {@link SourceCodeFileProvider} for the project
* under analysis.
*/
public PcmCodeSectionGenerator(final PcmSourceStatementLinkRepository sourceStateLinkRepository,
final SourceCodeFileProvider sourceCodeFileProvider) {
Validate.notNull(sourceStateLinkRepository);
this.sourceStateLinkRepository = sourceStateLinkRepository;
this.initialiseMap();
this.sourceCodeFileProvider = sourceCodeFileProvider;
}
/**
* Creating a private map to simplify access to the IDs.
*
*/
private void initialiseMap() {
this.mapIdToStatementLink = new HashMap<String, PcmSourceStatementLink>();
for (final PcmSourceStatementLink statementLink : this.sourceStateLinkRepository.getLinks()) {
final String statementLinkId = statementLink.getPcmElementId();
Validate.notNull(statementLinkId);
if (this.mapIdToStatementLink.containsKey(statementLinkId)
&& !this.mapIdToStatementLink.get(statementLinkId).equals(statementLink)) {
throw new IllegalArgumentException(
"The given SourceStateLinkRepository contains more than one statementLink for different IDs!");
}
this.mapIdToStatementLink.put(statementLink.getPcmElementId(), statementLink);
}
}
/**
* Creates a {@link CodeSection} for a given identifier.
*
* @param identifier the identifier that should represent a
* BranchBehaviour_BranchTransition, a BodyBehaviour_Loop,
* ExternalCallAction or InternalAction
* @return A {@link CodeSection} based on the given
* {@link PcmSourceStatementLinkRepository}
* @throws FileNotFoundException if File from the given Mapping was not found
*/
public CodeSection getCodeSectionForID(final String identifier) throws FileNotFoundException {
Validate.notNull(identifier);
if (!this.mapIdToStatementLink.containsKey(identifier)) {
throw new IllegalArgumentException(
"The given identifier " + identifier + " was not found in the given SourceStateLinkRepository");
}
final PcmSourceStatementLink statementLink = this.mapIdToStatementLink.get(identifier);
final SourceCodePosition scpFirst = statementLink.getFirstStatement();
final SourceCodePosition scpLast =
statementLink.getLastStatement() != null ? statementLink.getLastStatement() : scpFirst;
final File startFile = this.sourceCodeFileProvider.getSourceFile(scpFirst.getSourceCodeFile());
final File endFile = this.sourceCodeFileProvider.getSourceFile(scpLast.getSourceCodeFile());
if (startFile == null) {
throw new FileNotFoundException("No source file for class " + scpFirst.getSourceCodeFile() + " was found.");
}
if (endFile == null) {
throw new FileNotFoundException("No source file for class " + scpLast.getSourceCodeFile() + " was found.");
}
return new CodeSection(startFile, scpFirst.getCharacterIndex(), endFile, scpLast.getCharacterIndex());
}
}
|
package mil.dds.anet.beans;
import io.leangen.graphql.annotations.GraphQLIgnore;
import io.leangen.graphql.annotations.GraphQLQuery;
import io.leangen.graphql.annotations.GraphQLRootContext;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import javax.ws.rs.WebApplicationException;
import com.fasterxml.jackson.annotation.JsonIgnore;
import mil.dds.anet.AnetObjectEngine;
import mil.dds.anet.beans.Person.Role;
import mil.dds.anet.beans.AuthorizationGroup;
import mil.dds.anet.utils.DaoUtils;
import mil.dds.anet.utils.Utils;
import mil.dds.anet.views.AbstractAnetBean;
import mil.dds.anet.views.UuidFetcher;
public class Report extends AbstractAnetBean {
public enum ReportState { DRAFT, PENDING_APPROVAL, PUBLISHED, REJECTED, CANCELLED, FUTURE, APPROVED }
public enum Atmosphere { POSITIVE, NEUTRAL, NEGATIVE }
public enum ReportCancelledReason { CANCELLED_BY_ADVISOR,
CANCELLED_BY_PRINCIPAL,
CANCELLED_DUE_TO_TRANSPORTATION,
CANCELLED_DUE_TO_FORCE_PROTECTION,
CANCELLED_DUE_TO_ROUTES,
CANCELLED_DUE_TO_THREAT,
NO_REASON_GIVEN }
private ForeignObjectHolder<ApprovalStep> approvalStep = new ForeignObjectHolder<>();
ReportState state;
Instant releasedAt;
Instant engagementDate;
private Integer engagementDayOfWeek;
private ForeignObjectHolder<Location> location = new ForeignObjectHolder<>();
String intent;
String exsum; //can be null to autogenerate
Atmosphere atmosphere;
String atmosphereDetails;
ReportCancelledReason cancelledReason;
List<ReportPerson> attendees;
List<Task> tasks;
String keyOutcomes;
String nextSteps;
String reportText;
private ForeignObjectHolder<Person> author = new ForeignObjectHolder<>();
private ForeignObjectHolder<Organization> advisorOrg = new ForeignObjectHolder<>();
private ForeignObjectHolder<Organization> principalOrg = new ForeignObjectHolder<>();
private ForeignObjectHolder<ReportPerson> primaryAdvisor = new ForeignObjectHolder<>();
private ForeignObjectHolder<ReportPerson> primaryPrincipal = new ForeignObjectHolder<>();
List<Comment> comments;
private List<Tag> tags;
private ReportSensitiveInformation reportSensitiveInformation;
// The user who instantiated this; needed to determine access to sensitive information
private Person user;
private List<AuthorizationGroup> authorizationGroups;
private List<ReportAction> workflow;
@GraphQLQuery(name="approvalStep")
public CompletableFuture<ApprovalStep> loadApprovalStep(@GraphQLRootContext Map<String, Object> context) {
if (approvalStep.hasForeignObject()) {
return CompletableFuture.completedFuture(approvalStep.getForeignObject());
}
return new UuidFetcher<ApprovalStep>().load(context, "approvalSteps", approvalStep.getForeignUuid())
.thenApply(o -> { approvalStep.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setApprovalStepUuid(String approvalStepUuid) {
this.approvalStep = new ForeignObjectHolder<>(approvalStepUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getApprovalStepUuid() {
return approvalStep.getForeignUuid();
}
public void setApprovalStep(ApprovalStep approvalStep) {
this.approvalStep = new ForeignObjectHolder<>(approvalStep);
}
@GraphQLIgnore
public ApprovalStep getApprovalStep() {
return approvalStep.getForeignObject();
}
@GraphQLQuery(name="state")
public ReportState getState() {
return state;
}
public void setState(ReportState state) {
this.state = state;
}
@GraphQLQuery(name="releasedAt")
public Instant getReleasedAt() {
return releasedAt;
}
public void setReleasedAt(Instant releasedAt) {
this.releasedAt = releasedAt;
}
@GraphQLQuery(name="engagementDate")
public Instant getEngagementDate() {
return engagementDate;
}
public void setEngagementDate(Instant engagementDate) {
this.engagementDate = engagementDate;
}
/**
* Returns an Integer value from the set (1,2,3,4,5,6,7) in accordance with
* week days [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday].
*
* @return Integer engagement day of week
*/
@GraphQLQuery(name="engagementDayOfWeek")
public Integer getEngagementDayOfWeek() {
return engagementDayOfWeek;
}
public void setEngagementDayOfWeek(Integer engagementDayOfWeek) {
this.engagementDayOfWeek = engagementDayOfWeek;
}
@GraphQLQuery(name="location")
public CompletableFuture<Location> loadLocation(@GraphQLRootContext Map<String, Object> context) {
if (location.hasForeignObject()) {
return CompletableFuture.completedFuture(location.getForeignObject());
}
return new UuidFetcher<Location>().load(context, "locations", location.getForeignUuid())
.thenApply(o -> { location.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setLocationUuid(String locationUuid) {
this.location = new ForeignObjectHolder<>(locationUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getLocationUuid() {
return location.getForeignUuid();
}
public void setLocation(Location location) {
this.location = new ForeignObjectHolder<>(location);
}
@GraphQLIgnore
public Location getLocation() {
return location.getForeignObject();
}
@GraphQLQuery(name="intent")
public String getIntent() {
return intent;
}
@GraphQLQuery(name="exsum")
public String getExsum() {
return exsum;
}
public void setExsum(String exsum) {
this.exsum = Utils.trimStringReturnNull(exsum);
}
@GraphQLQuery(name="atmosphere")
public Atmosphere getAtmosphere() {
return atmosphere;
}
public void setAtmosphere(Atmosphere atmosphere) {
this.atmosphere = atmosphere;
}
@GraphQLQuery(name="atmosphereDetails")
public String getAtmosphereDetails() {
return atmosphereDetails;
}
public void setAtmosphereDetails(String atmosphereDetails) {
this.atmosphereDetails = Utils.trimStringReturnNull(atmosphereDetails);
}
@GraphQLQuery(name="cancelledReason")
public ReportCancelledReason getCancelledReason() {
return cancelledReason;
}
public void setCancelledReason(ReportCancelledReason cancelledReason) {
this.cancelledReason = cancelledReason;
}
public void setIntent(String intent) {
this.intent = Utils.trimStringReturnNull(intent);
}
@GraphQLQuery(name="attendees")
public CompletableFuture<List<ReportPerson>> loadAttendees(@GraphQLRootContext Map<String, Object> context) {
if (attendees != null) {
return CompletableFuture.completedFuture(attendees);
}
return AnetObjectEngine.getInstance().getReportDao().getAttendeesForReport(context, uuid)
.thenApply(o -> { attendees = o; return o; });
}
@GraphQLIgnore
public List<ReportPerson> getAttendees() {
return attendees;
}
public void setAttendees(List<ReportPerson> attendees) {
this.attendees = attendees;
}
@GraphQLQuery(name="primaryAdvisor")
public CompletableFuture<ReportPerson> loadPrimaryAdvisor(@GraphQLRootContext Map<String, Object> context) {
if (primaryAdvisor.hasForeignObject()) {
return CompletableFuture.completedFuture(primaryAdvisor.getForeignObject());
}
return loadAttendees(context) //Force the load of attendees
.thenApply(l ->
{
final ReportPerson o = l.stream().filter(p -> p.isPrimary() && p.getRole().equals(Role.ADVISOR))
.findFirst().orElse(null);
primaryAdvisor.setForeignObject(o);
return o;
});
}
@JsonIgnore
@GraphQLIgnore
public ReportPerson getPrimaryAdvisor() {
return primaryAdvisor.getForeignObject();
}
@GraphQLQuery(name="primaryPrincipal")
public CompletableFuture<ReportPerson> loadPrimaryPrincipal(@GraphQLRootContext Map<String, Object> context) {
if (primaryPrincipal.hasForeignObject()) {
return CompletableFuture.completedFuture(primaryPrincipal.getForeignObject());
}
return loadAttendees(context) //Force the load of attendees
.thenApply(l ->
{
final ReportPerson o = l.stream().filter(p -> p.isPrimary() && p.getRole().equals(Role.PRINCIPAL))
.findFirst().orElse(null);
primaryPrincipal.setForeignObject(o);
return o;
});
}
@JsonIgnore
@GraphQLIgnore
public ReportPerson getPrimaryPrincipal() {
return primaryPrincipal.getForeignObject();
}
@GraphQLQuery(name="tasks")
public CompletableFuture<List<Task>> loadTasks(@GraphQLRootContext Map<String, Object> context) {
if (tasks != null) {
return CompletableFuture.completedFuture(tasks);
}
return AnetObjectEngine.getInstance().getReportDao().getTasksForReport(context, uuid)
.thenApply(o -> { tasks = o; return o; });
}
public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}
@GraphQLIgnore
public List<Task> getTasks() {
return tasks;
}
@GraphQLQuery(name="keyOutcomes")
public String getKeyOutcomes() {
return keyOutcomes;
}
public void setKeyOutcomes(String keyOutcomes) {
this.keyOutcomes = Utils.trimStringReturnNull(keyOutcomes);
}
@GraphQLQuery(name="reportText")
public String getReportText() {
return reportText;
}
public void setReportText(String reportText) {
this.reportText = Utils.trimStringReturnNull(reportText);
}
@GraphQLQuery(name="nextSteps")
public String getNextSteps() {
return nextSteps;
}
public void setNextSteps(String nextSteps) {
this.nextSteps = Utils.trimStringReturnNull(nextSteps);
}
@GraphQLQuery(name="author")
public CompletableFuture<Person> loadAuthor(@GraphQLRootContext Map<String, Object> context) {
if (author.hasForeignObject()) {
return CompletableFuture.completedFuture(author.getForeignObject());
}
return new UuidFetcher<Person>().load(context, "people", author.getForeignUuid())
.thenApply(o -> { author.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setAuthorUuid(String authorUuid) {
this.author = new ForeignObjectHolder<>(authorUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getAuthorUuid() {
return author.getForeignUuid();
}
public void setAuthor(Person author) {
this.author = new ForeignObjectHolder<>(author);
}
@GraphQLIgnore
public Person getAuthor() {
return author.getForeignObject();
}
@GraphQLQuery(name="advisorOrg")
public CompletableFuture<Organization> loadAdvisorOrg(@GraphQLRootContext Map<String, Object> context) {
if (advisorOrg.hasForeignObject()) {
return CompletableFuture.completedFuture(advisorOrg.getForeignObject());
}
return new UuidFetcher<Organization>().load(context, "organizations", advisorOrg.getForeignUuid())
.thenApply(o -> { advisorOrg.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setAdvisorOrgUuid(String advisorOrgUuid) {
this.advisorOrg = new ForeignObjectHolder<>(advisorOrgUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getAdvisorOrgUuid() {
return advisorOrg.getForeignUuid();
}
public void setAdvisorOrg(Organization advisorOrg) {
this.advisorOrg = new ForeignObjectHolder<>(advisorOrg);
}
@GraphQLIgnore
public Organization getAdvisorOrg() {
return advisorOrg.getForeignObject();
}
@GraphQLQuery(name="principalOrg")
public CompletableFuture<Organization> loadPrincipalOrg(@GraphQLRootContext Map<String, Object> context) {
if (principalOrg.hasForeignObject()) {
return CompletableFuture.completedFuture(principalOrg.getForeignObject());
}
return new UuidFetcher<Organization>().load(context, "organizations", principalOrg.getForeignUuid())
.thenApply(o -> { principalOrg.setForeignObject(o); return o; });
}
@JsonIgnore
@GraphQLIgnore
public void setPrincipalOrgUuid(String principalOrgUuid) {
this.principalOrg = new ForeignObjectHolder<>(principalOrgUuid);
}
@JsonIgnore
@GraphQLIgnore
public String getPrincipalOrgUuid() {
return principalOrg.getForeignUuid();
}
@GraphQLIgnore
public Organization getPrincipalOrg() {
return principalOrg.getForeignObject();
}
public void setPrincipalOrg(Organization principalOrg) {
this.principalOrg = new ForeignObjectHolder<>(principalOrg);
}
@GraphQLQuery(name="comments") // TODO: batch load? (used in reports/{Minimal,Show}.js
public synchronized List<Comment> loadComments() {
if (comments == null) {
comments = AnetObjectEngine.getInstance().getCommentDao().getCommentsForReport(uuid);
}
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
@GraphQLIgnore
public List<Comment> getComments() {
return comments;
}
/*Returns a list of report actions. It depends on the report status:
* - for APPROVED or PUBLISHED reports, it returns all existing report actions
* - for reports in other steps it also creates report actions for all the
* approval steps for which it does not have related report actions yet.
*/
@GraphQLQuery(name="workflow")
public CompletableFuture<List<ReportAction>> loadWorkflow(@GraphQLRootContext Map<String, Object> context) {
if (workflow != null) {
return CompletableFuture.completedFuture(workflow);
}
AnetObjectEngine engine = AnetObjectEngine.getInstance();
return engine.getReportActionDao().getActionsForReport(context, uuid)
.thenCompose(actions -> {
//For reports which are not approved or published, make sure there
//is a report action for each approval step.
if (state == ReportState.APPROVED || state == ReportState.PUBLISHED) {
workflow = actions;
return CompletableFuture.completedFuture(workflow);
} else {
return getWorkflowForOrg(context, engine, getAdvisorOrgUuid())
.thenCompose(steps -> {
if (Utils.isEmptyOrNull(steps)) {
final String defaultOrgUuid = engine.getDefaultOrgUuid();
if (getAdvisorOrgUuid() == null || !Objects.equals(getAdvisorOrgUuid(), defaultOrgUuid)) {
return getDefaultWorkflow(context, engine, defaultOrgUuid);
}
}
return CompletableFuture.completedFuture(steps);
})
.thenCompose(steps -> {
final List<ReportAction> newApprovalStepsActions = createApprovalStepsActions(actions, steps);
actions.addAll(newApprovalStepsActions);
workflow = actions;
return CompletableFuture.completedFuture(workflow);
});
}
});
}
@GraphQLIgnore
public List<ReportAction> getWorkflow() {
return workflow;
}
public void setWorkflow(List<ReportAction> workflow) {
this.workflow = workflow;
}
private List<ReportAction> createApprovalStepsActions(List<ReportAction> actions, List<ApprovalStep> steps) {
final List<ReportAction> newActions = new LinkedList<ReportAction>();
for (final ApprovalStep step : steps) {
//Check if there are report actions for this step
final Optional<ReportAction> existing = actions.stream().filter(a ->
Objects.equals(DaoUtils.getUuid(step), a.getStepUuid())
).max(new Comparator<ReportAction>() {
public int compare(ReportAction a, ReportAction b) {
return a.getCreatedAt().compareTo(b.getCreatedAt());
}
});
if (!existing.isPresent()) {
//If there is no action for this step, create a new one and attach this step
final ReportAction action;
action = new ReportAction();
action.setStep(step);
newActions.add(action);
}
}
return newActions;
}
private CompletableFuture<List<ApprovalStep>> getWorkflowForOrg(Map<String, Object> context, AnetObjectEngine engine, String aoUuid) {
if (aoUuid == null) {
return CompletableFuture.completedFuture(new ArrayList<ApprovalStep>());
}
return engine.getApprovalStepsForOrg(context, aoUuid);
}
private CompletableFuture<List<ApprovalStep>> getDefaultWorkflow(Map<String, Object> context, AnetObjectEngine engine, String defaultOrgUuid) {
if (defaultOrgUuid == null) {
throw new WebApplicationException("Missing the DEFAULT_APPROVAL_ORGANIZATION admin setting");
}
return getWorkflowForOrg(context, engine, defaultOrgUuid);
}
@GraphQLQuery(name="tags")
public CompletableFuture<List<Tag>> loadTags(@GraphQLRootContext Map<String, Object> context) {
if (tags != null) {
return CompletableFuture.completedFuture(tags);
}
return AnetObjectEngine.getInstance().getReportDao().getTagsForReport(context, uuid)
.thenApply(o -> { tags = o; return o; });
}
@GraphQLIgnore
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
@GraphQLQuery(name="reportSensitiveInformation")
public CompletableFuture<ReportSensitiveInformation> loadReportSensitiveInformation(@GraphQLRootContext Map<String, Object> context) {
if (reportSensitiveInformation != null) {
return CompletableFuture.completedFuture(reportSensitiveInformation);
}
return AnetObjectEngine.getInstance().getReportSensitiveInformationDao().getForReport(context, this, user)
.thenApply(o -> { reportSensitiveInformation = o; return o; });
}
@GraphQLIgnore
public ReportSensitiveInformation getReportSensitiveInformation() {
return reportSensitiveInformation;
}
public void setReportSensitiveInformation(ReportSensitiveInformation reportSensitiveInformation) {
this.reportSensitiveInformation = reportSensitiveInformation;
}
@JsonIgnore
@GraphQLIgnore
public Person getUser() {
return user;
}
@JsonIgnore
@GraphQLIgnore
public void setUser(Person user) {
this.user = user;
}
@GraphQLQuery(name="authorizationGroups") // TODO: batch load? (used in reports/{Edit,Show}.js)
public synchronized List<AuthorizationGroup> loadAuthorizationGroups() {
if (authorizationGroups == null && uuid != null) {
authorizationGroups = AnetObjectEngine.getInstance().getReportDao().getAuthorizationGroupsForReport(uuid);
}
return authorizationGroups;
}
public void setAuthorizationGroups(List<AuthorizationGroup> authorizationGroups) {
this.authorizationGroups = authorizationGroups;
}
@GraphQLIgnore
public List<AuthorizationGroup> getAuthorizationGroups() {
return authorizationGroups;
}
@Override
public boolean equals(Object other) {
if (other == null || other.getClass() != this.getClass()) {
return false;
}
Report r = (Report) other;
return Objects.equals(r.getUuid(), uuid)
&& Objects.equals(r.getState(), state)
&& Objects.equals(r.getApprovalStepUuid(), getApprovalStepUuid())
&& Objects.equals(r.getCreatedAt(), createdAt)
&& Objects.equals(r.getUpdatedAt(), updatedAt)
&& Objects.equals(r.getEngagementDate(), engagementDate)
&& Objects.equals(r.getLocationUuid(), getLocationUuid())
&& Objects.equals(r.getIntent(), intent)
&& Objects.equals(r.getExsum(), exsum)
&& Objects.equals(r.getAtmosphere(), atmosphere)
&& Objects.equals(r.getAtmosphereDetails(), atmosphereDetails)
&& Objects.equals(r.getAttendees(), attendees)
&& Objects.equals(r.getTasks(), tasks)
&& Objects.equals(r.getReportText(), reportText)
&& Objects.equals(r.getNextSteps(), nextSteps)
&& Objects.equals(r.getAuthorUuid(), getAuthorUuid())
&& Objects.equals(r.getComments(), comments)
&& Objects.equals(r.getTags(), tags)
&& Objects.equals(r.getReportSensitiveInformation(), reportSensitiveInformation)
&& Objects.equals(r.getAuthorizationGroups(), authorizationGroups);
}
@Override
public int hashCode() {
return Objects.hash(uuid, state, approvalStep, createdAt, updatedAt,
location, intent, exsum, attendees, tasks, reportText,
nextSteps, author, comments, atmosphere, atmosphereDetails, engagementDate,
tags, reportSensitiveInformation, authorizationGroups);
}
public static Report createWithUuid(String uuid) {
final Report r = new Report();
r.setUuid(uuid);
return r;
}
@Override
public String toString() {
return String.format("[uuid:%s, intent:%s]", uuid, intent);
}
}
|
/*
* $Id: SimpleOperatorProcessor.java,v 1.8 2006-12-07 06:15:27 thib_gc Exp $
*/
package org.lockss.filter.pdf;
import java.io.IOException;
import java.util.List;
import org.pdfbox.util.PDFOperator;
/**
* <p>A PDF operator processor that simply passes its operands and
* operator through to the PDF page stream transform's output list
* unconditionally.</p>
* <p>{@link SimpleOperatorProcessor} instances, like
* {@link PdfOperatorProcessor} instances, <em>must</em> have a
* no-argument constructor, and are instantiated once per key
* associated with their class name during a given
* {@link PageStreamTransform} instantiation.</p>
* @author Thib Guicherd-Callin
*/
public class SimpleOperatorProcessor extends PdfOperatorProcessor {
/* Inherit documentation */
public void process(PageStreamTransform pageStreamTransform,
PDFOperator operator,
List operands)
throws IOException {
pageStreamTransform.getOutputList().addAll(operands);
pageStreamTransform.getOutputList().add(operator);
}
}
|
package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
import org.opendaylight.ovsdb.openstack.netvirt.api.Southbound;
import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;
import org.opendaylight.ovsdb.openstack.netvirt.providers.NetvirtProvidersProvider;
import org.opendaylight.ovsdb.utils.mdsal.openflow.InstructionUtils;
import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.InstructionsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.CheckedFuture;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Any ServiceInstance class that extends AbstractServiceInstance to be a part of the pipeline
* have 2 basic requirements : <br>
* 1. Program a default pipeline flow to take any unmatched traffic to the next table in the pipeline. <br>
* 2. Get Pipeline Instructions from AbstractServiceInstance (using getMutablePipelineInstructionBuilder) and
* use it in any matching flows that needs to be further processed by next service in the pipeline.
*
*/
public abstract class AbstractServiceInstance {
public static final String SERVICE_PROPERTY ="serviceProperty";
private static final Logger LOG = LoggerFactory.getLogger(AbstractServiceInstance.class);
public static final String OPENFLOW = "openflow:";
private DataBroker dataBroker = null;
// OSGi Services that we are dependent on.
private volatile PipelineOrchestrator orchestrator;
private volatile Southbound southbound;
// Concrete Service that this AbstractServiceInstance represents
private Service service;
public AbstractServiceInstance (Service service) {
this.service = service;
this.dataBroker = NetvirtProvidersProvider.getDataBroker();
}
protected void setDependencies(final ServiceReference ref, AbstractServiceInstance serviceInstance) {
this.orchestrator =
(PipelineOrchestrator) ServiceHelper.getGlobalInstance(PipelineOrchestrator.class, serviceInstance);
orchestrator.registerService(ref, serviceInstance);
this.southbound =
(Southbound) ServiceHelper.getGlobalInstance(Southbound.class, serviceInstance);
}
public boolean isBridgeInPipeline (Node node){
String bridgeName = southbound.getBridgeName(node);
return bridgeName != null && Constants.INTEGRATION_BRIDGE.equals(bridgeName);
}
/**
* Return the offset adjusted table for this {@link Service}
* @return The table id
*/
public short getTable() {
return (short)(orchestrator.getTableOffset() + service.getTable());
}
/**
* Return the offset adjusted table for the given {@link Service}
* @param service Identifies the openflow {@link Service}
* @return The table id
*/
public short getTable(Service service) {
return (short)(orchestrator.getTableOffset() + service.getTable());
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
public NodeBuilder createNodeBuilder(String nodeId) {
NodeBuilder builder = new NodeBuilder();
builder.setId(new NodeId(nodeId));
builder.setKey(new NodeKey(builder.getId()));
return builder;
}
private static InstanceIdentifier<Flow> createFlowPath(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
return InstanceIdentifier.builder(Nodes.class)
.child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
nodeBuilder.getKey())
.augmentation(FlowCapableNode.class)
.child(Table.class, new TableKey(flowBuilder.getTableId()))
.child(Flow.class, flowBuilder.getKey()).build();
}
private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node>
createNodePath(NodeBuilder nodeBuilder) {
return InstanceIdentifier.builder(Nodes.class)
.child(org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node.class,
nodeBuilder.getKey()).build();
}
/**
* This method returns the required Pipeline Instructions to by used by any matching flows that need
* to be further processed by next service in the pipeline.
*
* Important to note that this is a convenience method which returns a mutable instructionBuilder which
* needs to be further adjusted by the concrete ServiceInstance class such as setting the Instruction Order, etc.
* @return Newly created InstructionBuilder to be used along with other instructions on the main flow
*/
protected final InstructionBuilder getMutablePipelineInstructionBuilder() {
Service nextService = orchestrator.getNextServiceInPipeline(service);
if (nextService != null) {
return InstructionUtils.createGotoTableInstructions(new InstructionBuilder(),
orchestrator.getTable(nextService));
} else {
return InstructionUtils.createDropInstructions(new InstructionBuilder());
}
}
protected void writeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
if (NetvirtProvidersProvider.isMasterProviderInstance()) {
LOG.debug("writeFlow: flowBuilder: {}, nodeBuilder: {}",
flowBuilder.build(), nodeBuilder.build());
WriteTransaction modification = dataBroker.newWriteOnlyTransaction();
//modification.put(LogicalDatastoreType.CONFIGURATION, createNodePath(nodeBuilder),
// nodeBuilder.build(), true /*createMissingParents*/);
modification.put(LogicalDatastoreType.CONFIGURATION, createFlowPath(flowBuilder, nodeBuilder),
flowBuilder.build(), true /*createMissingParents*/);
CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
try {
commitFuture.checkedGet(); // TODO: Make it async (See bug 1362)
LOG.debug("Transaction success for write of Flow {}", flowBuilder.getFlowName());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
modification.cancel();
}
}
}
protected void removeFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
if (NetvirtProvidersProvider.isMasterProviderInstance()) {
WriteTransaction modification = dataBroker.newWriteOnlyTransaction();
modification.delete(LogicalDatastoreType.CONFIGURATION, createFlowPath(flowBuilder, nodeBuilder));
CheckedFuture<Void, TransactionCommitFailedException> commitFuture = modification.submit();
try {
commitFuture.get(); // TODO: Make it async (See bug 1362)
LOG.debug("Transaction success for deletion of Flow {}", flowBuilder.getFlowName());
} catch (Exception e) {
LOG.error(e.getMessage(), e);
modification.cancel();
}
}
}
public Flow getFlow(FlowBuilder flowBuilder, NodeBuilder nodeBuilder) {
ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction();
try {
Optional<Flow> data =
readTx.read(LogicalDatastoreType.CONFIGURATION, createFlowPath(flowBuilder, nodeBuilder)).get();
if (data.isPresent()) {
return data.get();
}
} catch (InterruptedException|ExecutionException e) {
LOG.error(e.getMessage(), e);
}
LOG.debug("Cannot find data for Flow {}", flowBuilder.getFlowName());
return null;
}
public org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node
getOpenFlowNode(String nodeId) {
ReadOnlyTransaction readTx = dataBroker.newReadOnlyTransaction();
try {
Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node> data =
readTx.read(LogicalDatastoreType.OPERATIONAL, createNodePath(createNodeBuilder(nodeId))).get();
if (data.isPresent()) {
return data.get();
}
} catch (InterruptedException|ExecutionException e) {
LOG.error(e.getMessage(), e);
}
LOG.debug("Cannot find data for Node {}", nodeId);
return null;
}
private long getDpid(Node node) {
long dpid = southbound.getDataPathId(node);
if (dpid == 0) {
LOG.warn("getDpid: dpid not found: {}", node);
}
return dpid;
}
/**
* Program Default Pipeline Flow.
*
* @param node on which the default pipeline flow is programmed.
*/
protected void programDefaultPipelineRule(Node node) {
if (!isBridgeInPipeline(node)) {
//LOG.trace("Bridge is not in pipeline {} ", node);
return;
}
MatchBuilder matchBuilder = new MatchBuilder();
FlowBuilder flowBuilder = new FlowBuilder();
long dpid = getDpid(node);
if (dpid == 0L) {
LOG.info("could not find dpid: {}", node.getNodeId());
return;
}
String nodeName = OPENFLOW + getDpid(node);
NodeBuilder nodeBuilder = createNodeBuilder(nodeName);
// Create the OF Actions and Instructions
InstructionsBuilder isb = new InstructionsBuilder();
// Instructions List Stores Individual Instructions
List<Instruction> instructions = Lists.newArrayList();
// Call the InstructionBuilder Methods Containing Actions
InstructionBuilder ib = this.getMutablePipelineInstructionBuilder();
ib.setOrder(0);
ib.setKey(new InstructionKey(0));
instructions.add(ib.build());
// Add InstructionBuilder to the Instruction(s)Builder List
isb.setInstruction(instructions);
// Add InstructionsBuilder to FlowBuilder
flowBuilder.setInstructions(isb.build());
String flowId = "DEFAULT_PIPELINE_FLOW_" + getTable();
flowBuilder.setId(new FlowId(flowId));
FlowKey key = new FlowKey(new FlowId(flowId));
flowBuilder.setMatch(matchBuilder.build());
flowBuilder.setPriority(0);
flowBuilder.setBarrier(false);
flowBuilder.setTableId(getTable());
flowBuilder.setKey(key);
flowBuilder.setFlowName(flowId);
flowBuilder.setHardTimeout(0);
flowBuilder.setIdleTimeout(0);
writeFlow(flowBuilder, nodeBuilder);
}
}
|
package org.opencms.configuration;
import org.opencms.file.CmsProperty;
import org.opencms.file.collectors.I_CmsResourceCollector;
import org.opencms.file.types.I_CmsResourceType;
import org.opencms.loader.CmsResourceManager;
import org.opencms.loader.I_CmsResourceLoader;
import org.opencms.main.CmsLog;
import org.opencms.main.OpenCms;
import org.opencms.util.CmsResourceTranslator;
import org.opencms.widgets.I_CmsWidget;
import org.opencms.xml.CmsXmlContentTypeManager;
import org.opencms.xml.types.I_CmsXmlSchemaType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.digester.Digester;
import org.dom4j.Element;
/**
* VFS master configuration class.<p>
*
* @author Alexander Kandzior (a.kandzior@alkacon.com)
* @since 5.3
*/
public class CmsVfsConfiguration extends A_CmsXmlConfiguration implements I_CmsXmlConfiguration {
/** The mapping node name. */
public static final String N_MAPPING = "mapping";
/** The mappings node name. */
public static final String N_MAPPINGS = "mappings";
/** The properties node name. */
public static final String N_PROPERTIES = "properties";
/** The resource types node name. */
public static final String N_RESOURCETYPES = "resourcetypes";
/** The node name of an individual resource type. */
public static final String N_TYPE = "type";
/** The widget attribute. */
protected static final String A_DEFAULTWIDGET = "defaultwidget";
/** The collector node name. */
protected static final String N_COLLECTOR = "collector";
/** The collectors node name. */
protected static final String N_COLLECTORS = "collectors";
/** The defaultfile node name. */
protected static final String N_DEFAULTFILE = "defaultfile";
/** The defaultfiles node name. */
protected static final String N_DEFAULTFILES = "defaultfiles";
/** File translations node name. */
protected static final String N_FILETRANSLATIONS = "filetranslations";
/** Folder translations node name. */
protected static final String N_FOLDERTRANSLATIONS = "foldertranslations";
/** The node name of an individual resource loader. */
protected static final String N_LOADER = "loader";
/** The resource loaders node name. */
protected static final String N_RESOURCELOADERS = "resourceloaders";
/** The main resource node name. */
protected static final String N_RESOURCES = "resources";
/** The schematype node name. */
protected static final String N_SCHEMATYPE = "schematype";
/** The schematypes node name. */
protected static final String N_SCHEMATYPES = "schematypes";
/** Individual translation node name. */
protected static final String N_TRANSLATION = "translation";
/** The translations master node name. */
protected static final String N_TRANSLATIONS = "translations";
/** The node name for the version history. */
protected static final String N_VERSIONHISTORY = "versionhistory";
/** The main vfs configuration node name. */
protected static final String N_VFS = "vfs";
/** The widget node name. */
protected static final String N_WIDGET = "widget";
/** The widgets node name. */
protected static final String N_WIDGETS = "widgets";
/** The xmlcontent node name. */
protected static final String N_XMLCONTENT = "xmlcontent";
/** The xmlcontents node name. */
protected static final String N_XMLCONTENTS = "xmlcontents";
/** The source attribute name. */
private static final String A_SOURCE = "source";
/** The target attribute name. */
private static final String A_TARGET = "target";
/** The name of the DTD for this configuration. */
private static final String C_CONFIGURATION_DTD_NAME = "opencms-vfs.dtd";
/** The name of the default XML file for this configuration. */
public static final String C_DEFAULT_XML_FILE_NAME = "opencms-vfs.xml";
/** The copy-resource node name.*/
private static final String N_COPY_RESOURCE = "copy-resource";
/** The copy-resources node name.*/
private static final String N_COPY_RESOURCES = "copy-resources";
/** The configured XML content type manager. */
CmsXmlContentTypeManager m_xmlContentTypeManager;
/** The list of configured default files. */
private List m_defaultFiles;
/** Controls if file translation is enabled. */
private boolean m_fileTranslationEnabled;
/** The list of file translations. */
private List m_fileTranslations;
/** Controls if folder translation is enabled. */
private boolean m_folderTranslationEnabled;
/** The list of folder translations. */
private List m_folderTranslations;
/** The configured resource manager. */
private CmsResourceManager m_resourceManager;
/**
* Public constructor, will be called by configuration manager.<p>
*/
public CmsVfsConfiguration() {
setXmlFileName(C_DEFAULT_XML_FILE_NAME);
m_fileTranslations = new ArrayList();
m_folderTranslations = new ArrayList();
m_defaultFiles = new ArrayList();
if (CmsLog.LOG.isInfoEnabled()) {
CmsLog.LOG.info(Messages.get().key(Messages.INIT_VFS_CONFIG_INIT_0));
}
}
/**
* Adds the resource type rules to the given digester.<p>
*
* @param digester the digester to add the rules to
*/
public static void addResourceTypeXmlRules(Digester digester) {
// add rules for resource types
digester.addObjectCreate("*/" + N_RESOURCETYPES + "/" + N_TYPE, A_CLASS, CmsConfigurationException.class);
digester.addCallMethod("*/" + N_RESOURCETYPES + "/" + N_TYPE, I_CmsConfigurationParameterHandler.C_INIT_CONFIGURATION_METHOD, 2);
// please note: the resource types use a special version of the init method with 2 parameters
digester.addCallParam("*/" + N_RESOURCETYPES + "/" + N_TYPE, 0, A_NAME);
digester.addCallParam("*/" + N_RESOURCETYPES + "/" + N_TYPE, 1, A_ID);
digester.addSetNext("*/" + N_RESOURCETYPES + "/" + N_TYPE, I_CmsResourceType.C_ADD_RESOURCE_TYPE_METHOD);
// add rules for default properties
digester.addObjectCreate("*/" + N_RESOURCETYPES + "/" + N_TYPE + "/" + N_PROPERTIES + "/" + N_PROPERTY, CmsProperty.class);
digester.addCallMethod("*/" + N_RESOURCETYPES + "/" + N_TYPE + "/" + N_PROPERTIES + "/" + N_PROPERTY + "/" + N_NAME, "setName", 1);
digester.addCallParam("*/" + N_RESOURCETYPES + "/" + N_TYPE + "/" + N_PROPERTIES + "/" + N_PROPERTY + "/" + N_NAME, 0);
digester.addCallMethod("*/" + N_RESOURCETYPES + "/" + N_TYPE + "/" + N_PROPERTIES + "/" + N_PROPERTY + "/" + N_VALUE, "setValue", 2);
digester.addCallParam("*/" + N_RESOURCETYPES + "/" + N_TYPE + "/" + N_PROPERTIES + "/" + N_PROPERTY + "/" + N_VALUE, 0);
digester.addCallParam("*/" + N_RESOURCETYPES + "/" + N_TYPE + "/" + N_PROPERTIES + "/" + N_PROPERTY + "/" + N_VALUE, 1, A_TYPE);
digester.addSetNext("*/" + N_RESOURCETYPES + "/" + N_TYPE + "/" + N_PROPERTIES + "/" + N_PROPERTY, "addDefaultProperty");
// extension mapping rules
digester.addCallMethod("*/" + N_RESOURCETYPES + "/" + N_TYPE + "/" + N_MAPPINGS + "/" + N_MAPPING, I_CmsResourceType.C_ADD_MAPPING_METHOD, 1);
digester.addCallParam ("*/" + N_RESOURCETYPES + "/" + N_TYPE + "/" + N_MAPPINGS + "/" + N_MAPPING, 0, A_SUFFIX);
// copy resource rules
digester.addCallMethod("*/" + N_RESOURCETYPES + "/" + N_TYPE + "/" + N_COPY_RESOURCES + "/" + N_COPY_RESOURCE, "addCopyResource", 3);
digester.addCallParam ("*/" + N_RESOURCETYPES + "/" + N_TYPE + "/" + N_COPY_RESOURCES + "/" + N_COPY_RESOURCE, 0, A_SOURCE);
digester.addCallParam ("*/" + N_RESOURCETYPES + "/" + N_TYPE + "/" + N_COPY_RESOURCES + "/" + N_COPY_RESOURCE, 1, A_TARGET);
digester.addCallParam ("*/" + N_RESOURCETYPES + "/" + N_TYPE + "/" + N_COPY_RESOURCES + "/" + N_COPY_RESOURCE, 2, A_TYPE);
}
/**
* Creates the xml output for resourcetype nodes.<p>
*
* @param startNode the startnode to add all rescource types to
* @param resourceTypes the list of resource types
* @param module flag, signaling to add them module resource types or not
*/
public static void generateResourceTypeXml(Element startNode, List resourceTypes, boolean module) {
for (int i = 0; i < resourceTypes.size(); i++) {
I_CmsResourceType resType = (I_CmsResourceType)resourceTypes.get(i);
// only add this resource type to the xml output, if it is no additional type defined
// in a module
if (resType.isAdditionalModuleResourceType() == module) {
Element resourceType = startNode.addElement(N_TYPE).addAttribute(A_CLASS, resType.getClass().getName());
// add type id and type name
resourceType.addAttribute(A_NAME, resType.getTypeName());
resourceType.addAttribute(A_ID, String.valueOf(resType.getTypeId()));
// add resource mappings
List mappings = resType.getConfiguredMappings();
if ((mappings != null) && (mappings.size() > 0)) {
Element mappingsNode = resourceType.addElement(N_MAPPINGS);
for (int j = 0; j < mappings.size(); j++) {
Element mapping = mappingsNode.addElement(N_MAPPING);
mapping.addAttribute(A_SUFFIX, (String)mappings.get(j));
}
}
// add default properties
List properties = resType.getConfiguredDefaultProperties();
if ((properties != null) && (properties.size() > 0)) {
Element propertiesNode = resourceType.addElement(N_PROPERTIES);
Iterator p = properties.iterator();
while (p.hasNext()) {
CmsProperty property = (CmsProperty)p.next();
Element propertyNode = propertiesNode.addElement(N_PROPERTY);
propertyNode.addElement(N_NAME).addText(property.getName());
if (property.getStructureValue() != null) {
propertyNode.addElement(N_VALUE).addCDATA(property.getStructureValue());
}
if (property.getResourceValue() != null) {
propertyNode.addElement(N_VALUE).addAttribute(A_TYPE, CmsProperty.TYPE_SHARED).addCDATA(
property.getResourceValue());
}
}
}
// add copy resources
List copyRes = resType.getConfiguredCopyResources();
if ((copyRes != null) && (copyRes.size() > 0)) {
Element copyResNode = resourceType.addElement(N_COPY_RESOURCES);
Iterator p = copyRes.iterator();
while (p.hasNext()) {
CmsConfigurationCopyResource cRes = (CmsConfigurationCopyResource)p.next();
Element cNode = copyResNode.addElement(N_COPY_RESOURCE);
cNode.addAttribute(A_SOURCE, cRes.getSource());
if (!cRes.isTargetWasNull()) {
cNode.addAttribute(A_TARGET, cRes.getTarget());
}
if (!cRes.isTypeWasNull()) {
cNode.addAttribute(A_TYPE, cRes.getTypeString());
}
}
}
// add optional parameters
Map prop = resType.getConfiguration();
if (prop != null) {
List sortedRuntimeProperties = new ArrayList(prop.keySet());
Collections.sort(sortedRuntimeProperties);
Iterator it = sortedRuntimeProperties.iterator();
while (it.hasNext()) {
String key = (String)it.next();
// create <param name="">value</param> subnodes
Object valueObject = prop.get(key);
String value = new String();
if (valueObject instanceof String) {
value = (String)valueObject;
} else if (valueObject instanceof Integer) {
value = ((Integer)valueObject).toString();
}
resourceType.addElement(N_PARAM).addAttribute(A_NAME, key).addText(value);
}
}
}
}
}
/**
* Adds a directory default file.<p>
*
* @param defaultFile the directory default file to add
*/
public void addDefaultFile(String defaultFile) {
m_defaultFiles.add(defaultFile);
if (CmsLog.LOG.isInfoEnabled()) {
CmsLog.LOG.info(
Messages.get().key(
Messages.INIT_VFS_DEFAULT_FILE_2,
new Integer(m_defaultFiles.size()),
defaultFile));
}
}
/**
* Adds one file translation rule.<p>
*
* @param translation the file translation rule to add
*/
public void addFileTranslation(String translation) {
m_fileTranslations.add(translation);
if (CmsLog.LOG.isInfoEnabled()) {
CmsLog.LOG.info(Messages.get().key(
Messages.INIT_VFS_ADD_FILE_TRANSLATION_1,
translation));
}
}
/**
* Adds one folder translation rule.<p>
*
* @param translation the folder translation rule to add
*/
public void addFolderTranslation(String translation) {
m_folderTranslations.add(translation);
if (CmsLog.LOG.isInfoEnabled()) {
CmsLog.LOG.info(Messages.get().key(
Messages.INIT_VFS_ADD_FOLDER_TRANSLATION_1,
translation));
}
}
/**
* @see org.opencms.configuration.I_CmsXmlConfiguration#addXmlDigesterRules(org.apache.commons.digester.Digester)
*/
public void addXmlDigesterRules(Digester digester) {
// add finish rule
digester.addCallMethod("*/" + N_VFS, "initializeFinished");
// creation of the resource manager
digester.addObjectCreate("*/" + N_VFS + "/" + N_RESOURCES, CmsResourceManager.class);
digester.addCallMethod("*/" + N_VFS + "/" + N_RESOURCES, I_CmsConfigurationParameterHandler.C_INIT_CONFIGURATION_METHOD);
digester.addSetNext("*/" + N_VFS + "/" + N_RESOURCES, "setResourceManager");
// add rules for resource loaders
digester.addObjectCreate("*/" + N_VFS + "/" + N_RESOURCES + "/" + N_RESOURCELOADERS + "/" + N_LOADER, A_CLASS, CmsConfigurationException.class);
digester.addCallMethod("*/" + N_VFS + "/" + N_RESOURCES + "/" + N_RESOURCELOADERS + "/" + N_LOADER, I_CmsConfigurationParameterHandler.C_INIT_CONFIGURATION_METHOD);
digester.addSetNext("*/" + N_VFS + "/" + N_RESOURCES + "/" + N_RESOURCELOADERS + "/" + N_LOADER, "addLoader");
// add rules for resource types
addResourceTypeXmlRules(digester);
// add rules for VFS content collectors
digester.addCallMethod("*/" + N_VFS + "/" + N_RESOURCES + "/" + N_COLLECTORS + "/" + N_COLLECTOR, "addContentCollector", 2);
digester.addCallParam("*/" + N_VFS + "/" + N_RESOURCES + "/" + N_COLLECTORS + "/" + N_COLLECTOR, 0, A_CLASS);
digester.addCallParam("*/" + N_VFS + "/" + N_RESOURCES + "/" + N_COLLECTORS + "/" + N_COLLECTOR, 1, A_ORDER);
// generic <param> parameter rules
digester.addCallMethod("*/" + I_CmsXmlConfiguration.N_PARAM, I_CmsConfigurationParameterHandler.C_ADD_PARAMETER_METHOD, 2);
digester.addCallParam ("*/" + I_CmsXmlConfiguration.N_PARAM, 0, I_CmsXmlConfiguration.A_NAME);
digester.addCallParam ("*/" + I_CmsXmlConfiguration.N_PARAM, 1);
// add rule for default files
digester.addCallMethod("*/" + N_VFS + "/" + N_DEFAULTFILES + "/" + N_DEFAULTFILE, "addDefaultFile", 1);
digester.addCallParam("*/" + N_VFS + "/" + N_DEFAULTFILES + "/" + N_DEFAULTFILE, 0, A_NAME);
// add rules for file translations
digester.addCallMethod("*/" + N_VFS + "/" + N_TRANSLATIONS + "/" + N_FILETRANSLATIONS + "/" + N_TRANSLATION, "addFileTranslation", 0);
digester.addCallMethod("*/" + N_VFS + "/" + N_TRANSLATIONS + "/" + N_FILETRANSLATIONS, "setFileTranslationEnabled", 1);
digester.addCallParam("*/" + N_VFS + "/" + N_TRANSLATIONS + "/" + N_FILETRANSLATIONS, 0, A_ENABLED);
// add rules for file translations
digester.addCallMethod("*/" + N_VFS + "/" + N_TRANSLATIONS + "/" + N_FOLDERTRANSLATIONS + "/" + N_TRANSLATION, "addFolderTranslation", 0);
digester.addCallMethod("*/" + N_VFS + "/" + N_TRANSLATIONS + "/" + N_FOLDERTRANSLATIONS, "setFolderTranslationEnabled", 1);
digester.addCallParam("*/" + N_VFS + "/" + N_TRANSLATIONS + "/" + N_FOLDERTRANSLATIONS, 0, A_ENABLED);
// XML content type manager creation rules
digester.addObjectCreate("*/" + N_VFS + "/" + N_XMLCONTENT, CmsXmlContentTypeManager.class);
digester.addSetNext("*/" + N_VFS + "/" + N_XMLCONTENT, "setXmlContentTypeManager");
// XML content widgets add rules
digester.addCallMethod("*/" + N_VFS + "/" + N_XMLCONTENT + "/" + N_WIDGETS + "/" + N_WIDGET, "addWidget", 2);
digester.addCallParam("*/" + N_VFS + "/" + N_XMLCONTENT + "/" + N_WIDGETS + "/" + N_WIDGET, 0, A_CLASS);
digester.addCallParam("*/" + N_VFS + "/" + N_XMLCONTENT + "/" + N_WIDGETS + "/" + N_WIDGET, 1, A_ALIAS);
// XML content schema type add rules
digester.addCallMethod("*/" + N_VFS + "/" + N_XMLCONTENT + "/" + N_SCHEMATYPES + "/" + N_SCHEMATYPE, "addSchemaType", 2);
digester.addCallParam("*/" + N_VFS + "/" + N_XMLCONTENT + "/" + N_SCHEMATYPES + "/" + N_SCHEMATYPE, 0, A_CLASS);
digester.addCallParam("*/" + N_VFS + "/" + N_XMLCONTENT + "/" + N_SCHEMATYPES + "/" + N_SCHEMATYPE, 1, A_DEFAULTWIDGET);
}
/**
* @see org.opencms.configuration.I_CmsXmlConfiguration#generateXml(org.dom4j.Element)
*/
public Element generateXml(Element parent) {
if (OpenCms.getRunLevel() >= OpenCms.RUNLEVEL_3_SHELL_ACCESS) {
m_resourceManager = OpenCms.getResourceManager();
m_xmlContentTypeManager = OpenCms.getXmlContentTypeManager();
m_defaultFiles = OpenCms.getDefaultFiles();
}
// generate vfs node and subnodes
Element vfs = parent.addElement(N_VFS);
// add resources main element
Element resources = vfs.addElement(N_RESOURCES);
// add resource loader
Element resourceloadersElement = resources.addElement(N_RESOURCELOADERS);
List loaders = m_resourceManager.getLoaders();
for (int i = 0; i < loaders.size(); i++) {
I_CmsResourceLoader loader = (I_CmsResourceLoader)loaders.get(i);
// add the loader node
Element loaderNode = resourceloadersElement.addElement(N_LOADER);
loaderNode.addAttribute(A_CLASS, loader.getClass().getName());
Map loaderConfiguration = loader.getConfiguration();
if (loaderConfiguration != null) {
Iterator it = loaderConfiguration.keySet().iterator();
while (it.hasNext()) {
String name = (String)it.next();
String value = loaderConfiguration.get(name).toString();
Element paramNode = loaderNode.addElement(N_PARAM);
paramNode.addAttribute(A_NAME, name);
paramNode.addText(value);
}
}
}
// add resource types
Element resourcetypesElement = resources.addElement(N_RESOURCETYPES);
List resourceTypes = m_resourceManager.getResourceTypes();
generateResourceTypeXml(resourcetypesElement, resourceTypes, false);
// add VFS content collectors
Element collectorsElement = resources.addElement(N_COLLECTORS);
Iterator it = m_resourceManager.getRegisteredContentCollectors().iterator();
while (it.hasNext()) {
I_CmsResourceCollector collector = (I_CmsResourceCollector)it.next();
collectorsElement.addElement(N_COLLECTOR)
.addAttribute(A_CLASS, collector.getClass().getName())
.addAttribute(A_ORDER, String.valueOf(collector.getOrder()));
}
// add default file names
Element defaultFileElement = vfs.addElement(N_DEFAULTFILES);
it = m_defaultFiles.iterator();
while (it.hasNext()) {
defaultFileElement.addElement(N_DEFAULTFILE).addAttribute(A_NAME, (String)it.next());
}
// add translation rules
Element translationsElement = vfs.addElement(N_TRANSLATIONS);
// file translation rules
Element fileTransElement = translationsElement.addElement(N_FILETRANSLATIONS).addAttribute(
A_ENABLED,
new Boolean(m_fileTranslationEnabled).toString());
it = m_fileTranslations.iterator();
while (it.hasNext()) {
fileTransElement.addElement(N_TRANSLATION).setText(it.next().toString());
}
// folder translation rules
Element folderTransElement =
translationsElement.addElement(N_FOLDERTRANSLATIONS)
.addAttribute(A_ENABLED, new Boolean(m_folderTranslationEnabled).toString());
it = m_folderTranslations.iterator();
while (it.hasNext()) {
folderTransElement.addElement(N_TRANSLATION).setText(it.next().toString());
}
// XML content configuration
Element xmlContentsElement = vfs.addElement(N_XMLCONTENT);
// XML widgets
Element xmlWidgetsElement = xmlContentsElement.addElement(N_WIDGETS);
it = m_xmlContentTypeManager.getRegisteredWidgetNames().iterator();
while (it.hasNext()) {
String widget = (String)it.next();
Element widgetElement = xmlWidgetsElement.addElement(N_WIDGET).addAttribute(A_CLASS, widget);
String alias = m_xmlContentTypeManager.getRegisteredWidgetAlias(widget);
if (alias != null) {
widgetElement.addAttribute(A_ALIAS, alias);
}
}
// XML content types
Element xmlSchemaTypesElement = xmlContentsElement.addElement(N_SCHEMATYPES);
it = m_xmlContentTypeManager.getRegisteredSchemaTypes().iterator();
while (it.hasNext()) {
I_CmsXmlSchemaType type = (I_CmsXmlSchemaType)it.next();
I_CmsWidget widget = m_xmlContentTypeManager.getWidgetDefault(type.getTypeName());
xmlSchemaTypesElement.addElement(N_SCHEMATYPE)
.addAttribute(A_CLASS, type.getClass().getName())
.addAttribute(A_DEFAULTWIDGET, widget.getClass().getName());
}
// return the vfs node
return vfs;
}
/**
* Returns the (umodifiable) list of configured directory default files.<p>
*
* @return the (umodifiable) list of configured directory default files
*/
public List getDefaultFiles() {
return Collections.unmodifiableList(m_defaultFiles);
}
/**
* @see org.opencms.configuration.I_CmsXmlConfiguration#getDtdFilename()
*/
public String getDtdFilename() {
return C_CONFIGURATION_DTD_NAME;
}
/**
* Returns the file resource translator that has been initialized
* with the configured file translation rules.<p>
*
* @return the file resource translator
*/
public CmsResourceTranslator getFileTranslator() {
String[] array = m_fileTranslationEnabled ? new String[m_fileTranslations.size()] : new String[0];
for (int i = 0; i < m_fileTranslations.size(); i++) {
array[i] = (String)m_fileTranslations.get(i);
}
return new CmsResourceTranslator(array, true);
}
/**
* Returns the folder resource translator that has been initialized
* with the configured folder translation rules.<p>
*
* @return the folder resource translator
*/
public CmsResourceTranslator getFolderTranslator() {
String[] array = m_folderTranslationEnabled ? new String[m_folderTranslations.size()] : new String[0];
for (int i = 0; i < m_folderTranslations.size(); i++) {
array[i] = (String)m_folderTranslations.get(i);
}
return new CmsResourceTranslator(array, false);
}
/**
* Returns the initialized resource manager.<p>
*
* @return the initialized resource manager
*/
public CmsResourceManager getResourceManager() {
return m_resourceManager;
}
/**
* Returns the configured XML content type manager.<p>
*
* @return the configured XML content type manager
*/
public CmsXmlContentTypeManager getXmlContentTypeManager() {
return m_xmlContentTypeManager;
}
/**
* Will be called when configuration of this object is finished.<p>
*/
public void initializeFinished() {
if (CmsLog.LOG.isInfoEnabled()) {
CmsLog.LOG.info(Messages.get().key(Messages.INIT_VFS_CONFIG_FINISHED_0));
}
}
/**
* Enables or disables the file translation rules.<p>
*
* @param value if "true", file translation is enabled, otherwise it is disabled
*/
public void setFileTranslationEnabled(String value) {
m_fileTranslationEnabled = Boolean.valueOf(value).booleanValue();
if (CmsLog.LOG.isInfoEnabled()) {
if (m_fileTranslationEnabled) {
CmsLog.LOG.info(Messages.get().key(Messages.INIT_VFS_FILE_TRANSLATION_ENABLE_0));
} else {
CmsLog.LOG.info(Messages.get().key(Messages.INIT_VFS_FILE_TRANSLATION_DISABLE_0));
}
}
}
/**
* Enables or disables the folder translation rules.<p>
*
* @param value if "true", folder translation is enabled, otherwise it is disabled
*/
public void setFolderTranslationEnabled(String value) {
m_folderTranslationEnabled = Boolean.valueOf(value).booleanValue();
if (CmsLog.LOG.isInfoEnabled()) {
if (m_folderTranslationEnabled) {
CmsLog.LOG.info(Messages.get().key(Messages.INIT_VFS_FOLDER_TRANSLATION_ENABLE_0));
} else {
CmsLog.LOG.info(Messages.get().key(Messages.INIT_VFS_FOLDER_TRANSLATION_DISABLE_0));
}
}
}
/**
* Sets the generated resource manager.<p>
*
* @param manager the resource manager to set
*/
public void setResourceManager(CmsResourceManager manager) {
m_resourceManager = manager;
}
/**
* Sets the generated XML content type manager.<p>
*
* @param manager the generated XML content type manager to set
*/
public void setXmlContentTypeManager(CmsXmlContentTypeManager manager) {
if (CmsLog.LOG.isInfoEnabled()) {
CmsLog.LOG.info(Messages.get().key(Messages.INIT_VFS_XML_CONTENT_FINISHED_0));
}
m_xmlContentTypeManager = manager;
}
}
|
package org.agmip.ui.quadui;
import com.rits.cloning.Cloner;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.agmip.dome.DomeUtil;
import org.agmip.dome.Engine;
import org.agmip.translators.csv.AlnkInput;
import org.agmip.translators.csv.DomeInput;
import org.agmip.util.MapUtil;
import org.apache.pivot.util.concurrent.Task;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ApplyDomeTask extends Task<HashMap> {
private static Logger log = LoggerFactory.getLogger(ApplyDomeTask.class);
private final HashMap<String, HashMap<String, Object>> ovlDomes = new HashMap<String, HashMap<String, Object>>();
private final HashMap<String, HashMap<String, Object>> stgDomes = new HashMap<String, HashMap<String, Object>>();
private HashMap<String, Object> linkDomes = new HashMap<String, Object>();
private HashMap<String, String> ovlLinks = new HashMap<String, String>();
private HashMap<String, String> stgLinks = new HashMap<String, String>();
private final HashMap<String, String> ovlNewDomeIdMap = new HashMap<String, String>();
private final HashMap<String, String> stgNewDomeIdMap = new HashMap<String, String>();
// private HashMap<String, ArrayList<String>> wthLinks = new HashMap<String, ArrayList<String>>();
// private HashMap<String, ArrayList<String>> soilLinks = new HashMap<String, ArrayList<String>>();
private HashMap source;
private String mode;
private boolean autoApply;
private int thrPoolSize;
public ApplyDomeTask(String linkFile, String fieldFile, String strategyFile, String mode, HashMap m, boolean autoApply) {
this.source = m;
this.mode = mode;
this.autoApply = autoApply;
// Setup the domes here.
loadDomeLinkFile(linkFile);
log.debug("link csv: {}", ovlLinks);
if (mode.equals("strategy")) {
loadDomeFile(strategyFile, stgDomes);
}
loadDomeFile(fieldFile, ovlDomes);
thrPoolSize = Runtime.getRuntime().availableProcessors();
}
public ApplyDomeTask(String linkFile, String fieldFile, String strategyFile, String mode, HashMap m, boolean autoApply, int thrPoolSize) {
this(linkFile, fieldFile, strategyFile, mode, m, autoApply);
this.thrPoolSize = thrPoolSize;
}
private void loadDomeLinkFile(String fileName) {
String fileNameTest = fileName.toUpperCase();
log.debug("Loading LINK file: {}", fileName);
linkDomes = null;
try {
if (fileNameTest.endsWith(".CSV")) {
log.debug("Entering single ACMO CSV file DOME handling");
AlnkInput reader = new AlnkInput();
linkDomes = (HashMap<String, Object>) reader.readFile(fileName);
} else if (fileNameTest.endsWith(".ALNK")) {
log.debug("Entering single ALNK file DOME handling");
AlnkInput reader = new AlnkInput();
linkDomes = (HashMap<String, Object>) reader.readFile(fileName);
}
if (linkDomes != null) {
log.debug("link info: {}", linkDomes.toString());
try {
if (!linkDomes.isEmpty()) {
if (linkDomes.containsKey("link_overlay")) {
ovlLinks = (HashMap<String, String>) linkDomes.get("link_overlay");
}
if (linkDomes.containsKey("link_stragty")) {
stgLinks = (HashMap<String, String>) linkDomes.get("link_stragty");
}
}
} catch (Exception ex) {
log.error("Error processing DOME file: {}", ex.getMessage());
HashMap<String, Object> d = new HashMap<String, Object>();
d.put("errors", ex.getMessage());
}
}
} catch (Exception ex) {
log.error("Error processing DOME file: {}", ex.getMessage());
HashMap<String, Object> d = new HashMap<String, Object>();
d.put("errors", ex.getMessage());
}
}
private String getLinkIds(String domeType, HashMap entry) {
String exname = MapUtil.getValueOr(entry, "exname", "");
String wst_id = MapUtil.getValueOr(entry, "wst_id", "");
String soil_id = MapUtil.getValueOr(entry, "soil_id", "");
String linkIdsExp = getLinkIds(domeType, "EXNAME", exname);
String linkIdsWst = getLinkIds(domeType, "WST_ID", wst_id);
String linkIdsSoil = getLinkIds(domeType, "SOIL_ID", soil_id);
String ret = "";
if (!linkIdsExp.equals("")) {
ret += linkIdsExp + "|";
}
if (!linkIdsWst.equals("")) {
ret += linkIdsWst + "|";
}
if (!linkIdsSoil.equals("")) {
ret += linkIdsSoil;
}
if (ret.endsWith("|")) {
ret = ret.substring(0, ret.length() - 1);
}
return ret;
}
private String getLinkIds(String domeType, String idType, String id) {
HashMap<String, String> links;
if (domeType.equals("strategy")) {
links = stgLinks;
} else if (domeType.equals("overlay")) {
links = ovlLinks;
} else {
return "";
}
if (links.isEmpty() || id.equals("")) {
return "";
}
String linkIds = "";
ArrayList<String> altLinkIds = new ArrayList();
altLinkIds.add(idType + "_ALL");
if (id.matches("[^_]+_\\d+$")) {
altLinkIds.add(idType + "_" + id.replaceAll("_\\d+$", ""));
altLinkIds.add(idType + "_" + id + "__1");
} else if (id.matches(".+_\\d+__\\d+$")) {
altLinkIds.add(idType + "_" + id.replaceAll("__\\d+$", ""));
altLinkIds.add(idType + "_" + id.replaceAll("_\\d+__\\d+$", ""));
}
altLinkIds.add(idType + "_" + id);
for (String linkId : altLinkIds) {
if (links.containsKey(linkId)) {
linkIds += links.get(linkId) + "|";
}
}
if (linkIds.endsWith("|")) {
linkIds = linkIds.substring(0, linkIds.length() - 1);
}
return linkIds;
}
private void reviseDomeIds(HashMap entry, String domeIds, String domeType) {
HashMap<String, HashMap<String, Object>> domes;
HashMap<String, String> domeClimIdMap;
String domeName;
if (domeType.equals("strategy")) {
domes = stgDomes;
domeClimIdMap = ovlNewDomeIdMap;
domeName = "seasonal_strategy";
} else if (domeType.equals("overlay")) {
domes = ovlDomes;
domeClimIdMap = stgNewDomeIdMap;
domeName = "field_overlay";
} else {
return;
}
StringBuilder newDomeIds = new StringBuilder();
for (String domeId : domeIds.split("[|]")) {
String[] metas = domeId.split("-");
if (metas.length < 7) {
if (domeClimIdMap.containsKey(domeId)) {
domeId = domeClimIdMap.get(domeId);
} else {
String climId = "";
HashMap<String, Object> dome = MapUtil.getObjectOr(domes, domeId, new HashMap());
// Only auto-fix the clim_id for seasonal strategy DOME
if (!domeType.equals("overlay")) {
climId = MapUtil.getValueOr(entry, "clim_id", "").toUpperCase();
if (!dome.isEmpty()) {
ArrayList<HashMap<String, String>> rules = DomeUtil.getRules(dome);
for (HashMap<String, String> rule : rules) {
String var = MapUtil.getValueOr(rule, "variable", "").toLowerCase();
if (var.equals("clim_id")) {
climId = MapUtil.getValueOr(rule, "args", climId).toUpperCase();
}
}
}
}
StringBuilder newDomeId = new StringBuilder();
for (int i = 0; i < metas.length - 1; i++) {
newDomeId.append(metas[i]).append("-");
}
newDomeId.append(climId).append("-").append(metas[metas.length - 1]);
domeClimIdMap.put(domeId, newDomeId.toString());
domeId = newDomeId.toString();
DomeUtil.updateMetaInfo(dome, domeId);
}
}
newDomeIds.append(domeId).append("|");
}
if (newDomeIds.charAt(newDomeIds.length() - 1) == '|') {
newDomeIds.deleteCharAt(newDomeIds.length() - 1);
}
entry.put(domeName, newDomeIds.toString());
}
private void loadDomeFile(String fileName, HashMap<String, HashMap<String, Object>> domes) {
String fileNameTest = fileName.toUpperCase();
log.info("Loading DOME file: {}", fileName);
if (fileNameTest.endsWith(".ZIP")) {
log.debug("Entering Zip file handling");
ZipFile z;
try {
z = new ZipFile(fileName);
Enumeration entries = z.entries();
while (entries.hasMoreElements()) {
// Do we handle nested zips? Not yet.
ZipEntry entry = (ZipEntry) entries.nextElement();
File zipFileName = new File(entry.getName());
if (zipFileName.getName().toLowerCase().endsWith(".csv") && !zipFileName.getName().startsWith(".")) {
log.debug("Processing file: {}", zipFileName.getName());
DomeInput translator = new DomeInput();
translator.readCSV(z.getInputStream(entry));
HashMap<String, Object> dome = translator.getDome();
log.debug("dome info: {}", dome.toString());
String domeName = DomeUtil.generateDomeName(dome);
if (!domeName.equals("
domes.put(domeName, new HashMap<String, Object>(dome));
}
}
}
z.close();
} catch (Exception ex) {
log.error("Error processing DOME file: {}", ex.getMessage());
HashMap<String, Object> d = new HashMap<String, Object>();
d.put("errors", ex.getMessage());
}
} else if (fileNameTest.endsWith(".CSV")) {
log.debug("Entering single CSV file DOME handling");
try {
DomeInput translator = new DomeInput();
HashMap<String, Object> dome = (HashMap<String, Object>) translator.readFile(fileName);
String domeName = DomeUtil.generateDomeName(dome);
log.debug("Dome name: {}", domeName);
log.debug("Dome layout: {}", dome.toString());
domes.put(domeName, dome);
} catch (Exception ex) {
log.error("Error processing DOME file: {}", ex.getMessage());
HashMap<String, Object> d = new HashMap<String, Object>();
d.put("errors", ex.getMessage());
}
} else if (fileNameTest.endsWith(".JSON") || fileNameTest.endsWith(".DOME")) {
log.debug("Entering single ACE Binary file DOME handling");
try {
ObjectMapper mapper = new ObjectMapper();
String json;
if (fileNameTest.endsWith(".JSON")) {
json = new Scanner(new FileInputStream(fileName), "UTF-8").useDelimiter("\\A").next();
} else {
json = new Scanner(new GZIPInputStream(new FileInputStream(fileName)), "UTF-8").useDelimiter("\\A").next();
}
HashMap<String, HashMap<String, Object>> tmp = mapper.readValue(json, new TypeReference<HashMap<String, HashMap<String, Object>>>() {
});
// domes.putAll(tmp);
for (HashMap dome : tmp.values()) {
String domeName = DomeUtil.generateDomeName(dome);
if (!domeName.equals("
domes.put(domeName, new HashMap<String, Object>(dome));
}
}
log.debug("Domes layout: {}", domes.toString());
} catch (Exception ex) {
log.error("Error processing DOME file: {}", ex.getMessage());
HashMap<String, Object> d = new HashMap<String, Object>();
d.put("errors", ex.getMessage());
}
}
}
@Override
public HashMap<String, Object> execute() {
// First extract all the domes and put them in a HashMap by DOME_NAME
// The read the DOME_NAME field of the CSV file
// Split the DOME_NAME, and then apply sequentially to the HashMap.
// PLEASE NOTE: This can be a massive undertaking if the source map
// is really large. Need to find optimization points.
HashMap<String, Object> output = new HashMap<String, Object>();
//HashMap<String, ArrayList<HashMap<String, String>>> dome;
// Load the dome
if (ovlDomes.isEmpty() && stgDomes.isEmpty()) {
log.info("No DOME to apply.");
HashMap<String, Object> d = new HashMap<String, Object>();
//d.put("domeinfo", new HashMap<String, String>());
d.put("domeoutput", source);
return d;
}
if (autoApply) {
HashMap<String, Object> d = new HashMap<String, Object>();
if (ovlDomes.size() > 1) {
log.error("Auto-Apply feature only allows one field overlay file per run");
d.put("errors", "Auto-Apply feature only allows one field overlay file per run");
return d;
} else if (stgDomes.size() > 1) {
log.error("Auto-Apply feature only allows one seasonal strategy file per run");
d.put("errors", "Auto-Apply feature only allows one seasonal strategy file per run");
return d;
}
}
// Flatten the data and apply the dome.
Engine domeEngine;
ArrayList<HashMap<String, Object>> flattenedData = MapUtil.flatPack(source);
boolean noExpMode = false;
if (flattenedData.isEmpty()) {
log.info("No experiment data detected, will try Weather and Soil data only mode");
noExpMode = true;
flattenedData.addAll(MapUtil.getRawPackageContents(source, "soils"));
flattenedData.addAll(MapUtil.getRawPackageContents(source, "weathers"));
// flatSoilAndWthData(flattenedData, "soil");
// flatSoilAndWthData(flattenedData, "weather");
if (flattenedData.isEmpty()) {
HashMap<String, Object> d = new HashMap<String, Object>();
log.error("No data found from input file, no DOME will be applied for data set {}", source.toString());
d.put("errors", "Loaded raw data is invalid, please check input files");
return d;
}
}
if (mode.equals("strategy")) {
log.debug("Domes: {}", stgDomes.toString());
log.debug("Entering Strategy mode!");
if (!noExpMode) {
updateWthReferences(updateExpReferences(true));
flattenedData = MapUtil.flatPack(source);
}
// int cnt = 0;
// for (HashMap<String, Object> entry : MapUtil.getRawPackageContents(source, "experiments")) {
// log.debug("Exp at {}: {}, {}",
// cnt,
// entry.get("wst_id"),
// entry.get("clim_id"),
// ((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).get("wst_id"),
// ((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).get("clim_id")
// cnt++;
String stgDomeName = "";
if (autoApply) {
for (String domeName : stgDomes.keySet()) {
stgDomeName = domeName;
}
log.info("Auto apply seasonal strategy: {}", stgDomeName);
}
Engine generatorEngine;
ArrayList<HashMap<String, Object>> strategyResults = new ArrayList<HashMap<String, Object>>();
for (HashMap<String, Object> entry : flattenedData) {
if (autoApply) {
entry.put("seasonal_strategy", stgDomeName);
}
String domeName = getLinkIds("strategy", entry);
if (domeName.equals("")) {
domeName = MapUtil.getValueOr(entry, "seasonal_strategy", "");
} else {
entry.put("seasonal_strategy", domeName);
log.debug("Apply seasonal strategy domes from link csv: {}", domeName);
}
entry.remove("seasonal_strategy");
reviseDomeIds(entry, domeName, "strategy");
String tmp[] = domeName.split("[|]");
String strategyName;
if (tmp.length > 1) {
log.warn("Multiple seasonal strategy dome is not supported yet, only the first dome will be applied");
for (int i = 1; i < tmp.length; i++) {
setFailedDomeId(entry, "seasonal_dome_failed", tmp[i]);
}
}
strategyName = tmp[0];
log.info("Apply DOME {} for {}", strategyName, MapUtil.getValueOr(entry, "exname", MapUtil.getValueOr(entry, "soil_id", MapUtil.getValueOr(entry, "wst_id", "<Unknow>"))));
log.debug("Looking for ss: {}", strategyName);
if (!strategyName.equals("")) {
if (stgDomes.containsKey(strategyName)) {
log.debug("Found strategyName");
entry.put("dome_applied", "Y");
entry.put("seasonal_dome_applied", "Y");
generatorEngine = new Engine(stgDomes.get(strategyName), true);
if (!noExpMode) {
// Check if there is no weather or soil data matched with experiment
if (((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).isEmpty()) {
log.warn("No scenario weather data found for: [{}]", MapUtil.getValueOr(entry, "exname", "N/A"));
}
if (((HashMap) MapUtil.getObjectOr(entry, "soil", new HashMap())).isEmpty()) {
log.warn("No soil data found for: [{}]", MapUtil.getValueOr(entry, "exname", "N/A"));
}
}
ArrayList<HashMap<String, Object>> newEntries = generatorEngine.applyStg(flatSoilAndWthData(entry, noExpMode));
log.debug("New Entries to add: {}", newEntries.size());
strategyResults.addAll(newEntries);
} else {
log.error("Cannot find strategy: {}", strategyName);
setFailedDomeId(entry, "seasonal_dome_failed", strategyName);
}
}
}
log.debug("=== FINISHED GENERATION ===");
log.debug("Generated count: {}", strategyResults.size());
ArrayList<HashMap<String, Object>> exp = MapUtil.getRawPackageContents(source, "experiments");
exp.clear();
exp.addAll(strategyResults);
flattenedData = MapUtil.flatPack(source);
if (noExpMode) {
flattenedData.addAll(MapUtil.getRawPackageContents(source, "soils"));
flattenedData.addAll(MapUtil.getRawPackageContents(source, "weathers"));
}
}
if (!noExpMode) {
if (mode.equals("strategy")) {
updateExpReferences(false);
} else {
updateWthReferences(updateExpReferences(false));
}
flattenedData = MapUtil.flatPack(source);
}
String ovlDomeName = "";
if (autoApply) {
for (String domeName : ovlDomes.keySet()) {
ovlDomeName = domeName;
}
log.info("Auto apply field overlay: {}", ovlDomeName);
}
int cnt = 0;
ArrayList<ApplyDomeRunner> engineRunners = new ArrayList();
ExecutorService executor;
if (thrPoolSize > 1) {
log.info("Create the thread pool with the size of {} for appling filed overlay DOME", thrPoolSize);
executor = Executors.newFixedThreadPool(thrPoolSize);
} else if (thrPoolSize == 1) {
log.info("Create the single thread pool for appling filed overlay DOME");
executor = Executors.newSingleThreadExecutor();
} else {
log.info("Create the cached thread pool with flexible size for appling filed overlay DOME");
executor = Executors.newCachedThreadPool();
}
HashMap<String, HashMap<String, ArrayList<HashMap<String, String>>>> soilDomeMap = new HashMap();
HashMap<String, HashMap<String, ArrayList<HashMap<String, String>>>> wthDomeMap = new HashMap();
HashSet<String> soilIds = getSWIdsSet("soils", new String[]{"soil_id"});
HashSet<String> wthIds = getSWIdsSet("weathers", new String[]{"wst_id", "clim_id"});
ArrayList<HashMap> soilDataArr = new ArrayList();
ArrayList<HashMap> wthDataArr = new ArrayList();
ArrayList<ArrayList<Engine>> soilEngines = new ArrayList();
ArrayList<ArrayList<Engine>> wthEngines = new ArrayList();
for (HashMap<String, Object> entry : flattenedData) {
log.debug("Exp at {}: {}, {}, {}",
cnt,
entry.get("wst_id"),
((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).get("wst_id"),
((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).get("clim_id"));
cnt++;
if (autoApply) {
entry.put("field_overlay", ovlDomeName);
}
String domeName = getLinkIds("overlay", entry);
if (domeName.equals("")) {
domeName = MapUtil.getValueOr(entry, "field_overlay", "");
} else {
entry.put("field_overlay", domeName);
log.debug("Apply field overlay domes from link csv: {}", domeName);
}
reviseDomeIds(entry, domeName, "overlay");
String soilId = MapUtil.getValueOr(entry, "soil_id", "");
String wstId = MapUtil.getValueOr(entry, "wst_id", "");
String climId = MapUtil.getValueOr(entry, "clim_id", "");
ArrayList<Engine> sEngines = new ArrayList();
ArrayList<Engine> wEngines = new ArrayList();
String sDomeIds = "";
String wDomeIds = "";
ArrayList<HashMap<String, String>> sRulesTotal = new ArrayList();
ArrayList<HashMap<String, String>> wRulesTotal = new ArrayList();
if (!domeName.equals("")) {
String tmp[] = domeName.split("[|]");
int tmpLength = tmp.length;
ArrayList<Engine> engines = new ArrayList();
for (int i = 0; i < tmpLength; i++) {
String tmpDomeId = tmp[i].toUpperCase();
log.debug("Apply DOME {} for {}", tmpDomeId, MapUtil.getValueOr(entry, "exname", MapUtil.getValueOr(entry, "soil_id", MapUtil.getValueOr(entry, "wst_id", "<Unknow>"))));
log.debug("Looking for dome_name: {}", tmpDomeId);
if (ovlDomes.containsKey(tmpDomeId)) {
domeEngine = new Engine(ovlDomes.get(tmpDomeId));
entry.put("dome_applied", "Y");
entry.put("field_dome_applied", "Y");
ArrayList<HashMap<String, String>> sRules = domeEngine.extractSoilRules();
if (!sRules.isEmpty()) {
if (sDomeIds.equals("")) {
sDomeIds = tmpDomeId;
} else {
sDomeIds += "|" + tmpDomeId;
}
sEngines.add(new Engine(sRules, tmpDomeId));
sRulesTotal.addAll(sRules);
}
ArrayList<HashMap<String, String>> wRules = domeEngine.extractWthRules();
if (!wRules.isEmpty()) {
if (wDomeIds.equals("")) {
wDomeIds = tmpDomeId;
} else {
wDomeIds += "|" + tmpDomeId;
}
wEngines.add(new Engine(wRules, tmpDomeId));
wRulesTotal.addAll(wRules);
}
engines.add(domeEngine);
} else {
log.error("Cannot find overlay: {}", tmpDomeId);
setFailedDomeId(entry, "field_dome_failed", tmpDomeId);
}
}
HashMap<String, ArrayList<HashMap<String, String>>> lastAppliedSoilDomes = soilDomeMap.get(soilId);
if (lastAppliedSoilDomes == null) {
soilDataArr.add(entry);
soilEngines.add(sEngines);
lastAppliedSoilDomes = new HashMap();
lastAppliedSoilDomes.put(sDomeIds, sRulesTotal);
soilDomeMap.put(soilId, lastAppliedSoilDomes);
} else if (!lastAppliedSoilDomes.containsKey(sDomeIds)) {
boolean isSameRules = false;
for (ArrayList<HashMap<String, String>> rules : lastAppliedSoilDomes.values()) {
if (rules.equals(sRulesTotal)) {
isSameRules = true;
break;
}
}
if (!isSameRules) {
replicateSoil(entry, soilIds);
soilDataArr.add(entry);
soilEngines.add(sEngines);
lastAppliedSoilDomes.put(sDomeIds, sRulesTotal);
}
}
HashMap<String, ArrayList<HashMap<String, String>>> lastAppliedWthDomes = wthDomeMap.get(wstId+climId);
if (lastAppliedWthDomes == null) {
wthDataArr.add(entry);
wthEngines.add(wEngines);
lastAppliedWthDomes = new HashMap();
lastAppliedWthDomes.put(wDomeIds, wRulesTotal);
wthDomeMap.put(wstId+climId, lastAppliedWthDomes);
} else if (!lastAppliedWthDomes.containsKey(wDomeIds)) {
boolean isSameRules = false;
for (ArrayList<HashMap<String, String>> rules : lastAppliedWthDomes.values()) {
if (rules.equals(wRulesTotal)) {
isSameRules = true;
break;
}
}
if (!isSameRules) {
replicateWth(entry, wthIds);
wthDataArr.add(entry);
wthEngines.add(wEngines);
lastAppliedWthDomes.put(wDomeIds, wRulesTotal);
}
}
engineRunners.add(new ApplyDomeRunner(engines, entry, noExpMode, mode));
}
}
for (int i = 0; i < soilDataArr.size(); i++) {
for (Engine e : soilEngines.get(i)) {
e.apply(flatSoilAndWthData(soilDataArr.get(i), noExpMode));
}
}
for (int i = 0; i < wthDataArr.size(); i++) {
for (Engine e : wthEngines.get(i)) {
e.apply(flatSoilAndWthData(wthDataArr.get(i), noExpMode));
}
}
for (ApplyDomeRunner engineRunner : engineRunners) {
executor.submit(engineRunner);
// engine.apply(flatSoilAndWthData(entry, noExpMode));
// ArrayList<String> strategyList = engine.getGenerators();
// if (!strategyList.isEmpty()) {
// log.warn("The following DOME commands in the field overlay file are ignored : {}", strategyList.toString());
// if (!noExpMode && !mode.equals("strategy")) {
// // Check if there is no weather or soil data matched with experiment
// if (((HashMap) MapUtil.getObjectOr(entry, "weather", new HashMap())).isEmpty()) {
// log.warn("No baseline weather data found for: [{}]", MapUtil.getValueOr(entry, "exname", "N/A"));
// if (((HashMap) MapUtil.getObjectOr(entry, "soil", new HashMap())).isEmpty()) {
// log.warn("No soil data found for: [{}]", MapUtil.getValueOr(entry, "exname", "N/A"));
}
executor.shutdown();
while (!executor.isTerminated()) {
}
// executor = null;
if (noExpMode) {
output.put("domeoutput", source);
} else {
output.put("domeoutput", MapUtil.bundle(flattenedData));
}
if (ovlDomes != null && !ovlDomes.isEmpty()) {
output.put("ovlDomes", ovlDomes);
}
if (stgDomes != null && !stgDomes.isEmpty()) {
output.put("stgDomes", stgDomes);
}
return output;
}
// private void flatSoilAndWthData(ArrayList<HashMap<String, Object>> flattenedData, String key) {
// ArrayList<HashMap<String, Object>> arr = MapUtil.getRawPackageContents(source, key + "s");
// for (HashMap<String, Object> data : arr) {
// HashMap<String, Object> tmp = new HashMap<String, Object>();
// tmp.put(key, data);
// flattenedData.add(tmp);
private HashMap<String, Object> flatSoilAndWthData(HashMap<String, Object> data, boolean noExpFlg) {
if (!noExpFlg) {
return data;
}
HashMap<String, Object> ret;
if (data.containsKey("dailyWeather")) {
ret = new HashMap<String, Object>();
ret.put("weather", data);
} else if (data.containsKey("soilLayer")) {
ret = new HashMap<String, Object>();
ret.put("soil", data);
} else {
ret = data;
}
return ret;
}
private void setFailedDomeId(HashMap data, String failKey, String failId) {
String failIds;
if ((failIds = (String) data.get(failKey)) != null) {
data.put(failKey, failId);
} else {
data.put(failKey, failIds + "|" + failId);
}
}
private boolean updateExpReferences(boolean isStgDome) {
ArrayList<HashMap<String, Object>> expArr = MapUtil.getRawPackageContents(source, "experiments");
boolean isClimIDchanged = false;
HashMap<String, HashMap<String, Object>> domes;
String linkid;
String domeKey;
int maxDomeNum;
if (isStgDome) {
domes = stgDomes;
linkid = "strategy";
domeKey = "seasonal_strategy";
maxDomeNum = 1;
} else {
domes = ovlDomes;
linkid = "field";
domeKey = "field_overlay";
maxDomeNum = Integer.MAX_VALUE;
}
// Pre-scan the seasnal DOME to update reference variables
String autoDomeName = "";
if (autoApply) {
for (String domeName : domes.keySet()) {
autoDomeName = domeName;
}
}
for (HashMap<String, Object> exp : expArr) {
String domeName = getLinkIds(linkid, exp);
if (domeName.equals("")) {
if (autoApply) {
domeName = autoDomeName;
} else {
domeName = MapUtil.getValueOr(exp, domeKey, "");
}
}
if (!domeName.equals("")) {
String tmp[] = domeName.split("[|]");
int tmpLength = Math.min(tmp.length, maxDomeNum);
for (int i = 0; i < tmpLength; i++) {
String tmpDomeId = tmp[i].toUpperCase();
log.debug("Looking for dome_name: {}", tmpDomeId);
if (domes.containsKey(tmpDomeId)) {
log.debug("Found DOME {}", tmpDomeId);
Engine domeEngine = new Engine(domes.get(tmpDomeId));
isClimIDchanged = domeEngine.updateWSRef(exp, isStgDome, mode.equals("strategy"));
// Check if the wst_id is switch to 8-bit long version
String wst_id = MapUtil.getValueOr(exp, "wst_id", "");
if (isStgDome && wst_id.length() < 8) {
exp.put("wst_id", wst_id + "0XXX");
exp.put("clim_id", "0XXX");
isClimIDchanged = true;
}
log.debug("New exp linkage: {}", exp);
}
}
}
}
return isClimIDchanged;
}
private void updateWthReferences(boolean isClimIDchanged) {
ArrayList<HashMap<String, Object>> wthArr = MapUtil.getRawPackageContents(source, "weathers");
boolean isStrategy = mode.equals("strategy");
HashMap<String, HashMap> unfixedWths = new HashMap();
HashSet<String> fixedWths = new HashSet();
for (HashMap<String, Object> wth : wthArr) {
String wst_id = MapUtil.getValueOr(wth, "wst_id", "");
String clim_id = MapUtil.getValueOr(wth, "clim_id", "");
if (clim_id.equals("")) {
if (wst_id.length() == 8) {
clim_id = wst_id.substring(4, 8);
} else {
clim_id = "0XXX";
}
}
// If user assign CLIM_ID in the DOME, or find non-baseline data in the overlay mode, then switch WST_ID to 8-bit version
if (isStrategy || isClimIDchanged || !clim_id.startsWith("0")) {
if (wst_id.length() < 8) {
wth.put("wst_id", wst_id + clim_id);
}
} else {
// Temporally switch all the WST_ID to 8-bit in the data set
if (wst_id.length() < 8) {
wth.put("wst_id", wst_id + clim_id);
} else {
wst_id = wst_id.substring(0, 4);
}
// Check if there is multiple baseline record for one site
if (unfixedWths.containsKey(wst_id)) {
log.warn("There is multiple baseline weather data for site [{}], please choose a particular baseline via field overlay DOME", wst_id);
unfixedWths.remove(wst_id);
fixedWths.add(wst_id);
} else {
if (!fixedWths.contains(wst_id)) {
unfixedWths.put(wst_id, wth);
}
}
}
}
// If no CLIM_ID provided in the overlay mode, then switch the baseline WST_ID to 4-bit.
if (!isStrategy && !unfixedWths.isEmpty()) {
for (String wst_id : unfixedWths.keySet()) {
unfixedWths.get(wst_id).put("wst_id", wst_id);
}
}
}
private void replicateSoil(HashMap entry, HashSet soilIds) {
String newSoilId = MapUtil.getValueOr(entry, "soil_id", "");
HashMap data = MapUtil.getObjectOr(entry, "soil", new HashMap());
if (data.isEmpty()) {
return;
}
Cloner cloner = new Cloner();
HashMap newData = cloner.deepClone(data);
ArrayList<HashMap<String, Object>> soils = MapUtil.getRawPackageContents(source, "soils");
int count = 1;
while (soilIds.contains(newSoilId + "_" + count)) {
count++;
}
newSoilId += "_" + count;
newData.put("soil_id", newSoilId);
entry.put("soil_id", newSoilId);
entry.put("soil", newData);
soilIds.add(newSoilId);
soils.add(newData);
}
private void replicateWth(HashMap entry, HashSet wthIds) {
String newWthId = MapUtil.getValueOr(entry, "wst_id", "");
String climId = MapUtil.getValueOr(entry, "clim_id", "");
HashMap data = MapUtil.getObjectOr(entry, "weather", new HashMap());
if (data.isEmpty()) {
return;
}
Cloner cloner = new Cloner();
HashMap newData = cloner.deepClone(data);
ArrayList<HashMap<String, Object>> wths = MapUtil.getRawPackageContents(source, "weathers");
String inst;
if (newWthId.length() > 1) {
inst = newWthId.substring(0, 2);
} else {
inst = newWthId + "0";
}
newWthId = inst + "01" + climId;
int count = 1;
while (wthIds.contains(newWthId) && count < 99) {
count++;
newWthId = String.format("%s%02d%s", inst, count, climId);
}
if (count == 99 && wthIds.contains(newWthId)) {
inst = inst.substring(0, 1);
newWthId = inst + "100" + climId;
while (wthIds.contains(newWthId)) {
count++;
newWthId = String.format("%s%03d%s", inst, count, climId);
}
}
newData.put("wst_id", newWthId);
entry.put("wst_id", newWthId);
entry.put("weather", newData);
wthIds.add(newWthId);
wths.add(newData);
}
private HashSet<String> getSWIdsSet(String dataKey, String... idKeys) {
HashSet<String> ret = new HashSet();
ArrayList<HashMap<String, Object>> arr = MapUtil.getRawPackageContents(source, dataKey);
for (HashMap data : arr) {
StringBuilder sb = new StringBuilder();
for (String idKey : idKeys) {
sb.append(MapUtil.getValueOr(data, idKey, ""));
}
ret.add(sb.toString());
}
return ret;
}
}
|
package edu.northwestern.bioinformatics.studycalendar.osgi.plugininstaller;
import edu.northwestern.bioinformatics.studycalendar.osgi.OsgiLayerIntegratedTestCase;
import edu.northwestern.bioinformatics.studycalendar.osgi.plugininstaller.internal.PluginInstaller;
import org.apache.commons.io.FileUtils;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.ManagedService;
import org.osgi.service.startlevel.StartLevel;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import static edu.northwestern.bioinformatics.studycalendar.osgi.OsgiLayerIntegratedTestHelper.*;
/**
* @author Rhett Sutphin
*/
public class PluginInstallerTest extends OsgiLayerIntegratedTestCase {
private static final String OUTSIDE_BUNDLE_NAME = "com.example.outside-bundle";
private static final long WAIT_FOR_FILEINSTALL = 3500L * (System.getenv("JOB_NAME") == null ? 1 : 10);
private File outsideBundleFilename;
private List<File> paths;
@Override
protected void setUp() throws Exception {
super.setUp();
outsideBundleFilename = new File(
getModuleRelativeDirectory("osgi-layer:integrated-tests", "src/test/resources"),
"outsideBundle.jar");
// stop host beans so that the (un-set-up) persistence manager doesn't interfere with things
stopBundle("edu.northwestern.bioinformatics.psc-osgi-layer-host-services");
paths = Arrays.asList(
PluginInstaller.pluginsPath(),
PluginInstaller.librariesPath(),
PluginInstaller.configurationsPath()
);
for (File path : paths) {
//noinspection ResultOfMethodCallIgnored
path.mkdirs();
}
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
for (File path : paths) {
FileUtils.deleteDirectory(path);
}
Thread.sleep(WAIT_FOR_FILEINSTALL);
// re-start in case any other tests depend on it
startBundle("edu.northwestern.bioinformatics.psc-osgi-layer-host-services");
}
public void testStartsBundlesInPluginDirectory() throws Exception {
deployOutsideBundleAndWait(PluginInstaller.pluginsPath());
assertEquals("Not started", Bundle.ACTIVE, findBundle(OUTSIDE_BUNDLE_NAME).getState());
}
public void testSetsStartLevelTo25ForBundlesInPluginDirectory() throws Exception {
deployOutsideBundleAndWait(PluginInstaller.pluginsPath());
assertEquals("Wrong level", 25,
getStartLevelService().getBundleStartLevel(findBundle(OUTSIDE_BUNDLE_NAME)));
}
public void testDoesNotStartBundlesInLibraryDirectory() throws Exception {
deployOutsideBundleAndWait(PluginInstaller.librariesPath());
assertEquals("Incorrectly started", Bundle.INSTALLED, findBundle(OUTSIDE_BUNDLE_NAME).getState());
}
public void testSetsStartLevelTo24ForBundlesInLibraryDirectory() throws Exception {
deployOutsideBundleAndWait(PluginInstaller.librariesPath());
assertEquals("Wrong level", 24,
getStartLevelService().getBundleStartLevel(findBundle(OUTSIDE_BUNDLE_NAME)));
}
private void deployOutsideBundleAndWait(File deployTo) throws IOException, InterruptedException {
FileUtils.copyFileToDirectory(outsideBundleFilename, deployTo);
System.out.println("Waiting for " + (WAIT_FOR_FILEINSTALL / 1000.0) + 's');
Thread.sleep(WAIT_FOR_FILEINSTALL);
}
private StartLevel getStartLevelService() throws IOException {
ServiceReference ref = getBundleContext().getServiceReference(StartLevel.class.getName());
assertNotNull("Can't find start level service", ref);
return (StartLevel) getBundleContext().getService(ref);
}
public void testAppliesConfigurationsInConfigurationDirectory() throws Exception {
String servicePid = "psc.mocks.echo.A";
startBundle(
"edu.northwestern.bioinformatics.psc-osgi-layer-mock", ManagedService.class.getName());
FileUtils.writeStringToFile(
new File(PluginInstaller.configurationsPath(), servicePid + ".cfg"),
"psc.mocks.String=quuxbar\n"
);
Thread.sleep(WAIT_FOR_FILEINSTALL);
ServiceReference[] refs = getBundleContext().getAllServiceReferences(
ManagedService.class.getName(), String.format("(%s=%s)", Constants.SERVICE_PID, servicePid));
assertEquals("Wrong services found: " + Arrays.asList(refs), 1, refs.length);
assertEquals("Configuration not applied",
"quuxbar", refs[0].getProperty("psc.mocks.String"));
}
}
|
package org.opencms.workplace.explorer;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsProperty;
import org.opencms.file.CmsPropertyDefinition;
import org.opencms.file.CmsResource;
import org.opencms.file.types.I_CmsResourceType;
import org.opencms.i18n.CmsEncoder;
import org.opencms.jsp.CmsJspActionElement;
import org.opencms.jsp.CmsJspNavBuilder;
import org.opencms.jsp.CmsJspNavElement;
import org.opencms.main.CmsException;
import org.opencms.main.CmsIllegalArgumentException;
import org.opencms.main.CmsLog;
import org.opencms.main.CmsRuntimeException;
import org.opencms.main.OpenCms;
import org.opencms.security.CmsRole;
import org.opencms.util.CmsRequestUtil;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUriSplitter;
import org.opencms.workplace.CmsWorkplaceMessages;
import org.opencms.workplace.CmsWorkplaceSettings;
import org.opencms.workplace.commons.CmsPropertyAdvanced;
import org.opencms.workplace.list.A_CmsListResourceTypeDialog;
import org.opencms.workplace.list.CmsListColumnDefinition;
import org.opencms.workplace.list.CmsListItem;
import org.opencms.workplace.list.CmsListItemSelectionCustomAction;
import org.opencms.workplace.list.CmsListMetadata;
import org.opencms.workplace.list.CmsListOrderEnum;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import org.apache.commons.logging.Log;
/**
* The new resource entry dialog which displays the possible "new actions" for the current user.<p>
*
* It handles the creation of "simple" resource types like plain or JSP resources.<p>
*
* The following files use this class:
* <ul>
* <li>/commons/newresource.jsp
* </ul>
* <p>
*
* @author Andreas Zahner
* @author Armen Markarian
* @author Peter Bonrad
*
* @version $Revision: 1.32 $
*
* @since 6.0.0
*/
public class CmsNewResource extends A_CmsListResourceTypeDialog {
/** The value for the resource name form action. */
public static final int ACTION_NEWFORM = 100;
/** The value for the resource name form submission action. */
public static final int ACTION_SUBMITFORM = 110;
/** Constant for the "Next" button in the build button methods. */
public static final int BUTTON_NEXT = 20;
/** The default suffix. */
public static final String DEFAULT_SUFFIX = ".html";
/** Delimiter for property values, e.g. for available resource types or template sites. */
public static final char DELIM_PROPERTYVALUES = ',';
/** The name for the advanced resource form action. */
public static final String DIALOG_ADVANCED = "advanced";
/** The name for the resource form action. */
public static final String DIALOG_NEWFORM = "newform";
/** The name for the resource form submission action. */
public static final String DIALOG_SUBMITFORM = "submitform";
/** The dialog type. */
public static final String DIALOG_TYPE = "newresource";
/** List column id constant. */
public static final String LIST_COLUMN_URI = "nrcu";
/** Request parameter name for the append html suffix checkbox. */
public static final String PARAM_APPENDSUFFIXHTML = "appendsuffixhtml";
/** Request parameter name for the current folder name. */
public static final String PARAM_CURRENTFOLDER = "currentfolder";
/** Request parameter name for the new form uri. */
public static final String PARAM_NEWFORMURI = "newformuri";
/** Request parameter name for the new resource edit properties flag. */
public static final String PARAM_NEWRESOURCEEDITPROPS = "newresourceeditprops";
/** Request parameter name for the new resource type. */
public static final String PARAM_NEWRESOURCETYPE = "newresourcetype";
/** Request parameter name for the new resource uri. */
public static final String PARAM_NEWRESOURCEURI = "newresourceuri";
/** The property value for available resource to reset behaviour to default dialog. */
public static final String VALUE_DEFAULT = "default";
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(CmsNewResource.class);
/**
* Returns the value for the Title property from the given resource name.<p>
*
* @param name the name of the resource
*
* @return the value for the Title property from the given resource name
*/
public static String computeNewTitleProperty(String name) {
String title = name;
int lastDot = title.lastIndexOf('.');
// check the mime type for the file extension
if ((lastDot > 0) && (lastDot < (title.length() - 1))) {
// remove suffix for Title and NavPos property
title = title.substring(0, lastDot);
}
return title;
}
/**
* A factory to return handlers to create new resources.<p>
*
* @param type the resource type name to get a new resource handler for, as specified in the explorer type settings
* @param defaultClassName a default handler class name, to be used if the handler class specified in the explorer type settings cannot be found
* @param context the JSP page context
* @param req the JSP request
* @param res the JSP response
* @return a new instance of the handler class
* @throws CmsRuntimeException if something goes wrong
*/
public static Object getNewResourceHandler(
String type,
String defaultClassName,
PageContext context,
HttpServletRequest req,
HttpServletResponse res) throws CmsRuntimeException {
if (CmsStringUtil.isEmpty(type)) {
// it's not possible to hardwire the resource type name on the JSP for Xml content types
type = req.getParameter(PARAM_NEWRESOURCETYPE);
}
String className = null;
CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(type);
if (CmsStringUtil.isNotEmpty(settings.getNewResourceHandlerClassName())) {
className = settings.getNewResourceHandlerClassName();
} else {
className = defaultClassName;
}
Class clazz = null;
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
if (LOG.isErrorEnabled()) {
LOG.error(Messages.get().getBundle().key(Messages.ERR_NEW_RES_HANDLER_CLASS_NOT_FOUND_1, className), e);
}
throw new CmsIllegalArgumentException(Messages.get().container(
Messages.ERR_NEW_RES_HANDLER_CLASS_NOT_FOUND_1,
className));
}
Object handler = null;
try {
Constructor constructor = clazz.getConstructor(new Class[] {
PageContext.class,
HttpServletRequest.class,
HttpServletResponse.class});
handler = constructor.newInstance(new Object[] {context, req, res});
} catch (Exception e) {
throw new CmsIllegalArgumentException(Messages.get().container(
Messages.ERR_NEW_RES_CONSTRUCTOR_NOT_FOUND_1,
className));
}
return handler;
}
/**
* Creates a single property object and sets the value individual or shared depending on the OpenCms settings.<p>
*
* @param name the name of the property
* @param value the value to set
* @return an initialized property object
*/
protected static CmsProperty createPropertyObject(String name, String value) {
CmsProperty prop = new CmsProperty();
prop.setAutoCreatePropertyDefinition(true);
prop.setName(name);
if (OpenCms.getWorkplaceManager().isDefaultPropertiesOnStructure()) {
prop.setValue(value, CmsProperty.TYPE_INDIVIDUAL);
} else {
prop.setValue(value, CmsProperty.TYPE_SHARED);
}
return prop;
}
/**
* Returns the properties to create automatically with the new VFS resource.<p>
*
* If configured, the Title and Navigation properties are set on resource creation.<p>
*
* @param cms the initialized CmsObject
* @param resourceName the full resource name
* @param resTypeName the name of the resource type
* @param title the Title String to use for the property values
* @return the List of initialized property objects
*/
protected static List createResourceProperties(CmsObject cms, String resourceName, String resTypeName, String title) {
// create property values
List properties = new ArrayList(3);
// get explorer type settings for the resource type
CmsExplorerTypeSettings settings = OpenCms.getWorkplaceManager().getExplorerTypeSetting(resTypeName);
if (settings.isAutoSetTitle()) {
// add the Title property
properties.add(createPropertyObject(CmsPropertyDefinition.PROPERTY_TITLE, title));
}
if (settings.isAutoSetNavigation()) {
// add the NavText property
properties.add(createPropertyObject(CmsPropertyDefinition.PROPERTY_NAVTEXT, title));
// calculate the new navigation position for the resource
List navList = CmsJspNavBuilder.getNavigationForFolder(cms, resourceName);
float navPos = 1;
if (navList.size() > 0) {
CmsJspNavElement nav = (CmsJspNavElement)navList.get(navList.size() - 1);
navPos = nav.getNavPosition() + 1;
}
// add the NavPos property
properties.add(createPropertyObject(CmsPropertyDefinition.PROPERTY_NAVPOS, String.valueOf(navPos)));
}
return properties;
}
private String m_availableResTypes;
private boolean m_limitedRestypes;
private String m_page;
private String m_paramAppendSuffixHtml;
private String m_paramCurrentFolder;
private String m_paramDialogMode;
private String m_paramNewFormUri;
private String m_paramNewResourceEditProps;
private String m_paramNewResourceType;
private String m_paramNewResourceUri;
private String m_paramPage;
/** a boolean flag that indicates if the create resource operation was successfull or not. */
private boolean m_resourceCreated;
/**
* Public constructor with JSP action element.<p>
*
* @param jsp an initialized JSP action element
*/
public CmsNewResource(CmsJspActionElement jsp) {
super(
jsp,
A_CmsListResourceTypeDialog.LIST_ID,
Messages.get().container(Messages.GUI_NEWRESOURCE_SELECT_TYPE_0),
null,
CmsListOrderEnum.ORDER_ASCENDING,
null);
}
/**
* Public constructor with JSP variables.<p>
*
* @param context the JSP page context
* @param req the JSP request
* @param res the JSP response
*/
public CmsNewResource(PageContext context, HttpServletRequest req, HttpServletResponse res) {
this(new CmsJspActionElement(context, req, res));
}
/**
* Used to close the current JSP dialog.<p>
*
* This method overwrites the close dialog method in the super class,
* because in case a new folder was created before, after this dialog the tree view has to be refreshed.<p>
*
* It tries to include the URI stored in the workplace settings.
* This URI is determined by the frame name, which has to be set
* in the framename parameter.<p>
*
* @throws JspException if including an element fails
*/
public void actionCloseDialog() throws JspException {
if (isCreateIndexMode()) {
// set the current explorer resource to the new created folder
String updateFolder = CmsResource.getParentFolder(getSettings().getExplorerResource());
getSettings().setExplorerResource(updateFolder);
List folderList = new ArrayList(1);
if (updateFolder != null) {
folderList.add(updateFolder);
}
getJsp().getRequest().setAttribute(REQUEST_ATTRIBUTE_RELOADTREE, folderList);
}
super.actionCloseDialog();
}
/**
* Creates the resource using the specified resource name and the newresourcetype parameter.<p>
*
* @throws JspException if inclusion of error dialog fails
*/
public void actionCreateResource() throws JspException {
try {
// calculate the new resource Title property value
String title = computeNewTitleProperty();
// create the full resource name
String fullResourceName = computeFullResourceName();
// create the Title and Navigation properties if configured
I_CmsResourceType resType = OpenCms.getResourceManager().getResourceType(getParamNewResourceType());
List properties = createResourceProperties(fullResourceName, resType.getTypeName(), title);
// create the resource
getCms().createResource(fullResourceName, resType.getTypeId(), null, properties);
setParamResource(fullResourceName);
setResourceCreated(true);
} catch (Throwable e) {
// error creating file, show error dialog
includeErrorpage(this, e);
}
}
/**
* @see org.opencms.workplace.list.A_CmsListDialog#actionDialog()
*/
public void actionDialog() throws JspException, ServletException, IOException {
super.actionDialog();
switch (getAction()) {
case ACTION_SUBMITFORM:
actionCreateResource();
if (isResourceCreated()) {
actionEditProperties(); // redirects only if the edit properties option was checked
}
break;
case ACTION_OK:
actionSelect();
break;
case ACTION_NEWFORM:
setParamAction(DIALOG_SUBMITFORM);
break;
case ACTION_DEFAULT:
default:
setParamAction(DIALOG_OK);
break;
}
}
/**
* Forwards to the property dialog if the resourceeditprops parameter is true.<p>
*
* If the parameter is not true, the dialog will be closed.<p>
*
* @throws IOException if forwarding to the property dialog fails
* @throws ServletException if forwarding to the property dialog fails
* @throws JspException if an inclusion fails
*/
public void actionEditProperties() throws IOException, JspException, ServletException {
boolean editProps = Boolean.valueOf(getParamNewResourceEditProps()).booleanValue();
if (editProps) {
// edit properties checkbox checked, forward to property dialog
Map params = new HashMap();
params.put(PARAM_RESOURCE, getParamResource());
if (isCreateIndexMode()) {
params.put(CmsPropertyAdvanced.PARAM_DIALOGMODE, CmsPropertyAdvanced.MODE_WIZARD_INDEXCREATED);
} else {
params.put(CmsPropertyAdvanced.PARAM_DIALOGMODE, CmsPropertyAdvanced.MODE_WIZARD);
}
sendForward(CmsPropertyAdvanced.URI_PROPERTY_DIALOG_HANDLER, params);
} else {
// edit properties not checked, close the dialog
actionCloseDialog();
}
}
/**
* Forwards to the next page of the new resource wizard after selecting the new resource type.<p>
*
* @throws IOException if forwarding fails
* @throws ServletException if forwarding fails
*/
public void actionSelect() throws IOException, ServletException {
String nextUri = getParamNewResourceUri();
if (!nextUri.startsWith("/")) {
// no absolute path given, use default dialog path
nextUri = PATH_DIALOGS + nextUri;
}
setParamAction(DIALOG_NEWFORM);
CmsUriSplitter splitter = new CmsUriSplitter(nextUri);
Map params = CmsRequestUtil.createParameterMap(splitter.getQuery());
params.putAll(paramsAsParameterMap());
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_page)) {
params.remove(PARAM_PAGE);
}
sendForward(splitter.getPrefix(), params);
}
/**
* Returns the value for the Title property from the given resource name.<p>
*
* @return the value for the Title property from the given resource name
*/
public String computeNewTitleProperty() {
return computeNewTitleProperty(getParamResource());
}
/**
* Builds a default button row with a continue and cancel button.<p>
*
* Override this to have special buttons for your dialog.<p>
*
* @return the button row
*/
public String dialogButtons() {
return dialogButtonsAdvancedNextCancel(
" onclick=\"submitAdvanced();\"",
"id=\"nextButton\" disabled=\"disabled\"",
null);
}
/**
* Builds a button row with an optional "advanced", "next" and a "cancel" button.<p>
*
* @param advancedAttrs optional attributes for the advanced button
* @param nextAttrs optional attributes for the next button
* @param cancelAttrs optional attributes for the cancel button
* @return the button row
*/
public String dialogButtonsAdvancedNextCancel(String advancedAttrs, String nextAttrs, String cancelAttrs) {
if (m_limitedRestypes && OpenCms.getRoleManager().hasRole(getCms(), CmsRole.VFS_MANAGER)) {
return dialogButtons(new int[] {BUTTON_ADVANCED, BUTTON_NEXT, BUTTON_CANCEL}, new String[] {
advancedAttrs,
nextAttrs,
cancelAttrs});
} else {
return dialogButtons(new int[] {BUTTON_NEXT, BUTTON_CANCEL}, new String[] {nextAttrs, cancelAttrs});
}
}
/**
* Builds a button row with a "next" and a "cancel" button.<p>
*
* @param nextAttrs optional attributes for the next button
* @param cancelAttrs optional attributes for the cancel button
* @return the button row
*/
public String dialogButtonsNextCancel(String nextAttrs, String cancelAttrs) {
return dialogButtons(new int[] {BUTTON_NEXT, BUTTON_CANCEL}, new String[] {nextAttrs, cancelAttrs});
}
/**
* Returns the parameter to check if a ".html" suffix should be added to the new resource name.<p>
*
* @return the parameter to check if a ".html" suffix should be added to the new resource name
*/
public String getParamAppendSuffixHtml() {
return m_paramAppendSuffixHtml;
}
/**
* Returns the current folder set by the http request.<p>
*
* If the request parameter value is null/empty then returns the default computed folder.<p>
*
* @return the current folder set by the request param or the computed current folder
*/
public String getParamCurrentFolder() {
if (CmsStringUtil.isEmpty(m_paramCurrentFolder)) {
return computeCurrentFolder();
}
return m_paramCurrentFolder;
}
/**
* Returns the value of the dialogmode parameter,
* or null if this parameter was not provided.<p>
*
* The dialogmode parameter stores the different modes of the property dialog,
* e.g. for displaying other buttons in the new resource wizard.<p>
*
* @return the value of the usetempfileproject parameter
*/
public String getParamDialogmode() {
return m_paramDialogMode;
}
/**
* Returns the new form URI parameter.<p>
*
* @return the new form URI parameter
*/
public String getParamNewFormUri() {
return m_paramNewFormUri;
}
/**
* Returns the new resource edit properties flag parameter.<p>
*
* @return the new resource edit properties flag parameter
*/
public String getParamNewResourceEditProps() {
return m_paramNewResourceEditProps;
}
/**
* Returns the new resource type parameter.<p>
*
* @return the new resource type parameter
*/
public String getParamNewResourceType() {
return m_paramNewResourceType;
}
/**
* Returns the new resource URI parameter.<p>
*
* @return the new resource URI parameter
*/
public String getParamNewResourceUri() {
return m_paramNewResourceUri;
}
/**
* Returns the paramPage.<p>
*
* @return the paramPage
*/
public String getParamPage() {
return m_paramPage;
}
/**
* Returns the suffix of the first default file. If nothing is defined, then ".html" is returned.<p>
*
* @return the suffix of the first default file otherwise ".html"
*/
public String getSuffixHtml() {
String result = "";
if (OpenCms.getDefaultFiles().size() > 0) {
String defaultfile = (String)OpenCms.getDefaultFiles().get(0);
int index = defaultfile.indexOf('.');
if (index >= 0) {
result = defaultfile.substring(index, defaultfile.length());
}
}
if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) {
result = DEFAULT_SUFFIX;
}
return result;
}
/**
* Returns true if the current mode is: create an index page in a newly created folder.<p>
*
* @return true if we are in wizard mode to create an index page, otherwise false
*/
public boolean isCreateIndexMode() {
return CmsPropertyAdvanced.MODE_WIZARD_CREATEINDEX.equals(getParamDialogmode());
}
/**
* Returns true if the resource is created successfully; otherwise false.<p>
*
* @return true if the resource is created successfully; otherwise false
*/
public boolean isResourceCreated() {
return m_resourceCreated;
}
/**
* Overrides the super implementation to avoid problems with double reqource input fields.<p>
*
* @see org.opencms.workplace.CmsWorkplace#paramsAsHidden()
*/
public String paramsAsHidden() {
String resourceName = getParamResource();
// remove resource parameter from hidden params to avoid problems with double input fields in form
setParamResource(null);
String params = super.paramsAsHidden();
// set resource parameter to stored value
setParamResource(resourceName);
return params;
}
/**
* Sets the parameter to check if a ".html" suffix should be added to the new resource name.<p>
*
* @param paramAppendSuffixHtml the parameter to check if a ".html" suffix should be added to the new resource name
*/
public void setParamAppendSuffixHtml(String paramAppendSuffixHtml) {
m_paramAppendSuffixHtml = paramAppendSuffixHtml;
}
/**
* Sets the current folder.<p>
*
* @param paramCurrentFolder the current folder to set
*/
public void setParamCurrentFolder(String paramCurrentFolder) {
m_paramCurrentFolder = paramCurrentFolder;
}
/**
* Sets the value of the dialogmode parameter.<p>
*
* @param value the value to set
*/
public void setParamDialogmode(String value) {
m_paramDialogMode = value;
}
/**
* Sets the new form URI parameter.<p>
*
* @param paramNewFormUri the new form URI parameter to set
*/
public void setParamNewFormUri(String paramNewFormUri) {
m_paramNewFormUri = paramNewFormUri;
}
/**
* Sets the new resource edit properties flag parameter.<p>
*
* @param newResourceEditProps the new resource edit properties flag parameter
*/
public void setParamNewResourceEditProps(String newResourceEditProps) {
m_paramNewResourceEditProps = newResourceEditProps;
}
/**
* Sets the new resource type parameter.<p>
*
* @param newResourceType the new resource type parameter
*/
public void setParamNewResourceType(String newResourceType) {
m_paramNewResourceType = newResourceType;
}
/**
* Sets the new resource URI parameter.<p>
*
* @param newResourceUri the new resource URI parameter
*/
public void setParamNewResourceUri(String newResourceUri) {
m_paramNewResourceUri = newResourceUri;
}
/**
* Sets the paramPage.<p>
*
* @param paramPage the paramPage to set
*/
public void setParamPage(String paramPage) {
m_paramPage = paramPage;
}
/**
* Sets the boolean flag successfullyCreated.<p>
*
* @param successfullyCreated a boolean flag that indicates if the create resource operation was successfull or not
*/
public void setResourceCreated(boolean successfullyCreated) {
m_resourceCreated = successfullyCreated;
}
/**
* Appends the suffix of the first default file suffix to the given resource name if no suffix is present and the
* append suffix option is checked.<p>
*
* @param resourceName the resource name to check
* @param forceSuffix if true, the suffix is appended overriding the append suffix option
* @return the resource name with the default file suffix if no suffix was present and the append suffix option is checked
*/
protected String appendSuffixHtml(String resourceName, boolean forceSuffix) {
// append the default suffix (".html") to new file if no standard type was provided
if ((forceSuffix || Boolean.valueOf(getParamAppendSuffixHtml()).booleanValue())) {
if (OpenCms.getResourceManager().getMimeType(resourceName, null, null) == null) {
resourceName += getSuffixHtml();
}
}
return resourceName;
}
/**
* Appends the full path to the new resource name given in the resource parameter.<p>
*
* @return the full path of the new resource
*/
protected String computeFullResourceName() {
// return the full resource name
// get the current folder
String currentFolder = getParamCurrentFolder();
if (CmsStringUtil.isEmpty(currentFolder)) {
currentFolder = computeCurrentFolder();
}
return currentFolder + getParamResource();
}
/**
* Returns the properties to create automatically with the new VFS resource.<p>
*
* If configured, the Title and Navigation properties are set on resource creation.<p>
*
* @param resourceName the full resource name
* @param resTypeName the name of the resource type
* @param title the Title String to use for the property values
* @return the List of initialized property objects
*/
protected List createResourceProperties(String resourceName, String resTypeName, String title) {
return createResourceProperties(getCms(), resourceName, resTypeName, title);
}
/**
* @see org.opencms.workplace.list.A_CmsListDialog#customHtmlStart()
*/
protected String customHtmlStart() {
StringBuffer result = new StringBuffer(256);
result.append(super.customHtmlStart());
result.append("<script type='text/javascript'>\n");
result.append("function enableButton() {\n");
result.append("\tvar theButton = document.getElementById(\"nextButton\");\n");
result.append("\tif (theButton.disabled == true) {\n");
result.append("\t\ttheButton.disabled = false;\n");
result.append("\t}\n");
result.append("}\n");
result.append("function submitAdvanced() {\n");
result.append("\tdocument.forms[\""
+ getList().getId()
+ "-form\"].action.value = \""
+ DIALOG_ADVANCED
+ "\";\n");
result.append("\tdocument.forms[\"" + getList().getId() + "-form\"].submit();\n");
result.append("}\n");
result.append("</script>");
return result.toString();
}
/**
* @see org.opencms.workplace.CmsDialog#dialogButtonsHtml(java.lang.StringBuffer, int, java.lang.String)
*/
protected void dialogButtonsHtml(StringBuffer result, int button, String attribute) {
attribute = appendDelimiter(attribute);
switch (button) {
case BUTTON_NEXT:
result.append("<input name=\"next\" type=\"submit\" value=\"");
result.append(key(Messages.GUI_BUTTON_NEXTSCREEN_0));
result.append("\" class=\"dialogbutton\"");
result.append(attribute);
result.append(">\n");
break;
default:
super.dialogButtonsHtml(result, button, attribute);
}
}
/**
* @see org.opencms.workplace.list.A_CmsListDialog#getListItems()
*/
protected List getListItems() {
List ret = new ArrayList();
Iterator i;
if (m_limitedRestypes) {
// available resource types limited, create list iterator of given limited types
List newResTypes;
if (m_availableResTypes.indexOf(DELIM_PROPERTYVALUES) > -1) {
newResTypes = CmsStringUtil.splitAsList(m_availableResTypes, DELIM_PROPERTYVALUES);
} else {
newResTypes = CmsStringUtil.splitAsList(m_availableResTypes, CmsProperty.VALUE_LIST_DELIMITER);
}
Iterator k = newResTypes.iterator();
List settings = new ArrayList(newResTypes.size());
while (k.hasNext()) {
String resType = (String)k.next();
// get settings for resource type
CmsExplorerTypeSettings set = OpenCms.getWorkplaceManager().getExplorerTypeSetting(resType);
if (set != null) {
// add found setting to available resource types
settings.add(set);
}
}
// sort explorer type settings by their order
Collections.sort(settings);
i = settings.iterator();
} else {
// create list iterator from all configured resource types
i = OpenCms.getWorkplaceManager().getExplorerTypeSettings().iterator();
}
CmsResource resource = null;
try {
resource = getCms().readResource(getParamCurrentFolder());
} catch (CmsException e) {
// ignore
}
while (i.hasNext()) {
CmsExplorerTypeSettings settings = (CmsExplorerTypeSettings)i.next();
if (!m_limitedRestypes) {
// check for the "new resource" page
if (m_page == null) {
if (CmsStringUtil.isNotEmpty(settings.getNewResourcePage())) {
continue;
}
} else if (!m_page.equals(settings.getNewResourcePage())) {
continue;
}
}
if (CmsStringUtil.isEmpty(settings.getNewResourceUri())) {
// no new resource URI specified for the current settings, dont't show the type
continue;
}
if (!settings.isEditable(getCms(), resource)
|| !settings.getAccess().getPermissions(getCms(), resource).requiresControlPermission()) {
continue;
}
// add found setting to list
CmsListItem item = getList().newItem(settings.getName());
item.set(LIST_COLUMN_NAME, key(settings.getKey()));
item.set(LIST_COLUMN_ICON, "<img src=\""
+ getSkinUri()
+ "filetypes/"
+ settings.getIcon()
+ "\" style=\"width: 16px; height: 16px;\" />");
item.set(LIST_COLUMN_URI, CmsEncoder.encode(settings.getNewResourceUri()));
ret.add(item);
}
return ret;
}
/**
* Returns the title to use for the dialog.<p>
*
* Checks if a custom title key is given in the explorer type settings
* and otherwise returns the default title from
* {@link CmsWorkplaceMessages#getNewResourceTitle(org.opencms.workplace.CmsWorkplace, String)}.<p>
*
* @return the title to use for the dialog
*/
protected String getTitle() {
String title = null;
CmsExplorerTypeSettings set = OpenCms.getWorkplaceManager().getExplorerTypeSetting(getParamNewResourceType());
if ((set != null) && (CmsStringUtil.isNotEmptyOrWhitespaceOnly(set.getTitleKey()))) {
title = getMessages().key(set.getTitleKey(), true);
}
if (CmsStringUtil.isEmptyOrWhitespaceOnly(title)) {
if (CmsStringUtil.isNotEmpty(getParamNewResourceType())) {
title = CmsWorkplaceMessages.getNewResourceTitle(this, getParamNewResourceType());
} else {
title = getParamTitle();
}
}
return title;
}
/**
* @see org.opencms.workplace.CmsWorkplace#initWorkplaceRequestValues(org.opencms.workplace.CmsWorkplaceSettings, javax.servlet.http.HttpServletRequest)
*/
protected void initWorkplaceRequestValues(CmsWorkplaceSettings settings, HttpServletRequest request) {
// set the dialog type
setParamDialogtype(DIALOG_TYPE);
// set default action
setAction(ACTION_DEFAULT);
super.initWorkplaceRequestValues(settings, request);
// build title for new resource dialog
setParamTitle(key(Messages.GUI_NEWRESOURCE_0));
if (CmsStringUtil.isNotEmpty(getParamPage())) {
m_page = getParamPage();
setParamPage(null);
if (CmsStringUtil.isEmptyOrWhitespaceOnly(getParamNewFormUri())
|| getParamNewResourceUri().indexOf("?" + PARAM_PAGE) != -1) {
setParamNewFormUri(getParamNewResourceUri());
setParamNewResourceUri(null);
}
if ((DIALOG_NEWFORM.equals(getParamAction())) || (LIST_INDEPENDENT_ACTION.equals(getParamAction()))) {
setParamAction(null);
}
}
// set the action for the JSP switch
if (DIALOG_OK.equals(getParamAction())) {
setAction(ACTION_OK);
} else if (DIALOG_SUBMITFORM.equals(getParamAction())) {
setAction(ACTION_SUBMITFORM);
} else if (DIALOG_NEWFORM.equals(getParamAction())) {
// set resource name if we are in new folder wizard mode
setInitialResourceName();
setAction(ACTION_NEWFORM);
// set the correct title
setParamTitle(getTitle());
} else if (DIALOG_CANCEL.equals(getParamAction())) {
setAction(ACTION_CANCEL);
} else {
if (!DIALOG_ADVANCED.equals(getParamAction()) && CmsStringUtil.isEmpty(m_page)) {
// check for presence of property limiting the new resource types to create
String newResTypesProperty = "";
try {
newResTypesProperty = getCms().readPropertyObject(
getParamCurrentFolder(),
CmsPropertyDefinition.PROPERTY_RESTYPES_AVAILABLE,
true).getValue();
} catch (CmsException e) {
// ignore this exception, this is a minor issue
}
if (CmsStringUtil.isNotEmpty(newResTypesProperty) && !newResTypesProperty.equals(VALUE_DEFAULT)) {
m_limitedRestypes = true;
m_availableResTypes = newResTypesProperty;
}
}
}
}
/**
* @see org.opencms.workplace.list.A_CmsListDialog#setColumns(org.opencms.workplace.list.CmsListMetadata)
*/
protected void setColumns(CmsListMetadata metadata) {
super.setColumns(metadata);
// add column uri
CmsListColumnDefinition uriCol = new CmsListColumnDefinition(LIST_COLUMN_URI);
uriCol.setName(Messages.get().container(Messages.GUI_NEWRESOURCE_LIST_COLS_URI_0));
uriCol.setVisible(false);
metadata.addColumn(uriCol);
CmsListItemSelectionCustomAction action = (CmsListItemSelectionCustomAction)metadata.getColumnDefinition(
LIST_COLUMN_SELECT).getDirectAction(LIST_ACTION_SEL);
action.setFieldName(PARAM_NEWRESOURCEURI);
action.setColumn(LIST_COLUMN_URI);
action.setAttributes(" onclick=\"enableButton();\"");
}
/**
* Sets the initial resource name of the new page.<p>
*
* This is used for the "new" wizard after creating a new folder followed
* by the "create index file" procedure.<p>
*/
protected void setInitialResourceName() {
if (isCreateIndexMode()) {
// creation of an index file in a new folder, use default file name
String defaultFile = "";
try {
defaultFile = (String)OpenCms.getDefaultFiles().get(0);
} catch (IndexOutOfBoundsException e) {
// list is empty, ignore
}
if (CmsStringUtil.isEmpty(defaultFile)) {
// make sure that the default file name is not empty
defaultFile = "index.html";
}
setParamResource(defaultFile);
} else {
setParamResource("");
}
}
}
|
package org.altbeacon.beacon;
import android.annotation.TargetApi;
import android.bluetooth.BluetoothDevice;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BeaconParser {
private static final String TAG = "BeaconParser";
private static final Pattern I_PATTERN = Pattern.compile("i\\:(\\d+)\\-(\\d+)(l?)");
private static final Pattern M_PATTERN = Pattern.compile("m\\:(\\d+)-(\\d+)\\=([0-9A-F-a-f]+)");
private static final Pattern D_PATTERN = Pattern.compile("d\\:(\\d+)\\-(\\d+)([bl]?)");
private static final Pattern P_PATTERN = Pattern.compile("p\\:(\\d+)\\-(\\d+)");
private static final char[] HEX_ARRAY = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
private Long mMatchingBeaconTypeCode;
protected List<Integer> mIdentifierStartOffsets;
protected List<Integer> mIdentifierEndOffsets;
protected List<Boolean> mIdentifierLittleEndianFlags;
protected List<Integer> mDataStartOffsets;
protected List<Integer> mDataEndOffsets;
protected List<Boolean> mDataLittleEndianFlags;
protected Integer mMatchingBeaconTypeCodeStartOffset;
protected Integer mMatchingBeaconTypeCodeEndOffset;
protected Integer mPowerStartOffset;
protected Integer mPowerEndOffset;
/**
* Makes a new BeaconParser. Should normally be immediately followed by a call to #setLayout
*/
public BeaconParser() {
mIdentifierStartOffsets = new ArrayList<Integer>();
mIdentifierEndOffsets = new ArrayList<Integer>();
mDataStartOffsets = new ArrayList<Integer>();
mDataEndOffsets = new ArrayList<Integer>();
mDataLittleEndianFlags = new ArrayList<Boolean>();
mIdentifierLittleEndianFlags = new ArrayList<Boolean>();
}
/**
* <p>Defines a beacon field parsing algorithm based on a string designating the zero-indexed
* offsets to bytes within a BLE advertisement.</p>
*
* <p>If you want to see examples of how other folks have set up BeaconParsers for different
* kinds of beacons, try doing a Google search for "getBeaconParsers" (include the quotes in
* the search.)</p>
*
* <p>Four prefixes are allowed in the string:</p>
*
* <pre>
* m - matching byte sequence for this beacon type to parse (exactly one required)
* i - identifier (at least one required, multiple allowed)
* p - power calibration field (exactly one required)
* d - data field (optional, multiple allowed)
* </pre>
*
* <p>Each prefix is followed by a colon, then an inclusive decimal byte offset for the field from
* the beginning of the advertisement. In the case of the m prefix, an = sign follows the byte
* offset, followed by a big endian hex representation of the bytes that must be matched for
* this beacon type. When multiple i or d entries exist in the string, they will be added in
* order of definition to the identifier or data array for the beacon when parsing the beacon
* advertisement. Terms are separated by commas.</p>
*
* <p>All offsets from the start of the advertisement are relative to the first byte of the
* two byte manufacturer code. The manufacturer code is therefore always at position 0-1</p>
*
* <p>All data field and identifier expressions may be optionally suffixed with the letter l, which
* indicates the field should be parsed as little endian. If not present, the field will be presumed
* to be big endian.
*
* <p>If the expression cannot be parsed, a <code>BeaconLayoutException</code> is thrown.</p>
*
* <p>Example of a parser string for AltBeacon:</p>
*
* </pre>
* "m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"
* </pre>
*
* <p>This signifies that the beacon type will be decoded when an advertisement is found with
* 0xbeac in bytes 2-3, and a three-part identifier will be pulled out of bytes 4-19, bytes
* 20-21 and bytes 22-23, respectively. A signed power calibration value will be pulled out of
* byte 24, and a data field will be pulled out of byte 25.</p>
*
* Note: bytes 0-1 of the BLE manufacturer advertisements are the two byte manufacturer code.
* Generally you should not match on these two bytes when using a BeaconParser, because it will
* limit your parser to matching only a transmitter made by a specific manufacturer. Software
* and operating systems that scan for beacons typically ignore these two bytes, allowing beacon
* manufacturers to use their own company code assigned by Bluetooth SIG. The default parser
* implementation will already pull out this company code and store it in the
* beacon.mManufacturer field. Matcher expressions should therefore start with "m2-3:" followed
* by the multi-byte hex value that signifies the beacon type.
*
* @param beaconLayout
* @return the BeaconParser instance
*/
public BeaconParser setBeaconLayout(String beaconLayout) {
String[] terms = beaconLayout.split(",");
for (String term : terms) {
boolean found = false;
Matcher matcher = I_PATTERN.matcher(term);
while (matcher.find()) {
found = true;
try {
int startOffset = Integer.parseInt(matcher.group(1));
int endOffset = Integer.parseInt(matcher.group(2));
Boolean littleEndian = matcher.group(3).equals("l");
mIdentifierLittleEndianFlags.add(littleEndian);
mIdentifierStartOffsets.add(startOffset);
mIdentifierEndOffsets.add(endOffset);
} catch (NumberFormatException e) {
throw new BeaconLayoutException("Cannot parse integer byte offset in term: " + term);
}
}
matcher = D_PATTERN.matcher(term);
while (matcher.find()) {
found = true;
try {
int startOffset = Integer.parseInt(matcher.group(1));
int endOffset = Integer.parseInt(matcher.group(2));
Boolean littleEndian = matcher.group(3).equals("l");
mDataLittleEndianFlags.add(littleEndian);
mDataStartOffsets.add(startOffset);
mDataEndOffsets.add(endOffset);
} catch (NumberFormatException e) {
throw new BeaconLayoutException("Cannot parse integer byte offset in term: " + term);
}
}
matcher = P_PATTERN.matcher(term);
while (matcher.find()) {
found = true;
try {
int startOffset = Integer.parseInt(matcher.group(1));
int endOffset = Integer.parseInt(matcher.group(2));
mPowerStartOffset=startOffset;
mPowerEndOffset=endOffset;
} catch (NumberFormatException e) {
throw new BeaconLayoutException("Cannot parse integer power byte offset in term: " + term);
}
}
matcher = M_PATTERN.matcher(term);
while (matcher.find()) {
found = true;
try {
int startOffset = Integer.parseInt(matcher.group(1));
int endOffset = Integer.parseInt(matcher.group(2));
mMatchingBeaconTypeCodeStartOffset = startOffset;
mMatchingBeaconTypeCodeEndOffset = endOffset;
} catch (NumberFormatException e) {
throw new BeaconLayoutException("Cannot parse integer byte offset in term: " + term);
}
String hexString = matcher.group(3);
try {
mMatchingBeaconTypeCode = Long.decode("0x"+hexString);
}
catch (NumberFormatException e) {
throw new BeaconLayoutException("Cannot parse beacon type code: "+hexString+" in term: " + term);
}
}
if (!found) {
BeaconManager.logDebug(TAG, "cannot parse term "+term);
throw new BeaconLayoutException("Cannot parse beacon layout term: " + term);
}
}
if (mPowerStartOffset == null || mPowerEndOffset == null) {
throw new BeaconLayoutException("You must supply a power byte offset with a prefix of 'p'");
}
if (mMatchingBeaconTypeCodeStartOffset == null || mMatchingBeaconTypeCodeEndOffset == null) {
throw new BeaconLayoutException("You must supply a matching beacon type expression with a prefix of 'm'");
}
if (mIdentifierStartOffsets.size() == 0 || mIdentifierEndOffsets.size() == 0) {
throw new BeaconLayoutException("You must supply at least one identifier offset withh a prefix of 'i'");
}
return this;
}
/**
* @see #mMatchingBeaconTypeCode
* @return
*/
public Long getMatchingBeaconTypeCode() {
return mMatchingBeaconTypeCode;
}
/**
* Construct a Beacon from a Bluetooth LE packet collected by Android's Bluetooth APIs,
* including the raw bluetooth device info
*
* @param scanData The actual packet bytes
* @param rssi The measured signal strength of the packet
* @param device The bluetooth device that was detected
* @return An instance of a <code>Beacon</code>
*/
@TargetApi(5)
public Beacon fromScanData(byte[] scanData, int rssi, BluetoothDevice device) {
return fromScanData(scanData, rssi, device, new Beacon());
}
@TargetApi(5)
protected Beacon fromScanData(byte[] scanData, int rssi, BluetoothDevice device, Beacon beacon) {
int startByte = 2;
boolean patternFound = false;
byte[] typeCodeBytes = longToByteArray(getMatchingBeaconTypeCode(), mMatchingBeaconTypeCodeEndOffset-mMatchingBeaconTypeCodeStartOffset+1);
while (startByte <= 5) {
if (byteArraysMatch(scanData, startByte+mMatchingBeaconTypeCodeStartOffset, typeCodeBytes, 0)) {
patternFound = true;
break;
}
startByte++;
}
if (patternFound == false) {
// This is not an beacon
BeaconManager.logDebug(TAG, "This is not a matching Beacon advertisement. (Was expecting "+byteArrayToString(typeCodeBytes)+". The bytes I see are: "+bytesToHex(scanData));
return null;
}
else {
BeaconManager.logDebug(TAG, "This is a recognized beacon advertisement -- "+String.format("%04x", getMatchingBeaconTypeCode())+" seen");
}
ArrayList<Identifier> identifiers = new ArrayList<Identifier>();
for (int i = 0; i < mIdentifierEndOffsets.size(); i++) {
String idString = byteArrayToFormattedString(scanData, mIdentifierStartOffsets.get(i)+startByte, mIdentifierEndOffsets.get(i)+startByte, mIdentifierLittleEndianFlags.get(i));
identifiers.add(Identifier.parse(idString));
}
ArrayList<Long> dataFields = new ArrayList<Long>();
for (int i = 0; i < mDataEndOffsets.size(); i++) {
String dataString = byteArrayToFormattedString(scanData, mDataStartOffsets.get(i)+startByte, mDataEndOffsets.get(i)+startByte, mDataLittleEndianFlags.get(i));
dataFields.add(Long.parseLong(dataString));
BeaconManager.logDebug(TAG, "parsing found data field "+i);
// TODO: error handling needed here on the parse
}
int txPower = 0;
String powerString = byteArrayToFormattedString(scanData, mPowerStartOffset+startByte, mPowerEndOffset+startByte, false);
txPower = Integer.parseInt(powerString);
// make sure it is a signed integer
if (txPower > 127) {
txPower -= 256;
}
// TODO: error handling needed on the parse
int beaconTypeCode = 0;
String beaconTypeString = byteArrayToFormattedString(scanData, mMatchingBeaconTypeCodeStartOffset+startByte, mMatchingBeaconTypeCodeEndOffset+startByte, false);
beaconTypeCode = Integer.parseInt(beaconTypeString);
// TODO: error handling needed on the parse
int manufacturer = 0;
String manufacturerString = byteArrayToFormattedString(scanData, startByte, startByte+1, true);
manufacturer = Integer.parseInt(manufacturerString);
String macAddress = null;
String name = null;
if (device != null) {
macAddress = device.getAddress();
name = device.getName();
}
beacon.mIdentifiers = identifiers;
beacon.mDataFields = dataFields;
beacon.mTxPower = txPower;
beacon.mRssi = rssi;
beacon.mBeaconTypeCode = beaconTypeCode;
beacon.mBluetoothAddress = macAddress;
beacon.mBluetoothName= name;
beacon.mManufacturer = manufacturer;
return beacon;
}
public BeaconParser setMatchingBeaconTypeCode(Long typeCode) {
mMatchingBeaconTypeCode = typeCode;
return this;
}
protected static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
int v;
for ( int j = 0; j < bytes.length; j++ ) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
public static class BeaconLayoutException extends RuntimeException {
public BeaconLayoutException(String s) {
}
}
protected byte[] longToByteArray(long longValue, int length) {
byte[] array = new byte[length];
for (int i = 0; i < length; i++){
//long mask = (long) Math.pow(256.0,1.0*(length-i))-1;
long mask = 0xffl << (length-i-1)*8;
long shift = (length-i-1)*8;
long value = ((longValue & mask) >> shift);
//BeaconManager.logDebug(TAG, "masked value is "+String.format("%08x",longValue & mask));
//BeaconManager.logDebug(TAG, "masked value shifted is "+String.format("%08x",(longValue & mask) >> shift));
//BeaconManager.logDebug(TAG, "for long "+String.format("%08x",longValue)+" at position: "+i+" of "+length+" mask: "+String.format("%08x",mask)+" shift: "+shift+" the value is "+String.format("%02x",value));
array[i] = (byte) value;
}
return array;
}
private boolean byteArraysMatch(byte[] array1, int offset1, byte[] array2, int offset2) {
int minSize = array1.length > array2.length ? array2.length : array1.length;
for (int i = 0; i < minSize; i++) {
if (array1[i+offset1] != array2[i+offset2]) {
return false;
}
}
return true;
}
private String byteArrayToString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(String.format("%02x", bytes[i]));
sb.append(" ");
}
return sb.toString().trim();
}
private String byteArrayToFormattedString(byte[] byteBuffer, int startIndex, int endIndex, Boolean littleEndian) {
byte[] bytes = new byte[endIndex-startIndex+1];
if (littleEndian) {
for (int i = 0; i <= endIndex-startIndex; i++) {
bytes[i] = byteBuffer[startIndex+bytes.length-1-i];
}
}
else {
for (int i = 0; i <= endIndex-startIndex; i++) {
bytes[i] = byteBuffer[startIndex+i];
}
}
int length = endIndex-startIndex +1;
// We treat a 1-4 byte number as decimal string
if (length < 5) {
Long number = 0l;
BeaconManager.logDebug(TAG, "Byte array is size "+bytes.length);
for (int i = 0; i < bytes.length; i++) {
BeaconManager.logDebug(TAG, "index is "+i);
long byteValue = (long) (bytes[bytes.length - i-1] & 0xff);
long positionValue = (long) Math.pow(256.0,i*1.0);
long calculatedValue = (long) (byteValue * positionValue);
BeaconManager.logDebug(TAG, "calculatedValue for position "+i+" with positionValue "+positionValue+" and byteValue "+byteValue+" is "+calculatedValue);
number += calculatedValue;
}
return number.toString();
}
// We treat a 7+ byte number as a hex string
String hexString = bytesToHex(bytes);
// And if it is a 12 byte number we add dashes to it to make it look like a standard UUID
if (bytes.length == 16) {
StringBuilder sb = new StringBuilder();
sb.append(hexString.substring(0,8));
sb.append("-");
sb.append(hexString.substring(8,12));
sb.append("-");
sb.append(hexString.substring(12,16));
sb.append("-");
sb.append(hexString.substring(16,20));
sb.append("-");
sb.append(hexString.substring(20,32));
return sb.toString();
}
return "0x"+hexString;
}
}
|
package org.muml.psm.allocation.algorithm.qvto;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.muml.psm.allocation.algorithm.main.IStrategy;
import org.muml.psm.allocation.algorithm.main.MultiStrategyConfiguration;
/**
* An abstract class that provides methods to construct a configuration
* property map based on a specific strategy class. Such a transformation
* property map can be passed, for instance, to the
* <code>QVToBasedStrategyTransformationRunner</code>'s
* <code>runTransformation</code> method.
*
*/
public abstract class AbstractQVToBasedMultiConfigurationStrategy implements IStrategy<MultiStrategyConfiguration> {
private static final String manyFeatureError = "A many feature is not supported: %s";
private static final String nullValueError = "A null value is not supported";
@Override
public @Nullable MultiStrategyConfiguration getConfiguration() {
return null;
}
@NonNull
protected Map<String, Object> getConfigurationPropertyMapFor(Class<?> strategy) {
Map<String, Object> map = new HashMap<String, Object>();
EObject configuration = getConfiguration().getConfigurationFor(strategy,
EObject.class);
if (configuration != null) {
// hmm what to do in the null case?
StringBuilder builder = new StringBuilder();
buildDictionaryString(builder, configuration);
// hmm should we cut off a potentially trailing ","? (the
// current qvto code can handle it)
map.put(getConfigurationPropertyNameFor(strategy), builder.toString());
}
return map;
}
@NonNull
protected abstract String getConfigurationPropertyNameFor(Class<?> strategy);
protected void buildDictionaryString(@NonNull StringBuilder builder, @NonNull EObject eObject) {
for (EAttribute attribute : eObject.eClass().getEAllAttributes()) {
buildKeyValueString(builder, eObject, attribute);
}
for (EReference reference : eObject.eClass().getEAllContainments()) {
if (reference.isMany()) {
throw new IllegalStateException(
String.format(manyFeatureError, reference));
}
eObject = (EObject) eObject.eGet(reference);
if (eObject != null) {
// hmm one big "dict"?
buildDictionaryString(builder, (EObject) eObject);
}
}
}
protected void buildKeyValueString(StringBuilder builder, EObject eObject, EAttribute attribute) {
builder.append(attribute.getName());
builder.append("=");
builder.append(convertValue(eObject.eGet(attribute)));
builder.append(",");
}
protected String convertValue(Object value) {
if (value == null) {
throw new IllegalArgumentException(nullValueError);
}
if (value instanceof Boolean) {
return (Boolean) value ? "true" : "false";
}
return value.toString();
}
}
|
package com.goncalossilva.googlemapseverywhere;
import com.goncalossilva.googlemapseverywhere.model.Circle;
import com.goncalossilva.googlemapseverywhere.model.CircleOptions;
import com.goncalossilva.googlemapseverywhere.model.GoogleMapBridge;
import com.goncalossilva.googlemapseverywhere.model.JavaScriptBridge;
import com.goncalossilva.googlemapseverywhere.model.LatLng;
import com.goncalossilva.googlemapseverywhere.model.Marker;
import com.goncalossilva.googlemapseverywhere.model.MarkerOptions;
import android.content.Context;
public final class GoogleMap {
private GoogleMapBridge mGoogleMapBridge;
GoogleMap(Context context, JavaScriptBridge javaScriptBridge, String mapId, GoogleMapOptions options) {
mGoogleMapBridge = new GoogleMapBridge(context, javaScriptBridge, mapId, options);
}
public void setMyLocationEnabled(boolean enabled) {
mGoogleMapBridge.setMyLocationEnabled(enabled);
}
public void setOnMapLoadedCallback(OnMapLoadedCallback callback) {
mGoogleMapBridge.setOnMapLoadedCallback(callback);
}
public void setOnMapClickListener(OnMapClickListener listener) {
mGoogleMapBridge.setOnMapClickListener(listener);
}
public void setOnMapLongClickListener(OnMapLongClickListener listener) {
mGoogleMapBridge.setOnMapLongClickListener(listener);
}
public void moveCamera(CameraUpdate update) {
mGoogleMapBridge.moveCamera(update);
}
public Marker addMarker(MarkerOptions options) {
return mGoogleMapBridge.addMarker(options);
}
public Circle addCircle(CircleOptions options) {
return mGoogleMapBridge.addCircle(options);
}
public interface OnMapLoadedCallback {
public void onMapLoaded();
}
public interface OnMapClickListener {
public void onMapClick(LatLng point);
}
public interface OnMapLongClickListener {
public void onMapLongClick(LatLng point);
}
}
|
package org.pikater.core.agents.system;
import java.util.ArrayList;
import java.util.List;
import jade.content.ContentElement;
import jade.content.lang.Codec.CodecException;
import jade.content.onto.OntologyException;
import jade.content.onto.Ontology;
import jade.content.onto.UngroundedException;
import jade.content.onto.basic.Action;
import jade.content.onto.basic.Result;
import jade.core.AID;
import jade.core.behaviours.TickerBehaviour;
import jade.domain.FIPANames;
import jade.domain.FIPAAgentManagement.NotUnderstoodException;
import jade.domain.FIPAAgentManagement.RefuseException;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.proto.AchieveREResponder;
import jade.proto.ContractNetInitiator;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;
import org.pikater.core.AgentNames;
import org.pikater.core.agents.system.managerAgent.ManagerAgentCommunicator;
import org.pikater.core.agents.PikaterAgent;
import org.pikater.core.ontology.AgentManagementOntology;
import org.pikater.core.ontology.DurationOntology;
import org.pikater.core.ontology.TaskOntology;
import org.pikater.core.ontology.subtrees.batchDescription.EvaluationMethod;
import org.pikater.core.ontology.subtrees.data.Data;
import org.pikater.core.ontology.subtrees.duration.Duration;
import org.pikater.core.ontology.subtrees.duration.GetDuration;
import org.pikater.core.ontology.subtrees.newOption.base.NewOption;
import org.pikater.core.ontology.subtrees.task.Eval;
import org.pikater.core.ontology.subtrees.task.Evaluation;
import org.pikater.core.ontology.subtrees.task.ExecuteTask;
import org.pikater.core.ontology.subtrees.task.Id;
import org.pikater.core.ontology.subtrees.task.Task;
public class Agent_Duration extends PikaterAgent {
private static final long serialVersionUID = -5555820420884978956L;
private final String LOG_LR_DURATIONS_NAME="log_LR_durations";
List<Duration> durations = new ArrayList<Duration>();
int t = 10000;
AID aid = null;
int id = 0;
boolean log_LR_durations = false;
@Override
protected String getAgentType(){
return "Duration";
}
public List<Ontology> getOntologies() {
List<Ontology> ontologies = new ArrayList<Ontology>();
ontologies.add(AgentManagementOntology.getInstance());
ontologies.add(DurationOntology.getInstance());
return ontologies;
}
@Override
protected void setup() {
initDefault();
registerWithDF(AgentNames.DURATION);
if (containsArgument(LOG_LR_DURATIONS_NAME)) {
if (isArgumentValueTrue(LOG_LR_DURATIONS_NAME)){
log_LR_durations = true;
}
}
// create linear regression agent
// send message to AgentManager to create an agent
ManagerAgentCommunicator communicator=new ManagerAgentCommunicator();
aid=communicator.createAgent(this,"LinearRegression","DurationServiceRegression",null);
// compute one LR (as the first one is usually longer)
addBehaviour(new ExecuteTaskInitiator(this, createCFPmessage(aid, this, "dc7ce6dea5a75110486760cfac1051a5")));
doWait(2000);
addBehaviour(new TestBehaviour(this, t));
Ontology ontology = DurationOntology.getInstance();
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchOntology(ontology.getName()), MessageTemplate.MatchPerformative(ACLMessage.REQUEST));
addBehaviour(new AchieveREResponder(this, mt) {
private static final long serialVersionUID = 1L;
@Override
protected ACLMessage handleRequest(ACLMessage request)
throws NotUnderstoodException, RefuseException {
try {
Action a = (Action) getContentManager().extractContent(request);
if (a.getAction() instanceof GetDuration) {
GetDuration gd = (GetDuration) a.getAction();
ACLMessage reply = request.createReply();
reply.setPerformative(ACLMessage.INFORM);
Duration duration = gd.getDuration();
duration.setLR_duration(
countDuration(duration.getStart(), duration.getDurationMiliseconds()));
Result r = new Result(gd, duration);
getContentManager().fillContent(reply, r);
return reply;
}
} catch (OntologyException e) {
Agent_Duration.this.logError(e.getMessage(), e);
} catch (CodecException e) {
Agent_Duration.this.logError(e.getMessage(), e);
}
ACLMessage failure = request.createReply();
failure.setPerformative(ACLMessage.FAILURE);
return failure;
}
});
}
private float countDuration(Date _start, int duration){
if (duration >= Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
float number_of_LRs = 0;
long start = _start.getTime();
// find the duration right before the start
int i_d = durations.size()-1;
while (start < (durations.get(i_d)).getStart().getTime()){
i_d
}
int i = 0;
long t1 = -1;
long t2 = -1;
long d = -1;
while (duration > 0){
try {
t1 = ((Duration)durations.get(i_d + i)).getStart().getTime();
if (i_d + i + 1 > durations.size()-1){
// after last LR
t2 = t1 + t; // expected time
}
else {
t2 = ((Duration)durations.get(i_d + i + 1)).getStart().getTime();
}
long time_between_LRs = t2 - t1;
// if (duration < t){
if (duration < time_between_LRs){
d = duration;
}
else {
// d = t;
d = Math.min(t2 - start, time_between_LRs); // osetreni prvniho useku
}
// System.out.println("d: " + d + " LR dur: " + ((Duration)durations.get(i_d + i)).getDuration());
number_of_LRs += (float)d / (float)(durations.get(i_d + i)).getDurationMiliseconds();
duration = duration - (int)Math.ceil(d);
i++;
}
catch (Exception e){
e.printStackTrace();
}
}
return number_of_LRs;
}
protected class TestBehaviour extends TickerBehaviour {
private static final long serialVersionUID = -2200601967185243650L;
private PikaterAgent agent;
public TestBehaviour(PikaterAgent agent, long period) {
super(agent, period);
this.agent = agent;
}
protected void onTick() {
// compute linear regression on random (but the same) dataset
addBehaviour(new ExecuteTaskInitiator(agent, createCFPmessage(aid, agent, "dc7ce6dea5a75110486760cfac1051a5")));
}
}
protected class ExecuteTaskInitiator extends ContractNetInitiator{
private static final long serialVersionUID = -4895199062239049907L;
private ACLMessage cfp;
private PikaterAgent agent;
public ExecuteTaskInitiator(PikaterAgent agent, ACLMessage cfp) {
super(agent, cfp);
this.agent = agent;
this.cfp = cfp;
}
protected void handlePropose(ACLMessage propose, Vector v) {
// System.out.println(myAgent.getLocalName()+": Agent "+propose.getSender().getName()+" proposed "+propose.getContent());
}
protected void handleRefuse(ACLMessage refuse) {
log("Agent "+refuse.getSender().getName()+" refused.", 1);
}
protected void handleFailure(ACLMessage failure) {
if (failure.getSender().equals(myAgent.getAMS())) {
// FAILURE notification from the JADE runtime: the receiver
// does not exist
log("Responder " + failure.getSender().getName() + " does not exist", 1);
}
else {
log("Agent "+failure.getSender().getName()+" failed", 1);
}
}
protected void handleAllResponses(Vector responses, Vector acceptances) {
// Evaluate proposals.
int bestProposal = Integer.MAX_VALUE;
AID bestProposer = null;
ACLMessage accept = null;
Enumeration e = responses.elements();
while (e.hasMoreElements()) {
ACLMessage msg = (ACLMessage) e.nextElement();
if (msg.getPerformative() == ACLMessage.PROPOSE) {
ACLMessage reply = msg.createReply();
reply.setPerformative(ACLMessage.REJECT_PROPOSAL);
acceptances.addElement(reply);
int proposal = Integer.parseInt(msg.getContent());
if (proposal < bestProposal) {
bestProposal = proposal;
bestProposer = msg.getSender();
accept = reply;
}
}
}
// Accept the proposal of the best proposer
if (accept != null) {
try {
ContentElement content = getContentManager().extractContent(cfp);
ExecuteTask execute = (ExecuteTask) (((Action) content).getAction());
Action a = new Action();
a.setAction(execute);
a.setActor(myAgent.getAID());
getContentManager().fillContent(accept, a);
} catch (CodecException exception) {
agent.logError(exception.getMessage(), exception);
} catch (OntologyException exception) {
agent.logError(exception.getMessage(), exception);
}
accept.setPerformative(ACLMessage.ACCEPT_PROPOSAL);
}
// TODO - if there is no proposer...
}
protected void handleInform(ACLMessage inform) {
log("Agent "+inform.getSender().getName() + " successfully performed the requested action", 2);
ContentElement content;
try {
content = getContentManager().extractContent(inform);
if (content instanceof Result) {
Result result = (Result) content;
jade.util.leap.List tasks = (jade.util.leap.List)result.getValue();
Task t = (Task) tasks.get(0);
if (durations.size() > 1000000) { // over 270 hours
durations.remove(0);
}
// save the duration of the computation to the list
Evaluation evaluation = (Evaluation)t.getResult();
List<Eval> ev = evaluation.getEvaluations();
Duration d = new Duration();
for (Eval eval : ev) {
if(eval.getName().equals("duration")){
d.setDurationMiliseconds((int)eval.getValue());
}
}
d.setStart(evaluation.getStart());
durations.add(d);
if (log_LR_durations){
// write duration into a file:
log(d.getStart() + " - " + d.getDurationMiliseconds());
}
}
} catch (UngroundedException e) {
agent.logError(e.getMessage(), e);
} catch (CodecException e) {
agent.logError(e.getMessage(), e);
} catch (OntologyException e) {
agent.logError(e.getMessage(), e);
}
}
} // end of call for proposal bahavior
protected ACLMessage createCFPmessage(AID aid, PikaterAgent agent, String filename) {
Ontology ontology = TaskOntology.getInstance();
// create CFP message for Linear Regression Computing Agent
ACLMessage cfp = new ACLMessage(ACLMessage.CFP);
cfp.setLanguage(codec.getName());
cfp.setOntology(ontology.getName());
cfp.addReceiver(aid);
cfp.setProtocol(FIPANames.InteractionProtocol.FIPA_CONTRACT_NET);
// We want to receive a reply in 10 secs
cfp.setReplyByDate(new java.util.Date(System.currentTimeMillis() + 10000));
org.pikater.core.ontology.subtrees.management.Agent ag =
new org.pikater.core.ontology.subtrees.management.Agent();
ag.setType("LinearRegression");
ag.setOptions(new ArrayList<NewOption>());
Data d = new Data();
d.setTestFileName("xxx");
d.setTrainFileName(filename);
d.setExternal_test_file_name("xxx");
d.setExternal_train_file_name("xxx");
d.setMode("train_only");
Task t = new Task();
Id _id = new Id();
_id.setIdentificator(Integer.toString(id));
id++;
t.setAgent(ag);
t.setData(d);
EvaluationMethod em = new EvaluationMethod();
em.setType("Standard"); // TODO don't evaluate at all
t.setEvaluationMethod(em);
t.setGetResults("after_each_computation");
t.setSaveResults(false);
ExecuteTask ex = new ExecuteTask();
ex.setTask(t);
try {
Action a = new Action();
a.setAction(ex);
a.setActor(this.getAID());
getContentManager().fillContent(cfp, a);
} catch (CodecException e) {
agent.logError(e.getMessage(), e);
} catch (OntologyException e) {
agent.logError(e.getMessage(), e);
}
return cfp;
} // end createCFPmessage()
}
|
package org.analogweb.core;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.analogweb.Application;
import org.analogweb.ApplicationContext;
import org.analogweb.ApplicationProcessor;
import org.analogweb.ApplicationProperties;
import org.analogweb.ContainerAdaptor;
import org.analogweb.ExceptionHandler;
import org.analogweb.ExceptionMapper;
import org.analogweb.Invocation;
import org.analogweb.InvocationArguments;
import org.analogweb.InvocationFactory;
import org.analogweb.InvocationInterceptor;
import org.analogweb.InvocationMetadata;
import org.analogweb.InvocationMetadataFactory;
import org.analogweb.InvocationMetadataFinder;
import org.analogweb.Invoker;
import org.analogweb.Module;
import org.analogweb.Modules;
import org.analogweb.ModulesBuilder;
import org.analogweb.ModulesConfig;
import org.analogweb.MutableRequestContext;
import org.analogweb.Renderable;
import org.analogweb.RenderableHolder;
import org.analogweb.RequestContext;
import org.analogweb.RequestPath;
import org.analogweb.RequestValueResolver;
import org.analogweb.RequestValueResolvers;
import org.analogweb.Response;
import org.analogweb.ResponseContext;
import org.analogweb.ResponseFormatter;
import org.analogweb.ResponseHandler;
import org.analogweb.RenderableResolver;
import org.analogweb.RouteRegistry;
import org.analogweb.TypeMapperContext;
import org.analogweb.WebApplicationException;
import org.analogweb.util.ApplicationPropertiesHolder;
import org.analogweb.util.ClassCollector;
import org.analogweb.util.CollectionUtils;
import org.analogweb.util.ReflectionUtils;
import org.analogweb.util.ResourceUtils;
import org.analogweb.util.StopWatch;
import org.analogweb.util.StringUtils;
import org.analogweb.util.SystemProperties;
import org.analogweb.util.Version;
import org.analogweb.util.logging.Log;
import org.analogweb.util.logging.Logs;
import org.analogweb.util.logging.Markers;
/**
* @author snowgoose
*/
public class WebApplication implements Application {
private static final Log log = Logs.getLog(WebApplication.class);
private Modules modules;
private RouteRegistry routes;
private ClassLoader classLoader;
private ApplicationContext resolver;
@Override
public void run(ApplicationContext resolver, ApplicationProperties props,
Collection<ClassCollector> collectors, ClassLoader classLoader) {
StopWatch sw = new StopWatch();
sw.start();
this.resolver = resolver;
this.classLoader = classLoader;
ApplicationPropertiesHolder.configure(this, props);
log.log(Markers.BOOT_APPLICATION, "IB000001");
List<Version> versions = Version.load(classLoader);
if (versions.isEmpty() == false && log.isInfoEnabled(Markers.BOOT_APPLICATION)) {
log.log(Markers.BOOT_APPLICATION, "IB000008");
for (Version v : versions) {
log.info(" " + v.getVersion() + " : " + v.getArtifactId());
}
}
Collection<String> invocationPackageNames = props.getComponentPackageNames();
log.log(Markers.BOOT_APPLICATION, "DB000001", invocationPackageNames);
Set<String> modulesPackageNames = new HashSet<String>();
if (CollectionUtils.isNotEmpty(invocationPackageNames)) {
modulesPackageNames.addAll(invocationPackageNames);
}
modulesPackageNames.add(DEFAULT_PACKAGE_NAME);
log.log(Markers.BOOT_APPLICATION, "DB000002", modulesPackageNames);
initApplication(collectors, modulesPackageNames, invocationPackageNames);
log.log(Markers.BOOT_APPLICATION, "IB000002", sw.stop());
}
@Override
public Response processRequest(RequestPath requestedPath, RequestContext requestContext,
ResponseContext responseContext) throws IOException, WebApplicationException {
InvocationMetadata metadata = null;
Modules mod = null;
List<ApplicationProcessor> processors = null;
RequestContext context = requestContext;
Response response = null;
try {
mod = getModules();
processors = mod.getApplicationProcessors();
MutableRequestContext mutableContext = new DefaultMutableRequestContext(context);
preMatching(processors, mutableContext, requestedPath);
context = mutableContext.unwrap();
RouteRegistry mapping = getRouteRegistry();
log.log(Markers.LIFECYCLE, "DL000004", requestedPath);
metadata = mapping.findInvocationMetadata(context, mod.getInvocationMetadataFinders());
if (metadata == null) {
log.log(Markers.LIFECYCLE, "DL000005", requestedPath);
return NOT_FOUND;
}
log.log(Markers.LIFECYCLE, "DL000006", requestedPath, metadata);
ContainerAdaptor invocationInstances = mod.getInvocationInstanceProvider();
RequestValueResolvers resolvers = mod.getRequestValueResolvers();
TypeMapperContext typeMapperContext = mod.getTypeMapperContext();
Invocation invocation = mod.getInvocationFactory().createInvocation(
invocationInstances, metadata, context, responseContext, typeMapperContext,
resolvers);
InvocationArguments arguments = invocation.getInvocationArguments();
prepareInvoke(processors, arguments, metadata, context, resolvers, typeMapperContext);
try {
Object invocationResult = mod.getInvoker().invoke(invocation, metadata, context,
responseContext);
log.log(Markers.LIFECYCLE, "DL000007", invocation.getInvocationInstance(),
invocationResult);
postInvoke(processors, invocationResult, arguments, metadata, context, resolvers);
response = handleResponse(mod, invocationResult, metadata, context, responseContext);
} catch (Exception e) {
log.log(Markers.LIFECYCLE, "DL000012", invocation.getInvocationInstance(), e);
onException(processors, e, arguments, metadata, context);
List<Object> args = arguments.asList();
throw new InvocationFailureException(e, metadata, args.toArray(new Object[args
.size()]));
}
afterCompletion(processors, context, responseContext, null);
} catch (InvokeInterruptedException e) {
response = handleResponse(mod, e.getInterruption(), metadata, context, responseContext);
afterCompletion(processors, context, responseContext, e);
} catch (Exception e) {
ExceptionHandler handler = mod.getExceptionHandler();
log.log(Markers.LIFECYCLE, "DL000009", (Object) e, handler);
Object exceptionResult = handler.handleException(e);
if (exceptionResult != null) {
response = handleResponse(mod, exceptionResult, metadata, context, responseContext);
afterCompletion(processors, context, responseContext, e);
} else {
afterCompletion(processors, context, responseContext, e);
throw new WebApplicationException(e);
}
}
return response;
}
protected void preMatching(List<ApplicationProcessor> processors,
MutableRequestContext request, RequestPath requestedPath) {
log.log(Markers.LIFECYCLE, "DL000017");
Object interruption = ApplicationProcessor.NO_INTERRUPTION;
for (ApplicationProcessor processor : processors) {
interruption = processor.preMatching(request, requestedPath);
if (interruption != ApplicationProcessor.NO_INTERRUPTION) {
throw new InvokeInterruptedException(interruption);
}
}
}
protected void prepareInvoke(List<ApplicationProcessor> processors, InvocationArguments args,
InvocationMetadata metadata, RequestContext request,
RequestValueResolvers attributesHandlers, TypeMapperContext typeMapperContext) {
log.log(Markers.LIFECYCLE, "DL000013");
Object interruption = ApplicationProcessor.NO_INTERRUPTION;
for (ApplicationProcessor processor : processors) {
interruption = processor.prepareInvoke(args, metadata, request, typeMapperContext,
attributesHandlers);
if (interruption != ApplicationProcessor.NO_INTERRUPTION) {
throw new InvokeInterruptedException(interruption);
}
}
}
protected void postInvoke(List<ApplicationProcessor> processors, Object invocationResult,
InvocationArguments args, InvocationMetadata metadata, RequestContext request,
RequestValueResolvers attributesHandlers) {
log.log(Markers.LIFECYCLE, "DL000014");
for (ApplicationProcessor processor : processors) {
processor.postInvoke(invocationResult, args, metadata, request, attributesHandlers);
}
}
protected void onException(List<ApplicationProcessor> processors, Exception thrown,
InvocationArguments args, InvocationMetadata metadata, RequestContext request) {
log.log(Markers.LIFECYCLE, "DL000015");
Object interruption = ApplicationProcessor.NO_INTERRUPTION;
for (ApplicationProcessor processor : processors) {
interruption = processor.processException(thrown, request, args, metadata);
if (interruption != ApplicationProcessor.NO_INTERRUPTION) {
throw new InvokeInterruptedException(interruption);
}
}
}
protected void afterCompletion(List<ApplicationProcessor> processors, RequestContext context,
ResponseContext responseContext, Exception e) {
log.log(Markers.LIFECYCLE, "DL000016");
for (ApplicationProcessor processor : processors) {
processor.afterCompletion(context, responseContext, e);
}
}
protected Response handleResponse(Modules modules, Object result, InvocationMetadata metadata,
RequestContext context, ResponseContext responseContext) throws IOException,
WebApplicationException {
RenderableResolver resultResolver = modules.getResponseResolver();
Renderable resolved = resultResolver.resolve(result, metadata, context, responseContext);
log.log(Markers.LIFECYCLE, "DL000008", result, result);
ResponseFormatter resultFormatter = null;
if (resolved instanceof RenderableHolder) {
Renderable renderable = ((RenderableHolder) resolved).getRenderable();
if (renderable != null) {
resultFormatter = modules.findResponseFormatter(renderable.getClass());
}
} else {
resultFormatter = modules.findResponseFormatter(resolved.getClass());
}
if (resultFormatter != null) {
log.log(Markers.LIFECYCLE, "DL000010", result, resultFormatter);
} else {
log.log(Markers.LIFECYCLE, "DL000011", result);
}
ResponseHandler resultHandler = modules.getResponseHandler();
return resultHandler.handleResult(resolved, resultFormatter, context, responseContext);
}
protected void initApplication(Collection<ClassCollector> collectors,
Set<String> modulePackageNames, Collection<String> invocationPackageNames) {
Collection<Class<?>> moduleClasses = collectClasses(modulePackageNames, collectors);
ModulesBuilder modulesBuilder = processConfigPreparation(ReflectionUtils
.filterClassAsImplementsInterface(ModulesConfig.class, moduleClasses));
ApplicationContext resolver = getApplicationContextResolver();
ContainerAdaptor defaultContainer = setUpDefaultContainer(resolver, moduleClasses);
Modules modules = modulesBuilder.buildModules(resolver, defaultContainer);
monitorModules(modules);
setModules(modules);
log.log(Markers.BOOT_APPLICATION, "DB000003", modules);
Collection<Class<?>> collectedInvocationClasses;
if (CollectionUtils.isEmpty(invocationPackageNames)) {
collectedInvocationClasses = collectAllClasses(collectors);
} else {
collectedInvocationClasses = collectClasses(invocationPackageNames, collectors);
}
setRouteRegistry(createRouteRegistry(collectedInvocationClasses,
modules.getInvocationMetadataFactories()));
}
private void monitorModules(Modules modules) {
if (log.isDebugEnabled(Markers.MONITOR_MODULES)) {
log.log(Markers.MONITOR_MODULES, "IB000009");
log.debug(Markers.MONITOR_MODULES, "++++++++++++++++++++++++++++");
log.debug(Markers.MONITOR_MODULES, "ApplicationProcessor");
log.debug(Markers.MONITOR_MODULES, "===");
for (ApplicationProcessor m : modules.getApplicationProcessors()) {
log.debug(Markers.MONITOR_MODULES, " - " + m.getClass().getCanonicalName());
}
log.debug(Markers.MONITOR_MODULES, "");
ExceptionHandler eh = modules.getExceptionHandler();
log.debug(Markers.MONITOR_MODULES, "ExceptionHandler");
log.debug(Markers.MONITOR_MODULES, "===");
log.debug(Markers.MONITOR_MODULES, " - " + eh.getClass().getCanonicalName());
log.debug(Markers.MONITOR_MODULES, "");
log.debug(Markers.MONITOR_MODULES, "ExceptionMapper");
log.debug(Markers.MONITOR_MODULES, "===");
for (ExceptionMapper m : modules.getExceptionMappers()) {
log.debug(Markers.MONITOR_MODULES, " - " + m.getClass().getCanonicalName());
}
log.debug(Markers.MONITOR_MODULES, "");
InvocationFactory f = modules.getInvocationFactory();
log.debug(Markers.MONITOR_MODULES, "InvocationFactory");
log.debug(Markers.MONITOR_MODULES, "===");
log.debug(Markers.MONITOR_MODULES, " - " + f.getClass().getCanonicalName());
log.debug(Markers.MONITOR_MODULES, "");
ContainerAdaptor ii = modules.getInvocationInstanceProvider();
log.debug(Markers.MONITOR_MODULES, "InvocationInstanceProvider");
log.debug(Markers.MONITOR_MODULES, "===");
log.debug(Markers.MONITOR_MODULES, " - " + ii.getClass().getCanonicalName());
log.debug(Markers.MONITOR_MODULES, "");
log.debug(Markers.MONITOR_MODULES, "InvocationInterceptor");
log.debug(Markers.MONITOR_MODULES, "===");
for (InvocationInterceptor m : modules.getInvocationInterceptors()) {
log.debug(Markers.MONITOR_MODULES, " - " + m.getClass().getCanonicalName());
}
log.debug(Markers.MONITOR_MODULES, "");
log.debug(Markers.MONITOR_MODULES, "InvocationMetadataFactory");
log.debug(Markers.MONITOR_MODULES, "===");
for (InvocationMetadataFactory m : modules.getInvocationMetadataFactories()) {
log.debug(Markers.MONITOR_MODULES, " - " + m.getClass().getCanonicalName());
}
log.debug(Markers.MONITOR_MODULES, "");
log.debug(Markers.MONITOR_MODULES, "InvocationMetadataFinder");
log.debug(Markers.MONITOR_MODULES, "===");
for (InvocationMetadataFinder m : modules.getInvocationMetadataFinders()) {
log.debug(Markers.MONITOR_MODULES, " - " + m.getClass().getCanonicalName());
}
Invoker ik = modules.getInvoker();
log.debug(Markers.MONITOR_MODULES, "");
log.debug(Markers.MONITOR_MODULES, "Invoker");
log.debug(Markers.MONITOR_MODULES, "===");
log.debug(Markers.MONITOR_MODULES, " - " + ik.getClass().getCanonicalName());
ContainerAdaptor mca = modules.getModulesContainerAdaptor();
log.debug(Markers.MONITOR_MODULES, "");
log.debug(Markers.MONITOR_MODULES, "ModulesContainerAdaptor");
log.debug(Markers.MONITOR_MODULES, "===");
log.debug(Markers.MONITOR_MODULES, " - " + mca.getClass().getCanonicalName());
log.debug(Markers.MONITOR_MODULES, "");
log.debug(Markers.MONITOR_MODULES, "RequestValueResolver");
log.debug(Markers.MONITOR_MODULES, "===");
for (RequestValueResolver m : modules.getRequestValueResolvers().all()) {
log.debug(Markers.MONITOR_MODULES, " - " + m.getClass().getCanonicalName());
}
ResponseHandler rh = modules.getResponseHandler();
log.debug(Markers.MONITOR_MODULES, "");
log.debug(Markers.MONITOR_MODULES, "ResponseHandler");
log.debug(Markers.MONITOR_MODULES, "===");
log.debug(Markers.MONITOR_MODULES, " - " + rh.getClass().getCanonicalName());
RenderableResolver rr = modules.getResponseResolver();
log.debug(Markers.MONITOR_MODULES, "");
log.debug(Markers.MONITOR_MODULES, "RenderableResolver");
log.debug(Markers.MONITOR_MODULES, "===");
log.debug(Markers.MONITOR_MODULES, " - " + rr.getClass().getCanonicalName());
log.debug(Markers.MONITOR_MODULES, "++++++++++++++++++++++++++++");
}
}
protected ModulesBuilder processConfigPreparation(List<Class<ModulesConfig>> configs) {
ModulesBuilder modulesBuilder = new DefaultModulesBuilder();
List<ModulesConfig> moduleConfigInstances = new ArrayList<ModulesConfig>();
for (Class<ModulesConfig> configClass : configs) {
ModulesConfig config = ReflectionUtils.getInstanceQuietly(configClass);
if (config != null) {
moduleConfigInstances.add(config);
}
}
Collections.sort(moduleConfigInstances, getModulesConfigComparator());
for (ModulesConfig config : moduleConfigInstances) {
log.log(Markers.BOOT_APPLICATION, "IB000003", config);
modulesBuilder = config.prepare(modulesBuilder);
}
return modulesBuilder;
}
protected Comparator<ModulesConfig> getModulesConfigComparator() {
return new ModulesConfigComparator();
}
protected ContainerAdaptor setUpDefaultContainer(ApplicationContext resolver,
Collection<Class<?>> rootModuleClasses) {
StaticMappingContainerAdaptorFactory factory = new StaticMappingContainerAdaptorFactory();
StaticMappingContainerAdaptor adaptor = factory.createContainerAdaptor(resolver);
for (Class<?> moduleClass : rootModuleClasses) {
if (Module.class.isAssignableFrom(moduleClass)) {
adaptor.register(moduleClass);
}
}
return adaptor;
}
protected RouteRegistry createRouteRegistry(Collection<Class<?>> collectedClasses,
List<InvocationMetadataFactory> factories) {
RouteRegistry mapping = new DefaultRouteRegistry();
for (Class<?> clazz : collectedClasses) {
for (InvocationMetadataFactory factory : factories) {
if (factory.containsInvocationClass(clazz)) {
for (InvocationMetadata actionMethodMetadata : factory
.createInvocationMetadatas(clazz)) {
log.log(Markers.BOOT_APPLICATION, "IB000004",
actionMethodMetadata.getDefinedPath(),
actionMethodMetadata.getInvocationClass(),
actionMethodMetadata.getMethodName());
mapping.register(actionMethodMetadata);
}
}
}
}
return mapping;
}
protected Collection<Class<?>> collectAllClasses(Collection<ClassCollector> collectors) {
Collection<Class<?>> collectedClasses = new HashSet<Class<?>>();
for (String resourceName : SystemProperties.classPathes()) {
URL resourceURL = ResourceUtils.findResource(resourceName);
for (ClassCollector collector : collectors) {
collectedClasses.addAll(collector.collect(StringUtils.EMPTY, resourceURL,
classLoader));
}
}
return collectedClasses;
}
protected Collection<Class<?>> collectClasses(Collection<String> rootPackageNames,
Collection<ClassCollector> collectors) {
Collection<Class<?>> collectedClasses = new HashSet<Class<?>>();
for (String packageName : rootPackageNames) {
for (URL resourceURL : ResourceUtils.findPackageResources(packageName, classLoader)) {
for (ClassCollector collector : collectors) {
collectedClasses.addAll(collector
.collect(packageName, resourceURL, classLoader));
}
}
}
return collectedClasses;
}
@Override
public RouteRegistry getRouteRegistry() {
return routes;
}
protected void setRouteRegistry(RouteRegistry registry) {
this.routes = registry;
}
@Override
public Modules getModules() {
return this.modules;
}
protected void setModules(Modules modules) {
this.modules = modules;
}
protected final ApplicationContext getApplicationContextResolver() {
return this.resolver;
}
@Override
public void dispose() {
this.classLoader = null;
this.resolver = null;
if (this.modules != null) {
this.modules.dispose();
this.modules = null;
}
if (this.routes != null) {
this.routes.dispose();
this.routes = null;
}
ApplicationPropertiesHolder.dispose(this);
}
}
|
package org.eclipse.che.ide.extension.machine.client;
import com.google.gwt.core.client.Scheduler;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.web.bindery.event.shared.EventBus;
import org.eclipse.che.ide.api.machine.events.WsAgentStateEvent;
import org.eclipse.che.ide.api.machine.events.WsAgentStateHandler;
import org.eclipse.che.ide.actions.StopWorkspaceAction;
import org.eclipse.che.ide.api.action.ActionManager;
import org.eclipse.che.ide.api.action.DefaultActionGroup;
import org.eclipse.che.ide.api.action.IdeActions;
import org.eclipse.che.ide.api.app.AppContext;
import org.eclipse.che.ide.api.constraints.Constraints;
import org.eclipse.che.ide.api.extension.Extension;
import org.eclipse.che.ide.api.icon.Icon;
import org.eclipse.che.ide.api.icon.IconRegistry;
import org.eclipse.che.ide.api.keybinding.KeyBindingAgent;
import org.eclipse.che.ide.api.keybinding.KeyBuilder;
import org.eclipse.che.ide.api.parts.PartStackType;
import org.eclipse.che.ide.api.parts.PerspectiveManager;
import org.eclipse.che.ide.api.parts.WorkspaceAgent;
import org.eclipse.che.ide.extension.machine.client.actions.CreateMachineAction;
import org.eclipse.che.ide.extension.machine.client.actions.CreateSnapshotAction;
import org.eclipse.che.ide.extension.machine.client.actions.DestroyMachineAction;
import org.eclipse.che.ide.extension.machine.client.actions.EditCommandsAction;
import org.eclipse.che.ide.extension.machine.client.actions.ExecuteSelectedCommandAction;
import org.eclipse.che.ide.extension.machine.client.actions.RestartMachineAction;
import org.eclipse.che.ide.extension.machine.client.actions.RunCommandAction;
import org.eclipse.che.ide.extension.machine.client.actions.SelectCommandComboBox;
import org.eclipse.che.ide.extension.machine.client.actions.SwitchPerspectiveAction;
import org.eclipse.che.ide.extension.machine.client.command.custom.CustomCommandType;
import org.eclipse.che.ide.extension.machine.client.command.valueproviders.ServerPortProvider;
import org.eclipse.che.ide.extension.machine.client.perspective.OperationsPerspective;
import org.eclipse.che.ide.extension.machine.client.processes.ConsolesPanelPresenter;
import org.eclipse.che.ide.extension.machine.client.actions.NewTerminalAction;
import org.eclipse.che.ide.extension.machine.client.processes.actions.CloseConsoleAction;
import org.eclipse.che.ide.extension.machine.client.processes.actions.ReRunProcessAction;
import org.eclipse.che.ide.extension.machine.client.processes.actions.StopProcessAction;
import org.eclipse.che.ide.extension.machine.client.targets.EditTargetsAction;
import org.eclipse.che.ide.util.input.KeyCodeMap;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_CENTER_TOOLBAR;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_MAIN_MENU;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_RIGHT_TOOLBAR;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_RUN;
import static org.eclipse.che.ide.api.action.IdeActions.GROUP_WORKSPACE;
import static org.eclipse.che.ide.api.constraints.Anchor.AFTER;
import static org.eclipse.che.ide.api.constraints.Constraints.FIRST;
import static org.eclipse.che.ide.workspace.perspectives.project.ProjectPerspective.PROJECT_PERSPECTIVE_ID;
/**
* Machine extension entry point.
*
* @author Artem Zatsarynnyi
* @author Dmitry Shnurenko
*/
@Singleton
@Extension(title = "Machine", version = "1.0.0")
public class MachineExtension {
public static final String GROUP_MACHINE_CONSOLE_TOOLBAR = "MachineConsoleToolbar";
public static final String GROUP_MACHINE_TOOLBAR = "MachineGroupToolbar";
public static final String GROUP_COMMANDS_DROPDOWN = "CommandsSelector";
public static final String GROUP_COMMANDS_LIST = "CommandsListGroup";
public static final String GROUP_MACHINES_DROPDOWN = "MachinesSelector";
public static final String GROUP_MACHINES_LIST = "MachinesListGroup";
@Inject
public MachineExtension(MachineResources machineResources,
final EventBus eventBus,
final WorkspaceAgent workspaceAgent,
final AppContext appContext,
final ConsolesPanelPresenter consolesPanelPresenter,
final Provider<ServerPortProvider> machinePortProvider,
final PerspectiveManager perspectiveManager,
IconRegistry iconRegistry,
CustomCommandType arbitraryCommandType) {
machineResources.getCss().ensureInjected();
eventBus.addHandler(WsAgentStateEvent.TYPE, new WsAgentStateHandler() {
@Override
public void onWsAgentStarted(WsAgentStateEvent event) {
machinePortProvider.get();
/* Do not show terminal on factories by default */
if (appContext.getFactory() == null) {
consolesPanelPresenter.newTerminal();
workspaceAgent.setActivePart(consolesPanelPresenter);
}
}
@Override
public void onWsAgentStopped(WsAgentStateEvent event) {
}
});
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
/* There is a bug in perspective management and it's unable to add Consoles part in
* OperationsPerspective and ProjectPerspective directly. Following code resolves the issue.
*/
/* Add Consoles to Operation perspective */
perspectiveManager.setPerspectiveId(OperationsPerspective.OPERATIONS_PERSPECTIVE_ID);
workspaceAgent.openPart(consolesPanelPresenter, PartStackType.INFORMATION);
/* Add Consoles to Project perspective */
perspectiveManager.setPerspectiveId(PROJECT_PERSPECTIVE_ID);
workspaceAgent.openPart(consolesPanelPresenter, PartStackType.INFORMATION);
if (appContext.getFactory() == null) {
workspaceAgent.setActivePart(consolesPanelPresenter);
}
}
});
iconRegistry.registerIcon(new Icon(arbitraryCommandType.getId() + ".commands.category.icon", machineResources.customCommandType()));
}
@Inject
private void prepareActions(MachineLocalizationConstant localizationConstant,
ActionManager actionManager,
KeyBindingAgent keyBinding,
ExecuteSelectedCommandAction executeSelectedCommandAction,
SelectCommandComboBox selectCommandAction,
EditCommandsAction editCommandsAction,
CreateMachineAction createMachine,
RestartMachineAction restartMachine,
DestroyMachineAction destroyMachineAction,
StopWorkspaceAction stopWorkspaceAction,
SwitchPerspectiveAction switchPerspectiveAction,
CreateSnapshotAction createSnapshotAction,
RunCommandAction runCommandAction,
NewTerminalAction newTerminalAction,
EditTargetsAction editTargetsAction,
IconRegistry iconRegistry,
MachineResources machineResources,
ReRunProcessAction reRunProcessAction,
StopProcessAction stopProcessAction,
CloseConsoleAction closeConsoleAction) {
final DefaultActionGroup mainMenu = (DefaultActionGroup)actionManager.getAction(GROUP_MAIN_MENU);
final DefaultActionGroup workspaceMenu = (DefaultActionGroup)actionManager.getAction(GROUP_WORKSPACE);
final DefaultActionGroup runMenu = (DefaultActionGroup)actionManager.getAction(GROUP_RUN);
// register actions
actionManager.registerAction("editCommands", editCommandsAction);
actionManager.registerAction("selectCommandAction", selectCommandAction);
actionManager.registerAction("executeSelectedCommand", executeSelectedCommandAction);
actionManager.registerAction("editTargets", editTargetsAction);
//add actions in machine menu
final DefaultActionGroup machineMenu = new DefaultActionGroup(localizationConstant.mainMenuMachine(), true, actionManager);
actionManager.registerAction("machine", machineMenu);
actionManager.registerAction("createMachine", createMachine);
actionManager.registerAction("destroyMachine", destroyMachineAction);
actionManager.registerAction("restartMachine", restartMachine);
actionManager.registerAction("stopWorkspace", stopWorkspaceAction);
actionManager.registerAction("createSnapshot", createSnapshotAction);
actionManager.registerAction("runCommand", runCommandAction);
actionManager.registerAction("newTerminal", newTerminalAction);
// add actions in main menu
runMenu.add(newTerminalAction, FIRST);
runMenu.addSeparator();
runMenu.add(editCommandsAction);
runMenu.add(editTargetsAction);
workspaceMenu.add(stopWorkspaceAction);
mainMenu.add(machineMenu, new Constraints(AFTER, IdeActions.GROUP_PROJECT));
machineMenu.add(createMachine);
machineMenu.add(restartMachine);
machineMenu.add(destroyMachineAction);
machineMenu.add(createSnapshotAction);
// add actions on center part of toolbar
final DefaultActionGroup centerToolbarGroup = (DefaultActionGroup)actionManager.getAction(GROUP_CENTER_TOOLBAR);
final DefaultActionGroup machineToolbarGroup = new DefaultActionGroup(GROUP_MACHINE_TOOLBAR, false, actionManager);
actionManager.registerAction(GROUP_MACHINE_TOOLBAR, machineToolbarGroup);
centerToolbarGroup.add(machineToolbarGroup, FIRST);
machineToolbarGroup.add(selectCommandAction);
final DefaultActionGroup executeToolbarGroup = new DefaultActionGroup(actionManager);
executeToolbarGroup.add(executeSelectedCommandAction);
machineToolbarGroup.add(executeToolbarGroup);
// add actions on right part of toolbar
final DefaultActionGroup rightToolbarGroup = (DefaultActionGroup)actionManager.getAction(GROUP_RIGHT_TOOLBAR);
rightToolbarGroup.add(switchPerspectiveAction);
// add group for list of machines
final DefaultActionGroup machinesList = new DefaultActionGroup(GROUP_MACHINES_DROPDOWN, true, actionManager);
actionManager.registerAction(GROUP_MACHINES_LIST, machinesList);
machinesList.add(editTargetsAction, FIRST);
// add group for list of commands
final DefaultActionGroup commandList = new DefaultActionGroup(GROUP_COMMANDS_DROPDOWN, true, actionManager);
actionManager.registerAction(GROUP_COMMANDS_LIST, commandList);
commandList.add(editCommandsAction, FIRST);
// Consoles tree context menu group
DefaultActionGroup consolesTreeContextMenu =
(DefaultActionGroup)actionManager.getAction(IdeActions.GROUP_CONSOLES_TREE_CONTEXT_MENU);
consolesTreeContextMenu.add(reRunProcessAction);
consolesTreeContextMenu.add(stopProcessAction);
consolesTreeContextMenu.add(closeConsoleAction);
// Define hot-keys
keyBinding.getGlobal().addKey(new KeyBuilder().alt().charCode(KeyCodeMap.F12).build(), "newTerminal");
iconRegistry.registerIcon(new Icon("che.machine.icon", machineResources.devMachine()));
}
}
|
package edu.chalmers.dat076.moviefinder.service;
import edu.chalmers.dat076.moviefinder.listener.FileSystemListener;
import edu.chalmers.dat076.moviefinder.model.TemporaryMedia;
import edu.chalmers.dat076.moviefinder.persistence.Movie;
import edu.chalmers.dat076.moviefinder.persistence.MovieRepository;
import edu.chalmers.dat076.moviefinder.utils.TitleParser;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.dao.DataIntegrityViolationException;
/**
*
* @author John
*/
public class FileThreadService implements FileSystemListener{
private final static Logger LOGGER = Logger.getLogger(FileThreadService.class.getName());
@Autowired
private TitleParser titleParser;
@Autowired
private MovieRepository movieRepository;
private List<File> checkFolders;
private LinkedList<WatchThread> threads;
@PostConstruct
public void init() throws IOException {
checkFolders = new LinkedList<>();
checkFolders.add(new File("C:/film"));
threads = new LinkedList<>();
for(File f : checkFolders){
threads.add(new WatchThread(f));
threads.getLast().setListener(this);
threads.getLast().start();
}
}
public void destory(){
for(WatchThread t : threads){
t.interrupt();
try {
t.join();
} catch (InterruptedException ex) {
}
}
}
@Override
public void initFile(String path) {
LOGGER.info("initFile: " + path);
TemporaryMedia temporaryMedia = titleParser.parseMedia(path);
Movie movie = new Movie(temporaryMedia.getName(), path);
try {
movieRepository.save(movie);
} catch (DataIntegrityViolationException e) {
// A Movie at this path already exist.
}
}
@Override
public void newFile(String path) {
LOGGER.info("newFile: " + path);
TemporaryMedia temporaryMedia = titleParser.parseMedia(path);
Movie movie = new Movie(temporaryMedia.getName(), path);
try {
movieRepository.save(movie);
} catch (DataIntegrityViolationException e) {
// A Movie at this path already exist.
}
}
@Override
public void oldPath(String path) {
LOGGER.info("oldPath: " + path);
Movie movie = movieRepository.findByFilePath(path);
if(movie != null) {
movieRepository.delete(movie);
}
}
}
|
package org.royaldev.royalcommands.rcommands;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.royaldev.royalcommands.RUtils;
import org.royaldev.royalcommands.RoyalCommands;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
public class CmdRules implements CommandExecutor {
RoyalCommands plugin;
public CmdRules(RoyalCommands instance) {
this.plugin = instance;
}
@Override
public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("rules")) {
if (!plugin.isAuthorized(cs, "rcmds.rules")) {
RUtils.dispNoPerms(cs);
return true;
}
File rulesf = new File(plugin.getDataFolder() + File.separator + "rules.txt");
if (!rulesf.exists()) {
cs.sendMessage(ChatColor.RED + "The rules.txt file was not found! Tell an admin.");
return true;
}
int tpage;
if (args.length < 1) {
tpage = 1;
} else {
try {
tpage = Integer.valueOf(args[0].trim());
} catch (Exception e) {
cs.sendMessage(ChatColor.RED + "The page number was invalid!");
return true;
}
}
int pages = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(rulesf));
String line;
java.util.List<String> rules = new ArrayList<String>();
while ((line = br.readLine()) != null) {
line = line.trim().replaceAll("(&([a-f0-9]))", "\u00A7$2");
rules.add(line);
if (line.trim().equals("###")) pages++;
}
if (tpage > pages || tpage < 1) {
cs.sendMessage(ChatColor.RED + "No such page!");
return true;
}
if (tpage == pages) {
cs.sendMessage(ChatColor.GOLD + "Page " + ChatColor.GRAY + tpage + ChatColor.GOLD + " of " + ChatColor.GRAY + pages + ChatColor.GOLD + ".");
} else {
cs.sendMessage(ChatColor.GOLD + "Page " + ChatColor.GRAY + tpage + ChatColor.GOLD + " of " + ChatColor.GRAY + pages + ChatColor.GOLD + ". " + ChatColor.GRAY + "/" + cmd.getName() + " " + (tpage + 1) + ChatColor.GOLD + " for next page.");
}
int cpage = 0;
for (String s : rules) {
if (s.trim().equals("
cpage++;
s = "";
}
if (cpage == tpage && !s.equals("")) {
cs.sendMessage(s);
}
}
} catch (Exception e) {
cs.sendMessage(ChatColor.RED + "The rules.txt file was not found! Tell an admin.");
return true;
}
return true;
}
return false;
}
}
|
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class Sudoku {
/**
* The array is modified in place
* @param sudoku
*/
public static int[][] solve(int[][] sudoku) {
int spot[] = {0, 0};
if (!nextEmpty(sudoku, spot)) {
return sudoku;
}
for (int i=0; i<10; i++) {
if (canPut(sudoku, spot, i)) {
sudoku[spot[0]][spot[1]] = i;
int [][]newSudoku = solve(sudoku);
if (!nextEmpty(newSudoku, new int[]{0, 0})) {
return newSudoku;
}
}
}
sudoku[spot[0]][spot[1]] = 0; // solution not found, backtrack
return sudoku;
}
private static boolean nextEmpty(int[][] sudoku, int[] spot) {
for (int i=0; i<sudoku.length; i++) {
for (int j=0; j<sudoku[i].length; j++) {
if (sudoku[i][j] == 0) {
spot[0] = i;
spot[1] = j;
return true;
}
}
}
return false;
}
private static boolean canPut(int[][] sudoku, int[] spot, int val) {
int x = spot[0];
int y = spot[1];
for (int i=0; i<sudoku.length; i++) {
// test row
if (sudoku[i][y] == val) {
return false;
}
// test column
if (sudoku[x][i] == val) {
return false;
}
}
// test square
int a = x-(x%3);
int b = y-(y%3);
for (int i=a; i<a+3; i++) {
for (int j=b; j<b+3; j++) {
if (sudoku[i][j] == val) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
File file = new File(args[0]);
// read entire file into memory
String input = null;
try {
input = new Scanner(file, "UTF-8").useDelimiter("\\A").next();
} catch (FileNotFoundException e) {
System.out.println("Could not find " + file.getName());
System.exit(1);
}
// solve all sudokus
long before = System.currentTimeMillis();
StringBuilder output = new StringBuilder();
String []lines = input.split("\\r?\\n");
ProgressBar bar = new ProgressBar(0, lines.length, 100, 100);
for (String line : lines) {
int [][]sudoku = Board.fromString(line);
output.append(Board.toString(solve(sudoku)));
bar.advance();
}
long duration = System.currentTimeMillis() - before;
// write solution to file output
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter("solved_" + file.getName()));
writer.write(output.toString());
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// time result
System.out.println("-- Elapsed time: " + duration + " ms.");
}
}
class Board {
public static final int BOARD_SIZE = 9;
public static int[][] fromString(String data) {
int[][] board = new int[BOARD_SIZE][BOARD_SIZE];
int i = 0, j = 0, ch = 0;
while (i < BOARD_SIZE && j < BOARD_SIZE) {
while (!Character.isDigit(data.charAt(ch))) {
ch++;
}
board[i][j] = data.charAt(ch++) - 48;
if (j == BOARD_SIZE - 1) {
i += 1 % BOARD_SIZE;
j = 0;
} else {
j += 1 % BOARD_SIZE;
}
}
return board;
}
public static String toString(int[][] board) {
StringBuilder out = new StringBuilder();
for (int i=0; i<board.length; i++) {
for (int j=0; j<board[i].length; j++) {
out.append(board[i][j]).append(" ");
}
out.append("\n");
}
out.append("\n");
return out.toString();
}
}
class ProgressBar {
private int totalSteps;
private int step;
private int resolution;
private int width;
public ProgressBar(int step, int totalSteps, int resolution, int width) {
this.step = step;
this.totalSteps = totalSteps;
this.resolution = resolution;
this.width = width;
}
public void advance() {
step++;
if (totalSteps/resolution == 0) return;
if (step % (totalSteps/resolution) != 0) return;
float ratio = step/(float)totalSteps;
int count = (int) (ratio * width);
System.out.printf("%3d%% [", (int) (ratio * 100));
for (int i=0; i<count; i++) System.out.printf("=");
for (int i=count; i<width; i++) System.out.printf(" ");
System.out.printf( "]\r ");
System.out.flush();
}
}
|
package me.jacobturner.castfast;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
public class CastFastS3 {
public static URL uploadFile(ArrayList<String> showData, String uploadFileName, String show) {
CastFastS3Credentials s3Credentials = new CastFastS3Credentials();
AmazonS3Client s3client = new AmazonS3Client(s3Credentials);
try {
File file = new File(uploadFileName);
String fileString = file.toString().split("/")[3];
s3client.putObject(new PutObjectRequest(s3Credentials.getBucket(), show.replace(" ", "-") + "/" + fileString, file));
s3client.setObjectAcl(s3Credentials.getBucket(), show.replace(" ", "-") + "/" + fileString, CannedAccessControlList.PublicRead);
return s3client.getUrl(s3Credentials.getBucket(), show.replace(" ", "-") + "/" + fileString);
} catch (AmazonServiceException ase) {
System.out.println("AmazonServiceException:");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
return null;
} catch (AmazonClientException ace) {
System.out.println("AmazonClientException: ");
System.out.println("Error Message: " + ace.getMessage());
return null;
}
}
}
|
package net.sf.pzfilereader.parserutils;
import java.util.List;
import junit.framework.TestCase;
import net.sf.pzfilereader.util.ParserUtils;
import net.sf.pzfilereader.utilities.UnitTestUtils;
public class ParserUtilsSplitLineTest extends TestCase {
private static final String[] DELIMITED_DATA_NO_BREAKS = { "Column 1", "Column 2", "Column 3", "Column 4", "Column 5" };
private static final String[] DELIMITED_DATA_WITH_BREAKS = { "Column 1 \r\n\r\n Test After Break \r\n Another Break",
"Column 2", "Column 3 \r\n\r\n Test After Break", "Column 4", "Column 5 \r\n\r\n Test After Break\r\n Another Break" };
// TODO think of a situation that actually breaks the parse. This still
// works because of the way it is coded
// to handle the excel CSV. Excel CSV has some elements qualified and others
// not
private static final String DELIMITED_BAD_DATA = "\"column 1\",\"column 2 ,\"column3\"";
// 0 = delimiter
// 1 = qualifier
private static final char[][] DELIM_QUAL_PAIR = { { ',', '\"' }, { '\t', '\"' }, { '|', '\"' }, { '_', '\"' }, { ',', 0 },
{ '|', 0 }, { '\t', 0 } };
/**
* Test without any line breaks
*
*/
public void testNoLineBreaks() {
// loop down all delimiter qualifier pairs to test
for (int i = 0; i < DELIM_QUAL_PAIR.length; i++) {
final char d = DELIM_QUAL_PAIR[i][0];
final char q = DELIM_QUAL_PAIR[i][1];
final String txtToParse = UnitTestUtils.buildDelimString(DELIMITED_DATA_NO_BREAKS, d, q);
final List splitLineResults = ParserUtils.splitLine(txtToParse, d, q, 10);
// check to make sure we have the same amount of elements which were
// expected
assertEquals("Expected size (d = [" + d + "] q = [" + (q != 0 ? String.valueOf(q) : "") + "] txt [" + txtToParse
+ "])", DELIMITED_DATA_NO_BREAKS.length, splitLineResults.size());
// loop through each value and compare what came back
for (int j = 0; j < DELIMITED_DATA_NO_BREAKS.length; j++) {
assertEquals("Data Element Value Does Not Match (d = [" + d + "] q = [" + q + "] txt [" + txtToParse + "])",
DELIMITED_DATA_NO_BREAKS[j], (String) splitLineResults.get(j));
}
}
}
/**
* Test with any line breaks
*
*/
public void testLineBreaks() {
// loop down all delimiter qualifier pairs to test
for (int i = 0; i < DELIM_QUAL_PAIR.length; i++) {
final char d = DELIM_QUAL_PAIR[i][0];
final char q = DELIM_QUAL_PAIR[i][1];
final String txtToParse = UnitTestUtils.buildDelimString(DELIMITED_DATA_WITH_BREAKS, d, q);
final List splitLineResults = ParserUtils.splitLine(txtToParse, d, q, 10);
// check to make sure we have the same amount of elements which were
// expected
assertEquals("Did Not Get Amount Of Elements Expected (d = " + d + " q = " + q + ")",
DELIMITED_DATA_WITH_BREAKS.length, splitLineResults.size());
// loop through each value and compare what came back
for (int j = 0; j < DELIMITED_DATA_WITH_BREAKS.length; j++) {
assertEquals("Data Element Value Does Not Match (d = " + d + " q = " + q + ")", DELIMITED_DATA_WITH_BREAKS[j],
(String) splitLineResults.get(j));
}
}
}
/**
* Test to make sure we get the correct amount of elements for malformed
* data
*/
public void testMalformedData() {
final List splitLineResults = ParserUtils.splitLine(DELIMITED_BAD_DATA, ',', '\"', 10);
assertEquals("Expecting 2 Data Elements From The Malformed Data", 2, splitLineResults.size());
}
/**
* Test some extreme cases
*/
public void testSomeExtremeCases() {
check(null, ',', '\"', new String[] {});
check("a", ',', '\"', new String[] { "a" });
check("", ',', '\"', new String[] { "" });
check(" ", ',', '\"', new String[] { "" });
check(" ", ',', '\"', new String[] { "" });
check(",", ',', '\"', new String[] { "", "" });
check(",,", ',', '\"', new String[] { "", "", "" });
check(",a,", ',', '\"', new String[] { "", "a", "" });
check("\"a,b,c\"", ',', '\"', new String[] { "a,b,c" });
check("\"a,b\",\"c\"", ',', '\"', new String[] { "a,b", "c" });
check("\"a , b\",\"c\"", ',', '\"', new String[] { "a , b", "c" });
check("a,b,c", ',', '\"', new String[] { "a", "b", "c" });
check("a b,c", ',', '\"', new String[] { "a b", "c" });
check(" a,b,c ", ',', '\"', new String[] { "a", "b", "c" });
check(" a, b ,c", ',', '\"', new String[] { "a", "b", "c" });
// example typically from Excel.
check("\"test1\",test2,\"0.00\",\"another, element here\",lastone", ',', '\"', new String[] { "test1", "test2", "0.00",
"another, element here", "lastone" });
check("\"FRED\",\"ZNAME\",\"Text Qualifier \" and seperator, in string\",\"ELYRIA\",\"OH\",\"\"", ',', '\"',
new String[] {"FRED", "ZNAME", "Text Qualifier \" and seperator, in string", "ELYRIA", "OH", ""});
check("a\",b,c\"", ',', '\"', new String[] { "a\"", "b", "c\"" });
check(" a, b ,c ", ',', '\"', new String[] { "a", "b", "c" });
check("\"a\", b , \"c\"", ',', '\"', new String[] { "a", "b", "c" });
check("\"\",,,,\"last one\"", ',', '\"', new String[] { "", "", "", "", "last one" });
check("\"first\",\"second\",", ',', '\"', new String[] { "first", "second", "" });
check("\" a,b,c\"", ',', '\"', new String[] { " a,b,c" });
check("\" a,b,c\",d", ',', '\"', new String[] { " a,b,c", "d" });
check("\"a, b,\"\"c\"", ',', '\"', new String[] { "a, b,\"c" });
check("\"a, b,\"\"c\", \" test\"", ',', '\"', new String[] { "a, b,\"c", " test" });
check("\"a, b,\"\"c\", test", ',', '\"', new String[] { "a, b,\"c", "test" });
check("one two three", ' ', '\u0000', new String[] {"one", "two", "three"});
check("\"one\" \"two\" three", ' ', '\"', new String[] {"one", "two", "three"});
check("\"one\" \"two\" three", ' ', '\"', new String[] {"one", "", "two", "", "three"});
check (" , , ", ',', '"', new String[] {"","",""});
check (" \t \t ", '\t', '"', new String[] {"","",""});
}
/**
* Test some extreme cases
*/
public void testSomeExtremeCases2() {
check("\"a,b,c\"", ',', '\'', new String[] { "\"a", "b", "c\"" });
check("\"a,b\",\"c\"", ',', '\'', new String[] { "\"a", "b\"", "\"c\"" });
check("a,b,c", ',', '\'', new String[] { "a", "b", "c" });
check(" a,b,c", ',', '\'', new String[] { "a", "b", "c" });
check(" a,b,c", ',', '\'', new String[] { "a", "b", "c" });
// example typically from Excel.
check("\"test1\",test2,\"0.00\",\"another, element here\",lastone", ',', '\'', new String[] { "\"test1\"", "test2",
"\"0.00\"", "\"another", "element here\"", "lastone" });
// what would you expect of these ones?
// +++++The parser allows qualified and unqualified elements to be
// contained
// on the same line. so it should break the elements down like so
// 1 = a" -->" is part of the data since the element did not start with
// a qualifier
// 2 = b
// 3 = c" --> same as
// a",b,c"
check("a\",b,c\"", ',', '\'', new String[] { "a\"", "b", "c\"" });
check("\" a,b,c\"", ',', '\'', new String[] { "\" a", "b", "c\"" });
check(" a, b ,c ", ',', '\'', new String[] { "a", "b", "c" });
}
private void check(final String txtToParse, final char delim, final char qualifier, final String[] expected) {
final List splitLineResults = ParserUtils.splitLine(txtToParse, delim, qualifier, 10);
assertEquals(
"Did Not Get Amount Of Elements Expected (d = " + delim + " q = " + qualifier + ") txt [" + txtToParse + "]",
expected.length, splitLineResults.size());
for (int i = 0; i < expected.length; i++) {
assertEquals("expecting...", expected[i], splitLineResults.get(i));
}
}
public static void main(final String[] args) {
junit.textui.TestRunner.run(ParserUtilsSplitLineTest.class);
}
}
|
package me.newyith.generator;
import me.newyith.memory.Memorable;
import me.newyith.memory.Memory;
import me.newyith.util.Debug;
import me.newyith.util.Point;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import java.util.*;
public class GeneratorCore implements Memorable {
//saved
private Set<Point> claimedPoints = new HashSet<>();
private Set<Point> claimedWallPoints = new HashSet<>();
private Point anchorPoint = null; //set by constructor
private GeneratorCoreAnimator animator = null; //set by constructor
private UUID placedByPlayerId = null; //set by onPlaced
private Set<Point> layerOutsideFortress = new HashSet<>();
private Set<Point> pointsInsideFortress = new HashSet<>(); //TODO: decide if I can remove pointsInsideFortress entirely
//not saved
private final int generationRangeLimit = 32;
public void saveTo(Memory m) {
m.save("claimedPoints", claimedPoints);
Debug.msg("saved claimedPoints: " + claimedPoints.size());
m.save("claimedWallPoints", claimedWallPoints);
Debug.msg("saved claimedWallPoints: " + claimedWallPoints.size());
m.save("anchorPoint", anchorPoint);
Debug.msg("saved anchorPoint: " + anchorPoint);
m.save("animator", animator);
m.save("placedByPlayerIdString", placedByPlayerId.toString());
//Debug.msg("saved placedByPlayerId: " + placedByPlayerId);
}
public static GeneratorCore loadFrom(Memory m) {
Set<Point> claimedPoints = m.loadPointSet("claimedPoints");
Debug.msg("loaded claimedPoints: " + claimedPoints.size());
Set<Point> claimedWallPoints = m.loadPointSet("claimedWallPoints");
Debug.msg("loaded claimedWallPoints: " + claimedWallPoints.size());
Point anchorPoint = m.loadPoint("anchorPoint");
Debug.msg("loaded anchorPoint: " + anchorPoint);
GeneratorCoreAnimator animator = m.loadGenerationAnimator("animator");
UUID placedByPlayerId = UUID.fromString(m.loadString("placedByPlayerIdString"));
//updateInsideOutside() called by runes manager (second stage loading)
GeneratorCore instance = new GeneratorCore(
animator,
claimedPoints,
claimedWallPoints,
anchorPoint,
placedByPlayerId);
return instance;
}
private GeneratorCore(
GeneratorCoreAnimator animator,
Set<Point> claimedPoints,
Set<Point> claimedWallPoints,
Point anchorPoint,
UUID placedByPlayerId) {
this.animator = animator;
this.claimedPoints = claimedPoints;
this.claimedWallPoints = claimedWallPoints;
this.anchorPoint = anchorPoint;
this.placedByPlayerId = placedByPlayerId;
}
//*/
/**
* Degenerates (turns off) the wall being generated by this generator.
*/
private void degenerateWall(boolean animate) {
Debug.msg("degenerateWall(" + String.valueOf(animate) + ")");
getClaimedPointsOfNearbyGenerators(); //make nearby generators look for and degenerate any claimed but unconnected blocks
animator.degenerate(animate);
}
private void generateWall() {
Debug.msg("generateWall()");
animator.wallMats.refresh(); //refresh protectable blocks list based on chest contents
List<List<Point>> generatableLayers = getGeneratableWallLayers();
List<List<Point>> wallLayers = Wall.merge(generatableLayers, animator.getGeneratedLayers());
Set<Point> wallPoints = Wall.flattenLayers(wallLayers);
updateClaimedPoints(wallPoints);
updateInsideOutside(wallPoints);
animator.generate(generatableLayers);
}
public void updateInsideOutside() {
updateInsideOutside(claimedWallPoints);
}
private void updateInsideOutside(Set<Point> wallPoints) {
layerOutsideFortress.clear();
pointsInsideFortress.clear();
if (wallPoints.size() > 0) {
Set<Point> layerAroundWall = getLayerAround(wallPoints);
//find a top block in layerAroundWall
Point top = layerAroundWall.iterator().next();
for (Point p : layerAroundWall) {
if (p.y > top.y) {
top = p;
}
}
//fill layerOutsideFortress
Point origin = top;
Set<Point> originLayer = new HashSet<>();
originLayer.add(origin);
Set<Material> wallMaterials = null; //traverse all block types
Set<Material> returnMaterials = null; //return all block types
int rangeLimit = 2 * generationRangeLimit + 2;
Set<Point> ignorePoints = wallPoints;
Set<Point> searchablePoints = new HashSet<>(layerAroundWall);
FortressGeneratorRune rune = FortressGeneratorRunesManager.getRune(anchorPoint);
searchablePoints.addAll(rune.getPoints());
layerOutsideFortress = Wall.getPointsConnected(origin, originLayer, wallMaterials, returnMaterials, rangeLimit, ignorePoints, searchablePoints);
layerOutsideFortress.addAll(originLayer);
layerOutsideFortress.retainAll(layerAroundWall);
//Debug.msg("layerOutsideFortress.size(): " + layerOutsideFortress.size());
//get layerInsideFortress
Set<Point> layerInsideFortress = new HashSet<>(layerAroundWall);
layerInsideFortress.removeAll(layerOutsideFortress);
//fill pointsInsideFortress
if (layerInsideFortress.size() > 0) {
origin = layerInsideFortress.iterator().next();
originLayer = layerInsideFortress;
wallMaterials = null; //traverse all block types
returnMaterials = null; //all block types
rangeLimit = 2 * generationRangeLimit;
ignorePoints = wallPoints;
searchablePoints = null; //search all points
pointsInsideFortress = Wall.getPointsConnected(origin, originLayer, wallMaterials, returnMaterials, rangeLimit, ignorePoints, searchablePoints);
pointsInsideFortress.addAll(originLayer);
}
// for (Point p : layerOutsideFortress) {
// Debug.particleAt(p, ParticleEffect.FLAME);
// for (Point p : pointsInsideFortress) {
// Debug.particleAt(p, ParticleEffect.HEART);
}
}
private List<List<Point>> getGeneratableWallLayers() {
Set<Point> claimedPoints = getClaimedPointsOfNearbyGenerators();
//return all connected wall points ignoring (and not traversing) claimedPoints (generationRangeLimit search range)
List<List<Point>> allowedWallLayers = getPointsConnectedAsLayers(animator.wallMats.getWallMaterials(), animator.wallMats.getGeneratableWallMaterials(), generationRangeLimit, claimedPoints);
return allowedWallLayers;
}
private void updateClaimedPoints(Set<Point> wallPoints) {
claimedPoints.clear();
//claim wallLayers
claimedWallPoints = wallPoints;
claimedPoints.addAll(claimedWallPoints);
//claim layer around wall
Set<Point> layerAroundWallPoints = getLayerAround(claimedWallPoints);
claimedPoints.addAll(layerAroundWallPoints);
FortressGeneratorRune rune = FortressGeneratorRunesManager.getRune(anchorPoint);
if (rune != null) {
//claim rune
Set<Point> runePoints = rune.getPoints();
claimedPoints.addAll(runePoints);
//claim layer around rune
Set<Point> layerAroundRune = getLayerAround(runePoints);
claimedPoints.addAll(layerAroundRune);
}
}
private Set<Point> getClaimedPointsOfNearbyGenerators() {
Set<FortressGeneratorRune> nearbyRunes = FortressGeneratorRunesManager.getOtherRunesInRange(anchorPoint, generationRangeLimit * 2 + 1); //not sure if the + 1 is needed
Set<Point> claimedPoints = new HashSet<>();
for (FortressGeneratorRune rune : nearbyRunes) {
claimedPoints.addAll(rune.getGeneratorCore().getClaimedPoints());
}
return claimedPoints;
}
private Set<Point> getClaimedPoints() {
//commented out because now that protectable blocks can be changed by user
//we don't want a generator to be able to degenerate another generator's generated points
//even though the other generator's points are no longer connected to the generator
//*/
|
package org.animotron.graph;
import org.animotron.statement.operator.THE;
import org.neo4j.graphdb.Node;
/**
* @author <a href="mailto:gazdovskyd@gmail.com">Evgeny Gazdovsky</a>
*
*/
public class Nodes {
public final static Node EXTENSION = THE._("extension");
public final static Node MIME_TYPE = THE._("mime-type");
public final static Node TYPE = THE._("type");
public final static Node FILE = THE._("file");
public final static Node NAME = THE._("name");
public final static Node URI = THE._("uri");
}
|
package com.ext.portlet.service.impl;
import com.ext.portlet.ProposalAttributeKeys;
import com.ext.portlet.model.*;
import com.ext.portlet.service.*;
import com.liferay.portal.dao.jdbc.DataSourceFactoryImpl;
import com.liferay.portal.kernel.bean.BeanReference;
import com.liferay.portal.kernel.bean.PortalBeanLocatorUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.model.User;
import com.liferay.portal.security.auth.CompanyThreadLocal;
import com.liferay.portal.security.permission.PermissionCheckerUtil;
import com.liferay.portal.service.MockContextProvider;
import com.liferay.portal.service.ResourceActionLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.spring.aop.ServiceBeanAutoProxyCreator;
import com.liferay.portal.util.InitUtil;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.xcolab.services.EventBusService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class PointsLocalServiceImplTest {
private static ContestLocalService contestLocalService;
private static ContestPhaseLocalService contestPhaseLocalService;
private static ProposalLocalService proposalLocalService;
private static Proposal2PhaseLocalService proposal2PhaseLocalService;
private static ProposalContestPhaseAttributeLocalService proposalContestPhaseAttributeLocalService;
private static PointsLocalService pointsLocalService;
private static PlanSectionDefinitionLocalService planSectionDefinitionLocalService;
private static SimpleDateFormat dateFormat;
private static AbstractApplicationContext ctx;
private Random rand = new Random();
@BeanReference(type = EventBusService.class)
private EventBusService eventBus;
@BeforeClass
public static void beforeTest() throws Exception {
dateFormat = new SimpleDateFormat("yyyy-M-d H:m:s", Locale.ENGLISH);
new DataSourceFactoryImpl();
new ServiceBeanAutoProxyCreator();
new MockContextProvider();
System.out.println("Before init");
InitUtil.initWithSpring();
System.out.println("after init with spring before ctx");
ResourceActionLocalServiceUtil.checkResourceActions();
CompanyThreadLocal.setCompanyId(10112l);
System.out.println("initialized?");
contestLocalService = (ContestLocalService) PortalBeanLocatorUtil.locate(ContestLocalService.class.getName());
contestPhaseLocalService = (ContestPhaseLocalService) PortalBeanLocatorUtil.locate(ContestPhaseLocalService.class.getName());
proposalLocalService = (ProposalLocalService) PortalBeanLocatorUtil.locate(ProposalLocalService.class.getName());
proposal2PhaseLocalService = (Proposal2PhaseLocalService) PortalBeanLocatorUtil.locate(Proposal2PhaseLocalService.class.getName());
proposalContestPhaseAttributeLocalService = (ProposalContestPhaseAttributeLocalService) PortalBeanLocatorUtil.locate(ProposalContestPhaseAttributeLocalService.class.getName());
pointsLocalService = (PointsLocalService) PortalBeanLocatorUtil.locate(PointsLocalService.class.getName());
planSectionDefinitionLocalService = (PlanSectionDefinitionLocalService) PortalBeanLocatorUtil.locate(PlanSectionDefinitionLocalService.class.getName());
}
@Test
public void testGlobalContestHypotheticalPoints() throws SystemException, PortalException, ParseException {
long authorId = 10144L;
PermissionCheckerUtil.setThreadValues(UserLocalServiceUtil.getUser(authorId));
//create global contest
Contest globalContest = contestLocalService.createNewContest(authorId, "Test-Global-Contest");
globalContest.setPoints(10000);
globalContest.setDefaultParentPointType(1);
contestLocalService.updateContest(globalContest);
//create phases
ContestPhase gCp1 = createContestPhase(globalContest, 1, false, "PROMOTE_DONE", "2014-08-01 00:00:00", "2014-08-10 00:00:00");
ContestPhase gCp2 = createContestPhase(globalContest, 16, true, "PROMOTE_DONE", "2014-08-10 00:00:01", "2014-08-14 00:00:00");
ContestPhase gCp3 = createContestPhase(globalContest, 18, false, "PROMOTE_DONE", "2014-08-14 00:00:01", "2014-08-16 00:00:00");
ContestPhase gCp4 = createContestPhase(globalContest, 19, true, "PROMOTE_DONE", "2014-08-16 00:00:01", "2014-08-20 00:00:00");
ContestPhase gCp5 = createContestPhase(globalContest, 15, false, "PROMOTE_DONE", "2014-08-20 00:00:01", "2015-09-24 00:00:00");
//this contest did not expire yet.
ContestPhase gCp6 = createContestPhase(globalContest, 17, false, "", "2015-09-24 00:00:01", null);
//create 10 proposals, advance half of them to the last phase.
List<Proposal> globalProposals = new ArrayList<Proposal>();
for (int i = 0; i < 10; i++) {
Proposal proposal = proposalLocalService.create(authorId, gCp1.getContestPhasePK());
globalProposals.add(proposal);
//copy to first phases
copyProposalToPhase(proposal, gCp2);
//copy half of the proposals to other phases
if (i > 4) {
copyProposalToPhase(proposal, gCp3);
copyProposalToPhase(proposal, gCp4);
copyProposalToPhase(proposal, gCp5);
}
}
//create side contests
List<Proposal> sideProposals = new ArrayList<Proposal>();
List<Contest> sideContests = new ArrayList<Contest>();
for (int i = 0; i < 2; i++) {
sideContests.add(contestLocalService.createNewContest(authorId, "Test-Side-Contest-"+(i+1)));
//create phases
ContestPhase sCp1 = createContestPhase(globalContest, 1, false, "PROMOTE_DONE", "2014-08-01 00:00:00", "2014-08-10 00:00:00");
ContestPhase sCp2 = createContestPhase(globalContest, 16, true, "PROMOTE_DONE", "2014-08-10 00:00:01", "2014-08-14 00:00:00");
ContestPhase sCp3 = createContestPhase(globalContest, 18, false, "PROMOTE_DONE", "2014-08-14 00:00:01", "2014-08-16 00:00:00");
ContestPhase sCp4 = createContestPhase(globalContest, 19, true, "PROMOTE_DONE", "2014-08-16 00:00:01", "2014-08-20 00:00:00");
ContestPhase sCp5 = createContestPhase(globalContest, 15, false, "PROMOTE_DONE", "2014-08-20 00:00:01", "2015-09-24 00:00:00");
//this contest did not expire yet.
ContestPhase sCp6 = createContestPhase(globalContest, 17, false, "", "2015-09-24 00:00:01", null);
for (int j = 0; j < 3; i++) {
Proposal proposal = proposalLocalService.create(authorId, gCp1.getContestPhasePK());
sideProposals.add(proposal);
//copy to first phases
copyProposalToPhase(proposal, gCp2);
//copy half of the proposals to other phases
if (i > 4) {
copyProposalToPhase(proposal, gCp3);
copyProposalToPhase(proposal, gCp4);
copyProposalToPhase(proposal, gCp5);
}
}
}
//create some links from global proposals to side proposals
String sectionText = "These are the subproposals we link to:\n"+
"http://127.0.0.1:8080/web/guest/plans/-/plans/contestId/"+sideContests.get(0).getContestPK()+"/planId/"+sideProposals.get(0).getProposalId()+"\n\n"+
"http://127.0.0.1:8080/web/guest/plans/-/plans/contestId/"+sideContests.get(0).getContestPK()+"/planId/"+sideProposals.get(1).getProposalId()+"\n\n"+
"http://127.0.0.1:8080/web/guest/plans/-/plans/contestId/"+sideContests.get(1).getContestPK()+"/planId/"+sideProposals.get(4).getProposalId()+" and "+
"http://127.0.0.1:8080/web/guest/plans/-/plans/contestId/"+sideContests.get(1).getContestPK()+"/planId/"+sideProposals.get(5).getProposalId()+" and "+
"http://127.0.0.1:8080/web/guest/plans/-/plans/contestId/"+globalContest.getContestPK()+"/planId/"+globalProposals.get(3).getProposalId();
//1300907 is the sub proposal plan section definition
proposalLocalService.setAttribute(authorId, globalProposals.get(6).getProposalId(), ProposalAttributeKeys.SECTION, 1300907L, sectionText);
//set some point distributions
//test the hypothetical points distribution now.
//assert the points
}
private void copyProposalToPhase(Proposal p, ContestPhase cp) throws SystemException {
Proposal2Phase p2p = proposal2PhaseLocalService.create(p.getProposalId(), cp.getContestPhasePK());
p2p.setVersionFrom(1);
p2p.setVersionTo(1);
proposal2PhaseLocalService.updateProposal2Phase(p2p);
}
private ContestPhase createContestPhase(Contest c, long type, boolean fellowScreeningActive, String autoPromote, String startDate, String endDate) throws SystemException, ParseException {
ContestPhase cp = contestPhaseLocalService.createContestPhase(100000);
cp.setContestPK(c.getContestPK());
cp.setContestPhaseType(type);
cp.setFellowScreeningActive(fellowScreeningActive);
cp.setContestPhaseAutopromote(autoPromote);
cp.setPhaseActiveOverride(false);
cp.setPhaseInactiveOverride(false);
cp.setPhaseStartDate(dateFormat.parse(startDate));
if (endDate != null) {
cp.setPhaseEndDate(dateFormat.parse(endDate));
}
contestPhaseLocalService.updateContestPhase(cp);
return cp;
}
}
|
package org.openlaszlo.compiler;
import java.io.*;
import java.util.*;
import org.jdom.Document;
import org.jdom.Element;
import org.openlaszlo.utils.ChainedException;
import org.apache.log4j.*;
/** Compiler for <code>library</code> elements.
*
* @author Oliver Steele
*/
class LibraryCompiler extends ToplevelCompiler {
final static String HREF_ANAME = "href";
/** Logger
*/
private static Logger mLogger = Logger.getLogger(Compiler.class);
LibraryCompiler(CompilationEnvironment env) {
super(env);
}
static boolean isElement(Element element) {
return element.getName().equals("library");
}
/** Return the library element and add the library to visited. If
* the library has already been visited, return null instead.
*/
static Element resolveLibraryElement(File file,
CompilationEnvironment env,
Set visited,
boolean validate)
{
try {
File key = file.getCanonicalFile();
if (!visited.contains(key)) {
visited.add(key);
// If we're compiling a loadable library, add this to
// the list of library files which which have been
// included by loadable libraries, so we can warn on
// duplicates.
if (env.isImportLib()) {
// compare this library file with the set of all known libraries that
// have been included in loadable modules. If this has been seen before,
// issue warning.
if (env.isImportLib() && env.getLoadableImportedLibraryFiles().containsKey(key)) {
env.warn(
/* (non-Javadoc)
* @i18n.test
* @org-mes="The library file \"" + p[0] + "\" included by loadable library \"" + p[1] + "\" was also included by another loadable library \"" + p[2] + "\". " + "This may lead to unexpected behavior, especially if the library defines new classes."
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
LibraryCompiler.class.getName(),"051018-77", new Object[] {file, env.getApplicationFile(), env.getLoadableImportedLibraryFiles().get(key)})
);
}
env.getLoadableImportedLibraryFiles().put(key, env.getApplicationFile());
}
Document doc = env.getParser().parse(file);
if (validate)
Parser.validate(doc, file.getPath(), env);
Element root = doc.getRootElement();
// Look for and add any includes from a binary library
String includesAttr = root.getAttributeValue("includes");
String base = new File(Parser.getSourcePathname(root)).getParent();
if (includesAttr != null) {
for (StringTokenizer st = new StringTokenizer(includesAttr);
st.hasMoreTokens();) {
String name = (String) st.nextToken();
visited.add((new File(base, name)).getCanonicalFile());
}
}
return root;
} else {
return null;
}
} catch (IOException e) {
throw new CompilationError(e);
}
}
/** Return the resolved library element and add the library to visited.
* If the library has already been visited, return null instead.
*/
static Element resolveLibraryElement(Element element,
CompilationEnvironment env,
Set visited,
boolean validate)
{
String href = element.getAttributeValue(HREF_ANAME);
if (href == null) {
return element;
}
File file = env.resolveReference(element, HREF_ANAME, true);
return resolveLibraryElement(file, env, visited, validate);
}
public void compile(Element element) throws CompilationError
{
element = resolveLibraryElement(
element, mEnv, mEnv.getImportedLibraryFiles(),
mEnv.getBooleanProperty(mEnv.VALIDATE_PROPERTY));
if (element != null) {
super.compile(element);
}
}
void updateSchema(Element element, ViewSchema schema, Set visited) {
element = resolveLibraryElement(element, mEnv, visited, false);
if (element != null) {
// If compiling a library we need to get the auto-includes
// into the schema
if (element.getParentElement() == null) {
for (Iterator iter = getLibraries(element).iterator();
iter.hasNext(); ) {
File file = (File) iter.next();
Compiler.updateSchemaFromLibrary(file, mEnv, schema, visited);
}
}
super.updateSchema(element, schema, visited);
// TODO [hqm 2005-02-09] can we compare any 'proxied' attribute here
// with the parent element (canvas) to warn if it conflicts.
}
}
}
|
package com.groupon.seleniumgridextras.tasks;
import com.groupon.seleniumgridextras.ExecuteCommand;
import com.groupon.seleniumgridextras.ExtrasEndPoint;
import com.groupon.seleniumgridextras.JsonResponseBuilder;
import com.groupon.seleniumgridextras.OSChecker;
import com.groupon.seleniumgridextras.RuntimeConfig;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public abstract class ExecuteOSTask extends ExtrasEndPoint{
final private
String
notImplementedError =
"This task was not implemented on " + OSChecker.getOSName();
public boolean waitToFinishTask = true;
protected JsonResponseBuilder jsonResponse;
public String execute() {
return execute("");
}
public String execute(Map<String, String> parameter) {
if (!parameter.isEmpty() && parameter.containsKey("parameter")) {
return execute(parameter.get("parameter").toString());
} else {
return execute();
}
}
public JsonResponseBuilder getJsonResponse() {
if (jsonResponse == null) {
jsonResponse = new JsonResponseBuilder();
}
return jsonResponse;
}
public String execute(String parameter) {
String
command =
OSChecker.isWindows() ? getWindowsCommand()
: OSChecker.isMac() ? getMacCommand() : getLinuxCommand();
return ExecuteCommand.execRuntime(command + parameter, waitToFinishTask);
}
// public abstract String getEndpoint();
// public abstract String getDescription();
public String getWindowsCommand(String parameter) {
getJsonResponse().addKeyValues("error",
notImplementedError + " " + this.getClass().getCanonicalName());
return getJsonResponse().toString();
}
public String getWindowsCommand() {
return getWindowsCommand("");
}
public String getLinuxCommand(String parameter) {
getJsonResponse().addKeyValues("error",
notImplementedError + " " + this.getClass().getCanonicalName());
return getJsonResponse().toString();
}
public String getLinuxCommand() {
return getLinuxCommand("");
}
public String getMacCommand(String parameter) {
return getLinuxCommand(parameter);
}
public String getMacCommand() {
return getLinuxCommand();
}
public boolean initialize() {
if (allDependenciesLoaded()) {
printInitilizedSuccessAndRegisterWithAPI();
return true;
} else {
printInitilizedFailure();
return false;
}
}
public void printInitilizedSuccessAndRegisterWithAPI() {
System.out.println(
"Y " + this.getClass().getSimpleName() + " - " + this.getEndpoint() + " - " + this
.getDescription());
registerApi();
}
public void printInitilizedFailure() {
System.out.println("N " + this.getClass().getSimpleName());
}
public Boolean allDependenciesLoaded() {
Boolean returnValue = true;
for (String module : getDependencies()) {
if (RuntimeConfig.checkIfModuleEnabled(module) && returnValue) {
} else {
System.out.println(" " + this.getClass().getSimpleName() + " depends on " + module
+ " but it is not activated");
returnValue = false;
}
}
return returnValue;
}
public List<String> getDependencies() {
List<String> dependencies = new LinkedList();
return dependencies;
}
}
|
package org.b3log.symphony.util;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.b3log.latke.Latkes;
import org.b3log.latke.cache.Cache;
import org.b3log.latke.cache.CacheFactory;
import org.b3log.latke.ioc.LatkeBeanManagerImpl;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.service.LangPropsServiceImpl;
import org.b3log.latke.util.MD5;
import org.b3log.latke.util.Stopwatchs;
import org.b3log.latke.util.Strings;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.safety.Whitelist;
import org.jsoup.select.Elements;
import org.pegdown.*;
import org.pegdown.ast.*;
import org.pegdown.plugins.ToHtmlSerializerPlugin;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.concurrent.*;
import static org.parboiled.common.Preconditions.checkArgNotNull;
public final class Markdowns {
/**
* Language service.
*/
public static final LangPropsService LANG_PROPS_SERVICE
= LatkeBeanManagerImpl.getInstance().getReference(LangPropsServiceImpl.class);
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(Markdowns.class);
/**
* Markdown cache.
*/
private static final Cache MD_CACHE = CacheFactory.getCache("markdown");
/**
* Markdown to HTML timeout.
*/
private static final int MD_TIMEOUT = 800;
/**
* Marked engine serve path.
*/
private static final String MARKED_ENGINE_URL = "http://localhost:8250";
/**
* Whether marked is available.
*/
public static boolean MARKED_AVAILABLE;
static {
MD_CACHE.setMaxCount(1024 * 10 * 4);
}
static {
try {
final URL url = new URL(MARKED_ENGINE_URL);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
final OutputStream outputStream = conn.getOutputStream();
IOUtils.write("Symphony ", outputStream, "UTF-8");
IOUtils.closeQuietly(outputStream);
final InputStream inputStream = conn.getInputStream();
final String html = IOUtils.toString(inputStream, "UTF-8");
IOUtils.closeQuietly(inputStream);
conn.disconnect();
MARKED_AVAILABLE = StringUtils.contains(html, "<p>Symphony </p>");
if (MARKED_AVAILABLE) {
LOGGER.log(Level.INFO, "[marked] is available, uses it for markdown processing");
} else {
LOGGER.log(Level.INFO, "[marked] is not available, uses built-in [pegdown] for markdown processing");
}
} catch (final Exception e) {
LOGGER.log(Level.INFO, "[marked] is not available, uses built-in [pegdown] for markdown processing: "
+ e.getMessage());
}
}
/**
* Private constructor.
*/
private Markdowns() {
}
/**
* Gets the safe HTML content of the specified content.
*
* @param content the specified content
* @param baseURI the specified base URI, the relative path value of href will starts with this URL
* @return safe HTML content
*/
public static String clean(final String content, final String baseURI) {
final Document.OutputSettings outputSettings = new Document.OutputSettings();
outputSettings.prettyPrint(false);
final String tmp = Jsoup.clean(content, baseURI, Whitelist.relaxed().
addAttributes(":all", "id", "target", "class").
addTags("span", "hr", "kbd", "samp", "tt", "del", "s", "strike", "u").
addAttributes("iframe", "src", "width", "height", "border", "marginwidth", "marginheight").
addAttributes("audio", "controls", "src").
addAttributes("video", "controls", "src", "width", "height").
addAttributes("source", "src", "media", "type").
addAttributes("object", "width", "height", "data", "type").
addAttributes("param", "name", "value").
addAttributes("embed", "src", "type", "width", "height", "wmode", "allowNetworking"),
outputSettings);
final Document doc = Jsoup.parse(tmp, baseURI, Parser.htmlParser());
final Elements ps = doc.getElementsByTag("p");
for (final Element p : ps) {
p.removeAttr("style");
}
final Elements as = doc.getElementsByTag("a");
for (final Element a : as) {
a.attr("rel", "nofollow");
final String href = a.attr("href");
if (href.startsWith(Latkes.getServePath())) {
continue;
}
a.attr("target", "_blank");
}
final Elements audios = doc.getElementsByTag("audio");
for (final Element audio : audios) {
audio.attr("preload", "none");
}
final Elements videos = doc.getElementsByTag("video");
for (final Element video : videos) {
video.attr("preload", "none");
}
String ret = doc.body().html();
ret = ret.replaceAll("(</?br\\s*/?>\\s*)+", "<br>"); // patch for Jsoup issue
return ret;
}
/**
* Converts the email or url text to HTML.
*
* @param markdownText the specified markdown text
* @return converted HTML, returns an empty string "" if the specified markdown text is "" or {@code null}, returns
* 'markdownErrorLabel' if exception
*/
public static String linkToHtml(final String markdownText) {
if (Strings.isEmptyOrNull(markdownText)) {
return "";
}
String ret = getHTML(markdownText);
if (null != ret) {
return ret;
}
final ExecutorService pool = Executors.newSingleThreadExecutor();
final long[] threadId = new long[1];
final Callable<String> call = new Callable<String>() {
@Override
public String call() throws Exception {
threadId[0] = Thread.currentThread().getId();
String ret = LANG_PROPS_SERVICE.get("contentRenderFailedLabel");
if (MARKED_AVAILABLE) {
ret = toHtmlByMarked(markdownText);
if (!StringUtils.startsWith(ret, "<p>")) {
ret = "<p>" + ret + "</p>";
}
} else {
final PegDownProcessor pegDownProcessor
= new PegDownProcessor(Extensions.ALL_OPTIONALS | Extensions.ALL_WITH_OPTIONALS);
final RootNode node = pegDownProcessor.parseMarkdown(markdownText.toCharArray());
ret = new ToHtmlSerializer(new LinkRenderer(), Collections.<String, VerbatimSerializer>emptyMap(),
Arrays.asList(new ToHtmlSerializerPlugin[0])).toHtml(node);
if (!StringUtils.startsWith(ret, "<p>")) {
ret = "<p>" + ret + "</p>";
}
ret = formatMarkdown(ret);
}
// cache it
putHTML(markdownText, ret);
return ret;
}
};
try {
final Future<String> future = pool.submit(call);
return future.get(MD_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (final TimeoutException e) {
LOGGER.log(Level.ERROR, "Markdown timeout [md=" + markdownText + "]");
final Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (final Thread thread : threads) {
if (thread.getId() == threadId[0]) {
thread.stop();
break;
}
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Markdown failed [md=" + markdownText + "]", e);
} finally {
pool.shutdownNow();
}
return "";
}
/**
* Converts the specified markdown text to HTML.
*
* @param markdownText the specified markdown text
* @return converted HTML, returns an empty string "" if the specified markdown text is "" or {@code null}, returns
* 'markdownErrorLabel' if exception
*/
public static String toHTML(final String markdownText) {
if (Strings.isEmptyOrNull(markdownText)) {
return "";
}
String ret = getHTML(markdownText);
if (null != ret) {
return ret;
}
final ExecutorService pool = Executors.newSingleThreadExecutor();
final long[] threadId = new long[1];
final Callable<String> call = new Callable<String>() {
@Override
public String call() throws Exception {
threadId[0] = Thread.currentThread().getId();
String ret = LANG_PROPS_SERVICE.get("contentRenderFailedLabel");
if (MARKED_AVAILABLE) {
ret = toHtmlByMarked(markdownText);
if (!StringUtils.startsWith(ret, "<p>")) {
ret = "<p>" + ret + "</p>";
}
} else {
final PegDownProcessor pegDownProcessor
= new PegDownProcessor(Extensions.ALL_OPTIONALS | Extensions.ALL_WITH_OPTIONALS);
final RootNode node = pegDownProcessor.parseMarkdown(markdownText.toCharArray());
ret = new ToHtmlSerializer(new LinkRenderer(), Collections.<String, VerbatimSerializer>emptyMap(),
Arrays.asList(new ToHtmlSerializerPlugin[0])).toHtml(node);
if (!StringUtils.startsWith(ret, "<p>")) {
ret = "<p>" + ret + "</p>";
}
ret = formatMarkdown(ret);
}
// cache it
putHTML(markdownText, ret);
return ret;
}
};
Stopwatchs.start("Md to HTML");
try {
final Future<String> future = pool.submit(call);
return future.get(MD_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (final TimeoutException e) {
LOGGER.log(Level.ERROR, "Markdown timeout [md=" + markdownText + "]");
final Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (final Thread thread : threads) {
if (thread.getId() == threadId[0]) {
thread.stop();
break;
}
}
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Markdown failed [md=" + markdownText + "]", e);
} finally {
pool.shutdownNow();
Stopwatchs.end();
}
return LANG_PROPS_SERVICE.get("contentRenderFailedLabel");
}
private static String toHtmlByMarked(final String markdownText) throws Exception {
final URL url = new URL(MARKED_ENGINE_URL);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
final OutputStream outputStream = conn.getOutputStream();
IOUtils.write(markdownText, outputStream, "UTF-8");
IOUtils.closeQuietly(outputStream);
final InputStream inputStream = conn.getInputStream();
final String html = IOUtils.toString(inputStream, "UTF-8");
IOUtils.closeQuietly(inputStream);
//conn.disconnect();
return html;
// Pangu space
// final Document doc = Jsoup.parse(html);
// doc.traverse(new NodeVisitor() {
// @Override
// public void head(final org.jsoup.nodes.Node node, int depth) {
// if (node instanceof org.jsoup.nodes.TextNode) {
// // final org.jsoup.nodes.TextNode textNode = (org.jsoup.nodes.TextNode) node;
// // textNode.text(Pangu.spacingText(textNode.getWholeText()));
// // FIXME: Pangu space
// @Override
// public void tail(org.jsoup.nodes.Node node, int depth) {
// doc.outputSettings().prettyPrint(false);
// String ret = doc.html();
// ret = StringUtils.substringBetween(ret, "<body>", "</body>");
// ret = StringUtils.trim(ret);
// return ret;
}
private static String formatMarkdown(final String markdownText) {
String ret = markdownText;
final Document doc = Jsoup.parse(markdownText, "", Parser.htmlParser());
final Elements tagA = doc.select("a");
for (int i = 0; i < tagA.size(); i++) {
final String search = tagA.get(i).attr("href");
final String replace = StringUtils.replace(search, "_", "[downline]");
ret = StringUtils.replace(ret, search, replace);
}
final Elements tagImg = doc.select("img");
for (int i = 0; i < tagImg.size(); i++) {
final String search = tagImg.get(i).attr("src");
final String replace = StringUtils.replace(search, "_", "[downline]");
ret = StringUtils.replace(ret, search, replace);
}
final Elements tagCode = doc.select("code");
for (int i = 0; i < tagCode.size(); i++) {
final String search = tagCode.get(i).html();
final String replace = StringUtils.replace(search, "_", "[downline]");
ret = StringUtils.replace(ret, search, replace);
}
String[] rets = ret.split("\n");
for (final String temp : rets) {
final String[] toStrong = StringUtils.substringsBetween(temp, "**", "**");
final String[] toEm = StringUtils.substringsBetween(temp, "_", "_");
if (toStrong != null && toStrong.length > 0) {
for (final String strong : toStrong) {
final String search = "**" + strong + "**";
final String replace = "<strong>" + strong + "</strong>";
ret = StringUtils.replace(ret, search, replace);
}
}
if (toEm != null && toEm.length > 0) {
for (final String em : toEm) {
final String search = "_" + em + "_";
final String replace = "<em>" + em + "<em>";
ret = StringUtils.replace(ret, search, replace);
}
}
}
ret = StringUtils.replace(ret, "[downline]", "_");
return ret;
}
/**
* Gets HTML for the specified markdown text.
*
* @param markdownText the specified markdown text
* @return HTML
*/
private static String getHTML(final String markdownText) {
final String hash = MD5.hash(markdownText);
return (String) MD_CACHE.get(hash);
}
/**
* Puts the specified HTML into cache.
*
* @param markdownText the specified markdown text
* @param html the specified HTML
*/
private static void putHTML(final String markdownText, final String html) {
final String hash = MD5.hash(markdownText);
MD_CACHE.put(hash, html);
}
/**
* Enhanced with {@link Pangu} for text node.
*/
private static class ToHtmlSerializer implements Visitor {
protected final Map<String, ReferenceNode> references = new HashMap<String, ReferenceNode>();
protected final Map<String, String> abbreviations = new HashMap<String, String>();
protected final LinkRenderer linkRenderer;
protected final List<ToHtmlSerializerPlugin> plugins;
protected Printer printer = new Printer();
protected TableNode currentTableNode;
protected int currentTableColumn;
protected boolean inTableHeader;
protected Map<String, VerbatimSerializer> verbatimSerializers;
public ToHtmlSerializer(LinkRenderer linkRenderer) {
this(linkRenderer, Collections.<ToHtmlSerializerPlugin>emptyList());
}
public ToHtmlSerializer(LinkRenderer linkRenderer, List<ToHtmlSerializerPlugin> plugins) {
this(linkRenderer, Collections.<String, VerbatimSerializer>emptyMap(), plugins);
}
public ToHtmlSerializer(final LinkRenderer linkRenderer, final Map<String, VerbatimSerializer> verbatimSerializers) {
this(linkRenderer, verbatimSerializers, Collections.<ToHtmlSerializerPlugin>emptyList());
}
public ToHtmlSerializer(final LinkRenderer linkRenderer, final Map<String, VerbatimSerializer> verbatimSerializers, final List<ToHtmlSerializerPlugin> plugins) {
this.linkRenderer = linkRenderer;
this.verbatimSerializers = new HashMap<>(verbatimSerializers);
if (!this.verbatimSerializers.containsKey(VerbatimSerializer.DEFAULT)) {
this.verbatimSerializers.put(VerbatimSerializer.DEFAULT, DefaultVerbatimSerializer.INSTANCE);
}
this.plugins = plugins;
}
public String toHtml(RootNode astRoot) {
checkArgNotNull(astRoot, "astRoot");
astRoot.accept(this);
return printer.getString();
}
public void visit(RootNode node) {
for (ReferenceNode refNode : node.getReferences()) {
visitChildren(refNode);
references.put(normalize(printer.getString()), refNode);
printer.clear();
}
for (AbbreviationNode abbrNode : node.getAbbreviations()) {
visitChildren(abbrNode);
String abbr = printer.getString();
printer.clear();
abbrNode.getExpansion().accept(this);
String expansion = printer.getString();
abbreviations.put(abbr, expansion);
printer.clear();
}
visitChildren(node);
}
public void visit(AbbreviationNode node) {
}
public void visit(AnchorLinkNode node) {
printLink(linkRenderer.render(node));
}
public void visit(AutoLinkNode node) {
printLink(linkRenderer.render(node));
}
public void visit(BlockQuoteNode node) {
printIndentedTag(node, "blockquote");
}
public void visit(BulletListNode node) {
printIndentedTag(node, "ul");
}
public void visit(CodeNode node) {
printTag(node, "code");
}
public void visit(DefinitionListNode node) {
printIndentedTag(node, "dl");
}
public void visit(DefinitionNode node) {
printConditionallyIndentedTag(node, "dd");
}
public void visit(DefinitionTermNode node) {
printConditionallyIndentedTag(node, "dt");
}
public void visit(ExpImageNode node) {
String text = printChildrenToString(node);
printImageTag(linkRenderer.render(node, text));
}
public void visit(ExpLinkNode node) {
String text = printChildrenToString(node);
printLink(linkRenderer.render(node, text));
}
public void visit(HeaderNode node) {
printBreakBeforeTag(node, "h" + node.getLevel());
}
public void visit(HtmlBlockNode node) {
String text = node.getText();
if (text.length() > 0) {
printer.println();
}
printer.print(text);
}
public void visit(InlineHtmlNode node) {
printer.print(node.getText());
}
public void visit(ListItemNode node) {
if (node instanceof TaskListNode) {
// vsch: #185 handle GitHub style task list items, these are a bit messy because the <input> checkbox needs to be
// included inside the optional <p></p> first grand-child of the list item, first child is always RootNode
// because the list item text is recursively parsed.
Node firstChild = node.getChildren().get(0).getChildren().get(0);
boolean firstIsPara = firstChild instanceof ParaNode;
int indent = node.getChildren().size() > 1 ? 2 : 0;
boolean startWasNewLine = printer.endsWithNewLine();
printer.println().print("<li class=\"task-list-item\">").indent(indent);
if (firstIsPara) {
printer.println().print("<p>");
printer.print("<input type=\"checkbox\" class=\"task-list-item-checkbox\"" + (((TaskListNode) node).isDone() ? " checked=\"checked\"" : "") + " disabled=\"disabled\"></input>");
visitChildren((SuperNode) firstChild);
// render the other children, the p tag is taken care of here
visitChildrenSkipFirst(node);
printer.print("</p>");
} else {
printer.print("<input type=\"checkbox\" class=\"task-list-item-checkbox\"" + (((TaskListNode) node).isDone() ? " checked=\"checked\"" : "") + " disabled=\"disabled\"></input>");
visitChildren(node);
}
printer.indent(-indent).printchkln(indent != 0).print("</li>")
.printchkln(startWasNewLine);
} else {
printConditionallyIndentedTag(node, "li");
}
}
public void visit(MailLinkNode node) {
printLink(linkRenderer.render(node));
}
public void visit(OrderedListNode node) {
printIndentedTag(node, "ol");
}
public void visit(ParaNode node) {
printBreakBeforeTag(node, "p");
}
public void visit(QuotedNode node) {
switch (node.getType()) {
case DoubleAngle:
printer.print("«");
visitChildren(node);
printer.print("»");
break;
case Double:
printer.print("“");
visitChildren(node);
printer.print("”");
break;
case Single:
printer.print("‘");
visitChildren(node);
printer.print("’");
break;
}
}
public void visit(ReferenceNode node) {
// reference nodes are not printed
}
public void visit(RefImageNode node) {
String text = printChildrenToString(node);
String key = node.referenceKey != null ? printChildrenToString(node.referenceKey) : text;
ReferenceNode refNode = references.get(normalize(key));
if (refNode == null) { // "fake" reference image link
printer.print("![").print(text).print(']');
if (node.separatorSpace != null) {
printer.print(node.separatorSpace).print('[');
if (node.referenceKey != null) {
printer.print(key);
}
printer.print(']');
}
} else {
printImageTag(linkRenderer.render(node, refNode.getUrl(), refNode.getTitle(), text));
}
}
public void visit(RefLinkNode node) {
String text = printChildrenToString(node);
String key = node.referenceKey != null ? printChildrenToString(node.referenceKey) : text;
ReferenceNode refNode = references.get(normalize(key));
if (refNode == null) { // "fake" reference link
printer.print('[').print(text).print(']');
if (node.separatorSpace != null) {
printer.print(node.separatorSpace).print('[');
if (node.referenceKey != null) {
printer.print(key);
}
printer.print(']');
}
} else {
printLink(linkRenderer.render(node, refNode.getUrl(), refNode.getTitle(), text));
}
}
public void visit(SimpleNode node) {
switch (node.getType()) {
case Apostrophe:
printer.print("’");
break;
case Ellipsis:
printer.print("…");
break;
case Emdash:
printer.print("—");
break;
case Endash:
printer.print("–");
break;
case HRule:
printer.println().print("<hr/>");
break;
case Linebreak:
printer.print("<br/>");
break;
case Nbsp:
printer.print(" ");
break;
default:
throw new IllegalStateException();
}
}
public void visit(StrongEmphSuperNode node) {
if (node.isClosed()) {
if (node.isStrong()) {
printTag(node, "strong");
} else {
printTag(node, "em");
}
} else {
//sequence was not closed, treat open chars as ordinary chars
printer.print(node.getChars());
visitChildren(node);
}
}
public void visit(StrikeNode node) {
printTag(node, "del");
}
public void visit(TableBodyNode node) {
printIndentedTag(node, "tbody");
}
@Override
public void visit(TableCaptionNode node) {
printer.println().print("<caption>");
visitChildren(node);
printer.print("</caption>");
}
public void visit(TableCellNode node) {
String tag = inTableHeader ? "th" : "td";
List<TableColumnNode> columns = currentTableNode.getColumns();
TableColumnNode column = columns.get(Math.min(currentTableColumn, columns.size() - 1));
printer.println().print('<').print(tag);
column.accept(this);
if (node.getColSpan() > 1) {
printer.print(" colspan=\"").print(Integer.toString(node.getColSpan())).print('"');
}
printer.print('>');
visitChildren(node);
printer.print('<').print('/').print(tag).print('>');
currentTableColumn += node.getColSpan();
}
public void visit(TableColumnNode node) {
switch (node.getAlignment()) {
case None:
break;
case Left:
printer.print(" align=\"left\"");
break;
case Right:
printer.print(" align=\"right\"");
break;
case Center:
printer.print(" align=\"center\"");
break;
default:
throw new IllegalStateException();
}
}
public void visit(TableHeaderNode node) {
inTableHeader = true;
printIndentedTag(node, "thead");
inTableHeader = false;
}
public void visit(TableNode node) {
currentTableNode = node;
printIndentedTag(node, "table");
currentTableNode = null;
}
public void visit(TableRowNode node) {
currentTableColumn = 0;
printIndentedTag(node, "tr");
}
public void visit(VerbatimNode node) {
VerbatimSerializer serializer = lookupSerializer(node.getType());
serializer.serialize(node, printer);
}
protected VerbatimSerializer lookupSerializer(final String type) {
if (type != null && verbatimSerializers.containsKey(type)) {
return verbatimSerializers.get(type);
} else {
return verbatimSerializers.get(VerbatimSerializer.DEFAULT);
}
}
public void visit(WikiLinkNode node) {
printLink(linkRenderer.render(node));
}
public void visit(TextNode node) {
if (abbreviations.isEmpty()) {
printer.print(Pangu.spacingText(node.getText()));
} else {
printWithAbbreviations(node.getText());
}
}
public void visit(SpecialTextNode node) {
printer.printEncoded(node.getText());
}
public void visit(SuperNode node) {
visitChildren(node);
}
public void visit(Node node) {
for (ToHtmlSerializerPlugin plugin : plugins) {
if (plugin.visit(node, this, printer)) {
return;
}
}
// override this method for processing custom Node implementations
throw new RuntimeException("Don't know how to handle node " + node);
}
// helpers
protected void visitChildren(SuperNode node) {
for (Node child : node.getChildren()) {
child.accept(this);
}
}
// helpers
protected void visitChildrenSkipFirst(SuperNode node) {
boolean first = true;
for (Node child : node.getChildren()) {
if (!first) {
child.accept(this);
}
first = false;
}
}
protected void printTag(TextNode node, String tag) {
printer.print('<').print(tag).print('>');
printer.printEncoded(node.getText());
printer.print('<').print('/').print(tag).print('>');
}
protected void printTag(SuperNode node, String tag) {
printer.print('<').print(tag).print('>');
visitChildren(node);
printer.print('<').print('/').print(tag).print('>');
}
protected void printBreakBeforeTag(SuperNode node, String tag) {
boolean startWasNewLine = printer.endsWithNewLine();
printer.println();
printTag(node, tag);
if (startWasNewLine) {
printer.println();
}
}
protected void printIndentedTag(SuperNode node, String tag) {
printer.println().print('<').print(tag).print('>').indent(+2);
visitChildren(node);
printer.indent(-2).println().print('<').print('/').print(tag).print('>');
}
protected void printConditionallyIndentedTag(SuperNode node, String tag) {
if (node.getChildren().size() > 1) {
printer.println().print('<').print(tag).print('>').indent(+2);
visitChildren(node);
printer.indent(-2).println().print('<').print('/').print(tag).print('>');
} else {
boolean startWasNewLine = printer.endsWithNewLine();
printer.println().print('<').print(tag).print('>');
visitChildren(node);
printer.print('<').print('/').print(tag).print('>').printchkln(startWasNewLine);
}
}
protected void printImageTag(LinkRenderer.Rendering rendering) {
printer.print("<img");
printAttribute("src", rendering.href);
// shouldn't include the alt attribute if its empty
if (!rendering.text.equals("")) {
printAttribute("alt", rendering.text);
}
for (LinkRenderer.Attribute attr : rendering.attributes) {
printAttribute(attr.name, attr.value);
}
printer.print(" />");
}
protected void printLink(LinkRenderer.Rendering rendering) {
printer.print('<').print('a');
printAttribute("href", rendering.href);
for (LinkRenderer.Attribute attr : rendering.attributes) {
printAttribute(attr.name, attr.value);
}
printer.print('>').print(rendering.text).print("</a>");
}
protected void printAttribute(String name, String value) {
printer.print(' ').print(name).print('=').print('"').print(value).print('"');
}
protected String printChildrenToString(SuperNode node) {
Printer priorPrinter = printer;
printer = new Printer();
visitChildren(node);
String result = printer.getString();
printer = priorPrinter;
return result;
}
protected String normalize(String string) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
switch (c) {
case ' ':
case '\n':
case '\t':
continue;
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
protected void printWithAbbreviations(String string) {
Map<Integer, Map.Entry<String, String>> expansions = null;
for (Map.Entry<String, String> entry : abbreviations.entrySet()) {
String abbr = entry.getKey();
int ix = 0;
while (true) {
int sx = string.indexOf(abbr, ix);
if (sx == -1) {
break;
}
// only allow whole word matches
ix = sx + abbr.length();
if (sx > 0 && Character.isLetterOrDigit(string.charAt(sx - 1))) {
continue;
}
if (ix < string.length() && Character.isLetterOrDigit(string.charAt(ix))) {
continue;
}
if (expansions == null) {
expansions = new TreeMap<Integer, Map.Entry<String, String>>();
}
expansions.put(sx, entry);
}
}
if (expansions != null) {
int ix = 0;
for (Map.Entry<Integer, Map.Entry<String, String>> entry : expansions.entrySet()) {
int sx = entry.getKey();
String abbr = entry.getValue().getKey();
String expansion = entry.getValue().getValue();
printer.printEncoded(string.substring(ix, sx));
printer.print("<abbr");
if (org.parboiled.common.StringUtils.isNotEmpty(expansion)) {
printer.print(" title=\"");
printer.printEncoded(expansion);
printer.print('"');
}
printer.print('>');
printer.printEncoded(abbr);
printer.print("</abbr>");
ix = sx + abbr.length();
}
printer.print(string.substring(ix));
} else {
printer.print(string);
}
}
}
}
|
package edu.wustl.common.query.impl;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import edu.common.dynamicextensions.domaininterface.TaggedValueInterface;
import edu.common.dynamicextensions.exception.DataTypeFactoryInitializationException;
import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException;
import edu.wustl.common.query.impl.predicate.AbstractPredicate;
import edu.wustl.common.query.impl.predicate.PredicateGenerator;
import edu.wustl.common.query.impl.predicate.Predicates;
import edu.wustl.common.querysuite.exceptions.MultipleRootsException;
import edu.wustl.common.querysuite.queryobject.IExpression;
import edu.wustl.common.querysuite.queryobject.IOutputAttribute;
import edu.wustl.query.util.global.Constants;
import edu.wustl.query.util.global.Utility;
/**
* @author juberahamad_patel
*
*/
public class PassOneXQueryGenerator extends AbstractXQueryGenerator
{
/**
* map of for variables and corresponding expressions created in pass one xquery
*/
private Map<IExpression, String> passOneForVariables;
public PassOneXQueryGenerator()
{
passOneForVariables = new LinkedHashMap<IExpression, String>();
}
/**
* build the for clause of xquery
* @param predicateGenerator
* @return the For Clause of XQuery
* @throws MultipleRootsException
* @throws DynamicExtensionsSystemException
*/
@Override
protected String buildXQueryForClause(PredicateGenerator predicateGenerator)
throws MultipleRootsException, DynamicExtensionsSystemException
{
StringBuilder xqueryForClause = new StringBuilder(1024);
setPassOneForVariables();
for (IExpression expression : getMainExpressions())
{
StringBuilder laterPart = new StringBuilder(1024);
String tableName = expression.getQueryEntity().getDynamicExtensionsEntity()
.getTableProperties().getName();
StringBuilder rootPath = new StringBuilder().append(Constants.QUERY_XMLCOLUMN).append(
Constants.QUERY_OPENING_PARENTHESIS).append("\"").append(tableName).append(
Constants.QUERY_DOT).append(Constants.QUERY_XMLDATA).append("\"").append(
Constants.QUERY_CLOSING_PARENTHESIS);
String variable = appendChildren(expression, predicateGenerator, laterPart);
xqueryForClause.append(Constants.QUERY_FOR).append(variable).append(' ').append(
Constants.IN).append(' ').append(rootPath.toString()).append(
laterPart.toString());
}
return xqueryForClause.toString();
}
/**
* set the for variables used in pass one xquery
* the assumption is that pass one for variables are present among general for variables
*/
private void setPassOneForVariables()
{
for (IExpression expression : getForVariables().keySet())
{
if (hasVersion(expression))
{
String variable = getForVariables().get(expression);
passOneForVariables.put(expression, variable);
}
}
}
/**
* append xquery fragments in the for clause for given expression
* and its children recursively
* @param expression
* @param predicateGenerator
* @param laterPart
* @return
*/
private String appendChildren(IExpression expression, PredicateGenerator predicateGenerator,
StringBuilder laterPart)
{
String variable = "";
String targetRole = getTargetRoles().get(expression);
if (targetRole != null)
{
laterPart.append('/').append(targetRole);
}
String entityName = expression.getQueryEntity().getDynamicExtensionsEntity().getName();
if (!getMainExpressions().contains(expression))
{
entityName = deCapitalize(entityName);
}
if (getMainExpressions().contains(expression))
{
laterPart.append('/').append(entityName);
}
if (hasVersion(expression))
{
laterPart.append('/').append(entityName);
String localPredicates = getAllDownstreamPredicates(predicateGenerator, expression, "");
laterPart.append('[').append(localPredicates).append(']');
variable = passOneForVariables.get(expression);
}
else
{
Predicates predicates = predicateGenerator.getPredicates(expression);
if (predicates != null)
{
replaceRhsForVariables(predicates);
laterPart.append('[').append(predicates.assemble()).append(']');
}
List<IExpression> children = getNonMainNonEmptyChildren(expression);
for (IExpression child : children)
{
IExpression firstChild = child;
variable = appendChildren(firstChild, predicateGenerator, laterPart);
}
}
return variable;
}
/**
* build the right paths for all the predicates of given expression
* and all its children relative to the expression, recursively
* @param predicateGenerator
* @param expression
* @param prefix
* @return
*/
private String getAllDownstreamPredicates(PredicateGenerator predicateGenerator,
IExpression expression, String prefix)
{
StringBuilder downStreamPredicates = new StringBuilder();
Predicates localPredicates = predicateGenerator.getPredicates(expression);
if (localPredicates == null)
{
return "";
}
replaceRhsForVariables(localPredicates);
downStreamPredicates.append(localPredicates.assemble(prefix)).append(Constants.QUERY_AND);
List<IExpression> children = getNonMainNonEmptyChildren(expression);
//end recursion
if (children.isEmpty())
{
return Utility.removeLastAnd(downStreamPredicates.toString());
}
for (IExpression child : children)
{
//skip children that do not have for variables
if (!getForVariables().containsKey(child))
{
continue;
}
String targetRole = getTargetRoles().get(child);
String entityName = deCapitalize(child.getQueryEntity().getDynamicExtensionsEntity()
.getName());
StringBuilder newPrefix = new StringBuilder(prefix);
if (targetRole != null)
{
newPrefix.append(targetRole).append('/');
}
newPrefix.append(entityName).append('/');
downStreamPredicates.append(
getAllDownstreamPredicates(predicateGenerator, child, newPrefix.toString()))
.append(Constants.QUERY_AND);
}
return Utility.removeLastAnd(downStreamPredicates.toString());
}
/**
* build the let clause
*/
@Override
protected String buildXQueryLetClause(PredicateGenerator predicateGenerator)
{
StringBuilder xqueryLetClause = new StringBuilder();
xqueryLetClause.append(Constants.QUERY_LET);
for (Entry<IOutputAttribute, String> entry : getAttributeAliases().entrySet())
{
xqueryLetClause.append(Constants.QUERY_DOLLAR).append(entry.getValue()).append(" := ");
IExpression expression = entry.getKey().getExpression();
//traverse down the hierarchy of the expression to find an expresssion which is in passOneForVariables
//this could also be theoratically up the hierarchy but not in our xmls
StringBuilder relativePath = new StringBuilder();
while (true)
{
if (passOneForVariables.containsKey(expression))
{
xqueryLetClause.append(passOneForVariables.get(expression)).append('/');
xqueryLetClause.append(relativePath.toString()).append(
entry.getKey().getAttribute().getName()).append(Constants.QUERY_COMMA);
break;
}
expression = getNonMainNonEmptyChildren(expression).get(0);
//additional "../" for entities having target role eg. demographicsCollection
if (getTargetRoles().containsKey(expression))
{
relativePath.append("../");
}
relativePath.append("../");
}
}
Utility.removeLastComma(xqueryLetClause);
return xqueryLetClause.toString();
}
/**
*
* @return the Return Clause of SQLXML
*/
@Override
protected String buildXQueryReturnClause()
{
StringBuilder xqueryReturnClause = new StringBuilder(Constants.QUERY_RETURN);
xqueryReturnClause.append("<return>");
for (String attributeAlias : getAttributeAliases().values())
{
xqueryReturnClause.append('<').append(attributeAlias).append('>');
xqueryReturnClause.append('{').append(Constants.QUERY_DOLLAR).append(attributeAlias)
.append('}');
xqueryReturnClause.append("</").append(attributeAlias).append('>');
}
xqueryReturnClause.append("</return>");
return xqueryReturnClause.toString();
}
/**
*
* @return Columns part of SQLXML
* @throws DataTypeFactoryInitializationException
*/
@Override
protected String buildColumnsPart() throws DataTypeFactoryInitializationException
{
StringBuilder columnsPart = new StringBuilder(512);
columnsPart.append(" columns ");
for (Entry<IOutputAttribute, String> entry : getAttributeAliases().entrySet())
{
String attributeAlias = entry.getValue();
String dataType = getDataTypeInformation(entry.getKey().getAttribute());
columnsPart.append(attributeAlias).append(' ').append(dataType).append(" path '")
.append(attributeAlias).append("'").append(Constants.QUERY_COMMA);
}
Utility.removeLastComma(columnsPart);
return columnsPart.toString();
}
/**
* build the 'passing' clause
*/
@Override
protected String buildPassingPart()
{
return "";
}
/**
* replace the RHS for variables in (eg. in joining conditions) in each predicate with
* a valid pass one for variable
*
*/
private void replaceRhsForVariables(Predicates predicates)
{
List<AbstractPredicate> predicateList = predicates.getPredicates();
for (AbstractPredicate predicate : predicateList)
{
String rhs = predicate.getRhs();
rhs = replaceRhsForVariable(rhs);
predicate.setRhs(rhs);
}
}
/**
* replace the for variable in the rhs with appropriate pass one for variable.
* the old for variable is replaced with an xpath expression involving an exisiting
* pass one for variable
*
* @param rhs
* @return
*/
private String replaceRhsForVariable(String rhs)
{
String newRhs = null;
//return unchanegd
if (rhs == null || !rhs.startsWith(String.valueOf(Constants.QUERY_DOLLAR)))
{
newRhs = rhs;
}
else
{
String forVariable = rhs.substring(0, rhs.indexOf('/'));
String attribute = rhs.substring(rhs.indexOf('/') + 1);
//return unchanged
if (passOneForVariables.containsValue(forVariable))
{
newRhs = rhs;
}
else
{
//traverse down the hierarchy of the expression to find an expresssion which is in passOneForVariables
//this could also be theoratically up the hierarchy but not in our xmls
IExpression expression = null;
StringBuilder relativePath = new StringBuilder();
StringBuilder path = new StringBuilder();
//find the expression corresponding to the for variable
for (Entry<IExpression, String> entry : getForVariables().entrySet())
{
if (forVariable.equals(entry.getValue()))
{
expression = entry.getKey();
break;
}
}
//build the relative path and the complete replacement of for variable
while (true)
{
if (passOneForVariables.containsValue(forVariable))
{
path.append(forVariable).append('/');
path.append(relativePath.toString());
path.append(attribute);
newRhs = path.toString();
break;
}
expression = getNonMainNonEmptyChildren(expression).get(0);
forVariable = getForVariables().get(expression);
//additional "../" for entities having target role eg. demographicsCollection
if (getTargetRoles().containsKey(expression))
{
relativePath.append("../");
}
relativePath.append("../");
}
}
}
return newRhs;
}
/**
* decide whether the given expression has a version tagged value
* associated with it
* @param expression
* @return
*/
public boolean hasVersion(IExpression expression)
{
Collection<TaggedValueInterface> taggedValues = expression.getQueryEntity()
.getDynamicExtensionsEntity().getTaggedValueCollection();
for (TaggedValueInterface taggedValue : taggedValues)
{
if (taggedValue.getKey().equalsIgnoreCase(Constants.VERSION))
{
return true;
}
}
return false;
}
@Override
protected String buildXQueryWhereClause(PredicateGenerator predicateGenerator)
{
String xQueryWherePart = predicateGenerator.getXQueryWherePart();
if (xQueryWherePart == null)
{
return "";
}
else
{
return new StringBuilder(Constants.WHERE).append(xQueryWherePart).toString();
}
}
}
|
package org.cactoos.io;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.cactoos.Scalar;
import org.cactoos.Text;
import org.cactoos.scalar.IoCheckedScalar;
import org.cactoos.scalar.StickyScalar;
import org.cactoos.text.JoinedText;
import org.cactoos.text.RandomText;
import org.cactoos.text.TextOf;
/**
* A temporary folder.
* This is ephemeral folder to be used in small scopes.
* The physical folder is deleted from the filesystem when the temp folder is
* closed.
* @since 1.0
*/
public final class TempFolder implements Scalar<Path>, Closeable {
/**
* Creates the temporary folder, returning its path.
*/
private final Scalar<Path> folder;
/**
* Ctor.
* Creates new folder in temporary directory
* with a random name.
* @since 1.0
*/
public TempFolder() {
this(
new JoinedText(
new TextOf(""),
new TextOf("tmp"),
new RandomText(
// @checkstyle MagicNumber (1 line)
5,
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z'
)
)
);
}
/**
* Ctor.
* Creates new folder in temporary directory.
* @param path Relative path to new directory.
* @since 1.0
*/
public TempFolder(final String path) {
this(new TextOf(path));
}
/**
* Ctor.
* Creates new folder in temporary directory.
* @param path Relative path to new directory.
* @since 1.0
*/
public TempFolder(final Text path) {
this(
new StickyScalar<>(
() -> Files.createDirectory(
Paths.get(
new JoinedText(
File.separator,
System.getProperty("java.io.tmpdir"),
path.asString()
).asString()
)
)
)
);
}
/**
* Primary ctor.
* @param flr Creates the folder and returns the path to it
* @since 1.0
*/
private TempFolder(final Scalar<Path> flr) {
this.folder = flr;
}
@Override
public Path value() throws Exception {
return this.folder.value();
}
@Override
public void close() throws IOException {
Files.delete(new IoCheckedScalar<>(this).value());
}
}
|
package com.exedio.cope;
import com.exedio.cope.testmodel.PointerItem;
import com.exedio.cope.testmodel.PointerItem2;
public class JoinOuterTest extends TestmodelTest
{
PointerItem leftJoined;
PointerItem leftLonely;
PointerItem2 rightJoined;
PointerItem2 rightLonely;
protected void setUp() throws Exception
{
super.setUp();
deleteOnTearDown(rightLonely = new PointerItem2("right"));
deleteOnTearDown(rightJoined = new PointerItem2("joined"));
deleteOnTearDown(leftJoined = new PointerItem("joined", rightJoined));
deleteOnTearDown(leftLonely = new PointerItem("left", rightJoined));
}
public void testJoin()
{
{
final Query query = new Query(PointerItem.TYPE, null);
query.join(PointerItem2.TYPE, Cope.equal(PointerItem.code, PointerItem2.code));
assertContains(leftJoined, query.search());
}
{
final Query query = new Query(PointerItem.TYPE, null);
query.joinOuterLeft(PointerItem2.TYPE, Cope.equal(PointerItem.code, PointerItem2.code));
assertContains(leftJoined, leftLonely, query.search());
}
{
final Query query = new Query(PointerItem.TYPE, null);
query.joinOuterRight(PointerItem2.TYPE, Cope.equal(PointerItem.code, PointerItem2.code));
if(hsqldb)
{
try
{
query.search();
fail("should have thrown RuntimeException");
}
catch(RuntimeException e)
{
assertEquals("hsqldb not support right outer joins", e.getMessage());
}
}
else
{
assertContains(leftJoined, null, query.search());
}
}
}
}
|
package au.edu.uts.eng.remotelabs.schedserver.session.impl;
import java.util.Date;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.Restrictions;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.DataAccessActivator;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.ResourcePermission;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.Session;
import au.edu.uts.eng.remotelabs.schedserver.logger.Logger;
import au.edu.uts.eng.remotelabs.schedserver.logger.LoggerActivator;
import au.edu.uts.eng.remotelabs.schedserver.queuer.QueueInfo;
/**
* Either expires or extends the time of all sessions which are close to
* the session duration duration.
*/
public class SessionExpiryChecker implements Runnable
{
/** Logger. */
private Logger logger;
/** Flag to specify if this is a test run. */
private boolean notTest = true;
public SessionExpiryChecker()
{
this.logger = LoggerActivator.getLogger();
}
@SuppressWarnings("unchecked")
@Override
public void run()
{
org.hibernate.Session db = null;
try
{
db = DataAccessActivator.getNewSession();
boolean kicked = false;
if (db == null)
{
this.logger.warn("Unable to obtain a database session, for rig session status checker. Ensure the " +
"SchedulingServer-DataAccess bundle is installed and active.");
return;
}
Criteria query = db.createCriteria(Session.class);
query.add(Restrictions.eq("active", Boolean.TRUE))
.add(Restrictions.isNotNull("assignmentTime"));
Date now = new Date();
List<Session> sessions = query.list();
for (Session ses : sessions)
{
ResourcePermission perm = ses.getResourcePermission();
int remaining = perm.getSessionDuration() + // The allowed session time
(perm.getAllowedExtensions() - ses.getExtensions()) * perm.getExtensionDuration() - // Extension time
Math.round((System.currentTimeMillis() - ses.getAssignmentTime().getTime()) / 1000); // In session time
if (ses.isInGrace())
{
if (remaining <= 0)
{
ses.setActive(false);
ses.setRemovalTime(now);
db.beginTransaction();
db.flush();
db.getTransaction().commit();
this.logger.info("Terminating session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
ses.getAssignedRigName() + " because it is expired and the grace period has elapsed.");
if (this.notTest) new RigReleaser().release(ses, db);
}
}
else if (remaining < ses.getRig().getRigType().getLogoffGraceDuration())
{
/* Need to make a decision whether to extend time or set for termination. */
if (ses.getExtensions() == 0)
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and cannot be extended. Marking " +
"session for expiry and giving a grace period.");
ses.setInGrace(true);
ses.setRemovalReason("No more session time extensions.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Notification warning. */
if (this.notTest) new RigNotifier().notify("Your session will expire in " + remaining + " seconds. " +
"Please finish and exit.", ses, db);
}
else if (QueueInfo.isQueued(ses.getRig(), db))
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and the rig is queued. Marking " +
"session for expiry and giving a grace period.");
ses.setInGrace(true);
ses.setRemovalReason("Rig is queued.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
/* Notification warning. */
if (this.notTest) new RigNotifier().notify("Your session will end in " + remaining + " seconds. " +
"After this you be removed, so please logoff.", ses, db);
}
else
{
this.logger.info("Session for " + ses.getUserNamespace() + ':' + ses.getUserName() + " on " +
"rig " + ses.getAssignedRigName() + " is expired and is having its session time extended.");
ses.setExtensions((short)(ses.getExtensions() - 1));
db.beginTransaction();
db.flush();
db.getTransaction().commit();
}
}
/* DODGY The 'kicked' flag is to only allow a single kick per
* pass. This is allow time for the rig to be released and take the
* queued session. This is a hack at best, but should be addressed
* by a released - cleaning up meta state. */
else if (!kicked && QueueInfo.isQueued(ses.getRig(), db) && perm.getUserClass().isKickable())
{
kicked = true;
/* No grace is being given. */
this.logger.info("A kickable user is using a rig that is queued for, so they are being removed.");
ses.setActive(false);
ses.setRemovalTime(now);
ses.setRemovalReason("Resource was queued and user was kickable.");
db.beginTransaction();
db.flush();
db.getTransaction().commit();
if (this.notTest) new RigReleaser().release(ses, db);
}
else if ((System.currentTimeMillis() - ses.getActivityLastUpdated().getTime()) / 1000 > perm.getSessionActivityTimeout())
{
/* Check activity. */
if (this.notTest) new SessionIdleKicker().kickIfIdle(ses, db);
}
}
}
catch (HibernateException hex)
{
this.logger.error("Failed to query database to expired sessions (Exception: " +
hex.getClass().getName() + ", Message:" + hex.getMessage() + ").");
if (db != null && db.getTransaction() != null)
{
try
{
db.getTransaction().rollback();
}
catch (HibernateException ex)
{
this.logger.error("Exception rolling back up session expiry transaction (Exception: " +
ex.getClass().getName() + "," + " Message: " + ex.getMessage() + ").");
}
}
}
finally
{
try
{
if (db != null) db.close();
}
catch (HibernateException ex)
{
this.logger.error("Exception cleaning up database session (Exception: " + ex.getClass().getName() + "," +
" Message: " + ex.getMessage() + ").");
}
}
}
}
|
package org.deri.tarql;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Map.Entry;
import org.apache.jena.atlas.io.IndentedWriter;
import org.apache.jena.graph.Triple;
import org.apache.jena.riot.system.StreamOps;
import org.apache.jena.riot.system.StreamRDF;
import org.apache.jena.riot.writer.WriterStreamRDFBlocks;
import org.apache.jena.riot.writer.WriterStreamRDFPlain;
import org.apache.jena.shared.PrefixMapping;
import org.apache.jena.shared.impl.PrefixMappingImpl;
import org.apache.jena.vocabulary.RDF;
/**
* Writes an iterator over triples to N-Triples or Turtle
* in a streaming fashion, that is, without needing to hold
* the entire thing in memory.
* <p>
* Instances are single-use.
* <p>
* There doesn't seem to be a pre-packaged version of this
* functionality in Jena/ARQ that doesn't require a Graph or Model.
*/
public class StreamingRDFWriter {
private final OutputStream out;
private final Iterator<Triple> triples;
public StreamingRDFWriter(OutputStream out, Iterator<Triple> triples) {
this.out = out;
this.triples = triples;
}
public void writeNTriples() {
StreamRDF writer = new WriterStreamRDFPlain(new IndentedWriter(out));
writer.start();
StreamOps.sendTriplesToStream(triples, writer);
writer.finish();
}
public void writeTurtle(String baseIRI, PrefixMapping prefixes) {
// Auto-register RDF prefix so that rdf:type is displayed well
// All other prefixes come from the query and should be as author intended
prefixes = ensureRDFPrefix(prefixes);
WriterStreamRDFBlocks writer = new WriterStreamRDFBlocks(out);
writer.start();
writer.base(baseIRI);
for (Entry<String, String> e : prefixes.getNsPrefixMap().entrySet()) {
writer.prefix(e.getKey(), e.getValue());
}
StreamOps.sendTriplesToStream(triples, writer);
writer.finish();
}
private PrefixMapping ensureRDFPrefix(PrefixMapping prefixes) {
// Some prefix already registered for the RDF namespace -- good enough
if (prefixes.getNsURIPrefix(RDF.getURI()) != null) return prefixes;
// rdf: is registered to something else -- give up
if (prefixes.getNsPrefixURI("rdf") == null) return prefixes;
// Register rdf:
PrefixMapping newPrefixes = new PrefixMappingImpl();
newPrefixes.setNsPrefixes(prefixes);
newPrefixes.setNsPrefix("rdf", RDF.getURI());
return newPrefixes;
}
}
|
package org.cryptonit.cloud;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import static org.cryptonit.cloud.Service.WEBAPP_RESOURCES_LOCATION;
/**
* @author Mathias Brossard
*/
@Path("")
public class Index {
@GET
public Response index() throws URISyntaxException {
URI uri = Thread.currentThread().getContextClassLoader().getResource(WEBAPP_RESOURCES_LOCATION + "/index.html").toURI();
return Response.ok(new File(uri), MediaType.TEXT_HTML).build();
}
}
|
package org.dungeon.entity.creatures;
import static org.dungeon.date.DungeonTimeUnit.HOUR;
import static org.dungeon.date.DungeonTimeUnit.SECOND;
import org.dungeon.achievements.AchievementTracker;
import org.dungeon.commands.IssuedCommand;
import org.dungeon.date.Date;
import org.dungeon.date.Period;
import org.dungeon.entity.Entity;
import org.dungeon.entity.items.BaseInventory;
import org.dungeon.entity.items.BookComponent;
import org.dungeon.entity.items.CreatureInventory.SimulationResult;
import org.dungeon.entity.items.FoodComponent;
import org.dungeon.entity.items.Item;
import org.dungeon.game.Direction;
import org.dungeon.game.Engine;
import org.dungeon.game.Game;
import org.dungeon.game.GameData;
import org.dungeon.game.ID;
import org.dungeon.game.Location;
import org.dungeon.game.Name;
import org.dungeon.game.PartOfDay;
import org.dungeon.game.Point;
import org.dungeon.game.QuantificationMode;
import org.dungeon.game.Random;
import org.dungeon.game.World;
import org.dungeon.io.IO;
import org.dungeon.io.Sleeper;
import org.dungeon.skill.Skill;
import org.dungeon.stats.ExplorationStatistics;
import org.dungeon.util.CounterMap;
import org.dungeon.util.Matches;
import org.dungeon.util.Messenger;
import org.dungeon.util.Percentage;
import org.dungeon.util.Selectable;
import org.dungeon.util.Utils;
import org.jetbrains.annotations.NotNull;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
/**
* Hero class that defines the creature that the player controls.
*/
public class Hero extends Creature {
// The longest possible sleep starts at 19:00 and ends at 05:15 (takes 10 hours and 15 minutes).
// It seems a good idea to let the Hero have one dream every 4 hours.
private static final long DREAM_DURATION_IN_SECONDS = 4 * HOUR.as(SECOND);
private static final int MILLISECONDS_TO_SLEEP_AN_HOUR = 500;
private static final int SECONDS_TO_PICK_UP_AN_ITEM = 10;
private static final int SECONDS_TO_DESTROY_AN_ITEM = 120;
private static final int SECONDS_TO_EAT_AN_ITEM = 30;
private static final int SECONDS_TO_DROP_AN_ITEM = 2;
private static final int SECONDS_TO_UNEQUIP = 4;
private static final int SECONDS_TO_EQUIP = 6;
private static final int SECONDS_TO_MILK_A_CREATURE = 45;
private static final int SECONDS_TO_READ_EQUIPPED_CLOCK = 4;
private static final int SECONDS_TO_READ_UNEQUIPPED_CLOCK = 10;
private static final String ROTATION_SKILL_SEPARATOR = ">";
private static final Percentage LUMINOSITY_TO_SEE_ADJACENT_LOCATIONS = new Percentage(0.4);
private static final int BATTLE_TURN_DURATION = 30;
private static final int HEAL_TEN_PERCENT = 3600;
private static final int MILK_NUTRITION = 12;
private final AchievementTracker achievementTracker = new AchievementTracker();
private final Date dateOfBirth;
Hero(CreaturePreset preset) {
super(preset);
dateOfBirth = new Date(432, 6, 4, 8, 30, 0);
}
public AchievementTracker getAchievementTracker() {
return achievementTracker;
}
/**
* Increments the Hero's health by a certain amount, without exceeding its maximum health.
* If at the end the Hero is completely healed, a messaging about this is written.
*/
private void addHealth(int amount) {
int sum = amount + getCurHealth();
if (sum >= getMaxHealth()) {
setCurHealth(getMaxHealth());
IO.writeString("You are completely healed.");
} else {
setCurHealth(sum);
}
}
/**
* Checks if the Hero is completely healed.
*/
private boolean isCompletelyHealed() {
return getMaxHealth() == getCurHealth();
}
/**
* Rest until the creature is healed to 60% of its health points.
* <p/>
*
* @return the number of seconds the hero rested.
*/
public int rest() {
final double healthFractionThroughRest = 0.6;
if (getCurHealth() >= (int) (healthFractionThroughRest * getMaxHealth())) {
IO.writeString("You are already rested.");
return 0;
} else {
double fractionHealed = healthFractionThroughRest - (double) getCurHealth() / (double) getMaxHealth();
IO.writeString("Resting...");
setCurHealth((int) (healthFractionThroughRest * getMaxHealth()));
IO.writeString("You feel rested.");
return (int) (HEAL_TEN_PERCENT * fractionHealed * 10);
}
}
/**
* Sleep until the sun rises.
* <p/>
* Depending on how much the Hero will sleep, this method may print a few dreams.
*
* @return the number of seconds the hero slept.
*/
public int sleep() {
int seconds = 0;
World world = getLocation().getWorld();
PartOfDay pod = world.getPartOfDay();
if (pod == PartOfDay.EVENING || pod == PartOfDay.MIDNIGHT || pod == PartOfDay.NIGHT) {
IO.writeString("You fall asleep.");
seconds = PartOfDay.getSecondsToNext(world.getWorldDate(), PartOfDay.DAWN);
// In order to increase realism, add up to 15 minutes to the time it would take to wake up exactly at dawn.
seconds += Random.nextInteger(15 * 60 + 1);
int healing = getMaxHealth() * seconds / HEAL_TEN_PERCENT / 10;
if (!isCompletelyHealed()) {
int health = getCurHealth() + healing;
if (health < getMaxHealth()) {
setCurHealth(health);
} else {
setCurHealth(getMaxHealth());
}
}
// Make a copy of seconds as it must be returned unaltered so that the Engine rolls time forwards correctly.
int remainingSeconds = seconds;
while (remainingSeconds > 0) {
if (remainingSeconds > DREAM_DURATION_IN_SECONDS) {
Sleeper.sleep(MILLISECONDS_TO_SLEEP_AN_HOUR * DREAM_DURATION_IN_SECONDS / HOUR.as(SECOND));
IO.writeString(GameData.getDreamLibrary().getNextDream());
remainingSeconds -= DREAM_DURATION_IN_SECONDS;
} else {
Sleeper.sleep(MILLISECONDS_TO_SLEEP_AN_HOUR * remainingSeconds / HOUR.as(SECOND));
break;
}
}
IO.writeString("You wake up.");
} else {
IO.writeString("You can only sleep at night.");
}
return seconds;
}
/**
* Checks if the Hero can see a given Entity based on the luminosity of the Location the Hero is in and on the
* visibility of the specified Entity.
*/
private boolean canSee(Entity entity) {
return entity.getVisibility().visibleUnder(getLocation().getLuminosity());
}
/**
* Checks if the Hero is able to see any Creature other than himself or herself at the current Location.
*
* @return true if the Hero is able to see any Creature other than himself or herself at the current Location
*/
private boolean canSeeACreature() {
for (Creature creature : getLocation().getCreatures()) {
if (creature != this && canSee(creature)) {
return true;
}
}
return false;
}
/**
* Convenience method that avoids code duplication.
* Returns whether the Hero can see a Creature, writing a warning if he or she can't.
*/
private boolean canSeeACreatureWarnIfNot() {
if (canSeeACreature()) {
return true;
} else {
IO.writeString("You do not see a possible target.");
return false;
}
}
/**
* Returns whether any Item of the current Location is visible to the Hero.
*/
private boolean canSeeAnItem() {
for (Item item : getLocation().getItemList()) {
if (canSee(item)) {
return true;
}
}
return false;
}
private boolean canSeeAdjacentLocations() {
return getLocation().getLuminosity().biggerThanOrEqualTo(LUMINOSITY_TO_SEE_ADJACENT_LOCATIONS);
}
private <T extends Entity> List<T> filterByVisibility(List<T> list) {
List<T> visible = new ArrayList<T>();
for (T entity : list) {
if (canSee(entity)) {
visible.add(entity);
}
}
return visible;
}
private <T extends Entity> Matches<T> filterByVisibility(Matches<T> matches) {
return Matches.fromCollection(filterByVisibility(matches.toList()));
}
/**
* Filters a List of Creatures, returning all that have a specified Tag.
*/
private List<Creature> filterByTag(List<Creature> list, Creature.Tag tag) {
List<Creature> visible = new ArrayList<Creature>();
for (Creature candidate : list) {
if (candidate.hasTag(tag)) {
visible.add(candidate);
}
}
return visible;
}
/**
* Prints the name of the player's current location and lists all creatures and items the character sees.
*
* @param walkedInFrom the Direction from which the Hero walked in. {@code null} if the Hero did not walk.
*/
public void look(Direction walkedInFrom) {
Location location = getLocation(); // Avoid multiple calls to the getter.
String description;
if (walkedInFrom != null) {
description = "You arrive at " + location.getName() + ".";
} else {
description = "You are at " + location.getName() + ".";
}
description += " " + location.getDescription().getInfo();
description += " " + "It is " + location.getWorld().getPartOfDay().toString().toLowerCase() + ".";
IO.writeString(description);
lookAdjacentLocations(walkedInFrom);
lookCreatures();
lookItems();
}
/**
* Looks to the Locations adjacent to the one the Hero is in, informing if the Hero cannot see the adjacent Locations.
*
* @param walkedInFrom the Direction from which the Hero walked in. {@code null} if the Hero did not walk.
*/
private void lookAdjacentLocations(Direction walkedInFrom) {
IO.writeNewLine();
if (!canSeeAdjacentLocations()) {
IO.writeString("You can't clearly see the surrounding locations.");
return;
}
World world = Game.getGameState().getWorld();
Point pos = Game.getGameState().getHeroPosition();
HashMap<String, ArrayList<Direction>> visibleLocations = new HashMap<String, ArrayList<Direction>>();
Collection<Direction> directions = Direction.getAllExcept(walkedInFrom); // Don't print the Location you just left.
for (Direction dir : directions) {
Point adjacentPoint = new Point(pos, dir);
Location adjacentLocation = world.getLocation(adjacentPoint);
ExplorationStatistics explorationStatistics = Game.getGameState().getStatistics().getExplorationStatistics();
explorationStatistics.createEntryIfNotExists(adjacentPoint, adjacentLocation.getID());
String locationName = adjacentLocation.getName().getSingular();
if (!visibleLocations.containsKey(locationName)) {
visibleLocations.put(locationName, new ArrayList<Direction>());
}
visibleLocations.get(locationName).add(dir);
}
StringBuilder stringBuilder = new StringBuilder();
for (Entry<String, ArrayList<Direction>> entry : visibleLocations.entrySet()) {
stringBuilder.append(String.format("To %s you see %s.\n", Utils.enumerate(entry.getValue()), entry.getKey()));
}
IO.writeString(stringBuilder.toString());
}
/**
* Prints a human-readable description of what Creatures the Hero sees.
*/
private void lookCreatures() {
List<Creature> creatures = new ArrayList<Creature>(getLocation().getCreatures());
creatures.remove(this);
creatures = filterByVisibility(creatures);
IO.writeNewLine();
if (creatures.isEmpty()) {
IO.writeString("You don't see anyone here.");
} else {
IO.writeString("Here you can see " + enumerateEntities(creatures) + ".");
}
}
/**
* Prints a human-readable description of what the Hero sees on the ground.
*/
private void lookItems() {
List<Item> items = getLocation().getItemList();
items = filterByVisibility(items);
if (!items.isEmpty()) {
IO.writeNewLine();
IO.writeString("On the ground you see " + enumerateEntities(items) + ".");
}
}
/**
* Returns a String representation of the enumeration of all the Entities in a given List.
*/
private String enumerateEntities(final List<? extends Entity> listOfEntities) {
CounterMap<Name> nameOccurrences = new CounterMap<Name>();
for (Entity entity : listOfEntities) {
nameOccurrences.incrementCounter(entity.getName());
}
ArrayList<String> quantifiedNames = new ArrayList<String>();
for (Name name : nameOccurrences.keySet()) {
quantifiedNames.add(name.getQuantifiedName(nameOccurrences.getCounter(name)));
}
return Utils.enumerate(quantifiedNames);
}
private Item selectInventoryItem(IssuedCommand issuedCommand) {
if (getInventory().getItemCount() == 0) {
IO.writeString("Your inventory is empty.");
return null;
} else {
return selectItem(issuedCommand, getInventory(), false);
}
}
/**
* Select an item of the current location based on the arguments of a command.
*
* @param issuedCommand an IssuedCommand object whose arguments will determine the item search
* @return an Item or {@code null}
*/
private Item selectLocationItem(IssuedCommand issuedCommand) {
if (filterByVisibility(getLocation().getItemList()).isEmpty()) {
IO.writeString("You don't see any items here.");
return null;
} else {
return selectItem(issuedCommand, getLocation().getInventory(), true);
}
}
/**
* Selects an item of the specified {@code BaseInventory} based on the arguments of a command.
*
* @param issuedCommand an IssuedCommand object whose arguments will determine the item search
* @param inventory an object of a subclass of {@code BaseInventory}
* @param checkForVisibility true if only visible items should be selectable
* @return an Item or {@code null}
*/
private Item selectItem(IssuedCommand issuedCommand, BaseInventory inventory, boolean checkForVisibility) {
List<Item> visibleItems;
if (checkForVisibility) {
visibleItems = filterByVisibility(inventory.getItems());
} else {
visibleItems = inventory.getItems();
}
if (issuedCommand.hasArguments() || checkIfAllEntitiesHaveTheSameName(visibleItems)) {
return findItem(visibleItems, issuedCommand.getArguments());
} else {
IO.writeString("You must specify an item.");
return null;
}
}
/**
* Attempts to find an item by its name in a specified Inventory.
*
* @return an Item object if there is a match. null otherwise.
*/
private Item findItem(List<Item> items, String[] tokens) {
Matches<Item> matches = Utils.findBestCompleteMatches(items, tokens);
if (matches.size() == 0) {
IO.writeString("Item not found.");
} else if (matches.size() == 1 || matches.getDifferentNames() == 1) {
return matches.getMatch(0);
} else {
Messenger.printAmbiguousSelectionMessage();
}
return null;
}
/**
* The method that lets the hero attack a target.
*
* @param issuedCommand the command entered by the player.
* @return an integer representing how many seconds the battle lasted.
*/
public int attackTarget(IssuedCommand issuedCommand) {
if (canSeeACreatureWarnIfNot()) {
Creature target = selectTarget(issuedCommand);
if (target != null) {
return Engine.battle(this, target) * BATTLE_TURN_DURATION;
}
}
return 0;
}
/**
* Attempts to select a target from the current location using the player input.
*
* @param issuedCommand the command entered by the player.
* @return a target Creature or {@code null}.
*/
private Creature selectTarget(IssuedCommand issuedCommand) {
List<Creature> visibleCreatures = filterByVisibility(getLocation().getCreatures());
if (issuedCommand.hasArguments() || checkIfAllEntitiesHaveTheSameName(visibleCreatures, this)) {
return findCreature(issuedCommand.getArguments());
} else {
IO.writeString("You must specify a target.");
return null;
}
}
/**
* Attempts to find a creature in the current location comparing its name to an array of string tokens.
* <p/>
* If there are no matches, {@code null} is returned.
* <p/>
* If there is one match, it is returned.
* <p/>
* If there are multiple matches but all have the same name, the first one is returned.
* <p/>
* If there are multiple matches with only two different names and one of these names is the Hero's name, the first
* creature match is returned.
* <p/>
* Lastly, if there are multiple matches that do not fall in one of the two categories above, {@code null} is
* returned.
*
* @param tokens an array of string tokens.
* @return a Creature or null.
*/
private Creature findCreature(String[] tokens) {
Matches<Creature> result = Utils.findBestCompleteMatches(getLocation().getCreatures(), tokens);
result = filterByVisibility(result);
if (result.size() == 0) {
IO.writeString("Creature not found.");
} else if (result.size() == 1 || result.getDifferentNames() == 1) {
return result.getMatch(0);
} else if (result.getDifferentNames() == 2 && result.hasMatchWithName(getName())) {
return result.getMatch(0).getName().equals(getName()) ? result.getMatch(1) : result.getMatch(0);
} else {
Messenger.printAmbiguousSelectionMessage();
}
return null;
}
/**
* Returns whether all Entities in a Collection have the same name or not.
*
* @param entities a {@code Collection} of Entities
* @return a boolean indicating if all Entities in the collection have the same name
*/
private boolean checkIfAllEntitiesHaveTheSameName(Collection<? extends Entity> entities) {
return checkIfAllEntitiesHaveTheSameName(entities, null);
}
/**
* Returns whether all Entities in a Collection have the same name or not.
*
* @param entities a {@code Collection} of Entities
* @param ignored an Entity to be ignored, should be {@code null} if no Entity is to be ignored
* @return a boolean indicating if all Entities in the collection have the same name
*/
private boolean checkIfAllEntitiesHaveTheSameName(Collection<? extends Entity> entities, Entity ignored) {
Name lastSeenName = null;
for (Entity entity : entities) {
if (ignored == null || entity != ignored) {
if (lastSeenName == null) {
lastSeenName = entity.getName();
} else {
if (!entity.getName().equals(lastSeenName)) { // Got an Entity with a different name.
return false;
}
}
}
}
return true;
}
/**
* Attempts to pick an Item and add it to the inventory.
*/
public int pickItem(IssuedCommand issuedCommand) {
if (canSeeAnItem()) {
Item selectedItem = selectLocationItem(issuedCommand);
if (selectedItem != null) {
SimulationResult result = getInventory().simulateItemAddition(selectedItem);
if (result == SimulationResult.AMOUNT_LIMIT) {
IO.writeString("Your inventory is full.");
} else if (result == SimulationResult.WEIGHT_LIMIT) {
IO.writeString("You can't carry more weight.");
} else if (result == SimulationResult.SUCCESSFUL) {
getLocation().removeItem(selectedItem);
addItem(selectedItem);
return SECONDS_TO_PICK_UP_AN_ITEM;
}
}
} else {
IO.writeString("You do not see any item you could pick up.");
}
return 0;
}
/**
* Adds an Item object to the inventory. As a precondition, simulateItemAddition(Item) should return SUCCESSFUL.
*
* @param item the Item to be added, not null
*/
public void addItem(Item item) {
if (getInventory().simulateItemAddition(item) == SimulationResult.SUCCESSFUL) {
getInventory().addItem(item);
IO.writeString(String.format("Added %s to the inventory.", item.getQualifiedName()));
} else {
throw new IllegalStateException("simulateItemAddition did not return SUCCESSFUL.");
}
}
/**
* Tries to equip an item from the inventory.
*/
public int parseEquip(IssuedCommand issuedCommand) {
Item selectedItem = selectInventoryItem(issuedCommand);
if (selectedItem != null) {
if (selectedItem.hasTag(Item.Tag.WEAPON)) {
equipWeapon(selectedItem);
return SECONDS_TO_EQUIP;
} else {
IO.writeString("You cannot equip that.");
}
}
return 0;
}
/**
* Attempts to drop an item from the hero's inventory.
*/
public int dropItem(IssuedCommand issuedCommand) {
Item selectedItem = selectInventoryItem(issuedCommand);
if (selectedItem != null) {
int totalTime = SECONDS_TO_DROP_AN_ITEM;
if (selectedItem == getWeapon()) {
totalTime += unequipWeapon();
}
dropItem(selectedItem);
IO.writeString(String.format("Dropped %s.", selectedItem.getQualifiedName()));
return totalTime;
}
return 0;
}
public void printInventory() {
Name item = Name.newInstance("item");
String firstLine;
if (getInventory().getItemCount() == 0) {
firstLine = "Your inventory is empty.";
} else {
String itemCount = item.getQuantifiedName(getInventory().getItemCount(), QuantificationMode.NUMBER);
firstLine = "You are carrying " + itemCount + ". Your inventory weights " + getInventory().getWeight() + ".";
}
IO.writeString(firstLine);
// Local variable to improve readability.
String itemLimit = item.getQuantifiedName(getInventory().getItemLimit(), QuantificationMode.NUMBER);
IO.writeString("Your maximum carrying capacity is " + itemLimit + " and " + getInventory().getWeightLimit() + ".");
if (getInventory().getItemCount() != 0) {
printItems();
}
}
/**
* Prints all items in the Hero's inventory. This function should only be called if the inventory is not empty.
*/
private void printItems() {
if (getInventory().getItemCount() == 0) {
throw new IllegalStateException("inventory item count is 0.");
}
IO.writeString("You are carrying:");
for (Item item : getInventory().getItems()) {
String name = String.format("%s (%s)", item.getQualifiedName(), item.getWeight());
if (hasWeapon() && getWeapon() == item) {
IO.writeString(" [Equipped] " + name);
} else {
IO.writeString(" " + name);
}
}
}
/**
* Attempts to eat an item from the ground.
*/
public int eatItem(IssuedCommand issuedCommand) {
Item selectedItem = selectInventoryItem(issuedCommand);
if (selectedItem != null) {
if (selectedItem.hasTag(Item.Tag.FOOD)) {
FoodComponent food = selectedItem.getFoodComponent();
double remainingBites = selectedItem.getCurIntegrity() / (double) food.getIntegrityDecrementOnEat();
int healthIncrement;
if (remainingBites >= 1.0) {
healthIncrement = food.getNutrition();
} else {
// The healing may vary from 0 up to (nutrition - 1) if there is not enough for a bite.
healthIncrement = (int) (food.getNutrition() * remainingBites);
}
selectedItem.decrementIntegrityByEat();
if (selectedItem.isBroken() && !selectedItem.hasTag(Item.Tag.REPAIRABLE)) {
IO.writeString("You ate " + selectedItem.getName() + ".");
} else {
IO.writeString("You ate a bit of " + selectedItem.getName() + ".");
}
addHealth(healthIncrement);
return SECONDS_TO_EAT_AN_ITEM;
} else {
IO.writeString("You can only eat food.");
}
}
return 0;
}
/**
* The method that enables a Hero to drink milk from a Creature.
*
* @param issuedCommand the command entered by the player
* @return how many seconds this action took
*/
public int parseMilk(IssuedCommand issuedCommand) {
if (canSeeACreatureWarnIfNot()) {
if (issuedCommand.hasArguments()) { // Specified which creature to milk from.
Creature selectedCreature = selectTarget(issuedCommand); // Finds the best match for the specified arguments.
if (selectedCreature != null) {
if (selectedCreature.hasTag(Creature.Tag.MILKABLE)) {
return milk(selectedCreature);
} else {
IO.writeString("This creature is not milkable.");
}
}
} else { // Filter milkable creatures.
List<Creature> visibleCreatures = filterByVisibility(getLocation().getCreatures());
List<Creature> milkableCreatures = filterByTag(visibleCreatures, Tag.MILKABLE);
if (milkableCreatures.isEmpty()) {
IO.writeString("You can't find a milkable creature.");
} else {
if (Matches.fromCollection(milkableCreatures).getDifferentNames() == 1) {
return milk(milkableCreatures.get(0));
} else {
IO.writeString("You need to be more specific.");
}
}
}
}
return 0;
}
private int milk(Creature creature) {
IO.writeString("You drink milk directly from " + creature.getName().getSingular() + ".");
addHealth(MILK_NUTRITION);
return SECONDS_TO_MILK_A_CREATURE;
}
public int readItem(IssuedCommand issuedCommand) {
Item selectedItem = selectInventoryItem(issuedCommand);
if (selectedItem != null) {
BookComponent book = selectedItem.getBookComponent();
if (book != null) {
IO.writeString(book.getText());
IO.writeNewLine();
if (book.isDidactic()) {
learnSkill(book);
}
return book.getTimeToRead();
} else {
IO.writeString("You can only read books.");
}
}
return 0;
}
/**
* Attempts to learn a skill from a BookComponent object. As a precondition, book must be didactic (teach a skill).
*
* @param book a BookComponent that returns true to isDidactic, not null
*/
private void learnSkill(@NotNull BookComponent book) {
if (!book.isDidactic()) {
throw new IllegalArgumentException("book should be didactic.");
}
Skill skill = new Skill(GameData.getSkillDefinitions().get(book.getSkillID()));
if (getSkillList().hasSkill(skill.getID())) {
IO.writeString("You already knew " + skill.getName() + ".");
} else {
getSkillList().addSkill(skill);
IO.writeString("You learned " + skill.getName() + ".");
}
}
/**
* Tries to destroy an item from the current location.
*/
public int destroyItem(IssuedCommand issuedCommand) {
Item target = selectLocationItem(issuedCommand);
if (target != null) {
if (target.hasTag(Item.Tag.REPAIRABLE)) {
if (target.isBroken()) {
IO.writeString(target.getName() + " is already crashed.");
} else {
target.setCurIntegrity(0);
IO.writeString(getName() + " crashed " + target.getName() + ".");
}
} else {
getLocation().removeItem(target);
IO.writeString(getName() + " destroyed " + target.getName() + ".");
}
return SECONDS_TO_DESTROY_AN_ITEM;
}
return 0;
}
private void equipWeapon(Item weapon) {
if (hasWeapon()) {
if (getWeapon() == weapon) {
IO.writeString(getName() + " is already equipping " + weapon.getName() + ".");
return;
} else {
unequipWeapon();
}
}
setWeapon(weapon);
IO.writeString(getName() + " equipped " + weapon.getName() + ".");
}
public int unequipWeapon() {
if (hasWeapon()) {
IO.writeString(getName() + " unequipped " + getWeapon().getName() + ".");
unsetWeapon();
return SECONDS_TO_UNEQUIP;
} else {
IO.writeString("You are not equipping a weapon.");
}
return 0;
}
/**
* Prints a message with the current status of the Hero.
*/
public void printAllStatus() {
StringBuilder builder = new StringBuilder();
builder.append(getName()).append("\n");
builder.append("You are ");
builder.append(HealthState.getHealthState(getCurHealth(), getMaxHealth()).toString().toLowerCase()).append(".\n");
builder.append("Your base attack is ").append(String.valueOf(getAttack())).append(".\n");
if (hasWeapon()) {
String format = "You are currently equipping %s, whose base damage is %d. This makes your total damage %d.\n";
int weaponBaseDamage = getWeapon().getWeaponComponent().getDamage();
int totalDamage = getAttack() + weaponBaseDamage;
builder.append(String.format(format, getWeapon().getQualifiedName(), weaponBaseDamage, totalDamage));
} else {
builder.append("You are fighting bare-handed.\n");
}
IO.writeString(builder.toString());
}
/**
* Prints the Hero's age.
*/
public void printAge() {
String age = new Period(dateOfBirth, Game.getGameState().getWorld().getWorldDate()).toString();
IO.writeString(String.format("You are %s old.", age), Color.CYAN);
}
/**
* Makes the Hero read the current date and time as well as he can.
*
* @return how many seconds the action took
*/
public int printDateAndTime() {
ItemIntegerPair pair = getBestClock();
Item clock = pair.getItem();
if (clock != null) {
IO.writeString(clock.getClockComponent().getTimeString());
}
World world = getLocation().getWorld();
Date worldDate = getLocation().getWorld().getWorldDate();
IO.writeString("You think it is " + worldDate.toDateString() + ".");
if (worldDate.getMonth() == dateOfBirth.getMonth() && worldDate.getDay() == dateOfBirth.getDay()) {
IO.writeString("Today is your birthday.");
}
IO.writeString("You can see that it is " + world.getPartOfDay().toString().toLowerCase() + ".");
return pair.getInteger();
}
/**
* Gets the easiest-to-access unbroken clock of the Hero. If the Hero has no unbroken clock, the easiest-to-access
* broken clock. Lastly, if the Hero does not have a clock at all, null is returned.
*
* @return an ItemIntegerPair object with the clock Item (or null) and how many seconds the search took in game time
*/
private ItemIntegerPair getBestClock() {
Item clock = null;
if (hasWeapon() && getWeapon().hasTag(Item.Tag.CLOCK)) {
if (!getWeapon().isBroken()) {
clock = getWeapon();
} else { // The Hero is equipping a broken clock: check if he has a working one in his inventory.
for (Item item : getInventory().getItems()) {
if (item.hasTag(Item.Tag.CLOCK) && !item.isBroken()) {
clock = item;
break;
}
}
if (clock == null) {
clock = getWeapon(); // The Hero does not have a working clock in his inventory: use the equipped one.
}
}
} else { // The Hero is not equipping a clock.
Item brokenClock = null;
for (Item item : getInventory().getItems()) {
if (item.hasTag(Item.Tag.CLOCK)) {
if (item.isBroken() && brokenClock == null) {
brokenClock = item;
} else {
clock = item;
break;
}
}
}
if (brokenClock != null) {
clock = brokenClock;
}
}
int timeSpent;
if (clock == null) {
timeSpent = 0;
} else if (clock == getWeapon()) {
timeSpent = SECONDS_TO_READ_EQUIPPED_CLOCK;
} else {
timeSpent = SECONDS_TO_READ_UNEQUIPPED_CLOCK;
}
return new ItemIntegerPair(clock, timeSpent);
}
/**
* Prints all the Skills that the Hero knows.
*/
public void printSkills() {
if (getSkillList().getSize() == 0) {
IO.writeString("You have not learned any skills yet.");
} else {
IO.writeString("You know the following skills:");
getSkillList().printSkillList();
}
}
/**
* Based on the arguments of the last issued command, makes a new SkillRotation for the Hero.
*
* @param issuedCommand the last command issued by the player.
*/
public void editRotation(IssuedCommand issuedCommand) {
if (issuedCommand.hasArguments()) {
List<String[]> skillNames = new ArrayList<String[]>();
List<String> currentSkillName = new ArrayList<String>();
for (String argument : issuedCommand.getArguments()) {
if (ROTATION_SKILL_SEPARATOR.equals(argument)) {
if (!currentSkillName.isEmpty()) {
String[] stringArray = new String[currentSkillName.size()];
currentSkillName.toArray(stringArray);
skillNames.add(stringArray);
currentSkillName.clear();
}
} else {
currentSkillName.add(argument);
}
}
if (!currentSkillName.isEmpty()) {
String[] stringArray = new String[currentSkillName.size()];
currentSkillName.toArray(stringArray);
skillNames.add(stringArray);
currentSkillName.clear();
}
if (skillNames.isEmpty()) {
IO.writeString("Provide skills arguments separated by '" + ROTATION_SKILL_SEPARATOR + "'.");
} else {
getSkillRotation().resetRotation();
ArrayList<Selectable> skillsList = new ArrayList<Selectable>(getSkillList().toListOfSelectable());
for (String[] skillName : skillNames) {
Matches<Selectable> result = Utils.findBestCompleteMatches(skillsList, skillName);
if (result.size() == 0) {
IO.writeString(Utils.stringArrayToString(skillName, " ") + " did not match any skill!");
} else {
if (result.getDifferentNames() == 1) {
getSkillRotation().addSkill((Skill) result.getMatch(0));
} else {
IO.writeString(Utils.stringArrayToString(skillName, " ") + " matched multiple skills!");
}
}
}
if (getSkillRotation().isEmpty()) {
IO.writeString("Failed to create a new skill rotation.");
} else {
IO.writeString("Created new skill rotation.");
}
}
} else {
if (getSkillRotation().isEmpty()) {
IO.writeString("You don't have a skill rotation.");
} else {
IO.writeString("This is your current skill rotation:");
getSkillRotation().printSkillRotation();
}
}
}
public int castRepairOnEquippedItem() {
ID repairID = new ID("REPAIR");
if (getSkillList().hasSkill(repairID)) {
if (hasWeapon()) {
if (getWeapon().hasTag(Item.Tag.REPAIRABLE)) {
getWeapon().incrementIntegrity(GameData.getSkillDefinitions().get(repairID).repair);
IO.writeString("You casted Repair on " + getWeapon().getName() + ".");
return 10; // Ten seconds to cast.
} else {
IO.writeString("The equipped item is not repairable.");
}
} else {
IO.writeString("You are not equipping anything.");
}
} else {
IO.writeString("You don't know how to cast Repair.");
}
return 0;
}
}
|
package org.javacs;
import com.google.common.reflect.ClassPath;
import java.lang.reflect.Constructor;
import sun.misc.Launcher;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class ClassPathIndex {
private final List<ClassPath.ClassInfo> topLevelClasses;
ClassPathIndex(Set<Path> classPath) {
this.topLevelClasses = classPath(classLoader(classPath)).getTopLevelClasses().stream()
.sorted(ClassPathIndex::shortestName)
.collect(Collectors.toList());
}
private static int shortestName(ClassPath.ClassInfo left, ClassPath.ClassInfo right) {
return Integer.compare(left.getSimpleName().length(), right.getSimpleName().length());
}
public static URLClassLoader parentClassLoader() {
URL[] bootstrap = Launcher.getBootstrapClassPath().getURLs();
return new URLClassLoader(bootstrap, null);
}
private static ClassPath classPath(URLClassLoader classLoader) {
try {
return ClassPath.from(classLoader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static URLClassLoader classLoader(Set<Path> classPath) {
URL[] urls = classPath.stream()
.flatMap(ClassPathIndex::url)
.toArray(URL[]::new);
return new URLClassLoader(urls, parentClassLoader());
}
private static Stream<URL> url(Path path) {
try {
return Stream.of(path.toUri().toURL());
} catch (MalformedURLException e) {
LOG.warning(e.getMessage());
return Stream.empty();
}
}
Stream<ClassPath.ClassInfo> topLevelClasses() {
return topLevelClasses.stream();
}
boolean isAccessibleFromPackage(ClassPath.ClassInfo info, String fromPackage) {
return info.getPackageName().equals(fromPackage) || isPublic(info);
}
private boolean isPublic(ClassPath.ClassInfo info) {
return Modifier.isPublic(info.load().getModifiers());
}
boolean hasAccessibleConstructor(ClassPath.ClassInfo info, String fromPackage) {
Class<?> load = info.load();
boolean isPublicClass = Modifier.isPublic(load.getModifiers()),
isSamePackage = fromPackage.equals(info.getPackageName());
for (Constructor<?> candidate : load.getDeclaredConstructors()) {
int modifiers = candidate.getModifiers();
if (isPublicClass && Modifier.isPublic(modifiers))
return true;
else if (isSamePackage && !Modifier.isPrivate(modifiers) && !Modifier.isProtected(modifiers))
return true;
}
return false;
}
/**
* Find all packages in parentPackage
*/
Stream<String> packagesStartingWith(String partialPackage) {
return topLevelClasses.stream()
.filter(c -> c.getPackageName().startsWith(partialPackage))
.map(c -> c.getPackageName());
}
Stream<ClassPath.ClassInfo> topLevelClassesIn(String parentPackage, String partialClass) {
return topLevelClasses.stream()
.filter(c -> c.getPackageName().equals(parentPackage) && Completions.containsCharactersInOrder(c.getSimpleName(), partialClass));
}
Optional<ClassPath.ClassInfo> loadPackage(String prefix) {
return topLevelClasses.stream()
.filter(c -> c.getPackageName().startsWith(prefix))
.findAny();
}
private static final Logger LOG = Logger.getLogger("main");
}
|
package com.gallatinsystems.survey.device.view;
import java.util.StringTokenizer;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.gallatinsystems.survey.device.R;
import com.gallatinsystems.survey.device.domain.Question;
import com.gallatinsystems.survey.device.domain.QuestionResponse;
import com.gallatinsystems.survey.device.util.ViewUtil;
/**
* Question that can handle geographic location input. This question can also
* listen to location updates from the GPS sensor on the device.
*
*
* @author Christopher Fagiani
*
*/
public class GeoQuestionView extends QuestionView implements OnClickListener,
LocationListener {
private static final int DEFAULT_WIDTH = 200;
private static final float UNKNOWN_ACCURACY = 99999999f;
private static final float ACCURACY_THRESHOLD = 100f;
private static final String DELIM = "|";
private Button geoButton;
private TextView latLabel;
private EditText latField;
private TextView lonLabel;
private EditText lonField;
private TextView elevationLabel;
private EditText elevationField;
private float lastAccuracy;
private boolean needUpdate = false;
public GeoQuestionView(Context context, Question q) {
super(context, q);
init();
}
protected void init() {
Context context = getContext();
TableRow tr = new TableRow(context);
TableLayout innerTable = new TableLayout(context);
TableRow innerRow = new TableRow(context);
latField = new EditText(context);
latField.setWidth(DEFAULT_WIDTH);
latLabel = new TextView(context);
latLabel.setText(R.string.lat);
innerRow.addView(latLabel);
innerRow.addView(latField);
innerTable.addView(innerRow);
innerRow = new TableRow(context);
lonField = new EditText(context);
lonField.setWidth(DEFAULT_WIDTH);
lonLabel = new TextView(context);
lonLabel.setText(R.string.lon);
innerRow.addView(lonLabel);
innerRow.addView(lonField);
innerTable.addView(innerRow);
innerRow = new TableRow(context);
elevationField = new EditText(context);
elevationField.setWidth(DEFAULT_WIDTH);
elevationLabel = new TextView(context);
elevationLabel.setText(R.string.elevation);
innerRow.addView(elevationLabel);
innerRow.addView(elevationField);
innerTable.addView(innerRow);
tr.addView(innerTable);
addView(tr);
tr = new TableRow(context);
geoButton = new Button(context);
geoButton.setText(R.string.getgeo);
geoButton.setOnClickListener(this);
tr.addView(geoButton);
addView(tr);
}
/**
* When the user clicks the "Populate Geo" button, start listening for
* location updates
*/
public void onClick(View v) {
LocationManager locMgr = (LocationManager) getContext()
.getSystemService(Context.LOCATION_SERVICE);
if (locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Location loc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc!= null){
//if the last location is accurate, then we can use it
if(loc.hasAccuracy() && loc.getAccuracy()< ACCURACY_THRESHOLD){
populateLocation(loc);
}
}
needUpdate = true;
lastAccuracy = UNKNOWN_ACCURACY;
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
this);
} else {
// we can't turn GPS on directly, the best we can do is launch the
// settings page
ViewUtil.showGPSDialog(getContext());
}
}
/**
* populates the fields on the UI with the location info from the event
*
* @param loc
*/
private void populateLocation(Location loc) {
latField.setText(loc.getLatitude() + "");
lonField.setText(loc.getLongitude() + "");
elevationField.setText(loc.getAltitude() + "");
setResponse(new QuestionResponse(loc.getLatitude() + DELIM
+ loc.getLongitude() + DELIM + loc.getAltitude(),
QuestionResponse.GEO_TYPE, getQuestion().getId()));
}
/**
* clears out the UI fields
*/
public void resetQuestion() {
super.resetQuestion();
latField.setText("");
lonField.setText("");
elevationField.setText("");
}
/**
* restores the file path for the file and turns on the complete icon if the
* file exists
*/
public void rehydrate(QuestionResponse resp) {
super.rehydrate(resp);
if (resp != null) {
if (resp.getValue() != null) {
StringTokenizer strTok = new StringTokenizer(resp.getValue(),
DELIM);
if (strTok.countTokens() == 3) {
latField.setText(strTok.nextToken());
lonField.setText(strTok.nextToken());
elevationField.setText(strTok.nextToken());
}
}
}
}
@Override
public void questionComplete(Bundle data) {
// completeIcon.setVisibility(View.VISIBLE);
}
/**
* called by the system when it gets location updates.
*/
public void onLocationChanged(Location location) {
float currentAccuracy = location.getAccuracy();
// if accuracy is 0 then the gps has no idea where we're at
if (currentAccuracy > 0) {
// if we're decreasing in accuracy or staying the same, or if we're
// below the accuracy threshold, stop listening for updates
if (currentAccuracy >= lastAccuracy
|| currentAccuracy <= ACCURACY_THRESHOLD) {
LocationManager locMgr = (LocationManager) getContext()
.getSystemService(Context.LOCATION_SERVICE);
locMgr.removeUpdates(this);
}
// if the location reading is more accurate than the last, update
// the view
if (lastAccuracy > currentAccuracy || needUpdate) {
lastAccuracy = currentAccuracy;
needUpdate = false;
populateLocation(location);
}
}else if (needUpdate){
needUpdate = false;
populateLocation(location);
}
}
public void onProviderDisabled(String provider) {
// no op. needed for LocationListener interface
}
public void onProviderEnabled(String provider) {
// no op. needed for LocationListener interface
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// no op. needed for LocationListener interface
}
}
|
package org.jtrfp.trcl.obj;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.jtrfp.trcl.Model;
import org.jtrfp.trcl.beh.AfterburnerBehavior;
import org.jtrfp.trcl.beh.AutoLeveling;
import org.jtrfp.trcl.beh.AutoLeveling.LevelingAxis;
import org.jtrfp.trcl.beh.Cloakable;
import org.jtrfp.trcl.beh.CollidesWithTerrain;
import org.jtrfp.trcl.beh.CollidesWithTunnelWalls;
import org.jtrfp.trcl.beh.DamageableBehavior;
import org.jtrfp.trcl.beh.DamageableBehavior.SupplyNotNeededException;
import org.jtrfp.trcl.beh.DamagedByCollisionWithGameplayObject;
import org.jtrfp.trcl.beh.DamagedByCollisionWithSurface;
import org.jtrfp.trcl.beh.HeadingXAlwaysPositiveBehavior;
import org.jtrfp.trcl.beh.LoopingPositionBehavior;
import org.jtrfp.trcl.beh.ProjectileFiringBehavior;
import org.jtrfp.trcl.beh.UpdatesNAVRadar;
import org.jtrfp.trcl.beh.UpgradeableProjectileFiringBehavior;
import org.jtrfp.trcl.beh.phy.AccelleratedByPropulsion;
import org.jtrfp.trcl.beh.phy.BouncesOffSurfaces;
import org.jtrfp.trcl.beh.phy.HasPropulsion;
import org.jtrfp.trcl.beh.phy.MovesByVelocity;
import org.jtrfp.trcl.beh.phy.RotationalDragBehavior;
import org.jtrfp.trcl.beh.phy.RotationalMomentumBehavior;
import org.jtrfp.trcl.beh.phy.VelocityDragBehavior;
import org.jtrfp.trcl.beh.ui.UpdatesHealthMeterBehavior;
import org.jtrfp.trcl.beh.ui.UpdatesThrottleMeterBehavior;
import org.jtrfp.trcl.beh.ui.UserInputRudderElevatorControlBehavior;
import org.jtrfp.trcl.beh.ui.UserInputThrottleControlBehavior;
import org.jtrfp.trcl.beh.ui.WeaponSelectionBehavior;
import org.jtrfp.trcl.core.Camera;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.core.ThreadManager;
import org.jtrfp.trcl.file.Weapon;
public class Player extends WorldObject {
private final Camera camera;
private int cameraDistance = 0;
private static final int SINGLE_SKL = 0;
public static final int CLOAK_COUNTDOWN_START = ThreadManager.GAMEPLAY_FPS * 30;// 30sec
public static final int INVINCIBILITY_COUNTDOWN_START = ThreadManager.GAMEPLAY_FPS * 30;// 30sec
private final ProjectileFiringBehavior[] weapons = new ProjectileFiringBehavior[Weapon
.values().length];
public Player(TR tr, Model model) {
super(tr, model);
setVisible(false);
DamageableBehavior db = new DamageableBehavior();
addBehavior(db);
String godMode = System.getProperty("org.jtrfp.trcl.godMode");
if (godMode != null) {
if (godMode.toUpperCase().contains("TRUE")) {
db.setEnable(false);
}
}
addBehavior(new AccelleratedByPropulsion());
addBehavior(new MovesByVelocity());
addBehavior(new HasPropulsion());
addBehavior(new CollidesWithTunnelWalls(true, true));
addBehavior(new UserInputThrottleControlBehavior());
addBehavior(new VelocityDragBehavior());
addBehavior(new AutoLeveling()
.setLevelingAxis(LevelingAxis.CROSS)
.setLevelingVector(Vector3D.PLUS_I)
.setRetainmentCoeff(1, .977, 1));
addBehavior(new UserInputRudderElevatorControlBehavior());
addBehavior(new RotationalMomentumBehavior());
addBehavior(new RotationalDragBehavior());
addBehavior(new CollidesWithTerrain());
addBehavior(new AfterburnerBehavior());
addBehavior(new LoopingPositionBehavior());
addBehavior(new HeadingXAlwaysPositiveBehavior().setEnable(false));
addBehavior(new UpdatesThrottleMeterBehavior().setController(tr
.getHudSystem().getThrottleMeter()));
addBehavior(new UpdatesHealthMeterBehavior().setController(tr
.getHudSystem().getHealthMeter()));
addBehavior(new DamagedByCollisionWithGameplayObject());
addBehavior(new DamagedByCollisionWithSurface());
addBehavior(new BouncesOffSurfaces());
addBehavior(new UpdatesNAVRadar());
addBehavior(new Cloakable());
final Weapon[] allWeapons = Weapon.values();
for (int i = 0; i < allWeapons.length; i++) {
final Weapon w = allWeapons[i];
if (w.getButtonToSelect() != -1) {
final ProjectileFiringBehavior pfb;
if (w.isLaser()) {// LASER
pfb = new UpgradeableProjectileFiringBehavior()
.setProjectileFactory(tr.getResourceManager()
.getProjectileFactories()[w.ordinal()]);
((UpgradeableProjectileFiringBehavior) pfb)
.setMaxCapabilityLevel(2)
.setFiringMultiplexMap(
new Vector3D[][] {
new Vector3D[] {
new Vector3D(5000, -3000, 0),
new Vector3D(-5000, -3000,
0) },// Level 0,
// single
new Vector3D[] {
new Vector3D(5000, -3000, 0),
new Vector3D(-5000, -3000,
0) },// Level 1,
// double
new Vector3D[] {
new Vector3D(5000, -3000, 0),
new Vector3D(-5000, -3000,
0),// Level 2 quad
new Vector3D(5000, 3000, 0),
new Vector3D(-5000, 3000, 0) } });// Level
// cont'd
}// end if(isLaser)
else {// NOT LASER
pfb = new ProjectileFiringBehavior().setFiringPositions(
new Vector3D[] { new Vector3D(5000, -3000, 0),
new Vector3D(-5000, -3000, 0) })
.setProjectileFactory(
tr.getResourceManager()
.getProjectileFactories()[w
.ordinal()]);
if (w == Weapon.DAM)
pfb.setAmmoLimit(1);
}
addBehavior(pfb);
weapons[w.getButtonToSelect() - 1] = pfb;
if(System.getProperties().containsKey("org.jtrfp.trcl.allAmmo")){
if(System.getProperty("org.jtrfp.trcl.allAmmo").toUpperCase().contains("TRUE")){
System.out.println("allAmmo cheat active for weapon "+w.getButtonToSelect());
pfb.setAmmoLimit(Integer.MAX_VALUE);
try{pfb.addSupply(Double.POSITIVE_INFINITY);}catch(SupplyNotNeededException e){}
}//end if(property=true)
}//end if(allAmmo)
}// end if(hasButton)
}
addBehavior(new WeaponSelectionBehavior().setBehaviors(weapons));
camera = tr.getRenderer().getCamera();
getBehavior().probeForBehavior(VelocityDragBehavior.class)
.setDragCoefficient(.86);
getBehavior().probeForBehavior(Propelled.class).setMinPropulsion(0);
getBehavior().probeForBehavior(Propelled.class)
.setMaxPropulsion(900000);
getBehavior().probeForBehavior(RotationalDragBehavior.class)
.setDragCoefficient(.86);
}//end constructor
@Override
public void setHeading(Vector3D lookAt) {
camera.setLookAtVector(lookAt);
camera.setPosition(new Vector3D(getPosition()).subtract(lookAt
.scalarMultiply(cameraDistance)));
super.setHeading(lookAt);
}
@Override
public void setTop(Vector3D top) {
camera.setUpVector(top);
super.setTop(top);
}
@Override
public Player setPosition(double[] pos) {
super.setPosition(pos);
return this;
}
@Override
public WorldObject notifyPositionChange() {
camera.setPosition(new Vector3D(getPosition()).subtract(getLookAt()
.scalarMultiply(cameraDistance)));
return super.notifyPositionChange();
}
/**
* @return the weapons
*/
public ProjectileFiringBehavior[] getWeapons() {
return weapons;
}
}// end Player
|
package org.jboss.modules;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A {@code ModuleLogger} which logs to a JDK logging category.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public final class JDKModuleLogger implements ModuleLogger {
private static final Level TRACE;
private static final Level DEBUG;
static {
Level trace = null;
Level debug = null;
try {
trace = Level.parse("TRACE");
} catch (IllegalArgumentException ignored) {
trace = Level.FINEST;
}
try {
debug = Level.parse("DEBUG");
} catch (IllegalArgumentException ignored) {
debug = Level.FINE;
}
TRACE = trace;
DEBUG = debug;
}
@SuppressWarnings({ "NonConstantLogger" })
private final Logger logger;
/**
* Construct a new instance.
*
* @param logger the logger to write to
*/
public JDKModuleLogger(final Logger logger) {
this.logger = logger;
}
/**
* Construct a new instance.
*
* @param category the name of the logger category to write to
*/
public JDKModuleLogger(final String category) {
this(Logger.getLogger(category));
}
/**
* Construct a new instance using the category {@code org.jboss.modules}.
*/
public JDKModuleLogger() {
this("org.jboss.modules");
}
private void doLog(final Level level, final String str) {
doLog(level, str, null);
}
private void doLog(final Level level, final String str, final Throwable t) {
try {
final ModuleLogRecord rec = new ModuleLogRecord(level, str);
rec.setLoggerName(logger.getName());
if (t != null) rec.setThrown(t);
logger.log(rec);
} catch (Throwable ignored) {
}
}
/** {@inheritDoc} */
public void trace(final String message) {
doLog(TRACE, message, null);
}
/** {@inheritDoc} */
public void trace(final String format, final Object arg1) {
if (logger.isLoggable(TRACE)) {
doLog(TRACE, String.format(format, arg1), null);
}
}
/** {@inheritDoc} */
public void trace(final String format, final Object arg1, final Object arg2) {
if (logger.isLoggable(TRACE)) {
doLog(TRACE, String.format(format, arg1, arg2));
}
}
/** {@inheritDoc} */
public void trace(final String format, final Object arg1, final Object arg2, final Object arg3) {
if (logger.isLoggable(TRACE)) {
doLog(TRACE, String.format(format, arg1, arg2, arg3));
}
}
/** {@inheritDoc} */
public void trace(final String format, final Object... args) {
if (logger.isLoggable(TRACE)) {
doLog(TRACE, String.format(format, (Object[]) args));
}
}
/** {@inheritDoc} */
public void trace(final Throwable t, final String message) {
doLog(TRACE, message, t);
}
/** {@inheritDoc} */
public void trace(final Throwable t, final String format, final Object arg1) {
if (logger.isLoggable(TRACE)) {
doLog(TRACE, String.format(format, arg1), t);
}
}
/** {@inheritDoc} */
public void trace(final Throwable t, final String format, final Object arg1, final Object arg2) {
if (logger.isLoggable(TRACE)) {
doLog(TRACE, String.format(format, arg1, arg2), t);
}
}
/** {@inheritDoc} */
public void trace(final Throwable t, final String format, final Object arg1, final Object arg2, final Object arg3) {
if (logger.isLoggable(TRACE)) {
doLog(TRACE, String.format(format, arg1, arg2, arg3), t);
}
}
/** {@inheritDoc} */
public void trace(final Throwable t, final String format, final Object... args) {
if (logger.isLoggable(TRACE)) {
doLog(TRACE, String.format(format, (Object[]) args), t);
}
}
/** {@inheritDoc} */
public void greeting() {
doLog(Level.INFO, String.format("JBoss Modules version %s", Main.getVersionString()));
}
/** {@inheritDoc} */
public void moduleDefined(final ModuleIdentifier identifier, final ModuleLoader moduleLoader) {
if (logger.isLoggable(DEBUG)) {
doLog(DEBUG, String.format("Module %s defined by %s", identifier, moduleLoader));
}
}
}
|
package org.jboss.modules;
import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarFile;
/**
* A fast, validating module.xml parser.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
* @author thomas.diesler@jboss.com
*/
final class ModuleXmlParser {
private static final PathFilter defaultExportFilter;
static {
final MultiplePathFilterBuilder builder = PathFilters.multiplePathFilterBuilder(true);
|
package roart.lang;
import java.util.Date;
import java.util.ArrayList;
import com.cybozu.labs.langdetect.Detector;
import com.cybozu.labs.langdetect.DetectorFactory;
import com.cybozu.labs.langdetect.Language;
import com.cybozu.labs.langdetect.LangDetectException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.*;
public class LanguageDetect {
private static Log log = LogFactory.getLog("LanguageDetect");
private static boolean inited = false;
public static void init(String profileDirectory) throws LangDetectException {
DetectorFactory.loadProfile(profileDirectory);
inited = true;
}
public static String detect(String text) {
try {
if (!inited) init("./profiles/");
Date d = logstart();
Detector detector = DetectorFactory.create();
detector.append(text);
String retstr = detector.detect();
logstop(d);
log.info("language " + retstr);
log.info("language2 " + LanguageDetect.detectLangs(text));
return retstr;
} catch (Exception e) {
log.error("exception", e);
}
return null;
}
public static ArrayList<Language> detectLangs(String text) throws LangDetectException {
if (!inited) init("profiles");
Detector detector = DetectorFactory.create();
detector.append(text);
return detector.getProbabilities();
}
public static Date logstart() {
return new Date();
}
public static void logstop (Date d) {
Date n = new Date();
long m = n.getTime() - d.getTime();
log.info("timerStop " + m);
}
}
|
package org.lappsgrid.vocabulary;
/**
* @author Keith Suderman
*/
public class Features
{
private Features()
{
}
public static final String PART_OF_SPEECH = "pos";
public static final String LEMMA = "lemma";
public static final String WORD = "word";
}
|
package org.minimalj.repository.sql;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.UUID;
import org.minimalj.model.Code;
import org.minimalj.model.Keys;
import org.minimalj.model.Keys.MethodProperty;
import org.minimalj.model.annotation.Searched;
import org.minimalj.model.properties.FlatProperties;
import org.minimalj.model.properties.PropertyInterface;
import org.minimalj.repository.list.RelationCriteria;
import org.minimalj.repository.query.AllCriteria;
import org.minimalj.repository.query.Criteria.AndCriteria;
import org.minimalj.repository.query.Criteria.OrCriteria;
import org.minimalj.repository.query.FieldCriteria;
import org.minimalj.repository.query.Limit;
import org.minimalj.repository.query.Order;
import org.minimalj.repository.query.Query;
import org.minimalj.repository.query.SearchCriteria;
import org.minimalj.util.FieldUtils;
import org.minimalj.util.GenericUtils;
import org.minimalj.util.IdUtils;
import org.minimalj.util.LoggingRuntimeException;
@SuppressWarnings("rawtypes")
public class Table<T> extends AbstractTable<T> {
private static final List<Object> EMPTY_WHERE_CLAUSE = Collections.singletonList("1=1");
protected final PropertyInterface idProperty;
protected final boolean optimisticLocking;
protected final String selectAllQuery;
protected final HashMap<PropertyInterface, ListTable> lists;
public Table(SqlRepository sqlRepository, Class<T> clazz) {
this(sqlRepository, null, clazz);
}
public Table(SqlRepository sqlRepository, String name, Class<T> clazz) {
super(sqlRepository, name, clazz);
this.idProperty = FlatProperties.getProperty(clazz, "id", true);
Objects.nonNull(idProperty);
this.optimisticLocking = FieldUtils.hasValidVersionfield(clazz);
List<PropertyInterface> lists = FlatProperties.getListProperties(clazz);
this.lists = createListTables(lists);
this.selectAllQuery = selectAllQuery();
}
@Override
public void createTable(SqlDialect dialect) {
super.createTable(dialect);
for (Object object : lists.values()) {
AbstractTable subTable = (AbstractTable) object;
subTable.createTable(dialect);
}
}
@Override
public void createIndexes(SqlDialect dialect) {
super.createIndexes(dialect);
for (Object object : lists.values()) {
AbstractTable subTable = (AbstractTable) object;
subTable.createIndexes(dialect);
}
}
@Override
public void createConstraints(SqlDialect dialect) {
super.createConstraints(dialect);
for (Object object : lists.values()) {
AbstractTable subTable = (AbstractTable) object;
subTable.createConstraints(dialect);
}
}
@Override
public void clear() {
for (Object object : lists.values()) {
AbstractTable subTable = (AbstractTable) object;
subTable.clear();
}
super.clear();
}
protected Object createId() {
return UUID.randomUUID().toString();
}
public Object insert(T object) {
try (PreparedStatement insertStatement = createStatement(sqlRepository.getConnection(), insertQuery, true)) {
Object id;
if (IdUtils.hasId(object.getClass())) {
id = IdUtils.getId(object);
if (id == null) {
id = createId();
IdUtils.setId(object, id);
}
} else {
id = createId();
}
setParameters(insertStatement, object, false, ParameterMode.INSERT, id);
insertStatement.execute();
insertLists(object);
if (object instanceof Code) {
sqlRepository.invalidateCodeCache(object.getClass());
}
return id;
} catch (SQLException x) {
throw new LoggingRuntimeException(x, sqlLogger, "Couldn't insert in " + getTableName() + " with " + object);
}
}
protected void insertLists(T object) {
for (Entry<PropertyInterface, ListTable> listEntry : lists.entrySet()) {
List list = (List) listEntry.getKey().getValue(object);
if (list != null && !list.isEmpty()) {
listEntry.getValue().addList(object, list);
}
}
}
public void delete(Object id) {
try (PreparedStatement updateStatement = createStatement(sqlRepository.getConnection(), deleteQuery, false)) {
updateStatement.setObject(1, id);
updateStatement.execute();
} catch (SQLException x) {
throw new LoggingRuntimeException(x, sqlLogger, "Couldn't delete " + getTableName() + " with ID " + id);
}
}
private LinkedHashMap<PropertyInterface, ListTable> createListTables(List<PropertyInterface> listProperties) {
LinkedHashMap<PropertyInterface, ListTable> lists = new LinkedHashMap<>();
for (PropertyInterface listProperty : listProperties) {
ListTable listTable = createListTable(listProperty);
lists.put(listProperty, listTable);
}
return lists;
}
ListTable createListTable(PropertyInterface property) {
Class<?> elementClass = GenericUtils.getGenericClass(property.getType());
String subTableName = buildSubTableName(property);
if (IdUtils.hasId(elementClass)) {
return new CrossTable<>(sqlRepository, subTableName, elementClass, idProperty);
} else {
return new SubTable(sqlRepository, subTableName, elementClass, idProperty);
}
}
protected String buildSubTableName(PropertyInterface property) {
return getTableName() + "__" + property.getName();
}
public void update(T object) {
updateWithId(object, IdUtils.getId(object));
}
void updateWithId(T object, Object id) {
try (PreparedStatement updateStatement = createStatement(sqlRepository.getConnection(), updateQuery, false)) {
int parameterIndex = setParameters(updateStatement, object, false, ParameterMode.UPDATE, id);
if (optimisticLocking) {
updateStatement.setInt(parameterIndex, IdUtils.getVersion(object));
updateStatement.execute();
if (updateStatement.getUpdateCount() == 0) {
throw new IllegalStateException("Optimistic locking failed");
}
} else {
updateStatement.execute();
}
for (Entry<PropertyInterface, ListTable> listTableEntry : lists.entrySet()) {
List list = (List) listTableEntry.getKey().getValue(object);
listTableEntry.getValue().replaceList(object, list);
}
if (object instanceof Code) {
sqlRepository.invalidateCodeCache(object.getClass());
}
} catch (SQLException x) {
throw new LoggingRuntimeException(x, sqlLogger, "Couldn't update in " + getTableName() + " with " + object);
}
}
public T read(Object id) {
try (PreparedStatement selectByIdStatement = createStatement(sqlRepository.getConnection(), selectByIdQuery, false)) {
selectByIdStatement.setObject(1, id);
T object = executeSelect(selectByIdStatement);
if (object != null) {
loadLists(object);
}
return object;
} catch (SQLException x) {
throw new LoggingRuntimeException(x, sqlLogger, "Couldn't read " + getTableName() + " with ID " + id);
}
}
public T read(Object id, Map<Class<?>, Map<Object, Object>> loadedReferences) {
try (PreparedStatement selectByIdStatement = createStatement(sqlRepository.getConnection(), selectByIdQuery, false)) {
selectByIdStatement.setObject(1, id);
T object = executeSelect(selectByIdStatement, loadedReferences);
if (object != null) {
loadLists(object);
}
return object;
} catch (SQLException x) {
throw new LoggingRuntimeException(x, sqlLogger, "Couldn't read " + getTableName() + " with ID " + id);
}
}
private List<String> getColumns(Object[] keys) {
List<String> result = new ArrayList<>();
PropertyInterface[] properties = Keys.getProperties(keys);
for (PropertyInterface p : properties) {
if (p instanceof MethodProperty) {
throw new IllegalArgumentException("Not possible to query for method properties");
} else if (p.getPath().equals("id")) {
result.add("id");
continue;
}
for (Map.Entry<String, PropertyInterface> entry : columns.entrySet()) {
PropertyInterface property = entry.getValue();
if (p.getPath().equals(property.getPath())) {
result.add(entry.getKey());
}
}
}
return result;
}
public List<Object> whereClause(Query query) {
List<Object> result;
if (query instanceof AndCriteria) {
AndCriteria andCriteria = (AndCriteria) query;
result = combine(andCriteria.getCriterias(), "AND");
} else if (query instanceof OrCriteria) {
OrCriteria orCriteria = (OrCriteria) query;
result = combine(orCriteria.getCriterias(), "OR");
} else if (query instanceof FieldCriteria) {
FieldCriteria fieldCriteria = (FieldCriteria) query;
result = new ArrayList<>();
Object value = fieldCriteria.getValue();
String term = whereStatement(fieldCriteria.getPath(), fieldCriteria.getOperator());
if (value != null && IdUtils.hasId(value.getClass())) {
value = IdUtils.getId(value);
}
result.add(term);
result.add(value);
} else if (query instanceof SearchCriteria) {
SearchCriteria searchCriteria = (SearchCriteria) query;
result = new ArrayList<>();
String search = convertUserSearch(searchCriteria.getQuery());
String clause = "(";
List<String> searchColumns = searchCriteria.getKeys() != null ? getColumns(searchCriteria.getKeys()) : findSearchColumns(clazz);
boolean first = true;
for (String column : searchColumns) {
if (!first) {
clause += " OR ";
} else {
first = false;
}
clause += column + (searchCriteria.isNotEqual() ? " NOT" : "") + " LIKE ?";
result.add(search);
}
clause += ")";
if (isHistorized()) {
clause += " and historized = 0";
}
result.add(0, clause); // insert at beginning
} else if (query instanceof RelationCriteria) {
RelationCriteria relationCriteria = (RelationCriteria) query;
result = new ArrayList<>();
String crossTableName = relationCriteria.getCrossName();
avoidSqlInjection(crossTableName);
String clause = "T.id = C.elementId AND C.id = ? ORDER BY C.position";
result.add(clause);
result.add(relationCriteria.getRelatedId());
} else if (query instanceof Limit) {
Limit limit = (Limit) query;
result = whereClause(limit.getQuery());
String s = (String) result.get(0);
s = s + " " + sqlRepository.getSqlDialect().limit(limit.getRows(), limit.getOffset());
result.set(0, s);
} else if (query instanceof Order) {
Order order = (Order) query;
List<Order> orders = new ArrayList<>();
orders.add(order);
while (order.getQuery() instanceof Order) {
order = (Order) order.getQuery();
orders.add(order);
}
result = whereClause(order.getQuery());
String s = (String) result.get(0);
s = s + " " + order(orders);
result.set(0, s);
} else if (query instanceof AllCriteria) {
result = new ArrayList<>(EMPTY_WHERE_CLAUSE);
} else if (query == null) {
result = EMPTY_WHERE_CLAUSE;
} else {
throw new IllegalArgumentException("Unknown criteria: " + query);
}
return result;
}
private void avoidSqlInjection(String crossTableName) {
if (!sqlRepository.getTableByName().containsKey(crossTableName)) {
throw new IllegalArgumentException("Invalid cross name: " + crossTableName);
}
}
private String order(List<Order> orders) {
StringBuilder s = new StringBuilder();
for (Order order : orders) {
if (s.length() == 0) {
s.append("ORDER BY ");
} else {
s.append(", ");
}
s.append(findColumn(order.getPath()));
if (!order.isAscending()) {
s.append(" DESC");
}
}
return s.toString();
}
private List<Object> combine(List<? extends Query> criterias, String operator) {
if (criterias.isEmpty()) {
return null;
} else if (criterias.size() == 1) {
return whereClause(criterias.get(0));
} else {
List<Object> whereClause = whereClause(criterias.get(0));
String clause = "(" + whereClause.get(0);
for (int i = 1; i<criterias.size(); i++) {
List<Object> whereClause2 = whereClause(criterias.get(i));
clause += " " + operator + " " + whereClause2.get(0);
if (whereClause2.size() > 1) {
whereClause.addAll(whereClause2.subList(1, whereClause2.size()));
}
}
clause += ")";
whereClause.set(0, clause); // replace
return whereClause;
}
}
public long count(Query query) {
query = getCriteria(query);
String tableName;
List<Object> whereClause;
if (query instanceof RelationCriteria) {
RelationCriteria relationCriteria = (RelationCriteria) query;
tableName = relationCriteria.getCrossName();
avoidSqlInjection(tableName);
whereClause = Arrays.asList("id = ?", relationCriteria.getRelatedId());
} else {
tableName = getTableName();
whereClause = whereClause(query);
}
String queryString = "SELECT COUNT(*) FROM " + tableName + (whereClause != EMPTY_WHERE_CLAUSE ? " WHERE " + whereClause.get(0) : "");
try (PreparedStatement statement = createStatement(sqlRepository.getConnection(), queryString, false)) {
for (int i = 1; i<whereClause.size(); i++) {
sqlRepository.getSqlDialect().setParameter(statement, i, whereClause.get(i), null); // TODO property is not known here anymore. Set<enum> will fail
}
return executeSelectCount(statement);
} catch (SQLException e) {
throw new LoggingRuntimeException(e, sqlLogger, "count failed");
}
}
private Query getCriteria(Query query) {
if (query instanceof Limit) {
query = ((Limit) query).getQuery();
}
while (query instanceof Order) {
query = ((Order) query).getQuery();
}
return query;
}
public <S> List<S> find(Query query, Class<S> resultClass) {
List<Object> whereClause = whereClause(query);
String select = getCriteria(query) instanceof RelationCriteria ? select(resultClass, (RelationCriteria) getCriteria(query)) : select(resultClass);
String queryString = select + (whereClause != EMPTY_WHERE_CLAUSE ? " WHERE " + whereClause.get(0) : "");
try (PreparedStatement statement = createStatement(sqlRepository.getConnection(), queryString, false)) {
for (int i = 1; i<whereClause.size(); i++) {
sqlRepository.getSqlDialect().setParameter(statement, i, whereClause.get(i), null); // TODO property is not known here anymore. Set<enum> will fail
}
return resultClass == getClazz() ? (List<S>) executeSelectAll(statement) : executeSelectViewAll(resultClass, statement);
} catch (SQLException e) {
throw new LoggingRuntimeException(e, sqlLogger, "read with SimpleCriteria failed");
}
}
public <S> S readView(Class<S> resultClass, Object id, Map<Class<?>, Map<Object, Object>> loadedReferences) {
String query = select(resultClass) + " WHERE id = ?";
try (PreparedStatement statement = createStatement(sqlRepository.getConnection(), query, false)) {
statement.setObject(1, id);
return executeSelectView(resultClass, statement, loadedReferences);
} catch (SQLException e) {
throw new LoggingRuntimeException(e, sqlLogger, "read with SimpleCriteria failed");
}
}
private String select(Class<?> resultClass) {
String querySql = "SELECT ";
if (resultClass == getClazz()) {
querySql += "*";
} else {
querySql += "id";
Map<String, PropertyInterface> propertiesByColumns = sqlRepository.findColumns(resultClass);
for (String column : propertiesByColumns.keySet()) {
querySql += ", "+ column;
}
}
querySql += " FROM " + getTableName();
return querySql;
}
private String select(Class<?> resultClass, RelationCriteria relationCriteria) {
String crossTableName = relationCriteria.getCrossName();
String querySql = "SELECT ";
if (resultClass == getClazz()) {
querySql += "T.*";
} else {
querySql += "T.id";
Map<String, PropertyInterface> propertiesByColumns = sqlRepository.findColumns(resultClass);
for (String column : propertiesByColumns.keySet()) {
querySql += ", T." + column;
}
}
querySql += " FROM " + getTableName() + " T, " + crossTableName + " C";
return querySql;
}
protected <S> List<S> executeSelectViewAll(Class<S> resultClass, PreparedStatement preparedStatement) throws SQLException {
List<S> result = new ArrayList<>();
try (ResultSet resultSet = preparedStatement.executeQuery()) {
Map<Class<?>, Map<Object, Object>> loadedReferences = new HashMap<>();
while (resultSet.next()) {
S resultObject = sqlRepository.readResultSetRow(resultClass, resultSet, loadedReferences);
loadViewLists(resultObject);
result.add(resultObject);
}
}
return result;
}
protected <S> S executeSelectView(Class<S> resultClass, PreparedStatement preparedStatement, Map<Class<?>, Map<Object, Object>> loadedReferences) throws SQLException {
S result = null;
try (ResultSet resultSet = preparedStatement.executeQuery()) {
if (resultSet.next()) {
result = sqlRepository.readResultSetRow(resultClass, resultSet, loadedReferences);
loadViewLists(result);
}
}
return result;
}
public String convertUserSearch(String s) {
s = s.replace('*', '%');
return s;
}
private List<String> findSearchColumns(Class<?> clazz) {
List<String> searchColumns = new ArrayList<>();
for (Map.Entry<String, PropertyInterface> entry : columns.entrySet()) {
PropertyInterface property = entry.getValue();
Searched searchable = property.getAnnotation(Searched.class);
if (searchable != null) {
searchColumns.add(entry.getKey());
}
}
if (searchColumns.isEmpty()) {
throw new IllegalArgumentException("No fields are annotated as 'Searched' in " + clazz.getName());
}
return searchColumns;
}
@SuppressWarnings("unchecked")
protected void loadLists(T object) throws SQLException {
for (Entry<PropertyInterface, ListTable> listTableEntry : lists.entrySet()) {
List values = listTableEntry.getValue().getList(object);
PropertyInterface listProperty = listTableEntry.getKey();
listProperty.setValue(object, values);
}
}
@SuppressWarnings("unchecked")
protected <S> void loadViewLists(S result) {
List<PropertyInterface> viewLists = FlatProperties.getListProperties(result.getClass());
for (PropertyInterface viewListProperty : viewLists) {
for (Entry<PropertyInterface, ListTable> listPropertyEntry : lists.entrySet()) {
if (viewListProperty.getPath().equals(listPropertyEntry.getKey().getPath())) {
List values = listPropertyEntry.getValue().getList(result);
viewListProperty.setValue(result, values);
break;
}
}
}
}
// Statements
@Override
protected String selectByIdQuery() {
StringBuilder query = new StringBuilder();
query.append("SELECT * FROM ").append(getTableName()).append(" WHERE id = ?");
return query.toString();
}
protected String selectAllQuery() {
StringBuilder query = new StringBuilder();
query.append("SELECT * FROM ").append(getTableName());
return query.toString();
}
@Override
protected String insertQuery() {
StringBuilder s = new StringBuilder();
s.append("INSERT INTO ").append(getTableName()).append(" (");
for (String columnName : getColumns().keySet()) {
s.append(columnName).append(", ");
}
s.append("id) VALUES (");
for (int i = 0; i<getColumns().size(); i++) {
s.append("?, ");
}
s.append("?)");
return s.toString();
}
@Override
protected String updateQuery() {
StringBuilder s = new StringBuilder();
s.append("UPDATE ").append(getTableName()).append(" SET ");
for (Object columnNameObject : getColumns().keySet()) {
s.append((String) columnNameObject).append("= ?, ");
}
// this is used in a callback where OptimisticLocking is not yet initialized
boolean optimisticLocking = FieldUtils.hasValidVersionfield(clazz);
if (optimisticLocking) {
s.append(" version = version + 1 WHERE id = ? AND version = ?");
} else {
s.delete(s.length()-2, s.length());
s.append(" WHERE id = ?");
}
return s.toString();
}
@Override
protected String deleteQuery() {
StringBuilder s = new StringBuilder();
s.append("DELETE FROM ").append(getTableName()).append(" WHERE id = ?");
return s.toString();
}
@Override
protected void addSpecialColumns(SqlDialect dialect, StringBuilder s) {
if (idProperty != null) {
dialect.addIdColumn(s, idProperty);
} else {
dialect.addIdColumn(s, Object.class, 36);
}
if (optimisticLocking) {
s.append(",\n version INTEGER DEFAULT 0");
}
}
@Override
protected void addPrimaryKey(SqlDialect dialect, StringBuilder s) {
dialect.addPrimaryKey(s, "id");
}
}
|
package uk.me.mjt.s3test;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.sun.net.httpserver.HttpExchange;
import uk.me.mjt.s3test.xml.ErrorResponseXmlDocument;
import uk.me.mjt.s3test.xml.ListBucketsXmlDocument;
import uk.me.mjt.s3test.xml.ListObjectsXmlDocument;
import uk.me.mjt.s3test.xml.XmlDocument;
public class S3Server extends Server {
private static final int NUMBER_OF_THREADS = 3;
private static final Pattern BUCKET_PATTERN = Pattern.compile("/([^/]+)/"); // Format is like "/bucketname/"
private static final Pattern REQUEST_PATH_PATTERN = Pattern.compile("/([^/]+)/(.+)"); // Format is like "/bucketname/asdf.txt"
private static final Pattern DOUBLE_DOT_PATTERN = Pattern.compile("(.*/)?\\.\\./+\\.\\.(/.*)?");
private static final Pattern BUCKET_NAME_MUST_MATCH_PATTERN = Pattern.compile("[a-z0-9\\.\\-]{3,63}");
private static final Pattern BUCKET_NAME_MUST_NOT_MATCH_PATTERN = Pattern.compile("(^[\\.\\-])|"
+ "([\\.\\-]$)|"
+ "([\\.\\-]{2})|"
+ "(^\\d+\\.\\d+\\.\\d+\\.\\d+$)");
public static final String PREFIX_QUERY_PARAMETER = "prefix";
public static final String S3_TEST_OWNER_ID = "7aab9dc7212a1061887ecb";
public static final String S3_TEST_OWNER_DISPLAY_NAME = "S3 Test";
private final Map<String, Bucket> buckets = new HashMap<>();
public S3Server() throws IOException {
this(null);
}
public S3Server(InetSocketAddress address) throws IOException {
super(address, NUMBER_OF_THREADS);
}
@Override
protected void handleGet(HttpExchange exchange) throws IOException {
String path = exchange.getRequestURI().getPath();
if (path.equals("/")) {
handleListBuckets(exchange);
return;
}
Matcher bucketPatternMatcher = BUCKET_PATTERN.matcher(path);
if (bucketPatternMatcher.matches()) {
String bucketName = bucketPatternMatcher.group(1);
handleListObjects(exchange, bucketName);
}
Matcher requestPathPatternMatcher = REQUEST_PATH_PATTERN.matcher(path);
if (!requestPathPatternMatcher.matches()) {
respondErrorAndClose(exchange, ErrorResponse.INVALID_URI);
return;
}
String bucketName = requestPathPatternMatcher.group(1);
String keyName = requestPathPatternMatcher.group(2);
if (DOUBLE_DOT_PATTERN.matcher(keyName).matches()) {
respondErrorAndClose(exchange, ErrorResponse.INVALID_URI);
return;
}
handleGetObject(exchange, bucketName, keyName);
}
@Override
protected void handlePut(HttpExchange exchange) throws IOException {
String path = exchange.getRequestURI().getPath();
Matcher bucketPatternMatcher = BUCKET_PATTERN.matcher(path);
if (bucketPatternMatcher.matches()) {
String bucketName = bucketPatternMatcher.group(1);
handlePutBucket(exchange, bucketName);
return;
}
Matcher requestPathPatternMatcher = REQUEST_PATH_PATTERN.matcher(path);
if (requestPathPatternMatcher.matches()) {
String bucketName = requestPathPatternMatcher.group(1);
String keyName = requestPathPatternMatcher.group(2);
handlePutObject(exchange, bucketName, keyName);
return;
}
respondErrorAndClose(exchange, ErrorResponse.INVALID_URI);
}
@Override
protected void handleDelete(HttpExchange exchange) throws IOException {
String path = exchange.getRequestURI().getPath();
Matcher bucketPatternMatcher = BUCKET_PATTERN.matcher(path);
if (bucketPatternMatcher.matches()) {
String bucketName = bucketPatternMatcher.group(1);
handleDeleteBucket(exchange,bucketName);
return;
}
Matcher requestPathPatternMatcher = REQUEST_PATH_PATTERN.matcher(path);
if (requestPathPatternMatcher.matches()) {
String bucketName = requestPathPatternMatcher.group(1);
String keyName = requestPathPatternMatcher.group(2);
handleDeleteObject(exchange, bucketName, keyName);
return;
}
respondErrorAndClose(exchange, ErrorResponse.INVALID_URI);
}
private void handleGetObject(HttpExchange exchange, String bucketName, String keyName) throws IOException {
if (buckets.containsKey(bucketName)) {
Bucket bucket = buckets.get(bucketName);
if (bucket.containsKey(keyName)) {
respondGetObjectAndClose(exchange, bucket.get(keyName));
} else {
respondErrorAndClose(exchange, ErrorResponse.NO_SUCH_KEY);
}
} else {
respondErrorAndClose(exchange, ErrorResponse.NO_SUCH_BUCKET);
}
}
private void handleListObjects(HttpExchange exchange, String bucketName) throws IOException {
if (buckets.containsKey(bucketName)) {
String prefix = getQueryParamValue(exchange.getRequestURI(), PREFIX_QUERY_PARAMETER);
respondListObjectsAndClose(exchange, bucketName, prefix);
} else {
respondErrorAndClose(exchange, ErrorResponse.NO_SUCH_BUCKET);
}
}
private void handleListBuckets(HttpExchange exchange) throws IOException {
respondWithXmlDocumentAndClose(
exchange,
HttpURLConnection.HTTP_OK,
new ListBucketsXmlDocument(
buckets,
S3_TEST_OWNER_ID,
S3_TEST_OWNER_DISPLAY_NAME
)
);
}
private void handlePutObject(HttpExchange exchange, String bucketName, String keyName) throws IOException {
if (DOUBLE_DOT_PATTERN.matcher(keyName).matches()) {
respondErrorAndClose(exchange, ErrorResponse.INVALID_URI);
return;
}
byte[] content = readRequestBodyFully(exchange);
if (buckets.containsKey(bucketName)) {
Bucket bucket = buckets.get(bucketName);
StoredObject storedObject = new StoredObject(keyName, content);
bucket.put(keyName, storedObject);
addHeader(exchange, HttpHeaders.E_TAG, "\"" + storedObject.md5HexString() + "\"");
respondAndClose(exchange, HttpURLConnection.HTTP_OK);
} else {
respondErrorAndClose(exchange, ErrorResponse.NO_SUCH_BUCKET);
}
}
private void handlePutBucket(HttpExchange exchange, String bucketName) throws IOException {
readRequestBodyFully(exchange);
if (!bucketNameValid(bucketName)) {
respondErrorAndClose(exchange, ErrorResponse.INVALID_BUCKET_NAME);
} else if (buckets.containsKey(bucketName)) {
respondErrorAndClose(exchange, ErrorResponse.BUCKET_ALREADY_EXISTS);
} else {
System.out.println("Creating bucket " + bucketName + ".");
buckets.put(bucketName, new Bucket(bucketName));
addHeader(exchange, HttpHeaders.LOCATION, "/" + bucketName);
respondAndClose(exchange, HttpURLConnection.HTTP_OK);
}
}
private void handleDeleteObject(HttpExchange exchange, String bucketName, String keyName) throws IOException {
readRequestBodyFully(exchange);
if (buckets.containsKey(bucketName)) {
Bucket bucket = buckets.get(bucketName);
bucket.remove(keyName);
}
respondAndClose(exchange, HttpURLConnection.HTTP_NO_CONTENT);
}
private void handleDeleteBucket(HttpExchange exchange, String bucketName) throws IOException {
if (buckets.containsKey(bucketName)) {
Bucket bucket = buckets.get(bucketName);
if (bucket.isEmpty()) {
respondErrorAndClose(exchange, ErrorResponse.BUCKET_NOT_EMPTY);
} else {
buckets.remove(bucketName);
respondAndClose(exchange, HttpURLConnection.HTTP_NO_CONTENT);
}
} else {
respondErrorAndClose(exchange, ErrorResponse.NO_SUCH_BUCKET);
}
}
private boolean bucketNameValid(String bucketName) {
return bucketName != null
&& BUCKET_NAME_MUST_MATCH_PATTERN.matcher(bucketName).matches()
&& !BUCKET_NAME_MUST_NOT_MATCH_PATTERN.matcher(bucketName).find();
}
private void respondListObjectsAndClose(HttpExchange exchange, String bucketName, String prefix) throws IOException {
respondWithXmlDocumentAndClose(
exchange,
HttpURLConnection.HTTP_OK,
new ListObjectsXmlDocument(
buckets.get(bucketName),
prefix,
S3_TEST_OWNER_ID,
S3_TEST_OWNER_DISPLAY_NAME
)
);
}
private void respondGetObjectAndClose(HttpExchange exchange, StoredObject storedObject) throws IOException {
byte[] response = storedObject.getContent();
addHeader(exchange, "ETag", "\"" + storedObject.md5HexString() + "\"");
addHeader(exchange, HttpHeaders.CONTENT_TYPE, "text/plain");
respondAndClose(exchange, HttpURLConnection.HTTP_OK, response);
}
private void respondWithXmlDocumentAndClose(HttpExchange exchange, int httpCode, XmlDocument xmlDocument) throws IOException {
xmlDocument.build();
addHeader(exchange, HttpHeaders.CONTENT_TYPE, "application/xml");
respondAndClose(exchange, httpCode, xmlDocument.toUtf8Bytes());
}
private void respondErrorAndClose(HttpExchange exchange, ErrorResponse errorResponse) throws IOException {
respondWithXmlDocumentAndClose(
exchange,
errorResponse.getStatusCode(),
new ErrorResponseXmlDocument(
errorResponse
)
);
}
}
|
package org.myrobotlab.service;
import java.io.IOException;
import java.util.List;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.kinematics.Point;
import org.myrobotlab.leap.LeapMotionListener;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.data.LeapData;
import org.myrobotlab.service.interfaces.LeapDataListener;
import org.myrobotlab.service.interfaces.LeapDataPublisher;
import org.myrobotlab.service.interfaces.PointPublisher;
import org.slf4j.Logger;
import com.leapmotion.leap.Controller;
import com.leapmotion.leap.Finger;
import com.leapmotion.leap.Frame;
import com.leapmotion.leap.Vector;
public class LeapMotion extends Service implements LeapDataListener, LeapDataPublisher, PointPublisher {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(LeapMotion.class);
transient LeapMotionListener listener = null;
transient Controller controller = new Controller();
public LeapData lastLeapData = null;
public LeapMotion(String n) {
super(n);
}
public void activateDefaultMode() {
controller.setPolicyFlags(Controller.PolicyFlag.POLICY_DEFAULT);
log.info("default mode active");
return;
}
public void activateVRMode() {
controller.setPolicyFlags(Controller.PolicyFlag.POLICY_OPTIMIZE_HMD);
log.info("virtual reality mode active");
return;
}
public void addFrameListener(Service service) {
addListener("publishFrame", service.getName(), "onFrame");
}
public void addLeapDataListener(Service service) {
addListener("publishLeapData", service.getName(), "onLeapData");
}
public void checkPolicy() {
log.info("controller.policyFlags()");
}
/**
* Return the angle of the finger for the hand specified This computes the
* angle based on the dot product of the palmNormal and the fingerDirection
* Theta = arccos( (V1.V2) / ( |V1| * |V2| )
*
* @param hand
* - "left" or "right"
* @param tip
* - 0 (thumb) / 1 (index) .. etc..
* @return angle in degrees
*/
public double getJointAngle(String hand, Integer tip) {
com.leapmotion.leap.Hand h = null;
if ("left".equalsIgnoreCase(hand)) {
// left hand
h = controller.frame().hands().leftmost();
} else {
// right hand
h = controller.frame().hands().rightmost();
}
// TODO: does this return the correct finger?
Finger f = h.fingers().get(tip);
Vector palmNormal = h.palmNormal();
Vector fDir = f.direction();
// TODO: validate that this is what we actually want.
// otherwise we can directly compute the angleTo in java.
float angleInRadians = palmNormal.angleTo(fDir);
// convert to degrees so it's easy to pass to servos
double angle = Math.toDegrees(angleInRadians);
return angle;
}
public float getLeftStrength() {
Frame frame = controller.frame();
com.leapmotion.leap.Hand hand = frame.hands().leftmost();
float strength = hand.grabStrength();
return strength;
}
public float getRightStrength() {
Frame frame = controller.frame();
com.leapmotion.leap.Hand hand = frame.hands().rightmost();
float strength = hand.grabStrength();
return strength;
}
@Override
public LeapData onLeapData(LeapData data) {
return data;
// TODO Auto-generated method stub
}
public Controller publishConnect(Controller controller) {
return controller;
}
public Controller publishDisconnect(Controller controller) {
return controller;
}
public Controller publishExit(Controller controller) {
return controller;
}
public Frame publishFrame(Frame frame) {
return frame;
}
public Controller publishInit(Controller controller) {
return controller;
}
@Override
public LeapData publishLeapData(LeapData data) {
// if (data != null) {
// log.info("DATA" + data.leftHand.posX);
return data;
}
@Override
public void startService() {
super.startService();
listener = new LeapMotionListener(this);
// we've been asked to start.. we should start tracking !
this.startTracking();
}
public void startTracking() {
controller.addListener(listener);
}
public void stopTracking() {
controller.removeListener(listener);
}
public static void main(String[] args) {
LoggingFactory.init(Level.INFO);
try {
LeapMotion leap = new LeapMotion("leap");
leap.startService();
Runtime.start("gui", "SwingGui");
Runtime.start("webgui", "WebGui");
// Have the sample listener receive events from the controller
// leap.startTracking();
// Keep this process running until Enter is pressed
log.info("Press Enter to quit...");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
// Remove the sample listener when done
} catch (Exception e) {
Logging.logError(e);
}
}
@Override
public List<Point> publishPoints(List<Point> points) {
return points;
}
public void addPointsListener(Service s) {
// TODO - reflect on a public heard method - if doesn't exist error ?
addListener("publishPoints", s.getName(), "onPoints");
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(LeapMotion.class.getCanonicalName());
meta.addDescription("Leap Motion Service");
meta.addCategory("sensor", "telerobotics");
meta.addDependency("leapmotion", "leap", "2.1.3");
// TODO: These will overwrite each other! we need to be selective for the platform of what we deploy.
// I believe the 32bit libraries would overwrite the 64bit libraries.
// meta.addDependency("leapmotion", "leap-linux32", "2.1.3", "zip");
// meta.addDependency("leapmotion", "leap-win32", "2.1.3", "zip");
// 64 bit support only for now. until we can switch out dependencies based on the current platform.
meta.addDependency("leapmotion", "leap-win64", "2.1.3", "zip");
meta.addDependency("leapmotion", "leap-mac64", "2.1.3", "zip");
meta.addDependency("leapmotion", "leap-linux64", "2.1.3", "zip");
return meta;
}
}
|
package water.parser;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import water.*;
import water.fvec.ParseDataset2.ParseProgressMonitor;
public abstract class CustomParser extends Iced {
public static final byte CHAR_TAB = '\t';
public static final byte CHAR_LF = 10;
public static final byte CHAR_SPACE = ' ';
public static final byte CHAR_CR = 13;
public static final byte CHAR_DOUBLE_QUOTE = '"';
public static final byte CHAR_SINGLE_QUOTE = '\'';
public final static int MAX_PREVIEW_COLS = 100;
public final static int MAX_PREVIEW_LINES = 50;
public final ParserSetup _setup;
public CustomParser(ParserSetup setup){_setup = setup;}
public static class PSetupGuess extends Iced {
public final ParserSetup _setup;
public final int _invalidLines;
public final int _validLines;
public final String [] _errors;
public Key _setupFromFile;
public Key _hdrFromFile;
public String [][] _data;
public final boolean _isValid;
public PSetupGuess(ParserSetup ps, int vlines, int ilines, String [][] data, boolean isValid, String [] errors){
_setup = ps;
_invalidLines = ilines;
_validLines = vlines;
_errors = errors;
_data = data;
_isValid = isValid;
}
public Set<String> checkDupColumnNames(){
return _setup.checkDupColumnNames();
}
public final boolean hasErrors(){
return _errors != null && _errors.length > 0;
}
@Override public String toString(){
if(!_isValid)
return "Parser setup appears to be broken, got " + _setup.toString();
else if(hasErrors())
return "Parser setup appears to work with some errors, got " + _setup.toString();
else
return "Parser setup working fine, got " + _setup.toString();
}
}
public enum ParserType {
AUTO(false),XLS(false),XLSX(false),CSV(true), SVMLight(true);
public final boolean parallelParseSupported;
ParserType(boolean par){parallelParseSupported = par;}
}
public static class ParserSetup extends Iced implements Cloneable{
public final ParserType _pType;
public final byte _separator;
public boolean _header;
public boolean _singleQuotes;
public String [] _columnNames;
public final int _ncols;
public enum Coltype {
NUM,ZERO,STR,AUTO,INVALID;
}
public static class TypeInfo extends Iced{
Coltype _type;
ValueString _naStr = new ValueString("");
boolean _strongGuess;
public void merge(TypeInfo tinfo){
if(_type == Coltype.AUTO || !_strongGuess && tinfo._strongGuess){ // copy over stuff from the other
_type = tinfo._type;
_naStr = tinfo._naStr;
_strongGuess = tinfo._strongGuess;
} else if(tinfo._type != Coltype.AUTO && !_strongGuess){
tinfo._type = Coltype.INVALID;
} // else just keep mine
}
}
public String [][] domains;
public double [] _min;
public double [] _max;
public int _nnums;
public int _nstr;
public int _missing;
public int _nzeros;
TypeInfo [] _types;
public ParserSetup() {
_pType = ParserType.AUTO;
_separator = CsvParser.AUTO_SEP;
_header = false;
_ncols = 0;
_columnNames = null;
}
protected ParserSetup(ParserType t) {
this(t,CsvParser.AUTO_SEP,0,false,null,false);
}
public ParserSetup(ParserType t, byte sep, boolean header) {
_pType = t;
_separator = sep;
_header = header;
_columnNames = null;
_ncols = 0;
}
public ParserSetup(ParserType t, byte sep, boolean header, boolean singleQuotes) {
_pType = t;
_separator = sep;
_header = header;
_columnNames = null;
_ncols = 0;
_singleQuotes = singleQuotes;
}
public ParserSetup(ParserType t, byte sep, int ncolumns, boolean header, String [] columnNames, boolean singleQuotes) {
_pType = t;
_separator = sep;
_ncols = ncolumns;
_header = header;
_columnNames = columnNames;
_singleQuotes = singleQuotes;
}
public boolean isSpecified(){
return _pType != ParserType.AUTO && _separator != CsvParser.AUTO_SEP && (_header || _ncols > 0);
}
public Set<String> checkDupColumnNames(){
HashSet<String> uniqueNames = new HashSet<String>();
HashSet<String> conflictingNames = new HashSet<String>();
if(_header){
for(String n:_columnNames){
if(!uniqueNames.contains(n)){
uniqueNames.add(n);
} else {
conflictingNames.add(n);
}
}
}
return conflictingNames;
}
@Override public ParserSetup clone(){
return new ParserSetup(_pType, _separator, _ncols,_header,null,_singleQuotes);
}
public boolean isCompatible(ParserSetup other){
if(other == null || _pType != other._pType)return false;
if(_pType == ParserType.CSV && (_separator != other._separator || _ncols != other._ncols))
return false;
if(_types == null) _types = other._types;
else if(other._types != null){
for(int i = 0; i < _types.length; ++i)
_types[i].merge(other._types[i]);
}
return true;
}
public CustomParser parser(){
switch(this._pType){
case CSV:
return new CsvParser(this);
case SVMLight:
return new SVMLightParser(this);
case XLS:
return new XlsParser(this);
default:
throw H2O.unimpl();
}
}
@Override public String toString(){
StringBuilder sb = new StringBuilder(_pType.name());
switch(_pType){
case SVMLight:
sb.append(" data with (estimated) " + _ncols + " columns.");
break;
case CSV:
sb.append(" data with " + _ncols + " columns using '" + (char)_separator + "' (\\" + _separator + "04d) as separator.");
break;
case XLS:
sb.append(" data with " + _ncols + " columns.");
break;
case AUTO:
sb.append("");
break;
default:
throw H2O.unimpl();
}
return sb.toString();
}
}
public boolean isCompatible(CustomParser p){return _setup == p._setup || (_setup != null && _setup.isCompatible(p._setup));}
public DataOut parallelParse(int cidx, final DataIn din, final DataOut dout) {throw new UnsupportedOperationException();}
public boolean parallelParseSupported(){return false;}
public DataOut streamParse( final InputStream is, final DataOut dout) throws Exception {
if(_setup._pType.parallelParseSupported){
StreamData din = new StreamData(is);
int cidx=0;
while( is.available() > 0 )
parallelParse(cidx++,din,dout);
parallelParse(cidx++,din,dout); // Parse the remaining partial 32K buffer
} else {
throw H2O.unimpl();
}
return dout;
}
// Zipped file; no parallel decompression; decompress into local chunks,
// parse local chunks; distribute chunks later.
public DataOut streamParse( final InputStream is, final StreamDataOut dout, ParseProgressMonitor pmon) throws IOException {
// All output into a fresh pile of NewChunks, one per column
if(_setup._pType.parallelParseSupported){
StreamData din = new StreamData(is);
int cidx=0;
StreamDataOut nextChunk = dout;
long lastProgress = pmon.progress();
while( is.available() > 0 ){
if (pmon.progress() > lastProgress) {
lastProgress = pmon.progress();
nextChunk.close();
if(dout != nextChunk) dout.reduce(nextChunk);
nextChunk = nextChunk.nextChunk();
}
parallelParse(cidx++,din,nextChunk);
}
parallelParse(cidx++,din,nextChunk); // Parse the remaining partial 32K buffer
nextChunk.close();
if(dout != nextChunk)dout.reduce(nextChunk);
} else {
throw H2O.unimpl();
}
return dout;
}
protected static final boolean isWhitespace(byte c) {
return (c == CHAR_SPACE) || (c == CHAR_TAB);
}
protected static final boolean isEOL(byte c) {
return ((c == CHAR_LF) || (c == CHAR_CR));
}
public interface DataIn {
// Get another chunk of byte data
public abstract byte[] getChunkData( int cidx );
public abstract int getChunkDataStart( int cidx );
public abstract void setChunkDataStart( int cidx, int offset );
}
public interface DataOut extends Freezable {
public void setColumnNames(String [] names);
// Register a newLine from the parser
public void newLine();
// True if already forced into a string column (skip number parsing)
public boolean isString(int colIdx);
// Add a number column with given digits & exp
public void addNumCol(int colIdx, long number, int exp);
// Add a number column with given digits & exp
public void addNumCol(int colIdx, double d);
// An an invalid / missing entry
public void addInvalidCol(int colIdx);
// Add a String column
public void addStrCol( int colIdx, ValueString str );
// Final rolling back of partial line
public void rollbackLine();
public void invalidLine(String err);
public void invalidValue(int line, int col);
}
public interface StreamDataOut extends DataOut {
StreamDataOut nextChunk();
StreamDataOut reduce(StreamDataOut dout);
StreamDataOut close();
StreamDataOut close(Futures fs);
}
public static class StreamData implements CustomParser.DataIn {
final transient InputStream _is;
private byte[] _bits0 = new byte[2*1024*1024]; //allows for row lengths up to 2M
private byte[] _bits1 = new byte[2*1024*1024];
private int _cidx0=-1, _cidx1=-1; // Chunk
private int _coff0=-1, _coff1=-1; // Last used byte in a chunk
public StreamData(InputStream is){_is = is;}
@Override public byte[] getChunkData(int cidx) {
if(cidx == _cidx0)return _bits0;
if(cidx == _cidx1)return _bits1;
assert cidx==_cidx0+1 || cidx==_cidx1+1;
byte[] bits = _cidx0<_cidx1 ? _bits0 : _bits1;
if( _cidx0<_cidx1 ) { _cidx0 = cidx; _coff0 = -1; }
else { _cidx1 = cidx; _coff1 = -1; }
// Read as much as the buffer will hold
int off=0;
try {
while( off < bits.length ) {
int len = _is.read(bits,off,bits.length-off);
if( len == -1 ) break;
off += len;
}
assert off == bits.length || _is.available() <= 0;
} catch( IOException ioe ) {
throw new RuntimeException(ioe);
}
if( off == bits.length ) return bits;
// Final read is short; cache the short-read
byte[] bits2 = (off == 0) ? null : Arrays.copyOf(bits,off);
if( _cidx0==cidx ) _bits0 = bits2;
else _bits1 = bits2;
return bits2;
}
@Override public int getChunkDataStart(int cidx) {
if( _cidx0 == cidx ) return _coff0;
if( _cidx1 == cidx ) return _coff1;
return 0;
}
@Override public void setChunkDataStart(int cidx, int offset) {
if( _cidx0 == cidx ) _coff0 = offset;
if( _cidx1 == cidx ) _coff1 = offset;
}
}
public abstract CustomParser clone();
public String [] headers(){return null;}
protected static class TypeGuesserDataOut extends Iced implements DataOut {
transient private HashSet<String> [] _domains;
int [] _nnums;
int [] _nstrings;
int [] _nzeros;
int _nlines = 0;
final int _ncols;
public TypeGuesserDataOut(int ncols){
_ncols = ncols;
_domains = new HashSet[ncols];
_nzeros = new int[ncols];
_nstrings = new int[ncols];
_nnums = new int[ncols];
for(int i = 0; i < ncols; ++i)
_domains[i] = new HashSet<String>();
}
// TODO: ugly quick hack, needs revisit
public ParserSetup.TypeInfo[] guessTypes() {
ParserSetup.TypeInfo [] res = new ParserSetup.TypeInfo[_ncols];
for(int i = 0; i < res.length; ++i)
res[i] = new ParserSetup.TypeInfo();
for(int i = 0; i < _ncols; ++i){
if(_domains[i].size() <= 1 && (double)_nnums[i] / _nlines >= .2) // clear number
res[i]._type = ParserSetup.Coltype.NUM;
else if(_domains[i].size() >= 2 && (_nzeros[i] > 0 && (Math.abs(_nzeros[i] + _nstrings[i] - _nlines) <= 1))) { // clear string/enum
res[i]._naStr = new ValueString("0");
res[i]._type = ParserSetup.Coltype.STR;
res[i]._strongGuess = true;
} else if(_domains[i].size() >= 0 && (_nstrings[i]/(double)_nlines) > .9) {
res[i]._type = ParserSetup.Coltype.STR;
} else { // some generic two strings, could be garbage or enums
if ((double)_nstrings[i] / _nlines >= .95) {
res[i]._type = ParserSetup.Coltype.STR;
res[i]._strongGuess = (double)_nstrings[i]/_nlines >= .99;
} else if (_nnums[i] > 0 && (double)_nnums[i] / _nlines > .2)
res[i]._type = ParserSetup.Coltype.NUM;
}
}
return res;
}
@Override
public void setColumnNames(String[] names) {}
@Override
public void newLine() {
++_nlines;
}
@Override
public boolean isString(int colIdx) {
return false;
}
@Override
public void addNumCol(int colIdx, long number, int exp) {
if(colIdx < _nnums.length)
if (number == 0)
++_nzeros[colIdx];
else
++_nnums[colIdx];
}
@Override
public void addNumCol(int colIdx, double d) {
if(colIdx < _nnums.length)
if (d == 0)
++_nzeros[colIdx];
else
++_nnums[colIdx];
}
@Override
public void addInvalidCol(int colIdx) {
}
@Override
public void addStrCol(int colIdx, ValueString str) {
if(colIdx < _nstrings.length) {
++_nstrings[colIdx];
_domains[colIdx].add(str.toString());
}
}
@Override
public void rollbackLine() {--_nlines;}
@Override
public void invalidLine(String err) {}
@Override
public void invalidValue(int line, int col) {}
}
protected static class CustomInspectDataOut extends Iced implements DataOut {
public int _nlines;
public int _ncols;
public int _invalidLines;
public boolean _header;
private String [] _colNames;
private String [][] _data = new String[MAX_PREVIEW_LINES][MAX_PREVIEW_COLS];
transient ArrayList<String> _errors;
public CustomInspectDataOut() {
for(int i = 0; i < MAX_PREVIEW_LINES;++i)
Arrays.fill(_data[i],"NA");
}
public String [][] data(){
String [][] res = Arrays.copyOf(_data, Math.min(MAX_PREVIEW_LINES, _nlines));
for(int i = 0; i < res.length; ++i)
res[i] = Arrays.copyOf(_data[i], Math.min(MAX_PREVIEW_COLS,_ncols));
return (_data = res);
}
@Override public void setColumnNames(String[] names) {
_colNames = names;
_data[0] = names;
++_nlines;
_ncols = names.length;
_header = true;
}
@Override public void newLine() {
++_nlines;
}
@Override public boolean isString(int colIdx) {return false;}
@Override public void addNumCol(int colIdx, long number, int exp) {
if(colIdx < _ncols && _nlines < MAX_PREVIEW_LINES)
_data[_nlines][colIdx] = Double.toString(number*PrettyPrint.pow10(exp));
}
@Override public void addNumCol(int colIdx, double d) {
if(colIdx < _ncols) {
_ncols = Math.max(_ncols, colIdx);
if (_nlines < MAX_PREVIEW_LINES && colIdx < MAX_PREVIEW_COLS)
_data[_nlines][colIdx] = Double.toString(d);
}
}
@Override public void addInvalidCol(int colIdx) {
if(colIdx < _ncols && _nlines < MAX_PREVIEW_LINES)
_data[_nlines][colIdx] = "NA";
}
@Override public void addStrCol(int colIdx, ValueString str) {
if(colIdx < _ncols && _nlines < MAX_PREVIEW_LINES)
_data[_nlines][colIdx] = str.toString();
}
@Override public void rollbackLine() {--_nlines;}
@Override public void invalidLine(String err) {
++_invalidLines;
_errors.add("Error at line: " + _nlines + ", reason: " + err);
}
@Override public void invalidValue(int linenum, int colnum) {}
}
}
|
package org.opennars.inference;
import org.opennars.control.DerivationContext;
import org.opennars.entity.*;
import org.opennars.io.Symbols;
import org.opennars.io.events.Events;
import org.opennars.language.*;
import org.opennars.main.Parameters;
import org.opennars.operator.Operation;
import org.opennars.storage.Memory;
import static org.opennars.io.Symbols.*;
import static org.opennars.language.Terms.equalSubTermsInRespectToImageAndProduct;
/**
* Table of inference rules, indexed by the TermLinks for the task and the
* belief. Used in indirective processing of a task, to dispatch inference cases
* to the relevant inference rules.
*/
public class RuleTables {
/**
* Entry point of the inference engine
*
* @param tLink The selected TaskLink, which will provide a task
* @param bLink The selected TermLink, which may provide a belief
* @param memory Reference to the memory
*/
public static void reason(final TaskLink tLink, final TermLink bLink, final DerivationContext nal) {
final Memory memory = nal.mem();
final Task task = nal.getCurrentTask();
final Sentence taskSentence = task.sentence;
final Term taskTerm = taskSentence.term; // cloning for substitution
Term beliefTerm = bLink.target; // cloning for substitution
final Concept beliefConcept = memory.concept(beliefTerm);
final Sentence belief = (beliefConcept != null) ? beliefConcept.getBelief(nal, task) : null;
nal.setCurrentBelief( belief );
if (belief != null) {
beliefTerm = belief.term; //because interval handling that differs on conceptual level
/*Sentence belief_event = beliefConcept.getBeliefForTemporalInference(task);
if(belief_event != null) {
boolean found_overlap = false;
if(Stamp.baseOverlap(task.sentence.stamp.evidentialBase, belief_event.stamp.evidentialBase)) {
found_overlap = true;
}
if(!found_overlap) { //temporal rules are inductive so no chance to succeed if there is an overlap
//and since the temporal rule is relatively expensive the check here was good.
Sentence inference_belief = belief;
nal.setCurrentBelief(belief_event);
nal.setTheNewStamp(task.sentence.stamp, belief_event.stamp, nal.memory.time());
TemporalRules.temporalInduction(task.sentence, belief_event, nal, true);
nal.setCurrentBelief(inference_belief);
nal.setTheNewStamp(task.sentence.stamp, belief.stamp, nal.memory.time());
}
}*/
//too restrictive, its checked for non-deductive inference rules in derivedTask (also for single prem)
nal.evidentalOverlap = Stamp.baseOverlap(task.sentence.stamp.evidentialBase, belief.stamp.evidentialBase);
if(nal.evidentalOverlap && (!task.sentence.isEternal() || !belief.isEternal())) {
return; //only allow for eternal reasoning for now to prevent derived event floods
}
nal.emit(Events.BeliefReason.class, belief, beliefTerm, taskTerm, nal);
if (LocalRules.match(task, belief, nal)) { //new tasks resulted from the match, so return
return;
}
}
//current belief and task may have changed, so set again:
nal.setCurrentBelief(belief);
nal.setCurrentTask(task);
//put here since LocalRules match should be possible even if the belief is foreign
if(equalSubTermsInRespectToImageAndProduct(taskTerm,beliefTerm))
return;
/*if ((memory.getNewTaskCount() > 0) && taskSentence.isJudgment()) {
return;
}*/
final short tIndex = tLink.getIndex(0);
short bIndex = bLink.getIndex(0);
switch (tLink.type) { // dispatch first by TaskLink type
case TermLink.SELF:
switch (bLink.type) {
case TermLink.COMPONENT:
compoundAndSelf((CompoundTerm) taskTerm, beliefTerm, true, bIndex, nal);
break;
case TermLink.COMPOUND:
compoundAndSelf((CompoundTerm) beliefTerm, taskTerm, false, bIndex, nal);
break;
case TermLink.COMPONENT_STATEMENT:
if (belief != null) {
if (taskTerm instanceof Statement) {
SyllogisticRules.detachment(taskSentence, belief, bIndex, nal);
}
} //else {
if(taskSentence.term instanceof Inheritance || taskSentence.term instanceof Similarity) {
StructuralRules.transformNegation((CompoundTerm) Negation.make(taskSentence.term), nal);
}
goalFromQuestion(task, taskTerm, nal);
break;
case TermLink.COMPOUND_STATEMENT:
if (belief != null) {
SyllogisticRules.detachment(belief, taskSentence, bIndex, nal);
}
break;
case TermLink.COMPONENT_CONDITION:
if ((belief != null) && (taskTerm instanceof Implication)) {
bIndex = bLink.getIndex(1);
SyllogisticRules.conditionalDedInd(task.sentence,(Implication) taskTerm, bIndex, beliefTerm, tIndex, nal);
}
break;
case TermLink.COMPOUND_CONDITION:
if ((belief != null) && (taskTerm instanceof Implication) && (beliefTerm instanceof Implication)) {
bIndex = bLink.getIndex(1);
SyllogisticRules.conditionalDedInd(belief,(Implication) beliefTerm, bIndex, taskTerm, tIndex, nal);
}
break;
}
break;
case TermLink.COMPOUND:
switch (bLink.type) {
case TermLink.COMPOUND:
compoundAndCompound((CompoundTerm) taskTerm, (CompoundTerm) beliefTerm, tIndex, bIndex, nal);
break;
case TermLink.COMPOUND_STATEMENT:
compoundAndStatement((CompoundTerm) taskTerm, tIndex, (Statement) beliefTerm, bIndex, beliefTerm, nal);
break;
case TermLink.COMPOUND_CONDITION:
if (belief != null) {
if (beliefTerm instanceof Implication) {
final Term[] u = new Term[] { beliefTerm, taskTerm };
if (Variables.unify(VAR_INDEPENDENT, ((Statement) beliefTerm).getSubject(), taskTerm, u, true)) { //only secure place that
final Sentence newBelief = belief.clone(u[0]); //allows partial match
final Sentence newTaskSentence = taskSentence.clone(u[1]);
detachmentWithVar(newBelief, newTaskSentence, bIndex, false, nal);
} else {
SyllogisticRules.conditionalDedInd(belief, (Implication) beliefTerm, bIndex, taskTerm, -1, nal);
}
} else if (beliefTerm instanceof Equivalence) {
SyllogisticRules.conditionalAna((Equivalence) beliefTerm, bIndex, taskTerm, -1, nal);
}
}
break;
}
break;
case TermLink.COMPOUND_STATEMENT:
switch (bLink.type) {
case TermLink.COMPONENT:
if (taskTerm instanceof Statement) {
goalFromWantBelief(task, tIndex, bIndex, taskTerm, nal, beliefTerm);
componentAndStatement((CompoundTerm) nal.getCurrentTerm(), bIndex, (Statement) taskTerm, tIndex, nal);
}
break;
case TermLink.COMPOUND:
if (taskTerm instanceof Statement) {
compoundAndStatement((CompoundTerm) beliefTerm, bIndex, (Statement) taskTerm, tIndex, beliefTerm, nal);
}
break;
case TermLink.COMPOUND_STATEMENT:
if (belief != null) {
syllogisms(tLink, bLink, taskTerm, beliefTerm, nal);
}
break;
case TermLink.COMPOUND_CONDITION:
if (belief != null) {
bIndex = bLink.getIndex(1);
if ((taskTerm instanceof Statement) && (beliefTerm instanceof Implication)) {
conditionalDedIndWithVar(belief, (Implication) beliefTerm, bIndex, (Statement) taskTerm, tIndex, nal);
}
}
break;
}
break;
case TermLink.COMPOUND_CONDITION:
switch (bLink.type) {
case TermLink.COMPOUND:
if (belief != null) {
detachmentWithVar(taskSentence, belief, tIndex, nal);
}
break;
case TermLink.COMPOUND_STATEMENT:
if (belief != null) {
if (taskTerm instanceof Implication) // TODO maybe put instanceof test within conditionalDedIndWithVar()
{
final Term subj = ((Statement) taskTerm).getSubject();
if (subj instanceof Negation) {
if (taskSentence.isJudgment()) {
componentAndStatement((CompoundTerm) subj, bIndex, (Statement) taskTerm, tIndex, nal);
} else {
componentAndStatement((CompoundTerm) subj, tIndex, (Statement) beliefTerm, bIndex, nal);
}
} else {
conditionalDedIndWithVar(task.sentence, (Implication) taskTerm, tIndex, (Statement) beliefTerm, bIndex, nal);
}
}
break;
}
break;
}
}
}
public static void goalFromWantBelief(final Task task, final short tIndex, final short bIndex, final Term taskTerm, final DerivationContext nal, final Term beliefTerm) {
if(task.sentence.isJudgment() && tIndex == 0 && bIndex == 1 && taskTerm instanceof Operation) {
final Operation op = (Operation) taskTerm;
if(op.getPredicate() == nal.memory.getOperator("^want")) {
final TruthValue newTruth = TruthFunctions.deduction(task.sentence.truth, Parameters.reliance);
nal.singlePremiseTask(((Operation)taskTerm).getArguments().term[1], Symbols.GOAL_MARK, newTruth, BudgetFunctions.forward(newTruth, nal));
}
}
}
private static void goalFromQuestion(final Task task, final Term taskTerm, final DerivationContext nal) {
if(task.sentence.punctuation==Symbols.QUESTION_MARK && (taskTerm instanceof Implication || taskTerm instanceof Equivalence)) { //<a =/> b>? |- a!
Term goalterm=null;
Term goalterm2=null;
if(taskTerm instanceof Implication) {
final Implication imp=(Implication)taskTerm;
if(imp.getTemporalOrder()!=TemporalRules.ORDER_BACKWARD || imp.getTemporalOrder()==TemporalRules.ORDER_CONCURRENT) {
if(!Parameters.CURIOSITY_FOR_OPERATOR_ONLY || imp.getSubject() instanceof Operation) {
goalterm=imp.getSubject();
}
if(goalterm instanceof Variable && goalterm.hasVarQuery() && (!Parameters.CURIOSITY_FOR_OPERATOR_ONLY || imp.getPredicate() instanceof Operation)) {
goalterm=imp.getPredicate(); //overwrite, it is a how question, in case of <?how =/> b> it is b! which is desired
}
}
else
if(imp.getTemporalOrder()==TemporalRules.ORDER_BACKWARD) {
if(!Parameters.CURIOSITY_FOR_OPERATOR_ONLY || imp.getPredicate() instanceof Operation) {
goalterm=imp.getPredicate();
}
if(goalterm instanceof Variable && goalterm.hasVarQuery() && (!Parameters.CURIOSITY_FOR_OPERATOR_ONLY || imp.getSubject() instanceof Operation)) {
goalterm=imp.getSubject(); //overwrite, it is a how question, in case of <?how =/> b> it is b! which is desired
}
}
}
else
if(taskTerm instanceof Equivalence) {
final Equivalence qu=(Equivalence)taskTerm;
if(qu.getTemporalOrder()==TemporalRules.ORDER_FORWARD || qu.getTemporalOrder()==TemporalRules.ORDER_CONCURRENT) {
if(!Parameters.CURIOSITY_FOR_OPERATOR_ONLY || qu.getSubject() instanceof Operation) {
goalterm=qu.getSubject();
}
if(!Parameters.CURIOSITY_FOR_OPERATOR_ONLY || qu.getPredicate() instanceof Operation) {
goalterm2=qu.getPredicate();
}
}
}
final TruthValue truth=new TruthValue(1.0f,Parameters.DEFAULT_GOAL_CONFIDENCE*Parameters.CURIOSITY_DESIRE_CONFIDENCE_MUL);
if(goalterm!=null && !(goalterm instanceof Variable) && goalterm instanceof CompoundTerm) {
goalterm=((CompoundTerm)goalterm).transformIndependentVariableToDependentVar((CompoundTerm) goalterm);
final Sentence sent=new Sentence(
goalterm,
Symbols.GOAL_MARK,
truth,
new Stamp(task.sentence.stamp,nal.memory.time()));
nal.singlePremiseTask(sent, new BudgetValue(task.getPriority()*Parameters.CURIOSITY_DESIRE_PRIORITY_MUL,task.getDurability()*Parameters.CURIOSITY_DESIRE_DURABILITY_MUL,BudgetFunctions.truthToQuality(truth)));
}
if(goalterm instanceof CompoundTerm && goalterm2!=null && !(goalterm2 instanceof Variable) && goalterm2 instanceof CompoundTerm) {
goalterm2=((CompoundTerm)goalterm).transformIndependentVariableToDependentVar((CompoundTerm) goalterm2);
final Sentence sent=new Sentence(
goalterm2,
Symbols.GOAL_MARK,
truth.clone(),
new Stamp(task.sentence.stamp,nal.memory.time()));
nal.singlePremiseTask(sent, new BudgetValue(task.getPriority()*Parameters.CURIOSITY_DESIRE_PRIORITY_MUL,task.getDurability()*Parameters.CURIOSITY_DESIRE_DURABILITY_MUL,BudgetFunctions.truthToQuality(truth)));
}
}
}
/**
* Meta-table of syllogistic rules, indexed by the content classes of the
* taskSentence and the belief
*
* @param tLink The link to task
* @param bLink The link to belief
* @param taskTerm The content of task
* @param beliefTerm The content of belief
* @param nal Reference to the memory
*/
private static void syllogisms(final TaskLink tLink, final TermLink bLink, final Term taskTerm, final Term beliefTerm, final DerivationContext nal) {
final Sentence taskSentence = nal.getCurrentTask().sentence;
final Sentence belief = nal.getCurrentBelief();
final int figure;
if (taskTerm instanceof Inheritance) {
if (beliefTerm instanceof Inheritance) {
figure = indexToFigure(tLink, bLink);
asymmetricAsymmetric(taskSentence, belief, figure, nal);
} else if (beliefTerm instanceof Similarity) {
figure = indexToFigure(tLink, bLink);
asymmetricSymmetric(taskSentence, belief, figure, nal);
} else {
detachmentWithVar(belief, taskSentence, bLink.getIndex(0), nal);
}
} else if (taskTerm instanceof Similarity) {
if (beliefTerm instanceof Inheritance) {
figure = indexToFigure(bLink, tLink);
asymmetricSymmetric(belief, taskSentence, figure, nal);
} else if (beliefTerm instanceof Similarity) {
figure = indexToFigure(bLink, tLink);
symmetricSymmetric(belief, taskSentence, figure, nal);
} else if (beliefTerm instanceof Implication) {
//Bridge to higher order statements:
figure = indexToFigure(tLink, bLink);
asymmetricSymmetric(belief, taskSentence, figure, nal);
} else if (beliefTerm instanceof Equivalence) {
//Bridge to higher order statements:
figure = indexToFigure(tLink, bLink);
symmetricSymmetric(belief, taskSentence, figure, nal);
}
} else if (taskTerm instanceof Implication) {
if (beliefTerm instanceof Implication) {
figure = indexToFigure(tLink, bLink);
asymmetricAsymmetric(taskSentence, belief, figure, nal);
} else if (beliefTerm instanceof Equivalence) {
figure = indexToFigure(tLink, bLink);
asymmetricSymmetric(taskSentence, belief, figure, nal);
} else if (beliefTerm instanceof Inheritance) {
detachmentWithVar(taskSentence, belief, tLink.getIndex(0), nal);
} else if (beliefTerm instanceof Similarity) {
//Bridge to higher order statements:
figure = indexToFigure(tLink, bLink);
asymmetricSymmetric(taskSentence, belief, figure, nal);
}
} else if (taskTerm instanceof Equivalence) {
if (beliefTerm instanceof Implication) {
figure = indexToFigure(bLink, tLink);
asymmetricSymmetric(belief, taskSentence, figure, nal);
} else if (beliefTerm instanceof Equivalence) {
figure = indexToFigure(bLink, tLink);
symmetricSymmetric(belief, taskSentence, figure, nal);
} else if (beliefTerm instanceof Inheritance) {
detachmentWithVar(taskSentence, belief, tLink.getIndex(0), nal);
} else if (beliefTerm instanceof Similarity) {
//Bridge to higher order statements:
figure = indexToFigure(tLink, bLink);
symmetricSymmetric(belief, taskSentence, figure, nal);
}
}
}
/**
* Decide the figure of syllogism according to the locations of the common
* term in the premises
*
* @param link1 The link to the first premise
* @param link2 The link to the second premise
* @return The figure of the syllogism, one of the four: 11, 12, 21, or 22
*/
private static final int indexToFigure(final TLink link1, final TLink link2) {
return (link1.getIndex(0) + 1) * 10 + (link2.getIndex(0) + 1);
}
/**
* Syllogistic rules whose both premises are on the same asymmetric relation
*
* @param taskSentence The taskSentence in the task
* @param belief The judgment in the belief
* @param figure The location of the shared term
* @param nal Reference to the memory
*/
private static void asymmetricAsymmetric(final Sentence taskSentence, final Sentence belief, final int figure, final DerivationContext nal) {
Statement taskStatement = (Statement) taskSentence.term;
Statement beliefStatement = (Statement) belief.term;
final Term t1;
final Term t2;
final Term[] u = new Term[] { taskStatement, beliefStatement };
switch (figure) {
case 11: // induction
if (Variables.unify(VAR_INDEPENDENT, taskStatement.getSubject(), beliefStatement.getSubject(), u)) {
taskStatement = (Statement) u[0];
beliefStatement = (Statement) u[1];
if (taskStatement.equals(beliefStatement)) {
return;
}
t1 = beliefStatement.getPredicate();
t2 = taskStatement.getPredicate();
final boolean sensational = SyllogisticRules.abdIndCom(t1, t2, taskSentence, belief, figure, nal);
if(sensational) {
return;
}
CompositionalRules.composeCompound(taskStatement, beliefStatement, 0, nal);
//if(taskSentence.getOccurenceTime()==Stamp.ETERNAL && belief.getOccurenceTime()==Stamp.ETERNAL)
CompositionalRules.introVarOuter(taskStatement, beliefStatement, 0, nal);//introVarImage(taskContent, beliefContent, index, memory);
CompositionalRules.eliminateVariableOfConditionAbductive(figure,taskSentence,belief,nal);
}
break;
case 12: // deduction
if (Variables.unify(VAR_INDEPENDENT, taskStatement.getSubject(), beliefStatement.getPredicate(), u)) {
taskStatement = (Statement) u[0];
beliefStatement = (Statement) u[1];
if (taskStatement.equals(beliefStatement)) {
return;
}
t1 = beliefStatement.getSubject();
t2 = taskStatement.getPredicate();
if (Variables.unify(VAR_QUERY, t1, t2, new Term[] { taskStatement, beliefStatement })) {
LocalRules.matchReverse(nal);
} else {
SyllogisticRules.dedExe(t1, t2, taskSentence, belief, nal);
}
}
break;
case 21: // exemplification
if (Variables.unify(VAR_INDEPENDENT, taskStatement.getPredicate(), beliefStatement.getSubject(), u)) {
taskStatement = (Statement) u[0];
beliefStatement = (Statement) u[1];
if (taskStatement.equals(beliefStatement)) {
return;
}
t1 = taskStatement.getSubject();
t2 = beliefStatement.getPredicate();
if (Variables.unify(VAR_QUERY, t1, t2, new Term[] { taskStatement, beliefStatement })) {
LocalRules.matchReverse(nal);
} else {
SyllogisticRules.dedExe(t1, t2, taskSentence, belief, nal);
}
}
break;
case 22: // abduction
if (Variables.unify(VAR_INDEPENDENT, taskStatement.getPredicate(), beliefStatement.getPredicate(), u)) {
taskStatement = (Statement) u[0];
beliefStatement = (Statement) u[1];
if (taskStatement.equals(beliefStatement)) {
return;
}
t1 = taskStatement.getSubject();
t2 = beliefStatement.getSubject();
if (!SyllogisticRules.conditionalAbd(t1, t2, taskStatement, beliefStatement, nal)) { // if conditional abduction, skip the following
final boolean sensational = SyllogisticRules.abdIndCom(t1, t2, taskSentence, belief, figure, nal);
if(sensational) {
return;
}
CompositionalRules.composeCompound(taskStatement, beliefStatement, 1, nal);
CompositionalRules.introVarOuter(taskStatement, beliefStatement, 1, nal);// introVarImage(taskContent, beliefContent, index, memory);
}
CompositionalRules.eliminateVariableOfConditionAbductive(figure,taskSentence,belief,nal);
}
break;
default:
}
}
/**
* Syllogistic rules whose first premise is on an asymmetric relation, and
* the second on a symmetric relation
*
* @param asym The asymmetric premise
* @param sym The symmetric premise
* @param figure The location of the shared term
* @param nal Reference to the memory
*/
private static void asymmetricSymmetric(final Sentence asym, final Sentence sym, final int figure, final DerivationContext nal) {
Statement asymSt = (Statement) asym.term;
Statement symSt = (Statement) sym.term;
final Term t1;
final Term t2;
final Term[] u = new Term[] { asymSt, symSt };
final EnumStatementSide figureLeft = retSideFromFigure(figure, EnumFigureSide.LEFT);
final EnumStatementSide figureRight = retSideFromFigure(figure, EnumFigureSide.RIGHT);
if (!Variables.unify(VAR_INDEPENDENT, retBySide(asymSt, figureLeft), retBySide(symSt, figureRight), u)) {
return;
}
asymSt = (Statement) u[0];
symSt = (Statement) u[1];
t1 = retBySide(asymSt, retOppositeSide(figureLeft));
t2 = retBySide(symSt, retOppositeSide(figureRight));
if (Variables.unify(VAR_QUERY, t1, t2, u)) {
LocalRules.matchAsymSym(asym, sym, figure, nal);
} else {
switch (figure) {
case 11:
case 12:
SyllogisticRules.analogy(t2, t1, asym, sym, figure, nal);
break;
case 21:
case 22:
SyllogisticRules.analogy(t1, t2, asym, sym, figure, nal);
break;
}
}
}
/**
* returns the subject (0) or predicate(1)
* @param statement statement for which the side has to be returned
* @param side subject(0) or predicate(1)
* @return the term of the side
*/
static Term retBySide(Statement statement, EnumStatementSide side) {
return side == EnumStatementSide.SUBJECT ? statement.getSubject() : statement.getPredicate();
}
static EnumStatementSide retOppositeSide(EnumStatementSide side) {
return side == EnumStatementSide.SUBJECT ? EnumStatementSide.PREDICATE : EnumStatementSide.SUBJECT;
}
/**
* converts the side of a figure to a zero based index - which determines the side of the Statement
*
* a figure is a encoding for the sides
* @param figure figure encoding as 11 or 12 or 21 or 22
* @param sideOfFigure side
* @return
*/
static EnumStatementSide retSideFromFigure(int figure, EnumFigureSide sideOfFigure) {
if( sideOfFigure == EnumFigureSide.LEFT ) {
switch(figure) {
case 11: return EnumStatementSide.SUBJECT;
case 12: return EnumStatementSide.SUBJECT;
case 21: return EnumStatementSide.PREDICATE;
case 22: return EnumStatementSide.PREDICATE;
}
}
else {
switch(figure) {
case 11: return EnumStatementSide.SUBJECT;
case 12: return EnumStatementSide.PREDICATE;
case 21: return EnumStatementSide.SUBJECT;
case 22: return EnumStatementSide.PREDICATE;
}
}
throw new IllegalArgumentException("figure is invalid");
}
enum EnumStatementSide {
SUBJECT,
PREDICATE,
}
enum EnumFigureSide {
LEFT,
RIGHT,
}
/**
* Syllogistic rules whose both premises are on the same symmetric relation
*
* @param belief The premise that comes from a belief
* @param taskSentence The premise that comes from a task
* @param figure The location of the shared term
* @param nal Reference to the memory
*/
private static void symmetricSymmetric(final Sentence belief, final Sentence taskSentence, final int figure, final DerivationContext nal) {
final Statement s1 = (Statement) belief.term;
final Statement s2 = (Statement) taskSentence.term;
final Term ut1; //parameters for unify()
final Term ut2;
Term rt1, rt2; //parameters for resemblance()
switch (figure) {
case 11:
ut1 = s1.getSubject();
ut2 = s2.getSubject();
rt1 = s1.getPredicate();
rt2 = s2.getPredicate();
break;
case 12:
ut1 = s1.getSubject();
ut2 = s2.getPredicate();
rt1 = s1.getPredicate();
rt2 = s2.getSubject();
break;
case 21:
ut1 = s1.getPredicate();
ut2 = s2.getSubject();
rt1 = s1.getSubject();
rt2 = s2.getPredicate();
break;
case 22:
ut1 = s1.getPredicate();
ut2 = s2.getPredicate();
rt1 = s1.getSubject();
rt2 = s2.getSubject();
break;
default:
throw new IllegalStateException("Invalid figure: " + figure);
}
final Term[] u = new Term[] { s1, s2 };
if (Variables.unify(VAR_INDEPENDENT, ut1, ut2, u)) {
//recalculate rt1, rt2 from above:
switch (figure) {
case 11: rt1 = s1.getPredicate(); rt2 = s2.getPredicate(); break;
case 12: rt1 = s1.getPredicate(); rt2 = s2.getSubject(); break;
case 21: rt1 = s1.getSubject(); rt2 = s2.getPredicate(); break;
case 22: rt1 = s1.getSubject(); rt2 = s2.getSubject(); break;
}
SyllogisticRules.resemblance(rt1, rt2, belief, taskSentence, figure, nal);
CompositionalRules.eliminateVariableOfConditionAbductive(
figure, taskSentence, belief, nal);
}
}
/**
* The detachment rule, with variable unification
*
* @param originalMainSentence The premise that is an Implication or
* Equivalence
* @param subSentence The premise that is the subject or predicate of the
* first one
* @param index The location of the second premise in the first
* @param nal Reference to the memory
*/
private static void detachmentWithVar(final Sentence originalMainSentence, final Sentence subSentence, final int index, final DerivationContext nal) {
detachmentWithVar(originalMainSentence, subSentence, index, true, nal);
}
private static void detachmentWithVar(final Sentence originalMainSentence, Sentence subSentence, final int index, final boolean checkTermAgain, final DerivationContext nal) {
if(originalMainSentence==null) {
return;
}
Sentence mainSentence = originalMainSentence; // for substitution
if (!(mainSentence.term instanceof Statement))
return;
final Statement statement = (Statement) mainSentence.term;
final Term component = statement.term[index];
final Term content = subSentence.term;
if (nal.getCurrentBelief() != null) {
final Term[] u = new Term[] { statement, content };
if (!component.hasVarIndep() && !component.hasVarDep()) { //because of example: <<(*,w1,#2) --> [good]> ==> <w1 --> TRANSLATE>>. <(*,w1,w2) --> [good]>.
SyllogisticRules.detachment(mainSentence, subSentence, index, checkTermAgain, nal);
} else if (Variables.unify(VAR_INDEPENDENT, component, content, u)) { //happens through syllogisms
mainSentence = mainSentence.clone(u[0]);
subSentence = subSentence.clone(u[1]);
SyllogisticRules.detachment(mainSentence, subSentence, index, false, nal);
} else if ((statement instanceof Implication) && (statement.getPredicate() instanceof Statement) && (nal.getCurrentTask().sentence.isJudgment())) {
final Statement s2 = (Statement) statement.getPredicate();
if ((content instanceof Statement) && (s2.getSubject().equals(((Statement) content).getSubject()))) {
CompositionalRules.introVarInner((Statement) content, s2, statement, nal);
}
CompositionalRules.IntroVarSameSubjectOrPredicate(originalMainSentence,subSentence,component,content,index,nal);
} else if ((statement instanceof Equivalence) && (statement.getPredicate() instanceof Statement) && (nal.getCurrentTask().sentence.isJudgment())) {
CompositionalRules.IntroVarSameSubjectOrPredicate(originalMainSentence,subSentence,component,content,index,nal);
}
}
}
/**
* Conditional deduction or induction, with variable unification
*
* @param conditional The premise that is an Implication with a Conjunction
* as condition
* @param index The location of the shared term in the condition
* @param statement The second premise that is a statement
* @param side The location of the shared term in the statement
* @param nal Reference to the memory
*/
private static void conditionalDedIndWithVar(final Sentence conditionalSentence, Implication conditional, final short index, Statement statement, short side, final DerivationContext nal) {
if (!(conditional.getSubject() instanceof CompoundTerm))
return;
final CompoundTerm condition = (CompoundTerm) conditional.getSubject();
if(condition instanceof Conjunction) { //conditionalDedIndWithVar
for(final Term t : condition.term) { //does not support the case where
if(t instanceof Variable) { //we have a variable inside of a conjunction
return; //(this can happen since we have # due to image transform,
} //although not for other conjunctions)
}
}
final Term component = condition.term[index];
Term component2 = null;
if (statement instanceof Inheritance || statement instanceof Similarity) {
component2 = statement;
side = -1;
} else if (statement instanceof Implication) {
component2 = statement.term[side];
}
if (component2 != null) {
final Term[] u = new Term[] { conditional, statement };
if (Variables.unify(VAR_INDEPENDENT, component, component2, u)) {
conditional = (Implication) u[0];
statement = (Statement) u[1];
SyllogisticRules.conditionalDedInd(conditionalSentence, conditional, index, statement, side, nal);
}
}
}
/**
* Inference between a compound term and a component of it
*
* @param compound The compound term
* @param component The component term
* @param compoundTask Whether the compound comes from the task
* @param nal Reference to the memory
*/
private static void compoundAndSelf(final CompoundTerm compound, final Term component, final boolean compoundTask, final int index, final DerivationContext nal) {
if ((compound instanceof Conjunction) || (compound instanceof Disjunction)) {
if (nal.getCurrentBelief() != null) {
if(compound.containsTerm(component)) {
StructuralRules.structuralCompound(compound, component, compoundTask, index, nal);
}
CompositionalRules.decomposeStatement(compound, component, compoundTask, index, nal);
} else if (compound.containsTerm(component)) {
StructuralRules.structuralCompound(compound, component, compoundTask, index, nal);
}
} else if (compound instanceof Negation) {
if (compoundTask) {
if (compound.term[0] instanceof CompoundTerm)
StructuralRules.transformNegation((CompoundTerm)compound.term[0], nal);
}
}
}
/**
* Inference between two compound terms
*
* @param taskTerm The compound from the task
* @param beliefTerm The compound from the belief
* @param nal Reference to the memory
*/
private static void compoundAndCompound(final CompoundTerm taskTerm, final CompoundTerm beliefTerm, final int tindex, final int bindex, final DerivationContext nal) {
if (taskTerm.getClass() == beliefTerm.getClass()) {
if (taskTerm.size() >= beliefTerm.size()) {
compoundAndSelf(taskTerm, beliefTerm, true, tindex, nal);
} else if (taskTerm.size() < beliefTerm.size()) {
compoundAndSelf(beliefTerm, taskTerm, false, bindex, nal);
}
}
}
/**
* Inference between a compound term and a statement
*
* @param compound The compound term
* @param index The location of the current term in the compound
* @param statement The statement
* @param side The location of the current term in the statement
* @param beliefTerm The content of the belief
* @param nal Reference to the memory
*/
private static void compoundAndStatement(CompoundTerm compound, final short index, Statement statement, final short side, final Term beliefTerm, final DerivationContext nal) {
if(index >= compound.term.length) {
return;
}
final Term component = compound.term[index];
final Task task = nal.getCurrentTask();
if (component.getClass() == statement.getClass()) {
if ((compound instanceof Conjunction) && (nal.getCurrentBelief() != null)) {
final Conjunction conj = (Conjunction) compound;
final Term[] u = new Term[] { compound, statement };
if (Variables.unify(VAR_DEPENDENT, component, statement, u)) {
compound = (Conjunction) u[0];
statement = (Statement) u[1];
if(conj.isSpatial || compound.getTemporalOrder() != TemporalRules.ORDER_FORWARD || //only allow dep var elimination
index == 0) { //for (&/ on first component!!
SyllogisticRules.elimiVarDep(compound, component,
statement.equals(beliefTerm),
nal);
}
} else if (task.sentence.isJudgment()) { // && !compound.containsTerm(component)) {
CompositionalRules.introVarInner(statement, (Statement) component, compound, nal);
}
}
} else {
if (task.sentence.isJudgment()) {
if (statement instanceof Inheritance) {
StructuralRules.structuralCompose1(compound, index, statement, nal);
if (!(compound instanceof SetExt || compound instanceof SetInt || compound instanceof Negation
|| compound instanceof Conjunction || compound instanceof Disjunction)) {
StructuralRules.structuralCompose2(compound, index, statement, side, nal);
} // {A --> B, A @ (A&C)} |- (A&C) --> (B&C)
} else if (!(compound instanceof Negation || compound instanceof Conjunction || compound instanceof Disjunction)) {
StructuralRules.structuralCompose2(compound, index, statement, side, nal);
} // {A <-> B, A @ (A&C)} |- (A&C) <-> (B&C)
}
}
}
/**
* Inference between a component term (of the current term) and a statement
*
* @param compound The compound term
* @param index The location of the current term in the compound
* @param statement The statement
* @param side The location of the current term in the statement
* @param nal Reference to the memory
*/
private static void componentAndStatement(final CompoundTerm compound, final short index, final Statement statement, final short side, final DerivationContext nal) {
if (statement instanceof Inheritance) {
StructuralRules.structuralDecompose1(compound, index, statement, nal);
if (!(compound instanceof SetExt) && !(compound instanceof SetInt)) {
StructuralRules.structuralDecompose2(statement, index, nal); // {(C-B) --> (C-A), A @ (C-A)} |- A --> B
} else {
StructuralRules.transformSetRelation(compound, statement, side, nal);
}
} else if (statement instanceof Similarity) {
StructuralRules.structuralDecompose2(statement, index, nal); // {(C-B) --> (C-A), A @ (C-A)} |- A --> B
if ((compound instanceof SetExt) || (compound instanceof SetInt)) {
StructuralRules.transformSetRelation(compound, statement, side, nal);
}
}
else if ((statement instanceof Implication) && (compound instanceof Negation)) {
if (index == 0) {
StructuralRules.contraposition(statement, nal.getCurrentTask().sentence, nal);
} else {
StructuralRules.contraposition(statement, nal.getCurrentBelief(), nal);
}
}
}
/**
* The TaskLink is of type TRANSFORM, and the conclusion is an equivalent
* transformation
*
* @param tLink The task link
* @param nal Reference to the memory
*/
public static void transformTask(final TaskLink tLink, final DerivationContext nal) {
final CompoundTerm content = (CompoundTerm) nal.getCurrentTask().getTerm();
final short[] indices = tLink.index;
Term inh = null;
if ((indices.length == 2) || (content instanceof Inheritance)) { // <(*, term,
inh = content;
} else if (indices.length == 3) { // <<(*, term,
inh = content.term[indices[0]];
} else if (indices.length == 4) { // <(&&, <(*, term,
final Term component = content.term[indices[0]];
if ((component instanceof Conjunction) && (((content instanceof Implication) && (indices[0] == 0)) || (content instanceof Equivalence))) {
final Term[] cterms = ((CompoundTerm) component).term;
if (indices[1] < cterms.length-1) {
inh = cterms[indices[1]];
}
else {
return;
}
} else {
return;
}
}
if (inh instanceof Inheritance) {
StructuralRules.transformProductImage((Inheritance) inh, content, indices, nal);
}
}
}
|
/**
* File Vec3.java
* @author Yuri Kravchik
* Created 16.10.2008
*/
package yk.jcommon.fastgeom;
import java.io.Serializable;
/**
* Vec3
*
* @author Yuri Kravchik Created 16.10.2008
*/
public class Vec3f implements Serializable {
public final float x, y, z;
public static final Vec3f ZERO = new Vec3f(0, 0, 0);
public static final Vec3f AXISX = new Vec3f(1, 0, 0);
public static final Vec3f AXISY = new Vec3f(0, 1, 0);
public static final Vec3f AXISZ = new Vec3f(0, 0, 1);
public Vec3f(final float x, final float y, final float z) {
this.x = x;
this.y = y;
this.z = z;
}
public static Vec3f v(final float x, final float y, final float z) {
return new Vec3f(x, y, z);
}
public static Vec3f v3(final float x, final float y, final float z) {
return new Vec3f(x, y, z);
}
public Vec3f(Vec2f v, float z) {
this(v.x, v.y, z);
}
public Vec3f(Vec3f from) {
this.x = from.x;
this.y = from.y;
this.z = from.z;
}
public Vec3f add(final Vec3f b) {
return new Vec3f(x + b.x, y + b.y, z + b.z);
}
public Vec3f add(float x, float y, float z) {
return new Vec3f(this.x + x, this.y + y, this.z + z);
}
public Vec3f crossProduct(final Vec3f b) {
return new Vec3f(y * b.z - z * b.y, z * b.x - x * b.z, x * b.y - y * b.x);
}
public Vec3f div(final float value) {
return new Vec3f(x / value, y / value, z / value);
}
public float getX() {
return x;
}
public Vec2f getXY() {
return new Vec2f(x, y);
}
public Vec2f getXZ() {
return new Vec2f(x, z);
}
public float getY() {
return y;
}
public Vec2f getYZ() {
return new Vec2f(y, z);
}
public float getZ() {
return z;
}
public Vec3f mul(final float b) {
return new Vec3f(x * b, y * b, z * b);
}
public Vec3f mul(final Vec3f b) {
return new Vec3f(x * b.x, y * b.y, z * b.z);
}
public Vec3f mul(float x, float y, float z) {
return new Vec3f(this.x * x, this.y * y, this.z * z);
}
public Vec3f normalized() {
final float radius = 1 / (float) Math.sqrt(x * x + y * y + z * z);
return new Vec3f(x * radius, y * radius, z * radius);
}
public Vec3f normalized(float r) {
final float radius = r / (float) Math.sqrt(x * x + y * y + z * z);
return new Vec3f(x * radius, y * radius, z * radius);
}
public float scalarProduct(final Vec3f b) {
return x * b.x + y * b.y + z * b.z;
}
public Vec3f sub(final Vec3f b) {
return new Vec3f(x - b.x, y - b.y, z - b.z);
}
public Vec3f sub(float x, float y, float z) {
return new Vec3f(this.x - x, this.y - y, this.z - z);
}
@Override
public String toString() {
return "x: " + x + " y: " + y + " z: " + z;
}
public float dist(Vec3f b) {
return sub(b).length();
}
public float length() {
return (float) Math.sqrt(x*x+y*y+z*z);
}
public static Vec3f mean(Vec3f... vv) {
return sum(vv).div(vv.length);
}
public static Vec3f sum(Vec3f... vv) {
float x = 0;
float y = 0;
float z = 0;
for (int i = 0; i < vv.length; i++) {
x += vv[i].x;
y += vv[i].y;
z += vv[i].z;
}
return new Vec3f(x, y, z);
}
public Vec3f mirror(Vec3f around) {
return sub(around).mul(-1).add(around);
}
/**
* this 0 -> 1 to
* @param to
* @param blend
* @return
*/
public Vec3f lerp(Vec3f to, float blend) {
return to.sub(this).mul(blend).add(this);
}
//0 - a, 1 - b
public static Vec3f mix(Vec3f a, Vec3f b, float ab) {
return b.sub(a).mul(ab).add(a);
}
public Vec3f plus(Vec3f other) {//groovy operator overloading
return add(other);
}
public Vec3f multiply(Vec3f other) {//groovy operator overloading
return mul(other);
}
public Vec3f multiply(float f) {//groovy operator overloading
return mul(f);
}
public Vec2f getXy() {
return new Vec2f(x, y);
}
}
|
package org.oucs.gaboto.timedim;
/**
* Utility class providing useful constants.
*
* @author Arno Mittelbach
* @version 0.1
*/
public class TimeUtils {
/**
* You could also refer to this as the beginning of time.
*
* Integer.MIN_INT does not work since the duration is also represented as an integer.
* This might be changed at some point to use longs instead of int.
*/
public static final TimeInstant BIG_BANG = new TimeInstant(-100000000, 0, 1);
/**
* You could also refer to this as the end of time or the big crunch ..
*
* Integer.MAXINT does not work since the duration is also represented as an integer.
* This might be changed at some point to use longs instead of integers.
*/
public static final TimeInstant DOOMS_DAY = new TimeInstant(100000000, 11, 31);
/**
* Describes the time span from BIG_BANG to DOOMS_DAY.
*
* @see #BIG_BANG
* @see #DOOMS_DAY
*/
public static final TimeSpan EXISTENCE = TimeSpan.createFromInstants(TimeUtils.BIG_BANG, TimeUtils.DOOMS_DAY);
}
|
package org.scribe.builder;
import org.scribe.builder.api.*;
import org.scribe.exceptions.*;
import org.scribe.model.*;
import org.scribe.oauth.*;
import org.scribe.utils.*;
/**
* Implementation of the Builder pattern, with a fluent interface that creates a
* {@link OAuthService}
*
* @author Pablo Fernandez
*
*/
public class ServiceBuilder
{
private String apiKey;
private String apiSecret;
private String callback;
private Api api;
private String scope;
public ServiceBuilder()
{
this.callback = OAuthConstants.OUT_OF_BAND;
}
/**
* Configures the {@link Api}
*
* @param apiClass the class of one of the existent {@link Api}s on org.scribe.api package
* @return the {@link ServiceBuilder} instance for method chaining
*/
public ServiceBuilder provider(Class<? extends Api> apiClass)
{
this.api = createApi(apiClass);
return this;
}
private Api createApi(Class<? extends Api> apiClass)
{
Preconditions.checkNotNull(apiClass, "Api class cannot be null");
Api api;
try
{
api = apiClass.newInstance();
}
catch(Exception e)
{
throw new OAuthException("Error while creating the Api object", e);
}
return api;
}
/**
* Adds an OAuth callback url
*
* @param callback callback url. Must be a valid url or 'oob' for out of band OAuth
* @return the {@link ServiceBuilder} instance for method chaining
*/
public ServiceBuilder callback(String callback)
{
Preconditions.checkValidOAuthCallback(callback, "Callback must be a valid URL or 'oob'");
this.callback = callback;
return this;
}
/**
* Configures the api key
*
* @param apiKey The api key for your application
* @return the {@link ServiceBuilder} instance for method chaining
*/
public ServiceBuilder apiKey(String apiKey)
{
Preconditions.checkEmptyString(apiKey, "Invalid Api key");
this.apiKey = apiKey;
return this;
}
/**
* Configures the api secret
*
* @param apiSecret The api secret for your application
* @return the {@link ServiceBuilder} instance for method chaining
*/
public ServiceBuilder apiSecret(String apiSecret)
{
Preconditions.checkEmptyString(apiSecret, "Invalid Api secret");
this.apiSecret = apiSecret;
return this;
}
/**
* Configures the OAuth scope. This is only necessary in some APIs (like Google's).
*
* @param scope The OAuth scope
* @return the {@link ServiceBuilder} instance for method chaining
*/
public ServiceBuilder scope(String scope)
{
Preconditions.checkEmptyString(scope, "Invalid OAuth scope");
this.scope = scope;
return this;
}
/**
* Returns the fully configured {@link OAuthService}
*
* @return fully configured {@link OAuthService}
*/
public OAuthService build()
{
Preconditions.checkNotNull(api, "You must specify a valid api through the provider() method");
Preconditions.checkEmptyString(apiKey, "You must provide an api key");
Preconditions.checkEmptyString(apiSecret, "You must provide an api secret");
return api.createService(apiKey, apiSecret, callback, scope);
}
}
|
package org.threeten.extra.chrono;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.DAY_OF_YEAR;
import static java.time.temporal.ChronoField.EPOCH_DAY;
import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
import static java.time.temporal.ChronoField.YEAR;
import static org.threeten.extra.chrono.PaxChronology.DAYS_IN_MONTH;
import static org.threeten.extra.chrono.PaxChronology.DAYS_IN_WEEK;
import static org.threeten.extra.chrono.PaxChronology.DAYS_IN_YEAR;
import static org.threeten.extra.chrono.PaxChronology.MONTHS_IN_YEAR;
import static org.threeten.extra.chrono.PaxChronology.WEEKS_IN_LEAP_MONTH;
import static org.threeten.extra.chrono.PaxChronology.WEEKS_IN_MONTH;
import static org.threeten.extra.chrono.PaxChronology.WEEKS_IN_YEAR;
import java.io.Serializable;
import java.time.Clock;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.chrono.ChronoLocalDate;
import java.time.chrono.ChronoLocalDateTime;
import java.time.chrono.ChronoPeriod;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalQueries;
import java.time.temporal.TemporalQuery;
import java.time.temporal.TemporalUnit;
import java.time.temporal.ValueRange;
public final class PaxDate
extends AbstractDate
implements ChronoLocalDate, Serializable {
/**
* Serialization version.
*/
private static final long serialVersionUID = -2229133057743750072L;
/**
* The difference between the ISO and Pax epoch day count (Pax 0001-01-01 to ISO 1970-01-01).
*/
private static final int PAX_0001_TO_ISO_1970 = 719163;
/**
* The days per 400 year cycle.
*/
private static final int DAYS_PER_LONG_CYCLE = (DAYS_IN_YEAR * 400) + (DAYS_IN_WEEK * 71);
/**
* The days per 100 year cycle.
*/
private static final int DAYS_PER_CYCLE = (DAYS_IN_YEAR * 100) + (DAYS_IN_WEEK * 18);
/**
* The days per 6 year cycle.
*/
private static final int DAYS_PER_SIX_CYCLE = (DAYS_IN_YEAR * 6) + (DAYS_IN_WEEK * 1);
/**
* Number of years in a decade.
*/
private static final int YEARS_IN_DECADE = 10;
/**
* Number of years in a century.
*/
private static final int YEARS_IN_CENTURY = 100;
/**
* Number of years in a millennium.
*/
private static final int YEARS_IN_MILLENNIUM = 1000;
/**
* The proleptic year.
*/
private final int prolepticYear;
/**
* The month.
*/
private final short month;
/**
* The day.
*/
private final short day;
/**
* Obtains the current {@code PaxDate} from the system clock in the default time-zone.
* <p>
* This will query the {@link Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current date.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @return the current date using the system clock and default time-zone, not null
*/
public static PaxDate now() {
return now(Clock.systemDefaultZone());
}
/**
* Obtains the current {@code PaxDate} from the system clock in the specified time-zone.
* <p>
* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.
* Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @param zone the zone ID to use, not null
* @return the current date using the system clock, not null
*/
public static PaxDate now(ZoneId zone) {
return now(Clock.system(zone));
}
/**
* Obtains the current {@code PaxDate} from the specified clock.
* <p>
* This will query the specified clock to obtain the current date - today.
* Using this method allows the use of an alternate clock for testing.
* The alternate clock may be introduced using {@linkplain Clock dependency injection}.
*
* @param clock the clock to use, not null
* @return the current date, not null
* @throws DateTimeException if the current date cannot be obtained
*/
public static PaxDate now(Clock clock) {
LocalDate now = LocalDate.now(clock);
return PaxDate.ofEpochDay(now.toEpochDay());
}
/**
* Obtains a {@code PaxDate} representing a date in the Pax calendar
* system from the proleptic-year, month-of-year and day-of-month fields.
* <p>
* This returns a {@code PaxDate} with the specified fields.
* The day must be valid for the year and month, otherwise an exception will be thrown.
*
* @param prolepticYear the Pax proleptic-year
* @param month the Pax month-of-year, from 1 to 14
* @param dayOfMonth the Pax day-of-month, from 1 to 28
* @return the date in Pax calendar system, not null
* @throws DateTimeException if the value of any field is out of range,
* or if the day-of-month is invalid for the month-year
*/
public static PaxDate of(int prolepticYear, int month, int dayOfMonth) {
YEAR.checkValidValue(prolepticYear);
PaxChronology.MONTH_OF_YEAR_RANGE.checkValidValue(month, MONTH_OF_YEAR);
PaxChronology.DAY_OF_MONTH_RANGE.checkValidValue(dayOfMonth, DAY_OF_MONTH);
if (month == MONTHS_IN_YEAR + 1 && !PaxChronology.INSTANCE.isLeapYear(prolepticYear)) {
throw new DateTimeException("Invalid month 14 as " + prolepticYear + "is not a leap year");
}
if (dayOfMonth > DAYS_IN_WEEK && month == MONTHS_IN_YEAR && PaxChronology.INSTANCE.isLeapYear(prolepticYear)) {
throw new DateTimeException("Invalid date during Pax as " + prolepticYear + " is a leap year");
}
return new PaxDate(prolepticYear, month, dayOfMonth);
}
public static PaxDate from(TemporalAccessor temporal) {
if (temporal instanceof PaxDate) {
return (PaxDate) temporal;
}
return PaxDate.ofEpochDay(temporal.getLong(EPOCH_DAY));
}
/**
* Obtains a {@code PaxDate} representing a date in the Pax calendar
* system from the proleptic-year and day-of-year fields.
* <p>
* This returns a {@code PaxDate} with the specified fields.
* The day must be valid for the year, otherwise an exception will be thrown.
*
* @param prolepticYear the Pax proleptic-year
* @param dayOfYear the Pax day-of-year, from 1 to 371
* @return the date in Pax calendar system, not null
* @throws DateTimeException if the value of any field is out of range,
* or if the day-of-year is invalid for the year
*/
static PaxDate ofYearDay(int prolepticYear, int dayOfYear) {
YEAR.checkValidValue(prolepticYear);
PaxChronology.DAY_OF_YEAR_RANGE.checkValidValue(dayOfYear, DAY_OF_YEAR);
boolean leap = PaxChronology.INSTANCE.isLeapYear(prolepticYear);
if (dayOfYear > DAYS_IN_YEAR && !leap) {
throw new DateTimeException("Invalid date 'DayOfYear " + dayOfYear + "' as '" + prolepticYear + "' is not a leap year");
}
int month = ((dayOfYear - 1) / DAYS_IN_MONTH) + 1;
// In leap years, the leap-month is shorter than the following month, so needs to be adjusted.
if (leap && month == MONTHS_IN_YEAR && dayOfYear >= (DAYS_IN_YEAR + DAYS_IN_WEEK) - DAYS_IN_MONTH + 1) {
month++;
}
// Subtract days-at-start-of-month from days in year
int dayOfMonth = dayOfYear - (month - 1) * DAYS_IN_MONTH;
// Adjust for shorter inserted leap-month.
if (month == MONTHS_IN_YEAR + 1) {
dayOfMonth += (DAYS_IN_MONTH - DAYS_IN_WEEK);
}
return of(prolepticYear, month, dayOfMonth);
}
/**
* Obtains a {@code PaxDate} representing a date in the Pax calendar
* system from the epoch-day.
*
* @param epochDay the epoch day to convert based on 1970-01-01 (ISO)
* @return the date in Pax calendar system, not null
* @throws DateTimeException if the epoch-day is out of range
*/
static PaxDate ofEpochDay(long epochDay) {
EPOCH_DAY.range().checkValidValue(epochDay, EPOCH_DAY);
// use of Pax 0001 makes non-leap century at end of (long) cycle.
long paxEpochDay = epochDay + PAX_0001_TO_ISO_1970;
int longCycle = (int) Math.floorDiv(paxEpochDay, DAYS_PER_LONG_CYCLE);
int cycle = (int) (paxEpochDay - longCycle * DAYS_PER_LONG_CYCLE) / DAYS_PER_CYCLE;
int dayOfCycle = (int) Math.floorMod(paxEpochDay - longCycle * DAYS_PER_LONG_CYCLE, DAYS_PER_CYCLE);
if (dayOfCycle >= DAYS_PER_CYCLE - DAYS_IN_YEAR - DAYS_IN_WEEK) {
// Is in the century year
int dayOfYear = dayOfCycle - (DAYS_PER_CYCLE - DAYS_IN_YEAR - DAYS_IN_WEEK) + 1;
return ofYearDay(longCycle * 400 + cycle * 100 + 100, dayOfYear);
}
// For negative years, the cycle of leap years runs the other direction for 99s and 6s.
if (paxEpochDay >= 0) {
if (dayOfCycle >= DAYS_PER_CYCLE - 2 * DAYS_IN_YEAR - 2 * DAYS_IN_WEEK) {
// Is in the '99 year
int dayOfYear = dayOfCycle - (DAYS_PER_CYCLE - 2 * DAYS_IN_YEAR - 2 * DAYS_IN_WEEK) + 1;
return ofYearDay(longCycle * 400 + cycle * 100 + 99, dayOfYear);
}
// Otherwise, part of the regular 6-year cycle.
int sixCycle = dayOfCycle / DAYS_PER_SIX_CYCLE;
int dayOfSixCycle = dayOfCycle % DAYS_PER_SIX_CYCLE;
int year = dayOfSixCycle / DAYS_IN_YEAR + 1;
int dayOfYear = dayOfSixCycle % DAYS_IN_YEAR + 1;
if (year == 7) {
year
dayOfYear += DAYS_IN_YEAR;
}
return ofYearDay(longCycle * 400 + cycle * 100 + sixCycle * 6 + year, dayOfYear);
} else {
if (dayOfCycle < DAYS_IN_YEAR + DAYS_IN_WEEK) {
// -'99 year is at _start_ of cycle (first year encountered).
return ofYearDay(longCycle * 400 + cycle * 100 + (100 - 99), dayOfCycle + 1);
}
// Otherwise, part of the regular 6-year cycle, but offset -'96 to be end of six-year-cycle first.
int offsetCycle = dayOfCycle + 2 * DAYS_IN_YEAR - DAYS_IN_WEEK;
int sixCycle = offsetCycle / DAYS_PER_SIX_CYCLE;
int dayOfSixCycle = offsetCycle % DAYS_PER_SIX_CYCLE;
int year = dayOfSixCycle / DAYS_IN_YEAR + 1;
int dayOfYear = dayOfSixCycle % DAYS_IN_YEAR + 1;
if (year == 7) {
year
dayOfYear += DAYS_IN_YEAR;
}
return ofYearDay(longCycle * 400 + cycle * 100 + (100 - (99 + 3 - (sixCycle * 6 + year))), dayOfYear);
}
}
private static PaxDate resolvePreviousValid(int prolepticYear, int month, int day) {
int monthR = Math.min(month, MONTHS_IN_YEAR + (PaxChronology.INSTANCE.isLeapYear(prolepticYear) ? 1 : 0));
int dayR = Math.min(day, month == MONTHS_IN_YEAR && PaxChronology.INSTANCE.isLeapYear(prolepticYear) ? DAYS_IN_WEEK : DAYS_IN_MONTH);
return PaxDate.of(prolepticYear, monthR, dayR);
}
/**
* Get the count of leap months since proleptic month 0.
* <p>
* This number is negative if the month is prior to Pax year 0.
** <p>
* Remember that if using this for things like turning months into days, you must first subtract this number from the proleptic month count.
*
* @param prolepticMonth The month.
* @return The number of leap months since proleptic month 0.
*/
private static long getLeapMonthsBefore(long prolepticMonth) {
long offsetMonth = prolepticMonth - (prolepticMonth <= 0 ? 13 : 13 - 1);
// First, see getLeapYearsBefore(...) for explanations.
// return 18 * Math.floorDiv(offsetMonth, 100 * MONTHS_IN_YEAR + (getLeapYearsBefore(100) + 1))
// - Math.floorDiv(offsetMonth, 400 * MONTHS_IN_YEAR + (getLeapYearsBefore(400) + 1))
// + (((Math.floorMod(offsetMonth, 100 * MONTHS_IN_YEAR + (getLeapYearsBefore(100) + 1)) - (offsetMonth <= 0 ? 100 * MONTHS_IN_YEAR + getLeapYearsBefore(100) : 0))
// / (99 * MONTHS_IN_YEAR + (getLeapYearsBefore(99) + 1))) + (offsetMonth <= 0 ? 1 : 0))
// + (Math.floorMod(offsetMonth, 100 * MONTHS_IN_YEAR + (getLeapYearsBefore(100) + 1)) + (offsetMonth <= 0 ? 2 * MONTHS_IN_YEAR - 1 : 0)) / (6 * MONTHS_IN_YEAR + 1);
return 18L * Math.floorDiv(offsetMonth, 1318)
- Math.floorDiv(offsetMonth, 5272)
+ (((Math.floorMod(offsetMonth, 1318) - (offsetMonth <= 0 ? 1317 : 0)) / 1304) + (offsetMonth <= 0 ? 1 : 0))
+ (Math.floorMod(offsetMonth, 1318) + (offsetMonth <= 0 ? 25 : 0)) / 79;
}
/**
* Get the count of leap years since Pax year 0.
* <p>
* This number is negative if the year is prior to Pax year 0.
*
* @param prolepticYear The year.
* @return The number of leap years since Pax year 0.
*/
private static long getLeapYearsBefore(long prolepticYear) {
// Some explanations are in order:
// - First, because this calculates "leap years from 0 to the start of the year",
// The 'current' year must be counted when the year is negative (hence Math.floorDiv(...)).
// - However, this means that there's a negative count which must be offset for the in-century years,
// which still occur at the "last two digits divisible by 6" (or 99) point.
// - Math.floorMod(...) returns a nicely positive result for negative years, counting 'down', but
// thus needs to be offset to make sure the first leap year is -6, and not -4...
// The second line, which calculates the '99 occurrences, runs "backwards", so must first be reversed, then the results flipped.
return 18L * Math.floorDiv(prolepticYear - 1, 100) - Math.floorDiv(prolepticYear - 1, 400) +
(Math.floorMod(prolepticYear - 1, 100) - (prolepticYear <= 0 ? 99 : 0)) / 99 + (prolepticYear <= 0 ? 1 : 0) +
((Math.floorMod(prolepticYear - 1, 100) + (prolepticYear <= 0 ? 2 : 0)) / 6);
}
/**
* Creates an instance from validated data.
*
* @param prolepticYear the Pax proleptic-year
* @param month the Pax month, from 1 to 14
* @param dayOfMonth the Pax day-of-month, from 1 to 28
*/
private PaxDate(int prolepticYear, int month, int dayOfMonth) {
this.prolepticYear = prolepticYear;
this.month = (short) month;
this.day = (short) dayOfMonth;
}
/**
* Validates the object.
*
* @return the resolved date, not null
*/
private Object readResolve() {
return PaxDate.of(prolepticYear, month, day);
}
@Override
int getProlepticYear() {
return prolepticYear;
}
@Override
int getMonth() {
return month;
}
@Override
int getDayOfMonth() {
return day;
}
@Override
int getDayOfYear() {
return (getMonth() - 1) * DAYS_IN_MONTH
- (getMonth() == MONTHS_IN_YEAR + 1 ? DAYS_IN_MONTH - DAYS_IN_WEEK : 0) + getDayOfMonth();
}
@Override
AbstractDate withDayOfYear(int value) {
return plusDays(value - getDayOfYear());
}
@Override
int lengthOfYearInMonths() {
return MONTHS_IN_YEAR + (isLeapYear() ? 1 : 0);
}
@Override
ValueRange rangeAlignedWeekOfMonth() {
return ValueRange.of(1, getMonth() == MONTHS_IN_YEAR && isLeapYear() ? WEEKS_IN_LEAP_MONTH : WEEKS_IN_MONTH);
}
@Override
PaxDate resolvePrevious(int newYear, int newMonth, int dayOfMonth) {
return resolvePreviousValid(newYear, newMonth, dayOfMonth);
}
@Override
public ValueRange range(TemporalField field) {
if (field == ChronoField.ALIGNED_WEEK_OF_YEAR) {
return ValueRange.of(1, WEEKS_IN_YEAR + (isLeapYear() ? 1 : 0));
} else if (field == ChronoField.MONTH_OF_YEAR) {
return ValueRange.of(1, MONTHS_IN_YEAR + (isLeapYear() ? 1 : 0));
}
return super.range(field);
}
/**
* Get the proleptic month from the start of the epoch (Pax 0000).
*
* @return The proleptic month.
*/
@Override
long getProlepticMonth() {
return ((long) getProlepticYear()) * MONTHS_IN_YEAR + getLeapYearsBefore(getProlepticYear()) + getMonth() - 1;
}
/**
* Gets the chronology of this date, which is the Pax calendar system.
* <p>
* The {@code Chronology} represents the calendar system in use.
* The era and other fields in {@link ChronoField} are defined by the chronology.
*
* @return the Pax chronology, not null
*/
@Override
public PaxChronology getChronology() {
return PaxChronology.INSTANCE;
}
/**
* Gets the era applicable at this date.
* <p>
* The Pax calendar system has two eras, 'CE' and 'BCE',
* defined by {@link PaxEra}.
*
* @return the era applicable at this date, not null
*/
@Override
public PaxEra getEra() {
return (prolepticYear >= 1 ? PaxEra.CE : PaxEra.BCE);
}
/**
* Returns the length of the month represented by this date.
* <p>
* This returns the length of the month in days.
* Month lengths do not match those of the ISO calendar system.
*
* @return the length of the month in days, from 7 to 28
*/
@Override
public int lengthOfMonth() {
switch (month) {
case 13:
return (isLeapYear() ? DAYS_IN_WEEK : DAYS_IN_MONTH);
default:
return DAYS_IN_MONTH;
}
}
@Override
public int lengthOfYear() {
return DAYS_IN_YEAR + (isLeapYear() ? DAYS_IN_WEEK : 0);
}
@Override
public PaxDate with(TemporalAdjuster adjuster) {
return (PaxDate) adjuster.adjustInto(this);
}
@Override
public PaxDate with(TemporalField field, long newValue) {
// Evaluate years as a special case, to deal with inserted leap months.
if (field == ChronoField.YEAR) {
return plusYears(newValue - getProlepticYear());
}
return (PaxDate) super.with(field, newValue);
}
@Override
public PaxDate plus(TemporalAmount amount) {
return (PaxDate) amount.addTo(this);
}
@Override
public PaxDate plus(long amountToAdd, TemporalUnit unit) {
return (PaxDate) super.plus(amountToAdd, unit);
}
/**
* Returns a copy of this {@code PaxDate} with the specified period in years added.
* <p>
* This method adds the specified amount to the years field in two steps:
* <ol>
* <li>Add the input years to the year field</li>
* <li>If necessary, shift the index to account for the inserted/deleted leap-month.</li>
* </ol>
* <p>
* In the Pax Calendar, the month of December is 13 in non-leap-years, and 14 in leap years.
* Shifting the index of the month thus means the month would still be the same.
* <p>
* In the case of moving from the inserted leap-month (destination year is non-leap), the month index is retained.
* This has the effect of retaining the same day-of-year.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param yearsToAdd the years to add, may be negative
* @return a {@code PaxDate} based on this date with the years added, not null
* @throws DateTimeException if the result exceeds the supported date range
*/
@Override
PaxDate plusYears(long yearsToAdd) {
if (yearsToAdd == 0) {
return this;
}
int newYear = YEAR.checkValidIntValue(getProlepticYear() + yearsToAdd);
// Retain actual month (not index) in the case where a leap month is to be inserted.
if (getMonth() == MONTHS_IN_YEAR && !isLeapYear() && PaxChronology.INSTANCE.isLeapYear(newYear)) {
return of(newYear, MONTHS_IN_YEAR + 1, getDayOfMonth());
}
// Otherwise, one of the following is true:
// 1 - Before the leap month, nothing to do (most common)
// 2 - Both source and destination in leap-month, nothing to do
// 3 - Both source and destination after leap month in leap year, nothing to do
// 4 - Source in leap month, but destination year not leap. Retain month index, preserving day-of-year.
// 5 - Source after leap month, but destination year not leap. Move month index back.
return resolvePreviousValid(newYear, month, day);
}
/**
* Returns a copy of this {@code PaxDate} with the specified period in months added.
* <p>
* This method adds the specified amount to the months field in three steps:
* <ol>
* <li>Add the input months to the month-of-year field</li>
* <li>Check if the resulting date would be invalid</li>
* <li>Adjust the day-of-month to the last valid day if necessary</li>
* </ol>
* <p>
* For example, 2006-12-13 plus one month would result in the invalid date 2006-13-13.
* Instead of returning an invalid result, the last valid day of the month, 2006-13-07, is selected instead.
* <p>
* This instance is immutable and unaffected by this method call.
*
* @param monthsToAdd the months to add, may be negative
* @return a {@code PaxDate} based on this date with the months added, not null
* @throws DateTimeException if the result exceeds the supported date range
*/
@Override
PaxDate plusMonths(long monthsToAdd) {
if (monthsToAdd == 0) {
return this;
}
long calcMonths = Math.addExact(getProlepticMonth(), monthsToAdd);
// "Regularize" the month count, as if years were all 13 months long.
long monthsRegularized = calcMonths - getLeapMonthsBefore(calcMonths);
int newYear = YEAR.checkValidIntValue(Math.floorDiv(monthsRegularized, MONTHS_IN_YEAR));
int newMonth = Math.toIntExact(calcMonths - (newYear * MONTHS_IN_YEAR + getLeapYearsBefore(newYear)) + 1);
return resolvePreviousValid(newYear, newMonth, getDayOfMonth());
}
@Override
public PaxDate minus(TemporalAmount amount) {
return (PaxDate) amount.subtractFrom(this);
}
@Override
public PaxDate minus(long amountToSubtract, TemporalUnit unit) {
return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
}
@Override // for covariant return type
@SuppressWarnings("unchecked")
public ChronoLocalDateTime<PaxDate> atTime(LocalTime localTime) {
return (ChronoLocalDateTime<PaxDate>) ChronoLocalDate.super.atTime(localTime);
}
@Override
public long until(Temporal endExclusive, TemporalUnit unit) {
return until(PaxDate.from(endExclusive), unit);
}
@Override
long until(AbstractDate end, TemporalUnit unit) {
if (unit instanceof ChronoUnit) {
PaxDate paxEnd = PaxDate.from(end);
switch ((ChronoUnit) unit) {
case YEARS:
return yearsUntil(paxEnd);
case DECADES:
return yearsUntil(paxEnd) / YEARS_IN_DECADE;
case CENTURIES:
return yearsUntil(paxEnd) / YEARS_IN_CENTURY;
case MILLENNIA:
return yearsUntil(paxEnd) / YEARS_IN_MILLENNIUM;
default:
break;
}
}
return super.until(end, unit);
}
/**
* Get the number of years from this date to the given day.
*
* @param end The end date.
* @return The number of years from this date to the given day.
*/
long yearsUntil(PaxDate end) {
// If either date is after the inserted leap month, and the other year isn't leap, simulate the effect of the inserted month.
long startYear = getProlepticYear() * 512L + getDayOfYear() + (this.getMonth() == MONTHS_IN_YEAR && !this.isLeapYear() && end.isLeapYear() ? DAYS_IN_WEEK : 0);
long endYear = end.getProlepticYear() * 512L + end.getDayOfYear() + (end.getMonth() == MONTHS_IN_YEAR && !end.isLeapYear() && this.isLeapYear() ? DAYS_IN_WEEK : 0);
return (endYear - startYear) / 512L;
}
@Override
public ChronoPeriod until(ChronoLocalDate endDate) {
PaxDate end = PaxDate.from(endDate);
int years = Math.toIntExact(yearsUntil(end));
// Get to the same "whole" year.
PaxDate sameYearEnd = end.plusYears(years);
int months = (int) monthsUntil(sameYearEnd);
int days = (int) daysUntil(sameYearEnd.plusMonths(months));
return getChronology().period(years, months, days);
}
@Override
public long toEpochDay() {
long days = ((long) getProlepticYear() - 1) * DAYS_IN_YEAR + getLeapYearsBefore(getProlepticYear()) * DAYS_IN_WEEK + getDayOfYear() - 1;
// Rebase to ISO 1970.
return days - PAX_0001_TO_ISO_1970;
}
}
|
package org.xtx.ut4converter.t3d;
import java.util.HashMap;
import java.util.Map;
import javax.vecmath.Vector3d;
import org.xtx.ut4converter.MapConverter;
import org.xtx.ut4converter.UTGames;
import org.xtx.ut4converter.UTGames.UnrealEngine;
import org.xtx.ut4converter.export.UTPackageExtractor;
import org.xtx.ut4converter.ucore.UPackageRessource;
/**
* Class for converting any actor related to sound (might be music as well) TODO
* merge with T3D Actor and delete this class because any actors can have sound
* property
*
* @author XtremeXp
*/
public class T3DSound extends T3DActor {
/**
* UE1, UE4
*/
UPackageRessource ambientSound;
AttenuationSettings attenuation = new AttenuationSettings();
/**
* UE1/2: (default: 190 max 255) UE3: UE4:
*/
Double soundVolume;
/**
* UE1/2: default 64 UE3: default 1 UE4: "Pitch Multiplier" default 1
*/
Double soundPitch;
/**
* UE3/4
*/
enum DistanceAlgorithm {
ATTENUATION_Linear, ATTENUATION_Logarithmic, ATTENUATION_Inverse, ATTENUATION_LogReverse, ATTENUATION_NaturalSound
}
/**
* Shape of "sound volume" only Sphere available for UE3
*/
enum Shape {
Sphere, Capsule, Box, Cone
}
/**
* UE3
*
* @author XtremeXp
*
*/
enum DistributionType {
DistributionDelayTime, DistributionMinRadius, DistributionMaxRadius, DistributionLPFMinRadius, DistributionLPFMaxRadius, DistributionVolume, DistributionPitch
}
/**
* UE4: TODO move out to ucore package ?
*/
class AttenuationSettings {
/**
* UE3/UE4: default true
*/
Boolean bAttenuate;
/**
* UE3/UE4: default true
*/
Boolean bSpatialize;
/**
* UE4 only default 20
*/
Double omniRadius;
/**
* In UE3 it's "DistanceModel"
*/
DistanceAlgorithm distanceAlgorithm = DistanceAlgorithm.ATTENUATION_Linear;
/**
* Only with UE4 and distance algorithm ATTENUATION_NaturalSound
*/
Double dBAttenuationAtMax = -60d;
/**
* Only in UE4, in UE3 it seems to be sphere by default
*/
Shape attenuationShape = Shape.Sphere;
/**
* UE4: is radius UE3: "MinRadius" (400 default)
*
*/
Vector3d attenuationShapeExtents = new Vector3d(400d, 0, 0);
/**
* UE4 only with attenuation shape "Cone" (default : 0)
*/
Double coneOffset;
/**
* in UE4: "MaxRadius" ? (5000 default) UE3: default 3600
*/
Double fallOffDistance;
/**
* UE3: LPFMinRadius (default 1500) UE4: default 3000
*/
Double LPFRadiusMin;
/**
* UE3: LPFMaxRadius (default 2500) UE4: default 6000
*/
Double LPFRadiusMax;
/**
* UE3: bAttenuateWithLowPassFilter UE4: default false
*/
Boolean bAttenuateWithLPF;
public String toString(UTGames.UnrealEngine engine) {
if (engine.version <= 3) {
return null;
}
// only UE4 support right now
else {
StringBuilder s = new StringBuilder("AttenuationOverrides=(");
Map<String, Object> props = new HashMap<>();
props.put("bAttenuateWithLPF", bAttenuateWithLPF);
props.put("bSpatialize", bSpatialize);
if (bSpatialize != null && bSpatialize) {
props.put("OmniRadius", omniRadius);
}
if (distanceAlgorithm == DistanceAlgorithm.ATTENUATION_NaturalSound) {
props.put("dBAttenuationAtMax", dBAttenuationAtMax);
}
if (attenuationShape == Shape.Cone) {
props.put("coneOffset", coneOffset);
}
props.put("AttenuationShapeExtents", attenuationShapeExtents);
props.put("FalloffDistance", fallOffDistance);
props.put("LPFRadiusMin", LPFRadiusMin);
props.put("LPFRadiusMax", LPFRadiusMax);
s.append(T3DUtils.getT3DLine(props));
s.append(")\n");
return s.toString();
}
}
}
/**
*
* @param mc
* @param t3dClass
*/
public T3DSound(MapConverter mc, String t3dClass) {
super(mc, t3dClass);
ue4RootCompType = T3DMatch.UE4_RCType.AUDIO;
initialise();
}
/**
* TODO some outside kind of UProperty class with defaults value for each UE
* version
*/
private void initialise() {
if (mapConverter.isFrom(UnrealEngine.UE1, UnrealEngine.UE2)) {
attenuation.attenuationShapeExtents.x = 64d; // Default Radius in
// UE1/2
soundVolume = 190d; // Default volume in UE1/2
soundPitch = 64d; // Default pitch in UE1/2
}
}
@Override
public boolean analyseT3DData(String line) {
if (line.startsWith("SoundRadius")) {
attenuation.attenuationShapeExtents.x = T3DUtils.getDouble(line);
}
else if (line.startsWith("SoundVolume")) {
soundVolume = T3DUtils.getDouble(line);
}
else if (line.startsWith("SoundPitch")) {
soundPitch = T3DUtils.getDouble(line);
}
// UE3
else if (line.startsWith("Min=")) {
Double min = T3DUtils.getDouble(line);
if (DistributionType.DistributionPitch.name().equals(currentSubObjectName)) {
soundPitch = min;
} else if (DistributionType.DistributionVolume.name().equals(currentSubObjectName)) {
soundVolume = min;
} else if (DistributionType.DistributionLPFMinRadius.name().equals(currentSubObjectName)) {
attenuation.LPFRadiusMin = min;
} else if (DistributionType.DistributionLPFMaxRadius.name().equals(currentSubObjectName)) {
attenuation.LPFRadiusMax = min;
} else if (DistributionType.DistributionMaxRadius.name().equals(currentSubObjectName)) {
attenuation.omniRadius = min;
} else if (DistributionType.DistributionMinRadius.name().equals(currentSubObjectName)) {
attenuation.omniRadius = min;
}
}
// UE3
else if (line.startsWith("Max=")) {
Double max = T3DUtils.getDouble(line);
if (DistributionType.DistributionPitch.name().equals(currentSubObjectName)) {
soundPitch = Math.max(soundPitch, max);
} else if (DistributionType.DistributionVolume.name().equals(currentSubObjectName)) {
soundVolume = getMax(soundVolume, max);
} else if (DistributionType.DistributionLPFMinRadius.name().equals(currentSubObjectName)) {
attenuation.LPFRadiusMin = getMax(attenuation.LPFRadiusMin, max);
} else if (DistributionType.DistributionLPFMaxRadius.name().equals(currentSubObjectName)) {
attenuation.LPFRadiusMax = getMax(attenuation.LPFRadiusMax, max);
} else if (DistributionType.DistributionMaxRadius.name().equals(currentSubObjectName)) {
attenuation.omniRadius = getMax(attenuation.omniRadius, max);
} else if (DistributionType.DistributionMinRadius.name().equals(currentSubObjectName)) {
attenuation.omniRadius = getMax(attenuation.omniRadius, max);
}
}
// UE1/2: AmbientSound=Sound'AmbAncient.Looping.Stower51'
// UE3: Wave=SoundNodeWave'A_Ambient_Loops.Water.water_drain01'
else if (line.startsWith("AmbientSound=") || line.startsWith("Wave=")) {
ambientSound = mapConverter.getUPackageRessource(line.split("\\'")[1], T3DRessource.Type.SOUND);
} else {
return super.analyseT3DData(line);
}
return true;
}
private Double getMax(Double currentMax, Double newMax){
if(currentMax == null){
return newMax;
} else {
return Math.max(currentMax, newMax);
}
}
@Override
public void scale(Double newScale) {
T3DUtils.scale(attenuation.attenuationShapeExtents, newScale);
attenuation.LPFRadiusMin = T3DUtils.scale(attenuation.LPFRadiusMin, newScale);
attenuation.LPFRadiusMax = T3DUtils.scale(attenuation.LPFRadiusMax, newScale);
attenuation.fallOffDistance = T3DUtils.scale(attenuation.fallOffDistance, newScale);
attenuation.omniRadius = T3DUtils.scale(attenuation.omniRadius, newScale);
super.scale(newScale);
}
@Override
public void convert() {
if (mapConverter.isFromUE1UE2ToUE3UE4()) {
if (soundVolume != null) {
soundVolume /= 255D; // default volume is 190 in UE1/2, default
// is 1 in UE3/4
// decreasing sound volume from UT2004 because seems "loudy" in
// UT4 ...
if (mapConverter.isFrom(UTGames.UnrealEngine.UE2)) {
soundVolume *= 0.15;
}
if (mapConverter.soundVolumeFactor != null) {
soundVolume = Math.min(1, soundVolume * mapConverter.soundVolumeFactor);
}
}
if (soundPitch != null) {
soundPitch /= 64D; // default pitch is 64 in UE1/2
}
// tested DM-ArcaneTemple (UT99)
attenuation.fallOffDistance = attenuation.attenuationShapeExtents.x * 24;
} else if (mapConverter.isFrom(UnrealEngine.UE3) && mapConverter.isTo(UnrealEngine.UE4)) {
// TODO
}
if (mapConverter.convertSounds() && ambientSound != null) {
ambientSound.export(UTPackageExtractor.getExtractor(mapConverter, ambientSound));
}
super.convert();
}
/**
*
* @return
*/
@Override
public String toString() {
if (ambientSound == null) {
return super.toString();
}
if (mapConverter.toUnrealEngine4()) {
if (!name.contains("Sound")) {
name += "Sound";
}
sbf.append(IDT).append("Begin Actor Class=AmbientSound Name=").append(name).append("\n");
sbf.append(IDT).append("\tBegin Object Class=AudioComponent Name=\"AudioComponent0\"\n");
sbf.append(IDT).append("\tEnd Object\n");
sbf.append(IDT).append("\tBegin Object Name=\"AudioComponent0\"\n");
sbf.append(IDT).append("\t\tbOverrideAttenuation=True\n");
sbf.append(IDT).append("\t\t").append(attenuation.toString(mapConverter.getOutputGame().engine));
if (ambientSound != null) {
sbf.append(IDT).append("\t\tSound=SoundCue'").append(ambientSound.getConvertedName(mapConverter)).append("'\n");
}
// bOverrideAttenuation=True
if (soundVolume != null) {
sbf.append(IDT).append("\t\tVolumeMultiplier=").append(soundVolume).append("\n");
}
if (soundPitch != null) {
sbf.append(IDT).append("\t\tPitchMultiplier=").append(soundPitch).append("\n");
}
writeLocRotAndScale();
sbf.append(IDT).append("\tEnd Object\n");
sbf.append(IDT).append("\tAudioComponent=AudioComponent0\n");
sbf.append(IDT).append("\tRootComponent=AudioComponent0\n");
writeEndActor();
}
return super.toString();
}
}
|
package pete.executables;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.commons.io.FileUtils;
import pete.metrics.adaptability.AdaptabilityAnalyzer;
import pete.metrics.installability.deployability.DeploymentPackageAnalyzer;
import pete.metrics.installability.server.AverageInstallationTimeCalculator;
import pete.metrics.portability.PortabilityAnalyzer;
import pete.reporting.Report;
import pete.reporting.ReportWriter;
public final class AnalysisWorkflow {
private final Path root;
private final DirectoryAnalyzer dirAnalyzer;
private FileAnalyzer fileAnalyzer;
private Report report;
public AnalysisWorkflow(Path root, AnalysisType type) {
this.root = root;
if (!Files.exists(root)) {
throw new IllegalArgumentException("path " + root.toString()
+ " does not exist");
}
if (AnalysisType.DEPLOYABILITY.equals(type)) {
fileAnalyzer = new DeploymentPackageAnalyzer();
} else if (AnalysisType.INSTALLABILITY.equals(type)) {
fileAnalyzer = new AverageInstallationTimeCalculator();
} else if (AnalysisType.PORTABILITY.equals(type)) {
fileAnalyzer = new PortabilityAnalyzer();
} else if (AnalysisType.ADAPTABILITY.equals(type)) {
fileAnalyzer = new AdaptabilityAnalyzer();
} else if (AnalysisType.UNKNOWN.equals(type)) {
throw new AnalysisException("no valid AnalysisType found");
}
dirAnalyzer = new DirectoryAnalyzer(fileAnalyzer);
}
public void start() {
if (!Files.isDirectory(root)) {
parseFile(root);
} else {
parseDirectory(root);
}
System.out.println("=======================================");
System.out.println("Analysis finished; writing results");
writeResults();
purgeTempDir();
}
private void parseFile(Path file) {
report = new Report();
fileAnalyzer.analyzeFile(file).forEach(
reportEntry -> report.addEntry(reportEntry));
}
private void parseDirectory(Path root) {
report = dirAnalyzer.analyzeDirectory(root);
}
private void writeResults() {
fileAnalyzer.traversalCompleted();
ReportWriter writer = new ReportWriter(report);
writer.writeToExcelFile("results.csv");
writer.writeToRFile("r-results.csv");
}
private void purgeTempDir() {
try {
FileUtils.deleteDirectory(new File("tmp"));
} catch (IOException e) {
// Not critical -> ignore
}
}
}
|
package org.pikater.core.agents.system.computationDescriptionParser.dependencyGraph.ComputationStrategies;
import jade.content.ContentElement;
import jade.content.lang.Codec.CodecException;
import jade.content.onto.OntologyException;
import jade.content.onto.UngroundedException;
import jade.content.onto.basic.Action;
import jade.content.onto.basic.Result;
import jade.core.AID;
import jade.domain.FIPAException;
import jade.domain.FIPANames;
import jade.domain.FIPAService;
import jade.lang.acl.ACLMessage;
import org.pikater.core.AgentNames;
import org.pikater.core.agents.system.Agent_Manager;
import org.pikater.core.agents.system.computationDescriptionParser.ComputationOutputBuffer;
import org.pikater.core.agents.system.computationDescriptionParser.dependencyGraph.ComputationNode;
import org.pikater.core.agents.system.computationDescriptionParser.dependencyGraph.ModelComputationNode;
import org.pikater.core.agents.system.computationDescriptionParser.dependencyGraph.StartComputationStrategy;
import org.pikater.core.agents.system.computationDescriptionParser.edges.DataSourceEdge;
import org.pikater.core.agents.system.computationDescriptionParser.edges.OptionEdge;
import org.pikater.core.agents.system.computationDescriptionParser.edges.SolutionEdge;
import org.pikater.core.agents.system.manager.ExecuteTaskBehaviour;
import org.pikater.core.ontology.FilenameTranslationOntology;
import org.pikater.core.ontology.TaskOntology;
import org.pikater.core.ontology.subtrees.data.Data;
import org.pikater.core.ontology.subtrees.file.TranslateFilename;
import org.pikater.core.ontology.subtrees.management.Agent;
import org.pikater.core.ontology.subtrees.newOption.NewOptionList;
import org.pikater.core.ontology.subtrees.newOption.ValuesForOption;
import org.pikater.core.ontology.subtrees.newOption.base.NewOption;
import org.pikater.core.ontology.subtrees.newOption.base.Value;
import org.pikater.core.ontology.subtrees.newOption.values.interfaces.IValueData;
import org.pikater.core.ontology.subtrees.search.SearchSolution;
import org.pikater.core.ontology.subtrees.task.ExecuteTask;
import org.pikater.core.ontology.subtrees.task.Task;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class CAStartComputationStrategy implements StartComputationStrategy{
Agent_Manager myAgent;
int graphId;
ModelComputationNode computationNode;
NewOptionList options;
public CAStartComputationStrategy (Agent_Manager manager,
int graphId, ModelComputationNode computationNode){
myAgent = manager;
this.graphId = graphId;
this.computationNode = computationNode;
}
public void execute(ComputationNode computation){
ACLMessage originalRequest = myAgent.getComputation(graphId).getMessage();
myAgent.addBehaviour(new ExecuteTaskBehaviour(myAgent, prepareRequest(), originalRequest, this));
}
public void processValidation(String dataSourceName){
DataSourceEdge dse = new DataSourceEdge();
dse.setDataSourceId(dataSourceName);
computationNode.addToOutputAndProcess(dse, "validation");
}
private ACLMessage prepareRequest(){
ExecuteTask ex = new ExecuteTask();
Task task = getTaskFromNode();
ex.setTask(task);
return execute2Message(ex);
}
//Create new options from solution with filled ? values (convert solution->options)
private NewOptionList fillOptionsWithSolution(List<NewOption> options, SearchSolution solution){
NewOptionList res_options = new NewOptionList();
List<NewOption> options_list = new ArrayList<>();
if(options==null){
return res_options;
}
//if no solution values to fill - return the option
if(solution.getValues() == null){
res_options.setOptions(options);
return res_options;
}
for (NewOption option:options)
{
if (option.isImmutable())
{
options_list.add(option);
}
else
{
for (int i=0;i<solution.getValues().size();i++)
{
String currentName=solution.getNames().get(i);
if (currentName.equals(option.getName()))
{
IValueData currentValue= solution.getValues().get(i);
NewOption clone=option.clone();
clone.setValuesWrapper(new ValuesForOption(new Value(currentValue)));
options_list.add(clone);
break;
}
}
}
}
res_options.setOptions(options_list);
return res_options;
}
private Task getTaskFromNode(){
Map<String, ComputationOutputBuffer> inputs = computationNode.getInputs();
Agent agent = new Agent();
if (options==null) {
OptionEdge optionEdge = (OptionEdge) inputs.get("options").getNext();
options = new NewOptionList(optionEdge.getOptions());
}
NewOptionList usedoptions=options;
// TODO zbavit se Options -> list instead
agent.setType(computationNode.getModelClass());
Task task = new Task();
if (inputs.get("searchedoptions") != null){
inputs.get("options").block();
SolutionEdge solutionEdge = (SolutionEdge)inputs.get("searchedoptions").getNext();
usedoptions = fillOptionsWithSolution(options.getOptions(), solutionEdge.getOptions());
task.setComputationId(solutionEdge.getComputationID());
}
agent.setOptions(usedoptions.getOptions());
Data data = new Data();
String training = ((DataSourceEdge)inputs.get("training").getNext()).getDataSourceId();
String testing = null;
if( inputs.get("testing") == null){
testing = training;
}
else{
testing = ((DataSourceEdge) inputs.get("testing").getNext()).getDataSourceId();
}
data.setExternal_train_file_name(training);
data.setExternal_test_file_name(testing);
data.setTestFileName(getHashOfFile(training, 1));
data.setTrainFileName(getHashOfFile(testing, 1));
task.setSave_results(true);
task.setNodeId(computationNode.getId());
task.setGraphId(graphId);
task.setAgent(agent);
task.setData(data);
task.setEvaluationMethod(computationNode.getEvaluationMethod());
return task;
}
public String getHashOfFile(String nameOfFile, int userID) {
TranslateFilename translate = new TranslateFilename();
translate.setExternalFilename(nameOfFile);
translate.setUserID(userID);
// create a request message
ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
msg.setSender(myAgent.getAID());
msg.addReceiver(new AID(AgentNames.DATA_MANAGER, false));
msg.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
msg.setLanguage(myAgent.getCodec().getName());
msg.setOntology(FilenameTranslationOntology.getInstance().getName());
// We want to receive a reply in 30 secs
msg.setReplyByDate(new Date(System.currentTimeMillis() + 30000));
//msg.setConversationId(problem.getGui_id() + agent.getLocalName());
Action a = new Action();
a.setAction(translate);
a.setActor(myAgent.getAID());
try {
myAgent.getContentManager().fillContent(msg, a);
} catch (CodecException ce) {
ce.printStackTrace();
} catch (OntologyException oe) {
oe.printStackTrace();
}
ACLMessage reply = null;
try {
reply = FIPAService.doFipaRequestClient(myAgent, msg);
} catch (FIPAException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ContentElement content = null;
String fileHash = null;
try {
content = myAgent.getContentManager().extractContent(reply);
} catch (UngroundedException e1) {
myAgent.logError(e1.getMessage(), e1);
} catch (CodecException e1) {
myAgent.logError(e1.getMessage(), e1);
} catch (OntologyException e1) {
myAgent.logError(e1.getMessage(), e1);
}
if (content instanceof Result) {
Result result = (Result) content;
fileHash = (String) result.getValue();
}
return fileHash;
}
public ACLMessage execute2Message(ExecuteTask ex) {
// create ACLMessage from Execute ontology action
ACLMessage request = new ACLMessage(ACLMessage.REQUEST);
request.setLanguage(myAgent.getCodec().getName());
request.setOntology(TaskOntology.getInstance().getName());
request.addReceiver(myAgent.getAgentByType(AgentNames.PLANNER));
request.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
Action a = new Action();
a.setAction(ex);
a.setActor(myAgent.getAID());
try {
myAgent.getContentManager().fillContent(request, a);
} catch (CodecException e) {
myAgent.logError(e.getMessage(), e);
} catch (OntologyException e) {
myAgent.logError(e.getMessage(), e);
}
return request;
}
}
|
package ratismal.drivebackup;
import ratismal.drivebackup.config.Config;
import ratismal.drivebackup.googledrive.GoogleUploader;
import ratismal.drivebackup.onedrive.OneDriveUploader;
import ratismal.drivebackup.util.FileUtil;
import ratismal.drivebackup.util.MessageUtil;
import java.io.File;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class UploadThread implements Runnable {
public UploadThread() {
}
@Override
public void run() {
MessageUtil.sendMessageToAllPlayers("Creating backups, server may lag for a little while...");
// Create Backup Here
HashMap<String, HashMap<String, String>> backupList = Config.getBackupList();
for (Map.Entry<String, HashMap<String, String>> set : backupList.entrySet()) {
String type = set.getKey();
String format = set.getValue().get("format");
String create = set.getValue().get("create");
MessageUtil.sendConsoleMessage("Doing backups for " + type);
if (create.equalsIgnoreCase("true")) {
FileUtil.makeBackup(type, format);
}
File file = FileUtil.getFileToUpload(type, format, false);
DecimalFormat df = new DecimalFormat("
try {
if (Config.isGoogleEnabled()) {
MessageUtil.sendConsoleMessage("Uploading file to GoogleDrive");
Date startTime = new Date();
GoogleUploader.uploadFile(file, type);
Date endTime = new Date();
double difference = endTime.getTime() - startTime.getTime();
double length = Double.valueOf(df.format(difference / 1000));
double speed = Double.valueOf(df.format((file.length() / 1024) / length));
MessageUtil.sendConsoleMessage("File uploaded in " +
length + " seconds (" + speed + " KB/s)");
}
if (Config.isOnedriveEnabled()) {
MessageUtil.sendConsoleMessage("Uploading file to OneDrive");
//Couldn't get around static issue, declared a new Instance.
OneDriveUploader onedrive = new OneDriveUploader();
Date startTime = new Date();
onedrive.uploadFile(file, type);
Date endTime = new Date();
double difference = endTime.getTime() - startTime.getTime();
double length = Double.valueOf(df.format(difference / 1000));
double speed = Double.valueOf(df.format((file.length() / 1024) / length));
MessageUtil.sendConsoleMessage("File uploaded in " +
length + " seconds (" + +speed + " KB/s)");
}
//MessageUtil.sendConsoleMessage("File Uploaded.");
} catch (Exception e) {
e.printStackTrace();
}
}
MessageUtil.sendMessageToAllPlayers("Backup complete. The next backup is in " + Config.getBackupDelay() / 20 / 60 + " minutes.");
}
}
|
package squeek.veganoption.items;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumAction;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import squeek.veganoption.entities.EntityBubble;
public class ItemSoapSolution extends Item
{
public ItemSoapSolution()
{
super();
setMaxStackSize(1);
setMaxDamage(15); // 16 uses
}
@Override
public EnumAction getItemUseAction(ItemStack itemStack)
{
return EnumAction.drink;
}
@Override
public int getMaxItemUseDuration(ItemStack itemStack)
{
return 16;
}
@Override
public ItemStack onEaten(ItemStack itemStack, World world, EntityPlayer player)
{
if (!world.isRemote)
{
world.spawnEntityInWorld(new EntityBubble(world, player));
}
itemStack.damageItem(1, player);
if (itemStack.stackSize == 0 && getContainerItem() != null)
{
return new ItemStack(getContainerItem());
}
return super.onEaten(itemStack, world, player);
}
@Override
public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player)
{
player.setItemInUse(itemStack, getMaxItemUseDuration(itemStack));
return super.onItemRightClick(itemStack, world, player);
}
}
|
package reborncore.common.util;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidUtil;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandlerItem;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class FluidUtils {
public static boolean drainContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot) {
ItemStack input = inv.getStackInSlot(inputSlot);
ItemStack output = inv.getStackInSlot(outputSlot);
IFluidHandlerItem inputFluidHandler = getFluidHandler(input);
if (inputFluidHandler != null) {
/*
* Making a simulation to check if the fluid can be drained into the
* fluidhandler.
*/
if (FluidUtil.tryFluidTransfer(fluidHandler, inputFluidHandler,
inputFluidHandler.getTankProperties()[0].getCapacity(), false) != null) {
// Changes are really applied and the fluid is drained.
FluidStack drained = FluidUtil.tryFluidTransfer(fluidHandler, inputFluidHandler,
inputFluidHandler.getTankProperties()[0].getCapacity(), true);
/*
* If the drained container doesn't disappear we need to update
* the inventory accordingly.
*/
if (drained != null && inputFluidHandler.getContainer() != ItemStack.EMPTY)
if (output == ItemStack.EMPTY) {
inv.setInventorySlotContents(outputSlot, inputFluidHandler.getContainer());
inv.decrStackSize(inputSlot, 1);
} else {
/*
* When output is not EMPTY, it is needed to check if
* the two stacks can be merged together, there was no
* simple way to make that check before.
*/
if (ItemUtils.isItemEqual(output, inputFluidHandler.getContainer(), true, true)) {
inv.getStackInSlot(outputSlot).setCount(inv.getStackInSlot(outputSlot).getCount() + 1);
inv.decrStackSize(inputSlot, 1);
} else {
/*
* Due to the late check of stacks merge we need to
* reverse any changes made to the FluidHandlers
* when the merge fail.
*/
FluidUtil.tryFluidTransfer(inputFluidHandler, fluidHandler, drained.amount, true);
return false;
}
}
return true;
}
}
return false;
}
public static boolean fillContainers(IFluidHandler fluidHandler, IInventory inv, int inputSlot, int outputSlot,
Fluid fluidToFill) {
ItemStack input = inv.getStackInSlot(inputSlot);
ItemStack output = inv.getStackInSlot(outputSlot);
if (input != ItemStack.EMPTY) {
IFluidHandlerItem inputFluidHandler = getFluidHandler(input);
/*
* The copy is needed to get the filled container without altering
* the original ItemStack.
*/
ItemStack containerCopy = input.copy();
containerCopy.setCount(1);
/*
* It's necessary to check before any alterations that the resulting
* ItemStack can be placed into the outputSlot.
*/
if (inputFluidHandler != null && (output == ItemStack.EMPTY
|| (output.getCount() < output.getMaxStackSize() && ItemUtils.isItemEqual(
FluidUtils.getFilledContainer(fluidToFill, containerCopy), output, true, true)))) {
/*
* Making a simulation to check if the fluid can be transfered
* into the fluidhandler.
*/
if (FluidUtil.tryFluidTransfer(inputFluidHandler, fluidHandler,
inputFluidHandler.getTankProperties()[0].getCapacity(), false) != null) {
// Changes are really applied and the fluid is transfered.
FluidUtil.tryFluidTransfer(inputFluidHandler, fluidHandler,
inputFluidHandler.getTankProperties()[0].getCapacity(), true);
// The inventory is modified and stacks are merged.
if (output == ItemStack.EMPTY)
inv.setInventorySlotContents(outputSlot, inputFluidHandler.getContainer());
else
inv.getStackInSlot(outputSlot).setCount(inv.getStackInSlot(outputSlot).getCount() + 1);
inv.decrStackSize(inputSlot, 1);
return true;
}
}
}
return false;
}
@Nullable
public static IFluidHandlerItem getFluidHandler(ItemStack container) {
ItemStack copy = container.copy();
copy.setCount(1);
return FluidUtil.getFluidHandler(copy);
}
@Nullable
public static FluidStack getFluidStackInContainer(@Nonnull ItemStack container) {
if (!container.isEmpty()) {
container = container.copy();
container.setCount(1);
final IFluidHandlerItem fluidHandler = FluidUtil.getFluidHandler(container);
if (fluidHandler != null) {
return fluidHandler.drain(Fluid.BUCKET_VOLUME, false);
}
}
return null;
}
@Nonnull
public static ItemStack getFilledContainer(Fluid fluid, ItemStack empty) {
if (fluid == null || empty == ItemStack.EMPTY)
return ItemStack.EMPTY;
IFluidHandlerItem fluidHandler = FluidUtil.getFluidHandler(empty);
fluidHandler.fill(new FluidStack(fluid, fluidHandler.getTankProperties()[0].getCapacity()), true);
return empty;
}
}
|
package scalability;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
public class LargeDatasetGenerator {
public static final int numberOfEmployees = 6;
public static final int numberOfTasks = numberOfEmployees*2;
public static final int numberOfSkillLevels = 1;
public static final int totalNumberOfSkills = numberOfSkillLevels*12;
public static final int maxNumberOfSkillsPerEmployee = 4;
public static final int maxNumberOfSkillsPerTask = 1;
public static final int monthsRange = 5;
public static int numberOfEmployeeSkillsRows = 0;
public static int numberOfTaskSkillsRows = 0;
private static String value1="", value2="", value3="", value4="";
public static void generateTestFiles() {
try{
PrintWriter writer = new PrintWriter("src/main/resources/large_dataset/Employees.txt", "UTF-8");
generateEmployees(writer);
writer.close();
writer = new PrintWriter("src/main/resources/large_dataset/Skills.txt", "UTF-8");
generateSkills(writer);
writer.close();
writer = new PrintWriter("src/main/resources/large_dataset/EmployeeSkills.txt", "UTF-8");
generateEmployeeSkills(writer);
writer.close();
writer = new PrintWriter("src/main/resources/large_dataset/TaskSkills.txt", "UTF-8");
generateTaskSkills(writer);
writer.close();
writer = new PrintWriter("src/main/resources/large_dataset/Tasks.txt", "UTF-8");
generateTasks(writer);
writer.close();
} catch (IOException e) {
// do something
}
}
private static void generateTasks(PrintWriter writer) {
StringBuilder builder = new StringBuilder();
String taskLine = "INSERT INTO `task` (`name`, `priority`, `start_time`, `end_time`) VALUES ('";
Date startDate;
Date endDate;
Random rand = new Random();
String[] priorities = {"HIGH", "MEDIUM", "LOW"};
int i=0;
while(i<numberOfTasks) {
value1 = new StringBuilder().append("Task").append(((Integer)(i+1)).toString()).toString();
value2 = priorities[rand.nextInt(3)];
startDate = getValidRandomDate();
endDate = getValidRandomDate();
while (endDate.before(startDate)) {
endDate = getValidRandomDate();
}
value3 = getDateValueInString(startDate);
value4 = getDateValueInString(endDate);
builder.append(taskLine);
builder.append(value1);
builder.append("', '");
builder.append(value2);
builder.append("', '");
builder.append(value3);
builder.append("', '");
builder.append(value4);
builder.append("');");
writer.println(builder.toString());
builder.delete(0, builder.length());
i++;
}
}
public static Date getValidRandomDate() {
int month, year, day;
Random call = new Random();
month = call.nextInt(monthsRange);
//year = call.nextInt(2017) + 1;
year = 2017;
day = call.nextInt(30);
GregorianCalendar calendar = new GregorianCalendar(year, month, day);
Date now = calendar.getTime();
//System.out.println(now);
return now;
}
private static String getDateValueInString(Date date) {
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
StringBuilder builder = new StringBuilder().append(year).append("-").append(month).append("-").append(day);
return builder.toString();
}
private static Date getRandomDate() {
long ms;
// Get a new random instance, seeded from the clock
Random rnd = new Random();
// Get an Epoch value roughly between 1940 and 2010
// -946771200000L = January 1, 1940
// Add up to 70 years to it (using modulus on the next long)
ms = -946771200000L + (Math.abs(rnd.nextLong()) % (70L * 365 * 24 * 60 * 60 * 1000));
// Construct a date
return new Date(ms);
}
/**
* @param writer
* @throws FileNotFoundException
*/
private static void generateEmployees(PrintWriter writer) throws FileNotFoundException {
StringBuilder builder = new StringBuilder();
String employeeLineStart = "INSERT INTO `employee` (`first_name`, `last_name`) VALUES ('";
int i=0;
value1 = "Employee";
while(i<numberOfEmployees) {
value2 = i+1+"";
builder.append(employeeLineStart);
builder.append(value1);
builder.append("', '");
builder.append(value2);
builder.append("');");
writer.println(builder.toString());
builder.delete(0, builder.length());
i++;
}
}
private static void generateSkills(PrintWriter writer) {
StringBuilder builder = new StringBuilder();
String skillLineStart = "INSERT INTO `skill` (`name`, `level`) VALUES ('";
int i=0;
String[] names = { "C++", "Java", "Python", "Ruby", "Linux Shell", "Functional Programming", "Artificial Intelligence", "SQL", "Databases", "Distributed Systems", "Regex", "Security" };
int[] levels = new int[numberOfSkillLevels];
while (i<levels.length) {
levels[i] = i+1;
i++;
}
for (int nameIndex=0; nameIndex<names.length; nameIndex++) {
value1= names[nameIndex];
for (int levelIndex=0; levelIndex<levels.length; levelIndex++) {
value2= ((Integer)levels[levelIndex]).toString();
builder.append(skillLineStart);
builder.append(value1);
builder.append("', '");
builder.append(value2);
builder.append("');");
writer.println(builder.toString());
builder.delete(0, builder.length());
}
}
}
private static void generateEmployeeSkills(PrintWriter writer) {
StringBuilder builder = new StringBuilder();
String employeeSkillLineStart = "INSERT INTO `employee_skill` (`employee_id`, `skill_id`) VALUES ('";
int i=0;
int[] employeeIds = new int[numberOfEmployees];
int[] skillIds = new int[totalNumberOfSkills];
while (i<employeeIds.length) {
employeeIds[i] = i+1;
i++;
}
i=0;
while (i<skillIds.length) {
skillIds[i] = i+1;
i++;
}
int numberOfSkills=0;
Random rand = new Random();
for (int eIndex=0; eIndex<employeeIds.length; eIndex++) {
value1= ((Integer)employeeIds[eIndex]).toString();
numberOfSkills = rand.nextInt(maxNumberOfSkillsPerEmployee) + 1;
numberOfEmployeeSkillsRows+=numberOfSkills;
int sCounter=0;
int[] employeeSkills = pickNRandom(skillIds, numberOfSkills);
while (sCounter<numberOfSkills){
value2= ((Integer)employeeSkills[sCounter++]).toString();
builder.append(employeeSkillLineStart);
builder.append(value1);
builder.append("', '");
builder.append(value2);
builder.append("');");
writer.println(builder.toString());
builder.delete(0, builder.length());
}
}
}
public static int[] pickNRandom(int[] array, int n) {
List<Integer> list = new ArrayList<Integer>(array.length);
for (int i : array)
list.add(i);
Collections.shuffle(list);
int[] answer = new int[n];
for (int i = 0; i < n; i++)
answer[i] = list.get(i);
Arrays.sort(answer);
return answer;
}
private static void generateTaskSkills(PrintWriter writer) {
StringBuilder builder = new StringBuilder();
String taskSkillLine = "INSERT INTO `task_skill` (`task_id`, `skill_id`) VALUES ('";
int i=0;
int[] taskIds = new int[numberOfTasks];
int[] skillIds = new int[totalNumberOfSkills];
while (i<taskIds.length) {
taskIds[i] = i+1;
i++;
}
i=0;
while (i<skillIds.length) {
skillIds[i] = i+1;
i++;
}
int numberOfSkills=0;
Random rand = new Random();
for (int tIndex=0; tIndex<taskIds.length; tIndex++) {
value1= ((Integer)taskIds[tIndex]).toString();
numberOfSkills = rand.nextInt(maxNumberOfSkillsPerTask) + 1;
numberOfTaskSkillsRows+=numberOfSkills;
int sCounter=0;
int[] taskSkills = pickNRandom(skillIds, numberOfSkills);
while (sCounter<numberOfSkills){
value2= ((Integer)taskSkills[sCounter++]).toString();
builder.append(taskSkillLine);
builder.append(value1);
builder.append("', '");
builder.append(value2);
builder.append("');");
writer.println(builder.toString());
builder.delete(0, builder.length());
}
}
}
}
|
package seedu.address.logic.parser;
import seedu.address.logic.commands.*;
import seedu.address.commons.util.StringUtil;
import seedu.address.commons.exceptions.IllegalValueException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
/**
* Parses user input.
*/
public class Parser {
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
private static final Pattern PERSON_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)");
private static final Pattern KEYWORDS_ARGS_FORMAT =
Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace
private static final Pattern PERSON_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes
Pattern.compile("(?<name>[^/]+)"
+ " (?<isPhonePrivate>p?)p/(?<phone>[^/]+)"
+ " (?<isEmailPrivate>p?)e/(?<email>[^/]+)"
+ " (?<isAddressPrivate>p?)a/(?<address>[^/]+)"
+ "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags
public Parser() {}
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
*/
public Command parseCommand(String userInput) {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddCommand.COMMAND_WORD:
return prepareAdd(arguments);
case NoteCommand.COMMAND_WORD:
return prepareNote(arguments);
case SelectCommand.COMMAND_WORD:
return prepareSelect(arguments);
case DeleteCommand.COMMAND_WORD:
return prepareDelete(arguments);
case ClearCommand.COMMAND_WORD:
return new ClearCommand();
case FindCommand.COMMAND_WORD:
return prepareFind(arguments);
case ListCommand.COMMAND_WORD:
return new ListCommand();
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
default:
return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND);
}
}
/**
* Parses arguments in the context of the add person command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareAdd(String args){
final Matcher matcher = PERSON_DATA_ARGS_FORMAT.matcher(args.trim());
// Validate arg string format
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
try {
return new AddCommand(
matcher.group("name"),
matcher.group("phone"),
matcher.group("email"),
getTagsFromArgs(matcher.group("tagArguments"))
);
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
/**
* Extracts the new person's tags from the add command's tag arguments string.
* Merges duplicate tag strings.
*/
private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException {
// no tags
if (tagArguments.isEmpty()) {
return Collections.emptySet();
}
// replace first delimiter prefix, then split
final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/"));
return new HashSet<>(tagStrings);
}
/**
* Parses arguments in the context of the note command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareNote(String args) {
final Matcher matcher = PERSON_DATA_ARGS_FORMAT.matcher(args.trim());
try {
return new NoteCommand(matcher.group("name"));
} catch (IllegalValueException ive) {
return new IncorrectCommand(ive.getMessage());
}
}
/**
* Parses arguments in the context of the delete person command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareDelete(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
return new DeleteCommand(index.get());
}
/**
* Parses arguments in the context of the select person command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareSelect(String args) {
Optional<Integer> index = parseIndex(args);
if(!index.isPresent()){
return new IncorrectCommand(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE));
}
return new SelectCommand(index.get());
}
/**
* Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index.
* Returns an {@code Optional.empty()} otherwise.
*/
private Optional<Integer> parseIndex(String command) {
final Matcher matcher = PERSON_INDEX_ARGS_FORMAT.matcher(command.trim());
if (!matcher.matches()) {
return Optional.empty();
}
String index = matcher.group("targetIndex");
if(!StringUtil.isUnsignedInteger(index)){
return Optional.empty();
}
return Optional.of(Integer.parseInt(index));
}
/**
* Parses arguments in the context of the find person command.
*
* @param args full command args string
* @return the prepared command
*/
private Command prepareFind(String args) {
final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim());
if (!matcher.matches()) {
return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
FindCommand.MESSAGE_USAGE));
}
// keywords delimited by whitespace
final String[] keywords = matcher.group("keywords").split("\\s+");
final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
return new FindCommand(keywordSet);
}
}
|
package seedu.address.model.person;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import seedu.address.commons.util.CollectionUtil;
import seedu.address.model.tag.Tag;
import seedu.address.model.tag.UniqueTagList;
/**
* Represents a Person in the address book.
* Guarantees: details are present and not null, field values are validated.
*/
public class Person implements ReadOnlyPerson {
private Name name;
private Phone phone;
private Email email;
private Address address;
private UniqueTagList tags;
/**
* Every field must be present and not null.
*/
public Person(Name name, Phone phone, Email email, Address address, UniqueTagList tags) {
assert !CollectionUtil.isAnyNull(name, phone, email, address, tags);
this.name = name;
this.phone = phone;
this.email = email;
this.address = address;
this.tags = new UniqueTagList(tags); // protect internal tags from changes in the arg list
}
/**
* Creates a copy of the given ReadOnlyPerson.
*/
public Person(ReadOnlyPerson source) {
this(source.getName(), source.getPhone(), source.getEmail(), source.getAddress(),
new UniqueTagList(source.getTags()));
}
public void setName(Name name) {
assert name != null;
this.name = name;
}
@Override
public Name getName() {
return name;
}
public void setPhone(Phone phone) {
assert phone != null;
this.phone = phone;
}
@Override
public Phone getPhone() {
return phone;
}
public void setEmail(Email email) {
assert email != null;
this.email = email;
}
@Override
public Email getEmail() {
return email;
}
public void setAddress(Address address) {
assert address != null;
this.address = address;
}
@Override
public Address getAddress() {
return address;
}
/**
* Returns an immutable tag set, which throws {@code UnsupportedOperationException}
* if modification is attempted.
*/
@Override
public Set<Tag> getTags() {
return Collections.unmodifiableSet(tags.toSet());
}
/**
* Replaces this person's tags with the tags in the argument tag list.
*/
public void setTags(UniqueTagList replacement) {
tags.setTags(replacement);
}
/**
* Updates this person with the details of {@code replacement}.
*/
public void resetData(ReadOnlyPerson replacement) {
assert replacement != null;
this.setName(replacement.getName());
this.setPhone(replacement.getPhone());
this.setEmail(replacement.getEmail());
this.setAddress(replacement.getAddress());
this.setTags(new UniqueTagList(replacement.getTags()));
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof ReadOnlyPerson // instanceof handles nulls
&& this.isSameStateAs((ReadOnlyPerson) other));
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing your own
return Objects.hash(name, phone, email, address, tags);
}
@Override
public String toString() {
return getAsText();
}
}
|
package org.cytoscape.myapp.cwru_chopper_algorithm.internal;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNetworkFactory;
import org.cytoscape.model.CyNetworkManager;
import org.cytoscape.myapp.cwru_chopper_algorithm.internal.ChopperNetworkTask;
import org.cytoscape.session.CyNetworkNaming;
import org.cytoscape.task.NetworkTaskFactory;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.model.CyNetworkViewFactory;
import org.cytoscape.view.model.CyNetworkViewManager;
import org.cytoscape.work.TaskIterator;
public class ChopperNetworkTaskFactory implements NetworkTaskFactory {
private final CyNetworkManager netMgr;
private final CyNetworkFactory cnf;
private final CyNetworkNaming namingUtil;
private CyNetworkView viewNetwork;
private CyNetworkViewFactory viewFactory;
private CyNetworkViewManager viewManager;
public ChopperNetworkTaskFactory(CyNetwork cN,
final CyNetworkManager netMgr,
final CyNetworkNaming namingUtil,
final CyNetworkFactory cnf,
CyNetworkView viewNetwork,
CyNetworkViewFactory viewFactory,
CyNetworkViewManager viewManager){
this.netMgr = netMgr;
this.namingUtil = namingUtil;
this.cnf = cnf;
this.viewNetwork = viewNetwork;
this.viewFactory = viewFactory;
this.viewManager = viewManager;
}
@Override
public TaskIterator createTaskIterator(CyNetwork network) {
return new TaskIterator(new ChopperNetworkTask(network, netMgr, cnf, namingUtil, viewNetwork, viewFactory, viewManager));
}
@Override
public boolean isReady(CyNetwork network) {
return network != null;
}
}
|
//@@author A0141094M
package seedu.typed.logic.parser;
/**
* Contains utility methods used for parsing strings for the command Find.
*/
public class FindUtil {
static final String QUERY_CANNOT_BE_EMPTY_MESSAGE = "query cannot be empty";
static final String QUERY_LEN_SHOULD_BE_ONE_MESSAGE = "query parameter should be a single word";
static final String QUERY_LEN_SHOULD_BE_LESS_THAN_ONE_MESSAGE = "query parameter should be empty or a single word";
static final String TAG_LEN_SHOULD_BE_ONE_MESSAGE = "tag parameter should be a single word";
static final String QUERY_CANNOT_BE_NULL_MESSAGE = "query cannot be null";
static final String STR_CANNOT_BE_NULL_MESSAGE = "str cannot be null";
private static final String QUERY_LEN_MUST_BE_POSITIVE_INT_MESSAGE = "length of query must be a positive int";
private static final String STR_LEN_MUST_BE_POSITIVE_INT_MESSAGE = "length of str must be a positive int";
private static final String WHITESPACE_DELIMITER = "\\s+";
private static final int MAX_EDIT_DISTANCE = 2; // lower distance = higher similarity
private static final int MAX_EDIT_DISTANCE_STRICT = 1;
/**
* Checks if {@code query} and {@code str} are an exact match, ignoring case.
*/
public static boolean isExactWordMatchIgnoreCase(String str, String query) {
assertCheckStrAndQuery(str, query);
str = str.toLowerCase();
query = query.toLowerCase();
return str.equals(query);
}
/**
* Checks if {@code query} is a substring of {@code str}, ignoring case.
*/
public static boolean isSubstringWordMatchIgnoreCase(String str, String query) {
assertCheckStrAndQuery(str, query);
str = str.toLowerCase();
query = query.toLowerCase();
return str.contains(query);
}
/**
* Checks if {@code query} is a fuzzy match to {@code str}, ignoring case.
* @param str non-null string
* @param query non-null, non-empty string that contains a single word
* @return isFuzzyMatch boolean indicating if str and query are a fuzzy match, i.e. similar
*/
public static boolean isFuzzyWordMatchIgnoreCase(String str, String query) {
assertCheckStrAndQuery(str, query);
str = str.toLowerCase();
query = query.toLowerCase();
if (str.length() <= 2) {
return isExactWordMatchIgnoreCase(str, query);
} else if (str.length() <= 4) {
return computeMinEditDistance(str, query) <= MAX_EDIT_DISTANCE_STRICT;
} else {
return computeMinEditDistance(str, query) <= MAX_EDIT_DISTANCE
|| isSubstringWordMatchIgnoreCase(str, query);
}
}
/**
* Checks if specified {@code str} is a similar match to any stored tags, ignoring case.
* @param tag non-null string that contains a single word
* @param query non-null string that contains a single word
* empty string always returns true
* @return isFuzzyMatch boolean indicating if str and word are a fuzzy match, i.e. similar
*/
public static boolean isFuzzyTagMatchIgnoreCase(String tag, String query) {
assert tag != null : STR_CANNOT_BE_NULL_MESSAGE;
assert query != null : QUERY_CANNOT_BE_NULL_MESSAGE;
assert tag.split(WHITESPACE_DELIMITER).length == 1 : TAG_LEN_SHOULD_BE_ONE_MESSAGE;
assert query.split(WHITESPACE_DELIMITER).length <= 1 : QUERY_LEN_SHOULD_BE_LESS_THAN_ONE_MESSAGE;
tag = tag.toLowerCase();
query = query.toLowerCase();
if (query.length() == 0) {
return true;
}
if (tag.length() <= 4) {
return isExactWordMatchIgnoreCase(tag, query);
} else {
return computeMinEditDistance(tag, query) <= MAX_EDIT_DISTANCE_STRICT
|| isSubstringWordMatchIgnoreCase(tag, query);
}
}
/**
* Computes the minimum edit distance between specified strings as a measure of similarity.
* @param str non-null string
* @param query non-null, non-empty string that contains a single word
* @return minimumEditDistance an int representation of how similar str and query are
*/
public static int computeMinEditDistance(String str, String query) {
assertCheckStrAndQuery(str, query);
int lenStr = str.length();
int lenWord = query.length();
return computeLevenshtein(initDistance(lenStr, lenWord), str, query);
}
/**
* Initializes the minimum edit distance table by padding the first row and column.
* @param lenStr length of str where str cannot be null
* @param lenQuery length of query where query cannot be null, empty, and must contain a single word
* @return editDistance an int array containing the initialized distances
*/
private static int[][] initDistance(int lenStr, int lenQuery) {
assert lenStr >= 0 : STR_LEN_MUST_BE_POSITIVE_INT_MESSAGE;
assert lenQuery >= 0 : QUERY_LEN_MUST_BE_POSITIVE_INT_MESSAGE;
int[][] editDistance = new int[lenStr + 1][lenQuery + 1];
for (int c = 0; c < lenQuery + 1; c++) {
editDistance[0][c] = c;
}
for (int r = 0; r < lenStr + 1; r++) {
editDistance[r][0] = r;
}
return editDistance;
}
/**
* Computes the edit distance of given indices using Levenshtein's operations.
* @param distance an array containing initialized distances
* @param str non-null string
* @param query non-null, non-empty string that contains a single word
* @return minimumEditDistance an int representation of how similar str and word are
*/
private static int computeLevenshtein(int[][] distance, String str, String query) {
assertCheckStrAndQuery(str, query);
for (int i = 1; i < distance.length; i++) {
for (int j = 1; j < distance[0].length; j++) {
int a = distance[i - 1][j] + 1;
int b = distance[i][j - 1] + 1;
int c = distance[i - 1][j - 1];
if (str.charAt(i - 1) != query.charAt(j - 1)) {
c += 1;
}
distance[i][j] = Math.min(a, Math.min(b, c));
}
}
return distance[distance.length - 1][distance[0].length - 1];
}
/**
* Checks that str is not null, and query is not null, not empty, and is a single word.
*/
private static void assertCheckStrAndQuery(String str, String query) {
assert str != null : STR_CANNOT_BE_NULL_MESSAGE;
assert query != null : QUERY_CANNOT_BE_NULL_MESSAGE;
assert !query.isEmpty() : QUERY_CANNOT_BE_EMPTY_MESSAGE;
assert query.split(WHITESPACE_DELIMITER).length == 1 : QUERY_LEN_SHOULD_BE_ONE_MESSAGE;
}
}
//@@author
|
package opendap.bes.dap2Responders;
import opendap.PathBuilder;
import opendap.auth.AuthenticationControls;
import opendap.bes.Version;
import opendap.bes.dap4Responders.Dap4Responder;
import opendap.bes.dap4Responders.MediaType;
import opendap.coreServlet.OPeNDAPException;
import opendap.coreServlet.ReqInfo;
import opendap.coreServlet.RequestCache;
import opendap.dap.Request;
import opendap.dap.User;
import opendap.http.mediaTypes.TextHtml;
import opendap.logging.LogUtil;
import opendap.namespaces.DAP;
import opendap.xml.Transformer;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.filter.ElementFilter;
import org.jdom.filter.Filter;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.transform.JDOMSource;
import org.owasp.encoder.Encode;
import org.slf4j.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.DataOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import static opendap.bes.dap4Responders.DatasetMetadata.HtmlDMR.encodeStringForJsInHtml;
public class Dap2IFH extends Dap4Responder {
private Logger _log;
private static String _defaultRequestSuffix = ".html";
private boolean _enforceRequiredUserSelection;
public Dap2IFH(String sysPath, BesApi besApi, boolean enforceRequiredUserSelection) {
this(sysPath,null, _defaultRequestSuffix, besApi, enforceRequiredUserSelection);
}
public Dap2IFH(String sysPath, String pathPrefix, String requestSuffixRegex, BesApi besApi, boolean enforceRequiredUserSelection) {
super(sysPath, pathPrefix, requestSuffixRegex, besApi);
_log = org.slf4j.LoggerFactory.getLogger(this.getClass());
_enforceRequiredUserSelection = enforceRequiredUserSelection;
setServiceRoleId("http://services.opendap.org/dap2/data_request_form");
setServiceTitle("DAP2 Dataset Form IFH");
setServiceDescription("DAP2 Data Request Form IFH (HTML).");
setServiceDescriptionLink("http://docs.opendap.org/index.php/DAP4:_Specification_Volume_2#DAP2:_HTML_DATA_Request_Form_Service");
setNormativeMediaType(new TextHtml(getRequestSuffix()));
_log.debug("Using RequestSuffix: '{}'", getRequestSuffix());
_log.debug("Using CombinedRequestSuffixRegex: '{}'", getCombinedRequestSuffixRegex());
}
public boolean isDataResponder(){ return false; }
public boolean isMetadataResponder(){ return true; }
public boolean enforceRequiredUserSelection() {
return _enforceRequiredUserSelection;
}
public void sendNormativeRepresentation(HttpServletRequest request, HttpServletResponse response) throws Exception {
// String context = request.getContextPath();
String requestedResourceId = ReqInfo.getLocalUrl(request);
String xmlBase = getXmlBase(request);
String resourceID = getResourceId(requestedResourceId, false);
String collectionUrl = ReqInfo.getCollectionUrl(request);
//QueryParameters qp = new QueryParameters(request);
Request oreq = new Request(null,request);
String constraintExpression = ReqInfo.getConstraintExpression(request);
BesApi besApi = getBesApi();
String supportEmail = besApi.getSupportEmail(requestedResourceId);
String mailtoHrefAttributeValue = OPeNDAPException.getSupportMailtoLink(request,200,"n/a",supportEmail);
_log.debug("Sending {} for dataset: {}",getServiceTitle(),resourceID);
MediaType responseMediaType = getNormativeMediaType();
// Stash the Media type in case there's an error. That way the error handler will know how to encode the error.
RequestCache.put(OPeNDAPException.ERROR_RESPONSE_MEDIA_TYPE_KEY, responseMediaType);
response.setContentType(responseMediaType.getMimeType());
Version.setOpendapMimeHeaders(request, response);
response.setHeader("Content-Description", getNormativeMediaType().getMimeType());
// Commented because of a bug in the OPeNDAP C++ stuff...
//response.setHeader("Content-Encoding", "plain");
XMLOutputter xmlo = new XMLOutputter(Format.getPrettyFormat());
Document ddx = new Document();
User user = new User(request);
besApi.getDDXDocument(user, resourceID,constraintExpression,xmlBase,ddx);
_log.debug(xmlo.outputString(ddx));
ddx.getRootElement().setAttribute("dataset_id",resourceID);
ddx.getRootElement().setAttribute("base", xmlBase, Namespace.XML_NAMESPACE); // not needed - DMR has it
String jsonLD = getDatasetJsonLD(collectionUrl,ddx);
_log.debug("JsonLD for dataset {}\n{}",requestedResourceId,jsonLD);
String currentDir = System.getProperty("user.dir");
_log.debug("Cached working directory: "+currentDir);
String xslDir = new PathBuilder(_systemPath).pathAppend("xsl").toString();
_log.debug("Changing working directory to "+ xslDir);
System.setProperty("user.dir",xslDir);
try {
String xsltDocName = "dap2_ifh.xsl";
// This Transformer class is an attempt at making the use of the saxon-9 API
// a little simpler to use. It makes it easy to set input parameters for the stylesheet.
// See the source code in opendap.xml.Transformer for more.
Transformer transformer = new Transformer(xsltDocName);
// transformer.setParameter("serviceContext", request.getServletContext().getContextPath()); // This is ServletAPI-3.0
transformer.setParameter("serviceContext", request.getContextPath()); // This is ServletAPI-2.5 (Tomcat 6 stopped here)
transformer.setParameter("docsService", oreq.getDocsServiceLocalID());
transformer.setParameter("HyraxVersion", Version.getHyraxVersionString());
transformer.setParameter("JsonLD", jsonLD);
transformer.setParameter("supportLink", mailtoHrefAttributeValue);
transformer.setParameter("enforceSelection", Boolean.toString(enforceRequiredUserSelection()));
AuthenticationControls.setLoginParameters(transformer,request);
// Transform the BES showCatalog response into a HTML page for the browser
DataOutputStream os = new DataOutputStream(response.getOutputStream());
transformer.transform(new JDOMSource(ddx), os);
os.flush();
LogUtil.setResponseSize(os.size());
_log.info("Sent {} size: {}", getServiceTitle(),os.size());
}
finally {
_log.debug("Restoring working directory to " + currentDir);
System.setProperty("user.dir", currentDir);
}
}
public String getDatasetJsonLD(String collectionUrl, Document ddx){
String indent = indent_inc;
Element dataset = ddx.getRootElement();
StringBuilder sb = new StringBuilder("\n");
sb.append("{\n");
sb.append(indent).append("\"@context\": {\n");
sb.append(indent).append(indent_inc).append("\"@vocab\": \"http://schema.org\"\n");
sb.append(indent).append("},\n");
sb.append(indent).append("\"@type\": \"Dataset\",\n");
String name = dataset.getAttributeValue("name");
sb.append(indent).append("\"name\": \"").append(name).append("\",\n");
String description = getBestDescription(dataset);
sb.append(indent).append("\"description\": \"").append(description).append("\",\n");
Attribute xmlBase = dataset.getAttribute("base", Namespace.XML_NAMESPACE);
String datasetUrl;
if(xmlBase==null){
_log.error("Unable to locate xml:base attribute for Dataset {}", name);
datasetUrl = PathBuilder.pathConcat(collectionUrl,name);
}
else {
datasetUrl = xmlBase.getValue();
}
sb.append(indent).append("\"url\": \"").append(datasetUrl).append("\",\n");
sb.append(indent).append("\"includedInDataCatalog\": { \n");
sb.append(indent).append(indent_inc).append("\"@type\": \"DataCatalog\", \n");
sb.append(indent).append(indent_inc).append("\"name\": \"Hyrax Data Server\", \n");
sb.append(indent).append(indent_inc).append("\"sameAs\": \"");
sb.append(PathBuilder.pathConcat(collectionUrl,"contents.html\"")).append("\n");
sb.append(indent).append("},\n");
List<Element> children = dataset.getChildren();
Vector<Element> variables = new Vector<>();
for(Element child : children){
if(!child.getName().equals("Attribute") && !child.getName().equals("blob")){
// It's not an Attribute so it must be a variable!
variables.add(child);
}
}
if(!variables.isEmpty()){
sb.append(indent).append("\"variableMeasured\": [\n");
// Top Level Attributes
String topLevelAttributes = attributesToProperties(dataset, datasetUrl, indent, true);
sb.append(topLevelAttributes);
boolean first = topLevelAttributes.isEmpty();
int mark = sb.length();
for(Element variable : variables){
if(!first)
sb.append(",\n");
sb.append(attributesToProperties(variable,variable.getAttributeValue("name"), indent, first));
if(sb.length()>mark)
first = false;
}
sb.append("\n");
sb.append(indent).append("]\n");
sb.append("}\n");
}
return sb.toString();
}
Filter attributeFilter = new ElementFilter("Attribute", DAP.DAPv32_NS);
private String indent_inc = " ";
public String attributesToProperties(Element variable, String name, String indent, boolean first){
String myIndent = indent + indent_inc;
StringBuilder sb = new StringBuilder();
sb.append(indent).append("{\n");
sb.append(myIndent).append("\"@type\": \"PropertyValue\",\n");
sb.append(myIndent).append("\"name\": \"").append(name).append("\",\n");
sb.append(myIndent).append("\"valueReference\": [ \n");
if(variable.getName().equals("Grid")){
// It's a Grid so we look at the Grid array to determine the GRid metadata content.
Element gridArray = variable.getChild("Array",DAP.DAPv32_NS);
if(gridArray!=null) {
List<Element> attributes = gridArray.getContent(attributeFilter);
sb.append(attributesToProperties(attributes, myIndent));
}
}
else if(variable.getName().equals("Sequence") || variable.getName().equals("Structure") ){
// It's a Container type... Wut do?
List<Element> attributes = variable.getContent(attributeFilter);
sb.append(attributesToProperties(attributes, myIndent));
//boolean first = true;
List<Element> children = variable.getChildren();
int mark = sb.length();
for(Element child : children){
if(!first)
sb.append(",\n");
sb.append(attributesToProperties(child, child.getAttributeValue("name"), myIndent, first));
if(sb.length()>mark)
first = false;
}
_log.error("attributesToProperties() - We don't have a good mapping for container types to JSON-LD markup.");
}
else {
// It's an atomic variable or an Array!
List<Element> attributes = variable.getContent(attributeFilter);
sb.append(attributesToProperties(attributes, myIndent));
}
sb.append("\n");
sb.append(myIndent).append("]\n");
sb.append(indent).append("}");
return sb.toString();
}
public String attributesToProperties(List<Element> attributes, String indent){
StringBuilder sb = new StringBuilder();
String myIndent = indent + indent_inc;
boolean first = true;
int mark = sb.length();
for(Element attribute : attributes){
if(attribute.getChild("Attribute",DAP.DAPv32_NS)!=null){
if(!first)
sb.append(",\n");
// It's an AttrTable so dig...
List<Element> myAttributes = attribute.getContent(attributeFilter);
sb.append(attributesToProperties(myAttributes,myIndent));
}
else {
// Not an AttrTable so it must have values...
String pValue = attributeToPropertyValue(attribute,myIndent);
if(!pValue.isEmpty()){
if(!first)
sb.append(",\n");
sb.append(pValue);
}
}
if(sb.length()>mark)
first = false;
}
return sb.toString();
}
public String attributeToPropertyValue(Element attribute, String indent){
StringBuilder sb = new StringBuilder();
List<Element> values = attribute.getChildren("value",DAP.DAPv32_NS);
if(!values.isEmpty()){
sb.append(indent).append("{\n");
sb.append(indent).append(indent_inc).append("\"@type\": \"PropertyValue\", \n");
sb.append(indent).append(indent_inc).append("\"name\": \"").append(Encode.forJavaScript(attribute.getAttributeValue("name"))).append("\", \n");
//sb.append(indent).append(indent_inc).append("\"type\": \"").append(Encode.forJavaScript(attribute.getAttributeValue("type"))).append("\", \n");
boolean jsEncode = true;
String type = attribute.getAttributeValue("type");
if(type !=null){
type = type.toLowerCase();
if (type.contains("int") ||
type.contains("float") ||
type.equals("byte")) {
jsEncode = false;
}
}
if(values.size()==1){
Element value = values.get(0);
sb.append(indent).append(indent_inc).append("\"value\": ");
if(jsEncode) {
sb.append(encodeStringForJsInHtml(value.getTextTrim()));
}
else {
sb.append("\"").append(value.getTextTrim()).append("\"");
}
}
else {
sb.append(indent).append(indent_inc).append("\"value\": [ ");
boolean first = true;
for(Element value : values){
if(!first)
sb.append(", ");
if(jsEncode) {
sb.append(encodeStringForJsInHtml(value.getTextTrim()));
}
else {
sb.append("\"").append(value.getTextTrim()).append("\"");
}
first = false;
}
sb.append(" ]");
}
sb.append(indent).append("}");
}
return sb.toString();
}
String getStringAttrValue(Element e, String target_name){
List<Element> dataset_attributes = e.getContent(attributeFilter);
for (Element attr: dataset_attributes) {
String type = e.getAttributeValue("type");
if (type == null) type = "";
String name = e.getAttributeValue("name");
if (name == null) name = "";
if(type.equalsIgnoreCase("string") && name.equalsIgnoreCase(target_name)){
Element valueElement = attr.getChild("Value",DAP.DAPv32_NS);
if(valueElement!=null){
return valueElement.getTextTrim();
}
}
}
return null;
}
public String getBestDescription(Element dapObj) {
String bestDescription = getDescription(dapObj);
if(bestDescription==null){
bestDescription = "The dataset contains no obvious metadata " +
"that might be used as a description.";
}
while(bestDescription.length()<55)
bestDescription += " ";
return bestDescription;
}
private String getDescription(Element dapObj){
String candidate = null;
List<Element> dataset_attributes = dapObj.getContent(attributeFilter);
Iterator<Element> itr = dataset_attributes.iterator();
while (itr.hasNext() && candidate==null){
Element attrElement = itr.next();
String type = attrElement.getAttributeValue("type");
if(type==null) type="";
String name = attrElement.getAttributeValue("name");
if(name==null) name="";
if(type.equalsIgnoreCase("container")){
// Then we recurse....
candidate = getDescription(attrElement);
}
else if(type.equalsIgnoreCase("string")){
// We only care about string valued attributes for a description...
String value = null;
Element valueElement = attrElement.getChild("Value",DAP.DAPv32_NS);
if(valueElement!=null)
value = valueElement.getTextTrim();
if(name.equalsIgnoreCase("description")){
candidate = value;
}
else if(name.equalsIgnoreCase("title")){
candidate = value;
}
}
}
return candidate;
}
}
|
package org.openhab.binding.zwave.internal.protocol.commandclass;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import org.openhab.binding.zwave.internal.protocol.SerialMessage;
import org.openhab.binding.zwave.internal.protocol.ZWaveController;
import org.openhab.binding.zwave.internal.protocol.ZWaveEndpoint;
import org.openhab.binding.zwave.internal.protocol.ZWaveNode;
import org.openhab.binding.zwave.internal.protocol.ZWaveSerialMessageException;
import org.openhab.binding.zwave.internal.protocol.commandclass.proprietary.FibaroFGRM222CommandClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
/**
* Z-Wave Command Class. Z-Wave device functions are controlled by command classes. A command class can be have one or
* multiple commands allowing the use of a certain function of the device.
*
* @author Chris Jackson
* @author Brian Crosby
*/
public abstract class ZWaveCommandClass {
@XStreamOmitField
private static final Logger logger = LoggerFactory.getLogger(ZWaveCommandClass.class);
private static final int SIZE_MASK = 0x07;
// private static final SCALE_MASK = 0x18; // unused
// private static final SCALE_SHIFT = 0x03; // unused
private static final int PRECISION_MASK = 0xe0;
private static final int PRECISION_SHIFT = 0x05;
@XStreamOmitField
private ZWaveNode node;
@XStreamOmitField
private ZWaveController controller;
private ZWaveEndpoint endpoint;
private int version = 0;
private int instances = 0;
@XStreamOmitField
protected int versionMax = 1;
@SuppressWarnings("unused")
private int versionSupported = 0;
/**
* Protected constructor. Initiates a new instance of a Command Class.
*
* @param node the node this instance commands.
* @param controller the controller to send messages to.
* @param endpoint the endpoint this Command class belongs to.
*/
protected ZWaveCommandClass(ZWaveNode node, ZWaveController controller, ZWaveEndpoint endpoint) {
this.node = node;
this.controller = controller;
this.endpoint = endpoint;
logger.debug("NODE {}: Command class {}, endpoint {} created", node.getNodeId(), getCommandClass().getLabel(),
endpoint);
}
/**
* Returns the node this command class belongs to.
*
* @return node
*/
protected ZWaveNode getNode() {
return node;
}
/**
* Sets the node this command class belongs to.
*
* @param node the node to set
*/
public void setNode(ZWaveNode node) {
this.node = node;
}
/**
* Returns the controller to send messages to.
*
* @return controller
*/
protected ZWaveController getController() {
return controller;
}
/**
* Sets the controller to send messages to.
*
* @param controller the controller to set
*/
public void setController(ZWaveController controller) {
this.controller = controller;
}
/**
* Returns the endpoint this command class belongs to.
*
* @return the endpoint this command class belongs to.
*/
public ZWaveEndpoint getEndpoint() {
return endpoint;
}
/**
* Sets the endpoint this command class belongs to.
*
* @param endpoint the endpoint to set
*/
public void setEndpoint(ZWaveEndpoint endpoint) {
this.endpoint = endpoint;
}
/**
* Returns the version of the command class.
*
* @return node
*/
public int getVersion() {
return version;
}
/**
* Sets the version number for this command class.
*
* @param version. The version number to set.
*/
public void setVersion(int version) {
// Record the version supported by the device
// This gets recorded in the XML so we know more about the device
versionSupported = version;
// Now set the version we are actually going to support
if (version > versionMax) {
this.version = versionMax;
logger.debug(
"NODE {}: Version = {}, version set to maximum supported by the binding. Enabling extra functionality.",
getNode().getNodeId(), versionMax);
} else {
this.version = version;
logger.debug("NODE {}: Version = {}, version set. Enabling extra functionality.", getNode().getNodeId(),
version);
}
}
/**
* The maximum version implemented by this command class.
*/
public int getMaxVersion() {
return versionMax;
}
/**
* Set options for this command class.
* Options are provided from the device configuration database
*
* @param options class
* @return true if options set ok
*/
public boolean setOptions(Map<String, String> options) {
return false;
}
/**
* Returns the number of instances of this command class
* in case the node supports the MULTI_INSTANCE command class (Version 1).
*
* @return the number of instances
*/
public int getInstances() {
return instances;
}
/**
* Returns the number of instances of this command class
* in case the node supports the MULTI_INSTANCE command class (Version 1).
*
* @param instances. The number of instances.
*/
public void setInstances(int instances) {
this.instances = instances;
}
/**
* Returns the command class.
*
* @return command class
*/
public abstract CommandClass getCommandClass();
/**
* Handles an incoming application command request.
*
* @param serialMessage the incoming message to process.
* @param offset the offset position from which to start message processing.
* @param endpoint the endpoint or instance number this message is meant for.
*/
public abstract void handleApplicationCommandRequest(SerialMessage serialMessage, int offset, int endpoint)
throws ZWaveSerialMessageException;
/**
* Gets an instance of the right command class.
* Returns null if the command class is not found.
*
* @param i the code to instantiate
* @param node the node this instance commands.
* @param controller the controller to send messages to.
* @return the ZWaveCommandClass instance that was instantiated, null otherwise
*/
public static ZWaveCommandClass getInstance(int i, ZWaveNode node, ZWaveController controller) {
return ZWaveCommandClass.getInstance(i, node, controller, null);
}
/**
* Gets an instance of the right command class.
* Returns null if the command class is not found.
*
* @param classId the code to instantiate
* @param node the node this instance commands.
* @param controller the controller to send messages to.
* @param endpoint the endpoint this Command class belongs to
* @return the ZWaveCommandClass instance that was instantiated, null otherwise
*/
public static ZWaveCommandClass getInstance(int classId, ZWaveNode node, ZWaveController controller,
ZWaveEndpoint endpoint) {
try {
CommandClass commandClass = CommandClass.getCommandClass(classId);
if (commandClass != null && commandClass.equals(CommandClass.MANUFACTURER_PROPRIETARY)) {
commandClass = CommandClass.getCommandClass(node.getManufacturer(), node.getDeviceType());
}
if (commandClass == null) {
logger.warn(String.format("NODE %d: Unknown command class 0x%02x", node.getNodeId(), classId));
return null;
}
Class<? extends ZWaveCommandClass> commandClassClass = commandClass.getCommandClassClass();
if (commandClassClass == null) {
logger.warn("NODE {}: Unsupported command class {}", node.getNodeId(), commandClass.getLabel(),
classId);
return null;
}
logger.debug("NODE {}: Creating new instance of command class {}", node.getNodeId(),
commandClass.getLabel());
Constructor<? extends ZWaveCommandClass> constructor = commandClassClass.getConstructor(ZWaveNode.class,
ZWaveController.class, ZWaveEndpoint.class);
return constructor.newInstance(new Object[] { node, controller, endpoint });
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
logger.error(String.format("NODE %d: Error instantiating command class 0x%02x", node.getNodeId(), classId));
e.printStackTrace();
return null;
}
}
/**
* Extract a decimal value from a byte array.
*
* @param buffer the buffer to be parsed.
* @param offset the offset at which to start reading
* @return the extracted decimal value
*/
protected BigDecimal extractValue(byte[] buffer, int offset) {
int size = buffer[offset] & SIZE_MASK;
int precision = (buffer[offset] & PRECISION_MASK) >> PRECISION_SHIFT;
if ((size + offset) >= buffer.length) {
logger.error("Error extracting value - length={}, offset={}, size={}.", buffer.length, offset, size);
throw new NumberFormatException();
}
int value = 0;
int i;
for (i = 0; i < size; ++i) {
value <<= 8;
value |= buffer[offset + i + 1] & 0xFF;
}
// Deal with sign extension. All values are signed
BigDecimal result;
if ((buffer[offset + 1] & 0x80) == 0x80) {
// MSB is signed
if (size == 1) {
value |= 0xffffff00;
} else if (size == 2) {
value |= 0xffff0000;
}
}
result = BigDecimal.valueOf(value);
BigDecimal divisor = BigDecimal.valueOf(Math.pow(10, precision));
return result.divide(divisor);
}
/**
* Extract a decimal value from a byte array.
*
* @param buffer the buffer to be parsed.
* @param offset the offset at which to start reading
* @return the extracted decimal value
*/
protected int extractValue(byte[] buffer, int offset, int size) {
int value = 0;
for (int i = 0; i < size; ++i) {
value <<= 8;
value |= buffer[offset + i] & 0xFF;
}
// Deal with sign extension. All values are signed
if ((buffer[offset] & 0x80) == 0x80) {
// MSB is signed
if (size == 1) {
value |= 0xffffff00;
} else if (size == 2) {
value |= 0xffff0000;
}
}
return value;
}
/**
* Encodes a decimal value as a byte array.
*
* @param value the decimal value to encode
* @param index the value index
* @return the value buffer
* @throws ArithmeticException when the supplied value is out of range.
* @since 1.4.0
*/
protected byte[] encodeValue(BigDecimal value) throws ArithmeticException {
// Remove any trailing zero's so we send the least amount of bytes possible
BigDecimal normalizedValue = value.stripTrailingZeros();
// Make our scale at least 0, precision cannot be more than 7 but
// this is guarded by the Integer min / max values already.
if (normalizedValue.scale() < 0) {
normalizedValue = normalizedValue.setScale(0);
}
if (normalizedValue.unscaledValue().compareTo(BigInteger.valueOf(Integer.MAX_VALUE)) > 0) {
throw new ArithmeticException();
} else if (normalizedValue.unscaledValue().compareTo(BigInteger.valueOf(Integer.MIN_VALUE)) < 0) {
throw new ArithmeticException();
}
// default size = 4
int size = 4;
// it might fit in a byte or short
if (normalizedValue.unscaledValue().intValue() >= Byte.MIN_VALUE
&& normalizedValue.unscaledValue().intValue() <= Byte.MAX_VALUE) {
size = 1;
} else if (normalizedValue.unscaledValue().intValue() >= Short.MIN_VALUE
&& normalizedValue.unscaledValue().intValue() <= Short.MAX_VALUE) {
size = 2;
}
int precision = normalizedValue.scale();
byte[] result = new byte[size + 1];
// precision + scale (unused) + size
result[0] = (byte) ((precision << PRECISION_SHIFT) | size);
int unscaledValue = normalizedValue.unscaledValue().intValue(); // ie. 22.5 = 225
for (int i = 0; i < size; i++) {
result[size - i] = (byte) ((unscaledValue >> (i * 8)) & 0xFF);
}
return result;
}
/**
* Command class enumeration. Lists all command classes available.
* Unsupported command classes by the binding return null for the command class Class.
*
* @author Jan-Willem Spuij
*/
@XStreamAlias("commandClass")
public enum CommandClass {
NO_OPERATION(0x00, "NO_OPERATION", ZWaveNoOperationCommandClass.class),
BASIC(0x20, "BASIC", ZWaveBasicCommandClass.class),
CONTROLLER_REPLICATION(0x21, "CONTROLLER_REPLICATION", ZWaveControllerReplicationCommandClass.class),
APPLICATION_STATUS(0x22, "APPLICATION_STATUS", ZWaveApplicationStatusClass.class),
ZIP_SERVICES(0x23, "ZIP_SERVICES", null),
ZIP_SERVER(0x24, "ZIP_SERVER", null),
SWITCH_BINARY(0x25, "SWITCH_BINARY", ZWaveBinarySwitchCommandClass.class),
SWITCH_MULTILEVEL(0x26, "SWITCH_MULTILEVEL", ZWaveMultiLevelSwitchCommandClass.class),
SWITCH_ALL(0x27, "SWITCH_ALL", ZWaveSwitchAllCommandClass.class),
SWITCH_TOGGLE_BINARY(0x28, "SWITCH_TOGGLE_BINARY", ZWaveBinaryToggleSwitchCommandClass.class),
SWITCH_TOGGLE_MULTILEVEL(0x29, "SWITCH_TOGGLE_MULTILEVEL", ZWaveMultiLevelToggleSwitchCommandClass.class),
CHIMNEY_FAN(0x2A, "CHIMNEY_FAN", ZWaveChimneyFanCommandClass.class),
SCENE_ACTIVATION(0x2B, "SCENE_ACTIVATION", ZWaveSceneActivationCommandClass.class),
SCENE_ACTUATOR_CONF(0x2C, "SCENE_ACTUATOR_CONF", ZWaveSceneActuatorConfigurationCommandClass.class),
SCENE_CONTROLLER_CONF(0x2D, "SCENE_CONTROLLER_CONF", ZWaveSceneControllerConfigurationCommandClass.class),
ZIP_CLIENT(0x2E, "ZIP_CLIENT", null),
ZIP_ADV_SERVICES(0x2F, "ZIP_ADV_SERVICES", null),
SENSOR_BINARY(0x30, "SENSOR_BINARY", ZWaveBinarySensorCommandClass.class),
SENSOR_MULTILEVEL(0x31, "SENSOR_MULTILEVEL", ZWaveMultiLevelSensorCommandClass.class),
METER(0x32, "METER", ZWaveMeterCommandClass.class),
COLOR(0x33, "COLOR", ZWaveColorCommandClass.class),
ZIP_ADV_CLIENT(0x34, "ZIP_ADV_CLIENT", null),
METER_PULSE(0x35, "METER_PULSE", ZWaveMeterPulseCommandClass.class),
METER_TBL_CONFIG(0x3C, "METER_TBL_CONFIG", ZWaveMeterTblConfigurationCommandClass.class),
METER_TBL_MONITOR(0x3D, "METER_TBL_MONITOR", ZWaveMeterTblMonitorCommandClass.class),
METER_TBL_PUSH(0x3E, "METER_TBL_PUSH", null),
HRV_STATUS(0x37, "HRV_STATUS", ZWaveHrvStatusCommandClass.class),
THERMOSTAT_HEATING(0x38, "THERMOSTAT_HEATING", null),
HRV_CONTROL(0x39, "HRV_CONTROL", ZWaveHrvControlCommandClass.class),
THERMOSTAT_MODE(0x40, "THERMOSTAT_MODE", ZWaveThermostatModeCommandClass.class),
THERMOSTAT_OPERATING_STATE(0x42, "THERMOSTAT_OPERATING_STATE", ZWaveThermostatOperatingStateCommandClass.class),
THERMOSTAT_SETPOINT(0x43, "THERMOSTAT_SETPOINT", ZWaveThermostatSetpointCommandClass.class),
THERMOSTAT_FAN_MODE(0x44, "THERMOSTAT_FAN_MODE", ZWaveThermostatFanModeCommandClass.class),
THERMOSTAT_FAN_STATE(0x45, "THERMOSTAT_FAN_STATE", ZWaveThermostatFanStateCommandClass.class),
CLIMATE_CONTROL_SCHEDULE(0x46, "CLIMATE_CONTROL_SCHEDULE", ZWaveClimateControlScheduleCommandClass.class),
THERMOSTAT_SETBACK(0x47, "THERMOSTAT_SETBACK", ZWaveThermostatSetbackCommandClass.class),
DOOR_LOCK_LOGGING(0x4C, "DOOR_LOCK_LOGGING", ZWaveDoorLockLoggingCommandClass.class),
SCHEDULE_ENTRY_LOCK(0x4E, "SCHEDULE_ENTRY_LOCK", ZWaveScheduleEntryLockCommandClass.class),
BASIC_WINDOW_COVERING(0x50, "BASIC_WINDOW_COVERING", ZWaveBasicWindowCoveringCommandClass.class),
MTP_WINDOW_COVERING(0x51, "MTP_WINDOW_COVERING", ZWaveMtpWindowCoveringCommandClass.class),
SCHEDULE(0x53, "SCHEDULE", ZWaveScheduleCommandClass.class),
CRC_16_ENCAP(0x56, "CRC_16_ENCAP", ZWaveCRC16EncapsulationCommandClass.class),
ASSOCIATION_GROUP_INFO(0x59, "ASSOCIATION_GROUP_INFO", ZwaveAssociationGroupInfoCommandClass.class),
DEVICE_RESET_LOCALLY(0x5a, "DEVICE_RESET_LOCALLY", ZWaveDeviceResetLocallyCommandClass.class),
CENTRAL_SCENE(0x5b, "CENTRAL_SCENE", ZWaveCentralSceneCommandClass.class),
ZWAVE_PLUS_INFO(0x5e, "ZWAVE_PLUS_INFO", ZWavePlusCommandClass.class),
MULTI_INSTANCE(0x60, "MULTI_INSTANCE", ZWaveMultiInstanceCommandClass.class),
DOOR_LOCK(0x62, "DOOR_LOCK", ZWaveDoorLockCommandClass.class),
USER_CODE(0x63, "USER_CODE", ZWaveUserCodeCommandClass.class),
BARRIER_OPERATOR(0x66, "BARRIER_OPERATOR", ZWaveBarrierOperatorCommandClass.class),
CONFIGURATION(0x70, "CONFIGURATION", ZWaveConfigurationCommandClass.class),
ALARM(0x71, "ALARM", ZWaveAlarmCommandClass.class),
MANUFACTURER_SPECIFIC(0x72, "MANUFACTURER_SPECIFIC", ZWaveManufacturerSpecificCommandClass.class),
POWERLEVEL(0x73, "POWERLEVEL", ZWavePowerLevelCommandClass.class),
PROTECTION(0x75, "PROTECTION", ZWaveProtectionCommandClass.class),
LOCK(0x76, "LOCK", ZWaveLockCommandClass.class),
NODE_NAMING(0x77, "NODE_NAMING", ZWaveNodeNamingCommandClass.class),
FIRMWARE_UPDATE_MD(0x7A, "FIRMWARE_UPDATE_MD", ZWaveFirmwareUpdateCommandClass.class),
GROUPING_NAME(0x7B, "GROUPING_NAME", ZWaveGroupingNameCommandClass.class),
REMOTE_ASSOCIATION_ACTIVATE(0x7C, "REMOTE_ASSOCIATION_ACTIVATE", null),
REMOTE_ASSOCIATION(0x7D, "REMOTE_ASSOCIATION", null),
BATTERY(0x80, "BATTERY", ZWaveBatteryCommandClass.class),
CLOCK(0x81, "CLOCK", ZWaveClockCommandClass.class),
HAIL(0x82, "HAIL", ZWaveHailCommandClass.class),
WAKE_UP(0x84, "WAKE_UP", ZWaveWakeUpCommandClass.class),
ASSOCIATION(0x85, "ASSOCIATION", ZWaveAssociationCommandClass.class),
VERSION(0x86, "VERSION", ZWaveVersionCommandClass.class),
INDICATOR(0x87, "INDICATOR", ZWaveIndicatorCommandClass.class),
PROPRIETARY(0x88, "PROPRIETARY", null),
LANGUAGE(0x89, "LANGUAGE", ZWaveLanguageCommandClass.class),
TIME(0x8A, "TIME", ZWaveTimeCommandClass.class),
TIME_PARAMETERS(0x8B, "TIME_PARAMETERS", ZWaveTimeParametersCommandClass.class),
GEOGRAPHIC_LOCATION(0x8C, "GEOGRAPHIC_LOCATION", null),
COMPOSITE(0x8D, "COMPOSITE", null),
MULTI_INSTANCE_ASSOCIATION(0x8E, "MULTI_INSTANCE_ASSOCIATION", null), // ZWaveMultiAssociationCommandClass.class),
MULTI_CMD(0x8F, "MULTI_CMD", ZWaveMultiCommandCommandClass.class),
ENERGY_PRODUCTION(0x90, "ENERGY_PRODUCTION", ZWaveEnergyProductionCommandClass.class),
// The getInstance method will catch this and translate to the correct
// class for the device.
MANUFACTURER_PROPRIETARY(0x91, "MANUFACTURER_PROPRIETARY", null),
SCREEN_MD(0x92, "SCREEN_MD", null),
SCREEN_ATTRIBUTES(0x93, "SCREEN_ATTRIBUTES", null),
SIMPLE_AV_CONTROL(0x94, "SIMPLE_AV_CONTROL", null),
AV_CONTENT_DIRECTORY_MD(0x95, "AV_CONTENT_DIRECTORY_MD", null),
AV_RENDERER_STATUS(0x96, "AV_RENDERER_STATUS", null),
AV_CONTENT_SEARCH_MD(0x97, "AV_CONTENT_SEARCH_MD", null),
SECURITY(0x98, "SECURITY", ZWaveSecurityCommandClassWithInitialization.class),
AV_TAGGING_MD(0x99, "AV_TAGGING_MD", null),
IP_CONFIGURATION(0x9A, "IP_CONFIGURATION", null),
ASSOCIATION_COMMAND_CONFIGURATION(0x9B, "ASSOCIATION_COMMAND_CONFIGURATION", null),
SENSOR_ALARM(0x9C, "SENSOR_ALARM", ZWaveAlarmSensorCommandClass.class),
SILENCE_ALARM(0x9D, "SILENCE_ALARM", ZWaveAlarmSilenceCommandClass.class),
SENSOR_CONFIGURATION(0x9E, "SENSOR_CONFIGURATION", ZWaveSensorConfigurationCommandClass.class),
MARK(0xEF, "MARK", null),
NON_INTEROPERABLE(0xF0, "NON_INTEROPERABLE", null),
FIBARO_FGRM_222(0x010F, 0x0301, "FIBARO_FGRM_222", FibaroFGRM222CommandClass.class);
/**
* A mapping between the integer code and its corresponding
* Command class to facilitate lookup by code.
*/
private static Map<Integer, CommandClass> codeToCommandClassMapping;
/**
* A mapping between the string label and its corresponding
* Command class to facilitate lookup by label.
*/
private static Map<String, CommandClass> labelToCommandClassMapping;
private static int getKeyFromManufacturerAndDeviceId(int manufacturer, int deviceId) {
return manufacturer << 16 | deviceId;
}
private int key;
private String label;
private Class<? extends ZWaveCommandClass> commandClassClass;
private CommandClass(int key, String label, Class<? extends ZWaveCommandClass> commandClassClass) {
this.key = key;
this.label = label;
this.commandClassClass = commandClassClass;
}
private CommandClass(int manufacturer, int deviceId, String label,
Class<? extends ZWaveCommandClass> commandClassClass) {
this(getKeyFromManufacturerAndDeviceId(manufacturer, deviceId), label, commandClassClass);
}
private static void initMapping() {
codeToCommandClassMapping = new HashMap<Integer, CommandClass>();
labelToCommandClassMapping = new HashMap<String, CommandClass>();
for (CommandClass s : values()) {
codeToCommandClassMapping.put(s.key, s);
labelToCommandClassMapping.put(s.label.toLowerCase(), s);
}
}
/**
* Lookup function based on the command class code.
* Returns null if there is no command class with code i
*
* @param i the code to lookup
* @return enumeration value of the command class.
*/
public static CommandClass getCommandClass(int i) {
if (codeToCommandClassMapping == null) {
initMapping();
}
return codeToCommandClassMapping.get(i);
}
/**
* Lookup function based on the manufacturer and device ID.
*
* @param manufacturer the manufacturer ID
* @param deviceId the device ID
* @return enumeration value of the command class or null if there is no command class.
*/
public static CommandClass getCommandClass(int manufacturer, int deviceId) {
return getCommandClass(getKeyFromManufacturerAndDeviceId(manufacturer, deviceId));
}
/**
* Lookup function based on the command class label.
* Returns null if there is no command class with that label.
*
* @param label the label to lookup
* @return enumeration value of the command class.
*/
public static CommandClass getCommandClass(String label) {
if (labelToCommandClassMapping == null) {
initMapping();
}
return labelToCommandClassMapping.get(label.toLowerCase());
}
/**
* @return the key
*/
public int getKey() {
return key;
}
/**
* @return the label
*/
public String getLabel() {
return label;
}
/**
* @return the command class Class
*/
public Class<? extends ZWaveCommandClass> getCommandClassClass() {
return commandClassClass;
}
}
}
|
package tigase.muc.modules;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import tigase.criteria.Criteria;
import tigase.criteria.ElementCriteria;
import tigase.muc.Affiliation;
import tigase.muc.DateUtil;
import tigase.muc.ElementWriter;
import tigase.muc.MucConfig;
import tigase.muc.Role;
import tigase.muc.Room;
import tigase.muc.RoomConfig;
import tigase.muc.RoomConfig.Anonymity;
import tigase.muc.exceptions.MUCException;
import tigase.muc.history.HistoryProvider;
import tigase.muc.logger.MucLogger;
import tigase.muc.modules.PresenceModule.DelayDeliveryThread.DelDeliverySend;
import tigase.muc.repository.IMucRepository;
import tigase.muc.repository.RepositoryException;
import tigase.server.Packet;
import tigase.util.TigaseStringprepException;
import tigase.xml.Element;
import tigase.xml.XMLNodeIfc;
import tigase.xmpp.Authorization;
import tigase.xmpp.BareJID;
import tigase.xmpp.JID;
/**
* @author bmalkow
*
*/
public class PresenceModule extends AbstractModule {
public static class DelayDeliveryThread extends Thread {
public static interface DelDeliverySend {
void sendDelayedPacket(Packet packet);
}
private final LinkedList<Element[]> items = new LinkedList<Element[]>();
private final DelDeliverySend sender;
public DelayDeliveryThread(DelDeliverySend component) {
this.sender = component;
}
/**
* @param elements
*/
public void put(Collection<Element> elements) {
if (elements != null && elements.size() > 0) {
items.push(elements.toArray(new Element[] {}));
}
}
public void put(Element element) {
items.add(new Element[] { element });
}
@Override
public void run() {
try {
do {
sleep(553);
if (items.size() > 0) {
Element[] toSend = items.poll();
if (toSend != null) {
for (Element element : toSend) {
try {
sender.sendDelayedPacket(Packet.packetInstance(element));
} catch (TigaseStringprepException ex) {
log.info("Packet addressing problem, stringprep failed: " + element);
}
}
}
}
} while (true);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static final Criteria CRIT = ElementCriteria.name("presence");
protected static final Logger log = Logger.getLogger(PresenceModule.class.getName());
private static Role getDefaultRole(final RoomConfig config, final Affiliation affiliation) {
Role newRole;
if (config.isRoomModerated() && affiliation == Affiliation.none) {
newRole = Role.visitor;
} else {
switch (affiliation) {
case admin:
newRole = Role.moderator;
break;
case member:
newRole = Role.participant;
break;
case none:
newRole = Role.participant;
break;
case outcast:
newRole = Role.none;
break;
case owner:
newRole = Role.moderator;
break;
default:
newRole = Role.none;
break;
}
}
return newRole;
}
private static Integer toInteger(String v, Integer defaultValue) {
if (v == null)
return defaultValue;
try {
return Integer.parseInt(v);
} catch (Exception e) {
return defaultValue;
}
}
private final Set<Criteria> allowedElements = new HashSet<Criteria>();
private final Set<Criteria> disallowedElements = new HashSet<Criteria>();
private boolean filterEnabled = true;
private final HistoryProvider historyProvider;
private boolean lockNewRoom = true;
private final MucLogger mucLogger;
public PresenceModule(MucConfig config, ElementWriter writer, IMucRepository mucRepository,
HistoryProvider historyProvider, DelDeliverySend sender, MucLogger mucLogger) {
super(config, writer, mucRepository);
this.historyProvider = historyProvider;
this.mucLogger = mucLogger;
this.filterEnabled = config.isPresenceFilterEnabled();
allowedElements.add(ElementCriteria.name("show"));
allowedElements.add(ElementCriteria.name("status"));
allowedElements.add(ElementCriteria.name("priority"));
allowedElements.add(ElementCriteria.xmlns("http://jabber.org/protocol/caps"));
log.config("Filtering presence children is " + (filterEnabled ? "enabled" : "disabled"));
}
/**
* @param room
* @param date
* @param senderJID
* @param nickName
*/
private void addJoinToHistory(Room room, Date date, JID senderJID, String nickName) {
if (historyProvider != null)
historyProvider.addJoinEvent(room, date, senderJID, nickName);
if (mucLogger != null && room.getConfig().isLoggingEnabled()) {
mucLogger.addJoinEvent(room, date, senderJID, nickName);
}
}
/**
* @param room
* @param date
* @param senderJID
* @param nickName
*/
private void addLeaveToHistory(Room room, Date date, JID senderJID, String nickName) {
if (historyProvider != null)
historyProvider.addLeaveEvent(room, date, senderJID, nickName);
if (mucLogger != null && room.getConfig().isLoggingEnabled()) {
mucLogger.addLeaveEvent(room, date, senderJID, nickName);
}
}
protected Element clonePresence(Element element) {
Element presence = new Element(element);
if (filterEnabled) {
List<Element> cc = element.getChildren();
if (cc != null) {
List<XMLNodeIfc> children = new ArrayList<XMLNodeIfc>();
for (Element c : cc) {
for (Criteria crit : allowedElements) {
if (crit.match(c)) {
children.add(c);
break;
}
}
}
presence.setChildren(children);
}
}
Element toRemove = presence.getChild("x", "http://jabber.org/protocol/muc");
if (toRemove != null)
presence.removeChild(toRemove);
return presence;
}
@Override
public String[] getFeatures() {
return null;
}
@Override
public Criteria getModuleCriteria() {
return CRIT;
}
public boolean isLockNewRoom() {
return lockNewRoom;
}
private Element preparePresence(JID occupantJid, final Element presence, Room room, BareJID roomJID, String nickName,
Affiliation affiliation, Role role, JID senderJID, boolean newRoomCreated, String newNickName) {
Anonymity anonymity = room.getConfig().getRoomAnonymity();
final Affiliation occupantAffiliation = room.getAffiliation(occupantJid.getBareJID());
try {
presence.setAttribute("from", JID.jidInstance(roomJID, nickName).toString());
} catch (TigaseStringprepException e) {
presence.setAttribute("from", roomJID + "/" + nickName);
}
presence.setAttribute("to", occupantJid.toString());
Element x = new Element("x", new String[] { "xmlns" }, new String[] { "http://jabber.org/protocol/muc#user" });
Element item = new Element("item", new String[] { "affiliation", "role", "nick" }, new String[] { affiliation.name(),
role.name(), nickName });
if (senderJID.equals(occupantJid)) {
x.addChild(new Element("status", new String[] { "code" }, new String[] { "110" }));
if (anonymity == Anonymity.nonanonymous) {
x.addChild(new Element("status", new String[] { "code" }, new String[] { "100" }));
}
if (room.getConfig().isLoggingEnabled()) {
x.addChild(new Element("status", new String[] { "code" }, new String[] { "170" }));
}
}
if (newRoomCreated) {
x.addChild(new Element("status", new String[] { "code" }, new String[] { "201" }));
}
if (anonymity == Anonymity.nonanonymous
|| (anonymity == Anonymity.semianonymous && occupantAffiliation.isViewOccupantsJid())) {
item.setAttribute("jid", senderJID.toString());
}
if (newNickName != null) {
x.addChild(new Element("status", new String[] { "code" }, new String[] { "303" }));
item.setAttribute("nick", newNickName);
}
x.addChild(item);
presence.addChild(x);
return presence;
}
private void preparePresenceToAllOccupants(final Element $presence, Room room, BareJID roomJID, String nickName,
Affiliation affiliation, Role role, JID senderJID, boolean newRoomCreated, String newNickName)
throws TigaseStringprepException {
for (String occupantNickname : room.getOccupantsNicknames()) {
for (JID occupantJid : room.getOccupantsJidsByNickname(occupantNickname)) {
Element presence = preparePresence(occupantJid, $presence.clone(), room, roomJID, nickName, affiliation, role,
senderJID, newRoomCreated, newNickName);
writer.write(Packet.packetInstance(presence));
}
}
}
private void preparePresenceToAllOccupants(Room room, BareJID roomJID, String nickName, Affiliation affiliation, Role role,
JID senderJID, boolean newRoomCreated, String newNickName) throws TigaseStringprepException {
Element presence;
if (newNickName != null) {
presence = new Element("presence");
presence.setAttribute("type", "unavailable");
} else if (room.getOccupantsNickname(senderJID) == null) {
presence = new Element("presence");
presence.setAttribute("type", "unavailable");
} else {
presence = room.getLastPresenceCopyByJid(senderJID.getBareJID());
}
preparePresenceToAllOccupants(presence, room, roomJID, nickName, affiliation, role, senderJID, newRoomCreated,
newNickName);
}
@Override
public void process(Packet element) throws MUCException, TigaseStringprepException {
final JID senderJID = JID.jidInstance(element.getAttribute("from"));
final BareJID roomJID = BareJID.bareJIDInstance(element.getAttribute("to"));
final String nickName = getNicknameFromJid(JID.jidInstance(element.getAttribute("to")));
final String presenceType = element.getAttribute("type");
if (presenceType != null && "error".equals(presenceType)) {
if (log.isLoggable(Level.FINER))
log.finer("Ignoring presence with type='" + presenceType + "' from " + senderJID);
return;
}
if (nickName == null) {
throw new MUCException(Authorization.JID_MALFORMED);
}
try {
Room room = repository.getRoom(roomJID);
if (presenceType != null && "unavailable".equals(presenceType)) {
processExit(room, element.getElement(), senderJID);
return;
}
final String knownNickname;
final boolean roomCreated;
if (room == null) {
log.info("Creating new room '" + roomJID + "' by user " + nickName + "' <" + senderJID.toString() + ">");
room = repository.createNewRoom(roomJID, senderJID);
room.addAffiliationByJid(senderJID.getBareJID(), Affiliation.owner);
room.setRoomLocked(this.lockNewRoom);
roomCreated = true;
knownNickname = null;
} else {
roomCreated = false;
knownNickname = room.getOccupantsNickname(senderJID);
}
final boolean probablyReEnter = element.getElement().getChild("x", "http://jabber.org/protocol/muc") != null;
if (probablyReEnter || knownNickname == null) {
processEntering(room, roomCreated, element.getElement(), senderJID, nickName);
} else if (knownNickname.equals(nickName)) {
processChangeAvailabilityStatus(room, element.getElement(), senderJID, knownNickname);
} else if (!knownNickname.equals(nickName)) {
processChangeNickname(room, element.getElement(), senderJID, knownNickname, nickName);
}
} catch (MUCException e) {
throw e;
} catch (TigaseStringprepException e) {
throw e;
} catch (RepositoryException e) {
throw new RuntimeException(e);
}
}
protected void processChangeAvailabilityStatus(final Room room, final Element presenceElement, final JID senderJID,
final String nickname) throws TigaseStringprepException {
if (log.isLoggable(Level.FINEST))
log.finest("Processing stanza " + presenceElement.toString());
room.updatePresenceByJid(null, clonePresence(presenceElement));
final Affiliation affiliation = room.getAffiliation(senderJID.getBareJID());
final Role role = room.getRole(nickname);
Element pe = room.getLastPresenceCopyByJid(senderJID.getBareJID());
preparePresenceToAllOccupants(pe, room, room.getRoomJID(), nickname, affiliation, role, senderJID, false, null);
}
protected void processChangeNickname(final Room room, final Element element, final JID senderJID,
final String senderNickname, final String newNickName) throws TigaseStringprepException, MUCException {
if (log.isLoggable(Level.FINEST))
log.finest("Processing stanza " + element.toString());
throw new MUCException(Authorization.FEATURE_NOT_IMPLEMENTED, "Will me done soon");
// TODO Example 23. Service Denies Room Join Because Roomnicks Are
// Locked Down (???)
}
protected void processEntering(final Room room, final boolean roomCreated, final Element element, final JID senderJID,
final String nickname) throws MUCException, TigaseStringprepException {
if (log.isLoggable(Level.FINEST))
log.finest("Processing stanza " + element.toString());
final Affiliation affiliation = room.getAffiliation(senderJID.getBareJID());
final Anonymity anonymity = room.getConfig().getRoomAnonymity();
final Element xElement = element.getChild("x", "http://jabber.org/protocol/muc");
final Element password = xElement == null ? null : xElement.getChild("password");
if (room.getConfig().isPasswordProtectedRoom()) {
final String psw = password == null ? null : password.getCData();
final String roomPassword = room.getConfig().getPassword();
if (psw == null || !psw.equals(roomPassword)) {
// Service Denies Access Because No Password Provided
log.finest("Password '" + psw + "' is not match to room password '" + roomPassword + "' ");
throw new MUCException(Authorization.NOT_AUTHORIZED);
}
}
if (room.isRoomLocked() && affiliation != Affiliation.owner) {
// Service Denies Access Because Room Does Not (Yet) Exist
throw new MUCException(Authorization.ITEM_NOT_FOUND);
}
if (!affiliation.isEnterOpenRoom()) {
// Service Denies Access Because User is Banned
log.info("User " + nickname + "' <" + senderJID.toString() + "> is on rooms '" + room.getRoomJID() + "' blacklist");
throw new MUCException(Authorization.FORBIDDEN);
} else if (room.getConfig().isRoomMembersOnly() && !affiliation.isEnterMembersOnlyRoom()) {
// Service Denies Access Because User Is Not on Member List
log.info("User " + nickname + "' <" + senderJID.toString() + "> is NOT on rooms '" + room.getRoomJID()
+ "' member list.");
throw new MUCException(Authorization.REGISTRATION_REQUIRED);
}
final BareJID currentOccupantJid = room.getOccupantsJidByNickname(nickname);
if (currentOccupantJid != null && !currentOccupantJid.equals(senderJID.getBareJID())) {
// Service Denies Access Because of Nick Conflict
throw new MUCException(Authorization.CONFLICT);
}
// TODO Service Informs User that Room Occupant Limit Has Been Reached
// Service Sends Presence from Existing Occupants to New Occupant
for (String occupantNickname : room.getOccupantsNicknames()) {
final Affiliation occupantAffiliation = room.getAffiliation(occupantNickname);
final Role occupantRole = room.getRole(occupantNickname);
final BareJID occupantJid = room.getOccupantsJidByNickname(occupantNickname);
Element presence = room.getLastPresenceCopyByJid(occupantJid);
presence.setAttribute("from", room.getRoomJID() + "/" + occupantNickname);
presence.setAttribute("to", senderJID.toString());
Element x = new Element("x", new String[] { "xmlns" }, new String[] { "http://jabber.org/protocol/muc#user" });
Element item = new Element("item", new String[] { "affiliation", "role", "nick" }, new String[] {
occupantAffiliation.name(), occupantRole.name(), occupantNickname });
if (anonymity == Anonymity.nonanonymous
|| (anonymity == Anonymity.semianonymous && (affiliation == Affiliation.admin || affiliation == Affiliation.owner))) {
item.setAttribute("jid", occupantJid.toString());
}
x.addChild(item);
presence.addChild(x);
writer.write(Packet.packetInstance(presence));
}
final Role newRole = getDefaultRole(room.getConfig(), affiliation);
log.finest("Occupant '" + nickname + "' <" + senderJID.toString() + "> is entering room " + room.getRoomJID()
+ " as role=" + newRole.name() + ", affiliation=" + affiliation.name());
room.addOccupantByJid(senderJID, nickname, newRole);
Element pe = clonePresence(element);
room.updatePresenceByJid(null, pe);
if (currentOccupantJid == null) {
// Service Sends New Occupant's Presence to All Occupants
// Service Sends New Occupant's Presence to New Occupant
preparePresenceToAllOccupants(room, room.getRoomJID(), nickname, affiliation, newRole, senderJID, roomCreated, null);
} else {
// Service Sends New Occupant's Presence to New Occupant
Element p = preparePresence(senderJID, pe, room, room.getRoomJID(), nickname, affiliation, newRole, senderJID,
roomCreated, null);
writer.writeElement(p);
}
Integer maxchars = null;
Integer maxstanzas = null;
Integer seconds = null;
Date since = null;
Element hist = xElement == null ? null : xElement.getChild("history");
if (hist != null) {
maxchars = toInteger(hist.getAttribute("maxchars"), null);
maxstanzas = toInteger(hist.getAttribute("maxstanzas"), null);
seconds = toInteger(hist.getAttribute("seconds"), null);
since = DateUtil.parse(hist.getAttribute("since"));
}
sendHistoryToUser(room, senderJID, maxchars, maxstanzas, seconds, since, writer);
if (room.getSubject() != null && room.getSubjectChangerNick() != null && room.getSubjectChangeDate() != null) {
Element message = new Element("message", new String[] { "type", "from", "to" }, new String[] { "groupchat",
room.getRoomJID() + "/" + room.getSubjectChangerNick(), senderJID.toString() });
message.addChild(new Element("subject", room.getSubject()));
String stamp = DateUtil.formatDatetime(room.getSubjectChangeDate());
Element delay = new Element("delay", new String[] { "xmlns", "stamp" }, new String[] { "urn:xmpp:delay", stamp });
delay.setAttribute("jid", room.getRoomJID() + "/" + room.getSubjectChangerNick());
Element x = new Element("x", new String[] { "xmlns", "stamp" }, new String[] { "jabber:x:delay",
DateUtil.formatOld(room.getSubjectChangeDate()) });
message.addChild(delay);
message.addChild(x);
writer.writeElement(message);
}
if (room.isRoomLocked()) {
sendMucMessage(room, room.getOccupantsNickname(senderJID), "Room is locked. Please configure.");
}
if (roomCreated) {
StringBuilder sb = new StringBuilder();
sb.append("Welcome! You created new Multi User Chat Room.");
if (room.isRoomLocked())
sb.append(" Room is locked now. Configure it please!");
else
sb.append(" Room is unlocked and ready for occupants!");
sendMucMessage(room, room.getOccupantsNickname(senderJID), sb.toString());
}
if (room.getConfig().isLoggingEnabled()) {
addJoinToHistory(room, new Date(), senderJID, nickname);
}
}
protected void processExit(final Room room, final Element presenceElement, final JID senderJID) throws MUCException,
TigaseStringprepException {
if (log.isLoggable(Level.FINEST))
log.finest("Processing stanza " + presenceElement.toString());
if (room == null)
throw new MUCException(Authorization.ITEM_NOT_FOUND, "Unkown room");
final String nickname = room.getOccupantsNickname(senderJID);
if (nickname == null)
throw new MUCException(Authorization.ITEM_NOT_FOUND, "Unkown occupant");
final Element pe = clonePresence(presenceElement);
final Affiliation affiliation = room.getAffiliation(senderJID.getBareJID());
final Role role = room.getRole(nickname);
final Element selfPresence = preparePresence(senderJID, pe, room, room.getRoomJID(), nickname, affiliation, role,
senderJID, false, null);
boolean nicknameGone = room.removeOccupant(senderJID);
room.updatePresenceByJid(senderJID, pe);
writer.writeElement(selfPresence);
// TODO if highest priority is gone, then send current highest priority
// to occupants
if (nicknameGone) {
preparePresenceToAllOccupants(pe, room, room.getRoomJID(), nickname, affiliation, role, senderJID, false, null);
if (room.getConfig().isLoggingEnabled()) {
addLeaveToHistory(room, new Date(), senderJID, nickname);
}
}
}
/**
* @param room
* @param senderJID
* @param maxchars
* @param maxstanzas
* @param seconds
* @param since
*/
private void sendHistoryToUser(final Room room, final JID senderJID, final Integer maxchars, final Integer maxstanzas,
final Integer seconds, final Date since, final ElementWriter writer) {
if (historyProvider != null)
historyProvider.getHistoryMessages(room, senderJID, maxchars, maxstanzas, seconds, since, writer);
}
public void setLockNewRoom(boolean lockNewRoom) {
this.lockNewRoom = lockNewRoom;
}
}
|
package org.csstudio.alarm.beast.ui.alarmtable;
import java.text.SimpleDateFormat;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.csstudio.alarm.beast.client.AlarmTreeItem;
import org.csstudio.alarm.beast.client.AlarmTreePV;
import org.csstudio.alarm.beast.client.AlarmTreeRoot;
import org.csstudio.alarm.beast.ui.actions.AcknowledgeAction;
import org.csstudio.alarm.beast.ui.actions.MaintenanceModeAction;
import org.csstudio.alarm.beast.ui.alarmtable.actions.ColumnConfigureAction;
import org.csstudio.alarm.beast.ui.alarmtable.actions.FilterAction;
import org.csstudio.alarm.beast.ui.alarmtable.actions.NewTableAction;
import org.csstudio.alarm.beast.ui.alarmtable.actions.ResetColumnsAction;
import org.csstudio.alarm.beast.ui.alarmtable.actions.SeparateCombineTablesAction;
import org.csstudio.alarm.beast.ui.alarmtable.actions.ShowFilterAction;
import org.csstudio.alarm.beast.ui.clientmodel.AlarmClientModel;
import org.csstudio.alarm.beast.ui.clientmodel.AlarmClientModelListener;
import org.csstudio.alarm.beast.ui.alarmtable.Preferences;
import org.csstudio.ui.util.dnd.ControlSystemDropTarget;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
/**
* Eclipse View for the alarm table.
*
* @author Kay Kasemir
* @author Jaka Bobnar - Combined/split alarm tables, configurable columns
*/
public class AlarmTableView extends ViewPart
{
public static final int PROP_FILTER = 555444;
public static final int PROP_FILTER_ITEM = 555445;
private static AtomicInteger secondaryId = new AtomicInteger(1);
/**
* Return the next secondary id that has not been opened.
*
* @return part
*/
public static String newSecondaryID(IViewPart part)
{
while (part.getSite().getPage().findViewReference(part.getSite().getId(), String.valueOf(secondaryId.get())) != null)
{
secondaryId.incrementAndGet();
}
return String.valueOf(secondaryId.get());
}
private AlarmClientModel model;
private AlarmClientModel defaultModel;
private AlarmClientModelListener modelListener = new AlarmClientModelListener()
{
@Override
public void newAlarmConfiguration(AlarmClientModel model)
{
parent.getDisplay().asyncExec(()->updateFilterItem());
}
@Override
public void serverTimeout(AlarmClientModel model)
{
}
@Override
public void serverModeUpdate(AlarmClientModel model, boolean maintenance_mode)
{
}
@Override
public void newAlarmState(AlarmClientModel model, AlarmTreePV pv, boolean parent_changed)
{
}
};
private Composite parent;
private GUI gui;
private MaintenanceModeAction maintenanceModeAction;
private IMemento memento;
private FilterType filterType;
/** Combined active and acknowledge alarms, group into separate tables? */
private boolean combinedTables;
/** Should severity icons blink or not */
private boolean blinkingIcons;
/** The time format string used for formatting the alarm time label */
private String timeFormat;
/** The name of the filter item */
private String filterItemPath;
/** The filter item, which should match the filterItemName and configurationName if the model is available */
private AlarmTreeItem filterItem;
private ColumnWrapper[] columns = ColumnWrapper.getNewWrappers();
@Override
public void init(IViewSite site, IMemento memento) throws PartInitException
{
this.memento = memento;
this.blinkingIcons = Preferences.isBlinkUnacknowledged();
restoreState(memento,site);
super.init(site);
}
@Override
public void dispose()
{
if (secondaryId.get() > 1)
{
secondaryId.decrementAndGet();
}
super.dispose();
}
@Override
public void createPartControl(final Composite parent)
{
this.parent = parent;
parent.setLayout(new FillLayout());
try
{
defaultModel = AlarmClientModel.getInstance();
defaultModel.addListener(modelListener);
if (filterItemPath != null)
{
model = AlarmClientModel.getInstance(getConfigNameFromPath(filterItemPath));
model.addListener(modelListener);
}
}
catch (final Throwable ex)
{ // Instead of actual GUI, create error message
final String error = ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage();
final String message = NLS.bind(org.csstudio.alarm.beast.ui.Messages.ServerErrorFmt, error);
// Add to log, also display in text widget
Logger.getLogger(Activator.ID).log(Level.SEVERE, "Cannot load alarm model", ex); //$NON-NLS-1$
parent.setLayout(new FillLayout());
new Text(parent, SWT.READ_ONLY | SWT.BORDER | SWT.MULTI).setText(message);
return;
}
// Arrange for model to be released
parent.addDisposeListener(new DisposeListener()
{
@Override
public void widgetDisposed(DisposeEvent e)
{
releaseModel(defaultModel);
releaseModel(model);
}
});
makeGUI();
createToolbar();
updateFilterItem();
}
private void restoreState(IMemento memento, IViewSite site)
{
if (memento == null)
{
this.combinedTables = Preferences.isCombinedAlarmTable();
this.filterType = FilterType.TREE;
this.columns = ColumnWrapper.fromSaveArray(Preferences.getColumns());
//set format for all tables except the main one
if (site.getSecondaryId() != null)
this.timeFormat = Preferences.getTimeFormat();
}
else
{
Boolean groupSet = memento.getBoolean(Preferences.ALARM_TABLE_COMBINED_TABLES);
this.combinedTables = groupSet == null ? Preferences.isCombinedAlarmTable() : groupSet;
String filterTypeSet = memento.getString(Preferences.ALARM_TABLE_FILTER_TYPE);
this.filterType = filterTypeSet == null ? FilterType.TREE : FilterType.valueOf(filterTypeSet.toUpperCase());
this.timeFormat = memento.getString(Preferences.ALARM_TABLE_TIME_FORMAT);
if (site.getSecondaryId() != null && this.timeFormat == null)
this.timeFormat = Preferences.getTimeFormat();
this.columns = ColumnWrapper.restoreColumns(memento.getChild(Preferences.ALARM_TABLE_COLUMN_SETTING));
String name = memento.getString(Preferences.ALARM_TABLE_FILTER_ITEM);
this.filterItemPath = name == null || name.isEmpty() ? null : name;
}
}
@Override
public void saveState(IMemento memento)
{
super.saveState(memento);
memento.putBoolean(Preferences.ALARM_TABLE_COMBINED_TABLES, combinedTables);
memento.putString(Preferences.ALARM_TABLE_FILTER_TYPE, filterType.name());
if (filterItem != null)
memento.putString(Preferences.ALARM_TABLE_FILTER_ITEM, filterItem.getPathName());
else if (filterItemPath != null)
memento.putString(Preferences.ALARM_TABLE_FILTER_ITEM, filterItemPath);
if (this.timeFormat != null)
memento.putString(Preferences.ALARM_TABLE_TIME_FORMAT, timeFormat);
IMemento columnsMemento = memento.createChild(Preferences.ALARM_TABLE_COLUMN_SETTING);
ColumnWrapper.saveColumns(columnsMemento, getUpdatedColumns());
if (gui != null)
{
ColumnInfo info = gui.getSortingColumn();
if (info != null)
memento.putString(Preferences.ALARM_TABLE_SORT_COLUMN, info.name());
memento.putBoolean(Preferences.ALARM_TABLE_SORT_UP, gui.isSortingUp());
}
}
private void createToolbar()
{
final IToolBarManager toolbar = getViewSite().getActionBars().getToolBarManager();
toolbar.removeAll();
if (defaultModel.isWriteAllowed())
{
maintenanceModeAction = new MaintenanceModeAction(defaultModel);
toolbar.add(maintenanceModeAction);
toolbar.add(new Separator());
AcknowledgeAction action = new AcknowledgeAction(true, gui.getActiveAlarmTable());
action.clearSelectionOnAcknowledgement(gui.getActiveAlarmTable());
toolbar.add(action);
action = new AcknowledgeAction(false, gui.getAcknowledgedAlarmTable());
action.clearSelectionOnAcknowledgement(gui.getAcknowledgedAlarmTable());
toolbar.add(action);
toolbar.add(new Separator());
}
for (FilterType f : FilterType.values())
toolbar.add(new FilterAction(this, f, this.filterType == f));
toolbar.add(new Separator());
final IMenuManager menu = getViewSite().getActionBars().getMenuManager();
menu.add(new NewTableAction(this));
menu.add(new Separator());
menu.add(new SeparateCombineTablesAction(this, true, combinedTables));
menu.add(new SeparateCombineTablesAction(this, false, !combinedTables));
menu.add(new Separator());
menu.add(new ColumnConfigureAction(this));
menu.add(new ResetColumnsAction(this));
menu.add(new Separator());
menu.add(new ShowFilterAction(this));
}
private void releaseModel(AlarmClientModel model) {
if (this.model != null)
{
this.model.removeListener(modelListener);
this.model.release();
this.model = null;
}
}
/**
* Set the filter item by its path. The path is transformed to an actual item, which is then applied as the filter
* item. If the item does not exist a null filter is applied.
*
* @see AlarmTableView#setFilterItem(AlarmTreeItem)
*
* @param path the path to filter on
* @throws Exception if the model for the given path could not be created
*/
public void setFilterItemPath(String path) throws Exception
{
this.filterItemPath = path;
if (filterItemPath == null || filterItemPath.isEmpty())
{
releaseModel(model);
setFilterType(FilterType.TREE);
}
else
{
String configName = getConfigNameFromPath(filterItemPath);
if (model == null || !model.getConfigurationName().equals(configName))
{
releaseModel(model);
this.model = AlarmClientModel.getInstance(configName);
this.model.addListener(modelListener);
}
setFilterType(FilterType.ITEM);
}
updateFilterItem();
}
/**
* @return the currently applied filter item
*/
public String getFilterItemPath()
{
return filterItemPath;
}
/**
* Updated the filter item according to the selected filter type and filter item path. The view title
* is also updated.
*/
private void updateFilterItem()
{
AlarmClientModel activeModel = null;
String name;
if (filterType == FilterType.TREE)
{
activeModel = defaultModel;
name = activeModel.getConfigurationName();
if (gui != null)
gui.setFilterItem(null, activeModel);
}
else
{
activeModel = model;
AlarmTreeRoot root = activeModel.getConfigTree().getRoot();
this.filterItem = root.getItemByPath(filterItemPath);
if (filterItem != null)
{
if (filterType == FilterType.ITEM)
name = filterItem.getName();
else
name = activeModel.getConfigurationName();
}
else
{
//filter path is set, but the item is null, because it
//either does not exist, or the model is not yet connected
int idx = filterItemPath.lastIndexOf('/');
name = idx < 0 ? filterItemPath : filterItemPath.substring(idx + 1);
}
if (gui != null)
gui.setFilterItem(filterType == FilterType.ITEM ? filterItem : null, activeModel);
}
if (maintenanceModeAction != null)
maintenanceModeAction.setModel(activeModel);
setPartName(NLS.bind(Messages.AlarmTablePartName, name));
setTitleToolTip(NLS.bind(Messages.AlarmTableTitleTT, name));
firePropertyChange(PROP_FILTER_ITEM);
}
/**
* @return the columns as they are currently visible and ordered in the table
*/
public ColumnWrapper[] getUpdatedColumns()
{
ColumnWrapper[] columns = ColumnWrapper.getCopy(this.columns);
if (gui != null)
gui.updateColumnOrder(columns);
return columns;
}
/**
* Set the columns for the table. The table will display the columns in the provided order and will show only those
* columns that have the visible flag set to true
*
* @param columns the columns to set on the table
*/
public void setColumns(ColumnWrapper[] columns)
{
this.columns = columns;
redoGUI();
}
private boolean makeGUI()
{
if (parent.isDisposed())
return false;
String s = memento == null ? null : memento.getString(Preferences.ALARM_TABLE_SORT_COLUMN);
ColumnInfo sorting = s == null ? ColumnInfo.PV : ColumnInfo.valueOf(s);
boolean sortUp = false;
if (memento != null) {
Boolean b = memento.getBoolean(Preferences.ALARM_TABLE_SORT_UP);
sortUp = b == null ? false : b;
}
if (gui != null)
{
sorting = gui.getSortingColumn();
sortUp = gui.isSortingUp();
gui.dispose();
}
gui = new GUI(parent, getSite(), defaultModel.isWriteAllowed(),
!combinedTables, columns, sorting, sortUp);
gui.setBlinking(blinkingIcons);
gui.setTimeFormat(timeFormat);
setUpDrop(gui.getActiveAlarmTable().getTable());
setUpDrop(gui.getAcknowledgedAlarmTable().getTable());
updateFilterItem();
return true;
}
private void setUpDrop(Control control)
{
if (control == null || control.getData(DND.DROP_TARGET_KEY) != null)
return;
new ControlSystemDropTarget(control, AlarmTreeItem.class, AlarmTreeItem[].class,
AlarmTreePV.class, AlarmTreePV[].class)
{
@Override
public void handleDrop(Object item)
{
try
{
if (item instanceof AlarmTreeItem[])
setFilterItemPath(((AlarmTreeItem[])item)[0].getPathName());
else if (item instanceof AlarmTreeItem || item instanceof AlarmTreePV)
setFilterItemPath(((AlarmTreeItem)item).getPathName());
else if (item instanceof AlarmTreePV[])
setFilterItemPath(((AlarmTreePV[])item)[0].getPathName());
}
catch (Exception e)
{
throw new IllegalArgumentException(e);
}
}
};
}
private void redoGUI()
{
if (gui != null)
{
parent.getDisplay().asyncExec(() ->
{
if (makeGUI())
parent.layout();
});
}
}
@Override
public void setFocus()
{
// NOP
}
/**
* Combine all alarms into a single table or group the alarms into two separate tables (by the acknowledge status).
*
* @param combinedTables true if the acknowledged and unacknowledged alarms should be displayed in a single table,
* or false if they should be displayed in separate tables
*/
public void setCombinedTables(boolean separated)
{
this.combinedTables = separated;
redoGUI();
}
/**
* Set the filter type for the table. The table will display alarms according to this filter. If the filter
* is {@link FilterType#TREE} all alarms from the root currently selected in the alarm tree; if the filter type
* is {@link FilterType#ROOT} all alarms from the root that is currently applied to this table (through filter item)
* will be displayed; if filter type is {@link FilterType#ITEM} only the alarms belonging to the filter item will
* be displayed.
*
* @param filterType the filter type to set
*/
public void setFilterType(FilterType filterType)
{
if (filterItemPath == null && (filterType == FilterType.ROOT || filterType == FilterType.ITEM)) {
throw new IllegalStateException("Cannot apply filter type " + filterType //$NON-NLS-1$
+ " if no filter item is defined."); //$NON-NLS-1$
}
this.filterType = filterType;
updateFilterItem();
firePropertyChange(PROP_FILTER);
}
/**
* @return the filter type currently selected for this table
*/
public FilterType getFilterType()
{
return this.filterType;
}
/**
* Enables or disables blinking of icons of the unacknowledged alarms.
*
* @param blinking true if the icons should be blinking or false otherwise
*/
public void setBlinkingIcons(boolean blinking)
{
this.blinkingIcons = blinking;
if (gui != null)
gui.setBlinking(blinking);
}
/**
* @return the alarm client model used by this table
*/
public AlarmClientModel getModel()
{
return filterType == FilterType.TREE ? defaultModel : model;
}
/**
* Sets the time format used for formatting the value in the time column. Format should be in the form acceptable by
* the {@link SimpleDateFormat}.
*
* @param format the format
*/
public void setTimeFormat(String format)
{
if (format != null && format.isEmpty())
format = null;
this.timeFormat = format;
if (gui != null)
gui.setTimeFormat(format);
}
/**
* @return the currently used time format or null if default
*/
public String getTimeFormat()
{
return timeFormat;
}
/**
* Parses the configuration name from the given path.
*
* @param path the path to parse
* @return configuration name
*/
public static String getConfigNameFromPath(String path) {
String name = path;
if (name.charAt(0) == '/')
name = name.substring(1);
return name.substring(0, name.indexOf('/'));
}
}
|
package us.myles.ViaVersion;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.bukkit.scheduler.BukkitRunnable;
import us.myles.ViaVersion.api.data.UserConnection;
import us.myles.ViaVersion.protocols.base.ProtocolInfo;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.Protocol1_9TO1_8;
import us.myles.ViaVersion.protocols.protocol1_9to1_8.storage.MovementTracker;
import us.myles.ViaVersion.util.PipelineUtil;
import us.myles.ViaVersion.util.ReflectionUtil;
import java.util.Map;
import java.util.UUID;
public class ViaIdleThread extends BukkitRunnable {
private final Map<UUID, UserConnection> portedPlayers;
private final Object idlePacket;
public ViaIdleThread(Map<UUID, UserConnection> portedPlayers) {
this.portedPlayers = portedPlayers;
try {
Class<?> idlePacketClass = ReflectionUtil.nms("PacketPlayInFlying");
idlePacket = idlePacketClass.newInstance();
} catch (InstantiationException | IllegalArgumentException | IllegalAccessException | ClassNotFoundException e) {
throw new RuntimeException("Couldn't find/make player idle packet, help!", e);
}
}
@Override
public void run() {
for (UserConnection info : portedPlayers.values()) {
if (info.get(ProtocolInfo.class).getPipeline().contains(Protocol1_9TO1_8.class)) {
long nextIdleUpdate = info.get(MovementTracker.class).getNextIdlePacket();
if (nextIdleUpdate <= System.currentTimeMillis()) {
ChannelHandlerContext context = PipelineUtil.getContextBefore("decoder", info.getChannel().pipeline());
if(info.getChannel().isOpen()) {
if (context != null) {
context.fireChannelRead(idlePacket);
info.get(MovementTracker.class).incrementIdlePacket();
}
}
}
}
}
}
}
|
package org.eclipse.smarthome.core.autoupdate.internal;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArraySet;
import org.eclipse.smarthome.core.autoupdate.AutoUpdateBindingConfigProvider;
import org.eclipse.smarthome.core.events.EventPublisher;
import org.eclipse.smarthome.core.items.GenericItem;
import org.eclipse.smarthome.core.items.ItemNotFoundException;
import org.eclipse.smarthome.core.items.ItemRegistry;
import org.eclipse.smarthome.core.items.events.AbstractItemEventSubscriber;
import org.eclipse.smarthome.core.items.events.ItemCommandEvent;
import org.eclipse.smarthome.core.items.events.ItemEventFactory;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.State;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AutoUpdateBinding extends AbstractItemEventSubscriber {
private final Logger logger = LoggerFactory.getLogger(AutoUpdateBinding.class);
protected ItemRegistry itemRegistry;
/** to keep track of all binding config providers */
protected Collection<AutoUpdateBindingConfigProvider> providers = new CopyOnWriteArraySet<>();
protected EventPublisher eventPublisher = null;
public void addBindingConfigProvider(AutoUpdateBindingConfigProvider provider) {
providers.add(provider);
}
public void removeBindingConfigProvider(AutoUpdateBindingConfigProvider provider) {
providers.remove(provider);
}
public void setEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public void unsetEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = null;
}
public void setItemRegistry(ItemRegistry itemRegistry) {
this.itemRegistry = itemRegistry;
}
public void unsetItemRegistry(ItemRegistry itemRegistry) {
this.itemRegistry = null;
}
/**
* <p>
* Iterates through all registered {@link AutoUpdateBindingConfigProvider}s and checks whether an autoupdate
* configuration is available for <code>itemName</code>.
* </p>
*
* <p>
* If there are more then one {@link AutoUpdateBindingConfigProvider}s providing a configuration the results are
* combined by a logical <em>OR</em>. If no configuration is provided at all the autoupdate defaults to
* <code>true</code> and an update is posted for the corresponding {@link State}.
* </p>
*
* @param itemName the item for which to find an autoupdate configuration
* @param command the command being received and posted as {@link State} update if <code>command</code> is instance
* of {@link State} as well.
*/
@Override
protected void receiveCommand(ItemCommandEvent commandEvent) {
Boolean autoUpdate = null;
String itemName = commandEvent.getItemName();
Command command = commandEvent.getItemCommand();
for (AutoUpdateBindingConfigProvider provider : providers) {
Boolean au = provider.autoUpdate(itemName);
if (au != null) {
autoUpdate = au;
if (Boolean.TRUE.equals(autoUpdate)) {
break;
}
}
}
// we didn't find any autoupdate configuration, so apply the default now
if (autoUpdate == null) {
autoUpdate = Boolean.TRUE;
}
if (autoUpdate && command instanceof State) {
postUpdate(itemName, (State) command);
} else {
logger.trace("Won't update item '{}' as it is not configured to update its state automatically.", itemName);
}
}
private void postUpdate(String itemName, State newState) {
if (itemRegistry != null) {
try {
GenericItem item = (GenericItem) itemRegistry.getItem(itemName);
boolean isAccepted = false;
if (item.getAcceptedDataTypes().contains(newState.getClass())) {
isAccepted = true;
} else {
// Look for class hierarchy
for (Class<? extends State> state : item.getAcceptedDataTypes()) {
try {
if (!state.isEnum()
&& state.newInstance().getClass().isAssignableFrom(newState.getClass())) {
isAccepted = true;
break;
}
} catch (InstantiationException e) {
logger.warn("InstantiationException on ", e.getMessage()); // Should never happen
} catch (IllegalAccessException e) {
logger.warn("IllegalAccessException on ", e.getMessage()); // Should never happen
}
}
}
if (isAccepted) {
eventPublisher.post(ItemEventFactory.createStateEvent(itemName, newState,
"org.eclipse.smarthome.core.autoupdate"));
} else {
logger.debug("Received update of a not accepted type (" + newState.getClass().getSimpleName()
+ ") for item " + itemName);
}
} catch (ItemNotFoundException e) {
logger.debug("Received update for non-existing item: {}", e.getMessage());
}
}
}
}
|
package vg.civcraft.mc.civmodcore;
import java.util.List;
import java.util.logging.Level;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
import vg.civcraft.mc.civmodcore.command.CommandHandler;
import vg.civcraft.mc.civmodcore.command.StandaloneCommandHandler;
import vg.civcraft.mc.civmodcore.playersettings.PlayerSettingAPI;
public abstract class ACivMod extends JavaPlugin {
@Deprecated
protected CommandHandler handle;
protected StandaloneCommandHandler newCommandHandler;
private static boolean initializedAPIs = false;
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (handle == null) {
return newCommandHandler.executeCommand(sender, command, args);
} else {
return handle.execute(sender, command, args);
}
}
@Override
public void onEnable() {
this.newCommandHandler = new StandaloneCommandHandler(this);
}
@Override
public void onDisable() {
PlayerSettingAPI.saveAll();
}
protected void registerListener(Listener listener) {
if (listener == null) {
throw new IllegalArgumentException("Cannot register a listener if it's null, you dummy");
}
getServer().getPluginManager().registerEvents(listener, this);
}
public void saveDefaultResource(String path) {
if (getResource(path) == null) {
saveResource(path, false);
}
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String alias, String[] args) {
if (handle == null) {
return newCommandHandler.tabCompleteCommand(sender, cmd, args);
} else {
return handle.complete(sender, cmd, args);
}
}
public CommandHandler getCommandHandler() {
return handle;
}
protected void setCommandHandler(CommandHandler handle) {
this.handle = handle;
}
/**
* Simple SEVERE level logging.
*/
public void severe(String message) {
getLogger().log(Level.SEVERE, message);
}
/**
* Simple SEVERE level logging with Throwable record.
*/
public void severe(String message, Throwable error) {
getLogger().log(Level.SEVERE, message, error);
}
/**
* Simple WARNING level logging.
*/
public void warning(String message) {
getLogger().log(Level.WARNING, message);
}
/**
* Simple WARNING level logging with Throwable record.
*/
public void warning(String message, Throwable error) {
getLogger().log(Level.WARNING, message, error);
}
/**
* Simple WARNING level logging with ellipsis notation shortcut for defered
* injection argument array.
*/
public void warning(String message, Object... vars) {
getLogger().log(Level.WARNING, message, vars);
}
/**
* Simple INFO level logging
*/
public void info(String message) {
getLogger().log(Level.INFO, message);
}
/**
* Simple INFO level logging with ellipsis notation shortcut for defered
* injection argument array.
*/
public void info(String message, Object... vars) {
getLogger().log(Level.INFO, message, vars);
}
/**
* Live activatable debug message (using {@link Config#DebugLog} to decide) at
* INFO level.
*
* Skipped if DebugLog is false.
*/
public void debug(String message) {
if (getConfig().getBoolean("debug", false)) {
getLogger().log(Level.INFO, message);
}
}
/**
* Live activatable debug message (using {@link Config#DebugLog} to decide) at
* INFO level with ellipsis notation shorcut for defered injection argument
* array.
*
* Skipped if DebugLog is false.
*/
public void debug(String message, Object... vars) {
if (getConfig().getBoolean("debug", false)) {
getLogger().log(Level.INFO, message, vars);
}
}
}
|
package xpress.retrieve;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import xpress.Mood;
import xpress.TagCloud;
import xpress.storage.Filter;
import xpress.storage.Repository;
import xpress.storage.Utils;
import xpress.storage.entity.VoteEntity;
public class TagCloudRetriever {
private final Repository repo;
public TagCloudRetriever(Repository repo) {
this.repo = repo;
}
public TagCloud retrieveTagCloudsFor(Mood mood) {
Filter filter = new Filter();
filter.setMood(mood);
List<VoteEntity> voteEntities = repo.getVotes(filter);
return buildTagCloudBasedOn(voteEntities);
}
private TagCloud buildTagCloudBasedOn(List<VoteEntity> voteEntities) {
Map<String, Integer> map = new LinkedHashMap<>();
if (voteEntities.isEmpty()) {
return new TagCloud(1, map);
}
//Also keep track of oldest & most recent time used for voteEntities, regardless of tag names etc..
long oldestTimeOfAll = voteEntities.get(0).getTime();
long mostRecentTimeOfAll = voteEntities.get(0).getTime();
/**
* This map will collaps all voteEntities by tagName. For each tag, it will holds the sum of voteEntities, and the most recent time this tag was updated.
*/
Map<String, VoteSummary> collapsedStats = new HashMap<String, VoteSummary>();
for (VoteEntity voteEntity : voteEntities) {
long voteTime = voteEntity.getTime();
//if x is less than known oldest time..
if (voteTime < oldestTimeOfAll) {
oldestTimeOfAll = voteTime;
}
//if the most recent time is actually older than x..
if (mostRecentTimeOfAll < voteTime) {
mostRecentTimeOfAll = voteTime;
}
//sum up the voteEntities for each tag
String tagName = voteEntity.getTag().trim();
if (tagName != null) {
VoteSummary voteSummary = collapsedStats.get(tagName);
if (voteSummary == null) {
voteSummary = new VoteSummary(tagName, 1, voteEntity.getTime());
} else {
voteSummary = new VoteSummary(tagName, voteSummary.getNumVotes() + 1, getMostRecentTimeForThisTag(voteEntity.getTime(),
voteSummary.getMostRecentTime()));
}
collapsedStats.put(tagName, voteSummary);
}
}
// System.out.println("Oldest of them all:" + Utils.prettyPrintDate(oldestTimeOfAll));
// System.out.println("Youngest of them all:" + Utils.prettyPrintDate(mostRecentTimeOfAll));
//update the map so that it holds the 'weight' of each tag
for (Entry<String, VoteSummary> entry : collapsedStats.entrySet()) {
String tagName = entry.getKey();
VoteSummary voteSummary = entry.getValue();
//compute weights, 70% by numVotes and 30% by time
int weigthByVotes = (int) (Math.ceil(0.9 * voteSummary.getNumVotes()));
int weightByTime = (int) (Math.ceil(0.1 * computeWeightByTime(oldestTimeOfAll, mostRecentTimeOfAll, voteSummary
.getMostRecentTime())));
map.put(tagName, weigthByVotes + weightByTime);
}
return new TagCloud(1, map);
}
private long getMostRecentTimeForThisTag(long a, long b) {
return Math.max(a, b);
}
private int computeWeightByTime(long oldestTime, long mostRecentTime, long x) {
//try to give percentage of how close x is to d2. if it's up to 100 % then it's 100 weight..
if (x == oldestTime)
return 0;
if (x == mostRecentTime)
return 100;
long totalLenght = mostRecentTime - oldestTime;
long lengthOfX = x - oldestTime;
int percent = (int) Math.ceil(lengthOfX * 100 / totalLenght);
// System.out.println("Computed score for " + Utils.prettyPrintDate(x) + " vs interval [" + Utils.prettyPrintDate(oldestTime) + ","
// + Utils.prettyPrintDate(mostRecentTime) + "] was: " + percent);
return (int) percent; // now safe to cast it since it < 100
}
/**
*
*
* @author Tiberiu Rogojan
*
*/
private class VoteSummary {
private final String tagName;
private final int numVotes;
private final long mostRecentTime;
public VoteSummary(String tagName, int numVotes, long mostRecentTime) {
this.tagName = tagName;
this.numVotes = numVotes;
this.mostRecentTime = mostRecentTime;
}
public String getTagName() {
return tagName;
}
public int getNumVotes() {
return numVotes;
}
public long getMostRecentTime() {
return mostRecentTime;
}
@Override
public String toString() {
return "VoteSummary [tagName=" + tagName + ", numVotes=" + numVotes + ", mostRecentTime="
+ Utils.prettyPrintDate(mostRecentTime) + "]";
}
}
}
|
package com.qualcomm.ftcrobotcontroller.opmodes;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
public class TeleOp extends OpMode {
// TODO Initiate all variables
DcMotor motor_left; //Forward Left
DcMotor motor_right;
Float driver_gamepad_x;
Float driver_gamepad_y;
@Override
public void init() {
// TODO Placeholder for hardware mapping, motor names may change
motor_left = hardwareMap.dcMotor.get("motor_1");
motor_right = hardwareMap.dcMotor.get("motor_2");
//Added this for the lads
driver_gamepad_x = gamepad1.left_stick_x;
driver_gamepad_y = gamepad1.left_stick_y;
}
@Override
public void loop() {
// TODO Example method/action of the motor, in this case applying power
if(driver_gamepad_y > 100)
{
//For the method .setPower() pass a value from -1 to 1 (inc. 0)
motor_left.setPower(1);
motor_right.setPower(1);
}
else if (driver_gamepad_y < -100)
{
motor_left.setPower(-1);
motor_right.setPower(-1);
}
else if (driver_gamepad_x > 100)
{
motor_left.setPower(1);
motor_right.setPower(-1);
}
else if (driver_gamepad_x < -100)
{
motor_left.setPower(-1);
motor_right.setPower(1);
}
else
{
motor_left.setPower(0);
motor_right.setPower(0);
}
}
}
|
// Begin CVS Header
// $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/bindings/java/unittests/Test_RunScan.java,v $
// $Revision: 1.5 $
// $Name: $
// End CVS Header
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// Properties, Inc. and EML Research, gGmbH.
package org.COPASI.unittests;
import java.lang.Math;
import java.util.HashMap;
import java.util.Set;
import java.util.Vector;
import java.util.Iterator;
import org.COPASI.*;
import junit.framework.*;
public class Test_RunScan extends TestCase
{
CModel mModel;
public Test_RunScan(String name)
{
super(name);
}
public CModel createModel()
{
try
{
CCopasiDataModel.getGlobal().newModel();
}
catch(Exception e)
{
return null;
}
CModel model=CCopasiDataModel.getGlobal().getModel();
model.setVolumeUnit(CModel.fl);
model.setTimeUnit(CModel.s);
model.setQuantityUnit(CModel.fMol);
CModelValue fixedModelValue=model.createModelValue("R",2.0);
CModelValue variableModelValue=model.createModelValue("K");
variableModelValue.setStatus(CModelEntity.ODE);
String s=fixedModelValue.getObject(new CCopasiObjectName("Reference=Value")).getCN().getString();
s="<"+s+">^2";
variableModelValue.setExpression(s);
variableModelValue.setInitialValue(0.0);
model.compileIfNecessary();
ObjectStdVector changedObjects=new ObjectStdVector();
changedObjects.add(fixedModelValue.getObject(new CCopasiObjectName("Reference=InitialValue")));
changedObjects.add(variableModelValue.getObject(new CCopasiObjectName("Reference=InitialValue")));
model.updateInitialValues(changedObjects);
return model;
}
public void setUp()
{
this.mModel=createModel();
}
public static CScanTask runScan(int subTask,Vector<CCopasiParameterGroup> scanItems,boolean adjustInitialValues)
{
CScanTask scanTask=(CScanTask)CCopasiDataModel.getGlobal().addTask(CCopasiTask.scan);
if(scanTask==null) return null;
CScanProblem scanProblem=(CScanProblem)scanTask.getProblem();
scanProblem.setSubtask(subTask);
scanProblem.setAdjustInitialConditions(adjustInitialValues);
if(scanProblem==null) return null;
CCopasiParameterGroup problemScanItems=scanProblem.getGroup("ScanItems");
if(problemScanItems==null) return null;
for(Iterator<CCopasiParameterGroup> it=scanItems.iterator();it.hasNext();)
{
CCopasiParameterGroup scanItem=(CCopasiParameterGroup)it.next();
problemScanItems.addParameter(scanItem);
}
boolean result=false;
try
{
if(scanTask.initialize(CCopasiTask.NO_OUTPUT,null)!=false)
{
result=scanTask.process(true);
}
}
catch(Exception e)
{
System.err.println("ERROR: "+e.getMessage());
}
if(!result)
{
return null;
}
return scanTask;
}
public void test_Scan_Repeat()
{
// set up the time course task
CTrajectoryTask task=null;
for(int x=0;x < CCopasiDataModel.getGlobal().getTaskList().size();x++)
{
if(CCopasiDataModel.getGlobal().getTask(x).getType()==CCopasiTask.timeCourse)
{
task=(CTrajectoryTask)CCopasiDataModel.getGlobal().getTask(x);
}
}
assertFalse(task==null);
task.setMethodType(CCopasiMethod.deterministic);
CCopasiProblem problem=task.getProblem();
assertFalse(problem==null);
CCopasiParameter parameter=problem.getParameter("StepSize");
assertFalse(parameter==null);
parameter.setDblValue(0.001);
parameter=problem.getParameter("Duration");
assertFalse(parameter==null);
parameter.setDblValue(10.0);
// we don't need to set method parameters
// we just use the default
//CCopasiMethod method=task.getMethod();
//assertFalse(method==null);
// create a report
CReportDefinitionVector reportDefs=CCopasiDataModel.getGlobal().getReportDefinitionList();
assertFalse(reportDefs==null);
CReportDefinition repDef=reportDefs.createReportDefinition("htmlConc","value table in HTML format");
repDef.setIsTable(false);
assertFalse(repDef==null);
CCopasiStaticString htmlHeader=new CCopasiStaticString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-
CCopasiStaticString htmlFooter=new CCopasiStaticString("</table>\n</body>\n</html>\n");
ReportItemVector header=repDef.getHeaderAddr();
assertFalse(header==null);
header.add(new CRegisteredObjectName(htmlHeader.getCN().getString()));
ReportItemVector footer=repDef.getFooterAddr();
assertFalse(footer==null);
footer.add(new CRegisteredObjectName(htmlFooter.getCN().getString()));
ReportItemVector body=repDef.getBodyAddr();
assertFalse(body==null);
CModel model=CCopasiDataModel.getGlobal().getModel();
assertFalse(model==null);
CCopasiObject timeObject=model.getObject(new CCopasiObjectName("Reference=Time"));
assertFalse(timeObject==null);
body.add(new CRegisteredObjectName(new CCopasiStaticString("<tr>\n<td>").getCN().getString()));
body.add(new CRegisteredObjectName(timeObject.getCN().getString()));
body.add(new CRegisteredObjectName(new CCopasiStaticString("</td>\n").getCN().getString()));
long i,iMax=model.getNumModelValues();
for(i=0;i<iMax;++i)
{
body.add(new CRegisteredObjectName(new CCopasiStaticString("<td>").getCN().getString()));
CModelValue mv=model.getModelValue(i);
assertFalse(mv==null);
CCopasiObject valueObject=mv.getObject(new CCopasiObjectName("Reference=Value"));
assertFalse(valueObject==null);
body.add(new CRegisteredObjectName(valueObject.getCN().getString()));
body.add(new CRegisteredObjectName(new CCopasiStaticString("</td>\n").getCN().getString()));
}
body.add(new CRegisteredObjectName(new CCopasiStaticString("</tr>\n").getCN().getString()));
repDef.setTaskType(CCopasiTask.timeCourse);
CReport report=task.getReport();
assertFalse(report==null);
report.setReportDefinition(repDef);
report.setAppend(false);
report.setTarget("table.xhtml");
//CCopasiDataModel.getGlobal().saveModel("testModel.cps",true);
try
{
task.process(true);
}
catch(Exception e)
{
assertFalse(true);
}
report.setReportDefinition(null);
report.setTarget("");
// store the result for R and K and set R and K
// back to their initial values
CModelValue mv=CCopasiDataModel.getGlobal().getModel().getModelValue("R");
assertFalse(mv==null);
double valueR=mv.getValue();
mv=CCopasiDataModel.getGlobal().getModel().getModelValue("K");
assertFalse(mv==null);
double valueK=mv.getValue();
CCopasiDataModel.getGlobal().getModel().applyInitialValues();
// now we set the length of the time course to 1/10th
// and do 10 repetitions and let the scan use the current values
// instead of the initial values
// then we should end up with the same result for R and K
parameter=problem.getParameter("Duration");
assertFalse(parameter==null);
parameter.setDblValue(1.0);
Vector<CCopasiParameterGroup> scanItems=new Vector<CCopasiParameterGroup>();
boolean adjustInitialConditions=true;
CCopasiParameterGroup parameterGroup=new CCopasiParameterGroup("scanItems");
parameterGroup.addParameter("Number of steps", CCopasiParameter.UINT);
parameterGroup.getParameter("Number of steps").setUIntValue(10);
parameterGroup.addParameter("Type", CCopasiParameter.UINT);
parameterGroup.getParameter("Type").setUIntValue(CScanProblem.SCAN_REPEAT);
parameterGroup.addParameter("Object", CCopasiParameter.CN);
parameterGroup.getParameter("Object").setStringValue("");
scanItems.add(parameterGroup);
CScanTask optTask=runScan(CCopasiTask.timeCourse,scanItems,adjustInitialConditions);
assertFalse(optTask==null);
mv=CCopasiDataModel.getGlobal().getModel().getModelValue("R");
assertFalse(mv==null);
assertTrue((mv.getValue()-valueR)/valueR < 1e-6);
mv=CCopasiDataModel.getGlobal().getModel().getModelValue("K");
assertFalse(mv==null);
assertTrue((mv.getValue()-valueK)/valueK < 1e-6);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(Test_RunScan.class);
}
}
|
package ru.stqa.pft.addressbook.tests;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ContactData;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
public class ContactPhoneTests extends TestBase {
@BeforeMethod
public void ensurePreconditions() {
app.goTo().homePage();
if (app.contact().all().size() == 0) {
app.contact().create
(new ContactData().withFirstname("Ivan").withLastname("Ivanov")
.withHomePhone("14").withMobile("15").withWorkPhone("16")
.withEmail("Ivanov@yandex.ru").withEmail2("Ivanov2@yandex.ru")
.withEmail3("Ivanov3@yandex.ru").withAddress("Samara"));
}
}
@Test
public void testContactPhones() {
app.goTo().homePage();
ContactData contact = app.contact().all().iterator().next();
ContactData contactInfoFromEditForm = app.contact().infoFromEditForm(contact);
assertThat(contact.getAllPhones(), equalTo(mergePhones(contactInfoFromEditForm)));
}
@Test
public void testContactEmails() {
app.goTo().homePage();
ContactData contact = app.contact().all().iterator().next();
ContactData contactInfoFromEditForm = app.contact().infoFromEditForm(contact);
assertThat(contact.getAllEmails(), equalTo(mergeEmails(contactInfoFromEditForm)));
}
@Test
public void testContactAddress() {
app.goTo().homePage();
ContactData contact = app.contact().all().iterator().next();
ContactData contactInfoFromEditForm = app.contact().infoFromEditForm(contact);
assertThat(contact.getAddress(), equalTo(contactInfoFromEditForm.getAddress()));
}
private String mergeEmails(ContactData contact) {
return Arrays.asList(contact.getEmail(), contact.getEmail2(), contact.getEmail3())
.stream().filter((s) -> !s.equals(""))
.collect(Collectors.joining("\n"));
}
private String mergePhones(ContactData contact) {
return Arrays.asList(contact.getHomePhone(), contact.getMobile(), contact.getWorkPhone())
.stream().filter((s) -> !s.equals(""))
.map(ContactPhoneTests::cleaned)
.collect(Collectors.joining("\n"));
}
public static String cleaned(String phone) {
return phone.replaceAll("\\s", "").replaceAll("[-()]]", "");
}
}
|
package ru.stqa.sch.addressbook.tests;
import org.testng.annotations.Test;
import ru.stqa.sch.addressbook.model.ContactData;
import ru.stqa.sch.addressbook.model.GroupData;
public class ModificationTests extends TestBase{
@Test
public void testGroupModification() {
app.getNavigationHelper().gotoGroupPage();
app.getGroupHelper().checkGroup(new GroupData("test1", null, null));
app.getGroupHelper().selectGroup();
app.getGroupHelper().initGroupModification();
app.getGroupHelper().fillGroupForm(new GroupData("test1", "header2", "footer2"));
app.getGroupHelper().submitGroupModification();
app.getGroupHelper().returnToGroupPage();
}
@Test
public void testContactModification() {
app.getGroupHelper().checkGroup(new GroupData("test1", null, null));
app.getContactHelper().checkContact(new ContactData("firstName2", "lastName2", "address2",
"123123", "test2@test.ru", "test1"), true);
app.getNavigationHelper().gotoHomePage();
app.getContactHelper().selectContact();
app.getContactHelper().initContactModification();
app.getContactHelper().fillContactForm(new ContactData("firstName3", "lastName3", "address3", "234234",
"test3@test.ru", null), false);
app.getContactHelper().submitContactModification();
app.getNavigationHelper().gotoHomePage();
}
}
|
package orm;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class DatasourceFactory {
private static final Logger logger = LogManager.getLogger(DatasourceFactory.class);
private static DataSource DATA_SOURCE;
private static ThreadLocal<Connection> CONNECTION_THREAD_LOCAL = new ThreadLocal<>();
// static {
// newDataSource(
// "jdbc:mysql://localhost:3306",
// "root", "root"
public static DataSource getMySQLDataSource() {
return DATA_SOURCE;
}
public static void newDataSource(String url, String user, String pwd) {
MysqlDataSource mysqlDS = new MysqlDataSource();
mysqlDS.setURL(url);
mysqlDS.setUser(user);
mysqlDS.setPassword(pwd);
try {
mysqlDS.setLoginTimeout(5);
mysqlDS.setResultSetSizeThreshold(1000);
} catch (SQLException e) {
logger.catching(e);
}
DATA_SOURCE = mysqlDS;
}
public static Connection getConnection() {
Connection connection = CONNECTION_THREAD_LOCAL.get();
try {
if (null == connection || connection.isClosed()) {
connection = getMySQLDataSource().getConnection();
connection.setTransactionIsolation(Connection.TRANSACTION_NONE);
}
} catch (SQLException e) {
logger.catching(e);
}
CONNECTION_THREAD_LOCAL.set(connection);
return connection;
}
public static void closeConnection(Connection conn) {
if (null == conn) {
return;
}
try {
if (conn.getTransactionIsolation() != Connection.TRANSACTION_NONE) {
return;
}
conn.close();
} catch (SQLException e) {
logger.catching(e);
}
}
public static void begin(int level) {
Connection connection = getConnection();
try {
connection.setTransactionIsolation(level);
} catch (SQLException e) {
logger.catching(e);
}
}
public static void commit() {
Connection connection = getConnection();
try {
connection.commit();
} catch (SQLException e1) {
logger.catching(e1);
try {
connection.rollback();
} catch (SQLException e2) {
logger.catching(e2);
}
} finally {
try {
connection.close();
} catch (SQLException e3) {
logger.catching(e3);
}
}
}
}
|
package com.cloud.test;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import com.cloud.utils.component.ComponentLocator;
import com.cloud.utils.db.DB;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.net.NetUtils;
public class PodZoneConfig {
public static void main(String[] args) {
PodZoneConfig config = ComponentLocator.inject(PodZoneConfig.class);
//config.run(args);
System.exit(0);
}
public void savePod(boolean printOutput, long id, String name, long dcId, String gateway, String cidr, int vlanStart, int vlanEnd) {
// Check that the cidr was valid
if (!IPRangeConfig.validCIDR(cidr)) printError("Please enter a valid CIDR for pod: " + name);
// Get the individual cidrAddress and cidrSize values
String[] cidrPair = cidr.split("\\/");
String cidrAddress = cidrPair[0];
String cidrSize = cidrPair[1];
String sql = null;
if (id != -1) sql = "INSERT INTO `cloud`.`host_pod_ref` (id, name, data_center_id, gateway, cidr_address, cidr_size) " + "VALUES ('" + id + "','" + name + "','" + dcId + "','" + gateway + "','" + cidrAddress + "','" + cidrSize + "')";
else sql = "INSERT INTO `cloud`.`host_pod_ref` (name, data_center_id, gateway, cidr_address, cidr_size) " + "VALUES ('" + name + "','" + dcId + "','" + gateway + "','" + cidrAddress + "','" + cidrSize + "')";
DatabaseConfig.saveSQL(sql, "Failed to save pod due to exception. Please contact Cloud Support.");
if (printOutput) System.out.println("Successfuly saved pod.");
}
public void checkAllPodCidrSubnets() {
Vector<Long> allZoneIDs = getAllZoneIDs();
for (Long dcId : allZoneIDs) {
HashMap<Long, Vector<Object>> currentPodCidrSubnets = getCurrentPodCidrSubnets(dcId.longValue());
String result = checkPodCidrSubnets(dcId.longValue(), currentPodCidrSubnets);
if (!result.equals("success")) printError(result);
}
}
private String checkPodCidrSubnets(long dcId, HashMap<Long, Vector<Object>> currentPodCidrSubnets) {
// DataCenterDao _dcDao = null;
// final ComponentLocator locator = ComponentLocator.getLocator("management-server");
// _dcDao = locator.getDao(DataCenterDao.class);
// For each pod, return an error if any of the following is true:
// 1. The pod's CIDR subnet conflicts with the guest network subnet
// 2. The pod's CIDR subnet conflicts with the CIDR subnet of any other pod
String zoneName = PodZoneConfig.getZoneName(dcId);
//get the guest network cidr and guest netmask from the zone
// DataCenterVO dcVo = _dcDao.findById(dcId);
String guestNetworkCidr = IPRangeConfig.getGuestNetworkCidr(dcId);
if (guestNetworkCidr == null || guestNetworkCidr.isEmpty()) return "Please specify a valid guest cidr";
String[] cidrTuple = guestNetworkCidr.split("\\/");
String guestIpNetwork = NetUtils.getIpRangeStartIpFromCidr(cidrTuple[0], Long.parseLong(cidrTuple[1]));
long guestCidrSize = Long.parseLong(cidrTuple[1]);
// Iterate through all pods in this zone
for (Long podId : currentPodCidrSubnets.keySet()) {
String podName;
if (podId.longValue() == -1) podName = "newPod";
else podName = PodZoneConfig.getPodName(podId.longValue(), dcId);
Vector<Object> cidrPair = currentPodCidrSubnets.get(podId);
String cidrAddress = (String) cidrPair.get(0);
long cidrSize = ((Long) cidrPair.get(1)).longValue();
long cidrSizeToUse = -1;
if (cidrSize < guestCidrSize) cidrSizeToUse = cidrSize;
else cidrSizeToUse = guestCidrSize;
String cidrSubnet = NetUtils.getCidrSubNet(cidrAddress, cidrSizeToUse);
String guestSubnet = NetUtils.getCidrSubNet(guestIpNetwork, cidrSizeToUse);
// Check that cidrSubnet does not equal guestSubnet
if (cidrSubnet.equals(guestSubnet)) {
if (podName.equals("newPod")) {
return "The subnet of the pod you are adding conflicts with the subnet of the Guest IP Network. Please specify a different CIDR.";
} else {
return "Warning: The subnet of pod " + podName + " in zone " + zoneName + " conflicts with the subnet of the Guest IP Network. Please change either the pod's CIDR or the Guest IP Network's subnet, and re-run install-vmops-management.";
}
}
// Iterate through the rest of the pods
for (Long otherPodId : currentPodCidrSubnets.keySet()) {
if (podId.equals(otherPodId)) continue;
// Check that cidrSubnet does not equal otherCidrSubnet
Vector<Object> otherCidrPair = currentPodCidrSubnets.get(otherPodId);
String otherCidrAddress = (String) otherCidrPair.get(0);
long otherCidrSize = ((Long) otherCidrPair.get(1)).longValue();
if (cidrSize < otherCidrSize) cidrSizeToUse = cidrSize;
else cidrSizeToUse = otherCidrSize;
cidrSubnet = NetUtils.getCidrSubNet(cidrAddress, cidrSizeToUse);
String otherCidrSubnet = NetUtils.getCidrSubNet(otherCidrAddress, cidrSizeToUse);
if (cidrSubnet.equals(otherCidrSubnet)) {
String otherPodName = PodZoneConfig.getPodName(otherPodId.longValue(), dcId);
if (podName.equals("newPod")) {
return "The subnet of the pod you are adding conflicts with the subnet of pod " + otherPodName + " in zone " + zoneName + ". Please specify a different CIDR.";
} else {
return "Warning: The pods " + podName + " and " + otherPodName + " in zone " + zoneName + " have conflicting CIDR subnets. Please change the CIDR of one of these pods.";
}
}
}
}
return "success";
}
@DB
protected HashMap<Long, Vector<Object>> getCurrentPodCidrSubnets(long dcId) {
HashMap<Long, Vector<Object>> currentPodCidrSubnets = new HashMap<Long, Vector<Object>>();
String selectSql = "SELECT id, cidr_address, cidr_size FROM host_pod_ref WHERE data_center_id=" + dcId;
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Long podId = rs.getLong("id");
String cidrAddress = rs.getString("cidr_address");
long cidrSize = rs.getLong("cidr_size");
Vector<Object> cidrPair = new Vector<Object>();
cidrPair.add(0, cidrAddress);
cidrPair.add(1, new Long(cidrSize));
currentPodCidrSubnets.put(podId, cidrPair);
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
printError("There was an issue with reading currently saved pod CIDR subnets. Please contact Cloud Support.");
return null;
}
return currentPodCidrSubnets;
}
public void deletePod(String name, long dcId) {
String sql = "DELETE FROM `cloud`.`host_pod_ref` WHERE name=\"" + name + "\" AND data_center_id=\"" + dcId + "\"";
DatabaseConfig.saveSQL(sql, "Failed to delete pod due to exception. Please contact Cloud Support.");
}
public long getVlanDbId(String zone, String vlanId) {
long zoneId = getZoneId(zone);
return DatabaseConfig.getDatabaseValueLong("SELECT * FROM `cloud`.`vlan` WHERE data_center_id=\"" + zoneId + "\" AND vlan_id =\"" + vlanId + "\"", "id",
"Unable to start DB connection to read vlan DB id. Please contact Cloud Support.");
}
public List<String> modifyVlan(String zone, boolean add, String vlanId, String vlanGateway, String vlanNetmask, String pod, String vlanType, String ipRange, long networkId) {
// Check if the zone is valid
long zoneId = getZoneId(zone);
if (zoneId == -1)
return genReturnList("false", "Please specify a valid zone.");
Long podId = pod!=null?getPodId(pod, zone):null;
if (podId != null && podId == -1)
return genReturnList("false", "Please specify a valid pod.");
if (add) {
// Make sure the gateway is valid
if (!NetUtils.isValidIp(vlanGateway))
return genReturnList("false", "Please specify a valid gateway.");
// Make sure the netmask is valid
if (!NetUtils.isValidIp(vlanNetmask))
return genReturnList("false", "Please specify a valid netmask.");
// Check if a vlan with the same vlanId already exists in the specified zone
if (getVlanDbId(zone, vlanId) != -1)
return genReturnList("false", "A VLAN with the specified VLAN ID already exists in zone " + zone + ".");
/*
// Check if another vlan in the same zone has the same subnet
String newVlanSubnet = NetUtils.getSubNet(vlanGateway, vlanNetmask);
List<VlanVO> vlans = _vlanDao.findByZone(zoneId);
for (VlanVO vlan : vlans) {
String currentVlanSubnet = NetUtils.getSubNet(vlan.getVlanGateway(), vlan.getVlanNetmask());
if (newVlanSubnet.equals(currentVlanSubnet))
return genReturnList("false", "The VLAN with ID " + vlan.getVlanId() + " in zone " + zone + " has the same subnet. Please specify a different gateway/netmask.");
}
*/
// Everything was fine, so persist the VLAN
saveVlan(zoneId, podId, vlanId, vlanGateway, vlanNetmask, vlanType, ipRange, networkId);
if (podId != null) {
long vlanDbId = getVlanDbId(zone, vlanId);
String sql = "INSERT INTO `cloud`.`pod_vlan_map` (pod_id, vlan_db_id) " + "VALUES ('" + podId + "','" + vlanDbId + "')";
DatabaseConfig.saveSQL(sql, "Failed to save pod_vlan_map due to exception vlanDbId=" + vlanDbId + ", podId=" + podId + ". Please contact Cloud Support.");
}
return genReturnList("true", "Successfully added VLAN.");
} else {
return genReturnList("false", "That operation is not suppored.");
}
/*
else {
// Check if a VLAN actually exists in the specified zone
long vlanDbId = getVlanDbId(zone, vlanId);
if (vlanDbId == -1)
return genReturnList("false", "A VLAN with ID " + vlanId + " does not exist in zone " + zone);
// Check if there are any public IPs that are in the specified vlan.
List<IPAddressVO> ips = _publicIpAddressDao.listByVlanDbId(vlanDbId);
if (ips.size() != 0)
return genReturnList("false", "Please delete all IP addresses that are in VLAN " + vlanId + " before deleting the VLAN.");
// Delete the vlan
_vlanDao.delete(vlanDbId);
return genReturnList("true", "Successfully deleted VLAN.");
}
*/
}
@DB
public void saveZone(boolean printOutput, long id, String name, String dns1, String dns2, String dns3, String dns4, int vnetStart, int vnetEnd, String guestNetworkCidr, String networkType) {
if (printOutput) System.out.println("Saving zone, please wait...");
String columns = null;
String values = null;
if (id != -1) {
columns = "(id, name";
values = "('" + id + "','" + name + "'";
} else {
columns = "(name";
values = "('" + name + "'";
}
if (dns1 != null) {
columns += ", dns1";
values += ",'" + dns1 + "'";
}
if (dns2 != null) {
columns += ", dns2";
values += ",'" + dns2 + "'";
}
if (dns3 != null) {
columns += ", internal_dns1";
values += ",'" + dns3 + "'";
}
if (dns4 != null) {
columns += ", internal_dns2";
values += ",'" + dns4 + "'";
}
if(guestNetworkCidr != null) {
columns += ", guest_network_cidr";
values += ",'" + guestNetworkCidr + "'";
}
if(networkType != null) {
columns += ", networktype";
values += ",'" + networkType + "'";
}
//save vnet information
columns += ", vnet";
values += ",'" + vnetStart + "-" + vnetEnd + "'";
columns += ")";
values += ")";
String sql = "INSERT INTO `cloud`.`data_center` " + columns + " VALUES " + values;
DatabaseConfig.saveSQL(sql, "Failed to save zone due to exception. Please contact Cloud Support.");
// Hardcode the vnet range to be the full range
int begin = 0x64;
int end = 64000;
// If vnet arguments were passed in, use them
if (vnetStart != -1 && vnetEnd != -1) {
begin = vnetStart;
end = vnetEnd;
}
long dcId = getZoneId(name);
String insertVnet = "INSERT INTO `cloud`.`op_dc_vnet_alloc` (vnet, data_center_id) VALUES ( ?, ?)";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(insertVnet);
for (int i = begin; i <= end; i++) {
stmt.setString(1, Integer.toString(i));
stmt.setLong(2, dcId);
stmt.addBatch();
}
stmt.executeBatch();
} catch (SQLException ex) {
printError("Error creating vnet for the data center. Please contact Cloud Support.");
}
if (printOutput) System.out.println("Successfully saved zone.");
}
public void deleteZone(String name) {
String sql = "DELETE FROM `cloud`.`data_center` WHERE name=\"" + name + "\"";
DatabaseConfig.saveSQL(sql, "Failed to delete zone due to exception. Please contact Cloud Support.");
}
public void saveVlan(long zoneId, Long podId, String vlanId, String vlanGateway, String vlanNetmask, String vlanType, String ipRange, long networkId) {
String sql = "INSERT INTO `cloud`.`vlan` (vlan_id, vlan_gateway, vlan_netmask, data_center_id, vlan_type, description, network_id) " + "VALUES ('" + vlanId + "','" + vlanGateway + "','" + vlanNetmask + "','" + zoneId + "','" + vlanType + "','" + ipRange + "','" + networkId + "')";
DatabaseConfig.saveSQL(sql, "Failed to save vlan due to exception. Please contact Cloud Support.");
}
public static long getPodId(String pod, String zone) {
long dcId = getZoneId(zone);
String selectSql = "SELECT * FROM `cloud`.`host_pod_ref` WHERE name = \"" + pod + "\" AND data_center_id = \"" + dcId + "\"";
String errorMsg = "Could not read pod ID fro mdatabase. Please contact Cloud Support.";
return DatabaseConfig.getDatabaseValueLong(selectSql, "id", errorMsg);
}
public static long getPodId(String pod, long dcId) {
String selectSql = "SELECT * FROM `cloud`.`host_pod_ref` WHERE name = \"" + pod + "\" AND data_center_id = \"" + dcId + "\"";
String errorMsg = "Could not read pod ID fro mdatabase. Please contact Cloud Support.";
return DatabaseConfig.getDatabaseValueLong(selectSql, "id", errorMsg);
}
public static long getZoneId(String zone) {
String selectSql = "SELECT * FROM `cloud`.`data_center` WHERE name = \"" + zone + "\"";
String errorMsg = "Could not read zone ID from database. Please contact Cloud Support.";
return DatabaseConfig.getDatabaseValueLong(selectSql, "id", errorMsg);
}
@DB
public Vector<Long> getAllZoneIDs() {
Vector<Long> allZoneIDs = new Vector<Long>();
String selectSql = "SELECT id FROM data_center";
Transaction txn = Transaction.currentTxn();
try {
PreparedStatement stmt = txn.prepareAutoCloseStatement(selectSql);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
Long dcId = rs.getLong("id");
allZoneIDs.add(dcId);
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
printError("There was an issue with reading zone IDs. Please contact Cloud Support.");
return null;
}
return allZoneIDs;
}
public static boolean validPod(String pod, String zone) {
return (getPodId(pod, zone) != -1);
}
public static boolean validZone(String zone) {
return (getZoneId(zone) != -1);
}
public static String getPodName(long podId, long dcId) {
return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`host_pod_ref` WHERE id=" + podId + " AND data_center_id=" + dcId, "name",
"Unable to start DB connection to read pod name. Please contact Cloud Support.");
}
public static String getZoneName(long dcId) {
return DatabaseConfig.getDatabaseValueString("SELECT * FROM `cloud`.`data_center` WHERE id=" + dcId, "name",
"Unable to start DB connection to read zone name. Please contact Cloud Support.");
}
private static void printError(String message) {
DatabaseConfig.printError(message);
}
private List<String> genReturnList(String success, String message) {
List<String> returnList = new ArrayList<String>();
returnList.add(0, success);
returnList.add(1, message);
return returnList;
}
}
|
package org.apollo.net.session;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apollo.ServerContext;
import org.apollo.game.GameConstants;
import org.apollo.game.GameService;
import org.apollo.game.message.Message;
import org.apollo.game.message.MessageHandlerChainSet;
import org.apollo.game.message.impl.LogoutMessage;
import org.apollo.game.model.entity.Player;
/**
* A game session.
*
* @author Graham
*/
public final class GameSession extends Session {
/**
* The logger for this class.
*/
private static final Logger logger = Logger.getLogger(GameSession.class.getName());
/**
* The server context.
*/
private final ServerContext context;
/**
* The queue of pending {@link Message}s.
*/
private final BlockingQueue<Message> messageQueue = new ArrayBlockingQueue<>(GameConstants.MESSAGES_PER_PULSE);
/**
* The player.
*/
private final Player player;
/**
* Creates a login session for the specified channel.
*
* @param channel The channel.
* @param context The server context.
* @param player The player.
*/
public GameSession(Channel channel, ServerContext context, Player player) {
super(channel);
this.context = context;
this.player = player;
}
@Override
public void destroy() {
context.getService(GameService.class).unregisterPlayer(player);
}
/**
* Encodes and dispatches the specified message.
*
* @param message The message.
*/
public void dispatchMessage(Message message) {
Channel channel = getChannel();
if (channel.isActive() && channel.isOpen()) {
ChannelFuture future = channel.writeAndFlush(message);
if (message.getClass() == LogoutMessage.class) {
future.addListener(ChannelFutureListener.CLOSE);
}
}
}
/**
* Handles pending messages for this session.
*
* @param chainSet The {@link MessageHandlerChainSet}
*/
public void handlePendingMessages(MessageHandlerChainSet chainSet) {
Message message;
while ((message = messageQueue.poll()) != null) {
try {
chainSet.notify(player, message);
} catch (Exception reason) {
logger.log(Level.SEVERE, "Uncaught exception thrown while handling message: " + message, reason);
}
}
}
/**
* Handles a player saver response.
*
* @param success A flag indicating if the save was successful.
*/
public void handlePlayerSaverResponse(boolean success) {
context.getService(GameService.class).finalizePlayerUnregistration(player);
}
@Override
public void messageReceived(Object message) {
if (messageQueue.size() >= GameConstants.MESSAGES_PER_PULSE) {
logger.warning("Too many messages in queue for game session, dropping...");
} else {
messageQueue.add((Message) message);
}
}
}
|
package Config;
import Individual.Individual;
public class Configuration {
public static final int POPULATION_SIZE = 500; /* population 100-500 */
public static final int NUMBER_OF_SELECTIONS = 10; // in Prozent
public static final int CROSSOVER = (POPULATION_SIZE - NUMBER_OF_SELECTIONS) / 2; /* sei der Anteil, der in jedem Schritt durch Crossover ersetzt wird */
public static final double MUTATIONRATE = 30; /* mutationsrate in Prozent */
public static final int NUMBER_OF_PERMUTATIONS = 1;
public static final Individual HYPOTHESE = new Individual();
public static final int BITSTRING_SIZE = 100;
public static int GENERATION_COUNTER = 0; /* counter for generations */
public static double BEST_FITNESS = 0; /* best individual */
public static final double FITNESS_THRESHOLD = 100; /* goal */
}
|
package org.bdgp.OpenHiCAMM;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.SwingUtilities;
import org.bdgp.OpenHiCAMM.ImageLog.ImageLogRecord;
import org.bdgp.OpenHiCAMM.DB.ModuleConfig;
import org.bdgp.OpenHiCAMM.DB.Task;
import org.bdgp.OpenHiCAMM.DB.WorkflowInstance;
import org.bdgp.OpenHiCAMM.DB.WorkflowModule;
import org.bdgp.OpenHiCAMM.Modules.Interfaces.Configuration;
import net.miginfocom.swing.MigLayout;
import java.awt.Frame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import static org.bdgp.OpenHiCAMM.Util.where;
/**
* The main workflow dialog.
* @author insitu
*/
@SuppressWarnings("serial")
public class WorkflowDialog extends JDialog {
// Swing widgets
JTextField workflowDir;
JFileChooser directoryChooser;
JComboBox<String> workflowInstance;
JComboBox<String> startModule;
JButton editWorkflowButton;
JButton startButton;
JLabel lblConfigure;
JButton btnConfigure;
JButton btnCreateNewInstance;
// The Micro-Manager plugin module
OpenHiCAMM mmslide;
// The workflow runner module
WorkflowRunner workflowRunner;
private JButton btnShowImageLog;
private JButton btnShowDatabaseManager;
ImageLog imageLog;
private JButton btnResume;
public WorkflowDialog(Frame parentFrame, OpenHiCAMM mmslide) {
super(parentFrame, "OpenHiCAMM");
this.mmslide = mmslide;
directoryChooser = new JFileChooser();
directoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
directoryChooser.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
}});
getContentPane().setLayout(new MigLayout("", "[][835.00,grow]", "[][][][][][]"));
JLabel lblChooseWorkflowDirectory = new JLabel("Workflow Directory");
getContentPane().add(lblChooseWorkflowDirectory, "cell 0 0,alignx trailing");
workflowDir = new JTextField();
workflowDir.setEditable(false);
workflowDir.setColumns(40);
getContentPane().add(workflowDir, "flowx,cell 1 0,growx");
JButton openWorkflowButton = new JButton("Choose");
getContentPane().add(openWorkflowButton, "cell 1 0");
JLabel lblChooseWorkflowInstance = new JLabel("Workflow Instance");
getContentPane().add(lblChooseWorkflowInstance, "cell 0 1,alignx trailing");
workflowInstance = new JComboBox<String>();
workflowInstance.setEnabled(false);
workflowInstance.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
initWorkflowRunner(false);
}
}});
btnCreateNewInstance = new JButton("Create New Instance");
btnCreateNewInstance.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Connection workflowDb = Connection.get(
new File(workflowDir.getText(), WorkflowRunner.WORKFLOW_DB).getPath());
Dao<WorkflowInstance> wfi = workflowDb.table(WorkflowInstance.class);
WorkflowInstance wf = new WorkflowInstance();
wfi.insert(wf);
wf.createStorageLocation(workflowDir.getText());
wfi.update(wf,"id");
List<String> workflowInstances = new ArrayList<String>();
for (WorkflowInstance instance : wfi.select()) {
workflowInstances.add(instance.getName());
}
Collections.sort(workflowInstances, Collections.reverseOrder());
workflowInstance.setModel(new DefaultComboBoxModel<String>(workflowInstances.toArray(new String[0])));
workflowInstance.setEnabled(true);
workflowInstance.getModel().setSelectedItem(wf.getName());
}
});
getContentPane().add(btnCreateNewInstance, "flowx,cell 1 1,alignx right");
getContentPane().add(workflowInstance, "cell 1 1,alignx right");
btnCreateNewInstance.setEnabled(false);
JLabel lblChooseStartTask = new JLabel("Start Task");
getContentPane().add(lblChooseStartTask, "cell 0 2,alignx trailing");
startModule = new JComboBox<String>();
startModule.setEnabled(false);
startModule.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) { }
}});
getContentPane().add(startModule, "cell 1 2,alignx trailing");
lblConfigure = new JLabel("Configure Modules");
getContentPane().add(lblConfigure, "cell 0 3,alignx trailing");
btnConfigure = new JButton("Configure...");
btnConfigure.setEnabled(false);
btnConfigure.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
initWorkflowRunner(false);
Map<String,Configuration> configurations = workflowRunner.getConfigurations();
WorkflowConfigurationDialog config = new WorkflowConfigurationDialog(
WorkflowDialog.this,
configurations,
workflowRunner.getInstanceDb().table(ModuleConfig.class),
workflowRunner.getWorkflowDb().table(ModuleConfig.class));
config.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
config.pack();
config.setVisible(true);
}
});
getContentPane().add(btnConfigure, "cell 1 3,alignx trailing");
startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Map<String,Configuration> configurations = workflowRunner.getConfigurations();
WorkflowConfigurationDialog config = new WorkflowConfigurationDialog(
WorkflowDialog.this,
configurations,
workflowRunner.getInstanceDb().table(ModuleConfig.class),
workflowRunner.getWorkflowDb().table(ModuleConfig.class));
if (config.validateConfiguration()) {
start(false);
}
}
});
startButton.setEnabled(false);
getContentPane().add(startButton, "flowx,cell 1 4,alignx trailing");
btnResume = new JButton("Resume");
btnResume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Map<String,Configuration> configurations = workflowRunner.getConfigurations();
WorkflowConfigurationDialog config = new WorkflowConfigurationDialog(
WorkflowDialog.this,
configurations,
workflowRunner.getInstanceDb().table(ModuleConfig.class),
workflowRunner.getWorkflowDb().table(ModuleConfig.class));
if (config.validateConfiguration()) {
start(true);
}
}
});
getContentPane().add(btnResume, "cell 1 4");
editWorkflowButton = new JButton("Edit Workflow...");
editWorkflowButton.setEnabled(false);
getContentPane().add(editWorkflowButton, "cell 1 0");
btnShowImageLog = new JButton("Show Image Log");
btnShowImageLog.setEnabled(true);
btnShowImageLog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (WorkflowDialog.this.workflowRunner != null) {
List<ImageLogRecord> records = WorkflowDialog.this.workflowRunner.getImageLogRecords();
imageLog = new ImageLog(records);
imageLog.setVisible(true);
}
}
});
getContentPane().add(btnShowImageLog, "cell 1 5,alignx right");
btnShowDatabaseManager = new JButton("Show Database Manager");
btnShowDatabaseManager.setEnabled(true);
btnShowDatabaseManager.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (WorkflowDialog.this.workflowRunner != null) {
WorkflowDialog.this.workflowRunner.getWorkflowDb().startDatabaseManager();
WorkflowDialog.this.workflowRunner.getInstanceDb().startDatabaseManager();
}
}
});
getContentPane().add(btnShowDatabaseManager, "cell 1 5,alignx right");
editWorkflowButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
WorkflowDesignerDialog designer = new WorkflowDesignerDialog(WorkflowDialog.this, new File(workflowDir.getText()));
designer.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
designer.pack();
designer.setVisible(true);
designer.addWindowListener(new WindowListener() {
@Override public void windowOpened(WindowEvent e) { }
@Override public void windowClosing(WindowEvent e) { }
@Override public void windowClosed(WindowEvent e) {
initWorkflowRunner(true);
WorkflowDialog.this.workflowRunner.deleteTaskRecords();
refresh();
}
@Override public void windowIconified(WindowEvent e) { }
@Override public void windowDeiconified(WindowEvent e) { }
@Override public void windowActivated(WindowEvent e) { }
@Override public void windowDeactivated(WindowEvent e) { }
});
}});
openWorkflowButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String oldWorkflowDir = workflowDir.getText();
if (directoryChooser.showDialog(WorkflowDialog.this,"Choose Workflow Directory") == JFileChooser.APPROVE_OPTION) {
workflowDir.setText(directoryChooser.getSelectedFile().getPath());
}
// If the workflow selection changed, then load the new workflow runner
if (!oldWorkflowDir.isEmpty() && !workflowDir.getText().equals(oldWorkflowDir)) {
WorkflowDialog.this.initWorkflowRunner(true);
}
// If a workflow directory was given, enable the edit button and refresh the UI control state
if (workflowDir.getText().length() > 0) {
editWorkflowButton.setEnabled(true);
refresh();
}
else {
editWorkflowButton.setEnabled(false);
}
}
});
}
/**
* Catch-all function to refresh the UI controls given the state of the dialog. This should be run whenever
* a model state change is made that can change the UI state.
*/
public void refresh() {
List<String> startModules = new ArrayList<String>();
if (workflowDir.getText().length() > 0) {
Connection workflowDb = Connection.get(
new File(workflowDir.getText(), WorkflowRunner.WORKFLOW_DB).getPath());
// get list of starting modules
Dao<WorkflowModule> modules = workflowDb.table(WorkflowModule.class);
for (WorkflowModule module : modules.select()) {
if (module.getParentId() == null) {
startModules.add(module.getId());
}
}
Collections.sort(startModules);
String startModuleId = null;
if (startModule.getModel() != null) {
startModuleId = (String)startModule.getItemAt(startModule.getSelectedIndex());
}
startModule.setModel(new DefaultComboBoxModel<String>(startModules.toArray(new String[0])));
if (startModuleId != null) {
startModule.setSelectedItem(startModuleId);
}
startModule.setEnabled(true);
// get the list of workflow instances
List<String> workflowInstances = new ArrayList<String>();
Dao<WorkflowInstance> wfi = workflowDb.table(WorkflowInstance.class);
for (WorkflowInstance instance : wfi.select()) {
workflowInstances.add(instance.getName());
}
Collections.sort(workflowInstances, Collections.reverseOrder());
workflowInstance.setModel(new DefaultComboBoxModel<String>(workflowInstances.toArray(new String[0])));
workflowInstance.setEnabled(true);
if (workflowInstances.size()>0) {
initWorkflowRunner(false);
}
if (startModules.size() > 0) {
btnConfigure.setEnabled(true);
startButton.setEnabled(true);
btnCreateNewInstance.setEnabled(true);
}
}
}
/**
* Create a new workflowRunner instance.
* @param force
*/
public void initWorkflowRunner(boolean force) {
Integer instanceId = workflowInstance.getSelectedIndex() < 0 ? null :
Integer.parseInt(((String)workflowInstance.getItemAt(workflowInstance.getSelectedIndex())).replaceAll("^WF",""));
if (workflowRunner == null || instanceId == null || !instanceId.equals(workflowRunner.getInstance().getId()) || force) {
workflowRunner = new WorkflowRunner(new File(workflowDir.getText()), instanceId, Level.INFO, mmslide);
}
}
/**
* Start the workflow runner and open the Workflow Runner dialog.
* Resume mode does not delete and re-create the Task/TaskConfig records before starting.
*/
public void start(boolean resume) {
// Make sure the workflow runner is initialized
initWorkflowRunner(false);
// Get the selected start module
String startModuleId = (String)startModule.getItemAt(startModule.getSelectedIndex());
List<Task> tasks = workflowRunner.getTaskStatus().select(where("moduleId", startModuleId));
if (tasks.size() > 0) {
if (JOptionPane.showConfirmDialog(null,
"There is existing run status data in the database. \n"+
"Are you sure you want to overwrite the existing data?",
"Confirm Overwrite Existing Run",
JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
{ return; }
}
// re-init the logger. This ensures each workflow run gets logged to a separate file.
workflowRunner.initLogger();
final WorkflowRunnerDialog wrd = new WorkflowRunnerDialog(this, workflowRunner, startModuleId);
wrd.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
wrd.pack();
// Refresh the UI controls
refresh();
// Start the workflow runner
workflowRunner.run(startModuleId, null, resume);
// Make the workflow runner dialog visible
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
wrd.setVisible(true);
}
});
}
}
|
package org.bdgp.OpenHiCAMM;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.SwingUtilities;
import org.bdgp.OpenHiCAMM.ImageLog.ImageLogRecord;
import org.bdgp.OpenHiCAMM.DB.ModuleConfig;
import org.bdgp.OpenHiCAMM.DB.Task;
import org.bdgp.OpenHiCAMM.DB.WorkflowInstance;
import org.bdgp.OpenHiCAMM.DB.WorkflowModule;
import org.bdgp.OpenHiCAMM.Modules.Interfaces.Configuration;
import net.miginfocom.swing.MigLayout;
import java.awt.Frame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import static org.bdgp.OpenHiCAMM.Util.where;
import javax.swing.JSpinner;
/**
* The main workflow dialog.
* @author insitu
*/
@SuppressWarnings("serial")
public class WorkflowDialog extends JDialog {
// Swing widgets
JTextField workflowDir;
JFileChooser directoryChooser;
JComboBox<String> workflowInstance;
JComboBox<String> startModule;
JButton editWorkflowButton;
JButton startButton;
JLabel lblConfigure;
JButton btnConfigure;
JButton btnCreateNewInstance;
// The Micro-Manager plugin module
OpenHiCAMM mmslide;
// The workflow runner module
WorkflowRunner workflowRunner;
WorkflowRunnerDialog workflowRunnerDialog;
JButton btnShowImageLog;
JButton btnShowDatabaseManager;
ImageLog imageLog;
JButton btnResume;
JSpinner numThreads;
private JLabel lblNumberOfThreads;
private boolean active = true;
public WorkflowDialog(Frame parentFrame, OpenHiCAMM mmslide) {
super(parentFrame, "OpenHiCAMM");
this.mmslide = mmslide;
directoryChooser = new JFileChooser();
directoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
directoryChooser.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!active) return;
refresh();
}});
getContentPane().setLayout(new MigLayout("", "[][483.00,grow]", "[][][][][][][]"));
JLabel lblChooseWorkflowDirectory = new JLabel("Workflow Directory");
getContentPane().add(lblChooseWorkflowDirectory, "cell 0 0,alignx trailing");
workflowDir = new JTextField();
workflowDir.setEditable(false);
workflowDir.setColumns(40);
getContentPane().add(workflowDir, "flowx,cell 1 0,growx");
JButton openWorkflowButton = new JButton("Choose");
getContentPane().add(openWorkflowButton, "cell 1 0");
JLabel lblChooseWorkflowInstance = new JLabel("Workflow Instance");
getContentPane().add(lblChooseWorkflowInstance, "cell 0 1,alignx trailing");
workflowInstance = new JComboBox<String>();
workflowInstance.setEnabled(false);
workflowInstance.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (!active) return;
if (e.getStateChange() == ItemEvent.SELECTED) {
initWorkflowRunner(false);
// Set resume button enabled/disabled
if (startModule.getModel() != null) {
String startModuleId = (String)startModule.getItemAt(startModule.getSelectedIndex());
if (startModuleId != null) {
List<Task> tasks = workflowRunner.getTaskStatus().select(where("moduleId", startModuleId));
btnResume.setEnabled(tasks.size() > 0);
}
else {
btnResume.setEnabled(false);
}
}
else {
btnResume.setEnabled(false);
}
}
refresh();
}});
btnCreateNewInstance = new JButton("Create New Instance");
btnCreateNewInstance.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (!active) return;
Connection workflowDb = Connection.get(
new File(workflowDir.getText(), WorkflowRunner.WORKFLOW_DB).getPath());
Dao<WorkflowInstance> wfi = workflowDb.table(WorkflowInstance.class);
WorkflowInstance wf = new WorkflowInstance();
wfi.insert(wf);
wf.createStorageLocation(workflowDir.getText());
wfi.update(wf,"id");
List<String> workflowInstances = new ArrayList<String>();
for (WorkflowInstance instance : wfi.select()) {
workflowInstances.add(instance.getName());
}
Collections.sort(workflowInstances, Collections.reverseOrder());
workflowInstance.setModel(new DefaultComboBoxModel<String>(workflowInstances.toArray(new String[0])));
workflowInstance.setEnabled(true);
workflowInstance.getModel().setSelectedItem(wf.getName());
refresh();
}
});
getContentPane().add(btnCreateNewInstance, "flowx,cell 1 1,alignx right");
getContentPane().add(workflowInstance, "cell 1 1,alignx right");
btnCreateNewInstance.setEnabled(false);
JLabel lblChooseStartTask = new JLabel("Start Task");
getContentPane().add(lblChooseStartTask, "cell 0 2,alignx trailing");
startModule = new JComboBox<String>();
startModule.setEnabled(false);
startModule.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (!active) return;
if (e.getStateChange() == ItemEvent.SELECTED) { }
refresh();
}});
getContentPane().add(startModule, "cell 1 2,alignx trailing");
lblConfigure = new JLabel("Configure Modules");
getContentPane().add(lblConfigure, "cell 0 3,alignx trailing");
btnConfigure = new JButton("Configure...");
btnConfigure.setEnabled(false);
btnConfigure.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!active) return;
initWorkflowRunner(false);
Map<String,Configuration> configurations = workflowRunner.getConfigurations();
WorkflowConfigurationDialog config = new WorkflowConfigurationDialog(
WorkflowDialog.this,
configurations,
workflowRunner.getInstanceDb().table(ModuleConfig.class),
workflowRunner.getWorkflowDb().table(ModuleConfig.class));
config.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
config.pack();
config.setVisible(true);
refresh();
}
});
getContentPane().add(btnConfigure, "cell 1 3,alignx trailing");
startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!active) return;
Map<String,Configuration> configurations = workflowRunner.getConfigurations();
WorkflowConfigurationDialog config = new WorkflowConfigurationDialog(
WorkflowDialog.this,
configurations,
workflowRunner.getInstanceDb().table(ModuleConfig.class),
workflowRunner.getWorkflowDb().table(ModuleConfig.class));
if (config.validateConfiguration()) {
start(false);
}
refresh();
}
});
lblNumberOfThreads = new JLabel("Number of Threads:");
getContentPane().add(lblNumberOfThreads, "cell 0 4");
numThreads = new JSpinner();
SpinnerNumberModel numThreadsModel = new SpinnerNumberModel();
numThreadsModel.setMinimum(1);
numThreadsModel.setMaximum(Runtime.getRuntime().availableProcessors());
numThreads.setModel(numThreadsModel);
numThreads.setValue(1);
getContentPane().add(numThreads, "cell 1 4,alignx right");
startButton.setEnabled(false);
getContentPane().add(startButton, "flowx,cell 1 5,alignx trailing");
btnResume = new JButton("Resume");
btnResume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!active) return;
Map<String,Configuration> configurations = workflowRunner.getConfigurations();
WorkflowConfigurationDialog config = new WorkflowConfigurationDialog(
WorkflowDialog.this,
configurations,
workflowRunner.getInstanceDb().table(ModuleConfig.class),
workflowRunner.getWorkflowDb().table(ModuleConfig.class));
if (config.validateConfiguration()) {
start(true);
}
refresh();
}
});
btnResume.setEnabled(false);
getContentPane().add(btnResume, "cell 1 5");
editWorkflowButton = new JButton("Edit Workflow...");
editWorkflowButton.setEnabled(false);
getContentPane().add(editWorkflowButton, "cell 1 0");
btnShowImageLog = new JButton("Show Image Log");
btnShowImageLog.setEnabled(true);
btnShowImageLog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!active) return;
if (WorkflowDialog.this.workflowRunner != null) {
List<ImageLogRecord> records = WorkflowDialog.this.workflowRunner.getImageLogRecords();
imageLog = new ImageLog(records);
imageLog.setVisible(true);
}
refresh();
}
});
getContentPane().add(btnShowImageLog, "cell 1 6,alignx right");
btnShowDatabaseManager = new JButton("Show Database Manager");
btnShowDatabaseManager.setEnabled(true);
btnShowDatabaseManager.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!active) return;
if (WorkflowDialog.this.workflowRunner != null) {
WorkflowDialog.this.workflowRunner.getWorkflowDb().startDatabaseManager();
WorkflowDialog.this.workflowRunner.getInstanceDb().startDatabaseManager();
}
refresh();
}
});
getContentPane().add(btnShowDatabaseManager, "cell 1 6,alignx right");
editWorkflowButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!active) return;
WorkflowDesignerDialog designer = new WorkflowDesignerDialog(WorkflowDialog.this, new File(workflowDir.getText()));
designer.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
designer.pack();
designer.setVisible(true);
designer.addWindowListener(new WindowAdapter() {
@Override public void windowClosed(WindowEvent e) {
initWorkflowRunner(true);
WorkflowDialog.this.workflowRunner.deleteTaskRecords();
refresh();
}
});
refresh();
}});
openWorkflowButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!active) return;
String oldWorkflowDir = workflowDir.getText();
if (directoryChooser.showDialog(WorkflowDialog.this,"Choose Workflow Directory") == JFileChooser.APPROVE_OPTION) {
workflowDir.setText(directoryChooser.getSelectedFile().getPath());
}
// If the workflow selection changed, then load the new workflow runner
if (!oldWorkflowDir.isEmpty() && !workflowDir.getText().equals(oldWorkflowDir)) {
WorkflowDialog.this.initWorkflowRunner(true);
}
// If a workflow directory was given, enable the edit button and refresh the UI control state
if (workflowDir.getText().length() > 0) {
editWorkflowButton.setEnabled(true);
}
else {
editWorkflowButton.setEnabled(false);
}
refresh();
}
});
refresh();
}
/**
* Catch-all function to refresh the UI controls given the state of the dialog. This should be run whenever
* a model state change is made that can change the UI state.
*/
public void refresh() {
try {
active = false;
List<String> startModules = new ArrayList<String>();
if (workflowDir.getText().length() > 0) {
Connection workflowDb = Connection.get(
new File(workflowDir.getText(), WorkflowRunner.WORKFLOW_DB).getPath());
// get list of starting modules
Dao<WorkflowModule> modules = workflowDb.table(WorkflowModule.class);
for (WorkflowModule module : modules.select()) {
if (module.getParentId() == null) {
startModules.add(module.getId());
}
}
Collections.sort(startModules);
String startModuleId = null;
if (startModule.getModel() != null) {
startModuleId = (String)startModule.getItemAt(startModule.getSelectedIndex());
}
startModule.setModel(new DefaultComboBoxModel<String>(startModules.toArray(new String[0])));
if (startModuleId == null && startModules.size() > 0) {
startModuleId = startModules.get(0);
}
if (startModuleId != null) {
startModule.setSelectedItem(startModuleId);
}
startModule.setEnabled(true);
// get the list of workflow instances
List<String> workflowInstances = new ArrayList<String>();
Dao<WorkflowInstance> wfi = workflowDb.table(WorkflowInstance.class);
for (WorkflowInstance instance : wfi.select()) {
workflowInstances.add(instance.getName());
}
Collections.sort(workflowInstances, Collections.reverseOrder());
String selectedInstance = (String)workflowInstance.getSelectedItem();
if (selectedInstance == null && workflowInstances.size() > 0) selectedInstance = workflowInstances.get(0);
workflowInstance.setModel(new DefaultComboBoxModel<String>(workflowInstances.toArray(new String[0])));
if (selectedInstance != null) workflowInstance.setSelectedItem(selectedInstance);
workflowInstance.setEnabled(true);
if (workflowInstances.size() > 0) {
initWorkflowRunner(false);
}
if (startModules.size() > 0) {
btnConfigure.setEnabled(true);
startButton.setEnabled(true);
btnCreateNewInstance.setEnabled(true);
if (startModuleId != null && workflowRunner != null) {
List<Task> tasks = workflowRunner.getTaskStatus().select(where("moduleId", startModuleId));
btnResume.setEnabled(tasks.size() > 0);
}
else {
btnResume.setEnabled(false);
}
}
else {
btnResume.setEnabled(false);
}
}
}
finally {
active = true;
}
}
/**
* Create a new workflowRunner instance.
* @param force
*/
public void initWorkflowRunner(boolean force) {
Integer instanceId = workflowInstance.getSelectedIndex() < 0 ? null :
Integer.parseInt(((String)workflowInstance.getItemAt(workflowInstance.getSelectedIndex())).replaceAll("^WF",""));
if (workflowRunner == null || instanceId == null || !instanceId.equals(workflowRunner.getInstance().getId()) || force) {
workflowRunner = new WorkflowRunner(new File(workflowDir.getText()), instanceId, Level.INFO, mmslide);
workflowRunnerDialog = new WorkflowRunnerDialog(WorkflowDialog.this, workflowRunner);
workflowRunnerDialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
workflowRunnerDialog.pack();
}
}
/**
* Start the workflow runner and open the Workflow Runner dialog.
* Resume mode does not delete and re-create the Task/TaskConfig records before starting.
*/
public void start(final boolean resume) {
// Make sure the workflow runner is initialized
initWorkflowRunner(false);
this.workflowRunner.setMaxThreads((Integer)numThreads.getValue());
// Get the selected start module
final String startModuleId = (String)startModule.getItemAt(startModule.getSelectedIndex());
if (!resume) {
List<Task> tasks = workflowRunner.getTaskStatus().select(where("moduleId", startModuleId));
if (tasks.size() > 0) {
if (JOptionPane.showConfirmDialog(null,
"There is existing run status data in the database. \n"+
"Are you sure you want to overwrite the existing data?",
"Confirm Overwrite Existing Run",
JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION)
{ return; }
}
}
// re-init the logger. This ensures each workflow run gets logged to a separate file.
workflowRunner.initLogger();
// Refresh the UI controls
refresh();
// Make the workflow runner dialog visible
// init the workflow runner dialog
if (workflowRunnerDialog == null) {
workflowRunnerDialog = new WorkflowRunnerDialog(WorkflowDialog.this, workflowRunner);
workflowRunnerDialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
workflowRunnerDialog.pack();
}
else {
workflowRunnerDialog.reset();
}
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
workflowRunnerDialog.setVisible(true);
}});
// Start the workflow runner
workflowRunner.run(startModuleId, null, resume);
}
}
|
package com.jacudibu.fileSystem;
import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.math.Quaternion;
import com.badlogic.gdx.math.Vector3;
import com.jacudibu.utility.Entities;
import com.jacudibu.components.NodeComponent;
public class PoseParser {
public static final int TIMESTAMP = 5;
private static final int QUATERNION_W = 10;
private static final int QUATERNION_X = 11;
private static final int QUATERNION_Y = 12;
private static final int QUATERNION_Z = 13;
private static final int POSITION_X = 16;
private static final int POSITION_Y = 17;
private static final int POSITION_Z = 18;
public static void parseFile(String path) {
parseFile(path, PathType.ABSOLUTE);
}
public static void parseFile(String path, PathType pathType) {
FileHandle file = FileSystem.getFileHandle(path, pathType);
if (!file.exists()) {
Gdx.app.error("ERROR", "Unable to parse file from " + path);
return;
}
String data = file.readString();
String[] dataPieces = data.split(" ");
Vector3 position = getVector3(dataPieces);
Quaternion rotation = getQuaternion(dataPieces);
createPair(position, rotation);
}
private static Vector3 getVector3(String[] dataPieces) {
Vector3 position = new Vector3();
position.x = Float.parseFloat(dataPieces[POSITION_X]);
position.y = Float.parseFloat(dataPieces[POSITION_Y]);
position.z = Float.parseFloat(dataPieces[POSITION_Z]);
return position;
}
private static Quaternion getQuaternion(String[] dataPieces) {
Quaternion rotation = new Quaternion();
rotation.w = Float.parseFloat(dataPieces[QUATERNION_W]);
rotation.x = Float.parseFloat(dataPieces[QUATERNION_X]);
rotation.y = Float.parseFloat(dataPieces[QUATERNION_Y]);
rotation.z = Float.parseFloat(dataPieces[QUATERNION_Z]);
return rotation;
}
private static void createPair(Vector3 position, Quaternion rotation) {
Entity newMarker = Entities.createMarker(position, rotation);
Entity newTracker = Entities.createTracker(new Vector3(), new Quaternion());
NodeComponent.get(newTracker).addOutgoing(newMarker);
}
}
|
package org.bdgp.OpenHiCAMM;
import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.bdgp.OpenHiCAMM.DB.Config;
import org.bdgp.OpenHiCAMM.DB.Image;
import org.bdgp.OpenHiCAMM.DB.ModuleConfig;
import org.bdgp.OpenHiCAMM.DB.Pool;
import org.bdgp.OpenHiCAMM.DB.PoolSlide;
import org.bdgp.OpenHiCAMM.DB.ROI;
import org.bdgp.OpenHiCAMM.DB.Slide;
import org.bdgp.OpenHiCAMM.DB.SlidePosList;
import org.bdgp.OpenHiCAMM.DB.Task;
import org.bdgp.OpenHiCAMM.DB.TaskConfig;
import org.bdgp.OpenHiCAMM.DB.TaskDispatch;
import org.bdgp.OpenHiCAMM.DB.WorkflowModule;
import org.bdgp.OpenHiCAMM.DB.Task.Status;
import org.bdgp.OpenHiCAMM.Modules.ROIFinderDialog;
import org.bdgp.OpenHiCAMM.Modules.SlideImager;
import org.bdgp.OpenHiCAMM.Modules.SlideImagerDialog;
import org.bdgp.OpenHiCAMM.Modules.Interfaces.Module;
import org.bdgp.OpenHiCAMM.Modules.Interfaces.Report;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.micromanager.MMStudio;
import org.micromanager.api.MultiStagePosition;
import org.micromanager.api.PositionList;
import org.micromanager.api.StagePosition;
import org.micromanager.utils.ImageLabelComparator;
import org.micromanager.utils.MDUtils;
import org.micromanager.utils.MMSerializationException;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import ij.IJ;
import ij.ImagePlus;
import ij.WindowManager;
import ij.gui.ImageRoi;
import ij.gui.NewImage;
import ij.gui.Overlay;
import ij.gui.Roi;
import ij.io.FileSaver;
import ij.measure.Measurements;
import ij.measure.ResultsTable;
import ij.plugin.filter.ParticleAnalyzer;
import ij.process.Blitter;
import ij.process.ImageProcessor;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Modality;
import mmcorej.CMMCore;
import static org.bdgp.OpenHiCAMM.Util.where;
import static org.bdgp.OpenHiCAMM.Tag.T.*;
public class WorkflowReport implements Report {
public static final int SLIDE_PREVIEW_WIDTH = 1280;
public static final int ROI_GRID_PREVIEW_WIDTH = 425;
private WorkflowRunner workflowRunner;
private WebEngine webEngine;
private String reportDir;
private String reportIndex;
private Integer prevPoolSlideId;
private Map<Integer,Boolean> isLoaderInitialized;
private Map<Integer,MultiStagePosition> msps;
private Map<Integer,Map<String,ModuleConfig>> moduleConfig;
private Map<Integer,Map<String,TaskConfig>> taskConfig;
private Alert alert = null;
public void jsLog(String message) {
IJ.log(String.format("[WorkflowReport:js] %s", message));
}
public void log(String message, Object... args) {
IJ.log(String.format("[WorkflowReport] %s", String.format(message, args)));
}
@Override public void initialize(WorkflowRunner workflowRunner, WebEngine webEngine, String reportDir, String reportIndex) {
this.workflowRunner = workflowRunner;
this.webEngine = webEngine;
this.reportDir = reportDir;
this.reportIndex = reportIndex;
isLoaderInitialized = new HashMap<Integer,Boolean>();
this.msps = new HashMap<>();
this.moduleConfig = new HashMap<>();
this.taskConfig = new HashMap<>();
}
private ModuleConfig getModuleConfig(int id, String key) {
Map<String,ModuleConfig> confs = moduleConfig.get(id);
if (confs == null) return null;
return confs.get(key);
}
private TaskConfig getTaskConfig(int id, String key) {
Map<String,TaskConfig> confs = taskConfig.get(id);
if (confs == null) return null;
return confs.get(key);
}
@Override
public void runReport() {
Dao<Pool> poolDao = this.workflowRunner.getWorkflowDb().table(Pool.class);
Dao<PoolSlide> psDao = this.workflowRunner.getWorkflowDb().table(PoolSlide.class);
Dao<Slide> slideDao = this.workflowRunner.getWorkflowDb().table(Slide.class);
// cache the module config
log("Caching the module config...");
for (ModuleConfig moduleConf : this.workflowRunner.getModuleConfig().select()) {
moduleConfig.putIfAbsent(moduleConf.getId(), new HashMap<>());
moduleConfig.get(moduleConf.getId()).put(moduleConf.getKey(), moduleConf);
}
// cache the task config
log("Caching the task config...");
for (TaskConfig taskConf : this.workflowRunner.getTaskConfig().select()) {
taskConfig.putIfAbsent(taskConf.getId(), new HashMap<>());
taskConfig.get(taskConf.getId()).put(taskConf.getKey(), taskConf);
}
// get the MSP from the task config
PositionList posList = new PositionList();
List<TaskConfig> mspConfs = this.workflowRunner.getTaskConfig().select(
where("key","MSP"));
log("Creating task->MSP table for %s tasks...", mspConfs.size());
for (TaskConfig mspConf : mspConfs) {
try {
JSONObject posListJson = new JSONObject().
put("POSITIONS", new JSONArray().put(new JSONObject(mspConf.getValue()))).
put("VERSION", 3).
put("ID","Micro-Manager XY-position list");
posList.restore(posListJson.toString());
MultiStagePosition msp = posList.getPosition(0);
msps.put(mspConf.getId(), msp);
}
catch (JSONException | MMSerializationException e) {throw new RuntimeException(e);}
}
// Find SlideImager modules where there is no associated posListModuleId module config
// This is the starting SlideImager module.
int[] reportCounter = new int[]{1};
Map<String,Runnable> runnables = new LinkedHashMap<String,Runnable>();
Tag index = Html().indent().with(()->{
Head().with(()->{
try {
// CSS
Style().raw(Resources.toString(Resources.getResource("bootstrap.min.css"), Charsets.UTF_8));
Style().raw(Resources.toString(Resources.getResource("bootstrap-theme.min.css"), Charsets.UTF_8));
Style().raw(Resources.toString(Resources.getResource("jquery.powertip.min.css"), Charsets.UTF_8));
// Javascript
Script().raw(Resources.toString(Resources.getResource("jquery-2.1.4.min.js"), Charsets.UTF_8));
Script().raw(Resources.toString(Resources.getResource("bootstrap.min.js"), Charsets.UTF_8));
Script().raw(Resources.toString(Resources.getResource("jquery.maphilight.js"), Charsets.UTF_8));
Script().raw(Resources.toString(Resources.getResource("jquery.powertip.min.js"), Charsets.UTF_8));
Script().raw(Resources.toString(Resources.getResource("notify.min.js"), Charsets.UTF_8));
Script().raw(Resources.toString(Resources.getResource("WorkflowReport.js"), Charsets.UTF_8));
}
catch (Exception e) {throw new RuntimeException(e);}
});
Body().with(()->{
SLIDE_IMAGERS:
for (Config canImageSlides : this.workflowRunner.getModuleConfig().select(
where("key","canImageSlides").
and("value", "yes")))
{
WorkflowModule slideImager = this.workflowRunner.getWorkflow().selectOne(
where("id", canImageSlides.getId()));
if (slideImager != null &&
getModuleConfig(slideImager.getId(), "posListModule") == null)
{
log("Working on slideImager: %s", slideImager);
// get the loader module
Integer loaderModuleId = slideImager.getParentId();
while (loaderModuleId != null) {
WorkflowModule loaderModule = this.workflowRunner.getWorkflow().selectOneOrDie(
where("id", loaderModuleId));
Config canLoadSlides = getModuleConfig(loaderModule.getId(), "canLoadSlides");
if (canLoadSlides != null && "yes".equals(canLoadSlides.getValue())) {
log("Using loaderModule: %s", loaderModule);
Config poolIdConf = getModuleConfig(loaderModule.getId(), "poolId");
if (poolIdConf != null) {
Pool pool = poolDao.selectOneOrDie(where("id", poolIdConf.getValue()));
List<PoolSlide> pss = psDao.select(where("poolId", pool.getId()));
if (!pss.isEmpty()) {
for (PoolSlide ps : pss) {
Slide slide = slideDao.selectOneOrDie(where("id", ps.getSlideId()));
String reportFile = String.format("report%03d.%s.cartridge%d.pos%02d.slide%05d.html",
reportCounter[0]++,
slideImager.getName(),
ps.getCartridgePosition(), ps
.getSlidePosition(),
ps.getSlideId());
P().with(()->{
A(String.format("Module %s, Experiment %s, Slide %s", slideImager.getName(), slide.getExperimentId(), ps)).
attr("href", reportFile);
});
Integer loaderModuleId_ = loaderModuleId;
runnables.put(reportFile, ()->{
log("Calling runReport(startModule=%s, poolSlide=%s, loaderModuleId=%s)",
slideImager, ps, loaderModuleId_);
WorkflowModule lm = this.workflowRunner.getWorkflow().selectOneOrDie(where("id", loaderModuleId_));
runReport(slideImager, ps, lm, reportFile);
});
}
continue SLIDE_IMAGERS;
}
}
}
loaderModuleId = loaderModule.getParentId();
}
String reportFile = String.format("report%03d.%s.html", reportCounter[0]++, slideImager.getName());
P().with(()->{
A(String.format("Module %s", slideImager)).
attr("href", reportFile);
});
runnables.put(reportFile, ()->{
log("Calling runReport(startModule=%s, poolSlide=null, loaderModuleId=null)", slideImager);
runReport(slideImager, null, null, reportFile);
});
}
}
});
});
ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
List<Future<?>> futures = new ArrayList<>();
for (Map.Entry<String,Runnable> entry : runnables.entrySet()) {
String reportFile = entry.getKey();
Runnable runnable = entry.getValue();
if (!new File(reportDir, reportFile).exists()) {
futures.add(pool.submit(()->{
Html().indent().with(()->{
Head().with(()->{
try {
// CSS
Style().raw(Resources.toString(Resources.getResource("bootstrap.min.css"), Charsets.UTF_8));
Style().raw(Resources.toString(Resources.getResource("bootstrap-theme.min.css"), Charsets.UTF_8));
Style().raw(Resources.toString(Resources.getResource("jquery.powertip.min.css"), Charsets.UTF_8));
// Javascript
Script().raw(Resources.toString(Resources.getResource("jquery-2.1.4.min.js"), Charsets.UTF_8));
Script().raw(Resources.toString(Resources.getResource("bootstrap.min.js"), Charsets.UTF_8));
Script().raw(Resources.toString(Resources.getResource("jquery.maphilight.js"), Charsets.UTF_8));
Script().raw(Resources.toString(Resources.getResource("jquery.powertip.min.js"), Charsets.UTF_8));
Script().raw(Resources.toString(Resources.getResource("notify.min.js"), Charsets.UTF_8));
Script().raw(Resources.toString(Resources.getResource("WorkflowReport.js"), Charsets.UTF_8));
}
catch (Exception e) {throw new RuntimeException(e);}
});
Body().with(()->{
runnable.run();
});
}).write(new File(reportDir, reportFile));
}));
}
}
for (Future<?> f : futures) {
try { f.get(); }
catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
// write the index last
index.write(new File(this.reportDir, this.reportIndex));
}
private void runReport(WorkflowModule startModule, PoolSlide poolSlide, WorkflowModule loaderModule, String reportFile) {
log("Called runReport(startModule=%s, poolSlide=%s)", startModule, poolSlide);
Dao<Slide> slideDao = this.workflowRunner.getWorkflowDb().table(Slide.class);
Dao<Image> imageDao = this.workflowRunner.getWorkflowDb().table(Image.class);
Dao<ROI> roiDao = this.workflowRunner.getWorkflowDb().table(ROI.class);
Dao<SlidePosList> slidePosListDao = this.workflowRunner.getWorkflowDb().table(SlidePosList.class);
// get a ROI ID -> moduleId(s) mapping from the slideposlist
Map<Integer, Set<Integer>> roiModules = new HashMap<>();
for (SlidePosList spl : slidePosListDao.select()) {
if (spl.getModuleId() != null) {
PositionList posList = spl.getPositionList();
for (MultiStagePosition msp : posList.getPositions()) {
String roiIdConf = msp.getProperty("ROI");
if (roiIdConf != null) {
Integer roiId = new Integer(roiIdConf);
if (!roiModules.containsKey(roiId)) roiModules.put(roiId, new HashSet<>());
roiModules.get(roiId).add(spl.getModuleId());
}
}
}
}
// get the associated hi res slide imager modules for each ROI finder module
// ROIFinder module ID -> List of associated imager module IDs
Map<String,Set<String>> roiImagers = new HashMap<>();
for (Task task : workflowRunner.getTaskStatus().select(
where("moduleId", startModule.getId())))
{
TaskConfig imageIdConf = getTaskConfig(task.getId(), "imageId");
if (imageIdConf != null) {
for (ROI roi : roiDao.select(where("imageId", imageIdConf.getValue()))) {
Set<Integer> roiModuleSet = roiModules.get(roi.getId());
if (roiModuleSet == null) {
//log(String.format("No ROI modules found for ROI %s!", roi));
}
else {
for (Integer roiModuleId : roiModuleSet) {
WorkflowModule roiModule = this.workflowRunner.getWorkflow().selectOne(where("id", roiModuleId));
if (roiModule != null) {
for (ModuleConfig posListModuleConf : this.workflowRunner.getModuleConfig().select(
where("key", "posListModule").
and("value", roiModule.getName())))
{
Config canImageSlides = getModuleConfig(posListModuleConf.getId(), "canImageSlides");
if (canImageSlides != null && "yes".equals(canImageSlides.getValue())) {
WorkflowModule imagerModule = this.workflowRunner.getWorkflow().selectOne(
where("id", posListModuleConf.getId()));
if (imagerModule != null) {
if (!roiImagers.containsKey(roiModule.getName())) roiImagers.put(roiModule.getName(), new HashSet<>());
roiImagers.get(roiModule.getName()).add(imagerModule.getName());
}
}
}
}
}
}
}
}
}
// display the title
Slide slide;
String slideName;
if (poolSlide != null) {
slide = slideDao.selectOneOrDie(where("id", poolSlide.getSlideId()));
slideName = slide.getName();
String title = String.format("SlideImager %s, Experiment %s, Slide %s, Pool %d, Cartridge %d, Slide Position %d",
startModule.getName(),
slide.getExperimentId(),
slide.getName(),
poolSlide.getPoolId(),
poolSlide.getCartridgePosition(),
poolSlide.getSlidePosition());
P().with(()->{
A("Back to Index Page").attr("href", this.reportIndex);
});
A().attr("name", String.format("report-%s-PS%s", startModule.getName(), poolSlide.getId()));
H1().text(title);
log("title = %s", title);
}
else {
slide = null;
slideName = "slide";
String title = String.format("SlideImager %s", startModule.getName());
A().attr("name", String.format("report-%s", startModule.getName()));
H1().text(title);
log("title = %s", title);
}
// get the pixel size of this slide imager config
Config pixelSizeConf = getModuleConfig(startModule.getId(), "pixelSize");
Double pixelSize = pixelSizeConf != null? new Double(pixelSizeConf.getValue()) : SlideImagerDialog.DEFAULT_PIXEL_SIZE_UM;
log("pixelSize = %f", pixelSize);
// get invertXAxis and invertYAxis conf values
Config invertXAxisConf = getModuleConfig(startModule.getId(), "invertXAxis");
boolean invertXAxis = invertXAxisConf == null || invertXAxisConf.getValue().equals("yes");
log("invertXAxis = %b", invertXAxis);
Config invertYAxisConf = getModuleConfig(startModule.getId(), "invertYAxis");
boolean invertYAxis = invertYAxisConf == null || invertYAxisConf.getValue().equals("yes");
log("invertYAxis = %b", invertYAxis);
// sort imageTasks by image position
List<Task> imageTasks = this.workflowRunner.getTaskStatus().select(
where("moduleId", startModule.getId()));
Map<String,Task> imageTaskPosIdx = new TreeMap<String,Task>(new ImageLabelComparator());
for (Task imageTask : imageTasks) {
Config slideIdConf = getTaskConfig(imageTask.getId(), "slideId");
if (poolSlide == null || new Integer(slideIdConf.getValue()).equals(poolSlide.getSlideId())) {
Config imageLabelConf = getTaskConfig(imageTask.getId(), "imageLabel");
if (imageLabelConf != null) {
imageTaskPosIdx.put(imageLabelConf.getValue(), imageTask);
}
}
}
imageTasks.clear();
imageTasks.addAll(imageTaskPosIdx.values());
log("imageTasks = %s", imageTasks);
final String acquisitionTime;
if (!imageTasks.isEmpty()) {
Config acquisitionTimeConf = getTaskConfig(imageTasks.get(0).getId(), "acquisitionTime");
if (acquisitionTimeConf != null) {
try {
acquisitionTime = new SimpleDateFormat("yyyyMMddHHmmss").format(
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse(
acquisitionTimeConf.getValue()));
}
catch (ParseException e) { throw new RuntimeException(e); }
}
else {
acquisitionTime = null;
}
}
else {
acquisitionTime = null;
}
// determine the bounds of the stage coordinates
Double minX_ = null, minY_ = null, maxX = null, maxY = null;
Integer imageWidth_ = null, imageHeight_ = null;
for (Task task : imageTasks) {
MultiStagePosition msp = getMsp(task);
if (minX_ == null || msp.getX() < minX_) minX_ = msp.getX();
if (maxX == null || msp.getX() > maxX) maxX = msp.getX();
if (minY_ == null || msp.getY() < minY_) minY_ = msp.getY();
if (maxY == null || msp.getY() > maxY) maxY = msp.getY();
if (imageWidth_ == null || imageHeight_ == null) {
Config imageIdConf = getTaskConfig(task.getId(), "imageId");
if (imageIdConf != null) {
Image image = imageDao.selectOneOrDie(where("id", new Integer(imageIdConf.getValue())));
log("Getting image size for image %s", image);
ImagePlus imp = null;
try { imp = image.getImagePlus(workflowRunner); }
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Couldn't retrieve image %s from the image cache!%n%s", image, sw);
}
if (imp != null) {
imageWidth_ = imp.getWidth();
imageHeight_ = imp.getHeight();
}
}
}
}
Double minX = minX_, minY = minY_;
Integer imageWidth = imageWidth_, imageHeight = imageHeight_;
log("minX = %f, minY = %f, maxX = %f, maxY = %f, imageWidth = %d, imageHeight = %d",
minX, minY, maxX, maxY, imageWidth, imageHeight);
if (minX != null && minY != null && maxX != null && maxY != null && imageWidth != null && imageHeight != null) {
int slideWidthPx = (int)Math.floor(((maxX - minX) / pixelSize) + (double)imageWidth);
int slideHeightPx = (int)Math.floor(((maxY - minY) / pixelSize) + (double)imageHeight);
log("slideWidthPx = %d, slideHeightPx = %d", slideWidthPx, slideHeightPx);
// this is the scale factor for creating the thumbnail images
double scaleFactor = (double)SLIDE_PREVIEW_WIDTH / (double)slideWidthPx;
log("scaleFactor = %f", scaleFactor);
int slidePreviewHeight = (int)Math.floor(scaleFactor * slideHeightPx);
log("slidePreviewHeight = %d", slidePreviewHeight);
ImagePlus slideThumb = NewImage.createRGBImage("slideThumb", SLIDE_PREVIEW_WIDTH, slidePreviewHeight, 1, NewImage.FILL_WHITE);
Map<Integer,Roi> imageRois = new LinkedHashMap<Integer,Roi>();
List<Roi> roiRois = new ArrayList<Roi>();
Map().attr("name",String.format("map-%s-%s", startModule.getName(), slideName)).with(()->{
// TODO: parallelize
for (Task task : imageTasks) {
Config imageIdConf = getTaskConfig(task.getId(), "imageId");
if (imageIdConf != null) {
MultiStagePosition msp = getMsp(task);
// Get a thumbnail of the image
Image image = imageDao.selectOneOrDie(where("id", new Integer(imageIdConf.getValue())));
log("Working on image; %s", image);
ImagePlus imp = null;
try { imp = image.getImagePlus(workflowRunner); }
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Couldn't retrieve image %s from the image cache!%n%s", image, sw);
}
if (imp != null) {
int width = imp.getWidth(), height = imp.getHeight();
log("Image width: %d, height: %d", width, height);
imp.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR);
imp.setProcessor(imp.getTitle(), imp.getProcessor().resize(
(int)Math.floor(imp.getWidth() * scaleFactor),
(int)Math.floor(imp.getHeight() * scaleFactor)));
log("Resized image width: %d, height: %d", imp.getWidth(), imp.getHeight());
int xloc = (int)Math.floor(((msp.getX() - minX) / pixelSize));
int xlocInvert = invertXAxis? slideWidthPx - (xloc + width) : xloc;
int xlocScale = (int)Math.floor(xlocInvert * scaleFactor);
log("xloc = %d, xlocInvert = %d, xlocScale = %d", xloc, xlocInvert, xlocScale);
int yloc = (int)Math.floor(((msp.getY() - minY) / pixelSize));
int ylocInvert = invertYAxis? slideHeightPx - (yloc + height) : yloc;
int ylocScale = (int)Math.floor(ylocInvert * scaleFactor);
log("yloc = %d, ylocInvert = %d, ylocScale = %d", yloc, ylocInvert, ylocScale);
// draw the thumbnail image
slideThumb.getProcessor().copyBits(imp.getProcessor(), xlocScale, ylocScale, Blitter.COPY);
// save the image ROI for the image map
Roi imageRoi = new Roi(xlocScale, ylocScale, imp.getWidth(), imp.getHeight());
imageRoi.setName(image.getName());
imageRoi.setProperty("id", new Integer(image.getId()).toString());
imageRois.put(image.getId(), imageRoi);
log("imageRoi = %s", imageRoi);
for (ROI roi : roiDao.select(where("imageId", image.getId()))) {
int roiX = (int)Math.floor(xlocScale + (roi.getX1() * scaleFactor));
int roiY = (int)Math.floor(ylocScale + (roi.getY1() * scaleFactor));
int roiWidth = (int)Math.floor((roi.getX2()-roi.getX1()+1) * scaleFactor);
int roiHeight = (int)Math.floor((roi.getY2()-roi.getY1()+1) * scaleFactor);
Roi r = new Roi(roiX, roiY, roiWidth, roiHeight);
r.setName(roi.toString());
r.setProperty("id", new Integer(roi.getId()).toString());
r.setStrokeColor(new Color(1f, 0f, 0f, 0.4f));
r.setStrokeWidth(0.4);
roiRois.add(r);
log("roiRoi = %s", r);
}
}
}
}
// write the ROI areas first so they take precedence
for (Roi roi : roiRois) {
Area().attr("shape","rect").
attr("coords", String.format("%d,%d,%d,%d",
(int)Math.floor(roi.getXBase()),
(int)Math.floor(roi.getYBase()),
(int)Math.floor(roi.getXBase()+roi.getFloatWidth()),
(int)Math.floor(roi.getYBase()+roi.getFloatHeight()))).
attr("href", String.format("#area-ROI-%s", roi.getProperty("id"))).
attr("title", roi.getName());
}
// next write the image ROIs
for (Roi roi : imageRois.values()) {
Area().attr("shape", "rect").
attr("coords", String.format("%d,%d,%d,%d",
(int)Math.floor(roi.getXBase()),
(int)Math.floor(roi.getYBase()),
(int)Math.floor(roi.getXBase()+roi.getFloatWidth()),
(int)Math.floor(roi.getYBase()+roi.getFloatHeight()))).
//attr("title", roi.getName()).
attr("onClick", String.format("report.showImage(%d); return false", new Integer(roi.getProperty("id"))));
}
// now draw the ROI rois in red
for (Roi roiRoi : roiRois) {
slideThumb.getProcessor().setColor(roiRoi.getStrokeColor());
slideThumb.getProcessor().draw(roiRoi);
}
});
// write the slide thumbnail as an embedded HTML image.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try { ImageIO.write(slideThumb.getBufferedImage(), "jpg", baos); }
catch (IOException e) {throw new RuntimeException(e);}
Img().attr("src", String.format("data:image/jpg;base64,%s",
Base64.getMimeEncoder().encodeToString(baos.toByteArray()))).
attr("width", slideThumb.getWidth()).
attr("height", slideThumb.getHeight()).
attr("usemap", String.format("#map-%s-%s", startModule.getName(), slideName)).
attr("class","map stageCoords").
attr("data-min-x", minX - imageWidth / 2.0 * pixelSize * (invertXAxis? -1.0 : 1.0)).
attr("data-max-x", maxX + imageWidth / 2.0 * pixelSize * (invertXAxis? -1.0 : 1.0)).
attr("data-min-y", minY - imageHeight / 2.0 * pixelSize * (invertYAxis? -1.0 : 1.0)).
attr("data-max-y", maxY + imageHeight / 2.0 * pixelSize * (invertYAxis? -1.0 : 1.0)).
attr("style", "border: 1px solid black");
// now render the individual ROI sections
// TODO: parallelize
for (Task task : imageTasks) {
Config imageIdConf = getTaskConfig(task.getId(), "imageId");
if (imageIdConf != null) {
Image image = imageDao.selectOneOrDie(where("id", new Integer(imageIdConf.getValue())));
// make sure this image was included in the slide thumbnail image
if (!imageRois.containsKey(image.getId())) continue;
MultiStagePosition msp = getMsp(task);
List<ROI> rois = roiDao.select(where("imageId", image.getId()));
Collections.sort(rois, (a,b)->a.getId()-b.getId());
for (ROI roi : rois) {
log("Working on ROI: %s", roi);
Hr();
A().attr("name", String.format("area-ROI-%s", roi.getId())).with(()->{
H2().text(String.format("Image %s, ROI %s", image, roi));
});
// go through each attached SlideImager and look for MSP's with an ROI property
// that matches this ROI's ID.
for (Map.Entry<String, Set<String>> entry : roiImagers.entrySet()) {
for (String imagerModuleName : entry.getValue()) {
WorkflowModule imager = this.workflowRunner.getWorkflow().selectOneOrDie(
where("name", imagerModuleName));
// get the hires pixel size for this imager
Config hiResPixelSizeConf = getModuleConfig(imager.getId(), "pixelSize");
Double hiResPixelSize = hiResPixelSizeConf != null? new Double(hiResPixelSizeConf.getValue()) : ROIFinderDialog.DEFAULT_HIRES_PIXEL_SIZE_UM;
log("hiResPixelSize = %f", hiResPixelSize);
// determine the stage coordinate bounds of this ROI tile grid.
// also get the image width and height of the acqusition.
Double minX2_=null, minY2_=null, maxX2_=null, maxY2_=null;
Integer imageWidth2_ = null, imageHeight2_ = null;
Map<String,List<Task>> imagerTasks = new TreeMap<String,List<Task>>(new ImageLabelComparator());
for (Task imagerTask : this.workflowRunner.getTaskStatus().select(
where("moduleId", imager.getId())))
{
Config imageIdConf2 = getTaskConfig(imagerTask.getId(), "imageId");
if (imageIdConf2 != null) {
MultiStagePosition imagerMsp = getMsp(imagerTask);
if (imagerMsp.hasProperty("ROI") && imagerMsp.getProperty("ROI").equals(new Integer(roi.getId()).toString()))
{
TaskConfig imageLabelConf = getTaskConfig(imagerTask.getId(), "imageLabel");
if (imageLabelConf == null ||
imageLabelConf.getValue() == null ||
imageLabelConf.getValue().isEmpty())
{
continue;
}
int[] indices = MDUtils.getIndices(imageLabelConf.getValue());
if (indices != null && indices.length >= 4) {
String imageLabel = MDUtils.generateLabel(indices[0], indices[1], indices[2], 0);
if (!imagerTasks.containsKey(imageLabel)) {
imagerTasks.put(imageLabel, new ArrayList<Task>());
}
imagerTasks.get(imageLabel).add(imagerTask);
if (minX2_ == null || imagerMsp.getX() < minX2_) minX2_ = imagerMsp.getX();
if (minY2_ == null || imagerMsp.getY() < minY2_) minY2_ = imagerMsp.getY();
if (maxX2_ == null || imagerMsp.getX() > maxX2_) maxX2_ = imagerMsp.getX();
if (maxY2_ == null || imagerMsp.getY() > maxY2_) maxY2_ = imagerMsp.getY();
if (imageWidth2_ == null || imageHeight2_ == null) {
Image image2 = imageDao.selectOneOrDie(
where("id", new Integer(imageIdConf2.getValue())));
log("Getting image size for image %s", image2);
ImagePlus imp = null;
try { imp = image2.getImagePlus(workflowRunner); }
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Couldn't retrieve image %s from the image cache!%n%s", image2, sw);
}
if (imp != null) {
imageWidth2_ = imp.getWidth();
imageHeight2_ = imp.getHeight();
}
}
}
}
}
}
Double minX2 = minX2_, minY2 = minY2_, maxX2 = maxX2_, maxY2 = maxY2_;
Integer imageWidth2 = imageWidth2_, imageHeight2 = imageHeight2_;
log("minX2 = %f, minY2 = %f, maxX2 = %f, maxY2 = %f, imageWidth2 = %d, imageHeight2 = %d",
minX2, minY2, maxX2_, maxY2_, imageWidth2_, imageHeight2_);
if (!imagerTasks.isEmpty() &&
minX2 != null &&
minY2 != null &&
maxX2_ != null &&
maxY2_ != null &&
imageWidth2_ != null &&
imageHeight2_ != null)
{
int gridWidthPx = (int)Math.floor(((maxX2_ - minX2_) / hiResPixelSize) + (double)imageWidth2_);
int gridHeightPx = (int)Math.floor(((maxY2_ - minY2_) / hiResPixelSize) + (double)imageHeight2_);
log("gridWidthPx = %d, gridHeightPx = %d", gridWidthPx, gridHeightPx);
// this is the scale factor for creating the thumbnail images
double gridScaleFactor = (double)ROI_GRID_PREVIEW_WIDTH / (double)gridWidthPx;
int gridPreviewHeight = (int)Math.floor(gridScaleFactor * gridHeightPx);
log("gridScaleFactor = %f, gridPreviewHeight = %d", gridScaleFactor, gridPreviewHeight);
ImagePlus roiGridThumb = NewImage.createRGBImage(
String.format("roiGridThumb-%s-ROI%d", imager.getName(), roi.getId()),
ROI_GRID_PREVIEW_WIDTH,
gridPreviewHeight,
1,
NewImage.FILL_WHITE);
log("roiGridThumb: width=%d, height=%d", roiGridThumb.getWidth(), roiGridThumb.getHeight());
Table().attr("class","table table-bordered table-hover table-striped").
with(()->{
Thead().with(()->{
Tr().with(()->{
Th().text("Image Properties");
Th().text("Source ROI Cutout");
Th().text("Tiled ROI Images");
Th().text("Stitched ROI Image");
Th().text("Curation");
});
});
Tbody().with(()->{
for (Map.Entry<String,List<Task>> imagerTaskEntry : imagerTasks.entrySet()) {
String imageLabel = imagerTaskEntry.getKey();
int[] indices = MDUtils.getIndices(imageLabel);
int channel = indices[0], slice = indices[1], frame = indices[2];
log("Working on channel %d, slice %d, frame %d", channel, slice, frame);
Tr().with(()->{
Th().with(()->{
P(String.format("Channel %d, Slice %d, Frame %d", channel, slice, frame));
// get the average stage position of all the tiled ROI images
int posCount = 0;
double xPos = 0.0;
double yPos = 0.0;
for (Task imagerTask : imagerTaskEntry.getValue()) {
MultiStagePosition imagerMsp = getMsp(imagerTask);
Config imageIdConf2 = getTaskConfig(imagerTask.getId(), "imageId");
if (imageIdConf2 != null) {
for (int i=0; i<imagerMsp.size(); ++i) {
StagePosition sp = imagerMsp.get(i);
if (sp.numAxes == 2 && sp.stageName.compareTo(imagerMsp.getDefaultXYStage()) == 0) {
xPos += sp.x;
yPos += sp.y;
++posCount;
break;
}
}
}
}
// add a link to load the slide and go to the stage position
if (posCount > 0) {
Double xPos_ = xPos / posCount;
Double yPos_ = yPos / posCount;
P().with(()->{
A().attr("onClick",
String.format("report.goToPosition(%d,%d,%f,%f); return false",
loaderModule.getId(),
poolSlide != null? poolSlide.getId() : -1,
xPos_,
yPos_)).
text(String.format("Go To Stage Position: (%.2f,%.2f)", xPos_, yPos_));
});
// add another link to put the slide back
if (poolSlide != null) {
P().with(()->{
A().attr("onClick", String.format("report.returnSlide(%d); return false",
loaderModule.getId())).
text("Return slide to loader");
});
}
}
});
Td().with(()->{
ImagePlus imp = null;
try { imp = image.getImagePlus(workflowRunner); }
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Couldn't retrieve image %s from the image cache!%n%s", image, sw);
}
if (imp != null) {
imp.setRoi(new Roi(roi.getX1(), roi.getY1(), roi.getX2()-roi.getX1()+1, roi.getY2()-roi.getY1()+1));
double roiScaleFactor = (double)ROI_GRID_PREVIEW_WIDTH / (double)(roi.getX2()-roi.getX1()+1);
int roiPreviewHeight = (int)Math.floor((roi.getY2()-roi.getY1()+1) * roiScaleFactor);
imp.setProcessor(imp.getTitle(), imp.getProcessor().crop().resize(
ROI_GRID_PREVIEW_WIDTH,
roiPreviewHeight));
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
//String dirs = new File(reportDir, reportFile).getPath().replaceAll("\\.html$", "");
//new File(dirs).mkdirs();
//new FileSaver(imp).saveAsJpeg(new File(dirs, String.format("ROI%s.roi_thumbnail.jpg", roi.getId())).getPath());
try { ImageIO.write(imp.getBufferedImage(), "jpg", baos2); }
catch (IOException e) {throw new RuntimeException(e);}
ImagePlus imp_ = imp;
A().attr("onClick", String.format("report.showImage(%d); return false", image.getId())).
with(()->{
Img().attr("src", String.format("data:image/jpg;base64,%s",
Base64.getMimeEncoder().encodeToString(baos2.toByteArray()))).
attr("width", ROI_GRID_PREVIEW_WIDTH).
attr("data-min-x", msp.getX() + (roi.getX1() - (imp_.getWidth() / 2.0)) * pixelSize * (invertXAxis? -1.0 : 1.0)).
attr("data-max-x", msp.getX() + (roi.getX2() - (imp_.getWidth() / 2.0)) * pixelSize * (invertXAxis? -1.0 : 1.0)).
attr("data-min-y", msp.getY() + (roi.getY1() - (imp_.getHeight() / 2.0)) * pixelSize * (invertYAxis? -1.0 : 1.0)).
attr("data-max-y", msp.getY() + (roi.getY2() - (imp_.getHeight() / 2.0)) * pixelSize * (invertYAxis? -1.0 : 1.0)).
//attr("title", roi.toString()).
attr("class", "stageCoords");
});
}
});
Td().with(()->{
List<Runnable> makeLinks = new ArrayList<>();
Map().attr("name", String.format("map-roi-%s-ROI%d", imager.getName(), roi.getId())).with(()->{
for (Task imagerTask : imagerTaskEntry.getValue()) {
Config imageIdConf2 = getTaskConfig(imagerTask.getId(), "imageId");
if (imageIdConf2 != null) {
MultiStagePosition imagerMsp = getMsp(imagerTask);
// Get a thumbnail of the image
Image image2 = imageDao.selectOneOrDie(where("id", new Integer(imageIdConf2.getValue())));
ImagePlus imp = null;
try { imp = image2.getImagePlus(workflowRunner); }
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Couldn't retrieve image %s from the image cache!%n%s", image2, sw);
}
if (imp != null) {
int width = imp.getWidth(), height = imp.getHeight();
log("imp: width=%d, height=%d", width, height);
imp.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR);
imp.setProcessor(imp.getTitle(), imp.getProcessor().resize(
(int)Math.floor(imp.getWidth() * gridScaleFactor),
(int)Math.floor(imp.getHeight() * gridScaleFactor)));
log("imp: resized width=%d, height=%d", imp.getWidth(), imp.getHeight());
int xloc = (int)Math.floor((imagerMsp.getX() - minX2) / hiResPixelSize);
int xlocInvert = invertXAxis? gridWidthPx - (xloc + width) : xloc;
int xlocScale = (int)Math.floor(xlocInvert * gridScaleFactor);
log("xloc=%d, xlocInvert=%d, xlocScale=%d", xloc, xlocInvert, xlocScale);
int yloc = (int)Math.floor((imagerMsp.getY() - minY2) / hiResPixelSize);
int ylocInvert = invertYAxis? gridHeightPx - (yloc + height) : yloc;
int ylocScale = (int)Math.floor(ylocInvert * gridScaleFactor);
log("yloc=%d, ylocInvert=%d, ylocScale=%d", yloc, ylocInvert, ylocScale);
roiGridThumb.getProcessor().copyBits(imp.getProcessor(), xlocScale, ylocScale, Blitter.COPY);
Roi tileRoi = new Roi(xlocScale, ylocScale, imp.getWidth(), imp.getHeight());
// make the tile image clickable
Area().attr("shape", "rect").
attr("coords", String.format("%d,%d,%d,%d",
(int)Math.floor(tileRoi.getXBase()),
(int)Math.floor(tileRoi.getYBase()),
(int)Math.floor(tileRoi.getXBase()+tileRoi.getFloatWidth()),
(int)Math.floor(tileRoi.getYBase()+tileRoi.getFloatHeight()))).
attr("title", image2.getName()).
attr("onClick", String.format("report.showImage(%d); return false", image2.getId()));
makeLinks.add(()->{
P().with(()->{
A().attr("onClick",String.format("report.checkPosCalibration(%d,%d,%f,%f,%f,%f,%f,%f,%f,%f); return false",
image.getId(),
image2.getId(),
pixelSize,
hiResPixelSize,
invertXAxis? -1.0 : 1.0,
invertYAxis? -1.0 : 1.0,
msp.getX(),
msp.getY(),
imagerMsp.getX(),
imagerMsp.getY())).
text(String.format("Check pos calibration for image %s", image2.getName()));
});
});
}
}
}
});
//String dirs = new File(reportDir, reportFile).getPath().replaceAll("\\.html$", "");
//new File(dirs).mkdirs();
//new FileSaver(roiGridThumb).saveAsJpeg(new File(dirs, String.format("ROI%s.grid_thumbnail.jpg", roi.getId())).getPath());
// write the grid thumbnail as an embedded HTML image.
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
try { ImageIO.write(roiGridThumb.getBufferedImage(), "jpg", baos2); }
catch (IOException e) {throw new RuntimeException(e);}
Img().attr("src", String.format("data:image/jpg;base64,%s",
Base64.getMimeEncoder().encodeToString(baos2.toByteArray()))).
attr("width", ROI_GRID_PREVIEW_WIDTH).
attr("class", "map stageCoords").
attr("data-min-x", minX2 - imageWidth2 / 2.0 * hiResPixelSize * (invertXAxis? -1.0 : 1.0)).
attr("data-max-x", maxX2 + imageWidth2 / 2.0 * hiResPixelSize * (invertXAxis? -1.0 : 1.0)).
attr("data-min-y", minY2 - imageHeight2 / 2.0 * hiResPixelSize * (invertYAxis? -1.0 : 1.0)).
attr("data-max-y", maxY2 + imageHeight2 / 2.0 * hiResPixelSize * (invertYAxis? -1.0 : 1.0)).
attr("usemap", String.format("#map-roi-%s-ROI%d", imager.getName(), roi.getId()));
for (Runnable r : makeLinks) {
r.run();
}
});
List<String> stitchedImageFiles = new ArrayList<>();
Td().with(()->{
// get the downstream stitcher tasks
Set<Task> stitcherTasks = new HashSet<Task>();
for (Task imagerTask : imagerTaskEntry.getValue()) {
for (TaskDispatch td : this.workflowRunner.getTaskDispatch().select(where("parentTaskId", imagerTask.getId()))) {
Task stitcherTask = this.workflowRunner.getTaskStatus().selectOneOrDie(
where("id", td.getTaskId()));
Config canStitchImages = getModuleConfig(stitcherTask.getModuleId(), "canStitchImages");
if (canStitchImages != null &&
"yes".equals(canStitchImages.getValue()) &&
stitcherTask.getStatus().equals(Status.SUCCESS))
{
stitcherTasks.add(stitcherTask);
}
}
}
for (Task stitcherTask : stitcherTasks) {
log("Working on stitcher task: %s", stitcherTask);
Config stitchedImageConf = getTaskConfig(stitcherTask.getId(), "stitchedImageFile");
if (stitchedImageConf != null && stitchedImageConf.getValue() != null && !stitchedImageConf.getValue().isEmpty()) {
String stitchedImage = stitchedImageConf.getValue();
if (!Paths.get(stitchedImage).isAbsolute()) {
stitchedImage = Paths.get(workflowRunner.getWorkflowDir().getPath()).resolve(Paths.get(stitchedImage)).toString();
}
if (!new File(stitchedImage).exists()) continue;
// see if there is an edited image. If so, display that instead.
String editedImagePath = getEditedImagePath(stitchedImage);
// if there is no edited image, attempt to auto-rotate the image
if (!new File(editedImagePath).exists()) {
ImagePlus imp = new ImagePlus(stitchedImage);
try {
ImagePlus imp2 = autoRotateImage(imp);
if (imp2 != null) {
new FileSaver(imp2).saveAsTiff(editedImagePath);
}
}
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Error when running autoRotateImage: %s", sw);
}
}
String stitchedImagePath = editedImagePath != null && new File(editedImagePath).exists()?
editedImagePath :
stitchedImage;
log("stitchedImagePath = %s", stitchedImagePath);
String stitchedImageRelPath;
stitchedImageRelPath = Paths.get(workflowRunner.getWorkflowDir().getPath()).relativize(Paths.get(stitchedImage)).toString();
stitchedImageFiles.add(stitchedImageRelPath);
// Get a thumbnail of the image
ImagePlus imp = new ImagePlus(stitchedImagePath);
if (imp == null || imp.getProcessor() == null) {
log("imp == null, skipping stitched image");
continue;
}
log("stitchedImage width = %d, height = %d", imp.getWidth(), imp.getHeight());
// crop the image
cropImage(imp);
// resize the image to thumbnail size
double stitchScaleFactor = (double)ROI_GRID_PREVIEW_WIDTH / (double)imp.getWidth();
log("stitchScaleFactor = %f", stitchScaleFactor);
int stitchPreviewHeight = (int)Math.floor(imp.getHeight() * stitchScaleFactor);
log("stitchPreviewHeight = %d", stitchPreviewHeight);
imp.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR);
imp.setProcessor(imp.getTitle(), imp.getProcessor().resize(
ROI_GRID_PREVIEW_WIDTH,
stitchPreviewHeight));
log("resized stitched image width=%d, height=%d", imp.getWidth(), imp.getHeight());
//String dirs = new File(reportDir, reportFile).getPath().replaceAll("\\.html$", "");
//new File(dirs).mkdirs();
//new FileSaver(imp).saveAsJpeg(new File(dirs, String.format("ROI%s.stitched_thumbnail.jpg", roi.getId())).getPath());
// write the stitched thumbnail as an embedded HTML image.
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
try { ImageIO.write(imp.getBufferedImage(), "jpg", baos2); }
catch (IOException e) {
throw new RuntimeException(e);
}
A().attr("onClick", String.format("report.showImageFile(\"%s\"); return false",
Util.escapeJavaStyleString(stitchedImageRelPath))).
with(()->{
Img().attr("src", String.format("data:image/jpg;base64,%s",
Base64.getMimeEncoder().encodeToString(baos2.toByteArray()))).
attr("width", ROI_GRID_PREVIEW_WIDTH).
attr("class", "stitched").
attr("data-path", stitchedImageRelPath).
attr("data-timestamp",
new SimpleDateFormat("yyyy-MM-dd.HH:mm:ss").format(
new File(stitchedImagePath).lastModified())).
attr("id", new File(stitchedImageRelPath).getName()).
attr("title", stitchedImageRelPath);
});
P().with(()->{
A().attr("onClick", String.format("report.flip(\"%s\", true, false); return false",
Util.escapeJavaStyleString(stitchedImageRelPath))).
text("Flip Horizontally");
text(" ");
A().attr("onClick", String.format("report.flip(\"%s\", false, true); return false",
Util.escapeJavaStyleString(stitchedImageRelPath))).
text("Flip Vertically");
});
}
}
});
// Curation buttons
String[] orientations = new String[]{"lateral","ventral","dorsal"};
String[] stages = new String[]{"1-3","4-6","7-8","9-10","11-12","13-16"};
String experimentId = String.format("%s.%s",
poolSlide != null && slide != null? String.format("C%sS%s.SLIDE%s.%s",
poolSlide.getCartridgePosition(),
poolSlide.getSlidePosition(),
slide.getId(),
slide.getExperimentId()) :
slide != null? String.format("SLIDE%s.%s",
slide.getId(),
slide.getExperimentId()) :
acquisitionTime != null? acquisitionTime :
"slide",
roi.getId()).replaceAll("[\\/ :_]+",".");
Td().with(()->{
Table().with(()->{
Tbody().with(()->{
for (String orientation : orientations) {
Tr().with(()->{
for (String stage : stages) {
Td().with(()->{
StringBuilder sb = new StringBuilder();
for (String stitchedImageFile : stitchedImageFiles) {
sb.append(String.format("report.curate(\"%s\",\"%s\",\"%s\",\"%s\");",
Util.escapeJavaStyleString(stitchedImageFile),
Util.escapeJavaStyleString(experimentId),
Util.escapeJavaStyleString(orientation),
Util.escapeJavaStyleString(stage)));
}
Button(String.format("%s %s", orientation, stage)).
attr("type","button").
attr("onclick", sb.toString());
});
}
});
}
});
});
});
});
}
});
});
}
}
}
}
}
}
}
}
public void showImage(int imageId) {
//log("called showImage(imageId=%d)", imageId);
Dao<Image> imageDao = this.workflowRunner.getWorkflowDb().table(Image.class);
Image image = imageDao.selectOneOrDie(where("id", imageId));
ImagePlus imp = image.getImagePlus(workflowRunner);
imp.show();
}
public void goToPosition(Integer loaderModuleId, int poolSlideId, double xPos, double yPos) {
synchronized(this) {
Dao<PoolSlide> poolSlideDao = this.workflowRunner.getWorkflowDb().table(PoolSlide.class);
PoolSlide poolSlide = poolSlideId > 0? poolSlideDao.selectOne(where("id", poolSlideId)) : null;
SwingUtilities.invokeLater(()->{
Double xPos_ = xPos;
Double yPos_ = yPos;
PoolSlide poolSlide_ = poolSlide;
Integer loaderModuleId_ = loaderModuleId;
Integer poolSlideId_ = poolSlideId;
Integer cartridgePosition = poolSlide_.getCartridgePosition();
Integer slidePosition = poolSlide_.getSlidePosition();
String slideMessage = poolSlide_ != null && loaderModuleId_ != null && prevPoolSlideId != poolSlideId_?
String.format(" on cartridge %d, slide %d?", cartridgePosition, slidePosition)
: "?";
String message = String.format("Would you like to move the stage to position (%.2f,%.2f)%s",
xPos_, yPos_, slideMessage);
if (JOptionPane.showConfirmDialog(null,
message,
"Move To Position",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{
new Thread(()->{
// load the slide
if (poolSlideId_ > 0 && loaderModuleId_ != null && this.prevPoolSlideId != poolSlideId_) {
WorkflowModule loaderModule = this.workflowRunner.getWorkflow().selectOneOrDie(
where("id", loaderModuleId_));
Module module = this.workflowRunner.getModuleInstances().get(loaderModule.getId());
if (module == null) throw new RuntimeException(String.format("Could not find instance for module %s!", loaderModule));
// init loader and scan for slides
if (this.isLoaderInitialized.get(loaderModuleId_) == null || !this.isLoaderInitialized.get(loaderModuleId_)) {
try {
Method initSlideLoader = module.getClass().getDeclaredMethod("initSlideLoader", boolean.class);
initSlideLoader.invoke(module, true);
Method scanForSlides = module.getClass().getDeclaredMethod("scanForSlides");
scanForSlides.invoke(module);
this.isLoaderInitialized.put(loaderModuleId_, true);
}
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Couldn't scan for slides!%n%s", sw);
return;
}
}
// unload the previous slide first
if (this.prevPoolSlideId != null) {
PoolSlide prevPoolSlide = poolSlideDao.selectOneOrDie(where("id", prevPoolSlideId));
try {
Method unloadSlide = module.getClass().getDeclaredMethod("unloadSlide", PoolSlide.class);
unloadSlide.invoke(module, prevPoolSlide);
}
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Couldn't unload slide %s from stage!%n%s", prevPoolSlide, sw);
return;
}
}
// now load the slide
try {
Method loadSlide = module.getClass().getDeclaredMethod("loadSlide", PoolSlide.class);
loadSlide.invoke(module, poolSlide_);
// set previous pool slide to this slide
this.prevPoolSlideId = poolSlideId_;
}
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Couldn't unload slide %s from stage!%n%s", poolSlide, sw);
return;
}
}
// move the stage
CMMCore core = MMStudio.getInstance().getMMCore();
try { SlideImager.moveStage(this.getClass().getSimpleName(), core, xPos_, yPos_, null); }
catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Error while attempting to move stage to coordinates: (%.2f,%.2f)%n%s", xPos_, yPos_, sw);
return;
}
// autofocus?
SwingUtilities.invokeLater(()->{
if (JOptionPane.showConfirmDialog(null,
"Autofocus now?",
"Move To Position",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{
new Thread(()->{
MMStudio.getInstance().autofocusNow();
}).start();
}
});
}).start();
}
});
}
}
public void returnSlide(Integer loaderModuleId) {
synchronized(this) {
if (this.prevPoolSlideId != null) {
SwingUtilities.invokeLater(()->{
if (JOptionPane.showConfirmDialog(null,
String.format("Would you like to return the slide to the loader?"),
"Return Slide to Stage",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{
new Thread(()->{
WorkflowModule loaderModule = this.workflowRunner.getWorkflow().selectOneOrDie(
where("id", loaderModuleId));
Module module = this.workflowRunner.getModuleInstances().get(loaderModule.getId());
if (module == null) throw new RuntimeException(String.format("Could not find instance for module %s!", loaderModule));
Dao<PoolSlide> poolSlideDao = this.workflowRunner.getWorkflowDb().table(PoolSlide.class);
PoolSlide prevPoolSlide = poolSlideDao.selectOneOrDie(where("id", prevPoolSlideId));
try {
Method unloadSlide = module.getClass().getDeclaredMethod("unloadSlide", PoolSlide.class);
unloadSlide.invoke(module, prevPoolSlide);
this.prevPoolSlideId = null;
}
catch (Throwable e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log("Couldn't unload slide %s from stage!%n%s", prevPoolSlide, sw);
return;
}
}).start();
}
});
}
}
}
public void showInstructions() {
if (alert == null) {
String instructions = Div().with(()->{
H1("Manual Curation Instructions:");
Ul().with(()->{
Li("Make sure image or Fiji toolbar is in focus");
Li("To flip the image horizontally, select Image -> Transform - Flip Horizontally from the menu");
Li("To flip the image vertically, select Image -> Transform - Flip Vertically from the menu");
Li("Rotation").with(()->{
Ul().with(()->{
Li("To rotate the image, select Image -> Transform -> Rotate");
Li("Check the \"Preview\" box to see the rotated image");
Li("Select the angle of rotation");
});
});
Li("Cropping").with(()->{
Ul().with(()->{
Li("To crop the image, first select Edit -> Selection -> Specify from the menu");
Li(String.format("Set the width to %s and the height to %s", CURATE_IMAGE_WIDTH, CURATE_IMAGE_HEIGHT));
Li("Using the mouse, drag the upper-left corner of the selection box to the upper-left corner of the ROI shape");
Li("Hold down the ALT key, then using the mouse, drag the lower-right corner of the selection box to the lower-right corner of the ROI shape");
Li("Using the mouse, drag the selection box to reposition the selection box until it completely covers the ROI shape");
Li("Once the selection box is positioned correctly, select Image -> Crop from the menu");
});
});
Li("Resizing").with(()->{
Ul().with(()->{
Li("To resize the image, select Image -> Adjust -> Size from the menu");
Li(String.format("Set the width to %s and the height to %s", CURATE_IMAGE_WIDTH, CURATE_IMAGE_HEIGHT));
Li("Uncheck constrain aspect ratio if necessary");
});
});
Li("To save the edited image, select File -> Save from the menu");
Li("To close the edited image window, select File -> Close from the menu");
Li("The updated image should now appear in the report page. Press a curation button to transfer the file into the database");
});
}).toString();
alert = new Alert(AlertType.INFORMATION);
alert.initModality(Modality.NONE);
alert.setHeaderText("Manual Curation Instructions");
WebView webView = new WebView();
webView.getEngine().loadContent(instructions);
webView.setPrefSize(1280, 1024);
alert.getDialogPane().setContent(webView);
}
alert.show();
}
private Map<String,Boolean> changedImages = new HashMap<>();
private String getEditedImagePath(String imagePath) {
return imagePath.replaceFirst("([.][^.]+)?$", ".edited$1");
}
public synchronized String changedImages() {
List<String> changedImageList = new ArrayList<>();
for (Map.Entry<String,Boolean> entry : changedImages.entrySet()) {
String imagePath = entry.getKey();
String editedImagePath = getEditedImagePath(imagePath);
File editedImageFile = new File(editedImagePath);
Boolean changed = entry.getValue();
ImagePlus imp = WindowManager.getImage(editedImageFile.getName());
if (imp == null) {
changedImages.remove(imagePath);
changedImageList.add(imagePath);
}
else if (imp.changes != changed) {
changedImageList.add(imagePath);
}
}
String changedImages = String.join("\n", changedImageList);
//IJ.log(String.format("changedImages=%s", changedImages));
return changedImages;
}
public boolean isEdited(String imagePath) {
if (!Paths.get(imagePath).isAbsolute()) {
imagePath = Paths.get(workflowRunner.getWorkflowDir().getPath()).resolve(Paths.get(imagePath)).toString();
}
String editedImagePath = getEditedImagePath(imagePath);
File editedImageFile = new File(editedImagePath);
return editedImageFile.exists();
}
public String getImageBase64(String imagePath) {
if (!Paths.get(imagePath).isAbsolute()) {
imagePath = Paths.get(workflowRunner.getWorkflowDir().getPath()).resolve(Paths.get(imagePath)).toString();
}
String editedImagePath = getEditedImagePath(imagePath);
File editedImageFile = new File(editedImagePath);
ImagePlus imp = editedImageFile.exists()? new ImagePlus(editedImagePath) : new ImagePlus(imagePath);
cropImage(imp);
double stitchScaleFactor = (double)ROI_GRID_PREVIEW_WIDTH / (double)imp.getWidth();
int stitchPreviewHeight = (int)Math.floor(imp.getHeight() * stitchScaleFactor);
imp.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR);
imp.setProcessor(imp.getTitle(), imp.getProcessor().resize(
ROI_GRID_PREVIEW_WIDTH,
stitchPreviewHeight));
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
try { ImageIO.write(imp.getBufferedImage(), "jpg", baos2); }
catch (IOException e) {throw new RuntimeException(e);}
String base64 = String.format("data:image/jpg;base64,%s",
Base64.getMimeEncoder().encodeToString(baos2.toByteArray()));
//IJ.log(String.format("image=%s, base64=%s", imagePath, base64));
return base64;
}
public synchronized void showImageFile(String imagePath) {
if (!Paths.get(imagePath).isAbsolute()) {
imagePath = Paths.get(workflowRunner.getWorkflowDir().getPath()).resolve(Paths.get(imagePath)).toString();
}
//log("called showImageFile(imagePath=%s)", imagePath);
String editedImagePath = getEditedImagePath(imagePath);
File editedImageFile = new File(editedImagePath);
ImagePlus imp = WindowManager.getImage(editedImageFile.getName());
if (imp == null) {
File imageFile = new File(imagePath);
if (!imageFile.exists()) {
throw new RuntimeException(String.format("Could not find image file %s!", imagePath));
}
if (editedImageFile.exists()) {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Confirmation Dialog");
alert.setHeaderText("Keep your edits?");
alert.setContentText(String.format("Edited file %s already exists, keep your edits?", editedImagePath));
alert.getButtonTypes().clear();
alert.getButtonTypes().addAll(ButtonType.YES, ButtonType.NO);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.NO) {
try { Files.copy(imageFile, editedImageFile); }
catch (IOException e) {throw new RuntimeException(e);}
}
}
else {
try { Files.copy(imageFile, editedImageFile); }
catch (IOException e) {throw new RuntimeException(e);}
}
imp = new ImagePlus(editedImagePath);
}
showInstructions();
imp.show();
changedImages.put(imagePath, imp.changes);
}
public static final int CURATE_IMAGE_WIDTH = 1520;
public static final int CURATE_IMAGE_HEIGHT = 1080;
public void cropImage(ImagePlus imp) {
// resize to smaller source dimension maintaining aspect ratio
int image_width = imp.getWidth() < imp.getHeight()?
CURATE_IMAGE_WIDTH :
(int)Math.ceil((double)imp.getWidth()*((double)CURATE_IMAGE_HEIGHT/(double)imp.getHeight()));
int image_height = imp.getWidth() < imp.getHeight()?
(int)Math.ceil((double)imp.getHeight()*((double)CURATE_IMAGE_WIDTH/(double)imp.getWidth())) :
CURATE_IMAGE_HEIGHT;
imp.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR);
ImageProcessor proc;
try {
proc = imp.getProcessor().resize(image_width, image_height);
}
catch (Throwable e) {
log("Could not resize image %s with width %s, height %s:%n%s", imp, image_width, image_height, e);
return;
}
imp.setProcessor(imp.getTitle(), proc);
// then do a centered crop
ImageProcessor processor = imp.getProcessor();
processor.setRoi(
Math.max(0, (int)Math.floor(((double)imp.getWidth()/2.0) - ((double)CURATE_IMAGE_WIDTH/2.0))),
Math.max(0, (int)Math.floor(((double)imp.getHeight()/2.0) - ((double)CURATE_IMAGE_HEIGHT/2.0))),
CURATE_IMAGE_WIDTH, CURATE_IMAGE_HEIGHT);
processor = processor.crop();
imp.setProcessor(imp.getTitle(), processor);
}
/**
* If the user presses a curation button, copy and rename the stitched image into the curation folder.
* @param stitchedImagePath The path to the stitched image
* @param orientation The embryo's orientation
* @param stage Curated timepoint in hours
*/
public void curate(String stitchedImagePath, String experimentId, String orientation, String stage) {
if (!Paths.get(stitchedImagePath).isAbsolute()) {
stitchedImagePath = Paths.get(workflowRunner.getWorkflowDir().getPath()).resolve(Paths.get(stitchedImagePath)).toString();
}
// /data/insitu_images/images/stage${stage}/lm(l|d|v)_${experiment_id}_${stage}.jpg
String imagesFolder = "/data/insitu_images/images";
String stageFolderName = String.format("stage%s",stage);
String fileName = String.format("lm%s_%s_%s.jpg", orientation.charAt(0), experimentId, stage);
String outputFile = Paths.get(imagesFolder, stageFolderName, fileName).toString();
String editedImagePath = getEditedImagePath(stitchedImagePath);
File editedImageFile = new File(editedImagePath);
ImagePlus imp = editedImageFile.exists()? new ImagePlus(editedImagePath) : new ImagePlus(stitchedImagePath);
cropImage(imp);
if (new FileSaver(imp).saveAsJpeg(outputFile)) {
this.webEngine.executeScript(String.format(
"(function(f,d){$.notify('Image \"'+f+'\" was created in \"'+d+'\".','success')})(\"%s\",\"%s\")",
Util.escapeJavaStyleString(fileName),
Util.escapeJavaStyleString(Paths.get(imagesFolder, stageFolderName).toString())));
}
else {
this.webEngine.executeScript(String.format(
"(function(f){$.notify('Failed to write image \"'+f+'\"!','error')})(\"%s\")",
Util.escapeJavaStyleString(outputFile)));
}
}
public void goToURL(String url) {
try { url = Paths.get(this.reportDir).resolve(url).toUri().toURL().toString(); }
catch (MalformedURLException e) {throw new RuntimeException(e);}
this.webEngine.load(url);
}
public void checkPosCalibration(
int image1Id,
int image2Id,
double pixelSize,
double hiResPixelSize,
double invertX,
double invertY,
double image1X,
double image1Y,
double image2X,
double image2Y)
{
Dao<Image> imageDao = this.workflowRunner.getWorkflowDb().table(Image.class);
Image image1 = imageDao.selectOneOrDie(where("id", image1Id));
ImagePlus imp1 = image1.getImagePlus(workflowRunner);
Image image2 = imageDao.selectOneOrDie(where("id", image2Id));
ImagePlus imp2 = image2.getImagePlus(workflowRunner);
imp2.setProcessor(imp2.getProcessor().resize(
(int)Math.floor(imp2.getWidth() * (hiResPixelSize / pixelSize)),
(int)Math.floor(imp2.getHeight() * (hiResPixelSize / pixelSize))));
int roiX = (int)Math.floor((image2X - image1X) / pixelSize * invertX + (imp1.getWidth() / 2.0) - (imp2.getWidth() / 2.0));
int roiY = (int)Math.floor((image2Y - image1Y) / pixelSize * invertY + (imp1.getHeight() / 2.0) - (imp2.getHeight() / 2.0));
int roiWidth = imp2.getWidth();
int roiHeight = imp2.getHeight();
ImageRoi roi = new ImageRoi(roiX, roiY, imp2.getProcessor());
roi.setName(image2.getName());
roi.setOpacity(0.3);
Overlay overlayList = imp1.getOverlay();
if (overlayList == null) overlayList = new Overlay();
overlayList.add(roi);
imp1.setOverlay(overlayList);
// pop open the window
imp1.setHideOverlay(false);
imp1.show();
// wait for window to close, then calculate the ROI diff
imp1.getWindow().addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent e) {
Overlay overlayList = imp1.getOverlay();
if (overlayList != null) {
for (int i=0; i<overlayList.size(); ++i) {
Roi roi2 = overlayList.get(i);
if (Objects.equals(roi2.getName(), image2.getName())) {
int diffXPx = (int)Math.floor(
(roi2.getXBase() + roi2.getFloatWidth() / 2.0)
- (roiX + roiWidth / 2.0));
int diffYPx = (int)Math.floor(
(roi2.getYBase() + roi2.getFloatHeight() / 2.0)
- (roiY + roiHeight / 2.0));
double diffX = diffXPx * pixelSize * invertX;
double diffY = diffYPx * pixelSize * invertY;
// write the diff to the log and stderr
String message = String.format("PosCalibrator\tref_image\t%s\tcompare_image\t%s\tpixel_offset\t%d\t%d\tstage_offset\t%.2f\t%.2f",
image1.getName(), image2.getName(), diffXPx, diffYPx, diffX, diffY);
IJ.log(message);
System.err.println(message);
}
}
}
}
});
}
private MultiStagePosition getMsp(Task task) {
MultiStagePosition msp = this.msps.get(task.getId());
if (msp == null) throw new RuntimeException(String.format("Could not find MSP conf for task %s!", task));
return msp;
}
private ImagePlus autoRotateImage(ImagePlus imp) {
log("called autoRotateImage(imp=%s)", imp);
// create the image we will use to determine the angle of rotation
ImagePlus imp2 = new ImagePlus();
imp2.setProcessor(imp.getProcessor().duplicate());
// create the return image
ImagePlus imp3 = new ImagePlus();
imp3.setProcessor(imp.getProcessor().duplicate());
// convert image to 8-bit
IJ.run(imp2, "8-bit", "");
// crop out black rectangles
int x1 = 0;
int x2 = imp2.getWidth()-1;
int y1 = 0;
int y2 = imp2.getHeight()-1;
int cropX1 = -1;
int cropX2 = -1;
int cropY1 = -1;
int cropY2 = -1;
while ((cropX1 < 0 || cropY1 < 0 || cropX2 < 0 || cropY2 < 0) && x1 < x2 && y1 < y2) {
if (cropX1 < 0) {
int black=0;
for (int y=y1; y<=y2; ++y) {
int value = imp2.getPixel(x1, y)[0];
if (value == 0) {
++x1;
++black;
break;
}
}
if (black == 0) {
cropX1 = x1;
}
}
if (cropX2 < 0) {
int black=0;
for (int y=y1; y<=y2; ++y) {
int value = imp2.getPixel(x2, y)[0];
if (value == 0) {
--x2;
++black;
break;
}
}
if (black == 0) {
cropX2 = x2;
}
}
if (cropY1 < 0) {
int black=0;
for (int x=x1; x<=x2; ++x) {
int value = imp2.getPixel(x, y1)[0];
if (value == 0) {
++y1;
++black;
break;
}
}
if (black == 0) {
cropY1 = y1;
}
}
if (cropY2 < 0) {
int black=0;
for (int x=x1; x<=x2; ++x) {
int value = imp2.getPixel(x, y2)[0];
if (value == 0) {
--y2;
++black;
break;
}
}
if (black == 0) {
cropY2 = y2;
}
}
}
// cropping failed
final double MIN_SIZE_RATIO = 0.4;
final int MIN_WIDTH = (int)Math.floor(imp.getWidth()*MIN_SIZE_RATIO);
final int MIN_HEIGHT = (int)Math.floor(imp.getHeight()*MIN_SIZE_RATIO);
if ((cropX1<0 || cropY1<0 || cropX2<0 || cropY2<0) || !(cropX1+MIN_WIDTH < cropX2 && cropY1+MIN_HEIGHT < cropY2)) {
return null;
}
imp2.setRoi(new Roi(cropX1, cropY1, cropX2-cropX1+1, cropY2-cropY1+1));
imp2.setProcessor(imp2.getTitle(), imp2.getProcessor().crop());
// scale to width 200, keep aspect ratio
final int SCALE_WIDTH = 200;
double scaleFactor = (double)SCALE_WIDTH / (double)imp2.getWidth();
imp2.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR);
imp2.setProcessor(imp2.getTitle(), imp2.getProcessor().resize(
(int)Math.floor(imp2.getWidth() * scaleFactor),
(int)Math.floor(imp2.getHeight() * scaleFactor)));
// subtract background
IJ.run(imp2, "Subtract Background...", "rolling=20 light sliding");
// run threshold
IJ.setAutoThreshold(imp2, "Triangle");
// despeckle 5x
IJ.run(imp, "Despeckle", "");
IJ.run(imp, "Despeckle", "");
IJ.run(imp, "Despeckle", "");
IJ.run(imp, "Despeckle", "");
IJ.run(imp, "Despeckle", "");
// run gray morphology erode
IJ.run(imp2, "Gray Morphology", "radius=7 type=circle operator=erode");
// analyze particles to get angle of rotation
ResultsTable rt = new ResultsTable();
ParticleAnalyzer particleAnalyzer = new ParticleAnalyzer(
ParticleAnalyzer.EXCLUDE_EDGE_PARTICLES|
ParticleAnalyzer.CLEAR_WORKSHEET|
ParticleAnalyzer.IN_SITU_SHOW,
Measurements.AREA|
Measurements.MEAN|
Measurements.MIN_MAX|
Measurements.CENTER_OF_MASS|
Measurements.RECT|
Measurements.SHAPE_DESCRIPTORS|
Measurements.ELLIPSE|
Measurements.PERIMETER|
Measurements.AREA_FRACTION,
rt, 20.0, Double.POSITIVE_INFINITY);
if (!particleAnalyzer.analyze(imp2)) {
// particle analyzer failed
return null;
}
// Get the largest object
double maxArea = 0.0;
int largest = -1;
for (int i=0; i < rt.getCounter(); i++) {
double area = rt.getValue("Area", i);
if (maxArea < area) {
maxArea = area;
largest = i;
}
}
if (largest < 0) {
// particle analyzer returned no results
return null;
}
double bx = rt.getValue("BX", largest) / scaleFactor;
//double by = rt.getValue("BY", largest) / scaleFactor;
double width = rt.getValue("Width", largest) / scaleFactor;
//double height = rt.getValue("Height", largest) / scaleFactor;
double major = rt.getValue("Major", largest) / scaleFactor;
//double minor = rt.getValue("Minor", largest) / scaleFactor;
double angle = rt.getValue("Angle", largest);
double centerX = bx+(width/2.0);
//double centerY = by+(height/2.0);
// compute histogram of pixel color values
Map<Integer,Long> histo = new HashMap<>();
for (int y=0; y<imp3.getHeight(); ++y) {
for (int x=0; x<imp3.getWidth(); ++x) {
int[] pixel = imp3.getPixel(x, y);
if (pixel.length >= 3) {
int value = new Color(pixel[0], pixel[1], pixel[2]).getRGB();
histo.put(value, histo.getOrDefault(value, 0L)+1L);
}
else if (pixel.length >= 1) {
histo.put(pixel[0], histo.getOrDefault(pixel[0], 0L)+1L);
}
}
}
// get the modal color value for the image
int mode = 0;
long modeCount = 0;
for (Map.Entry<Integer,Long> entry : histo.entrySet()) {
if (modeCount < entry.getValue()) {
mode = entry.getKey();
modeCount = entry.getValue();
}
}
// set the background color to the modal color value
imp3.getProcessor().setBackgroundValue(mode);
// rotate by that angle
imp3.getProcessor().setInterpolationMethod(ImageProcessor.BILINEAR);
imp3.getProcessor().rotate(angle);
// now crop and return
final double PADDING=0.20;
imp3.setRoi(new Roi(
Math.max(0, centerX-(major/2.0)-Math.floor(PADDING*major)),
0,
Math.min(imp3.getWidth(), major+(Math.floor(PADDING*major)*2.0)),
imp3.getHeight()));
imp3.setProcessor(imp3.getTitle(), imp3.getProcessor().crop());
// fill any black pixels with the modal background color
for (int y=0; y<imp3.getHeight(); ++y) {
PIXEL:
for (int x=0; x<imp3.getWidth(); ++x) {
int[] pixel = imp3.getPixel(x, y);
for (int i=0; i<pixel.length; ++i) {
if (pixel[i] != 0) continue PIXEL;
}
imp3.getProcessor().putPixel(x, y, mode);
}
}
return imp3;
}
public synchronized void flip(String imagePath, boolean horiz, boolean vert) {
if (!Paths.get(imagePath).isAbsolute()) {
imagePath = Paths.get(workflowRunner.getWorkflowDir().getPath()).resolve(Paths.get(imagePath)).toString();
}
log("called flip(imagePath=%s, horiz=%s, vert=%s)", imagePath, horiz, vert);
String editedImagePath = getEditedImagePath(imagePath);
File editedImageFile = new File(editedImagePath);
File imageFile = new File(imagePath);
if (!imageFile.exists()) {
throw new RuntimeException(String.format("Could not find image file %s!", imagePath));
}
ImagePlus imp = new ImagePlus(editedImageFile.exists()? editedImageFile.getPath() : imageFile.getPath());
if (horiz) imp.getProcessor().flipHorizontal();
if (vert) imp.getProcessor().flipVertical();
new FileSaver(imp).saveAsTiff(editedImagePath);
changedImages.put(imagePath, true);
}
public boolean isUpToDate(String imagePath, String timestamp) {
if (!Paths.get(imagePath).isAbsolute()) {
imagePath = Paths.get(workflowRunner.getWorkflowDir().getPath()).resolve(Paths.get(imagePath)).toString();
}
File imageFile = new File(imagePath);
if (!imageFile.exists()) throw new RuntimeException(String.format("Could not find file %s", imagePath));
Date lastModified = new Date(imageFile.lastModified());
Date timestampDate;
try { timestampDate = new SimpleDateFormat("yyyy-MM-dd.HH:mm:ss").parse(timestamp); }
catch (ParseException e) {throw new RuntimeException(e);}
return lastModified.getTime() <= timestampDate.getTime();
}
}
|
package edu.umd.cs.piccolo;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Paint;
import java.awt.Transparency;
import java.awt.geom.AffineTransform;
import java.awt.geom.Dimension2D;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javax.swing.event.EventListenerList;
import javax.swing.event.SwingPropertyChangeSupport;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import edu.umd.cs.piccolo.activities.PActivity;
import edu.umd.cs.piccolo.activities.PColorActivity;
import edu.umd.cs.piccolo.activities.PInterpolatingActivity;
import edu.umd.cs.piccolo.activities.PTransformActivity;
import edu.umd.cs.piccolo.event.PInputEventListener;
import edu.umd.cs.piccolo.util.PAffineTransform;
import edu.umd.cs.piccolo.util.PAffineTransformException;
import edu.umd.cs.piccolo.util.PBounds;
import edu.umd.cs.piccolo.util.PNodeFilter;
import edu.umd.cs.piccolo.util.PObjectOutputStream;
import edu.umd.cs.piccolo.util.PPaintContext;
import edu.umd.cs.piccolo.util.PPickPath;
import edu.umd.cs.piccolo.util.PUtil;
/**
* <b>PNode</b> is the central abstraction in Piccolo. All objects that are
* visible on the screen are instances of the node class. All nodes may have
* other "child" nodes added to them.
* <p>
* See edu.umd.piccolo.examples.NodeExample.java for demonstrations of how nodes
* can be used and how new types of nodes can be created.
* <P>
*
* @version 1.0
* @author Jesse Grosjean
*/
public class PNode implements Cloneable, Serializable, Printable {
/**
* The minimum difference in transparency required before the transparency
* is allowed to change. Done for efficiency reasons. I doubt very much that
* the human eye could tell the difference between 0.01 and 0.02
* transparency.
*/
private static final float TRANSPARENCY_RESOLUTION = 0.01f;
/**
* Allows for future serialization code to understand versioned binary
* formats.
*/
private static final long serialVersionUID = 1L;
/**
* The property name that identifies a change in this node's client
* propertie (see {@link #getClientProperty getClientProperty}). In an
* property change event the new value will be a reference to the map of
* client properties but old value will always be null.
*/
public static final String PROPERTY_CLIENT_PROPERTIES = "clientProperties";
/**
* The property code that identifies a change in this node's client
* propertie (see {@link #getClientProperty getClientProperty}). In an
* property change event the new value will be a reference to the map of
* client properties but old value will always be null.
*/
public static final int PROPERTY_CODE_CLIENT_PROPERTIES = 1 << 0;
/**
* The property name that identifies a change of this node's bounds (see
* {@link #getBounds getBounds}, {@link #getBoundsReference
* getBoundsReference}). In any property change event the new value will be
* a reference to this node's bounds, but old value will always be null.
*/
public static final String PROPERTY_BOUNDS = "bounds";
/**
* The property code that identifies a change of this node's bounds (see
* {@link #getBounds getBounds}, {@link #getBoundsReference
* getBoundsReference}). In any property change event the new value will be
* a reference to this node's bounds, but old value will always be null.
*/
public static final int PROPERTY_CODE_BOUNDS = 1 << 1;
/**
* The property name that identifies a change of this node's full bounds
* (see {@link #getFullBounds getFullBounds},
* {@link #getFullBoundsReference getFullBoundsReference}). In any property
* change event the new value will be a reference to this node's full bounds
* cache, but old value will always be null.
*/
public static final String PROPERTY_FULL_BOUNDS = "fullBounds";
/**
* The property code that identifies a change of this node's full bounds
* (see {@link #getFullBounds getFullBounds},
* {@link #getFullBoundsReference getFullBoundsReference}). In any property
* change event the new value will be a reference to this node's full bounds
* cache, but old value will always be null.
*/
public static final int PROPERTY_CODE_FULL_BOUNDS = 1 << 2;
/**
* The property name that identifies a change of this node's transform (see
* {@link #getTransform getTransform}, {@link #getTransformReference
* getTransformReference}). In any property change event the new value will
* be a reference to this node's transform, but old value will always be
* null.
*/
public static final String PROPERTY_TRANSFORM = "transform";
/**
* The property code that identifies a change of this node's transform (see
* {@link #getTransform getTransform}, {@link #getTransformReference
* getTransformReference}). In any property change event the new value will
* be a reference to this node's transform, but old value will always be
* null.
*/
public static final int PROPERTY_CODE_TRANSFORM = 1 << 3;
/**
* The property name that identifies a change of this node's visibility (see
* {@link #getVisible getVisible}). Both old value and new value will be
* null in any property change event.
*/
public static final String PROPERTY_VISIBLE = "visible";
/**
* The property code that identifies a change of this node's visibility (see
* {@link #getVisible getVisible}). Both old value and new value will be
* null in any property change event.
*/
public static final int PROPERTY_CODE_VISIBLE = 1 << 4;
/**
* The property name that identifies a change of this node's paint (see
* {@link #getPaint getPaint}). Both old value and new value will be set
* correctly in any property change event.
*/
public static final String PROPERTY_PAINT = "paint";
/**
* The property code that identifies a change of this node's paint (see
* {@link #getPaint getPaint}). Both old value and new value will be set
* correctly in any property change event.
*/
public static final int PROPERTY_CODE_PAINT = 1 << 5;
/**
* The property name that identifies a change of this node's transparency
* (see {@link #getTransparency getTransparency}). Both old value and new
* value will be null in any property change event.
*/
public static final String PROPERTY_TRANSPARENCY = "transparency";
/**
* The property code that identifies a change of this node's transparency
* (see {@link #getTransparency getTransparency}). Both old value and new
* value will be null in any property change event.
*/
public static final int PROPERTY_CODE_TRANSPARENCY = 1 << 6;
/**
* The property name that identifies a change of this node's pickable status
* (see {@link #getPickable getPickable}). Both old value and new value will
* be null in any property change event.
*/
public static final String PROPERTY_PICKABLE = "pickable";
/**
* The property code that identifies a change of this node's pickable status
* (see {@link #getPickable getPickable}). Both old value and new value will
* be null in any property change event.
*/
public static final int PROPERTY_CODE_PICKABLE = 1 << 7;
/**
* The property name that identifies a change of this node's children
* pickable status (see {@link #getChildrenPickable getChildrenPickable}).
* Both old value and new value will be null in any property change event.
*/
public static final String PROPERTY_CHILDREN_PICKABLE = "childrenPickable";
/**
* The property code that identifies a change of this node's children
* pickable status (see {@link #getChildrenPickable getChildrenPickable}).
* Both old value and new value will be null in any property change event.
*/
public static final int PROPERTY_CODE_CHILDREN_PICKABLE = 1 << 8;
/**
* The property name that identifies a change in the set of this node's
* direct children (see {@link #getChildrenReference getChildrenReference},
* {@link #getChildrenIterator getChildrenIterator}). In any property change
* event the new value will be a reference to this node's children, but old
* value will always be null.
*/
public static final String PROPERTY_CHILDREN = "children";
/**
* The property code that identifies a change in the set of this node's
* direct children (see {@link #getChildrenReference getChildrenReference},
* {@link #getChildrenIterator getChildrenIterator}). In any property change
* event the new value will be a reference to this node's children, but old
* value will always be null.
*/
public static final int PROPERTY_CODE_CHILDREN = 1 << 9;
/**
* The property name that identifies a change of this node's parent (see
* {@link #getParent getParent}). Both old value and new value will be set
* correctly in any property change event.
*/
public static final String PROPERTY_PARENT = "parent";
/**
* The property code that identifies a change of this node's parent (see
* {@link #getParent getParent}). Both old value and new value will be set
* correctly in any property change event.
*/
public static final int PROPERTY_CODE_PARENT = 1 << 10;
/** Is an optimization for use during repaints. */
private static final PBounds TEMP_REPAINT_BOUNDS = new PBounds();
/** The single scene graph delegate that receives low level node events. */
public static PSceneGraphDelegate SCENE_GRAPH_DELEGATE = null;
/** Tracks the parent of this node, may be null. */
private transient PNode parent;
/** Tracks all immediate child nodes. */
private List children;
/** Bounds of the PNode. */
private final PBounds bounds;
/** Transform that applies to this node in relation to its parent. */
private PAffineTransform transform;
/** The paint to use for the background of this node. */
private Paint paint;
/**
* How Opaque this node should be 1f = fully opaque, 0f = completely
* transparent.
*/
private float transparency;
/** A modifiable set of client properties. */
private MutableAttributeSet clientProperties;
/**
* An optimization that remembers the full bounds of a node rather than
* computing it every time.
*/
private PBounds fullBoundsCache;
/**
* Mask used when deciding whether to bubble up property change events to
* parents.
*/
private int propertyChangeParentMask = 0;
/** Used to handle property change listeners. */
private transient SwingPropertyChangeSupport changeSupport;
/** List of event listeners. */
private transient EventListenerList listenerList;
/** Whether this node is pickable or not. */
private boolean pickable;
/**
* Whether to stop processing pick at this node and not bother drilling down
* into children.
*/
private boolean childrenPickable;
/** Whether this node will be rendered. */
private boolean visible;
private boolean childBoundsVolatile;
/** Whether this node needs to be repainted. */
private boolean paintInvalid;
/** Whether children need to be repainted. */
private boolean childPaintInvalid;
/** Whether this node's bounds have changed, and so needs to be relaid out. */
private boolean boundsChanged;
/** Whether this node's full bounds need to be recomputed. */
private boolean fullBoundsInvalid;
/** Whether this node's child bounds need to be recomputed. */
private boolean childBoundsInvalid;
private boolean occluded;
/** Stores the name associated to this node. */
private String name;
/**
* toImage fill strategy that stretches the node be as large as possible
* while still retaining its aspect ratio.
*
* @since 1.3
*/
public static final int FILL_STRATEGY_ASPECT_FIT = 1;
/**
* toImage fill strategy that stretches the node be large enough to cover
* the image, and centers it.
*
* @since 1.3
*/
public static final int FILL_STRATEGY_ASPECT_COVER = 2;
/**
* toImage fill strategy that stretches the node to be exactly the
* dimensions of the image. Will result in distortion if the aspect ratios
* are different.
*
* @since 1.3
*/
public static final int FILL_STRATEGY_EXACT_FIT = 4;
/**
* Creates a new PNode with the given name.
*
* @since 1.3
* @param newName name to assign to node
*/
public PNode(final String newName) {
this();
setName(newName);
}
/**
* Constructs a new PNode.
* <P>
* By default a node's paint is null, and bounds are empty. These values
* must be set for the node to show up on the screen once it's added to a
* scene graph.
*/
public PNode() {
bounds = new PBounds();
fullBoundsCache = new PBounds();
transparency = 1.0f;
pickable = true;
childrenPickable = true;
visible = true;
}
// Animation - Methods to animate this node.
// Note that animation is implemented by activities (PActivity),
// so if you need more control over your animation look at the
// activities package. Each animate method creates an animation that
// will animate the node from its current state to the new state
// specified over the given duration. These methods will try to
// automatically schedule the new activity, but if the node does not
// descend from the root node when the method is called then the
// activity will not be scheduled and you must schedule it manually.
/**
* Animate this node's bounds from their current location when the activity
* starts to the specified bounds. If this node descends from the root then
* the activity will be scheduled, else the returned activity should be
* scheduled manually. If two different transform activities are scheduled
* for the same node at the same time, they will both be applied to the
* node, but the last one scheduled will be applied last on each frame, so
* it will appear to have replaced the original. Generally you will not want
* to do that. Note this method animates the node's bounds, but does not
* change the node's transform. Use animateTransformToBounds() to animate
* the node's transform instead.
*
* @param x left of target bounds
* @param y top of target bounds
* @param width width of target bounds
* @param height height of target bounds
* @param duration amount of time that the animation should take
* @return the newly scheduled activity
*/
public PInterpolatingActivity animateToBounds(final double x, final double y, final double width,
final double height, final long duration) {
if (duration == 0) {
setBounds(x, y, width, height);
return null;
}
final PBounds dst = new PBounds(x, y, width, height);
final PInterpolatingActivity interpolatingActivity = new PInterpolatingActivity(duration,
PUtil.DEFAULT_ACTIVITY_STEP_RATE) {
private PBounds src;
protected void activityStarted() {
src = getBounds();
startResizeBounds();
super.activityStarted();
}
public void setRelativeTargetValue(final float zeroToOne) {
PNode.this.setBounds(src.x + zeroToOne * (dst.x - src.x), src.y + zeroToOne * (dst.y - src.y),
src.width + zeroToOne * (dst.width - src.width), src.height + zeroToOne
* (dst.height - src.height));
}
protected void activityFinished() {
super.activityFinished();
endResizeBounds();
}
};
addActivity(interpolatingActivity);
return interpolatingActivity;
}
/**
* Animate this node from it's current transform when the activity starts a
* new transform that will fit the node into the given bounds. If this node
* descends from the root then the activity will be scheduled, else the
* returned activity should be scheduled manually. If two different
* transform activities are scheduled for the same node at the same time,
* they will both be applied to the node, but the last one scheduled will be
* applied last on each frame, so it will appear to have replaced the
* original. Generally you will not want to do that. Note this method
* animates the node's transform, but does not directly change the node's
* bounds rectangle. Use animateToBounds() to animate the node's bounds
* rectangle instead.
*
* @param x left of target bounds
* @param y top of target bounds
* @param width width of target bounds
* @param height height of target bounds
* @param duration amount of time that the animation should take
* @return the newly scheduled activity
*/
public PTransformActivity animateTransformToBounds(final double x, final double y, final double width,
final double height, final long duration) {
final PAffineTransform t = new PAffineTransform();
t.setToScale(width / getWidth(), height / getHeight());
final double scale = t.getScale();
t.setOffset(x - getX() * scale, y - getY() * scale);
return animateToTransform(t, duration);
}
/**
* Animate this node's transform from its current location when the activity
* starts to the specified location, scale, and rotation. If this node
* descends from the root then the activity will be scheduled, else the
* returned activity should be scheduled manually. If two different
* transform activities are scheduled for the same node at the same time,
* they will both be applied to the node, but the last one scheduled will be
* applied last on each frame, so it will appear to have replaced the
* original. Generally you will not want to do that.
*
* @param x the final target x position of node
* @param y the final target y position of node
* @param duration amount of time that the animation should take
* @param scale the final scale for the duration
* @param theta final theta value (in radians) for the animation
* @return the newly scheduled activity
*/
public PTransformActivity animateToPositionScaleRotation(final double x, final double y, final double scale,
final double theta, final long duration) {
final PAffineTransform t = getTransform();
t.setOffset(x, y);
t.setScale(scale);
t.setRotation(theta);
return animateToTransform(t, duration);
}
/**
* Animate this node's transform from its current values when the activity
* starts to the new values specified in the given transform. If this node
* descends from the root then the activity will be scheduled, else the
* returned activity should be scheduled manually. If two different
* transform activities are scheduled for the same node at the same time,
* they will both be applied to the node, but the last one scheduled will be
* applied last on each frame, so it will appear to have replaced the
* original. Generally you will not want to do that.
*
* @param destTransform the final transform value
* @param duration amount of time that the animation should take
* @return the newly scheduled activity
*/
public PTransformActivity animateToTransform(final AffineTransform destTransform, final long duration) {
if (duration == 0) {
setTransform(destTransform);
return null;
}
else {
final PTransformActivity.Target t = new PTransformActivity.Target() {
public void setTransform(final AffineTransform aTransform) {
PNode.this.setTransform(aTransform);
}
public void getSourceMatrix(final double[] aSource) {
PNode.this.getTransformReference(true).getMatrix(aSource);
}
};
final PTransformActivity ta = new PTransformActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE, t,
destTransform);
addActivity(ta);
return ta;
}
}
/**
* Animate this node's color from its current value to the new value
* specified. This meathod assumes that this nodes paint property is of type
* color. If this node descends from the root then the activity will be
* scheduled, else the returned activity should be scheduled manually. If
* two different color activities are scheduled for the same node at the
* same time, they will both be applied to the node, but the last one
* scheduled will be applied last on each frame, so it will appear to have
* replaced the original. Generally you will not want to do that.
*
* @param destColor final color value.
* @param duration amount of time that the animation should take
* @return the newly scheduled activity
*/
public PInterpolatingActivity animateToColor(final Color destColor, final long duration) {
if (duration == 0) {
setPaint(destColor);
return null;
}
else {
final PColorActivity.Target t = new PColorActivity.Target() {
public Color getColor() {
return (Color) getPaint();
}
public void setColor(final Color color) {
setPaint(color);
}
};
final PColorActivity ca = new PColorActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE, t, destColor);
addActivity(ca);
return ca;
}
}
/**
* Animate this node's transparency from its current value to the new value
* specified. Transparency values must range from zero to one. If this node
* descends from the root then the activity will be scheduled, else the
* returned activity should be scheduled manually. If two different
* transparency activities are scheduled for the same node at the same time,
* they will both be applied to the node, but the last one scheduled will be
* applied last on each frame, so it will appear to have replaced the
* original. Generally you will not want to do that.
*
* @param zeroToOne final transparency value.
* @param duration amount of time that the animation should take
* @return the newly scheduled activity
*/
public PInterpolatingActivity animateToTransparency(final float zeroToOne, final long duration) {
if (duration == 0) {
setTransparency(zeroToOne);
return null;
}
else {
final float dest = zeroToOne;
final PInterpolatingActivity ta = new PInterpolatingActivity(duration, PUtil.DEFAULT_ACTIVITY_STEP_RATE) {
private float source;
protected void activityStarted() {
source = getTransparency();
super.activityStarted();
}
public void setRelativeTargetValue(final float zeroToOne) {
PNode.this.setTransparency(source + zeroToOne * (dest - source));
}
};
addActivity(ta);
return ta;
}
}
/**
* Schedule the given activity with the root, note that only scheduled
* activities will be stepped. If the activity is successfully added true is
* returned, else false.
*
* @param activity new activity to schedule
* @return true if the activity is successfully scheduled.
*/
public boolean addActivity(final PActivity activity) {
final PRoot r = getRoot();
if (r != null) {
return r.addActivity(activity);
}
return false;
}
// Client Properties - Methods for managing client properties for
// this node.
// Client properties provide a way for programmers to attach
// extra information to a node without having to subclass it and
// add new instance variables.
/**
* Return mutable attributed set of client properties associated with this
* node.
*
* @return the client properties associated to this node
*/
public MutableAttributeSet getClientProperties() {
if (clientProperties == null) {
clientProperties = new SimpleAttributeSet();
}
return clientProperties;
}
/**
* Returns the value of the client attribute with the specified key. Only
* attributes added with <code>addAttribute</code> will return a non-null
* value.
*
* @param key key to use while fetching client attribute
*
* @return the value of this attribute or null
*/
public Object getAttribute(final Object key) {
if (clientProperties == null || key == null) {
return null;
}
else {
return clientProperties.getAttribute(key);
}
}
public void addAttribute(final Object key, final Object value) {
if (value == null && clientProperties == null) {
return;
}
final Object oldValue = getAttribute(key);
if (value != oldValue) {
if (clientProperties == null) {
clientProperties = new SimpleAttributeSet();
}
if (value == null) {
clientProperties.removeAttribute(key);
}
else {
clientProperties.addAttribute(key, value);
}
if (clientProperties.getAttributeCount() == 0 && clientProperties.getResolveParent() == null) {
clientProperties = null;
}
firePropertyChange(PROPERTY_CODE_CLIENT_PROPERTIES, PROPERTY_CLIENT_PROPERTIES, null, clientProperties);
firePropertyChange(PROPERTY_CODE_CLIENT_PROPERTIES, key.toString(), oldValue, value);
}
}
/**
* Returns an enumeration of all keys maped to attribute values values.
*
* @return an Enumeration over attribute keys
*/
public Enumeration getClientPropertyKeysEnumeration() {
if (clientProperties == null) {
return PUtil.NULL_ENUMERATION;
}
else {
return clientProperties.getAttributeNames();
}
}
// convenience methods for attributes
/**
* Fetches the value of the requested attribute, returning defaultValue is
* not found.
*
* @param key attribute to search for
* @param defaultValue value to return if attribute is not found
*
* @return value of attribute or defaultValue if not found
*/
public Object getAttribute(final Object key, final Object defaultValue) {
final Object value = getAttribute(key);
if (value == null) {
return defaultValue;
}
return value;
}
/**
* Fetches the boolean value of the requested attribute, returning
* defaultValue is not found.
*
* @param key attribute to search for
* @param defaultValue value to return if attribute is not found
*
* @return value of attribute or defaultValue if not found
*/
public boolean getBooleanAttribute(final Object key, final boolean defaultValue) {
final Boolean value = (Boolean) getAttribute(key);
if (value == null) {
return defaultValue;
}
return value.booleanValue();
}
/**
* Fetches the integer value of the requested attribute, returning
* defaultValue is not found.
*
* @param key attribute to search for
* @param defaultValue value to return if attribute is not found
*
* @return value of attribute or defaultValue if not found
*/
public int getIntegerAttribute(final Object key, final int defaultValue) {
final Number value = (Number) getAttribute(key);
if (value == null) {
return defaultValue;
}
return value.intValue();
}
/**
* Fetches the double value of the requested attribute, returning
* defaultValue is not found.
*
* @param key attribute to search for
* @param defaultValue value to return if attribute is not found
*
* @return value of attribute or defaultValue if not found
*/
public double getDoubleAttribute(final Object key, final double defaultValue) {
final Number value = (Number) getAttribute(key);
if (value == null) {
return defaultValue;
}
return value.doubleValue();
}
/**
* @deprecated use getAttribute(Object key)instead.
*
* @param key name of property to search for
* @return value of matching client property
*/
public Object getClientProperty(final Object key) {
return getAttribute(key);
}
/**
* @deprecated use addAttribute(Object key, Object value)instead.
*
* @param key name of property to add
* @param value value or new attribute
*/
public void addClientProperty(final Object key, final Object value) {
addAttribute(key, value);
}
/**
* @deprecated use getClientPropertyKeysEnumerator() instead.
*
* @return iterator for client property keys
*/
public Iterator getClientPropertyKeysIterator() {
final Enumeration enumeration = getClientPropertyKeysEnumeration();
return new ClientPropertyKeyIterator(enumeration);
}
// Copying - Methods for copying this node and its descendants.
// Copying is implemented in terms of serialization.
/**
* The copy method copies this node and all of its descendants. Note that
* copying is implemented in terms of java serialization. See the
* serialization notes for more information.
*
* @return new copy of this node or null if the node was not serializable
*/
public Object clone() {
try {
final byte[] ser = PObjectOutputStream.toByteArray(this);
return new ObjectInputStream(new ByteArrayInputStream(ser)).readObject();
}
catch (final IOException e) {
return null;
}
catch (final ClassNotFoundException e) {
return null;
}
}
// Coordinate System Conversions - Methods for converting
// geometry between this nodes local coordinates and the other
// major coordinate systems.
// Each nodes has an affine transform that it uses to define its
// own coordinate system. For example if you create a new node and
// add it to the canvas it will appear in the upper right corner. Its
// coordinate system matches the coordinate system of its parent
// (the root node) at this point. But if you move this node by calling
// node.translate() the nodes affine transform will be modified and the
// node will appear at a different location on the screen. The node
// coordinate system no longer matches the coordinate system of its
// parent.
// This is useful because it means that the node's methods for
// rendering and picking don't need to worry about the fact that
// the node has been moved to another position on the screen, they
// keep working just like they did when it was in the upper right
// hand corner of the screen.
// The problem is now that each node defines its own coordinate
// system it is difficult to compare the positions of two node with
// each other. These methods are all meant to help solve that problem.
// The terms used in the methods are as follows:
// local - The local or base coordinate system of a node.
// parent - The coordinate system of a node's parent
// global - The topmost coordinate system, above the root node.
// Normally when comparing the positions of two nodes you will
// convert the local position of each node to the global coordinate
// system, and then compare the positions in that common coordinate
// system.
/**
* Transform the given point from this node's local coordinate system to its
* parent's local coordinate system. Note that this will modify the point
* parameter.
*
* @param localPoint point in local coordinate system to be transformed.
* @return point in parent's local coordinate system
*/
public Point2D localToParent(final Point2D localPoint) {
if (transform == null) {
return localPoint;
}
return transform.transform(localPoint, localPoint);
}
/**
* Transform the given dimension from this node's local coordinate system to
* its parent's local coordinate system. Note that this will modify the
* dimension parameter.
*
* @param localDimension dimension in local coordinate system to be
* transformed.
* @return dimension in parent's local coordinate system
*/
public Dimension2D localToParent(final Dimension2D localDimension) {
if (transform == null) {
return localDimension;
}
return transform.transform(localDimension, localDimension);
}
/**
* Transform the given rectangle from this node's local coordinate system to
* its parent's local coordinate system. Note that this will modify the
* rectangle parameter.
*
* @param localRectangle rectangle in local coordinate system to be
* transformed.
* @return rectangle in parent's local coordinate system
*/
public Rectangle2D localToParent(final Rectangle2D localRectangle) {
if (transform == null) {
return localRectangle;
}
return transform.transform(localRectangle, localRectangle);
}
/**
* Transform the given point from this node's parent's local coordinate
* system to the local coordinate system of this node. Note that this will
* modify the point parameter.
*
* @param parentPoint point in parent's coordinate system to be transformed.
* @return point in this node's local coordinate system
*/
public Point2D parentToLocal(final Point2D parentPoint) {
if (transform == null) {
return parentPoint;
}
return transform.inverseTransform(parentPoint, parentPoint);
}
/**
* Transform the given dimension from this node's parent's local coordinate
* system to the local coordinate system of this node. Note that this will
* modify the dimension parameter.
*
* @param parentDimension dimension in parent's coordinate system to be
* transformed.
* @return dimension in this node's local coordinate system
*/
public Dimension2D parentToLocal(final Dimension2D parentDimension) {
if (transform == null) {
return parentDimension;
}
return transform.inverseTransform(parentDimension, parentDimension);
}
/**
* Transform the given rectangle from this node's parent's local coordinate
* system to the local coordinate system of this node. Note that this will
* modify the rectangle parameter.
*
* @param parentRectangle rectangle in parent's coordinate system to be
* transformed.
* @return rectangle in this node's local coordinate system
*/
public Rectangle2D parentToLocal(final Rectangle2D parentRectangle) {
if (transform == null) {
return parentRectangle;
}
return transform.inverseTransform(parentRectangle, parentRectangle);
}
/**
* Transform the given point from this node's local coordinate system to the
* global coordinate system. Note that this will modify the point parameter.
*
* @param localPoint point in local coordinate system to be transformed.
* @return point in global coordinates
*/
public Point2D localToGlobal(final Point2D localPoint) {
PNode n = this;
while (n != null) {
n.localToParent(localPoint);
n = n.parent;
}
return localPoint;
}
/**
* Transform the given dimension from this node's local coordinate system to
* the global coordinate system. Note that this will modify the dimension
* parameter.
*
* @param localDimension dimension in local coordinate system to be
* transformed.
* @return dimension in global coordinates
*/
public Dimension2D localToGlobal(final Dimension2D localDimension) {
PNode n = this;
while (n != null) {
n.localToParent(localDimension);
n = n.parent;
}
return localDimension;
}
/**
* Transform the given rectangle from this node's local coordinate system to
* the global coordinate system. Note that this will modify the rectangle
* parameter.
*
* @param localRectangle rectangle in local coordinate system to be
* transformed.
* @return rectangle in global coordinates
*/
public Rectangle2D localToGlobal(final Rectangle2D localRectangle) {
PNode n = this;
while (n != null) {
n.localToParent(localRectangle);
n = n.parent;
}
return localRectangle;
}
/**
* Transform the given point from global coordinates to this node's local
* coordinate system. Note that this will modify the point parameter.
*
* @param globalPoint point in global coordinates to be transformed.
* @return point in this node's local coordinate system.
*/
public Point2D globalToLocal(final Point2D globalPoint) {
final PAffineTransform globalTransform = computeGlobalTransform(this);
return globalTransform.inverseTransform(globalPoint, globalPoint);
}
private PAffineTransform computeGlobalTransform(final PNode node) {
if (node == null) {
return new PAffineTransform();
}
final PAffineTransform parentGlobalTransform = computeGlobalTransform(node.parent);
if (node.transform != null) {
parentGlobalTransform.concatenate(node.transform);
}
return parentGlobalTransform;
}
/**
* Transform the given dimension from global coordinates to this node's
* local coordinate system. Note that this will modify the dimension
* parameter.
*
* @param globalDimension dimension in global coordinates to be transformed.
* @return dimension in this node's local coordinate system.
*/
public Dimension2D globalToLocal(final Dimension2D globalDimension) {
if (parent != null) {
parent.globalToLocal(globalDimension);
}
return parentToLocal(globalDimension);
}
/**
* Transform the given rectangle from global coordinates to this node's
* local coordinate system. Note that this will modify the rectangle
* parameter.
*
* @param globalRectangle rectangle in global coordinates to be transformed.
* @return rectangle in this node's local coordinate system.
*/
public Rectangle2D globalToLocal(final Rectangle2D globalRectangle) {
if (parent != null) {
parent.globalToLocal(globalRectangle);
}
return parentToLocal(globalRectangle);
}
/**
* Return the transform that converts local coordinates at this node to the
* global coordinate system.
*
* @param dest PAffineTransform to transform to global coordinates
* @return The concatenation of transforms from the top node down to this
* node.
*/
public PAffineTransform getLocalToGlobalTransform(final PAffineTransform dest) {
PAffineTransform result = dest;
if (parent != null) {
result = parent.getLocalToGlobalTransform(result);
if (transform != null) {
result.concatenate(transform);
}
}
else if (dest == null) {
result = getTransform();
}
else if (transform != null) {
result.setTransform(transform);
}
else {
result.setToIdentity();
}
return result;
}
/**
* Return the transform that converts global coordinates to local
* coordinates of this node.
*
* @param dest PAffineTransform to transform from global to local
*
* @return The inverse of the concatenation of transforms from the root down
* to this node.
*/
public PAffineTransform getGlobalToLocalTransform(final PAffineTransform dest) {
PAffineTransform result = getLocalToGlobalTransform(dest);
try {
result.setTransform(result.createInverse());
}
catch (final NoninvertibleTransformException e) {
throw new PAffineTransformException(e, result);
}
return result;
}
// Event Listeners - Methods for adding and removing event listeners
// from a node.
// Here methods are provided to add property change listeners and
// input event listeners. The property change listeners are notified
// when certain properties of this node change, and the input event
// listeners are notified when the nodes receives new key and mouse
// events.
/**
* Return the list of event listeners associated with this node.
*
* @return event listener list or null
*/
public EventListenerList getListenerList() {
return listenerList;
}
/**
* Adds the specified input event listener to receive input events from this
* node.
*
* @param listener the new input listener
*/
public void addInputEventListener(final PInputEventListener listener) {
if (listenerList == null) {
listenerList = new EventListenerList();
}
getListenerList().add(PInputEventListener.class, listener);
}
/**
* Removes the specified input event listener so that it no longer receives
* input events from this node.
*
* @param listener the input listener to remove
*/
public void removeInputEventListener(final PInputEventListener listener) {
if (listenerList == null) {
return;
}
getListenerList().remove(PInputEventListener.class, listener);
if (listenerList.getListenerCount() == 0) {
listenerList = null;
}
}
/**
* Add a PropertyChangeListener to the listener list. The listener is
* registered for all properties. See the fields in PNode and subclasses
* that start with PROPERTY_ to find out which properties exist.
*
* @param listener The PropertyChangeListener to be added
*/
public void addPropertyChangeListener(final PropertyChangeListener listener) {
if (changeSupport == null) {
changeSupport = new SwingPropertyChangeSupport(this);
}
changeSupport.addPropertyChangeListener(listener);
}
/**
* Add a PropertyChangeListener for a specific property. The listener will
* be invoked only when a call on firePropertyChange names that specific
* property. See the fields in PNode and subclasses that start with
* PROPERTY_ to find out which properties are supported.
*
* @param propertyName The name of the property to listen on.
* @param listener The PropertyChangeListener to be added
*/
public void addPropertyChangeListener(final String propertyName, final PropertyChangeListener listener) {
if (listener == null) {
return;
}
if (changeSupport == null) {
changeSupport = new SwingPropertyChangeSupport(this);
}
changeSupport.addPropertyChangeListener(propertyName, listener);
}
/**
* Remove a PropertyChangeListener from the listener list. This removes a
* PropertyChangeListener that was registered for all properties.
*
* @param listener The PropertyChangeListener to be removed
*/
public void removePropertyChangeListener(final PropertyChangeListener listener) {
if (changeSupport != null) {
changeSupport.removePropertyChangeListener(listener);
}
}
/**
* Remove a PropertyChangeListener for a specific property.
*
* @param propertyName The name of the property that was listened on.
* @param listener The PropertyChangeListener to be removed
*/
public void removePropertyChangeListener(final String propertyName, final PropertyChangeListener listener) {
if (listener == null) {
return;
}
if (changeSupport == null) {
return;
}
changeSupport.removePropertyChangeListener(propertyName, listener);
}
/**
* Return the propertyChangeParentMask that determines which property change
* events are forwared to this nodes parent so that its property change
* listeners will also be notified.
*
* @return mask used for deciding whether to bubble property changes up to
* parent
*/
public int getPropertyChangeParentMask() {
return propertyChangeParentMask;
}
/**
* Set the propertyChangeParentMask that determines which property change
* events are forwared to this nodes parent so that its property change
* listeners will also be notified.
*
* @param propertyChangeParentMask new mask for property change bubble up
*/
public void setPropertyChangeParentMask(final int propertyChangeParentMask) {
this.propertyChangeParentMask = propertyChangeParentMask;
}
/**
* Report a bound property update to any registered listeners. No event is
* fired if old and new are equal and non-null. If the propertyCode exists
* in this node's propertyChangeParentMask then a property change event will
* also be fired on this nodes parent.
*
* @param propertyCode The code of the property changed.
* @param propertyName The name of the property that was changed.
* @param oldValue The old value of the property.
* @param newValue The new value of the property.
*/
protected void firePropertyChange(final int propertyCode, final String propertyName, final Object oldValue,
final Object newValue) {
PropertyChangeEvent event = null;
if (changeSupport != null) {
event = new PropertyChangeEvent(this, propertyName, oldValue, newValue);
changeSupport.firePropertyChange(event);
}
if (parent != null && (propertyCode & propertyChangeParentMask) != 0) {
if (event == null) {
event = new PropertyChangeEvent(this, propertyName, oldValue, newValue);
}
parent.fireChildPropertyChange(event, propertyCode);
}
}
/**
* Called by child node to forward property change events up the node tree
* so that property change listeners registered with this node will be
* notified of property changes of its children nodes. For performance
* reason only propertyCodes listed in the propertyChangeParentMask are
* forwarded.
*
* @param event The property change event containing source node and changed
* values.
* @param propertyCode The code of the property changed.
*/
protected void fireChildPropertyChange(final PropertyChangeEvent event, final int propertyCode) {
if (changeSupport != null) {
changeSupport.firePropertyChange(event);
}
if (parent != null && (propertyCode & propertyChangeParentMask) != 0) {
parent.fireChildPropertyChange(event, propertyCode);
}
}
// Bounds Geometry - Methods for setting and querying the bounds
// of this node.
// The bounds of a node store the node's position and size in
// the nodes local coordinate system. Many node subclasses will need
// to override the setBounds method so that they can update their
// internal state appropriately. See PPath for an example.
// Since the bounds are stored in the local coordinate system
// they WILL NOT change if the node is scaled, translated, or rotated.
// The bounds may be accessed with either getBounds, or
// getBoundsReference. The former returns a copy of the bounds
// the latter returns a reference to the nodes bounds that should
// normally not be modified. If a node is marked as volatile then
// it may modify its bounds before returning them from getBoundsReference,
// otherwise it may not.
/**
* Return a copy of this node's bounds. These bounds are stored in the local
* coordinate system of this node and do not include the bounds of any of
* this node's children.
*
* @return copy of this node's local bounds
*/
public PBounds getBounds() {
return (PBounds) getBoundsReference().clone();
}
/**
* Return a direct reference to this node's bounds. These bounds are stored
* in the local coordinate system of this node and do not include the bounds
* of any of this node's children. The value returned should not be
* modified.
*
* @return direct reference to local bounds
*/
public PBounds getBoundsReference() {
return bounds;
}
/**
* Notify this node that you will begin to repeatedly call <code>setBounds
* </code>. When you
* are done call <code>endResizeBounds</code> to let the node know that you
* are done.
*/
public void startResizeBounds() {
}
/**
* Notify this node that you have finished a resize bounds sequence.
*/
public void endResizeBounds() {
}
/**
* Set's this node's bounds left position, leaving y, width, and height
* unchanged.
*
* @param x new x position of bounds
*
* @return whether the change was successful
*/
public boolean setX(final double x) {
return setBounds(x, getY(), getWidth(), getHeight());
}
/**
* Set's this node's bounds top position, leaving x, width, and height
* unchanged.
*
* @param y new y position of bounds
*
* @return whether the change was successful
*/
public boolean setY(final double y) {
return setBounds(getX(), y, getWidth(), getHeight());
}
/**
* Set's this node's bounds width, leaving x, y, and height unchanged.
*
* @param width new width position of bounds
*
* @return whether the change was successful
*/
public boolean setWidth(final double width) {
return setBounds(getX(), getY(), width, getHeight());
}
/**
* Set's this node's bounds height, leaving x, y, and width unchanged.
*
* @param height new height position of bounds
*
* @return whether the change was successful
*/
public boolean setHeight(final double height) {
return setBounds(getX(), getY(), getWidth(), height);
}
/**
* Set the bounds of this node to the given value. These bounds are stored
* in the local coordinate system of this node.
*
* @param newBounds bounds to apply to this node
*
* @return true if the bounds changed.
*/
public boolean setBounds(final Rectangle2D newBounds) {
return setBounds(newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight());
}
/**
* Set the bounds of this node to the given position and size. These bounds
* are stored in the local coordinate system of this node.
*
* If the width or height is less then or equal to zero then the bound's
* empty bit will be set to true.
*
* Subclasses must call the super.setBounds() method.
*
* @param x x position of bounds
* @param y y position of bounds
* @param width width to apply to the bounds
* @param height height to apply to the bounds
*
* @return true if the bounds changed.
*/
public boolean setBounds(final double x, final double y, final double width, final double height) {
if (bounds.x != x || bounds.y != y || bounds.width != width || bounds.height != height) {
bounds.setRect(x, y, width, height);
if (width <= 0 || height <= 0) {
bounds.reset();
}
internalUpdateBounds(x, y, width, height);
invalidatePaint();
signalBoundsChanged();
return true;
}
// Don't put any invalidating code here or else nodes with volatile
// bounds will
// create a soft infinite loop (calling Swing.invokeLater()) when they
// validate
// their bounds.
return false;
}
/**
* Gives nodes a chance to update their internal structure before bounds
* changed notifications are sent. When this message is recived the nodes
* bounds field will contain the new value.
*
* See PPath for an example that uses this method.
*
* @param x x position of bounds
* @param y y position of bounds
* @param width width to apply to the bounds
* @param height height to apply to the bounds
*/
protected void internalUpdateBounds(final double x, final double y, final double width, final double height) {
}
/**
* Set the empty bit of this bounds to true.
*/
public void resetBounds() {
setBounds(0, 0, 0, 0);
}
/**
* Return the x position (in local coords) of this node's bounds.
*
* @return local x position of bounds
*/
public double getX() {
return getBoundsReference().getX();
}
/**
* Return the y position (in local coords) of this node's bounds.
*
* @return local y position of bounds
*/
public double getY() {
return getBoundsReference().getY();
}
/**
* Return the width (in local coords) of this node's bounds.
*
* @return local width of bounds
*/
public double getWidth() {
return getBoundsReference().getWidth();
}
/**
* Return the height (in local coords) of this node's bounds.
*
* @return local width of bounds
*/
public double getHeight() {
return getBoundsReference().getHeight();
}
/**
* Return a copy of the bounds of this node in the global coordinate system.
*
* @return the bounds in global coordinate system.
*/
public PBounds getGlobalBounds() {
return (PBounds) localToGlobal(getBounds());
}
/**
* Center the bounds of this node so that they are centered on the given
* point specified on the local coordinates of this node. Note that this
* method will modify the nodes bounds, while centerFullBoundsOnPoint will
* modify the nodes transform.
*
* @param localX x position of point around which to center bounds
* @param localY y position of point around which to center bounds
*
* @return true if the bounds changed.
*/
public boolean centerBoundsOnPoint(final double localX, final double localY) {
final double dx = localX - bounds.getCenterX();
final double dy = localY - bounds.getCenterY();
return setBounds(bounds.x + dx, bounds.y + dy, bounds.width, bounds.height);
}
/**
* Center the full bounds of this node so that they are centered on the
* given point specified on the local coordinates of this nodes parent. Note
* that this method will modify the nodes transform, while
* centerBoundsOnPoint will modify the nodes bounds.
*
* @param parentX x position around which to center full bounds
* @param parentY y position around which to center full bounds
*/
public void centerFullBoundsOnPoint(final double parentX, final double parentY) {
final double dx = parentX - getFullBoundsReference().getCenterX();
final double dy = parentY - getFullBoundsReference().getCenterY();
offset(dx, dy);
}
/**
* Return true if this node intersects the given rectangle specified in
* local bounds. If the geometry of this node is complex this method can
* become expensive, it is therefore recommended that
* <code>fullIntersects</code> is used for quick rejects before calling this
* method.
*
* @param localBounds the bounds to test for intersection against
* @return true if the given rectangle intersects this nodes geometry.
*/
public boolean intersects(final Rectangle2D localBounds) {
if (localBounds == null) {
return true;
}
return getBoundsReference().intersects(localBounds);
}
// Full Bounds - Methods for computing and querying the
// full bounds of this node.
// The full bounds of a node store the nodes bounds
// together with the union of the bounds of all the
// node's descendants. The full bounds are stored in the parent
// coordinate system of this node, the full bounds DOES change
// when you translate, scale, or rotate this node.
// The full bounds may be accessed with either getFullBounds, or
// getFullBoundsReference. The former returns a copy of the full bounds
// the latter returns a reference to the node's full bounds that should
// not be modified.
/**
* Return a copy of this node's full bounds. These bounds are stored in the
* parent coordinate system of this node and they include the union of this
* node's bounds and all the bounds of it's descendants.
*
* @return a copy of this node's full bounds.
*/
public PBounds getFullBounds() {
return (PBounds) getFullBoundsReference().clone();
}
/**
* Return a reference to this node's full bounds cache. These bounds are
* stored in the parent coordinate system of this node and they include the
* union of this node's bounds and all the bounds of it's descendants. The
* bounds returned by this method should not be modified.
*
* @return a reference to this node's full bounds cache.
*/
public PBounds getFullBoundsReference() {
validateFullBounds();
return fullBoundsCache;
}
/**
* Compute and return the full bounds of this node. If the dstBounds
* parameter is not null then it will be used to return the results instead
* of creating a new PBounds.
*
* @param dstBounds if not null the new bounds will be stored here
* @return the full bounds in the parent coordinate system of this node
*/
public PBounds computeFullBounds(final PBounds dstBounds) {
final PBounds result = getUnionOfChildrenBounds(dstBounds);
result.add(getBoundsReference());
localToParent(result);
return result;
}
/**
* Compute and return the union of the full bounds of all the children of
* this node. If the dstBounds parameter is not null then it will be used to
* return the results instead of creating a new PBounds.
*
* @param dstBounds if not null the new bounds will be stored here
* @return union of children bounds
*/
public PBounds getUnionOfChildrenBounds(final PBounds dstBounds) {
PBounds resultBounds;
if (dstBounds == null) {
resultBounds = new PBounds();
}
else {
resultBounds = dstBounds;
resultBounds.resetToZero();
}
final int count = getChildrenCount();
for (int i = 0; i < count; i++) {
final PNode each = (PNode) children.get(i);
resultBounds.add(each.getFullBoundsReference());
}
return resultBounds;
}
/**
* Return a copy of the full bounds of this node in the global coordinate
* system.
*
* @return the full bounds in global coordinate system.
*/
public PBounds getGlobalFullBounds() {
final PBounds b = getFullBounds();
if (parent != null) {
parent.localToGlobal(b);
}
return b;
}
/**
* Return true if the full bounds of this node intersects with the specified
* bounds.
*
* @param parentBounds the bounds to test for intersection against
* (specified in parent's coordinate system)
* @return true if this nodes full bounds intersect the given bounds.
*/
public boolean fullIntersects(final Rectangle2D parentBounds) {
if (parentBounds == null) {
return true;
}
return getFullBoundsReference().intersects(parentBounds);
}
// Bounds Damage Management - Methods used to invalidate and validate
// the bounds of nodes.
/**
* Return true if this nodes bounds may change at any time. The default
* behavior is to return false, subclasses that override this method to
* return true should also override getBoundsReference() and compute their
* volatile bounds there before returning the reference.
*
* @return true if this node has volatile bounds
*/
protected boolean getBoundsVolatile() {
return false;
}
/**
* Return true if this node has a child with volatile bounds.
*
* @return true if this node has a child with volatile bounds
*/
protected boolean getChildBoundsVolatile() {
return childBoundsVolatile;
}
/**
* Set if this node has a child with volatile bounds. This should normally
* be managed automatically by the bounds validation process.
*
* @param childBoundsVolatile true if this node has a descendant with
* volatile bounds
*/
protected void setChildBoundsVolatile(final boolean childBoundsVolatile) {
this.childBoundsVolatile = childBoundsVolatile;
}
/**
* Return true if this node's bounds have recently changed. This flag will
* be reset on the next call of validateFullBounds.
*
* @return true if this node's bounds have changed.
*/
protected boolean getBoundsChanged() {
return boundsChanged;
}
/**
* Set the bounds chnaged flag. This flag will be reset on the next call of
* validateFullBounds.
*
* @param boundsChanged true if this nodes bounds have changed.
*/
protected void setBoundsChanged(final boolean boundsChanged) {
this.boundsChanged = boundsChanged;
}
/**
* Return true if the full bounds of this node are invalid. This means that
* the full bounds of this node have changed and need to be recomputed.
*
* @return true if the full bounds of this node are invalid
*/
protected boolean getFullBoundsInvalid() {
return fullBoundsInvalid;
}
/**
* Set the full bounds invalid flag. This flag is set when the full bounds
* of this node need to be recomputed as is the case when this node is
* transformed or when one of this node's children changes geometry.
*
* @param fullBoundsInvalid true=invalid, false=valid
*/
protected void setFullBoundsInvalid(final boolean fullBoundsInvalid) {
this.fullBoundsInvalid = fullBoundsInvalid;
}
/**
* Return true if one of this node's descendants has invalid bounds.
*
* @return whether child bounds are invalid
*/
protected boolean getChildBoundsInvalid() {
return childBoundsInvalid;
}
/**
* Set the flag indicating that one of this node's descendants has invalid
* bounds.
*
* @param childBoundsInvalid true=invalid, false=valid
*/
protected void setChildBoundsInvalid(final boolean childBoundsInvalid) {
this.childBoundsInvalid = childBoundsInvalid;
}
/**
* This method should be called when the bounds of this node are changed. It
* invalidates the full bounds of this node, and also notifies each of this
* nodes children that their parent's bounds have changed. As a result of
* this method getting called this nodes layoutChildren will be called.
*/
public void signalBoundsChanged() {
invalidateFullBounds();
setBoundsChanged(true);
firePropertyChange(PROPERTY_CODE_BOUNDS, PROPERTY_BOUNDS, null, bounds);
final int count = getChildrenCount();
for (int i = 0; i < count; i++) {
final PNode each = (PNode) children.get(i);
each.parentBoundsChanged();
}
}
/**
* Invalidate this node's layout, so that later layoutChildren will get
* called.
*/
public void invalidateLayout() {
invalidateFullBounds();
}
/**
* A notification that the bounds of this node's parent have changed.
*/
protected void parentBoundsChanged() {
}
/**
* Invalidates the full bounds of this node, and sets the child bounds
* invalid flag on each of this node's ancestors.
*/
public void invalidateFullBounds() {
setFullBoundsInvalid(true);
PNode n = parent;
while (n != null && !n.getChildBoundsInvalid()) {
n.setChildBoundsInvalid(true);
n = n.parent;
}
if (SCENE_GRAPH_DELEGATE != null) {
SCENE_GRAPH_DELEGATE.nodeFullBoundsInvalidated(this);
}
}
/**
* This method is called to validate the bounds of this node and all of its
* descendants. It returns true if this nodes bounds or the bounds of any of
* its descendants are marked as volatile.
*
* @return true if this node or any of its descendants have volatile bounds
*/
protected boolean validateFullBounds() {
final boolean boundsVolatile = getBoundsVolatile();
// 1. Only compute new bounds if invalid flags are set.
if (fullBoundsInvalid || childBoundsInvalid || boundsVolatile || childBoundsVolatile) {
// 2. If my bounds are volatile and they have not been changed then
// signal a change.
// For most cases this will do nothing, but if a nodes bounds depend
// on its model, then
// validate bounds has the responsibility of making the bounds match
// the models value.
// For example PPaths validateBounds method makes sure that the
// bounds are equal to the
// bounds of the GeneralPath model.
if (boundsVolatile && !boundsChanged) {
signalBoundsChanged();
}
// 3. If the bounds of on of my decendents are invalidate then
// validate the bounds of all of my children.
if (childBoundsInvalid || childBoundsVolatile) {
childBoundsVolatile = false;
final int count = getChildrenCount();
for (int i = 0; i < count; i++) {
final PNode each = (PNode) children.get(i);
childBoundsVolatile |= each.validateFullBounds();
}
}
// 4. Now that my children's bounds are valid and my own bounds are
// valid run any layout algorithm here. Note that if you try to
// layout volatile
// children piccolo will most likely start a "soft" infinite loop.
// It won't freeze
// your program, but it will make an infinite number of calls to
// SwingUtilities
// invoke later. You don't want to do that.
layoutChildren();
// 5. If the full bounds cache is invalid then recompute the full
// bounds cache here after our own bounds and the children's bounds
// have been computed above.
if (fullBoundsInvalid) {
final double oldX = fullBoundsCache.x;
final double oldY = fullBoundsCache.y;
final double oldWidth = fullBoundsCache.width;
final double oldHeight = fullBoundsCache.height;
final boolean oldEmpty = fullBoundsCache.isEmpty();
// 6. This will call getFullBoundsReference on all of the
// children. So if the above
// layoutChildren method changed the bounds of any of the
// children they will be
// validated again here.
fullBoundsCache = computeFullBounds(fullBoundsCache);
final boolean fullBoundsChanged = fullBoundsCache.x != oldX || fullBoundsCache.y != oldY
|| fullBoundsCache.width != oldWidth || fullBoundsCache.height != oldHeight
|| fullBoundsCache.isEmpty() != oldEmpty;
// 7. If the new full bounds cache differs from the previous
// cache then
// tell our parent to invalidate their full bounds. This is how
// bounds changes
// deep in the tree percolate up.
if (fullBoundsChanged) {
if (parent != null) {
parent.invalidateFullBounds();
}
firePropertyChange(PROPERTY_CODE_FULL_BOUNDS, PROPERTY_FULL_BOUNDS, null, fullBoundsCache);
// 8. If our paint was invalid make sure to repaint our old
// full bounds. The
// new bounds will be computed later in the validatePaint
// pass.
if (paintInvalid && !oldEmpty) {
TEMP_REPAINT_BOUNDS.setRect(oldX, oldY, oldWidth, oldHeight);
repaintFrom(TEMP_REPAINT_BOUNDS, this);
}
}
}
// 9. Clear the invalid bounds flags.
boundsChanged = false;
fullBoundsInvalid = false;
childBoundsInvalid = false;
}
return boundsVolatile || childBoundsVolatile;
}
/**
* Nodes that apply layout constraints to their children should override
* this method and do the layout there.
*/
protected void layoutChildren() {
}
// Node Transform - Methods to manipulate the node's transform.
// Each node has a transform that is used to define the nodes
// local coordinate system. IE it is applied before picking and
// rendering the node.
// The usual way to move nodes about on the canvas is to manipulate
// this transform, as opposed to changing the bounds of the
// node.
// Since this transform defines the local coordinate system of this
// node the following methods with affect the global position both
// this node and all of its descendants.
/**
* Returns the rotation applied by this node's transform in radians. This
* rotation affects this node and all its descendants. The value returned
* will be between 0 and 2pi radians.
*
* @return rotation in radians.
*/
public double getRotation() {
if (transform == null) {
return 0;
}
return transform.getRotation();
}
/**
* Sets the rotation of this nodes transform in radians. This will affect
* this node and all its descendents.
*
* @param theta rotation in radians
*/
public void setRotation(final double theta) {
rotate(theta - getRotation());
}
/**
* Rotates this node by theta (in radians) about the 0,0 point. This will
* affect this node and all its descendants.
*
* @param theta the amount to rotate by in radians
*/
public void rotate(final double theta) {
rotateAboutPoint(theta, 0, 0);
}
/**
* Rotates this node by theta (in radians), and then translates the node so
* that the x, y position of its fullBounds stays constant.
*
* @param theta the amount to rotate by in radians
*/
public void rotateInPlace(final double theta) {
PBounds b = getFullBoundsReference();
final double px = b.x;
final double py = b.y;
rotateAboutPoint(theta, 0, 0);
b = getFullBoundsReference();
offset(px - b.x, py - b.y);
}
/**
* Rotates this node by theta (in radians) about the given point. This will
* affect this node and all its descendants.
*
* @param theta the amount to rotate by in radians
* @param point the point about which to rotate
*/
public void rotateAboutPoint(final double theta, final Point2D point) {
rotateAboutPoint(theta, point.getX(), point.getY());
}
/**
* Rotates this node by theta (in radians) about the given point. This will
* affect this node and all its descendants.
*
* @param theta the amount to rotate by in radians
* @param x the x coordinate of the point around which to rotate
* @param y the y coordinate of the point around which to rotate
*/
public void rotateAboutPoint(final double theta, final double x, final double y) {
getTransformReference(true).rotate(theta, x, y);
invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_TRANSFORM, PROPERTY_TRANSFORM, null, transform);
}
/**
* Return the total amount of rotation applied to this node by its own
* transform together with the transforms of all its ancestors. The value
* returned will be between 0 and 2pi radians.
*
* @return the total amount of rotation applied to this node in radians
*/
public double getGlobalRotation() {
return getLocalToGlobalTransform(null).getRotation();
}
/**
* Set the global rotation (in radians) of this node. This is implemented by
* rotating this nodes transform the required amount so that the nodes
* global rotation is as requested.
*
* @param theta the amount to rotate by in radians relative to the global
* coordinate system.
*/
public void setGlobalRotation(final double theta) {
if (parent != null) {
setRotation(theta - parent.getGlobalRotation());
}
else {
setRotation(theta);
}
}
/**
* Return the scale applied by this node's transform. The scale is effecting
* this node and all its descendants.
*
* @return scale applied by this nodes transform.
*/
public double getScale() {
if (transform == null) {
return 1;
}
return transform.getScale();
}
/**
* Set the scale of this node's transform. The scale will affect this node
* and all its descendants.
*
* @param scale the scale to set the transform to
*/
public void setScale(final double scale) {
if (scale == 0) {
throw new RuntimeException("Can't set scale to 0");
}
scale(scale / getScale());
}
/**
* Scale this nodes transform by the given amount. This will affect this
* node and all of its descendants.
*
* @param scale the amount to scale by
*/
public void scale(final double scale) {
scaleAboutPoint(scale, 0, 0);
}
/**
* Scale this nodes transform by the given amount about the specified point.
* This will affect this node and all of its descendants.
*
* @param scale the amount to scale by
* @param point the point to scale about
*/
public void scaleAboutPoint(final double scale, final Point2D point) {
scaleAboutPoint(scale, point.getX(), point.getY());
}
/**
* Scale this nodes transform by the given amount about the specified point.
* This will affect this node and all of its descendants.
*
* @param scale the amount to scale by
* @param x the x coordinate of the point around which to scale
* @param y the y coordinate of the point around which to scale
*/
public void scaleAboutPoint(final double scale, final double x, final double y) {
getTransformReference(true).scaleAboutPoint(scale, x, y);
invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_TRANSFORM, PROPERTY_TRANSFORM, null, transform);
}
/**
* Return the global scale that is being applied to this node by its
* transform together with the transforms of all its ancestors.
*
* @return global scale of this node
*/
public double getGlobalScale() {
return getLocalToGlobalTransform(null).getScale();
}
/**
* Set the global scale of this node. This is implemented by scaling this
* nodes transform the required amount so that the nodes global scale is as
* requested.
*
* @param scale the desired global scale
*/
public void setGlobalScale(final double scale) {
if (parent != null) {
setScale(scale / parent.getGlobalScale());
}
else {
setScale(scale);
}
}
/**
* Returns the x offset of this node as applied by its transform.
*
* @return x offset of this node as applied by its transform
*/
public double getXOffset() {
if (transform == null) {
return 0;
}
return transform.getTranslateX();
}
/**
* Returns the y offset of this node as applied by its transform.
*
* @return y offset of this node as applied by its transform
*/
public double getYOffset() {
if (transform == null) {
return 0;
}
return transform.getTranslateY();
}
/**
* Return the offset that is being applied to this node by its transform.
* This offset effects this node and all of its descendants and is specified
* in the parent coordinate system. This returns the values that are in the
* m02 and m12 positions in the affine transform.
*
* @return a point representing the x and y offset
*/
public Point2D getOffset() {
if (transform == null) {
return new Point2D.Double();
}
return new Point2D.Double(transform.getTranslateX(), transform.getTranslateY());
}
/**
* Set the offset that is being applied to this node by its transform. This
* offset effects this node and all of its descendants and is specified in
* the nodes parent coordinate system. This directly sets the values of the
* m02 and m12 positions in the affine transform. Unlike "PNode.translate()"
* it is not effected by the transforms scale.
*
* @param point value of new offset
*/
public void setOffset(final Point2D point) {
setOffset(point.getX(), point.getY());
}
/**
* Set the offset that is being applied to this node by its transform. This
* offset effects this node and all of its descendants and is specified in
* the nodes parent coordinate system. This directly sets the values of the
* m02 and m12 positions in the affine transform. Unlike "PNode.translate()"
* it is not effected by the transforms scale.
*
* @param x amount of x offset
* @param y amount of y offset
*/
public void setOffset(final double x, final double y) {
getTransformReference(true).setOffset(x, y);
invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_TRANSFORM, PROPERTY_TRANSFORM, null, transform);
}
/**
* Offset this node relative to the parents coordinate system, and is NOT
* effected by this nodes current scale or rotation. This is implemented by
* directly adding dx to the m02 position and dy to the m12 position in the
* affine transform.
*
* @param dx amount to add to this nodes current x Offset
* @param dy amount to add to this nodes current y Offset
*/
public void offset(final double dx, final double dy) {
getTransformReference(true);
setOffset(transform.getTranslateX() + dx, transform.getTranslateY() + dy);
}
/**
* Translate this node's transform by the given amount, using the standard
* affine transform translate method. This translation effects this node and
* all of its descendants.
*
* @param dx amount to add to this nodes current x translation
* @param dy amount to add to this nodes current y translation
*/
public void translate(final double dx, final double dy) {
getTransformReference(true).translate(dx, dy);
invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_TRANSFORM, PROPERTY_TRANSFORM, null, transform);
}
/**
* Return the global translation that is being applied to this node by its
* transform together with the transforms of all its ancestors.
*
* @return the global translation applied to this node
*/
public Point2D getGlobalTranslation() {
final Point2D p = getOffset();
if (parent != null) {
parent.localToGlobal(p);
}
return p;
}
/**
* Set the global translation of this node. This is implemented by
* translating this nodes transform the required amount so that the nodes
* global scale is as requested.
*
* @param globalPoint the desired global translation
*/
public void setGlobalTranslation(final Point2D globalPoint) {
if (parent != null) {
parent.getGlobalToLocalTransform(null).transform(globalPoint, globalPoint);
}
setOffset(globalPoint);
}
/**
* Transform this nodes transform by the given transform.
*
* @param aTransform the transform to apply.
*/
public void transformBy(final AffineTransform aTransform) {
getTransformReference(true).concatenate(aTransform);
invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_TRANSFORM, PROPERTY_TRANSFORM, null, transform);
}
/**
* Linearly interpolates between a and b, based on t. Specifically, it
* computes lerp(a, b, t) = a + t*(b - a). This produces a result that
* changes from a (when t = 0) to b (when t = 1).
*
* @param t variable 'time' parameter
* @param a from point
* @param b to Point
*
* @return linear interpolation between and b at time interval t (given as #
* between 0f and 1f)
*/
public static double lerp(final double t, final double a, final double b) {
return a + t * (b - a);
}
/**
* This will calculate the necessary transform in order to make this node
* appear at a particular position relative to the specified bounding box.
* The source point specifies a point in the unit square (0, 0) - (1, 1)
* that represents an anchor point on the corresponding node to this
* transform. The destination point specifies an anchor point on the
* reference node. The position method then computes the transform that
* results in transforming this node so that the source anchor point
* coincides with the reference anchor point. This can be useful for layout
* algorithms as it is straightforward to position one object relative to
* another.
* <p>
* For example, If you have two nodes, A and B, and you call
*
* <PRE>
* Point2D srcPt = new Point2D.Double(1.0, 0.0);
* Point2D destPt = new Point2D.Double(0.0, 0.0);
* A.position(srcPt, destPt, B.getGlobalBounds(), 750, null);
* </PRE>
*
* The result is that A will move so that its upper-right corner is at the
* same place as the upper-left corner of B, and the transition will be
* smoothly animated over a period of 750 milliseconds.
*
* @since 1.3
* @param srcPt The anchor point on this transform's node (normalized to a
* unit square)
* @param destPt The anchor point on destination bounds (normalized to a
* unit square)
* @param destBounds The bounds (in global coordinates) used to calculate
* this transform's node
* @param millis Number of milliseconds over which to perform the animation
*
* @return newly scheduled activity or node if activity could not be
* scheduled
*/
public PActivity animateToRelativePosition(final Point2D srcPt, final Point2D destPt, final Rectangle2D destBounds,
final int millis) {
double srcx, srcy;
double destx, desty;
double dx, dy;
Point2D pt1, pt2;
if (parent == null) {
return null;
}
else {
// First compute translation amount in global coordinates
final Rectangle2D srcBounds = getGlobalFullBounds();
srcx = lerp(srcPt.getX(), srcBounds.getX(), srcBounds.getX() + srcBounds.getWidth());
srcy = lerp(srcPt.getY(), srcBounds.getY(), srcBounds.getY() + srcBounds.getHeight());
destx = lerp(destPt.getX(), destBounds.getX(), destBounds.getX() + destBounds.getWidth());
desty = lerp(destPt.getY(), destBounds.getY(), destBounds.getY() + destBounds.getHeight());
// Convert vector to local coordinates
pt1 = new Point2D.Double(srcx, srcy);
globalToLocal(pt1);
pt2 = new Point2D.Double(destx, desty);
globalToLocal(pt2);
dx = pt2.getX() - pt1.getX();
dy = pt2.getY() - pt1.getY();
// Finally, animate change
final PAffineTransform at = new PAffineTransform(getTransformReference(true));
at.translate(dx, dy);
return animateToTransform(at, millis);
}
}
/**
* @deprecated in favor of animateToRelativePosition
*
* It will calculate the necessary transform in order to make
* this node appear at a particular position relative to the
* specified bounding box. The source point specifies a point in
* the unit square (0, 0) - (1, 1) that represents an anchor
* point on the corresponding node to this transform. The
* destination point specifies an anchor point on the reference
* node. The position method then computes the transform that
* results in transforming this node so that the source anchor
* point coincides with the reference anchor point. This can be
* useful for layout algorithms as it is straightforward to
* position one object relative to another.
* <p>
* For example, If you have two nodes, A and B, and you call
*
* <PRE>
* Point2D srcPt = new Point2D.Double(1.0, 0.0);
* Point2D destPt = new Point2D.Double(0.0, 0.0);
* A.position(srcPt, destPt, B.getGlobalBounds(), 750, null);
* </PRE>
*
* The result is that A will move so that its upper-right corner
* is at the same place as the upper-left corner of B, and the
* transition will be smoothly animated over a period of 750
* milliseconds.
*
* @param srcPt The anchor point on this transform's node (normalized to a
* unit square)
* @param destPt The anchor point on destination bounds (normalized to a
* unit square)
* @param destBounds The bounds (in global coordinates) used to calculate
* this transform's node
* @param millis Number of milliseconds over which to perform the animation
*/
public void position(final Point2D srcPt, final Point2D destPt, final Rectangle2D destBounds, final int millis) {
animateToRelativePosition(srcPt, destPt, destBounds, millis);
};
/**
* Return a copy of the transform associated with this node.
*
* @return copy of this node's transform
*/
public PAffineTransform getTransform() {
if (transform == null) {
return new PAffineTransform();
}
else {
return (PAffineTransform) transform.clone();
}
}
/**
* Return a reference to the transform associated with this node. This
* returned transform should not be modified. PNode transforms are created
* lazily when needed. If you access the transform reference before the
* transform has been created it may return null. The
* createNewTransformIfNull parameter is used to specify that the PNode
* should create a new transform (and assign that transform to the nodes
* local transform variable) instead of returning null.
*
* @param createNewTransformIfNull if the transform has not been
* initialised, should it be?
*
* @return reference to this node's transform
*/
public PAffineTransform getTransformReference(final boolean createNewTransformIfNull) {
if (transform == null && createNewTransformIfNull) {
transform = new PAffineTransform();
}
return transform;
}
/**
* Return an inverted copy of the transform associated with this node.
*
* @return inverted copy of this node's transform
*/
public PAffineTransform getInverseTransform() {
if (transform == null) {
return new PAffineTransform();
}
try {
return new PAffineTransform(transform.createInverse());
}
catch (final NoninvertibleTransformException e) {
throw new PAffineTransformException(e, transform);
}
}
/**
* Set the transform applied to this node.
*
* @param transform the new transform value
*/
public void setTransform(final AffineTransform transform) {
if (transform == null) {
this.transform = null;
}
else {
getTransformReference(true).setTransform(transform);
}
invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_TRANSFORM, PROPERTY_TRANSFORM, null, this.transform);
}
// Paint Damage Management - Methods used to invalidate the areas of
// the screen that this node appears in so that they will later get
// painted.
// Generally you will not need to call these invalidate methods
// when starting out with Piccolo2d because methods such as setPaint
// already automatically call them for you. You will need to call
// them when you start creating your own nodes.
// When you do create you own nodes the only method that you will
// normally need to call is invalidatePaint. This method marks the
// nodes as having invalid paint, the root node's UI cycle will then
// later discover this damage and report it to the Java repaint manager.
// Repainting is normally done with PNode.invalidatePaint() instead of
// directly calling PNode.repaint() because PNode.repaint() requires
// the nodes bounds to be computed right away. But with invalidatePaint
// the bounds computation can be delayed until the end of the root's UI
// cycle, and this can add up to a bit savings when modifying a
// large number of nodes all at once.
// The other methods here will rarely be called except internally
// from the framework.
/**
* Return true if this nodes paint is invalid, in which case the node needs
* to be repainted.
*
* @return true if this node needs to be repainted
*/
public boolean getPaintInvalid() {
return paintInvalid;
}
/**
* Mark this node as having invalid paint. If this is set the node will
* later be repainted. Node this method is most often used internally.
*
* @param paintInvalid true if this node should be repainted
*/
public void setPaintInvalid(final boolean paintInvalid) {
this.paintInvalid = paintInvalid;
}
/**
* Return true if this node has a child with invalid paint.
*
* @return true if this node has a child with invalid paint
*/
public boolean getChildPaintInvalid() {
return childPaintInvalid;
}
/**
* Mark this node as having a child with invalid paint.
*
* @param childPaintInvalid true if this node has a child with invalid paint
*/
public void setChildPaintInvalid(final boolean childPaintInvalid) {
this.childPaintInvalid = childPaintInvalid;
}
/**
* Invalidate this node's paint, and mark all of its ancestors as having a
* node with invalid paint.
*/
public void invalidatePaint() {
setPaintInvalid(true);
PNode n = parent;
while (n != null && !n.getChildPaintInvalid()) {
n.setChildPaintInvalid(true);
n = n.parent;
}
if (SCENE_GRAPH_DELEGATE != null) {
SCENE_GRAPH_DELEGATE.nodePaintInvalidated(this);
}
}
/**
* Repaint this node and any of its descendants if they have invalid paint.
*/
public void validateFullPaint() {
if (getPaintInvalid()) {
repaint();
setPaintInvalid(false);
}
if (getChildPaintInvalid()) {
final int count = getChildrenCount();
for (int i = 0; i < count; i++) {
final PNode each = (PNode) children.get(i);
each.validateFullPaint();
}
setChildPaintInvalid(false);
}
}
/**
* Mark the area on the screen represented by this nodes full bounds as
* needing a repaint.
*/
public void repaint() {
TEMP_REPAINT_BOUNDS.setRect(getFullBoundsReference());
repaintFrom(TEMP_REPAINT_BOUNDS, this);
}
/**
* Pass the given repaint request up the tree, so that any cameras can
* invalidate that region on their associated canvas.
*
* @param localBounds the bounds to repaint
* @param childOrThis if childOrThis does not equal this then this nodes
* transform will be applied to the localBounds param
*/
public void repaintFrom(final PBounds localBounds, final PNode childOrThis) {
if (parent != null) {
if (childOrThis != this) {
localToParent(localBounds);
}
else if (!getVisible()) {
return;
}
parent.repaintFrom(localBounds, this);
}
}
// Occluding - Methods to support occluding optimisation. Not yet
// complete.
/**
* Returns whether this node is Opaque.
*
* @param boundary boundary to check and see if this node covers completely.
*
* @return true if opaque
*/
public boolean isOpaque(final Rectangle2D boundary) {
return false;
}
/**
* Returns whether this node has been flagged as occluded.
*
* @return true if occluded
*/
public boolean getOccluded() {
return occluded;
}
/**
* Flags this node as occluded.
*
* @param occluded new value for occluded
*/
public void setOccluded(final boolean occluded) {
this.occluded = occluded;
}
// Painting - Methods for painting this node and its children
// Painting is how a node defines its visual representation on the
// screen, and is done in the local coordinate system of the node.
// The default painting behavior is to first paint the node, and
// then paint the node's children on top of the node. If a node
// needs wants specialised painting behavior it can override:
// paint() - Painting here will happen before the children
// are painted, so the children will be painted on top of painting done
// here.
// paintAfterChildren() - Painting here will happen after the children
// are painted, so it will paint on top of them.
// Note that you should not normally need to override fullPaint().
// The visible flag can be used to make a node invisible so that
// it will never get painted.
/**
* Return true if this node is visible, that is if it will paint itself and
* descendants.
*
* @return true if this node and its descendants are visible.
*/
public boolean getVisible() {
return visible;
}
/**
* Set the visibility of this node and its descendants.
*
* @param isVisible true if this node and its descendants are visible
*/
public void setVisible(final boolean isVisible) {
if (getVisible() != isVisible) {
if (!isVisible) {
repaint();
}
visible = isVisible;
firePropertyChange(PROPERTY_CODE_VISIBLE, PROPERTY_VISIBLE, null, null);
invalidatePaint();
}
}
/**
* Return the paint used while painting this node. This value may be null.
*
* @return the paint used while painting this node.
*/
public Paint getPaint() {
return paint;
}
/**
* Set the paint used to paint this node, which may be null.
*
* @param newPaint paint that this node should use when painting itself.
*/
public void setPaint(final Paint newPaint) {
if (paint == newPaint) {
return;
}
final Paint oldPaint = paint;
paint = newPaint;
invalidatePaint();
firePropertyChange(PROPERTY_CODE_PAINT, PROPERTY_PAINT, oldPaint, paint);
}
/**
* Return the transparency used when painting this node. Note that this
* transparency is also applied to all of the node's descendants.
*
* @return how transparent this node is 0f = completely transparent, 1f =
* completely opaque
*/
public float getTransparency() {
return transparency;
}
/**
* Set the transparency used to paint this node. Note that this transparency
* applies to this node and all of its descendants.
*
* @param newTransparency transparency value for this node. 0f = fully
* transparent, 1f = fully opaque
*/
public void setTransparency(final float newTransparency) {
if (Math.abs(transparency - newTransparency) > TRANSPARENCY_RESOLUTION) {
final float oldTransparency = transparency;
transparency = newTransparency;
invalidatePaint();
firePropertyChange(PROPERTY_CODE_TRANSPARENCY, PROPERTY_TRANSPARENCY, new Float(oldTransparency),
new Float(newTransparency));
}
}
/**
* Paint this node behind any of its children nodes. Subclasses that define
* a different appearance should override this method and paint themselves
* there.
*
* @param paintContext the paint context to use for painting the node
*/
protected void paint(final PPaintContext paintContext) {
if (paint != null) {
final Graphics2D g2 = paintContext.getGraphics();
g2.setPaint(paint);
g2.fill(getBoundsReference());
}
}
/**
* Paint this node and all of its descendants. Most subclasses do not need
* to override this method, they should override <code>paint</code> or
* <code>paintAfterChildren</code> instead.
*
* @param paintContext the paint context to use for painting this node and
* its children
*/
public void fullPaint(final PPaintContext paintContext) {
if (getVisible() && fullIntersects(paintContext.getLocalClip())) {
paintContext.pushTransform(transform);
paintContext.pushTransparency(transparency);
if (!getOccluded()) {
paint(paintContext);
}
final int count = getChildrenCount();
for (int i = 0; i < count; i++) {
final PNode each = (PNode) children.get(i);
each.fullPaint(paintContext);
}
paintAfterChildren(paintContext);
paintContext.popTransparency(transparency);
paintContext.popTransform(transform);
}
}
/**
* Subclasses that wish to do additional painting after their children are
* painted should override this method and do that painting here.
*
* @param paintContext the paint context to sue for painting after the
* children are painted
*/
protected void paintAfterChildren(final PPaintContext paintContext) {
}
/**
* Return a new Image representing this node and all of its children. The
* image size will be equal to the size of this nodes full bounds.
*
* @return a new image representing this node and its descendants
*/
public Image toImage() {
final PBounds b = getFullBoundsReference();
return toImage((int) Math.ceil(b.getWidth()), (int) Math.ceil(b.getHeight()), null);
}
/**
* Return a new Image of the requested size representing this node and all
* of its children. If backGroundPaint is null the resulting image will have
* transparent regions, otherwise those regions will be filled with the
* backgroundPaint.
*
* @param width pixel width of the resulting image
* @param height pixel height of the resulting image
* @param backgroundPaint paint to fill the image with before drawing this
* node, may be null
*
* @return a new image representing this node and its descendants
*/
public Image toImage(final int width, final int height, final Paint backgroundPaint) {
BufferedImage result;
if (GraphicsEnvironment.isHeadless()) {
result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
else {
final GraphicsConfiguration graphicsConfiguration = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration();
result = graphicsConfiguration.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
}
return toImage(result, backgroundPaint);
}
/**
* Paint a representation of this node into the specified buffered image. If
* background, paint is null, then the image will not be filled with a color
* prior to rendering
*
* @param image Image onto which this node will be painted
* @param backGroundPaint will fill background of image with this. May be
* null.
* @return a rendering of this image and its descendants onto the specified
* image
*/
public Image toImage(final BufferedImage image, final Paint backGroundPaint) {
return toImage(image, backGroundPaint, FILL_STRATEGY_ASPECT_FIT);
}
/**
* Paint a representation of this node into the specified buffered image. If
* background, paint is null, then the image will not be filled with a color
* prior to rendering
*
* @since 1.3
* @param image Image onto which this node will be painted
* @param backGroundPaint will fill background of image with this. May be
* null.
* @param fillStrategy strategy to use regarding how node will cover the
* image
* @return a rendering of this image and its descendants onto the specified
* image
*/
public Image toImage(final BufferedImage image, final Paint backGroundPaint, final int fillStrategy) {
final int imageWidth = image.getWidth();
final int imageHeight = image.getHeight();
final Graphics2D g2 = image.createGraphics();
if (backGroundPaint != null) {
g2.setPaint(backGroundPaint);
g2.fillRect(0, 0, imageWidth, imageHeight);
}
g2.setClip(0, 0, imageWidth, imageHeight);
final PBounds nodeBounds = getFullBounds();
nodeBounds.expandNearestIntegerDimensions();
final double nodeWidth = nodeBounds.getWidth();
final double nodeHeight = nodeBounds.getHeight();
double imageRatio = imageWidth / (imageHeight * 1.0);
double nodeRatio = nodeWidth / nodeHeight;
double scale;
switch (fillStrategy) {
case FILL_STRATEGY_ASPECT_FIT:
// scale the graphics so node's full bounds fit in the imageable
// bounds but aspect ration is retained
if (nodeRatio <= imageRatio) {
scale = image.getHeight() / nodeHeight;
}
else {
scale = image.getWidth() / nodeWidth;
}
g2.scale(scale, scale);
g2.translate(-nodeBounds.x, -nodeBounds.y);
break;
case FILL_STRATEGY_ASPECT_COVER:
// scale the graphics so node completely covers the imageable
// area, but retains its aspect ratio.
if (nodeRatio <= imageRatio) {
scale = image.getWidth() / nodeWidth;
}
else {
scale = image.getHeight() / nodeHeight;
}
g2.scale(scale, scale);
break;
case FILL_STRATEGY_EXACT_FIT:
// scale the node so that it covers then entire image,
// distorting it if necessary.
g2.scale(image.getWidth() / nodeWidth, image.getHeight() / nodeHeight);
g2.translate(-nodeBounds.x, -nodeBounds.y);
break;
default:
throw new IllegalArgumentException("Fill strategy provided is invalid");
}
final PPaintContext pc = new PPaintContext(g2);
pc.setRenderQuality(PPaintContext.HIGH_QUALITY_RENDERING);
fullPaint(pc);
return image;
}
/**
* Constructs a new PrinterJob, allows the user to select which printer to
* print to, And then prints the node.
*/
public void print() {
final PrinterJob printJob = PrinterJob.getPrinterJob();
final PageFormat pageFormat = printJob.defaultPage();
final Book book = new Book();
book.append(this, pageFormat);
printJob.setPageable(book);
if (printJob.printDialog()) {
try {
printJob.print();
}
catch (final PrinterException e) {
throw new RuntimeException("Error Printing", e);
}
}
}
/**
* Prints the node into the given Graphics context using the specified
* format. The zero based index of the requested page is specified by
* pageIndex. If the requested page does not exist then this method returns
* NO_SUCH_PAGE; otherwise PAGE_EXISTS is returned. If the printable object
* aborts the print job then it throws a PrinterException.
*
* @param graphics the context into which the node is drawn
* @param pageFormat the size and orientation of the page
* @param pageIndex the zero based index of the page to be drawn
*
* @return Either NO_SUCH_PAGE or PAGE_EXISTS
*/
public int print(final Graphics graphics, final PageFormat pageFormat, final int pageIndex) {
if (pageIndex != 0) {
return NO_SUCH_PAGE;
}
if (!(graphics instanceof Graphics2D)) {
throw new IllegalArgumentException("Provided graphics context is not a Graphics2D object");
}
final Graphics2D g2 = (Graphics2D) graphics;
final PBounds imageBounds = getFullBounds();
imageBounds.expandNearestIntegerDimensions();
g2.setClip(0, 0, (int) pageFormat.getWidth(), (int) pageFormat.getHeight());
g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
// scale the graphics so node's full bounds fit in the imageable bounds.
double scale = pageFormat.getImageableWidth() / imageBounds.getWidth();
if (pageFormat.getImageableHeight() / imageBounds.getHeight() < scale) {
scale = pageFormat.getImageableHeight() / imageBounds.getHeight();
}
g2.scale(scale, scale);
g2.translate(-imageBounds.x, -imageBounds.y);
final PPaintContext pc = new PPaintContext(g2);
pc.setRenderQuality(PPaintContext.HIGH_QUALITY_RENDERING);
fullPaint(pc);
return PAGE_EXISTS;
}
// Picking - Methods for picking this node and its children.
// Picking is used to determine the node that intersects a point or
// rectangle on the screen. It is most frequently used by the
// PInputManager to determine the node that the cursor is over.
// The intersects() method is used to determine if a node has
// been picked or not. The default implementation just test to see
// if the pick bounds intersects the bounds of the node. Subclasses
// whose geometry (a circle for example) does not match up exactly with
// the bounds should override the intersects() method.
// The default picking behavior is to first try to pick the nodes
// children, and then try to pick the nodes own bounds. If a node
// wants specialized picking behavior it can override:
// pick() - Pick nodes here that should be picked before the nodes
// children are picked.
// pickAfterChildren() - Pick nodes here that should be picked after the
// node's children are picked.
// Note that fullPick should not normally be overridden.
// The pickable and childrenPickable flags can be used to make a
// node or it children not pickable even if their geometry does
// intersect the pick bounds.
/**
* Return true if this node is pickable. Only pickable nodes can receive
* input events. Nodes are pickable by default.
*
* @return true if this node is pickable
*/
public boolean getPickable() {
return pickable;
}
/**
* Set the pickable flag for this node. Only pickable nodes can receive
* input events. Nodes are pickable by default.
*
* @param isPickable true if this node is pickable
*/
public void setPickable(final boolean isPickable) {
if (getPickable() != isPickable) {
pickable = isPickable;
firePropertyChange(PROPERTY_CODE_PICKABLE, PROPERTY_PICKABLE, null, null);
}
}
/**
* Return true if the children of this node should be picked. If this flag
* is false then this node will not try to pick its children. Children are
* pickable by default.
*
* @return true if this node tries to pick its children
*/
public boolean getChildrenPickable() {
return childrenPickable;
}
/**
* Set the children pickable flag. If this flag is false then this node will
* not try to pick its children. Children are pickable by default.
*
* @param areChildrenPickable true if this node tries to pick its children
*/
public void setChildrenPickable(final boolean areChildrenPickable) {
if (getChildrenPickable() != areChildrenPickable) {
childrenPickable = areChildrenPickable;
firePropertyChange(PROPERTY_CODE_CHILDREN_PICKABLE, PROPERTY_CHILDREN_PICKABLE, null, null);
}
}
/**
* Try to pick this node before its children have had a chance to be picked.
* Nodes that paint on top of their children may want to override this
* method to if the pick path intersects that paint.
*
* @param pickPath the pick path used for the pick operation
* @return true if this node was picked
*/
protected boolean pick(final PPickPath pickPath) {
return false;
}
/**
* Try to pick this node and all of its descendants. Most subclasses should
* not need to override this method. Instead they should override
* <code>pick</code> or <code>pickAfterChildren</code>.
*
* @param pickPath the pick path to add the node to if its picked
* @return true if this node or one of its descendants was picked.
*/
public boolean fullPick(final PPickPath pickPath) {
if (getVisible() && (getPickable() || getChildrenPickable()) && fullIntersects(pickPath.getPickBounds())) {
pickPath.pushNode(this);
pickPath.pushTransform(transform);
final boolean thisPickable = getPickable() && pickPath.acceptsNode(this);
if (thisPickable && pick(pickPath)) {
return true;
}
if (getChildrenPickable()) {
final int count = getChildrenCount();
for (int i = count - 1; i >= 0; i
final PNode each = (PNode) children.get(i);
if (each.fullPick(pickPath)) {
return true;
}
}
}
if (thisPickable && pickAfterChildren(pickPath)) {
return true;
}
pickPath.popTransform(transform);
pickPath.popNode(this);
}
return false;
}
/**
* Finds all descendants of this node that intersect with the given bounds
* and adds them to the results array.
*
* @param fullBounds bounds to compare against
* @param results array into which to add matches
*/
public void findIntersectingNodes(final Rectangle2D fullBounds, final ArrayList results) {
if (fullIntersects(fullBounds)) {
final Rectangle2D localBounds = parentToLocal((Rectangle2D) fullBounds.clone());
if (intersects(localBounds)) {
results.add(this);
}
final int count = getChildrenCount();
for (int i = count - 1; i >= 0; i
final PNode each = (PNode) children.get(i);
each.findIntersectingNodes(localBounds, results);
}
}
}
/**
* Try to pick this node after its children have had a chance to be picked.
* Most subclasses the define a different geometry will need to override
* this method.
*
* @param pickPath the pick path used for the pick operation
* @return true if this node was picked
*/
protected boolean pickAfterChildren(final PPickPath pickPath) {
if (intersects(pickPath.getPickBounds())) {
return true;
}
return false;
}
// Structure - Methods for manipulating and traversing the
// parent child relationship
// Most of these methods won't need to be overridden by subclasses
// but you will use them frequently to build up your node structures.
/**
* Add a node to be a new child of this node. The new node is added to the
* end of the list of this node's children. If child was previously a child
* of another node, it is removed from that first.
*
* @param child the new child to add to this node
*/
public void addChild(final PNode child) {
int insertIndex = getChildrenCount();
if (child.parent == this) {
insertIndex
}
addChild(insertIndex, child);
}
/**
* Add a node to be a new child of this node at the specified index. If
* child was previously a child of another node, it is removed from that
* node first.
*
* @param index where in the children list to insert the child
* @param child the new child to add to this node
*/
public void addChild(final int index, final PNode child) {
final PNode oldParent = child.getParent();
if (oldParent != null) {
oldParent.removeChild(child);
}
child.setParent(this);
getChildrenReference().add(index, child);
child.invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_CHILDREN, PROPERTY_CHILDREN, null, children);
}
/**
* Add a collection of nodes to be children of this node. If these nodes
* already have parents they will first be removed from those parents.
*
* @param nodes a collection of nodes to be added to this node
*/
public void addChildren(final Collection nodes) {
final Iterator i = nodes.iterator();
while (i.hasNext()) {
final PNode each = (PNode) i.next();
addChild(each);
}
}
/**
* Return true if this node is an ancestor of the parameter node.
*
* @param node a possible descendant node
* @return true if this node is an ancestor of the given node
*/
public boolean isAncestorOf(final PNode node) {
PNode p = node.parent;
while (p != null) {
if (p == this) {
return true;
}
p = p.parent;
}
return false;
}
/**
* Return true if this node is a descendant of the parameter node.
*
* @param node a possible ancestor node
* @return true if this nodes descends from the given node
*/
public boolean isDescendentOf(final PNode node) {
PNode p = parent;
while (p != null) {
if (p == node) {
return true;
}
p = p.parent;
}
return false;
}
/**
* Return true if this node descends from the root.
*
* @return whether this node descends from root node
*/
public boolean isDescendentOfRoot() {
return getRoot() != null;
}
/**
* Change the order of this node in its parent's children list so that it
* will draw in back of all of its other sibling nodes.
*/
public void moveToBack() {
final PNode p = parent;
if (p != null) {
p.removeChild(this);
p.addChild(0, this);
}
}
/**
* Change the order of this node in its parent's children list so that it
* will draw in back of the specified sibling node.
*
* @param sibling sibling to move in back of
*/
public void moveInBackOf(final PNode sibling) {
final PNode p = parent;
if (p != null && p == sibling.getParent()) {
p.removeChild(this);
final int index = p.indexOfChild(sibling);
p.addChild(index, this);
}
}
/**
* Change the order of this node in its parent's children list so that it
* will draw in front of all of its other sibling nodes.
*/
public void moveToFront() {
final PNode p = parent;
if (p != null) {
p.removeChild(this);
p.addChild(this);
}
}
/**
* Change the order of this node in its parent's children list so that it
* will draw in front of the specified sibling node.
*
* @param sibling sibling to move in front of
*/
public void moveInFrontOf(final PNode sibling) {
final PNode p = parent;
if (p != null && p == sibling.getParent()) {
p.removeChild(this);
final int index = p.indexOfChild(sibling);
p.addChild(index + 1, this);
}
}
/**
* Return the parent of this node. This will be null if this node has not
* been added to a parent yet.
*
* @return this nodes parent or null
*/
public PNode getParent() {
return parent;
}
/**
* Set the parent of this node. Note this is set automatically when adding
* and removing children.
*
* @param newParent the parent to which this node should be added
*/
public void setParent(final PNode newParent) {
final PNode old = parent;
parent = newParent;
firePropertyChange(PROPERTY_CODE_PARENT, PROPERTY_PARENT, old, parent);
}
/**
* Return the index where the given child is stored.
*
* @param child child so search for
* @return index of child or -1 if not found
*/
public int indexOfChild(final PNode child) {
if (children == null) {
return -1;
}
return children.indexOf(child);
}
/**
* Remove the given child from this node's children list. Any subsequent
* children are shifted to the left (one is subtracted from their indices).
* The removed child's parent is set to null.
*
* @param child the child to remove
* @return the removed child
*/
public PNode removeChild(final PNode child) {
final int index = indexOfChild(child);
if (index == -1) {
return null;
}
return removeChild(index);
}
/**
* Remove the child at the specified position of this group node's children.
* Any subsequent children are shifted to the left (one is subtracted from
* their indices). The removed child's parent is set to null.
*
* @param index the index of the child to remove
* @return the removed child
*/
public PNode removeChild(final int index) {
if (children == null) {
return null;
}
final PNode child = (PNode) children.remove(index);
if (children.size() == 0) {
children = null;
}
child.repaint();
child.setParent(null);
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_CHILDREN, PROPERTY_CHILDREN, null, children);
return child;
}
/**
* Remove all the children in the given collection from this node's list of
* children. All removed nodes will have their parent set to null.
*
* @param childrenNodes the collection of children to remove
*/
public void removeChildren(final Collection childrenNodes) {
final Iterator i = childrenNodes.iterator();
while (i.hasNext()) {
final PNode each = (PNode) i.next();
removeChild(each);
}
}
/**
* Remove all the children from this node. Node this method is more
* efficient then removing each child individually.
*/
public void removeAllChildren() {
if (children != null) {
final int count = children.size();
for (int i = 0; i < count; i++) {
final PNode each = (PNode) children.get(i);
each.setParent(null);
}
children = null;
invalidatePaint();
invalidateFullBounds();
firePropertyChange(PROPERTY_CODE_CHILDREN, PROPERTY_CHILDREN, null, children);
}
}
/**
* Delete this node by removing it from its parent's list of children.
*/
public void removeFromParent() {
if (parent != null) {
parent.removeChild(this);
}
}
/**
* Set the parent of this node, and transform the node in such a way that it
* doesn't move in global coordinates.
*
* @param newParent The new parent of this node.
*/
public void reparent(final PNode newParent) {
final AffineTransform originalTransform = getLocalToGlobalTransform(null);
final AffineTransform newTransform = newParent.getGlobalToLocalTransform(null);
newTransform.concatenate(originalTransform);
removeFromParent();
setTransform(newTransform);
newParent.addChild(this);
computeFullBounds(fullBoundsCache);
}
/**
* Swaps this node out of the scene graph tree, and replaces it with the
* specified replacement node. This node is left dangling, and it is up to
* the caller to manage it. The replacement node will be added to this
* node's parent in the same position as this was. That is, if this was the
* 3rd child of its parent, then after calling replaceWith(), the
* replacement node will also be the 3rd child of its parent. If this node
* has no parent when replace is called, then nothing will be done at all.
*
* @param replacementNode the new node that replaces the current node in the
* scene graph tree.
*/
public void replaceWith(final PNode replacementNode) {
if (parent != null) {
final PNode p = parent;
final int index = p.getChildrenReference().indexOf(this);
p.removeChild(this);
p.addChild(index, replacementNode);
}
}
/**
* Sets the name of this null, may be null.
*
* @since 1.3
* @param name new name for this node
*/
public void setName(final String name) {
this.name = name;
}
/**
* Returns the name given to this node.
*
* @since 1.3
* @return name given to this node, may be null
*/
public String getName() {
return name;
}
/**
* Return the number of children that this node has.
*
* @return the number of children
*/
public int getChildrenCount() {
if (children == null) {
return 0;
}
return children.size();
}
/**
* Return the child node at the specified index.
*
* @param index a child index
* @return the child node at the specified index
*/
public PNode getChild(final int index) {
return (PNode) children.get(index);
}
/**
* Return a reference to the list used to manage this node's children. This
* list should not be modified.
*
* @return reference to the children list
*/
public List getChildrenReference() {
if (children == null) {
children = new ArrayList();
}
return children;
}
/**
* Return an iterator over this node's direct descendant children.
*
* @return iterator over this nodes children
*/
public ListIterator getChildrenIterator() {
if (children == null) {
return Collections.EMPTY_LIST.listIterator();
}
return Collections.unmodifiableList(children).listIterator();
}
/**
* Return the root node (instance of PRoot). If this node does not descend
* from a PRoot then null will be returned.
*
* @return root element of this node, or null if this node does not descend
* from a PRoot
*/
public PRoot getRoot() {
if (parent != null) {
return parent.getRoot();
}
return null;
}
/**
* Return a collection containing this node and all of its descendant nodes.
*
* @return a new collection containing this node and all descendants
*/
public Collection getAllNodes() {
return getAllNodes(null, null);
}
/**
* Return a collection containing the subset of this node and all of its
* descendant nodes that are accepted by the given node filter. If the
* filter is null then all nodes will be accepted. If the results parameter
* is not null then it will be used to collect this subset instead of
* creating a new collection.
*
* @param filter the filter used to determine the subset
* @param resultantNodes where matching nodes should be added
* @return a collection containing this node and all descendants
*/
public Collection getAllNodes(final PNodeFilter filter, final Collection resultantNodes) {
Collection results;
if (resultantNodes == null) {
results = new ArrayList();
}
else {
results = resultantNodes;
}
if (filter == null || filter.accept(this)) {
results.add(this);
}
if (filter == null || filter.acceptChildrenOf(this)) {
final int count = getChildrenCount();
for (int i = 0; i < count; i++) {
final PNode each = (PNode) children.get(i);
each.getAllNodes(filter, results);
}
}
return results;
}
// Serialization - Nodes conditionally serialize their parent.
// This means that only the parents that were unconditionally
// (using writeObject) serialized by someone else will be restored
// when the node is unserialized.
/**
* Write this node and all of its descendant nodes to the given outputsteam.
* This stream must be an instance of PObjectOutputStream or serialization
* will fail. This nodes parent is written out conditionally, that is it
* will only be written out if someone else writes it out unconditionally.
*
* @param out the output stream to write to, must be an instance of
* PObjectOutputStream
* @throws IOException when an error occurs speaking to underlying
* ObjectOutputStream
*/
private void writeObject(final ObjectOutputStream out) throws IOException {
if (!(out instanceof PObjectOutputStream)) {
throw new IllegalArgumentException("PNode.writeObject may only be used with PObjectOutputStreams");
}
out.defaultWriteObject();
((PObjectOutputStream) out).writeConditionalObject(parent);
}
/**
* Read this node and all of its descendants in from the given input stream.
*
* @param in the stream to read from
*
* @throws IOException when an error occurs speaking to underlying
* ObjectOutputStream
* @throws ClassNotFoundException when a class is deserialized that no
* longer exists. This can happen if it's renamed or deleted.
*/
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
parent = (PNode) in.readObject();
}
protected String paramString() {
return "";
}
/**
* Returns an array of input event listeners that are attached to this node.
*
* @since 1.3
* @return event listeners attached to this node
*/
public PInputEventListener[] getInputEventListeners() {
if (listenerList == null || listenerList.getListenerCount() == 0) {
return new PInputEventListener[] {};
}
final EventListener[] listeners = listenerList.getListeners(PInputEventListener.class);
final PInputEventListener[] result = new PInputEventListener[listeners.length];
for (int i = 0; i < listeners.length; i++) {
result[i] = (PInputEventListener) listeners[i];
}
return result;
}
private static final class ClientPropertyKeyIterator implements Iterator {
private final Enumeration enumeration;
private ClientPropertyKeyIterator(final Enumeration enumeration) {
this.enumeration = enumeration;
}
public boolean hasNext() {
return enumeration.hasMoreElements();
}
public Object next() {
return enumeration.nextElement();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* <b>PSceneGraphDelegate</b> is an interface to receive low level node
* events. It together with PNode.SCENE_GRAPH_DELEGATE gives Piccolo2d users
* an efficient way to learn about low level changes in Piccolo's scene
* graph. Most users will not need to use this.
*/
public interface PSceneGraphDelegate {
/**
* Called to notify delegate that the node needs repainting.
*
* @param node node needing repaint
*/
void nodePaintInvalidated(PNode node);
/**
* Called to notify delegate that the node and all it's children need
* repainting.
*
* @param node node needing repaint
*/
void nodeFullBoundsInvalidated(PNode node);
}
}
|
package com.facebook.animated.webpdrawable;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import com.facebook.animated.webp.WebPFrame;
import com.facebook.animated.webp.WebPImage;
import com.facebook.fresco.animation.backend.AnimationBackend;
import java.io.BufferedInputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
/** Animation backend that is used to draw webp frames. */
public class WebpAnimationBackend implements AnimationBackend {
private final Rect mRenderDstRect = new Rect();
private final Rect mRenderSrcRect = new Rect();
private final WebPImage mWebPImage;
private Rect mBounds;
@GuardedBy("this")
private @Nullable Bitmap mTempBitmap;
public static WebpAnimationBackend create(String filePath) throws IOException {
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(filePath));
is.mark(Integer.MAX_VALUE);
byte[] targetArray = new byte[is.available()];
is.read(targetArray);
WebPImage webPImage = WebPImage.createFromByteArray(targetArray, null);
is.reset();
return new WebpAnimationBackend(webPImage);
} finally {
closeSilently(is);
}
}
private WebpAnimationBackend(WebPImage webPImage) {
mWebPImage = webPImage;
}
@Override
public boolean drawFrame(Drawable parent, Canvas canvas, int frameNumber) {
WebPFrame frame = mWebPImage.getFrame(frameNumber);
double xScale = (double) mBounds.width() / (double) parent.getIntrinsicWidth();
double yScale = (double) mBounds.height() / (double) parent.getIntrinsicHeight();
int frameWidth = (int) Math.round(frame.getWidth() * xScale);
int frameHeight = (int) Math.round(frame.getHeight() * yScale);
int xOffset = (int) (frame.getXOffset() * xScale);
int yOffset = (int) (frame.getYOffset() * yScale);
synchronized (this) {
int renderedWidth = mBounds.width();
int renderedHeight = mBounds.height();
// Update the temp bitmap to be >= rendered dimensions
prepareTempBitmapForThisSize(renderedWidth, renderedHeight);
if (mTempBitmap == null) {
return false;
}
frame.renderFrame(frameWidth, frameHeight, mTempBitmap);
// Temporary bitmap can be bigger than frame, so we should draw only rendered area of bitmap
mRenderSrcRect.set(0, 0, renderedWidth, renderedHeight);
mRenderDstRect.set(xOffset, yOffset, xOffset + renderedWidth, yOffset + renderedHeight);
canvas.drawBitmap(mTempBitmap, mRenderSrcRect, mRenderDstRect, null);
}
return true;
}
@Override
public void setAlpha(int alpha) {
// unimplemented
}
@Override
public void setColorFilter(@Nullable ColorFilter colorFilter) {
// unimplemented
}
@Override
public synchronized void setBounds(Rect bounds) {
mBounds = bounds;
}
@Override
public int getIntrinsicWidth() {
return mWebPImage.getWidth();
}
@Override
public int getIntrinsicHeight() {
return mWebPImage.getHeight();
}
@Override
public int getSizeInBytes() {
return 0;
}
@Override
public void clear() {
mWebPImage.dispose();
}
@Override
public int getFrameCount() {
return mWebPImage.getFrameCount();
}
@Override
public int getFrameDurationMs(int frameNumber) {
return mWebPImage.getFrameDurations()[frameNumber];
}
@Override
public int getLoopCount() {
return mWebPImage.getLoopCount();
}
private synchronized void prepareTempBitmapForThisSize(int width, int height) {
// Different webp frames can be different size,
// So we need to ensure we can fit next frame to temporary bitmap
if (mTempBitmap != null
&& (mTempBitmap.getWidth() < width || mTempBitmap.getHeight() < height)) {
clearTempBitmap();
}
if (mTempBitmap == null) {
mTempBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
}
mTempBitmap.eraseColor(Color.TRANSPARENT);
}
private synchronized void clearTempBitmap() {
if (mTempBitmap != null) {
mTempBitmap.recycle();
mTempBitmap = null;
}
}
private static void closeSilently(@Nullable Closeable closeable) {
if (closeable == null) {
return;
}
try {
closeable.close();
} catch (IOException ignored) {
// ignore
}
}
}
|
package org.javasimon.jdbc4;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Simon JDBC4 Proxy Driver.
* <p>
* An application should not use this class directly. The application (if standalone)
* should use {@link java.sql.DriverManager} only. For example:
* </p>
* <pre>
* Connection conn = DriverManager.getConnection("jdbc:simon:oracle:thin:...", "scott", "tiger");</pre>
*
* Simon driver has following format of JDBC connection string:
* <pre>{@literal
* jdbc:simon:<real driver conn string>;<param1>=<value1>;...}</pre>
* Simon driver recognizes two parameters:
* <ul>
* <li>
* {@code SIMON_REAL_DRV} - if you don't want or can't register real driver for any
* reason, you can use this parameter and Simon proxy driver will do the registration
* for you. You don't need to specify real driver parameter for some well known databases.
* Simon proxy driver recognize database by first key word after JDBC and register.
* </li>
* <li>
* {@code SIMON_PREFIX} - setting this parameter you can choose different prefix
* for all monitors for one instance of driver. For example, setting
* {@code SIMON_PREFIX=com.foo} will ensure that all proxy related Simons are located
* under the subtree specified by the prefix, e.g. {@code com.foo.conn}, <code>com.foo.stmt</code>,
* <code>com.foo.select</code>, etc. If no prefix is set, default {@code org.javasimon.jdbc} prefix
* is used.
* </li>
* </ul> `
*
* By default, there is no need to load any driver explicitly, because drivers are loaded automatically
* (since JDK 1.5) if they are in class path and jar have appropriate
* meta information (see {@link java.sql.DriverManager}).
*
* If this is not a case for any reason, you need to register Simon proxy driver at least.
* For real driver Simon proxy driver contains following procedure for find and register it:
* <ol>
* <li>Simon proxy driver tries if there is registered driver for driver key word.
* <li>If not, driver tries if there is real driver parameter in info properties and then registers it.
* <li>If not, driver tries to find driver by key word within internal list of well known drivers and
* then registers it. For now, list contains default drivers for Oracle, PostgreSQL, Enterprise DB, H2,
* MySQL.
* <li>If not, driver tries to find real driver param within connection string and then registers it.
* <li>If not, getting new connection fails.
* </ol>
* The safest way to get Simon proxy driver work is to load the drivers, the real one (i.e. oracle)
* and a Simon proxy driver explicitly. This can be done using Class.forName. To load the driver and open a
* database connection, use following code:
* <pre>
* Class.forName("oracle.jdbc.driver.OracleDriver"); // loads real driver
* Class.forName("org.javasimon.jdbc4.Driver"); // loads Simon proxy driver
* Connection conn = DriverManager.getConnection(
* "jdbc:simon:oracle:thin:...", "scott", "tiger");</pre>
*
* @author Radovan Sninsky
* @author <a href="mailto:virgo47@gmail.com">Richard "Virgo" Richter</a>
* @see java.sql.DriverManager#getConnection(String)
* @since 2.4
*/
public final class Driver implements java.sql.Driver {
/**
* Name for the property holding the real driver class value.
*/
public static final String REAL_DRIVER = "simon_real_drv";
public static final String DEFAULT_PREFIX = "org.javasimon.jdbc";
/**
* Name for the driver property holding the hierarchy prefix given to JDBC Simons.
*/
public static final String PREFIX = "simon_prefix";
static {
try {
DriverManager.registerDriver(new Driver());
} catch (Exception e) {
// don't know what to do yet, maybe throw RuntimeException ???
e.printStackTrace();
}
}
private final Properties drivers = new Properties();
/**
* Class constructor. It loads well known driver list from resource file drivers.properties.
*/
public Driver() {
try {
InputStream stream = null;
try {
// TODO: limited to known drivers, better find driver later based on JDBC URL without "simon" word
stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("org/javasimon/jdbc4/drivers.properties");
drivers.load(stream);
} finally {
if (stream != null) {
stream.close();
}
}
} catch (IOException e) {
// log somewhere
}
}
/**
* Opens new Simon proxy driver connection associated with real connection to the specified database.
*
* @param simonUrl JDBC connection string (i.e. jdbc:simon:h2:file:test)
* @param info properties for connection
* @return open connection to database or null if provided url is not accepted by this driver
* @throws java.sql.SQLException if there is no real driver registered/recognized or opening real connection fails
* @see org.javasimon.jdbc4.Driver
*/
@Override
public Connection connect(String simonUrl, Properties info) throws SQLException {
if (!acceptsURL(simonUrl)) {
return null;
}
Url url = new Url(simonUrl);
java.sql.Driver driver = getRealDriver(url, info);
return new SimonConnection(driver.connect(url.getRealUrl(), info), url.getPrefix());
}
/**
* Tries to determine driver class, instantiate it and register if already not registered.
* For more detail look at {@link org.javasimon.jdbc4.Driver} class javadoc.
*
* @param url instance of url object that represents url
* @param info parameters from {@link #connect(String, java.util.Properties)} method
* @return instance of real driver
* @throws java.sql.SQLException if real driver can't be determined or is not registerd
*/
private java.sql.Driver getRealDriver(Url url, Properties info) throws SQLException {
java.sql.Driver drv = null;
try {
drv = DriverManager.getDriver(url.getRealUrl());
} catch (SQLException e) {
// nothing, not an error
}
if (drv == null && info != null && info.keySet().contains(REAL_DRIVER)) {
drv = registerDriver(info.getProperty(REAL_DRIVER));
}
if (drv == null && url.getDriverId() != null) {
drv = registerDriver(drivers.getProperty(url.getDriverId()));
}
if (drv == null) {
if (url.getRealDriver() != null) {
drv = registerDriver(url.getRealDriver());
}
}
if (drv == null) {
throw new SQLException("Real driver is not registered and can't determine real driver class name for registration.");
}
return drv;
}
/**
* Registers real driver through {@link java.sql.DriverManager}.
*
* @param name real driver class name
* @return instance of registered real driver
* @throws java.sql.SQLException if registration fails
*/
private java.sql.Driver registerDriver(String name) throws SQLException {
try {
java.sql.Driver d = (java.sql.Driver) Class.forName(name).newInstance();
DriverManager.registerDriver(d);
return d;
} catch (SQLException e) {
throw e;
} catch (Exception e) {
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean acceptsURL(String url) throws SQLException {
return url != null && url.toLowerCase().startsWith(Url.SIMON_JDBC);
}
/**
* {@inheritDoc}
*/
@Override
public DriverPropertyInfo[] getPropertyInfo(String s, Properties properties) throws SQLException {
return new DriverPropertyInfo[0];
}
/**
* {@inheritDoc}
*/
@Override
public int getMajorVersion() {
return 2;
}
/**
* {@inheritDoc}
*/
@Override
public int getMinorVersion() {
return 4;
}
/**
* {@inheritDoc}
*/
@Override
public boolean jdbcCompliant() {
return true;
}
/**
* Class Url represents Simon JDBC url. It parses given url and than provides getters for
* driver's propreties if provided or default values.
*
* @author Radovan Sninsky
* @since 2.4
*/
static class Url {
private static final String SIMON_JDBC = "jdbc:simon";
private static final Pattern DRIVER_FROM_URL_PATTERN = Pattern.compile(SIMON_JDBC + ":(.*):.*");
private String realUrl;
private String driverId;
private String realDriver;
private String prefix;
/**
* Class constructor, parses given URL and recognizes driver's properties.
*
* @param url given JDBC URL
*/
Url(String url) {
Matcher m = DRIVER_FROM_URL_PATTERN.matcher(url);
if (m.matches()) {
driverId = m.group(1);
}
StringTokenizer st = new StringTokenizer(url, ";");
while (st.hasMoreTokens()) {
String tokenPairStr = st.nextToken().trim();
String[] tokenPair = tokenPairStr.split("=", 2);
String token = tokenPair[0];
String tokenValue = tokenPair.length == 2 ? tokenPair[1].trim() : null;
if (tokenPairStr.startsWith("jdbc")) {
realUrl = tokenPairStr.replaceFirst(SIMON_JDBC, "jdbc");
} else if (token.equalsIgnoreCase(REAL_DRIVER)) {
realDriver = tokenValue;
} else if (token.equalsIgnoreCase(PREFIX)) {
prefix = tokenValue;
} else {
realUrl += ";" + tokenPairStr;
}
}
}
/**
* Returns orignal JDBC URL without any Simon stuff.
*
* @return original JDBC URL
*/
public String getRealUrl() {
return realUrl;
}
/**
* Returns driver identifier (eg. oracle, postgres, mysql, h2, etc.).
*
* @return driver identifier
*/
public String getDriverId() {
return driverId;
}
/**
* Returns fully qualified class name of the real driver.
*
* @return driver class FQN
*/
public String getRealDriver() {
return realDriver;
}
/**
* Returns prefix for hierarchy of JDBC related Simons.
*
* @return prefix for JDBC Simons
*/
public String getPrefix() {
return prefix == null ? DEFAULT_PREFIX : prefix;
}
}
}
|
package hudson.model;
import hudson.ExtensionPoint;
import hudson.Launcher;
import hudson.Plugin;
import hudson.tasks.BuildStep;
import hudson.tasks.Builder;
import hudson.tasks.Publisher;
import java.io.IOException;
/**
* Extensible property of {@link Job}.
*
* <p>
* {@link Plugin}s can extend this to define custom properties
* for {@link Job}s. {@link JobProperty}s show up in the user
* configuration screen, and they are persisted with the job object.
*
* <p>
* Configuration screen should be defined in <tt>config.jelly</tt>.
* Within this page, the {@link JobProperty} instance is available
* as <tt>instance</tt> variable (while <tt>it</tt> refers to {@link Job}.
*
* <p>
* Starting 1.150, {@link JobProperty} implements {@link BuildStep},
* meaning it gets the same hook as {@link Publisher} and {@link Builder}.
* The primary intention of this mechanism is so that {@link JobProperty}s
* can add actions to the new build.
*
*
* @author Kohsuke Kawaguchi
* @see JobPropertyDescriptor
* @since 1.72
*/
public abstract class JobProperty<J extends Job<?,?>> implements Describable<JobProperty<?>>, BuildStep, ExtensionPoint {
/**
* The {@link Job} object that owns this property.
* This value will be set by the Hudson code.
* Derived classes can expect this value to be always set.
*/
protected transient J owner;
/**
* Hook for performing post-initialization action.
*
* <p>
* This method is invoked in two cases. One is when the {@link Job} that owns
* this property is loaded from disk, and the other is when a job is re-configured
* and all the {@link JobProperty} instances got re-created.
*/
protected void setOwner(J owner) {
this.owner = owner;
}
/**
* {@inheritDoc}
*/
public abstract JobPropertyDescriptor getDescriptor();
/**
* {@link Action} to be displayed in the job page.
*
* @param job
* Always the same as {@link #owner} but passed in anyway for backward compatibility (I guess.)
* You really need not use this value at all.
* @return
* null if there's no such action.
* @since 1.102
*/
public Action getJobAction(J job) {
return null;
}
// default no-op implementation
public boolean prebuild(AbstractBuild<?,?> build, BuildListener listener) {
return true;
}
public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
return true;
}
public final Action getProjectAction(AbstractProject<?,?> project) {
return getJobAction((J)project);
}
}
|
package org.ensembl.healthcheck.util;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* General utilities (not database-related). For database-related utilities, see
* {@link DBUtils DBUtils}.
*/
public final class Utils {
static final Logger log = Logger.getLogger(Utils.class.getCanonicalName());
// hide constructor to prevent instantiation
private Utils() {
}
/**
* Read the <code>database.properties</code> file into the System properties
* so that it can be overridden with -D.
*
* @param propertiesFileName
* The properties file to read.
* @param skipBuildDatabaseURLs
* Don't automatically build database URLs. Should generally be
* false.
*/
public static void readPropertiesFileIntoSystem(final String propertiesFileName, final boolean skipBuildDatabaseURLs) {
String propsFile;
// Prepend home directory if not absolute path
if (propertiesFileName.indexOf(File.separator) == -1) {
propsFile = System.getProperty("user.dir") + File.separator + propertiesFileName;
} else {
propsFile = propertiesFileName;
}
Properties dbProps = Utils.readSimplePropertiesFile(propsFile);
log.fine("\n
for(String name: dbProps.stringPropertyNames()) {
String value = dbProps.getProperty(name);
log.fine("name = " + name + " value = " + value);
// add to System
System.setProperty(name, value);
}
log.fine("\n
if (!skipBuildDatabaseURLs) {
buildDatabaseURLs();
}
} // readPropertiesFile
/**
* Build database URLs from system properties.
*
* @param propertiesFileName
* The properties file to read.
*/
public static void buildDatabaseURLs() {
// others done in DatabaseServer
// ... and for output database URL
String outputDatabaseURL = System.getProperty("output.databaseURL");
if (outputDatabaseURL == null || outputDatabaseURL.equals("")) {
// build it
outputDatabaseURL = "jdbc:mysql:
if (System.getProperty("output.host") != null) {
outputDatabaseURL += System.getProperty("output.host");
}
if (System.getProperty("output.port") != null) {
outputDatabaseURL += ":" + System.getProperty("output.port");
}
outputDatabaseURL += "/";
System.setProperty("output.databaseURL", outputDatabaseURL);
} else {
// validate output database URL - if it doesn't start with jdbc: this
// can
// cause confusion
String prefix = outputDatabaseURL.substring(0, 5);
if (!prefix.equalsIgnoreCase("jdbc:")) {
System.err
.println("WARNING - output.databaseURL property should start with jdbc: but it does not seem to. Check this if you experience problems loading the database driver");
}
}
}
// /**
// * Check that certain properties are set.
// */
// private static void checkProperties() {
// // check that properties that need to be set are set
// String[] requiredProps = { "port", "host", "user" };
// for (int i = 0; i < requiredProps.length; i++) {
// if (System.getProperty(requiredProps[i]) == null) {
// String msg = "WARNING: " + requiredProps[i] + " is not set in config file or on command line - cannot connect to database";
// System.err.println(msg);
// throw new RuntimeException(msg);
/**
* Read a properties file.
*
* @param propertiesFileName
* The name of the properties file to use.
* @return The Properties hashtable.
*/
public static Properties readSimplePropertiesFile(String propertiesFileName) {
Properties props = new Properties();
try {
FileInputStream in = new FileInputStream(propertiesFileName);
props.load(in);
in.close();
} catch (Exception e) {
String msg = "Could not read from file "+propertiesFileName;
throw new RuntimeException(msg);
}
return props;
} // readPropertiesFile
/**
* Print a list of Strings, one per line.
*
* @param l
* The List to be printed.
*/
public static void printList(List<? extends Object> l) {
for(Object o: l) {
System.out.println(String.valueOf(o));
}
} // printList
/**
* Concatenate a list of Strings into a single String.
*
* @param list
* The Strings to list.
* @param delim
* The delimiter to use.
* @return A String containing the elements of list separated by delim. No
* trailing delimiter.
*/
public static String listToString(List<? extends Object> list, String delim) {
StringBuilder buf = new StringBuilder();
Iterator<?> it = list.iterator();
while (it.hasNext()) {
buf.append(String.valueOf(it.next()));
if (it.hasNext()) {
buf.append(delim);
}
}
return buf.toString();
}
/**
* Concatenate an array of Strings into a single String.
*
* @param a
* The Strings to list.
* @param delim
* The delimiter to use.
* @return A String containing the elements of a separated by delim. No
* trailing delimiter.
*/
public static String arrayToString(String[] a, String delim) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < a.length; i++) {
buf.append(a[i]);
if (i + 1 < a.length) {
buf.append(delim);
}
}
return buf.toString();
}
/**
* Print the keys in a HashMap.
*
* @param m
* The map to use.
*/
public static void printKeys(Map<? extends Object, ? extends Object> m) {
for (Object s : m.keySet()) {
System.out.println(s);
}
} // printKeys
/**
* Print the keys and values in a HashMap.
*
* @param m
* The map to use.
*/
public static void printMap(Map<String, String> m) {
Set<Map.Entry<String, String>> set = m.entrySet();
for (Map.Entry<String, String> e : set) {
System.out.println(String.format("%s %s", e.getKey(), e.getValue()));
}
} // printMap
/**
* Print an array of Strings, one per line.
*
* @param a
* The array to be printed.
*/
public static void printArray(String[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
} // printArray
/**
* Print an Enumeration, one String per line.
*
* @param e
* The enumeration to be printed.
*/
public static void printEnumeration(Enumeration<?> e) {
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
}
} // printEnumeration
/**
* Split a classpath-like string into a list of constituent paths.
*
* @param classPath
* The String to split.
* @param delim
* FileSystem classpath delimiter.
* @return An array containing one string per path, in the order they appear
* in classPath.
*/
public static String[] splitClassPath(String classPath, String delim) {
StringTokenizer tok = new StringTokenizer(classPath, delim);
String[] paths = new String[tok.countTokens()];
int i = 0;
while (tok.hasMoreElements()) {
paths[i++] = tok.nextToken();
}
return paths;
} // splitClassPath
/**
* Search an array of strings for those that contain a pattern.
*
* @param paths
* The List to search.
* @param pattern
* The pattern to look for.
* @return The matching paths, in the order that they were in the input array.
*/
public static String[] grepPaths(String[] paths, String pattern) {
int count = 0;
for (int i = 0; i < paths.length; i++) {
if (paths[i].indexOf(pattern) > -1) {
count++;
}
}
String[] greppedPaths = new String[count];
int j = 0;
for (int i = 0; i < paths.length; i++) {
if (paths[i].indexOf(pattern) > -1) {
greppedPaths[j++] = paths[i];
}
}
return greppedPaths;
} // grepPaths
/**
* Print the contents of a jar file.
*
* @param path
* The path to the jar file.
*/
public static void printJarFileContents(String path) {
try {
JarFile f = new JarFile(path);
printEnumeration(f.entries());
} catch (IOException ioe) {
ioe.printStackTrace();
}
} // printJarFileContents
/**
* Truncate a string to a certain number of characters.
*
* @param str
* The string to truncate.
* @param size
* The maximum number of characters.
* @param useEllipsis
* If true, add "..." to the truncated string to show it's been
* truncated.
* @return The truncated String, with ellipsis if specified.
*/
public static String truncate(String str, int size, boolean useEllipsis) {
String result = str;
if (str != null && str.length() > size) {
result = str.substring(0, size);
if (useEllipsis) {
result += "...";
}
}
return result;
} // truncate
/**
* Pad (on the right) a string with a certain number of characters.
*
* @return The padded String.
* @param size
* The desired length of the final, padded string.
* @param str
* The String to add the padding to.
* @param pad
* The String to pad with.
*/
public static String pad(String str, String pad, int size) {
StringBuffer result = new StringBuffer(str);
int startSize = str.length();
for (int i = startSize; i < size; i++) {
result.append(pad);
}
return result.toString();
} // pad
/**
* Read a text file.
*
* @param name
* The name of the file to read.
* @return An array of Strings representing the lines of the file.
*/
public static String[] readTextFile(String name) {
List<String> lines = new ArrayList<String>();
String line = null;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(name));
while ((line = br.readLine()) != null) {
lines.add(line);
}
}
catch (FileNotFoundException e) {
log.log(Level.WARNING, "Cannot find "+name, e);
}
catch (IOException e) {
log.log(Level.WARNING, "Error whilst reading "+name, e);
}
finally {
closeClosable(br);
}
return (String[]) lines.toArray(new String[lines.size()]);
} // readTextFile
/**
* Null safe way of closing down a Closable object
*/
public static void closeClosable(Closeable closable) {
try {
if(closable != null)
closable.close();
}
catch(IOException e) {
log.log(Level.WARNING, "Found exception whilst closing handle", e);
}
}
/**
* Check if a String is in an array of Strings. The whole array is searched
* (until a match is found); this is quite slow but does not require the array
* to be sorted in any way beforehand.
*
* @param str
* The String to search for.
* @param a
* The array to search through.
* @param caseSensitive
* If true, case sensitive searching is done.
* @return true if str is in a.
*/
public static boolean stringInArray(String str, String[] a, boolean caseSensitive) {
boolean result = false;
for (int i = 0; i < a.length; i++) {
if (caseSensitive) {
if (a[i].equals(str)) {
result = true;
break;
}
} else {
if (a[i].equalsIgnoreCase(str)) {
result = true;
break;
}
}
}
return result;
}
/**
* Check if an object is in an array. The whole array is searched (until a
* match is found); this is quite slow but does not require the array to be
* sorted in any way beforehand.
*
* @param o
* The Object to search for.
* @param a
* The array to search through.
* @return true if o is in a.
*/
public static boolean objectInArray(Object o, Object[] a) {
for (int i = 0; i < a.length; i++) {
if (a[i].equals(o)) {
return true;
}
}
return false;
}
/**
* Return an array containing all of the subdirectories of a given directory.
*
* @param parentDir
* The directory to look in.
* @return All the subdirectories (if any) in parentDir.
*/
public static String[] getSubDirs(String parentDir) {
List<String> dirs = new ArrayList<String>();
File parentDirFile = new File(parentDir);
String[] filesAndDirs = parentDirFile.list();
if (filesAndDirs != null) {
for (int i = 0; i < filesAndDirs.length; i++) {
File f = new File(parentDir + File.separator + filesAndDirs[i]);
if (f.isDirectory()) {
dirs.add(filesAndDirs[i]);
}
}
}
return (String[]) (dirs.toArray(new String[dirs.size()]));
}
/**
* Remove the objects from one array that are present in another.
*
* @param source
* The array to be filtered.
* @param remove
* An array of objects to be removed from source.
* @return A new array containing all objects that are in source minus any
* that are in remove.
*/
public static Object[] filterArray(Object[] source, Object[] remove) {
List<Object> result = new ArrayList<Object>();
for (int i = 0; i < source.length; i++) {
if (!objectInArray(source[i], remove)) {
result.add(source[i]);
}
}
return result.toArray(new Object[result.size()]);
}
/**
* Format a time as hours, minutes and seconds.
*
* @param time
* The time in ms, e.g. from System.currentTimeMillis()
* @return The time formatted as e.g. 4 hours 2 min 3s. Hours is largest unit
* currently supported.
*/
public static String formatTimeString(long time) {
String s = "";
Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(time);
// TODO years etc
// Calendar.HOUR starts from 1
if (cal.get(Calendar.HOUR_OF_DAY) > 1) {
s += (cal.get(Calendar.HOUR_OF_DAY) - 1) + " hours ";
}
if (cal.get(Calendar.MINUTE) > 0) {
s += cal.get(Calendar.MINUTE) + " min ";
}
if (cal.get(Calendar.SECOND) > 0) {
s += cal.get(Calendar.SECOND) + "s ";
}
if (time < 1000) {
s = time + "ms";
}
return s;
}
/**
* Delete a file.
*
* @param file
* The file to delete.
*/
public static void deleteFile(String file) {
File f = new File(file);
boolean retVal = f.delete();
if (!retVal) {
System.err.println(String.format("Error - could not delete %s", file));
}
}
/**
* Write/append a string to a file.
*
* @param file
* The file to write to.
* @param str
* The string to write.
* @param append
* If true, append the string to the file if it already exists.
* @param newLine
* If true, add a new line character after writing
*/
public static void writeStringToFile(String file, String str, boolean append, boolean newLine) {
try {
FileWriter fw = new FileWriter(file, append);
fw.write(str);
if (newLine) {
fw.write("\n");
}
fw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* Convert a list of Longs to an array of longs.
*/
public static long[] listToArrayLong(List<? extends Number> list) {
long[] array = new long[list.size()];
int i = 0;
for(Number n: list) {
array[i++] = n.longValue();
}
return array;
}
/**
* Convert the first character of a string to upper case. Ignore the rest of
* the string.
*/
public static String ucFirst(String str) {
String first = str.substring(0, 1).toUpperCase();
String last = str.substring(1);
return first + last;
}
public static String truncateDatabaseName(String db) {
if (db.length() <= 27) {
return db;
}
// change genus to single letter
int underscoreIndex = db.indexOf("_");
String genusLetter = db.substring(0, 1);
String result = genusLetter + "_" + db.substring(underscoreIndex + 1);
// if length is *still* > 27, change long database type to an abbreviated
// version
if (result.length() > 27) {
result = result.replaceAll("otherfeatures", "other...");
}
return result;
}
public static String truncateTestName(String test) {
return (test.length() <= 27) ? test : test.substring(0, 28);
}
public static String[] removeStringFromArray(String[] tables, String table) {
String[] result = new String[tables.length - 1];
int j = 0;
for (int i = 0; i < tables.length; i++) {
if (!tables[i].equalsIgnoreCase(table)) {
if (j < result.length) {
result[j++] = tables[i];
}
}
}
return result;
}
/**
* Convert a list to a HashMap, where the key and value of each map element is the same as each list element.
*/
public static HashMap<Object,Object> listToMap(List<Object> list) {
HashMap<Object,Object> map = new HashMap<Object,Object>();
for (Object o : list) {
map.put(o, o);
}
return map;
}
/**
* Convert an array to a HashMap, where the key and value of each map element is the same as each list element.
*/
public static HashMap<Object,Object> arrayToMap(Object[] array) {
return listToMap(Arrays.asList(array));
}
/**
* Create a list of databases and groups from the properties file. Multiple properties can be used as long as they start with
* output.databases, e.g. <code>
* output.databases1 = ^[a-k].*_core_63.*:release
* output.databases2 = ^[l-z].*_core_63.*:release
* </code> Individual properties can also contain multiple comma-separated sets.
*/
public static List<String> getDatabasesAndGroups() {
List<String> list = new ArrayList<String>();
Properties props = System.getProperties();
for (Enumeration<?> en = props.propertyNames(); en.hasMoreElements();) {
String key = (String) en.nextElement();
if (key.startsWith("output.databases")) {
String value = props.getProperty(key);
list.addAll(Arrays.asList(value.split(",")));
}
}
return list;
}
} // Utils
|
package whelk.importer;
import io.prometheus.client.Counter;
import se.kb.libris.util.marc.Datafield;
import se.kb.libris.util.marc.Field;
import se.kb.libris.util.marc.MarcRecord;
import whelk.Document;
import whelk.IdGenerator;
import whelk.JsonLd;
import whelk.Whelk;
import whelk.component.ElasticSearch;
import whelk.component.PostgreSQLComponent;
import whelk.converter.MarcJSONConverter;
import whelk.converter.marc.MarcFrameConverter;
import whelk.exception.TooHighEncodingLevelException;
import whelk.filter.LinkFinder;
import whelk.util.LegacyIntegrationTools;
import whelk.util.PropertyLoader;
import whelk.triples.*;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.sql.*;
import java.util.*;
class XL
{
private static final String ENC_PRELIMINARY_STATUS = "marc:PartialPreliminaryLevel";
private static final String ENC_PREPUBLICATION_STATUS = "marc:PrepublicationLevel";
private static final String ENC_ABBREVIVATED_STATUS = "marc:AbbreviatedLevel";
private static final String ENC_MINMAL_STATUS = "marc:MinimalLevel";
private Whelk m_whelk;
private LinkFinder m_linkfinder;
private Parameters m_parameters;
private Properties m_properties;
private MarcFrameConverter m_marcFrameConverter;
private static boolean verbose = false;
// The predicates listed here are those that must always be represented as lists in jsonld, even if the list
// has only a single member.
private Set<String> m_repeatableTerms;
private final static String IMPORT_SYSTEM_CODE = "batch import";
XL(Parameters parameters) throws IOException
{
m_parameters = parameters;
verbose = m_parameters.getVerbose();
m_properties = PropertyLoader.loadProperties("secret");
m_whelk = Whelk.createLoadedSearchWhelk(m_properties);
m_repeatableTerms = m_whelk.getJsonld().getRepeatableTerms();
m_marcFrameConverter = m_whelk.createMarcFrameConverter();
m_linkfinder = new LinkFinder(m_whelk.getStorage());
}
/**
* Write a ISO2709 MarcRecord to LibrisXL. returns a resource ID if the resulting document (merged or new) was in "bib".
* This ID should then be passed (as 'relatedWithBibResourceId') when importing any subsequent related holdings post.
* Returns null when supplied a hold post.
*/
String importISO2709(MarcRecord incomingMarcRecord,
String relatedWithBibResourceId,
Counter importedBibRecords,
Counter importedHoldRecords,
Counter enrichedBibRecords,
Counter enrichedHoldRecords,
Counter encounteredMulBibs)
throws Exception
{
String collection = "bib"; // assumption
if (incomingMarcRecord.getLeader(6) == 'u' || incomingMarcRecord.getLeader(6) == 'v' ||
incomingMarcRecord.getLeader(6) == 'x' || incomingMarcRecord.getLeader(6) == 'y')
collection = "hold";
Set<String> duplicateIDs = getDuplicates(incomingMarcRecord, collection, relatedWithBibResourceId);
String resultingResourceId = null;
//System.err.println("Incoming [" + collection + "] document had: " + duplicateIDs.size() + " existing duplicates:\n" + duplicateIDs);
// If an incoming holding record is marked deleted, attempt to find any duplicates for it in Libris and delete them.
if (collection.equals("hold") && incomingMarcRecord.getLeader(5) == 'd')
{
for (String id : duplicateIDs)
m_whelk.remove(id, IMPORT_SYSTEM_CODE, null);
return null;
}
if (duplicateIDs.size() == 0) // No coinciding documents, simple import
{
resultingResourceId = importNewRecord(incomingMarcRecord, collection, relatedWithBibResourceId, null);
if (collection.equals("bib"))
importedBibRecords.inc();
else
importedHoldRecords.inc();
}
else if (duplicateIDs.size() == 1) // Enrich ("merge") or replace
{
if (collection.equals("bib"))
{
if ( m_parameters.getReplaceBib() )
{
String idToReplace = duplicateIDs.iterator().next();
resultingResourceId = importNewRecord(incomingMarcRecord, collection, relatedWithBibResourceId, idToReplace);
importedBibRecords.inc();
}
else // Merge bib
{
resultingResourceId = enrichRecord((String) duplicateIDs.toArray()[0], incomingMarcRecord, collection, relatedWithBibResourceId);
enrichedBibRecords.inc();
}
}
else // collection = hold
{
if ( m_parameters.getReplaceHold() ) // Replace hold
{
String idToReplace = duplicateIDs.iterator().next();
resultingResourceId = importNewRecord(incomingMarcRecord, collection, relatedWithBibResourceId, idToReplace);
importedHoldRecords.inc();
}
else // Merge hold
{
resultingResourceId = enrichRecord((String) duplicateIDs.toArray()[0], incomingMarcRecord, collection, relatedWithBibResourceId);
enrichedHoldRecords.inc();
}
}
}
else
{
// Multiple coinciding documents.
encounteredMulBibs.inc();
if (m_parameters.getEnrichMulDup())
{
for (String id : duplicateIDs)
{
enrichRecord( id, incomingMarcRecord, collection, relatedWithBibResourceId );
}
}
if (collection.equals("bib"))
{
// In order to keep the program deterministic, the bib post to which subsequent holdings should attach
// when there are multiple duplicates is defined as the one with the "lowest" alpha numeric id.
List<String> duplicateList = new ArrayList<>(duplicateIDs);
Collections.sort(duplicateList);
String selectedDuplicateId = duplicateList.get(0);
if (!selectedDuplicateId.startsWith(Document.getBASE_URI().toString()))
selectedDuplicateId = Document.getBASE_URI().toString() + selectedDuplicateId;
resultingResourceId = m_whelk.getStorage().getThingId(selectedDuplicateId);
}
else
resultingResourceId = null;
}
return resultingResourceId;
}
private String importNewRecord(MarcRecord marcRecord, String collection, String relatedWithBibResourceId, String replaceSystemId)
{
String incomingId = IdGenerator.generate();
if (replaceSystemId != null)
incomingId = replaceSystemId;
Document rdfDoc = convertToRDF(marcRecord, incomingId);
if (collection.equals("hold"))
rdfDoc.setHoldingFor(relatedWithBibResourceId);
if (!m_parameters.getReadOnly())
{
rdfDoc.setRecordStatus(ENC_PRELIMINARY_STATUS);
// Doing a replace (but preserving old IDs)
if (replaceSystemId != null)
{
m_whelk.getStorage().storeAtomicUpdate(replaceSystemId, false, IMPORT_SYSTEM_CODE, null,
(Document doc) ->
{
String existingEncodingLevel = doc.getEncodingLevel();
String newEncodingLevel = rdfDoc.getEncodingLevel();
if (existingEncodingLevel == null || !mayOverwriteExistingEncodingLevel(existingEncodingLevel, newEncodingLevel))
throw new TooHighEncodingLevelException();
List<String> recordIDs = doc.getRecordIdentifiers();
List<String> thingIDs = doc.getThingIdentifiers();
doc.data = rdfDoc.data;
// The mainID must remain unaffected.
doc.deepPromoteId(recordIDs.get(0));
for (String recordID : recordIDs)
doc.addRecordIdentifier(recordID);
for (String thingID : thingIDs)
doc.addThingIdentifier(thingID);
});
}
else
{
// Doing simple "new"
m_whelk.createDocument(rdfDoc, IMPORT_SYSTEM_CODE, null, collection, false);
}
}
else
{
if ( verbose )
{
System.out.println("info: Would now (if --live had been specified) have written the following json-ld to whelk as a new record:\n"
+ rdfDoc.getDataAsString());
}
}
if (collection.equals("bib"))
return rdfDoc.getThingIdentifiers().get(0);
return null;
}
private String enrichRecord(String ourId, MarcRecord incomingMarcRecord, String collection, String relatedWithBibResourceId)
throws IOException
{
Document rdfDoc = convertToRDF(incomingMarcRecord, ourId);
if (collection.equals("hold"))
rdfDoc.setHoldingFor(relatedWithBibResourceId);
if (!m_parameters.getReadOnly())
{
try
{
m_whelk.storeAtomicUpdate(ourId, false, IMPORT_SYSTEM_CODE, null,
(Document doc) ->
{
if (collection.equals("bib"))
{
String existingEncodingLevel = doc.getEncodingLevel();
String newEncodingLevel = rdfDoc.getEncodingLevel();
if (existingEncodingLevel == null || !mayOverwriteExistingEncodingLevel(existingEncodingLevel, newEncodingLevel))
throw new TooHighEncodingLevelException();
}
enrich( doc, rdfDoc );
});
}
catch (TooHighEncodingLevelException e)
{
if ( verbose )
{
System.out.println("info: Not enriching id: " + ourId + ", because it no longer has encoding level marc:PartialPreliminaryLevel");
}
}
}
else
{
Document doc = m_whelk.getStorage().load( ourId );
enrich( doc, rdfDoc );
if ( verbose )
{
System.out.println("info: Would now (if --live had been specified) have written the following (merged) json-ld to whelk:\n");
System.out.println("id:\n" + doc.getShortId());
System.out.println("data:\n" + doc.getDataAsString());
}
}
if (collection.equals("bib"))
return rdfDoc.getThingIdentifiers().get(0);
return null;
}
private boolean mayOverwriteExistingEncodingLevel(String existingEncodingLevel, String newEncodingLevel)
{
switch (newEncodingLevel)
{
case ENC_PRELIMINARY_STATUS:
if (existingEncodingLevel.equals(ENC_PRELIMINARY_STATUS))
return true;
break;
case ENC_PREPUBLICATION_STATUS:
if (existingEncodingLevel.equals(ENC_PRELIMINARY_STATUS) || existingEncodingLevel.equals(ENC_PREPUBLICATION_STATUS)) // 5 || 8
return true;
break;
case ENC_ABBREVIVATED_STATUS:
if (existingEncodingLevel.equals(ENC_PRELIMINARY_STATUS) || existingEncodingLevel.equals(ENC_PREPUBLICATION_STATUS)) // 5 || 8
return true;
break;
case ENC_MINMAL_STATUS:
if (existingEncodingLevel.equals(ENC_PRELIMINARY_STATUS) || existingEncodingLevel.equals(ENC_PREPUBLICATION_STATUS)) // 5 || 8
return true;
break;
}
return false;
}
private void enrich(Document mutableDocument, Document withDocument)
{
JsonldSerializer serializer = new JsonldSerializer();
List<String[]> withTriples = serializer.deserialize(withDocument.data);
List<String[]> originalTriples = serializer.deserialize(mutableDocument.data);
Graph originalGraph = new Graph(originalTriples);
Graph withGraph = new Graph(withTriples);
// This is temporary, these special rules should not be hardcoded here, but rather obtained from (presumably)
// whelk-core's marcframe.json.
Map<String, Graph.PREDICATE_RULES> specialRules = new HashMap<>();
for (String term : m_repeatableTerms)
specialRules.put(term, Graph.PREDICATE_RULES.RULE_AGGREGATE);
specialRules.put("created", Graph.PREDICATE_RULES.RULE_PREFER_ORIGINAL);
specialRules.put("controlNumber", Graph.PREDICATE_RULES.RULE_PREFER_ORIGINAL);
specialRules.put("modified", Graph.PREDICATE_RULES.RULE_PREFER_INCOMING);
specialRules.put("marc:encLevel", Graph.PREDICATE_RULES.RULE_PREFER_ORIGINAL);
originalGraph.enrichWith(withGraph, specialRules);
Map enrichedData = JsonldSerializer.serialize(originalGraph.getTriples(), m_repeatableTerms);
boolean deleteUnreferencedData = true;
JsonldSerializer.normalize(enrichedData, mutableDocument.getShortId(), deleteUnreferencedData);
mutableDocument.data = enrichedData;
}
private Document convertToRDF(MarcRecord marcRecord, String id)
{
while (marcRecord.getControlfields("001").size() > 0)
marcRecord.getFields().remove(marcRecord.getControlfields("001").get(0));
marcRecord.addField(marcRecord.createControlfield("001", id));
Map convertedData = m_marcFrameConverter.convert(MarcJSONConverter.toJSONMap(marcRecord), id);
Document convertedDocument = new Document(convertedData);
convertedDocument.deepReplaceId(Document.getBASE_URI().toString()+id);
m_linkfinder.normalizeIdentifiers(convertedDocument);
return convertedDocument;
}
private Set<String> getDuplicates(MarcRecord marcRecord, String collection, String relatedWithBibResourceId)
throws SQLException
{
switch (collection)
{
case "bib":
return getBibDuplicates(marcRecord);
case "hold":
return getHoldDuplicates(marcRecord, relatedWithBibResourceId);
default:
return new HashSet<>();
}
}
private Set<String> getHoldDuplicates(MarcRecord marcRecord, String relatedWithBibResourceId)
throws SQLException
{
Set<String> duplicateIDs = new HashSet<>();
// Assumes the post being imported carries a valid libris id in 001, and "SE-LIBR" or "LIBRIS" in 003
duplicateIDs.addAll(getDuplicatesOnLibrisID(marcRecord, "hold"));
duplicateIDs.addAll(getDuplicatesOnHeldByHoldingFor(marcRecord, relatedWithBibResourceId));
return duplicateIDs;
}
private Set<String> getBibDuplicates(MarcRecord marcRecord)
throws SQLException
{
Set<String> duplicateIDs = new HashSet<>();
for (Parameters.DUPLICATION_TYPE dupType : m_parameters.getDuplicationTypes())
{
switch (dupType)
{
case DUPTYPE_ISBNA: // International Standard Book Number (only from subfield A)
for (Field field : marcRecord.getFields("020"))
{
String isbn = DigId.grepIsbna( (Datafield) field );
if (isbn != null)
{
duplicateIDs.addAll(getDuplicatesOnISBN( isbn.toUpperCase() ));
}
}
break;
case DUPTYPE_ISBNZ: // International Standard Book Number (only from subfield Z)
for (Field field : marcRecord.getFields("020"))
{
String isbn = DigId.grepIsbnz( (Datafield) field );
if (isbn != null)
{
duplicateIDs.addAll(getDuplicatesOnISBN( isbn.toUpperCase() ));
}
}
break;
case DUPTYPE_ISSNA: // International Standard Serial Number (only from marc 022_A)
for (Field field : marcRecord.getFields("022"))
{
String issn = DigId.grepIssn( (Datafield) field, 'a' );
if (issn != null)
{
duplicateIDs.addAll(getDuplicatesOnISSN( issn.toUpperCase() ));
}
}
break;
case DUPTYPE_ISSNZ: // International Standard Serial Number (only from marc 022_Z)
for (Field field : marcRecord.getFields("022"))
{
String issn = DigId.grepIssn( (Datafield) field, 'z' );
if (issn != null)
{
duplicateIDs.addAll(getDuplicatesOnISSN( issn.toUpperCase() ));
}
}
break;
case DUPTYPE_035A:
// Unique id number in another system.
duplicateIDs.addAll(getDuplicatesOn035a(marcRecord));
break;
case DUPTYPE_LIBRISID:
// Assumes the post being imported carries a valid libris id in 001, and "SE-LIBR" or "LIBRIS" in 003
duplicateIDs.addAll(getDuplicatesOnLibrisID(marcRecord, "bib"));
break;
}
}
return duplicateIDs;
}
private List<String> getDuplicatesOnLibrisID(MarcRecord marcRecord, String collection)
throws SQLException
{
String librisId = DigId.grepLibrisId(marcRecord);
if (librisId == null)
return new ArrayList<>();
// completely numeric? = classic voyager id.
// In theory an xl id could (though insanely unlikely) also be numeric :(
if (librisId.matches("[0-9]+"))
{
librisId = "http://libris.kb.se/"+collection+"/"+librisId;
}
else if ( ! librisId.startsWith(Document.getBASE_URI().toString()))
{
librisId = Document.getBASE_URI().toString() + librisId;
}
try(Connection connection = m_whelk.getStorage().getConnection();
PreparedStatement statement = getOnId_ps(connection, librisId);
ResultSet resultSet = statement.executeQuery())
{
return collectIDs(resultSet);
}
}
private List<String> getDuplicatesOn035a(MarcRecord marcRecord)
throws SQLException
{
List<String> results = new ArrayList<>();
for (Field field : marcRecord.getFields("035"))
{
String systemNumber = DigId.grep035a( (Datafield) field );
try(Connection connection = m_whelk.getStorage().getConnection();
PreparedStatement statement = getOnSystemNumber_ps(connection, systemNumber);
ResultSet resultSet = statement.executeQuery())
{
results.addAll( collectIDs(resultSet) );
}
}
return results;
}
private List<String> getDuplicatesOnISBN(String isbn)
throws SQLException
{
if (isbn == null)
return new ArrayList<>();
String numericIsbn = isbn.replaceAll("-", "");
try(Connection connection = m_whelk.getStorage().getConnection();
PreparedStatement statement = getOnISBN_ps(connection, numericIsbn);
ResultSet resultSet = statement.executeQuery())
{
return collectIDs(resultSet);
}
}
private List<String> getDuplicatesOnISSN(String issn)
throws SQLException
{
if (issn == null)
return new ArrayList<>();
try(Connection connection = m_whelk.getStorage().getConnection();
PreparedStatement statement = getOnISSN_ps(connection, issn);
ResultSet resultSet = statement.executeQuery())
{
return collectIDs(resultSet);
}
}
private List<String> getDuplicatesOnHeldByHoldingFor(MarcRecord marcRecord, String relatedWithBibResourceId)
throws SQLException
{
if (marcRecord.getFields("852").size() < 1)
return new ArrayList<>();
Datafield df = (Datafield) marcRecord.getFields("852").get(0);
if (df.getSubfields("b").size() < 1)
return new ArrayList<>();
String sigel = df.getSubfields("b").get(0).getData();
String library = LegacyIntegrationTools.legacySigelToUri(sigel);
try(Connection connection = m_whelk.getStorage().getConnection();
PreparedStatement statement = getOnHeldByHoldingFor_ps(connection, library, relatedWithBibResourceId);
ResultSet resultSet = statement.executeQuery())
{
return collectIDs(resultSet);
}
}
private PreparedStatement getOnId_ps(Connection connection, String id)
throws SQLException
{
String query = "SELECT id FROM lddb__identifiers WHERE iri = ?";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, id);
return statement;
}
/**
* "System number" is our ld equivalent of marc's 035a
*/
private PreparedStatement getOnSystemNumber_ps(Connection connection, String systemNumber)
throws SQLException
{
String query = "SELECT id FROM lddb WHERE data#>'{@graph,0,identifiedBy}' @> ?";
PreparedStatement statement = connection.prepareStatement(query);
statement.setObject(1, "[{\"@type\": \"SystemNumber\", \"value\": \"" + systemNumber + "\"}]", java.sql.Types.OTHER);
return statement;
}
private PreparedStatement getOnISBN_ps(Connection connection, String isbn)
throws SQLException
{
// required to be completely numeric (base 11, 0-9+x).
if (!isbn.matches("[\\dxX]+"))
isbn = "0";
String query = "SELECT id FROM lddb WHERE data#>'{@graph,1,identifiedBy}' @> ?";
PreparedStatement statement = connection.prepareStatement(query);
statement.setObject(1, "[{\"@type\": \"ISBN\", \"value\": \"" + isbn + "\"}]", java.sql.Types.OTHER);
return statement;
}
private PreparedStatement getOnISSN_ps(Connection connection, String issn)
throws SQLException
{
// (base 11, 0-9+x and SINGLE hyphens only).
if (!issn.matches("^(-[xX\\d]|[xX\\d])+$"))
issn = "0";
String query = "SELECT id FROM lddb WHERE data#>'{@graph,1,identifiedBy}' @> ?";
PreparedStatement statement = connection.prepareStatement(query);
statement.setObject(1, "[{\"@type\": \"ISSN\", \"value\": \"" + issn + "\"}]", java.sql.Types.OTHER);
return statement;
}
private PreparedStatement getOnHeldByHoldingFor_ps(Connection connection, String heldBy, String holdingForId)
throws SQLException
{
String libraryUri = LegacyIntegrationTools.legacySigelToUri(heldBy);
// Here be dragons. The always-works query is this:
/*String query =
"SELECT lddb.id from lddb " +
"INNER JOIN lddb__identifiers id1 ON lddb.data#>>'{@graph,1,itemOf,@id}' = id1.iri " +
"INNER JOIN lddb__identifiers id2 ON id1.id = id2.id " +
"WHERE " +
"data#>>'{@graph,1,heldBy,@id}' = ? " +
"AND " +
"id2.iri = ?";*/
// This query REQUIRES that links be on the primary ID only. This works beacuse of link-finding step2, but if
// that should ever change this query would break.
String query = "SELECT id from lddb WHERE data#>>'{@graph,1,heldBy,@id}' = ? AND data#>>'{@graph,1,itemOf,@id}' = ? AND deleted = false";
PreparedStatement statement = connection.prepareStatement(query);
statement.setString(1, libraryUri);
statement.setString(2, holdingForId);
return statement;
}
private List<String> collectIDs(ResultSet resultSet)
throws SQLException
{
List<String> ids = new ArrayList<>();
while (resultSet.next())
{
ids.add(resultSet.getString("id"));
}
return ids;
}
//private class TooHighEncodingLevelException extends RuntimeException {}
}
|
package blasd.apex.core.agent;
import java.io.File;
import java.lang.instrument.Instrumentation;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ehcache.sizeof.impl.AgentLoaderSpy;
import org.springframework.boot.loader.tools.AgentAttacher;
/**
* The entry point for the instrumentation agent.
*
* Either the premain method is called by adding the JVM arg -javaagent. Or one could call the
* {@link InstrumentationAgent#getInstrumentation()} method. Anyway, tools.jar will have to be present at Runtime
*
* @author Benoit Lacelle
*
*/
public class InstrumentationAgent {
// SLF4J in not available in the Agents
protected static final Logger LOGGER = Logger.getLogger(InstrumentationAgent.class.getName());
// The initialization can fail for many reasons (tools.jar not available,...)
private static final AtomicBoolean INIT_TRIED = new AtomicBoolean(false);
private static final AtomicReference<Instrumentation> INTRUMENTATION_REF = new AtomicReference<Instrumentation>();
protected InstrumentationAgent() {
// Hide the constructor
}
/**
* This premain method is called by adding a JVM argument:
*
* -javaagent:path\to\jar\monitor-1.SNAPSHOT.jar
*
*/
public static void premain(String args, Instrumentation instr) {
System.out.println(InstrumentationAgent.class + ": premain");
INTRUMENTATION_REF.set(instr);
}
public static void agentmain(String args, Instrumentation instr) {
System.out.println(InstrumentationAgent.class + ": agentmain");
INTRUMENTATION_REF.set(instr);
}
public static void ensureAgentInitialisation() {
// Try only once to hook the agent
if (INIT_TRIED.compareAndSet(false, true)) {
try {
File holdingJarPath = ApexAgentHelper.getOrMakeHoldingJarPath(InstrumentationAgent.class);
if (holdingJarPath != null) {
// TODO we may want a custom .attach method to enable options
String suffix = InstrumentationAgent.class + " from " + holdingJarPath;
LOGGER.log(Level.INFO, "Attaching the agent for " + suffix);
AgentAttacher.attach(holdingJarPath);
LOGGER.log(Level.INFO, "Attached successfully the agent for " + suffix);
} else {
LOGGER.log(Level.SEVERE, "Can not find a jar holding the class " + InstrumentationAgent.class);
}
} catch (RuntimeException e) {
// makes sure the exception gets printed at
// least once
e.printStackTrace();
LOGGER.log(Level.SEVERE, "Ouch", e);
throw e;
}
}
}
/**
*
* @return an {@link Instrumentation} instance as instantiated by the JVM itself
*/
public static Instrumentation getInstrumentation() {
InstrumentationAgent.ensureAgentInitialisation();
return INTRUMENTATION_REF.get();
}
/**
*
* @return an {@link Instrumentation} instance as instantiated by the JVM itself, or null if anything bad happened
*/
public static Instrumentation safeGetInstrumentation() {
if (new Random().nextInt() >= 0) {
return AgentLoaderSpy.getInstrumentation();
}
try {
return getInstrumentation();
} catch (Throwable e) {
Throwable s = e;
while (s != null) {
System.out.println(s.getMessage());
System.out.println(s.getClass());
System.out.println(Arrays.asList(s.getStackTrace()));
if (s == e.getCause()) {
break;
} else {
s = e.getCause();
}
}
LOGGER.log(Level.INFO, "Issue while getting instrumentation", e);
return null;
}
}
}
|
package com.jme3.texture;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.export.Savable;
import com.jme3.math.FastMath;
import com.jme3.renderer.Caps;
import com.jme3.renderer.Renderer;
import com.jme3.texture.image.ColorSpace;
import com.jme3.texture.image.LastTextureState;
import com.jme3.util.BufferUtils;
import com.jme3.util.NativeObject;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* <code>Image</code> defines a data format for a graphical image. The image
* is defined by a format, a height and width, and the image data. The width and
* height must be greater than 0. The data is contained in a byte buffer, and
* should be packed before creation of the image object.
*
* @author Mark Powell
* @author Joshua Slack
* @version $Id: Image.java 4131 2009-03-19 20:15:28Z blaine.dev $
*/
public class Image extends NativeObject implements Savable /*, Cloneable*/ {
public enum Format {
/**
* 8-bit alpha
*/
Alpha8(8),
@Deprecated
Reserved1(0),
/**
* 8-bit grayscale/luminance.
*/
Luminance8(8),
@Deprecated
Reserved2(0),
/**
* half-precision floating-point grayscale/luminance.
*
* Requires {@link Caps#FloatTexture}.
*/
Luminance16F(16,true),
/**
* single-precision floating-point grayscale/luminance.
*
* Requires {@link Caps#FloatTexture}.
*/
Luminance32F(32,true),
/**
* 8-bit luminance/grayscale and 8-bit alpha.
*/
Luminance8Alpha8(16),
@Deprecated
Reserved3(0),
/**
* half-precision floating-point grayscale/luminance and alpha.
*
* Requires {@link Caps#FloatTexture}.
*/
Luminance16FAlpha16F(32,true),
@Deprecated
Reserved4(0),
@Deprecated
Reserved5(0),
/**
* 8-bit blue, green, and red.
*/
BGR8(24), // BGR and ABGR formats are often used on windows systems
/**
* 8-bit red, green, and blue.
*/
RGB8(24),
@Deprecated
Reserved6(0),
@Deprecated
Reserved7(0),
/**
* 5-bit red, 6-bit green, and 5-bit blue.
*/
RGB565(16),
@Deprecated
Reserved8(0),
/**
* 5-bit red, green, and blue with 1-bit alpha.
*/
RGB5A1(16),
/**
* 8-bit red, green, blue, and alpha.
*/
RGBA8(32),
/**
* 8-bit alpha, blue, green, and red.
*/
ABGR8(32),
/**
* 8-bit alpha, red, blue and green
*/
ARGB8(32),
/**
* 8-bit blue, green, red and alpha.
*/
BGRA8(32),
@Deprecated
Reserved9(0),
/**
* S3TC compression DXT1.
*/
DXT1(4,false,true, false),
/**
* S3TC compression DXT1 with 1-bit alpha.
*/
DXT1A(4,false,true, false),
/**
* S3TC compression DXT3 with 4-bit alpha.
*/
DXT3(8,false,true, false),
/**
* S3TC compression DXT5 with interpolated 8-bit alpha.
*
*/
DXT5(8,false,true, false),
/**
* Luminance-Alpha Texture Compression.
*
* @deprecated Not supported by OpenGL 3.0.
*/
@Deprecated
Reserved10(0),
/**
* Arbitrary depth format. The precision is chosen by the video
* hardware.
*/
Depth(0,true,false,false),
/**
* 16-bit depth.
*/
Depth16(16,true,false,false),
/**
* 24-bit depth.
*/
Depth24(24,true,false,false),
/**
* 32-bit depth.
*/
Depth32(32,true,false,false),
/**
* single-precision floating point depth.
*
* Requires {@link Caps#FloatDepthBuffer}.
*/
Depth32F(32,true,false,true),
/**
* Texture data is stored as {@link Format#RGB16F} in system memory,
* but will be converted to {@link Format#RGB111110F} when sent
* to the video hardware.
*
* Requires {@link Caps#FloatTexture} and {@link Caps#PackedFloatTexture}.
*/
RGB16F_to_RGB111110F(48,true),
/**
* unsigned floating-point red, green and blue that uses 32 bits.
*
* Requires {@link Caps#PackedFloatTexture}.
*/
RGB111110F(32,true),
/**
* Texture data is stored as {@link Format#RGB16F} in system memory,
* but will be converted to {@link Format#RGB9E5} when sent
* to the video hardware.
*
* Requires {@link Caps#FloatTexture} and {@link Caps#SharedExponentTexture}.
*/
RGB16F_to_RGB9E5(48,true),
/**
* 9-bit red, green and blue with 5-bit exponent.
*
* Requires {@link Caps#SharedExponentTexture}.
*/
RGB9E5(32,true),
/**
* half-precision floating point red, green, and blue.
*
* Requires {@link Caps#FloatTexture}.
*/
RGB16F(48,true),
/**
* half-precision floating point red, green, blue, and alpha.
*
* Requires {@link Caps#FloatTexture}.
*/
RGBA16F(64,true),
/**
* single-precision floating point red, green, and blue.
*
* Requires {@link Caps#FloatTexture}.
*/
RGB32F(96,true),
/**
* single-precision floating point red, green, blue and alpha.
*
* Requires {@link Caps#FloatTexture}.
*/
RGBA32F(128,true),
@Deprecated
Reserved11(0),
/**
* 24-bit depth with 8-bit stencil.
* Check the cap {@link Caps#PackedDepthStencilBuffer}.
*/
Depth24Stencil8(32, true, false, false),
@Deprecated
Reserved12(0),
/**
* Ericsson Texture Compression. Typically used on Android.
*
* Requires {@link Caps#TextureCompressionETC1}.
*/
ETC1(4, false, true, false);
private int bpp;
private boolean isDepth;
private boolean isCompressed;
private boolean isFloatingPoint;
private Format(int bpp){
this.bpp = bpp;
}
private Format(int bpp, boolean isFP){
this(bpp);
this.isFloatingPoint = isFP;
}
private Format(int bpp, boolean isDepth, boolean isCompressed, boolean isFP){
this(bpp, isFP);
this.isDepth = isDepth;
this.isCompressed = isCompressed;
}
/**
* @return bits per pixel.
*/
public int getBitsPerPixel(){
return bpp;
}
/**
* @return True if this format is a depth format, false otherwise.
*/
public boolean isDepthFormat(){
return isDepth;
}
/**
* @return True if this format is a depth + stencil (packed) format, false otherwise.
*/
boolean isDepthStencilFormat() {
return this == Depth24Stencil8;
}
/**
* @return True if this is a compressed image format, false if
* uncompressed.
*/
public boolean isCompressed() {
return isCompressed;
}
/**
* @return True if this image format is in floating point,
* false if it is an integer format.
*/
public boolean isFloatingPont(){
return isFloatingPoint;
}
}
// image attributes
protected Format format;
protected int width, height, depth;
protected int[] mipMapSizes;
protected ArrayList<ByteBuffer> data;
protected int multiSamples = 1;
protected ColorSpace colorSpace = null;
// protected int mipOffset = 0;
// attributes relating to GL object
protected boolean mipsWereGenerated = false;
protected boolean needGeneratedMips = false;
protected LastTextureState lastTextureState = new LastTextureState();
/**
* Internal use only.
* The renderer stores the texture state set from the last texture
* so it doesn't have to change it unless necessary.
*
* @return The image parameter state.
*/
public LastTextureState getLastTextureState() {
return lastTextureState;
}
/**
* Internal use only.
* The renderer marks which images have generated mipmaps in VRAM
* and which do not, so it can generate them as needed.
*
* @param generated If mipmaps were generated or not.
*/
public void setMipmapsGenerated(boolean generated) {
this.mipsWereGenerated = generated;
}
/**
* Internal use only.
* Check if the renderer has generated mipmaps for this image in VRAM
* or not.
*
* @return If mipmaps were generated already.
*/
public boolean isMipmapsGenerated() {
return mipsWereGenerated;
}
/**
* (Package private) Called by {@link Texture} when
* {@link #isMipmapsGenerated() } is false in order to generate
* mipmaps for this image.
*/
void setNeedGeneratedMipmaps() {
needGeneratedMips = true;
}
/**
* @return True if the image needs to have mipmaps generated
* for it (as requested by the texture). This stays true even
* after mipmaps have been generated.
*/
public boolean isGeneratedMipmapsRequired() {
return needGeneratedMips;
}
/**
* Sets the update needed flag, while also checking if mipmaps
* need to be regenerated.
*/
@Override
public void setUpdateNeeded() {
super.setUpdateNeeded();
if (isGeneratedMipmapsRequired() && !hasMipmaps()) {
// Mipmaps are no longer valid, since the image was changed.
setMipmapsGenerated(false);
}
}
/**
* Determine if the image is NPOT.
*
* @return if the image is a non-power-of-2 image, e.g. having dimensions
* that are not powers of 2.
*/
public boolean isNPOT() {
return width != 0 && height != 0
&& (!FastMath.isPowerOfTwo(width) || !FastMath.isPowerOfTwo(height));
}
@Override
public void resetObject() {
this.id = -1;
this.mipsWereGenerated = false;
this.lastTextureState.reset();
setUpdateNeeded();
}
@Override
protected void deleteNativeBuffers() {
for (ByteBuffer buf : data) {
BufferUtils.destroyDirectBuffer(buf);
}
}
@Override
public void deleteObject(Object rendererObject) {
((Renderer)rendererObject).deleteImage(this);
}
@Override
public NativeObject createDestructableClone() {
return new Image(id);
}
@Override
public long getUniqueId() {
return ((long)OBJTYPE_TEXTURE << 32) | ((long)id);
}
/**
* @return A shallow clone of this image. The data is not cloned.
*/
@Override
public Image clone(){
Image clone = (Image) super.clone();
clone.mipMapSizes = mipMapSizes != null ? mipMapSizes.clone() : null;
clone.data = data != null ? new ArrayList<ByteBuffer>(data) : null;
clone.lastTextureState = new LastTextureState();
clone.setUpdateNeeded();
return clone;
}
/**
* Constructor instantiates a new <code>Image</code> object. All values
* are undefined.
*/
public Image() {
super();
data = new ArrayList<ByteBuffer>(1);
}
protected Image(int id){
super(id);
}
/**
* Constructor instantiates a new <code>Image</code> object. The
* attributes of the image are defined during construction.
*
* @param format
* the data format of the image.
* @param width
* the width of the image.
* @param height
* the height of the image.
* @param data
* the image data.
* @param mipMapSizes
* the array of mipmap sizes, or null for no mipmaps.
* @param colorSpace
* @see ColorSpace the colorSpace of the image
*/
public Image(Format format, int width, int height, int depth, ArrayList<ByteBuffer> data,
int[] mipMapSizes, ColorSpace colorSpace) {
this();
if (mipMapSizes != null) {
if (mipMapSizes.length <= 1) {
mipMapSizes = null;
} else {
needGeneratedMips = false;
mipsWereGenerated = true;
}
}
setFormat(format);
this.width = width;
this.height = height;
this.data = data;
this.depth = depth;
this.mipMapSizes = mipMapSizes;
this.colorSpace = colorSpace;
}
/**
* @see {@link #Image(com.jme3.texture.Image.Format, int, int, int, java.util.ArrayList, int[], boolean)}
* @param format
* @param width
* @param height
* @param depth
* @param data
* @param mipMapSizes
* @deprecated use {@link #Image(com.jme3.texture.Image.Format, int, int, int, java.util.ArrayList, int[], boolean)}
*/
@Deprecated
public Image(Format format, int width, int height, int depth, ArrayList<ByteBuffer> data,
int[] mipMapSizes) {
this(format, width, height, depth, data, mipMapSizes, ColorSpace.Linear);
}
/**
* Constructor instantiates a new <code>Image</code> object. The
* attributes of the image are defined during construction.
*
* @param format
* the data format of the image.
* @param width
* the width of the image.
* @param height
* the height of the image.
* @param data
* the image data.
* @param mipMapSizes
* the array of mipmap sizes, or null for no mipmaps.
* @param colorSpace
* @see ColorSpace the colorSpace of the image
*/
public Image(Format format, int width, int height, ByteBuffer data,
int[] mipMapSizes, ColorSpace colorSpace) {
this();
if (mipMapSizes != null && mipMapSizes.length <= 1) {
mipMapSizes = null;
} else {
needGeneratedMips = false;
mipsWereGenerated = true;
}
setFormat(format);
this.width = width;
this.height = height;
if (data != null){
this.data = new ArrayList<ByteBuffer>(1);
this.data.add(data);
}
this.mipMapSizes = mipMapSizes;
this.colorSpace = colorSpace;
}
/**
* @see {@link #Image(com.jme3.texture.Image.Format, int, int, java.nio.ByteBuffer, int[], boolean)}
* @param format
* @param width
* @param height
* @param data
* @param mipMapSizes
* @deprecated use {@link #Image(com.jme3.texture.Image.Format, int, int, java.nio.ByteBuffer, int[], boolean)}
*/
@Deprecated
public Image(Format format, int width, int height, ByteBuffer data,
int[] mipMapSizes) {
this(format, width, height, data, mipMapSizes, ColorSpace.Linear);
}
/**
* Constructor instantiates a new <code>Image</code> object. The
* attributes of the image are defined during construction.
*
* @param format
* the data format of the image.
* @param width
* the width of the image.
* @param height
* the height of the image.
* @param data
* the image data.
* @param colorSpace
* @see ColorSpace the colorSpace of the image
*/
public Image(Format format, int width, int height, int depth, ArrayList<ByteBuffer> data, ColorSpace colorSpace) {
this(format, width, height, depth, data, null, colorSpace);
}
/**
* @see {@link #Image(com.jme3.texture.Image.Format, int, int, int, java.util.ArrayList, boolean)}
* @param format
* @param width
* @param height
* @param depth
* @param data
* @deprecated use {@link #Image(com.jme3.texture.Image.Format, int, int, int, java.util.ArrayList, boolean)}
*/
@Deprecated
public Image(Format format, int width, int height, int depth, ArrayList<ByteBuffer> data) {
this(format, width, height, depth, data, ColorSpace.Linear);
}
/**
* Constructor instantiates a new <code>Image</code> object. The
* attributes of the image are defined during construction.
*
* @param format
* the data format of the image.
* @param width
* the width of the image.
* @param height
* the height of the image.
* @param data
* the image data.
* @param colorSpace
* @see ColorSpace the colorSpace of the image
*/
public Image(Format format, int width, int height, ByteBuffer data, ColorSpace colorSpace) {
this(format, width, height, data, null, colorSpace);
}
/**
* @see {@link #Image(com.jme3.texture.Image.Format, int, int, java.nio.ByteBuffer, boolean)}
* @param format
* @param width
* @param height
* @param data
* @deprecated use {@link #Image(com.jme3.texture.Image.Format, int, int, java.nio.ByteBuffer, boolean)}
*/
@Deprecated
public Image(Format format, int width, int height, ByteBuffer data) {
this(format, width, height, data, null, ColorSpace.Linear);
}
/**
* @return The number of samples (for multisampled textures).
* @see Image#setMultiSamples(int)
*/
public int getMultiSamples() {
return multiSamples;
}
/**
* @param multiSamples Set the number of samples to use for this image,
* setting this to a value higher than 1 turns this image/texture
* into a multisample texture (on OpenGL3.1 and higher).
*/
public void setMultiSamples(int multiSamples) {
if (multiSamples <= 0)
throw new IllegalArgumentException("multiSamples must be > 0");
if (getData(0) != null)
throw new IllegalArgumentException("Cannot upload data as multisample texture");
if (hasMipmaps())
throw new IllegalArgumentException("Multisample textures do not support mipmaps");
this.multiSamples = multiSamples;
}
/**
* <code>setData</code> sets the data that makes up the image. This data
* is packed into an array of <code>ByteBuffer</code> objects.
*
* @param data
* the data that contains the image information.
*/
public void setData(ArrayList<ByteBuffer> data) {
this.data = data;
setUpdateNeeded();
}
/**
* <code>setData</code> sets the data that makes up the image. This data
* is packed into a single <code>ByteBuffer</code>.
*
* @param data
* the data that contains the image information.
*/
public void setData(ByteBuffer data) {
this.data = new ArrayList<ByteBuffer>(1);
this.data.add(data);
setUpdateNeeded();
}
public void addData(ByteBuffer data) {
if (this.data == null)
this.data = new ArrayList<ByteBuffer>(1);
this.data.add(data);
setUpdateNeeded();
}
public void setData(int index, ByteBuffer data) {
if (index >= 0) {
while (this.data.size() <= index) {
this.data.add(null);
}
this.data.set(index, data);
setUpdateNeeded();
} else {
throw new IllegalArgumentException("index must be greater than or equal to 0.");
}
}
/**
* @deprecated This feature is no longer used by the engine
*/
@Deprecated
public void setEfficentData(Object efficientData){
}
/**
* @deprecated This feature is no longer used by the engine
*/
@Deprecated
public Object getEfficentData(){
return null;
}
/**
* Sets the mipmap sizes stored in this image's data buffer. Mipmaps are
* stored sequentially, and the first mipmap is the main image data. To
* specify no mipmaps, pass null and this will automatically be expanded
* into a single mipmap of the full
*
* @param mipMapSizes
* the mipmap sizes array, or null for a single image map.
*/
public void setMipMapSizes(int[] mipMapSizes) {
if (mipMapSizes != null && mipMapSizes.length <= 1)
mipMapSizes = null;
this.mipMapSizes = mipMapSizes;
if (mipMapSizes != null) {
needGeneratedMips = false;
mipsWereGenerated = false;
} else {
needGeneratedMips = true;
mipsWereGenerated = false;
}
setUpdateNeeded();
}
/**
* <code>setHeight</code> sets the height value of the image. It is
* typically a good idea to try to keep this as a multiple of 2.
*
* @param height
* the height of the image.
*/
public void setHeight(int height) {
this.height = height;
setUpdateNeeded();
}
/**
* <code>setDepth</code> sets the depth value of the image. It is
* typically a good idea to try to keep this as a multiple of 2. This is
* used for 3d images.
*
* @param depth
* the depth of the image.
*/
public void setDepth(int depth) {
this.depth = depth;
setUpdateNeeded();
}
/**
* <code>setWidth</code> sets the width value of the image. It is
* typically a good idea to try to keep this as a multiple of 2.
*
* @param width
* the width of the image.
*/
public void setWidth(int width) {
this.width = width;
setUpdateNeeded();
}
/**
* <code>setFormat</code> sets the image format for this image.
*
* @param format
* the image format.
* @throws NullPointerException
* if format is null
* @see Format
*/
public void setFormat(Format format) {
if (format == null) {
throw new NullPointerException("format may not be null.");
}
this.format = format;
setUpdateNeeded();
}
/**
* <code>getFormat</code> returns the image format for this image.
*
* @return the image format.
* @see Format
*/
public Format getFormat() {
return format;
}
/**
* <code>getWidth</code> returns the width of this image.
*
* @return the width of this image.
*/
public int getWidth() {
return width;
}
/**
* <code>getHeight</code> returns the height of this image.
*
* @return the height of this image.
*/
public int getHeight() {
return height;
}
/**
* <code>getDepth</code> returns the depth of this image (for 3d images).
*
* @return the depth of this image.
*/
public int getDepth() {
return depth;
}
/**
* <code>getData</code> returns the data for this image. If the data is
* undefined, null will be returned.
*
* @return the data for this image.
*/
public List<ByteBuffer> getData() {
return data;
}
/**
* <code>getData</code> returns the data for this image. If the data is
* undefined, null will be returned.
*
* @return the data for this image.
*/
public ByteBuffer getData(int index) {
if (data.size() > index)
return data.get(index);
else
return null;
}
/**
* Returns whether the image data contains mipmaps.
*
* @return true if the image data contains mipmaps, false if not.
*/
public boolean hasMipmaps() {
return mipMapSizes != null;
}
/**
* Returns the mipmap sizes for this image.
*
* @return the mipmap sizes for this image.
*/
public int[] getMipMapSizes() {
return mipMapSizes;
}
/**
* image loader is responsible for setting this attribute based on the color
* space in which the image has been encoded with. In the majority of cases,
* this flag will be set to sRGB by default since many image formats do not
* contain any color space information and the most frequently used colors
* space is sRGB
*
* The material loader may override this attribute to Lineat if it determines that
* such conversion must not be performed, for example, when loading normal
* maps.
*
* @param colorSpace @see ColorSpace. Set to sRGB to enable srgb -> linear
* conversion, Linear otherwise.
*
* @seealso Renderer#setLinearizeSrgbImages(boolean)
*
*/
public void setColorSpace(ColorSpace colorSpace) {
this.colorSpace = colorSpace;
}
/**
* Specifies that this image is an SRGB image and therefore must undergo an
* sRGB -> linear RGB color conversion prior to being read by a shader and
* with the {@link Renderer#setLinearizeSrgbImages(boolean)} option is
* enabled.
*
* This option is only supported for the 8-bit color and grayscale image
* formats. Determines if the image is in SRGB color space or not.
*
* @return True, if the image is an SRGB image, false if it is linear RGB.
*
* @seealso Renderer#setLinearizeSrgbImages(boolean)
*/
public ColorSpace getColorSpace() {
return colorSpace;
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append("[size=").append(width).append("x").append(height);
if (depth > 1)
sb.append("x").append(depth);
sb.append(", format=").append(format.name());
if (hasMipmaps())
sb.append(", mips");
if (getId() >= 0)
sb.append(", id=").append(id);
sb.append("]");
return sb.toString();
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof Image)) {
return false;
}
Image that = (Image) other;
if (this.getFormat() != that.getFormat())
return false;
if (this.getWidth() != that.getWidth())
return false;
if (this.getHeight() != that.getHeight())
return false;
if (this.getData() != null && !this.getData().equals(that.getData()))
return false;
if (this.getData() == null && that.getData() != null)
return false;
if (this.getMipMapSizes() != null
&& !Arrays.equals(this.getMipMapSizes(), that.getMipMapSizes()))
return false;
if (this.getMipMapSizes() == null && that.getMipMapSizes() != null)
return false;
if (this.getMultiSamples() != that.getMultiSamples())
return false;
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + (this.format != null ? this.format.hashCode() : 0);
hash = 97 * hash + this.width;
hash = 97 * hash + this.height;
hash = 97 * hash + this.depth;
hash = 97 * hash + Arrays.hashCode(this.mipMapSizes);
hash = 97 * hash + (this.data != null ? this.data.hashCode() : 0);
hash = 97 * hash + this.multiSamples;
return hash;
}
public void write(JmeExporter e) throws IOException {
OutputCapsule capsule = e.getCapsule(this);
capsule.write(format, "format", Format.RGBA8);
capsule.write(width, "width", 0);
capsule.write(height, "height", 0);
capsule.write(depth, "depth", 0);
capsule.write(mipMapSizes, "mipMapSizes", null);
capsule.write(multiSamples, "multiSamples", 1);
capsule.writeByteBufferArrayList(data, "data", null);
}
public void read(JmeImporter e) throws IOException {
InputCapsule capsule = e.getCapsule(this);
format = capsule.readEnum("format", Format.class, Format.RGBA8);
width = capsule.readInt("width", 0);
height = capsule.readInt("height", 0);
depth = capsule.readInt("depth", 0);
mipMapSizes = capsule.readIntArray("mipMapSizes", null);
multiSamples = capsule.readInt("multiSamples", 1);
data = (ArrayList<ByteBuffer>) capsule.readByteBufferArrayList("data", null);
if (mipMapSizes != null) {
needGeneratedMips = false;
mipsWereGenerated = true;
}
}
}
|
// Triple Play - utilities for use in PlayN-based games
package tripleplay.flump;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import playn.core.Image;
import playn.core.Json;
import playn.core.util.Callback;
import static playn.core.PlayN.*;
import react.Value;
public class Library
{
/** The original frame rate of movies in this library. */
public final float frameRate;
/** The symbols defined in this library. */
public final Map<String,Symbol> symbols;
protected Library (Json.Object json, String baseDir, final Callback<Library> callback) {
frameRate = json.getNumber("frameRate");
final Map<String,Symbol> symbols = new HashMap<String,Symbol>();
this.symbols = Collections.unmodifiableMap(symbols);
final ArrayList<Movie.Symbol> movies = new ArrayList<Movie.Symbol>();
for (Json.Object movieJson : json.getArray("movies", Json.Object.class)) {
Movie.Symbol movie = new Movie.Symbol(this, movieJson);
movies.add(movie);
symbols.put(movie.name(), movie);
}
Json.TypedArray<Json.Object> atlases = json.getArray("atlases", Json.Object.class);
final Value<Integer> remainingAtlases = Value.create(atlases.length());
remainingAtlases.connectNotify(new Value.Listener<Integer>() {
public void onChange (Integer remaining, Integer _) {
if (remaining > 0) return;
// When all the symbols have been loaded, go through and resolve references
for (Movie.Symbol movie : movies) {
for (LayerData layer : movie.layers) {
for (KeyframeData kf : layer.keyframes) {
Symbol symbol = symbols.get(kf._symbolName);
if (symbol != null) {
if (layer._lastSymbol == null) {
layer._lastSymbol = symbol;
} else if (layer._lastSymbol != symbol) {
layer._multipleSymbols = true;
}
kf._symbol = symbol;
}
}
}
}
// We're done!
callback.onSuccess(Library.this);
}
});
for (final Json.Object atlasJson : atlases) {
Image atlas = assets().getImage(baseDir + "/" + atlasJson.getString("file"));
atlas.addCallback(new Callback.Chain<Image>(callback) {
public void onSuccess (Image atlas) {
for (Json.Object textureJson : atlasJson.getArray("textures", Json.Object.class)) {
Texture.Symbol texture = new Texture.Symbol(textureJson, atlas);
symbols.put(texture.name(), texture);
}
remainingAtlases.update(remainingAtlases.get() - 1);
}
});
}
}
/**
* Loads a Library from PlayN assets.
* @param baseDir The base directory, containing library.json and texture atlases.
*/
public static void fromAssets (final String baseDir, final Callback<Library> callback) {
assert(callback != null); // Fail fast
assets().getText(baseDir + "/library.json", new Callback.Chain<String>(callback) {
public void onSuccess (String text) {
Library lib = null;
try {
lib = new Library(json().parse(text), baseDir, callback);
} catch (Exception err) {
callback.onFailure(err);
}
}
});
}
/** Creates an instance of a symbol, or throws if the symbol name is not in this library. */
public Instance createInstance (String symbolName) {
Symbol symbol = symbols.get(symbolName);
if (symbol == null) {
throw new IllegalArgumentException("Missing required symbol [name=" + symbolName + "]");
}
return symbol.createInstance();
}
public Movie createMovie (String symbolName) {
return (Movie)createInstance(symbolName);
}
}
|
// $Id: PullPushAdapter.java,v 1.10 2004/09/30 14:47:34 belaban Exp $
package org.jgroups.blocks;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.*;
import org.jgroups.util.Util;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
* Allows a client of <em>Channel</em> to be notified when messages have been received
* instead of having to actively poll the channel for new messages. Typically used in the
* client role (receive()). As this class does not implement interface
* <code>Transport</code>, but <b>uses</b> it for receiving messages, an underlying object
* has to be used to send messages (e.g. the channel on which an object of this class relies).<p>
* Multiple MembershipListeners can register with the PullPushAdapter; when a view is received, they
* will all be notified. There is one main message listener which sends and receives message. In addition,
* MessageListeners can register with a certain tag (identifier), and then send messages tagged with this
* identifier. When a message with such an identifier is received, the corresponding MessageListener will be
* looked up and the message dispatched to it. If no tag is found (default), the main MessageListener will
* receive the message.
* @author Bela Ban
* @version $Revision
*/
public class PullPushAdapter implements Runnable, ChannelListener {
protected Transport transport=null;
protected MessageListener listener=null; // main message receiver
protected final List membership_listeners=new ArrayList();
protected Thread receiver_thread=null;
protected final HashMap listeners=new HashMap(); // keys=identifier (Serializable), values=MessageListeners
protected final Log log=LogFactory.getLog(getClass());
static final String PULL_HEADER="PULL_HEADER";
public PullPushAdapter(Transport transport) {
this.transport=transport;
start();
}
public PullPushAdapter(Transport transport, MessageListener l) {
this.transport=transport;
setListener(l);
start();
}
public PullPushAdapter(Transport transport, MembershipListener ml) {
this.transport=transport;
addMembershipListener(ml);
start();
}
public PullPushAdapter(Transport transport, MessageListener l, MembershipListener ml) {
this.transport=transport;
setListener(l);
addMembershipListener(ml);
start();
}
public Transport getTransport() {
return transport;
}
public void start() {
if(receiver_thread == null) {
receiver_thread=new Thread(this, "PullPushAdapterThread");
receiver_thread.setDaemon(true);
receiver_thread.start();
}
if(transport instanceof JChannel)
((JChannel)transport).setChannelListener(this);
}
public void stop() {
Thread tmp=null;
if(receiver_thread != null && receiver_thread.isAlive()) {
tmp=receiver_thread;
receiver_thread=null;
tmp.interrupt();
try {
tmp.join(1000);
}
catch(Exception ex) {
}
}
receiver_thread=null;
}
/**
* Sends a message to the group - listeners to this identifier will receive the messages
* @param identifier the key that the proper listeners are listenting on
* @param msg the Message to be sent
* @see registerListener
*/
public void send(Serializable identifier, Message msg) throws Exception {
if(msg == null) {
if(log.isErrorEnabled()) log.error("msg is null");
return;
}
if(identifier == null)
transport.send(msg);
else {
msg.putHeader(PULL_HEADER, new PullHeader(identifier));
transport.send(msg);
}
}
/**
* sends a message with no identifier , listener member will get this message on the other group members
* @param msg the Message to be sent
* @throws Exception
*/
public void send(Message msg) throws Exception {
send(null, msg);
}
public void setListener(MessageListener l) {
listener=l;
}
/**
* sets a listener to messages with a given identifier messages sent with this identifier in there header will be routed to this listener
* <b>note: there could be only one listener for one identifier, if you want to register a different listener to an already registered identifier then unregister first</b>
* @param identifier - messages sent on the group with this object will be receive by this listener
* @param l - the listener that will get the message
*/
public void registerListener(Serializable identifier, MessageListener l) {
if(l == null || identifier == null) {
if(log.isErrorEnabled()) log.error("message listener or identifier is null");
return;
}
if(listeners.containsKey(identifier)) {
if(log.isErrorEnabled()) log.error("listener with identifier=" + identifier +
" already exists, choose a different identifier or unregister current listener");
// we do not want to overwrite the listener
return;
}
listeners.put(identifier, l);
}
/**
* removes a listener to a given identifier from the listeners map
* @param identifier - the key to whom we do not want to listen any more
*/
public void unregisterListener(Serializable identifier) {
listeners.remove(identifier);
}
/** @deprecated Use {@link #addMembershipListener} */
public void setMembershipListener(MembershipListener ml) {
addMembershipListener(ml);
}
public void addMembershipListener(MembershipListener l) {
if(l != null && !membership_listeners.contains(l))
membership_listeners.add(l);
}
public void removeMembershipListener(MembershipListener l) {
if(l != null && membership_listeners.contains(l))
membership_listeners.remove(l);
}
/**
* Reentrant run(): message reception is serialized, then the listener is notified of the
* message reception
*/
public void run() {
Object obj;
while(receiver_thread != null) {
try {
obj=transport.receive(0);
if(obj == null)
continue;
if(obj instanceof Message) {
handleMessage((Message)obj);
}
else if(obj instanceof GetStateEvent) {
byte[] retval=null;
if(listener != null) {
try {
retval=listener.getState();
}
catch(Throwable t) {
log.error("getState() from application failed, will return empty state", t);
}
}
else {
log.warn("no listener registered, returning empty state");
}
if(transport instanceof Channel) {
((Channel)transport).returnState(retval);
}
else {
if(log.isErrorEnabled())
log.error("underlying transport is not a Channel, but a " +
transport.getClass().getName() + ": cannot return state using returnState()");
continue;
}
}
else if(obj instanceof SetStateEvent) {
if(listener != null) {
try {
listener.setState(((SetStateEvent)obj).getArg());
}
catch(ClassCastException cast_ex) {
if(log.isErrorEnabled()) log.error("received SetStateEvent, but argument " +
((SetStateEvent)obj).getArg() + " is not serializable ! Discarding message.");
continue;
}
}
}
else if(obj instanceof View) {
notifyViewChange((View)obj);
}
else if(obj instanceof SuspectEvent) {
notifySuspect((Address)((SuspectEvent)obj).getMember());
}
else if(obj instanceof BlockEvent) {
notifyBlock();
}
}
catch(ChannelNotConnectedException conn) {
Address local_addr=((Channel)transport).getLocalAddress();
if(log.isWarnEnabled()) log.warn('[' + (local_addr == null ? "<null>" : local_addr.toString()) +
"] channel not connected, exception is " + conn);
Util.sleep(1000);
receiver_thread=null;
break;
}
catch(ChannelClosedException closed_ex) {
Address local_addr=((Channel)transport).getLocalAddress();
if(log.isWarnEnabled()) log.warn('[' + (local_addr == null ? "<null>" : local_addr.toString()) +
"] channel closed, exception is " + closed_ex);
Util.sleep(1000);
receiver_thread=null;
break;
}
catch(Throwable e) {
}
}
}
/**
* Check whether the message has an identifier. If yes, lookup the MessageListener associated with the
* given identifier in the hashtable and dispatch to it. Otherwise just use the main (default) message
* listener
*/
protected void handleMessage(Message msg) {
PullHeader hdr=(PullHeader)msg.getHeader(PULL_HEADER);
Serializable identifier;
MessageListener l;
if(hdr != null && (identifier=hdr.getIdentifier()) != null) {
l=(MessageListener)listeners.get(identifier);
if(l == null) {
if(log.isErrorEnabled()) log.error("received a messages tagged with identifier=" +
identifier + ", but there is no registration for that identifier. Will drop message");
}
else
l.receive(msg);
}
else {
if(listener != null)
listener.receive(msg);
}
}
protected void notifyViewChange(View v) {
MembershipListener l;
if(v == null) return;
for(Iterator it=membership_listeners.iterator(); it.hasNext();) {
l=(MembershipListener)it.next();
try {
l.viewAccepted(v);
}
catch(Throwable ex) {
if(log.isErrorEnabled()) log.error("exception notifying " + l + ": " + ex);
}
}
}
protected void notifySuspect(Address suspected_mbr) {
MembershipListener l;
if(suspected_mbr == null) return;
for(Iterator it=membership_listeners.iterator(); it.hasNext();) {
l=(MembershipListener)it.next();
try {
l.suspect(suspected_mbr);
}
catch(Throwable ex) {
if(log.isErrorEnabled()) log.error("exception notifying " + l + ": " + ex);
}
}
}
protected void notifyBlock() {
MembershipListener l;
for(Iterator it=membership_listeners.iterator(); it.hasNext();) {
l=(MembershipListener)it.next();
try {
l.block();
}
catch(Throwable ex) {
if(log.isErrorEnabled()) log.error("exception notifying " + l + ": " + ex);
}
}
}
public void channelConnected(Channel channel) {
}
public void channelDisconnected(Channel channel) {
}
public void channelClosed(Channel channel) {
}
public void channelShunned() {
}
public void channelReconnected(Address addr) {
if(receiver_thread == null)
start();
}
public static final class PullHeader extends Header {
Serializable identifier=null;
public PullHeader() {
; // used by externalization
}
public PullHeader(Serializable identifier) {
this.identifier=identifier;
}
public Serializable getIdentifier() {
return identifier;
}
public long size() {
return 128;
}
public String toString() {
return "PullHeader";
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(identifier);
}
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
identifier=(Serializable)in.readObject();
}
}
/**
* @return Returns the listener.
*/
public MessageListener getListener() {
return listener;
}
}
|
package cz.metacentrum.perun.core.impl.modules.attributes;
import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.AttributesManager;
import cz.metacentrum.perun.core.api.Group;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException;
import cz.metacentrum.perun.core.impl.PerunSessionImpl;
import cz.metacentrum.perun.core.implApi.modules.attributes.GroupVirtualAttributesModuleAbstract;
import cz.metacentrum.perun.core.implApi.modules.attributes.GroupVirtualAttributesModuleImplApi;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Module for virtual group attribute.
*
* Return login-namespace:userId, elixir-persistent, preferredMail and login for all user in group as JSON.
* @author Pavel Vyskocil <vyskocilpavel@muni.cz>
*/
public class urn_perun_group_attribute_def_virt_denbiProjectMembers extends GroupVirtualAttributesModuleAbstract implements GroupVirtualAttributesModuleImplApi {
public static final String USER_ID = "urn:perun:user:attribute-def:core:id";
public static final String ELIXIR_PERSISTENT = "urn:perun:user:attribute-def:virt:login-namespace:elixir-persistent";
public static final String PREFERRED_MAIL = "urn:perun:user:attribute-def:def:preferredMail";
public static final String ELIXIR_LOGIN = "urn:perun:user:attribute-def:def:login-namespace:elixir";
@Override
public Attribute getAttributeValue(PerunSessionImpl perunSession, Group group, AttributeDefinition attribute) throws InternalErrorException {
List<User> users = perunSession.getPerunBl().getGroupsManagerBl().getGroupUsers(perunSession, group);
JSONArray jsonMembers = new JSONArray();
for (User user: users) {
JSONObject jsonUser = new JSONObject();
try{
Attribute userId = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, user, USER_ID);
jsonUser.put(userId.getFriendlyName(), userId.getValue());
Attribute elixirPersistent = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, user, ELIXIR_PERSISTENT);
jsonUser.put(elixirPersistent.getFriendlyName(), elixirPersistent.getValue());
Attribute preferredMail = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, user, PREFERRED_MAIL);
jsonUser.put(preferredMail.getFriendlyName(), preferredMail.getValue());
Attribute elixirLogin = perunSession.getPerunBl().getAttributesManagerBl().getAttribute(perunSession, user, ELIXIR_LOGIN);
jsonUser.put(elixirLogin.getFriendlyName(), elixirLogin.getValue());
jsonMembers.put(jsonUser);
} catch (JSONException | AttributeNotExistsException | WrongAttributeAssignmentException e){
throw new InternalErrorException(e);
}
}
Attribute members = new Attribute(attribute);
members.setValue(jsonMembers.toString());
return members;
}
//IMPORTANT - this is very performance demanding operation, we will skip it
/*
@Override
public List<String> getStrongDependencies() {
List<String> strongDependencies = new ArrayList<>();
strongDependencies.add(USER_ID);
strongDependencies.add(ELIXIR_PERSISTENT);
strongDependencies.add(PREFERRED_MAIL);
strongDependencies.add(ELIXIR_LOGIN);
return strongDependencies;
}*/
@Override
public AttributeDefinition getAttributeDefinition() {
AttributeDefinition attr = new AttributeDefinition();
attr.setNamespace(AttributesManager.NS_GROUP_ATTR_VIRT);
attr.setFriendlyName("denbiProjectMembers");
attr.setDisplayName("Project Members");
attr.setType(String.class.getName());
attr.setDescription("Project Members");
return attr;
}
}
|
package com.ayoza.camera_sputnik.camerasputnik.activities;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.ayoza.camera_sputnik.camerasputnik.R;
import com.ayoza.camera_sputnik.camerasputnik.arduino.managers.TrackMgr;
import com.ayoza.camera_sputnik.camerasputnik.exceptions.TrackException;
import com.ayoza.camera_sputnik.camerasputnik.gallery.entities.PagerContainer;
import com.ayoza.camera_sputnik.camerasputnik.storage.entities.ImageSputnik;
import java.util.List;
public class GalleryActivity extends Activity {
//gallery object
// private ViewPager picGallery;
//image view for larger display
//private ImageView picView;
PagerContainer mContainer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
TrackMgr trackMgr = TrackMgr.getInstance(this);
List<ImageSputnik> currentImages = null;
try {
currentImages = trackMgr.getAllImagesFromCurrentTrack();
} catch (TrackException e) {
e.printStackTrace();
}
if (currentImages != null) {
for (ImageSputnik image : currentImages) {
System.out.println("image filename: " + image.getFilename());
}
}
mContainer = (PagerContainer) findViewById(R.id.pager_container);
ViewPager pager = mContainer.getViewPager();
PagerAdapter adapter = new GalleryAdapter(currentImages);
pager.setAdapter(adapter);
//Necessary or the pager will only have one extra page to show
// make this at least however many pages you can see
pager.setOffscreenPageLimit(adapter.getCount());
//A little space between pages
pager.setPageMargin(15);
//If hardware acceleration is enabled, you should also remove
// clipping on the pager for its children.
pager.setClipChildren(false);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
System.out.println("nothing");
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
//Nothing special about this adapter, just throwing up colored views for demo
private class GalleryAdapter extends PagerAdapter {
private List<ImageSputnik> images = null;
public GalleryAdapter(List<ImageSputnik> images) {
this.images = images;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
//TextView view = new TextView(GalleryActivity.this);
ImageSputnik imageSputnik = images.get(position);
ImageView jpgView = new ImageView(GalleryActivity.this);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
// TODO set full path for filename
Bitmap bm = BitmapFactory.decodeFile(imageSputnik.getFilename(), options);
jpgView.setImageBitmap(bm);
/*
view.setText("Item "+position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50, position * 10, position * 50));
*/
//container.addView(view);
container.addView(jpgView);
//return view;
return jpgView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
@Override
public int getCount() {
return images != null ? images.size() : 0;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.