repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
levigo/recordmapper | src/main/java/org/jadice/recordmapper/cobol/CBLRecordAttributes.java | 304 | package org.jadice.recordmapper.cobol;
import org.jadice.recordmapper.Endian;
import org.jadice.recordmapper.RecordAttributes;
public class CBLRecordAttributes implements RecordAttributes {
private final Endian endian = Endian.BIG;
public Endian getEndian() {
return endian;
}
}
| bsd-3-clause |
Caleydo/caleydo | org.caleydo.view.table/src/org/caleydo/view/table/CustomDisplayConverter.java | 2209 | /*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
******************************************************************************/
package org.caleydo.view.table;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
import org.caleydo.core.data.collection.column.container.CategoricalContainer;
import org.caleydo.core.data.collection.column.container.IntContainer;
import org.eclipse.nebula.widgets.nattable.data.convert.DisplayConverter;
/**
* a custom {@link DisplayConverter} to manipulate the representation of numbers, such that changing the format is
* possible
*
* @author Samuel Gratzl
*
*/
public class CustomDisplayConverter extends DisplayConverter {
private final DecimalFormat formatter = new DecimalFormat("0.000",
DecimalFormatSymbols.getInstance(Locale.ENGLISH));
public CustomDisplayConverter() {
formatter.setMinimumFractionDigits(3);
}
public void changeMinFractionDigits(int delta) {
int value = Math.max(0, formatter.getMinimumFractionDigits() + delta);
formatter.setMinimumFractionDigits(value);
formatter.setMaximumFractionDigits(value);
}
@Override
public Object canonicalToDisplayValue(Object sourceValue) {
if (sourceValue == null)
return "";
if (sourceValue instanceof Float) {
Float f = (Float) sourceValue;
if (f.isNaN())
return "";
return formatter.format(f);
} else if (sourceValue instanceof Integer) {
Integer i = (Integer) sourceValue;
return i.intValue() == IntContainer.UNKNOWN_VALUE ? "" : i.toString();
} else if (sourceValue instanceof String) {
String s = (String) sourceValue;
return CategoricalContainer.UNKNOWN_CATEOGRY_STRING.equals(s) ? "" : s;
}
return sourceValue.toString();
}
@Override
public Object displayToCanonicalValue(Object destinationValue) {
if (destinationValue == null || destinationValue.toString().length() == 0) {
return null;
} else {
return destinationValue.toString();
}
}
}
| bsd-3-clause |
percolate/percolate-java-sdk | core/src/main/java/com/percolate/sdk/dto/Folder.java | 3759 | package com.percolate.sdk.dto;
import com.fasterxml.jackson.annotation.*;
import com.percolate.sdk.interfaces.HasExtraFields;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Folder implements Serializable, HasExtraFields {
private static final long serialVersionUID = -4687496017833725703L;
@JsonProperty("id")
protected String id;
@JsonProperty("scope_id")
protected String scopeId;
@JsonProperty("parent_id")
protected String parentId;
@JsonProperty("path_ids")
protected List<String> pathIds;
@JsonProperty("name")
protected String name;
@JsonProperty("description")
protected String description;
@JsonProperty("deleted")
protected Boolean deleted;
@JsonProperty("child_count")
protected Integer childCount;
@JsonProperty("asset_count")
protected Integer assetCount;
@JsonProperty("creator_id")
protected String creatorId;
@JsonProperty("created_at")
protected String createdAt;
@JsonProperty("updated_at")
protected String updatedAt;
@JsonIgnore
protected Map<String, Object> extraFields = new HashMap<>();
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public List<String> getPathIds() {
return pathIds;
}
public void setPathIds(List<String> pathIds) {
this.pathIds = pathIds;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
public Integer getChildCount() {
return childCount;
}
public void setChildCount(Integer childCount) {
this.childCount = childCount;
}
public Integer getAssetCount() {
return assetCount;
}
public void setAssetCount(Integer assetCount) {
this.assetCount = assetCount;
}
public String getCreatorId() {
return creatorId;
}
public void setCreatorId(String creatorId) {
this.creatorId = creatorId;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
@Override
public Map<String, Object> getExtraFields() {
if (extraFields == null) {
extraFields = new HashMap<>();
}
return extraFields;
}
@Override
@JsonAnySetter
public void putExtraField(String key, Object value) {
getExtraFields().put(key, value);
}
}
| bsd-3-clause |
GabrielDancause/jbooktrader | GabArbitrage/source/com/jarbitrager/platform/optimizer/DivideAndConquerOptimizerRunner.java | 4290 | package com.jarbitrager.platform.optimizer;
import com.jarbitrager.platform.model.*;
import com.jarbitrager.platform.preferences.*;
import com.jarbitrager.platform.strategy.*;
import java.util.*;
import java.util.concurrent.*;
/**
* Runs a trading strategy in the optimizer mode using a data file containing
* historical market snapshots.
*/
public class DivideAndConquerOptimizerRunner extends OptimizerRunner {
public DivideAndConquerOptimizerRunner(OptimizerDialog optimizerDialog, Strategy strategy, StrategyParams params) throws JArbitragerException {
super(optimizerDialog, strategy, params);
}
@Override
public void optimize() throws JArbitragerException {
List<StrategyParams> topParams = new ArrayList<StrategyParams>();
StrategyParams startingParams = new StrategyParams(strategyParams);
topParams.add(startingParams);
int dimensions = strategyParams.size();
HashSet<String> uniqueParams = new HashSet<String>();
int maxRange = 0;
for (StrategyParam param : startingParams.getAll()) {
maxRange = Math.max(maxRange, param.getMax() - param.getMin());
}
int divider = 3;
int iterationsRemaining = 1 + (int) (Math.log(maxRange) / Math.log(divider / 2.0));
long completedSteps = 0;
LinkedList<StrategyParams> tasks = new LinkedList<StrategyParams>();
Queue<StrategyParams> filteredTasks = new LinkedBlockingQueue<StrategyParams>();
PreferencesHolder prefs = PreferencesHolder.getInstance();
int chunkSize = 100 * prefs.getInt(JArbitragerPreferences.DivideAndConquerCoverage);
int numberOfCandidates = Math.max(1, (int) (chunkSize / Math.pow(divider, dimensions)));
int filteredTasksSize;
do {
tasks.clear();
int maxPartsPerDimension = (topParams.size() == 1) ? Math.max(divider, (int) Math.pow(chunkSize, 1.0 / dimensions)) : divider;
for (StrategyParams params : topParams) {
for (StrategyParam param : params.getAll()) {
int step = Math.max(1, (param.getMax() - param.getMin()) / (maxPartsPerDimension - 1));
param.setStep(step);
}
tasks.addAll(getTasks(params));
}
filteredTasks.clear();
for (StrategyParams params : tasks) {
String key = params.getKey();
if (!uniqueParams.contains(key)) {
uniqueParams.add(key);
filteredTasks.add(params);
}
}
long totalSteps = completedSteps + snapshotCount * iterationsRemaining * filteredTasks.size();
setTotalSteps(totalSteps);
filteredTasksSize = filteredTasks.size();
setTotalStrategies(filteredTasksSize);
execute(filteredTasks);
iterationsRemaining--;
completedSteps += snapshotCount * filteredTasks.size();
if (optimizationResults.isEmpty() && !cancelled) {
throw new JArbitragerException("No strategies found within the specified parameter boundaries.");
}
topParams.clear();
int maxIndex = Math.min(numberOfCandidates, optimizationResults.size());
for (int index = 0; index < maxIndex; index++) {
StrategyParams params = optimizationResults.get(index).getParams();
for (StrategyParam param : params.getAll()) {
String name = param.getName();
int value = param.getValue();
int displacement = (int) Math.ceil(param.getStep() / (double) divider);
StrategyParam originalParam = strategyParams.get(name);
// Don't push beyond the user-specified boundaries
param.setMin(Math.max(originalParam.getMin(), value - displacement));
param.setMax(Math.min(originalParam.getMax(), value + displacement));
}
topParams.add(new StrategyParams(params));
}
} while (filteredTasksSize > 0 && !cancelled);
}
}
| bsd-3-clause |
fraisse/jbehave-desktop | desktop-examples/desktop-example-swing-calculator/src/test/java/desktop/example/calculator/test/wraper/CalculatorWraperApplication.java | 478 | package desktop.example.calculator.test.wraper;
import org.jbehave.desktop.swing.AbstractSwingApplication;
import desktop.example.calculator.CalculatorPanel;
/**
* This concrete class extends the AbstractSwingApplication and
* wrapper the Calculator main class.
*
* @author Cristiano Gavião
*
*/
public class CalculatorWraperApplication extends AbstractSwingApplication {
public CalculatorWraperApplication() {
super(CalculatorPanel.class, new String[0]);
}
}
| bsd-3-clause |
virgo47/javasimon | core/src/main/java/org/javasimon/callback/logging/PeriodicLogTemplate.java | 2038 | package org.javasimon.callback.logging;
import org.javasimon.clock.SimonClock;
/**
* Log template that logs something after every N milliseconds.
* The {@link #isEnabled(Object)} is only true after N milliseconds from the last log.
*
* @author gquintana
*/
public class PeriodicLogTemplate<C> extends DelegateLogTemplate<C> {
/** Maximum time between two calls to log method. */
private final long period;
/** Clock object used to get current time */
private final SimonClock clock;
/** Timestamp of next invocation. */
private long nextTime;
/**
* Constructor with other template and the required period in ms.
*
* @param delegate concrete log template
* @param period logging period in milliseconds
*/
public PeriodicLogTemplate(LogTemplate<C> delegate, long period) {
this(delegate, period, SimonClock.SYSTEM);
}
public PeriodicLogTemplate(LogTemplate<C> delegate, long period, SimonClock clock) {
super(delegate);
this.period = period;
this.clock = clock;
initNextTime();
}
/**
* Get next invocation time time.
*
* @return next time
*/
public long getNextTime() {
return nextTime;
}
/**
* Get current timestamp.
*
* @return current timestamp
*/
long getCurrentTime() {
return clock.milliTime();
}
/** Computes the next timestamp. */
private synchronized void initNextTime() {
nextTime = getCurrentTime() + period;
}
/** Indicates whether next timestamp is in past. */
public synchronized boolean isNextTimePassed() {
return nextTime < getCurrentTime();
}
/**
* {@inheritDoc}
*
* @return true if delegate is true and enough time passed since last log
*/
@Override
protected boolean isEnabled(C context) {
return super.isEnabled(context) && isNextTimePassed();
}
/**
* {@inheritDoc}
* <p>
* Next time is updated after delegate log is called.
*/
@Override
protected void log(String message) {
super.log(message);
initNextTime();
}
}
| bsd-3-clause |
gnodet/test | src/main/java/jline/NoInterruptUnixTerminal.java | 1136 | /*
* Copyright (C) 2009 the original author(s).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jline;
// Based on Apache Karaf impl
/**
* Non-interruptable (via CTRL-C) {@link UnixTerminal}.
*
* @since 2.0
*/
public class NoInterruptUnixTerminal
extends UnixTerminal
{
public NoInterruptUnixTerminal() throws Exception {
super();
}
@Override
public void init() throws Exception {
super.init();
getSettings().set("intr undef");
}
@Override
public void restore() throws Exception {
getSettings().set("intr ^C");
super.restore();
}
}
| bsd-3-clause |
scaladyno/ductilej | docs/wasp-2010-2-22-src/xnocombsuper.java | 430 | class LibBase {
LibBase (String arg) {
...
}
LibBase (int arg) {
...
}
}
class Foo extends LibBase {
static Class<?>[][] Foo$SIGS = {
{ String.class }, { Integer.TYPE }};
Foo (Object arg, Class<?> arg$T) {
switch (RT.resolve(Foo$SIGS, arg$T)) {
case 0: { super(RT.cast(String.class, arg)); }
case 1: { super(RT.cast(Integer.TYPE, arg)); }
}
}
}
| bsd-3-clause |
ProgrammerDan/AddGun | src/main/java/com/programmerdan/minecraft/addgun/listeners/CompatListener.java | 1297 | package com.programmerdan.minecraft.addgun.listeners;
import java.util.concurrent.Executors;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import com.biggestnerd.devotedpvp.ItemSafeEvent;
import com.programmerdan.minecraft.addgun.AddGun;
import com.programmerdan.minecraft.addgun.ammo.Bullet;
import com.programmerdan.minecraft.addgun.ammo.Magazine;
import com.programmerdan.minecraft.addgun.guns.StandardGun;
import org.bukkit.inventory.ItemStack;
public class CompatListener implements Listener {
AddGun plugin;
public CompatListener() {
plugin = AddGun.getPlugin();
}
@EventHandler
public void safeEventListener(ItemSafeEvent safe) {
ItemStack item = safe.getItem();
if (item == null) return;
StandardGun gun = plugin.getGuns().findGun(item);
if (gun != null && gun.validGun(item)) {
safe.setValid();
return;
}
Magazine mag = plugin.getAmmo().findMagazine(item);
// TODO: validmag check
if (mag != null && item.getAmount() == 1) {
safe.setValid();
return;
}
Bullet bullet = plugin.getAmmo().findBullet(item);
if (bullet != null) {
if (item.getAmount() <= item.getMaxStackSize() && item.getAmount() > 0) {
safe.setValid();
}
}
}
}
| bsd-3-clause |
spakzad/ocs | bundle/jsky.app.ot/src/main/java/jsky/app/ot/tpe/TpeImageWidget.java | 34818 | package jsky.app.ot.tpe;
import edu.gemini.catalog.ui.QueryResultsFrame;
import edu.gemini.catalog.ui.tpe.CatalogImageDisplay;
import edu.gemini.shared.util.immutable.*;
import edu.gemini.spModel.core.Coordinates;
import edu.gemini.spModel.core.SiderealTarget;
import edu.gemini.spModel.gemini.obscomp.SPSiteQuality;
import edu.gemini.spModel.obs.context.ObsContext;
import edu.gemini.spModel.obscomp.SPInstObsComp;
import edu.gemini.spModel.target.*;
import edu.gemini.spModel.target.env.TargetEnvironment;
import edu.gemini.spModel.target.obsComp.TargetObsComp;
import edu.gemini.spModel.target.offset.OffsetPosBase;
import edu.gemini.spModel.telescope.PosAngleConstraint;
import edu.gemini.spModel.telescope.PosAngleConstraintAware;
import edu.gemini.spModel.util.Angle;
import jsky.app.ot.tpe.gems.GemsGuideStarSearchDialog;
import jsky.app.ot.util.OtColor;
import jsky.app.ot.util.PolygonD;
import jsky.util.gui.Resources;
import jsky.app.ot.util.ScreenMath;
import jsky.coords.CoordinateConverter;
import jsky.coords.WorldCoords;
import jsky.image.gui.PickObject;
import jsky.image.gui.PickObjectStatistics;
import jsky.navigator.NavigatorPane;
import jsky.util.gui.DialogUtil;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.event.MouseInputListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.*;
import java.util.List;
import java.util.logging.Logger;
/**
* This class is concerned with drawing targets, WFS etc., on an image.
*/
public class TpeImageWidget extends CatalogImageDisplay implements MouseInputListener,
TelescopePosWatcher, PropertyChangeListener {
private static final Logger LOG = Logger.getLogger(TpeImageWidget.class.getName());
// List of mouse observers
private final Vector<TpeMouseObserver> _mouseObs = new Vector<>();
// List of image view observers
private final Vector<TpeViewObserver> _viewObs = new Vector<>();
// Information about the image
private TpeContext _ctx = TpeContext.empty();
private final TpeImageInfo _imgInfo = new TpeImageInfo();
// True if the image info is valid
private boolean _imgInfoValid = false;
// List of image info observers
private final Vector<TpeImageInfoObserver> _infoObs = new Vector<>();
// A list of position editor features that can be drawn on the image.
private final Vector<TpeImageFeature> _featureList = new Vector<>();
// The current item being dragged
private TpeDraggableFeature _dragFeature;
// Base position in J2000
private WorldCoords _basePos = new WorldCoords();
// Base pos not visible
private boolean _baseOutOfView = false;
// Dialog for GeMS manual guide star selection
private GemsGuideStarSearchDialog _gemsGuideStarSearchDialog;
// Action to use to show the guide star search window
private final AbstractAction _manualGuideStarAction = new AbstractAction(
"Manual GS",
Resources.getIcon("gsmanual.png")) {
{
putValue(Action.SHORT_DESCRIPTION, "Query a guide star catalog, review candidates, and select");
}
@Override public void actionPerformed(ActionEvent evt) {
try {
manualGuideStarSearch();
} catch (Exception e) {
DialogUtil.error(e);
}
}
};
private boolean _viewingOffsets;
/**
* Constructor.
*
* @param parent the parent frame or internal frame
*/
public TpeImageWidget(final Component parent) {
super(parent, new NavigatorPane());
addMouseListener(this);
addMouseMotionListener(this);
}
/**
* Return true if this is the main application window (enables exit menu item)
*/
@Override
public boolean isMainWindow() {
return false; // grumble
}
/**
* Overrides the base class version to add the OT graphics.
*
* @param g the graphics context
* @param region if not null, the region to paint
*/
@Override
public synchronized void paintLayer(final Graphics2D g, final Rectangle2D region) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
super.paintLayer(g, region);
if (_ctx.isEmpty()) return;
if (!_imgInfoValid) {
if (!setBasePos(_basePos)) {
return;
}
}
final java.util.List<TpeMessage> messages = new ArrayList<>();
for (final TpeImageFeature tif : _featureList) {
tif.draw(g, _imgInfo);
// Gather any warnings from this feature.
final Option<Collection<TpeMessage>> opt = tif.getMessages();
if (opt.isDefined()) {
messages.addAll(opt.getValue());
}
}
if (_baseOutOfView) {
messages.add(TpeMessage.warningMessage("Base position is out of view."));
}
if (messages.size() > 0) displayMessages(messages, g);
}
private static final Font MESSAGE_FONT = new Font("dialog", Font.PLAIN, 12);
private static final ImageIcon ERROR_ICON = Resources.getIcon("error_tsk.gif");
private static final ImageIcon WARNING_ICON = Resources.getIcon("warn_tsk.gif");
private static final ImageIcon INFO_ICON = Resources.getIcon("info_tsk.gif");
private void displayMessages(final java.util.List<TpeMessage> messages, final Graphics2D g) {
Collections.sort(messages);
Collections.reverse(messages);
int vPad = 6;
int hPad = 10;
FontMetrics fm = g.getFontMetrics();
int lineHeight = fm.getHeight() + vPad;
Color origColor = g.getColor();
Font origFont = g.getFont();
g.setFont(MESSAGE_FONT);
int y = getHeight();
for (TpeMessage msg : messages) {
y -= lineHeight;
g.setColor(getMessageColor(msg));
g.fillRect(0, y, getWidth(), lineHeight);
ImageIcon icon = getMessageIcon(msg);
int iconY = y + (lineHeight - icon.getIconHeight()) / 2;
g.drawImage(icon.getImage(), hPad, iconY, null);
g.setColor(Color.black);
int strX = hPad * 2 + icon.getIconWidth();
int strY = y + fm.getLeading() + fm.getAscent() + vPad / 2;
g.drawString(msg.getMessage(), strX, strY);
}
// Separate the items with a line.
for (int i = 1; i < messages.size(); ++i) {
int lineY = getHeight() - i * lineHeight;
g.setColor(OtColor.DARKER_BG_GREY);
g.drawLine(0, lineY, getWidth(), lineY);
}
g.setColor(origColor);
g.setFont(origFont);
}
private Color getMessageColor(final TpeMessage msg) {
switch (msg.getMessageType()) {
case INFO:
return OtColor.LIGHT_GREY;
case ERROR:
return OtColor.LIGHT_ORANGE;
default:
case WARNING:
return OtColor.BANANA;
}
}
private ImageIcon getMessageIcon(final TpeMessage msg) {
switch (msg.getMessageType()) {
case INFO:
return INFO_ICON;
case ERROR:
return ERROR_ICON;
default:
case WARNING:
return WARNING_ICON;
}
}
synchronized void addMouseObserver(final TpeMouseObserver obs) {
if (!_mouseObs.contains(obs)) {
_mouseObs.addElement(obs);
}
}
/**
* Tell all the mouse observers about the new mouse event.
*/
private void _notifyMouseObs(final MouseEvent e) {
try {
final TpeMouseEvent tme = _initMouseEvent(e);
for (final TpeMouseObserver mo : _mouseObs) {
mo.tpeMouseEvent(this, tme);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Tell all the view observers that the view has changed.
*/
private void _notifyViewObs() {
for (final TpeViewObserver vo : _viewObs) {
vo.tpeViewChange(this);
}
}
synchronized void addViewObserver(final TpeViewObserver obs) {
if (!_viewObs.contains(obs)) {
_viewObs.addElement(obs);
}
}
synchronized void deleteViewObserver(final TpeViewObserver obs) {
_viewObs.removeElement(obs);
}
@Override
public void loadSkyImage() {
try {
TelescopePosEditor tpe = TpeManager.get();
if (tpe != null) {
tpe.getSkyImage(_ctx);
}
} catch (Exception e) {
DialogUtil.error(e);
}
}
// -- These implement the MouseInputListener interface --
@Override public void mousePressed(final MouseEvent e) {
_notifyMouseObs(e);
}
@Override public void mouseDragged(final MouseEvent e) {
_notifyMouseObs(e);
}
@Override public void mouseReleased(final MouseEvent e) {
_notifyMouseObs(e);
}
@Override public void mouseMoved(final MouseEvent e) {
_notifyMouseObs(e);
}
@Override public void mouseClicked(final MouseEvent e) {
_notifyMouseObs(e);
}
@Override public void mouseEntered(final MouseEvent e) {
_notifyMouseObs(e);
}
@Override public void mouseExited(final MouseEvent e) {
_notifyMouseObs(e);
}
/**
* Is the TpeImageWidget initialized?
*/
boolean isImgInfoValid() {
return _imgInfoValid;
}
public synchronized void addInfoObserver(final TpeImageInfoObserver obs) {
if (!_infoObs.contains(obs)) {
_infoObs.addElement(obs);
}
}
public synchronized void deleteInfoObserver(final TpeImageInfoObserver obs) {
_infoObs.removeElement(obs);
}
private void _notifyInfoObs() {
final List<TpeImageInfoObserver> l;
synchronized (_infoObs) {
l = new ArrayList<>(_infoObs);
}
for (final TpeImageInfoObserver o : l) {
o.imageInfoUpdate(this, _imgInfo);
}
}
/**
* Return true if there is valid image info, and try to update it if needed
*/
private boolean _isImageValid() {
if (!_imgInfoValid) {
setBasePos(_imgInfo.getBasePos());
}
return _imgInfoValid;
}
/**
* called when the image has changed to update the display
*/
@Override
public synchronized void updateImage() {
_imgInfoValid = false;
super.updateImage();
try {
// might throw an exception if changing images and WCS is not yet initialized
_notifyViewObs();
} catch (Exception e) {
// ignore: This happens when a new image was just loaded and WCS was not initialized yet
// Retry again later in newImage(), below.
}
}
/**
* Convert the given user coordinates location to world coordinates.
*/
private WorldCoords userToWorldCoords(final double x, final double y) {
final Point2D.Double p = new Point2D.Double(x, y);
getCoordinateConverter().userToWorldCoords(p, false);
return new WorldCoords(p.x, p.y, getCoordinateConverter().getEquinox());
}
/**
* Convert the given world coordinate position to a user coordinates position.
*/
private Point2D.Double worldToUserCoords(final WorldCoords pos) {
final double[] raDec = pos.getRaDec(getCoordinateConverter().getEquinox());
final Point2D.Double p = new Point2D.Double(raDec[0], raDec[1]);
getCoordinateConverter().worldToUserCoords(p, false);
return p;
}
/**
* Convert the given world coordinate position to screen coordinates.
*/
private Point2D.Double worldToScreenCoords(final WorldCoords pos) {
final double[] raDec = pos.getRaDec(getCoordinateConverter().getEquinox());
final Point2D.Double p = new Point2D.Double(raDec[0], raDec[1]);
getCoordinateConverter().worldToScreenCoords(p, false);
return p;
}
/**
* Convert an offset from the base position (in arcsec) to a screen coordinates location.
*/
public Point2D.Double offsetToScreenCoords(final double xOff, final double yOff) {
if (!_isImageValid()) {
return null;
}
final double ppa = _imgInfo.getPixelsPerArcsec();
final Point2D.Double baseScreenPos = _imgInfo.getBaseScreenPos();
final double xPix = baseScreenPos.x - (xOff * ppa * _imgInfo.flipRA());
final double yPix = baseScreenPos.y - (yOff * ppa);
return skyRotate(xPix, yPix);
}
/**
* Convert the given screen coordinates to an offset from the base position (in arcsec).
*/
private double[] screenCoordsToOffset(final double x, final double y) {
if (!_isImageValid()) {
return null;
}
// un-rotate
final double angle = -_imgInfo.getCorrectedPosAngleRadians();
final Point2D.Double baseScreenPos = _imgInfo.getBaseScreenPos();
final double xBase = baseScreenPos.x;
final double yBase = baseScreenPos.y;
final Point2D.Double pd = ScreenMath.rotateRadians(x, y, angle, xBase, yBase);
final double ppa = _imgInfo.getPixelsPerArcsec();
double xOff = (baseScreenPos.x - pd.x) / (ppa * _imgInfo.flipRA());
double yOff = (baseScreenPos.y - pd.y) / ppa;
xOff = Math.round(xOff * 1000.0) / 1000.0;
yOff = Math.round(yOff * 1000.0) / 1000.0;
return new double[]{xOff, yOff};
}
/**
* Convert a TaggedPos to a screen coordinates.
*/
Point2D.Double taggedPosToScreenCoords(final WatchablePos tp) {
if (tp instanceof OffsetPosBase) {
final double x = ((OffsetPosBase) tp).getXaxis();
final double y = ((OffsetPosBase) tp).getYaxis();
return offsetToScreenCoords(x, y);
}
// Get the equinox assumed by the coordinate conversion methods (depends on current image)
final SPTarget target = (SPTarget) tp;
final Option<Long> when = _ctx.schedulingBlockStartJava();
final double x = target.getRaDegrees(when).getOrElse(0.0);
final double y = target.getDecDegrees(when).getOrElse(0.0);
final WorldCoords pos = new WorldCoords(x, y, 2000.);
return worldToScreenCoords(pos);
}
/**
* Rotate a point through the current position angle, relative to
* the base position, correcting for sky rotation.
*/
private Point2D.Double skyRotate(final double x, final double y) {
if (!_isImageValid()) {
return null;
}
final double angle = _imgInfo.getCorrectedPosAngleRadians();
final Point2D.Double baseScreenPos = _imgInfo.getBaseScreenPos();
final double xBase = baseScreenPos.x;
final double yBase = baseScreenPos.y;
return ScreenMath.rotateRadians(x, y, angle, xBase, yBase);
}
/**
* Rotate a polygon through the current position angle, relative to
* the base position, correcting for sky rotation.
*/
public void skyRotate(final PolygonD p) {
if (!_isImageValid()) {
return;
}
final double angle = _imgInfo.getCorrectedPosAngleRadians();
final Point2D.Double baseScreenPos = _imgInfo.getBaseScreenPos();
final double xBase = baseScreenPos.x;
final double yBase = baseScreenPos.y;
ScreenMath.rotateRadians(p, angle, xBase, yBase);
}
private TpeMouseEvent _initMouseEvent(final MouseEvent evt) {
if (_isImageValid()) {
final Point2D.Double mp = new Point2D.Double(evt.getX(), evt.getY());
// snap to catalog symbol position, if user clicked on one
final Point2D.Double p = new Point2D.Double(mp.x, mp.y);
getCoordinateConverter().screenToUserCoords(p, false);
final double[] d = screenCoordsToOffset(mp.x, mp.y);
final Option<TpeImageWidget> source = new Some<>(this);
if (evt.getID() == MouseEvent.MOUSE_CLICKED) {
final Option<SiderealTarget> skyObject = getCatalogPosition(mp);
final Option<String> name = skyObject.map(SiderealTarget::name);
if (!skyObject.isDefined()) {
Coordinates pos = CoordinatesUtilities.userToWorldCoords(getCoordinateConverter(), p.x, p.y);
return new TpeMouseEvent(evt, evt.getID(), source, pos, name, (int) Math.round(mp.x), (int) Math.round(mp.y), skyObject, d[0], d[1]);
} else {
Coordinates pos = skyObject.map(SiderealTarget::coordinates).getOrElse(Coordinates.zero());
return new TpeMouseEvent(evt, evt.getID(), source, pos, name, (int) Math.round(mp.x), (int) Math.round(mp.y), skyObject, d[0], d[1]);
}
} else {
Coordinates pos = CoordinatesUtilities.userToWorldCoords(getCoordinateConverter(), p.x, p.y);
return new TpeMouseEvent(evt, evt.getID(), source, pos, None.instance(), (int) Math.round(mp.x), (int) Math.round(mp.y), None.instance(), d[0], d[1]);
}
} else {
return new TpeMouseEvent(evt);
}
}
/**
* This method is called before and after a new image is loaded, each time
* with a different argument.
*
* @param before set to true before the image is loaded and false afterwards
*/
@Override
public void newImage(final boolean before) {
super.newImage(before);
if (!before) {
try {
_notifyViewObs();
} catch (Exception e) {
//die silently
}
}
}
public TpeContext getContext() {
return _ctx;
}
/**
* If the given screen coordinates point is within a displayed catalog symbol, set it to
* point to the center of the symbol and return the world coordinates position
* from the catalog table row. Otherwise, return null and do nothing.
*/
private Option<SiderealTarget> getCatalogPosition(final Point2D.Double p) {
return plotter().getCatalogObjectAt(p);
}
/**
* Clear the image display.
*/
@Override
public void clear() {
LOG.finest("TpeImageWidget.clear()");
if (_ctx.isEmpty()) {
blankImage(0.0, 0.0);
} else {
WorldCoords basePos = _imgInfo.getBasePos();
blankImage(basePos.getRaDeg(), basePos.getDecDeg());
}
}
/**
* Return true if the image has been cleared.
* (Overrides parent class version to stop the table plotting code from
* generating new blank images when plotting tables, since the blank
* images are generated by OT code).
*/
@Override
public boolean isClear() {
return false;
}
/**
* Display the FITS table at the given HDU index.
*/
@Override
public void displayFITSTable(final int hdu) {
super.displayFITSTable(hdu);
}
/**
* Reset internal state to view a new observation and position table.
*/
public void reset(final TpeContext ctx) {
LOG.finest("TpeImageWidget.reset()");
if (_ctx.instrument().isDefined()) {
_ctx.instrument().get().removePropertyChangeListener(this);
}
if (_ctx.targets().base().isDefined()) {
_ctx.targets().base().get().deleteWatcher(this);
}
_ctx = ctx;
if (_ctx.targets().base().isEmpty()) {
// There is no target to view, but we need to update the image
// widgets with new WCS info.
clear();
}
// add new listeners
if (_ctx.instrument().isDefined()) {
// This is bad but it is the only way to link changes from the instrument
// to the dialog box, talk about side-effects
if (_gemsGuideStarSearchDialog != null) {
_gemsGuideStarSearchDialog.updatedInstrument(ctx.instrument());
}
_ctx.instrument().get().addPropertyChangeListener(this);
setPosAngle(_ctx.instrument().get().getPosAngleDegrees());
}
if (_ctx.targets().base().isDefined()) {
final SPTarget base = _ctx.targets().base().get();
base.addWatcher(this);
basePosUpdate(base);
}
repaint();
}
/**
* Add the given image feature to the list.
*/
void addFeature(final TpeImageFeature tif) {
if (featureAdded(tif)) {
return;
}
_featureList.addElement(tif);
if (_imgInfoValid) {
tif.reinit(this, _imgInfo);
}
repaint();
}
/**
* Return true if the given image feature has been added already.
*/
private boolean featureAdded(final TpeImageFeature tif) {
return _featureList.contains(tif);
}
/**
* Delete the given image feature from the list.
*/
void deleteFeature(final TpeImageFeature tif) {
if (!featureAdded(tif)) {
return;
}
_featureList.removeElement(tif);
tif.unloaded();
repaint();
}
/**
* Called when a mouse drag operation starts.
*/
public void dragStart(final TpeMouseEvent evt) {
if ((!_imgInfoValid)) return;
Object dragObject = null;
for (final TpeImageFeature tif : _featureList) {
if (tif instanceof TpeDraggableFeature) {
final TpeDraggableFeature tdf = (TpeDraggableFeature) tif;
final Option<Object> dragOpt = tdf.dragStart(evt, _imgInfo);
if (dragOpt.isDefined()) {
dragObject = dragOpt.getValue();
_dragFeature = tdf;
drag(evt);
break;
}
}
}
if (dragObject == null) return;
// Let anybody who wants to know about this drag know
final Option<ObsContext> ctxOpt = getObsContext();
if (ctxOpt.isDefined()) {
final ObsContext ctx = ctxOpt.getValue();
for (final TpeImageFeature tif : _featureList) {
if (tif instanceof TpeDragSensitive) {
((TpeDragSensitive) tif).handleDragStarted(dragObject, ctx);
}
}
}
}
/**
* Called while dragging the mouse over the image.
*/
public void drag(final TpeMouseEvent evt) {
if (_dragFeature == null) {
return;
}
_dragFeature.drag(evt);
}
/**
* Called at the end of a mouse drag operation.
*/
public void dragStop(final TpeMouseEvent evt) {
if (_dragFeature == null) {
return; // Weren't dragging anything
}
_dragFeature.dragStop(evt);
_dragFeature = null;
// Let anybody who wants to know about this drag know
final Option<ObsContext> ctxOpt = getObsContext();
if (!ctxOpt.isEmpty()) {
final ObsContext ctx = ctxOpt.getValue();
_featureList.stream().filter(tif -> tif instanceof TpeDragSensitive).forEach(tif ->
((TpeDragSensitive) tif).handleDragStopped(ctx)
);
}
}
public void action(final TpeMouseEvent tme) {
if (!_imgInfoValid) return;
_featureList.stream().filter(tif -> tif instanceof TpeActionableFeature).forEach(tif ->
((TpeActionableFeature) tif).action(tme)
);
}
/**
* Create an image feature item, based on the given arguments, and return true if successful.
*/
public void create(final TpeMouseEvent tme, final TpeCreatableItem item) {
if (!_imgInfoValid) return;
item.create(tme, _imgInfo);
}
/**
* Erase the image feature at the mouse position.
*/
public boolean erase(final TpeMouseEvent tme) {
if (!_imgInfoValid) return false;
for (final TpeImageFeature tif : _featureList) {
if (tif instanceof TpeEraseableFeature) {
final TpeEraseableFeature tef = (TpeEraseableFeature) tif;
if (tef.erase(tme)) {
return true;
}
}
}
return false;
}
/**
* Implements the PropertyChangeListener interface
*/
@Override
public void propertyChange(final PropertyChangeEvent evt) {
_checkPosAngle();
repaint();
}
@Override
public void telescopePosUpdate(final WatchablePos tp) {
basePosUpdate((SPTarget) tp);
}
/**
* The Base position has been updated.
*/
private void basePosUpdate(final SPTarget target) {
final Option<Long> when = _ctx.schedulingBlockStartJava();
final double x = target.getRaDegrees(when).getOrElse(0.0);
final double y = target.getDecDegrees(when).getOrElse(0.0);
WorldCoords pos = new WorldCoords(x, y, 2000.);
setBasePos(pos);
repaint();
}
/**
* Gets the context of the current observation.
*/
public Option<ObsContext> getObsContext() {
return _ctx.obsContextJava();
}
/**
* Gets the context of the current observation (ignoring site conditions
* if not present)
*/
public Option<ObsContext> getMinimalObsContext() {
final Option<ObsContext> fullContext = getObsContext();
// check if "full" context is available
if (fullContext.isEmpty()) {
// UX-1012: no -> try to return a context that contains the information needed for drawing only
return getMinimalDrawingObsContext();
} else {
// yes -> return the full context (this should be the normal case)
return fullContext;
}
}
/**
* Gets a minimal context for drawing that does not bother with information that is not needed for drawing
* like the conditions for example. This method will provide a context useful for drawing when there is no
* condition node. This solves issue UX-1012.
*/
private Option<ObsContext> getMinimalDrawingObsContext() {
return _ctx.obsContextJavaWithConditions(SPSiteQuality.Conditions.WORST);
}
public boolean isViewingOffsets() {
return _viewingOffsets;
}
public void setViewingOffsets(boolean viewingOffsets) {
_viewingOffsets = viewingOffsets;
}
// Check if the instrument's position angle has changed and update the _imgInfo object
private void _checkPosAngle() {
if (_ctx.instrument().isDefined()) {
final double d = _ctx.instrument().get().getPosAngleDegrees();
if (d != _imgInfo.getPosAngleDegrees()) {
_imgInfo.setPosAngleDegrees(d);
_notifyInfoObs();
for (final TpeImageFeature tif : _featureList) {
tif.posAngleUpdate(_imgInfo);
}
}
}
}
/**
* Set the position angle in degrees.
*/
public boolean setPosAngle(final double posAngle) {
final SPInstObsComp inst = _ctx.instrument().orNull();
final Double d = _ctx.instrument().posAngleOrZero();
if ((d != posAngle) && (inst != null)) {
inst.setPosAngle(posAngle);
if (inst instanceof PosAngleConstraintAware) {
final PosAngleConstraintAware pacInst = (PosAngleConstraintAware) inst;
if (pacInst.getPosAngleConstraint() == PosAngleConstraint.PARALLACTIC_ANGLE)
pacInst.setPosAngleConstraint(PosAngleConstraint.PARALLACTIC_OVERRIDE);
}
}
if (!getCoordinateConverter().isWCS()) {
_imgInfoValid = false;
return false;
}
_imgInfo.setPosAngleDegrees(posAngle);
_notifyInfoObs();
for (final TpeImageFeature tif : _featureList) {
tif.posAngleUpdate(_imgInfo);
}
return true;
}
/**
* Return the instrument node corresponding to the currently selected node
*/
public SPInstObsComp getInstObsComp() {
if (_ctx.instrument().isDefined()) return _ctx.instrument().get();
else return null;
}
/**
* Set the base position to the given coordinates (overrides parent class version).
*/
private boolean setBasePos(final WorldCoords pos) {
_basePos = pos;
final CoordinateConverter cc = getCoordinateConverter();
if (!cc.isWCS()) {
_imgInfoValid = false;
return false;
}
try {
_imgInfo.setBaseScreenPos(worldToScreenCoords(pos));
_imgInfo.setBasePos(pos);
} catch (Exception e) {
return false;
}
// Get two points, one at the base and one an arcmin north of the base
final Point2D.Double temp1 = worldToUserCoords(pos);
final Point2D.Double temp2 = worldToUserCoords(
new WorldCoords(pos.getRaDeg(), pos.getDecDeg() + 0.01666667));
// Get the difference in x,y and the distance between the two points
final double xdPrime = temp2.x - temp1.x;
final double ydPrime = temp2.y - temp1.y;
// Measure theta from the y axis: ie. a cartesian coordinate system
// rotated by 90 degrees.
double theta = Angle.atanRadians(xdPrime / ydPrime);
if (ydPrime > 0) {
theta = Angle.normalizeRadians(theta + Math.PI);
}
if (Angle.almostZeroRadians(theta)) {
theta = 0.;
}
_imgInfo.setTheta(theta);
// Convert the two points to pixel coordinates on the screen
cc.userToScreenCoords(temp1, false);
cc.userToScreenCoords(temp2, false);
// Get the difference in x,y pixels between the two points
final double xiPrime = temp2.x - temp1.x;
final double yiPrime = temp2.y - temp1.y;
final double r = Math.sqrt(xiPrime * xiPrime + yiPrime * yiPrime);
// Divide the 1 min distance by 60 arcsec to get pixels/perArcsec
_imgInfo.setPixelsPerArcsec(r / 60.0);
// Find out where WCS East is, so that we know which way the position angle increases
final double angle = Math.PI / 2.;
final Point2D.Double baseScreenPos = _imgInfo.getBaseScreenPos();
final double xBase = baseScreenPos.x;
final double yBase = baseScreenPos.y;
final Point2D.Double east = ScreenMath.rotateRadians(temp2.x, temp2.y, angle, xBase,
yBase);
try {
cc.screenToWorldCoords(east, false);
} catch (Exception e) {
_imgInfoValid = false;
return false;
}
// Handle 360 / 0 wrap
double eastX = east.x;
double posRa = pos.getRaDeg();
if (Math.abs(Math.round(eastX) - Math.round(posRa)) == 360) {
if (Math.round(east.x) == 0) {
eastX += 360.0;
} else {
posRa += 360.0;
}
}
_imgInfo.setFlipRA(eastX < posRa);
_imgInfoValid = true;
_notifyInfoObs();
for (final TpeImageFeature tif : _featureList) {
tif.reinit(this, _imgInfo);
}
_baseOutOfView = _imgInfoValid && !isVisible(_imgInfo.getBaseScreenPos());
return true;
}
/**
* @return <code>true</code> if the point is visible in the image widget;
* <code>false</code> otherwise
*/
public boolean isVisible(Point2D.Double p) {
return (p.x >= 0) && (p.y >= 0) && (p.x < getWidth()) && (p.y < getHeight());
}
/**
* Return the base or center position in world coordinates.
* If there is no base position, this method returns the center point
* of the image. If the image does not support WCS, this method returns (0,0).
* The position returned here should be used as the base position
* for any catalog or image server requests.
*/
public WorldCoords getBasePos() {
if (_imgInfoValid && !_ctx.isEmpty()) {
return _basePos;
}
return super.getBasePos();
}
// manual guide star selection dialog
public void manualGuideStarSearch() {
if (GuideStarSupport.hasGemsComponent(_ctx)) {
showGemsGuideStarSearchDialog();
} else {
openCatalogNavigator();
}
}
private void openCatalogNavigator() {
QueryResultsFrame.instance().showOn(this, _ctx);
}
private void showGemsGuideStarSearchDialog() {
if (_gemsGuideStarSearchDialog == null) {
_gemsGuideStarSearchDialog = new GemsGuideStarSearchDialog(this, scala.concurrent.ExecutionContext$.MODULE$.global());
} else {
_gemsGuideStarSearchDialog.reset();
_gemsGuideStarSearchDialog.setVisible(true);
}
try {
_gemsGuideStarSearchDialog.query();
} catch (Exception e) {
DialogUtil.error(e);
}
}
/**
* Return the action that displays the guide star dialog
*/
AbstractAction getManualGuideStarAction() {
return _manualGuideStarAction;
}
@Override
public void pickedObject() {
super.pickedObject();
PickObject pickObject = getPickObjectPanel();
PickObjectStatistics stats = pickObject.getStatistics();
if (stats != null) {
WorldCoords coords = stats.getCenterPos();
TargetObsComp obsComp = getContext().targets().orNull();
if (obsComp != null && !pickObject.isUpdate()) {
SPTarget newTarget = new SPTarget(coords.getRaDeg(), coords.getDecDeg());
if (stats.getRow().size() > 0 && stats.getRow().elementAt(0) != null) {
newTarget.setName(stats.getRow().elementAt(0).toString());
}
TargetEnvironment te = obsComp.getTargetEnvironment().setUserTargets(obsComp.getTargetEnvironment().getUserTargets().append(newTarget));
obsComp.setTargetEnvironment(te);
getContext().targets().commit();
}
} else {
DialogUtil.error("No object was selected");
}
}
}
| bsd-3-clause |
NCIP/catissue-core | software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/action/AnticipatorySpecimenViewAction.java | 26075 | /*L
* Copyright Washington University in St. Louis
* Copyright SemanticBits
* Copyright Persistent Systems
* Copyright Krishagni
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/catissue-core/LICENSE.txt for details.
*/
package edu.wustl.catissuecore.action;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.actionForm.SpecimenCollectionGroupForm;
import edu.wustl.catissuecore.actionForm.ViewSpecimenSummaryForm;
import edu.wustl.catissuecore.bean.CollectionProtocolEventBean;
import edu.wustl.catissuecore.bean.GenericSpecimen;
import edu.wustl.catissuecore.bean.GenericSpecimenVO;
import edu.wustl.catissuecore.bizlogic.NewSpecimenBizLogic;
import edu.wustl.catissuecore.bizlogic.SpecimenCollectionGroupBizLogic;
import edu.wustl.catissuecore.domain.AbstractSpecimen;
import edu.wustl.catissuecore.domain.MolecularSpecimen;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenCharacteristics;
import edu.wustl.catissuecore.domain.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domain.SpecimenRequirement;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.util.CollectionProtocolUtil;
import edu.wustl.catissuecore.util.IdComparator;
import edu.wustl.catissuecore.util.SpecimenAutoStorageContainer;
import edu.wustl.catissuecore.util.SpecimenUtil;
import edu.wustl.catissuecore.util.global.AppUtility;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.Variables;
import edu.wustl.common.action.BaseAction;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.util.global.Status;
import edu.wustl.common.util.global.Validator;
import edu.wustl.common.util.logger.Logger;
import edu.wustl.dao.DAO;
import edu.wustl.dao.exception.DAOException;
// TODO: Auto-generated Javadoc
/**
* The Class AnticipatorySpecimenViewAction.
*
* @author abhijit_naik
*/
public class AnticipatorySpecimenViewAction extends BaseAction
{
/**
* .
*/
private static final String SPECIMEN_KEY_PREFIX = "S_";
/**
* cpId.
*/
Long cpId = null;
/**
* logger.
*/
private static final Logger LOGGER = Logger
.getCommonLogger(AnticipatorySpecimenViewAction.class);
/**
* asignedPositonSet.
*/
private Set asignedPositonSet = null;
/**
* Overrides the executeSecureAction method of SecureAction class.
* @param mapping
* object of ActionMapping
* @param form : object of ActionForm
* @param request
* object of HttpServletRequest
* @param response
* object of HttpServletResponse
* @throws Exception
* generic exception
* @return ActionForward : ActionForward
*/
@Override
public ActionForward executeAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
final SessionDataBean sessionDataBean = this.getSessionData(request);
DAO dao = null;
String target = Constants.SUCCESS;
try
{
dao = AppUtility.openDAOSession(sessionDataBean);
this.asignedPositonSet = new HashSet();
boolean isFromSpecimenEditPage = false;
final SpecimenCollectionGroupForm specimenCollectionGroupForm = (SpecimenCollectionGroupForm) form;
final HttpSession session = request.getSession();
Long identifier = specimenCollectionGroupForm.getId();
Long specimenId = null;
final SpecimenAutoStorageContainer autoStorageContainer = new SpecimenAutoStorageContainer();
final HashMap forwardToHashMap = (HashMap) request.getAttribute("forwardToHashMap");
if (forwardToHashMap != null)
{
identifier = (Long) forwardToHashMap.get("specimenCollectionGroupId");
if (identifier != null)
{
specimenCollectionGroupForm.setId(identifier);
}
specimenId = (Long) forwardToHashMap.get("specimenId");
if (specimenId != null)
{
session.setAttribute(Constants.SPECIMENFORM, specimenId);
isFromSpecimenEditPage = true;
}
}
final SpecimenCollectionGroupBizLogic scgBizLogic = new SpecimenCollectionGroupBizLogic();
session.setAttribute(Constants.SCGFORM, specimenCollectionGroupForm.getId());
final SpecimenCollectionGroup specimencollectionGroup = scgBizLogic.getSCGFromId(identifier,
sessionDataBean, dao);
if (specimencollectionGroup.getActivityStatus().equalsIgnoreCase(
Status.ACTIVITY_STATUS_DISABLED.toString()))
{
target = Status.ACTIVITY_STATUS_DISABLED.toString();
}
this.cpId = specimencollectionGroup.getCollectionProtocolRegistration()
.getCollectionProtocol().getId();
if (isFromSpecimenEditPage)
{
final Collection<Specimen> scgSpecimenList = specimencollectionGroup.getSpecimenCollection();
this.getSpcimensToShowOnSummary(specimenId, scgSpecimenList, session,
autoStorageContainer, dao);
}
else
{
this.addSCGSpecimensToSession(session, specimencollectionGroup,
autoStorageContainer, dao);
}
request.setAttribute("RequestType",
ViewSpecimenSummaryForm.REQUEST_TYPE_ANTICIPAT_SPECIMENS);
autoStorageContainer.setCollectionProtocol(this.cpId);
autoStorageContainer.setSpecimenStoragePositions(sessionDataBean);
if (request.getParameter("target") != null)
{
target = request.getParameter("target");
}
autoStorageContainer.fillAllocatedPositionSet(this.asignedPositonSet);
session.setAttribute("asignedPositonSet", this.asignedPositonSet);
}
finally
{
AppUtility.closeDAOSession(dao);
}
return mapping.findForward(target);
}
/**
* Add scg specimens to session.
* @param session : session
* @param specimencollectionGroup : specimencollectionGroup
* @throws DAOException : DAOException
* @throws BizLogicException : BizLogicException
*/
private void addSCGSpecimensToSession(HttpSession session,
SpecimenCollectionGroup specimencollectionGroup,
SpecimenAutoStorageContainer autoStorageContainer, DAO dao) throws DAOException,
BizLogicException
{
final LinkedHashMap<String, CollectionProtocolEventBean> cpEventMap = new LinkedHashMap<String, CollectionProtocolEventBean>();
final CollectionProtocolEventBean eventBean = new CollectionProtocolEventBean();
eventBean.setUniqueIdentifier(String.valueOf(specimencollectionGroup.getId().longValue()));
// sorting of specimen collection accoding to id
final LinkedList<Specimen> specimenList = new LinkedList<Specimen>();
Collection<Specimen> specimenCollection=specimencollectionGroup.getSpecimenCollection();
if(specimenCollection!=null)
{
final Iterator<Specimen> itr = specimenCollection.iterator();
while (itr.hasNext())
{
final Specimen specimen = itr.next();
if (!Status.ACTIVITY_STATUS_DISABLED.toString().equals(specimen.getActivityStatus()))
{
specimenList.add(specimen);
}
}
}
final Comparator spIdComp = new IdComparator();
Collections.sort(specimenList, spIdComp);
final Iterator itr2 = specimenList.iterator();
final NewSpecimenBizLogic specBizLogic = new NewSpecimenBizLogic();
while (itr2.hasNext())
{
final Specimen specimen = (Specimen) itr2.next();
if (specimen.getChildSpecimenCollection() != null)
{
final long lastAliquotNo = specBizLogic.getTotalNoOfAliquotSpecimen(specimen
.getId(), dao);
final LinkedList<Specimen> childList = new LinkedList(specimen
.getChildSpecimenCollection());
Collections.sort(childList, spIdComp);
this.setLabelInSpecimen(specimen.getId(), childList, lastAliquotNo);
}
}
eventBean.setSpecimenRequirementbeanMap(this.getSpecimensMap(specimenList, this.cpId,
autoStorageContainer));
// eventBean.setSpecimenRequirementbeanMap(getSpecimensMap(
// specimencollectionGroup.getSpecimenCollection(),cpId ));
final String globalSpecimenId = "E" + eventBean.getUniqueIdentifier() + "_";
cpEventMap.put(globalSpecimenId, eventBean);
session.removeAttribute(Constants.COLLECTION_PROTOCOL_EVENT_SESSION_MAP);
session.setAttribute(Constants.COLLECTION_PROTOCOL_EVENT_SESSION_MAP, cpEventMap);
}
/**
*
* @param specimenCollection : specimenCollection
* @param collectionProtocolId : collectionProtocolId
* @return LinkedHashMap : LinkedHashMap
* @throws DAOException : DAOException
*/
protected LinkedHashMap<String, GenericSpecimen> getSpecimensMap(
Collection<Specimen> specimenCollection, long collectionProtocolId,
SpecimenAutoStorageContainer autoStorageContainer) throws DAOException
{
LinkedHashMap<String, GenericSpecimen> specimenMap = new LinkedHashMap<String, GenericSpecimen>();
final Iterator<Specimen> specimenIterator = specimenCollection.iterator();
while (specimenIterator.hasNext())
{
final Specimen specimen = specimenIterator.next();
if (specimen.getParentSpecimen() == null)
{
final GenericSpecimenVO specBean = this.getSpecimenBean(specimen, null);
this.addToSpToAutoCont(specBean, autoStorageContainer);
this.setChildren(specimen, specBean, autoStorageContainer);
specBean.setUniqueIdentifier(SPECIMEN_KEY_PREFIX + specimen.getId());
specBean.setCollectionProtocolId(collectionProtocolId);
specimenMap = this.getOrderedMap(specimenMap, specimen.getId(), specBean,
SPECIMEN_KEY_PREFIX);
}
}
return specimenMap;
}
/**
*
* @param specimenCollection : specimenCollection
* @param specimenId : specimenId
* @param collectionProtocolId : collectionProtocolId
* @return LinkedHashMap < String , GenericSpecimen > : LinkedHashMap
* @throws DAOException : DAOException
*/
protected LinkedHashMap<String, GenericSpecimen> getSpecimensMap(Collection specimenCollection,
long specimenId, long collectionProtocolId,
SpecimenAutoStorageContainer autoStorageContainer) throws DAOException
{
final LinkedHashMap<String, GenericSpecimen> specimenMap = new LinkedHashMap<String, GenericSpecimen>();
final Iterator specimenIterator = specimenCollection.iterator();
while (specimenIterator.hasNext())
{
final Specimen specimen = (Specimen) specimenIterator.next();
if (specimen.getId() != null && specimen.getId() == specimenId)
{
final GenericSpecimenVO specBean = this.getSpecimenBean(specimen, null);
this.addToSpToAutoCont(specBean, autoStorageContainer);
this.setChildren(specimen, specBean, autoStorageContainer);
specBean.setUniqueIdentifier("S_" + specimen.getId());
specBean.setCollectionProtocolId(collectionProtocolId);
specimenMap.put("S_" + specimen.getId(), specBean);
}
}
return specimenMap;
}
/**
*
* @param specimenMap : specimenMap
* @param identifier : id
* @param specBean : specBean
* @param prefix : prefix
* @return LinkedHashMap < String , GenericSpecimen > : LinkedHashMap
*/
private LinkedHashMap<String, GenericSpecimen> getOrderedMap(
LinkedHashMap<String, GenericSpecimen> specimenMap, Long identifier,
GenericSpecimenVO specBean, String prefix)
{
final LinkedHashMap<String, GenericSpecimen> orderedMap = new LinkedHashMap<String, GenericSpecimen>();
final Object[] keyArray = specimenMap.keySet().toArray();
for (final Object element : keyArray)
{
final String keyVal = (String) element;
final String keyId = keyVal.substring(prefix.length());
if (Long.parseLong(keyId) > identifier)
{
orderedMap.put(keyVal, specimenMap.get(keyVal));
specimenMap.remove(keyVal);
}
}
specimenMap.put(prefix + identifier, specBean);
if (!orderedMap.isEmpty())
{
specimenMap.putAll(orderedMap);
}
return specimenMap;
}
/**
*
* @param specimen : specimen
* @param parentSpecimenVO : parentSpecimenVO
* @throws DAOException : DAOException
*/
protected void setChildren(Specimen specimen, GenericSpecimen parentSpecimenVO,
SpecimenAutoStorageContainer autoStorageContainer) throws DAOException
{
final Collection<AbstractSpecimen> specimenChildren = specimen.getChildSpecimenCollection();
final List<AbstractSpecimen> specimenChildrenCollection = new LinkedList<AbstractSpecimen>(
specimenChildren);
CollectionProtocolUtil.getSortedCPEventList(specimenChildrenCollection);
if (specimenChildrenCollection == null || specimenChildrenCollection.isEmpty())
{
return;
}
final Iterator<AbstractSpecimen> iterator = specimenChildrenCollection.iterator();
LinkedHashMap<String, GenericSpecimen> aliquotMap = new LinkedHashMap<String, GenericSpecimen>();
LinkedHashMap<String, GenericSpecimen> derivedMap = new LinkedHashMap<String, GenericSpecimen>();
while (iterator.hasNext())
{
final Specimen childSpecimen = (Specimen) iterator.next();
final String lineage = childSpecimen.getLineage();
final GenericSpecimenVO specimenBean = this.getSpecimenBean(childSpecimen, specimen
.getLabel());
// addToSpToAutoCont(specimenBean);
this.setChildren(childSpecimen, specimenBean, autoStorageContainer);
final String prefix = lineage + specimen.getId() + "_";
specimenBean.setUniqueIdentifier(prefix + childSpecimen.getId());
if (Constants.ALIQUOT.equals(childSpecimen.getLineage()))
{
aliquotMap = this.getOrderedMap(aliquotMap, childSpecimen.getId(), specimenBean,
prefix);
}
else
{
derivedMap = this.getOrderedMap(derivedMap, childSpecimen.getId(), specimenBean,
prefix);
}
specimenBean.setCollectionProtocolId(this.cpId);
}
if (aliquotMap != null && !aliquotMap.isEmpty())
{
final Iterator<String> aliquotItr = aliquotMap.keySet().iterator();
while (aliquotItr.hasNext())
{
final String key = aliquotItr.next();
final GenericSpecimenVO spec = (GenericSpecimenVO) aliquotMap.get(key);
this.addToSpToAutoCont(spec, autoStorageContainer);
}
}
if (derivedMap != null && !derivedMap.isEmpty())
{
final Iterator<String> derivedItr = derivedMap.keySet().iterator();
while (derivedItr.hasNext())
{
final String key = derivedItr.next();
final GenericSpecimenVO spec = (GenericSpecimenVO) derivedMap.get(key);
this.addToSpToAutoCont(spec, autoStorageContainer);
}
}
// parentSpecimenVO.setGenerateLabel(specimen.getSpecimenCollectionGroup().getCollectionProtocolRegistration().getCollectionProtocol().getGenerateLabel());
parentSpecimenVO.setAliquotSpecimenCollection(aliquotMap);
parentSpecimenVO.setDeriveSpecimenCollection(derivedMap);
}
/**
*
* @param specimen : specimen
* @param parentName : parentName
* @return GenericSpecimenVO : GenericSpecimenVO
* @throws DAOException : DAOException
*/
protected GenericSpecimenVO getSpecimenBean(Specimen specimen, String parentName)
throws DAOException
{
final GenericSpecimenVO specimenDataBean = new GenericSpecimenVO();
specimenDataBean.setBarCode(specimen.getBarcode());
specimenDataBean.setClassName(specimen.getSpecimenClass());
specimenDataBean.setDisplayName(specimen.getLabel());
specimenDataBean.setPathologicalStatus(specimen.getPathologicalStatus());
specimenDataBean.setId(specimen.getId().longValue());
specimenDataBean.setParentName(parentName);
if (specimen.getInitialQuantity() != null)
{
specimenDataBean.setQuantity(specimen.getInitialQuantity().toString());
}
specimenDataBean.setCheckedSpecimen(false);
specimenDataBean.setPrintSpecimen(specimenDataBean.getPrintSpecimen());// Bug
if (Constants.SPECIMEN_COLLECTED.equals(specimen.getCollectionStatus()))
{
specimenDataBean.setReadOnly(true);
}
specimenDataBean.setType(specimen.getSpecimenType());
final SpecimenCharacteristics characteristics = specimen.getSpecimenCharacteristics();
if (characteristics != null)
{
specimenDataBean.setTissueSide(characteristics.getTissueSide());
specimenDataBean.setTissueSite(characteristics.getTissueSite());
}
String concentration = "";
if ("Molecular".equals(specimen.getSpecimenClass()))
{
concentration = String.valueOf(((MolecularSpecimen) specimen)
.getConcentrationInMicrogramPerMicroliter());
}
specimenDataBean.setConcentration(concentration);
String storageType = null;
if (specimen != null && specimen.getSpecimenPosition() != null)
{
final StorageContainer container = specimen.getSpecimenPosition().getStorageContainer();
LOGGER.info("-----------Container while getting from domain--:" + container);
specimenDataBean.setContainerId(String.valueOf(container.getId()));
specimenDataBean.setSelectedContainerName(container.getName());
specimenDataBean.setPositionDimensionOne(String.valueOf(specimen.getSpecimenPosition()
.getPositionDimensionOne()));
specimenDataBean.setPositionDimensionTwo(String.valueOf(specimen.getSpecimenPosition()
.getPositionDimensionTwo()));
specimenDataBean.setStorageContainerForSpecimen("Auto");
}
// Mandar : 18Aug08 to check for virtual specimens which are collected
// after updating the initial storage types. START
else if (specimen != null && specimen.getSpecimenPosition() == null
&& "Collected".equals(specimen.getCollectionStatus()))
{
specimenDataBean.setStorageContainerForSpecimen("Virtual");
} // //Mandar : 18Aug08 to check for virtual specimens which are
// collected after updating the initial storage types. END
else
{
storageType = this.getStorageType(specimen);
specimenDataBean.setStorageContainerForSpecimen(storageType);
}
if(Variables.isTemplateBasedLblGeneratorAvl)//bug 18681
{
specimenDataBean.setGenerateLabel(isGenLabel(specimen));
}
else
{
specimenDataBean.setGenerateLabel(Variables.isSpecimenLabelGeneratorAvl);// || isGenLabel(specimen));
}
return specimenDataBean;
}
/**
* Checks if is gen label.
*
* @param objSpecimen the obj specimen
*
* @return true, if checks if is gen label
*/
private boolean isGenLabel(final Specimen objSpecimen)
{
boolean isGenLabelON = false;
if(Variables.isTemplateBasedLblGeneratorAvl)
{
String lineage = objSpecimen.getLineage();
String specimenLabelFormat = objSpecimen.getSpecimenCollectionGroup().getCollectionProtocolRegistration().getCollectionProtocol().getSpecimenLabelFormat();
String derLabelFormat = objSpecimen.getSpecimenCollectionGroup().getCollectionProtocolRegistration().getCollectionProtocol().getDerivativeLabelFormat();
String alLabelFomrat = objSpecimen.getSpecimenCollectionGroup().getCollectionProtocolRegistration().getCollectionProtocol().getAliquotLabelFormat();
if(isLabelFormatEmpty(objSpecimen))
{
isGenLabelON = false;
}
else if(isLabelFromatCPDefault(objSpecimen))
{
isGenLabelON = SpecimenUtil.isLblGenOnForCP(specimenLabelFormat, derLabelFormat, alLabelFomrat, lineage);
}
else if(!isLabelFromatCPDefault(objSpecimen))
{
isGenLabelON = true;
}
else if(objSpecimen.getSpecimenRequirement() == null)
{
isGenLabelON = SpecimenUtil.isLblGenOnForCP(specimenLabelFormat, derLabelFormat, alLabelFomrat, lineage);
}
}
return isGenLabelON;
}
/**
* @param objSpecimen
* @return
*/
private boolean isLabelFromatCPDefault(final Specimen objSpecimen)
{
return objSpecimen.getSpecimenRequirement() != null && !Validator.isEmpty(objSpecimen.getSpecimenRequirement().getLabelFormat()) && objSpecimen.getSpecimenRequirement().getLabelFormat().contains("%CP_DEFAULT%");
}
/**
* @param objSpecimen
* @return
*/
private boolean isLabelFormatEmpty(final Specimen objSpecimen)
{
return objSpecimen.getSpecimenRequirement() != null && Validator.isEmpty(objSpecimen.getSpecimenRequirement().getLabelFormat());
}
/**
*
* @param specimenDataBean : specimenDataBean
*/
private void addToSpToAutoCont(GenericSpecimenVO specimenDataBean,
SpecimenAutoStorageContainer autoStorageContainer)
{
if ("Auto".equals(specimenDataBean.getStorageContainerForSpecimen()))
{
autoStorageContainer.addSpecimen(specimenDataBean, specimenDataBean.getClassName());
}
}
/**
*
* @param specimen : specimen
* @return String : String
*/
private String getStorageType(Specimen specimen)
{
String storageType;
final SpecimenRequirement reqSpecimen = specimen.getSpecimenRequirement();
if (reqSpecimen == null)
{
storageType = "Virtual";
}
else
{
storageType = reqSpecimen.getStorageType();
}
return storageType;
}
/**
*
* @param session : session
* @param specimenId : specimenId
* @param specimenList : specimenList
* @throws DAOException : DAOException
* @throws BizLogicException : BizLogicException
*/
private void addSpecimensToSession(HttpSession session, Long specimenId, List specimenList,
SpecimenAutoStorageContainer autoStorageContainer, DAO dao) throws DAOException,
BizLogicException
{
final LinkedHashMap<String, CollectionProtocolEventBean> cpEventMap = new LinkedHashMap<String, CollectionProtocolEventBean>();
final NewSpecimenBizLogic specBizLogic = new NewSpecimenBizLogic();
final CollectionProtocolEventBean eventBean = new CollectionProtocolEventBean();
eventBean.setUniqueIdentifier(String.valueOf(specimenId.longValue()));
// sorting of specimen collection accoding to id
final Comparator spIdComp = new IdComparator();
Collections.sort(specimenList, spIdComp);
// List specList = new LinkedList();
long lastAliquotNo = specBizLogic.getTotalNoOfAliquotSpecimen(specimenId, dao);
this.setLabelInSpecimen(specimenId, specimenList, lastAliquotNo);
final Iterator itr2 = specimenList.iterator();
while (itr2.hasNext())
{
final Specimen specimen = (Specimen) itr2.next();
if (specimen.getChildSpecimenCollection() != null)
{
lastAliquotNo = specBizLogic.getTotalNoOfAliquotSpecimen(specimen.getId(), dao);
final LinkedList<AbstractSpecimen> childList = new LinkedList<AbstractSpecimen>(specimen
.getChildSpecimenCollection());
Collections.sort(childList, spIdComp);
this.setLabelInSpecimen(specimen.getId(), childList, lastAliquotNo);
}
}
eventBean.setSpecimenRequirementbeanMap(this.getSpecimensMap(specimenList, specimenId,
this.cpId, autoStorageContainer));
final String globalSpecimenId = "E" + eventBean.getUniqueIdentifier() + "_";
cpEventMap.put(globalSpecimenId, eventBean);
session.removeAttribute(Constants.COLLECTION_PROTOCOL_EVENT_SESSION_MAP);
session.setAttribute(Constants.COLLECTION_PROTOCOL_EVENT_SESSION_MAP, cpEventMap);
}
/**
*
* @param specimenId : specimenId
* @param scgSpecimenList : scgSpecimenList
* @param session : session
* @throws DAOException : DAOException
* @throws BizLogicException : BizLogicException
*/
private void getSpcimensToShowOnSummary(long specimenId, Collection<Specimen> scgSpecimenList,
HttpSession session, SpecimenAutoStorageContainer autoStorageContainer, DAO dao)
throws DAOException, BizLogicException
{
final List<Specimen> specimenList = new ArrayList<Specimen>();
if (scgSpecimenList != null)
{
final Iterator<Specimen> itr = scgSpecimenList.iterator();
while (itr.hasNext())
{
final Specimen specimen = (Specimen) itr.next();
if (!Status.ACTIVITY_STATUS_DISABLED.toString()
.equals(specimen.getActivityStatus()))
{
if (specimen.getId().equals(specimenId)
|| (specimen.getParentSpecimen() != null && specimen
.getParentSpecimen().getId().equals(specimenId)))
{
specimenList.add(specimen);
}
}
}
}
this.addSpecimensToSession(session, specimenId, specimenList, autoStorageContainer, dao);
}
/**
*
* @param specimenId : specimenId
* @param specimenList : specimenList
* @param lastChildNo : lastChildNo
* @throws DAOException : DAOException
*/
public void setLabelInSpecimen(Long specimenId, Collection specimenList, long lastChildNo)
throws DAOException
{
if (specimenList != null)
{
final Iterator itr = specimenList.iterator();
while (itr.hasNext())
{
final Specimen specimen = (Specimen) itr.next();
lastChildNo = setLabelForSpecimen(specimenId, lastChildNo, specimen);
}
}
}
/**
* Set Label For Specimen.
* @param specimenId Long
* @param lastChildNo Long
* @param specimen Specimen
* @return lastChildNo long
*/
private long setLabelForSpecimen(Long specimenId, long lastChildNo, final Specimen specimen)
{
if (specimen.getId().equals(specimenId)
|| (specimen.getParentSpecimen() != null && specimen.getParentSpecimen()
.getId().equals(specimenId)))
{
if (specimen.getLabel() == null || specimen.getLabel().equals(""))
{
if (specimen.getLineage().equals(Constants.ALIQUOT))
{
if( !isGenLabel(specimen))
{
if (specimen.getParentSpecimen().getLabel() != null)
{
specimen.setLabel(
specimen.getParentSpecimen().getLabel() + "_"
+ (++lastChildNo));
}
}
}
}
}
return lastChildNo;
}
}
| bsd-3-clause |
vanadium/java | lib/src/main/java/io/v/v23/options/RpcOptions.java | 3789 | // Copyright 2016 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package io.v.v23.options;
import org.joda.time.Duration;
import javax.annotation.Nullable;
import io.v.v23.OptionDefs;
import io.v.v23.Options;
import io.v.v23.naming.MountEntry;
import io.v.v23.security.Authorizer;
import io.v.v23.security.VSecurity;
/**
* Strongly-typed alternative to {@link io.v.v23.Options} for RPCs, supporting more options. See
* also
* <a href="https://github.com/vanadium/go.v23/blob/master/options/options.go">v.io/v23/options</a>.
*/
public final class RpcOptions {
private static Authorizer migrateNameResolutionAuthorizer(final Options opts) {
if (opts.has(OptionDefs.SKIP_SERVER_ENDPOINT_AUTHORIZATION) &&
opts.get(OptionDefs.SKIP_SERVER_ENDPOINT_AUTHORIZATION, Boolean.class))
return VSecurity.newAllowEveryoneAuthorizer();
return !opts.has(OptionDefs.NAME_RESOLUTION_AUTHORIZER)
? null
: opts.get(OptionDefs.NAME_RESOLUTION_AUTHORIZER, Authorizer.class);
}
private static Authorizer migrateServerAuthorizer(final Options opts) {
if (opts.has(OptionDefs.SKIP_SERVER_ENDPOINT_AUTHORIZATION) &&
opts.get(OptionDefs.SKIP_SERVER_ENDPOINT_AUTHORIZATION, Boolean.class))
return VSecurity.newAllowEveryoneAuthorizer();
return !opts.has(OptionDefs.SERVER_AUTHORIZER)
? null
: opts.get(OptionDefs.SERVER_AUTHORIZER, Authorizer.class);
}
/**
* @deprecated For migration purposes only; call overloads taking {@code RpcOptions} directly.
*/
@Nullable public static RpcOptions migrateOptions(@Nullable final Options legacy) {
return legacy == null ? null : new RpcOptions()
.nameResolutionAuthorizer(migrateNameResolutionAuthorizer(legacy))
.serverAuthorizer(migrateServerAuthorizer(legacy));
}
private Authorizer nameResolutionAuthorizer, serverAuthorizer;
private MountEntry preresolved;
private boolean noRetry;
private Duration connectionTimeout, channelTimeout;
public RpcOptions nameResolutionAuthorizer(final Authorizer nameResolutionAuthorizer) {
this.nameResolutionAuthorizer = nameResolutionAuthorizer;
return this;
}
public RpcOptions serverAuthorizer(final Authorizer serverAuthorizer) {
this.serverAuthorizer = serverAuthorizer;
return this;
}
public RpcOptions preresolved(final MountEntry preresolved) {
this.preresolved = preresolved;
return this;
}
public RpcOptions noRetry(final boolean noRetry) {
this.noRetry = noRetry;
return this;
}
public RpcOptions connectionTimeout(final Duration connectionTimeout) {
this.connectionTimeout = connectionTimeout;
return this;
}
public RpcOptions channelTimeout(final Duration channelTimeout) {
this.channelTimeout = channelTimeout;
return this;
}
public Authorizer nameResolutionAuthorizer() {
return this.nameResolutionAuthorizer;
}
public Authorizer serverAuthorizer() {
return this.serverAuthorizer;
}
public MountEntry preresolved() {
return this.preresolved;
}
public boolean noRetry() {
return this.noRetry;
}
public Duration connectionTimeout() {
return this.connectionTimeout;
}
public Duration channelTimeout() {
return this.channelTimeout;
}
public RpcOptions skipServerEndpointAuthorization() {
nameResolutionAuthorizer = serverAuthorizer = VSecurity.newAllowEveryoneAuthorizer();
return this;
}
}
| bsd-3-clause |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/category/CategoryOption.java | 4469 | /*
* Copyright (c) 2004-2021, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.category;
import android.database.Cursor;
import androidx.annotation.Nullable;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.gabrielittner.auto.value.cursor.ColumnAdapter;
import com.google.auto.value.AutoValue;
import org.hisp.dhis.android.core.arch.db.adapters.custom.internal.AccessColumnAdapter;
import org.hisp.dhis.android.core.arch.db.adapters.custom.internal.DbDateColumnAdapter;
import org.hisp.dhis.android.core.arch.db.adapters.ignore.internal.IgnoreObjectWithUidListColumnAdapter;
import org.hisp.dhis.android.core.arch.helpers.AccessHelper;
import org.hisp.dhis.android.core.common.Access;
import org.hisp.dhis.android.core.common.BaseNameableObject;
import org.hisp.dhis.android.core.common.CoreObject;
import org.hisp.dhis.android.core.common.ObjectWithUid;
import java.util.Date;
import java.util.List;
@AutoValue
@JsonDeserialize(builder = AutoValue_CategoryOption.Builder.class)
public abstract class CategoryOption extends BaseNameableObject implements CoreObject {
@Nullable
@JsonProperty()
@ColumnAdapter(DbDateColumnAdapter.class)
public abstract Date startDate();
@Nullable
@JsonProperty()
@ColumnAdapter(DbDateColumnAdapter.class)
public abstract Date endDate();
@JsonProperty()
@ColumnAdapter(AccessColumnAdapter.class)
public abstract Access access();
/**
* This method only return results in versions greater or equal to 2.37.
*/
@Nullable
@JsonProperty()
@ColumnAdapter(IgnoreObjectWithUidListColumnAdapter.class)
public abstract List<ObjectWithUid> organisationUnits();
public static CategoryOption create(Cursor cursor) {
return $AutoValue_CategoryOption.createFromCursor(cursor);
}
public abstract Builder toBuilder();
public static Builder builder() {
return new AutoValue_CategoryOption.Builder();
}
@AutoValue.Builder
@JsonPOJOBuilder(withPrefix = "")
public static abstract class Builder extends BaseNameableObject.Builder<Builder> {
public abstract Builder id(Long id);
public abstract Builder startDate(@Nullable Date startDate);
public abstract Builder endDate(@Nullable Date endDate);
public abstract Builder access(Access access);
public abstract Builder organisationUnits(@Nullable List<ObjectWithUid> organisationUnits);
abstract CategoryOption autoBuild();
// Auxiliary fields
abstract Access access();
public CategoryOption build() {
try {
access();
} catch (IllegalStateException e) {
access(AccessHelper.defaultAccess());
}
return autoBuild();
}
}
} | bsd-3-clause |
zzuegg/jmonkeyengine | jme3-core/src/main/java/com/jme3/input/ChaseCamera.java | 37635 | /*
* Copyright (c) 2009-2020 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.input;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.input.controls.*;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import com.jme3.renderer.Camera;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.Control;
import com.jme3.util.clone.Cloner;
import com.jme3.util.clone.JmeCloneable;
import java.io.IOException;
/**
* A camera that follows a spatial and can turn around it by dragging the mouse
* @author nehon
*/
public class ChaseCamera implements ActionListener, AnalogListener, Control, JmeCloneable {
protected Spatial target = null;
protected float minVerticalRotation = 0.00f;
protected float maxVerticalRotation = FastMath.PI / 2;
protected float minDistance = 1.0f;
protected float maxDistance = 40.0f;
protected float distance = 20;
protected float rotationSpeed = 1.0f;
protected float rotation = 0;
protected float trailingRotationInertia = 0.05f;
protected float zoomSensitivity = 2f;
protected float rotationSensitivity = 5f;
protected float chasingSensitivity = 5f;
protected float trailingSensitivity = 0.5f;
protected float vRotation = FastMath.PI / 6;
protected boolean smoothMotion = false;
protected boolean trailingEnabled = true;
protected float rotationLerpFactor = 0;
protected float trailingLerpFactor = 0;
protected boolean rotating = false;
protected boolean vRotating = false;
protected float targetRotation = rotation;
protected InputManager inputManager;
protected Vector3f initialUpVec;
protected float targetVRotation = vRotation;
protected float vRotationLerpFactor = 0;
protected float targetDistance = distance;
protected float distanceLerpFactor = 0;
protected boolean zooming = false;
protected boolean trailing = false;
protected boolean chasing = false;
protected boolean veryCloseRotation = true;
protected boolean canRotate;
protected float offsetDistance = 0.002f;
protected Vector3f prevPos;
protected boolean targetMoves = false;
protected boolean enabled = true;
protected Camera cam = null;
protected final Vector3f targetDir = new Vector3f();
protected float previousTargetRotation;
protected final Vector3f pos = new Vector3f();
protected Vector3f targetLocation = new Vector3f(0, 0, 0);
protected boolean dragToRotate = true;
protected Vector3f lookAtOffset = new Vector3f(0, 0, 0);
protected boolean leftClickRotate = true;
protected boolean rightClickRotate = true;
protected Vector3f temp = new Vector3f(0, 0, 0);
protected boolean invertYaxis = false;
protected boolean invertXaxis = false;
/**
* @deprecated use {@link CameraInput#CHASECAM_DOWN}
*/
@Deprecated
public final static String ChaseCamDown = "ChaseCamDown";
/**
* @deprecated use {@link CameraInput#CHASECAM_UP}
*/
@Deprecated
public final static String ChaseCamUp = "ChaseCamUp";
/**
* @deprecated use {@link CameraInput#CHASECAM_ZOOMIN}
*/
@Deprecated
public final static String ChaseCamZoomIn = "ChaseCamZoomIn";
/**
* @deprecated use {@link CameraInput#CHASECAM_ZOOMOUT}
*/
@Deprecated
public final static String ChaseCamZoomOut = "ChaseCamZoomOut";
/**
* @deprecated use {@link CameraInput#CHASECAM_MOVELEFT}
*/
@Deprecated
public final static String ChaseCamMoveLeft = "ChaseCamMoveLeft";
/**
* @deprecated use {@link CameraInput#CHASECAM_MOVERIGHT}
*/
@Deprecated
public final static String ChaseCamMoveRight = "ChaseCamMoveRight";
/**
* @deprecated use {@link CameraInput#CHASECAM_TOGGLEROTATE}
*/
@Deprecated
public final static String ChaseCamToggleRotate = "ChaseCamToggleRotate";
protected boolean zoomin;
protected boolean hideCursorOnRotate = true;
/**
* Constructs the chase camera
* @param cam the application camera
* @param target the spatial to follow
*/
public ChaseCamera(Camera cam, final Spatial target) {
this(cam);
target.addControl(this);
}
/**
* Constructs the chase camera
* if you use this constructor you have to attach the cam later to a spatial
* doing spatial.addControl(chaseCamera);
* @param cam the application camera
*/
public ChaseCamera(Camera cam) {
this.cam = cam;
initialUpVec = cam.getUp().clone();
}
/**
* Constructs the chase camera, and registers inputs
* if you use this constructor you have to attach the cam later to a spatial
* doing spatial.addControl(chaseCamera);
* @param cam the application camera
* @param inputManager the inputManager of the application to register inputs
*/
public ChaseCamera(Camera cam, InputManager inputManager) {
this(cam);
registerWithInput(inputManager);
}
/**
* Constructs the chase camera, and registers inputs
* @param cam the application camera
* @param target the spatial to follow
* @param inputManager the inputManager of the application to register inputs
*/
public ChaseCamera(Camera cam, final Spatial target, InputManager inputManager) {
this(cam, target);
registerWithInput(inputManager);
}
@Override
public void onAction(String name, boolean keyPressed, float tpf) {
if (dragToRotate) {
if (name.equals(CameraInput.CHASECAM_TOGGLEROTATE) && enabled) {
if (keyPressed) {
canRotate = true;
if (hideCursorOnRotate) {
inputManager.setCursorVisible(false);
}
} else {
canRotate = false;
if (hideCursorOnRotate) {
inputManager.setCursorVisible(true);
}
}
}
}
}
@Override
public void onAnalog(String name, float value, float tpf) {
if (name.equals(CameraInput.CHASECAM_MOVELEFT)) {
rotateCamera(-value);
} else if (name.equals(CameraInput.CHASECAM_MOVERIGHT)) {
rotateCamera(value);
} else if (name.equals(CameraInput.CHASECAM_UP)) {
vRotateCamera(value);
} else if (name.equals(CameraInput.CHASECAM_DOWN)) {
vRotateCamera(-value);
} else if (name.equals(CameraInput.CHASECAM_ZOOMIN)) {
zoomCamera(-value);
if (zoomin == false) {
distanceLerpFactor = 0;
}
zoomin = true;
} else if (name.equals(CameraInput.CHASECAM_ZOOMOUT)) {
zoomCamera(+value);
if (zoomin == true) {
distanceLerpFactor = 0;
}
zoomin = false;
}
}
/**
* Registers inputs with the input manager
* @param inputManager
*/
public final void registerWithInput(InputManager inputManager) {
String[] inputs = {CameraInput.CHASECAM_TOGGLEROTATE,
CameraInput.CHASECAM_DOWN,
CameraInput.CHASECAM_UP,
CameraInput.CHASECAM_MOVELEFT,
CameraInput.CHASECAM_MOVERIGHT,
CameraInput.CHASECAM_ZOOMIN,
CameraInput.CHASECAM_ZOOMOUT};
this.inputManager = inputManager;
if (!invertYaxis) {
inputManager.addMapping(CameraInput.CHASECAM_DOWN, new MouseAxisTrigger(MouseInput.AXIS_Y, true));
inputManager.addMapping(CameraInput.CHASECAM_UP, new MouseAxisTrigger(MouseInput.AXIS_Y, false));
} else {
inputManager.addMapping(CameraInput.CHASECAM_DOWN, new MouseAxisTrigger(MouseInput.AXIS_Y, false));
inputManager.addMapping(CameraInput.CHASECAM_UP, new MouseAxisTrigger(MouseInput.AXIS_Y, true));
}
inputManager.addMapping(CameraInput.CHASECAM_ZOOMIN, new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false));
inputManager.addMapping(CameraInput.CHASECAM_ZOOMOUT, new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true));
if (!invertXaxis) {
inputManager.addMapping(CameraInput.CHASECAM_MOVELEFT, new MouseAxisTrigger(MouseInput.AXIS_X, true));
inputManager.addMapping(CameraInput.CHASECAM_MOVERIGHT, new MouseAxisTrigger(MouseInput.AXIS_X, false));
} else {
inputManager.addMapping(CameraInput.CHASECAM_MOVELEFT, new MouseAxisTrigger(MouseInput.AXIS_X, false));
inputManager.addMapping(CameraInput.CHASECAM_MOVERIGHT, new MouseAxisTrigger(MouseInput.AXIS_X, true));
}
inputManager.addMapping(CameraInput.CHASECAM_TOGGLEROTATE, new MouseButtonTrigger(MouseInput.BUTTON_LEFT));
inputManager.addMapping(CameraInput.CHASECAM_TOGGLEROTATE, new MouseButtonTrigger(MouseInput.BUTTON_RIGHT));
inputManager.addListener(this, inputs);
}
/**
* Cleans up the input mappings from the input manager.
* Undoes the work of registerWithInput().
* @param mgr the InputManager to clean up
*/
public void cleanupWithInput(InputManager mgr){
mgr.deleteMapping(CameraInput.CHASECAM_TOGGLEROTATE);
mgr.deleteMapping(CameraInput.CHASECAM_DOWN);
mgr.deleteMapping(CameraInput.CHASECAM_UP);
mgr.deleteMapping(CameraInput.CHASECAM_MOVELEFT);
mgr.deleteMapping(CameraInput.CHASECAM_MOVERIGHT);
mgr.deleteMapping(CameraInput.CHASECAM_ZOOMIN);
mgr.deleteMapping(CameraInput.CHASECAM_ZOOMOUT);
mgr.removeListener(this);
}
/**
* Sets custom triggers for toggling the rotation of the cam
* default are
* new MouseButtonTrigger(MouseInput.BUTTON_LEFT) left mouse button
* new MouseButtonTrigger(MouseInput.BUTTON_RIGHT) right mouse button
* @param triggers
*/
public void setToggleRotationTrigger(Trigger... triggers) {
inputManager.deleteMapping(CameraInput.CHASECAM_TOGGLEROTATE);
inputManager.addMapping(CameraInput.CHASECAM_TOGGLEROTATE, triggers);
inputManager.addListener(this, CameraInput.CHASECAM_TOGGLEROTATE);
}
/**
* Sets custom triggers for zooming in the cam
* default is
* new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true) mouse wheel up
* @param triggers
*/
public void setZoomInTrigger(Trigger... triggers) {
inputManager.deleteMapping(CameraInput.CHASECAM_ZOOMIN);
inputManager.addMapping(CameraInput.CHASECAM_ZOOMIN, triggers);
inputManager.addListener(this, CameraInput.CHASECAM_ZOOMIN);
}
/**
* Sets custom triggers for zooming out the cam
* default is
* new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false) mouse wheel down
* @param triggers
*/
public void setZoomOutTrigger(Trigger... triggers) {
inputManager.deleteMapping(CameraInput.CHASECAM_ZOOMOUT);
inputManager.addMapping(CameraInput.CHASECAM_ZOOMOUT, triggers);
inputManager.addListener(this, CameraInput.CHASECAM_ZOOMOUT);
}
protected void computePosition() {
float hDistance = (distance) * FastMath.sin((FastMath.PI / 2) - vRotation);
pos.set(hDistance * FastMath.cos(rotation), (distance) * FastMath.sin(vRotation), hDistance * FastMath.sin(rotation));
pos.addLocal(target.getWorldTranslation());
}
//rotate the camera around the target on the horizontal plane
protected void rotateCamera(float value) {
if (!canRotate || !enabled) {
return;
}
rotating = true;
targetRotation += value * rotationSpeed;
}
//move the camera toward or away the target
protected void zoomCamera(float value) {
if (!enabled) {
return;
}
zooming = true;
targetDistance += value * zoomSensitivity;
if (targetDistance > maxDistance) {
targetDistance = maxDistance;
}
if (targetDistance < minDistance) {
targetDistance = minDistance;
}
if (veryCloseRotation) {
if ((targetVRotation < minVerticalRotation) && (targetDistance > (minDistance + 1.0f))) {
targetVRotation = minVerticalRotation;
}
}
}
//rotate the camera around the target on the vertical plane
protected void vRotateCamera(float value) {
if (!canRotate || !enabled) {
return;
}
vRotating = true;
float lastGoodRot = targetVRotation;
targetVRotation += value * rotationSpeed;
if (targetVRotation > maxVerticalRotation) {
targetVRotation = lastGoodRot;
}
if (veryCloseRotation) {
if ((targetVRotation < minVerticalRotation) && (targetDistance > (minDistance + 1.0f))) {
targetVRotation = minVerticalRotation;
} else if (targetVRotation < -FastMath.DEG_TO_RAD * 90) {
targetVRotation = lastGoodRot;
}
} else {
if ((targetVRotation < minVerticalRotation)) {
targetVRotation = lastGoodRot;
}
}
}
/**
* Updates the camera, should only be called internally
*/
protected void updateCamera(float tpf) {
if (enabled) {
targetLocation.set(target.getWorldTranslation()).addLocal(lookAtOffset);
if (smoothMotion) {
//computation of target direction
targetDir.set(targetLocation).subtractLocal(prevPos);
float dist = targetDir.length();
//Low pass filtering on the target postition to avoid shaking when physics are enabled.
if (offsetDistance < dist) {
//target moves, start chasing.
chasing = true;
//target moves, start trailing if it has to.
if (trailingEnabled) {
trailing = true;
}
//target moves...
targetMoves = true;
} else {
//if target was moving, we compute a slight offset in rotation to avoid a rought stop of the cam
//We do not if the player is rotationg the cam
if (targetMoves && !canRotate) {
if (targetRotation - rotation > trailingRotationInertia) {
targetRotation = rotation + trailingRotationInertia;
} else if (targetRotation - rotation < -trailingRotationInertia) {
targetRotation = rotation - trailingRotationInertia;
}
}
//Target stops
targetMoves = false;
}
//the user is rotating the cam by dragging the mouse
if (canRotate) {
//reset the trailing lerp factor
trailingLerpFactor = 0;
//stop trailing user has the control
trailing = false;
}
if (trailingEnabled && trailing) {
if (targetMoves) {
//computation if the inverted direction of the target
Vector3f a = targetDir.negate().normalizeLocal();
//the x unit vector
Vector3f b = Vector3f.UNIT_X;
//2d is good enough
a.y = 0;
//computation of the rotation angle between the x axis and the trail
if (targetDir.z > 0) {
targetRotation = FastMath.TWO_PI - FastMath.acos(a.dot(b));
} else {
targetRotation = FastMath.acos(a.dot(b));
}
if (targetRotation - rotation > FastMath.PI || targetRotation - rotation < -FastMath.PI) {
targetRotation -= FastMath.TWO_PI;
}
//if there is an important change in the direction while trailing reset of the lerp factor to avoid jumpy movements
if (targetRotation != previousTargetRotation && FastMath.abs(targetRotation - previousTargetRotation) > FastMath.PI / 8) {
trailingLerpFactor = 0;
}
previousTargetRotation = targetRotation;
}
//computing lerp factor
trailingLerpFactor = Math.min(trailingLerpFactor + tpf * tpf * trailingSensitivity, 1);
//computing rotation by linear interpolation
rotation = FastMath.interpolateLinear(trailingLerpFactor, rotation, targetRotation);
//if the rotation is near the target rotation we're good, that's over
if (targetRotation + 0.01f >= rotation && targetRotation - 0.01f <= rotation) {
trailing = false;
trailingLerpFactor = 0;
}
}
//linear interpolation of the distance while chasing
if (chasing) {
distance = temp.set(targetLocation).subtractLocal(cam.getLocation()).length();
distanceLerpFactor = Math.min(distanceLerpFactor + (tpf * tpf * chasingSensitivity * 0.05f), 1);
distance = FastMath.interpolateLinear(distanceLerpFactor, distance, targetDistance);
if (targetDistance + 0.01f >= distance && targetDistance - 0.01f <= distance) {
distanceLerpFactor = 0;
chasing = false;
}
}
//linear interpolation of the distance while zooming
if (zooming) {
distanceLerpFactor = Math.min(distanceLerpFactor + (tpf * tpf * zoomSensitivity), 1);
distance = FastMath.interpolateLinear(distanceLerpFactor, distance, targetDistance);
if (targetDistance + 0.1f >= distance && targetDistance - 0.1f <= distance) {
zooming = false;
distanceLerpFactor = 0;
}
}
//linear interpolation of the rotation while rotating horizontally
if (rotating) {
rotationLerpFactor = Math.min(rotationLerpFactor + tpf * tpf * rotationSensitivity, 1);
rotation = FastMath.interpolateLinear(rotationLerpFactor, rotation, targetRotation);
if (targetRotation + 0.01f >= rotation && targetRotation - 0.01f <= rotation) {
rotating = false;
rotationLerpFactor = 0;
}
}
//linear interpolation of the rotation while rotating vertically
if (vRotating) {
vRotationLerpFactor = Math.min(vRotationLerpFactor + tpf * tpf * rotationSensitivity, 1);
vRotation = FastMath.interpolateLinear(vRotationLerpFactor, vRotation, targetVRotation);
if (targetVRotation + 0.01f >= vRotation && targetVRotation - 0.01f <= vRotation) {
vRotating = false;
vRotationLerpFactor = 0;
}
}
//computing the position
computePosition();
//setting the position at last
cam.setLocation(pos.addLocal(lookAtOffset));
} else {
//easy no smooth motion
vRotation = targetVRotation;
rotation = targetRotation;
distance = targetDistance;
computePosition();
cam.setLocation(pos.addLocal(lookAtOffset));
}
//keeping track on the previous position of the target
prevPos.set(targetLocation);
//the cam looks at the target
cam.lookAt(targetLocation, initialUpVec);
}
}
/**
* Return the enabled/disabled state of the camera
* @return true if the camera is enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* Enable or disable the camera
* @param enabled true to enable
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
if (!enabled) {
canRotate = false; // reset this flag in-case it was on before
}
}
/**
* Returns the max zoom distance of the camera (default is 40)
* @return maxDistance
*/
public float getMaxDistance() {
return maxDistance;
}
/**
* Sets the max zoom distance of the camera (default is 40)
* @param maxDistance
*/
public void setMaxDistance(float maxDistance) {
this.maxDistance = maxDistance;
if (maxDistance < distance) {
zoomCamera(maxDistance - distance);
}
}
/**
* Returns the min zoom distance of the camera (default is 1)
* @return minDistance
*/
public float getMinDistance() {
return minDistance;
}
/**
* Sets the min zoom distance of the camera (default is 1)
*/
public void setMinDistance(float minDistance) {
this.minDistance = minDistance;
if (minDistance > distance) {
zoomCamera(distance - minDistance);
}
}
/**
* clone this camera for a spatial
*
* @param spatial
* @return never
*/
@Deprecated
@Override
public Control cloneForSpatial(Spatial spatial) {
throw new UnsupportedOperationException();
}
@Override
public Object jmeClone() {
ChaseCamera cc = new ChaseCamera(cam, inputManager);
cc.target = target;
cc.setMaxDistance(getMaxDistance());
cc.setMinDistance(getMinDistance());
return cc;
}
@Override
public void cloneFields( Cloner cloner, Object original ) {
this.target = cloner.clone(target);
computePosition();
prevPos = new Vector3f(target.getWorldTranslation());
cam.setLocation(pos);
}
/**
* Sets the spacial for the camera control, should only be used internally
* @param spatial
*/
@Override
public void setSpatial(Spatial spatial) {
target = spatial;
if (spatial == null) {
return;
}
computePosition();
prevPos = new Vector3f(target.getWorldTranslation());
cam.setLocation(pos);
}
/**
* update the camera control, should only be used internally
* @param tpf
*/
@Override
public void update(float tpf) {
updateCamera(tpf);
}
/**
* renders the camera control, should only be used internally
* @param rm
* @param vp
*/
@Override
public void render(RenderManager rm, ViewPort vp) {
//nothing to render
}
/**
* Write the camera
* @param ex the exporter
* @throws IOException
*/
@Override
public void write(JmeExporter ex) throws IOException {
throw new UnsupportedOperationException("remove ChaseCamera before saving");
}
/**
* Read the camera
* @param im
* @throws IOException
*/
@Override
public void read(JmeImporter im) throws IOException {
InputCapsule ic = im.getCapsule(this);
maxDistance = ic.readFloat("maxDistance", 40);
minDistance = ic.readFloat("minDistance", 1);
}
/**
* @return The maximal vertical rotation angle in radian of the camera around the target
*/
public float getMaxVerticalRotation() {
return maxVerticalRotation;
}
/**
* Sets the maximal vertical rotation angle in radian of the camera around the target. Default is Pi/2;
* @param maxVerticalRotation
*/
public void setMaxVerticalRotation(float maxVerticalRotation) {
this.maxVerticalRotation = maxVerticalRotation;
}
/**
*
* @return The minimal vertical rotation angle in radian of the camera around the target
*/
public float getMinVerticalRotation() {
return minVerticalRotation;
}
/**
* Sets the minimal vertical rotation angle in radian of the camera around the target default is 0;
* @param minHeight
*/
public void setMinVerticalRotation(float minHeight) {
this.minVerticalRotation = minHeight;
}
/**
* @return True is smooth motion is enabled for this chase camera
*/
public boolean isSmoothMotion() {
return smoothMotion;
}
/**
* Enables smooth motion for this chase camera
* @param smoothMotion
*/
public void setSmoothMotion(boolean smoothMotion) {
this.smoothMotion = smoothMotion;
}
/**
* returns the chasing sensitivity
* @return the sensitivity
*/
public float getChasingSensitivity() {
return chasingSensitivity;
}
/**
*
* Sets the chasing sensitivity, the lower the value the slower the camera will follow the target when it moves
* default is 5
* Only has an effect if smoothMotion is set to true and trailing is enabled
* @param chasingSensitivity
*/
public void setChasingSensitivity(float chasingSensitivity) {
this.chasingSensitivity = chasingSensitivity;
}
/**
* Returns the rotation sensitivity
* @return the sensitivity
*/
public float getRotationSensitivity() {
return rotationSensitivity;
}
/**
* Sets the rotation sensitivity, the lower the value the slower the camera will rotates around the target when dragging with the mouse
* default is 5, values over 5 should have no effect.
* If you want a significant slow down try values below 1.
* Only has an effect if smoothMotion is set to true
* @param rotationSensitivity
*/
public void setRotationSensitivity(float rotationSensitivity) {
this.rotationSensitivity = rotationSensitivity;
}
/**
* returns true if the trailing is enabled
* @return true if enabled, otherwise false
*/
public boolean isTrailingEnabled() {
return trailingEnabled;
}
/**
* Enable the camera trailing : The camera smoothly go in the targets trail when it moves.
* Only has an effect if smoothMotion is set to true
* @param trailingEnabled
*/
public void setTrailingEnabled(boolean trailingEnabled) {
this.trailingEnabled = trailingEnabled;
}
/**
*
* returns the trailing rotation inertia
* @return the inertia
*/
public float getTrailingRotationInertia() {
return trailingRotationInertia;
}
/**
* Sets the trailing rotation inertia : default is 0.1. This prevent the camera to roughtly stop when the target stops moving
* before the camera reached the trail position.
* Only has an effect if smoothMotion is set to true and trailing is enabled
* @param trailingRotationInertia
*/
public void setTrailingRotationInertia(float trailingRotationInertia) {
this.trailingRotationInertia = trailingRotationInertia;
}
/**
* returns the trailing sensitivity
* @return the sensitivity
*/
public float getTrailingSensitivity() {
return trailingSensitivity;
}
/**
* Only has an effect if smoothMotion is set to true and trailing is enabled
* Sets the trailing sensitivity, the lower the value, the slower the camera will go in the target trail when it moves.
* default is 0.5;
* @param trailingSensitivity
*/
public void setTrailingSensitivity(float trailingSensitivity) {
this.trailingSensitivity = trailingSensitivity;
}
/**
* returns the zoom sensitivity
* @return the sensitivity
*/
public float getZoomSensitivity() {
return zoomSensitivity;
}
/**
* Sets the zoom sensitivity, the lower the value, the slower the camera will zoom in and out.
* default is 2.
* @param zoomSensitivity
*/
public void setZoomSensitivity(float zoomSensitivity) {
this.zoomSensitivity = zoomSensitivity;
}
/**
* Returns the rotation speed when the mouse is moved.
*
* @return the rotation speed when the mouse is moved.
*/
public float getRotationSpeed() {
return rotationSpeed;
}
/**
* Sets the rotate amount when user moves his mouse, the lower the value,
* the slower the camera will rotate. default is 1.
*
* @param rotationSpeed Rotation speed on mouse movement, default is 1.
*/
public void setRotationSpeed(float rotationSpeed) {
this.rotationSpeed = rotationSpeed;
}
/**
* Sets the default distance at start of application
* @param defaultDistance
*/
public void setDefaultDistance(float defaultDistance) {
distance = defaultDistance;
targetDistance = distance;
}
/**
* sets the default horizontal rotation in radian of the camera at start of the application
* @param angleInRad
*/
public void setDefaultHorizontalRotation(float angleInRad) {
rotation = angleInRad;
targetRotation = angleInRad;
}
/**
* sets the default vertical rotation in radian of the camera at start of the application
* @param angleInRad
*/
public void setDefaultVerticalRotation(float angleInRad) {
vRotation = angleInRad;
targetVRotation = angleInRad;
}
/**
* @return If drag to rotate feature is enabled.
*
* @see #setDragToRotate(boolean)
*/
public boolean isDragToRotate() {
return dragToRotate;
}
/**
* @param dragToRotate When true, the user must hold the mouse button
* and drag over the screen to rotate the camera, and the cursor is
* visible until dragged. Otherwise, the cursor is invisible at all times
* and holding the mouse button is not needed to rotate the camera.
* This feature is disabled by default.
*/
public void setDragToRotate(boolean dragToRotate) {
this.dragToRotate = dragToRotate;
this.canRotate = !dragToRotate;
inputManager.setCursorVisible(dragToRotate);
}
/**
* @param rotateOnlyWhenClose When this flag is set to false the chase
* camera will always rotate around its spatial independently of their
* distance to one another. If set to true, the chase camera will only
* be allowed to rotated below the "horizon" when the distance is smaller
* than minDistance + 1.0f (when fully zoomed-in).
*/
public void setDownRotateOnCloseViewOnly(boolean rotateOnlyWhenClose) {
veryCloseRotation = rotateOnlyWhenClose;
}
/**
* @return True if rotation below the vertical plane of the spatial tied
* to the camera is allowed only when zoomed in at minDistance + 1.0f.
* False if vertical rotation is always allowed.
*/
public boolean getDownRotateOnCloseViewOnly() {
return veryCloseRotation;
}
/**
* return the current distance from the camera to the target
* @return the distance
*/
public float getDistanceToTarget() {
return distance;
}
/**
* returns the current horizontal rotation around the target in radians
* @return the angle
*/
public float getHorizontalRotation() {
return rotation;
}
/**
* returns the current vertical rotation around the target in radians.
* @return the angle in radians
*/
public float getVerticalRotation() {
return vRotation;
}
/**
* returns the offset from the target's position where the camera looks at
* @return the pre-existing vector
*/
public Vector3f getLookAtOffset() {
return lookAtOffset;
}
/**
* Sets the offset from the target's position where the camera looks at
* @param lookAtOffset
*/
public void setLookAtOffset(Vector3f lookAtOffset) {
this.lookAtOffset = lookAtOffset;
}
/**
* Sets the up vector of the camera used for the lookAt on the target
* @param up
*/
public void setUpVector(Vector3f up) {
initialUpVec = up;
}
/**
* Returns the up vector of the camera used for the lookAt on the target
* @return the pre-existing vector
*/
public Vector3f getUpVector() {
return initialUpVec;
}
public boolean isHideCursorOnRotate() {
return hideCursorOnRotate;
}
public void setHideCursorOnRotate(boolean hideCursorOnRotate) {
this.hideCursorOnRotate = hideCursorOnRotate;
}
/**
* invert the vertical axis movement of the mouse
* @param invertYaxis
*/
public void setInvertVerticalAxis(boolean invertYaxis) {
this.invertYaxis = invertYaxis;
inputManager.deleteMapping(CameraInput.CHASECAM_DOWN);
inputManager.deleteMapping(CameraInput.CHASECAM_UP);
if (!invertYaxis) {
inputManager.addMapping(CameraInput.CHASECAM_DOWN, new MouseAxisTrigger(MouseInput.AXIS_Y, true));
inputManager.addMapping(CameraInput.CHASECAM_UP, new MouseAxisTrigger(MouseInput.AXIS_Y, false));
} else {
inputManager.addMapping(CameraInput.CHASECAM_DOWN, new MouseAxisTrigger(MouseInput.AXIS_Y, false));
inputManager.addMapping(CameraInput.CHASECAM_UP, new MouseAxisTrigger(MouseInput.AXIS_Y, true));
}
inputManager.addListener(this, CameraInput.CHASECAM_DOWN, CameraInput.CHASECAM_UP);
}
/**
* invert the Horizontal axis movement of the mouse
* @param invertXaxis
*/
public void setInvertHorizontalAxis(boolean invertXaxis) {
this.invertXaxis = invertXaxis;
inputManager.deleteMapping(CameraInput.CHASECAM_MOVELEFT);
inputManager.deleteMapping(CameraInput.CHASECAM_MOVERIGHT);
if (!invertXaxis) {
inputManager.addMapping(CameraInput.CHASECAM_MOVELEFT, new MouseAxisTrigger(MouseInput.AXIS_X, true));
inputManager.addMapping(CameraInput.CHASECAM_MOVERIGHT, new MouseAxisTrigger(MouseInput.AXIS_X, false));
} else {
inputManager.addMapping(CameraInput.CHASECAM_MOVELEFT, new MouseAxisTrigger(MouseInput.AXIS_X, false));
inputManager.addMapping(CameraInput.CHASECAM_MOVERIGHT, new MouseAxisTrigger(MouseInput.AXIS_X, true));
}
inputManager.addListener(this, CameraInput.CHASECAM_MOVELEFT, CameraInput.CHASECAM_MOVERIGHT);
}
}
| bsd-3-clause |
mg6maciej/hrisey-intellij-plugin | lombok-plugin/src/test/java/de/plushnikov/intellij/plugin/action/delombok/DelombokEqualsAndHashcodeActionTest.java | 884 | package de.plushnikov.intellij.plugin.action.delombok;
import com.intellij.openapi.actionSystem.AnAction;
import de.plushnikov.intellij.plugin.action.LombokLightActionTest;
public class DelombokEqualsAndHashcodeActionTest extends LombokLightActionTest {
protected AnAction getAction() {
return new DelombokEqualsAndHashCodeAction();
}
@Override
protected String getBasePath() {
return super.getBasePath() + "/action/delombok/equalsandhashcode";
}
public void testEqualsAndHashCodeSimple() throws Exception {
doTest();
}
public void testEqualsAndHashCodeOf() throws Exception {
doTest();
}
public void testEqualsAndHashCodeNoGetters() throws Exception {
doTest();
}
public void testEqualsAndHashCodeExclude() throws Exception {
doTest();
}
public void testEqualsAndHashCodeCallSuper() throws Exception {
doTest();
}
}
| bsd-3-clause |
lang010/acit | leetcode/552.student-attendance-record-ii.425589930.ac.java | 1982 | /*
* @lc app=leetcode id=552 lang=java
*
* [552] Student Attendance Record II
*
* https://leetcode.com/problems/student-attendance-record-ii/description/
*
* algorithms
* Hard (37.06%)
* Total Accepted: 27K
* Total Submissions: 72.8K
* Testcase Example: '1'
*
* Given a positive integer n, return the number of all possible attendance
* records with length n, which will be regarded as rewardable. The answer may
* be very large, return it after mod 10^9 + 7.
*
* A student attendance record is a string that only contains the following
* three characters:
*
*
*
* 'A' : Absent.
* 'L' : Late.
* 'P' : Present.
*
*
*
*
* A record is regarded as rewardable if it doesn't contain more than one 'A'
* (absent) or more than two continuous 'L' (late).
*
* Example 1:
*
* Input: n = 2
* Output: 8
* Explanation:
* There are 8 records with length 2 will be regarded as rewardable:
* "PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL"
* Only "AA" won't be regarded as rewardable owing to more than one absent
* times.
*
*
*
* Note:
* The value of n won't exceed 100,000.
*
*
*
*
*/
class Solution {
public int checkRecord(int n) {
// Initial states.
long all = 3, hasA = 1, end1L = 1, end2L = 0, hasAEnd1L = 0, hasAEnd2L = 0;
long mod = 1000000007l;
for (int i = 1; i < n; i++) {
// Next states.
long all0 = all + all - hasA + all - end2L;
long hasA0 = all - hasA + hasA + hasA - hasAEnd2L;
long end1L0 = all - end1L - end2L;
long end2L0 = end1L;
long hasAEnd1L0 = hasA - hasAEnd1L - hasAEnd2L;
long hasAEnd2L0 = hasAEnd1L;
all = all0 % mod;
hasA = hasA0 % mod;
end1L = end1L0 % mod;
end2L = end2L0 % mod;
hasAEnd1L = hasAEnd1L0 % mod;
hasAEnd2L = hasAEnd2L0 % mod;
}
return (int) ((all+mod) % mod);
}
}
| bsd-3-clause |
GameRevision/GWLP-R | protocol/src/main/java/gwlpr/protocol/gameserver/inbound/P035_Unknown.java | 576 |
package gwlpr.protocol.gameserver.inbound;
import gwlpr.protocol.serialization.GWMessage;
/**
* Auto-generated by PacketCodeGen.
*
*/
public final class P035_Unknown
extends GWMessage
{
private long unknown1;
@Override
public short getHeader() {
return 35;
}
public long getUnknown1() {
return unknown1;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("P035_Unknown[");
sb.append("unknown1=").append(this.unknown1).append("]");
return sb.toString();
}
}
| bsd-3-clause |
frc4343/max2014 | src/ca/_4343/max3/commands/drivetrain/DriveToDistance.java | 1829 | /*
* FRC Team 4343
* Visit us at www.4343.ca
*/
package ca._4343.max3.commands.drivetrain;
import ca._4343.max3.commands.CommandBase;
/**
*
* @author Brian Ho <www.4343.ca>
* @author Tedi Papajorgji <www.4343.ca>
*/
public class DriveToDistance extends CommandBase {
private final String direction;
private final double distance;
/**
* Constructor determining direction and distance to drive to
* @param direction Accepts either "forward" or "reverse" case-insensitive
* @param distance Distance to drive to before stopping
*/
public DriveToDistance(String direction, double distance) {
this.direction = direction;
this.distance = distance;
requires(rangeFinder);
requires(driveTrain);
}
/**
* Called just before this Command runs the first time
*/
protected void initialize() {
}
/**
* Called repeatedly when this Command is scheduled to run
*/
protected void execute() {
if (rangeFinder.getDistanceInInches() != distance) {
driveTrain.arcadeDrive(direction.equalsIgnoreCase("forward") ? 1 : -1, 0); // If an invalid paramter is given then it is treated as reverse
}
}
/**
* Make this return true when this Command no longer needs to run execute()
* @return True, when robot is at specified distance
*/
protected boolean isFinished() {
return rangeFinder.getDistanceInInches() == distance;
}
/**
* Called once after isFinished returns true
*/
protected void end() {
}
/**
* Called when another command which requires one or more of the same
* subsystems is scheduled to run
*/
protected void interrupted() {
}
}
| bsd-3-clause |
RobotsByTheC/CMonster2016 | src/main/java/org/usfirst/frc/team2084/CMonster2016/commands/TakeSnapshot.java | 949 | /*
* Copyright (c) 2016 RobotsByTheC. All rights reserved.
*
* Open Source Software - may be modified and shared by FRC teams. The code must
* be accompanied by the BSD license file in the root directory of the project.
*/
package org.usfirst.frc.team2084.CMonster2016.commands;
import org.usfirst.frc.team2084.CMonster2016.vision.VisionParameters;
import edu.wpi.first.wpilibj.command.Command;
/**
* Command that signals the vision system to save a snapshot.
*
* @author Ben Wolsieffer
*/
public class TakeSnapshot extends Command {
public TakeSnapshot() {
setRunWhenDisabled(true);
}
@Override
protected void initialize() {
VisionParameters.takeSnapshot();
}
@Override
protected void execute() {
}
@Override
protected boolean isFinished() {
return true;
}
@Override
protected void end() {
}
@Override
protected void interrupted() {
}
}
| bsd-3-clause |
wiki05/google-auth-library-java | oauth2_http/javatests/com/google/auth/oauth2/ServiceAccountCredentialsTest.java | 7369 | package com.google.auth.oauth2;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.google.api.client.json.GenericJson;
import com.google.auth.TestUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.InputStream;
import java.io.IOException;
import java.net.URI;
import java.security.PrivateKey;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Test case for {@link ServiceAccountCredentials}.
*/
@RunWith(JUnit4.class)
public class ServiceAccountCredentialsTest {
private final static String SA_CLIENT_EMAIL =
"36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr@developer.gserviceaccount.com";
private final static String SA_CLIENT_ID =
"36680232662-vrd7ji19qe3nelgchd0ah2csanun6bnr.apps.googleusercontent.com";
private final static String SA_PRIVATE_KEY_ID =
"d84a4fefcf50791d4a90f2d7af17469d6282df9d";
static final String SA_PRIVATE_KEY_PKCS8 = "-----BEGIN PRIVATE KEY-----\n"
+ "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALX0PQoe1igW12i"
+ "kv1bN/r9lN749y2ijmbc/mFHPyS3hNTyOCjDvBbXYbDhQJzWVUikh4mvGBA07qTj79Xc3yBDfKP2IeyYQIFe0t0"
+ "zkd7R9Zdn98Y2rIQC47aAbDfubtkU1U72t4zL11kHvoa0/RuFZjncvlr42X7be7lYh4p3NAgMBAAECgYASk5wDw"
+ "4Az2ZkmeuN6Fk/y9H+Lcb2pskJIXjrL533vrDWGOC48LrsThMQPv8cxBky8HFSEklPpkfTF95tpD43iVwJRB/Gr"
+ "CtGTw65IfJ4/tI09h6zGc4yqvIo1cHX/LQ+SxKLGyir/dQM925rGt/VojxY5ryJR7GLbCzxPnJm/oQJBANwOCO6"
+ "D2hy1LQYJhXh7O+RLtA/tSnT1xyMQsGT+uUCMiKS2bSKx2wxo9k7h3OegNJIu1q6nZ6AbxDK8H3+d0dUCQQDTrP"
+ "SXagBxzp8PecbaCHjzNRSQE2in81qYnrAFNB4o3DpHyMMY6s5ALLeHKscEWnqP8Ur6X4PvzZecCWU9BKAZAkAut"
+ "LPknAuxSCsUOvUfS1i87ex77Ot+w6POp34pEX+UWb+u5iFn2cQacDTHLV1LtE80L8jVLSbrbrlH43H0DjU5AkEA"
+ "gidhycxS86dxpEljnOMCw8CKoUBd5I880IUahEiUltk7OLJYS/Ts1wbn3kPOVX3wyJs8WBDtBkFrDHW2ezth2QJ"
+ "ADj3e1YhMVdjJW5jqwlD/VNddGjgzyunmiZg0uOXsHXbytYmsA545S8KRQFaJKFXYYFo2kOjqOiC1T2cAzMDjCQ"
+ "==\n-----END PRIVATE KEY-----\n";
private static final String ACCESS_TOKEN = "1/MkSJoj1xsli0AccessToken_NKPY2";
private final static Collection<String> SCOPES = Collections.singletonList("dummy.scope");
private final static Collection<String> EMPTY_SCOPES = Collections.<String>emptyList();
private static final URI CALL_URI = URI.create("http://googleapis.com/testapi/v1/foo");
@Test
public void createdScoped_clones() throws IOException {
PrivateKey privateKey = ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8);
GoogleCredentials credentials = new ServiceAccountCredentials(
SA_CLIENT_ID, SA_CLIENT_EMAIL, privateKey, SA_PRIVATE_KEY_ID, null);
List<String> newScopes = Arrays.asList("scope1", "scope2");
ServiceAccountCredentials newCredentials =
(ServiceAccountCredentials) credentials.createScoped(newScopes);
assertEquals(SA_CLIENT_ID, newCredentials.getClientId());
assertEquals(SA_CLIENT_EMAIL, newCredentials.getClientEmail());
assertEquals(privateKey, newCredentials.getPrivateKey());
assertEquals(SA_PRIVATE_KEY_ID, newCredentials.getPrivateKeyId());
assertArrayEquals(newScopes.toArray(), newCredentials.getScopes().toArray());
}
@Test
public void createdScoped_enablesAccessTokens() throws IOException {
MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN);
GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8(
SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID, null, transport);
try {
credentials.getRequestMetadata(CALL_URI);
fail("Should not be able to get token without scopes");
} catch (Exception expected) {
}
GoogleCredentials scopedCredentials = credentials.createScoped(SCOPES);
Map<String, List<String>> metadata = scopedCredentials.getRequestMetadata(CALL_URI);
TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN);
}
@Test
public void createScopedRequired_emptyScopes_true() throws IOException {
GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8(
SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID, EMPTY_SCOPES);
assertTrue(credentials.createScopedRequired());
}
@Test
public void createScopedRequired_nonEmptyScopes_false() throws IOException {
GoogleCredentials credentials = ServiceAccountCredentials.fromPkcs8(
SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID, SCOPES);
assertFalse(credentials.createScopedRequired());
}
@Test
public void fromJSON_hasAccessToken() throws IOException {
MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN);
GenericJson json = writeServiceAccountJson(
SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID);
GoogleCredentials credentials = ServiceAccountCredentials.fromJson(json, transport);
credentials = credentials.createScoped(SCOPES);
Map<String, List<String>> metadata = credentials.getRequestMetadata(CALL_URI);
TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN);
}
@Test
public void getRequestMetadata_hasAccessToken() throws IOException {
MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN);
OAuth2Credentials credentials = ServiceAccountCredentials.fromPkcs8(
SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID, SCOPES, transport);
Map<String, List<String>> metadata = credentials.getRequestMetadata(CALL_URI);
TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN);
}
@Test
public void getScopes_nullReturnsEmpty() throws IOException {
ServiceAccountCredentials credentials = ServiceAccountCredentials.fromPkcs8(
SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID, null);
Collection<String> scopes = credentials.getScopes();
assertNotNull(scopes);
assertTrue(scopes.isEmpty());
}
static GenericJson writeServiceAccountJson(
String clientId, String clientEmail, String privateKeyPkcs8, String privateKeyId) {
GenericJson json = new GenericJson();
if (clientId != null) {
json.put("client_id", clientId);
}
if (clientEmail != null) {
json.put("client_email", clientEmail);
}
if (privateKeyPkcs8 != null) {
json.put("private_key", privateKeyPkcs8);
}
if (privateKeyId != null) {
json.put("private_key_id", privateKeyId);
}
json.put("type", GoogleCredentials.SERVICE_ACCOUNT_FILE_TYPE);
return json;
}
static InputStream writeServiceAccountAccountStream(String clientId, String clientEmail,
String privateKeyPkcs8, String privateKeyId) throws IOException {
GenericJson json =
writeServiceAccountJson(clientId, clientEmail, privateKeyPkcs8, privateKeyId);
InputStream stream = TestUtils.jsonToInputStream(json);
return stream;
}
}
| bsd-3-clause |
sahara-labs/scheduling-server | Session/src/au/edu/uts/eng/remotelabs/schedserver/session/pojo/impl/SessionServiceImpl.java | 3629 | /**
* SAHARA Scheduling Server
*
* Schedules and assigns local laboratory rigs.
*
* @license See LICENSE in the top level directory for complete license terms.
*
* Copyright (c) 2011, Michael Diponio
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Technology, Sydney nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Michael Diponio (mdiponio)
* @date 6th August 2011
*/
package au.edu.uts.eng.remotelabs.schedserver.session.pojo.impl;
import java.util.Date;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.entities.Session;
import au.edu.uts.eng.remotelabs.schedserver.dataaccess.listener.SessionEventListener.SessionEvent;
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.session.SessionActivator;
import au.edu.uts.eng.remotelabs.schedserver.session.pojo.SessionService;
/**
* Implementation of the Session POJO service.
*/
public class SessionServiceImpl implements SessionService
{
/** Logger. */
private Logger logger;
public SessionServiceImpl()
{
this.logger = LoggerActivator.getLogger();
}
@Override
public boolean finishSession(Session ses, String reason, org.hibernate.Session db)
{
/* Only sessions that are active and in session will be finished. */
if (!ses.isActive() || ses.getAssignmentTime() == null)
{
this.logger.warn("Session '" + ses.getId() + "' not assigned to rig so will not be finished.");
return false;
}
/* Finish session. */
this.logger.debug("Finishing session '" + ses.getId() + "' with reason: " + reason);
db.beginTransaction();
ses.setActive(false);
ses.setRemovalReason(reason);
ses.setRemovalTime(new Date());
db.flush();
db.getTransaction().commit();
/* Fire session finished event. */
SessionActivator.notifySessionEvent(SessionEvent.FINISHED, ses, db);
/* Local session, release the rig. */
SessionActivator.release(ses, db);
return true;
}
}
| bsd-3-clause |
NCIP/catissue-test | src/edu/wustl/catissuecore/service/globus/resource/CaTissueSuiteResourceBase.java | 16279 | /*L
* Copyright Washington University in St. Louis
* Copyright SemanticBits
* Copyright Persistent Systems
* Copyright Krishagni
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/catissue-test/LICENSE.txt for details.
*/
package edu.wustl.catissuecore.service.globus.resource;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.advertisement.AdvertisementClient;
import gov.nih.nci.cagrid.advertisement.exceptions.UnregistrationException;
import edu.wustl.catissuecore.common.CaTissueSuiteConstants;
import edu.wustl.catissuecore.stubs.CaTissueSuiteResourceProperties;
import edu.wustl.catissuecore.service.CaTissueSuiteConfiguration;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.xml.namespace.QName;
import gov.nih.nci.cagrid.introduce.servicetools.FilePersistenceHelper;
import gov.nih.nci.cagrid.introduce.servicetools.PersistenceHelper;
import gov.nih.nci.cagrid.introduce.servicetools.ReflectionResource;
import org.apache.axis.MessageContext;
import org.apache.axis.message.MessageElement;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.globus.mds.aggregator.types.AggregatorConfig;
import org.globus.mds.aggregator.types.AggregatorContent;
import org.globus.mds.aggregator.types.GetMultipleResourcePropertiesPollType;
import org.globus.mds.servicegroup.client.ServiceGroupRegistrationParameters;
import org.globus.wsrf.InvalidResourceKeyException;
import org.globus.wsrf.NoSuchResourceException;
import org.globus.wsrf.Constants;
import org.globus.wsrf.Resource;
import org.globus.wsrf.ResourceException;
import org.globus.wsrf.RemoveCallback;
import org.globus.wsrf.PersistenceCallback;
import org.globus.wsrf.ResourceContext;
import org.globus.wsrf.ResourceException;
import org.globus.wsrf.ResourceContextException;
import org.globus.wsrf.ResourceIdentifier;
import org.globus.wsrf.ResourceKey;
import org.globus.wsrf.ResourceLifetime;
import org.globus.wsrf.ResourceProperties;
import org.globus.wsrf.ResourceProperty;
import org.globus.wsrf.ResourcePropertySet;
import org.globus.wsrf.config.ContainerConfig;
import org.globus.wsrf.container.ServiceHost;
import org.globus.wsrf.encoding.DeserializationException;
import org.globus.wsrf.encoding.ObjectDeserializer;
import org.globus.wsrf.impl.ReflectionResourceProperty;
import org.globus.wsrf.impl.SimpleResourceProperty;
import org.globus.wsrf.impl.SimpleResourcePropertyMetaData;
import org.globus.wsrf.impl.SimpleResourcePropertySet;
import org.globus.wsrf.impl.security.descriptor.ResourceSecurityDescriptor;
import org.globus.wsrf.impl.servicegroup.client.ServiceGroupRegistrationClient;
import org.globus.wsrf.jndi.Initializable;
import org.globus.wsrf.security.SecureResource;
import org.globus.wsrf.utils.AddressingUtils;
import org.globus.wsrf.Topic;
import org.globus.wsrf.TopicList;
import org.globus.wsrf.TopicListAccessor;
import org.globus.wsrf.utils.SubscriptionPersistenceUtils;
import org.globus.wsrf.impl.ResourcePropertyTopic;
import org.globus.wsrf.impl.SimpleTopicList;
import org.oasis.wsrf.lifetime.TerminationNotification;
/**
* DO NOT EDIT: This class is autogenerated!
*
* This class is the base class of the resource type created for this service.
* It contains accessor and utility methods for managing any resource properties
* of these resource as well as code for registering any properties selected
* to the index service.
*
* @created by Introduce Toolkit version 1.2
*
*/
public abstract class CaTissueSuiteResourceBase extends ReflectionResource implements Resource
{
static final Log logger = LogFactory.getLog(CaTissueSuiteResourceBase.class);
private CaTissueSuiteResourceConfiguration configuration;
// this can be used to cancel the registration renewal
private AdvertisementClient registrationClient;
private URL baseURL;
private boolean beingLoaded = false;
public CaTissueSuiteResourceBase() {
}
/**
* @see org.globus.wsrf.jndi.Initializable#initialize()
*/
public void initialize(Object resourceBean,
QName resourceElementQName,
Object id) throws ResourceException {
// Call the super initialize on the ReflectionResource
super.initialize(resourceBean,resourceElementQName,id);
// this loads the metadata from XML files if this is the main service
populateResourceProperties();
// register the service to the index service
refreshRegistration(true);
}
//Getters/Setters for ResourceProperties
public gov.nih.nci.cagrid.metadata.dataservice.DomainModel getDomainModel(){
return ((CaTissueSuiteResourceProperties) getResourceBean()).getDomainModel();
}
public void setDomainModel(gov.nih.nci.cagrid.metadata.dataservice.DomainModel domainModel ) throws ResourceException {
ResourceProperty prop = getResourcePropertySet().get(CaTissueSuiteConstants.DOMAINMODEL);
prop.set(0, domainModel);
}
public gov.nih.nci.cagrid.metadata.ServiceMetadata getServiceMetadata(){
return ((CaTissueSuiteResourceProperties) getResourceBean()).getServiceMetadata();
}
public void setServiceMetadata(gov.nih.nci.cagrid.metadata.ServiceMetadata serviceMetadata ) throws ResourceException {
ResourceProperty prop = getResourcePropertySet().get(CaTissueSuiteConstants.SERVICEMETADATA);
prop.set(0, serviceMetadata);
}
public CaTissueSuiteResourceConfiguration getConfiguration() {
if (this.configuration != null) {
return this.configuration;
}
MessageContext ctx = MessageContext.getCurrentContext();
String servicePath = ctx.getTargetService();
servicePath = servicePath.substring(0,servicePath.lastIndexOf("/"));
servicePath+="/CaTissueSuite";
String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/configuration";
logger.debug("Will read configuration from jndi name: " + jndiName);
try {
Context initialContext = new InitialContext();
this.configuration = (CaTissueSuiteResourceConfiguration) initialContext.lookup(jndiName);
} catch (Exception e) {
logger.error("when performing JNDI lookup for " + jndiName + ": " + e, e);
}
return this.configuration;
}
/**
* This checks the configuration file, and attempts to register to the
* IndexService if shouldPerformRegistration==true. It will first read the
* current container URL, and compare it against the saved value. If the
* value exists, it will only try to reregister if the values are different.
* This exists to handle fixing the registration URL which may be incorrect
* during initialization, then later corrected during invocation. The
* existence of baseURL does not imply successful registration (a non-null
* registrationClient does). We will only attempt to reregister when the URL
* changes (to prevent attempting registration with each invocation if there
* is a configuration problem).
*/
public void refreshRegistration(boolean forceRefresh) {
if (getConfiguration().shouldPerformRegistration()) {
// first check to see if there are any resource properties that
// require registration
ResourceContext ctx;
try {
MessageContext msgContext = MessageContext.getCurrentContext();
if (msgContext == null) {
logger.error("Unable to determine message context!");
return;
}
ctx = ResourceContext.getResourceContext(msgContext);
} catch (ResourceContextException e) {
logger.error("Could not get ResourceContext: " + e, e);
return;
}
EndpointReferenceType epr;
try {
// since this is a singleton, pretty sure we dont't want to
// register the key (allows multiple instances of same service
// on successive restarts)
epr = AddressingUtils.createEndpointReference(ctx, null);
} catch (Exception e) {
logger.error("Could not form EPR: " + e, e);
return;
}
ServiceGroupRegistrationParameters params = null;
File registrationFile = new File(ContainerConfig.getBaseDirectory() + File.separator
+ getConfiguration().getRegistrationTemplateFile());
if (registrationFile.exists() && registrationFile.canRead()) {
logger.debug("Loading registration argumentsrmation from:" + registrationFile);
try {
params = ServiceGroupRegistrationClient.readParams(registrationFile.getAbsolutePath());
} catch (Exception e) {
logger.error("Unable to read registration file:" + registrationFile, e);
}
// set our service's EPR as the registrant, or use the specified
// value
EndpointReferenceType registrantEpr = params.getRegistrantEPR();
if (registrantEpr == null) {
params.setRegistrantEPR(epr);
}
} else {
logger.error("Unable to read registration file:" + registrationFile);
}
if (params != null) {
AggregatorContent content = (AggregatorContent) params.getContent();
AggregatorConfig config = content.getAggregatorConfig();
MessageElement[] elements = config.get_any();
GetMultipleResourcePropertiesPollType pollType = null;
try {
pollType = (GetMultipleResourcePropertiesPollType) ObjectDeserializer.toObject(elements[0],
GetMultipleResourcePropertiesPollType.class);
} catch (DeserializationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (pollType != null) {
// if there are properties names that need to be registered then
// register them to the index service
if (pollType.getResourcePropertyNames()!=null && pollType.getResourcePropertyNames().length != 0) {
URL currentContainerURL = null;
try {
currentContainerURL = ServiceHost.getBaseURL();
} catch (IOException e) {
logger.error("Unable to determine container's URL! Skipping registration.", e);
return;
}
if (this.baseURL != null) {
// we've tried to register before (or we are being
// forced to
// retry)
// do a string comparison as we don't want to do DNS
// lookups
// for comparison
if (forceRefresh || !this.baseURL.equals(currentContainerURL)) {
// we've tried to register before, and we have a
// different
// URL now.. so cancel the old registration (if
// it
// exists),
// and try to redo it.
if (registrationClient != null) {
try {
this.registrationClient.unregister();
} catch (UnregistrationException e) {
logger
.error("Problem unregistering existing registration:" + e.getMessage(), e);
}
}
// save the new value
this.baseURL = currentContainerURL;
logger.info("Refreshing existing registration [container URL=" + this.baseURL + "].");
} else {
// URLs are the same (and we weren't forced), so
// don't
// try
// to reregister
return;
}
} else {
// we've never saved the baseURL (and therefore
// haven't
// tried to
// register)
this.baseURL = currentContainerURL;
logger.info("Attempting registration for the first time[container URL=" + this.baseURL
+ "].");
}
try {
// perform the registration for this service
this.registrationClient = new AdvertisementClient(params);
this.registrationClient.register();
} catch (Exception e) {
logger.error("Exception when trying to register service (" + epr + "): " + e, e);
}
} else {
logger.info("No resource properties to register for service (" + epr + ")");
}
} else {
logger.warn("Registration file deserialized with no poll type (" + epr + ")");
}
} else {
logger.warn("Registration file deserialized with returned null SeviceGroupParams");
}
} else {
logger.info("Skipping registration.");
}
}
private void populateResourceProperties() {
loadDomainModelFromFile();
loadServiceMetadataFromFile();
}
private void loadDomainModelFromFile() {
if(getDomainModel()==null){
try {
File dataFile = new File(ContainerConfig.getBaseDirectory() + File.separator
+ getConfiguration().getDomainModelFile());
((CaTissueSuiteResourceProperties) this.getResourceBean()).setDomainModel((gov.nih.nci.cagrid.metadata.dataservice.DomainModel) Utils.deserializeDocument(dataFile.getAbsolutePath(),
gov.nih.nci.cagrid.metadata.dataservice.DomainModel.class));
} catch (Exception e) {
logger.error("ERROR: problem populating metadata from file: " + e.getMessage(), e);
}
}
}
private void loadServiceMetadataFromFile() {
if(getServiceMetadata()==null){
try {
File dataFile = new File(ContainerConfig.getBaseDirectory() + File.separator
+ getConfiguration().getServiceMetadataFile());
((CaTissueSuiteResourceProperties) this.getResourceBean()).setServiceMetadata((gov.nih.nci.cagrid.metadata.ServiceMetadata) Utils.deserializeDocument(dataFile.getAbsolutePath(),
gov.nih.nci.cagrid.metadata.ServiceMetadata.class));
} catch (Exception e) {
logger.error("ERROR: problem populating metadata from file: " + e.getMessage(), e);
}
}
}
} | bsd-3-clause |
rlgomes/dtf | src/java/com/yahoo/dtf/actions/basic/Sleep.java | 2383 | package com.yahoo.dtf.actions.basic;
import com.yahoo.dtf.actions.Action;
import com.yahoo.dtf.exception.DTFException;
import com.yahoo.dtf.exception.ParseException;
import com.yahoo.dtf.util.TimeUtil;
/**
* @dtf.tag sleep
*
* @dtf.since 1.0
* @dtf.author Rodney Gomes
*
* @dtf.tag.desc The sleep tag will pause the execution of the test case at this
* point for the amount of time specified in the property
* <code>time</code>. The time attribute itself has a special
* syntax which is explained below.
*
* @dtf.tag.example
* <sleep time="3s"/>
*
* @dtf.tag.example
* <sleep time="2d"/>
*/
public class Sleep extends Action {
/**
* @dtf.attr time
* @dtf.attr.desc Specifies the amount of time to sleep. This time can be
* defined with the follow suffixes:
* <table border="1">
* <tr>
* <th>Value</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>s</td>
* <td>Seconds</td>
* </tr>
* <tr>
* <td>h</td>
* <td>Hours</td>
* </tr>
* <tr>
* <td>d</td>
* <td>Days</td>
* </tr>
* <tr>
* <td>m</td>
* <td>Months</td>
* </tr>
* </table>
*/
private String time = null;
public Sleep() { }
public void execute() throws DTFException {
try {
if (getLogger().isDebugEnabled())
getLogger().debug("Sleeping for " + getTime());
long value = TimeUtil.parseTime("time",getTime());
if (value < 0)
throw new DTFException("Sleep can not be negative.");
Thread.sleep(value);
} catch (InterruptedException e) {
throw new DTFException("Issue during sleep.",e);
}
}
public String getTime() throws ParseException { return replaceProperties(time); }
public void setTime(String time) { this.time = time; }
}
| bsd-3-clause |
thiaguten/spring-noxml-crud | src/main/java/br/com/thiaguten/spring/utils/EmailUtils.java | 4406 | /*
* #%L
* %%
* Copyright (C) 2015 - 2016 Thiago Gutenberg Carvalho da Costa.
* %%
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the Thiago Gutenberg Carvalho da Costa. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package br.com.thiaguten.spring.utils;
import java.net.IDN;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
/**
* Lógica copiada do Hibernate Validator (EmailValidator).
* <p>
* Eu não sei porque a mensagem da anotação
* {@link org.hibernate.validator.constraints.Email} não está sendo mostrada a
* partir do arquivo message.properties
*/
public abstract class EmailUtils {
private static final String ATOM = "[a-z0-9!#$%&'*+/=?^_`{|}~-]";
private static final String DOMAIN = ATOM + "+(\\." + ATOM + "+)*";
private static final String IP_DOMAIN = "\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\]";
/**
* Regular expression for the local part of an email address (everything before '@')
*/
private static final Pattern localPattern = java.util.regex.Pattern.compile(
ATOM + "+(\\." + ATOM + "+)*", CASE_INSENSITIVE
);
/**
* Regular expression for the domain part of an email address (everything after '@')
*/
private static final Pattern domainPattern = java.util.regex.Pattern.compile(
DOMAIN + "|" + IP_DOMAIN, CASE_INSENSITIVE
);
public static boolean isValid(CharSequence value) {
if (value == null || value.length() == 0) {
return true;
}
// split email at '@' and consider local and domain part separately;
// note a split limit of 3 is used as it causes all characters following to an (illegal) second @ character to
// be put into a separate array element, avoiding the regex application in this case since the resulting array
// has more than 2 elements
String[] emailParts = value.toString().split("@", 3);
if (emailParts.length != 2) {
return false;
}
// if we have a trailing dot in local or domain part we have an invalid email address.
// the regular expression match would take care of this, but IDN.toASCII drops trailing the trailing '.'
// (imo a bug in the implementation)
return !(emailParts[0].endsWith(".") || emailParts[1].endsWith(".")) && matchPart(emailParts[0], localPattern) && matchPart(emailParts[1], domainPattern);
}
private static boolean matchPart(String part, Pattern pattern) {
try {
part = IDN.toASCII(part);
} catch (IllegalArgumentException e) {
// occurs when the label is too long (>63, even though it should probably be 64 - see http://www.rfc-editor.org/errata_search.php?rfc=3696,
// practically that should not be a problem)
return false;
}
Matcher matcher = pattern.matcher(part);
return matcher.matches();
}
}
| bsd-3-clause |
NCIP/cagrid | cagrid/Software/core/caGrid/projects/transfer/src/org/cagrid/transfer/context/common/TransferServiceContextI.java | 1269 | package org.cagrid.transfer.context.common;
import java.rmi.RemoteException;
/**
* This class is autogenerated, DO NOT EDIT.
*
* This interface represents the API which is accessable on the grid service from the client.
*
* @created by Introduce Toolkit version 1.2
*
*/
public interface TransferServiceContextI {
public org.oasis.wsrf.lifetime.DestroyResponse destroy(org.oasis.wsrf.lifetime.Destroy params) throws RemoteException ;
public org.oasis.wsrf.lifetime.SetTerminationTimeResponse setTerminationTime(org.oasis.wsrf.lifetime.SetTerminationTime params) throws RemoteException ;
/**
* Returns the descriptor which can be used by the TransferClientHelper to download or upload the data.
*
*/
public org.cagrid.transfer.descriptor.DataTransferDescriptor getDataTransferDescriptor() throws RemoteException ;
public org.oasis.wsn.SubscribeResponse subscribe(org.oasis.wsn.Subscribe params) throws RemoteException ;
/**
* Get the status of the data.
*
*/
public org.cagrid.transfer.descriptor.Status getStatus() throws RemoteException ;
/**
* Set the status of the transfer data.
*
* @param status
*/
public void setStatus(org.cagrid.transfer.descriptor.Status status) throws RemoteException ;
}
| bsd-3-clause |
genome-vendor/apollo | src/java/apollo/gui/TableColumnChooser.java | 3734 | package apollo.gui;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import javax.swing.*;
import apollo.gui.*;
import apollo.config.*;
public class TableColumnChooser extends JPanel implements ActionListener {
ArrayListTransferHandler arrayListHandler;
FeatureProperty featureProperty;
DefaultListModel includedProps, excludedProps;
public TableColumnChooser(FeatureProperty fp) {
arrayListHandler = new ArrayListTransferHandler();
JList list1, list2;
JButton applyButton;
featureProperty = fp;
includedProps = new DefaultListModel();
excludedProps = new DefaultListModel();
dividePropertyStrings();
list1 = new JList(excludedProps);
list1.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list1.setTransferHandler(arrayListHandler);
list1.setDragEnabled(true);
JScrollPane list1View = new JScrollPane(list1);
list1View.setPreferredSize(new Dimension(200, 400));
JLabel header1 = new JLabel("Other columns");
JPanel panel1 = new JPanel();
panel1.setLayout(new BorderLayout());
panel1.add(header1, BorderLayout.NORTH);
panel1.add(list1View, BorderLayout.CENTER);
panel1.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
list2 = new JList(includedProps);
list2.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list2.setTransferHandler(arrayListHandler);
list2.setDragEnabled(true);
JScrollPane list2View = new JScrollPane(list2);
list2View.setPreferredSize(new Dimension(200, 400));
JLabel header2 = new JLabel("Displayed columns");
JPanel panel2 = new JPanel();
panel2.setLayout(new BorderLayout());
panel2.add(header2, BorderLayout.NORTH);
panel2.add(list2View, BorderLayout.CENTER);
panel2.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
applyButton = new JButton("Apply");
applyButton.addActionListener(this);
setLayout(new BorderLayout());
JLabel info = new JLabel("Drag items between lists to add/remove and within list to reorder columns");
add(info, BorderLayout.NORTH);
add(panel1, BorderLayout.LINE_START);
add(panel2, BorderLayout.LINE_END);
add(applyButton, BorderLayout.SOUTH);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
public void actionPerformed(ActionEvent e) {
Vector columns = new Vector();
Enumeration includedPropsEnum = includedProps.elements();
while(includedPropsEnum.hasMoreElements()) {
String name = (String)includedPropsEnum.nextElement();
//System.out.println("column= " + name);
columns.addElement(new ColumnProperty(name));
}
featureProperty.setColumns(columns);
}
private void dividePropertyStrings() {
Enumeration allColumnNameEnum = DetailInfo.getAllPropertyStrings();
Vector includedColumns = featureProperty.getColumns();
HashSet includedColumnNames = new HashSet();
for (int i=0;i<includedColumns.size();i++) {
ColumnProperty cp = (ColumnProperty)includedColumns.elementAt(i);
includedColumnNames.add(cp.getHeading());
}
while(allColumnNameEnum.hasMoreElements()) {
String name = (String)allColumnNameEnum.nextElement();
if (!includedColumnNames.contains(name)) {
//System.out.println("Excluded: " + name);
excludedProps.addElement(name);
}
}
// Add them separately so they are in order
Iterator incIter = includedColumns.iterator();
while(incIter.hasNext()) {
String name = ((ColumnProperty)incIter.next()).getHeading();
//System.out.println("Included: " + name);
includedProps.addElement(name);
}
}
}
| bsd-3-clause |
TheFakeMontyOnTheRun/derelict | derelict-core-java/src/main/java/br/odb/derelict/core/items/BlowTorch.java | 2287 | package br.odb.derelict.core.items;
import br.odb.gameworld.ActiveItem;
import br.odb.gameworld.CharacterActor;
import br.odb.gameworld.Item;
import br.odb.gameworld.exceptions.ItemActionNotSupportedException;
public class BlowTorch extends ActiveItem implements Toxic, Destructive {
public static final String NAME = "blowtorch";
public static final float DEFAULT_FUEL_USAGE = 10.0f;
public static final float DEFAULT_IDLE_FUEL_USAGE = 0.0001f;
public static final float DEFAULT_TOXICITY = 0.25f;
public static final int DEFAULT_DESTRUCTIVE_POWER = 50;
public static final String ORIGINAL_DESCRIPTION = "precision vintage-but-rather-well-kept metal cutter (fuel: %.2f).";
float fuel;
public BlowTorch(float initialFluel) {
super( BlowTorch.NAME );
fuel = initialFluel;
updateFuelStatus();
}
@Override
public String getTurnOnSound() {
return "blowtorch-turned-on";
}
@Override
public void use(CharacterActor user) throws ItemActionNotSupportedException {
throw new ItemActionNotSupportedException( "This can't be used on it's on." + ( isActive() ? " Go look for something to cutout with this." : " Activate it and use it on other stuff." ) );
}
@Override
public String getUseItemSound() {
return isActive() ? "blowtorch-used" : "";
}
public float getFuel() {
return fuel;
}
@Override
public ActiveItem toggle() {
super.toggle();
updateFuelStatus();
return this;
}
private void updateFuelStatus() {
if (fuel < 0.0f) {
fuel = 0.0f;
}
weight = 20 + (fuel / 10);
setDescription(String.format(ORIGINAL_DESCRIPTION, fuel ) );
setIsDepleted(fuel <= 0.0f);
setActive( isActive() && ( !isDepleted() ) );
}
@Override
public void wasUsedOn(Item item1) throws ItemActionNotSupportedException {
if ( isActive() ) {
super.wasUsedOn(item1);
fuel -= DEFAULT_FUEL_USAGE;
updateFuelStatus();
} else {
throw new ItemActionNotSupportedException( "Inactive" );
}
}
@Override
public void update(long MS) {
if (isActive()) {
fuel -= DEFAULT_IDLE_FUEL_USAGE * MS;
updateFuelStatus();
}
}
@Override
public float getToxicity() {
return isActive() ? DEFAULT_TOXICITY : 0.0f;
}
@Override
public float getDestructivePower() {
return DEFAULT_DESTRUCTIVE_POWER;
}
}
| bsd-3-clause |
codeaudit/Foundry | Components/LearningCore/Test/gov/sandia/cognition/statistics/distribution/GammaDistributionTest.java | 10531 | /*
* File: GammaDistributionTest.java
* Authors: Kevin R. Dixon
* Company: Sandia National Laboratories
* Project: Cognitive Foundry
*
* Copyright October 2, 2007, Sandia Corporation. Under the terms of Contract
* DE-AC04-94AL85000, there is a non-exclusive license for use of this work by
* or on behalf of the U.S. Government. Export of this program may require a
* license from the United States Government. See CopyrightHistory.txt for
* complete details.
*
*/
package gov.sandia.cognition.statistics.distribution;
import gov.sandia.cognition.math.matrix.Vector;
import gov.sandia.cognition.statistics.SmoothUnivariateDistributionTestHarness;
/**
* Unit testsf or class {@link GammaDistribution}.
*
* @author Kevin R. Dixon
*/
public class GammaDistributionTest
extends SmoothUnivariateDistributionTestHarness
{
/**
* Constructor
* @param testName name
*/
public GammaDistributionTest(
String testName )
{
super( testName );
}
@Override
public GammaDistribution createInstance()
{
double shape = RANDOM.nextDouble() * 5 + 2;
double scale = RANDOM.nextDouble() * 5 + 1;
return new GammaDistribution( shape, scale );
}
/**
* Default constructor
*/
public void testDefaultConstructor()
{
System.out.println( "Default constructor" );
GammaDistribution g = new GammaDistribution.CDF();
assertEquals( GammaDistribution.DEFAULT_SHAPE, g.getShape() );
assertEquals( GammaDistribution.DEFAULT_SCALE, g.getScale() );
g = new GammaDistribution.PDF();
assertEquals( GammaDistribution.DEFAULT_SHAPE, g.getShape() );
assertEquals( GammaDistribution.DEFAULT_SCALE, g.getScale() );
}
@Override
public void testPDFKnownValues()
{
System.out.println( "PDF.evaluate" );
// I got these values from octave's gamma_pdf() function
// However, octave's second parameter is INVERTED from my expecatation
// Thus, GammaDistribution.evaluate( x, dof, theta ) == gamma_pdf(x, dof, 1/theta)
assertEquals( 0.3678794412, GammaDistribution.PDF.evaluate( 1.0, 1.0, 1.0 ), TOLERANCE );
assertEquals( 0.0497870684, GammaDistribution.PDF.evaluate( 3.0, 1.0, 1.0 ), TOLERANCE );
assertEquals( 0.1493612051, GammaDistribution.PDF.evaluate( 3.0, 2.0, 1.0 ), TOLERANCE );
assertEquals( 0.1673476201, GammaDistribution.PDF.evaluate( 3.0, 2.0, 2.0 ), TOLERANCE );
assertEquals( 0.0396463705, GammaDistribution.PDF.evaluate( 3.0, 4.5, 2.0 ), TOLERANCE );
assertEquals( 0.0871725152, GammaDistribution.PDF.evaluate( 5.0, 4.5, 2.0 ), TOLERANCE );
}
/**
* Test of getShape method, of class gov.sandia.cognition.learning.util.statistics.distribution.GammaDistribution.
*/
public void testGetShape()
{
System.out.println( "getShape" );
double shape = RANDOM.nextDouble() * 5.0;
double scale = RANDOM.nextDouble() * 5.0;
GammaDistribution.PDF instance = new GammaDistribution.PDF( shape, scale );
assertEquals( shape, instance.getShape() );
}
/**
* Test of setShape method, of class gov.sandia.cognition.learning.util.statistics.distribution.GammaDistribution.
*/
public void testSetShape()
{
System.out.println( "setShape" );
GammaDistribution.PDF instance = this.createInstance().getProbabilityFunction();
assertTrue( instance.getShape() > 0.0 );
double s2 = instance.getShape() + 1.0;
instance.setShape( s2 );
assertEquals( s2, instance.getShape() );
try
{
instance.setShape( 0.0 );
fail( "Shape must be > 0.0" );
}
catch (Exception e)
{
System.out.println( "Good: " + e );
}
}
/**
* Test of getScale method, of class gov.sandia.cognition.learning.util.statistics.distribution.GammaDistribution.
*/
public void testGetScale()
{
System.out.println( "getScale" );
double shape = RANDOM.nextDouble() * 5.0;
double scale = RANDOM.nextDouble() * 5.0;
GammaDistribution.PDF instance = new GammaDistribution.PDF( shape, scale );
assertEquals( scale, instance.getScale() );
}
/**
* Test of setScale method, of class gov.sandia.cognition.learning.util.statistics.distribution.GammaDistribution.
*/
public void testSetScale()
{
System.out.println( "setScale" );
GammaDistribution instance = this.createInstance();
assertTrue( instance.getScale() > 0.0 );
double s2 = instance.getScale() + 1.0;
instance.setScale( s2 );
assertEquals( s2, instance.getScale() );
assertEquals(1.0 / s2, instance.getRate(), TOLERANCE);
try
{
instance.setScale( 0.0 );
fail( "Scale must be > 0.0" );
}
catch (Exception e)
{
System.out.println( "Good: " + e );
}
}
/**
* Test of getRate method, of class GammaDistribution.
*/
public void testGetRate()
{
System.out.println("getRate");
double shape = RANDOM.nextDouble() * 5.0;
double scale = RANDOM.nextDouble() * 5.0;
double rate = 1.0 / scale;
GammaDistribution.PDF instance = new GammaDistribution.PDF(shape, scale);
assertEquals(rate, instance.getRate(), TOLERANCE);
}
/**
* Test of setRate method, of class GammaDistribution.
*/
public void testSetRate()
{
System.out.println("setRate");
GammaDistribution instance = this.createInstance();
assertTrue(instance.getRate() > 0.0);
double r2 = instance.getRate() + 1.0;
instance.setRate(r2);
assertEquals(r2, instance.getRate(), TOLERANCE);
assertEquals(1.0 / r2, instance.getScale(), TOLERANCE);
boolean exceptionThrown = false;
try
{
instance.setRate(0.0);
}
catch (Exception e)
{
exceptionThrown = true;
}
finally
{
assertTrue(exceptionThrown);
}
}
@Override
public void testCDFKnownValues()
{
System.out.println( "CDF.evaluate" );
// I got these values from octave's gamma_cdf() function
// However, octave's second parameter is INVERTED from my expecatation
// Thus, GammaDistribution.CDF.evaluate( x, dof, theta ) == gamma_cdf(x, dof, 1/theta)
assertEquals( 0.6321205588, GammaDistribution.CDF.evaluate( 1.0, 1.0, 1.0 ), TOLERANCE );
assertEquals( 0.8008517625, GammaDistribution.CDF.evaluate( 3.0, 2.0, 1.0 ), TOLERANCE );
assertEquals( 0.0549772417, GammaDistribution.CDF.evaluate( 1.5, 2.0, 4.0 ), TOLERANCE );
assertEquals( 0.0231152878, GammaDistribution.CDF.evaluate( 1.5, 3.0, 2.5 ), TOLERANCE );
}
@Override
public void testKnownConvertToVector()
{
GammaDistribution cdf = this.createInstance();
Vector x = cdf.convertToVector();
assertEquals( 2, x.getDimensionality() );
assertEquals( cdf.getShape(), x.getElement( 0 ) );
assertEquals( cdf.getScale(), x.getElement( 1 ) );
}
@Override
public void testPDFConstructors()
{
System.out.println( "PDF Constructors" );
GammaDistribution.PDF f = new GammaDistribution.PDF();
assertEquals( GammaDistribution.DEFAULT_SCALE, f.getScale() );
assertEquals( GammaDistribution.DEFAULT_SHAPE, f.getShape() );
double shape = Math.abs( RANDOM.nextDouble() );
double scale = Math.abs( RANDOM.nextDouble() );
f = new GammaDistribution.PDF( shape, scale );
assertEquals( shape, f.getShape() );
assertEquals( scale, f.getScale() );
GammaDistribution.PDF f2 = new GammaDistribution.PDF( f );
assertEquals( f.getShape(), f2.getShape() );
assertEquals( f.getScale(), f2.getScale() );
}
@Override
public void testDistributionConstructors()
{
System.out.println( "Constructors" );
GammaDistribution f = new GammaDistribution();
assertEquals( GammaDistribution.DEFAULT_SCALE, f.getScale() );
assertEquals( GammaDistribution.DEFAULT_SHAPE, f.getShape() );
double shape = Math.abs( RANDOM.nextDouble() );
double scale = Math.abs( RANDOM.nextDouble() );
f = new GammaDistribution( shape, scale );
assertEquals( shape, f.getShape() );
assertEquals( scale, f.getScale() );
GammaDistribution f2 = new GammaDistribution( f );
assertEquals( f.getShape(), f2.getShape() );
assertEquals( f.getScale(), f2.getScale() );
}
@Override
public void testCDFConstructors()
{
System.out.println( "CDF Constructors" );
GammaDistribution.CDF f = new GammaDistribution.CDF();
assertEquals( GammaDistribution.DEFAULT_SCALE, f.getScale() );
assertEquals( GammaDistribution.DEFAULT_SHAPE, f.getShape() );
double shape = Math.abs( RANDOM.nextDouble() );
double scale = Math.abs( RANDOM.nextDouble() );
f = new GammaDistribution.CDF( shape, scale );
assertEquals( shape, f.getShape() );
assertEquals( scale, f.getScale() );
GammaDistribution.CDF f2 = new GammaDistribution.CDF( f );
assertEquals( f.getShape(), f2.getShape() );
assertEquals( f.getScale(), f2.getScale() );
}
/**
* toString
*/
public void testToString()
{
System.out.println( "toString" );
GammaDistribution gamma = this.createInstance();
System.out.println( "Gamma: " + gamma.toString() );
assertNotNull( gamma.toString() );
}
/**
* Learner
*/
public void testLearner()
{
System.out.println( "Learner" );
GammaDistribution.MomentMatchingEstimator learner =
new GammaDistribution.MomentMatchingEstimator();
this.distributionEstimatorTest(learner);
}
/**
* Weighted learner
*/
public void testWeightedLearner()
{
System.out.println( "Weighted Learner" );
GammaDistribution.WeightedMomentMatchingEstimator learner =
new GammaDistribution.WeightedMomentMatchingEstimator();
this.weightedDistributionEstimatorTest(learner);
}
}
| bsd-3-clause |
motech/motech-server-pillreminder | platform/server-bundle/src/main/java/org/motechproject/server/ui/impl/UIFrameworkServiceImpl.java | 2385 | package org.motechproject.server.ui.impl;
import org.motechproject.osgi.web.ModuleRegistrationData;
import org.motechproject.osgi.web.UIFrameworkService;
import org.motechproject.server.ui.ex.AlreadyRegisteredException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@Service("uiFrameworkService")
public class UIFrameworkServiceImpl implements UIFrameworkService {
private static final Logger LOG = LoggerFactory.getLogger(UIFrameworkServiceImpl.class);
private Map<String, ModuleRegistrationData> individuals = new HashMap<>();
private Map<String, ModuleRegistrationData> links = new HashMap<>();
@Override
public void registerModule(ModuleRegistrationData module) {
String moduleName = module.getModuleName();
if (links.containsKey(moduleName) || individuals.containsKey(moduleName)) {
throw new AlreadyRegisteredException("Module already registered");
}
if (module.getSubMenu().isEmpty()) {
links.put(moduleName, module);
} else {
individuals.put(moduleName, module);
}
LOG.debug(String.format("Module %s registered in UI framework", module.getModuleName()));
}
@Override
public void unregisterModule(String moduleName) {
if (links.containsKey(moduleName)) {
links.remove(moduleName);
}
if (individuals.containsKey(moduleName)) {
individuals.remove(moduleName);
}
LOG.debug(String.format("Module %s unregistered from UI framework", moduleName));
}
@Override
public Map<String, Collection<ModuleRegistrationData>> getRegisteredModules() {
Map<String, Collection<ModuleRegistrationData>> map = new HashMap<>(2);
map.put(MODULES_WITH_SUBMENU, individuals.values());
map.put(MODULES_WITHOUT_SUBMENU, links.values());
return map;
}
@Override
public ModuleRegistrationData getModuleData(String moduleName) {
ModuleRegistrationData module = null;
if (links.containsKey(moduleName)) {
module = links.get(moduleName);
} else if (individuals.containsKey(moduleName)) {
module = individuals.get(moduleName);
}
return module;
}
}
| bsd-3-clause |
arnaudsj/carrot2 | core/carrot2-util-text/src-test/org/carrot2/text/preprocessing/filter/GenitiveLabelFilterTest.java | 2017 |
/*
* Carrot2 project.
*
* Copyright (C) 2002-2010, Dawid Weiss, Stanisław Osiński.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the repository checkout or at:
* http://www.carrot2.org/carrot2.LICENSE
*/
package org.carrot2.text.preprocessing.filter;
import org.carrot2.text.preprocessing.LabelFilterProcessor;
import org.carrot2.text.preprocessing.LabelFilterTestBase;
import org.junit.Test;
/**
* Test cases for {@link GenitiveLabelFilter}.
*/
public class GenitiveLabelFilterTest extends LabelFilterTestBase
{
@Override
protected void initializeFilters(LabelFilterProcessor filterProcessor)
{
filterProcessor.genitiveLabelFilter.enabled = true;
}
@Test
public void testEmpty()
{
final int [] expectedLabelsFeatureIndex = new int [] {};
check(expectedLabelsFeatureIndex);
}
@Test
public void testNoGenitiveWords()
{
createDocuments("abc . abc", "abcd . abcd");
final int [] expectedLabelsFeatureIndex = new int []
{
0, 1
};
check(expectedLabelsFeatureIndex);
}
@Test
public void testGenitiveWords()
{
createDocuments("abcs' . abcs'", "abcd`s . abcd`s");
final int [] expectedLabelsFeatureIndex = new int [] {};
check(expectedLabelsFeatureIndex);
}
@Test
public void testNoGenitiveEndingPhrases()
{
createDocuments("country's minister'll . country's minister'll");
final int [] expectedLabelsFeatureIndex = new int []
{
wordIndices.get("minister'll"), 2
};
check(expectedLabelsFeatureIndex, 1);
}
@Test
public void testGenitiveEndingPhrases()
{
createDocuments("country minister`s . country's minister`s");
final int [] expectedLabelsFeatureIndex = new int []
{
wordIndices.get("country")
};
check(expectedLabelsFeatureIndex);
}
}
| bsd-3-clause |
FuseMCNetwork/ZCore | src/main/java/net/fusemc/zcore/featureSystem/features/spectatorFeature/SpectatorListener.java | 5977 | package net.fusemc.zcore.featureSystem.features.spectatorFeature;
import com.google.common.collect.Lists;
import net.fusemc.zcore.util.LocationUtil;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.*;
import java.util.List;
import java.util.Random;
public class SpectatorListener implements Listener {
private SpectatorController controller;
public SpectatorListener(SpectatorController controller) {
this.controller = controller;
}
@EventHandler
public void onHunger(FoodLevelChangeEvent e) {
if (controller.getSpectators().contains(e.getEntity())) {
e.setCancelled(true);
}
}
@EventHandler
public void onGetDamage(EntityDamageEvent e) {
if (controller.getSpectators().contains(e.getEntity())) {
e.setCancelled(true);
if (e.getCause() == EntityDamageEvent.DamageCause.VOID) {
Player random = SpectatorController.getRandomPlayerWithoutACertainPlayer((Player) e.getEntity());
if (controller.getSpawn() != null || random == null) {
e.getEntity().teleport(controller.getSpawn());
} else {
e.getEntity().teleport(random);
}
}
}
}
@EventHandler
public void onHitPlayer(EntityDamageByEntityEvent e) {
if (controller.getSpectators().contains(e.getDamager())){
e.setCancelled(true);
}
}
@EventHandler
public void onInteract(PlayerInteractEvent e) {
if (controller.getSpectators().contains(e.getPlayer())) {
e.setCancelled(true);
if (e.getItem() == null || e.getItem().getItemMeta() == null || e.getItem().getItemMeta().getDisplayName() == null) return;
String itemName = e.getItem().getItemMeta().getDisplayName();
if (itemName.equals(SpectatorController.LOBBYNAME)) {
e.getPlayer().kickPlayer("lobby");
} else if (itemName.equals(SpectatorController.TELEPORTERNAME)) {
e.getPlayer().openInventory(controller.getCompassInventory());
}
}
}
@EventHandler
public void onItemDrop(PlayerDropItemEvent e) {
if (controller.getSpectators().contains(e.getPlayer())) {
e.getItemDrop().remove();
controller.giveItems(e.getPlayer());
}
}
@EventHandler
public void onPickUp(PlayerPickupItemEvent e) {
if (controller.getSpectators().contains(e.getPlayer()))
e.setCancelled(true);
}
@EventHandler
public void onInventoryClick(InventoryClickEvent e) {
if (controller.getSpectators().contains((Player) e.getWhoClicked())) {
if (e.getClickedInventory().getName() != null && e.getClickedInventory().getName().equals(SpectatorController.TELEPORTERNAME)) {
if (e.getCurrentItem() != null && e.getCurrentItem().getItemMeta() != null && e.getCurrentItem().getItemMeta().getDisplayName() != null) {
e.getWhoClicked().teleport(Bukkit.getPlayerExact(ChatColor.stripColor(e.getCurrentItem().getItemMeta().getDisplayName())).getLocation());
}
}
e.setCancelled(true);
}
}
@EventHandler
public void onItemConsume(PlayerItemConsumeEvent e)
{
if (controller.getSpectators().contains(e.getPlayer())) {
e.setCancelled(true);
}
}
@EventHandler
public void onPlayerXPChange(PlayerExpChangeEvent e)
{
if (controller.getSpectators().contains(e.getPlayer())) {
e.setAmount(0);
}
}
@EventHandler
public void onRespawn(PlayerRespawnEvent e) {
if (controller.getSpectators().contains(e.getPlayer())) {
Player p = e.getPlayer();
p.setAllowFlight(true);
p.setFlying(true);
controller.giveItems(p);
if (controller.getSpawn() != null) {
e.setRespawnLocation(LocationUtil.centerLocation(controller.getSpawn()));
} else {
e.setRespawnLocation(p.getLocation());
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerQuit(PlayerQuitEvent e) {
if (controller.getSpectators().contains(e.getPlayer())) {
controller.getSpectators().remove(e.getPlayer());
}
if (controller.getPlayingPlayers().contains(e.getPlayer())) {
controller.getPlayingPlayers().remove(e.getPlayer());
}
controller.updateCompassInventory();
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onKick(PlayerKickEvent e) {
if (controller.getSpectators().contains(e.getPlayer())) {
controller.getSpectators().remove(e.getPlayer());
}
if (controller.getPlayingPlayers().contains(e.getPlayer())) {
controller.getPlayingPlayers().remove(e.getPlayer());
}
controller.updateCompassInventory();
}
//if player joins hide all spetators for him
// BUT
//he is a playing player
@EventHandler
public void onPlayerJoin(PlayerJoinEvent e) {
controller.getPlayingPlayers().add(e.getPlayer());
for (Player p : controller.getSpectators()) {
e.getPlayer().hidePlayer(p);
}
}
@EventHandler
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
if(controller.getSpectators().contains(event.getPlayer())) {
event.setCancelled(true);
}
}
}
| bsd-3-clause |
beyama/android-a2r-client | src/eu/addicted2random/a2rclient/osc/DoubleType.java | 867 | package eu.addicted2random.a2rclient.osc;
import eu.addicted2random.a2rclient.utils.Range;
public class DoubleType extends NumberType {
public DoubleType(Range range) {
super(Double.class, range);
}
public DoubleType() {
this(null);
}
@Override
public char getTypeCode(Object object) {
if(object == null) return 'N';
return 'd';
}
@Override
public String getTypeName() {
return "double";
}
@Override
public Type setRange(Range range) {
return new DoubleType(range);
}
@Override
public Object cast(Object object) {
if(object == null)
return null;
if(object instanceof Double)
return object;
if(object instanceof Number)
return ((Number)object).doubleValue();
throw new ClassCastException(String.format("Can't cast '%s' to Double", object.getClass().getName()));
}
}
| bsd-3-clause |
NCIP/calims | calims2-api/test/unit/java/gov/nih/nci/calims2/business/administration/contactinformation/ContactInformationValidatorMockup.java | 1921 | /*L
* Copyright Moxie Informatics.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/calims/LICENSE.txt for details.
*/
/**
*
*/
package gov.nih.nci.calims2.business.administration.contactinformation;
import java.util.HashSet;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.metadata.BeanDescriptor;
import gov.nih.nci.calims2.business.util.validation.ConstraintViolationImpl;
import gov.nih.nci.calims2.domain.administration.ContactInformation;
/**
* @author connollym@moxieinformatics.com
*
*/
public class ContactInformationValidatorMockup implements Validator {
private ContactInformation testEntity;
/**
* @return testEntity The entity to return.
*/
public ContactInformation getEntity() {
return testEntity;
}
/**
* {@inheritDoc}
*/
public BeanDescriptor getConstraintsForClass(Class<?> clazz) {
return null;
}
/**
* {@inheritDoc}
*/
public <T> T unwrap(Class<T> contactInformation) {
return null;
}
/**
* {@inheritDoc}
*/
public <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) {
testEntity = (ContactInformation) object;
Set<ConstraintViolation<T>> violations = new HashSet<ConstraintViolation<T>>();
if (testEntity.getName() == null) {
ConstraintViolationImpl<T> violation = new ConstraintViolationImpl<T>();
violation.setMessage("Name required.");
violations.add(violation);
}
return violations;
}
/**
* {@inheritDoc}
*/
public <T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyName, Class<?>... groups) {
return null;
}
/**
* {@inheritDoc}
*/
public <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) {
return null;
}
}
| bsd-3-clause |
janlugt/HipG | src/hipg/compile/NotificationCall.java | 4112 | /**
* Copyright (c) 2010, 2011 Vrije Universiteit Amsterdam.
* Written by Ela Krepska e.l.krepska@vu.nl.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package hipg.compile;
import hipg.compile.Simulator.StackElement;
import java.util.ArrayList;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ClassGen;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.ObjectType;
public class NotificationCall {
private static int uniqId = 0;
/** Class that the method containing this blocking call is in. */
private final ClassGen cg;
/** Handle of this blocking call. */
private final InstructionHandle handle;
/** The call. */
private final InvokeInstruction invoke;
/** Stack before the call. */
private final ArrayList<StackElement> stack;
/** Called notification method. */
private final NotificationMethod notificationMethod;
/** Unique id */
private final int id = uniqId++;
/** Creates a blocking call. */
public NotificationCall(ClassGen cg, InstructionHandle handle, InvokeInstruction invoke,
ArrayList<StackElement> stack, NotificationMethod notificationMethod) {
this.cg = cg;
this.handle = handle;
this.invoke = invoke;
this.stack = stack;
this.notificationMethod = notificationMethod;
}
public InstructionHandle getHandle() {
return handle;
}
public InvokeInstruction getInvoke() {
return invoke;
}
public ArrayList<StackElement> getStack() {
return stack;
}
public String getCalledMethodName() {
return invoke.getMethodName(cg.getConstantPool());
}
public NotificationMethod getNotificationMethod() {
return notificationMethod;
}
public int getId() {
return id;
}
@Override
public String toString() {
return toString(false);
}
public String toString(boolean detail) {
StringBuilder sb = new StringBuilder();
sb.append(invoke.getMethodName(cg.getConstantPool()));
if (detail) {
// print stack
sb.append("[");
sb.append("stack: ");
if (stack.size() == 0) {
sb.append("empty");
} else {
for (int i = 0; i < stack.size(); i++)
sb.append(stack.get(i) + (i + 1 < stack.size() ? ", " : ""));
}
}
return sb.toString();
}
public static NotificationMethod checkNonBlockingCall(Simulator simulator, InvokeInstruction invoke,
ArrayList<NotificationMethod> notificationMethods) throws ClassNotFoundException {
/*
* check if called on a synchronizer
*/
final String calledClassName = ((ObjectType) simulator.getReferenceType(invoke)).getClassName();
final JavaClass calledClass = ClassRepository.lookupClass(calledClassName);
if (!calledClass.instanceOf(ClassRepository.getSynchronizerInterface())) {
return null;
}
/*
* check if the call refers to one of the notification methods
* identified in the target class
*/
final String methodName = simulator.getMethodName(invoke);
NotificationMethod notificationMethod = null;
for (NotificationMethod nm : notificationMethods) {
Method method = nm.getMethod();
if (method.getName().equals(methodName) && method.getSignature().equals(simulator.getSignature(invoke))) {
if (notificationMethod != null) {
throw new RuntimeException("Two notifications method fit the call to " + methodName + " on "
+ calledClassName + " with signature " + method.getSignature());
}
notificationMethod = nm;
}
}
return notificationMethod;
}
}
| bsd-3-clause |
frc-4931/2014-Robot | CompetitionRobot/src/org/frc4931/robot/command/groups/CompleteCapture.java | 577 | package org.frc4931.robot.command.groups;
import org.frc4931.robot.Subsystems;
import org.frc4931.robot.command.SetState;
import org.frc4931.robot.command.TwoState.State;
import org.frc4931.robot.command.roller.StopRoller;
import edu.wpi.first.wpilibj.command.CommandGroup;
/**
* Raises the arm and stops the roller.
*/
public class CompleteCapture extends CommandGroup{
/**
* Constructs the command group.
*/
public CompleteCapture() {
// addParallel(new RollIn());
addSequential(new SetState(Subsystems.arm, State.UP));
addSequential(new StopRoller());
}
}
| bsd-3-clause |
Flux7Labs/cassandra-training | hector/src/main/java/com/flux7/CassandraMultipleReadDemo.java | 2338 | package com.flux7;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.Row;
import me.prettyprint.hector.api.beans.Rows;
import me.prettyprint.hector.api.exceptions.HectorException;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.mutation.Mutator;
import me.prettyprint.hector.api.query.MultigetSliceQuery;
import me.prettyprint.hector.api.query.QueryResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CassandraMultipleReadDemo extends CassandraConfig{
private static final Logger LOGGER = LoggerFactory.getLogger(CassandraMultipleReadDemo.class);
private static StringSerializer stringSerializer = StringSerializer.get();
public static void main(String[] args) throws Exception {
Cluster cluster = HFactory.getOrCreateCluster("test", CASSANDRA_ADDRESS);
Keyspace keyspaceOperator = HFactory.createKeyspace("test", cluster);
try {
MultigetSliceQuery<String, String, String> multigetSliceQuery =
HFactory.createMultigetSliceQuery(keyspaceOperator, stringSerializer, stringSerializer, stringSerializer);
multigetSliceQuery.setColumnFamily("users");
multigetSliceQuery.setKeys("Brenda", "thrift","Alex", "BOB", "fake_key_4");
// set null range for empty byte[] on the underlying predicate
multigetSliceQuery.setRange(null, null, false, 3);
System.out.println(multigetSliceQuery);
QueryResult<Rows<String, String, String>> result = multigetSliceQuery.execute();
Rows<String, String, String> orderedRows = result.get();
LOGGER.info("Contents of rows: \n");
LOGGER.info("---------------------------------------------------");
for (Row<String, String, String> r : orderedRows) {
LOGGER.info(" " + r);
}
LOGGER.info("---------------------------------------------------");
} catch (HectorException he) {
he.printStackTrace();
}
cluster.getConnectionManager().shutdown();
}
}
| bsd-3-clause |
n-at/availability-monitor | src/main/java/ru/doublebyte/availabilitymonitor/storages/TestResultStorage.java | 2102 | package ru.doublebyte.availabilitymonitor.storages;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.doublebyte.availabilitymonitor.entities.TestResult;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
public class TestResultStorage extends AbstractStorage<TestResult> {
private static final Logger logger = LoggerFactory.getLogger(TestResultStorage.class);
private static final Random RANDOM = new Random();
private Map<Long, TestResult> testResults = new ConcurrentHashMap<>();
public TestResultStorage() {
try {
setFileName("test_result.json");
testResults = load(new TypeReference<Map<Long, TestResult>>() {});
} catch (Exception e) {
logger.error("TestResults load error", e);
}
}
///////////////////////////////////////////////////////////////////////////
@Override
public List<TestResult> getAll() {
return new ArrayList<>(testResults.values());
}
@Override
public TestResult get(Long id) {
if (!testResults.containsKey(id)) {
throw new IllegalArgumentException(String.format("TestResult with id %d not found", id));
}
return testResults.get(id);
}
@Override
public TestResult save(TestResult testResult) {
Long id = RANDOM.nextLong();
if (testResult.getId() != null) {
id = testResult.getId();
} else {
testResult.setId(id);
}
testResults.put(id, testResult);
save(testResults);
return testResult;
}
@Override
public void delete(Long id) {
if (!testResults.containsKey(id)) {
throw new IllegalArgumentException(String.format("TestResult with id %d not found", id));
}
testResults.remove(id);
save(testResults);
}
@Override
public void delete(TestResult value) {
delete(value.getId());
}
}
| bsd-3-clause |
vactowb/jbehave-core | examples/trader/src/main/java/org/jbehave/examples/trader/stories/ExamplesTableLoadedFromClasspath.java | 166 | package org.jbehave.examples.trader.stories;
import org.jbehave.examples.trader.TraderStory;
public class ExamplesTableLoadedFromClasspath extends TraderStory {
}
| bsd-3-clause |
messagebird/java-rest-api | api/src/main/java/com/messagebird/objects/voicecalls/VoiceCallFlowResponse.java | 916 | package com.messagebird.objects.voicecalls;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
public class VoiceCallFlowResponse implements Serializable {
private static final long serialVersionUID = -3429781513863789117L;
private List<VoiceCallFlow> data;
@JsonProperty("_links")
private Map<String, String> links;
public List<VoiceCallFlow> getData() {
return data;
}
public void setData(List<VoiceCallFlow> data) {
this.data = data;
}
public Map<String, String> getLinks() {
return links;
}
public void setLinks(Map<String, String> links) {
this.links = links;
}
@Override
public String toString() {
return "VoiceCallResponse{" +
"data=" + data +
", links=" + links +
'}';
}
}
| bsd-3-clause |
ViDA-NYU/data-polygamy | data-polygamy/src/main/java/edu/nyu/vida/data_polygamy/resolution/ToCity.java | 875 | /* Copyright (C) 2016 New York University
This file is part of Data Polygamy which is released under the Revised BSD License
See file LICENSE for full license details. */
package edu.nyu.vida.data_polygamy.resolution;
import java.util.ArrayList;
public class ToCity implements SpatialResolution {
private int[] positions;
public ToCity(int[] spatialPos) {
this.positions = spatialPos;
}
@Override
public ArrayList<Integer> translate(String[] input) {
// assuming all the neighborhood and grid data is from NYC
ArrayList<Integer> output = new ArrayList<Integer>();
for (int i = 0; i < positions.length; i++)
output.add(0);
return output;
}
@Override
public int translate(int[] input) {
// assuming all the neighborhood and grid data is from NYC
return 0;
}
}
| bsd-3-clause |
marrocamp/nasa-VICAR | vos/java/jpl/mipl/io/vicar/test/TestXMLWrite.java | 1995 | package jpl.mipl.io.vicar.test;
import java.io.*;
import jpl.mipl.io.vicar.*;
import org.w3c.dom.*;
import org.apache.xml.serialize.*;
/**
* TestXMLWrite program. Takes a VICAR file, and creates an XML file with
* the contents of it. The XML file will not be pretty (i.e. no formatting
* is done). The original label is (optionally) written as text to a third
* file, for ease of comparison.
* <p>
* Note: <em>This program has dependencies on the Xerces XML parser.</em>
* These dependencies should be removed when JDK 1.4 becomes available.
*/
public class TestXMLWrite
{
public static void main(String argv[]) throws Exception
{
if (argv.length != 2 && argv.length != 3) {
System.out.println("Usage:");
System.out.println("% java jpl.mipl.io.vicar.test.TestXMLWrite vicar_file xml_file {text_file}");
System.out.println("Takes a VICAR file and writes the label as XML");
System.out.println("and optionally writes the VICAR label as text");
System.exit(0);
}
Document doc = new org.apache.xerces.dom.DocumentImpl();
try {
VicarInputFile vif = new VicarInputFile(argv[0]);
VicarLabel vl = vif.getVicarLabel();
System.out.println("VICAR label:");
System.out.println(vl);
if (argv.length == 3)
new PrintStream(new FileOutputStream(argv[2])).println(vl);
Node xml = vl.toXML(doc);
doc.appendChild(xml);
SerializerFactory factory =
SerializerFactory.getSerializerFactory("xml");
// Write to stdout
System.out.println("XML label:");
Serializer serializer = factory.makeSerializer(
System.out, new OutputFormat(doc));
serializer.asDOMSerializer().serialize(doc);
System.out.println();
// Write to output file
serializer = factory.makeSerializer(
new FileOutputStream(argv[1]), new OutputFormat(doc));
serializer.asDOMSerializer().serialize(doc);
} catch (Exception e) {
System.out.println("me: " + e);
e.printStackTrace();
}
}
}
| bsd-3-clause |
AIT-Rescue/AIT-Rescue | AgentDevelopmentKit/src/main/java/adk/launcher/option/OptionServer.java | 476 | package adk.launcher.option;
import rescuecore2.Constants;
import rescuecore2.config.Config;
public class OptionServer extends Option {
@Override
public String getKey() {
return "-s";
}
@Override
public void setValue(Config config, String[] datas) {
if (datas.length == 3) {
config.setValue(Constants.KERNEL_HOST_NAME_KEY, datas[1]);
config.setValue(Constants.KERNEL_PORT_NUMBER_KEY, datas[2]);
}
}
} | bsd-3-clause |
dimitarp/basex | basex-core/src/main/java/org/basex/core/users/Algorithm.java | 554 | package org.basex.core.users;
import java.util.*;
/**
* Algorithms.
*
* @author BaseX Team 2005-20, BSD License
* @author Christian Gruen
*/
public enum Algorithm {
/** Digest. */
DIGEST(Code.HASH),
/** Salted SHA-256. */
SALTED_SHA256(Code.SALT, Code.HASH);
/** Used codes. */
final Code[] codes;
/**
* Constructor.
* @param codes used codes
*/
Algorithm(final Code... codes) {
this.codes = codes;
}
@Override
public String toString() {
return name().toLowerCase(Locale.ENGLISH).replace('_', '-');
}
}
| bsd-3-clause |
sgrailways/giftidea | android/src/main/java/com/sgrailways/giftidea/ListenerFactory.java | 2960 | package com.sgrailways.giftidea;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import com.sgrailways.giftidea.core.domain.Recipient;
import com.sgrailways.giftidea.events.DeleteIdeaEvent;
import com.sgrailways.giftidea.events.GotItEvent;
import com.sgrailways.giftidea.listeners.DialogDismissListener;
import com.sgrailways.giftidea.wiring.ForActivity;
import com.squareup.otto.Bus;
import javax.inject.Inject;
public class ListenerFactory {
private final Bus bus;
private final Toaster toaster;
private final Context context;
private final DialogDismissListener dialogDismissListener;
private final Session session;
@Inject
public ListenerFactory(Bus bus, Toaster toaster, @ForActivity Context context, DialogDismissListener dialogDismissListener, Session session) {
this.bus = bus;
this.toaster = toaster;
this.context = context;
this.dialogDismissListener = dialogDismissListener;
this.session = session;
}
public DialogInterface.OnClickListener deleteIdeaListener(final Long id, final String message) {
return new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
bus.post(new DeleteIdeaEvent(id));
toaster.show(message);
}
};
}
public View.OnClickListener gotItListener(final Long id, final Recipient recipient, final String message) {
return new View.OnClickListener() {
public void onClick(View v) {
bus.post(new GotItEvent(id, recipient.getName()));
toaster.show(message);
}
};
}
public View.OnClickListener editIdeaListener(final Long id, final Recipient recipient) {
return new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, IdeaActivity.class);
intent.putExtra("ideaId", id);
session.setActiveRecipient(recipient);
context.startActivity(intent);
}
};
}
public View.OnClickListener confirmDeleteListener(final Long id, final Recipient recipient, final String deletedMessage, final Activity activity) {
return new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(activity)
.setNegativeButton(R.string.cancel, dialogDismissListener)
.setPositiveButton(R.string.delete, deleteIdeaListener(id, deletedMessage))
.setTitle(R.string.confirmation)
.setMessage("Delete idea for " + recipient.getName() + "?");
alert.create().show();
}
};
}
}
| bsd-3-clause |
UrielCh/ovh-java-sdk | ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/dbaas/logs/OvhUrl.java | 251 | package net.minidev.ovh.api.dbaas.logs;
/**
* Web address
*/
public class OvhUrl {
/**
* Web URI
*
* canBeNull && readOnly
*/
public String address;
/**
* Service type
*
* canBeNull && readOnly
*/
public OvhUrlTypeEnum type;
}
| bsd-3-clause |
NCIP/cabio | software/biogopher/src/gov/nih/nci/caBIOApp/report/Row.java | 449 | /*L
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cabio/LICENSE.txt for details.
*/
package gov.nih.nci.caBIOApp.report;
public interface Row {
public Cell createCell(String s);
public void addCell(Cell c);
public void addCells(Cell[] l);
public void setCells(Cell[] l);
public Cell[] getCells();
public int getNumCells();
} | bsd-3-clause |
NCIP/cacore-sdk | sdk-toolkit/iso-example-project/junit/src/test/gov/nih/nci/cacoresdk/domain/other/datatype/DsetTelDataTypeTest.java | 15043 | /*L
* Copyright Ekagra Software Technologies Ltd.
* Copyright SAIC, SAIC-Frederick
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cacore-sdk/LICENSE.txt for details.
*/
package test.gov.nih.nci.cacoresdk.domain.other.datatype;
/*
* Test case for DsetTel ( DSET<TEL> ) data type
*/
import gov.nih.nci.cacoresdk.domain.other.datatype.DsetTelDataType;
import gov.nih.nci.iso21090.NullFlavor;
import gov.nih.nci.iso21090.Tel;
import gov.nih.nci.system.applicationservice.ApplicationException;
import gov.nih.nci.system.query.hibernate.HQLCriteria;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import test.gov.nih.nci.cacoresdk.SDKISOTestBase;
public class DsetTelDataTypeTest extends SDKISOTestBase
{
/**
* Returns name of the test case
* @return
*/
public static String getTestCaseName()
{
return "Dset Tel Datatype Test Case";
}
/**
* Uses Nested Search Criteria for search
* Verifies that the results are returned
* Verifies size of the result set
*
* @throws ApplicationException
*/
@SuppressWarnings("unchecked")
public void testQueryRowCount() throws ApplicationException
{
DsetTelDataType searchObject = new DsetTelDataType();
Collection results = search("gov.nih.nci.cacoresdk.domain.other.datatype.DsetTelDataType",searchObject );
assertNotNull(results);
assertEquals(15,results.size());
}
/**
* Uses HQL for search
* Verifies that the results are returned
* Verifies size of the result set
*
* @throws ApplicationException
*/
public void testQueryRowCountHQL() throws ApplicationException
{
HQLCriteria criteria = new HQLCriteria("from gov.nih.nci.cacoresdk.domain.other.datatype.DsetTelDataType");
int count = getApplicationService().getQueryRowCount(criteria, "gov.nih.nci.cacoresdk.domain.other.datatype.DsetTelDataType");
assertEquals(15,count);
}
/**
* Search Value1 by detached criteria Test
*
* @throws ApplicationException
*/
/* public void testDsetTelValue1ByDetachedCriteria() throws ApplicationException, URISyntaxException
{
DetachedCriteria criteria = DetachedCriteria.forClass(DsetTelDataType.class);
criteria.add(Property.forName("value1.item.value").isNotNull());
criteria.addOrder(Order.asc("id"));
Collection<DsetTelDataType> result = search(criteria, "gov.nih.nci.cacoresdk.domain.other.datatype.DsetTelDataType");
assertEquals(5, result.size());
List index = new ArrayList();
index.add("1");
index.add("2");
index.add("3");
index.add("4");
index.add("5");
assertValue1(result, index);
}
*/
/**
* Search Value1 by HQL criteria Test
*
* @throws ApplicationException
*/
@SuppressWarnings("unchecked")
public void testDsetTelValue1ByHQLCriteria() throws ApplicationException, URISyntaxException
{
HQLCriteria criteria = new HQLCriteria("from gov.nih.nci.cacoresdk.domain.other.datatype.DsetTelDataType a where a.value1.item.value is not null order by a.id asc");
Collection<DsetTelDataType> result = search(criteria, "gov.nih.nci.cacoresdk.domain.other.datatype.DsetTelDataType");
assertEquals(5, result.size());
List index = new ArrayList();
index.add("1");
index.add("2");
index.add("3");
index.add("4");
index.add("5");
assertValue1(result, index);
}
/**
* Search Value2 by detached criteria Test
*
* @throws ApplicationException
*/
/* public void testDsetTelValue2ByDetachedCriteria() throws ApplicationException, URISyntaxException
{
DetachedCriteria criteria = DetachedCriteria.forClass(DsetTelDataType.class);
criteria.add(Property.forName("value2.item.value").isNotNull());
criteria.addOrder(Order.asc("id"));
Collection<DsetTelDataType> result = search(criteria, "gov.nih.nci.cacoresdk.domain.other.datatype.DsetTelDataType");
assertEquals(5, result.size());
List index = new ArrayList();
index.add("6");
index.add("7");
index.add("8");
index.add("9");
index.add("10");
assertValue2(result, index);
}
*/
/**
* Search Value2 by HQL criteria Test
*
* @throws ApplicationException
*/
@SuppressWarnings("unchecked")
public void testDsetTelValue2ByHQLCriteria() throws ApplicationException, URISyntaxException
{
HQLCriteria criteria = new HQLCriteria("from gov.nih.nci.cacoresdk.domain.other.datatype.DsetTelDataType a where a.value2.item.value is not null order by a.id asc asc");
Collection<DsetTelDataType> result = search(criteria, "gov.nih.nci.cacoresdk.domain.other.datatype.DsetTelDataType");
assertEquals(5, result.size());
List index = new ArrayList();
index.add("6");
index.add("7");
index.add("8");
index.add("9");
index.add("10");
assertValue2(result, index);
}
/**
* Search Value2 by detached criteria Test
*
* @throws ApplicationException
*/
/* public void testDsetTelValue3ByDetachedCriteria() throws ApplicationException, URISyntaxException
{
DetachedCriteria criteria = DetachedCriteria.forClass(DsetTelDataType.class);
criteria.add(Property.forName("value3.item.value").isNotNull());
criteria.addOrder(Order.asc("id"));
Collection<DsetTelDataType> result = search(criteria, "gov.nih.nci.cacoresdk.domain.other.datatype.DsetTelDataType");
assertEquals(5, result.size());
List index = new ArrayList();
index.add("11");
index.add("12");
index.add("13");
index.add("14");
index.add("15");
assertValue3(result, index);
}
*/
/**
* Search Value2 by HQL criteria Test
*
* @throws ApplicationException
*/
@SuppressWarnings("unchecked")
public void testDsetTelValue3ByHQLCriteria() throws ApplicationException, URISyntaxException
{
HQLCriteria criteria = new HQLCriteria("from gov.nih.nci.cacoresdk.domain.other.datatype.DsetTelDataType a where a.value3.item.value is not null order by a.id asc asc");
Collection<DsetTelDataType> result = search(criteria, "gov.nih.nci.cacoresdk.domain.other.datatype.DsetTelDataType");
assertEquals(5, result.size());
List index = new ArrayList();
index.add("11");
index.add("12");
index.add("13");
index.add("14");
index.add("15");
assertValue3(result, index);
}
/**
* Test Value1 for correct values
*
* @throws ApplicationException
*/
@SuppressWarnings("unchecked")
public void testTelValue() throws ApplicationException, URISyntaxException
{
DetachedCriteria criteria = DetachedCriteria.forClass(DsetTelDataType.class);
criteria.addOrder(Order.asc("id"));
Collection<DsetTelDataType> result = search(criteria, "gov.nih.nci.cacoresdk.domain.other.datatype.DsetTelDataType");
assertValue1(result, null);
assertValue2(result, null);
assertValue3(result, null);
}
private void assertValue1(Collection<DsetTelDataType> result, List<Integer> index) throws URISyntaxException
{
assertNotNull(result);
int counter = 1;
for(DsetTelDataType data : result)
{
//Validate 1st record
if((index == null && counter == 1) || (index != null && index.contains("1")))
{
if(index != null)
index.remove("1");
assertNotNull(data);
assertNotNull(data.getValue1());
Tel item = data.getValue1().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7891"), item.getValue());
counter++;
continue;
}
//Validate 2nd record
else if((index == null && counter == 2) || (index != null && index.contains("2")))
{
if(index != null)
index.remove("2");
assertNotNull(data);
assertNotNull(data.getValue1());
Tel item = data.getValue1().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7892"), item.getValue());
counter++;
continue;
}
//Validate 3rd record
else if((index == null && counter == 3) || (index != null && index.contains("3")))
{
if(index != null)
index.remove("3");
assertNotNull(data);
assertNotNull(data.getValue1());
Tel item = data.getValue1().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7893"), item.getValue());
counter++;
continue;
}
//Validate 4th record
else if((index == null && counter == 4) || (index != null && index.contains("4")))
{
if(index != null)
index.remove("4");
assertNotNull(data);
assertNotNull(data.getValue1());
Tel item = data.getValue1().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7894"), item.getValue());
counter++;
continue;
}
//Validate 5th record
else if((index == null && counter == 5) || (index != null && index.contains("5")))
{
if(index != null)
index.remove("5");
assertNotNull(data);
assertNotNull(data.getValue1());
Tel item = data.getValue1().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7895"), item.getValue());
counter++;
continue;
}
//Validate all remaining records
else
{
assertNotNull(data);
assertNotNull(data.getValue1());
assertNull(data.getValue1().getItem());
assertEquals(NullFlavor.NI, data.getValue1().getNullFlavor());
counter++;
}
}
}
private void assertValue2(Collection<DsetTelDataType> result, List<Integer> index) throws URISyntaxException
{
assertNotNull(result);
int counter = 1;
for(DsetTelDataType data : result)
{
//Validate 6th record
if((index == null && counter == 6) || (index != null && index.contains("6")))
{
if(index != null)
index.remove("6");
assertNotNull(data);
assertNotNull(data.getValue2());
Tel item = data.getValue2().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7891"), item.getValue());
counter++;
continue;
}
//Validate 7th record
else if((index == null && counter == 7) || (index != null && index.contains("7")))
{
if(index != null)
index.remove("7");
assertNotNull(data);
assertNotNull(data.getValue2());
Tel item = data.getValue2().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7892"), item.getValue());
counter++;
continue;
}
//Validate 8th record
else if((index == null && counter == 8) || (index != null && index.contains("8")))
{
if(index != null)
index.remove("8");
assertNotNull(data);
assertNotNull(data.getValue2());
Tel item = data.getValue2().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7893"), item.getValue());
counter++;
continue;
}
//Validate 9th record
else if((index == null && counter == 9) || (index != null && index.contains("9")))
{
if(index != null)
index.remove("9");
assertNotNull(data);
assertNotNull(data.getValue2());
Tel item = data.getValue2().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7894"), item.getValue());
counter++;
continue;
}
//Validate 10th record
else if((index == null && counter == 10) || (index != null && index.contains("10")))
{
if(index != null)
index.remove("10");
assertNotNull(data);
assertNotNull(data.getValue2());
Tel item = data.getValue2().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7895"), item.getValue());
counter++;
continue;
}
//Validate all remaining records
else
{
assertNotNull(data);
assertNotNull(data.getValue2());
assertNull(data.getValue2().getItem());
assertEquals(NullFlavor.NI, data.getValue2().getNullFlavor());
counter++;
}
}
}
private void assertValue3(Collection<DsetTelDataType> result, List<Integer> index) throws URISyntaxException
{
assertNotNull(result);
int counter = 1;
for(DsetTelDataType data : result)
{
//Validate 11th record
if((index == null && counter == 11) || (index != null && index.contains("11")))
{
if(index != null)
index.remove("11");
assertNotNull(data);
assertNotNull(data.getValue3());
Tel item = data.getValue3().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7892"), item.getValue());
counter++;
continue;
}
//Validate 12th record
else if((index == null && counter == 12) || (index != null && index.contains("12")))
{
if(index != null)
index.remove("12");
assertNotNull(data);
assertNotNull(data.getValue3());
Tel item = data.getValue3().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7892"), item.getValue());
counter++;
continue;
}
//Validate 13th record
else if((index == null && counter == 13) || (index != null && index.contains("13")))
{
if(index != null)
index.remove("13");
assertNotNull(data);
assertNotNull(data.getValue3());
Tel item = data.getValue3().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7892"), item.getValue());
counter++;
continue;
}
//Validate 14th record
else if((index == null && counter == 14) || (index != null && index.contains("14")))
{
if(index != null)
index.remove("14");
assertNotNull(data);
assertNotNull(data.getValue3());
Tel item = data.getValue3().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7892"), item.getValue());
counter++;
continue;
}
//Validate 15th record
else if((index == null && counter == 15) || (index != null && index.contains("15")))
{
if(index != null)
index.remove("15");
assertNotNull(data);
assertNotNull(data.getValue3());
Tel item = data.getValue3().getItem().iterator().next();
assertNull(item.getNullFlavor());
assertEquals(new URI("tel://123-456-7892"), item.getValue());
counter++;
continue;
}
//Validate all remaining records
else
{
assertNotNull(data);
assertNotNull(data.getValue3());
assertNull(data.getValue3().getItem());
assertEquals(NullFlavor.NI, data.getValue3().getNullFlavor());
counter++;
}
}
}
}
| bsd-3-clause |
NCIP/catrip | codebase/projects/queryservice/src/gov/nih/nci/catrip/cagrid/catripquery/service/globus/QueryServiceProviderImpl.java | 1995 | /*L
* Copyright Duke Comprehensive Cancer Center
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/catrip/LICENSE.txt for details.
*/
package gov.nih.nci.catrip.cagrid.catripquery.service.globus;
import gov.nih.nci.catrip.cagrid.catripquery.service.QueryServiceImpl;
import java.rmi.RemoteException;
/**
* DO NOT EDIT: This class is autogenerated!
*
* This class implements each method in the portType of the service. Each method call represented
* in the port type will be then mapped into the unwrapped implementation which the user provides
* in the QueryServiceImpl class. This class handles the boxing and unboxing of each method call
* so that it can be correclty mapped in the unboxed interface that the developer has designed and
* has implemented. Authorization callbacks are automatically made for each method based
* on each methods authorization requirements.
*
* @created by Introduce Toolkit version 1.0
*
*/
public class QueryServiceProviderImpl{
QueryServiceImpl impl;
public QueryServiceProviderImpl() throws RemoteException {
impl = new QueryServiceImpl();
}
public gov.nih.nci.catrip.cagrid.catripquery.stubs.SaveResponse save(gov.nih.nci.catrip.cagrid.catripquery.stubs.SaveRequest params) throws RemoteException {
QueryServiceAuthorization.authorizeSave();
gov.nih.nci.catrip.cagrid.catripquery.stubs.SaveResponse boxedResult = new gov.nih.nci.catrip.cagrid.catripquery.stubs.SaveResponse();
impl.save(params.getCatripQuery().getCatripQuery());
return boxedResult;
}
public gov.nih.nci.catrip.cagrid.catripquery.stubs.DeleteResponse delete(gov.nih.nci.catrip.cagrid.catripquery.stubs.DeleteRequest params) throws RemoteException {
QueryServiceAuthorization.authorizeDelete();
gov.nih.nci.catrip.cagrid.catripquery.stubs.DeleteResponse boxedResult = new gov.nih.nci.catrip.cagrid.catripquery.stubs.DeleteResponse();
impl.delete(params.get_long());
return boxedResult;
}
}
| bsd-3-clause |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/category/internal/CategoryCategoryComboChildrenAppender.java | 3576 | /*
* Copyright (c) 2004-2021, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.category.internal;
import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter;
import org.hisp.dhis.android.core.arch.db.stores.internal.LinkChildStore;
import org.hisp.dhis.android.core.arch.db.stores.internal.StoreFactory;
import org.hisp.dhis.android.core.arch.db.stores.projections.internal.LinkTableChildProjection;
import org.hisp.dhis.android.core.arch.repositories.children.internal.ChildrenAppender;
import org.hisp.dhis.android.core.category.Category;
import org.hisp.dhis.android.core.category.CategoryCategoryComboLinkTableInfo;
import org.hisp.dhis.android.core.category.CategoryCombo;
import org.hisp.dhis.android.core.category.CategoryTableInfo;
final class CategoryCategoryComboChildrenAppender extends ChildrenAppender<CategoryCombo> {
private static final LinkTableChildProjection CHILD_PROJECTION = new LinkTableChildProjection(
CategoryTableInfo.TABLE_INFO,
CategoryCategoryComboLinkTableInfo.Columns.CATEGORY_COMBO,
CategoryCategoryComboLinkTableInfo.Columns.CATEGORY);
private final LinkChildStore<CategoryCombo, Category> linkChildStore;
private CategoryCategoryComboChildrenAppender(LinkChildStore<CategoryCombo, Category> linkChildStore) {
this.linkChildStore = linkChildStore;
}
@Override
protected CategoryCombo appendChildren(CategoryCombo categoryCombo) {
CategoryCombo.Builder builder = categoryCombo.toBuilder();
builder.categories(linkChildStore.getChildren(categoryCombo));
return builder.build();
}
static ChildrenAppender<CategoryCombo> create(DatabaseAdapter databaseAdapter) {
return new CategoryCategoryComboChildrenAppender(
StoreFactory.linkChildStore(
databaseAdapter,
CategoryCategoryComboLinkTableInfo.TABLE_INFO,
CHILD_PROJECTION,
Category::create
)
);
}
} | bsd-3-clause |
iig-uni-freiburg/SWAT20 | src/de/uni/freiburg/iig/telematik/swat/patterns/logic/Helpers.java | 464 | package de.uni.freiburg.iig.telematik.swat.patterns.logic;
public class Helpers {
public static void main (String args[]){
System.out.println(cutOffLabelInfo("t1(bla)"));
}
public static String cutOffLabelInfo(String str) {
int index1 = str.indexOf("(");
int index2 = str.indexOf(")");
String pref = str.substring(0, index1);
String suf = str.substring(index2 + 1, str.length());
str = pref + suf;
return str;
}
}
| bsd-3-clause |
Team319/RecyleRush | src/org/usfirst/frc319/RecyleRush/commands/ToteLightsFunction.java | 1645 | // RobotBuilder Version: 1.5
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc319.RecyleRush.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc319.RecyleRush.Robot;
/**
*
*/
public class ToteLightsFunction extends Command {
public ToteLightsFunction() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
requires(Robot.toteLights);
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
Robot.toteLights.LightUpWhenToteIsInPosition();
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| bsd-3-clause |
HWRobotics/hwrobot2013 | src/org/usfirst/frc1148/modules/AutoDriveModule.java | 2710 | package org.usfirst.frc1148.modules;
import org.usfirst.frc1148.data.MoveData;
import org.usfirst.frc1148.interfaces.RobotModule;
import edu.wpi.first.wpilibj.DigitalInput;
public class AutoDriveModule implements RobotModule {
DigitalInput rangefinderMid;
DigitalInput rangefinderClose;
int targetDegrees = 0;
boolean autoOrient = false;
boolean approachWall = false;
RobotDriver driver;
public AutoDriveModule(RobotDriver driver) {
this.driver = driver;
}
public void initModule() {
rangefinderMid = new DigitalInput(2);
rangefinderClose = new DigitalInput(3);
}
public void activateModule() {
Disable();
}
public void deactivateModule() {
}
public AutoDriveModule Disable() {
MoveData data = driver.getMoveData();
if (autoOrient) {
data.rotationSpeed = 0;
}
if (approachWall) {
data.speed = 0;
}
autoOrient = approachWall = false;
return this;
}
public AutoDriveModule OrientTo(int degrees) {
autoOrient = true;
targetDegrees = degrees;
return this;
}
public AutoDriveModule ApproachWall() {
approachWall = true;
return this;
}
public void updateTick(int mode) {
MoveData data = driver.getMoveData();
if (autoOrient) {
double angle = driver.getGyroAngleInRange();
double diff = Math.abs(hdgDiff(angle, targetDegrees));
double speed;
if (diff > 1) {
if (diff < 45) {
speed = Math.abs(diff / 45);
speed = speed * speed;
} else if (diff < 100) {
speed = 0.4;
} else {
speed = 0.8;
}
if (isTurnCCW(angle, targetDegrees)) {
speed *= -1;
}
data.rotationSpeed = speed;
} else {
data.rotationSpeed = 0;
}
}
//approachWall = true; //VERY F**ING IMPORTANT TO CHANGE THIS
//if(approachWall){
//System.out.println("APPROACH WALL: MID: "+rangefinderMid.get()+" CLOSE: "+rangefinderClose.get());
//}
}
double hdgDiff(double h1, double h2) { // angle between two headings
double diff = (h1 - h2 + 3600 % 360);
return diff <= 180 ? diff : 360 - diff;
}
boolean isTurnCCW(double hdg, double newHdg) { // should a new heading turn left ie. CCW?
double diff = newHdg - hdg; // CCW = counter-clockwise ie. left
return diff > 0 ? diff > 180 : diff >= -180;
}
}
| bsd-3-clause |
NCIP/c3pr | codebase/projects/core/test/src/java/edu/duke/cabig/c3pr/utils/GridSecurityUtilsUnitTest.java | 5690 | /*******************************************************************************
* Copyright Duke Comprehensive Cancer Center and SemanticBits
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/c3pr/LICENSE.txt for details.
******************************************************************************/
package edu.duke.cabig.c3pr.utils;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetailsService;
import org.easymock.classextension.EasyMock;
import edu.duke.cabig.c3pr.AbstractTestCase;
import edu.duke.cabig.c3pr.constants.RoleTypes;
public class GridSecurityUtilsUnitTest extends AbstractTestCase {
private UserDetailsService userDetailsService;
private GridSecurityUtils gridSecurityUtils;
@Override
protected void setUp() throws Exception {
super.setUp();
userDetailsService= registerMockFor(UserDetailsService.class);
gridSecurityUtils=new GridSecurityUtils();
gridSecurityUtils.setUserDetailsService(userDetailsService);
}
public void testGetUserIdFromGridIdentity(){
String userId=gridSecurityUtils.getUserIdFromGridIdentity("/O=caBIG/OU=caGrid/OU=Training/OU=Dorian/CN=SmokeTest");
assertEquals("SmokeTest", userId);
}
public void testGetUserIdFromGridIdentityNULLIdentity(){
String userId=gridSecurityUtils.getUserIdFromGridIdentity("");
assertEquals("", userId);
}
public void testLoadUserAuthentication(){
User user=new User("SmokeTest", "password", true, true, true, true,new GrantedAuthorityImpl[]{new GrantedAuthorityImpl("Admin")});
EasyMock.expect(userDetailsService.loadUserByUsername("SmokeTest")).andReturn(user);
replayMocks();
try {
User returnedUser=gridSecurityUtils.loadUserAuthentication("SmokeTest");
assertEquals("SmokeTest", returnedUser.getUsername());
assertEquals("password", returnedUser.getPassword());
assertEquals("Admin", returnedUser.getAuthorities()[0].getAuthority());
User secureUser =(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
assertEquals("SmokeTest", secureUser.getUsername());
assertEquals("password", secureUser.getPassword());
assertEquals("Admin", secureUser.getAuthorities()[0].getAuthority());
verifyMocks();
} catch (RemoteException e) {
e.printStackTrace();
fail("Shouldnt have thrown exception");
}
}
public void testLoadUserAuthenticationException(){
EasyMock.expect(userDetailsService.loadUserByUsername("SmokeTest")).andReturn(null);
replayMocks();
try {
User returnedUser=gridSecurityUtils.loadUserAuthentication("SmokeTest");
fail("Should have thrown exception");
} catch (RemoteException e) {
verifyMocks();
}
}
public void testGetRolesAdmin(){
User user=new User("SmokeTest", "password", true, true, true, true,new GrantedAuthorityImpl[]{new GrantedAuthorityImpl("ROLE_system_administrator")});
EasyMock.expect(userDetailsService.loadUserByUsername("SmokeTest")).andReturn(user);
replayMocks();
try {
List<RoleTypes> roles=gridSecurityUtils.getRoles("SmokeTest");
assertEquals(RoleTypes.SYSTEM_ADMINISTRATOR, roles.get(0));
verifyMocks();
} catch (RemoteException e) {
e.printStackTrace();
fail("Shouldnt have thrown exception");
}
}
public void testGetRolesAll(){
User user=new User("SmokeTest", "password", true, true, true, true,new GrantedAuthorityImpl[]{new GrantedAuthorityImpl("ROLE_data_importer"),
new GrantedAuthorityImpl("ROLE_person_and_organization_information_manager"),
new GrantedAuthorityImpl("ROLE_registrar"),
new GrantedAuthorityImpl("ROLE_user_administrator"),});
EasyMock.expect(userDetailsService.loadUserByUsername("SmokeTest")).andReturn(user);
replayMocks();
try {
List<RoleTypes> roles=gridSecurityUtils.getRoles("SmokeTest");
assertEquals(RoleTypes.DATA_IMPORTER, roles.get(0));
assertEquals(RoleTypes.PERSON_AND_ORGANIZATION_INFORMATION_MANAGER, roles.get(1));
assertEquals(RoleTypes.REGISTRAR, roles.get(2));
assertEquals(RoleTypes.USER_ADMINISTRATOR, roles.get(3));
verifyMocks();
} catch (RemoteException e) {
e.printStackTrace();
fail("Shouldnt have thrown exception");
}
}
public void testGetRolesInvalidRole(){
User user=new User("SmokeTest", "password", true, true, true, true,new GrantedAuthorityImpl[]{new GrantedAuthorityImpl("wrong"),new GrantedAuthorityImpl("ROLE_user_administrator")});
EasyMock.expect(userDetailsService.loadUserByUsername("SmokeTest")).andReturn(user);
replayMocks();
try {
List<RoleTypes> roles=gridSecurityUtils.getRoles("SmokeTest");
assertEquals("wrong size", 1, roles.size());
assertEquals(RoleTypes.USER_ADMINISTRATOR, roles.get(0));
verifyMocks();
} catch (RemoteException e) {
e.printStackTrace();
fail("Should have thrown exception");
verifyMocks();
}
}
public void testGetRolesAsString(){
ArrayList<RoleTypes> roles=new ArrayList<RoleTypes>();
roles.add(RoleTypes.DATA_ANALYST);
roles.add(RoleTypes.REGISTRAR);
roles.add(RoleTypes.STUDY_CREATOR);
roles.add(RoleTypes.STUDY_QA_MANAGER);
String roleString=gridSecurityUtils.getRolesAsString(roles);
assertEquals("{"+RoleTypes.DATA_ANALYST.getDisplayName()+","+RoleTypes.REGISTRAR.getDisplayName()+","+RoleTypes.STUDY_CREATOR.getDisplayName()+","+RoleTypes.STUDY_QA_MANAGER.getDisplayName()+","+"}", roleString);
}
}
| bsd-3-clause |
endlessm/chromium-browser | chrome/android/java/src/org/chromium/chrome/browser/toolbar/top/StartSurfaceToolbarViewBinder.java | 4870 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.toolbar.top;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.ACCESSIBILITY_ENABLED;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.APP_MENU_BUTTON_HELPER;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.BUTTONS_CLICKABLE;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.IDENTITY_DISC_AT_START;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.IDENTITY_DISC_CLICK_HANDLER;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.IDENTITY_DISC_DESCRIPTION;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.IDENTITY_DISC_IMAGE;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.IDENTITY_DISC_IS_VISIBLE;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.INCOGNITO_STATE_PROVIDER;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.INCOGNITO_SWITCHER_VISIBLE;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.IN_START_SURFACE_MODE;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.IS_INCOGNITO;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.IS_VISIBLE;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.LOGO_IS_VISIBLE;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.MENU_IS_VISIBLE;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.NEW_TAB_BUTTON_AT_START;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.NEW_TAB_BUTTON_IS_VISIBLE;
import static org.chromium.chrome.browser.toolbar.top.StartSurfaceToolbarProperties.NEW_TAB_CLICK_HANDLER;
import org.chromium.ui.modelutil.PropertyKey;
import org.chromium.ui.modelutil.PropertyModel;
// The view binder of the tasks surface view.
class StartSurfaceToolbarViewBinder {
public static void bind(
PropertyModel model, StartSurfaceToolbarView view, PropertyKey propertyKey) {
if (propertyKey == ACCESSIBILITY_ENABLED) {
view.onAccessibilityStatusChanged(model.get(ACCESSIBILITY_ENABLED));
} else if (propertyKey == APP_MENU_BUTTON_HELPER) {
view.setAppMenuButtonHelper(model.get(APP_MENU_BUTTON_HELPER));
} else if (propertyKey == BUTTONS_CLICKABLE) {
view.setButtonClickableState(model.get(BUTTONS_CLICKABLE));
} else if (propertyKey == INCOGNITO_SWITCHER_VISIBLE) {
view.setIncognitoSwitcherVisibility((Boolean) model.get(INCOGNITO_SWITCHER_VISIBLE));
} else if (propertyKey == IDENTITY_DISC_AT_START) {
view.setIdentityDiscAtStart(model.get(IDENTITY_DISC_AT_START));
} else if (propertyKey == IDENTITY_DISC_CLICK_HANDLER) {
view.setIdentityDiscClickHandler(model.get(IDENTITY_DISC_CLICK_HANDLER));
} else if (propertyKey == IDENTITY_DISC_DESCRIPTION) {
view.setIdentityDiscContentDescription(model.get(IDENTITY_DISC_DESCRIPTION));
} else if (propertyKey == IDENTITY_DISC_IMAGE) {
view.setIdentityDiscImage(model.get(IDENTITY_DISC_IMAGE));
} else if (propertyKey == IDENTITY_DISC_IS_VISIBLE) {
view.setIdentityDiscVisibility(model.get(IDENTITY_DISC_IS_VISIBLE));
} else if (propertyKey == INCOGNITO_STATE_PROVIDER) {
view.setIncognitoStateProvider(model.get(INCOGNITO_STATE_PROVIDER));
} else if (propertyKey == IN_START_SURFACE_MODE) {
view.setStartSurfaceMode(model.get(IN_START_SURFACE_MODE));
} else if (propertyKey == IS_INCOGNITO) {
view.updateIncognito(model.get(IS_INCOGNITO));
} else if (propertyKey == IS_VISIBLE) {
view.setToolbarVisibility(model.get(IS_VISIBLE));
} else if (propertyKey == LOGO_IS_VISIBLE) {
view.setLogoVisibility(model.get(LOGO_IS_VISIBLE));
} else if (propertyKey == MENU_IS_VISIBLE) {
view.setMenuButtonVisibility(model.get(MENU_IS_VISIBLE));
} else if (propertyKey == NEW_TAB_CLICK_HANDLER) {
view.setOnNewTabClickHandler(model.get(NEW_TAB_CLICK_HANDLER));
} else if (propertyKey == NEW_TAB_BUTTON_AT_START) {
view.setNewTabButtonAtStart(model.get(NEW_TAB_BUTTON_AT_START));
} else if (propertyKey == NEW_TAB_BUTTON_IS_VISIBLE) {
view.setNewTabButtonVisibility(model.get(NEW_TAB_BUTTON_IS_VISIBLE));
}
}
}
| bsd-3-clause |
rwth-acis/LAS2peer-Monitoring-Data-Provision-Service | app/src/main/java/i5/las2peer/services/mobsos/successModeling/TextFormatter.java | 4257 | package i5.las2peer.services.mobsos.successModeling;
import i5.las2peer.services.mobsos.successModeling.RestApiV2.ChatException;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* Text formatting functions used to format text to be used by the chatbot
*/
public class TextFormatter {
protected static String formatMeasures(NodeList measures) {
String response = "";
for (int i = 0; i < measures.getLength(); i++) {
response +=
(i + 1) +
". " +
((Element) measures.item(i)).getAttribute("name") +
"\n";
}
return response;
}
protected static String formatSuccesFactors(NodeList factors)
throws ChatException {
String response = "";
for (int i = 0; i < factors.getLength(); i++) {
response +=
(i + 1) +
". " +
((Element) factors.item(i)).getAttribute("name") +
"\n";
}
return response;
}
protected static String formatSuccessDimensions(List<String> dimensions) {
String response = "";
for (int i = 0; i < dimensions.size(); i++) {
String dimension = dimensions.get(i);
response += (i + 1) + ". " + dimension + "\n";
}
return response;
}
/**
* Formats the success model from an xml string as a text
* @param xml success model as string
* @param dimension if set only the specified dimention is transformed into text
* @param measuresOnly wheter to only list the success measures
* @return
* @throws Exception
*/
protected static String SuccessModelToText(
String xml,
String dimension,
boolean measuresOnly
)
throws Exception {
String res = "";
Document model = XMLTools.loadXMLFromString(xml);
NodeList dimensions = model.getElementsByTagName("dimension");
for (int i = 0; i < dimensions.getLength(); i++) {
if (
dimension == null ||
dimension.equals(((Element) dimensions.item(i)).getAttribute("name"))
) {
if (!measuresOnly) {
res += (i + 1) + ") ";
}
res += dimensionToText((Element) dimensions.item(i), measuresOnly);
}
}
return res;
}
protected static String SuccessModelToText(Document model) throws Exception {
String res = "";
NodeList dimensions = model.getElementsByTagName("dimension");
for (int i = 0; i < dimensions.getLength(); i++) {
res += dimensionToText((Element) dimensions.item(i));
}
return res;
}
private static String dimensionToText(Element dimension) {
String res = "";
res += dimension.getAttribute("name") + ":\n";
NodeList factors = dimension.getElementsByTagName("factor");
for (int i = 0; i < factors.getLength(); i++) {
res += " -" + factorToText((Element) factors.item(i));
}
return res;
}
private static String dimensionToText(
Element dimension,
boolean measuresOnly
) {
String res = "";
if (!measuresOnly) {
res += dimension.getAttribute("name") + ":\n";
}
NodeList factors = dimension.getElementsByTagName("factor");
for (int i = 0; i < factors.getLength(); i++) {
if (!measuresOnly) {
res += " -";
}
res += factorToText((Element) factors.item(i), measuresOnly);
}
return res;
}
private static String factorToText(Element factor) {
String res = "";
res += factor.getAttribute("name") + ":\n";
NodeList measures = ((Element) factor).getElementsByTagName("measure");
for (int j = 0; j < measures.getLength(); j++) {
res += " • " + measureToText((Element) measures.item(j));
}
return res;
}
private static String factorToText(Element factor, boolean measuresOnly) {
String res = "";
if (!measuresOnly) {
res += factor.getAttribute("name") + ":\n";
}
NodeList measures = ((Element) factor).getElementsByTagName("measure");
for (int j = 0; j < measures.getLength(); j++) {
if (!measuresOnly) {
res += " ";
}
res += "• " + measureToText((Element) measures.item(j));
}
return res;
}
private static String measureToText(Element measure) {
return measure.getAttribute("name") + "\n";
}
}
| bsd-3-clause |
NCIP/cagrid | cagrid/Software/core/integration-tests/projects/sdk41StyleTests/src/org/cagrid/data/styles/cacore41/test/steps/SDK41StyleCreationStep.java | 4529 | package org.cagrid.data.styles.cacore41.test.steps;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.data.ExtensionDataUtils;
import gov.nih.nci.cagrid.data.extension.Data;
import gov.nih.nci.cagrid.data.extension.ServiceFeatures;
import gov.nih.nci.cagrid.data.extension.ServiceStyle;
import gov.nih.nci.cagrid.introduce.IntroduceConstants;
import gov.nih.nci.cagrid.introduce.beans.ServiceDescription;
import gov.nih.nci.cagrid.introduce.beans.extension.ExtensionType;
import gov.nih.nci.cagrid.introduce.beans.extension.ExtensionTypeExtensionData;
import gov.nih.nci.cagrid.introduce.common.ServiceInformation;
import java.io.File;
import org.cagrid.data.styles.cacore41.test.SDK41ServiceStyleSystemTestConstants;
import org.cagrid.data.test.creation.CreationStep;
import org.cagrid.data.test.creation.DataTestCaseInfo;
/**
* SDK41StyleCreationStep
* Test step to create a new caGrid data service
* using the caCORE SDK 4.1 service style
*
* @author David Ervin
*
* @created Jan 29, 2008 1:18:44 PM
* @version $Id: SDK41StyleCreationStep.java,v 1.2 2009-04-10 15:15:24 dervin Exp $
*/
public class SDK41StyleCreationStep extends CreationStep {
private ServiceInformation serviceInformation = null;
public SDK41StyleCreationStep(DataTestCaseInfo serviceInfo, String introduceDir) {
super(serviceInfo, introduceDir);
}
/**
* Extended to turn on the cacore 4.1 style in the service model
*/
protected void postSkeletonCreation() throws Throwable {
setServiceStyle();
SDK41StyleConfigurationStep step = new SDK41StyleConfigurationStep(new File(serviceInfo.getDir()));
step.runStep();
}
protected void postSkeletonPostCreation() throws Throwable {
// service style config here?
}
private void setServiceStyle() throws Throwable {
Data extensionData = getExtensionData();
ServiceFeatures features = extensionData.getServiceFeatures();
if (features == null) {
features = new ServiceFeatures();
extensionData.setServiceFeatures(features);
}
features.setServiceStyle(new ServiceStyle(SDK41ServiceStyleSystemTestConstants.STYLE_NAME, "1.4"));
storeExtensionData(extensionData);
}
private Data getExtensionData() throws Throwable {
ServiceDescription serviceDesc = getServiceInformation().getServiceDescriptor();
ExtensionType[] extensions = serviceDesc.getExtensions().getExtension();
ExtensionType dataExtension = null;
for (int i = 0; i < extensions.length; i++) {
if (extensions[i].getName().equals("data")) {
dataExtension = extensions[i];
break;
}
}
if (dataExtension.getExtensionData() == null) {
dataExtension.setExtensionData(new ExtensionTypeExtensionData());
}
assertNotNull("Data service extension was not found in the service model", dataExtension);
Data extensionData = ExtensionDataUtils.getExtensionData(dataExtension.getExtensionData());
return extensionData;
}
private void storeExtensionData(Data data) throws Throwable {
File serviceModelFile = new File(serviceInfo.getDir() + File.separator + IntroduceConstants.INTRODUCE_XML_FILE);
ServiceDescription serviceDesc = getServiceInformation().getServiceDescriptor();
ExtensionType[] extensions = serviceDesc.getExtensions().getExtension();
ExtensionType dataExtension = null;
for (int i = 0; i < extensions.length; i++) {
if (extensions[i].getName().equals("data")) {
dataExtension = extensions[i];
break;
}
}
assertNotNull("Data service extension was not found in the service model", dataExtension);
if (dataExtension.getExtensionData() == null) {
dataExtension.setExtensionData(new ExtensionTypeExtensionData());
}
ExtensionDataUtils.storeExtensionData(dataExtension.getExtensionData(), data);
Utils.serializeDocument(serviceModelFile.getAbsolutePath(), serviceDesc, IntroduceConstants.INTRODUCE_SKELETON_QNAME);
}
private ServiceInformation getServiceInformation() throws Exception {
if (serviceInformation == null) {
serviceInformation = new ServiceInformation(new File(serviceInfo.getDir()));
}
return serviceInformation;
}
}
| bsd-3-clause |
dbastin/donkey | src/java/test/org/burroloco/butcher/fixture/checker/file/FileExistsPollingBlock.java | 367 | package org.burroloco.butcher.fixture.checker.file;
import org.burroloco.butcher.util.poll.PollingBlock;
import java.io.File;
public class FileExistsPollingBlock implements PollingBlock {
private final File file;
public FileExistsPollingBlock(File file) {
this.file = file;
}
public boolean call() {
return file.exists();
}
}
| bsd-3-clause |
codeaudit/Foundry | Components/LearningCore/Source/gov/sandia/cognition/statistics/distribution/BetaDistribution.java | 16911 | /*
* File: BetaDistribution.java
* Authors: Kevin R. Dixon
* Company: Sandia National Laboratories
* Project: Cognitive Foundry
*
* Copyright October 2, 2007, Sandia Corporation. Under the terms of Contract
* DE-AC04-94AL85000, there is a non-exclusive license for use of this work by
* or on behalf of the U.S. Government. Export of this program may require a
* license from the United States Government. See CopyrightHistory.txt for
* complete details.
*
*/
package gov.sandia.cognition.statistics.distribution;
import gov.sandia.cognition.annotation.PublicationReference;
import gov.sandia.cognition.annotation.PublicationType;
import gov.sandia.cognition.math.MathUtil;
import gov.sandia.cognition.math.UnivariateStatisticsUtil;
import gov.sandia.cognition.math.matrix.VectorFactory;
import gov.sandia.cognition.math.matrix.Vector;
import gov.sandia.cognition.statistics.AbstractClosedFormSmoothUnivariateDistribution;
import gov.sandia.cognition.statistics.DistributionEstimator;
import gov.sandia.cognition.statistics.DistributionWeightedEstimator;
import gov.sandia.cognition.statistics.EstimableDistribution;
import gov.sandia.cognition.statistics.UnivariateProbabilityDensityFunction;
import gov.sandia.cognition.statistics.SmoothCumulativeDistributionFunction;
import gov.sandia.cognition.util.AbstractCloneableSerializable;
import gov.sandia.cognition.util.Pair;
import gov.sandia.cognition.util.WeightedValue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;
/**
* Computes the Beta-family of probability distributions.
*
* @author Kevin R. Dixon
* @since 2.0
*
*/
@PublicationReference(
author="Wikipedia",
title="Beta distribution",
type=PublicationType.WebPage,
year=2009,
url="http://en.wikipedia.org/wiki/Beta_distribution"
)
public class BetaDistribution
extends AbstractClosedFormSmoothUnivariateDistribution
implements EstimableDistribution<Double,BetaDistribution>
{
/**
* Default alpha, {@value}.
*/
public static final double DEFAULT_ALPHA = 2.0;
/**
* Default beta, {@value}.
*/
public static final double DEFAULT_BETA = 2.0;
/**
* Alpha shape parameter, must be greater than 0 (typically greater than 1)
*/
private double alpha;
/**
* Alpha shape parameter, must be greater than 0 (typically greater than 1)
*/
private double beta;
/**
* Default constructor.
*/
public BetaDistribution()
{
this( DEFAULT_ALPHA, DEFAULT_BETA );
}
/**
* Creates a new instance of BetaDistribution
* @param alpha
* Alpha shape parameter, must be greater than 0 (typically greater than 1)
* @param beta
* Beta shape parameter, must be greater than 0 (typically greater than 1)
*/
public BetaDistribution(
final double alpha,
final double beta )
{
this.setAlpha( alpha );
this.setBeta( beta );
}
/**
* Copy Constructor
* @param other
* BetaDistribution to copy
*/
public BetaDistribution(
final BetaDistribution other )
{
this( other.getAlpha(), other.getBeta() );
}
@Override
public BetaDistribution clone()
{
return (BetaDistribution) super.clone();
}
@Override
public double getMeanAsDouble()
{
return this.getAlpha() / (this.getAlpha() + this.getBeta());
}
@Override
public double getVariance()
{
double numerator = this.getAlpha() * this.getBeta();
double apb = this.getAlpha() + this.getBeta();
double denominator = apb * apb * (apb + 1);
return numerator / denominator;
}
@Override
public double sampleAsDouble(
final Random random)
{
final double x = GammaDistribution.sampleAsDouble(
this.alpha, 1.0, random);
final double y = GammaDistribution.sampleAsDouble(
this.beta, 1.0, random);
return x / (x + y);
}
@Override
public void sampleInto(
final Random random,
final double[] output,
final int start,
final int length)
{
final double[] Xs = GammaDistribution.sampleAsDoubles(
this.alpha, 1.0, random, length);
final double[] Ys = GammaDistribution.sampleAsDoubles(
this.beta, 1.0, random, length);
final int end = start + length;
for (int i = start; i < end; i++)
{
final double x = Xs[i - start];
final double y = Ys[i - start];
output[i] = x / (x + y);
}
}
/**
* Gets the parameters of the distribution
* @return
* 2-dimensional Vector with [alpha beta]
*/
@Override
public Vector convertToVector()
{
return VectorFactory.getDefault().copyValues(
this.getAlpha(), this.getBeta() );
}
/**
* Sets the parameters of the distribution
* @param parameters
* 2-dimensional Vector with [alpha beta]
*/
@Override
public void convertFromVector(
final Vector parameters )
{
if (parameters.getDimensionality() != 2)
{
throw new IllegalArgumentException(
"Expecting 2-dimensional parameter Vector!" );
}
this.setAlpha( parameters.getElement( 0 ) );
this.setBeta( parameters.getElement( 1 ) );
}
/**
* Getter for alpha
* @return
* Alpha shape parameter, must be greater than 0 (typically greater than 1)
*/
public double getAlpha()
{
return this.alpha;
}
/**
* Setter for alpha
* @param alpha
* Alpha shape parameter, must be greater than 0 (typically greater than 1)
*/
public void setAlpha(
final double alpha )
{
if (alpha <= 0.0)
{
throw new IllegalArgumentException( "Alpha must be > 0.0" );
}
this.alpha = alpha;
}
/**
* Getter for beta
* @return
* Beta shape parameter, must be greater than 0 (typically greater than 1)
*/
public double getBeta()
{
return this.beta;
}
/**
* Setter for beta
* @param beta
* Beta shape parameter, must be greater than 0 (typically greater than 1)
*/
public void setBeta(
final double beta )
{
if (beta <= 0.0)
{
throw new IllegalArgumentException( "Beta must be > 0.0" );
}
this.beta = beta;
}
@Override
public BetaDistribution.CDF getCDF()
{
return new BetaDistribution.CDF( this );
}
@Override
public BetaDistribution.PDF getProbabilityFunction()
{
return new BetaDistribution.PDF( this );
}
@Override
public Double getMinSupport()
{
return 0.0;
}
@Override
public Double getMaxSupport()
{
return 1.0;
}
@Override
public BetaDistribution.MomentMatchingEstimator getEstimator()
{
return new BetaDistribution.MomentMatchingEstimator();
}
/**
* Estimates the parameters of a Beta distribution using the matching
* of moments, not maximum likelihood.
*/
@PublicationReference(
author={
"Andrew Gelman",
"John B. Carlin",
"Hal S. Stern",
"Donald B. Rubin"
},
title="Bayesian Data Analysis, Second Edition",
type=PublicationType.Book,
year=2004,
pages=582,
notes="Equation A.3"
)
public static class MomentMatchingEstimator
extends AbstractCloneableSerializable
implements DistributionEstimator<Double,BetaDistribution>
{
/**
* Default constructor
*/
public MomentMatchingEstimator()
{
}
@Override
public BetaDistribution learn(
final Collection<? extends Double> data)
{
Pair<Double,Double> pair =
UnivariateStatisticsUtil.computeMeanAndVariance(data);
return learn( pair.getFirst(), pair.getSecond() );
}
/**
* Computes the Beta distribution describes by the given moments
* @param mean
* Mean of the distribution
* @param variance
* Variance of the distribution
* @return
* Beta distribution that has the same mean/variance as the
* given parameters.
*/
public static BetaDistribution learn(
final double mean,
final double variance )
{
double apb = mean*(1.0-mean) / variance - 1.0;
double alpha = Math.abs(apb * mean);
double beta = Math.abs(apb * (1.0-mean));
return new BetaDistribution( alpha, beta );
}
}
/**
* Estimates the parameters of a Beta distribution using the matching
* of moments, not maximum likelihood.
*/
@PublicationReference(
author={
"Andrew Gelman",
"John B. Carlin",
"Hal S. Stern",
"Donald B. Rubin"
},
title="Bayesian Data Analysis, Second Edition",
type=PublicationType.Book,
year=2004,
pages=582,
notes="Equation A.3"
)
public static class WeightedMomentMatchingEstimator
extends AbstractCloneableSerializable
implements DistributionWeightedEstimator<Double,BetaDistribution>
{
/**
* Default constructor
*/
public WeightedMomentMatchingEstimator()
{
}
@Override
public BetaDistribution learn(
final Collection<? extends WeightedValue<? extends Double>> data)
{
Pair<Double,Double> pair =
UnivariateStatisticsUtil.computeWeightedMeanAndVariance(data);
return MomentMatchingEstimator.learn(
pair.getFirst(), pair.getSecond() );
}
}
/**
* Beta distribution probability density function
*/
public static class PDF
extends BetaDistribution
implements UnivariateProbabilityDensityFunction
{
/**
* Default constructor.
*/
public PDF()
{
super();
}
/**
* Creates a new PDF
* @param alpha
* Alpha shape parameter, must be greater than 0 (typically greater than 1)
* @param beta
* Beta shape parameter, must be greater than 0 (typically greater than 1)
*/
public PDF(
final double alpha,
final double beta )
{
super( alpha, beta );
}
/**
* Copy constructor
* @param other
* Underlying Beta Distribution
*/
public PDF(
final BetaDistribution other )
{
super( other );
}
@Override
public Double evaluate(
final Double input )
{
return this.evaluate( input.doubleValue() );
}
@Override
public double evaluateAsDouble(
final Double input)
{
return this.evaluate(input.doubleValue());
}
@Override
public double evaluate(
final double input )
{
return evaluate( input, this.getAlpha(), this.getBeta() );
}
/**
* Evaluate the Beta-distribution PDF for beta(x;alpha,beta)
* @param x
* Input to the beta PDF, must be on the interval [0,1]
* @param alpha
* Alpha shape parameter, must be greater than 0 (typically greater than 1)
* @param beta
* Beta shape parameter, must be greater than 0 (typically greater than 1)
* @return
* beta(x;alpha,beta)
*/
public static double evaluate(
final double x,
final double alpha,
final double beta )
{
double p;
if (x < 0.0)
{
p = 0.0;
}
else if (x > 1.0)
{
p = 0.0;
}
else
{
p = Math.exp( logEvaluate(x, alpha, beta) );
}
return p;
}
@Override
public double logEvaluate(
final Double input)
{
return this.logEvaluate((double) input);
}
@Override
public double logEvaluate(
final double input)
{
return logEvaluate(input, this.getAlpha(), this.getBeta() );
}
/**
* Evaluate the Beta-distribution PDF for beta(x;alpha,beta)
* @param x
* Input to the beta PDF, must be on the interval [0,1]
* @param alpha
* Alpha shape parameter, must be greater than 0 (typically greater than 1)
* @param beta
* Beta shape parameter, must be greater than 0 (typically greater than 1)
* @return
* beta(x;alpha,beta)
*/
public static double logEvaluate(
final double x,
final double alpha,
final double beta )
{
double plog;
if (x < 0.0)
{
plog = Math.log(0.0);
}
else if (x > 1.0)
{
plog = Math.log(0.0);
}
else
{
final double n1 = (alpha-1) * Math.log(x);
final double n2 = (beta-1) * Math.log( 1.0-x );
final double d1 = MathUtil.logBetaFunction( alpha, beta );
plog = n1 + n2 - d1;
}
return plog;
}
@Override
public BetaDistribution.PDF getProbabilityFunction()
{
return this;
}
}
/**
* CDF of the Beta-family distribution
*/
public static class CDF
extends BetaDistribution
implements SmoothCumulativeDistributionFunction
{
/**
* Default constructor.
*/
public CDF()
{
super();
}
/**
* Creates a new CDF
* @param alpha
* Alpha shape parameter, must be greater than 0 (typically greater than 1)
* @param beta
* Beta shape parameter, must be greater than 0 (typically greater than 1)
*/
public CDF(
final double alpha,
final double beta )
{
super( alpha, beta );
}
/**
* Copy constructor
* @param other
* Underlying Beta Distribution
*/
public CDF(
final BetaDistribution other )
{
super( other );
}
@Override
public Double evaluate(
final Double input )
{
return this.evaluate( input.doubleValue() );
}
@Override
public double evaluateAsDouble(
final Double input)
{
return this.evaluate(input.doubleValue());
}
@Override
public double evaluate(
final double input )
{
return evaluate(
input, this.getAlpha(), this.getBeta() );
}
/**
* Evaluate the Beta-distribution CDF for Beta(x;alpha,beta)
* @param x
* Input to the beta CDF, must be on the interval [0,1]
* @param alpha
* Alpha shape parameter, must be greater than 0 (typically greater than 1)
* @param beta
* Beta shape parameter, must be greater than 0 (typically greater than 1)
* @return
* Beta(x;alpha,beta)
*/
public static double evaluate(
final double x,
final double alpha,
final double beta )
{
double p;
if (x <= 0.0)
{
p = 0.0;
}
else if (x >= 1.0)
{
p = 1.0;
}
else
{
p = MathUtil.regularizedIncompleteBetaFunction( alpha, beta, x );
}
return p;
}
@Override
public BetaDistribution.CDF getCDF()
{
return this;
}
@Override
public BetaDistribution.PDF getDerivative()
{
return this.getProbabilityFunction();
}
@Override
public Double differentiate(
final Double input)
{
return this.getDerivative().evaluate(input);
}
}
}
| bsd-3-clause |
Caleydo/caleydo | org.caleydo.view.treemap/src/org/caleydo/view/treemap/SerializedTreeMapView.java | 1090 | /*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
******************************************************************************/
package org.caleydo.view.treemap;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.caleydo.core.serialize.ASerializedSingleTablePerspectiveBasedView;
import org.caleydo.core.view.ISingleTablePerspectiveBasedView;
/**
* Serialized form of a treemap view.
*
* @author Marc Streit
*/
@XmlRootElement
@XmlType
public class SerializedTreeMapView extends ASerializedSingleTablePerspectiveBasedView {
/**
* Default constructor with default initialization
*/
public SerializedTreeMapView() {
}
public SerializedTreeMapView(ISingleTablePerspectiveBasedView view) {
super(view);
}
@Override
public String getViewType() {
return GLTreeMap.VIEW_TYPE;
}
}
| bsd-3-clause |
treejames/StarAppSquare | src/com/nd/android/u/square/dataStructure/ImgInfo.java | 2395 | package com.nd.android.u.square.dataStructure;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Parcel;
import android.os.Parcelable;
/**
* ImgInfo数据结构
*
* <br>Created 2014-8-21 下午3:14:34
* @version
* @author chenpeng
*
* @see
*/
public class ImgInfo implements Parcelable{
public long id;// 图片ID[必选]
// public int column;// 所占格数(1,2,3)
public int width;// 图片宽度[必选]
public int height;// 图片高度[必选]
public long size;// 字节数[必选]
public String ext;// 图片文件实际格式:jpg,gif,png[必选]
public String thumbUrl;
public ImgInfo(String ext, String thumbUrl) {
super();
this.id = -1;
this.ext = ext;
this.thumbUrl = thumbUrl;
}
public ImgInfo(long id, int width, int height, long size, String ext, String thumbUrl) {
super();
this.id = id;
this.width = width;
this.height = height;
this.size = size;
this.ext = ext;
this.thumbUrl = thumbUrl;
}
public static final Parcelable.Creator<ImgInfo> CREATOR = new Creator<ImgInfo>() {
@Override
public ImgInfo[] newArray(int size) {
return new ImgInfo[size];
}
@Override
public ImgInfo createFromParcel(Parcel source) {
return new ImgInfo(source);
}
};
private ImgInfo(Parcel source){
id = source.readLong();
width = source.readInt();
height = source.readInt();
size = source.readLong();
ext = source.readString();
thumbUrl = source.readString();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeInt(width);
dest.writeInt(height);
dest.writeLong(size);
dest.writeString(ext);
dest.writeString(thumbUrl);
}
public JSONObject toJsonObject() throws JSONException{
JSONObject jb = new JSONObject();
jb.put("id", id);
jb.put("width", width);
jb.put("height", height);
jb.put("size", size);
jb.put("ext", ext);
jb.put("thumbUrl", thumbUrl);
return jb;
}
}
| bsd-3-clause |
NCIP/cagrid-core | caGrid/projects/dataExtensions/src/java/core/gov/nih/nci/cagrid/data/common/ModelInformationUtil.java | 6309 | /**
*============================================================================
* Copyright The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC, and
* Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-core/LICENSE.txt for details.
*============================================================================
**/
package gov.nih.nci.cagrid.data.common;
import gov.nih.nci.cagrid.introduce.beans.ServiceDescription;
import gov.nih.nci.cagrid.introduce.beans.namespace.NamespaceType;
import gov.nih.nci.cagrid.introduce.beans.namespace.SchemaElementType;
import gov.nih.nci.cagrid.introduce.common.CommonTools;
public class ModelInformationUtil {
private ServiceDescription serviceDesc = null;
public ModelInformationUtil(ServiceDescription serviceDesc) {
this.serviceDesc = serviceDesc;
}
/**
* Gets the namespace type which maps to the model package
*
* @param pack
* The package to get a namespace mapping for
* @return
* The namespace type, or null if no namespace is mapped to the package
*/
public NamespaceType getMappedNamespace(String packageName) {
NamespaceType mapped = null;
if (serviceDesc.getNamespaces() != null && serviceDesc.getNamespaces().getNamespace() != null) {
for (NamespaceType nsType : serviceDesc.getNamespaces().getNamespace()) {
if (packageName.equals(nsType.getPackageName())) {
mapped = nsType;
break;
}
}
}
return mapped;
}
/**
* Gets the element mapped to the class
*
* @param pack
* The package in which the class resides
* @param clazz
* The class to get an element mapping for
* @return
* The schema element type, or null if no namespace or element is mapped
*/
public SchemaElementType getMappedElement(String packageName, String className) {
SchemaElementType mapped = null;
NamespaceType nsType = getMappedNamespace(packageName);
if (nsType != null && nsType.getSchemaElement() != null) {
for (SchemaElementType element : nsType.getSchemaElement()) {
if (className.equals(element.getClassName())) {
mapped = element;
break;
}
}
}
return mapped;
}
public void setMappedNamespace(String packageName, String namespace) throws Exception {
// find the namespace
NamespaceType nsType = null;
if (serviceDesc.getNamespaces() != null) {
nsType = CommonTools.getNamespaceType(serviceDesc.getNamespaces(), namespace);
}
if (nsType == null) {
throw new Exception("No namespace " + namespace + " was found in the service model");
}
// set the package mapping
nsType.setPackageName(packageName);
}
/**
* Sets the element name mapped to the class. The package must first
* be mapped to a namespace in the service model or this method will fail
*
* @param pack
* The package in which the class resides
* @param clazz
* The class to map
* @param elementName
* The name of the element to map
* @throws Exception
* If the package is not mapped to a namespace or an element
* of the given name could not be found
*/
public void setMappedElementName(String packageName, String className, String elementName) throws Exception {
NamespaceType mappedNamespace = getMappedNamespace(packageName);
if (mappedNamespace == null) {
throw new Exception("No namespace was mapped to the package " + packageName);
}
SchemaElementType element = CommonTools.getSchemaElementType(mappedNamespace, elementName);
if (element == null) {
throw new Exception("No element " + elementName
+ " could be found in the namespace " + mappedNamespace.getNamespace());
}
element.setClassName(className);
}
public boolean unsetMappedNamespace(String packageName) throws Exception {
boolean found = false;
for (NamespaceType nsType : serviceDesc.getNamespaces().getNamespace()) {
if (packageName.equals(nsType.getPackageName())) {
nsType.setPackageName(null);
// unset all schema elements too
for (SchemaElementType element : nsType.getSchemaElement()) {
element.setClassName(null);
element.setSerializer(null);
element.setDeserializer(null);
}
found = true;
break;
}
}
return found;
}
/**
* Removes an element to class mapping from the service's namespace information
*
* @param packageName
* The class's package name
* @param className
* The short class name
* @return
* True if an element was found and updated, false otherwise
* @throws Exception
*/
public boolean unsetMappedElementName(String packageName, String className) throws Exception {
NamespaceType mappedNamespace = getMappedNamespace(packageName);
if (mappedNamespace == null) {
throw new Exception("No namespace was mapped to the package " + packageName);
}
boolean found = false;
// walk the elements and if one os mapped to the class name, null out the class name
if (mappedNamespace.getSchemaElement() != null) {
for (SchemaElementType element : mappedNamespace.getSchemaElement()) {
if (className.equals(element.getClassName())) {
element.setClassName(null);
element.setSerializer(null);
element.setDeserializer(null);
found = true;
break;
}
}
}
return found;
}
}
| bsd-3-clause |
jayjaybillings/thesis | org.eclipse.ice.client.vaadin/src/main/java/org/eclipse/ice/client/vaadin/DataComponentLayout.java | 3228 | package org.eclipse.ice.client.vaadin;
import org.eclipse.ice.datastructures.ICEObject.IUpdateable;
import org.eclipse.ice.datastructures.ICEObject.IUpdateableListener;
import org.eclipse.ice.datastructures.entry.ContinuousEntry;
import org.eclipse.ice.datastructures.entry.DiscreteEntry;
import org.eclipse.ice.datastructures.entry.ExecutableEntry;
import org.eclipse.ice.datastructures.entry.FileEntry;
import org.eclipse.ice.datastructures.entry.IEntryVisitor;
import org.eclipse.ice.datastructures.entry.MultiValueEntry;
import org.eclipse.ice.datastructures.entry.StringEntry;
import org.eclipse.ice.datastructures.form.DataComponent;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.event.FieldEvents.TextChangeEvent;
import com.vaadin.event.FieldEvents.TextChangeListener;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
public class DataComponentLayout extends VerticalLayout implements IEntryVisitor, IUpdateableListener {
/**
*
*/
private static final long serialVersionUID = 1L;
private DataComponent component;
public DataComponentLayout(DataComponent comp) {
super();
component = comp;
component.retrieveAllEntries().forEach(entry -> {
entry.accept(this);
});
setMargin(true);
setSpacing(true);
component.register(this);
setCaption(component.getName());
}
@Override
public void visit(StringEntry entry) {
// TODO Auto-generated method stub
TextField text = new TextField();
text.setCaption(entry.getName());
text.setDescription(entry.getDescription());
text.setValue(entry.getValue() == null ? entry.getDefaultValue() : entry.getValue());
text.addTextChangeListener(event -> entry.setValue(event.getText()));
addComponent(text);
}
@Override
public void visit(DiscreteEntry entry) {
// TODO Auto-generated method stub
ComboBox dropdown = new ComboBox();
dropdown.setCaption(entry.getName());
dropdown.setDescription(entry.getDescription());
dropdown.addItems(entry.getAllowedValues());
dropdown.addValueChangeListener(e -> entry.setValue((String)dropdown.getValue()));
dropdown.setValue(entry.getAllowedValues().get(0));
addComponent(dropdown);
}
@Override
public void visit(ExecutableEntry entry) {
// TODO Auto-generated method stub
System.out.println("ExecutableEntry not implemented");
}
@Override
public void visit(ContinuousEntry entry) {
// TODO Auto-generated method stub
System.out.println("ContinuousEntry not implemented");
}
@Override
public void visit(FileEntry entry) {
// TODO Auto-generated method stub
System.out.println("FileEntry not implemented");
}
@Override
public void visit(MultiValueEntry entry) {
// TODO Auto-generated method stub
System.out.println("MultiValueEntry not implemented");
}
@Override
public void update(IUpdateable dataComponent) {
System.out.println("UPDATING " + dataComponent.getName());
getUI().getSession().getLockInstance().lock();
try {
removeAllComponents();
component.retrieveAllEntries().forEach(entry -> {
entry.accept(this);
});
} finally {
getUI().getSession().getLockInstance().unlock();
}
}
}
| bsd-3-clause |
liry/gooddata-java | src/main/java/com/gooddata/dataset/Datasets.java | 799 | /**
* Copyright (C) 2004-2016, GoodData(R) Corporation. All rights reserved.
* This source code is licensed under the BSD-style license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
package com.gooddata.dataset;
import com.fasterxml.jackson.annotation.*;
import com.gooddata.gdc.AboutLinks;
import java.util.List;
/**
* Dataset links
* @deprecated use {@link DatasetLinks} instead.
*/
@Deprecated
class Datasets extends AboutLinks {
public static final String URI = "/gdc/md/{project}/ldm/singleloadinterface";
@JsonCreator
public Datasets(@JsonProperty("category") String category, @JsonProperty("summary") String summary,
@JsonProperty("links") List<Link> links) {
super(category, summary, null, links);
}
}
| bsd-3-clause |
ericdahl/hello-ecs | app/src/main/java/example/endpoints/AppController.java | 850 | package example.endpoints;
import example.services.CountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AppController {
@Value("${HOSTNAME:unknown}")
private String hostname;
private final CountService counterService;
@Autowired
public AppController(CountService counterService) {
this.counterService = counterService;
}
@GetMapping(produces = MediaType.TEXT_PLAIN_VALUE)
public String index() {
final long count = counterService.count();
return "Hello from " + hostname + " (count is " + count + ")";
}
}
| bsd-3-clause |
thegreatape/slim | yuicompressor-2.4.2/src/com/yahoo/platform/yui/compressor/CssCompressor.java | 7176 | /*
* YUI Compressor
* Author: Julien Lecomte <jlecomte@yahoo-inc.com>
* Copyright (c) 2007, Yahoo! Inc. All rights reserved.
* Code licensed under the BSD License:
* http://developer.yahoo.net/yui/license.txt
*
* This code is a port of Isaac Schlueter's cssmin utility.
*/
package com.yahoo.platform.yui.compressor;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class CssCompressor {
private StringBuffer srcsb = new StringBuffer();
public CssCompressor(Reader in) throws IOException {
// Read the stream...
int c;
while ((c = in.read()) != -1) {
srcsb.append((char) c);
}
}
public String compress(int linebreakpos) throws IOException{
return compress(null, linebreakpos);
}
public String compress(Writer out, int linebreakpos)
throws IOException {
Pattern p;
Matcher m;
String css;
StringBuffer sb;
int startIndex, endIndex;
// Remove all comment blocks...
startIndex = 0;
boolean iemac = false;
boolean preserve = false;
sb = new StringBuffer(srcsb.toString());
while ((startIndex = sb.indexOf("/*", startIndex)) >= 0) {
preserve = sb.length() > startIndex + 2 && sb.charAt(startIndex + 2) == '!';
endIndex = sb.indexOf("*/", startIndex + 2);
if (endIndex < 0) {
if (!preserve) {
sb.delete(startIndex, sb.length());
}
} else if (endIndex >= startIndex + 2) {
if (sb.charAt(endIndex-1) == '\\') {
// Looks like a comment to hide rules from IE Mac.
// Leave this comment, and the following one, alone...
startIndex = endIndex + 2;
iemac = true;
} else if (iemac) {
startIndex = endIndex + 2;
iemac = false;
} else if (!preserve) {
sb.delete(startIndex, endIndex + 2);
} else {
startIndex = endIndex + 2;
}
}
}
css = sb.toString();
// Normalize all whitespace strings to single spaces. Easier to work with that way.
css = css.replaceAll("\\s+", " ");
// Make a pseudo class for the Box Model Hack
css = css.replaceAll("\"\\\\\"}\\\\\"\"", "___PSEUDOCLASSBMH___");
// Remove the spaces before the things that should not have spaces before them.
// But, be careful not to turn "p :link {...}" into "p:link{...}"
// Swap out any pseudo-class colons with the token, and then swap back.
sb = new StringBuffer();
p = Pattern.compile("(^|\\})(([^\\{:])+:)+([^\\{]*\\{)");
m = p.matcher(css);
while (m.find()) {
String s = m.group();
s = s.replaceAll(":", "___PSEUDOCLASSCOLON___");
m.appendReplacement(sb, s);
}
m.appendTail(sb);
css = sb.toString();
css = css.replaceAll("\\s+([!{};:>+\\(\\)\\],])", "$1");
css = css.replaceAll("___PSEUDOCLASSCOLON___", ":");
// Remove the spaces after the things that should not have spaces after them.
css = css.replaceAll("([!{}:;>+\\(\\[,])\\s+", "$1");
// Add the semicolon where it's missing.
css = css.replaceAll("([^;\\}])}", "$1;}");
// Replace 0(px,em,%) with 0.
css = css.replaceAll("([\\s:])(0)(px|em|%|in|cm|mm|pc|pt|ex)", "$1$2");
// Replace 0 0 0 0; with 0.
css = css.replaceAll(":0 0 0 0;", ":0;");
css = css.replaceAll(":0 0 0;", ":0;");
css = css.replaceAll(":0 0;", ":0;");
// Replace background-position:0; with background-position:0 0;
css = css.replaceAll("background-position:0;", "background-position:0 0;");
// Replace 0.6 to .6, but only when preceded by : or a white-space
css = css.replaceAll("(:|\\s)0+\\.(\\d+)", "$1.$2");
// Shorten colors from rgb(51,102,153) to #336699
// This makes it more likely that it'll get further compressed in the next step.
p = Pattern.compile("rgb\\s*\\(\\s*([0-9,\\s]+)\\s*\\)");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
String[] rgbcolors = m.group(1).split(",");
StringBuffer hexcolor = new StringBuffer("#");
for (int i = 0; i < rgbcolors.length; i++) {
int val = Integer.parseInt(rgbcolors[i]);
if (val < 16) {
hexcolor.append("0");
}
hexcolor.append(Integer.toHexString(val));
}
m.appendReplacement(sb, hexcolor.toString());
}
m.appendTail(sb);
css = sb.toString();
// Shorten colors from #AABBCC to #ABC. Note that we want to make sure
// the color is not preceded by either ", " or =. Indeed, the property
// filter: chroma(color="#FFFFFF");
// would become
// filter: chroma(color="#FFF");
// which makes the filter break in IE.
p = Pattern.compile("([^\"'=\\s])(\\s*)#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])");
m = p.matcher(css);
sb = new StringBuffer();
while (m.find()) {
// Test for AABBCC pattern
if (m.group(3).equalsIgnoreCase(m.group(4)) &&
m.group(5).equalsIgnoreCase(m.group(6)) &&
m.group(7).equalsIgnoreCase(m.group(8))) {
m.appendReplacement(sb, m.group(1) + m.group(2) + "#" + m.group(3) + m.group(5) + m.group(7));
} else {
m.appendReplacement(sb, m.group());
}
}
m.appendTail(sb);
css = sb.toString();
// Remove empty rules.
css = css.replaceAll("[^\\}]+\\{;\\}", "");
if (linebreakpos >= 0) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
int i = 0;
int linestartpos = 0;
sb = new StringBuffer(css);
while (i < sb.length()) {
char c = sb.charAt(i++);
if (c == '}' && i - linestartpos > linebreakpos) {
sb.insert(i, '\n');
linestartpos = i;
}
}
css = sb.toString();
}
// Replace the pseudo class for the Box Model Hack
css = css.replaceAll("___PSEUDOCLASSBMH___", "\"\\\\\"}\\\\\"\"");
// Replace multiple semi-colons in a row by a single one
// See SF bug #1980989
css = css.replaceAll(";;+", ";");
// Trim the final string (for any leading or trailing white spaces)
css = css.trim();
if(out != null){
out.write(css);
}
return css;
}
}
| bsd-3-clause |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/dedicated/server/OvhVmacTypeEnum.java | 277 | package net.minidev.ovh.api.dedicated.server;
/**
* Distinct type of virtual mac
*/
public enum OvhVmacTypeEnum {
ovh("ovh"),
vmware("vmware");
final String value;
OvhVmacTypeEnum(String s) {
this.value = s;
}
public String toString() {
return this.value;
}
}
| bsd-3-clause |
bdzimmer/pixel-editor | src/main/java/bdzimmer/pixeleditor/view/PaletteWindow.java | 8983 | // Copyright (c) 2016 Ben Zimmer. All rights reserved.
// A more flexible version of PaletteWindow using the new data model
package bdzimmer.pixeleditor.view;
import bdzimmer.pixeleditor.controller.PaletteUtils;
import bdzimmer.pixeleditor.model.Color;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.Image;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
// TODO: use CommonWindow
// TODO: consider scala rewrite
public class PaletteWindow extends JFrame {
private static final long serialVersionUID = 1L;
private static final int swatchSize = 16;
private static final int cols = 16;
private final Color[] palette;
private final Canvas cColorLabel;
private final BufferedImage image;
private final ImagePanel imagePanel;
private final int length;
private final int rows;
private final int colorFactor;
private final int bitsPerChannel;
public final Updater updater;
private JSpinner rVal = new JSpinner();
private JSpinner gVal = new JSpinner();
private JSpinner bVal = new JSpinner();
private int selectedIdx = 0;
public PaletteWindow(
String title,
Color[] palette,
int bitsPerChannel,
Updater updater) {
setTitle(title);
this.palette = palette;
length = this.palette.length;
this.updater = updater;
rows = (length + cols - 1) / cols;
image = PaletteWindow.imageForPalette(length, cols, swatchSize);
imagePanel = new ImagePanel(image);
add(imagePanel);
// Currently selected color
cColorLabel = new Canvas();
cColorLabel.setSize(32, 32);
cColorLabel.setBackground(new java.awt.Color(0, 0, 0));
this.bitsPerChannel = bitsPerChannel;
final int colorMax = (1 << bitsPerChannel) - 1;
colorFactor = (1 << (8 - bitsPerChannel));
rVal.setModel(new SpinnerNumberModel(0, 0, colorMax, 1));
gVal.setModel(new SpinnerNumberModel(0, 0, colorMax, 1));
bVal.setModel(new SpinnerNumberModel(0, 0, colorMax, 1));
rVal.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
SpinnerNumberModel currentModel = (SpinnerNumberModel)((JSpinner) event.getSource()).getModel();
int red = (Integer)currentModel.getValue();
Color cc = PaletteWindow.this.palette[selectedIdx];
Color nc = new Color(red, cc.g(), cc.b());
PaletteWindow.this.palette[selectedIdx] = nc;
update();
}
});
gVal.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
SpinnerNumberModel currentModel = (SpinnerNumberModel)((JSpinner) event.getSource()).getModel();
int green = (Integer)currentModel.getValue();
Color cc = PaletteWindow.this.palette[selectedIdx];
Color nc = new Color(cc.r(), green, cc.b());
PaletteWindow.this.palette[selectedIdx] = nc;
update();
}
});
bVal.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
SpinnerNumberModel currentModel = (SpinnerNumberModel)((JSpinner) event.getSource()).getModel();
int blue = (Integer)currentModel.getValue();
Color cc = PaletteWindow.this.palette[selectedIdx];
Color nc = new Color(cc.r(), cc.g(), blue);
PaletteWindow.this.palette[selectedIdx] = nc;
update();
}
});
imagePanel.setToolTipText("<html>right click: grab color<br />left click: set color<br />alt-left click: interpolate colors</html>");
imagePanel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
int clickedIdx = (int) ((event.getY() / swatchSize) * cols) + (int) (event.getX() / swatchSize);
// System.out.println("clicked color: " + clickedColor + " " + PaletteEditorNew.this.palette[clickedColor]);
if (clickedIdx < length && clickedIdx >= 0) {
if (event.isMetaDown()) {
// right click - grab color
selectedIdx = clickedIdx;
} else {
// left click - interpolate or copy set color
if (event.isAltDown()) {
System.out.println("linear interpolation");
PaletteUtils.interpolateLinear(
PaletteWindow.this.palette, selectedIdx, clickedIdx);
} else {
Color srcColor = PaletteWindow.this.palette[selectedIdx];
PaletteWindow.this.palette[clickedIdx] = new Color(srcColor.r(), srcColor.g(), srcColor.b());
}
// update after done updating the colors / current selection
selectedIdx = clickedIdx;
}
update();
}
}
});
JPanel sp = new JPanel();
sp.setMaximumSize(imagePanel.getSize());
sp.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
sp.add(new JLabel("R"));
sp.add(rVal);
sp.add(new JLabel("G"));
sp.add(gVal);
sp.add(new JLabel("B"));
sp.add(bVal);
sp.add(cColorLabel);
add(sp, BorderLayout.SOUTH);
addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent event) {
update();
}
});
setFocusable(true);
addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent event) {
Color color = PaletteWindow.this.palette[selectedIdx];
int r = color.r();
int g = color.g();
int b = color.b();
if (event.getKeyCode() == KeyEvent.VK_A) {
r++; if (r > colorMax) r = 0;
} else if (event.getKeyCode() == KeyEvent.VK_Z) {
r--; if (r < 0) r = colorMax;
} else if (event.getKeyCode() == KeyEvent.VK_S) {
g++; if (g > colorMax) g = 0;
} else if (event.getKeyCode() == KeyEvent.VK_X) {
g--; if (g < 0) g = colorMax;
} else if (event.getKeyCode() == KeyEvent.VK_D) {
b++; if (b > colorMax) b = 0;
} else if (event.getKeyCode() == KeyEvent.VK_C) {
b--; if (b < 0) b = colorMax;
}
PaletteWindow.this.palette[selectedIdx] = new Color(r, g, b);
update();
}
public void keyReleased(KeyEvent event) {}
public void keyTyped(KeyEvent event) {}
});
pack();
setResizable(false);
}
public void refreshPalette() {
// redraw palette swatches
PaletteWindow.drawPalette(image, palette, bitsPerChannel, rows, cols, swatchSize);
// draw the selection
Graphics gr = image.getGraphics();
final java.awt.Color selectColor = new java.awt.Color(230, 0, 230);
gr.setColor(selectColor);
int x = (selectedIdx % cols) * swatchSize;
int y = (int) (selectedIdx / cols) * swatchSize;
gr.drawRect(x, y, swatchSize, swatchSize);
imagePanel.repaint();
// update the color sample and spinners
Color color = palette[selectedIdx];
cColorLabel.setBackground(new java.awt.Color(
color.r() * colorFactor, color.g() * colorFactor, color.b() * colorFactor));
updateSpinners();
}
public void updateSpinners() {
final Color color = palette[selectedIdx];
rVal.setValue(color.r());
gVal.setValue(color.g());
bVal.setValue(color.b());
}
public void update() {
if (updater != null) {
updater.update();
}
refreshPalette();
}
public void paint(Graphics g) {
super.paint(g);
refreshPalette();
}
////////
public int getSelectedIdx() {
return selectedIdx;
}
public void setSelectedIdx(int selectedIdx) {
this.selectedIdx = selectedIdx;
}
public Color[] getPalette() {
return palette;
}
public int getBitsPerChannel() {
return bitsPerChannel;
}
///
public static void drawPalette(Image image, Color[] palette, int bitsPerChannel, int rows, int cols, int swatchSize) {
int colorFactor = (1 << (8 - bitsPerChannel));
Graphics gr = image.getGraphics();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
final int colorIdx = i * cols + j;
if (colorIdx < palette.length) {
Color color = palette[colorIdx];
gr.setColor(new java.awt.Color(
color.r() * colorFactor, color.g() * colorFactor, color.b() * colorFactor));
gr.fillRect(j * swatchSize, i * swatchSize, swatchSize, swatchSize);
}
}
}
}
public static BufferedImage imageForPalette(int length, int cols, int swatchSize) {
int rows = length / cols;
return new BufferedImage(cols * swatchSize, rows * swatchSize, BufferedImage.TYPE_INT_RGB);
}
}
| bsd-3-clause |
cfmobile/arca-android | arca-core/arca-provider/src/main/java/io/pivotal/arca/provider/ColumnName.java | 336 | package io.pivotal.arca.provider;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ColumnName {
String value();
}
| bsd-3-clause |
endlessm/chromium-browser | chrome/android/java/src/org/chromium/chrome/browser/firstrun/FirstRunUtils.java | 5055 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.firstrun;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.UserManager;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.ContextUtils;
import org.chromium.base.annotations.NativeMethods;
import org.chromium.chrome.browser.metrics.UmaSessionStats;
import org.chromium.chrome.browser.preferences.ChromePreferenceKeys;
import org.chromium.chrome.browser.preferences.SharedPreferencesManager;
import org.chromium.components.signin.AccountManagerFacade;
import org.chromium.components.signin.AccountManagerFacadeProvider;
/** Provides first run related utility functions. */
public class FirstRunUtils {
private static Boolean sHasGoogleAccountAuthenticator;
/**
* Synchronizes first run native and Java preferences.
* Must be called after native initialization.
*/
public static void cacheFirstRunPrefs() {
SharedPreferencesManager javaPrefs = SharedPreferencesManager.getInstance();
// Set both Java and native prefs if any of the three indicators indicate ToS has been
// accepted. This needed because:
// - Old versions only set native pref, so this syncs Java pref.
// - Backup & restore does not restore native pref, so this needs to update it.
// - checkAnyUserHasSeenToS() may be true which needs to sync its state to the prefs.
boolean javaPrefValue =
javaPrefs.readBoolean(ChromePreferenceKeys.FIRST_RUN_CACHED_TOS_ACCEPTED, false);
boolean nativePrefValue = isFirstRunEulaAccepted();
boolean userHasSeenTos =
ToSAckedReceiver.checkAnyUserHasSeenToS();
boolean isFirstRunComplete = FirstRunStatus.getFirstRunFlowComplete();
if (javaPrefValue || nativePrefValue || userHasSeenTos || isFirstRunComplete) {
if (!javaPrefValue) {
javaPrefs.writeBoolean(ChromePreferenceKeys.FIRST_RUN_CACHED_TOS_ACCEPTED, true);
}
if (!nativePrefValue) {
setEulaAccepted();
}
}
}
/**
* @return Whether the user has accepted Chrome Terms of Service.
*/
public static boolean didAcceptTermsOfService() {
// Note: Does not check FirstRunUtils.isFirstRunEulaAccepted() because this may be called
// before native is initialized.
return SharedPreferencesManager.getInstance().readBoolean(
ChromePreferenceKeys.FIRST_RUN_CACHED_TOS_ACCEPTED, false)
|| ToSAckedReceiver.checkAnyUserHasSeenToS();
}
/**
* Sets the EULA/Terms of Services state as "ACCEPTED".
* @param allowCrashUpload True if the user allows to upload crash dumps and collect stats.
*/
public static void acceptTermsOfService(boolean allowCrashUpload) {
UmaSessionStats.changeMetricsReportingConsent(allowCrashUpload);
SharedPreferencesManager.getInstance().writeBoolean(
ChromePreferenceKeys.FIRST_RUN_CACHED_TOS_ACCEPTED, true);
setEulaAccepted();
}
/**
* Determines whether or not the user has a Google account (so we can sync) or can add one.
* @return Whether or not sync is allowed on this device.
*/
static boolean canAllowSync() {
return (hasGoogleAccountAuthenticator() && hasSyncPermissions()) || hasGoogleAccounts();
}
@VisibleForTesting
static boolean hasGoogleAccountAuthenticator() {
if (sHasGoogleAccountAuthenticator == null) {
AccountManagerFacade accountHelper = AccountManagerFacadeProvider.getInstance();
sHasGoogleAccountAuthenticator = accountHelper.hasGoogleAccountAuthenticator();
}
return sHasGoogleAccountAuthenticator;
}
@VisibleForTesting
static boolean hasGoogleAccounts() {
return !AccountManagerFacadeProvider.getInstance().tryGetGoogleAccounts().isEmpty();
}
@SuppressLint("InlinedApi")
private static boolean hasSyncPermissions() {
UserManager manager = (UserManager) ContextUtils.getApplicationContext().getSystemService(
Context.USER_SERVICE);
Bundle userRestrictions = manager.getUserRestrictions();
return !userRestrictions.getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, false);
}
/**
* @return Whether EULA has been accepted by the user.
*/
public static boolean isFirstRunEulaAccepted() {
return FirstRunUtilsJni.get().getFirstRunEulaAccepted();
}
/**
* Sets the preference that signals when the user has accepted the EULA.
*/
public static void setEulaAccepted() {
FirstRunUtilsJni.get().setEulaAccepted();
}
@NativeMethods
public interface Natives {
boolean getFirstRunEulaAccepted();
void setEulaAccepted();
}
}
| bsd-3-clause |
landrito/api-client-staging | generated/java/proto-google-cloud-logging-v2/src/main/java/com/google/logging/v2/ListLogEntriesRequest.java | 55652 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/logging/v2/logging.proto
package com.google.logging.v2;
/**
* <pre>
* The parameters to `ListLogEntries`.
* </pre>
*
* Protobuf type {@code google.logging.v2.ListLogEntriesRequest}
*/
public final class ListLogEntriesRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.logging.v2.ListLogEntriesRequest)
ListLogEntriesRequestOrBuilder {
// Use ListLogEntriesRequest.newBuilder() to construct.
private ListLogEntriesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListLogEntriesRequest() {
projectIds_ = com.google.protobuf.LazyStringArrayList.EMPTY;
resourceNames_ = com.google.protobuf.LazyStringArrayList.EMPTY;
filter_ = "";
orderBy_ = "";
pageSize_ = 0;
pageToken_ = "";
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private ListLogEntriesRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 10: {
java.lang.String s = input.readStringRequireUtf8();
if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
projectIds_ = new com.google.protobuf.LazyStringArrayList();
mutable_bitField0_ |= 0x00000001;
}
projectIds_.add(s);
break;
}
case 18: {
java.lang.String s = input.readStringRequireUtf8();
filter_ = s;
break;
}
case 26: {
java.lang.String s = input.readStringRequireUtf8();
orderBy_ = s;
break;
}
case 32: {
pageSize_ = input.readInt32();
break;
}
case 42: {
java.lang.String s = input.readStringRequireUtf8();
pageToken_ = s;
break;
}
case 66: {
java.lang.String s = input.readStringRequireUtf8();
if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) {
resourceNames_ = new com.google.protobuf.LazyStringArrayList();
mutable_bitField0_ |= 0x00000002;
}
resourceNames_.add(s);
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
projectIds_ = projectIds_.getUnmodifiableView();
}
if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) {
resourceNames_ = resourceNames_.getUnmodifiableView();
}
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.logging.v2.LoggingProto.internal_static_google_logging_v2_ListLogEntriesRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.logging.v2.LoggingProto.internal_static_google_logging_v2_ListLogEntriesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.logging.v2.ListLogEntriesRequest.class, com.google.logging.v2.ListLogEntriesRequest.Builder.class);
}
private int bitField0_;
public static final int PROJECT_IDS_FIELD_NUMBER = 1;
private com.google.protobuf.LazyStringList projectIds_;
/**
* <pre>
* Deprecated. Use `resource_names` instead. One or more project identifiers
* or project numbers from which to retrieve log entries. Example:
* `"my-project-1A"`. If present, these project identifiers are converted to
* resource name format and added to the list of resources in
* `resource_names`.
* </pre>
*
* <code>repeated string project_ids = 1;</code>
*/
public com.google.protobuf.ProtocolStringList
getProjectIdsList() {
return projectIds_;
}
/**
* <pre>
* Deprecated. Use `resource_names` instead. One or more project identifiers
* or project numbers from which to retrieve log entries. Example:
* `"my-project-1A"`. If present, these project identifiers are converted to
* resource name format and added to the list of resources in
* `resource_names`.
* </pre>
*
* <code>repeated string project_ids = 1;</code>
*/
public int getProjectIdsCount() {
return projectIds_.size();
}
/**
* <pre>
* Deprecated. Use `resource_names` instead. One or more project identifiers
* or project numbers from which to retrieve log entries. Example:
* `"my-project-1A"`. If present, these project identifiers are converted to
* resource name format and added to the list of resources in
* `resource_names`.
* </pre>
*
* <code>repeated string project_ids = 1;</code>
*/
public java.lang.String getProjectIds(int index) {
return projectIds_.get(index);
}
/**
* <pre>
* Deprecated. Use `resource_names` instead. One or more project identifiers
* or project numbers from which to retrieve log entries. Example:
* `"my-project-1A"`. If present, these project identifiers are converted to
* resource name format and added to the list of resources in
* `resource_names`.
* </pre>
*
* <code>repeated string project_ids = 1;</code>
*/
public com.google.protobuf.ByteString
getProjectIdsBytes(int index) {
return projectIds_.getByteString(index);
}
public static final int RESOURCE_NAMES_FIELD_NUMBER = 8;
private com.google.protobuf.LazyStringList resourceNames_;
/**
* <pre>
* Required. Names of one or more parent resources from which to
* retrieve log entries:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* Projects listed in the `project_ids` field are added to this list.
* </pre>
*
* <code>repeated string resource_names = 8;</code>
*/
public com.google.protobuf.ProtocolStringList
getResourceNamesList() {
return resourceNames_;
}
/**
* <pre>
* Required. Names of one or more parent resources from which to
* retrieve log entries:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* Projects listed in the `project_ids` field are added to this list.
* </pre>
*
* <code>repeated string resource_names = 8;</code>
*/
public int getResourceNamesCount() {
return resourceNames_.size();
}
/**
* <pre>
* Required. Names of one or more parent resources from which to
* retrieve log entries:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* Projects listed in the `project_ids` field are added to this list.
* </pre>
*
* <code>repeated string resource_names = 8;</code>
*/
public java.lang.String getResourceNames(int index) {
return resourceNames_.get(index);
}
/**
* <pre>
* Required. Names of one or more parent resources from which to
* retrieve log entries:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* Projects listed in the `project_ids` field are added to this list.
* </pre>
*
* <code>repeated string resource_names = 8;</code>
*/
public com.google.protobuf.ByteString
getResourceNamesBytes(int index) {
return resourceNames_.getByteString(index);
}
public static final int FILTER_FIELD_NUMBER = 2;
private volatile java.lang.Object filter_;
/**
* <pre>
* Optional. A filter that chooses which log entries to return. See [Advanced
* Logs Filters](/logging/docs/view/advanced_filters). Only log entries that
* match the filter are returned. An empty filter matches all log entries in
* the resources listed in `resource_names`. Referencing a parent resource
* that is not listed in `resource_names` will cause the filter to return no
* results.
* The maximum length of the filter is 20000 characters.
* </pre>
*
* <code>optional string filter = 2;</code>
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
* <pre>
* Optional. A filter that chooses which log entries to return. See [Advanced
* Logs Filters](/logging/docs/view/advanced_filters). Only log entries that
* match the filter are returned. An empty filter matches all log entries in
* the resources listed in `resource_names`. Referencing a parent resource
* that is not listed in `resource_names` will cause the filter to return no
* results.
* The maximum length of the filter is 20000 characters.
* </pre>
*
* <code>optional string filter = 2;</code>
*/
public com.google.protobuf.ByteString
getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORDER_BY_FIELD_NUMBER = 3;
private volatile java.lang.Object orderBy_;
/**
* <pre>
* Optional. How the results should be sorted. Presently, the only permitted
* values are `"timestamp asc"` (default) and `"timestamp desc"`. The first
* option returns entries in order of increasing values of
* `LogEntry.timestamp` (oldest first), and the second option returns entries
* in order of decreasing timestamps (newest first). Entries with equal
* timestamps are returned in order of their `insert_id` values.
* </pre>
*
* <code>optional string order_by = 3;</code>
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
}
}
/**
* <pre>
* Optional. How the results should be sorted. Presently, the only permitted
* values are `"timestamp asc"` (default) and `"timestamp desc"`. The first
* option returns entries in order of increasing values of
* `LogEntry.timestamp` (oldest first), and the second option returns entries
* in order of decreasing timestamps (newest first). Entries with equal
* timestamps are returned in order of their `insert_id` values.
* </pre>
*
* <code>optional string order_by = 3;</code>
*/
public com.google.protobuf.ByteString
getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 4;
private int pageSize_;
/**
* <pre>
* Optional. The maximum number of results to return from this request.
* Non-positive values are ignored. The presence of `next_page_token` in the
* response indicates that more results might be available.
* </pre>
*
* <code>optional int32 page_size = 4;</code>
*/
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 5;
private volatile java.lang.Object pageToken_;
/**
* <pre>
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `page_token` must be the value of
* `next_page_token` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* </pre>
*
* <code>optional string page_token = 5;</code>
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
* <pre>
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `page_token` must be the value of
* `next_page_token` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* </pre>
*
* <code>optional string page_token = 5;</code>
*/
public com.google.protobuf.ByteString
getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
for (int i = 0; i < projectIds_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, projectIds_.getRaw(i));
}
if (!getFilterBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, filter_);
}
if (!getOrderByBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, orderBy_);
}
if (pageSize_ != 0) {
output.writeInt32(4, pageSize_);
}
if (!getPageTokenBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, pageToken_);
}
for (int i = 0; i < resourceNames_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 8, resourceNames_.getRaw(i));
}
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
{
int dataSize = 0;
for (int i = 0; i < projectIds_.size(); i++) {
dataSize += computeStringSizeNoTag(projectIds_.getRaw(i));
}
size += dataSize;
size += 1 * getProjectIdsList().size();
}
if (!getFilterBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, filter_);
}
if (!getOrderByBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, orderBy_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(4, pageSize_);
}
if (!getPageTokenBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, pageToken_);
}
{
int dataSize = 0;
for (int i = 0; i < resourceNames_.size(); i++) {
dataSize += computeStringSizeNoTag(resourceNames_.getRaw(i));
}
size += dataSize;
size += 1 * getResourceNamesList().size();
}
memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.logging.v2.ListLogEntriesRequest)) {
return super.equals(obj);
}
com.google.logging.v2.ListLogEntriesRequest other = (com.google.logging.v2.ListLogEntriesRequest) obj;
boolean result = true;
result = result && getProjectIdsList()
.equals(other.getProjectIdsList());
result = result && getResourceNamesList()
.equals(other.getResourceNamesList());
result = result && getFilter()
.equals(other.getFilter());
result = result && getOrderBy()
.equals(other.getOrderBy());
result = result && (getPageSize()
== other.getPageSize());
result = result && getPageToken()
.equals(other.getPageToken());
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptorForType().hashCode();
if (getProjectIdsCount() > 0) {
hash = (37 * hash) + PROJECT_IDS_FIELD_NUMBER;
hash = (53 * hash) + getProjectIdsList().hashCode();
}
if (getResourceNamesCount() > 0) {
hash = (37 * hash) + RESOURCE_NAMES_FIELD_NUMBER;
hash = (53 * hash) + getResourceNamesList().hashCode();
}
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.logging.v2.ListLogEntriesRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.logging.v2.ListLogEntriesRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.logging.v2.ListLogEntriesRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.logging.v2.ListLogEntriesRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.logging.v2.ListLogEntriesRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.logging.v2.ListLogEntriesRequest parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.logging.v2.ListLogEntriesRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.logging.v2.ListLogEntriesRequest parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.logging.v2.ListLogEntriesRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.logging.v2.ListLogEntriesRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.logging.v2.ListLogEntriesRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* The parameters to `ListLogEntries`.
* </pre>
*
* Protobuf type {@code google.logging.v2.ListLogEntriesRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.logging.v2.ListLogEntriesRequest)
com.google.logging.v2.ListLogEntriesRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.logging.v2.LoggingProto.internal_static_google_logging_v2_ListLogEntriesRequest_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.logging.v2.LoggingProto.internal_static_google_logging_v2_ListLogEntriesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.logging.v2.ListLogEntriesRequest.class, com.google.logging.v2.ListLogEntriesRequest.Builder.class);
}
// Construct using com.google.logging.v2.ListLogEntriesRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
projectIds_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000001);
resourceNames_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000002);
filter_ = "";
orderBy_ = "";
pageSize_ = 0;
pageToken_ = "";
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.logging.v2.LoggingProto.internal_static_google_logging_v2_ListLogEntriesRequest_descriptor;
}
public com.google.logging.v2.ListLogEntriesRequest getDefaultInstanceForType() {
return com.google.logging.v2.ListLogEntriesRequest.getDefaultInstance();
}
public com.google.logging.v2.ListLogEntriesRequest build() {
com.google.logging.v2.ListLogEntriesRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.google.logging.v2.ListLogEntriesRequest buildPartial() {
com.google.logging.v2.ListLogEntriesRequest result = new com.google.logging.v2.ListLogEntriesRequest(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
projectIds_ = projectIds_.getUnmodifiableView();
bitField0_ = (bitField0_ & ~0x00000001);
}
result.projectIds_ = projectIds_;
if (((bitField0_ & 0x00000002) == 0x00000002)) {
resourceNames_ = resourceNames_.getUnmodifiableView();
bitField0_ = (bitField0_ & ~0x00000002);
}
result.resourceNames_ = resourceNames_;
result.filter_ = filter_;
result.orderBy_ = orderBy_;
result.pageSize_ = pageSize_;
result.pageToken_ = pageToken_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.logging.v2.ListLogEntriesRequest) {
return mergeFrom((com.google.logging.v2.ListLogEntriesRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.logging.v2.ListLogEntriesRequest other) {
if (other == com.google.logging.v2.ListLogEntriesRequest.getDefaultInstance()) return this;
if (!other.projectIds_.isEmpty()) {
if (projectIds_.isEmpty()) {
projectIds_ = other.projectIds_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureProjectIdsIsMutable();
projectIds_.addAll(other.projectIds_);
}
onChanged();
}
if (!other.resourceNames_.isEmpty()) {
if (resourceNames_.isEmpty()) {
resourceNames_ = other.resourceNames_;
bitField0_ = (bitField0_ & ~0x00000002);
} else {
ensureResourceNamesIsMutable();
resourceNames_.addAll(other.resourceNames_);
}
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
onChanged();
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
onChanged();
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.logging.v2.ListLogEntriesRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.logging.v2.ListLogEntriesRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private com.google.protobuf.LazyStringList projectIds_ = com.google.protobuf.LazyStringArrayList.EMPTY;
private void ensureProjectIdsIsMutable() {
if (!((bitField0_ & 0x00000001) == 0x00000001)) {
projectIds_ = new com.google.protobuf.LazyStringArrayList(projectIds_);
bitField0_ |= 0x00000001;
}
}
/**
* <pre>
* Deprecated. Use `resource_names` instead. One or more project identifiers
* or project numbers from which to retrieve log entries. Example:
* `"my-project-1A"`. If present, these project identifiers are converted to
* resource name format and added to the list of resources in
* `resource_names`.
* </pre>
*
* <code>repeated string project_ids = 1;</code>
*/
public com.google.protobuf.ProtocolStringList
getProjectIdsList() {
return projectIds_.getUnmodifiableView();
}
/**
* <pre>
* Deprecated. Use `resource_names` instead. One or more project identifiers
* or project numbers from which to retrieve log entries. Example:
* `"my-project-1A"`. If present, these project identifiers are converted to
* resource name format and added to the list of resources in
* `resource_names`.
* </pre>
*
* <code>repeated string project_ids = 1;</code>
*/
public int getProjectIdsCount() {
return projectIds_.size();
}
/**
* <pre>
* Deprecated. Use `resource_names` instead. One or more project identifiers
* or project numbers from which to retrieve log entries. Example:
* `"my-project-1A"`. If present, these project identifiers are converted to
* resource name format and added to the list of resources in
* `resource_names`.
* </pre>
*
* <code>repeated string project_ids = 1;</code>
*/
public java.lang.String getProjectIds(int index) {
return projectIds_.get(index);
}
/**
* <pre>
* Deprecated. Use `resource_names` instead. One or more project identifiers
* or project numbers from which to retrieve log entries. Example:
* `"my-project-1A"`. If present, these project identifiers are converted to
* resource name format and added to the list of resources in
* `resource_names`.
* </pre>
*
* <code>repeated string project_ids = 1;</code>
*/
public com.google.protobuf.ByteString
getProjectIdsBytes(int index) {
return projectIds_.getByteString(index);
}
/**
* <pre>
* Deprecated. Use `resource_names` instead. One or more project identifiers
* or project numbers from which to retrieve log entries. Example:
* `"my-project-1A"`. If present, these project identifiers are converted to
* resource name format and added to the list of resources in
* `resource_names`.
* </pre>
*
* <code>repeated string project_ids = 1;</code>
*/
public Builder setProjectIds(
int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureProjectIdsIsMutable();
projectIds_.set(index, value);
onChanged();
return this;
}
/**
* <pre>
* Deprecated. Use `resource_names` instead. One or more project identifiers
* or project numbers from which to retrieve log entries. Example:
* `"my-project-1A"`. If present, these project identifiers are converted to
* resource name format and added to the list of resources in
* `resource_names`.
* </pre>
*
* <code>repeated string project_ids = 1;</code>
*/
public Builder addProjectIds(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureProjectIdsIsMutable();
projectIds_.add(value);
onChanged();
return this;
}
/**
* <pre>
* Deprecated. Use `resource_names` instead. One or more project identifiers
* or project numbers from which to retrieve log entries. Example:
* `"my-project-1A"`. If present, these project identifiers are converted to
* resource name format and added to the list of resources in
* `resource_names`.
* </pre>
*
* <code>repeated string project_ids = 1;</code>
*/
public Builder addAllProjectIds(
java.lang.Iterable<java.lang.String> values) {
ensureProjectIdsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, projectIds_);
onChanged();
return this;
}
/**
* <pre>
* Deprecated. Use `resource_names` instead. One or more project identifiers
* or project numbers from which to retrieve log entries. Example:
* `"my-project-1A"`. If present, these project identifiers are converted to
* resource name format and added to the list of resources in
* `resource_names`.
* </pre>
*
* <code>repeated string project_ids = 1;</code>
*/
public Builder clearProjectIds() {
projectIds_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Deprecated. Use `resource_names` instead. One or more project identifiers
* or project numbers from which to retrieve log entries. Example:
* `"my-project-1A"`. If present, these project identifiers are converted to
* resource name format and added to the list of resources in
* `resource_names`.
* </pre>
*
* <code>repeated string project_ids = 1;</code>
*/
public Builder addProjectIdsBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureProjectIdsIsMutable();
projectIds_.add(value);
onChanged();
return this;
}
private com.google.protobuf.LazyStringList resourceNames_ = com.google.protobuf.LazyStringArrayList.EMPTY;
private void ensureResourceNamesIsMutable() {
if (!((bitField0_ & 0x00000002) == 0x00000002)) {
resourceNames_ = new com.google.protobuf.LazyStringArrayList(resourceNames_);
bitField0_ |= 0x00000002;
}
}
/**
* <pre>
* Required. Names of one or more parent resources from which to
* retrieve log entries:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* Projects listed in the `project_ids` field are added to this list.
* </pre>
*
* <code>repeated string resource_names = 8;</code>
*/
public com.google.protobuf.ProtocolStringList
getResourceNamesList() {
return resourceNames_.getUnmodifiableView();
}
/**
* <pre>
* Required. Names of one or more parent resources from which to
* retrieve log entries:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* Projects listed in the `project_ids` field are added to this list.
* </pre>
*
* <code>repeated string resource_names = 8;</code>
*/
public int getResourceNamesCount() {
return resourceNames_.size();
}
/**
* <pre>
* Required. Names of one or more parent resources from which to
* retrieve log entries:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* Projects listed in the `project_ids` field are added to this list.
* </pre>
*
* <code>repeated string resource_names = 8;</code>
*/
public java.lang.String getResourceNames(int index) {
return resourceNames_.get(index);
}
/**
* <pre>
* Required. Names of one or more parent resources from which to
* retrieve log entries:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* Projects listed in the `project_ids` field are added to this list.
* </pre>
*
* <code>repeated string resource_names = 8;</code>
*/
public com.google.protobuf.ByteString
getResourceNamesBytes(int index) {
return resourceNames_.getByteString(index);
}
/**
* <pre>
* Required. Names of one or more parent resources from which to
* retrieve log entries:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* Projects listed in the `project_ids` field are added to this list.
* </pre>
*
* <code>repeated string resource_names = 8;</code>
*/
public Builder setResourceNames(
int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureResourceNamesIsMutable();
resourceNames_.set(index, value);
onChanged();
return this;
}
/**
* <pre>
* Required. Names of one or more parent resources from which to
* retrieve log entries:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* Projects listed in the `project_ids` field are added to this list.
* </pre>
*
* <code>repeated string resource_names = 8;</code>
*/
public Builder addResourceNames(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureResourceNamesIsMutable();
resourceNames_.add(value);
onChanged();
return this;
}
/**
* <pre>
* Required. Names of one or more parent resources from which to
* retrieve log entries:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* Projects listed in the `project_ids` field are added to this list.
* </pre>
*
* <code>repeated string resource_names = 8;</code>
*/
public Builder addAllResourceNames(
java.lang.Iterable<java.lang.String> values) {
ensureResourceNamesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, resourceNames_);
onChanged();
return this;
}
/**
* <pre>
* Required. Names of one or more parent resources from which to
* retrieve log entries:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* Projects listed in the `project_ids` field are added to this list.
* </pre>
*
* <code>repeated string resource_names = 8;</code>
*/
public Builder clearResourceNames() {
resourceNames_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
* <pre>
* Required. Names of one or more parent resources from which to
* retrieve log entries:
* "projects/[PROJECT_ID]"
* "organizations/[ORGANIZATION_ID]"
* "billingAccounts/[BILLING_ACCOUNT_ID]"
* "folders/[FOLDER_ID]"
* Projects listed in the `project_ids` field are added to this list.
* </pre>
*
* <code>repeated string resource_names = 8;</code>
*/
public Builder addResourceNamesBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureResourceNamesIsMutable();
resourceNames_.add(value);
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
* <pre>
* Optional. A filter that chooses which log entries to return. See [Advanced
* Logs Filters](/logging/docs/view/advanced_filters). Only log entries that
* match the filter are returned. An empty filter matches all log entries in
* the resources listed in `resource_names`. Referencing a parent resource
* that is not listed in `resource_names` will cause the filter to return no
* results.
* The maximum length of the filter is 20000 characters.
* </pre>
*
* <code>optional string filter = 2;</code>
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Optional. A filter that chooses which log entries to return. See [Advanced
* Logs Filters](/logging/docs/view/advanced_filters). Only log entries that
* match the filter are returned. An empty filter matches all log entries in
* the resources listed in `resource_names`. Referencing a parent resource
* that is not listed in `resource_names` will cause the filter to return no
* results.
* The maximum length of the filter is 20000 characters.
* </pre>
*
* <code>optional string filter = 2;</code>
*/
public com.google.protobuf.ByteString
getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Optional. A filter that chooses which log entries to return. See [Advanced
* Logs Filters](/logging/docs/view/advanced_filters). Only log entries that
* match the filter are returned. An empty filter matches all log entries in
* the resources listed in `resource_names`. Referencing a parent resource
* that is not listed in `resource_names` will cause the filter to return no
* results.
* The maximum length of the filter is 20000 characters.
* </pre>
*
* <code>optional string filter = 2;</code>
*/
public Builder setFilter(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
onChanged();
return this;
}
/**
* <pre>
* Optional. A filter that chooses which log entries to return. See [Advanced
* Logs Filters](/logging/docs/view/advanced_filters). Only log entries that
* match the filter are returned. An empty filter matches all log entries in
* the resources listed in `resource_names`. Referencing a parent resource
* that is not listed in `resource_names` will cause the filter to return no
* results.
* The maximum length of the filter is 20000 characters.
* </pre>
*
* <code>optional string filter = 2;</code>
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
onChanged();
return this;
}
/**
* <pre>
* Optional. A filter that chooses which log entries to return. See [Advanced
* Logs Filters](/logging/docs/view/advanced_filters). Only log entries that
* match the filter are returned. An empty filter matches all log entries in
* the resources listed in `resource_names`. Referencing a parent resource
* that is not listed in `resource_names` will cause the filter to return no
* results.
* The maximum length of the filter is 20000 characters.
* </pre>
*
* <code>optional string filter = 2;</code>
*/
public Builder setFilterBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
* <pre>
* Optional. How the results should be sorted. Presently, the only permitted
* values are `"timestamp asc"` (default) and `"timestamp desc"`. The first
* option returns entries in order of increasing values of
* `LogEntry.timestamp` (oldest first), and the second option returns entries
* in order of decreasing timestamps (newest first). Entries with equal
* timestamps are returned in order of their `insert_id` values.
* </pre>
*
* <code>optional string order_by = 3;</code>
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Optional. How the results should be sorted. Presently, the only permitted
* values are `"timestamp asc"` (default) and `"timestamp desc"`. The first
* option returns entries in order of increasing values of
* `LogEntry.timestamp` (oldest first), and the second option returns entries
* in order of decreasing timestamps (newest first). Entries with equal
* timestamps are returned in order of their `insert_id` values.
* </pre>
*
* <code>optional string order_by = 3;</code>
*/
public com.google.protobuf.ByteString
getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Optional. How the results should be sorted. Presently, the only permitted
* values are `"timestamp asc"` (default) and `"timestamp desc"`. The first
* option returns entries in order of increasing values of
* `LogEntry.timestamp` (oldest first), and the second option returns entries
* in order of decreasing timestamps (newest first). Entries with equal
* timestamps are returned in order of their `insert_id` values.
* </pre>
*
* <code>optional string order_by = 3;</code>
*/
public Builder setOrderBy(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
onChanged();
return this;
}
/**
* <pre>
* Optional. How the results should be sorted. Presently, the only permitted
* values are `"timestamp asc"` (default) and `"timestamp desc"`. The first
* option returns entries in order of increasing values of
* `LogEntry.timestamp` (oldest first), and the second option returns entries
* in order of decreasing timestamps (newest first). Entries with equal
* timestamps are returned in order of their `insert_id` values.
* </pre>
*
* <code>optional string order_by = 3;</code>
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
onChanged();
return this;
}
/**
* <pre>
* Optional. How the results should be sorted. Presently, the only permitted
* values are `"timestamp asc"` (default) and `"timestamp desc"`. The first
* option returns entries in order of increasing values of
* `LogEntry.timestamp` (oldest first), and the second option returns entries
* in order of decreasing timestamps (newest first). Entries with equal
* timestamps are returned in order of their `insert_id` values.
* </pre>
*
* <code>optional string order_by = 3;</code>
*/
public Builder setOrderByBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
onChanged();
return this;
}
private int pageSize_ ;
/**
* <pre>
* Optional. The maximum number of results to return from this request.
* Non-positive values are ignored. The presence of `next_page_token` in the
* response indicates that more results might be available.
* </pre>
*
* <code>optional int32 page_size = 4;</code>
*/
public int getPageSize() {
return pageSize_;
}
/**
* <pre>
* Optional. The maximum number of results to return from this request.
* Non-positive values are ignored. The presence of `next_page_token` in the
* response indicates that more results might be available.
* </pre>
*
* <code>optional int32 page_size = 4;</code>
*/
public Builder setPageSize(int value) {
pageSize_ = value;
onChanged();
return this;
}
/**
* <pre>
* Optional. The maximum number of results to return from this request.
* Non-positive values are ignored. The presence of `next_page_token` in the
* response indicates that more results might be available.
* </pre>
*
* <code>optional int32 page_size = 4;</code>
*/
public Builder clearPageSize() {
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
* <pre>
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `page_token` must be the value of
* `next_page_token` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* </pre>
*
* <code>optional string page_token = 5;</code>
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `page_token` must be the value of
* `next_page_token` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* </pre>
*
* <code>optional string page_token = 5;</code>
*/
public com.google.protobuf.ByteString
getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `page_token` must be the value of
* `next_page_token` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* </pre>
*
* <code>optional string page_token = 5;</code>
*/
public Builder setPageToken(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
onChanged();
return this;
}
/**
* <pre>
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `page_token` must be the value of
* `next_page_token` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* </pre>
*
* <code>optional string page_token = 5;</code>
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
onChanged();
return this;
}
/**
* <pre>
* Optional. If present, then retrieve the next batch of results from the
* preceding call to this method. `page_token` must be the value of
* `next_page_token` from the previous response. The values of other method
* parameters should be identical to those in the previous call.
* </pre>
*
* <code>optional string page_token = 5;</code>
*/
public Builder setPageTokenBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
onChanged();
return this;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:google.logging.v2.ListLogEntriesRequest)
}
// @@protoc_insertion_point(class_scope:google.logging.v2.ListLogEntriesRequest)
private static final com.google.logging.v2.ListLogEntriesRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.logging.v2.ListLogEntriesRequest();
}
public static com.google.logging.v2.ListLogEntriesRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListLogEntriesRequest>
PARSER = new com.google.protobuf.AbstractParser<ListLogEntriesRequest>() {
public ListLogEntriesRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ListLogEntriesRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ListLogEntriesRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListLogEntriesRequest> getParserForType() {
return PARSER;
}
public com.google.logging.v2.ListLogEntriesRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| bsd-3-clause |
sfhsfembot/fembot2014A | src/org/usfirst/frc692/AerialAssist2014/commands/ShooterReverse.java | 3954 | // RobotBuilder Version: 1.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc692.AerialAssist2014.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc692.AerialAssist2014.Robot;
/**
*
*/
public class ShooterReverse extends Command {
public ShooterReverse() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
}
// Called just before this Command runs the first time
protected void initialize() {
//Robot.shooter.shooterMotorOneReverse();
//commented out because the shooter cannot be initialized here and there
//is a conditional statement in execute telling the shooter to reverse when the
//statement is met
//AC 1/16/14
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
if(Robot.shooter.isBackLimitShooterNotPressed())
{
System.out.println("Back limit is not pressed.");
Robot.shooter.shooterMotorOneReverse();
}
/*
* if the back limit switch is not pressed, the system will print out "Back
* limit is not pressed" and the shooter motor will go in reverse
* AO 1/16/14
*/
else
{
System.out.println("Back limit is pressed.");
}
/*
* if the back limit switch is pressed, the system will print out "Back
* limit is pressed"
* AO 1/16/16
*/
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
if(Robot.shooter.isBackShooterLimitPressed())
{
System.out.println("Back limit switch has been pressed.");
return true;
}
/*
* if the back limit switch is pressed, the system will print out "Back
* limit has been pressed" and the command will end
* AO 1/16/14
*/
else
{
return false;
}
}
// Called once after isFinished returns true
protected void end() {
Robot.shooter.shooterMotorOneStop();
System.out.println("Now calling shooter end method.");
}
/*
* the shooter motor stops, then system will print out "Now calling the
* shooter to end.
* AO 1/16/14
*/
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
while(Robot.shooter.isBackLimitShooterNotPressed())
{
Robot.shooter.shooterMotorOneReverse();
System.out.println("Back shooter limit is still not pressed and the shooter is still going in reverse.");
}
/*
* while the back limit switch is interrupted or not pressed, the system
* will print out "Back shooter limit is still not pressed and the shooter\
* is still going in reverse and the motor will continue in reverse
* AO 1/16/14
*/
Robot.shooter.shooterMotorOneReverse();
System.out.println("Shooter is going back.");
end();
}
/*when interrupted the shooter will go back and stop
* AC 1/16/14
*/
}
| bsd-3-clause |
petablox-project/petablox | src/petablox/analyses/syntax/RelTrap.java | 1033 | package petablox.analyses.syntax;
import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
import soot.Trap;
import soot.jimple.internal.JTrap;
import petablox.program.visitors.IMethodVisitor;
import petablox.project.Petablox;
import petablox.project.analyses.ProgramRel;
@Petablox(name = "Trap", sign = "M0,T0,P0,P1,P2:M0_T0xP0xP1xP2")
public class RelTrap extends ProgramRel implements IMethodVisitor {
@Override
public void visit(SootClass m) { }
@Override
public void visit(SootMethod m) {
if (m.isConcrete()) {
for (Trap trap : m.getActiveBody().getTraps()){
if (trap instanceof JTrap) {
try {
add(m, trap.getException().getType(), trap.getBeginUnit(), trap.getEndUnit(),
trap.getHandlerUnit());
} catch (Exception e) {
System.out.println("WARN: Trap not found " + trap);
}
}
}
}
}
}
| bsd-3-clause |
vivo-project/Vitro | api/src/main/java/edu/cornell/mannlib/vitro/webapp/web/templatemodels/VClassGroupTemplateModel.java | 2168 | /* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.web.templatemodels;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
public class VClassGroupTemplateModel extends BaseTemplateModel {
private static final Log log = LogFactory.getLog(VClassGroupTemplateModel.class.getName());
private final VClassGroup vClassGroup;
private List<VClassTemplateModel> classes;
public VClassGroupTemplateModel(VClassGroup vClassGroup) {
this.vClassGroup = vClassGroup;
}
public int getDisplayRank() {
return vClassGroup.getDisplayRank();
}
public String getUri() {
return vClassGroup.getURI();
}
public String getNamespace() {
return vClassGroup.getNamespace();
}
public String getLocalName() {
return vClassGroup.getLocalName();
}
public String getPublicName() {
return vClassGroup.getPublicName();
}
// Protect the template against a group without a name.
public String getDisplayName() {
String displayName = getPublicName();
if (StringUtils.isBlank(displayName)) {
displayName = getLocalName().replaceFirst("vitroClassGroup", "");
}
return displayName;
}
public List<VClassTemplateModel> getClasses() {
if (classes == null) {
List<VClass> classList = vClassGroup.getVitroClassList();
classes = new ArrayList<VClassTemplateModel>();
for (VClass vc : classList) {
classes.add(new VClassTemplateModel(vc));
}
}
return classes;
}
public int getIndividualCount(){
if( vClassGroup.isIndividualCountSet() )
return vClassGroup.getIndividualCount();
else
return 0;
}
public boolean isIndividualCountSet(){
return vClassGroup.isIndividualCountSet();
}
}
| bsd-3-clause |
teamed/requs | requs-core/src/main/java/org/requs/facet/syntax/ontology/XeInformal.java | 2551 | /**
* Copyright (c) 2009-2017, requs.org
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the requs.org nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.requs.facet.syntax.ontology;
import com.jcabi.aspects.Loggable;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.xembly.Directives;
/**
* Xembly informal.
*
* @author Yegor Bugayenko (yegor@tpc2.com)
* @version $Id$
* @since 1.1
*/
@ToString
@EqualsAndHashCode(of = { "dirs", "start" })
@Loggable(Loggable.DEBUG)
final class XeInformal implements Informal {
/**
* All directives.
*/
private final transient Directives dirs;
/**
* Starting XPath.
*/
private final transient String start;
/**
* Ctor.
* @param directives Directives to extend
* @param xpath XPath to start with
*/
XeInformal(final Directives directives, final String xpath) {
this.dirs = directives;
this.start = xpath;
}
@Override
public void explain(final String informal) {
this.dirs.xpath(this.start).strict(1)
.addIf("info").add("informal").set(informal);
}
}
| bsd-3-clause |
trcooke/fun-with-java8 | src/main/java/StreamIterationOverStrings.java | 812 | import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.counting;
public class StreamIterationOverStrings {
public String listAsString(List<String> strings) {
return strings.stream().collect(Collectors.joining(" "));
}
public List<String> prependToEach(List<String> strings, char c) {
return strings.stream()
.map(e -> c + e)
.collect(Collectors.toList());
}
public Map<Character, Integer> charOccurrences(String s) {
return s.chars().collect(
HashMap::new,
(m, c) -> m.merge((char) c, 1, Integer::sum),
HashMap::putAll);
}
}
| bsd-3-clause |
Hubertzhang/ingress-intel-total-conversion | mobile/app/src/main/java/org/exarhteam/iitc_mobile/IITC_Application.java | 1156 | package org.exarhteam.iitc_mobile;
import android.app.Application;
import android.preference.PreferenceManager;
import java.io.File;
/*
* To write the WebView cache to external storage we need to override the
* getCacheDir method of the main application. Some internal Android code seems
* to call getApplicationContext().getCacheDir(); instead of
* getContext().getCacheDir(); to decide where to store and read cached files.
*/
public class IITC_Application extends Application {
@Override
public File getCacheDir() {
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("pref_external_storage", false)) {
return (getExternalCacheDir() != null) ? getExternalCacheDir() : super.getCacheDir();
} else {
return super.getCacheDir();
}
}
@Override
public File getFilesDir() {
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("pref_external_storage", false)) {
return (getExternalFilesDir(null) != null) ? getExternalFilesDir(null) : super.getFilesDir();
} else {
return super.getFilesDir();
}
}
}
| isc |
uwol/cobol85parser | src/test/java/gov/nist/IX216ATest.java | 542 | package gov.nist;
import java.io.File;
import io.proleap.cobol.preprocessor.CobolPreprocessor.CobolSourceFormatEnum;
import io.proleap.cobol.runner.CobolParseTestRunner;
import io.proleap.cobol.runner.impl.CobolParseTestRunnerImpl;
import org.junit.Test;
public class IX216ATest {
@Test
public void test() throws Exception {
final File inputFile = new File("src/test/resources/gov/nist/IX216A.CBL");
final CobolParseTestRunner runner = new CobolParseTestRunnerImpl();
runner.parseFile(inputFile, CobolSourceFormatEnum.FIXED);
}
} | mit |
liuz7/java-client-api | jenkins-client/src/main/java/com/offbytwo/jenkins/model/BaseModel.java | 651 | /*
* Copyright (c) 2013 Cosmin Stejerean, Karl Heinz Marbaise, and contributors.
*
* Distributed under the MIT license: http://opensource.org/licenses/MIT
*/
package com.offbytwo.jenkins.model;
import com.offbytwo.jenkins.client.JenkinsHttpClient;
/**
* The base model.
*
*/
public class BaseModel {
private String _class;
public String get_class() {
return _class;
}
//TODO: We should make this private
protected JenkinsHttpClient client;
public JenkinsHttpClient getClient() {
return client;
}
public void setClient(JenkinsHttpClient client) {
this.client = client;
}
}
| mit |
jucimarjr/ooerlang | examples/headfirst/19_Interpreter/Java/Evaluator.java | 991 | //Este fonte foi retirado de: http://en.wikibooks.org/wiki/Computer_Science_Design_Patterns/Interpreter
//Ultimo acesso em Agosto de 2013
public class Evaluator implements Expression {
private Expression syntaxTree;
Stack<Expression> expressionStack = new Stack<Expression>();
public Evaluator(String expression) {
for (String token : expression.split(" ")) {
if (token.equals("+")) {
Expression subExpression = new Plus(expressionStack.pop(),
expressionStack.pop());
expressionStack.push(subExpression);
} else if (token.equals("-")) {
Expression right = expressionStack.pop();
Expression left = expressionStack.pop();
Expression subExpression = new Minus(left, right);
expressionStack.push(subExpression);
} else
expressionStack.push(new Variable(token));
}
syntaxTree = expressionStack.pop();
}
public int interpret(Map<String, Expression> context) {
return syntaxTree.interpret(context);
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/LoadBalancingRuleImpl.java | 3455 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2018_08_01.implementation;
import com.microsoft.azure.management.network.v2018_08_01.LoadBalancingRule;
import com.microsoft.azure.arm.model.implementation.IndexableRefreshableWrapperImpl;
import rx.Observable;
import com.microsoft.azure.SubResource;
import com.microsoft.azure.management.network.v2018_08_01.LoadDistribution;
import com.microsoft.azure.management.network.v2018_08_01.TransportProtocol;
class LoadBalancingRuleImpl extends IndexableRefreshableWrapperImpl<LoadBalancingRule, LoadBalancingRuleInner> implements LoadBalancingRule {
private final NetworkManager manager;
private String resourceGroupName;
private String loadBalancerName;
private String loadBalancingRuleName;
LoadBalancingRuleImpl(LoadBalancingRuleInner inner, NetworkManager manager) {
super(null, inner);
this.manager = manager;
// set resource ancestor and positional variables
this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups");
this.loadBalancerName = IdParsingUtils.getValueFromIdByName(inner.id(), "loadBalancers");
this.loadBalancingRuleName = IdParsingUtils.getValueFromIdByName(inner.id(), "loadBalancingRules");
}
@Override
public NetworkManager manager() {
return this.manager;
}
@Override
protected Observable<LoadBalancingRuleInner> getInnerAsync() {
LoadBalancerLoadBalancingRulesInner client = this.manager().inner().loadBalancerLoadBalancingRules();
return client.getAsync(this.resourceGroupName, this.loadBalancerName, this.loadBalancingRuleName);
}
@Override
public SubResource backendAddressPool() {
return this.inner().backendAddressPool();
}
@Override
public Integer backendPort() {
return this.inner().backendPort();
}
@Override
public Boolean disableOutboundSnat() {
return this.inner().disableOutboundSnat();
}
@Override
public Boolean enableFloatingIP() {
return this.inner().enableFloatingIP();
}
@Override
public Boolean enableTcpReset() {
return this.inner().enableTcpReset();
}
@Override
public String etag() {
return this.inner().etag();
}
@Override
public SubResource frontendIPConfiguration() {
return this.inner().frontendIPConfiguration();
}
@Override
public int frontendPort() {
return this.inner().frontendPort();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public Integer idleTimeoutInMinutes() {
return this.inner().idleTimeoutInMinutes();
}
@Override
public LoadDistribution loadDistribution() {
return this.inner().loadDistribution();
}
@Override
public String name() {
return this.inner().name();
}
@Override
public SubResource probe() {
return this.inner().probe();
}
@Override
public TransportProtocol protocol() {
return this.inner().protocol();
}
@Override
public String provisioningState() {
return this.inner().provisioningState();
}
}
| mit |
darshanhs90/Java-Coding | src/April2021PrepLeetcode/_0403FrogJump.java | 1058 | package April2021PrepLeetcode;
import java.util.HashMap;
public class _0403FrogJump {
public static void main(String[] args) {
System.out.println(canCross(new int[] { 0, 1, 3, 5, 6, 8, 12, 17 }));
System.out.println(canCross(new int[] { 0, 1, 2, 3, 4, 8, 9, 11 }));
}
public static boolean canCross(int[] stones) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < stones.length; i++) {
map.put(stones[i], i);
}
return canCross(0, 0, map);
}
public static boolean canCross(int currVal, int jump, HashMap<Integer, Integer> map) {
if (map.get(currVal) == map.size() - 1)
return true;
if (jump - 1 > 0 && map.containsKey(currVal + jump - 1)) {
if (canCross(currVal + jump - 1, jump - 1, map))
return true;
}
if (jump > 0 && map.containsKey(currVal + jump)) {
if (canCross(currVal + jump, jump, map))
return true;
}
if (jump + 1 > 0 && map.containsKey(currVal + jump + 1)) {
if (canCross(currVal + jump + 1, jump + 1, map))
return true;
}
return false;
}
}
| mit |
bradleysykes/game_leprechaun | src/model/Effects.java | 643 | package model;
import java.util.ArrayList;
import java.util.List;
import model.stats.Stat;
import model.stats.StatCollection;
public class Effects extends StatCollection{
public Effects() {
super("Effects");
}
public Effects(Effects e){
this();
for(Effect effect : e.getEffects())
this.addEffect(effect);
}
public void addEffect(Effect effect){
this.addStat(effect);
}
public void removeEffect(Effect Effect) {
this.removeStat(Effect);
}
public List<Effect> getEffects(){
List<Effect> toReturn = new ArrayList<Effect>();
for(Stat s : this.getStats())
toReturn.add((Effect) s);
return toReturn;
}
}
| mit |
jayhorn/cav_experiments | jayhorn_cav16_ae/benchmarks/MinePump/spec1-5/product6/MinePumpSystem/MinePump.java | 1261 | package MinePumpSystem;
import MinePumpSystem.Environment;
public class MinePump {
boolean pumpRunning = false;
boolean systemActive = true;
Environment env;
public MinePump(Environment env) {
super();
this.env = env;
}
public void timeShift() {
if (pumpRunning)
env.lowerWaterLevel();
if (systemActive)
processEnvironment();
}
private void processEnvironment__wrappee__base () {
}
public void processEnvironment() {
if (pumpRunning && isMethaneAlarm()) {
deactivatePump();
} else {
processEnvironment__wrappee__base();
}
}
void activatePump() {
pumpRunning = true;
}
public boolean isPumpRunning() {
return pumpRunning;
}
void deactivatePump() {
pumpRunning = false;
}
boolean isMethaneAlarm() {
return env.isMethaneLevelCritical();
}
@Override
public String toString() {
return "Pump(System:" + (systemActive?"On":"Off") + ",Pump:" + (pumpRunning?"On":"Off") +") " + env.toString();
}
public Environment getEnv() {
return env;
}
public void startSystem() {
assert !pumpRunning;
systemActive = true;
}
public void stopSystem() {
// feature not present
}
public boolean isSystemActive() {
return systemActive;
}
}
| mit |
tbepler/seq-svm | src/org/apache/commons/math3/linear/SparseRealVector.java | 1452 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.linear;
/**
* Marker class for RealVectors that require sparse backing storage
* <p>
* Caveat: Implementation are allowed to assume that, for any {@code x},
* the equality {@code x * 0d == 0d} holds. But it is is not true for
* {@code NaN}. Moreover, zero entries will lose their sign.
* Some operations (that involve {@code NaN} and/or infinities) may
* thus give incorrect results, like multiplications, divisions or
* functions mapping.
* </p>
* @version $Id: SparseRealVector.java 1570254 2014-02-20 16:16:19Z luc $
* @since 2.0
*/
public abstract class SparseRealVector extends RealVector {}
| mit |
navalev/azure-sdk-for-java | sdk/cosmosdb/mgmt-v2019_08_01/src/main/java/com/microsoft/azure/management/cosmosdb/v2019_08_01/TriggerOperation.java | 1677 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.cosmosdb.v2019_08_01;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;
/**
* Defines values for TriggerOperation.
*/
public final class TriggerOperation extends ExpandableStringEnum<TriggerOperation> {
/** Static value All for TriggerOperation. */
public static final TriggerOperation ALL = fromString("All");
/** Static value Create for TriggerOperation. */
public static final TriggerOperation CREATE = fromString("Create");
/** Static value Update for TriggerOperation. */
public static final TriggerOperation UPDATE = fromString("Update");
/** Static value Delete for TriggerOperation. */
public static final TriggerOperation DELETE = fromString("Delete");
/** Static value Replace for TriggerOperation. */
public static final TriggerOperation REPLACE = fromString("Replace");
/**
* Creates or finds a TriggerOperation from its string representation.
* @param name a name to look for
* @return the corresponding TriggerOperation
*/
@JsonCreator
public static TriggerOperation fromString(String name) {
return fromString(name, TriggerOperation.class);
}
/**
* @return known TriggerOperation values
*/
public static Collection<TriggerOperation> values() {
return values(TriggerOperation.class);
}
}
| mit |
0359xiaodong/android-utils | src/at/int32/android/utils/ui/binding/IViewRunnable.java | 158 | package at.int32.android.utils.ui.binding;
import android.view.View;
public interface IViewRunnable<T, V extends View> {
public void run(T data, V view);
} | mit |
diedertimmers/oxAuth | Client/src/test/java/org/xdi/oxauth/ws/rs/FederationMetadataWebServiceHttpTest.java | 6164 | /*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.xdi.oxauth.ws.rs;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.xdi.oxauth.BaseTest;
import org.xdi.oxauth.client.FederationMetadataClient;
import org.xdi.oxauth.client.FederationMetadataRequest;
import org.xdi.oxauth.client.FederationMetadataResponse;
import org.xdi.oxauth.model.federation.FederationOP;
import org.xdi.oxauth.model.federation.FederationRP;
import java.util.List;
import static org.testng.Assert.*;
/**
* @author Yuriy Zabrovarnyy
* @version 0.9, 28/09/2012
*/
public class FederationMetadataWebServiceHttpTest extends BaseTest {
@Test
public void requestExistingFederationMetadataIdList() throws Exception {
showTitle("requestExistingFederationMetadataIdList");
FederationMetadataClient client = new FederationMetadataClient(federationMetadataEndpoint);
FederationMetadataResponse response = client.execGetMetadataIds();
showClient(client);
assertEquals(response.getStatus(), 200, "Unexpected response code. Entity: " + response.getEntity());
assertNotNull(response.getEntity(), "The entity is null");
assertTrue(response.getExistingMetadataIdList() != null && !response.getExistingMetadataIdList().isEmpty(),
"MetadataId list is empty. It's expected to have not empty list");
}
@Parameters({"federationMetadataId"})
@Test
public void requestFederationMetadataById(final String federationMetadataId) throws Exception {
showTitle("requestFederationMetadataId");
FederationMetadataRequest request = new FederationMetadataRequest();
request.setSigned(false);
request.setFederationId(federationMetadataId);
FederationMetadataClient client = new FederationMetadataClient(federationMetadataEndpoint);
FederationMetadataResponse response = client.exec(request);
showClient(client);
assertEquals(response.getStatus(), 200, "Unexpected response code. Entity: " + response.getEntity());
assertNotNull(response.getEntity(), "The entity is null");
assertNotNull(response.getMetadata(), "The metadata is null");
assertNotNull(response.getMetadata().getId(), "The metadata id is null");
assertNotNull(response.getMetadata().getDisplayName(), "The metadata displayName is null");
assertNotNull(response.getMetadata().getIntervalCheck(), "The metadata intervalCheck is not set");
final List<FederationRP> rpList = response.getMetadata().getRpList();
final List<FederationOP> opList = response.getMetadata().getOpList();
assertTrue(rpList != null && !rpList.isEmpty(), "The metadata rp list is not set");
assertTrue(opList != null && !opList.isEmpty(), "The metadata op list is not set");
assertNotNull(rpList.get(0).getDisplayName(), "The metadata rp's display_name attribute is not set");
assertNotNull(rpList.get(0).getRedirectUri(), "The metadata rp's redirect_uri attribute is not set");
assertNotNull(opList.get(0).getDisplayName(), "The metadata op's display_name attribute is not set");
assertNotNull(opList.get(0).getOpId(), "The metadata op's op_id attribute is not set");
assertNotNull(opList.get(0).getDomain(), "The metadata op's domain attribute is not set");
}
@Parameters({"federationMetadataId"})
@Test
public void requestFederationMetadataByIdNotSigned(final String federationMetadataId) throws Exception {
showTitle("requestFederationMetadataId");
FederationMetadataClient client = new FederationMetadataClient(federationMetadataEndpoint);
FederationMetadataRequest request = new FederationMetadataRequest();
request.setFederationId(federationMetadataId);
request.setSigned(false);
FederationMetadataResponse response = client.exec(request);
showClient(client);
assertEquals(response.getStatus(), 200, "Unexpected response code. Entity: " + response.getEntity());
assertNotNull(response.getEntity(), "The entity is null");
assertNotNull(response.getMetadata(), "The metadata is null");
assertNotNull(response.getMetadata().getId(), "The metadata id is null");
assertNotNull(response.getMetadata().getDisplayName(), "The metadata displayName is null");
assertNotNull(response.getMetadata().getIntervalCheck(), "The metadata intervalCheck is not set");
final List<FederationRP> rpList = response.getMetadata().getRpList();
final List<FederationOP> opList = response.getMetadata().getOpList();
assertTrue(rpList != null && !rpList.isEmpty(), "The metadata rp list is not set");
assertTrue(opList != null && !opList.isEmpty(), "The metadata op list is not set");
assertNotNull(rpList.get(0).getDisplayName(), "The metadata rp's display_name attribute is not set");
assertNotNull(rpList.get(0).getRedirectUri(), "The metadata rp's redirect_uri attribute is not set");
assertNotNull(opList.get(0).getDisplayName(), "The metadata op's display_name attribute is not set");
assertNotNull(opList.get(0).getOpId(), "The metadata op's op_id attribute is not set");
assertNotNull(opList.get(0).getDomain(), "The metadata op's domain attribute is not set");
}
@Test
public void requestFederationMetadataByIdFail() throws Exception {
showTitle("requestFederationMetadataIdFail");
FederationMetadataClient client = new FederationMetadataClient(federationMetadataEndpoint);
FederationMetadataResponse response = client.execGetMetadataById("notExistingId");
showClient(client);
assertEquals(response.getStatus(), 400, "Unexpected response code. Entity: " + response.getEntity());
assertNotNull(response.getEntity(), "The entity is null");
assertNotNull(response.getErrorType(), "The error type is null");
assertNotNull(response.getErrorDescription(), "The error description is null");
}
} | mit |
Safewhere/kombit-service-java | XmlTooling/src/org/opensaml/xml/signature/impl/TransformUnmarshaller.java | 1977 | /*
* Licensed to the University Corporation for Advanced Internet Development,
* Inc. (UCAID) under one or more contributor license agreements. See the
* NOTICE file distributed with this work for additional information regarding
* copyright ownership. The UCAID licenses this file to You under the Apache
* License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opensaml.xml.signature.impl;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.io.UnmarshallingException;
import org.opensaml.xml.signature.Transform;
import org.w3c.dom.Attr;
/**
* A thread-safe Unmarshaller for {@link org.opensaml.xml.signature.Transform} objects.
*/
public class TransformUnmarshaller extends AbstractXMLSignatureUnmarshaller {
/** {@inheritDoc} */
protected void processAttribute(XMLObject xmlObject, Attr attribute) throws UnmarshallingException {
Transform transform = (Transform) xmlObject;
if (attribute.getLocalName().equals(Transform.ALGORITHM_ATTRIB_NAME)) {
transform.setAlgorithm(attribute.getValue());
} else {
super.processAttribute(xmlObject, attribute);
}
}
/** {@inheritDoc} */
protected void processChildElement(XMLObject parentXMLObject, XMLObject childXMLObject)
throws UnmarshallingException {
Transform transform = (Transform) parentXMLObject;
// Has <any> open content model + XPath children
transform.getAllChildren().add(childXMLObject);
}
}
| mit |
gammamusic/gamma | src/main/java/teste/MidiNoteAcordeC.java | 4127 | package teste;
/*
* MidiNote.java
*
* This file is part of jsresources.org
*/
import java.util.ArrayList;
import java.util.List;
/*
* Copyright (c) 1999 - 2006 by Matthias Pfisterer
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
|<--- this code is formatted to fit into 80 columns --->|
*/
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.MidiMessage;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.SysexMessage;
// TODO: an optional delay parameter that is added to getMicrosecondPosition to be used as timestamp for the event delivery.
/** <titleabbrev>MidiNote</titleabbrev>
<title>Playing a note on a MIDI device</title>
<formalpara><title>Purpose</title>
<para>Plays a single note on a MIDI device. The MIDI device can
be a software synthesizer, an internal hardware synthesizer or
any device connected to the MIDI OUT port.</para>
</formalpara>
<formalpara><title>Usage</title>
<para>
<cmdsynopsis><command>java MidiNote</command>
<arg choice="opt"><replaceable class="parameter">devicename</replaceable></arg>
<arg choice="plain"><replaceable class="parameter">keynumber</replaceable></arg>
<arg choice="plain"><replaceable class="parameter">velocity</replaceable></arg>
<arg choice="plain"><replaceable class="parameter">duration</replaceable></arg>
</cmdsynopsis>
</para></formalpara>
<formalpara><title>Parameters</title>
<variablelist>
<varlistentry>
<term><replaceable class="parameter">devicename</replaceable></term>
<listitem><para>the name of the device to send the MIDI messages to</para></listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">keynumber</replaceable></term>
<listitem><para>the MIDI key number</para></listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">velocity</replaceable></term>
<listitem><para>the velocity</para></listitem>
</varlistentry>
<varlistentry>
<term><replaceable class="parameter">duration</replaceable></term>
<listitem><para>the duration in milliseconds</para></listitem>
</varlistentry>
</variablelist>
</formalpara>
<formalpara><title>Bugs, limitations</title>
<para>Not well-tested.</para>
</formalpara>
<formalpara><title>Source code</title>
<para>
<ulink url="MidiNote.java.html">MidiNote.java</ulink>,
<ulink url="MidiCommon.java.html">MidiCommon.java</ulink>
</para>
</formalpara>
*/
public class MidiNoteAcordeC {
public static void main(String[] args) {
List<Integer> notes = new ArrayList<Integer>();
notes.add(60); //C
notes.add(64); //E
notes.add(67); //G
MidiNotePlay.play(notes, "DANIEL");
}
}
/*** MidiNote.java ***/ | mit |
darshanhs90/Java-Coding | src/Feb2021Leetcode/_0063UniquePathsII.java | 612 | package Feb2021Leetcode;
public class _0063UniquePathsII {
public static void main(String[] args) {
System.out.println(uniquePathsWithObstacles(
new int[][] { new int[] { 0, 0, 0 }, new int[] { 0, 1, 0 }, new int[] { 0, 0, 0 } }));
System.out.println(uniquePathsWithObstacles(new int[][] { new int[] { 0, 1 }, new int[] { 0, 0 } }));
System.out.println(uniquePathsWithObstacles(new int[][] { new int[] { 1, 1 }, new int[] { 1, 0 } }));
System.out.println(uniquePathsWithObstacles(new int[][] { new int[] { 1, 0 } }));
}
public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
}
}
| mit |
kornel-schrenk/DiveInoDroid | app/src/main/java/hu/diveino/droid/dao/SchemaContract.java | 1185 | package hu.diveino.droid.dao;
import android.provider.BaseColumns;
public final class SchemaContract {
private SchemaContract() {}
public static class DiveProfileTable implements BaseColumns {
public static final String TABLE_NAME = "DIVE_PROFILE";
public static final String COLUMN_NAME_DIVE_DURATION = "DIVE_DURATION";
public static final String COLUMN_NAME_MAX_DEPTH = "MAX_DEPTH";
public static final String COLUMN_NAME_MIN_TEMPERATURE = "MIN_TEMPERATURE";
public static final String COLUMN_NAME_OXYGEN_PERCENTAGE = "OXYGEN_PERCENTAGE";
public static final String COLUMN_NAME_DIVE_DATE_TIME = "DIVE_DATE_TIME";
}
public static class ProfileItemTable implements BaseColumns {
public static final String TABLE_NAME = "PROFILE_ITEM";
public static final String COLUMN_NAME_DIVE_PROFILE_ID = "DIVE_PROFILE_ID";
public static final String COLUMN_NAME_DEPTH = "DEPTH";
public static final String COLUMN_NAME_PRESSURE = "PRESSURE";
public static final String COLUMN_NAME_DURATION = "DURATION";
public static final String COLUMN_NAME_TEMPERATURE = "TEMPERATURE";
}
}
| mit |
danthemellowman/Processing-Android-Eclipse-Demos | processing-android/core/src/com/processing/core/PMatrix3D.java | 22874 | /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2005-12 Ben Fry and Casey Reas
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License version 2.1 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package com.processing.core;
/**
* 4x4 matrix implementation.
*/
public final class PMatrix3D implements PMatrix /*, PConstants*/ {
public float m00, m01, m02, m03;
public float m10, m11, m12, m13;
public float m20, m21, m22, m23;
public float m30, m31, m32, m33;
// locally allocated version to avoid creating new memory
protected PMatrix3D inverseCopy;
public PMatrix3D() {
reset();
}
public PMatrix3D(float m00, float m01, float m02,
float m10, float m11, float m12) {
set(m00, m01, m02, 0,
m10, m11, m12, 0,
0, 0, 1, 0,
0, 0, 0, 1);
}
public PMatrix3D(float m00, float m01, float m02, float m03,
float m10, float m11, float m12, float m13,
float m20, float m21, float m22, float m23,
float m30, float m31, float m32, float m33) {
set(m00, m01, m02, m03,
m10, m11, m12, m13,
m20, m21, m22, m23,
m30, m31, m32, m33);
}
public PMatrix3D(PMatrix matrix) {
set(matrix);
}
public void reset() {
set(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
}
/**
* Returns a copy of this PMatrix.
*/
public PMatrix3D get() {
PMatrix3D outgoing = new PMatrix3D();
outgoing.set(this);
return outgoing;
}
/**
* Copies the matrix contents into a 16 entry float array.
* If target is null (or not the correct size), a new array will be created.
*/
public float[] get(float[] target) {
if ((target == null) || (target.length != 16)) {
target = new float[16];
}
target[0] = m00;
target[1] = m01;
target[2] = m02;
target[3] = m03;
target[4] = m10;
target[5] = m11;
target[6] = m12;
target[7] = m13;
target[8] = m20;
target[9] = m21;
target[10] = m22;
target[11] = m23;
target[12] = m30;
target[13] = m31;
target[14] = m32;
target[15] = m33;
return target;
}
public void set(PMatrix matrix) {
if (matrix instanceof PMatrix3D) {
PMatrix3D src = (PMatrix3D) matrix;
set(src.m00, src.m01, src.m02, src.m03,
src.m10, src.m11, src.m12, src.m13,
src.m20, src.m21, src.m22, src.m23,
src.m30, src.m31, src.m32, src.m33);
} else {
PMatrix2D src = (PMatrix2D) matrix;
set(src.m00, src.m01, 0, src.m02,
src.m10, src.m11, 0, src.m12,
0, 0, 1, 0,
0, 0, 0, 1);
}
}
public void set(float[] source) {
if (source.length == 6) {
set(source[0], source[1], source[2],
source[3], source[4], source[5]);
} else if (source.length == 16) {
m00 = source[0];
m01 = source[1];
m02 = source[2];
m03 = source[3];
m10 = source[4];
m11 = source[5];
m12 = source[6];
m13 = source[7];
m20 = source[8];
m21 = source[9];
m22 = source[10];
m23 = source[11];
m30 = source[12];
m31 = source[13];
m32 = source[14];
m33 = source[15];
}
}
public void set(float m00, float m01, float m02,
float m10, float m11, float m12) {
set(m00, m01, 0, m02,
m10, m11, 0, m12,
0, 0, 1, 0,
0, 0, 0, 1);
}
public void set(float m00, float m01, float m02, float m03,
float m10, float m11, float m12, float m13,
float m20, float m21, float m22, float m23,
float m30, float m31, float m32, float m33) {
this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03;
this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13;
this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23;
this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33;
}
public void translate(float tx, float ty) {
translate(tx, ty, 0);
}
// public void invTranslate(float tx, float ty) {
// invTranslate(tx, ty, 0);
// }
public void translate(float tx, float ty, float tz) {
m03 += tx*m00 + ty*m01 + tz*m02;
m13 += tx*m10 + ty*m11 + tz*m12;
m23 += tx*m20 + ty*m21 + tz*m22;
m33 += tx*m30 + ty*m31 + tz*m32;
}
public void rotate(float angle) {
rotateZ(angle);
}
public void rotateX(float angle) {
float c = cos(angle);
float s = sin(angle);
apply(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
}
public void rotateY(float angle) {
float c = cos(angle);
float s = sin(angle);
apply(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
}
public void rotateZ(float angle) {
float c = cos(angle);
float s = sin(angle);
apply(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
}
public void rotate(float angle, float v0, float v1, float v2) {
float norm2 = v0 * v0 + v1 * v1 + v2 * v2;
if (norm2 < PConstants.EPSILON) {
// The vector is zero, cannot apply rotation.
return;
}
if (Math.abs(norm2 - 1) > PConstants.EPSILON) {
// The rotation vector is not normalized.
float norm = PApplet.sqrt(norm2);
v0 /= norm;
v1 /= norm;
v2 /= norm;
}
float c = cos(angle);
float s = sin(angle);
float t = 1.0f - c;
apply((t*v0*v0) + c, (t*v0*v1) - (s*v2), (t*v0*v2) + (s*v1), 0,
(t*v0*v1) + (s*v2), (t*v1*v1) + c, (t*v1*v2) - (s*v0), 0,
(t*v0*v2) - (s*v1), (t*v1*v2) + (s*v0), (t*v2*v2) + c, 0,
0, 0, 0, 1);
}
public void scale(float s) {
//apply(s, 0, 0, 0, 0, s, 0, 0, 0, 0, s, 0, 0, 0, 0, 1);
scale(s, s, s);
}
public void scale(float sx, float sy) {
//apply(sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
scale(sx, sy, 1);
}
public void scale(float x, float y, float z) {
//apply(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
m00 *= x; m01 *= y; m02 *= z;
m10 *= x; m11 *= y; m12 *= z;
m20 *= x; m21 *= y; m22 *= z;
m30 *= x; m31 *= y; m32 *= z;
}
public void shearX(float angle) {
float t = (float) Math.tan(angle);
apply(1, t, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
}
public void shearY(float angle) {
float t = (float) Math.tan(angle);
apply(1, 0, 0, 0,
t, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
}
public void apply(PMatrix source) {
if (source instanceof PMatrix2D) {
apply((PMatrix2D) source);
} else if (source instanceof PMatrix3D) {
apply((PMatrix3D) source);
}
}
public void apply(PMatrix2D source) {
apply(source.m00, source.m01, 0, source.m02,
source.m10, source.m11, 0, source.m12,
0, 0, 1, 0,
0, 0, 0, 1);
}
public void apply(PMatrix3D source) {
apply(source.m00, source.m01, source.m02, source.m03,
source.m10, source.m11, source.m12, source.m13,
source.m20, source.m21, source.m22, source.m23,
source.m30, source.m31, source.m32, source.m33);
}
public void apply(float n00, float n01, float n02,
float n10, float n11, float n12) {
apply(n00, n01, 0, n02,
n10, n11, 0, n12,
0, 0, 1, 0,
0, 0, 0, 1);
}
public void apply(float n00, float n01, float n02, float n03,
float n10, float n11, float n12, float n13,
float n20, float n21, float n22, float n23,
float n30, float n31, float n32, float n33) {
float r00 = m00*n00 + m01*n10 + m02*n20 + m03*n30;
float r01 = m00*n01 + m01*n11 + m02*n21 + m03*n31;
float r02 = m00*n02 + m01*n12 + m02*n22 + m03*n32;
float r03 = m00*n03 + m01*n13 + m02*n23 + m03*n33;
float r10 = m10*n00 + m11*n10 + m12*n20 + m13*n30;
float r11 = m10*n01 + m11*n11 + m12*n21 + m13*n31;
float r12 = m10*n02 + m11*n12 + m12*n22 + m13*n32;
float r13 = m10*n03 + m11*n13 + m12*n23 + m13*n33;
float r20 = m20*n00 + m21*n10 + m22*n20 + m23*n30;
float r21 = m20*n01 + m21*n11 + m22*n21 + m23*n31;
float r22 = m20*n02 + m21*n12 + m22*n22 + m23*n32;
float r23 = m20*n03 + m21*n13 + m22*n23 + m23*n33;
float r30 = m30*n00 + m31*n10 + m32*n20 + m33*n30;
float r31 = m30*n01 + m31*n11 + m32*n21 + m33*n31;
float r32 = m30*n02 + m31*n12 + m32*n22 + m33*n32;
float r33 = m30*n03 + m31*n13 + m32*n23 + m33*n33;
m00 = r00; m01 = r01; m02 = r02; m03 = r03;
m10 = r10; m11 = r11; m12 = r12; m13 = r13;
m20 = r20; m21 = r21; m22 = r22; m23 = r23;
m30 = r30; m31 = r31; m32 = r32; m33 = r33;
}
public void preApply(PMatrix2D left) {
preApply(left.m00, left.m01, 0, left.m02,
left.m10, left.m11, 0, left.m12,
0, 0, 1, 0,
0, 0, 0, 1);
}
/**
* Apply another matrix to the left of this one.
*/
public void preApply(PMatrix3D left) {
preApply(left.m00, left.m01, left.m02, left.m03,
left.m10, left.m11, left.m12, left.m13,
left.m20, left.m21, left.m22, left.m23,
left.m30, left.m31, left.m32, left.m33);
}
public void preApply(float n00, float n01, float n02,
float n10, float n11, float n12) {
preApply(n00, n01, 0, n02,
n10, n11, 0, n12,
0, 0, 1, 0,
0, 0, 0, 1);
}
public void preApply(float n00, float n01, float n02, float n03,
float n10, float n11, float n12, float n13,
float n20, float n21, float n22, float n23,
float n30, float n31, float n32, float n33) {
float r00 = n00*m00 + n01*m10 + n02*m20 + n03*m30;
float r01 = n00*m01 + n01*m11 + n02*m21 + n03*m31;
float r02 = n00*m02 + n01*m12 + n02*m22 + n03*m32;
float r03 = n00*m03 + n01*m13 + n02*m23 + n03*m33;
float r10 = n10*m00 + n11*m10 + n12*m20 + n13*m30;
float r11 = n10*m01 + n11*m11 + n12*m21 + n13*m31;
float r12 = n10*m02 + n11*m12 + n12*m22 + n13*m32;
float r13 = n10*m03 + n11*m13 + n12*m23 + n13*m33;
float r20 = n20*m00 + n21*m10 + n22*m20 + n23*m30;
float r21 = n20*m01 + n21*m11 + n22*m21 + n23*m31;
float r22 = n20*m02 + n21*m12 + n22*m22 + n23*m32;
float r23 = n20*m03 + n21*m13 + n22*m23 + n23*m33;
float r30 = n30*m00 + n31*m10 + n32*m20 + n33*m30;
float r31 = n30*m01 + n31*m11 + n32*m21 + n33*m31;
float r32 = n30*m02 + n31*m12 + n32*m22 + n33*m32;
float r33 = n30*m03 + n31*m13 + n32*m23 + n33*m33;
m00 = r00; m01 = r01; m02 = r02; m03 = r03;
m10 = r10; m11 = r11; m12 = r12; m13 = r13;
m20 = r20; m21 = r21; m22 = r22; m23 = r23;
m30 = r30; m31 = r31; m32 = r32; m33 = r33;
}
//////////////////////////////////////////////////////////////
public PVector mult(PVector source, PVector target) {
if (target == null) {
target = new PVector();
}
target.set(m00*source.x + m01*source.y + m02*source.z + m03,
m10*source.x + m11*source.y + m12*source.z + m13,
m20*source.x + m21*source.y + m22*source.z + m23);
// float tw = m30*source.x + m31*source.y + m32*source.z + m33;
// if (tw != 0 && tw != 1) {
// target.div(tw);
// }
return target;
}
/*
public PVector cmult(PVector source, PVector target) {
if (target == null) {
target = new PVector();
}
target.x = m00*source.x + m10*source.y + m20*source.z + m30;
target.y = m01*source.x + m11*source.y + m21*source.z + m31;
target.z = m02*source.x + m12*source.y + m22*source.z + m32;
float tw = m03*source.x + m13*source.y + m23*source.z + m33;
if (tw != 0 && tw != 1) {
target.div(tw);
}
return target;
}
*/
/**
* Multiply a three or four element vector against this matrix. If out is
* null or not length 3 or 4, a new float array (length 3) will be returned.
*/
public float[] mult(float[] source, float[] target) {
if (target == null || target.length < 3) {
target = new float[3];
}
if (source == target) {
throw new RuntimeException("The source and target vectors used in " +
"PMatrix3D.mult() cannot be identical.");
}
if (target.length == 3) {
target[0] = m00*source[0] + m01*source[1] + m02*source[2] + m03;
target[1] = m10*source[0] + m11*source[1] + m12*source[2] + m13;
target[2] = m20*source[0] + m21*source[1] + m22*source[2] + m23;
//float w = m30*source[0] + m31*source[1] + m32*source[2] + m33;
//if (w != 0 && w != 1) {
// target[0] /= w; target[1] /= w; target[2] /= w;
//}
} else if (target.length > 3) {
target[0] = m00*source[0] + m01*source[1] + m02*source[2] + m03*source[3];
target[1] = m10*source[0] + m11*source[1] + m12*source[2] + m13*source[3];
target[2] = m20*source[0] + m21*source[1] + m22*source[2] + m23*source[3];
target[3] = m30*source[0] + m31*source[1] + m32*source[2] + m33*source[3];
}
return target;
}
public float multX(float x, float y) {
return m00*x + m01*y + m03;
}
public float multY(float x, float y) {
return m10*x + m11*y + m13;
}
public float multX(float x, float y, float z) {
return m00*x + m01*y + m02*z + m03;
}
public float multY(float x, float y, float z) {
return m10*x + m11*y + m12*z + m13;
}
public float multZ(float x, float y, float z) {
return m20*x + m21*y + m22*z + m23;
}
public float multW(float x, float y, float z) {
return m30*x + m31*y + m32*z + m33;
}
public float multX(float x, float y, float z, float w) {
return m00*x + m01*y + m02*z + m03*w;
}
public float multY(float x, float y, float z, float w) {
return m10*x + m11*y + m12*z + m13*w;
}
public float multZ(float x, float y, float z, float w) {
return m20*x + m21*y + m22*z + m23*w;
}
public float multW(float x, float y, float z, float w) {
return m30*x + m31*y + m32*z + m33*w;
}
/**
* Transpose this matrix.
*/
public void transpose() {
float temp;
temp = m01; m01 = m10; m10 = temp;
temp = m02; m02 = m20; m20 = temp;
temp = m03; m03 = m30; m30 = temp;
temp = m12; m12 = m21; m21 = temp;
temp = m13; m13 = m31; m31 = temp;
temp = m23; m23 = m32; m32 = temp;
}
/**
* Invert this matrix.
* @return true if successful
*/
public boolean invert() {
float determinant = determinant();
if (determinant == 0) {
return false;
}
// first row
float t00 = determinant3x3(m11, m12, m13, m21, m22, m23, m31, m32, m33);
float t01 = -determinant3x3(m10, m12, m13, m20, m22, m23, m30, m32, m33);
float t02 = determinant3x3(m10, m11, m13, m20, m21, m23, m30, m31, m33);
float t03 = -determinant3x3(m10, m11, m12, m20, m21, m22, m30, m31, m32);
// second row
float t10 = -determinant3x3(m01, m02, m03, m21, m22, m23, m31, m32, m33);
float t11 = determinant3x3(m00, m02, m03, m20, m22, m23, m30, m32, m33);
float t12 = -determinant3x3(m00, m01, m03, m20, m21, m23, m30, m31, m33);
float t13 = determinant3x3(m00, m01, m02, m20, m21, m22, m30, m31, m32);
// third row
float t20 = determinant3x3(m01, m02, m03, m11, m12, m13, m31, m32, m33);
float t21 = -determinant3x3(m00, m02, m03, m10, m12, m13, m30, m32, m33);
float t22 = determinant3x3(m00, m01, m03, m10, m11, m13, m30, m31, m33);
float t23 = -determinant3x3(m00, m01, m02, m10, m11, m12, m30, m31, m32);
// fourth row
float t30 = -determinant3x3(m01, m02, m03, m11, m12, m13, m21, m22, m23);
float t31 = determinant3x3(m00, m02, m03, m10, m12, m13, m20, m22, m23);
float t32 = -determinant3x3(m00, m01, m03, m10, m11, m13, m20, m21, m23);
float t33 = determinant3x3(m00, m01, m02, m10, m11, m12, m20, m21, m22);
// transpose and divide by the determinant
m00 = t00 / determinant;
m01 = t10 / determinant;
m02 = t20 / determinant;
m03 = t30 / determinant;
m10 = t01 / determinant;
m11 = t11 / determinant;
m12 = t21 / determinant;
m13 = t31 / determinant;
m20 = t02 / determinant;
m21 = t12 / determinant;
m22 = t22 / determinant;
m23 = t32 / determinant;
m30 = t03 / determinant;
m31 = t13 / determinant;
m32 = t23 / determinant;
m33 = t33 / determinant;
return true;
}
/**
* Calculate the determinant of a 3x3 matrix.
* @return result
*/
private float determinant3x3(float t00, float t01, float t02,
float t10, float t11, float t12,
float t20, float t21, float t22) {
return (t00 * (t11 * t22 - t12 * t21) +
t01 * (t12 * t20 - t10 * t22) +
t02 * (t10 * t21 - t11 * t20));
}
/**
* @return the determinant of the matrix
*/
public float determinant() {
float f =
m00
* ((m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32)
- m13 * m22 * m31
- m11 * m23 * m32
- m12 * m21 * m33);
f -= m01
* ((m10 * m22 * m33 + m12 * m23 * m30 + m13 * m20 * m32)
- m13 * m22 * m30
- m10 * m23 * m32
- m12 * m20 * m33);
f += m02
* ((m10 * m21 * m33 + m11 * m23 * m30 + m13 * m20 * m31)
- m13 * m21 * m30
- m10 * m23 * m31
- m11 * m20 * m33);
f -= m03
* ((m10 * m21 * m32 + m11 * m22 * m30 + m12 * m20 * m31)
- m12 * m21 * m30
- m10 * m22 * m31
- m11 * m20 * m32);
return f;
}
//////////////////////////////////////////////////////////////
// REVERSE VERSIONS OF MATRIX OPERATIONS
// These functions should not be used, as they will be removed in the future.
protected void invTranslate(float tx, float ty, float tz) {
preApply(1, 0, 0, -tx,
0, 1, 0, -ty,
0, 0, 1, -tz,
0, 0, 0, 1);
}
protected void invRotateX(float angle) {
float c = cos(-angle);
float s = sin(-angle);
preApply(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
}
protected void invRotateY(float angle) {
float c = cos(-angle);
float s = sin(-angle);
preApply(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
}
protected void invRotateZ(float angle) {
float c = cos(-angle);
float s = sin(-angle);
preApply(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
}
protected void invRotate(float angle, float v0, float v1, float v2) {
//TODO should make sure this vector is normalized
float c = cos(-angle);
float s = sin(-angle);
float t = 1.0f - c;
preApply((t*v0*v0) + c, (t*v0*v1) - (s*v2), (t*v0*v2) + (s*v1), 0,
(t*v0*v1) + (s*v2), (t*v1*v1) + c, (t*v1*v2) - (s*v0), 0,
(t*v0*v2) - (s*v1), (t*v1*v2) + (s*v0), (t*v2*v2) + c, 0,
0, 0, 0, 1);
}
protected void invScale(float x, float y, float z) {
preApply(1/x, 0, 0, 0, 0, 1/y, 0, 0, 0, 0, 1/z, 0, 0, 0, 0, 1);
}
protected boolean invApply(float n00, float n01, float n02, float n03,
float n10, float n11, float n12, float n13,
float n20, float n21, float n22, float n23,
float n30, float n31, float n32, float n33) {
if (inverseCopy == null) {
inverseCopy = new PMatrix3D();
}
inverseCopy.set(n00, n01, n02, n03,
n10, n11, n12, n13,
n20, n21, n22, n23,
n30, n31, n32, n33);
if (!inverseCopy.invert()) {
return false;
}
preApply(inverseCopy);
return true;
}
//////////////////////////////////////////////////////////////
public void print() {
/*
System.out.println(m00 + " " + m01 + " " + m02 + " " + m03 + "\n" +
m10 + " " + m11 + " " + m12 + " " + m13 + "\n" +
m20 + " " + m21 + " " + m22 + " " + m23 + "\n" +
m30 + " " + m31 + " " + m32 + " " + m33 + "\n");
*/
int big = (int) Math.abs(max(max(max(max(abs(m00), abs(m01)),
max(abs(m02), abs(m03))),
max(max(abs(m10), abs(m11)),
max(abs(m12), abs(m13)))),
max(max(max(abs(m20), abs(m21)),
max(abs(m22), abs(m23))),
max(max(abs(m30), abs(m31)),
max(abs(m32), abs(m33))))));
int digits = 1;
if (Float.isNaN(big) || Float.isInfinite(big)) { // avoid infinite loop
digits = 5;
} else {
while ((big /= 10) != 0) digits++; // cheap log()
}
System.out.println(PApplet.nfs(m00, digits, 4) + " " +
PApplet.nfs(m01, digits, 4) + " " +
PApplet.nfs(m02, digits, 4) + " " +
PApplet.nfs(m03, digits, 4));
System.out.println(PApplet.nfs(m10, digits, 4) + " " +
PApplet.nfs(m11, digits, 4) + " " +
PApplet.nfs(m12, digits, 4) + " " +
PApplet.nfs(m13, digits, 4));
System.out.println(PApplet.nfs(m20, digits, 4) + " " +
PApplet.nfs(m21, digits, 4) + " " +
PApplet.nfs(m22, digits, 4) + " " +
PApplet.nfs(m23, digits, 4));
System.out.println(PApplet.nfs(m30, digits, 4) + " " +
PApplet.nfs(m31, digits, 4) + " " +
PApplet.nfs(m32, digits, 4) + " " +
PApplet.nfs(m33, digits, 4));
System.out.println();
}
//////////////////////////////////////////////////////////////
static private final float max(float a, float b) {
return (a > b) ? a : b;
}
static private final float abs(float a) {
return (a < 0) ? -a : a;
}
static private final float sin(float angle) {
return (float) Math.sin(angle);
}
static private final float cos(float angle) {
return (float) Math.cos(angle);
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/compute/mgmt-v2018_09_30/src/main/java/com/microsoft/azure/management/compute/v2018_09_30/Snapshot.java | 8812 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.compute.v2018_09_30;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.Resource;
import com.microsoft.azure.arm.resources.models.GroupableResourceCore;
import com.microsoft.azure.arm.resources.models.HasResourceGroup;
import com.microsoft.azure.arm.model.Refreshable;
import com.microsoft.azure.arm.model.Updatable;
import com.microsoft.azure.arm.model.Appliable;
import com.microsoft.azure.arm.model.Creatable;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.compute.v2018_09_30.implementation.ComputeManager;
import org.joda.time.DateTime;
import com.microsoft.azure.management.compute.v2018_09_30.implementation.SnapshotInner;
/**
* Type representing Snapshot.
*/
public interface Snapshot extends HasInner<SnapshotInner>, Resource, GroupableResourceCore<ComputeManager, SnapshotInner>, HasResourceGroup, Refreshable<Snapshot>, Updatable<Snapshot.Update>, HasManager<ComputeManager> {
/**
* @return the creationData value.
*/
CreationData creationData();
/**
* @return the diskSizeGB value.
*/
Integer diskSizeGB();
/**
* @return the encryptionSettingsCollection value.
*/
EncryptionSettingsCollection encryptionSettingsCollection();
/**
* @return the hyperVGeneration value.
*/
HyperVGeneration hyperVGeneration();
/**
* @return the managedBy value.
*/
String managedBy();
/**
* @return the osType value.
*/
OperatingSystemTypes osType();
/**
* @return the provisioningState value.
*/
String provisioningState();
/**
* @return the sku value.
*/
SnapshotSku sku();
/**
* @return the timeCreated value.
*/
DateTime timeCreated();
/**
* The entirety of the Snapshot definition.
*/
interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreationData, DefinitionStages.WithCreate {
}
/**
* Grouping of Snapshot definition stages.
*/
interface DefinitionStages {
/**
* The first stage of a Snapshot definition.
*/
interface Blank extends GroupableResourceCore.DefinitionWithRegion<WithGroup> {
}
/**
* The stage of the Snapshot definition allowing to specify the resource group.
*/
interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup<WithCreationData> {
}
/**
* The stage of the snapshot definition allowing to specify CreationData.
*/
interface WithCreationData {
/**
* Specifies creationData.
* @param creationData Disk source information. CreationData information cannot be changed after the disk has been created
* @return the next definition stage
*/
WithCreate withCreationData(CreationData creationData);
}
/**
* The stage of the snapshot definition allowing to specify DiskSizeGB.
*/
interface WithDiskSizeGB {
/**
* Specifies diskSizeGB.
* @param diskSizeGB If creationData.createOption is Empty, this field is mandatory and it indicates the size of the VHD to create. If this field is present for updates or creation with other options, it indicates a resize. Resizes are only allowed if the disk is not attached to a running VM, and can only increase the disk's size
* @return the next definition stage
*/
WithCreate withDiskSizeGB(Integer diskSizeGB);
}
/**
* The stage of the snapshot definition allowing to specify EncryptionSettingsCollection.
*/
interface WithEncryptionSettingsCollection {
/**
* Specifies encryptionSettingsCollection.
* @param encryptionSettingsCollection Encryption settings collection used be Azure Disk Encryption, can contain multiple encryption settings per disk or snapshot
* @return the next definition stage
*/
WithCreate withEncryptionSettingsCollection(EncryptionSettingsCollection encryptionSettingsCollection);
}
/**
* The stage of the snapshot definition allowing to specify HyperVGeneration.
*/
interface WithHyperVGeneration {
/**
* Specifies hyperVGeneration.
* @param hyperVGeneration The hypervisor generation of the Virtual Machine. Applicable to OS disks only. Possible values include: 'V1', 'V2'
* @return the next definition stage
*/
WithCreate withHyperVGeneration(HyperVGeneration hyperVGeneration);
}
/**
* The stage of the snapshot definition allowing to specify OsType.
*/
interface WithOsType {
/**
* Specifies osType.
* @param osType The Operating System type. Possible values include: 'Windows', 'Linux'
* @return the next definition stage
*/
WithCreate withOsType(OperatingSystemTypes osType);
}
/**
* The stage of the snapshot definition allowing to specify Sku.
*/
interface WithSku {
/**
* Specifies sku.
* @param sku the sku parameter value
* @return the next definition stage
*/
WithCreate withSku(SnapshotSku sku);
}
/**
* The stage of the definition which contains all the minimum required inputs for
* the resource to be created (via {@link WithCreate#create()}), but also allows
* for any other optional settings to be specified.
*/
interface WithCreate extends Creatable<Snapshot>, Resource.DefinitionWithTags<WithCreate>, DefinitionStages.WithDiskSizeGB, DefinitionStages.WithEncryptionSettingsCollection, DefinitionStages.WithHyperVGeneration, DefinitionStages.WithOsType, DefinitionStages.WithSku {
}
}
/**
* The template for a Snapshot update operation, containing all the settings that can be modified.
*/
interface Update extends Appliable<Snapshot>, Resource.UpdateWithTags<Update>, UpdateStages.WithDiskSizeGB, UpdateStages.WithEncryptionSettingsCollection, UpdateStages.WithOsType, UpdateStages.WithSku {
}
/**
* Grouping of Snapshot update stages.
*/
interface UpdateStages {
/**
* The stage of the snapshot update allowing to specify DiskSizeGB.
*/
interface WithDiskSizeGB {
/**
* Specifies diskSizeGB.
* @param diskSizeGB If creationData.createOption is Empty, this field is mandatory and it indicates the size of the VHD to create. If this field is present for updates or creation with other options, it indicates a resize. Resizes are only allowed if the disk is not attached to a running VM, and can only increase the disk's size
* @return the next update stage
*/
Update withDiskSizeGB(Integer diskSizeGB);
}
/**
* The stage of the snapshot update allowing to specify EncryptionSettingsCollection.
*/
interface WithEncryptionSettingsCollection {
/**
* Specifies encryptionSettingsCollection.
* @param encryptionSettingsCollection Encryption settings collection used be Azure Disk Encryption, can contain multiple encryption settings per disk or snapshot
* @return the next update stage
*/
Update withEncryptionSettingsCollection(EncryptionSettingsCollection encryptionSettingsCollection);
}
/**
* The stage of the snapshot update allowing to specify OsType.
*/
interface WithOsType {
/**
* Specifies osType.
* @param osType the Operating System type. Possible values include: 'Windows', 'Linux'
* @return the next update stage
*/
Update withOsType(OperatingSystemTypes osType);
}
/**
* The stage of the snapshot update allowing to specify Sku.
*/
interface WithSku {
/**
* Specifies sku.
* @param sku the sku parameter value
* @return the next update stage
*/
Update withSku(SnapshotSku sku);
}
}
}
| mit |
C-Aniruddh/xPlodMusic | src/com/aniruddhc/xPlod/ui/widgets/RepeatingImageButton.java | 4143 | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aniruddhc.xPlod.ui.widgets;
import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
/**
* A button that will repeatedly call a 'listener' method as long as the button
* is pressed.
*/
public class RepeatingImageButton extends ImageButton {
private long mStartTime;
private int mRepeatCount;
private RepeatListener mListener;
private long mInterval = 500;
public RepeatingImageButton(Context context) {
this(context, null);
}
public RepeatingImageButton(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.imageButtonStyle);
}
public RepeatingImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFocusable(true);
setLongClickable(true);
}
/**
* Sets the listener to be called while the button is pressed and the
* interval in milliseconds with which it will be called.
*
* @param l The listener that will be called
* @param interval The interval in milliseconds for calls
*/
public void setRepeatListener(RepeatListener l, long interval) {
mListener = l;
mInterval = interval;
}
@Override
public boolean performLongClick() {
mStartTime = SystemClock.elapsedRealtime();
mRepeatCount = 0;
post(mRepeater);
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
// remove the repeater, but call the hook one more time
removeCallbacks(mRepeater);
if (mStartTime != 0) {
doRepeat(true);
mStartTime = 0;
}
}
return super.onTouchEvent(event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
// need to call super to make long press work, but return
// true so that the application doesn't get the down event.
super.onKeyDown(keyCode, event);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER:
// remove the repeater, but call the hook one more time
removeCallbacks(mRepeater);
if (mStartTime != 0) {
doRepeat(true);
mStartTime = 0;
}
}
return super.onKeyUp(keyCode, event);
}
private final Runnable mRepeater = new Runnable() {
@Override
public void run() {
doRepeat(false);
if (isPressed()) {
postDelayed(this, mInterval);
}
}
};
private void doRepeat(boolean last) {
long now = SystemClock.elapsedRealtime();
if (mListener != null) {
mListener.onRepeat(this, now - mStartTime, last ? -1 : mRepeatCount++);
}
}
public interface RepeatListener {
void onRepeat(View v, long duration, int repeatcount);
}
}
| mit |
ssdwa/android | dConnectManager/dConnectManager/src/org/deviceconnect/android/manager/setting/KeywordDialogFragment.java | 2278 | /*
KeywordDialogFragment.java
Copyright (c) 2014 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
package org.deviceconnect.android.manager.setting;
import org.deviceconnect.android.manager.DConnectService;
import org.deviceconnect.android.manager.R;
import org.deviceconnect.message.intent.message.IntentDConnectMessage;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
/**
* キーワード表示用フラグメント.
*
* @author NTT DOCOMO, INC.
*/
public class KeywordDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
String keyword = sp.getString(getString(R.string.key_settings_dconn_keyword), null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final Dialog dialog = builder.setTitle(R.string.activity_keyword).setMessage(keyword)
.setPositiveButton(R.string.activity_keyword_ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
dialog.dismiss();
}
}).create();
return dialog;
}
@Override
public void onStop() {
super.onStop();
getActivity().finish();
// dConnectManagerにダイアログを閉じたことを通知.
Intent request = getActivity().getIntent();
int requestCode = request.getIntExtra(IntentDConnectMessage.EXTRA_REQUEST_CODE, -1);
if (requestCode == -1) {
return;
}
Intent intent = new Intent();
intent.setClass(getActivity(), DConnectService.class);
intent.setAction(IntentDConnectMessage.ACTION_RESPONSE);
intent.putExtra(IntentDConnectMessage.EXTRA_REQUEST_CODE, requestCode);
getActivity().startService(intent);
}
}
| mit |
uwol/cobol85parser | src/test/java/gov/nist/RL301MTest.java | 542 | package gov.nist;
import java.io.File;
import io.proleap.cobol.preprocessor.CobolPreprocessor.CobolSourceFormatEnum;
import io.proleap.cobol.runner.CobolParseTestRunner;
import io.proleap.cobol.runner.impl.CobolParseTestRunnerImpl;
import org.junit.Test;
public class RL301MTest {
@Test
public void test() throws Exception {
final File inputFile = new File("src/test/resources/gov/nist/RL301M.CBL");
final CobolParseTestRunner runner = new CobolParseTestRunnerImpl();
runner.parseFile(inputFile, CobolSourceFormatEnum.FIXED);
}
} | mit |
sdgdsffdsfff/csustRepo | trunk/src/com/yunstudio/service/GsCatalogService.java | 227 | package com.yunstudio.service;
import java.util.List;
import com.yunstudio.entity.RepGscatalog;
public interface GsCatalogService extends BaseService<RepGscatalog> {
List<RepGscatalog> findGscatalogByName(String name);
}
| mit |
treejames/JMD | src/org/apache/bcel/classfile/Utility.java | 48975 | /*
* Copyright 2000-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.bcel.classfile;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.FilterReader;
import java.io.FilterWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.bcel.Constants;
import org.apache.bcel.util.ByteSequence;
/**
* Utility functions that do not really belong to any class in particular.
*
* @version $Id: Utility.java 386056 2006-03-15 11:31:56Z tcurdt $
* @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A>
*/
public abstract class Utility {
private static int unwrap( ThreadLocal tl ) {
return ((Integer) tl.get()).intValue();
}
private static void wrap( ThreadLocal tl, int value ) {
tl.set(new Integer(value));
}
private static ThreadLocal consumed_chars = new ThreadLocal() {
protected Object initialValue() {
return new Integer(0);
}
};/* How many chars have been consumed
* during parsing in signatureToString().
* Read by methodSignatureToString().
* Set by side effect,but only internally.
*/
private static boolean wide = false; /* The `WIDE' instruction is used in the
* byte code to allow 16-bit wide indices
* for local variables. This opcode
* precedes an `ILOAD', e.g.. The opcode
* immediately following takes an extra
* byte which is combined with the
* following byte to form a
* 16-bit value.
*/
/**
* Convert bit field of flags into string such as `static final'.
*
* @param access_flags Access flags
* @return String representation of flags
*/
public static final String accessToString( int access_flags ) {
return accessToString(access_flags, false);
}
/**
* Convert bit field of flags into string such as `static final'.
*
* Special case: Classes compiled with new compilers and with the
* `ACC_SUPER' flag would be said to be "synchronized". This is
* because SUN used the same value for the flags `ACC_SUPER' and
* `ACC_SYNCHRONIZED'.
*
* @param access_flags Access flags
* @param for_class access flags are for class qualifiers ?
* @return String representation of flags
*/
public static final String accessToString( int access_flags, boolean for_class ) {
StringBuffer buf = new StringBuffer();
int p = 0;
for (int i = 0; p < Constants.MAX_ACC_FLAG; i++) { // Loop through known flags
p = pow2(i);
if ((access_flags & p) != 0) {
/* Special case: Classes compiled with new compilers and with the
* `ACC_SUPER' flag would be said to be "synchronized". This is
* because SUN used the same value for the flags `ACC_SUPER' and
* `ACC_SYNCHRONIZED'.
*/
if (for_class && ((p == Constants.ACC_SUPER) || (p == Constants.ACC_INTERFACE))) {
continue;
}
buf.append(Constants.ACCESS_NAMES[i]).append(" ");
}
}
return buf.toString().trim();
}
/**
* @return "class" or "interface", depending on the ACC_INTERFACE flag
*/
public static final String classOrInterface( int access_flags ) {
return ((access_flags & Constants.ACC_INTERFACE) != 0) ? "interface" : "class";
}
/**
* Disassemble a byte array of JVM byte codes starting from code line
* `index' and return the disassembled string representation. Decode only
* `num' opcodes (including their operands), use -1 if you want to
* decompile everything.
*
* @param code byte code array
* @param constant_pool Array of constants
* @param index offset in `code' array
* <EM>(number of opcodes, not bytes!)</EM>
* @param length number of opcodes to decompile, -1 for all
* @param verbose be verbose, e.g. print constant pool index
* @return String representation of byte codes
*/
public static final String codeToString( byte[] code, ConstantPool constant_pool, int index,
int length, boolean verbose ) {
StringBuffer buf = new StringBuffer(code.length * 20); // Should be sufficient
ByteSequence stream = new ByteSequence(code);
try {
for (int i = 0; i < index; i++) {
codeToString(stream, constant_pool, verbose);
}
for (int i = 0; stream.available() > 0; i++) {
if ((length < 0) || (i < length)) {
String indices = fillup(stream.getIndex() + ":", 6, true, ' ');
buf.append(indices).append(codeToString(stream, constant_pool, verbose))
.append('\n');
}
}
} catch (IOException e) {
System.out.println(buf.toString());
e.printStackTrace();
throw new ClassFormatException("Byte code error: " + e);
}
return buf.toString();
}
public static final String codeToString( byte[] code, ConstantPool constant_pool, int index,
int length ) {
return codeToString(code, constant_pool, index, length, true);
}
/**
* Disassemble a stream of byte codes and return the
* string representation.
*
* @param bytes stream of bytes
* @param constant_pool Array of constants
* @param verbose be verbose, e.g. print constant pool index
* @return String representation of byte code
*/
public static final String codeToString( ByteSequence bytes, ConstantPool constant_pool,
boolean verbose ) throws IOException {
short opcode = (short) bytes.readUnsignedByte();
int default_offset = 0, low, high, npairs;
int index, vindex, constant;
int[] match, jump_table;
int no_pad_bytes = 0, offset;
StringBuffer buf = new StringBuffer(Constants.OPCODE_NAMES[opcode]);
/* Special case: Skip (0-3) padding bytes, i.e., the
* following bytes are 4-byte-aligned
*/
if ((opcode == Constants.TABLESWITCH) || (opcode == Constants.LOOKUPSWITCH)) {
int remainder = bytes.getIndex() % 4;
no_pad_bytes = (remainder == 0) ? 0 : 4 - remainder;
for (int i = 0; i < no_pad_bytes; i++) {
byte b;
if ((b = bytes.readByte()) != 0) {
System.err.println("Warning: Padding byte != 0 in "
+ Constants.OPCODE_NAMES[opcode] + ":" + b);
}
}
// Both cases have a field default_offset in common
default_offset = bytes.readInt();
}
switch (opcode) {
/* Table switch has variable length arguments.
*/
case Constants.TABLESWITCH:
low = bytes.readInt();
high = bytes.readInt();
offset = bytes.getIndex() - 12 - no_pad_bytes - 1;
default_offset += offset;
buf.append("\tdefault = ").append(default_offset).append(", low = ").append(low)
.append(", high = ").append(high).append("(");
jump_table = new int[high - low + 1];
for (int i = 0; i < jump_table.length; i++) {
jump_table[i] = offset + bytes.readInt();
buf.append(jump_table[i]);
if (i < jump_table.length - 1) {
buf.append(", ");
}
}
buf.append(")");
break;
/* Lookup switch has variable length arguments.
*/
case Constants.LOOKUPSWITCH: {
npairs = bytes.readInt();
offset = bytes.getIndex() - 8 - no_pad_bytes - 1;
match = new int[npairs];
jump_table = new int[npairs];
default_offset += offset;
buf.append("\tdefault = ").append(default_offset).append(", npairs = ").append(
npairs).append(" (");
for (int i = 0; i < npairs; i++) {
match[i] = bytes.readInt();
jump_table[i] = offset + bytes.readInt();
buf.append("(").append(match[i]).append(", ").append(jump_table[i]).append(")");
if (i < npairs - 1) {
buf.append(", ");
}
}
buf.append(")");
}
break;
/* Two address bytes + offset from start of byte stream form the
* jump target
*/
case Constants.GOTO:
case Constants.IFEQ:
case Constants.IFGE:
case Constants.IFGT:
case Constants.IFLE:
case Constants.IFLT:
case Constants.JSR:
case Constants.IFNE:
case Constants.IFNONNULL:
case Constants.IFNULL:
case Constants.IF_ACMPEQ:
case Constants.IF_ACMPNE:
case Constants.IF_ICMPEQ:
case Constants.IF_ICMPGE:
case Constants.IF_ICMPGT:
case Constants.IF_ICMPLE:
case Constants.IF_ICMPLT:
case Constants.IF_ICMPNE:
buf.append("\t\t#").append((bytes.getIndex() - 1) + bytes.readShort());
break;
/* 32-bit wide jumps
*/
case Constants.GOTO_W:
case Constants.JSR_W:
buf.append("\t\t#").append(((bytes.getIndex() - 1) + bytes.readInt()));
break;
/* Index byte references local variable (register)
*/
case Constants.ALOAD:
case Constants.ASTORE:
case Constants.DLOAD:
case Constants.DSTORE:
case Constants.FLOAD:
case Constants.FSTORE:
case Constants.ILOAD:
case Constants.ISTORE:
case Constants.LLOAD:
case Constants.LSTORE:
case Constants.RET:
if (wide) {
vindex = bytes.readUnsignedShort();
wide = false; // Clear flag
} else {
vindex = bytes.readUnsignedByte();
}
buf.append("\t\t%").append(vindex);
break;
/*
* Remember wide byte which is used to form a 16-bit address in the
* following instruction. Relies on that the method is called again with
* the following opcode.
*/
case Constants.WIDE:
wide = true;
buf.append("\t(wide)");
break;
/* Array of basic type.
*/
case Constants.NEWARRAY:
buf.append("\t\t<").append(Constants.TYPE_NAMES[bytes.readByte()]).append(">");
break;
/* Access object/class fields.
*/
case Constants.GETFIELD:
case Constants.GETSTATIC:
case Constants.PUTFIELD:
case Constants.PUTSTATIC:
index = bytes.readUnsignedShort();
buf.append("\t\t").append(
constant_pool.constantToString(index, Constants.CONSTANT_Fieldref)).append(
(verbose ? " (" + index + ")" : ""));
break;
/* Operands are references to classes in constant pool
*/
case Constants.NEW:
case Constants.CHECKCAST:
buf.append("\t");
case Constants.INSTANCEOF:
index = bytes.readUnsignedShort();
buf.append("\t<").append(
constant_pool.constantToString(index, Constants.CONSTANT_Class))
.append(">").append((verbose ? " (" + index + ")" : ""));
break;
/* Operands are references to methods in constant pool
*/
case Constants.INVOKESPECIAL:
case Constants.INVOKESTATIC:
case Constants.INVOKEVIRTUAL:
index = bytes.readUnsignedShort();
buf.append("\t").append(
constant_pool.constantToString(index, Constants.CONSTANT_Methodref))
.append((verbose ? " (" + index + ")" : ""));
break;
case Constants.INVOKEINTERFACE:
index = bytes.readUnsignedShort();
int nargs = bytes.readUnsignedByte(); // historical, redundant
buf.append("\t").append(
constant_pool
.constantToString(index, Constants.CONSTANT_InterfaceMethodref))
.append(verbose ? " (" + index + ")\t" : "").append(nargs).append("\t")
.append(bytes.readUnsignedByte()); // Last byte is a reserved space
break;
/* Operands are references to items in constant pool
*/
case Constants.LDC_W:
case Constants.LDC2_W:
index = bytes.readUnsignedShort();
buf.append("\t\t").append(
constant_pool.constantToString(index, constant_pool.getConstant(index)
.getTag())).append((verbose ? " (" + index + ")" : ""));
break;
case Constants.LDC:
index = bytes.readUnsignedByte();
buf.append("\t\t").append(
constant_pool.constantToString(index, constant_pool.getConstant(index)
.getTag())).append((verbose ? " (" + index + ")" : ""));
break;
/* Array of references.
*/
case Constants.ANEWARRAY:
index = bytes.readUnsignedShort();
buf.append("\t\t<").append(
compactClassName(constant_pool.getConstantString(index,
Constants.CONSTANT_Class), false)).append(">").append(
(verbose ? " (" + index + ")" : ""));
break;
/* Multidimensional array of references.
*/
case Constants.MULTIANEWARRAY: {
index = bytes.readUnsignedShort();
int dimensions = bytes.readUnsignedByte();
buf.append("\t<").append(
compactClassName(constant_pool.getConstantString(index,
Constants.CONSTANT_Class), false)).append(">\t").append(dimensions)
.append((verbose ? " (" + index + ")" : ""));
}
break;
/* Increment local variable.
*/
case Constants.IINC:
if (wide) {
vindex = bytes.readUnsignedShort();
constant = bytes.readShort();
wide = false;
} else {
vindex = bytes.readUnsignedByte();
constant = bytes.readByte();
}
buf.append("\t\t%").append(vindex).append("\t").append(constant);
break;
default:
if (Constants.NO_OF_OPERANDS[opcode] > 0) {
for (int i = 0; i < Constants.TYPE_OF_OPERANDS[opcode].length; i++) {
buf.append("\t\t");
switch (Constants.TYPE_OF_OPERANDS[opcode][i]) {
case Constants.T_BYTE:
buf.append(bytes.readByte());
break;
case Constants.T_SHORT:
buf.append(bytes.readShort());
break;
case Constants.T_INT:
buf.append(bytes.readInt());
break;
default: // Never reached
System.err.println("Unreachable default case reached!");
System.exit(-1);
}
}
}
}
return buf.toString();
}
public static final String codeToString( ByteSequence bytes, ConstantPool constant_pool )
throws IOException {
return codeToString(bytes, constant_pool, true);
}
/**
* Shorten long class names, <em>java/lang/String</em> becomes
* <em>String</em>.
*
* @param str The long class name
* @return Compacted class name
*/
public static final String compactClassName( String str ) {
return compactClassName(str, true);
}
/**
* Shorten long class name <em>str</em>, i.e., chop off the <em>prefix</em>,
* if the
* class name starts with this string and the flag <em>chopit</em> is true.
* Slashes <em>/</em> are converted to dots <em>.</em>.
*
* @param str The long class name
* @param prefix The prefix the get rid off
* @param chopit Flag that determines whether chopping is executed or not
* @return Compacted class name
*/
public static final String compactClassName( String str, String prefix, boolean chopit ) {
int len = prefix.length();
str = str.replace('/', '.'); // Is `/' on all systems, even DOS
if (chopit) {
// If string starts with `prefix' and contains no further dots
if (str.startsWith(prefix) && (str.substring(len).indexOf('.') == -1)) {
str = str.substring(len);
}
}
return str;
}
/**
* Shorten long class names, <em>java/lang/String</em> becomes
* <em>java.lang.String</em>,
* e.g.. If <em>chopit</em> is <em>true</em> the prefix <em>java.lang</em>
* is also removed.
*
* @param str The long class name
* @param chopit Flag that determines whether chopping is executed or not
* @return Compacted class name
*/
public static final String compactClassName( String str, boolean chopit ) {
return compactClassName(str, "java.lang.", chopit);
}
/**
* @return `flag' with bit `i' set to 1
*/
public static final int setBit( int flag, int i ) {
return flag | pow2(i);
}
/**
* @return `flag' with bit `i' set to 0
*/
public static final int clearBit( int flag, int i ) {
int bit = pow2(i);
return (flag & bit) == 0 ? flag : flag ^ bit;
}
/**
* @return true, if bit `i' in `flag' is set
*/
public static final boolean isSet( int flag, int i ) {
return (flag & pow2(i)) != 0;
}
/**
* Converts string containing the method return and argument types
* to a byte code method signature.
*
* @param ret Return type of method
* @param argv Types of method arguments
* @return Byte code representation of method signature
*/
public final static String methodTypeToSignature( String ret, String[] argv )
throws ClassFormatException {
StringBuffer buf = new StringBuffer("(");
String str;
if (argv != null) {
for (int i = 0; i < argv.length; i++) {
str = getSignature(argv[i]);
if (str.endsWith("V")) {
throw new ClassFormatException("Invalid type: " + argv[i]);
}
buf.append(str);
}
}
str = getSignature(ret);
buf.append(")").append(str);
return buf.toString();
}
/**
* @param signature Method signature
* @return Array of argument types
* @throws ClassFormatException
*/
public static final String[] methodSignatureArgumentTypes( String signature )
throws ClassFormatException {
return methodSignatureArgumentTypes(signature, true);
}
/**
* @param signature Method signature
* @param chopit Shorten class names ?
* @return Array of argument types
* @throws ClassFormatException
*/
public static final String[] methodSignatureArgumentTypes( String signature, boolean chopit )
throws ClassFormatException {
List vec = new ArrayList();
int index;
try { // Read all declarations between for `(' and `)'
if (signature.charAt(0) != '(') {
throw new ClassFormatException("Invalid method signature: " + signature);
}
index = 1; // current string position
while (signature.charAt(index) != ')') {
vec.add(signatureToString(signature.substring(index), chopit));
//corrected concurrent private static field acess
index += unwrap(consumed_chars); // update position
}
} catch (StringIndexOutOfBoundsException e) { // Should never occur
throw new ClassFormatException("Invalid method signature: " + signature);
}
return (String[]) vec.toArray(new String[vec.size()]);
}
/**
* @param signature Method signature
* @return return type of method
* @throws ClassFormatException
*/
public static final String methodSignatureReturnType( String signature )
throws ClassFormatException {
return methodSignatureReturnType(signature, true);
}
/**
* @param signature Method signature
* @param chopit Shorten class names ?
* @return return type of method
* @throws ClassFormatException
*/
public static final String methodSignatureReturnType( String signature, boolean chopit )
throws ClassFormatException {
int index;
String type;
try {
// Read return type after `)'
index = signature.lastIndexOf(')') + 1;
type = signatureToString(signature.substring(index), chopit);
} catch (StringIndexOutOfBoundsException e) { // Should never occur
throw new ClassFormatException("Invalid method signature: " + signature);
}
return type;
}
/**
* Converts method signature to string with all class names compacted.
*
* @param signature to convert
* @param name of method
* @param access flags of method
* @return Human readable signature
*/
public static final String methodSignatureToString( String signature, String name, String access ) {
return methodSignatureToString(signature, name, access, true);
}
public static final String methodSignatureToString( String signature, String name,
String access, boolean chopit ) {
return methodSignatureToString(signature, name, access, chopit, null);
}
/**
* A returntype signature represents the return value from a method.
* It is a series of bytes in the following grammar:
*
* <return_signature> ::= <field_type> | V
*
* The character V indicates that the method returns no value. Otherwise, the
* signature indicates the type of the return value.
* An argument signature represents an argument passed to a method:
*
* <argument_signature> ::= <field_type>
*
* A method signature represents the arguments that the method expects, and
* the value that it returns.
* <method_signature> ::= (<arguments_signature>) <return_signature>
* <arguments_signature>::= <argument_signature>*
*
* This method converts such a string into a Java type declaration like
* `void main(String[])' and throws a `ClassFormatException' when the parsed
* type is invalid.
*
* @param signature Method signature
* @param name Method name
* @param access Method access rights
* @return Java type declaration
* @throws ClassFormatException
*/
public static final String methodSignatureToString( String signature, String name,
String access, boolean chopit, LocalVariableTable vars ) throws ClassFormatException {
StringBuffer buf = new StringBuffer("(");
String type;
int index;
int var_index = (access.indexOf("static") >= 0) ? 0 : 1;
try { // Read all declarations between for `(' and `)'
if (signature.charAt(0) != '(') {
throw new ClassFormatException("Invalid method signature: " + signature);
}
index = 1; // current string position
while (signature.charAt(index) != ')') {
String param_type = signatureToString(signature.substring(index), chopit);
buf.append(param_type);
if (vars != null) {
LocalVariable l = vars.getLocalVariable(var_index);
if (l != null) {
buf.append(" ").append(l.getName());
}
} else {
buf.append(" arg").append(var_index);
}
if ("double".equals(param_type) || "long".equals(param_type)) {
var_index += 2;
} else {
var_index++;
}
buf.append(", ");
//corrected concurrent private static field acess
index += unwrap(consumed_chars); // update position
}
index++; // update position
// Read return type after `)'
type = signatureToString(signature.substring(index), chopit);
} catch (StringIndexOutOfBoundsException e) { // Should never occur
throw new ClassFormatException("Invalid method signature: " + signature);
}
if (buf.length() > 1) {
buf.setLength(buf.length() - 2);
}
buf.append(")");
return access + ((access.length() > 0) ? " " : "") + // May be an empty string
type + " " + name + buf.toString();
}
// Guess what this does
private static final int pow2( int n ) {
return 1 << n;
}
/**
* Replace all occurences of <em>old</em> in <em>str</em> with <em>new</em>.
*
* @param str String to permute
* @param old String to be replaced
* @param new_ Replacement string
* @return new String object
*/
public static final String replace( String str, String old, String new_ ) {
int index, old_index;
StringBuffer buf = new StringBuffer();
try {
if ((index = str.indexOf(old)) != -1) { // `old' found in str
old_index = 0; // String start offset
// While we have something to replace
while ((index = str.indexOf(old, old_index)) != -1) {
buf.append(str.substring(old_index, index)); // append prefix
buf.append(new_); // append replacement
old_index = index + old.length(); // Skip `old'.length chars
}
buf.append(str.substring(old_index)); // append rest of string
str = buf.toString();
}
} catch (StringIndexOutOfBoundsException e) { // Should not occur
System.err.println(e);
}
return str;
}
/**
* Converts signature to string with all class names compacted.
*
* @param signature to convert
* @return Human readable signature
*/
public static final String signatureToString( String signature ) {
return signatureToString(signature, true);
}
/**
* The field signature represents the value of an argument to a function or
* the value of a variable. It is a series of bytes generated by the
* following grammar:
*
* <PRE>
* <field_signature> ::= <field_type>
* <field_type> ::= <base_type>|<object_type>|<array_type>
* <base_type> ::= B|C|D|F|I|J|S|Z
* <object_type> ::= L<fullclassname>;
* <array_type> ::= [<field_type>
*
* The meaning of the base types is as follows:
* B byte signed byte
* C char character
* D double double precision IEEE float
* F float single precision IEEE float
* I int integer
* J long long integer
* L<fullclassname>; ... an object of the given class
* S short signed short
* Z boolean true or false
* [<field sig> ... array
* </PRE>
*
* This method converts this string into a Java type declaration such as
* `String[]' and throws a `ClassFormatException' when the parsed type is
* invalid.
*
* @param signature Class signature
* @param chopit Flag that determines whether chopping is executed or not
* @return Java type declaration
* @throws ClassFormatException
*/
public static final String signatureToString( String signature, boolean chopit ) {
//corrected concurrent private static field acess
wrap(consumed_chars, 1); // This is the default, read just one char like `B'
try {
switch (signature.charAt(0)) {
case 'B':
return "byte";
case 'C':
return "char";
case 'D':
return "double";
case 'F':
return "float";
case 'I':
return "int";
case 'J':
return "long";
case 'L': { // Full class name
int index = signature.indexOf(';'); // Look for closing `;'
if (index < 0) {
throw new ClassFormatException("Invalid signature: " + signature);
}
//corrected concurrent private static field acess
wrap(consumed_chars, index + 1); // "Lblabla;" `L' and `;' are removed
return compactClassName(signature.substring(1, index), chopit);
}
case 'S':
return "short";
case 'Z':
return "boolean";
case '[': { // Array declaration
int n;
StringBuffer brackets;
String type;
int consumed_chars; // Shadows global var
brackets = new StringBuffer(); // Accumulate []'s
// Count opening brackets and look for optional size argument
for (n = 0; signature.charAt(n) == '['; n++) {
brackets.append("[]");
}
consumed_chars = n; // Remember value
// The rest of the string denotes a `<field_type>'
type = signatureToString(signature.substring(n), chopit);
//corrected concurrent private static field acess
//Utility.consumed_chars += consumed_chars; is replaced by:
int _temp = unwrap(Utility.consumed_chars) + consumed_chars;
wrap(Utility.consumed_chars, _temp);
return type + brackets.toString();
}
case 'V':
return "void";
default:
throw new ClassFormatException("Invalid signature: `" + signature + "'");
}
} catch (StringIndexOutOfBoundsException e) { // Should never occur
throw new ClassFormatException("Invalid signature: " + e + ":" + signature);
}
}
/** Parse Java type such as "char", or "java.lang.String[]" and return the
* signature in byte code format, e.g. "C" or "[Ljava/lang/String;" respectively.
*
* @param type Java type
* @return byte code signature
*/
public static String getSignature( String type ) {
StringBuffer buf = new StringBuffer();
char[] chars = type.toCharArray();
boolean char_found = false, delim = false;
int index = -1;
loop: for (int i = 0; i < chars.length; i++) {
switch (chars[i]) {
case ' ':
case '\t':
case '\n':
case '\r':
case '\f':
if (char_found) {
delim = true;
}
break;
case '[':
if (!char_found) {
throw new RuntimeException("Illegal type: " + type);
}
index = i;
break loop;
default:
char_found = true;
if (!delim) {
buf.append(chars[i]);
}
}
}
int brackets = 0;
if (index > 0) {
brackets = countBrackets(type.substring(index));
}
type = buf.toString();
buf.setLength(0);
for (int i = 0; i < brackets; i++) {
buf.append('[');
}
boolean found = false;
for (int i = Constants.T_BOOLEAN; (i <= Constants.T_VOID) && !found; i++) {
if (Constants.TYPE_NAMES[i].equals(type)) {
found = true;
buf.append(Constants.SHORT_TYPE_NAMES[i]);
}
}
if (!found) {
buf.append('L').append(type.replace('.', '/')).append(';');
}
return buf.toString();
}
private static int countBrackets( String brackets ) {
char[] chars = brackets.toCharArray();
int count = 0;
boolean open = false;
for (int i = 0; i < chars.length; i++) {
switch (chars[i]) {
case '[':
if (open) {
throw new RuntimeException("Illegally nested brackets:" + brackets);
}
open = true;
break;
case ']':
if (!open) {
throw new RuntimeException("Illegally nested brackets:" + brackets);
}
open = false;
count++;
break;
default:
// Don't care
}
}
if (open) {
throw new RuntimeException("Illegally nested brackets:" + brackets);
}
return count;
}
/**
* Return type of method signature as a byte value as defined in <em>Constants</em>
*
* @param signature in format described above
* @return type of method signature
* @see Constants
*/
public static final byte typeOfMethodSignature( String signature ) throws ClassFormatException {
int index;
try {
if (signature.charAt(0) != '(') {
throw new ClassFormatException("Invalid method signature: " + signature);
}
index = signature.lastIndexOf(')') + 1;
return typeOfSignature(signature.substring(index));
} catch (StringIndexOutOfBoundsException e) {
throw new ClassFormatException("Invalid method signature: " + signature);
}
}
/**
* Return type of signature as a byte value as defined in <em>Constants</em>
*
* @param signature in format described above
* @return type of signature
* @see Constants
*/
public static final byte typeOfSignature( String signature ) throws ClassFormatException {
try {
switch (signature.charAt(0)) {
case 'B':
return Constants.T_BYTE;
case 'C':
return Constants.T_CHAR;
case 'D':
return Constants.T_DOUBLE;
case 'F':
return Constants.T_FLOAT;
case 'I':
return Constants.T_INT;
case 'J':
return Constants.T_LONG;
case 'L':
return Constants.T_REFERENCE;
case '[':
return Constants.T_ARRAY;
case 'V':
return Constants.T_VOID;
case 'Z':
return Constants.T_BOOLEAN;
case 'S':
return Constants.T_SHORT;
default:
throw new ClassFormatException("Invalid method signature: " + signature);
}
} catch (StringIndexOutOfBoundsException e) {
throw new ClassFormatException("Invalid method signature: " + signature);
}
}
/** Map opcode names to opcode numbers. E.g., return Constants.ALOAD for "aload"
*/
public static short searchOpcode( String name ) {
name = name.toLowerCase(Locale.ENGLISH);
for (short i = 0; i < Constants.OPCODE_NAMES.length; i++) {
if (Constants.OPCODE_NAMES[i].equals(name)) {
return i;
}
}
return -1;
}
/**
* Convert (signed) byte to (unsigned) short value, i.e., all negative
* values become positive.
*/
private static final short byteToShort( byte b ) {
return (b < 0) ? (short) (256 + b) : (short) b;
}
/** Convert bytes into hexidecimal string
*
* @return bytes as hexidecimal string, e.g. 00 FA 12 ...
*/
public static final String toHexString( byte[] bytes ) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
short b = byteToShort(bytes[i]);
String hex = Integer.toString(b, 0x10);
if (b < 0x10) {
buf.append('0');
}
buf.append(hex);
if (i < bytes.length - 1) {
buf.append(' ');
}
}
return buf.toString();
}
/**
* Return a string for an integer justified left or right and filled up with
* `fill' characters if necessary.
*
* @param i integer to format
* @param length length of desired string
* @param left_justify format left or right
* @param fill fill character
* @return formatted int
*/
public static final String format( int i, int length, boolean left_justify, char fill ) {
return fillup(Integer.toString(i), length, left_justify, fill);
}
/**
* Fillup char with up to length characters with char `fill' and justify it left or right.
*
* @param str string to format
* @param length length of desired string
* @param left_justify format left or right
* @param fill fill character
* @return formatted string
*/
public static final String fillup( String str, int length, boolean left_justify, char fill ) {
int len = length - str.length();
char[] buf = new char[(len < 0) ? 0 : len];
for (int j = 0; j < buf.length; j++) {
buf[j] = fill;
}
if (left_justify) {
return str + new String(buf);
}
return new String(buf) + str;
}
static final boolean equals( byte[] a, byte[] b ) {
int size;
if ((size = a.length) != b.length) {
return false;
}
for (int i = 0; i < size; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
public static final void printArray( PrintStream out, Object[] obj ) {
out.println(printArray(obj, true));
}
public static final void printArray( PrintWriter out, Object[] obj ) {
out.println(printArray(obj, true));
}
public static final String printArray( Object[] obj ) {
return printArray(obj, true);
}
public static final String printArray( Object[] obj, boolean braces ) {
return printArray(obj, braces, false);
}
public static final String printArray( Object[] obj, boolean braces, boolean quote ) {
if (obj == null) {
return null;
}
StringBuffer buf = new StringBuffer();
if (braces) {
buf.append('{');
}
for (int i = 0; i < obj.length; i++) {
if (obj[i] != null) {
buf.append((quote ? "\"" : "")).append(obj[i].toString()).append(
(quote ? "\"" : ""));
} else {
buf.append("null");
}
if (i < obj.length - 1) {
buf.append(", ");
}
}
if (braces) {
buf.append('}');
}
return buf.toString();
}
/** @return true, if character is one of (a, ... z, A, ... Z, 0, ... 9, _)
*/
public static boolean isJavaIdentifierPart( char ch ) {
return ((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z'))
|| ((ch >= '0') && (ch <= '9')) || (ch == '_');
}
/** Encode byte array it into Java identifier string, i.e., a string
* that only contains the following characters: (a, ... z, A, ... Z,
* 0, ... 9, _, $). The encoding algorithm itself is not too
* clever: if the current byte's ASCII value already is a valid Java
* identifier part, leave it as it is. Otherwise it writes the
* escape character($) followed by <p><ul><li> the ASCII value as a
* hexadecimal string, if the value is not in the range
* 200..247</li> <li>a Java identifier char not used in a lowercase
* hexadecimal string, if the value is in the range
* 200..247</li><ul></p>
*
* <p>This operation inflates the original byte array by roughly 40-50%</p>
*
* @param bytes the byte array to convert
* @param compress use gzip to minimize string
*/
public static String encode( byte[] bytes, boolean compress ) throws IOException {
if (compress) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gos = new GZIPOutputStream(baos);
gos.write(bytes, 0, bytes.length);
gos.close();
baos.close();
bytes = baos.toByteArray();
}
CharArrayWriter caw = new CharArrayWriter();
JavaWriter jw = new JavaWriter(caw);
for (int i = 0; i < bytes.length; i++) {
int in = bytes[i] & 0x000000ff; // Normalize to unsigned
jw.write(in);
}
return caw.toString();
}
/** Decode a string back to a byte array.
*
* @param s the string to convert
* @param uncompress use gzip to uncompress the stream of bytes
*/
public static byte[] decode( String s, boolean uncompress ) throws IOException {
char[] chars = s.toCharArray();
CharArrayReader car = new CharArrayReader(chars);
JavaReader jr = new JavaReader(car);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int ch;
while ((ch = jr.read()) >= 0) {
bos.write(ch);
}
bos.close();
car.close();
jr.close();
byte[] bytes = bos.toByteArray();
if (uncompress) {
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
byte[] tmp = new byte[bytes.length * 3]; // Rough estimate
int count = 0;
int b;
while ((b = gis.read()) >= 0) {
tmp[count++] = (byte) b;
}
bytes = new byte[count];
System.arraycopy(tmp, 0, bytes, 0, count);
}
return bytes;
}
// A-Z, g-z, _, $
private static final int FREE_CHARS = 48;
static int[] CHAR_MAP = new int[FREE_CHARS];
static int[] MAP_CHAR = new int[256]; // Reverse map
private static final char ESCAPE_CHAR = '$';
static {
int j = 0;
for (int i = 'A'; i <= 'Z'; i++) {
CHAR_MAP[j] = i;
MAP_CHAR[i] = j;
j++;
}
for (int i = 'g'; i <= 'z'; i++) {
CHAR_MAP[j] = i;
MAP_CHAR[i] = j;
j++;
}
CHAR_MAP[j] = '$';
MAP_CHAR['$'] = j;
j++;
CHAR_MAP[j] = '_';
MAP_CHAR['_'] = j;
}
/** Decode characters into bytes.
* Used by <a href="Utility.html#decode(java.lang.String, boolean)">decode()</a>
*/
private static class JavaReader extends FilterReader {
public JavaReader(Reader in) {
super(in);
}
public int read() throws IOException {
int b = in.read();
if (b != ESCAPE_CHAR) {
return b;
}
int i = in.read();
if (i < 0) {
return -1;
}
if (((i >= '0') && (i <= '9')) || ((i >= 'a') && (i <= 'f'))) { // Normal escape
int j = in.read();
if (j < 0) {
return -1;
}
char[] tmp = {
(char) i, (char) j
};
int s = Integer.parseInt(new String(tmp), 16);
return s;
}
return MAP_CHAR[i];
}
public int read( char[] cbuf, int off, int len ) throws IOException {
for (int i = 0; i < len; i++) {
cbuf[off + i] = (char) read();
}
return len;
}
}
/** Encode bytes into valid java identifier characters.
* Used by <a href="Utility.html#encode(byte[], boolean)">encode()</a>
*/
private static class JavaWriter extends FilterWriter {
public JavaWriter(Writer out) {
super(out);
}
public void write( int b ) throws IOException {
if (isJavaIdentifierPart((char) b) && (b != ESCAPE_CHAR)) {
out.write(b);
} else {
out.write(ESCAPE_CHAR); // Escape character
// Special escape
if (b >= 0 && b < FREE_CHARS) {
out.write(CHAR_MAP[b]);
} else { // Normal escape
char[] tmp = Integer.toHexString(b).toCharArray();
if (tmp.length == 1) {
out.write('0');
out.write(tmp[0]);
} else {
out.write(tmp[0]);
out.write(tmp[1]);
}
}
}
}
public void write( char[] cbuf, int off, int len ) throws IOException {
for (int i = 0; i < len; i++) {
write(cbuf[off + i]);
}
}
public void write( String str, int off, int len ) throws IOException {
write(str.toCharArray(), off, len);
}
}
/**
* Escape all occurences of newline chars '\n', quotes \", etc.
*/
public static final String convertString( String label ) {
char[] ch = label.toCharArray();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < ch.length; i++) {
switch (ch[i]) {
case '\n':
buf.append("\\n");
break;
case '\r':
buf.append("\\r");
break;
case '\"':
buf.append("\\\"");
break;
case '\'':
buf.append("\\'");
break;
case '\\':
buf.append("\\\\");
break;
default:
buf.append(ch[i]);
break;
}
}
return buf.toString();
}
}
| mit |
chipster/chipster | src/main/java/fi/csc/microarray/client/visualisation/methods/gbrowser/gui/GenomeInfo.java | 955 | package fi.csc.microarray.client.visualisation.methods.gbrowser.gui;
import java.net.URL;
public class GenomeInfo {
private String species;
private String version;
private URL ensemblBrowserUrl;
private URL ucscBrowserUrl;
private String sortId;
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public URL getEnsembl() {
return ensemblBrowserUrl;
}
public void setEnsemblBrowserUrl(URL ensemblBrowserUrl) {
this.ensemblBrowserUrl = ensemblBrowserUrl;
}
public URL getBrowserUrl() {
return ucscBrowserUrl;
}
public void setUcscBrowserUrl(URL ucscBrowserUrl) {
this.ucscBrowserUrl = ucscBrowserUrl;
}
public String getSortId() {
return sortId;
}
public void setSortId(String sortId) {
this.sortId = sortId;
}
} | mit |
bigbang87/deadly-monsters | forge-1.12/src/main/java/com/dmonsters/ai/EntityAIChaseTroughBlocks.java | 1897 | package com.dmonsters.ai;
import net.minecraft.entity.EntityCreature;
import net.minecraft.entity.ai.EntityAIBase;
import net.minecraft.entity.ai.RandomPositionGenerator;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
public class EntityAIChaseTroughBlocks extends EntityAIBase {
private EntityCreature theEntity;
private double movePosX;
private double movePosY;
private double movePosZ;
private final double movementSpeed;
public EntityAIChaseTroughBlocks(EntityCreature creatureIn, double speedIn) {
this.theEntity = creatureIn;
this.movementSpeed = speedIn;
this.setMutexBits(1);
theEntity = creatureIn;
}
public boolean shouldExecute()
{
if (this.theEntity.isWithinHomeDistanceCurrentPosition())
{
return false;
}
else
{
BlockPos blockpos = this.theEntity.getHomePosition();
Vec3d vec3d = RandomPositionGenerator.findRandomTargetBlockTowards(this.theEntity, 16, 7, new Vec3d((double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ()));
if (vec3d == null)
{
return false;
}
else
{
this.movePosX = vec3d.x;
this.movePosY = vec3d.y;
this.movePosZ = vec3d.z;
return true;
}
}
}
public boolean continueExecuting()
{
boolean result = !this.theEntity.getNavigator().noPath();
System.out.println("Radek: continue result: " + result);
return result;
}
public void startExecuting()
{
System.out.println("Radek: start");
this.theEntity.getNavigator().tryMoveToXYZ(this.movePosX, this.movePosY, this.movePosZ, this.movementSpeed);
}
} | mit |