answer
stringlengths 17
10.2M
|
|---|
package org.rstudio.studio.client.workbench;
import org.rstudio.core.client.command.CommandBinder;
import org.rstudio.core.client.command.Handler;
import org.rstudio.core.client.dom.DocumentEx;
import org.rstudio.core.client.widget.MiniPopupPanel;
import org.rstudio.studio.client.workbench.commands.Commands;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class ShowDOMElementIDs
{
interface Binder extends CommandBinder<Commands, ShowDOMElementIDs>
{
}
@Inject
public ShowDOMElementIDs(Binder binder,
Commands commands)
{
binder.bind(commands, this);
panel_ = new MiniPopupPanel();
html_ = new HTML();
panel_.add(html_);
panel_.addAttachHandler(new AttachEvent.Handler()
{
@Override
public void onAttachOrDetach(AttachEvent event)
{
if (event.isAttached())
{
startMonitoring();
}
else
{
stopMonitoring();
}
}
});
}
@Handler
public void onShowDomElementIds()
{
if (panel_.isShowing())
{
panel_.hide();
}
else
{
panel_.show();
}
}
private void startMonitoring()
{
stopMonitoring();
handler_ = Event.addNativePreviewHandler((NativePreviewEvent preview) ->
{
if (preview.getTypeInt() != Event.ONMOUSEMOVE)
return;
NativeEvent event = preview.getNativeEvent();
int x = event.getClientX();
int y = event.getClientY();
Element[] els = DocumentEx.get().elementsFromPoint(x, y);
SafeHtmlBuilder builder = new SafeHtmlBuilder();
builder.appendHtmlConstant("<div>");
for (Element el : els)
{
String id = el.getId();
String[] classNames = el.getClassName().split(" ");
boolean interesting = false;
if (id.startsWith("rstudio_"))
interesting = true;
for (String className : classNames)
{
if (className.startsWith("rstudio_"))
{
interesting = true;
break;
}
}
if (!interesting)
continue;
builder.appendHtmlConstant("<span style='color: rgb(217, 95, 2)'>");
builder.appendEscaped(el.getTagName().toLowerCase());
builder.appendHtmlConstant("</span>");
for (String className : classNames)
{
if (className.startsWith("rstudio_"))
{
builder.appendHtmlConstant("<span style='color: rgb(117, 112, 179)'>");
builder.appendEscaped(".");
builder.appendEscaped(className);
builder.appendHtmlConstant("</span>");
}
}
if (!id.isEmpty())
{
builder.appendHtmlConstant("<span style='color: rgb(28, 158, 119)'>");
builder.appendEscaped("
builder.appendEscaped(id);
builder.appendHtmlConstant("</span>");
}
builder.appendHtmlConstant("<br>");
}
builder.appendHtmlConstant("</div>");
html_.setHTML(builder.toSafeHtml());
});
}
private void stopMonitoring()
{
if (handler_ != null)
{
handler_.removeHandler();
handler_ = null;
}
}
private HandlerRegistration handler_;
private final MiniPopupPanel panel_;
private final HTML html_;
}
|
package io.core9.plugin.thumbnails;
import io.core9.plugin.filesmanager.FileRepository;
import io.core9.plugin.server.VirtualHost;
import io.core9.plugin.server.request.Request;
import java.util.HashMap;
import java.util.Map;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import net.xeoh.plugins.base.annotations.injections.InjectPlugin;
@PluginImplementation
public class ThumbnailAdminPluginImpl implements ThumbnailAdminPlugin {
@InjectPlugin
private ThumbnailPlugin thumbnails;
@InjectPlugin
private FileRepository files;
@Override
public String getControllerName() {
return "images";
}
@Override
public void handle(Request request) {
String type = (String) request.getParams().get("type");
String name = (String) request.getParams().get("id");
switch(type) {
case "refresh":
createProfiles(request.getVirtualHost());
request.getResponse().end();
break;
case "flush":
if(name != null) {
VirtualHost vhost = request.getVirtualHost();
ImageProfile profile = getProfile(vhost, name);
flushProfile(vhost, profile);
} else {
flushProfiles(request.getVirtualHost());
}
request.getResponse().end();
break;
default:
break;
}
}
private ImageProfile getProfile(VirtualHost vhost, String name) {
return thumbnails.getVirtualHostRegistry(vhost).get(name);
}
/**
* Create the profiles for a virtual host
* @param vhost
*/
private void createProfiles(VirtualHost vhost) {
thumbnails.createProfiles(vhost);
}
/**
* Flush all image profiles for a vhost
* @param vhost
*/
private void flushProfiles(VirtualHost vhost) {
for(ImageProfile profile : thumbnails.getVirtualHostRegistry(vhost).values()) {
flushProfile(vhost, profile);
}
}
/**
* Flush an image profile (by name)
* @param vhost
* @param name
*/
private void flushProfile(VirtualHost vhost, ImageProfile profile) {
Map<String,Object> query = new HashMap<String, Object>();
query.put("metadata.profile", profile.getName());
files.removeFiles(profile.retrieveDatabase(vhost), profile.retrieveBucket(), query);
}
}
|
package se.lu.esss.ics.jels.smf.impl;
import java.net.URI;
import java.net.URISyntaxException;
import se.lu.esss.ics.jels.smf.attr.ESSFieldMapBucket;
import xal.ca.Channel;
import xal.ca.ChannelFactory;
import xal.smf.attr.AttributeBucket;
import xal.smf.impl.RfCavity;
import xal.smf.impl.RfGap;
import xal.smf.impl.qualify.ElementTypeManager;
import xal.smf.impl.qualify.QualifierFactory;
import xal.tools.data.DataAdaptor;
import xal.tools.xml.XmlDataAdaptor;
/**
* ESS implementation of Field Maps.
*
* @author Ivo List <[email protected]>
*
*/
public class ESSFieldMap extends RfGap {
public static final String s_strType = "FM";
/*
* Local Attributes
*/
protected ESSFieldMapBucket m_bucFieldMap; // FieldMap parameters
protected FieldProfile fieldProfile; // field profile
static {
registerType();
}
public ESSFieldMap(String strId) {
this(strId, null);
}
public ESSFieldMap(String strId, ChannelFactory channelFactory) {
super(strId, channelFactory);
setFieldMapBucket(new ESSFieldMapBucket());
}
@Override
public String getType() {
return s_strType;
}
/*
* Register type for qualification
*/
private static void registerType() {
ElementTypeManager typeManager = ElementTypeManager.defaultManager();
typeManager.registerType(ESSFieldMap.class, s_strType);
typeManager.registerType(ESSFieldMap.class, "fieldmap");
}
/*
* Attributes
*/
public ESSFieldMapBucket getFieldMapBucket() {
return m_bucFieldMap;
}
public void setFieldMapBucket(ESSFieldMapBucket buc) {
m_bucFieldMap = buc;
super.addBucket(buc);
}
/** Override AcceleratorNode implementation to check for a ESSFieldMapBucket */
public void addBucket(AttributeBucket buc) {
if (buc.getClass().equals( ESSFieldMapBucket.class ))
setFieldMapBucket((ESSFieldMapBucket)buc);
super.addBucket(buc);
}
/** Electric field intensity factor */
public double getXelmax() { return m_bucFieldMap.getXelmax(); }
/** Default (design) cavity RF phase (deg) */
public double getPhase() { return m_bucFieldMap.getPhase(); }
/** Design cavity resonant frequency (MHz) */
public double getFrequency() { return m_bucFieldMap.getFrequency(); }
/** FieldMap file */
public String getFieldMapFile() { return m_bucFieldMap.getFieldMapFile(); }
/** Position + gapOffset where cavity RF phase is given (m) relative to element's start */
public double getPhasePosition() { return m_bucFieldMap.getPhasePosition() + m_bucFieldMap.getGapOffset(); }
/** Electric field intensity factor */
public void setXelmax(double dblVal) { m_bucFieldMap.setXelmax(dblVal); }
/** Default (design) cavity RF phase (deg) */
public void setPhase(double dblVal) { m_bucFieldMap.setPhase(dblVal); }
/** Design cavity resonant frequency (MHz) */
public void setFrequency(double dblVal) { m_bucFieldMap.setFrequency(dblVal); }
/** FieldMap file */
public void setFieldMapFile(String strVal) { m_bucFieldMap.setFieldMapFile(strVal); }
/** Field profile */
public FieldProfile getFieldProfile() { return fieldProfile; }
/** Field profile */
public void setFieldProfile(FieldProfile fieldProfile) { this.fieldProfile = fieldProfile; }
/**
* Loads the field profile if necessary
*/
@Override
public void update(DataAdaptor adaptor) throws NumberFormatException {
super.update(adaptor);
try {
fieldProfile = FieldProfile.getInstance(new URI(((XmlDataAdaptor)adaptor).document().getDocumentURI()).resolve(getFieldMapFile()+".edz").toString());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
@Override
public double getDesignPropertyValue(String propertyName) {
final Property property = Property.valueOf( propertyName );
try {
if (getParent() instanceof RfCavity) {
RfCavity cavity = (RfCavity)getParent();
switch( property ) {
case ETL:
return cavity.getDfltCavAmp() * getXelmax() / (fieldProfile.getE0L(cavity.getCavFreq())/fieldProfile.getLength());
case PHASE:
return cavity.getDfltCavPhase();
case FREQUENCY:
return cavity.getCavFreq();
case FIELD:
return getXelmax();
default:
throw new IllegalArgumentException( "Unsupported FieldMap design value property: " + propertyName );
}
}
switch( property ) {
case ETL:
return getXelmax()*1e-6;
case PHASE:
return getPhase();
case FREQUENCY:
return getFrequency();
case FIELD:
return getXelmax()*1e-6;
default:
throw new IllegalArgumentException( "Unsupported FieldMap design value property: " + propertyName );
}
}
catch( IllegalArgumentException exception ) {
return super.getDesignPropertyValue( propertyName );
}
}
}
|
package Control;
import Model.Jeu;
import View.Fenetre;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ControlButton extends Control implements ActionListener {
/**
* Constructeur de ControlButton
*/
public ControlButton(Jeu jeu, Fenetre fenetre) {
super(jeu, fenetre);
fenetre.setControlButton(this);
}
/**
* Traitement des boutons
*
* @param e
*/
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
for(int i = 0; i < this.jeu.getGrille().getHauteur(); i++) {
for(int j = 0; j < this.jeu.getGrille().getLargeur(); j++) {
if(this.fenetre.getGrille()[i][j] == source) {
System.out.println("Clic sur case");
jeu.devoileCase(i, j);
}
}
}
for(int i = 0; i < this.jeu.getGrille().getHauteur(); i++) {
for(int j = 0; j < this.jeu.getGrille().getLargeur(); j++) {
if (! this.jeu.getGrille().getGrille()[i][j].isMine()) {
fenetre.editColor(i,j);
fenetre.updateFen();
System.out.print("
}
}
}
}
}
|
package org.pentaho.di.ui.spoon.trans;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.log4j.spi.LoggingEvent;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.window.DefaultToolTip;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.MouseWheelListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Widget;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.EngineMetaInterface;
import org.pentaho.di.core.NotePadMeta;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.dnd.DragAndDropContainer;
import org.pentaho.di.core.dnd.XMLTransfer;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleValueException;
import org.pentaho.di.core.gui.AreaOwner;
import org.pentaho.di.core.gui.BasePainter;
import org.pentaho.di.core.gui.GCInterface;
import org.pentaho.di.core.gui.Point;
import org.pentaho.di.core.gui.Redrawable;
import org.pentaho.di.core.gui.SnapAllignDistribute;
import org.pentaho.di.core.logging.CentralLogStore;
import org.pentaho.di.core.logging.DefaultLogLevel;
import org.pentaho.di.core.logging.HasLogChannelInterface;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.core.logging.LogMessage;
import org.pentaho.di.core.logging.LogParentProvidedInterface;
import org.pentaho.di.core.logging.LoggingObjectInterface;
import org.pentaho.di.core.logging.LoggingRegistry;
import org.pentaho.di.core.plugins.PluginInterface;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.plugins.StepPluginType;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.lineage.TransDataLineage;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.RepositoryObjectType;
import org.pentaho.di.shared.SharedObjects;
import org.pentaho.di.trans.DatabaseImpact;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransExecutionConfiguration;
import org.pentaho.di.trans.TransHopMeta;
import org.pentaho.di.trans.TransListener;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.TransPainter;
import org.pentaho.di.trans.debug.BreakPointListener;
import org.pentaho.di.trans.debug.StepDebugMeta;
import org.pentaho.di.trans.debug.TransDebugMeta;
import org.pentaho.di.trans.step.RemoteStep;
import org.pentaho.di.trans.step.RowListener;
import org.pentaho.di.trans.step.StepErrorMeta;
import org.pentaho.di.trans.step.StepIOMetaInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.step.StepMetaDataCombi;
import org.pentaho.di.trans.step.errorhandling.Stream;
import org.pentaho.di.trans.step.errorhandling.StreamIcon;
import org.pentaho.di.trans.step.errorhandling.StreamInterface;
import org.pentaho.di.trans.step.errorhandling.StreamInterface.StreamType;
import org.pentaho.di.trans.steps.mapping.MappingMeta;
import org.pentaho.di.trans.steps.tableinput.TableInputMeta;
import org.pentaho.di.ui.core.ConstUI;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.dialog.DialogClosedListener;
import org.pentaho.di.ui.core.dialog.EnterNumberDialog;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.dialog.PreviewRowsDialog;
import org.pentaho.di.ui.core.dialog.StepFieldsDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.widget.CheckBoxToolTip;
import org.pentaho.di.ui.core.widget.CheckBoxToolTipListener;
import org.pentaho.di.ui.repository.dialog.RepositoryExplorerDialog;
import org.pentaho.di.ui.repository.dialog.RepositoryRevisionBrowserDialogInterface;
import org.pentaho.di.ui.spoon.AbstractGraph;
import org.pentaho.di.ui.spoon.SWTGC;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.spoon.SpoonPluginManager;
import org.pentaho.di.ui.spoon.SwtScrollBar;
import org.pentaho.di.ui.spoon.TabItemInterface;
import org.pentaho.di.ui.spoon.XulSpoonResourceBundle;
import org.pentaho.di.ui.spoon.XulSpoonSettingsManager;
import org.pentaho.di.ui.spoon.dialog.DeleteMessageBox;
import org.pentaho.di.ui.spoon.dialog.EnterPreviewRowsDialog;
import org.pentaho.di.ui.spoon.dialog.NotePadDialog;
import org.pentaho.di.ui.spoon.dialog.SearchFieldsProgressDialog;
import org.pentaho.di.ui.trans.dialog.TransDialog;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.XulLoader;
import org.pentaho.ui.xul.components.XulMenuitem;
import org.pentaho.ui.xul.components.XulToolbarbutton;
import org.pentaho.ui.xul.containers.XulMenu;
import org.pentaho.ui.xul.containers.XulMenupopup;
import org.pentaho.ui.xul.containers.XulToolbar;
import org.pentaho.ui.xul.dom.Document;
import org.pentaho.ui.xul.impl.XulEventHandler;
import org.pentaho.ui.xul.swt.SwtXulLoader;
/**
* This class handles the display of the transformations in a graphical way using icons, arrows, etc.
* One transformation is handled per TransGraph
*
* @author Matt
* @since 17-mei-2003
*
*/
public class TransGraph extends AbstractGraph implements XulEventHandler, Redrawable, TabItemInterface, LogParentProvidedInterface, MouseListener, MouseMoveListener, MouseTrackListener, MouseWheelListener, KeyListener {
private static Class<?> PKG = Spoon.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private LogChannelInterface log;
private static final int HOP_SEL_MARGIN = 9;
private static final String XUL_FILE_TRANS_TOOLBAR = "ui/trans-toolbar.xul"; //$NON-NLS-1$
public final static String START_TEXT = BaseMessages.getString(PKG, "TransLog.Button.StartTransformation"); //$NON-NLS-1$
public final static String PAUSE_TEXT = BaseMessages.getString(PKG, "TransLog.Button.PauseTransformation"); //$NON-NLS-1$
public final static String RESUME_TEXT = BaseMessages.getString(PKG, "TransLog.Button.ResumeTransformation"); //$NON-NLS-1$
public final static String STOP_TEXT = BaseMessages.getString(PKG, "TransLog.Button.StopTransformation"); //$NON-NLS-1$
private TransMeta transMeta;
public Trans trans;
private Shell shell;
private Composite mainComposite;
private DefaultToolTip toolTip;
private CheckBoxToolTip helpTip;
private XulToolbar toolbar;
private int iconsize;
private Point lastclick;
private Point lastMove;
private Point previous_step_locations[];
private Point previous_note_locations[];
private List<StepMeta> selectedSteps;
private StepMeta selectedStep;
private List<StepMeta> mouseOverSteps;
private List<NotePadMeta> selectedNotes;
private NotePadMeta selectedNote;
private TransHopMeta candidate;
private Point drop_candidate;
private Spoon spoon;
// public boolean shift, control;
private boolean split_hop;
private int lastButton;
private TransHopMeta last_hop_split;
private org.pentaho.di.core.gui.Rectangle selectionRegion;
/**
* A list of remarks on the current Transformation...
*/
private List<CheckResultInterface> remarks;
/**
* A list of impacts of the current transformation on the used databases.
*/
private List<DatabaseImpact> impact;
/**
* Indicates whether or not an impact analysis has already run.
*/
private boolean impactFinished;
private TransHistoryRefresher spoonHistoryRefresher;
private TransDebugMeta lastTransDebugMeta;
private Map<String, XulMenupopup> menuMap = new HashMap<String, XulMenupopup>();
protected int currentMouseX = 0;
protected int currentMouseY = 0;
protected NotePadMeta ni = null;
protected TransHopMeta currentHop;
protected StepMeta currentStep;
private List<AreaOwner> areaOwners;
// private Text filenameLabel;
private SashForm sashForm;
public Composite extraViewComposite;
public CTabFolder extraViewTabFolder;
private boolean initialized;
private boolean running;
private boolean halted;
private boolean halting;
private boolean debug;
private boolean pausing;
public TransLogDelegate transLogDelegate;
public TransGridDelegate transGridDelegate;
public TransHistoryDelegate transHistoryDelegate;
public TransPerfDelegate transPerfDelegate;
/** A map that keeps track of which log line was written by which step */
private Map<StepMeta, String> stepLogMap;
private StepMeta startHopStep;
private Point endHopLocation;
private boolean startErrorHopStep;
private StepMeta noInputStep;
private StepMeta endHopStep;
private StreamType candidateHopType;
private Map<StepMeta, DelayTimer> delayTimers;
private StepMeta showTargetStreamsStep;
private XulDomContainer xulDomContainer;
public void setCurrentNote(NotePadMeta ni) {
this.ni = ni;
}
public NotePadMeta getCurrentNote() {
return ni;
}
public TransHopMeta getCurrentHop() {
return currentHop;
}
public void setCurrentHop(TransHopMeta currentHop) {
this.currentHop = currentHop;
}
public StepMeta getCurrentStep() {
return currentStep;
}
public void setCurrentStep(StepMeta currentStep) {
this.currentStep = currentStep;
}
public TransGraph(Composite parent, final Spoon spoon, final TransMeta transMeta) {
super(parent, SWT.NONE);
this.shell = parent.getShell();
this.spoon = spoon;
this.transMeta = transMeta;
this.areaOwners = new ArrayList<AreaOwner>();
this.log = spoon.getLog();
this.mouseOverSteps = new ArrayList<StepMeta>();
this.delayTimers = new HashMap<StepMeta, DelayTimer>();
transLogDelegate = new TransLogDelegate(spoon, this);
transGridDelegate = new TransGridDelegate(spoon, this);
transHistoryDelegate = new TransHistoryDelegate(spoon, this);
transPerfDelegate = new TransPerfDelegate(spoon, this);
try {
XulLoader loader = new SwtXulLoader();
loader.setSettingsManager(XulSpoonSettingsManager.getInstance());
ResourceBundle bundle = new XulSpoonResourceBundle(Spoon.class);
XulDomContainer container = loader.loadXul(XUL_FILE_TRANS_TOOLBAR, bundle);
container.addEventHandler(this);
SpoonPluginManager.getInstance().applyPluginsForContainer("trans-graph", xulDomContainer);
setXulDomContainer(container);
} catch (XulException e1) {
log.logError("Error loading XUL resource bundle for Spoon", e1);
}
setLayout(new FormLayout());
setLayoutData(new GridData(GridData.FILL_BOTH));
// Add a tool-bar at the top of the tab
// The form-data is set on the native widget automatically
addToolBar();
setControlStates(); // enable / disable the icons in the toolbar too.
// The main composite contains the graph view, but if needed also
// a view with an extra tab containing log, etc.
mainComposite = new Composite(this, SWT.NONE);
mainComposite.setLayout(new FillLayout());
Control toolbarControl = (Control) toolbar.getManagedObject();
FormData toolbarFd = new FormData();
toolbarFd.left = new FormAttachment(0, 0);
toolbarFd.right = new FormAttachment(100, 0);
toolbarControl.setLayoutData(toolbarFd);
toolbarControl.setParent(this);
FormData fdMainComposite = new FormData();
fdMainComposite.left = new FormAttachment(0, 0);
fdMainComposite.top = new FormAttachment((Control) toolbar.getManagedObject(), 0);
fdMainComposite.right = new FormAttachment(100, 0);
fdMainComposite.bottom = new FormAttachment(100, 0);
mainComposite.setLayoutData(fdMainComposite);
// To allow for a splitter later on, we will add the splitter here...
sashForm = new SashForm(mainComposite, SWT.VERTICAL);
// Add a canvas below it, use up all space initially
canvas = new Canvas(sashForm, SWT.V_SCROLL | SWT.H_SCROLL | SWT.NO_BACKGROUND | SWT.BORDER);
sashForm.setWeights(new int[] { 100, });
try {
// first get the XML document
menuMap.put("trans-graph-hop", (XulMenupopup) getXulDomContainer().getDocumentRoot().getElementById("trans-graph-hop")); //$NON-NLS-1$ //$NON-NLS-2$
menuMap.put("trans-graph-entry", (XulMenupopup) getXulDomContainer().getDocumentRoot().getElementById("trans-graph-entry")); //$NON-NLS-1$//$NON-NLS-2$
menuMap.put("trans-graph-background", (XulMenupopup) getXulDomContainer().getDocumentRoot().getElementById("trans-graph-background")); //$NON-NLS-1$//$NON-NLS-2$
menuMap.put("trans-graph-note", (XulMenupopup) getXulDomContainer().getDocumentRoot().getElementById("trans-graph-note")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (Throwable t) {
// TODO log this
t.printStackTrace();
}
toolTip = new DefaultToolTip(canvas, ToolTip.NO_RECREATE, true);
toolTip.setRespectMonitorBounds(true);
toolTip.setRespectDisplayBounds(true);
toolTip.setPopupDelay(350);
toolTip.setHideDelay(5000);
toolTip.setShift(new org.eclipse.swt.graphics.Point(ConstUI.TOOLTIP_OFFSET, ConstUI.TOOLTIP_OFFSET));
helpTip = new CheckBoxToolTip(canvas);
helpTip.addCheckBoxToolTipListener(new CheckBoxToolTipListener() {
public void checkBoxSelected(boolean enabled) {
spoon.props.setShowingHelpToolTips(enabled);
}
});
iconsize = spoon.props.getIconSize();
clearSettings();
remarks = new ArrayList<CheckResultInterface>();
impact = new ArrayList<DatabaseImpact>();
impactFinished = false;
hori = canvas.getHorizontalBar();
vert = canvas.getVerticalBar();
hori.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
redraw();
}
});
vert.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
redraw();
}
});
hori.setThumb(100);
vert.setThumb(100);
hori.setVisible(true);
vert.setVisible(true);
setVisible(true);
newProps();
canvas.setBackground(GUIResource.getInstance().getColorBackground());
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
if (!spoon.isStopped())
TransGraph.this.paintControl(e);
}
});
selectedSteps = null;
lastclick = null;
/*
* Handle the mouse...
*/
canvas.addMouseListener(this);
canvas.addMouseMoveListener(this);
canvas.addMouseTrackListener(this);
canvas.addMouseWheelListener(this);
canvas.addKeyListener(this);
// Drag & Drop for steps
Transfer[] ttypes = new Transfer[] { XMLTransfer.getInstance() };
DropTarget ddTarget = new DropTarget(canvas, DND.DROP_MOVE);
ddTarget.setTransfer(ttypes);
ddTarget.addDropListener(new DropTargetListener() {
public void dragEnter(DropTargetEvent event) {
clearSettings();
drop_candidate = PropsUI.calculateGridPosition(getRealPosition(canvas, event.x, event.y));
redraw();
}
public void dragLeave(DropTargetEvent event) {
drop_candidate = null;
redraw();
}
public void dragOperationChanged(DropTargetEvent event) {
}
public void dragOver(DropTargetEvent event) {
drop_candidate = PropsUI.calculateGridPosition(getRealPosition(canvas, event.x, event.y));
redraw();
}
public void drop(DropTargetEvent event) {
// no data to copy, indicate failure in event.detail
if (event.data == null) {
event.detail = DND.DROP_NONE;
return;
}
// System.out.println("Dropping a step!!");
// What's the real drop position?
Point p = getRealPosition(canvas, event.x, event.y);
// We expect a Drag and Drop container... (encased in XML)
try {
DragAndDropContainer container = (DragAndDropContainer) event.data;
StepMeta stepMeta = null;
boolean newstep = false;
switch (container.getType()) {
// Put an existing one on the canvas.
case DragAndDropContainer.TYPE_STEP: {
// Drop hidden step onto canvas....
stepMeta = transMeta.findStep(container.getData());
if (stepMeta != null) {
if (stepMeta.isDrawn() || transMeta.isStepUsedInTransHops(stepMeta)) {
MessageBox mb = new MessageBox(shell, SWT.OK);
mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.StepIsAlreadyOnCanvas.Message")); //$NON-NLS-1$
mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.StepIsAlreadyOnCanvas.Title")); //$NON-NLS-1$
mb.open();
return;
}
// This step gets the drawn attribute and position set below.
} else {
// Unknown step dropped: ignore this to be safe!
return;
}
}
break;
// Create a new step
case DragAndDropContainer.TYPE_BASE_STEP_TYPE: {
// Not an existing step: data refers to the type of step to create
String steptype = container.getData();
stepMeta = spoon.newStep(transMeta, steptype, steptype, false, true);
if (stepMeta != null) {
newstep = true;
} else {
return; // Cancelled pressed in dialog or unable to create step.
}
}
break;
// Create a new TableInput step using the selected connection...
case DragAndDropContainer.TYPE_DATABASE_CONNECTION: {
newstep = true;
String connectionName = container.getData();
TableInputMeta tii = new TableInputMeta();
tii.setDatabaseMeta(transMeta.findDatabase(connectionName));
PluginRegistry registry = PluginRegistry.getInstance();
String stepID = registry.getPluginId(StepPluginType.class, tii);
PluginInterface stepPlugin = registry.findPluginWithId(StepPluginType.class, stepID);
String stepName = transMeta.getAlternativeStepname(stepPlugin.getName());
stepMeta = new StepMeta(stepID, stepName, tii);
if (spoon.editStep(transMeta, stepMeta) != null) {
transMeta.addStep(stepMeta);
spoon.refreshTree();
spoon.refreshGraph();
} else {
return;
}
}
break;
// Drag hop on the canvas: create a new Hop...
case DragAndDropContainer.TYPE_TRANS_HOP: {
newHop();
return;
}
default: {
// Nothing we can use: give an error!
MessageBox mb = new MessageBox(shell, SWT.OK);
mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.ItemCanNotBePlacedOnCanvas.Message")); //$NON-NLS-1$
mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.ItemCanNotBePlacedOnCanvas.Title")); //$NON-NLS-1$
mb.open();
return;
}
}
transMeta.unselectAll();
StepMeta before = null;
if (!newstep) {
before= (StepMeta) stepMeta.clone();
}
stepMeta.drawStep();
stepMeta.setSelected(true);
PropsUI.setLocation(stepMeta, p.x, p.y);
if (newstep) {
spoon.addUndoNew(transMeta, new StepMeta[] { stepMeta }, new int[] { transMeta.indexOfStep(stepMeta) });
} else {
spoon.addUndoChange(transMeta, new StepMeta[] { before }, new StepMeta[] { (StepMeta) stepMeta.clone() }, new int[] { transMeta.indexOfStep(stepMeta) });
}
canvas.forceFocus();
redraw();
// See if we want to draw a tool tip explaining how to create new hops...
if (newstep && transMeta.nrSteps() > 1 && transMeta.nrSteps() < 5 && spoon.props.isShowingHelpToolTips()) {
showHelpTip(p.x, p.y, BaseMessages.getString(PKG, "TransGraph.HelpToolTip.CreatingHops.Title"), //$NON-NLS-1$
BaseMessages.getString(PKG, "TransGraph.HelpToolTip.CreatingHops.Message")); //$NON-NLS-1$
}
} catch (Exception e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "TransGraph.Dialog.ErrorDroppingObject.Message"), //$NON-NLS-1$
BaseMessages.getString(PKG, "TransGraph.Dialog.ErrorDroppingObject.Title"), e); //$NON-NLS-1$
}
}
public void dropAccept(DropTargetEvent event) {
}
});
setBackground(GUIResource.getInstance().getColorBackground());
// Add a timer to set correct the state of the run/stop buttons every 2 seconds...
final Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
public void run() {
setControlStates();
}
};
timer.schedule(timerTask, 2000, 1000);
// Make sure the timer stops when we close the tab...
addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent arg0) {
timer.cancel();
}
});
}
public void mouseDoubleClick(MouseEvent e) {
clearSettings();
Point real = screen2real(e.x, e.y);
// Hide the tooltip!
hideToolTips();
StepMeta stepMeta = transMeta.getStep(real.x, real.y, iconsize);
if (stepMeta != null) {
if (e.button == 1) {
editStep(stepMeta);
}
else {
editDescription(stepMeta);
}
} else {
// Check if point lies on one of the many hop-lines...
TransHopMeta online = findHop(real.x, real.y);
if (online != null) {
editHop(online);
} else {
NotePadMeta ni = transMeta.getNote(real.x, real.y);
if (ni != null) {
selectedNote = null;
editNote(ni);
} else {
// See if the double click was in one of the area's...
for (AreaOwner areaOwner : areaOwners) {
if (areaOwner.contains(real.x, real.y)) {
if (areaOwner.getParent() instanceof StepMeta
&& areaOwner.getOwner().equals(TransPainter.STRING_PARTITIONING_CURRENT_STEP)) {
StepMeta step = (StepMeta) areaOwner.getParent();
spoon.editPartitioning(transMeta, step);
break;
}
}
}
}
}
}
}
public void mouseDown(MouseEvent e) {
boolean alt = (e.stateMask & SWT.ALT) != 0;
boolean control = (e.stateMask & SWT.CONTROL) != 0;
boolean shift = (e.stateMask & SWT.SHIFT) != 0;
lastButton = e.button;
Point real = screen2real(e.x, e.y);
lastclick = new Point(real.x, real.y);
// Hide the tooltip!
hideToolTips();
// Set the pop-up menu
if (e.button == 3) {
setMenu(real.x, real.y);
return;
}
// A single left or middle click on one of the area owners...
if (e.button == 1 || e.button == 2) {
AreaOwner areaOwner = getVisibleAreaOwner(real.x, real.y);
if (areaOwner != null) {
switch (areaOwner.getAreaType()) {
case STEP_OUTPUT_HOP_ICON:
// Click on the output icon means: start of drag
// Action: We show the input icons on the other steps...
{
selectedStep = null;
startHopStep = (StepMeta) areaOwner.getParent();
candidateHopType = null;
startErrorHopStep = false;
// stopStepMouseOverDelayTimer(startHopStep);
}
break;
case STEP_INPUT_HOP_ICON:
// Click on the input icon means: start to a new hop
// In this case, we set the end hop step...
{
selectedStep = null;
startHopStep = null;
endHopStep = (StepMeta) areaOwner.getParent();
candidateHopType = null;
startErrorHopStep = false;
// stopStepMouseOverDelayTimer(endHopStep);
}
break;
case HOP_ERROR_ICON:
// Click on the error icon means: Edit error handling
{
StepMeta stepMeta = (StepMeta) areaOwner.getParent();
spoon.editStepErrorHandling(transMeta, stepMeta);
}
break;
case STEP_TARGET_HOP_ICON_OPTION:
// Below, see showStepTargetOptions()
break;
case STEP_EDIT_ICON:
{
clearSettings();
currentStep = (StepMeta) areaOwner.getParent();
stopStepMouseOverDelayTimer(currentStep);
editStep();
}
break;
case STEP_MENU_ICON:
clearSettings();
StepMeta stepMeta = (StepMeta) areaOwner.getParent();
setMenu(stepMeta.getLocation().x, stepMeta.getLocation().y);
break;
case STEP_ICON :
stepMeta = (StepMeta) areaOwner.getOwner();
currentStep = stepMeta;
if (candidate != null) {
addCandidateAsHop(e.x, e.y);
}
// ALT-Click: edit error handling
if (e.button == 1 && alt && stepMeta.supportsErrorHandling()) {
spoon.editStepErrorHandling(transMeta, stepMeta);
return;
}
// SHIFT CLICK is start of drag to create a new hop
else if (e.button == 2 || (e.button == 1 && shift)) {
startHopStep = stepMeta;
} else {
selectedSteps = transMeta.getSelectedSteps();
selectedStep = stepMeta;
// When an icon is moved that is not selected, it gets
// selected too late.
// It is not captured here, but in the mouseMoveListener...
previous_step_locations = transMeta.getSelectedStepLocations();
Point p = stepMeta.getLocation();
iconoffset = new Point(real.x - p.x, real.y - p.y);
}
redraw();
break;
case NOTE:
ni = (NotePadMeta) areaOwner.getOwner();
selectedNotes = transMeta.getSelectedNotes();
selectedNote = ni;
Point loc = ni.getLocation();
previous_note_locations = transMeta.getSelectedNoteLocations();
noteoffset = new Point(real.x - loc.x, real.y - loc.y);
redraw();
break;
}
} else {
// A hop? --> enable/disable
TransHopMeta hop = findHop(real.x, real.y);
if (hop!=null) {
TransHopMeta before = (TransHopMeta) hop.clone();
hop.setEnabled(!hop.isEnabled());
TransHopMeta after = (TransHopMeta) hop.clone();
spoon.addUndoChange(transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after }, new int[] { transMeta.indexOfTransHop(hop) });
redraw();
} else {
// No area-owner & no hop means : background click:
startHopStep = null;
if (!control) {
selectionRegion = new org.pentaho.di.core.gui.Rectangle(real.x, real.y, 0, 0);
}
redraw();
}
}
}
}
public void mouseUp(MouseEvent e) {
boolean control = (e.stateMask & SWT.CONTROL) != 0;
if (iconoffset == null)
iconoffset = new Point(0, 0);
Point real = screen2real(e.x, e.y);
Point icon = new Point(real.x - iconoffset.x, real.y - iconoffset.y);
AreaOwner areaOwner = getVisibleAreaOwner(real.x, real.y);
// Quick new hop option? (drag from one step to another)
if (candidate != null && areaOwner!=null) {
switch(areaOwner.getAreaType()) {
case STEP_ICON : currentStep = (StepMeta) areaOwner.getOwner(); break;
case STEP_INPUT_HOP_ICON : currentStep = (StepMeta) areaOwner.getParent(); break;
}
addCandidateAsHop(e.x, e.y);
redraw();
}
// Did we select a region on the screen? Mark steps in region as
// selected
else {
if (selectionRegion != null) {
selectionRegion.width = real.x - selectionRegion.x;
selectionRegion.height = real.y - selectionRegion.y;
transMeta.unselectAll();
selectInRect(transMeta, selectionRegion);
selectionRegion = null;
stopStepMouseOverDelayTimers();
redraw();
}
// Clicked on an icon?
else {
if (selectedStep != null && startHopStep==null) {
if (e.button == 1) {
Point realclick = screen2real(e.x, e.y);
if (lastclick.x == realclick.x && lastclick.y == realclick.y) {
// Flip selection when control is pressed!
if (control) {
selectedStep.flipSelected();
} else {
// Otherwise, select only the icon clicked on!
transMeta.unselectAll();
selectedStep.setSelected(true);
}
} else {
// Find out which Steps & Notes are selected
selectedSteps = transMeta.getSelectedSteps();
selectedNotes = transMeta.getSelectedNotes();
// We moved around some items: store undo info...
boolean also = false;
if (selectedNotes != null && selectedNotes.size() > 0 && previous_note_locations != null) {
int indexes[] = transMeta.getNoteIndexes(selectedNotes);
addUndoPosition(selectedNotes.toArray(new NotePadMeta[selectedNotes.size()]), indexes, previous_note_locations, transMeta
.getSelectedNoteLocations(), also);
also = selectedSteps != null && selectedSteps.size() > 0;
}
if (selectedSteps != null && previous_step_locations != null) {
int indexes[] = transMeta.getStepIndexes(selectedSteps);
addUndoPosition(selectedSteps.toArray(new StepMeta[selectedSteps.size()]), indexes, previous_step_locations, transMeta.getSelectedStepLocations(), also);
}
}
}
// OK, we moved the step, did we move it across a hop?
// If so, ask to split the hop!
if (split_hop) {
TransHopMeta hi = findHop(icon.x + iconsize / 2, icon.y + iconsize / 2, selectedStep);
if (hi != null) {
splitHop(hi);
}
split_hop = false;
}
selectedSteps = null;
selectedNotes = null;
selectedStep = null;
selectedNote = null;
startHopStep = null;
endHopLocation = null;
redraw();
spoon.setShellText();
}
// Notes?
else {
if (selectedNote != null) {
if (e.button == 1) {
if (lastclick.x == e.x && lastclick.y == e.y) {
// Flip selection when control is pressed!
if (control) {
selectedNote.flipSelected();
} else {
// Otherwise, select only the note clicked on!
transMeta.unselectAll();
selectedNote.setSelected(true);
}
} else {
// Find out which Steps & Notes are selected
selectedSteps = transMeta.getSelectedSteps();
selectedNotes = transMeta.getSelectedNotes();
// We moved around some items: store undo info...
boolean also = false;
if (selectedNotes != null && selectedNotes.size() > 0 && previous_note_locations != null) {
int indexes[] = transMeta.getNoteIndexes(selectedNotes);
addUndoPosition(selectedNotes.toArray(new NotePadMeta[selectedNotes.size()]), indexes, previous_note_locations, transMeta.getSelectedNoteLocations(), also);
also = selectedSteps != null && selectedSteps.size() > 0;
}
if (selectedSteps != null && selectedSteps.size() > 0 && previous_step_locations != null) {
int indexes[] = transMeta.getStepIndexes(selectedSteps);
addUndoPosition(selectedSteps.toArray(new StepMeta[selectedSteps.size()]), indexes, previous_step_locations, transMeta.getSelectedStepLocations(), also);
}
}
}
selectedNotes = null;
selectedSteps = null;
selectedStep = null;
selectedNote = null;
startHopStep = null;
endHopLocation = null;
} else {
if (areaOwner==null && selectionRegion==null) {
// Hit absolutely nothing: clear the settings
clearSettings();
}
}
}
}
}
lastButton = 0;
}
private void splitHop(TransHopMeta hi) {
int id = 0;
if (!spoon.props.getAutoSplit()) {
MessageDialogWithToggle md = new MessageDialogWithToggle(
shell,
BaseMessages.getString(PKG, "TransGraph.Dialog.SplitHop.Title"), null, //$NON-NLS-1$
BaseMessages.getString(PKG, "TransGraph.Dialog.SplitHop.Message") + Const.CR + hi.toString(), MessageDialog.QUESTION, new String[] { //$NON-NLS-1$
BaseMessages.getString(PKG, "System.Button.Yes"), BaseMessages.getString(PKG, "System.Button.No") }, 0, BaseMessages.getString(PKG, "TransGraph.Dialog.Option.SplitHop.DoNotAskAgain"), spoon.props.getAutoSplit()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
MessageDialogWithToggle.setDefaultImage(GUIResource.getInstance().getImageSpoon());
id = md.open();
spoon.props.setAutoSplit(md.getToggleState());
}
if ((id & 0xFF) == 0) // Means: "Yes" button clicked!
{
// Only split A-->--B by putting C in between IF...
// C-->--A or B-->--C don't exists...
// A ==> hi.getFromStep()
// B ==> hi.getToStep();
// C ==> selected_step
boolean caExists = transMeta.findTransHop(selectedStep, hi.getFromStep()) != null;
boolean bcExists = transMeta.findTransHop(hi.getToStep(), selectedStep) != null;
if (!caExists && !bcExists) {
// In case step A targets B then we now need to target C
StepIOMetaInterface fromIo = hi.getFromStep().getStepMetaInterface().getStepIOMeta();
for (StreamInterface stream : fromIo.getTargetStreams()) {
if (stream.getStepMeta()!=null && stream.getStepMeta().equals(hi.getToStep())) {
// This target stream was directed to B, now we need to direct it to C
stream.setStepMeta(selectedStep);
}
}
// In case step B sources from A then we now need to source from C
StepIOMetaInterface toIo = hi.getToStep().getStepMetaInterface().getStepIOMeta();
for (StreamInterface stream : toIo.getInfoStreams()) {
if (stream.getStepMeta()!=null && stream.getStepMeta().equals(hi.getFromStep())) {
// This info stream was reading from B, now we need to direct it to C
stream.setStepMeta(selectedStep);
}
}
TransHopMeta newhop1 = new TransHopMeta(hi.getFromStep(), selectedStep);
transMeta.addTransHop(newhop1);
TransHopMeta newhop2 = new TransHopMeta(selectedStep, hi.getToStep());
transMeta.addTransHop(newhop2);
spoon.addUndoNew(transMeta, new TransHopMeta[] { newhop2 }, new int[] { transMeta.indexOfTransHop(newhop2) }, true);
int idx = transMeta.indexOfTransHop(hi);
spoon.addUndoDelete(transMeta, new TransHopMeta[] { hi }, new int[] { idx }, true);
transMeta.removeTransHop(idx);
spoon.refreshTree();
} else {
// Silently discard this hop-split attempt.
}
}
}
public void mouseMove(MouseEvent e) {
boolean shift = (e.stateMask & SWT.SHIFT) != 0;
noInputStep = null;
// disable the tooltip
toolTip.hide();
// Remember the last position of the mouse for paste with keyboard
lastMove = new Point(e.x, e.y);
Point real = screen2real(e.x, e.y);
if (iconoffset == null) {
iconoffset = new Point(0, 0);
}
Point icon = new Point(real.x - iconoffset.x, real.y - iconoffset.y);
if (noteoffset == null) {
noteoffset = new Point(0, 0);
}
Point note = new Point(real.x - noteoffset.x, real.y - noteoffset.y);
// Moved over an area?
AreaOwner areaOwner = getVisibleAreaOwner(real.x, real.y);
if (areaOwner!=null) {
switch (areaOwner.getAreaType()) {
case STEP_ICON :
{
StepMeta stepMeta = (StepMeta) areaOwner.getOwner();
resetDelayTimer(stepMeta);
}
break;
case MINI_ICONS_BALLOON : // Give the timer a bit more time
{
StepMeta stepMeta = (StepMeta)areaOwner.getParent();
resetDelayTimer(stepMeta);
}
break;
default:
break;
}
}
// First see if the icon we clicked on was selected.
// If the icon was not selected, we should un-select all other
// icons, selected and move only the one icon
if (selectedStep != null && !selectedStep.isSelected()) {
transMeta.unselectAll();
selectedStep.setSelected(true);
selectedSteps = new ArrayList<StepMeta>();
selectedSteps.add(selectedStep);
previous_step_locations = new Point[] { selectedStep.getLocation() };
redraw();
}
else if (selectedNote != null && !selectedNote.isSelected()) {
transMeta.unselectAll();
selectedNote.setSelected(true);
selectedNotes = new ArrayList<NotePadMeta>();
selectedNotes.add(selectedNote);
previous_note_locations = new Point[] { selectedNote.getLocation() };
redraw();
}
// Did we select a region...?
else if (selectionRegion != null && startHopStep==null) {
selectionRegion.width = real.x - selectionRegion.x;
selectionRegion.height = real.y - selectionRegion.y;
redraw();
}
// Move around steps & notes
else if (selectedStep != null && lastButton == 1 && !shift && startHopStep==null) {
/*
* One or more icons are selected and moved around...
*
* new : new position of the ICON (not the mouse pointer) dx : difference with previous
* position
*/
int dx = icon.x - selectedStep.getLocation().x;
int dy = icon.y - selectedStep.getLocation().y;
// See if we have a hop-split candidate
TransHopMeta hi = findHop(icon.x + iconsize / 2, icon.y + iconsize / 2, selectedStep);
if (hi != null) {
// OK, we want to split the hop in 2
if (!hi.getFromStep().equals(selectedStep) && !hi.getToStep().equals(selectedStep)) {
split_hop = true;
last_hop_split = hi;
hi.split = true;
}
} else {
if (last_hop_split != null) {
last_hop_split.split = false;
last_hop_split = null;
split_hop = false;
}
}
selectedNotes = transMeta.getSelectedNotes();
selectedSteps = transMeta.getSelectedSteps();
// Adjust location of selected steps...
if (selectedSteps != null) {
for (int i = 0; i < selectedSteps.size(); i++) {
StepMeta stepMeta = selectedSteps.get(i);
PropsUI.setLocation(stepMeta, stepMeta.getLocation().x + dx, stepMeta.getLocation().y + dy);
stopStepMouseOverDelayTimer(stepMeta);
}
}
// Adjust location of selected hops...
if (selectedNotes != null) {
for (int i = 0; i < selectedNotes.size(); i++) {
NotePadMeta ni = selectedNotes.get(i);
PropsUI.setLocation(ni, ni.getLocation().x + dx, ni.getLocation().y + dy);
}
}
redraw();
}
// Are we creating a new hop with the middle button or pressing SHIFT?
else if ((startHopStep!=null && endHopStep==null) || (endHopStep!=null && startHopStep==null)) {
StepMeta stepMeta = transMeta.getStep(real.x, real.y, iconsize);
endHopLocation = new Point(real.x, real.y);
if (stepMeta != null && ((startHopStep!=null && !startHopStep.equals(stepMeta)) || (endHopStep!=null && !endHopStep.equals(stepMeta))) ) {
StepIOMetaInterface ioMeta = stepMeta.getStepMetaInterface().getStepIOMeta();
if (candidate == null) {
// See if the step accepts input. If not, we can't create a new hop...
if (startHopStep!=null) {
if (ioMeta.isInputAcceptor()) {
candidate = new TransHopMeta(startHopStep, stepMeta);
endHopLocation=null;
} else {
noInputStep=stepMeta;
toolTip.setImage(null);
toolTip.setText("This step does not accept any input from other steps"); //$NON-NLS-1$
toolTip.show(new org.eclipse.swt.graphics.Point(real.x, real.y));
}
} else if (endHopStep!=null) {
if (ioMeta.isOutputProducer()) {
candidate = new TransHopMeta(stepMeta, endHopStep);
endHopLocation=null;
} else {
noInputStep=stepMeta;
toolTip.setImage(null);
toolTip.setText("This step doesn't pass any output to other steps. (except perhaps for targetted output)"); //$NON-NLS-1$
toolTip.show(new org.eclipse.swt.graphics.Point(real.x, real.y));
}
}
}
} else {
if (candidate != null) {
candidate = null;
redraw();
}
}
redraw();
}
// Move around notes & steps
if (selectedNote != null) {
if (lastButton == 1 && !shift) {
/*
* One or more notes are selected and moved around...
*
* new : new position of the note (not the mouse pointer) dx : difference with previous
* position
*/
int dx = note.x - selectedNote.getLocation().x;
int dy = note.y - selectedNote.getLocation().y;
selectedNotes = transMeta.getSelectedNotes();
selectedSteps = transMeta.getSelectedSteps();
// Adjust location of selected steps...
if (selectedSteps != null)
for (int i = 0; i < selectedSteps.size(); i++) {
StepMeta stepMeta = selectedSteps.get(i);
PropsUI.setLocation(stepMeta, stepMeta.getLocation().x + dx, stepMeta.getLocation().y + dy);
}
// Adjust location of selected hops...
if (selectedNotes != null)
for (int i = 0; i < selectedNotes.size(); i++) {
NotePadMeta ni = selectedNotes.get(i);
PropsUI.setLocation(ni, ni.getLocation().x + dx, ni.getLocation().y + dy);
}
redraw();
}
}
}
public void mouseHover(MouseEvent e) {
boolean tip = true;
toolTip.hide();
Point real = screen2real(e.x, e.y);
AreaOwner areaOwner = getVisibleAreaOwner(real.x, real.y);
if (areaOwner!=null) {
switch (areaOwner.getAreaType()) {
case STEP_ICON :
StepMeta stepMeta = (StepMeta) areaOwner.getOwner();
if (!mouseOverSteps.contains(stepMeta)) {
addStepMouseOverDelayTimer(stepMeta);
redraw();
tip=false;
}
break;
}
}
if (tip) {
// Show a tool tip upon mouse-over of an object on the canvas
if (!helpTip.isVisible()) {
setToolTip(real.x, real.y, e.x, e.y);
}
}
}
public void mouseScrolled(MouseEvent e) {
/*
if (e.count == 3) {
// scroll up
zoomIn();
} else if (e.count == -3) {
// scroll down
zoomOut();
}
}
*/
}
private void addCandidateAsHop(int mouseX, int mouseY) {
boolean forward = startHopStep!=null;
StepMeta fromStep = candidate.getFromStep();
StepMeta toStep = candidate.getToStep();
// See what the options are.
// - Does the source step has multiple stream options?
// - Does the target step have multiple input stream options?
List<StreamInterface> streams=new ArrayList<StreamInterface>();
StepIOMetaInterface fromIoMeta = fromStep.getStepMetaInterface().getStepIOMeta();
List<StreamInterface> targetStreams = fromIoMeta.getTargetStreams();
if (forward) {
streams.addAll(targetStreams);
}
StepIOMetaInterface toIoMeta = toStep.getStepMetaInterface().getStepIOMeta();
List<StreamInterface> infoStreams = toIoMeta.getInfoStreams();
if (!forward) {
streams.addAll(infoStreams);
}
if (forward) {
if (fromIoMeta.isOutputProducer() && toStep.equals(currentStep)) {
streams.add( new Stream(StreamType.OUTPUT, fromStep, "Main output of step", StreamIcon.OUTPUT, null) ); //$NON-NLS-1$
}
if (fromStep.supportsErrorHandling() && toStep.equals(currentStep)) {
streams.add( new Stream(StreamType.ERROR, fromStep, "Error handling of step", StreamIcon.ERROR, null) ); //$NON-NLS-1$
}
} else {
if (toIoMeta.isInputAcceptor() && fromStep.equals(currentStep)) {
streams.add( new Stream(StreamType.INPUT, toStep, "Main input of step", StreamIcon.INPUT, null) ); //$NON-NLS-1$
}
if (fromStep.supportsErrorHandling() && fromStep.equals(currentStep)) {
streams.add( new Stream(StreamType.ERROR, fromStep, "Error handling of step", StreamIcon.ERROR, null) ); //$NON-NLS-1$
}
}
// Targets can be dynamically added to this step...
if (forward) {
streams.addAll( fromStep.getStepMetaInterface().getOptionalStreams() );
} else {
streams.addAll( toStep.getStepMetaInterface().getOptionalStreams() );
}
// Show a list of options on the canvas...
if (streams.size()>1) {
// Show a pop-up menu with all the possible options...
Menu menu = new Menu(canvas);
for (final StreamInterface stream : streams) {
MenuItem item = new MenuItem(menu, SWT.NONE);
item.setText(Const.NVL(stream.getDescription(), "")); //$NON-NLS-1$
item.setImage( SWTGC.getNativeImage(BasePainter.getStreamIconImage(stream.getStreamIcon())) );
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
addHop(stream);
}
});
}
menu.setLocation(canvas.toDisplay(mouseX, mouseY));
menu.setVisible(true);
return;
} if (streams.size()==1) {
addHop(streams.get(0));
} else {
return;
}
/*
if (transMeta.findTransHop(candidate) == null) {
spoon.newHop(transMeta, candidate);
}
if (startErrorHopStep) {
addErrorHop();
}
if (startTargetHopStream != null) {
// Auto-configure the target in the source step...
//
startTargetHopStream.setStepMeta(candidate.getToStep());
startTargetHopStream.setStepname(candidate.getToStep().getName());
startTargetHopStream = null;
}
*/
candidate = null;
selectedSteps = null;
startHopStep = null;
endHopLocation = null;
startErrorHopStep = false;
// redraw();
}
protected void addHop(StreamInterface stream) {
switch(stream.getStreamType()) {
case ERROR :
addErrorHop();
spoon.newHop(transMeta, candidate);
break;
case INPUT:
spoon.newHop(transMeta, candidate);
break;
case OUTPUT :
StepErrorMeta stepErrorMeta = candidate.getFromStep().getStepErrorMeta();
if (stepErrorMeta!=null && stepErrorMeta.getTargetStep()!=null) {
if (stepErrorMeta.getTargetStep().equals(candidate.getToStep())) {
candidate.getFromStep().setStepErrorMeta(null);
}
}
spoon.newHop(transMeta, candidate);
break;
case INFO :
stream.setStepMeta(candidate.getFromStep());
candidate.getToStep().getStepMetaInterface().handleStreamSelection(stream);
spoon.newHop(transMeta, candidate);
break;
case TARGET :
// We connect a target of the source step to an output step...
stream.setStepMeta(candidate.getToStep());
candidate.getFromStep().getStepMetaInterface().handleStreamSelection(stream);
spoon.newHop(transMeta, candidate);
break;
}
clearSettings();
}
private void addErrorHop() {
// Automatically configure the step error handling too!
StepErrorMeta errorMeta = candidate.getFromStep().getStepErrorMeta();
if (errorMeta == null) {
errorMeta = new StepErrorMeta(transMeta, candidate.getFromStep());
}
errorMeta.setEnabled(true);
errorMeta.setTargetStep(candidate.getToStep());
candidate.getFromStep().setStepErrorMeta(errorMeta);
}
private void resetDelayTimer(StepMeta stepMeta) {
DelayTimer delayTimer = delayTimers.get(stepMeta);
if (delayTimer!=null) {
delayTimer.reset();
}
}
/*
private void showStepTargetOptions(final StepMeta stepMeta, StepIOMetaInterface ioMeta, int x, int y) {
if (!Const.isEmpty(ioMeta.getTargetStepnames())) {
final Menu menu = new Menu(canvas);
for (final StreamInterface stream : ioMeta.getTargetStreams()) {
MenuItem menuItem = new MenuItem(menu, SWT.NONE);
menuItem.setText(stream.getDescription());
menuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
// Click on the target icon means: create a new target hop
//
if (startHopStep==null) {
startHopStep = stepMeta;
}
menu.setVisible(false);
menu.dispose();
redraw();
}
});
}
menu.setLocation(x, y);
menu.setVisible(true);
resetDelayTimer(stepMeta);
//showTargetStreamsStep = stepMeta;
}
}
*/
public void mouseEnter(MouseEvent arg0) {
}
public void mouseExit(MouseEvent arg0) {
}
private synchronized void addStepMouseOverDelayTimer(final StepMeta stepMeta) {
// Don't add the same mouse over delay timer twice...
if (mouseOverSteps.contains(stepMeta)) return;
mouseOverSteps.add(stepMeta);
DelayTimer delayTimer = new DelayTimer(2500, new DelayListener() {
public void expired() {
mouseOverSteps.remove(stepMeta);
delayTimers.remove(stepMeta);
showTargetStreamsStep=null;
asyncRedraw();
}
});
new Thread(delayTimer).start();
delayTimers.put(stepMeta, delayTimer);
}
private void stopStepMouseOverDelayTimer(final StepMeta stepMeta) {
DelayTimer delayTimer = delayTimers.get(stepMeta);
if (delayTimer!=null) {
delayTimer.stop();
}
}
private void stopStepMouseOverDelayTimers() {
for (DelayTimer timer : delayTimers.values()) {
timer.stop();
}
}
protected void asyncRedraw() {
spoon.getDisplay().asyncExec(new Runnable() {
public void run() {
if (!TransGraph.this.isDisposed()) {
TransGraph.this.redraw();
}
}
});
}
private void addToolBar() {
try {
toolbar = (XulToolbar) getXulDomContainer().getDocumentRoot().getElementById("nav-toolbar"); //$NON-NLS-1$
ToolBar swtToolbar = (ToolBar) toolbar.getManagedObject();
swtToolbar.pack();
// Hack alert : more XUL limitations...
// TODO: no longer a limitation use toolbaritem
ToolItem sep = new ToolItem(swtToolbar, SWT.SEPARATOR);
zoomLabel = new Combo(swtToolbar, SWT.DROP_DOWN);
zoomLabel.setItems(TransPainter.magnificationDescriptions);
zoomLabel.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent arg0) {
readMagnification();
}
});
zoomLabel.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event) {
if (event.character == SWT.CR) {
readMagnification();
}
}
});
setZoomLabel();
zoomLabel.pack();
sep.setWidth(80);
sep.setControl(zoomLabel);
swtToolbar.pack();
} catch (Throwable t) {
log.logError("Error loading the navigation toolbar for Spoon", t);
new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Exception.ErrorReadingXULFile.Title"), //$NON-NLS-1$
BaseMessages.getString(PKG, "Spoon.Exception.ErrorReadingXULFile.Message", XUL_FILE_TRANS_TOOLBAR), new Exception(t)); //$NON-NLS-1$
}
}
/**
* Allows for magnifying to any percentage entered by the user...
*/
private void readMagnification(){
String possibleText = zoomLabel.getText();
possibleText = possibleText.replace("%", ""); //$NON-NLS-1$//$NON-NLS-2$
float possibleFloatMagnification;
try {
possibleFloatMagnification = Float.parseFloat(possibleText) / 100;
magnification = possibleFloatMagnification;
if (zoomLabel.getText().indexOf('%') < 0) {
zoomLabel.setText(zoomLabel.getText().concat("%")); //$NON-NLS-1$
}
} catch (Exception e) {
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_ERROR);
mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.InvalidZoomMeasurement.Message", zoomLabel.getText())); //$NON-NLS-1$
mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.InvalidZoomMeasurement.Title")); //$NON-NLS-1$
mb.open();
}
redraw();
}
protected void hideToolTips() {
toolTip.hide();
helpTip.hide();
}
private void showHelpTip(int x, int y, String tipTitle, String tipMessage) {
helpTip.setTitle(tipTitle);
helpTip.setMessage(tipMessage.replaceAll("\n", Const.CR)); //$NON-NLS-1$
helpTip.setCheckBoxMessage(BaseMessages.getString(PKG, "TransGraph.HelpToolTip.DoNotShowAnyMoreCheckBox.Message")); //$NON-NLS-1$
// helpTip.hide();
// int iconSize = spoon.props.getIconSize();
org.eclipse.swt.graphics.Point location = new org.eclipse.swt.graphics.Point(x - 5, y - 5);
helpTip.show(location);
}
/**
* Select all the steps in a certain (screen) rectangle
*
* @param rect The selection area as a rectangle
*/
public void selectInRect(TransMeta transMeta, org.pentaho.di.core.gui.Rectangle rect) {
if (rect.height < 0 || rect.width < 0) {
org.pentaho.di.core.gui.Rectangle rectified = new org.pentaho.di.core.gui.Rectangle(rect.x, rect.y, rect.width, rect.height);
// Only for people not dragging from left top to right bottom
if (rectified.height < 0) {
rectified.y = rectified.y + rectified.height;
rectified.height = -rectified.height;
}
if (rectified.width < 0) {
rectified.x = rectified.x + rectified.width;
rectified.width = -rectified.width;
}
rect = rectified;
}
for (int i = 0; i < transMeta.nrSteps(); i++) {
StepMeta stepMeta = transMeta.getStep(i);
Point a = stepMeta.getLocation();
if (rect.contains(a.x, a.y))
stepMeta.setSelected(true);
}
for (int i = 0; i < transMeta.nrNotes(); i++) {
NotePadMeta ni = transMeta.getNote(i);
Point a = ni.getLocation();
Point b = new Point(a.x + ni.width, a.y + ni.height);
if (rect.contains(a.x, a.y) && rect.contains(b.x, b.y))
ni.setSelected(true);
}
}
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.ESC) {
clearSettings();
redraw();
}
if (e.keyCode == SWT.DEL) {
List<StepMeta> stepMeta = transMeta.getSelectedSteps();
if (stepMeta != null && stepMeta.size()> 0) {
delSelected(null);
}
}
if (e.keyCode == SWT.F1) {
spoon.browseVersionHistory();
}
if (e.keyCode == SWT.F2) {
spoon.editKettlePropertiesFile();
}
// CTRL-UP : allignTop();
if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.CONTROL) != 0) {
alligntop();
}
// CTRL-DOWN : allignBottom();
if (e.keyCode == SWT.ARROW_DOWN && (e.stateMask & SWT.CONTROL) != 0) {
allignbottom();
}
// CTRL-LEFT : allignleft();
if (e.keyCode == SWT.ARROW_LEFT && (e.stateMask & SWT.CONTROL) != 0) {
allignleft();
}
// CTRL-RIGHT : allignRight();
if (e.keyCode == SWT.ARROW_RIGHT && (e.stateMask & SWT.CONTROL) != 0) {
allignright();
}
// ALT-RIGHT : distributeHorizontal();
if (e.keyCode == SWT.ARROW_RIGHT && (e.stateMask & SWT.ALT) != 0) {
distributehorizontal();
}
// ALT-UP : distributeVertical();
if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.ALT) != 0) {
distributevertical();
}
// ALT-HOME : snap to grid
if (e.keyCode == SWT.HOME && (e.stateMask & SWT.ALT) != 0) {
snaptogrid(ConstUI.GRID_SIZE);
}
if (e.character == 'E' && (e.stateMask & SWT.CTRL) != 0) {
checkErrorVisuals();
}
// SPACE : over a step: show output fields...
if (e.character == ' ' && lastMove != null) {
// TODO: debugging code, remove later on!
dumpLoggingRegistry();
Point real = screen2real(lastMove.x, lastMove.y);
// Hide the tooltip!
hideToolTips();
// Set the pop-up menu
StepMeta stepMeta = transMeta.getStep(real.x, real.y, iconsize);
if (stepMeta != null) {
// OK, we found a step, show the output fields...
inputOutputFields(stepMeta, false);
}
}
// CTRL-W or CTRL-F4 : close tab
if ((e.character=='w' && (e.stateMask & SWT.CONTROL) != 0 ) ||
(e.keyCode==SWT.F4 && (e.stateMask & SWT.CONTROL) != 0 )
)
{
dispose();
}
}
public void keyReleased(KeyEvent e) {
}
public boolean setFocus() {
return canvas.setFocus();
}
public void renameStep(StepMeta stepMeta, String stepname) {
String newname = stepname;
StepMeta smeta = transMeta.findStep(newname, stepMeta);
int nr = 2;
while (smeta != null) {
newname = stepname + " " + nr; //$NON-NLS-1$
smeta = transMeta.findStep(newname);
nr++;
}
if (nr > 2) {
stepname = newname;
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.StepnameExists.Message", stepname)); // $NON-NLS-1$ //$NON-NLS-1$
mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.StepnameExists.Title")); // $NON-NLS-1$ //$NON-NLS-1$
mb.open();
}
stepMeta.setName(stepname);
stepMeta.setChanged();
spoon.refreshTree(); // to reflect the new name
spoon.refreshGraph();
}
public void clearSettings() {
selectedStep = null;
noInputStep = null;
selectedNote = null;
selectedSteps = null;
selectionRegion = null;
candidate = null;
last_hop_split = null;
lastButton = 0;
iconoffset = null;
startHopStep = null;
endHopStep = null;
endHopLocation = null;
mouseOverSteps.clear();
for (int i = 0; i < transMeta.nrTransHops(); i++) {
transMeta.getTransHop(i).split = false;
}
stopStepMouseOverDelayTimers();
}
public String[] getDropStrings(String str, String sep) {
StringTokenizer strtok = new StringTokenizer(str, sep);
String retval[] = new String[strtok.countTokens()];
int i = 0;
while (strtok.hasMoreElements()) {
retval[i] = strtok.nextToken();
i++;
}
return retval;
}
public Point getRealPosition(Composite canvas, int x, int y) {
Point p = new Point(0, 0);
Composite follow = canvas;
while (follow != null) {
org.eclipse.swt.graphics.Point loc = follow.getLocation();
Point xy = new Point(loc.x, loc.y);
p.x += xy.x;
p.y += xy.y;
follow = follow.getParent();
}
int offsetX = -16;
int offsetY = -64;
if (Const.isOSX()) {
offsetX = -2;
offsetY = -24;
}
p.x = x - p.x + offsetX;
p.y = y - p.y + offsetY;
return screen2real(p.x, p.y);
}
/**
* See if location (x,y) is on a line between two steps: the hop!
* @param x
* @param y
* @return the transformation hop on the specified location, otherwise: null
*/
private TransHopMeta findHop(int x, int y) {
return findHop(x, y, null);
}
/**
* See if location (x,y) is on a line between two steps: the hop!
* @param x
* @param y
* @param exclude the step to exclude from the hops (from or to location). Specify null if no step is to be excluded.
* @return the transformation hop on the specified location, otherwise: null
*/
private TransHopMeta findHop(int x, int y, StepMeta exclude) {
int i;
TransHopMeta online = null;
for (i = 0; i < transMeta.nrTransHops(); i++) {
TransHopMeta hi = transMeta.getTransHop(i);
StepMeta fs = hi.getFromStep();
StepMeta ts = hi.getToStep();
if (fs == null || ts == null)
return null;
// If either the "from" or "to" step is excluded, skip this hop.
if (exclude != null && (exclude.equals(fs) || exclude.equals(ts)))
continue;
int line[] = getLine(fs, ts);
if (pointOnLine(x, y, line))
online = hi;
}
return online;
}
private int[] getLine(StepMeta fs, StepMeta ts) {
Point from = fs.getLocation();
Point to = ts.getLocation();
offset = getOffset();
int x1 = from.x + iconsize / 2;
int y1 = from.y + iconsize / 2;
int x2 = to.x + iconsize / 2;
int y2 = to.y + iconsize / 2;
return new int[] { x1, y1, x2, y2 };
}
public void hideStep() {
for (int i = 0; i < transMeta.nrSteps(); i++) {
StepMeta sti = transMeta.getStep(i);
if (sti.isDrawn() && sti.isSelected()) {
sti.hideStep();
spoon.refreshTree();
}
}
getCurrentStep().hideStep();
spoon.refreshTree();
redraw();
}
public void checkSelectedSteps() {
spoon.checkTrans(transMeta, true);
}
public void detachStep() {
detach(getCurrentStep());
selectedSteps = null;
}
public void generateMappingToThisStep() {
spoon.generateFieldMapping(transMeta, getCurrentStep());
}
public void partitioning() {
spoon.editPartitioning(transMeta, getCurrentStep());
}
public void clustering() {
List<StepMeta> selected = transMeta.getSelectedSteps();
if (selected!=null && selected.size()>0) {
spoon.editClustering(transMeta, transMeta.getSelectedSteps());
} else {
spoon.editClustering(transMeta, getCurrentStep());
}
}
public void errorHandling() {
spoon.editStepErrorHandling(transMeta, getCurrentStep());
}
public void newHopChoice() {
selectedSteps = null;
newHop();
}
public void editStep() {
selectedSteps = null;
editStep(getCurrentStep());
}
public void editDescription() {
editDescription(getCurrentStep());
}
public void setDistributes() {
getCurrentStep().setDistributes(true);
spoon.refreshGraph();
spoon.refreshTree();
}
public void setCopies() {
getCurrentStep().setDistributes(false);
spoon.refreshGraph();
spoon.refreshTree();
}
public void copies() {
final boolean multipleOK = checkNumberOfCopies(transMeta, getCurrentStep());
selectedSteps = null;
String tt = BaseMessages.getString(PKG, "TransGraph.Dialog.NrOfCopiesOfStep.Title"); //$NON-NLS-1$
String mt = BaseMessages.getString(PKG, "TransGraph.Dialog.NrOfCopiesOfStep.Message"); //$NON-NLS-1$
EnterNumberDialog nd = new EnterNumberDialog(shell, getCurrentStep().getCopies(), tt, mt);
int cop = nd.open();
if (cop >= 0) {
if (cop == 0)
cop = 1;
if (!multipleOK) {
cop = 1;
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING);
mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.MultipleCopiesAreNotAllowedHere.Message")); //$NON-NLS-1$
mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.MultipleCopiesAreNotAllowedHere.Title")); //$NON-NLS-1$
mb.open();
}
if (getCurrentStep().getCopies() != cop) {
getCurrentStep().setCopies(cop);
spoon.refreshGraph();
}
}
}
public void dupeStep() {
try {
List<StepMeta> steps = transMeta.getSelectedSteps();
if (steps.size() <= 1) {
spoon.dupeStep(transMeta, getCurrentStep());
} else {
for (StepMeta stepMeta : steps) {
spoon.dupeStep(transMeta, stepMeta);
}
}
} catch (Exception ex) {
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "TransGraph.Dialog.ErrorDuplicatingStep.Title"), BaseMessages.getString(PKG, "TransGraph.Dialog.ErrorDuplicatingStep.Message"), ex); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public void copyStep() {
spoon.copySelected(transMeta, transMeta.getSelectedSteps(), transMeta.getSelectedNotes());
}
public void delSelected() {
delSelected(getCurrentStep());
}
public void fieldsBefore() {
selectedSteps = null;
inputOutputFields(getCurrentStep(), true);
}
public void fieldsAfter() {
selectedSteps = null;
inputOutputFields(getCurrentStep(), false);
}
public void fieldsLineage() {
TransDataLineage tdl = new TransDataLineage(transMeta);
try {
tdl.calculateLineage();
}
catch(Exception e) {
new ErrorDialog(shell, "Lineage error", "Unexpected lineage calculation error", e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public void editHop() {
selectionRegion = null;
editHop(getCurrentHop());
}
public void flipHopDirection() {
selectionRegion = null;
TransHopMeta hi = getCurrentHop();
hi.flip();
if (transMeta.hasLoop(hi.getFromStep())) {
spoon.refreshGraph();
MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING);
mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.LoopsAreNotAllowed.Message")); //$NON-NLS-1$
mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.LoopsAreNotAllowed.Title")); //$NON-NLS-1$
mb.open();
hi.flip();
spoon.refreshGraph();
} else {
hi.setChanged();
spoon.refreshGraph();
spoon.refreshTree();
spoon.setShellText();
}
}
public void enableHop() {
selectionRegion = null;
TransHopMeta hi = getCurrentHop();
TransHopMeta before = (TransHopMeta) hi.clone();
hi.setEnabled(!hi.isEnabled());
if (transMeta.hasLoop(hi.getToStep())) {
hi.setEnabled(!hi.isEnabled());
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.LoopAfterHopEnabled.Message")); //$NON-NLS-1$
mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.LoopAfterHopEnabled.Title")); //$NON-NLS-1$
mb.open();
} else {
TransHopMeta after = (TransHopMeta) hi.clone();
spoon.addUndoChange(transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after }, new int[] { transMeta
.indexOfTransHop(hi) });
spoon.refreshGraph();
spoon.refreshTree();
}
}
public void deleteHop() {
selectionRegion = null;
TransHopMeta hi = getCurrentHop();
int idx = transMeta.indexOfTransHop(hi);
spoon.addUndoDelete(transMeta, new TransHopMeta[] { (TransHopMeta) hi.clone() }, new int[] { idx });
transMeta.removeTransHop(idx);
spoon.refreshTree();
spoon.refreshGraph();
}
public void enableHopsBetweenSelectedSteps() {
enableHopsBetweenSelectedSteps(true);
}
public void disableHopsBetweenSelectedSteps() {
enableHopsBetweenSelectedSteps(false);
}
/**
* This method enables or disables all the hops between the selected steps.
*
**/
public void enableHopsBetweenSelectedSteps(boolean enabled) {
List<StepMeta> list = transMeta.getSelectedSteps();
for (int i=0;i<transMeta.nrTransHops();i++) {
TransHopMeta hop = transMeta.getTransHop(i);
if (list.contains(hop.getFromStep()) && list.contains(hop.getToStep())) {
TransHopMeta before = (TransHopMeta) hop.clone();
hop.setEnabled(enabled);
TransHopMeta after = (TransHopMeta) hop.clone();
spoon.addUndoChange(transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after }, new int[] { transMeta.indexOfTransHop(hop) });
}
}
spoon.refreshGraph();
}
public void enableHopsDownstream() {
enableDisableHopsDownstream(true);
}
public void disableHopsDownstream() {
enableDisableHopsDownstream(false);
}
public void enableDisableHopsDownstream(boolean enabled) {
if (currentHop==null) return;
TransHopMeta before = (TransHopMeta) currentHop.clone();
currentHop.setEnabled(enabled);
TransHopMeta after = (TransHopMeta) currentHop.clone();
spoon.addUndoChange(transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after }, new int[] { transMeta.indexOfTransHop(currentHop) });
enableDisableNextHops(currentHop.getToStep(), enabled);
spoon.refreshGraph();
}
private void enableDisableNextHops(StepMeta from, boolean enabled) {
for (StepMeta to : transMeta.getSteps()) {
TransHopMeta hop = transMeta.findTransHop(from, to, true);
if (hop!=null) {
TransHopMeta before = (TransHopMeta) hop.clone();
hop.setEnabled(enabled);
TransHopMeta after = (TransHopMeta) hop.clone();
spoon.addUndoChange(transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after }, new int[] { transMeta.indexOfTransHop(hop) });
enableDisableNextHops(to, enabled);
}
}
}
public void editNote() {
selectionRegion = null;
editNote(getCurrentNote());
}
public void deleteNote() {
selectionRegion = null;
int idx = transMeta.indexOfNote(ni);
if (idx >= 0) {
transMeta.removeNote(idx);
spoon.addUndoDelete(transMeta, new NotePadMeta[] { (NotePadMeta) ni.clone() }, new int[] { idx });
redraw();
}
}
public void raiseNote() {
selectionRegion = null;
int idx = transMeta.indexOfNote(getCurrentNote());
if (idx >= 0) {
transMeta.raiseNote(idx);
//TBD: spoon.addUndoRaise(transMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} );
}
redraw();
}
public void lowerNote() {
selectionRegion = null;
int idx = transMeta.indexOfNote(getCurrentNote());
if (idx >= 0) {
transMeta.lowerNote(idx);
//TBD: spoon.addUndoLower(transMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} );
}
redraw();
}
public void newNote() {
selectionRegion = null;
String title = BaseMessages.getString(PKG, "TransGraph.Dialog.NoteEditor.Title"); //$NON-NLS-1$
NotePadDialog dd = new NotePadDialog(shell, title); //$NON-NLS-1$
NotePadMeta n = dd.open();
if (n != null)
{
NotePadMeta npi = new NotePadMeta(n.getNote(), lastclick.x, lastclick.y, ConstUI.NOTE_MIN_SIZE,
ConstUI.NOTE_MIN_SIZE,n.getFontName(),n.getFontSize(), n.isFontBold(), n.isFontItalic(),
n.getFontColorRed(),n.getFontColorGreen(),n.getFontColorBlue(),
n.getBackGroundColorRed(), n.getBackGroundColorGreen(),n.getBackGroundColorBlue(),
n.getBorderColorRed(), n.getBorderColorGreen(),n.getBorderColorBlue(),
n.isDrawShadow());
transMeta.addNote(npi);
spoon.addUndoNew(transMeta, new NotePadMeta[] { npi }, new int[] { transMeta.indexOfNote(npi) });
redraw();
}
}
public void paste() {
final String clipcontent = spoon.fromClipboard();
Point loc = new Point(currentMouseX, currentMouseY);
spoon.pasteXML(transMeta, clipcontent, loc);
}
public void settings() {
editProperties(transMeta, spoon, spoon.getRepository(), true);
}
public void newStep(String description) {
StepMeta stepMeta = spoon.newStep(transMeta, description, description, false, true);
PropsUI.setLocation(stepMeta, currentMouseX, currentMouseY);
stepMeta.setDraw(true);
redraw();
}
/**
* This sets the popup-menu on the background of the canvas based on the xy coordinate of the mouse. This method is
* called after a mouse-click.
*
* @param x X-coordinate on screen
* @param y Y-coordinate on screen
*/
private synchronized void setMenu(int x, int y) {
try {
currentMouseX = x;
currentMouseY = y;
final StepMeta stepMeta = transMeta.getStep(x, y, iconsize);
if (stepMeta != null) // We clicked on a Step!
{
setCurrentStep(stepMeta);
XulMenupopup menu = menuMap.get("trans-graph-entry"); //$NON-NLS-1$
if (menu != null) {
List<StepMeta> selection = transMeta.getSelectedSteps();
int sels = selection.size();
Document doc = getXulDomContainer().getDocumentRoot();
XulMenuitem item = (XulMenuitem) doc.getElementById("trans-graph-entry-newhop"); //$NON-NLS-1$
item.setDisabled(sels != 2);
item = (XulMenuitem) doc.getElementById("trans-graph-entry-open-mapping"); //$NON-NLS-1$
item.setDisabled(!stepMeta.isMapping());
item = (XulMenuitem) doc.getElementById("trans-graph-entry-align-snap"); //$NON-NLS-1$
item.setLabel(BaseMessages.getString(PKG, "TransGraph.PopupMenu.SnapToGrid") + ConstUI.GRID_SIZE + ")\tALT-HOME"); //$NON-NLS-1$ //$NON-NLS-2$
XulMenu men = (XulMenu) doc.getElementById("trans-graph-entry-sniff");
men.setDisabled(trans==null || trans.isRunning() == false); //$NON-NLS-1$
item = (XulMenuitem) doc.getElementById("trans-graph-entry-sniff-input"); //$NON-NLS-1$
item.setDisabled(trans==null || trans.isRunning() == false); //$NON-NLS-1$
item = (XulMenuitem) doc.getElementById("trans-graph-entry-sniff-output"); //$NON-NLS-1$
item.setDisabled(trans==null || trans.isRunning() == false); //$NON-NLS-1$
item = (XulMenuitem) doc.getElementById("trans-graph-entry-sniff-error"); //$NON-NLS-1$
item.setDisabled(!(stepMeta.supportsErrorHandling() && stepMeta.getStepErrorMeta()!=null && stepMeta.getStepErrorMeta().getTargetStep()!=null && trans!=null && trans.isRunning()));
XulMenu aMenu = (XulMenu) doc.getElementById("trans-graph-entry-align"); //$NON-NLS-1$
if (aMenu != null) {
aMenu.setDisabled(sels < 2);
}
item = (XulMenuitem) doc.getElementById("trans-graph-entry-data-movement-distribute"); //$NON-NLS-1$
item.setSelected(stepMeta.isDistributes());
item = (XulMenuitem) doc.getElementById("trans-graph-entry-data-movement-copy"); //$NON-NLS-1$
item.setSelected(!stepMeta.isDistributes());
item = (XulMenuitem) doc.getElementById("trans-graph-entry-hide"); //$NON-NLS-1$
item.setDisabled(!(stepMeta.isDrawn() && !transMeta.isStepUsedInTransHops(stepMeta)));
item = (XulMenuitem) doc.getElementById("trans-graph-entry-detach"); //$NON-NLS-1$
item.setDisabled(!transMeta.isStepUsedInTransHops(stepMeta));
item = (XulMenuitem) doc.getElementById("trans-graph-entry-errors"); //$NON-NLS-1$
item.setDisabled(!stepMeta.supportsErrorHandling());
ConstUI.displayMenu((Menu)menu.getManagedObject(), canvas);
}
} else {
final TransHopMeta hi = findHop(x, y);
if (hi != null) // We clicked on a HOP!
{
XulMenupopup menu = menuMap.get("trans-graph-hop"); //$NON-NLS-1$
if (menu != null) {
setCurrentHop(hi);
XulMenuitem item = (XulMenuitem) getXulDomContainer().getDocumentRoot().getElementById("trans-graph-hop-enabled"); //$NON-NLS-1$
if (item != null) {
if (hi.isEnabled()) {
item.setLabel(BaseMessages.getString(PKG, "TransGraph.PopupMenu.DisableHop")); //$NON-NLS-1$
} else {
item.setLabel(BaseMessages.getString(PKG, "TransGraph.PopupMenu.EnableHop")); //$NON-NLS-1$
}
}
ConstUI.displayMenu((Menu)menu.getManagedObject(), canvas);
}
} else {
// Clicked on the background: maybe we hit a note?
final NotePadMeta ni = transMeta.getNote(x, y);
setCurrentNote(ni);
if (ni != null) {
XulMenupopup menu = menuMap.get("trans-graph-note"); //$NON-NLS-1$
if (menu != null) {
ConstUI.displayMenu((Menu)menu.getManagedObject(), canvas);
}
} else {
XulMenupopup menu = menuMap.get("trans-graph-background"); //$NON-NLS-1$
if (menu != null) {
final String clipcontent = spoon.fromClipboard();
XulMenuitem item = (XulMenuitem) getXulDomContainer().getDocumentRoot().getElementById("trans-graph-background-paste"); //$NON-NLS-1$
if (item != null) {
item.setDisabled(clipcontent == null);
}
ConstUI.displayMenu((Menu)menu.getManagedObject(), canvas);
}
}
}
}
} catch (Throwable t) {
// TODO: fix this: log somehow, is IGNORED for now.
t.printStackTrace();
}
}
public void selectAll() {
spoon.editSelectAll();
}
public void clearSelection() {
spoon.editUnselectAll();
}
private boolean checkNumberOfCopies(TransMeta transMeta, StepMeta stepMeta) {
boolean enabled = true;
List<StepMeta> prevSteps = transMeta.findPreviousSteps(stepMeta);
for (StepMeta prevStep : prevSteps) {
// See what the target steps are.
// If one of the target steps is our original step, we can't start multiple copies
String[] targetSteps = prevStep.getStepMetaInterface().getStepIOMeta().getTargetStepnames();
if (targetSteps != null) {
for (int t = 0; t < targetSteps.length && enabled; t++) {
if (!Const.isEmpty(targetSteps[t]) && targetSteps[t].equalsIgnoreCase(stepMeta.getName()))
enabled = false;
}
}
}
return enabled;
}
private AreaOwner setToolTip(int x, int y, int screenX, int screenY) {
AreaOwner subject = null;
if (!spoon.getProperties().showToolTips())
return subject;
canvas.setToolTipText(null);
String newTip = null;
Image tipImage = null;
final TransHopMeta hi = findHop(x, y);
// check the area owner list...
StringBuffer tip = new StringBuffer();
AreaOwner areaOwner = getVisibleAreaOwner(x, y);
if (areaOwner!=null) {
switch (areaOwner.getAreaType()) {
case REMOTE_INPUT_STEP:
StepMeta step = (StepMeta) areaOwner.getParent();
tip.append("Remote input steps:").append(Const.CR).append("-----------------------").append(Const.CR); //$NON-NLS-1$//$NON-NLS-2$
for (RemoteStep remoteStep : step.getRemoteInputSteps()) {
tip.append(remoteStep.toString()).append(Const.CR);
}
break;
case REMOTE_OUTPUT_STEP:
step = (StepMeta) areaOwner.getParent();
tip.append("Remote output steps:").append(Const.CR).append("-----------------------").append(Const.CR); //$NON-NLS-1$ //$NON-NLS-2$
for (RemoteStep remoteStep : step.getRemoteOutputSteps()) {
tip.append(remoteStep.toString()).append(Const.CR);
}
break;
case STEP_PARTITIONING:
step = (StepMeta) areaOwner.getParent();
tip.append("Step partitioning:").append(Const.CR).append("-----------------------").append(Const.CR); //$NON-NLS-1$ //$NON-NLS-2$
tip.append(step.getStepPartitioningMeta().toString()).append(Const.CR);
if (step.getTargetStepPartitioningMeta() != null) {
tip.append(Const.CR).append(Const.CR).append("TARGET: " + step.getTargetStepPartitioningMeta().toString()).append(Const.CR); //$NON-NLS-1$
}
break;
case STEP_ERROR_ICON:
String log = (String) areaOwner.getParent();
tip.append(log);
tipImage = GUIResource.getInstance().getImageStepError();
break;
case HOP_COPY_ICON:
step = (StepMeta) areaOwner.getParent();
tip.append(BaseMessages.getString(PKG, "TransGraph.Hop.Tooltip.HopTypeCopy", step.getName(), Const.CR)); //$NON-NLS-1$
tipImage = GUIResource.getInstance().getImageCopyHop();
break;
case HOP_INFO_ICON:
StepMeta from = (StepMeta) areaOwner.getParent();
StepMeta to = (StepMeta) areaOwner.getOwner();
tip.append(BaseMessages.getString(PKG, "TransGraph.Hop.Tooltip.HopTypeInfo", to.getName(), from.getName(), Const.CR)); //$NON-NLS-1$
tipImage = GUIResource.getInstance().getImageInfoHop();
break;
case HOP_ERROR_ICON:
from = (StepMeta) areaOwner.getParent();
to = (StepMeta) areaOwner.getOwner();
areaOwner.getOwner();
tip.append(BaseMessages.getString(PKG, "TransGraph.Hop.Tooltip.HopTypeError", from.getName(), to.getName(), Const.CR)); //$NON-NLS-1$
tipImage = GUIResource.getInstance().getImageErrorHop();
break;
case HOP_INFO_STEP_COPIES_ERROR:
from = (StepMeta) areaOwner.getParent();
to = (StepMeta) areaOwner.getOwner();
tip.append(BaseMessages.getString(PKG, "TransGraph.Hop.Tooltip.InfoStepCopies", from.getName(), to.getName(), Const.CR)); //$NON-NLS-1$
tipImage = GUIResource.getInstance().getImageStepError();
break;
case STEP_INPUT_HOP_ICON:
// StepMeta subjectStep = (StepMeta) (areaOwner.getParent());
tip.append(BaseMessages.getString(PKG, "TransGraph.StepInputConnector.Tooltip")); //$NON-NLS-1$
tipImage = GUIResource.getInstance().getImageHopInput();
break;
case STEP_OUTPUT_HOP_ICON:
//subjectStep = (StepMeta) (areaOwner.getParent());
tip.append(BaseMessages.getString(PKG, "TransGraph.StepOutputConnector.Tooltip")); //$NON-NLS-1$
tipImage = GUIResource.getInstance().getImageHopOutput();
break;
case STEP_INFO_HOP_ICON:
// subjectStep = (StepMeta) (areaOwner.getParent());
// StreamInterface stream = (StreamInterface) areaOwner.getOwner();
StepIOMetaInterface ioMeta = (StepIOMetaInterface) areaOwner.getOwner();
tip.append(BaseMessages.getString(PKG, "TransGraph.StepInfoConnector.Tooltip")+Const.CR+ioMeta.toString()); //$NON-NLS-1$
tipImage = GUIResource.getInstance().getImageHopOutput();
break;
case STEP_TARGET_HOP_ICON:
StreamInterface stream = (StreamInterface) areaOwner.getOwner();
tip.append(stream.getDescription());
tipImage = GUIResource.getInstance().getImageHopOutput();
break;
case STEP_ERROR_HOP_ICON:
StepMeta stepMeta = (StepMeta)areaOwner.getParent();
if (stepMeta.supportsErrorHandling()) {
tip.append(BaseMessages.getString(PKG, "TransGraph.StepSupportsErrorHandling.Tooltip")); //$NON-NLS-1$
} else {
tip.append(BaseMessages.getString(PKG, "TransGraph.StepDoesNotSupportsErrorHandling.Tooltip")); //$NON-NLS-1$
}
tipImage = GUIResource.getInstance().getImageHopOutput();
break;
case STEP_EDIT_ICON:
stepMeta = (StepMeta) (areaOwner.getParent());
tip.append(BaseMessages.getString(PKG, "TransGraph.EditStep.Tooltip")); //$NON-NLS-1$
tipImage = GUIResource.getInstance().getImageEdit();
break;
}
}
if (hi != null) // We clicked on a HOP!
{
// Set the tooltip for the hop:
tip.append(Const.CR).append("Hop information: ").append(newTip = hi.toString()).append(Const.CR); //$NON-NLS-1$
}
if (tip.length() == 0) {
newTip = null;
} else {
newTip = tip.toString();
}
if (newTip == null) {
toolTip.hide();
if (hi != null) // We clicked on a HOP!
{
// Set the tooltip for the hop:
newTip = BaseMessages.getString(PKG, "TransGraph.Dialog.HopInfo") + Const.CR + BaseMessages.getString(PKG, "TransGraph.Dialog.HopInfo.SourceStep") + " " + hi.getFromStep().getName() + Const.CR //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
+ BaseMessages.getString(PKG, "TransGraph.Dialog.HopInfo.TargetStep") + " " + hi.getToStep().getName() + Const.CR + BaseMessages.getString(PKG, "TransGraph.Dialog.HopInfo.Status") + " " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
+ (hi.isEnabled() ? BaseMessages.getString(PKG, "TransGraph.Dialog.HopInfo.Enable") : BaseMessages.getString(PKG, "TransGraph.Dialog.HopInfo.Disable")); //$NON-NLS-1$ //$NON-NLS-2$
toolTip.setText(newTip);
if (hi.isEnabled())
toolTip.setImage(GUIResource.getInstance().getImageHop());
else
toolTip.setImage(GUIResource.getInstance().getImageDisabledHop());
toolTip.show(new org.eclipse.swt.graphics.Point(screenX, screenY));
} else {
newTip = null;
}
} else if (!newTip.equalsIgnoreCase(getToolTipText())) {
if (tipImage != null) {
toolTip.setImage(tipImage);
} else {
toolTip.setImage(GUIResource.getInstance().getImageSpoon());
}
toolTip.setText(newTip);
toolTip.hide();
toolTip.show(new org.eclipse.swt.graphics.Point(x, y));
}
return subject;
}
public AreaOwner getVisibleAreaOwner(int x, int y) {
for (int i=areaOwners.size()-1;i>=0;i
AreaOwner areaOwner = areaOwners.get(i);
if (areaOwner.contains(x, y)) {
return areaOwner;
}
}
return null;
}
public void delSelected(StepMeta stMeta) {
List<StepMeta> selection = transMeta.getSelectedSteps();
if (selection.size() == 0) {
spoon.delStep(transMeta, stMeta);
return;
}
// Get the list of steps that would be deleted
List<String> stepList = new ArrayList<String>();
for (int i = transMeta.nrSteps() - 1; i >= 0; i
StepMeta stepMeta = transMeta.getStep(i);
if (stepMeta.isSelected() || (stMeta != null && stMeta.equals(stepMeta))) {
stepList.add(stepMeta.getName());
}
}
// Create and display the delete confirmation dialog
MessageBox mb = new DeleteMessageBox(shell, BaseMessages.getString(PKG, "TransGraph.Dialog.Warning.DeleteSteps.Message"), //$NON-NLS-1$
stepList);
int result = mb.open();
if (result == SWT.YES) {
// Delete the steps
for (int i = transMeta.nrSteps() - 1; i >= 0; i
StepMeta stepMeta = transMeta.getStep(i);
if (stepMeta.isSelected() || (stMeta != null && stMeta.equals(stepMeta))) {
spoon.delStep(transMeta, stepMeta);
}
}
}
}
public void editDescription(StepMeta stepMeta) {
String title = BaseMessages.getString(PKG, "TransGraph.Dialog.StepDescription.Title"); //$NON-NLS-1$
String message = BaseMessages.getString(PKG, "TransGraph.Dialog.StepDescription.Message"); //$NON-NLS-1$
EnterTextDialog dd = new EnterTextDialog(shell, title, message, stepMeta.getDescription());
String d = dd.open();
if (d != null)
stepMeta.setDescription(d);
}
/**
* Display the input- or outputfields for a step.
*
* @param stepMeta The step (it's metadata) to query
* @param before set to true if you want to have the fields going INTO the step, false if you want to see all the
* fields that exit the step.
*/
private void inputOutputFields(StepMeta stepMeta, boolean before) {
spoon.refreshGraph();
transMeta.setRepository(spoon.rep);
SearchFieldsProgressDialog op = new SearchFieldsProgressDialog(transMeta, stepMeta, before);
try {
final ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell);
// Run something in the background to cancel active database queries, forecably if needed!
Runnable run = new Runnable() {
public void run() {
IProgressMonitor monitor = pmd.getProgressMonitor();
while (pmd.getShell() == null || (!pmd.getShell().isDisposed() && !monitor.isCanceled())) {
try {
Thread.sleep(250);
} catch (InterruptedException e) {
}
;
}
if (monitor.isCanceled()) // Disconnect and see what happens!
{
try {
transMeta.cancelQueries();
} catch (Exception e) {
}
;
}
}
};
// Dump the cancel looker in the background!
new Thread(run).start();
pmd.run(true, true, op);
} catch (InvocationTargetException e) {
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "TransGraph.Dialog.GettingFields.Title"), BaseMessages.getString(PKG, "TransGraph.Dialog.GettingFields.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InterruptedException e) {
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "TransGraph.Dialog.GettingFields.Title"), BaseMessages.getString(PKG, "TransGraph.Dialog.GettingFields.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
RowMetaInterface fields = op.getFields();
if (fields != null && fields.size() > 0) {
StepFieldsDialog sfd = new StepFieldsDialog(shell, transMeta, SWT.NONE, stepMeta.getName(), fields);
String sn = (String) sfd.open();
if (sn != null) {
StepMeta esi = transMeta.findStep(sn);
if (esi != null) {
editStep(esi);
}
}
} else {
MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION);
mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.CouldntFindFields.Message")); //$NON-NLS-1$
mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.CouldntFindFields.Title")); //$NON-NLS-1$
mb.open();
}
}
public void paintControl(PaintEvent e) {
Point area = getArea();
if (area.x == 0 || area.y == 0)
return; // nothing to do!
Display disp = shell.getDisplay();
Image img = getTransformationImage(disp, area.x, area.y, magnification);
e.gc.drawImage(img, 0, 0);
img.dispose();
// spoon.setShellText();
}
public Image getTransformationImage(Device device, int x, int y, float magnificationFactor) {
GCInterface gc = new SWTGC(device, new Point(x, y), iconsize);
TransPainter transPainter = new TransPainter( gc,
transMeta, new Point(x, y), new SwtScrollBar(hori), new SwtScrollBar(vert), candidate, drop_candidate,
selectionRegion,
areaOwners,
mouseOverSteps,
PropsUI.getInstance().getIconSize(),
PropsUI.getInstance().getLineWidth(),
PropsUI.getInstance().getCanvasGridSize(),
PropsUI.getInstance().getShadowSize(),
PropsUI.getInstance().isAntiAliasingEnabled(),
PropsUI.getInstance().getNoteFont().getName(),
PropsUI.getInstance().getNoteFont().getHeight()
);
transPainter.setMagnification(magnificationFactor);
transPainter.setStepLogMap(stepLogMap);
transPainter.setStartHopStep(startHopStep);
transPainter.setEndHopLocation(endHopLocation);
transPainter.setNoInputStep(noInputStep);
transPainter.setEndHopStep(endHopStep);
transPainter.setCandidateHopType(candidateHopType);
transPainter.setStartErrorHopStep(startErrorHopStep);
transPainter.setShowTargetStreamsStep(showTargetStreamsStep);
transPainter.buildTransformationImage();
Image img = (Image)gc.getImage();
return img;
}
protected Point getOffset() {
Point area = getArea();
Point max = transMeta.getMaximum();
Point thumb = getThumb(area, max);
return getOffset(thumb, area);
}
private void editStep(StepMeta stepMeta) {
spoon.editStep(transMeta, stepMeta);
}
private void editNote(NotePadMeta ni) {
NotePadMeta before = (NotePadMeta) ni.clone();
String title = BaseMessages.getString(PKG, "TransGraph.Dialog.EditNote.Title"); //$NON-NLS-1$
NotePadDialog dd = new NotePadDialog(shell, title, ni);
NotePadMeta n = dd.open();
if (n != null)
{
ni.setChanged();
ni.setNote(n.getNote());
ni.setFontName(n.getFontName());
ni.setFontSize(n.getFontSize());
ni.setFontBold(n.isFontBold());
ni.setFontItalic(n.isFontItalic());
// font color
ni.setFontColorRed(n.getFontColorRed());
ni.setFontColorGreen(n.getFontColorGreen());
ni.setFontColorBlue(n.getFontColorBlue());
// background color
ni.setBackGroundColorRed(n.getBackGroundColorRed());
ni.setBackGroundColorGreen(n.getBackGroundColorGreen());
ni.setBackGroundColorBlue(n.getBackGroundColorBlue());
// border color
ni.setBorderColorRed(n.getBorderColorRed());
ni.setBorderColorGreen(n.getBorderColorGreen());
ni.setBorderColorBlue(n.getBorderColorBlue());
ni.setDrawShadow(n.isDrawShadow());
ni.width = ConstUI.NOTE_MIN_SIZE;
ni.height = ConstUI.NOTE_MIN_SIZE;
NotePadMeta after = (NotePadMeta) ni.clone();
spoon.addUndoChange(transMeta, new NotePadMeta[] { before }, new NotePadMeta[] { after }, new int[] { transMeta
.indexOfNote(ni) });
spoon.refreshGraph();
}
}
private void editHop(TransHopMeta transHopMeta) {
String name = transHopMeta.toString();
if(log.isDebug()) log.logDebug(BaseMessages.getString(PKG, "TransGraph.Logging.EditingHop") + name); //$NON-NLS-1$
spoon.editHop(transMeta, transHopMeta);
}
private void newHop() {
List<StepMeta> selection = transMeta.getSelectedSteps();
if (selection.size()==2) {
StepMeta fr = selection.get(0);
StepMeta to = selection.get(1);
spoon.newHop(transMeta, fr, to);
}
}
private boolean pointOnLine(int x, int y, int line[]) {
int dx, dy;
int pm = HOP_SEL_MARGIN / 2;
boolean retval = false;
for (dx = -pm; dx <= pm && !retval; dx++) {
for (dy = -pm; dy <= pm && !retval; dy++) {
retval = pointOnThinLine(x + dx, y + dy, line);
}
}
return retval;
}
private boolean pointOnThinLine(int x, int y, int line[]) {
int x1 = line[0];
int y1 = line[1];
int x2 = line[2];
int y2 = line[3];
// Not in the square formed by these 2 points: ignore!
if (!(((x >= x1 && x <= x2) || (x >= x2 && x <= x1)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))))
return false;
double angle_line = Math.atan2(y2 - y1, x2 - x1) + Math.PI;
double angle_point = Math.atan2(y - y1, x - x1) + Math.PI;
// Same angle, or close enough?
if (angle_point >= angle_line - 0.01 && angle_point <= angle_line + 0.01)
return true;
return false;
}
private SnapAllignDistribute createSnapAllignDistribute() {
List<StepMeta> selection = transMeta.getSelectedSteps();
int[] indices = transMeta.getStepIndexes(selection);
return new SnapAllignDistribute(transMeta, selection, indices, spoon, this);
}
public void snaptogrid() {
snaptogrid(ConstUI.GRID_SIZE);
}
private void snaptogrid(int size) {
createSnapAllignDistribute().snaptogrid(size);
}
public void allignleft() {
createSnapAllignDistribute().allignleft();
}
public void allignright() {
createSnapAllignDistribute().allignright();
}
public void alligntop() {
createSnapAllignDistribute().alligntop();
}
public void allignbottom() {
createSnapAllignDistribute().allignbottom();
}
public void distributehorizontal() {
createSnapAllignDistribute().distributehorizontal();
}
public void distributevertical() {
createSnapAllignDistribute().distributevertical();
}
private void detach(StepMeta stepMeta) {
TransHopMeta hfrom = transMeta.findTransHopTo(stepMeta);
TransHopMeta hto = transMeta.findTransHopFrom(stepMeta);
if (hfrom != null && hto != null) {
if (transMeta.findTransHop(hfrom.getFromStep(), hto.getToStep()) == null) {
TransHopMeta hnew = new TransHopMeta(hfrom.getFromStep(), hto.getToStep());
transMeta.addTransHop(hnew);
spoon.addUndoNew(transMeta, new TransHopMeta[] { hnew }, new int[] { transMeta.indexOfTransHop(hnew) });
spoon.refreshTree();
}
}
if (hfrom != null) {
int fromidx = transMeta.indexOfTransHop(hfrom);
if (fromidx >= 0) {
transMeta.removeTransHop(fromidx);
spoon.refreshTree();
}
}
if (hto != null) {
int toidx = transMeta.indexOfTransHop(hto);
if (toidx >= 0) {
transMeta.removeTransHop(toidx);
spoon.refreshTree();
}
}
spoon.refreshTree();
redraw();
}
// Preview the selected steps...
public void preview() {
spoon.previewTransformation();
}
public void newProps() {
iconsize = spoon.props.getIconSize();
}
public String toString() {
return this.getClass().getName();
}
public EngineMetaInterface getMeta() {
return transMeta;
}
/**
* @param transMeta the transMeta to set
*/
public void setTransMeta(TransMeta transMeta) {
this.transMeta = transMeta;
}
// Change of step, connection, hop or note...
public void addUndoPosition(Object obj[], int pos[], Point prev[], Point curr[]) {
addUndoPosition(obj, pos, prev, curr, false);
}
// Change of step, connection, hop or note...
public void addUndoPosition(Object obj[], int pos[], Point prev[], Point curr[], boolean nextAlso) {
// It's better to store the indexes of the objects, not the objects itself!
transMeta.addUndo(obj, null, pos, prev, curr, TransMeta.TYPE_UNDO_POSITION, nextAlso);
spoon.setUndoMenu(transMeta);
}
public boolean applyChanges() throws KettleException {
return spoon.saveToFile(transMeta);
}
public boolean canBeClosed() {
return !transMeta.hasChanged();
}
public TransMeta getManagedObject() {
return transMeta;
}
public boolean hasContentChanged() {
return transMeta.hasChanged();
}
public List<CheckResultInterface> getRemarks() {
return remarks;
}
public void setRemarks(List<CheckResultInterface> remarks) {
this.remarks = remarks;
}
public List<DatabaseImpact> getImpact() {
return impact;
}
public void setImpact(List<DatabaseImpact> impact) {
this.impact = impact;
}
public boolean isImpactFinished() {
return impactFinished;
}
public void setImpactFinished(boolean impactHasRun) {
this.impactFinished = impactHasRun;
}
/**
* @return the lastMove
*/
public Point getLastMove() {
return lastMove;
}
public static boolean editProperties(TransMeta transMeta, Spoon spoon, Repository rep, boolean allowDirectoryChange) {
return editProperties(transMeta, spoon, rep, allowDirectoryChange, null);
}
public static boolean editProperties(TransMeta transMeta, Spoon spoon, Repository rep, boolean allowDirectoryChange,
TransDialog.Tabs currentTab) {
if (transMeta == null)
return false;
TransDialog tid = new TransDialog(spoon.getShell(), SWT.NONE, transMeta, rep, currentTab);
tid.setDirectoryChangeAllowed(allowDirectoryChange);
TransMeta ti = tid.open();
// Load shared objects
if (tid.isSharedObjectsFileChanged()) {
try {
SharedObjects sharedObjects = rep!=null ? rep.readTransSharedObjects(transMeta) : transMeta.readSharedObjects();
spoon.sharedObjectsFileMap.put(sharedObjects.getFilename(), sharedObjects);
} catch (KettleException e) {
new ErrorDialog(spoon.getShell(), BaseMessages.getString(PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Title"), //$NON-NLS-1$
BaseMessages.getString(PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Message", spoon.makeTabName(transMeta, true)), e); //$NON-NLS-1$
}
// If we added properties, add them to the variables too, so that they appear in the CTRL-SPACE variable completion.
spoon.setParametersAsVariablesInUI(transMeta, transMeta);
spoon.refreshTree();
spoon.delegates.tabs.renameTabs(); // cheap operation, might as will do it anyway
}
spoon.setShellText();
return ti != null;
}
public void openFile() {
spoon.openFile();
}
public void saveFile() throws KettleException {
spoon.saveFile();
}
public void saveFileAs() throws KettleException {
spoon.saveFileAs();
}
public void saveXMLFileToVfs() {
spoon.saveXMLFileToVfs();
}
public void printFile() {
spoon.printFile();
}
public void runTransformation() {
spoon.runFile();
}
public void pauseTransformation() {
pauseResume();
}
public void stopTransformation() {
stop();
}
public void previewFile() {
spoon.previewFile();
}
public void debugFile() {
spoon.debugFile();
}
public void transReplay() {
spoon.replayTransformation();
}
public void checkTrans() {
spoon.checkTrans();
}
public void analyseImpact() {
spoon.analyseImpact();
}
public void getSQL() {
spoon.getSQL();
}
public void exploreDatabase() {
spoon.exploreDatabase();
}
public boolean isExecutionResultsPaneVisible() {
return extraViewComposite != null && !extraViewComposite.isDisposed();
}
public void showExecutionResults() {
if (isExecutionResultsPaneVisible()) {
disposeExtraView();
} else {
addAllTabs();
}
}
public void browseVersionHistory() {
try {
if (spoon.rep.exists(transMeta.getName(), transMeta.getRepositoryDirectory(), RepositoryObjectType.TRANSFORMATION)) {
RepositoryRevisionBrowserDialogInterface dialog = RepositoryExplorerDialog.getVersionBrowserDialog(shell, spoon.rep, transMeta);
String versionLabel = dialog.open();
if (versionLabel!=null) {
spoon.loadObjectFromRepository(transMeta.getName(), transMeta.getRepositoryElementType(), transMeta.getRepositoryDirectory(), versionLabel);
}
} else {
MessageBox box = new MessageBox(shell, SWT.CLOSE | SWT.ICON_ERROR);
box.setText("Sorry"); //$NON-NLS-1$
box.setMessage("Can't find this transformation in the repository"); //$NON-NLS-1$
box.open();
}
} catch (Exception e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "TransGraph.VersionBrowserException.Title"), BaseMessages.getString(PKG, "TransGraph.VersionBrowserException.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/**
* If the extra tab view at the bottom is empty, we close it.
*/
public void checkEmptyExtraView() {
if (extraViewTabFolder.getItemCount() == 0) {
disposeExtraView();
}
}
private void disposeExtraView() {
extraViewComposite.dispose();
sashForm.layout();
sashForm.setWeights(new int[] { 100, });
XulToolbarbutton button = (XulToolbarbutton) toolbar.getElementById("trans-show-results"); //$NON-NLS-1$
button.setTooltiptext(BaseMessages.getString(PKG, "Spoon.Tooltip.ShowExecutionResults")); //$NON-NLS-1$
ToolItem toolItem = (ToolItem) button.getManagedObject();
toolItem.setImage(GUIResource.getInstance().getImageShowResults());
}
private void minMaxExtraView() {
// What is the state?
boolean maximized = sashForm.getMaximizedControl() != null;
if (maximized) {
// Minimize
sashForm.setMaximizedControl(null);
minMaxButton.setImage(GUIResource.getInstance().getImageMaximizePanel());
minMaxButton.setToolTipText(BaseMessages.getString(PKG, "TransGraph.ExecutionResultsPanel.MaxButton.Tooltip")); //$NON-NLS-1$
} else {
// Maximize
sashForm.setMaximizedControl(extraViewComposite);
minMaxButton.setImage(GUIResource.getInstance().getImageMinimizePanel());
minMaxButton.setToolTipText(BaseMessages.getString(PKG, "TransGraph.ExecutionResultsPanel.MinButton.Tooltip")); //$NON-NLS-1$
}
}
/**
* @return the toolbar
*/
public XulToolbar getToolbar() {
return toolbar;
}
/**
* @param toolbar the toolbar to set
*/
public void setToolbar(XulToolbar toolbar) {
this.toolbar = toolbar;
}
private Label closeButton;
private Label minMaxButton;
/**
* Add an extra view to the main composite SashForm
*/
public void addExtraView() {
extraViewComposite = new Composite(sashForm, SWT.NONE);
FormLayout extraCompositeFormLayout = new FormLayout();
extraCompositeFormLayout.marginWidth = 2;
extraCompositeFormLayout.marginHeight = 2;
extraViewComposite.setLayout(extraCompositeFormLayout);
// Put a close and max button to the upper right corner...
closeButton = new Label(extraViewComposite, SWT.NONE);
closeButton.setImage(GUIResource.getInstance().getImageClosePanel());
closeButton.setToolTipText(BaseMessages.getString(PKG, "TransGraph.ExecutionResultsPanel.CloseButton.Tooltip")); //$NON-NLS-1$
FormData fdClose = new FormData();
fdClose.right = new FormAttachment(100, 0);
fdClose.top = new FormAttachment(0, 0);
closeButton.setLayoutData(fdClose);
closeButton.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
disposeExtraView();
}
});
minMaxButton = new Label(extraViewComposite, SWT.NONE);
minMaxButton.setImage(GUIResource.getInstance().getImageMaximizePanel());
minMaxButton.setToolTipText(BaseMessages.getString(PKG, "TransGraph.ExecutionResultsPanel.MaxButton.Tooltip")); //$NON-NLS-1$
FormData fdMinMax = new FormData();
fdMinMax.right = new FormAttachment(closeButton, -Const.MARGIN);
fdMinMax.top = new FormAttachment(0, 0);
minMaxButton.setLayoutData(fdMinMax);
minMaxButton.addMouseListener(new MouseAdapter() {
public void mouseDown(MouseEvent e) {
minMaxExtraView();
}
});
// Add a label at the top: Results
Label wResultsLabel = new Label(extraViewComposite, SWT.LEFT);
wResultsLabel.setFont(GUIResource.getInstance().getFontMediumBold());
wResultsLabel.setBackground(GUIResource.getInstance().getColorLightGray());
wResultsLabel.setText(BaseMessages.getString(PKG, "TransLog.ResultsPanel.NameLabel")); //$NON-NLS-1$
FormData fdResultsLabel = new FormData();
fdResultsLabel.left = new FormAttachment(0, 0);
fdResultsLabel.right = new FormAttachment(minMaxButton, -Const.MARGIN);
fdResultsLabel.top = new FormAttachment(0, 0);
wResultsLabel.setLayoutData(fdResultsLabel);
// Add a tab folder ...
extraViewTabFolder = new CTabFolder(extraViewComposite, SWT.MULTI);
spoon.props.setLook(extraViewTabFolder, Props.WIDGET_STYLE_TAB);
extraViewTabFolder.addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent arg0) {
if (sashForm.getMaximizedControl() == null) {
sashForm.setMaximizedControl(extraViewComposite);
} else {
sashForm.setMaximizedControl(null);
}
}
});
FormData fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.top = new FormAttachment(wResultsLabel, Const.MARGIN);
fdTabFolder.bottom = new FormAttachment(100, 0);
extraViewTabFolder.setLayoutData(fdTabFolder);
sashForm.setWeights(new int[] { 60, 40, });
}
public void checkErrors() {
if (trans != null) {
if (!trans.isFinished()) {
if (trans.getErrors() != 0) {
trans.killAll();
}
}
}
}
public synchronized void start(TransExecutionConfiguration executionConfiguration) throws KettleException {
// Auto save feature...
if (transMeta.hasChanged()) {
if (spoon.props.getAutoSave()) {
spoon.saveToFile(transMeta);
} else {
MessageDialogWithToggle md = new MessageDialogWithToggle(
shell,
BaseMessages.getString(PKG, "TransLog.Dialog.FileHasChanged.Title"), //$NON-NLS-1$
null,
BaseMessages.getString(PKG, "TransLog.Dialog.FileHasChanged1.Message") + Const.CR + BaseMessages.getString(PKG, "TransLog.Dialog.FileHasChanged2.Message") + Const.CR, //$NON-NLS-1$ //$NON-NLS-2$
MessageDialog.QUESTION, new String[] {
BaseMessages.getString(PKG, "System.Button.Yes"), BaseMessages.getString(PKG, "System.Button.No") }, //$NON-NLS-1$ //$NON-NLS-2$
0, BaseMessages.getString(PKG, "TransLog.Dialog.Option.AutoSaveTransformation"), //$NON-NLS-1$
spoon.props.getAutoSave());
int answer = md.open();
if ((answer & 0xFF) == 0) {
spoon.saveToFile(transMeta);
}
spoon.props.setAutoSave(md.getToggleState());
}
}
if (((transMeta.getName() != null && transMeta.getObjectId() != null && spoon.rep != null) || // Repository available & name / id set
(transMeta.getFilename() != null && spoon.rep == null) // No repository & filename set
)
&& !transMeta.hasChanged() // Didn't change
) {
if (trans == null || (trans != null && !running)) {
try {
// Set the requested logging level..
DefaultLogLevel.setLogLevel(executionConfiguration.getLogLevel());
transMeta.injectVariables(executionConfiguration.getVariables());
// Set the named parameters
Map<String, String> paramMap = executionConfiguration.getParams();
Set<String> keys = paramMap.keySet();
for ( String key : keys ) {
transMeta.setParameterValue(key, Const.NVL(paramMap.get(key), "")); //$NON-NLS-1$
}
transMeta.activateParameters();
// Do we need to clear the log before running?
if (executionConfiguration.isClearingLog()) {
transLogDelegate.clearLog();
}
// Also make sure to clear the log entries in the central log store & registry
if (trans!=null) {
CentralLogStore.discardLines(trans.getLogChannelId(), true);
}
// Important: even though transMeta is passed to the Trans constructor, it is not the same object as is in memory
// To be able to completely test this, we need to run it as we would normally do in pan
trans = new Trans(transMeta, spoon.rep, transMeta.getName(), transMeta.getRepositoryDirectory().getPath(), transMeta.getFilename());
trans.setLogLevel(executionConfiguration.getLogLevel());
trans.setReplayDate(executionConfiguration.getReplayDate());
trans.setRepository(executionConfiguration.getRepository());
trans.setMonitored(true);
log.logBasic(BaseMessages.getString(PKG, "TransLog.Log.TransformationOpened")); //$NON-NLS-1$
} catch (KettleException e) {
trans = null;
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "TransLog.Dialog.ErrorOpeningTransformation.Title"), BaseMessages.getString(PKG, "TransLog.Dialog.ErrorOpeningTransformation.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
if (trans != null) {
Map<String, String> arguments = executionConfiguration.getArguments();
final String args[];
if (arguments != null)
args = convertArguments(arguments);
else
args = null;
log.logMinimal(BaseMessages.getString(PKG, "TransLog.Log.LaunchingTransformation") + trans.getTransMeta().getName() + "]..."); //$NON-NLS-1$ //$NON-NLS-2$
trans.setSafeModeEnabled(executionConfiguration.isSafeModeEnabled());
// Launch the step preparation in a different thread.
// That way Spoon doesn't block anymore and that way we can follow the progress of the initialization
final Thread parentThread = Thread.currentThread();
shell.getDisplay().asyncExec(new Runnable() {
public void run() {
addAllTabs();
prepareTrans(parentThread, args);
}
});
log.logMinimal(BaseMessages.getString(PKG, "TransLog.Log.StartedExecutionOfTransformation")); //$NON-NLS-1$
setControlStates();
}
} else {
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(BaseMessages.getString(PKG, "TransLog.Dialog.DoNoStartTransformationTwice.Title")); //$NON-NLS-1$
m.setMessage(BaseMessages.getString(PKG, "TransLog.Dialog.DoNoStartTransformationTwice.Message")); //$NON-NLS-1$
m.open();
}
} else {
if (transMeta.hasChanged()) {
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(BaseMessages.getString(PKG, "TransLog.Dialog.SaveTransformationBeforeRunning.Title")); //$NON-NLS-1$
m.setMessage(BaseMessages.getString(PKG, "TransLog.Dialog.SaveTransformationBeforeRunning.Message")); //$NON-NLS-1$
m.open();
} else if (spoon.rep != null && transMeta.getName() == null) {
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(BaseMessages.getString(PKG, "TransLog.Dialog.GiveTransformationANameBeforeRunning.Title")); //$NON-NLS-1$
m.setMessage(BaseMessages.getString(PKG, "TransLog.Dialog.GiveTransformationANameBeforeRunning.Message")); //$NON-NLS-1$
m.open();
} else {
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(BaseMessages.getString(PKG, "TransLog.Dialog.SaveTransformationBeforeRunning2.Title")); //$NON-NLS-1$
m.setMessage(BaseMessages.getString(PKG, "TransLog.Dialog.SaveTransformationBeforeRunning2.Message")); //$NON-NLS-1$
m.open();
}
}
}
public void addAllTabs() {
CTabItem tabItemSelection = null;
if (extraViewTabFolder!=null && !extraViewTabFolder.isDisposed()) {
tabItemSelection = extraViewTabFolder.getSelection();
}
transHistoryDelegate.addTransHistory();
transLogDelegate.addTransLog();
transGridDelegate.addTransGrid();
transPerfDelegate.addTransPerf();
if (tabItemSelection!=null) {
extraViewTabFolder.setSelection(tabItemSelection);
} else {
extraViewTabFolder.setSelection(transGridDelegate.getTransGridTab());
}
XulToolbarbutton button = (XulToolbarbutton) toolbar.getElementById("trans-show-results"); //$NON-NLS-1$
button.setTooltiptext(BaseMessages.getString(PKG, "Spoon.Tooltip.HideExecutionResults")); //$NON-NLS-1$
ToolItem toolItem = (ToolItem) button.getManagedObject();
toolItem.setImage(GUIResource.getInstance().getImageHideResults());
}
public synchronized void debug(TransExecutionConfiguration executionConfiguration, TransDebugMeta transDebugMeta) {
if (!running) {
try {
this.lastTransDebugMeta = transDebugMeta;
log.setLogLevel(executionConfiguration.getLogLevel());
if(log.isDetailed()) log.logDetailed(BaseMessages.getString(PKG, "TransLog.Log.DoPreview")); //$NON-NLS-1$
String[] args = null;
Map<String, String> arguments = executionConfiguration.getArguments();
if (arguments != null) {
args = convertArguments(arguments);
}
transMeta.injectVariables(executionConfiguration.getVariables());
// Set the named parameters
Map<String, String> paramMap = executionConfiguration.getParams();
Set<String> keys = paramMap.keySet();
for ( String key : keys ) {
transMeta.setParameterValue(key, Const.NVL(paramMap.get(key), "")); //$NON-NLS-1$
}
transMeta.activateParameters();
// Do we need to clear the log before running?
if (executionConfiguration.isClearingLog()) {
transLogDelegate.clearLog();
}
// Create a new transformation to execution
trans = new Trans(transMeta);
trans.setSafeModeEnabled(executionConfiguration.isSafeModeEnabled());
trans.setPreview(true);
trans.prepareExecution(args);
// Add the row listeners to the allocated threads
transDebugMeta.addRowListenersToTransformation(trans);
// What method should we call back when a break-point is hit?
transDebugMeta.addBreakPointListers(new BreakPointListener() {
public void breakPointHit(TransDebugMeta transDebugMeta, StepDebugMeta stepDebugMeta,
RowMetaInterface rowBufferMeta, List<Object[]> rowBuffer) {
showPreview(transDebugMeta, stepDebugMeta, rowBufferMeta, rowBuffer);
}
});
// Start the threads for the steps...
startThreads();
debug = true;
// Show the execution results view...
shell.getDisplay().asyncExec(new Runnable() {
public void run() {
addAllTabs();
}
});
} catch (Exception e) {
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "TransLog.Dialog.UnexpectedErrorDuringPreview.Title"), BaseMessages.getString(PKG, "TransLog.Dialog.UnexpectedErrorDuringPreview.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING);
m.setText(BaseMessages.getString(PKG, "TransLog.Dialog.DoNoPreviewWhileRunning.Title")); //$NON-NLS-1$
m.setMessage(BaseMessages.getString(PKG, "TransLog.Dialog.DoNoPreviewWhileRunning.Message")); //$NON-NLS-1$
m.open();
}
checkErrorVisuals();
}
public synchronized void showPreview(final TransDebugMeta transDebugMeta, final StepDebugMeta stepDebugMeta,
final RowMetaInterface rowBufferMeta, final List<Object[]> rowBuffer) {
shell.getDisplay().asyncExec(new Runnable() {
public void run() {
if (isDisposed())
return;
spoon.enableMenus();
// The transformation is now paused, indicate this in the log dialog...
pausing = true;
setControlStates();
checkErrorVisuals();
PreviewRowsDialog previewRowsDialog = new PreviewRowsDialog(shell, transMeta, SWT.APPLICATION_MODAL,
stepDebugMeta.getStepMeta().getName(), rowBufferMeta, rowBuffer);
previewRowsDialog.setProposingToGetMoreRows(true);
previewRowsDialog.setProposingToStop(true);
previewRowsDialog.open();
if (previewRowsDialog.isAskingForMoreRows()) {
// clear the row buffer.
// That way if you click resume, you get the next N rows for the step :-)
rowBuffer.clear();
// Resume running: find more rows...
pauseResume();
}
if (previewRowsDialog.isAskingToStop()) {
// Stop running
stop();
}
}
});
}
private String[] convertArguments(Map<String, String> arguments) {
String[] argumentNames = arguments.keySet().toArray(new String[arguments.size()]);
Arrays.sort(argumentNames);
String args[] = new String[argumentNames.length];
for (int i = 0; i < args.length; i++) {
String argumentName = argumentNames[i];
args[i] = arguments.get(argumentName);
}
return args;
}
public void stop() {
if (running && !halting) {
halting = true;
trans.stopAll();
log.logMinimal(BaseMessages.getString(PKG, "TransLog.Log.ProcessingOfTransformationStopped")); //$NON-NLS-1$
running = false;
initialized = false;
halted = false;
halting = false;
setControlStates();
transMeta.setInternalKettleVariables(); // set the original vars back as they may be changed by a mapping
}
}
public synchronized void pauseResume() {
if (running) {
// Get the pause toolbar item
if (!pausing) {
pausing = true;
trans.pauseRunning();
setControlStates();
} else {
pausing = false;
trans.resumeRunning();
setControlStates();
}
}
}
private boolean controlDisposed(XulToolbarbutton button) {
if (button.getManagedObject() instanceof Widget) {
Widget widget = (Widget) button.getManagedObject();
return widget.isDisposed();
}
return false;
}
public synchronized void setControlStates() {
if (getDisplay().isDisposed()) return;
if (((Control)toolbar.getManagedObject()).isDisposed()) return;
getDisplay().asyncExec(new Runnable() {
public void run() {
// Start/Run button...
XulToolbarbutton runButton = (XulToolbarbutton) toolbar.getElementById("process-run"); //$NON-NLS-1$
if (runButton != null && !controlDisposed(runButton)) {
runButton.setDisabled(running);
}
// Pause button...
XulToolbarbutton pauseButton = (XulToolbarbutton) toolbar.getElementById("trans-pause"); //$NON-NLS-1$
if (pauseButton != null && !controlDisposed(pauseButton)) {
pauseButton.setDisabled(!running);
pauseButton.setLabel(pausing ? RESUME_TEXT : PAUSE_TEXT);
pauseButton.setTooltiptext(pausing ? BaseMessages.getString(PKG, "Spoon.Tooltip.ResumeTranformation") : BaseMessages //$NON-NLS-1$
.getString(PKG, "Spoon.Tooltip.PauseTranformation")); //$NON-NLS-1$
}
// Stop button...
XulToolbarbutton stopButton = (XulToolbarbutton) toolbar.getElementById("trans-stop"); //$NON-NLS-1$
if (stopButton != null && !controlDisposed(stopButton)) {
stopButton.setDisabled(!running);
}
// Debug button...
XulToolbarbutton debugButton = (XulToolbarbutton) toolbar.getElementById("trans-debug"); //$NON-NLS-1$
if (debugButton != null && !controlDisposed(debugButton)) {
debugButton.setDisabled(running);
}
// Preview button...
XulToolbarbutton previewButton = (XulToolbarbutton) toolbar.getElementById("trans-preview"); //$NON-NLS-1$
if (previewButton != null && !controlDisposed(previewButton)) {
previewButton.setDisabled(running);
}
}
});
}
private synchronized void prepareTrans(final Thread parentThread, final String[] args) {
Runnable runnable = new Runnable() {
public void run() {
try {
trans.prepareExecution(args);
initialized = true;
} catch (KettleException e) {
log.logError(trans.getName()+": preparing transformation execution failed", e); //$NON-NLS-1$
checkErrorVisuals();
}
halted = trans.hasHaltedSteps();
if (trans.isReadyToStart()) {
checkStartThreads();// After init, launch the threads.
} else {
initialized = false;
running = false;
checkErrorVisuals();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
private void checkStartThreads() {
if (initialized && !running && trans != null) {
startThreads();
}
}
private synchronized void startThreads() {
running = true;
try {
// Add a listener to the transformation.
// If the transformation is done, we want to do the end processing, etc.
trans.addTransListener(new TransListener() {
public void transFinished(Trans trans) {
checkTransEnded();
checkErrorVisuals();
}
});
trans.startThreads();
setControlStates();
} catch (KettleException e) {
log.logError("Error starting step threads", e); //$NON-NLS-1$
checkErrorVisuals();
}
// See if we have to fire off the performance graph updater etc.
getDisplay().asyncExec(new Runnable() {
public void run() {
if (transPerfDelegate.getTransPerfTab() != null) {
// If there is a tab open, try to the correct content on there now
transPerfDelegate.setupContent();
transPerfDelegate.layoutPerfComposite();
}
}
});
}
private void checkTransEnded() {
if (trans != null) {
if (trans.isFinished() && (running || halted)) {
log.logMinimal(BaseMessages.getString(PKG, "TransLog.Log.TransformationHasFinished")); //$NON-NLS-1$
running = false;
initialized = false;
halted = false;
halting = false;
if (spoonHistoryRefresher != null)
spoonHistoryRefresher.markRefreshNeeded();
setControlStates();
// OK, also see if we had a debugging session going on.
// If so and we didn't hit a breakpoint yet, display the show
// preview dialog...
if (debug && lastTransDebugMeta != null && lastTransDebugMeta.getTotalNumberOfHits() == 0) {
debug = false;
showLastPreviewResults();
}
debug = false;
checkErrorVisuals();
shell.getDisplay().asyncExec(new Runnable() {
public void run() {
redraw();
}
});
}
}
}
private void checkErrorVisuals() {
if (trans.getErrors() > 0) {
// Get the logging text and filter it out. Store it in the stepLogMap...
stepLogMap = new HashMap<StepMeta, String>();
shell.getDisplay().syncExec(new Runnable() {
public void run() {
for (StepMetaDataCombi combi : trans.getSteps()) {
if (combi.step.getErrors() > 0) {
String channelId = combi.step.getLogChannel().getLogChannelId();
List<LoggingEvent> eventList = CentralLogStore.getLogBufferFromTo(channelId, false, 0, CentralLogStore.getLastBufferLineNr());
StringBuilder logText = new StringBuilder();
for (LoggingEvent event : eventList) {
Object message = event.getMessage();
if (message instanceof LogMessage) {
LogMessage logMessage = (LogMessage) message;
if (logMessage.isError()) {
logText.append(logMessage.getMessage()).append(Const.CR);
}
}
}
stepLogMap.put(combi.stepMeta, logText.toString());
}
}
}
});
} else {
stepLogMap = null;
}
// Redraw the canvas to show the error icons etc.
shell.getDisplay().asyncExec(new Runnable() {
public void run() {
redraw();
}
});
}
public synchronized void showLastPreviewResults() {
if (lastTransDebugMeta == null || lastTransDebugMeta.getStepDebugMetaMap().isEmpty())
return;
final List<String> stepnames = new ArrayList<String>();
final List<RowMetaInterface> rowMetas = new ArrayList<RowMetaInterface>();
final List<List<Object[]>> rowBuffers = new ArrayList<List<Object[]>>();
// Assemble the buffers etc in the old style...
for (StepMeta stepMeta : lastTransDebugMeta.getStepDebugMetaMap().keySet()) {
StepDebugMeta stepDebugMeta = lastTransDebugMeta.getStepDebugMetaMap().get(stepMeta);
stepnames.add(stepMeta.getName());
rowMetas.add(stepDebugMeta.getRowBufferMeta());
rowBuffers.add(stepDebugMeta.getRowBuffer());
}
getDisplay().asyncExec(new Runnable() {
public void run() {
EnterPreviewRowsDialog dialog = new EnterPreviewRowsDialog(shell, SWT.NONE, stepnames, rowMetas, rowBuffers);
dialog.open();
}
});
}
/**
* Open the transformation mentioned in the mapping...
*/
public void openMapping() {
try {
MappingMeta meta = (MappingMeta) this.currentStep.getStepMetaInterface();
TransMeta mappingMeta = MappingMeta.loadMappingMeta(meta, spoon.rep, transMeta);
mappingMeta.clearChanged();
spoon.addTransGraph(mappingMeta);
TransGraph subTransGraph = spoon.getActiveTransGraph();
attachActiveTrans(subTransGraph, this.currentStep);
} catch(Exception e) {
new ErrorDialog(shell, BaseMessages.getString(PKG, "TransGraph.Exception.UnableToLoadMapping.Title"), BaseMessages.getString(PKG, "TransGraph.Exception.UnableToLoadMapping.Message"), e); //$NON-NLS-1$//$NON-NLS-2$
}
}
/**
* Finds the last active transformation in the running job to the opened transMeta
*
* @param transGraph
* @param jobEntryCopy
*/
private void attachActiveTrans(TransGraph transGraph, StepMeta stepMeta) {
if (trans!=null && transGraph!=null) {
Trans subTransformation = trans.getActiveSubtransformations().get(stepMeta.getName());
transGraph.setTrans(subTransformation);
if (!transGraph.isExecutionResultsPaneVisible()) {
transGraph.showExecutionResults();
}
transGraph.setControlStates();
}
}
/**
* @return the running
*/
public boolean isRunning() {
return running;
}
/**
* @param running the running to set
*/
public void setRunning(boolean running) {
this.running = running;
}
/**
* @return the lastTransDebugMeta
*/
public TransDebugMeta getLastTransDebugMeta() {
return lastTransDebugMeta;
}
/**
* @return the halting
*/
public boolean isHalting() {
return halting;
}
/**
* @param halting the halting to set
*/
public void setHalting(boolean halting) {
this.halting = halting;
}
/**
* @return the stepLogMap
*/
public Map<StepMeta, String> getStepLogMap() {
return stepLogMap;
}
/**
* @param stepLogMap
* the stepLogMap to set
*/
public void setStepLogMap(Map<StepMeta, String> stepLogMap) {
this.stepLogMap = stepLogMap;
}
public void dumpLoggingRegistry() {
LoggingRegistry registry = LoggingRegistry.getInstance();
Map<String, LoggingObjectInterface> loggingMap = registry.getMap();
for (LoggingObjectInterface loggingObject : loggingMap.values()) {
System.out.println(loggingObject.getLogChannelId()+" - "+loggingObject.getObjectName()+" - "+loggingObject.getObjectType()); //$NON-NLS-1$ //$NON-NLS-2$
}
}
public HasLogChannelInterface getLogChannelProvider() {
return trans;
}
public synchronized void setTrans(Trans trans) {
this.trans = trans;
if (trans!=null) {
pausing = trans.isPaused();
initialized = trans.isInitializing();
running = trans.isRunning();
halted = trans.isStopped();
}
}
public void sniffInput() {
sniff(true, false, false);
}
public void sniffOutput() {
sniff(false, true, false);
}
public void sniffError() {
sniff(false, false, true);
}
public void sniff(final boolean input, final boolean output, final boolean error) {
StepMeta stepMeta = getCurrentStep();
if(stepMeta == null || trans == null){
return;
}
final StepInterface runThread = trans.findRunThread(stepMeta.getName());
if (runThread!=null) {
List<Object[]> rows = new ArrayList<Object[]>();
final PreviewRowsDialog dialog = new PreviewRowsDialog(shell, trans, SWT.NONE, stepMeta.getName(), null, rows);
dialog.setDynamic(true);
// Add a row listener that sends the rows over to the dialog...
final RowListener rowListener = new RowListener() {
public void rowReadEvent(RowMetaInterface rowMeta, Object[] row) throws KettleStepException {
if (input) {
try {
dialog.addDataRow(rowMeta, rowMeta.cloneRow(row));
} catch (KettleValueException e) {
throw new KettleStepException(e);
}
}
}
public void rowWrittenEvent(RowMetaInterface rowMeta, Object[] row) throws KettleStepException {
if (output) {
try {
dialog.addDataRow(rowMeta, rowMeta.cloneRow(row));
} catch (KettleValueException e) {
throw new KettleStepException(e);
}
}
}
public void errorRowWrittenEvent(RowMetaInterface rowMeta, Object[] row) throws KettleStepException {
if (error) {
try {
dialog.addDataRow(rowMeta, rowMeta.cloneRow(row));
} catch (KettleValueException e) {
throw new KettleStepException(e);
}
}
}
};
// When the dialog is closed, make sure to remove the listener!
dialog.addDialogClosedListener(new DialogClosedListener() {
public void dialogClosed() {
runThread.removeRowListener(rowListener);
}
});
// Open the dialog in a separate thread to make sure it doesn't block
getDisplay().asyncExec(new Runnable() {
public void run() {
dialog.open();
}
});
runThread.addRowListener(rowListener);
}
}
/* (non-Javadoc)
* @see org.pentaho.ui.xul.impl.XulEventHandler#getName()
*/
public String getName() {
return "transgraph"; //$NON-NLS-1$
}
/* (non-Javadoc)
* @see org.pentaho.ui.xul.impl.XulEventHandler#getXulDomContainer()
*/
public XulDomContainer getXulDomContainer() {
return xulDomContainer;
}
/* (non-Javadoc)
* @see org.pentaho.ui.xul.impl.XulEventHandler#setName(java.lang.String)
*/
public void setName(String arg0) {
}
/* (non-Javadoc)
* @see org.pentaho.ui.xul.impl.XulEventHandler#setXulDomContainer(org.pentaho.ui.xul.XulDomContainer)
*/
public void setXulDomContainer(XulDomContainer xulDomContainer) {
this.xulDomContainer = xulDomContainer;
}
public boolean canHandleSave() {
return true;
}
@Override
public int showChangedWarning() throws KettleException {
return showChangedWarning(transMeta.getName());
}
}
|
package jsettlers.logic.movable;
import java.io.Serializable;
import jsettlers.algorithms.path.Path;
import jsettlers.common.material.EMaterialType;
import jsettlers.common.material.ESearchType;
import jsettlers.common.movable.EAction;
import jsettlers.common.movable.EDirection;
import jsettlers.common.movable.EMovableType;
import jsettlers.common.position.ShortPoint2D;
import jsettlers.logic.movable.interfaces.AbstractStrategyGrid;
import jsettlers.logic.movable.interfaces.IAttackable;
import jsettlers.logic.movable.strategies.BearerMovableStrategy;
import jsettlers.logic.movable.strategies.BricklayerStrategy;
import jsettlers.logic.movable.strategies.BuildingWorkerStrategy;
import jsettlers.logic.movable.strategies.DiggerStrategy;
import jsettlers.logic.movable.strategies.soldiers.BowmanStrategy;
import jsettlers.logic.movable.strategies.soldiers.InfantryStrategy;
import jsettlers.logic.movable.strategies.specialists.DummySpecialistStrategy;
import jsettlers.logic.movable.strategies.specialists.GeologistStrategy;
import jsettlers.logic.movable.strategies.specialists.PioneerStrategy;
import jsettlers.logic.player.Player;
/**
* Abstract super class of all movable strategies.
*
* @author Andreas Eberle
*
*/
public abstract class MovableStrategy implements Serializable {
private static final long serialVersionUID = 3135655342562634378L;
private final Movable movable;
protected MovableStrategy(Movable movable) {
this.movable = movable;
}
public static MovableStrategy getStrategy(Movable movable, EMovableType movableType) {
switch (movableType) {
case BEARER:
return new BearerMovableStrategy(movable);
case SWORDSMAN_L1:
case SWORDSMAN_L2:
case SWORDSMAN_L3:
case PIKEMAN_L1:
case PIKEMAN_L2:
case PIKEMAN_L3:
return new InfantryStrategy(movable, movableType);
case BOWMAN_L1:
case BOWMAN_L2:
case BOWMAN_L3:
return new BowmanStrategy(movable, movableType);
case BAKER:
case CHARCOAL_BURNER:
case FARMER:
case FISHERMAN:
case FORESTER:
case MELTER:
case MILLER:
case MINER:
case PIG_FARMER:
case LUMBERJACK:
case SAWMILLER:
case SLAUGHTERER:
case SMITH:
case STONECUTTER:
case WATERWORKER:
return new BuildingWorkerStrategy(movable, movableType);
case DIGGER:
return new DiggerStrategy(movable);
case BRICKLAYER:
return new BricklayerStrategy(movable);
case PIONEER:
return new PioneerStrategy(movable);
case GEOLOGIST:
return new GeologistStrategy(movable);
case THIEF:
return new DummySpecialistStrategy(movable);
default:
assert false : "requested movableType: " + movableType + " but have no strategy for this type!";
return null;
}
}
protected void action() {
}
protected final void convertTo(EMovableType movableType) {
movable.convertTo(movableType);
}
protected final EMaterialType setMaterial(EMaterialType materialType) {
return movable.setMaterial(materialType);
}
protected final void playAction(EAction movableAction, float duration) { // TODO @Andreas : rename EAction to EMovableAction
movable.playAction(movableAction, duration);
}
protected final void lookInDirection(EDirection direction) {
movable.lookInDirection(direction);
}
protected final boolean goToPos(ShortPoint2D targetPos) {
return movable.goToPos(targetPos);
}
protected final AbstractStrategyGrid getStrategyGrid() {
return movable.getStrategyGrid();
}
/**
* Tries to go a step in the given direction.
*
* @param direction
* direction to go
* @return true if the step can and will immediately be executed. <br>
* false if the target position is generally blocked or a movable occupies that position.
*/
protected final boolean goInDirection(EDirection direction) {
return movable.goInDirection(direction);
}
/**
* Forces the movable to go a step in the given direction (if it is not blocked).
*
* @param direction
* direction to go
*/
protected final void forceGoInDirection(EDirection direction) {
movable.forceGoInDirection(direction);
}
public final void setPosition(ShortPoint2D pos) {
movable.setPos(pos);
}
protected final void setVisible(boolean visible) {
movable.setVisible(visible);
}
/**
*
* @param dijkstra
* if true, dijkstra algorithm is used<br>
* if false, in area finder is used.
* @param centerX
* @param centerY
* @param radius
* @param searchType
* @return
*/
protected final boolean preSearchPath(boolean dijkstra, short centerX, short centerY, short radius, ESearchType searchType) {
return movable.preSearchPath(dijkstra, centerX, centerY, radius, searchType);
}
protected final void followPresearchedPath() {
movable.followPresearchedPath();
}
protected final void enableNothingToDoAction(boolean enable) {
movable.enableNothingToDoAction(enable);
}
protected void setSelected(boolean selected) {
movable.setSelected(selected);
}
protected final boolean fitsSearchType(ShortPoint2D pos, ESearchType searchType) {
return movable.getStrategyGrid().fitsSearchType(movable, pos, searchType);
}
protected final boolean isValidPosition(ShortPoint2D position) {
return movable.isValidPosition(position);
}
public final ShortPoint2D getPos() {
return movable.getPos();
}
protected final EMaterialType getMaterial() {
return movable.getMaterial();
}
protected final Player getPlayer() {
return movable.getPlayer();
}
protected Movable getMovable() {
return movable;
}
protected final void abortPath() {
movable.abortPath();
}
/**
* Checks preconditions before the next path step can be gone.
*
* @param pathTarget
* Target of the current path.
* @param step
* The number of the current step where 1 means the first step.
*
* @return true if the path should be continued<br>
* false if it must be stopped.
*/
protected boolean checkPathStepPreconditions(ShortPoint2D pathTarget, int step) {
return true;
}
/**
* This method is called when a movable is killed or converted to another strategy and can be used for finalization work in the strategy.
*
* @param pathTarget
* if the movable is currently walking on a path, this is the target of the path<br>
* else it is null.
*/
protected void strategyKilledEvent(ShortPoint2D pathTarget) { // used in overriding methods
}
/**
*
* @param oldPosition
* The position the movable was positioned before the new path has been calculated and the first step on the new path has been done.
* @param oldTargetPos
* The target position of the old path or null if no old path was set.
* @param targetPos
* The new target position.
*/
protected void moveToPathSet(ShortPoint2D oldPosition, ShortPoint2D oldTargetPos, ShortPoint2D targetPos) {
}
/**
* This method may only be called if this movable shall be informed about a movable that's in it's search radius.
*
* @param other
* The other movable.
*/
protected void informAboutAttackable(IAttackable other) {
}
protected boolean isMoveToAble() {
return false;
}
protected Path findWayAroundObstacle(EDirection direction, ShortPoint2D position, Path path) {
if (!(path.getStep() < path.getLength() - 1)) { // if path has no position left
return path;
}
AbstractStrategyGrid grid = movable.getStrategyGrid();
EDirection leftDir = direction.getNeighbor(-1);
EDirection rightDir = direction.getNeighbor(1);
ShortPoint2D leftPos = leftDir.getNextHexPoint(position);
ShortPoint2D leftStraightPos = direction.getNextHexPoint(leftPos);
ShortPoint2D rightPos = rightDir.getNextHexPoint(position);
ShortPoint2D rightStraightPos = direction.getNextHexPoint(rightPos);
ShortPoint2D twoStraight = direction.getNextHexPoint(position, 2);
ShortPoint2D overNextPos = path.getOverNextPos();
if (twoStraight.equals(overNextPos)) {
if (isValidPosition(leftPos) && grid.hasNoMovableAt(leftPos.x, leftPos.y) && isValidPosition(leftStraightPos)) {
path.goToNextStep();
path = new Path(path, leftPos, leftStraightPos);
} else if (isValidPosition(rightPos) && grid.hasNoMovableAt(rightPos.x, rightPos.y) && isValidPosition(rightStraightPos)) {
path.goToNextStep();
path = new Path(path, rightPos, rightStraightPos);
} else {
// TODO @Andreas Eberle maybe calculate a new path
}
} else if (leftStraightPos.equals(overNextPos) && grid.hasNoMovableAt(leftPos.x, leftPos.y)) {
path.goToNextStep();
path = new Path(path, leftPos);
} else if (rightStraightPos.equals(overNextPos) && grid.hasNoMovableAt(rightPos.x, rightPos.y)) {
path.goToNextStep();
path = new Path(path, rightPos);
} else {
// TODO @Andreas Eberle maybe calculate a new path
}
return path;
}
protected void stopOrStartWorking(boolean stop) {
}
protected void sleep(short waitTime) {
movable.wait(waitTime);
}
}
|
package com.cgutman.adblib;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
/**
* This class represents an ADB connection.
* @author Cameron Gutman
*/
public class AdbConnection implements Closeable {
/** The underlying socket that this class uses to
* communicate with the target device.
*/
protected Socket socket;
/** The last allocated local stream ID. The ID
* chosen for the next stream will be this value + 1.
*/
protected int lastLocalId;
/**
* The input stream that this class uses to read from
* the socket.
*/
protected InputStream inputStream;
/**
* The output stream that this class uses to read from
* the socket.
*/
protected OutputStream outputStream;
/**
* The backend thread that handles responding to ADB packets.
*/
protected Thread connectionThread;
/**
* Specifies whether a connect has been attempted
*/
protected boolean connectAttempted;
/**
* Specifies whether a CNXN packet has been received from the peer.
*/
protected boolean connected;
/**
* Specifies the maximum amount data that can be sent to the remote peer.
* This is only valid after connect() returns successfully.
*/
protected int maxData;
/**
* An initialized ADB crypto object that contains a key pair.
*/
protected AdbCrypto crypto;
/**
* Specifies whether this connection has already sent a signed token.
*/
protected boolean sentSignature;
protected volatile boolean isFine = true;
protected AdbMessageManager msgManager;
protected volatile boolean stopFlag = false;
/**
* Internal constructor to initialize some internal state
*/
private AdbConnection()
{
msgManager = new AdbMessageManager(this);
lastLocalId = 0;
connectionThread = createConnectionThread();
}
/**
* Creates a AdbConnection object associated with the socket and
* crypto object specified.
* @param socket The socket that the connection will use for communcation.
* @param crypto The crypto object that stores the key pair for authentication.
* @return A new AdbConnection object.
* @throws IOException If there is a socket error
*/
public static AdbConnection create(Socket socket, AdbCrypto crypto) throws IOException
{
AdbConnection newConn = new AdbConnection();
newConn.crypto = crypto;
newConn.socket = socket;
// bufferedStream
newConn.inputStream = socket.getInputStream();
newConn.outputStream = socket.getOutputStream();
/* Disable Nagle because we're sending tiny packets */
socket.setTcpNoDelay(true);
// 16K
socket.setSendBufferSize(16 * 1024);
// 64K
socket.setReceiveBufferSize(64 * 1024);
socket.setTrafficClass(0x10);
socket.setPerformancePreferences(0, 2, 1);
return newConn;
}
/**
* Creates a new connection thread.
* @return A new connection thread.
*/
private Thread createConnectionThread()
{
@SuppressWarnings("resource")
final AdbConnection conn = this;
return new Thread(new Runnable() {
@Override
public void run() {
while (!stopFlag && !connectionThread.isInterrupted())
{
try {
/* Read and parse a message off the socket's input stream */
AdbProtocol.AdbMessage msg = AdbProtocol.AdbMessage.parseAdbMessage(inputStream);
/* Verify magic and checksum */
msgManager.pushMessage(msg);
//System.out.println("Receive CMD:" + cmd + "; arg0 " + msg.arg0 + "; arg1: " + msg.arg1 + "; data: " + msg.payloadLength);
} catch (Exception e) {
/* The cleanup is taken care of by a combination of this thread
* and close() */
break;
}
}
stopFlag = false;
/* This thread takes care of cleaning up pending streams */
synchronized (conn) {
cleanupStreams();
conn.notifyAll();
conn.connectAttempted = false;
}
}
});
}
/**
* Gets the max data size that the remote client supports.
* A connection must have been attempted before calling this routine.
* This routine will block if a connection is in progress.
* @return The maximum data size indicated in the connect packet.
* @throws InterruptedException If a connection cannot be waited on.
* @throws IOException if the connection fails
*/
public int getMaxData() throws InterruptedException, IOException
{
if (!connectAttempted)
throw new IllegalStateException("connect() must be called first");
synchronized (this) {
/* Block if a connection is pending, but not yet complete */
if (!connected)
wait();
if (!connected) {
throw new IOException("Connection failed");
}
}
return maxData;
}
/**
*
* @throws IOException
* @throws InterruptedException
*/
public void connect() throws IOException, InterruptedException {
connect(0L);
}
/**
* Connects to the remote device. This routine will block until the connection
* completes.
* @throws IOException If the socket fails while connecting
* @throws InterruptedException If we are unable to wait for the connection to finish
*/
public void connect(long timeout) throws IOException, InterruptedException
{
if (connected)
throw new IllegalStateException("Already connected");
/* Write the CONNECT packet */
outputStream.write(AdbProtocol.generateConnect());
outputStream.flush();
/* Start the connection thread to respond to the peer */
connectAttempted = true;
connectionThread.start();
/* Wait for the connection to go live */
synchronized (this) {
if (!connected)
wait(timeout);
if (!connected) {
throw new IOException("Connection failed");
}
}
}
/**
* Opens an AdbStream object corresponding to the specified destination.
* This routine will block until the connection completes.
* @param destination The destination to open on the target
* @return AdbStream object corresponding to the specified destination
* @throws UnsupportedEncodingException If the destination cannot be encoded to UTF-8
* @throws IOException If the stream fails while sending the packet
* @throws InterruptedException If we are unable to wait for the connection to finish
*/
public AdbStream open(String destination) throws UnsupportedEncodingException, IOException, InterruptedException
{
int localId = ++lastLocalId;
if (!connectAttempted)
throw new IllegalStateException("connect() must be called first");
/* Wait for the connect response */
if (!connected) {
synchronized (this) {
if (!connected)
wait();
if (!connected) {
throw new IOException("Connection failed");
}
}
}
/* Add this stream to this list of half-open streams */
AdbStream stream = new AdbStream(this, localId);
msgManager.addAdbStream(localId, stream);
/* Send the open */
outputStream.write(AdbProtocol.generateOpen(localId, destination));
outputStream.flush();
/* Wait for the connection thread to receive the OKAY */
synchronized (stream) {
stream.wait(5000);
}
/* Check if the open was rejected */
// if (stream.isClosed())
// throw new ConnectException("Stream open actively rejected by remote peer");
/* We're fully setup now */
return stream;
}
/**
* This function terminates all I/O on streams associated with this ADB connection
*/
private void cleanupStreams() {
msgManager.cleanupStreams();
}
/** This routine closes the Adb connection and underlying socket
* @throws IOException if the socket fails to close
*/
@Override
public void close() throws IOException {
/* If the connection thread hasn't spawned yet, there's nothing to do */
if (connectionThread == null)
return;
/* Closing the socket will kick the connection thread */
socket.close();
/* Wait for the connection thread to die */
connectionThread.interrupt();
try {
connectionThread.join();
} catch (InterruptedException e) { }
}
public boolean isFine() {
return isFine && connectAttempted && connected;
}
public synchronized void setFine(boolean isFine) {
this.isFine = isFine;
}
}
|
package com.addicks.sendash.admin;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import com.addicks.sendash.admin.service.CustomUserDetailsService;
@Configuration
public class OAuth2ServerConfiguration {
private static final String RESOURCE_ID = "restservice";
@Configuration
@EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/github").permitAll().and().authorizeRequests()
.antMatchers("/api/admin").hasRole("ADMIN");
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration
extends AuthorizationServerConfigurerAdapter {
@Autowired
private DataSource dataSource;
private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Autowired
private CustomUserDetailsService userDetailsService;
@Bean
public JdbcTokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Bean
protected AuthorizationCodeServices authorizationCodeServices() {
return new JdbcAuthorizationCodeServices(dataSource);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.passwordEncoder(passwordEncoder);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authorizationCodeServices(authorizationCodeServices())
.authenticationManager(authenticationManager).tokenStore(tokenStore())
.userDetailsService(userDetailsService).approvalStoreDisabled();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource).passwordEncoder(passwordEncoder).withClient("sendashWebApp")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("USER").scopes("read", "write").resourceIds(RESOURCE_ID)
.accessTokenValiditySeconds(10800).secret("GoGoVCHeckProApp");
}
}
}
|
package com.qozix.tileview.tiles;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.animation.AnimationUtils;
import com.qozix.tileview.detail.DetailLevel;
import com.qozix.tileview.geom.FloatMathHelper;
import com.qozix.tileview.graphics.BitmapProvider;
import com.qozix.tileview.graphics.BitmapRecycler;
import java.lang.ref.WeakReference;
public class Tile {
public enum State {
UNASSIGNED,
PENDING_DECODE,
DECODED
}
private static final int DEFAULT_TRANSITION_DURATION = 200;
private State mState = State.UNASSIGNED;
private int mWidth;
private int mHeight;
private int mLeft;
private int mTop;
private int mRight;
private int mBottom;
private float mProgress;
private int mRow;
private int mColumn;
private float mDetailLevelScale;
private Object mData;
private Bitmap mBitmap;
private Rect mIntrinsicRect = new Rect();
private Rect mBaseRect = new Rect();
private Rect mRelativeRect = new Rect();
private Rect mScaledRect = new Rect();
public Long mRenderTimeStamp;
private boolean mTransitionsEnabled;
private int mTransitionDuration = DEFAULT_TRANSITION_DURATION;
private Paint mPaint;
private DetailLevel mDetailLevel;
private WeakReference<TileRenderRunnable> mTileRenderRunnableWeakReference;
private WeakReference<BitmapRecycler> mBitmapRecyclerReference;
public Tile( int column, int row, int width, int height, Object data, DetailLevel detailLevel ) {
mRow = row;
mColumn = column;
mWidth = width;
mHeight = height;
mLeft = column * width;
mTop = row * height;
mRight = mLeft + mWidth;
mBottom = mTop + mHeight;
mData = data;
mDetailLevel = detailLevel;
mDetailLevelScale = mDetailLevel.getScale();
updateRects();
}
public int getWidth() {
return mWidth;
}
public int getHeight() {
return mHeight;
}
public int getLeft() {
return mLeft;
}
public int getTop() {
return mTop;
}
public int getRow() {
return mRow;
}
public int getColumn() {
return mColumn;
}
public Object getData() {
return mData;
}
public Bitmap getBitmap() {
return mBitmap;
}
public boolean hasBitmap() {
return mBitmap != null;
}
public Rect getBaseRect() {
return mBaseRect;
}
public Rect getRelativeRect() {
return mRelativeRect;
}
/**
* @deprecated
* @return
*/
public float getRendered() {
return mProgress;
}
/**
* @deprecated
*/
public void stampTime() {
// no op
}
public Rect getScaledRect( float scale ) {
mScaledRect.set(
(int) (mRelativeRect.left * scale),
(int) (mRelativeRect.top * scale),
(int) (mRelativeRect.right * scale),
(int) (mRelativeRect.bottom * scale)
);
return mScaledRect;
}
private void updateRects() {
mIntrinsicRect.set( 0, 0, mWidth, mHeight );
mBaseRect.set( mLeft, mTop, mRight, mBottom );
mRelativeRect.set(
FloatMathHelper.unscale( mLeft, mDetailLevelScale ),
FloatMathHelper.unscale( mTop, mDetailLevelScale ),
FloatMathHelper.unscale( mRight, mDetailLevelScale ),
FloatMathHelper.unscale( mBottom, mDetailLevelScale )
);
mScaledRect.set( mRelativeRect );
}
public void setTransitionDuration( int transitionDuration ) {
mTransitionDuration = transitionDuration;
}
public State getState() {
return mState;
}
public void setState( State state ) {
mState = state;
}
public void execute( TileRenderPoolExecutor tileRenderPoolExecutor ) {
execute( tileRenderPoolExecutor, null );
}
public void execute( TileRenderPoolExecutor tileRenderPoolExecutor, BitmapRecycler recycler ) {
if(mState != State.UNASSIGNED){
return;
}
mState = State.PENDING_DECODE;
TileRenderRunnable runnable = new TileRenderRunnable();
mTileRenderRunnableWeakReference = new WeakReference<>( runnable );
mBitmapRecyclerReference = new WeakReference<>( recycler );
runnable.setTile( this );
runnable.setTileRenderPoolExecutor( tileRenderPoolExecutor );
tileRenderPoolExecutor.execute( runnable );
}
public void computeProgress(){
if( !mTransitionsEnabled ) {
return;
}
if( mRenderTimeStamp == null ) {
mRenderTimeStamp = AnimationUtils.currentAnimationTimeMillis();
mProgress = 0;
return;
}
double elapsed = AnimationUtils.currentAnimationTimeMillis() - mRenderTimeStamp;
mProgress = (float) Math.min( 1, elapsed / mTransitionDuration );
if( mProgress == 1f ) {
mRenderTimeStamp = null;
mTransitionsEnabled = false;
}
}
public void setTransitionsEnabled( boolean enabled ) {
mTransitionsEnabled = enabled;
if( enabled ) {
mProgress = 0f;
}
}
public DetailLevel getDetailLevel() {
return mDetailLevel;
}
public boolean getIsDirty() {
return mTransitionsEnabled && mProgress < 1f;
}
public Paint getPaint() {
if( !mTransitionsEnabled ) {
return mPaint = null;
}
if( mPaint == null ) {
mPaint = new Paint();
}
mPaint.setAlpha( (int) (255 * mProgress) );
return mPaint;
}
void generateBitmap( Context context, BitmapProvider bitmapProvider ) {
if( mBitmap != null ) {
return;
}
mBitmap = bitmapProvider.getBitmap( this, context );
mWidth = mBitmap.getWidth();
mHeight = mBitmap.getHeight();
mRight = mLeft + mWidth;
mBottom = mTop + mHeight;
updateRects();
mState = State.DECODED;
}
/**
* Deprecated
* @param b
*/
void destroy( boolean b ) {
reset();
}
void reset() {
if( mState == State.PENDING_DECODE ) {
if ( mTileRenderRunnableWeakReference != null ) {
TileRenderRunnable runnable = mTileRenderRunnableWeakReference.get();
if( runnable != null ) {
runnable.cancel( true );
}
}
}
mState = State.UNASSIGNED;
mRenderTimeStamp = null;
if( mBitmap != null ) {
BitmapRecycler recycler = mBitmapRecyclerReference.get();
if( recycler != null ) {
recycler.recycleBitmap( mBitmap );
}
}
mBitmap = null;
}
/**
* @param canvas The canvas the tile's bitmap should be drawn into
*/
public void draw( Canvas canvas ) {
if( mBitmap != null && !mBitmap.isRecycled() ) {
canvas.drawBitmap( mBitmap, mIntrinsicRect, mRelativeRect, getPaint() );
}
}
@Override
public int hashCode() {
int hash = 17;
hash = hash * 31 + getColumn();
hash = hash * 31 + getRow();
hash = hash * 31 + (int) (1000 * getDetailLevel().getScale());
return hash;
}
@Override
public boolean equals( Object o ) {
if( this == o ) {
return true;
}
if( o instanceof Tile ) {
Tile m = (Tile) o;
return m.getRow() == getRow()
&& m.getColumn() == getColumn()
&& m.getDetailLevel().getScale() == getDetailLevel().getScale();
}
return false;
}
public String toShortString(){
return mColumn + ":" + mRow;
}
}
|
package to.etc.domui.fts;
import java.sql.*;
import to.etc.dbpool.*;
import to.etc.domui.fts.db.*;
import to.etc.domui.fts.nl.*;
import to.etc.util.*;
public class AnalyzerTest {
private Connection m_dbc;
private IFtsLanguage m_lang;
public static void main(String[] args) {
try {
new AnalyzerTest().run();
} catch(Exception x) {
x.printStackTrace();
}
}
private void indexOne(IndexWriter iw, String res, long dockey, String mime) throws Exception {
iw.setDocument("TEST", dockey);
iw.resetStats();
System.out.println("
long ts = System.nanoTime();
Analyzer.analyze(res, iw, m_lang, mime);
iw.flush(); // Force all cached stuff to the database.
ts = System.nanoTime() - ts;
System.out.println("Indexer completed in "+StringTool.strNanoTime(ts));
ts = System.nanoTime();
m_dbc.commit();
ts = System.nanoTime() - ts;
System.out.println("Commit completed in "+StringTool.strNanoTime(ts));
iw.stats();
}
private void run() throws Exception {
openDB();
m_lang = new DutchLanguage();
IndexWriter iw = null;
try {
iw = new IndexWriter(m_dbc);
indexOne(iw, "testnl.txt", 1, "text/text");
// indexOne(iw, "verne.txt", 2, "text/text");
indexOne(iw, "verne.html", 3, "text/html");
} finally {
try { if(iw != null) iw.close(); } catch(Exception x) {}
try { if(m_dbc != null) m_dbc.close(); } catch(Exception x) {}
}
}
private void openDB() throws Exception {
ConnectionPool pool = PoolManager.getInstance().definePool("jalpg");
// ConnectionPool pool = PoolManager.getInstance().definePool("vpdemo");
m_dbc = pool.getUnpooledDataSource().getConnection();
m_dbc.setAutoCommit(false);
}
}
|
package io.kaif.web.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.kaif.config.SpringProfile;
import io.kaif.model.exception.DomainException;
import io.kaif.web.support.AbstractRestExceptionHandler;
import io.kaif.web.support.AccessDeniedException;
import io.kaif.web.support.RestErrorResponse;
@ControllerAdvice(annotations = RestController.class)
public class RestExceptionHandler extends AbstractRestExceptionHandler {
public static class TranslatedRestErrorResponse extends RestErrorResponse {
private static final long serialVersionUID = 1360949999878207L;
public TranslatedRestErrorResponse(int code, String reason) {
super(code, reason);
}
@JsonProperty
public boolean getTranslated() {
return true;
}
@Override
public String toString() {
return "{\"code\":"
+ getCode()
+ ",\"reason\":\""
+ getReason()
+ "\""
+ ",\"translated\":true}";
}
}
@Autowired
private Environment environment;
@ExceptionHandler(AccessDeniedException.class)
@ResponseBody
public ResponseEntity<RestErrorResponse> handleRestAccessDeniedException(final AccessDeniedException ex,
final WebRequest request) {
final HttpStatus status = HttpStatus.UNAUTHORIZED;
final RestErrorResponse errorResponse = new RestErrorResponse(status.value(),
i18n(request, "rest-error.RestAccessDeniedException"));
if (environment.acceptsProfiles(SpringProfile.DEV)) {
//only dev server log detail access denied
logException(ex, errorResponse, request);
} else {
logger.warn("{} {}", guessUri(request), ex.getClass().getSimpleName());
}
return new ResponseEntity<>(errorResponse, status);
}
@ExceptionHandler(DomainException.class)
@ResponseBody
public ResponseEntity<TranslatedRestErrorResponse> handleDomainException(final DomainException ex,
final WebRequest request) {
final HttpStatus status = HttpStatus.BAD_REQUEST;
final TranslatedRestErrorResponse errorResponse = new TranslatedRestErrorResponse(status.value(),
i18n(request, ex.i18nKey(), ex.i18nArgs().toArray()));
//note that domain exception do not use detail log
logger.warn("{} {}", guessUri(request), ex.getClass().getSimpleName());
return new ResponseEntity<>(errorResponse, status);
}
private String guessUri(WebRequest request) {
String uri = "non uri";
if (request instanceof ServletWebRequest) {
uri = ((ServletWebRequest) request).getRequest().getRequestURI();
}
return uri;
}
}
|
package com.akiban.sql.pg;
import com.akiban.ais.model.*;
import com.akiban.server.types.AkType;
import com.akiban.server.types3.aksql.aktypes.AkBool;
import com.akiban.server.types3.mcompat.mtypes.MNumeric;
import com.akiban.server.types3.mcompat.mtypes.MString;
import com.akiban.sql.parser.ParameterNode;
import com.akiban.sql.parser.StatementNode;
import com.akiban.sql.server.ServerValueEncoder;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.util.*;
import java.util.regex.*;
/**
* Canned handling for fixed SQL text that comes from tools that
* believe they are talking to a real Postgres database.
*/
public class PostgresEmulatedMetaDataStatement implements PostgresStatement
{
enum Query {
// ODBC driver sends this at the start; returning no rows is fine (and normal).
ODBC_LO_TYPE_QUERY("select oid, typbasetype from pg_type where typname = 'lo'"),
SEQUEL_B_TYPE_QUERY("select oid, typname from pg_type where typtype = 'b'"),
NPGSQL_TYPE_QUERY("SELECT typname, oid FROM pg_type WHERE typname IN \\((.+)\\)", true),
// PSQL \dn
PSQL_LIST_SCHEMAS("SELECT n.nspname AS \"Name\",\\s*" +
"(?:pg_catalog.pg_get_userbyid\\(n.nspowner\\)|u.usename) AS \"Owner\"\\s+" +
"FROM pg_catalog.pg_namespace n\\s+" +
"(?:LEFT JOIN pg_catalog.pg_user u\\s+" +
"ON n.nspowner=u.usesysid\\s+)?" +
"(?:WHERE\\s+)?" +
"(?:\\(n.nspname !~ '\\^pg_temp_' OR\\s+" +
"n.nspname = \\(pg_catalog.current_schemas\\(true\\)\\)\\[1\\]\\)\\s+)?" +
"(n.nspname !~ '\\^pg_' AND n.nspname <> 'information_schema'\\s+)?" +
"(?:AND\\s+)?" +
"(n.nspname ~ '(.+)'\\s+)?" + // 2 (3)
"ORDER BY 1;?", true),
// PSQL \d, \dt, \dv
PSQL_LIST_TABLES("SELECT n.nspname as \"Schema\",\\s*" +
"c.relname as \"Name\",\\s*" +
"CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' (?:WHEN 'f' THEN 'foreign table' )?END as \"Type\",\\s+" +
"(?:pg_catalog.pg_get_userbyid\\(c.relowner\\)|u.usename) as \"Owner\"\\s+" +
"FROM pg_catalog.pg_class c\\s+" +
"(?:LEFT JOIN pg_catalog.pg_user u ON u.usesysid = c.relowner\\s+)?" +
"LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\\s+" +
"WHERE c.relkind IN \\((.+)\\)\\s+" +
"(AND n.nspname <> 'pg_catalog'\\s+" +
"AND n.nspname <> 'information_schema'\\s+)?" +
"(?:AND n.nspname !~ '\\^pg_toast'\\s+)?" +
"(?:(AND n.nspname NOT IN \\('pg_catalog', 'pg_toast'\\)\\s+)|" +
"(AND n.nspname = 'pg_catalog')\\s+)?" +
"(AND c.relname ~ '(.+)'\\s+)?" + // 5 (6)
"(AND n.nspname ~ '(.+)'\\s+)?" + // 7 (8)
"(?:AND pg_catalog.pg_table_is_visible\\(c.oid\\)\\s+)?" +
"(AND c.relname ~ '(.+)'\\s+)?" + // 9 (10)
"ORDER BY 1,2;?", true),
// PSQL \d NAME
PSQL_DESCRIBE_TABLES_1("SELECT c.oid,\\s*" +
"n.nspname,\\s*" +
"c.relname\\s+" +
"FROM pg_catalog.pg_class c\\s+" +
"LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\\s+" +
"WHERE " +
"(?:pg_catalog.pg_table_is_visible\\(c.oid\\)\\s+AND )?" +
"(n.nspname ~ '(.+)'\\s+)?" + // 1 (2)
"((?:AND )?c.relname ~ '(.+)'\\s+)?" + // 3 (4)
"((?:AND )?n.nspname ~ '(.+)'\\s+)?" + // 5 (6)
"(?:AND pg_catalog.pg_table_is_visible\\(c.oid\\)\\s+)?" +
"ORDER BY 2, 3;?", true),
PSQL_DESCRIBE_TABLES_2("SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, c.relhastriggers, c.relhasoids, '', c.reltablespace\\s+" +
"FROM pg_catalog.pg_class c\\s+" +
"LEFT JOIN pg_catalog.pg_class tc ON \\(c.reltoastrelid = tc.oid\\)\\s+" +
"WHERE c.oid = '(-?\\d+)';?\\s*", true),
PSQL_DESCRIBE_TABLES_2X("SELECT relhasindex, relkind, relchecks, reltriggers, relhasrules\\s+" +
"FROM pg_catalog.pg_class\\s+" +
"WHERE oid = '(-?\\d+)';?\\s*", true),
PSQL_DESCRIBE_TABLES_3("SELECT a.attname,\\s*" +
"pg_catalog.format_type\\(a.atttypid, a.atttypmod\\),\\s*" +
"\\(SELECT substring\\((?:pg_catalog.pg_get_expr\\(d.adbin, d.adrelid\\)|d.adsrc) for 128\\)\\s*" +
"FROM pg_catalog.pg_attrdef d\\s+" +
"WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef\\),\\s*" +
"a.attnotnull, a.attnum,?\\s*" +
"(NULL AS attcollation\\s+)?" +
"FROM pg_catalog.pg_attribute a\\s+" +
"WHERE a.attrelid = '(-?\\d+)' AND a.attnum > 0 AND NOT a.attisdropped\\s+" +
"ORDER BY a.attnum;?", true),
PSQL_DESCRIBE_TABLES_4A("SELECT c.oid::pg_catalog.regclass FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i WHERE c.oid=i.inhparent AND i.inhrelid = '(-?\\d+)' ORDER BY inhseqno;?", true),
PSQL_DESCRIBE_TABLES_4B("SELECT c.oid::pg_catalog.regclass FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i WHERE c.oid=i.inhrelid AND i.inhparent = '(-?\\d+)' ORDER BY c.oid::pg_catalog.regclass::pg_catalog.text;?", true),
PSQL_DESCRIBE_TABLES_5("SELECT c.relname FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i WHERE c.oid=i.inhparent AND i.inhrelid = '(-?\\d+)' ORDER BY inhseqno ASC;?", true),
PSQL_DESCRIBE_INDEXES("SELECT c2.relname, i.indisprimary, i.indisunique(, i.indisclustered, i.indisvalid)?, pg_catalog.pg_get_indexdef\\(i.indexrelid(?:, 0, true)?\\),?\\s*" +
"(null AS constraintdef, null AS contype, false AS condeferrable, false AS condeferred, )?(?:c2.reltablespace)?\\s+" +
"FROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i\\s+" +
"WHERE c.oid = '(-?\\d+)' AND c.oid = i.indrelid AND i.indexrelid = c2.oid\\s+" +
"ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname;?", true),
PSQL_DESCRIBE_VIEW("SELECT pg_catalog.pg_get_viewdef\\('(-?\\d+)'::pg_catalog.oid, true\\);?", true);
private String sql;
private Pattern pattern;
Query(String sql) {
this.sql = sql;
}
Query(String str, boolean regexp) {
if (regexp) {
pattern = Pattern.compile(str);
}
else {
sql = str;
}
}
public boolean matches(String sql, List<String> groups) {
if (pattern == null) {
if (sql.equalsIgnoreCase(this.sql)) {
groups.add(sql);
return true;
}
}
else {
Matcher matcher = pattern.matcher(sql);
if (matcher.matches()) {
for (int i = 0; i <= matcher.groupCount(); i++) {
groups.add(matcher.group(i));
}
return true;
}
}
return false;
}
}
private Query query;
private List<String> groups;
private boolean usePVals;
private long aisGeneration;
protected PostgresEmulatedMetaDataStatement(Query query, List<String> groups, boolean usePVals) {
this.query = query;
this.groups = groups;
this.usePVals = usePVals;
}
private static final boolean FIELDS_NULLABLE = true;
static final PostgresType BOOL_PG_TYPE =
new PostgresType(PostgresType.TypeOid.BOOL_TYPE_OID, (short)1, -1, AkType.BOOL, AkBool.INSTANCE.instance(FIELDS_NULLABLE));
static final PostgresType INT2_PG_TYPE =
new PostgresType(PostgresType.TypeOid.INT2_TYPE_OID, (short)2, -1, AkType.LONG, MNumeric.SMALLINT.instance(FIELDS_NULLABLE));
static final PostgresType OID_PG_TYPE =
new PostgresType(PostgresType.TypeOid.OID_TYPE_OID, (short)4, -1, AkType.LONG, MNumeric.INT.instance(FIELDS_NULLABLE));
static final PostgresType TYPNAME_PG_TYPE =
new PostgresType(PostgresType.TypeOid.NAME_TYPE_OID, (short)255, -1, AkType.VARCHAR, MString.VARCHAR.instance(FIELDS_NULLABLE));
static final PostgresType IDENT_PG_TYPE =
new PostgresType(PostgresType.TypeOid.NAME_TYPE_OID, (short)128, -1, AkType.VARCHAR, MString.VARCHAR.instance(FIELDS_NULLABLE));
static final PostgresType LIST_TYPE_PG_TYPE =
new PostgresType(PostgresType.TypeOid.NAME_TYPE_OID, (short)13, -1, AkType.VARCHAR, MString.VARCHAR.instance(FIELDS_NULLABLE));
static final PostgresType CHAR0_PG_TYPE =
new PostgresType(PostgresType.TypeOid.NAME_TYPE_OID, (short)0, -1, AkType.VARCHAR, MString.VARCHAR.instance(FIELDS_NULLABLE));
static final PostgresType CHAR1_PG_TYPE =
new PostgresType(PostgresType.TypeOid.NAME_TYPE_OID, (short)1, -1, AkType.VARCHAR, MString.VARCHAR.instance(FIELDS_NULLABLE));
static final PostgresType INDEXDEF_PG_TYPE =
new PostgresType(PostgresType.TypeOid.NAME_TYPE_OID, (short)1024, -1, AkType.VARCHAR, MString.VARCHAR.instance(FIELDS_NULLABLE));
static final PostgresType VIEWDEF_PG_TYPE =
new PostgresType(PostgresType.TypeOid.NAME_TYPE_OID, (short)32768, -1, AkType.VARCHAR, MString.VARCHAR.instance(FIELDS_NULLABLE));
@Override
public PostgresType[] getParameterTypes() {
return null;
}
@Override
public void sendDescription(PostgresQueryContext context, boolean always)
throws IOException {
int ncols;
String[] names;
PostgresType[] types;
switch (query) {
case ODBC_LO_TYPE_QUERY:
ncols = 2;
names = new String[] { "oid", "typbasetype" };
types = new PostgresType[] { OID_PG_TYPE, OID_PG_TYPE };
break;
case SEQUEL_B_TYPE_QUERY:
ncols = 2;
names = new String[] { "oid", "typname" };
types = new PostgresType[] { OID_PG_TYPE, TYPNAME_PG_TYPE };
break;
case NPGSQL_TYPE_QUERY:
ncols = 2;
names = new String[] { "typname", "oid" };
types = new PostgresType[] { TYPNAME_PG_TYPE, OID_PG_TYPE };
break;
case PSQL_LIST_SCHEMAS:
ncols = 2;
names = new String[] { "Name", "Owner" };
types = new PostgresType[] { IDENT_PG_TYPE, IDENT_PG_TYPE };
break;
case PSQL_LIST_TABLES:
ncols = 4;
names = new String[] { "Schema", "Name", "Type", "Owner" };
types = new PostgresType[] { IDENT_PG_TYPE, IDENT_PG_TYPE, LIST_TYPE_PG_TYPE, IDENT_PG_TYPE };
break;
case PSQL_DESCRIBE_TABLES_1:
ncols = 3;
names = new String[] { "oid", "nspname", "relname" };
types = new PostgresType[] { OID_PG_TYPE, IDENT_PG_TYPE, IDENT_PG_TYPE };
break;
case PSQL_DESCRIBE_TABLES_2:
ncols = 8;
names = new String[] { "relchecks", "relkind", "relhasindex", "relhasrules", "relhastriggers", "relhasoids", "?column?", "reltablespace" };
types = new PostgresType[] { INT2_PG_TYPE, CHAR1_PG_TYPE, BOOL_PG_TYPE, BOOL_PG_TYPE, BOOL_PG_TYPE, BOOL_PG_TYPE, BOOL_PG_TYPE, CHAR0_PG_TYPE, OID_PG_TYPE };
break;
case PSQL_DESCRIBE_TABLES_2X:
ncols = 5;
names = new String[] { "relhasindex", "relkind", "relchecks", "reltriggers", "relhasrules" };
types = new PostgresType[] { BOOL_PG_TYPE, CHAR1_PG_TYPE, INT2_PG_TYPE, INT2_PG_TYPE, BOOL_PG_TYPE };
break;
case PSQL_DESCRIBE_TABLES_3:
ncols = (groups.get(1) != null) ? 6 : 5;
names = new String[] { "attname", "format_type", "?column?", "attnotnull", "attnum", "attcollation" };
types = new PostgresType[] { IDENT_PG_TYPE, TYPNAME_PG_TYPE, CHAR0_PG_TYPE, BOOL_PG_TYPE, INT2_PG_TYPE, CHAR0_PG_TYPE };
break;
case PSQL_DESCRIBE_TABLES_4A:
case PSQL_DESCRIBE_TABLES_4B:
ncols = 1;
names = new String[] { "oid" };
types = new PostgresType[] { OID_PG_TYPE };
break;
case PSQL_DESCRIBE_TABLES_5:
ncols = 1;
names = new String[] { "relname" };
types = new PostgresType[] { IDENT_PG_TYPE };
break;
case PSQL_DESCRIBE_INDEXES:
if (groups.get(1) == null) {
ncols = 4;
names = new String[] { "relname", "indisprimary", "indisunique", "pg_get_indexdef" };
types = new PostgresType[] { IDENT_PG_TYPE, BOOL_PG_TYPE, BOOL_PG_TYPE, INDEXDEF_PG_TYPE };
}
if (groups.get(2) == null) {
ncols = 7;
names = new String[] { "relname", "indisprimary", "indisunique", "indisclustered", "indisvalid", "pg_get_indexdef", "reltablespace" };
types = new PostgresType[] { IDENT_PG_TYPE, BOOL_PG_TYPE, BOOL_PG_TYPE, BOOL_PG_TYPE, BOOL_PG_TYPE, INDEXDEF_PG_TYPE, INT2_PG_TYPE };
}
else {
ncols = 11;
names = new String[] { "relname", "indisprimary", "indisunique", "indisclustered", "indisvalid", "pg_get_indexdef", "constraintdef", "contype", "condeferrable", "condeferred", "reltablespace" };
types = new PostgresType[] { IDENT_PG_TYPE, BOOL_PG_TYPE, BOOL_PG_TYPE, BOOL_PG_TYPE, BOOL_PG_TYPE, INDEXDEF_PG_TYPE, CHAR0_PG_TYPE, CHAR0_PG_TYPE, BOOL_PG_TYPE, BOOL_PG_TYPE, INT2_PG_TYPE };
}
break;
case PSQL_DESCRIBE_VIEW:
ncols = 1;
names = new String[] { "pg_get_viewdef" };
types = new PostgresType[] { VIEWDEF_PG_TYPE };
break;
default:
return;
}
PostgresServerSession server = context.getServer();
PostgresMessenger messenger = server.getMessenger();
messenger.beginMessage(PostgresMessages.ROW_DESCRIPTION_TYPE.code());
messenger.writeShort(ncols);
for (int i = 0; i < ncols; i++) {
PostgresType type = types[i];
messenger.writeString(names[i]); // attname
messenger.writeInt(0); // attrelid
messenger.writeShort(0); // attnum
messenger.writeInt(type.getOid()); // atttypid
messenger.writeShort(type.getLength()); // attlen
messenger.writeInt(type.getModifier()); // atttypmod
messenger.writeShort(0);
}
messenger.sendMessage();
}
@Override
public TransactionMode getTransactionMode() {
return TransactionMode.READ;
}
@Override
public TransactionAbortedMode getTransactionAbortedMode() {
return TransactionAbortedMode.NOT_ALLOWED;
}
@Override
public AISGenerationMode getAISGenerationMode() {
return AISGenerationMode.ALLOWED;
}
@Override
public int execute(PostgresQueryContext context, int maxrows) throws IOException {
PostgresServerSession server = context.getServer();
PostgresMessenger messenger = server.getMessenger();
int nrows = 0;
switch (query) {
case ODBC_LO_TYPE_QUERY:
nrows = odbcLoTypeQuery(messenger, maxrows);
break;
case SEQUEL_B_TYPE_QUERY:
nrows = sequelBTypeQuery(messenger, maxrows, usePVals);
break;
case NPGSQL_TYPE_QUERY:
nrows = npgsqlTypeQuery(messenger, maxrows, usePVals);
break;
case PSQL_LIST_SCHEMAS:
nrows = psqlListSchemasQuery(server, messenger, maxrows, usePVals);
break;
case PSQL_LIST_TABLES:
nrows = psqlListTablesQuery(server, messenger, maxrows, usePVals);
break;
case PSQL_DESCRIBE_TABLES_1:
nrows = psqlDescribeTables1Query(server, messenger, maxrows, usePVals);
break;
case PSQL_DESCRIBE_TABLES_2:
nrows = psqlDescribeTables2Query(server, messenger, maxrows, usePVals);
break;
case PSQL_DESCRIBE_TABLES_2X:
nrows = psqlDescribeTables2XQuery(server, messenger, maxrows, usePVals);
break;
case PSQL_DESCRIBE_TABLES_3:
nrows = psqlDescribeTables3Query(server, messenger, maxrows, usePVals);
break;
case PSQL_DESCRIBE_TABLES_4A:
case PSQL_DESCRIBE_TABLES_4B:
case PSQL_DESCRIBE_TABLES_5:
nrows = psqlDescribeTables4Query(server, messenger, maxrows, usePVals);
break;
case PSQL_DESCRIBE_INDEXES:
nrows = psqlDescribeIndexesQuery(server, messenger, maxrows, usePVals);
break;
case PSQL_DESCRIBE_VIEW:
nrows = psqlDescribeViewQuery(server, messenger, maxrows, usePVals);
break;
}
{
messenger.beginMessage(PostgresMessages.COMMAND_COMPLETE_TYPE.code());
messenger.writeString("SELECT " + nrows);
messenger.sendMessage();
}
return nrows;
}
@Override
public boolean hasAISGeneration() {
return aisGeneration != 0;
}
@Override
public void setAISGeneration(long aisGeneration) {
this.aisGeneration = aisGeneration;
}
@Override
public long getAISGeneration() {
return aisGeneration;
}
@Override
public PostgresStatement finishGenerating(PostgresServerSession server,
String sql, StatementNode stmt,
List<ParameterNode> params, int[] paramTypes) {
return this;
}
private int odbcLoTypeQuery(PostgresMessenger messenger, int maxrows) {
return 0;
}
protected void writeColumn(PostgresMessenger messenger, ServerValueEncoder encoder, boolean usePVals,
Object value, PostgresType type) throws IOException {
ByteArrayOutputStream bytes;
if (usePVals) {
bytes = encoder.encodePObject(value, type, false);
}
else {
bytes = encoder.encodeObject(value, type, false);
}
if (bytes == null) {
messenger.writeInt(-1);
}
else {
messenger.writeInt(bytes.size());
messenger.writeByteStream(bytes);
}
}
private int sequelBTypeQuery(PostgresMessenger messenger, int maxrows, boolean usePVals) throws IOException {
int nrows = 0;
ServerValueEncoder encoder = new ServerValueEncoder(messenger.getEncoding());
for (PostgresType.TypeOid pgtype : PostgresType.TypeOid.values()) {
if (pgtype.getType() == PostgresType.TypeOid.TypType.BASE) {
messenger.beginMessage(PostgresMessages.DATA_ROW_TYPE.code());
messenger.writeShort(2); // 2 columns for this query
writeColumn(messenger, encoder, usePVals,
pgtype.getOid(), OID_PG_TYPE);
writeColumn(messenger, encoder, usePVals,
pgtype.getName(), TYPNAME_PG_TYPE);
messenger.sendMessage();
nrows++;
if ((maxrows > 0) && (nrows >= maxrows)) {
break;
}
}
}
return nrows;
}
private int npgsqlTypeQuery(PostgresMessenger messenger, int maxrows, boolean usePVals) throws IOException {
int nrows = 0;
ServerValueEncoder encoder = new ServerValueEncoder(messenger.getEncoding());
List<String> types = new ArrayList<String>();
for (String type : groups.get(1).split(",")) {
if ((type.charAt(0) == '\'') && (type.charAt(type.length()-1) == '\''))
type = type.substring(1, type.length()-1);
types.add(type);
}
for (PostgresType.TypeOid pgtype : PostgresType.TypeOid.values()) {
if (types.contains(pgtype.getName())) {
messenger.beginMessage(PostgresMessages.DATA_ROW_TYPE.code());
messenger.writeShort(2); // 2 columns for this query
writeColumn(messenger, encoder, usePVals,
pgtype.getName(), TYPNAME_PG_TYPE);
writeColumn(messenger, encoder, usePVals,
pgtype.getOid(), OID_PG_TYPE);
messenger.sendMessage();
nrows++;
if ((maxrows > 0) && (nrows >= maxrows)) {
break;
}
}
}
return nrows;
}
private int psqlListSchemasQuery(PostgresServerSession server, PostgresMessenger messenger, int maxrows, boolean usePVals) throws IOException {
int nrows = 0;
ServerValueEncoder encoder = new ServerValueEncoder(messenger.getEncoding());
AkibanInformationSchema ais = server.getAIS();
List<String> names = new ArrayList<String>(ais.getSchemas().keySet());
boolean noIS = (groups.get(1) != null);
Pattern pattern = null;
if (groups.get(2) != null)
pattern = Pattern.compile(groups.get(3));
Iterator<String> iter = names.iterator();
while (iter.hasNext()) {
String name = iter.next();
if ((noIS &&
name.equals(TableName.INFORMATION_SCHEMA)) ||
((pattern != null) &&
!pattern.matcher(name).find()))
iter.remove();
}
Collections.sort(names);
for (String name : names) {
messenger.beginMessage(PostgresMessages.DATA_ROW_TYPE.code());
messenger.writeShort(2); // 2 columns for this query
writeColumn(messenger, encoder, usePVals,
name, IDENT_PG_TYPE);
writeColumn(messenger, encoder, usePVals,
null, IDENT_PG_TYPE);
messenger.sendMessage();
nrows++;
if ((maxrows > 0) && (nrows >= maxrows)) {
break;
}
}
return nrows;
}
private int psqlListTablesQuery(PostgresServerSession server, PostgresMessenger messenger, int maxrows, boolean usePVals) throws IOException {
int nrows = 0;
ServerValueEncoder encoder = new ServerValueEncoder(messenger.getEncoding());
List<String> types = Arrays.asList(groups.get(1).split(","));
List<TableName> names = new ArrayList<TableName>();
AkibanInformationSchema ais = server.getAIS();
if (types.contains("'r'"))
names.addAll(ais.getUserTables().keySet());
if (types.contains("'v'"))
names.addAll(ais.getViews().keySet());
boolean noIS = (groups.get(2) != null) || (groups.get(3) != null);
boolean onlyIS = (groups.get(4) != null);
Pattern schemaPattern = null, tablePattern = null;
if (groups.get(5) != null)
tablePattern = Pattern.compile(groups.get(6));
if (groups.get(7) != null)
schemaPattern = Pattern.compile(groups.get(8));
if (groups.get(9) != null)
tablePattern = Pattern.compile(groups.get(10));
Iterator<TableName> iter = names.iterator();
while (iter.hasNext()) {
TableName name = iter.next();
boolean keep = true;
if ((name.getSchemaName().equals(TableName.INFORMATION_SCHEMA) ? noIS : onlyIS) ||
((schemaPattern != null) &&
!schemaPattern.matcher(name.getSchemaName()).find()) ||
((tablePattern != null) &&
!tablePattern.matcher(name.getTableName()).find()))
iter.remove();
}
Collections.sort(names);
for (TableName name : names) {
messenger.beginMessage(PostgresMessages.DATA_ROW_TYPE.code());
messenger.writeShort(4); // 4 columns for this query
writeColumn(messenger, encoder, usePVals,
name.getSchemaName(), IDENT_PG_TYPE);
writeColumn(messenger, encoder, usePVals,
name.getTableName(), IDENT_PG_TYPE);
String type = (ais.getColumnar(name).isView()) ? "view" : "table";
writeColumn(messenger, encoder, usePVals,
type, LIST_TYPE_PG_TYPE);
writeColumn(messenger, encoder, usePVals,
null, IDENT_PG_TYPE);
messenger.sendMessage();
nrows++;
if ((maxrows > 0) && (nrows >= maxrows)) {
break;
}
}
return nrows;
}
private int psqlDescribeTables1Query(PostgresServerSession server, PostgresMessenger messenger, int maxrows, boolean usePVals) throws IOException {
int nrows = 0;
ServerValueEncoder encoder = new ServerValueEncoder(messenger.getEncoding());
Map<Integer,TableName> nonTableNames = null;
List<TableName> names = new ArrayList<TableName>();
AkibanInformationSchema ais = server.getAIS();
names.addAll(ais.getUserTables().keySet());
names.addAll(ais.getViews().keySet());
Pattern schemaPattern = null, tablePattern = null;
if (groups.get(1) != null)
schemaPattern = Pattern.compile(groups.get(2));
if (groups.get(3) != null)
tablePattern = Pattern.compile(groups.get(4));
if (groups.get(5) != null)
schemaPattern = Pattern.compile(groups.get(6));
Iterator<TableName> iter = names.iterator();
while (iter.hasNext()) {
TableName name = iter.next();
if (((schemaPattern != null) &&
!schemaPattern.matcher(name.getSchemaName()).find()) ||
((tablePattern != null) &&
!tablePattern.matcher(name.getTableName()).find()))
iter.remove();
}
Collections.sort(names);
for (TableName name : names) {
int id;
Columnar table = ais.getColumnar(name);
if (table.isTable())
id = ((Table)table).getTableId();
else {
if (nonTableNames == null)
nonTableNames = new HashMap<Integer,TableName>();
id = - (nonTableNames.size() + 1);
nonTableNames.put(id, name);
}
messenger.beginMessage(PostgresMessages.DATA_ROW_TYPE.code());
messenger.writeShort(3); // 3 columns for this query
writeColumn(messenger, encoder, usePVals,
id, OID_PG_TYPE);
writeColumn(messenger, encoder, usePVals,
name.getSchemaName(), IDENT_PG_TYPE);
writeColumn(messenger, encoder, usePVals,
name.getTableName(), IDENT_PG_TYPE);
messenger.sendMessage();
nrows++;
if ((maxrows > 0) && (nrows >= maxrows)) {
break;
}
}
server.setAttribute("psql_nonTableNames", nonTableNames);
return nrows;
}
private Columnar getTableById(PostgresServerSession server, String group) {
AkibanInformationSchema ais = server.getAIS();
int id = Integer.parseInt(group);
if (id < 0) {
Map<Integer,TableName> nonTableNames = (Map<Integer,TableName>)
server.getAttribute("psql_nonTableNames");
if (nonTableNames != null) {
TableName name = nonTableNames.get(id);
if (name != null) {
return ais.getColumnar(name);
}
}
return null;
}
else {
return ais.getUserTable(id);
}
}
private int psqlDescribeTables2Query(PostgresServerSession server, PostgresMessenger messenger, int maxrows, boolean usePVals) throws IOException {
ServerValueEncoder encoder = new ServerValueEncoder(messenger.getEncoding());
Columnar table = getTableById(server, groups.get(1));
if (table == null) return 0;
messenger.beginMessage(PostgresMessages.DATA_ROW_TYPE.code());
messenger.writeShort(8); // 8 columns for this query
writeColumn(messenger, encoder, usePVals, // relchecks
(short)0, INT2_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // relkind
table.isView() ? "v" : "r", CHAR1_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // relhasindex
hasIndexes(table) ? "t" : "f", CHAR1_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // relhasrules
false, BOOL_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // relhastriggers
false, BOOL_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // relhasoids
false, BOOL_PG_TYPE);
writeColumn(messenger, encoder, usePVals,
"", CHAR0_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // reltablespacae
0, OID_PG_TYPE);
messenger.sendMessage();
return 1;
}
private int psqlDescribeTables2XQuery(PostgresServerSession server, PostgresMessenger messenger, int maxrows, boolean usePVals) throws IOException {
ServerValueEncoder encoder = new ServerValueEncoder(messenger.getEncoding());
Columnar table = getTableById(server, groups.get(1));
if (table == null) return 0;
messenger.beginMessage(PostgresMessages.DATA_ROW_TYPE.code());
messenger.writeShort(5); // 5 columns for this query
writeColumn(messenger, encoder, usePVals, // relhasindex
hasIndexes(table) ? "t" : "f", CHAR1_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // relkind
table.isView() ? "v" : "r", CHAR1_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // relchecks
(short)0, INT2_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // reltriggers
(short)0, INT2_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // relhasrules
false, BOOL_PG_TYPE);
messenger.sendMessage();
return 1;
}
private int psqlDescribeTables3Query(PostgresServerSession server, PostgresMessenger messenger, int maxrows, boolean usePVals) throws IOException {
int nrows = 0;
ServerValueEncoder encoder = new ServerValueEncoder(messenger.getEncoding());
Columnar table = getTableById(server, groups.get(2));
if (table == null) return 0;
boolean hasCollation = (groups.get(1) != null);
for (Column column : table.getColumns()) {
messenger.beginMessage(PostgresMessages.DATA_ROW_TYPE.code());
messenger.writeShort(hasCollation ? 6 : 5); // 5-6 columns for this query
writeColumn(messenger, encoder, usePVals, // attname
column.getName(), IDENT_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // format_type
column.getTypeDescription(), TYPNAME_PG_TYPE);
writeColumn(messenger, encoder, usePVals,
null, CHAR0_PG_TYPE);
// This should use BOOL_PG_TYPE, except that does true/false, not t/f.
writeColumn(messenger, encoder, usePVals, // attnotnull
column.getNullable() ? "f" : "t", CHAR1_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // attnum
column.getPosition().shortValue(), INT2_PG_TYPE);
if (hasCollation)
writeColumn(messenger, encoder, usePVals, // attcollation
null, CHAR0_PG_TYPE);
messenger.sendMessage();
nrows++;
if ((maxrows > 0) && (nrows >= maxrows)) {
break;
}
}
return nrows;
}
private int psqlDescribeTables4Query(PostgresServerSession server, PostgresMessenger messenger, int maxrows, boolean usePVals) throws IOException {
ServerValueEncoder encoder = new ServerValueEncoder(messenger.getEncoding());
Columnar table = getTableById(server, groups.get(1));
if (table == null) return 0;
return 0;
}
private int psqlDescribeIndexesQuery(PostgresServerSession server, PostgresMessenger messenger, int maxrows, boolean usePVals) throws IOException {
int nrows = 0;
ServerValueEncoder encoder = new ServerValueEncoder(messenger.getEncoding());
Columnar columnar = getTableById(server, groups.get(3));
if ((columnar == null) || !columnar.isTable()) return 0;
UserTable table = (UserTable)columnar;
Map<String,Index> indexes = new TreeMap<String,Index>();
for (Index index : table.getIndexesIncludingInternal()) {
if (isAkibanPKIndex(index)) continue;
indexes.put(index.getIndexName().getName(), index);
}
for (Index index : table.getGroup().getIndexes()) {
if (table == index.leafMostTable()) {
indexes.put(index.getIndexName().getName(), index);
}
}
int ncols;
if (groups.get(1) == null) {
ncols = 4;
}
if (groups.get(2) == null) {
ncols = 7;
}
else {
ncols = 11;
}
for (Index index : indexes.values()) {
messenger.beginMessage(PostgresMessages.DATA_ROW_TYPE.code());
messenger.writeShort(ncols); // 4-7-11 columns for this query
writeColumn(messenger, encoder, usePVals, // relname
index.getIndexName().getName(), IDENT_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // indisprimary
(index.getIndexName().getName().equals(Index.PRIMARY_KEY_CONSTRAINT)) ? "t" : "f", CHAR1_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // indisunique
(index.isUnique()) ? "t" : "f", CHAR1_PG_TYPE);
if (ncols > 4) {
writeColumn(messenger, encoder, usePVals, // indisclustered
false, BOOL_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // indisvalid
"t", CHAR1_PG_TYPE);
}
writeColumn(messenger, encoder, usePVals, // pg_get_indexdef
formatIndexdef(index, table), INDEXDEF_PG_TYPE);
if (ncols > 7) {
writeColumn(messenger, encoder, usePVals, // constraintdef
null, CHAR0_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // contype
null, CHAR0_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // condeferragble
false, BOOL_PG_TYPE);
writeColumn(messenger, encoder, usePVals, // condeferred
false, BOOL_PG_TYPE);
}
if (ncols > 4) {
writeColumn(messenger, encoder, usePVals, // reltablespace
0, OID_PG_TYPE);
}
messenger.sendMessage();
nrows++;
if ((maxrows > 0) && (nrows >= maxrows)) {
break;
}
}
return nrows;
}
private boolean hasIndexes(Columnar table) {
if (!table.isTable())
return false;
Collection<? extends Index> indexes = ((UserTable)table).getIndexes();
if (indexes.isEmpty())
return false;
if (indexes.size() > 1)
return true;
if (isAkibanPKIndex(indexes.iterator().next()))
return false;
return true;
}
private boolean isAkibanPKIndex(Index index) {
List<IndexColumn> indexColumns = index.getKeyColumns();
return ((indexColumns.size() == 1) &&
indexColumns.get(0).getColumn().isAkibanPKColumn());
}
private String formatIndexdef(Index index, UserTable table) {
StringBuilder str = new StringBuilder();
// Postgres CREATE INDEX has USING method, btree|hash|gist|gin|...
// That is where the client starts including output.
// Only issue is that for PRIMARY KEY, it prints a comma in
// anticipation of some method word before the column.
str.append(" USING ");
int firstSpatialColumn = Integer.MAX_VALUE;
int lastSpatialColumn = Integer.MIN_VALUE;
if (index.getIndexMethod() == Index.IndexMethod.Z_ORDER_LAT_LON) {
firstSpatialColumn = index.firstSpatialArgument();
lastSpatialColumn = firstSpatialColumn + index.dimensions() - 1;
}
str.append("(");
boolean first = true;
for (IndexColumn icolumn : index.getKeyColumns()) {
Column column = icolumn.getColumn();
if (first) {
first = false;
}
else {
str.append(", ");
}
int positionInIndex = icolumn.getPosition();
if (positionInIndex == firstSpatialColumn) {
str.append(index.getIndexMethod().name());
str.append('(');
}
if (column.getTable() != table) {
str.append(column.getTable().getName().getTableName())
.append(".");
}
str.append(column.getName());
if (positionInIndex == lastSpatialColumn) {
str.append(')');
}
}
str.append(")");
if (index.isGroupIndex()) {
str.append(" USING " + index.getJoinType() + " JOIN");
}
return str.toString();
}
private int psqlDescribeViewQuery(PostgresServerSession server, PostgresMessenger messenger, int maxrows, boolean usePVals) throws IOException {
ServerValueEncoder encoder = new ServerValueEncoder(messenger.getEncoding());
Columnar table = getTableById(server, groups.get(1));
if ((table == null) || !table.isView()) return 0;
View view = (View)table;
messenger.beginMessage(PostgresMessages.DATA_ROW_TYPE.code());
messenger.writeShort(1); // 1 column for this query
writeColumn(messenger, encoder, usePVals, // pg_get_viewdef
view.getDefinition(), VIEWDEF_PG_TYPE);
messenger.sendMessage();
return 1;
}
}
|
package org.antlr.v4.test;
import org.junit.Test;
/** TODO: delete since i don't built DFA anymore for lexer */
public class TestLexerDFAConstruction extends BaseTest {
@Test public void unicode() throws Exception {
String g =
"lexer grammar L;\n" +
"A : '\\u0030'..'\\u8000'+ 'a' ;\n" + // TODO: FAILS; \\u not converted
"B : '\\u0020' ;";
String expecting =
"";
checkLexerDFA(g, expecting);
}
@Test public void keywordvsID() throws Exception {
String g =
"lexer grammar L2;\n" +
"IF : 'if' ;\n" +
"ID : 'a'..'z'+ ;\n" +
"INT : DIGIT+ ;\n" +
"public fragment\n" +
"DIGIT : '0'..'9' ;";
String expecting =
":s1=> INT-{'0'..'9'}->:s1=> INT\n" +
":s2=> ID-{'a'..'z'}->:s2=> ID\n" +
":s3=> ID-'f'->:s4=> IF ID\n" +
":s3=> ID-{'a'..'e', 'g'..'z'}->:s2=> ID\n" +
":s4=> IF ID-{'a'..'z'}->:s2=> ID\n" +
"s0-'i'->:s3=> ID\n" +
"s0-{'0'..'9'}->:s1=> INT\n" +
"s0-{'a'..'h', 'j'..'z'}->:s2=> ID\n";
checkLexerDFA(g, expecting);
}
@Test public void recursiveMatchingTwoAlts() throws Exception {
// ambig with ACTION; accept state will try both after matching
// since one is recursive
String g =
"lexer grammar L3;\n" +
"SPECIAL : '{{}}' ;\n" +
"ACTION : '{' (FOO | 'x')* '}' ;\n" +
"fragment\n" +
"FOO : ACTION ;\n" +
"LCURLY : '{' ;";
String expecting =
":s1=> LCURLY-'x'->s4\n" +
":s1=> LCURLY-'{'->s3\n" +
":s1=> LCURLY-'}'->:s2=> ACTION\n" +
"s0-'{'->:s1=> LCURLY\n" +
"s3-'x'->s6\n" +
"s3-'}'->s5\n" +
"s4-'x'->s4\n" +
"s4-'{'->s7\n" +
"s4-'}'->:s2=> ACTION\n" +
"s5-'x'->s4\n" +
"s5-'{'->s7\n" +
"s5-'}'->:s8=> SPECIAL ACTION\n" + // order meaningful here: SPECIAL ACTION
"s6-'x'->s6\n" +
"s6-'}'->s9\n" +
"s7-'x'->s6\n" +
"s7-'}'->s9\n" +
"s9-'x'->s4\n" +
"s9-'{'->s7\n" +
"s9-'}'->:s2=> ACTION\n";
checkLexerDFA(g, expecting);
}
@Test public void testMode() throws Exception {
String g =
"lexer grammar L;\n"+
"A : 'a' ;\n" +
"X : 'x' ;\n" +
"mode FOO;\n" +
"B : 'b' ;\n" +
"C : 'c' ;\n";
String expecting =
"s0-'b'->:s1=> B\n" +
"s0-'c'->:s2=> C\n";
checkLexerDFA(g, "FOO", expecting);
}
public void _template() throws Exception {
String g =
"";
String expecting =
"";
checkLexerDFA(g, expecting);
}
}
|
package com.epam.ta.reportportal.commons.querygen;
import com.epam.ta.reportportal.ws.model.ErrorType;
import org.jooq.Operator;
import org.jooq.impl.DSL;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import static com.epam.ta.reportportal.commons.Predicates.or;
import static com.epam.ta.reportportal.commons.querygen.FilterRules.*;
import static com.epam.ta.reportportal.commons.validation.BusinessRule.expect;
import static com.epam.ta.reportportal.commons.validation.BusinessRule.fail;
import static com.epam.ta.reportportal.commons.validation.Suppliers.formattedSupplier;
import static com.epam.ta.reportportal.ws.model.ErrorType.INCORRECT_FILTER_PARAMETERS;
import static java.lang.Long.parseLong;
import static java.util.Date.from;
import static org.jooq.impl.DSL.any;
import static org.jooq.impl.DSL.field;
/**
* Types of supported filtering
*
* @author Andrei Varabyeu
*/
public enum Condition {
/**
* EQUALS condition
*/
EQUALS("eq") {
@Override
public org.jooq.Condition toCondition(FilterCondition filter, CriteriaHolder criteriaHolder) {
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
return field(criteriaHolder.getQueryCriteria()).eq(this.castValue(criteriaHolder,
filter.getValue(),
INCORRECT_FILTER_PARAMETERS
));
}
@Override
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(isNegative, val -> Objects.equals(val, false)).verify(errorType,
"Filter is incorrect. '!' can't be used with 'is' - use 'ne' instead"
);
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return criteriaHolder.castValue(value, errorType);
}
},
/**
* Not equals condition
*/
NOT_EQUALS("ne") {
@Override
public org.jooq.Condition toCondition(FilterCondition filter, CriteriaHolder criteriaHolder) {
return field(criteriaHolder.getQueryCriteria()).ne(this.castValue(criteriaHolder, filter.getValue(), INCORRECT_FILTER_PARAMETERS));
}
@Override
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
// object type validations is not required here
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return criteriaHolder.castValue(value, errorType);
}
},
/**
* Contains operation. NON case sensitive
*/
CONTAINS("cnt") {
@Override
public org.jooq.Condition toCondition(FilterCondition filter, CriteriaHolder criteriaHolder) {
/* Validate only strings */
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
return field(criteriaHolder.getQueryCriteria()).like("%" + filter.getValue() + "%");
}
@Override
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, filterForString()).verify(errorType,
formattedSupplier("Contains condition applyable only for strings. Type of field is '{}'",
criteriaHolder.getDataType().getSimpleName()
)
);
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String values, ErrorType errorType) {
// values cast is not required here
return values;
}
},
// /**
// * Size operation
// */
// SIZE("size") {
// @Override
// public org.jooq.Condition toCondition(FilterCondition filter, CriteriaHolder criteriaHolder) {
// /* Validate only numbers */
// this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
// field(filter.getSearchCriteria()).size(Integer.parseInt(filter.getValue()));
// @Override
// public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
// expect(criteriaHolder, filterForCollections()).verify(errorType, formattedSupplier(
// "'Size' condition applyable only for collection data types. Type of field is '{}'",
// criteriaHolder.getDataType().getSimpleName()
// expect(value, number()).verify(errorType, formattedSupplier("Provided value '{}' is not a number", value));
// @Override
// public Object castValue(CriteriaHolder criteriaHolder, String values, ErrorType errorType) {
// // values cast is not required here
// return values;
/**
* Exists condition
*/
EXISTS("ex") {
@Override
public org.jooq.Condition toCondition(FilterCondition filter, CriteriaHolder criteriaHolder) {
return field(filter.getSearchCriteria()).isNotNull();
}
@Override
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
// object type validations is not required here
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String values, ErrorType errorType) {
// values cast is not required here
return values;
}
},
/**
* IN condition. Accepts filter value as comma-separated list
*/
IN("in") {
@Override
public org.jooq.Condition toCondition(FilterCondition filter, CriteriaHolder criteriaHolder) {
return field(filter.getSearchCriteria()).eq(any(castValue(criteriaHolder, filter.getValue(), INCORRECT_FILTER_PARAMETERS)));
}
@Override
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
// object type validations is not required here
}
@Override
public Object[] castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return castArray(criteriaHolder, value, errorType);
}
},
/**
* HAS condition. Accepts filter value as comma-separated list. Returns
* 'TRUE' of all provided values exist in collection<br>
* <b>Applicable only for collections</b>
*/
HAS("has") {
@Override
public org.jooq.Condition toCondition(FilterCondition filter, CriteriaHolder criteriaHolder) {
/* Validate only collections */
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
return DSL.condition(Operator.AND,
Arrays.stream((Object[]) this.castValue(criteriaHolder, filter.getValue(), INCORRECT_FILTER_PARAMETERS))
.map(val -> field(filter.getSearchCriteria()).in(val))
.collect(Collectors.toList())
);
}
@Override
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, filterForCollections()).verify(errorType, formattedSupplier(
"'HAS' condition applyable only for collection data types. Type of field is '{}'",
criteriaHolder.getDataType().getSimpleName()
));
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return castArray(criteriaHolder, value, errorType);
}
},
/**
* Greater than condition
*/
GREATER_THAN("gt") {
@Override
public org.jooq.Condition toCondition(FilterCondition filter, CriteriaHolder criteriaHolder) {
/* Validate only numbers & dates */
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
return field(filter.getSearchCriteria()).greaterThan(this.castValue(criteriaHolder,
filter.getValue(),
INCORRECT_FILTER_PARAMETERS
));
}
@Override
@SuppressWarnings("unchecked")
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, or(filterForNumbers(), filterForDates(), filterForLogLevel())).verify(errorType, formattedSupplier(
"'Greater than' condition applyable only for positive Numbers or Dates. Type of field is '{}'",
criteriaHolder.getDataType().getSimpleName()
));
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return criteriaHolder.castValue(value, errorType);
}
},
/**
* Greater than or Equals condition
*/
GREATER_THAN_OR_EQUALS("gte") {
@Override
public org.jooq.Condition toCondition(FilterCondition filter, CriteriaHolder criteriaHolder) {
/* Validate only numbers & dates */
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
return field(filter.getSearchCriteria()).greaterOrEqual(this.castValue(criteriaHolder,
filter.getValue(),
INCORRECT_FILTER_PARAMETERS
));
}
@Override
@SuppressWarnings("unchecked")
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, or(filterForNumbers(), filterForDates(), filterForLogLevel())).verify(errorType, formattedSupplier(
"'Greater than or equals' condition applyable only for positive Numbers or Dates. Type of field is '{}'",
criteriaHolder.getDataType().getSimpleName()
));
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return criteriaHolder.castValue(value, errorType);
}
},
/**
* Lower than condition
*/
LOWER_THAN("lt") {
@Override
public org.jooq.Condition toCondition(FilterCondition filter, CriteriaHolder criteriaHolder) {
/* Validate only numbers & dates */
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
return field(filter.getSearchCriteria()).lessThan(this.castValue(criteriaHolder,
filter.getValue(),
INCORRECT_FILTER_PARAMETERS
));
}
@Override
@SuppressWarnings("unchecked")
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, or(filterForNumbers(), filterForDates(), filterForLogLevel())).verify(errorType, formattedSupplier(
"'Lower than' condition applyable only for positive Numbers or Dates. Type of field is '{}'",
criteriaHolder.getDataType().getSimpleName()
));
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return criteriaHolder.castValue(value, errorType);
}
},
/**
* Lower than or Equals condition
*/
LOWER_THAN_OR_EQUALS("lte") {
@Override
public org.jooq.Condition toCondition(FilterCondition filter, CriteriaHolder criteriaHolder) {
/* Validate only numbers & dates */
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
return field(filter.getSearchCriteria()).lessOrEqual(this.castValue(criteriaHolder,
filter.getValue(),
INCORRECT_FILTER_PARAMETERS
));
}
@Override
@SuppressWarnings("unchecked")
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, or(filterForNumbers(), filterForDates(), filterForLogLevel())).verify(errorType, formattedSupplier(
"'Lower than or equals' condition applyable only for positive Numbers or Dates. Type of field is '{}'",
criteriaHolder.getDataType().getSimpleName()
));
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
return criteriaHolder.castValue(value, errorType);
}
},
/**
* Between condition. Include boundaries
*/
BETWEEN("btw") {
@Override
@SuppressWarnings("unchecked")
public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType) {
expect(criteriaHolder, or(filterForNumbers(), filterForDates(), filterForLogLevel())).verify(errorType,
formattedSupplier("'Between' condition applyable only for positive Numbers, Dates or specific TimeStamp values. "
+ "Type of field is '{}'", criteriaHolder.getDataType().getSimpleName())
);
if (value.contains(VALUES_SEPARATOR)) {
expect(value.split(VALUES_SEPARATOR), countOfValues(2)).verify(errorType,
formattedSupplier("Incorrect between filter format. Expected='value1,value2'. Provided filter is '{}'", value)
);
} else if (value.contains(TIMESTAMP_SEPARATOR)) {
final String[] values = value.split(TIMESTAMP_SEPARATOR);
expect(values, countOfValues(BETWEEN_FILTER_VALUES_COUNT)).verify(errorType, formattedSupplier(
"Incorrect between filter format. Expected='TIMESTAMP_CONSTANT;TimeZoneOffset'. Provided filter is '{}'",
value
));
expect(values[ZONE_OFFSET_INDEX], zoneOffset()).verify(errorType,
formattedSupplier("Incorrect zoneOffset. Expected='+h, +hh, +hh:mm'. Provided value is '{}'", values[ZONE_OFFSET_INDEX])
);
expect(values[ZERO_TIMESTAMP_INDEX], timeStamp()).verify(errorType,
formattedSupplier("Incorrect timestamp. Expected number. Provided value is '{}'", values[ZERO_TIMESTAMP_INDEX])
);
expect(values[FIRST_TIMESTAMP_INDEX], timeStamp()).verify(errorType,
formattedSupplier("Incorrect timestamp. Expected number. Provided value is '{}'", values[FIRST_TIMESTAMP_INDEX])
);
} else {
fail().withError(errorType, formattedSupplier(
"Incorrect between filter format. Filter value should be separated by ',' or ';'. Provided filter is '{}'",
value
));
}
}
@Override
public org.jooq.Condition toCondition(FilterCondition filter, CriteriaHolder criteriaHolder) {
this.validate(criteriaHolder, filter.getValue(), filter.isNegative(), INCORRECT_FILTER_PARAMETERS);
Object[] castedValues;
if (filter.getValue().contains(",")) {
castedValues = (Object[]) this.castValue(criteriaHolder, filter.getValue(), INCORRECT_FILTER_PARAMETERS);
} else {
String[] values = filter.getValue().split(";");
ZoneOffset offset = ZoneOffset.of(values[2]);
ZonedDateTime localDateTime = ZonedDateTime.now(offset).toLocalDate().atStartOfDay(offset);
long start = from(localDateTime.plusMinutes(parseLong(values[0])).toInstant()).getTime();
long end = from(localDateTime.plusMinutes(parseLong(values[1])).toInstant()).getTime();
String newValue = start + "," + end;
castedValues = (Object[]) this.castValue(criteriaHolder, newValue, INCORRECT_FILTER_PARAMETERS);
}
return DSL.condition(Operator.AND,
field(filter.getSearchCriteria()).greaterOrEqual(castedValues[0]),
field(filter.getSearchCriteria()).lessOrEqual(castedValues[1])
);
}
@Override
public Object castValue(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
/* For linguistic dynamic date range literals */
if (value.contains(";")) {
return value;
} else {
return castArray(criteriaHolder, value, errorType);
}
}
};
/*
* Workaround. Added to be able to use as constant in annotations
*/
public static final String EQ = "eq.";
public static final String CNT = "cnt.";
public static final String VALUES_SEPARATOR = ",";
public static final String TIMESTAMP_SEPARATOR = ";";
public static final String NEGATIVE_MARKER = "!";
public static final Integer BETWEEN_FILTER_VALUES_COUNT = 3;
public static final Integer ZERO_TIMESTAMP_INDEX = 0;
public static final Integer FIRST_TIMESTAMP_INDEX = 1;
public static final Integer ZONE_OFFSET_INDEX = 2;
private String marker;
Condition(final String marker) {
this.marker = marker;
}
abstract public org.jooq.Condition toCondition(FilterCondition filter, CriteriaHolder criteriaHolder);
/**
* Validate condition value. This method should be overridden in all
* conditions which contains validations
*
* @param criteriaHolder Criteria description
* @param value Value to be casted
* @param isNegative Whether filter is negative
*/
abstract public void validate(CriteriaHolder criteriaHolder, String value, boolean isNegative, ErrorType errorType);
/**
* Cast filter values according condition.
*
* @param criteriaHolder Criteria description
* @param values Value to be casted
* @return Casted value
*/
abstract public Object castValue(CriteriaHolder criteriaHolder, String values, ErrorType errorType);
public String getMarker() {
return marker;
}
/**
* Finds condition by marker. If there is no condition with specified marker
* returns NULL
*
* @param marker Marker to be checked
* @return Condition if found or NULL
*/
public static Optional<Condition> findByMarker(String marker) {
// Negative condition excluder
if (isNegative(marker)) {
marker = marker.substring(1);
}
String finalMarker = marker;
return Arrays.stream(values()).filter(it -> it.getMarker().equals(finalMarker)).findAny();
}
/**
* Check whether condition is negative
*
* @param marker Marker to check
* @return TRUE of negative
*/
public static boolean isNegative(String marker) {
return marker.startsWith(NEGATIVE_MARKER);
}
/**
* Makes filter marker negative
*
* @param negative Whether condition is negative
* @param marker Marker to check
* @return TRUE of negative
*/
public static String makeNegative(boolean negative, String marker) {
String result;
if (negative) {
result = marker.startsWith(NEGATIVE_MARKER) ? marker : NEGATIVE_MARKER.concat(marker);
} else {
result = marker.startsWith(NEGATIVE_MARKER) ? marker.substring(1, marker.length()) : marker;
}
return result;
}
/**
* Cast values for filters which have many values(filters with
* conditions:btw, in, etc)
*
* @param criteriaHolder Criteria description
* @param value Value to be casted
* @return Casted value
*/
public Object[] castArray(CriteriaHolder criteriaHolder, String value, ErrorType errorType) {
String[] values = value.split(VALUES_SEPARATOR);
Object[] castedValues = new Object[values.length];
if (!String.class.equals(criteriaHolder.getDataType())) {
for (int index = 0; index < values.length; index++) {
castedValues[index] = criteriaHolder.castValue(values[index].trim(), errorType);
}
} else {
castedValues = values;
}
return castedValues;
}
}
|
package com.github.onsdigital.florence.filter;
import com.github.davidcarboni.restolino.framework.Filter;
import com.github.onsdigital.florence.configuration.Configuration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
/**
* Routes all traffic to Tredegar, Unless it is recognised as a florence file being requested.
*/
public class TredegarProxy implements Filter {
private static final String florenceToken = "/florence";
private static final String zebedeeToken = "/zebedee";
private static final String tredegarBaseUrl = Configuration.getTredegarUrl();
private static final String zebedeeBaseUrl = Configuration.getZebedeeUrl();
private static final List<String> florencePaths = Arrays.asList("/");
@Override
public boolean filter(HttpServletRequest request, HttpServletResponse response) {
String requestUri = request.getRequestURI();
String requestQueryString = request.getQueryString() != null ? request.getQueryString() : "";
try {
if (florencePaths.contains(requestUri)
|| requestUri.startsWith(florenceToken)) {
return true; // carry on and serve the file from florence
}
String requestBaseUrl = tredegarBaseUrl; // proxy to tredegar by default.
if (requestUri.startsWith(zebedeeToken)) {
requestUri = requestUri.replace(zebedeeToken, "");
requestBaseUrl = zebedeeBaseUrl;
System.out.println("Proxy request to zebedee @ " + zebedeeBaseUrl);
}
HttpRequestBase proxyRequest;
switch (request.getMethod()) {
case "POST":
proxyRequest = new HttpPost(requestBaseUrl + requestUri + "?" + requestQueryString);
((HttpPost) proxyRequest).setEntity(new InputStreamEntity(request.getInputStream()));
break;
default:
proxyRequest = new HttpGet(requestBaseUrl + requestUri + "?" + requestQueryString);
break;
}
CloseableHttpClient httpClient = HttpClients.createDefault();
// copy the request headers.
Enumeration<String> headerNames = request.getHeaderNames();
String accessToken = "";
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
if (!headerName.equals("Content-Length"))
proxyRequest.addHeader(headerName, request.getHeader(headerName));
if (headerName.equals("access_token"))
accessToken = request.getHeader("access_token");
}
if (requestBaseUrl == zebedeeBaseUrl && StringUtils.isNotEmpty(accessToken)) {
proxyRequest.addHeader("X-Florence-Token", accessToken);
}
CloseableHttpResponse proxyResponse = httpClient.execute(proxyRequest);
try {
HttpEntity responseEntity = proxyResponse.getEntity();
// copy headers from the response
for (Header header : proxyResponse.getAllHeaders()) {
response.setHeader(header.getName(), header.getValue());
}
response.setStatus(proxyResponse.getStatusLine().getStatusCode());
if (responseEntity != null && responseEntity.getContent() != null)
IOUtils.copy(responseEntity.getContent(), response.getOutputStream());
EntityUtils.consume(responseEntity);
} catch (IOException e) {
return true;
} finally {
proxyResponse.close();
}
} catch (IOException e) {
return true;
}
return false;
}
}
|
package de.hpi.bpmn2execpn.converter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import de.hpi.bpmn.BPMNDiagram;
import de.hpi.bpmn.Container;
import de.hpi.bpmn.DataObject;
import de.hpi.bpmn.Edge;
import de.hpi.bpmn.EndEvent;
import de.hpi.bpmn.IntermediateEvent;
import de.hpi.bpmn.SubProcess;
import de.hpi.bpmn.Task;
import de.hpi.bpmn.exec.ExecDataObject;
import de.hpi.bpmn2execpn.model.ExecConversionContext;
import de.hpi.bpmn2execpn.model.ExecTask;
import de.hpi.bpmn2pn.converter.Converter;
import de.hpi.bpmn2pn.model.ConversionContext;
import de.hpi.bpmn2pn.model.SubProcessPlaces;
import de.hpi.execpn.AutomaticTransition;
import de.hpi.execpn.ExecFlowRelationship;
import de.hpi.execpn.ExecPNFactory;
import de.hpi.execpn.ExecPetriNet;
import de.hpi.execpn.ExecPlace;
import de.hpi.execpn.ExecTransition;
import de.hpi.execpn.FormTransition;
import de.hpi.execpn.TransformationTransition;
import de.hpi.execpn.pnml.Locator;
import de.hpi.petrinet.FlowRelationship;
import de.hpi.petrinet.PetriNet;
import de.hpi.petrinet.Place;
import de.hpi.petrinet.Transition;
public class ExecConverter extends Converter {
private static final String baseXsltURL = "http://localhost:3000/examples/contextPlace/";
private static final String copyXsltURL = baseXsltURL + "copy_xslt.xsl";
private static final String extractDataURL = baseXsltURL + "extract_processdata.xsl";
private static final String extractFormDataURL = baseXsltURL + "extract_init_processdata.xsl";
private static final String extractAllocateDataURL = baseXsltURL + "extract_allocate_processdata.xsl";
private static final String extractFinishDataURL = baseXsltURL + "extract_finish_processdata.xsl";
private static String enginePostURL;
private String contextPath;
protected String standardModel;
protected String baseFileName;
public ExecConverter(BPMNDiagram diagram, String modelURL, String contextPath) {
super(diagram, new ExecPNFactory(modelURL));
this.standardModel = modelURL;
this.contextPath = contextPath;
}
public void setBaseFileName(String basefilename) {
this.baseFileName = basefilename;
}
@Override
protected void handleDiagram(PetriNet net, ConversionContext c) {
((ExecPetriNet) net).setName(diagram.getTitle());
}
@Override
protected void createStartPlaces(PetriNet net, ConversionContext c) {
// do nothing...: we want start transitions instead of start places
}
@Override
protected Transition addXOROptionTransition(PetriNet net, Edge e) {
String name = e.getId();
if(e.getName() != null && e.getName().length() > 0)
name = e.getName();
return addLabeledTransition(net, "option"+e.getId(), e, 0, name);
}
@Override
/* Executable BPMN diagrams shouldn't have a place at the end, because finished
* cases shouldn't leave some tokens in the net
* TODO: this override just copies the code, but don't add a place in the case, if
* there is no subprocess place endP => top processes don't have a endP yet... Is
* there any nicer solution? Perhaps through a configuration flag?
* */
protected void handleEndEvent(PetriNet net, EndEvent event, ConversionContext c) {
Container process = event.getProcess();
if (process == null) {
process = event.getParent();
}
Transition t = addLabeledTransition(net, event.getId(), event, 0, event.getLabel());
handleMessageFlow(net, event, t, t, c);
addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(event)), t);
Place p = c.getSubprocessPlaces(process).endP;
addFlowRelationship(net, t, p);
if (c.ancestorHasExcpH)
handleExceptions(net, event, t, c);
}
// TODO this is a dirty hack...
@Override
protected void handleTask(PetriNet net, Task task, ConversionContext c) {
ExecTask exTask = new ExecTask();
exTask.setId(task.getId());
exTask.setLabel(task.getLabel());
exTask.setResourceId(task.getResourceId());
String taskDesignation = exTask.getTaskDesignation();
// create model, form and bindings
String model = null;
String form = null;
String bindings = null;
exTask.pl_inited = addPlace(net, "pl_inited_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_ready = addPlace(net, "pl_ready_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_running = addPlace(net, "pl_running_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_deciding = addPlace(net, "pl_deciding_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_suspended = addPlace(net, "pl_suspended_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_complete = addPlace(net, "pl_complete_" + task.getId(), ExecPlace.Type.flow);
exTask.pl_context = addPlace(net, "pl_context_" + task.getId(), ExecPlace.Type.context);
// create transitions
AutomaticTransition enable = addAutomaticTransition(net, "tr_enable_" + task.getId(), taskDesignation);
FormTransition submit = addFormTransition(net, "tr_submit_" + task.getId(), task.getLabel());
FormTransition delegate = addFormTransition(net, "tr_delegate_" + task.getId(), taskDesignation);
FormTransition review = addFormTransition(net, "tr_review_" + task.getId(), taskDesignation);
exTask.tr_init = addAutomaticTransition(net, "tr_init_" + task.getId(), taskDesignation);
exTask.tr_enable = enable;
exTask.tr_allocate = addTransformationTransition(net, "tr_allocate_" + task.getId(), taskDesignation,"allocate", copyXsltURL);
exTask.tr_submit = submit;
exTask.tr_delegate = delegate;
exTask.tr_review = review;
exTask.tr_done = addAutomaticTransition(net, "tr_done_" + task.getId(), taskDesignation);
exTask.tr_suspend = addTransformationTransition(net, "tr_suspend_" + task.getId(), taskDesignation, "suspend", copyXsltURL);
exTask.tr_resume = addTransformationTransition(net, "tr_resume_" + task.getId(), taskDesignation, "resume", copyXsltURL);
exTask.tr_finish = addAutomaticTransition(net, "tr_finish_" + task.getId(), taskDesignation);
exTask.tr_init.setContextPlaceID(exTask.pl_context.getId());
exTask.tr_enable.setContextPlaceID(exTask.pl_context.getId());
exTask.tr_submit.setContextPlaceID(exTask.pl_context.getId());
exTask.tr_allocate.setContextPlaceID(exTask.pl_context.getId());
exTask.tr_delegate.setContextPlaceID(exTask.pl_context.getId());
exTask.tr_review.setContextPlaceID(exTask.pl_context.getId());
exTask.tr_done.setContextPlaceID(exTask.pl_context.getId());
exTask.tr_suspend.setContextPlaceID(exTask.pl_context.getId());
exTask.tr_resume.setContextPlaceID(exTask.pl_context.getId());
exTask.tr_finish.setContextPlaceID(exTask.pl_context.getId());
// create Documents for model, form, bindings
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ;
try {
DocumentBuilder parser = factory.newDocumentBuilder ( ) ;
Document modelDoc = parser.newDocument();
//modelDoc.appendChild(modelDoc.createElement("engine-info"));
Node places = modelDoc.appendChild(modelDoc.createElement("places"));
Node data = places.appendChild(modelDoc.createElement("data"));
//Node metaData = places.appendChild(modelDoc.createElement("metadata"));
//Node processData = places.appendChild(modelDoc.createElement("processdata"));
// initialize engine Post URL
PropertiesConfiguration config = new PropertiesConfiguration("pnengine.properties");
this.enginePostURL = config.getString("pnengine.url") + "/documents/";
// interrogate all incoming data objects for task, create DataPlaces for them and create Task model
HashMap<String, Node> processdataMap = new HashMap<String, Node>();
List<Edge> edges_in = task.getIncomingEdges();
for (Edge edge : edges_in) {
if (edge.getSource() instanceof ExecDataObject) {
ExecDataObject dataObject = (ExecDataObject)edge.getSource();
Place dataPlace = ExecTask.getDataPlace(dataObject.getId());
// for incoming data objects of task: create read dependencies
addReadOnlyExecFlowRelationship(net, dataPlace, exTask.tr_enable, null);
// create XML Structure for Task
String modelXML = dataObject.getModel();
// attach to task model
Element dataEl = modelDoc.createElement("data");
dataEl.setAttribute("place_id", dataObject.getId());
//placesEl.appendChild(dataEl);
try {
Document doc = parser.parse(new InputSource(new StringReader(modelXML)));
NodeList elements = doc.getElementsByTagName("xsd:element");
//Node processdata = doc.getDocumentElement().getFirstChild().getFirstChild();
if (elements.getLength() > 0){
processdataMap.put(dataObject.getId(), elements.item(0));
// if contained in an ad-hoc subprocess, add
// data dependency
Container parent = task.getParent();
if (parent instanceof SubProcess && ((SubProcess)parent).isAdhoc()){
// TODO: Use Node List??? - ugly solution
//addDataDependeny(net, exTask, dataPlace, elements);
}
}
} catch (Exception io) {
io.printStackTrace();
}
}
}
// interrogate all outgoing data objects for task, create DataPlaces for them and create Task model
List<Edge> edges_out = task.getOutgoingEdges();
for (Edge edge : edges_out) {
if (edge.getTarget() instanceof ExecDataObject) {
ExecDataObject dataObject = (ExecDataObject)edge.getTarget();
// for incoming data objects of task: create read dependencies
if (!isContainedIn(dataObject, processdataMap)) {
// create XML Structure for Task
String modelXML = dataObject.getModel();
modelXML =
"<html xmlns=\"http:
"xmlns:xsi=\"http:
"xsi:schemaLocation=\"http:
"http:
modelXML;
try {
Document doc = parser.parse(new InputSource(new StringReader(modelXML)));
NodeList processdata = doc.getElementsByTagName("xsd:element");
//Node processdata = doc.getDocumentElement().getFirstChild().getFirstChild();
if (processdata.getLength() > 0)
processdataMap.put(dataObject.getId(), processdata.item(0));
} catch (Exception io) {
io.printStackTrace();
}
addReadOnlyExecFlowRelationship(net, ExecTask.getDataPlace(dataObject.getId()), exTask.tr_enable, null);
}
addExecFlowRelationship(net, exTask.tr_finish, ExecTask.getDataPlace(dataObject.getId()), create_extract_processdata_xsl(dataObject, parser));
addFlowRelationship(net, ExecTask.getDataPlace(dataObject.getId()), exTask.tr_finish);
}
}
// build form Document template without attributes
Document formDoc = buildFormTemplate(parser);
// adds form fields of necessary attributes
formDoc = addFormFields(formDoc, processdataMap);
// build bindings Document for attributes
Document bindDoc = buildBindingsDocument(parser);
// adds binding attributes for tags
bindDoc = addBindings(bindDoc, processdataMap);
// persist form and bindings and save URL
model = this.postDataToURL(domToString(modelDoc),enginePostURL);
form = this.postDataToURL(domToString(formDoc),enginePostURL);
String bindingsString = domToString(bindDoc);
bindings = this.postDataToURL(
bindingsString.replace("<bindings>", "").replace("</bindings>", ""),
enginePostURL);
// set URLs for transitions
submit.setModelURL(model);
submit.setFormURL(form);
submit.setBindingsURL(bindings);
delegate.setModelURL(model);
delegate.setFormURL(form);
delegate.setBindingsURL(bindings);
review.setModelURL(model);
review.setFormURL(form);
review.setBindingsURL(bindings);
} catch (ConfigurationException e1) {
e1.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException io) {
io.printStackTrace();
} catch (SAXException sax) {
sax.printStackTrace();
}
// add role dependencies
String rolename = task.getRolename();
// integrate context place
exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/startTime"));
exTask.pl_context.addLocator(new Locator("endTime", "xsd:string", "/data/metadata/endTime"));
exTask.pl_context.addLocator(new Locator("status", "xsd:string", "/data/metadata/status"));
exTask.pl_context.addLocator(new Locator("owner", "xsd:string", "/data/executiondata/owner"));
exTask.pl_context.addLocator(new Locator("isDelegated", "xsd:string", "/data/metadata/isDelegated"));
exTask.pl_context.addLocator(new Locator("isReviewed", "xsd:string", "/data/metadata/isReviewed"));
exTask.pl_context.addLocator(new Locator("reviewRequested", "xsd:string", "/data/metadata/reviewRequested"));
exTask.pl_context.addLocator(new Locator("startTime", "xsd:string", "/data/metadata/firstOwner"));
exTask.pl_context.addLocator(new Locator("actions", "xsd:string", "/data/metadata/actions"));
//init transition
addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.tr_init);
addFlowRelationship(net, exTask.tr_init, exTask.pl_inited);
//enable transition
//note: structure of context place must be initialized by engine
//addFlowRelationship(net, c.map.get(getIncomingSequenceFlow(task)), exTask.tr_enable);
addFlowRelationship(net, exTask.pl_inited, exTask.tr_enable);
addExecFlowRelationship(net, exTask.tr_enable, exTask.pl_ready, extractFormDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_enable);
addExecFlowRelationship(net, exTask.tr_enable, exTask.pl_context, baseXsltURL + "context_enable.xsl");
enable.setModelURL(model);
// allocate Transition
addFlowRelationship(net, exTask.pl_ready, exTask.tr_allocate);
addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_running, extractAllocateDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_allocate);
addExecFlowRelationship(net, exTask.tr_allocate, exTask.pl_context, baseXsltURL + "context_allocate.xsl");
exTask.tr_allocate.setRolename(rolename);
if (task.isSkippable()) {
// skip Transition
exTask.setSkippable(true);
exTask.tr_skip = addTransformationTransition(net, "tr_skip_" + task.getId(), taskDesignation, "skip", copyXsltURL);
exTask.tr_skip.setContextPlaceID(exTask.pl_context.getId());
addFlowRelationship(net, exTask.pl_ready, exTask.tr_skip);
addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_complete, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_skip);
addExecFlowRelationship(net, exTask.tr_skip, exTask.pl_context, baseXsltURL + "context_skip.xsl");
}
// submit Transition
submit.setAction("submit");
addFlowRelationship(net, exTask.pl_running, exTask.tr_submit);
addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_deciding, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_submit);
addExecFlowRelationship(net, exTask.tr_submit, exTask.pl_context, baseXsltURL + "context_submit.xsl");
exTask.tr_submit.setRolename(rolename);
submit.setFormURL(form);
submit.setBindingsURL(bindings);
// delegate Transition
delegate.setAction("delegate");
delegate.setGuard(exTask.pl_context.getId() + ".isDelegated == 'true'");
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_delegate);
addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_running, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_delegate);
addExecFlowRelationship(net, exTask.tr_delegate, exTask.pl_context, baseXsltURL + "context_delegate.xsl");
exTask.tr_delegate.setRolename(rolename);
delegate.setFormURL(form);
delegate.setBindingsURL(bindings);
// review Transition
review.setAction("review");
review.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".reviewRequested == 'true'");
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_review);
addExecFlowRelationship(net, exTask.tr_review, exTask.pl_complete, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_review);
addExecFlowRelationship(net, exTask.tr_review, exTask.pl_context, baseXsltURL + "context_review.xsl");
exTask.tr_review.setRolename(rolename);
review.setFormURL(form);
review.setBindingsURL(bindings);
// done Transition
addFlowRelationship(net, exTask.pl_deciding, exTask.tr_done);
addFlowRelationship(net, exTask.tr_done, exTask.pl_complete);
addFlowRelationship(net, exTask.pl_context, exTask.tr_done);
addExecFlowRelationship(net, exTask.tr_done, exTask.pl_context, baseXsltURL + "context_done.xsl");
exTask.tr_done.setGuard(exTask.pl_context.getId() + ".isDelegated != 'true' && " + exTask.pl_context.getId() + ".reviewRequested != 'true'");
// suspend
addFlowRelationship(net, exTask.pl_running, exTask.tr_suspend);
addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_suspended, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_suspend);
addExecFlowRelationship(net, exTask.tr_suspend, exTask.pl_context, baseXsltURL + "context_suspend.xsl");
exTask.tr_suspend.setRolename(rolename);
// resume
addFlowRelationship(net, exTask.pl_suspended, exTask.tr_resume);
addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_running, extractDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_resume);
addExecFlowRelationship(net, exTask.tr_resume, exTask.pl_context, baseXsltURL + "context_resume.xsl");
exTask.tr_resume.setRolename(rolename);
// finish transition
addFlowRelationship(net, exTask.pl_complete, exTask.tr_finish);
addExecFlowRelationship(net, exTask.tr_finish, c.map.get(getOutgoingSequenceFlow(task)), extractFinishDataURL);
addFlowRelationship(net, exTask.pl_context, exTask.tr_finish);
addExecFlowRelationship(net, exTask.tr_finish, exTask.pl_context, baseXsltURL + "context_finish.xsl");
assert(c instanceof ExecConversionContext);
((ExecConversionContext)c).addToSubprocessToExecTasksMap(task.getParent(), exTask);
handleMessageFlow(net, task, exTask.tr_allocate, exTask.tr_submit, c);
if (c.ancestorHasExcpH)
handleExceptions(net, task, exTask.tr_submit, c);
for (IntermediateEvent event : task.getAttachedEvents())
handleAttachedIntermediateEventForTask(net, event, c);
}
@Override
protected void handleSubProcess(PetriNet net, SubProcess process,
ConversionContext c) {
super.handleSubProcess(net, process, c);
if (process.isAdhoc()) {
handleAdHocSubProcess(net, process, c);
}
}
protected void handleAdHocSubProcess(PetriNet net, SubProcess process, ConversionContext c) {
SubProcessPlaces pl = c.getSubprocessPlaces(process);
boolean isParallel = process.isParallelOrdering();
// start and end transitions
Transition startT = addSilentTransition(net, "ad-hoc_start_" + process.getId(), process, 1);
Transition endT = addSilentTransition(net, "ad-hoc_end_" + process.getId(), process, 1);
Transition defaultEndT = addSilentTransition(net, "ad-hoc_defaultEnd_" + process.getId(), process, 1);
addFlowRelationship(net, pl.startP, startT);
addFlowRelationship(net, defaultEndT, pl.endP);
addFlowRelationship(net, endT, pl.endP);
// standard completion condition check
Place updatedState = addPlace(net, "ad-hoc_updatedState_" + process.getId());
String completionConditionString = getCompletionConditionString(process);
if (completionConditionString.length() == 0) {
completionConditionString = "false";
}
ExecTransition finalize = (ExecTransition)addSilentTransition(net, "ad-hoc_finalize_" + process.getId(), process, 0);
finalize.setGuard(completionConditionString);
ExecTransition resume = (ExecTransition)addSilentTransition(net, "ad-hoc_resume_" + process.getId(), process, 0);
resume.setGuard("!("+completionConditionString+")" );
// synchronization and completionCondition checks(synch, corresponds to enableStarting)
Place synch = addPlace(net, "ad-hoc_synch_" + process.getId());
addFlowRelationship(net, startT, synch);
addFlowRelationship(net, synch, defaultEndT);
addFlowRelationship(net, updatedState, resume);
addFlowRelationship(net, updatedState, finalize);
if (isParallel){
addFlowRelationship(net, synch, finalize);
} else {
addFlowRelationship(net, resume, synch);
}
// data place specific constructs
List<Place> dataObjectPlaces = getAccessedDataObjectsPlaces(process);
for (Place place : dataObjectPlaces){
addReadOnlyFlowRelationship(net, place, resume);
addReadOnlyFlowRelationship(net, place, finalize);
}
// task specific constructs
assert (c instanceof ExecConversionContext);
List<ExecTask> taskList = ((ExecConversionContext)c).subprocessToExecTasksMap.get(process);
if (taskList != null) {
for (ExecTask exTask : taskList) {
Place enabled = addPlace(net, "ad-hoc_task_enabled_" + exTask.getId());
Place executed = addPlace(net, "ad-hoc_task_executed_" + exTask.getId());
addFlowRelationship(net, startT, enabled);
addFlowRelationship(net, enabled, exTask.tr_init);
if (isParallel){
addReadOnlyFlowRelationship(net, synch, exTask.tr_allocate);
} else {
addFlowRelationship(net, synch, exTask.tr_allocate);
}
addFlowRelationship(net, exTask.tr_finish, executed);
addFlowRelationship(net, exTask.tr_finish, updatedState);
addFlowRelationship(net, executed, defaultEndT);
if (exTask.isSkippable()) {
addFlowRelationship(net, synch, exTask.tr_skip);
}
// let completioncondition cheks access the context place
addReadOnlyFlowRelationship(net, exTask.pl_context, resume);
addReadOnlyFlowRelationship(net, exTask.pl_context, finalize);
// finishing construct(finalize with skip, finish and abort)
Place enableFinalize = addPlace(net, "ad-hoc_enable_finalize_task_" + exTask.getId());
Place taskFinalized = addPlace(net, "ad-hoc_task_finalized_" + exTask.getId());
Transition skipReady = addSilentTransition(net, "ad-hoc_skipready_task_" + exTask.getId(), exTask, 0);
Transition skipEnabled = addSilentTransition(net, "ad-hoc_skipenabled_task_" + exTask.getId(), exTask, 0);
Transition finish = addSilentTransition(net, "ad-hoc_finish_task_" + exTask.getId(), exTask, 0);
addFlowRelationship(net, finalize, enableFinalize);
addFlowRelationship(net, enableFinalize, skipReady);
addFlowRelationship(net, exTask.pl_ready, skipReady);
addFlowRelationship(net, skipReady, taskFinalized);
addFlowRelationship(net, enableFinalize, skipEnabled);
addFlowRelationship(net, enabled, skipEnabled);
addFlowRelationship(net, skipEnabled, taskFinalized);
addFlowRelationship(net, enableFinalize, finish);
addFlowRelationship(net, executed, finish);
addFlowRelationship(net, finish, taskFinalized);
addFlowRelationship(net, taskFinalized, endT);
}
}
}
private String getCompletionConditionString(SubProcess adHocSubprocess){
assert (adHocSubprocess.isAdhoc());
StringBuffer result = new StringBuffer();
String input = adHocSubprocess.getCompletionCondition();
if (input != null && !input.equals("")){
Pattern pattern = Pattern.compile(
"stateExpression\\( *'(\\w*)' *, *'(\\w*)' *\\)|"+
"dataExpression\\( *'(\\w*)' *, *'(\\w*)' *, *'(\\w*)' *\\)|"+
"(&)|(\\|)|(\\()|(\\))|(!)");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String groupStateExpr1 = matcher.group(1);
String groupStateExpr2 = matcher.group(2);
String groupDataExpr1 = matcher.group(3);
String groupDataExpr2 = matcher.group(4);
String groupDataExpr3 = matcher.group(5);
String groupAnd = matcher.group(6);
String groupOr = matcher.group(7);
String groupLP = matcher.group(8);
String groupRP = matcher.group(9);
String groupNot = matcher.group(10);
if (groupStateExpr1 != null && groupStateExpr2 != null){
result.append("place_pl_context_"+groupStateExpr1+".status=='"+groupStateExpr2+"'");
} else if (groupDataExpr1 != null && groupDataExpr2 != null && groupDataExpr3 != null){
result.append("place_pl_data_"+groupDataExpr1+"."+groupDataExpr2+"=='"+groupDataExpr3+"'");
} else if (groupAnd != null) {
result.append("&&");
} else if (groupOr != null) {
result.append("||");
} else if (groupLP != null) {
result.append(groupLP);
} else if (groupRP != null) {
result.append(groupRP);
} else if (groupNot != null) {
result.append(groupNot);
}
}
}
return result.toString();
}
private List<Place> getAccessedDataObjectsPlaces(SubProcess adHocSubprocess){
assert (adHocSubprocess.isAdhoc());
List<Place> list = new ArrayList<Place>();
String input = adHocSubprocess.getCompletionCondition();
if (input != null && !input.equals("")){
Pattern pattern = Pattern.compile("dataExpression\\( *'(\\w*)' *, *'(\\w*)' *, *'(\\w*)' *\\)|");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String groupDataExpr1 = matcher.group(1);
String groupDataExpr2 = matcher.group(2);
String groupDataExpr3 = matcher.group(3);
if (groupDataExpr1 != null && groupDataExpr2 != null && groupDataExpr3 != null){
Place place = ExecTask.getDataPlace(groupDataExpr1);
if (place != null){
list.add(place);
}
}
}
}
return list;
}
private void addDataDependeny(PetriNet net, ExecTask execTask, Place dataPlace, NodeList elements){
StringBuffer guardStringBuffer = new StringBuffer();
for (int i = 0 ; i<elements.getLength(); i++){
String name = elements.item(i).getAttributes().getNamedItem("name").getNodeValue();
if (guardStringBuffer.length() > 0){
guardStringBuffer.append("&&");
}
guardStringBuffer.append(dataPlace.getId()+"."+name+"!=''");
}
if (guardStringBuffer.length() > 0){
String formerGuard = execTask.tr_allocate.getGuard();
if (formerGuard != null && formerGuard.length() > 0){
guardStringBuffer.append("&&("+formerGuard+")");
}
String guardString = guardStringBuffer.toString();
execTask.tr_allocate.setGuard(guardString);
addReadOnlyFlowRelationship(net, dataPlace, execTask.tr_allocate);
}
}
@Override
protected void handleDataObject(PetriNet net, DataObject object, ConversionContext c){
try {
if (object instanceof ExecDataObject) {
ExecDataObject dataobject = (ExecDataObject) object;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ;
DocumentBuilder parser = factory.newDocumentBuilder ( ) ;
//create data place for Task
ExecPlace dataPlace = addPlace(net,"pl_data_"+dataobject.getId(), ExecPlace.Type.data);
dataPlace.setName(dataobject.getId());
ExecTask.addDataPlace(dataPlace);
// create Document for data places
Document placesDoc = parser.newDocument();
Element data = placesDoc.createElement("data");
placesDoc.appendChild(data);
Element processData = placesDoc.createElement("processdata");
data.appendChild(processData);
processData.setAttribute("name",dataobject.getId());
// receive elements
String modelXML = dataobject.getModel();
Document doc = parser.parse(new InputSource(new StringReader(modelXML)));
Node dataElement = (Element) doc.getDocumentElement().getElementsByTagName("xsd:element").item(0);
for (; dataElement != null; dataElement = dataElement.getNextSibling()) {
// fetch elements
if (dataElement.getNodeType() != Node.ELEMENT_NODE) continue;
String nodeName = dataElement.getAttributes().getNamedItem("name").getTextContent().replaceAll(" " , "");
String nodeType = dataElement.getAttributes().getNamedItem("type").getTextContent();
// append dataElements to dataPlaceModel
Element element = placesDoc.createElement(nodeName);
element.setAttribute("type", nodeType);
processData.appendChild(element);
dataPlace.setModel(domToString(placesDoc));
// for dataplaces add locators
dataPlace.addLocator(new Locator(
nodeName, nodeType, "/data/processdata/"+nodeName));
};
}
} catch (Exception io) {
io.printStackTrace();
}
}
public TransformationTransition addTransformationTransition(PetriNet net, String id, String task, String action, String xsltURL) {
TransformationTransition t =((ExecPNFactory) pnfactory).createTransformationTransition();
t.setId(id);
t.setLabel(id);
t.setTask(task);
t.setAction(action);
t.setXsltURL(xsltURL);
net.getTransitions().add(t);
return t;
}
public ExecFlowRelationship addExecFlowRelationship(PetriNet net,
de.hpi.petrinet.Node source, de.hpi.petrinet.Node target, String xsltURL) {
if (source == null || target == null)
return null;
ExecFlowRelationship rel = (ExecFlowRelationship)pnfactory.createFlowRelationship();
rel.setSource(source);
rel.setTarget(target);
rel.setTransformationURL(xsltURL);
net.getFlowRelationships().add(rel);
return rel;
}
public ExecFlowRelationship addReadOnlyExecFlowRelationship(PetriNet net,
de.hpi.petrinet.Place source, de.hpi.petrinet.Transition target, String xsltURL) {
ExecFlowRelationship rel = addExecFlowRelationship(net, source, target, xsltURL);
if (rel == null){
return null;
}
rel.setMode(ExecFlowRelationship.RELATION_MODE_READTOKEN);
return rel;
}
public FormTransition addFormTransition(PetriNet net, String id, String task) {
FormTransition t = ((ExecPNFactory)pnfactory).createFormTransition();
t.setId(id);
t.setLabel(id);
t.setTask(task);
net.getTransitions().add(t);
return t;
}
public AutomaticTransition addAutomaticTransition(PetriNet net, String id, String task) {
AutomaticTransition t = ((ExecPNFactory)pnfactory).createAutomaticTransition();
t.setId(id);
t.setLabel(id);
t.setTask(task);
t.setXsltURL(copyXsltURL);
net.getTransitions().add(t);
return t;
}
public ExecPlace addPlace(PetriNet net, String id, ExecPlace.Type type) {
ExecPlace p = (ExecPlace)((ExecPNFactory)pnfactory).createPlace();
p.setId(id);
if (type != null)
p.setType(type);
net.getPlaces().add(p);
return p;
}
Document buildFormTemplate(DocumentBuilder parser)
throws IOException, SAXException{
Document template = parser.parse(new File(contextPath+"execution/form.xml"));
return template;
}
// build Structure for forms: go for all data/processdata child nodes
Document addFormFields(Document doc, HashMap<String, Node> processdataMap) {
Node root = doc.getFirstChild();
Element div = doc.createElement("div");
div.setAttribute("class", "formatted");
root.appendChild(div);
div.appendChild(doc.createElement("br"));
Element table = doc.createElement("table");
div.appendChild(table);
Element trhead = doc.createElement("tr");
table.appendChild(trhead);
Element th1 = doc.createElement("th");
trhead.appendChild(th1);
Element th2 = doc.createElement("th");
trhead.appendChild(th2);
Element th3 = doc.createElement("th");
trhead.appendChild(th3);
Element th4 = doc.createElement("th");
trhead.appendChild(th4);
Element th5 = doc.createElement("th");
trhead.appendChild(th5);
th3.setAttribute("align", "left");
th3.setTextContent("Values");
Element xgroup1 = doc.createElement("x:group");
th5.appendChild(xgroup1);
xgroup1.setAttribute("ref", "instance('ui_settings')/delegationstate");
Element xgroup2 = doc.createElement("x:group");
th5.appendChild(xgroup2);
xgroup2.setAttribute("ref", "instance('ui_settings')/reevaluationstate");
xgroup2.setTextContent("Recent Values");
for (String dataObjectName : processdataMap.keySet()){
Node processDataChild = processdataMap.get(dataObjectName);
do {
if (processDataChild == null) break;
if (processDataChild.getNodeType() != Node.ELEMENT_NODE) continue;
String attributeName, attributeType;
Node name = processDataChild.getAttributes().getNamedItem("name");
if (name == null) continue;
attributeName = name.getNodeValue().replaceAll(" " , "");
Node type = processDataChild.getAttributes().getNamedItem("type");
if (type == null) continue;
attributeType = type.getNodeValue();
// for template watch in engine folder "/public/examples/delegation/formulartemplate"
Element trbody = doc.createElement("tr");
table.appendChild(trbody);
Element td1 = doc.createElement("td");
trbody.appendChild(td1);
Element td2 = doc.createElement("td");
trbody.appendChild(td2);
Element td3 = doc.createElement("td");
trbody.appendChild(td3);
Element td4 = doc.createElement("td");
trbody.appendChild(td4);
Element td5 = doc.createElement("td");
trbody.appendChild(td5);
td1.setTextContent(name.getNodeValue());
Element nameinput = doc.createElement("x:input");
nameinput.setAttribute("ref", "instance('output-token')/places/processdata[@name='"+dataObjectName+"']/" + attributeName);
nameinput.setAttribute("class", "inputclass");
td3.appendChild(nameinput);
Element reevaluationgroup = doc.createElement("x:group");
reevaluationgroup.setAttribute("ref", "instance('ui_settings')/reevaluationstate");
td5.appendChild(reevaluationgroup);
// REEVALUATION values displaying
// end REEVALUATION values displaying
div.appendChild(doc.createElement("br"));
div.appendChild(doc.createElement("br"));
} while ((processDataChild = processDataChild.getNextSibling()) != null);
}
{
Element group = doc.createElement("x:group");
group.setAttribute("bind", "delegationstate");
root.appendChild(group);
//delegateButton
Element deltrigger = doc.createElement("x:trigger");
deltrigger.setAttribute("ref", "instance('ui_settings')/delegatebutton");
group.appendChild(deltrigger);
Element dellabel = doc.createElement("x:label");
dellabel.setTextContent("Delegate");
deltrigger.appendChild(dellabel);
Element delaction = doc.createElement("x:action");
delaction.setAttribute("ev:event", "DOMActivate");
deltrigger.appendChild(delaction);
Element delaction2 = doc.createElement("x:action");
delaction2.setAttribute("ev:event", "DOMActivate");
deltrigger.appendChild(delaction2);
Element send = doc.createElement("x:send");
send.setAttribute("submission", "form1");
delaction2.appendChild(send);
//values
Element value1 = doc.createElement("x:setvalue");
value1.setAttribute("bind", "isDelegated");
value1.setTextContent("false");
delaction.appendChild(value1);
Element value2 = doc.createElement("x:setvalue");
value2.setAttribute("bind", "isReviewed");
value2.setTextContent("false");
delaction.appendChild(value2);
Element value3 = doc.createElement("x:setvalue");
value3.setAttribute("bind", "delegatedFrom");
value3.setAttribute("value", "instance('output-token')/places/metadata/owner");
delaction.appendChild(value3);
Element value4 = doc.createElement("x:setvalue");
value4.setAttribute("bind", "firstOwner");
value4.setAttribute("value", "instance('output-token')/places/metadata/owner");
delaction.appendChild(value4);
Element value5 = doc.createElement("x:setvalue");
value5.setAttribute("bind", "firstOwner.readonly");
value5.setTextContent("true");
delaction.appendChild(value5);
Element value6 = doc.createElement("x:setvalue");
value6.setAttribute("bind", "owner");
value6.setAttribute("value", "instance('output-token')/places/metadata/delegate");
delaction.appendChild(value6);
for (String dataObjectName : processdataMap.keySet()){
Node processDataChild = processdataMap.get(dataObjectName);
do {
if (processDataChild == null) break;
if (processDataChild.getNodeType() != Node.ELEMENT_NODE) continue;
String attributeName, attributeType;
Node name = processDataChild.getAttributes().getNamedItem("name");
if (name == null) continue;
attributeName = name.getNodeValue().replaceAll(" " , "");
Node type = processDataChild.getAttributes().getNamedItem("type");
if (type == null) continue;
attributeType = type.getNodeValue();
Element valuereadonly = doc.createElement("x:setvalue");
valuereadonly.setAttribute("bind", dataObjectName+"_"+attributeName + ".readonly");
valuereadonly.setAttribute("value", "instance('ui_settings')/"+dataObjectName+"_"+attributeName+"/@futurereadonly = 'true'");
delaction.appendChild(valuereadonly);
Element valuewritable = doc.createElement("x:setvalue");
valuewritable.setAttribute("bind", dataObjectName+"_"+attributeName + ".writable");
valuewritable.setAttribute("value", "instance('ui_settings')/"+dataObjectName+"_"+attributeName+"/@futurewritable = 'true'");
delaction.appendChild(valuewritable);
} while ((processDataChild = processDataChild.getNextSibling()) != null);
}
//cancelButton
Element canceltrigger = doc.createElement("x:trigger");
canceltrigger.setAttribute("ref", "instance('ui_settings')/cancelbutton");
group.appendChild(canceltrigger);
Element cancellabel = doc.createElement("x:label");
cancellabel.setTextContent("Cancel");
canceltrigger.appendChild(cancellabel);
Element cancelaction = doc.createElement("x:action");
cancelaction.setAttribute("ev:event", "DOMActivate");
canceltrigger.appendChild(cancelaction);
Element cancelaction2 = doc.createElement("x:action");
cancelaction2.setAttribute("ev:event", "DOMActivate");
canceltrigger.appendChild(cancelaction2);
Element cancelsend = doc.createElement("x:send");
cancelsend.setAttribute("submission", "form1");
cancelaction2.appendChild(cancelsend);
//values
Element cancelvalue1 = doc.createElement("x:setvalue");
cancelvalue1.setAttribute("bind", "isDelegated");
cancelvalue1.setTextContent("false");
cancelaction.appendChild(cancelvalue1);
Element cancelvalue2 = doc.createElement("x:setvalue");
cancelvalue2.setAttribute("bind", "isReviewed");
cancelvalue2.setTextContent("false");
cancelaction.appendChild(cancelvalue2);
}
{
Element group = doc.createElement("x:group");
group.setAttribute("bind", "reviewstate");
root.appendChild(group);
//reviewsubmitbutton
Element reviewtrigger = doc.createElement("x:trigger");
reviewtrigger.setAttribute("ref", "instance('ui_settings')/reviewsubmitbutton");
group.appendChild(reviewtrigger);
Element reviewlabel = doc.createElement("x:label");
reviewlabel.setTextContent("Review");
reviewtrigger.appendChild(reviewlabel);
Element reviewaction = doc.createElement("x:action");
reviewaction.setAttribute("ev:event", "DOMActivate");
reviewtrigger.appendChild(reviewaction);
Element reviewaction2 = doc.createElement("x:action");
reviewaction2.setAttribute("ev:event", "DOMActivate");
reviewtrigger.appendChild(reviewaction2);
Element reviewsend = doc.createElement("x:send");
reviewsend.setAttribute("submission", "form1");
reviewaction2.appendChild(reviewsend);
//values
Element reviewvalue1 = doc.createElement("x:setvalue");
reviewvalue1.setAttribute("bind", "wantToReview");
reviewvalue1.setTextContent("false");
reviewaction.appendChild(reviewvalue1);
Element reviewvalue2 = doc.createElement("x:setvalue");
reviewvalue2.setAttribute("bind", "isReviewed");
reviewvalue2.setTextContent("false");
reviewaction.appendChild(reviewvalue2);
}
{
Element group = doc.createElement("x:group");
group.setAttribute("bind", "executionstate");
root.appendChild(group);
//submitButton
Element submittrigger = doc.createElement("x:trigger");
submittrigger.setAttribute("ref", "instance('ui_settings')/submitbutton");
group.appendChild(submittrigger);
Element submitlabel = doc.createElement("x:label");
submitlabel.setTextContent("Submit");
submittrigger.appendChild(submitlabel);
Element submitaction = doc.createElement("x:action");
submitaction.setAttribute("ev:event", "DOMActivate");
submittrigger.appendChild(submitaction);
Element submitaction2 = doc.createElement("x:action");
submitaction2.setAttribute("ev:event", "DOMActivate");
submittrigger.appendChild(submitaction2);
Element send = doc.createElement("x:send");
send.setAttribute("submission", "form1");
submitaction2.appendChild(send);
//values
Element value1 = doc.createElement("x:setvalue");
value1.setAttribute("bind", "delegatedFrom");
value1.setTextContent("");
submitaction.appendChild(value1);
Element value2 = doc.createElement("x:setvalue");
value2.setAttribute("bind", "isDelegated");
value2.setTextContent("false");
submitaction.appendChild(value2);
Element value3 = doc.createElement("x:setvalue");
value3.setAttribute("bind", "isReviewed");
value3.setTextContent("true");
submitaction.appendChild(value3);
Element value4 = doc.createElement("x:setvalue");
value4.setAttribute("bind", "owner");
value4.setAttribute("value", "instance('output-token')/places/metadata/firstOwner");
submitaction.appendChild(value4);
for (String dataObjectName : processdataMap.keySet()){
Node processDataChild = processdataMap.get(dataObjectName);
do {
if (processDataChild == null) break;
if (processDataChild.getNodeType() != Node.ELEMENT_NODE) continue;
String attributeName, attributeType;
Node name = processDataChild.getAttributes().getNamedItem("name");
if (name == null) continue;
attributeName = name.getNodeValue().replaceAll(" " , "");
Node type = processDataChild.getAttributes().getNamedItem("type");
if (type == null) continue;
attributeType = type.getNodeValue();
Element valuereadonly = doc.createElement("x:setvalue");
valuereadonly.setAttribute("bind", dataObjectName+"_"+attributeName + ".readonly");
valuereadonly.setTextContent("false");
submitaction.appendChild(valuereadonly);
Element valuewritable = doc.createElement("x:setvalue");
valuewritable.setAttribute("bind", dataObjectName+"_"+attributeName + ".writable");
valuewritable.setTextContent("true");
submitaction.appendChild(valuewritable);
} while ((processDataChild = processDataChild.getNextSibling()) != null);
}
// interactButton
Element interacttrigger = doc.createElement("x:trigger");
interacttrigger.setAttribute("ref", "instance('ui_settings')/interactbutton");
group.appendChild(interacttrigger);
Element interactlabel = doc.createElement("x:label");
interactlabel.setTextContent("Interact");
interacttrigger.appendChild(interactlabel);
Element interactaction = doc.createElement("x:action");
interactaction.setAttribute("ev:event", "DOMActivate");
interacttrigger.appendChild(interactaction);
Element interactaction2 = doc.createElement("x:action");
interactaction2.setAttribute("ev:event", "DOMActivate");
interacttrigger.appendChild(interactaction2);
Element interactsend = doc.createElement("x:send");
interactsend.setAttribute("submission", "form1");
interactaction2.appendChild(interactsend);
//values
Element interactvalue1 = doc.createElement("x:setvalue");
interactvalue1.setAttribute("bind", "isDelegated");
interactvalue1.setTextContent("true");
interactaction.appendChild(interactvalue1);
Element interactvalue2 = doc.createElement("x:setvalue");
interactvalue2.setAttribute("bind", "isReviewed");
interactvalue2.setTextContent("false");
interactaction.appendChild(interactvalue2);
}
return doc;
}
Document buildBindingsDocument(DocumentBuilder parser)
throws IOException, SAXException{
Document bindDoc = parser.parse(new File(contextPath+"execution/bindings.xml"));
return bindDoc;
}
// build structure for bindings
Document addBindings(Document doc, HashMap<String, Node> processdataMap) {
Node root = doc.getFirstChild();
//add necessary ui_settings nodes
NodeList list = doc.getDocumentElement().getElementsByTagName("x:instance");
for (int i = 0; i < list.getLength(); i++) {
NamedNodeMap attributes = list.item(i).getAttributes();
if (attributes.getNamedItem("id").getNodeValue().equals("ui_settings")) {
for (String dataObjectName : processdataMap.keySet()){
Node processDataChild = processdataMap.get(dataObjectName);
do {
if (processDataChild == null) break;
if (processDataChild.getNodeType() != Node.ELEMENT_NODE) continue;
String attributeName, attributeType;
Node name = processDataChild.getAttributes().getNamedItem("name");
if (name == null) continue;
attributeName = name.getNodeValue().replaceAll(" " , "");
Node type = processDataChild.getAttributes().getNamedItem("type");
if (type == null) continue;
attributeType = type.getNodeValue();
Element property = doc.createElement(dataObjectName + "_" + attributeName);
property.setAttribute("futurereadonly", "false");
property.setAttribute("futurewritable", "false");
for (Node ui_setting_nodes = list.item(i).getFirstChild(); ; ui_setting_nodes = ui_setting_nodes.getNextSibling()) {
if (ui_setting_nodes.getNodeName().equals("#text")) continue;
ui_setting_nodes.appendChild(property);
break;
}
} while ((processDataChild = processDataChild.getNextSibling()) != null);
}
}
}
// add necessary token bindings
for (String dataObjectName : processdataMap.keySet()){
Node processDataChild = processdataMap.get(dataObjectName);
do {
if (processDataChild == null) break;
if (processDataChild.getNodeType() != Node.ELEMENT_NODE) continue;
String attributeName, attributeType;
Node name = processDataChild.getAttributes().getNamedItem("name");
if (name == null) continue;
attributeName = name.getNodeValue().replaceAll(" " , "");
Node type = processDataChild.getAttributes().getNamedItem("type");
if (type == null) continue;
attributeType = type.getNodeValue();
Element bind1 = doc.createElement("x:bind");
bind1.setAttribute("id", dataObjectName+"_"+attributeName);
bind1.setAttribute("nodeset", "instance('output-token')/places/processdata[" + "@name='"+dataObjectName+"'" + "]/" +attributeName);
root.appendChild(bind1);
Element bind2 = doc.createElement("x:bind");
bind2.setAttribute("id", dataObjectName+"_"+attributeName+".readonly");
bind2.setAttribute("nodeset", "instance('output-token')/places/processdata[" + "@name='"+dataObjectName+"'" + "]/" +attributeName + "/@readonly");
root.appendChild(bind2);
Element bind3 = doc.createElement("x:bind");
bind3.setAttribute("id", dataObjectName+"_"+attributeName+".writable");
bind3.setAttribute("nodeset", "instance('output-token')/places/processdata[" + "@name='"+dataObjectName+"'" + "]/" +attributeName +"/@writable");
root.appendChild(bind3);
Element bind4 = doc.createElement("x:bind");
bind4.setAttribute("type", "xsd:boolean");
bind4.setAttribute("nodeset", "instance('output-token')/places/processdata[" + "@name='"+dataObjectName+"'" + "]/" +attributeName +"/@readonly");
root.appendChild(bind4);
Element bind5 = doc.createElement("x:bind");
bind5.setAttribute("type", "xsd:boolean");
bind5.setAttribute("nodeset", "instance('output-token')/places/processdata[" + "@name='"+dataObjectName+"'" + "]/" +attributeName +"/@writable");
root.appendChild(bind5);
Element bind6 = doc.createElement("x:bind");
bind6.setAttribute("type", "xsd:boolean");
bind6.setAttribute("nodeset", "instance('ui_settings')/" + dataObjectName + "_" +attributeName +"/@futurereadonly");
bind6.setAttribute("id", dataObjectName + "_" + attributeName + ".futurereadonly");
root.appendChild(bind6);
Element bind7 = doc.createElement("x:bind");
bind7.setAttribute("type", "xsd:boolean");
bind7.setAttribute("nodeset", "instance('ui_settings')/" + dataObjectName + "_" +attributeName +"/@futurewritable");
bind7.setAttribute("id", dataObjectName + "_" + attributeName + ".futurewritable");
root.appendChild(bind7);
Element bind8 = doc.createElement("x:bind");
bind8.setAttribute("nodeset", "instance('ui_settings')/" + dataObjectName+"_"+attributeName +"/@futurewritable");
bind8.setAttribute("relevant", "instance('output-token')/places/metadata/isDelegated = 'true' and instance('output-token')/places/processdata[" + "@name='"+dataObjectName+"'" + "]/" +attributeName +"/@writable = 'true'");
root.appendChild(bind8);
Element bind9 = doc.createElement("x:bind");
bind9.setAttribute("nodeset", "instance('ui_settings')/" + dataObjectName+"_"+attributeName +"/@futurereadonly");
bind9.setAttribute("relevant", "instance('output-token')/places/metadata/isDelegated = 'true' and ((instance('output-token')/places/processdata[" + "@name='"+dataObjectName+"'" + "]/" +attributeName +"/@readonly = 'true' and instance('output-token')/places/processdata[" + "@name='"+dataObjectName+"'" + "]/" +attributeName +"/@writable != 'true') or instance('output-token')/places/processdata[" + "@name='"+dataObjectName+"'" + "]/" +attributeName +"/@writable = 'true')");
root.appendChild(bind9);
Element bind10 = doc.createElement("x:bind");
bind10.setAttribute("nodeset", "instance('output-token')/places/processdata[" + "@name='"+dataObjectName+"'" + "]/" +attributeName);
bind10.setAttribute("readonly", "instance('output-token')/places/processdata[" + "@name='"+dataObjectName+"'" + "]/" +attributeName +"/@readonly = 'true'");
root.appendChild(bind10);
Element bind11 = doc.createElement("x:bind");
bind11.setAttribute("nodeset", "instance('ui_settings')/" + dataObjectName+"_"+attributeName);
bind11.setAttribute("relevant", "not(instance('output-token')/places/processdata[" + "@name='"+dataObjectName+"'" + "]/" +attributeName +"/@writable != 'true' and instance('output-token')/places/processdata[" + "@name='"+dataObjectName+"'" + "]/" +attributeName +"/@readonly != 'true')");
bind11.setAttribute("id", "fade." + dataObjectName+"_"+attributeName);
root.appendChild(bind11);
Element bind12 = doc.createElement("x:bind");
bind12.setAttribute("nodeset", "instance('ui_settings')/" + dataObjectName+"_"+attributeName +"/@futurewritable");
bind12.setAttribute("readonly", "instance('ui_settings')/" + dataObjectName+"_"+attributeName +"/@futurereadonly = 'true'");
root.appendChild(bind12);
Element bind13 = doc.createElement("x:bind");
bind13.setAttribute("nodeset", "instance('ui_settings')/" + dataObjectName+"_"+attributeName +"/@futurereadonly");
bind13.setAttribute("readonly", "instance('ui_settings')/" + dataObjectName+"_"+attributeName +"/@futurewritable = 'true'");
root.appendChild(bind13);
} while ((processDataChild = processDataChild.getNextSibling()) != null);
}
return doc;
}
@Override
protected ConversionContext setupConversionContext() {
return new ExecConversionContext();
}
/**
* Writes *requestData* to url *targetURL* as form-data
* This is the same as pressing submit on a POST type HTML form
* Throws:
* MalformedURLException for bad URL String
* IOException when connection can not be made, or error when
* reading response
* TODO: HOW DOES IT WORK KAI??
*
* @param requestData string to POST to the URL.
* empty for no post data
* @param targetURL string of url to post to
* and read response.
* @return string response from url.
*/
private String postDataToURL(String requestData,
String targetURL)
throws MalformedURLException, IOException {
String URLResponse = "";
// open the connection and prepare it to POST
URL url = new URL(targetURL);
HttpURLConnection URLconn = (HttpURLConnection) url.openConnection();
URLconn.setDoOutput(true);
URLconn.setDoInput(true);
URLconn.setAllowUserInteraction(false);
URLconn.setUseCaches (false);
URLconn.setRequestMethod("POST");
URLconn.setRequestProperty("Content-Length", "" + requestData.length());
URLconn.setRequestProperty("Content-Language", "en-US");
URLconn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
URLconn.setRequestProperty("Authorization", "Basic a2Fp0g==");
DataOutputStream dataOutStream =
new DataOutputStream(URLconn.getOutputStream());
// Send the data
dataOutStream.writeBytes(requestData);
dataOutStream.flush();
dataOutStream.close();
// Read the response
int resp = URLconn.getResponseCode();
if (URLconn.getResponseCode() == HttpURLConnection.HTTP_OK)
URLResponse = URLconn.getURL().toString();
else
throw new IOException("ResponseCode for post to engine was not OK!");
// while((nextLine = reader.readLine()) != null) {
// URLResponse += nextLine;
// reader.close();
return URLResponse;
}
/**
* checks if such a <processdata id="..."> tag exists, that conforms to dataobject id
* @param dataObject DataObject, that could be already mapped to the <data> childs
* @param list List of <data> childs
* @return is tag existent?
*/
private boolean isContainedIn(ExecDataObject dataObject, NodeList list){
for (int procdata = 0; procdata<list.getLength(); procdata++) {
NamedNodeMap attributeList = list.item(procdata).getAttributes();
for (int attr = 0; attr<attributeList.getLength(); attr++) {
Node attribute = attributeList.item(attr);
if (list.item(procdata).getNodeName() == "processData" && attribute.equals(dataObject.getId()))
return true;
}
}
return false;
}
private boolean isContainedIn(ExecDataObject dataObject, HashMap<String, Node> map){
Set<String> list = map.keySet();
if (list.contains(dataObject.getId()))
return true;
return false;
}
/**
* returns a map with key dataPlace (conforms to dataObject id) and attributes of dataObject
* @param data
* @return
*/
private HashMap<String, NodeList> getProcessDataNodes(Node data) {
HashMap<String, NodeList> targetMap = new HashMap<String, NodeList>();
NodeList list = data.getChildNodes();
for (int i = 0; i<list.getLength(); i++) {
if (list.item(i).getNodeName().equals("processdata")) {
String id = list.item(i).getAttributes().getNamedItem("id").getNodeName();
NodeList attributes = list.item(i).getChildNodes();
targetMap.put(id, attributes);
}
}
return targetMap;
}
private String domToString(Document document) {
// Normalizing the DOM
document.getDocumentElement().normalize();
StringWriter domAsString = new StringWriter();
try {
// Prepare the DOM document for writing
Source source = new DOMSource(document);
// Prepare the output file
Result result = new StreamResult(domAsString);
// Write the DOM document to the file
// Get Transformer
Transformer transformer = TransformerFactory.newInstance()
.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
// Write to a String
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
System.out.println("TransformerConfigurationException: " + e);
} catch (TransformerException e) {
System.out.println("TransformerException: " + e);
}
return domAsString.toString();
}
String create_extract_processdata_xsl(ExecDataObject dataObject, DocumentBuilder parser)
throws IOException{
Document xslDoc = parser.newDocument();
Element stylesheet = xslDoc.createElement("xsl:stylesheet");
stylesheet.setAttribute("version", "1.0");
stylesheet.setAttribute("xmlns:xsl", "http:
xslDoc.appendChild(stylesheet);
Element template = xslDoc.createElement("xsl:template");
template.setAttribute("match", "/");
stylesheet.appendChild(template);
Element data = xslDoc.createElement("data");
template.appendChild(data);
Element apply = xslDoc.createElement("xsl:apply-templates");
template.setAttribute("select", "/places/processdata");
data.appendChild(apply);
Element template2 = xslDoc.createElement("xsl:template");
template2.setAttribute("match", "processdata[@target_place=\'pl_data_"+ dataObject.getId() +"\']");
stylesheet.appendChild(template2);
Element processdata = xslDoc.createElement("processdata");
template2.appendChild(processdata);
Element attribute1 = xslDoc.createElement("xsl:attribute");
attribute1.setAttribute("name", "target_place");
processdata.appendChild(attribute1);
Element value1 = xslDoc.createElement("xsl:value-of");
value1.setAttribute("select", "@target_place");
attribute1.appendChild(value1);
Element attribute2 = xslDoc.createElement("xsl:attribute");
attribute2.setAttribute("name", "place_id");
processdata.appendChild(attribute2);
Element value2 = xslDoc.createElement("xsl:value-of");
value2.setAttribute("select", "@place_id");
attribute2.appendChild(value2);
Element attribute3 = xslDoc.createElement("xsl:attribute");
attribute3.setAttribute("name", "name");
processdata.appendChild(attribute3);
Element value3 = xslDoc.createElement("xsl:value-of");
value3.setAttribute("select", "@name");
attribute3.appendChild(value3);
Element copy = xslDoc.createElement("xsl:copy-of");
/* Test
Element template = xslDoc.createElement("xsl:template");
template.setAttribute("match", "/");
stylesheet.appendChild(template);
Element data = xslDoc.createElement("data");
template.appendChild(data);
Element copy = xslDoc.createElement("xsl:copy-of");
copy.setAttribute("select", "*");
data.appendChild(copy);
*/
return postDataToURL(domToString(xslDoc),enginePostURL);
}
public FlowRelationship addReadOnlyFlowRelationship(PetriNet net,
de.hpi.petrinet.Place source, de.hpi.petrinet.Transition target) {
ExecFlowRelationship rel = (ExecFlowRelationship)addFlowRelationship(net, source, target);
if (rel == null){
return null;
}
rel.setMode(ExecFlowRelationship.RELATION_MODE_READTOKEN);
return rel;
}
}
|
package com.alamkanak.weekview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewCompat;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.widget.OverScroller;
import android.widget.Scroller;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class WeekView extends View {
public static final int LENGTH_SHORT = 1;
public static final int LENGTH_LONG = 2;
private final Context mContext;
private Calendar mToday;
private Calendar mStartDate;
private Paint mTimeTextPaint;
private float mTimeTextWidth;
private float mTimeTextHeight;
private Paint mHeaderTextPaint;
private float mHeaderTextHeight;
private GestureDetectorCompat mGestureDetector;
private OverScroller mScroller;
private PointF mCurrentOrigin = new PointF(0f, 0f);
private Direction mCurrentScrollDirection = Direction.NONE;
private Paint mHeaderBackgroundPaint;
private float mWidthPerDay;
private Paint mDayBackgroundPaint;
private Paint mHourSeparatorPaint;
private float mHeaderMarginBottom;
private Paint mTodayBackgroundPaint;
private Paint mTodayHeaderTextPaint;
private Paint mEventBackgroundPaint;
private float mHeaderColumnWidth;
private List<EventRect> mEventRects;
private TextPaint mEventTextPaint;
private Paint mHeaderColumnBackgroundPaint;
private Scroller mStickyScroller;
private int mFetchedMonths[] = new int[3];
private boolean mRefreshEvents = false;
private float mDistanceY = 0;
private float mDistanceX = 0;
private Direction mCurrentFlingDirection = Direction.NONE;
// Attributes and their default values.
private int mHourHeight = 50;
private int mColumnGap = 10;
private int mFirstDayOfWeek = Calendar.MONDAY;
private int mTextSize = 12;
private int mHeaderColumnPadding = 10;
private int mHeaderColumnTextColor = Color.BLACK;
private int mNumberOfVisibleDays = 3;
private int mHeaderRowPadding = 10;
private int mHeaderRowBackgroundColor = Color.WHITE;
private int mDayBackgroundColor = Color.rgb(245, 245, 245);
private int mHourSeparatorColor = Color.rgb(230, 230, 230);
private int mTodayBackgroundColor = Color.rgb(239, 247, 254);
private int mHourSeparatorHeight = 2;
private int mTodayHeaderTextColor = Color.rgb(39, 137, 228);
private int mEventTextSize = 12;
private int mEventTextColor = Color.BLACK;
private int mEventPadding = 8;
private int mHeaderColumnBackgroundColor = Color.WHITE;
private int mDefaultEventColor;
private boolean mIsFirstDraw = true;
private int mDayNameLength = LENGTH_LONG;
private int mOverlappingEventGap = 0;
private int mEventMarginVertical = 0;
private Calendar mFirstVisibleDay;
private Calendar mLastVisibleDay;
// Listeners.
private EventClickListener mEventClickListener;
private EventLongPressListener mEventLongPressListener;
private MonthChangeListener mMonthChangeListener;
private final GestureDetector.SimpleOnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
mScroller.forceFinished(true);
mStickyScroller.forceFinished(true);
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (mCurrentScrollDirection == Direction.NONE) {
if (Math.abs(distanceX) > Math.abs(distanceY)){
if(distanceX > 0)
mCurrentScrollDirection = Direction.LEFT;
else
mCurrentScrollDirection = Direction.RIGHT;
mCurrentFlingDirection = mCurrentScrollDirection;
}
else {
mCurrentFlingDirection = Direction.VERTICAL;
mCurrentScrollDirection = Direction.VERTICAL;
}
}
mDistanceX = distanceX;
mDistanceY = distanceY;
invalidate();
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
mScroller.forceFinished(true);
mStickyScroller.forceFinished(true);
if (mCurrentFlingDirection.isHorizontal()){
mScroller.fling((int) mCurrentOrigin.x, 0, (int) velocityX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
}
else if (mCurrentFlingDirection == Direction.VERTICAL){
mScroller.fling(0, (int) mCurrentOrigin.y, 0, (int) velocityY, 0, 0, (int) -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 - getHeight()), 0);
}
ViewCompat.postInvalidateOnAnimation(WeekView.this);
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (mEventRects != null && mEventClickListener != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventClickListener.onEventClick(event.originalEvent, event.rectF);
playSoundEffect(SoundEffectConstants.CLICK);
break;
}
}
}
return super.onSingleTapConfirmed(e);
}
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
if (mEventLongPressListener != null && mEventRects != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventLongPressListener.onEventLongPress(event.originalEvent, event.rectF);
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
break;
}
}
}
}
};
private enum Direction {
NONE(false), VERTICAL(false), LEFT(true), RIGHT(true);
public boolean isHorizontal(){
return this.isHorizontal;
}
Direction(boolean isHorizontal){
this.isHorizontal = isHorizontal;
}
private boolean isHorizontal;
}
public WeekView(Context context) {
this(context, null);
}
public WeekView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WeekView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// Hold references.
mContext = context;
// Get the attribute values (if any).
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.WeekView, 0, 0);
try {
mFirstDayOfWeek = a.getInteger(R.styleable.WeekView_firstDayOfWeek, mFirstDayOfWeek);
mHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourHeight, mHourHeight);
mTextSize = a.getDimensionPixelSize(R.styleable.WeekView_textSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, context.getResources().getDisplayMetrics()));
mHeaderColumnPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerColumnPadding, mHeaderColumnPadding);
mColumnGap = a.getDimensionPixelSize(R.styleable.WeekView_columnGap, mColumnGap);
mHeaderColumnTextColor = a.getColor(R.styleable.WeekView_headerColumnTextColor, mHeaderColumnTextColor);
mNumberOfVisibleDays = a.getInteger(R.styleable.WeekView_noOfVisibleDays, mNumberOfVisibleDays);
mHeaderRowPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerRowPadding, mHeaderRowPadding);
mHeaderRowBackgroundColor = a.getColor(R.styleable.WeekView_headerRowBackgroundColor, mHeaderRowBackgroundColor);
mDayBackgroundColor = a.getColor(R.styleable.WeekView_dayBackgroundColor, mDayBackgroundColor);
mHourSeparatorColor = a.getColor(R.styleable.WeekView_hourSeparatorColor, mHourSeparatorColor);
mTodayBackgroundColor = a.getColor(R.styleable.WeekView_todayBackgroundColor, mTodayBackgroundColor);
mHourSeparatorHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mHourSeparatorHeight);
mTodayHeaderTextColor = a.getColor(R.styleable.WeekView_todayHeaderTextColor, mTodayHeaderTextColor);
mEventTextSize = a.getDimensionPixelSize(R.styleable.WeekView_eventTextSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mEventTextSize, context.getResources().getDisplayMetrics()));
mEventTextColor = a.getColor(R.styleable.WeekView_eventTextColor, mEventTextColor);
mEventPadding = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mEventPadding);
mHeaderColumnBackgroundColor = a.getColor(R.styleable.WeekView_headerColumnBackground, mHeaderColumnBackgroundColor);
mDayNameLength = a.getInteger(R.styleable.WeekView_dayNameLength, mDayNameLength);
mOverlappingEventGap = a.getDimensionPixelSize(R.styleable.WeekView_overlappingEventGap, mOverlappingEventGap);
mEventMarginVertical = a.getDimensionPixelSize(R.styleable.WeekView_eventMarginVertical, mEventMarginVertical);
} finally {
a.recycle();
}
init();
}
private void init() {
// Get the date today.
mToday = Calendar.getInstance();
mToday.set(Calendar.HOUR_OF_DAY, 0);
mToday.set(Calendar.MINUTE, 0);
mToday.set(Calendar.SECOND, 0);
// Scrolling initialization.
mGestureDetector = new GestureDetectorCompat(mContext, mGestureListener);
mScroller = new OverScroller(mContext);
mStickyScroller = new Scroller(mContext);
// Measure settings for time column.
mTimeTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTimeTextPaint.setTextAlign(Paint.Align.RIGHT);
mTimeTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setColor(mHeaderColumnTextColor);
Rect rect = new Rect();
mTimeTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mTimeTextWidth = mTimeTextPaint.measureText("00 PM");
mTimeTextHeight = rect.height();
mHeaderMarginBottom = mTimeTextHeight / 2;
// Measure settings for header row.
mHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mHeaderTextPaint.setColor(mHeaderColumnTextColor);
mHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mHeaderTextHeight = rect.height();
mHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
// Prepare header background paint.
mHeaderBackgroundPaint = new Paint();
mHeaderBackgroundPaint.setColor(mHeaderRowBackgroundColor);
// Prepare day background color paint.
mDayBackgroundPaint = new Paint();
mDayBackgroundPaint.setColor(mDayBackgroundColor);
// Prepare hour separator color paint.
mHourSeparatorPaint = new Paint();
mHourSeparatorPaint.setStyle(Paint.Style.STROKE);
mHourSeparatorPaint.setStrokeWidth(mHourSeparatorHeight);
mHourSeparatorPaint.setColor(mHourSeparatorColor);
// Prepare today background color paint.
mTodayBackgroundPaint = new Paint();
mTodayBackgroundPaint.setColor(mTodayBackgroundColor);
// Prepare today header text color paint.
mTodayHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTodayHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mTodayHeaderTextPaint.setTextSize(mTextSize);
mTodayHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
mTodayHeaderTextPaint.setColor(mTodayHeaderTextColor);
// Prepare event background color.
mEventBackgroundPaint = new Paint();
mEventBackgroundPaint.setColor(Color.rgb(174, 208, 238));
// Prepare header column background color.
mHeaderColumnBackgroundPaint = new Paint();
mHeaderColumnBackgroundPaint.setColor(mHeaderColumnBackgroundColor);
// Prepare event text size and color.
mEventTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
mEventTextPaint.setStyle(Paint.Style.FILL);
mEventTextPaint.setColor(mEventTextColor);
mEventTextPaint.setTextSize(mEventTextSize);
mStartDate = (Calendar) mToday.clone();
// Set default event color.
mDefaultEventColor = Color.parseColor("#9fc6e7");
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the header row.
drawHeaderRowAndEvents(canvas);
// Draw the time column and all the axes/separators.
drawTimeColumnAndAxes(canvas);
// Hide everything in the first cell (top left corner).
canvas.drawRect(0, 0, mTimeTextWidth + mHeaderColumnPadding * 2, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Hide anything that is in the bottom margin of the header row.
canvas.drawRect(mHeaderColumnWidth, mHeaderTextHeight + mHeaderRowPadding * 2, getWidth(), mHeaderRowPadding * 2 + mHeaderTextHeight + mHeaderMarginBottom + mTimeTextHeight/2 - mHourSeparatorHeight / 2, mHeaderColumnBackgroundPaint);
}
private void drawTimeColumnAndAxes(Canvas canvas) {
// Do not let the view go above/below the limit due to scrolling. Set the max and min limit of the scroll.
if (mCurrentScrollDirection == Direction.VERTICAL) {
if (mCurrentOrigin.y - mDistanceY > 0) mCurrentOrigin.y = 0;
else if (mCurrentOrigin.y - mDistanceY < -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 - getHeight())) mCurrentOrigin.y = -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 - getHeight());
else mCurrentOrigin.y -= mDistanceY;
}
// Draw the background color for the header column.
canvas.drawRect(0, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderColumnWidth, getHeight(), mHeaderColumnBackgroundPaint);
for (int i = 0; i < 24; i++) {
float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * i + mHeaderMarginBottom;
// Draw the text if its y position is not outside of the visible area. The pivot point of the text is the point at the bottom-right corner.
if (top < getHeight()) canvas.drawText(getTimeString(i), mTimeTextWidth + mHeaderColumnPadding, top + mTimeTextHeight, mTimeTextPaint);
}
}
private void drawHeaderRowAndEvents(Canvas canvas) {
// Calculate the available width for each day.
mHeaderColumnWidth = mTimeTextWidth + mHeaderColumnPadding *2;
mWidthPerDay = getWidth() - mHeaderColumnWidth - mColumnGap * (mNumberOfVisibleDays - 1);
mWidthPerDay = mWidthPerDay/mNumberOfVisibleDays;
// If the week view is being drawn for the first time, then consider the first day of week.
if (mIsFirstDraw && mNumberOfVisibleDays >= 7) {
if (mToday.get(Calendar.DAY_OF_WEEK) != mFirstDayOfWeek) {
int difference = 7 + (mToday.get(Calendar.DAY_OF_WEEK) - mFirstDayOfWeek);
mCurrentOrigin.x += (mWidthPerDay + mColumnGap) * difference;
}
mIsFirstDraw = false;
}
// Consider scroll offset.
if (mCurrentScrollDirection.isHorizontal()) mCurrentOrigin.x -= mDistanceX;
int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
float startFromPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps +
mHeaderColumnWidth;
float startPixel = startFromPixel;
// Prepare to iterate for each day.
Calendar day = (Calendar) mToday.clone();
day.add(Calendar.HOUR, 6);
// Prepare to iterate for each hour to draw the hour lines.
int lineCount = (int) ((getHeight() - mHeaderTextHeight - mHeaderRowPadding * 2 -
mHeaderMarginBottom) / mHourHeight) + 1;
lineCount = (lineCount) * (mNumberOfVisibleDays+1);
float[] hourLines = new float[lineCount * 4];
// Clear the cache for events rectangles.
if (mEventRects != null) {
for (EventRect eventRect: mEventRects) {
eventRect.rectF = null;
}
}
// Iterate through each day.
mFirstVisibleDay = (Calendar) mToday.clone();
mFirstVisibleDay.add(Calendar.DATE, leftDaysWithGaps);
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1;
dayNumber++) {
// Check if the day is today.
day = (Calendar) mToday.clone();
mLastVisibleDay = (Calendar) day.clone();
day.add(Calendar.DATE, dayNumber - 1);
mLastVisibleDay.add(Calendar.DATE, dayNumber - 2);
boolean sameDay = isSameDay(day, mToday);
// Get more events if necessary. We want to store the events 3 months beforehand. Get
// events only when it is the first iteration of the loop.
if (mEventRects == null || mRefreshEvents || (dayNumber == leftDaysWithGaps + 1 && mFetchedMonths[1] != day.get(Calendar.MONTH)+1 && day.get(Calendar.DAY_OF_MONTH) == 15)) {
getMoreEvents(day);
mRefreshEvents = false;
}
// Draw background color for each day.
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start> 0)
canvas.drawRect(start, mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom, startPixel + mWidthPerDay, getHeight(), sameDay ? mTodayBackgroundPaint : mDayBackgroundPaint);
// Prepare the separator lines for hours.
int i = 0;
for (int hourNumber = 0; hourNumber < 24; hourNumber++) {
float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * hourNumber + mTimeTextHeight/2 + mHeaderMarginBottom;
if (top > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom - mHourSeparatorHeight && top < getHeight() && startPixel + mWidthPerDay - start > 0){
hourLines[i * 4] = start;
hourLines[i * 4 + 1] = top;
hourLines[i * 4 + 2] = startPixel + mWidthPerDay;
hourLines[i * 4 + 3] = top;
i++;
}
}
// Draw the lines for hours.
canvas.drawLines(hourLines, mHourSeparatorPaint);
// Draw the events.
drawEvents(day, startPixel, canvas);
// In the next iteration, start from the next day.
startPixel += mWidthPerDay + mColumnGap;
}
// Draw the header background.
canvas.drawRect(0, 0, getWidth(), mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Draw the header row texts.
startPixel = startFromPixel;
for (int dayNumber=leftDaysWithGaps+1; dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1; dayNumber++) {
// Check if the day is today.
day = (Calendar) mToday.clone();
day.add(Calendar.DATE, dayNumber - 1);
boolean sameDay = isSameDay(day, mToday);
// Draw the day labels.
String dayLabel = String.format("%s %d/%02d", getDayName(day), day.get(Calendar.MONTH) + 1, day.get(Calendar.DAY_OF_MONTH));
canvas.drawText(dayLabel, startPixel + mWidthPerDay / 2, mHeaderTextHeight + mHeaderRowPadding, sameDay ? mTodayHeaderTextPaint : mHeaderTextPaint);
startPixel += mWidthPerDay + mColumnGap;
}
}
/**
* Draw all the events of a particular day.
* @param date The day.
* @param startFromPixel The left position of the day area. The events will never go any left from this value.
* @param canvas The canvas to draw upon.
*/
private void drawEvents(Calendar date, float startFromPixel, Canvas canvas) {
if (mEventRects != null && mEventRects.size() > 0) {
for (int i = 0; i < mEventRects.size(); i++) {
if (isSameDay(mEventRects.get(i).event.getStartTime(), date)) {
// Calculate top.
float top = mHourHeight * 24 * mEventRects.get(i).top / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 + mEventMarginVertical;
float originalTop = top;
if (top < mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2)
top = mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2;
// Calculate bottom.
float bottom = mEventRects.get(i).bottom;
bottom = mHourHeight * 24 * bottom / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 - mEventMarginVertical;
// Calculate left and right.
float left = startFromPixel + mEventRects.get(i).left * mWidthPerDay;
if (left < startFromPixel)
left += mOverlappingEventGap;
float originalLeft = left;
float right = left + mEventRects.get(i).width * mWidthPerDay;
if (right < startFromPixel + mWidthPerDay)
right -= mOverlappingEventGap;
if (left < mHeaderColumnWidth) left = mHeaderColumnWidth;
// Draw the event and the event name on top of it.
RectF eventRectF = new RectF(left, top, right, bottom);
if (bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 && left < right &&
eventRectF.right > mHeaderColumnWidth &&
eventRectF.left < getWidth() &&
eventRectF.bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom &&
eventRectF.top < getHeight() &&
left < right
) {
mEventRects.get(i).rectF = eventRectF;
mEventBackgroundPaint.setColor(mEventRects.get(i).event.getColor() == 0 ? mDefaultEventColor : mEventRects.get(i).event.getColor());
canvas.drawRect(mEventRects.get(i).rectF, mEventBackgroundPaint);
drawText(mEventRects.get(i).event.getName(), mEventRects.get(i).rectF, canvas, originalTop, originalLeft);
}
else
mEventRects.get(i).rectF = null;
}
}
}
}
/**
* Draw the name of the event on top of the event rectangle.
* @param text The text to draw.
* @param rect The rectangle on which the text is to be drawn.
* @param canvas The canvas to draw upon.
* @param originalTop The original top position of the rectangle. The rectangle may have some of its portion outside of the visible area.
* @param originalLeft The original left position of the rectangle. The rectangle may have some of its portion outside of the visible area.
*/
private void drawText(String text, RectF rect, Canvas canvas, float originalTop, float originalLeft) {
if (rect.right - rect.left - mEventPadding * 2 < 0) return;
// Get text dimensions
StaticLayout textLayout = new StaticLayout(text, mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
// Crop height
int availableHeight = (int) (rect.bottom - originalTop - mEventPadding * 2);
int lineHeight = textLayout.getHeight() / textLayout.getLineCount();
if (lineHeight < availableHeight && textLayout.getHeight() > rect.height() - mEventPadding * 2) {
int lineCount = textLayout.getLineCount();
int availableLineCount = (int) Math.floor(lineCount * availableHeight / textLayout.getHeight());
float widthAvailable = (rect.right - originalLeft - mEventPadding * 2) * availableLineCount;
textLayout = new StaticLayout(TextUtils.ellipsize(text, mEventTextPaint, widthAvailable, TextUtils.TruncateAt.END), mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
else if (lineHeight >= availableHeight) {
int width = (int) (rect.right - originalLeft - mEventPadding * 2);
textLayout = new StaticLayout(TextUtils.ellipsize(text, mEventTextPaint, width, TextUtils.TruncateAt.END), mEventTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, false);
}
// Draw text
canvas.save();
canvas.translate(originalLeft + mEventPadding, originalTop + mEventPadding);
textLayout.draw(canvas);
canvas.restore();
}
/**
* A class to hold reference to the events and their visual representation. An EventRect is
* actually the rectangle that is drawn on the calendar for a given event. There may be more
* than one rectangle for a single event (an event that expands more than one day). In that
* case two instances of the EventRect will be used for a single event. The given event will be
* stored in "originalEvent". But the event that corresponds to rectangle the rectangle
* instance will be stored in "event".
*/
private class EventRect {
public WeekViewEvent event;
public WeekViewEvent originalEvent;
public RectF rectF;
public float left;
public float width;
public float top;
public float bottom;
/**
* Create a new instance of event rect. An EventRect is actually the rectangle that is drawn
* on the calendar for a given event. There may be more than one rectangle for a single
* event (an event that expands more than one day). In that case two instances of the
* EventRect will be used for a single event. The given event will be stored in
* "originalEvent". But the event that corresponds to rectangle the rectangle instance will
* be stored in "event".
* @param event Represents the event which this instance of rectangle represents.
* @param originalEvent The original event that was passed by the user.
* @param rectF The rectangle.
*/
public EventRect(WeekViewEvent event, WeekViewEvent originalEvent, RectF rectF) {
this.event = event;
this.rectF = rectF;
this.originalEvent = originalEvent;
}
}
/**
* Gets more events of one/more month(s) if necessary. This method is called when the user is
* scrolling the week view. The week view stores the events of three months: the visible month,
* the previous month, the next month.
* @param day The day where the user is currently is.
*/
private void getMoreEvents(Calendar day) {
// Delete all events if its not current month +- 1.
deleteFarMonths(day);
// Get more events if the month is changed.
if (mEventRects == null)
mEventRects = new ArrayList<EventRect>();
if (mMonthChangeListener == null && !isInEditMode())
throw new IllegalStateException("You must provide a MonthChangeListener");
// If a refresh was requested then reset some variables.
if (mRefreshEvents) {
mEventRects.clear();
mFetchedMonths = new int[3];
}
// Get events of previous month.
int previousMonth = (day.get(Calendar.MONTH) == 0?12:day.get(Calendar.MONTH));
int nextMonth = (day.get(Calendar.MONTH)+2 == 13 ?1:day.get(Calendar.MONTH)+2);
int[] lastFetchedMonth = mFetchedMonths.clone();
if (mFetchedMonths[0] < 1 || mFetchedMonths[0] != previousMonth || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, previousMonth) && !isInEditMode()){
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange((previousMonth==12)?day.get(Calendar.YEAR)-1:day.get(Calendar.YEAR), previousMonth);
sortEvents(events);
for (WeekViewEvent event: events) {
cacheEvent(event);
}
}
mFetchedMonths[0] = previousMonth;
}
// Get events of this month.
if (mFetchedMonths[1] < 1 || mFetchedMonths[1] != day.get(Calendar.MONTH)+1 || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, day.get(Calendar.MONTH)+1) && !isInEditMode()) {
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange(day.get(Calendar.YEAR), day.get(Calendar.MONTH) + 1);
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
}
mFetchedMonths[1] = day.get(Calendar.MONTH)+1;
}
// Get events of next month.
if (mFetchedMonths[2] < 1 || mFetchedMonths[2] != nextMonth || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, nextMonth) && !isInEditMode()) {
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange(nextMonth == 1 ? day.get(Calendar.YEAR) + 1 : day.get(Calendar.YEAR), nextMonth);
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
}
mFetchedMonths[2] = nextMonth;
}
// Prepare to calculate positions of each events.
ArrayList<EventRect> tempEvents = new ArrayList<EventRect>(mEventRects);
mEventRects = new ArrayList<EventRect>();
Calendar dayCounter = (Calendar) day.clone();
dayCounter.add(Calendar.MONTH, -1);
dayCounter.set(Calendar.DAY_OF_MONTH, 1);
Calendar maxDay = (Calendar) day.clone();
maxDay.add(Calendar.MONTH, 1);
maxDay.set(Calendar.DAY_OF_MONTH, maxDay.getActualMaximum(Calendar.DAY_OF_MONTH));
// Iterate through each day to calculate the position of the events.
while (dayCounter.getTimeInMillis() <= maxDay.getTimeInMillis()) {
ArrayList<EventRect> eventRects = new ArrayList<EventRect>();
for (EventRect eventRect : tempEvents) {
if (isSameDay(eventRect.event.getStartTime(), dayCounter))
eventRects.add(eventRect);
}
computePositionOfEvents(eventRects);
dayCounter.add(Calendar.DATE, 1);
}
}
private void cacheEvent(WeekViewEvent event) {
if (!isSameDay(event.getStartTime(), event.getEndTime())) {
Calendar endTime = (Calendar) event.getStartTime().clone();
endTime.set(Calendar.HOUR_OF_DAY, 23);
endTime.set(Calendar.MINUTE, 59);
Calendar startTime = (Calendar) event.getEndTime().clone();
startTime.set(Calendar.HOUR_OF_DAY, 00);
startTime.set(Calendar.MINUTE, 0);
WeekViewEvent event1 = new WeekViewEvent(event.getId(), event.getName(), event.getStartTime(), endTime);
event1.setColor(event.getColor());
WeekViewEvent event2 = new WeekViewEvent(event.getId(), event.getName(), startTime, event.getEndTime());
event2.setColor(event.getColor());
mEventRects.add(new EventRect(event1, event, null));
mEventRects.add(new EventRect(event2, event, null));
}
else
mEventRects.add(new EventRect(event, event, null));
}
/**
* Sorts the events in ascending order.
* @param events The events to be sorted.
*/
private void sortEvents(List<WeekViewEvent> events) {
Collections.sort(events, new Comparator<WeekViewEvent>() {
@Override
public int compare(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
int comparator = start1 > start2 ? 1 : (start1 < start2 ? -1 : 0);
if (comparator == 0) {
long end1 = event1.getEndTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
comparator = end1 > end2 ? 1 : (end1 < end2 ? -1 : 0);
}
return comparator;
}
});
}
/**
* Calculates the left and right positions of each events. This comes handy specially if events
* are overlapping.
* @param eventRects The events along with their wrapper class.
*/
private void computePositionOfEvents(List<EventRect> eventRects) {
// Make "collision groups" for all events that collide with others.
List<List<EventRect>> collisionGroups = new ArrayList<List<EventRect>>();
for (EventRect eventRect : eventRects) {
boolean isPlaced = false;
outerLoop:
for (List<EventRect> collisionGroup : collisionGroups) {
for (EventRect groupEvent : collisionGroup) {
if (isEventsCollide(groupEvent.event, eventRect.event)) {
collisionGroup.add(eventRect);
isPlaced = true;
break outerLoop;
}
}
}
if (!isPlaced) {
List<EventRect> newGroup = new ArrayList<EventRect>();
newGroup.add(eventRect);
collisionGroups.add(newGroup);
}
}
for (List<EventRect> collisionGroup : collisionGroups) {
expandEventsToMaxWidth(collisionGroup);
}
}
/**
* Expands all the events to maximum possible width. The events will try to occupy maximum
* space available horizontally.
* @param collisionGroup The group of events which overlap with each other.
*/
private void expandEventsToMaxWidth(List<EventRect> collisionGroup) {
// Expand the events to maximum possible width.
List<List<EventRect>> columns = new ArrayList<List<EventRect>>();
columns.add(new ArrayList<EventRect>());
for (EventRect eventRect : collisionGroup) {
boolean isPlaced = false;
for (List<EventRect> column : columns) {
if (column.size() == 0) {
column.add(eventRect);
isPlaced = true;
}
else if (!isEventsCollide(eventRect.event, column.get(column.size()-1).event)) {
column.add(eventRect);
isPlaced = true;
break;
}
}
if (!isPlaced) {
List<EventRect> newColumn = new ArrayList<EventRect>();
newColumn.add(eventRect);
columns.add(newColumn);
}
}
// Calculate left and right position for all the events.
int maxRowCount = columns.get(0).size();
for (int i = 0; i < maxRowCount; i++) {
// Set the left and right values of the event.
float j = 0;
for (List<EventRect> column : columns) {
if (column.size() >= i+1) {
EventRect eventRect = column.get(i);
eventRect.width = 1f / columns.size();
eventRect.left = j / columns.size();
eventRect.top = eventRect.event.getStartTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getStartTime().get(Calendar.MINUTE);
eventRect.bottom = eventRect.event.getEndTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getEndTime().get(Calendar.MINUTE);
mEventRects.add(eventRect);
}
j++;
}
}
}
/**
* Checks if two events overlap.
* @param event1 The first event.
* @param event2 The second event.
* @return true if the events overlap.
*/
private boolean isEventsCollide(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long end1 = event1.getEndTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
return !((start1 >= end2) || (end1 <= start2));
}
/**
* Checks if time1 occurs after (or at the same time) time2.
* @param time1 The time to check.
* @param time2 The time to check against.
* @return true if time1 and time2 are equal or if time1 is after time2. Otherwise false.
*/
private boolean isTimeAfterOrEquals(Calendar time1, Calendar time2) {
return !(time1 == null || time2 == null) && time1.getTimeInMillis() >= time2.getTimeInMillis();
}
/**
* Deletes the events of the months that are too far away from the current month.
* @param currentDay The current day.
*/
private void deleteFarMonths(Calendar currentDay) {
if (mEventRects == null) return;
Calendar nextMonth = (Calendar) currentDay.clone();
nextMonth.add(Calendar.MONTH, 1);
nextMonth.set(Calendar.DAY_OF_MONTH, nextMonth.getActualMaximum(Calendar.DAY_OF_MONTH));
nextMonth.set(Calendar.HOUR_OF_DAY, 12);
nextMonth.set(Calendar.MINUTE, 59);
nextMonth.set(Calendar.SECOND, 59);
Calendar prevMonth = (Calendar) currentDay.clone();
prevMonth.add(Calendar.MONTH, -1);
prevMonth.set(Calendar.DAY_OF_MONTH, 1);
prevMonth.set(Calendar.HOUR_OF_DAY, 0);
prevMonth.set(Calendar.MINUTE, 0);
prevMonth.set(Calendar.SECOND, 0);
List<EventRect> newEvents = new ArrayList<EventRect>();
for (EventRect eventRect : mEventRects) {
boolean isFarMonth = eventRect.event.getStartTime().getTimeInMillis() > nextMonth.getTimeInMillis() || eventRect.event.getEndTime().getTimeInMillis() < prevMonth.getTimeInMillis();
if (!isFarMonth) newEvents.add(eventRect);
}
mEventRects.clear();
mEventRects.addAll(newEvents);
}
// Functions related to setting and getting the properties.
public void setOnEventClickListener (EventClickListener listener) {
this.mEventClickListener = listener;
}
public EventClickListener getEventClickListener() {
return mEventClickListener;
}
public MonthChangeListener getMonthChangeListener() {
return mMonthChangeListener;
}
public void setMonthChangeListener(MonthChangeListener monthChangeListener) {
this.mMonthChangeListener = monthChangeListener;
}
public EventLongPressListener getEventLongPressListener() {
return mEventLongPressListener;
}
public void setEventLongPressListener(EventLongPressListener eventLongPressListener) {
this.mEventLongPressListener = eventLongPressListener;
}
/**
* Get the number of visible days in a week.
* @return The number of visible days in a week.
*/
public int getNumberOfVisibleDays() {
return mNumberOfVisibleDays;
}
/**
* Set the number of visible days in a week.
* @param numberOfVisibleDays The number of visible days in a week.
*/
public void setNumberOfVisibleDays(int numberOfVisibleDays) {
this.mNumberOfVisibleDays = numberOfVisibleDays;
mCurrentOrigin.x = 0;
mCurrentOrigin.y = 0;
invalidate();
}
public int getHourHeight() {
return mHourHeight;
}
public void setHourHeight(int hourHeight) {
mHourHeight = hourHeight;
invalidate();
}
public int getColumnGap() {
return mColumnGap;
}
public void setColumnGap(int columnGap) {
mColumnGap = columnGap;
invalidate();
}
public int getFirstDayOfWeek() {
return mFirstDayOfWeek;
}
/**
* Set the first day of the week. First day of the week is used only when the week view is first
* drawn. It does not of any effect after user starts scrolling horizontally.
* <p>
* <b>Note:</b> This method will only work if the week view is set to display more than 6 days at
* once.
* </p>
* @param firstDayOfWeek The supported values are {@link java.util.Calendar#SUNDAY},
* {@link java.util.Calendar#MONDAY}, {@link java.util.Calendar#TUESDAY},
* {@link java.util.Calendar#WEDNESDAY}, {@link java.util.Calendar#THURSDAY},
* {@link java.util.Calendar#FRIDAY}.
*/
public void setFirstDayOfWeek(int firstDayOfWeek) {
mFirstDayOfWeek = firstDayOfWeek;
invalidate();
}
public int getTextSize() {
return mTextSize;
}
public void setTextSize(int textSize) {
mTextSize = textSize;
mTodayHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setTextSize(mTextSize);
invalidate();
}
public int getHeaderColumnPadding() {
return mHeaderColumnPadding;
}
public void setHeaderColumnPadding(int headerColumnPadding) {
mHeaderColumnPadding = headerColumnPadding;
invalidate();
}
public int getHeaderColumnTextColor() {
return mHeaderColumnTextColor;
}
public void setHeaderColumnTextColor(int headerColumnTextColor) {
mHeaderColumnTextColor = headerColumnTextColor;
invalidate();
}
public int getHeaderRowPadding() {
return mHeaderRowPadding;
}
public void setHeaderRowPadding(int headerRowPadding) {
mHeaderRowPadding = headerRowPadding;
invalidate();
}
public int getHeaderRowBackgroundColor() {
return mHeaderRowBackgroundColor;
}
public void setHeaderRowBackgroundColor(int headerRowBackgroundColor) {
mHeaderRowBackgroundColor = headerRowBackgroundColor;
invalidate();
}
public int getDayBackgroundColor() {
return mDayBackgroundColor;
}
public void setDayBackgroundColor(int dayBackgroundColor) {
mDayBackgroundColor = dayBackgroundColor;
invalidate();
}
public int getHourSeparatorColor() {
return mHourSeparatorColor;
}
public void setHourSeparatorColor(int hourSeparatorColor) {
mHourSeparatorColor = hourSeparatorColor;
invalidate();
}
public int getTodayBackgroundColor() {
return mTodayBackgroundColor;
}
public void setTodayBackgroundColor(int todayBackgroundColor) {
mTodayBackgroundColor = todayBackgroundColor;
invalidate();
}
public int getHourSeparatorHeight() {
return mHourSeparatorHeight;
}
public void setHourSeparatorHeight(int hourSeparatorHeight) {
mHourSeparatorHeight = hourSeparatorHeight;
invalidate();
}
public int getTodayHeaderTextColor() {
return mTodayHeaderTextColor;
}
public void setTodayHeaderTextColor(int todayHeaderTextColor) {
mTodayHeaderTextColor = todayHeaderTextColor;
invalidate();
}
public int getEventTextSize() {
return mEventTextSize;
}
public void setEventTextSize(int eventTextSize) {
mEventTextSize = eventTextSize;
mEventTextPaint.setTextSize(mEventTextSize);
invalidate();
}
public int getEventTextColor() {
return mEventTextColor;
}
public void setEventTextColor(int eventTextColor) {
mEventTextColor = eventTextColor;
invalidate();
}
public int getEventPadding() {
return mEventPadding;
}
public void setEventPadding(int eventPadding) {
mEventPadding = eventPadding;
invalidate();
}
public int getHeaderColumnBackgroundColor() {
return mHeaderColumnBackgroundColor;
}
public void setHeaderColumnBackgroundColor(int headerColumnBackgroundColor) {
mHeaderColumnBackgroundColor = headerColumnBackgroundColor;
invalidate();
}
public int getDefaultEventColor() {
return mDefaultEventColor;
}
public void setDefaultEventColor(int defaultEventColor) {
mDefaultEventColor = defaultEventColor;
invalidate();
}
public int getDayNameLength() {
return mDayNameLength;
}
/**
* Set the length of the day name displayed in the header row. Example of short day names is
* 'M' for 'Monday' and example of long day names is 'Mon' for 'Monday'.
* @param length Supported values are {@link com.alamkanak.weekview.WeekView#LENGTH_SHORT} and
* {@link com.alamkanak.weekview.WeekView#LENGTH_LONG}.
*/
public void setDayNameLength(int length) {
if (length != LENGTH_LONG && length != LENGTH_SHORT) {
throw new IllegalArgumentException("length parameter must be either LENGTH_LONG or LENGTH_SHORT");
}
this.mDayNameLength = length;
}
public int getOverlappingEventGap() {
return mOverlappingEventGap;
}
/**
* Set the gap between overlapping events.
* @param overlappingEventGap The gap between overlapping events.
*/
public void setOverlappingEventGap(int overlappingEventGap) {
this.mOverlappingEventGap = overlappingEventGap;
invalidate();
}
public int getEventMarginVertical() {
return mEventMarginVertical;
}
/**
* Set the top and bottom margin of the event. The event will release this margin from the top
* and bottom edge. This margin is useful for differentiation consecutive events.
* @param eventMarginVertical The top and bottom margin.
*/
public void setEventMarginVertical(int eventMarginVertical) {
this.mEventMarginVertical = eventMarginVertical;
invalidate();
}
/**
* Returns the first visible day in the week view.
* @return The first visible day in the week view.
*/
public Calendar getFirstVisibleDay() {
return mFirstVisibleDay;
}
/**
* Returns the last visible day in the week view.
* @return The last visible day in the week view.
*/
public Calendar getLastVisibleDay() {
return mLastVisibleDay;
}
// Functions related to scrolling.
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mCurrentScrollDirection.isHorizontal()) {
float leftDays = Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap));
int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay+mColumnGap));
mStickyScroller.startScroll((int) mCurrentOrigin.x, 0, - nearestOrigin, 0);
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
}
return mGestureDetector.onTouchEvent(event);
}
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.computeScrollOffset()) {
if (Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) < mWidthPerDay + mColumnGap && Math.abs(mScroller.getFinalX() - mScroller.getStartX()) != 0) {
mScroller.forceFinished(true);
float leftDays = Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap));
if(mCurrentScrollDirection == Direction.LEFT)
leftDays
else
leftDays++;
int nearestOrigin = (int) ((mCurrentOrigin.x - leftDays * (mWidthPerDay+mColumnGap)));
mStickyScroller.startScroll((int) mCurrentOrigin.x, 0, - nearestOrigin, 0);
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
else {
if (mCurrentFlingDirection == Direction.VERTICAL) mCurrentOrigin.y = mScroller.getCurrY();
else mCurrentOrigin.x = mScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
mCurrentScrollDirection = Direction.NONE;
}
if (mStickyScroller.computeScrollOffset()) {
mCurrentOrigin.x = mStickyScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
}
// Public methods.
/**
* Show today on the week view.
*/
public void goToToday() {
Calendar today = Calendar.getInstance();
goToDate(today);
}
/**
* Show a specific day on the week view.
* @param date The date to show.
*/
public void goToDate(Calendar date) {
mScroller.forceFinished(true);
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
mRefreshEvents = true;
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
int dateDifference = (int) (date.getTimeInMillis() - today.getTimeInMillis()) / (1000 * 60 * 60 * 24);
mCurrentOrigin.x = - dateDifference * (mWidthPerDay + mColumnGap);
invalidate();
}
/**
* Refreshes the view and loads the events again.
*/
public void notifyDatasetChanged(){
mRefreshEvents = true;
invalidate();
}
/**
* Vertically scroll to a specific hour in the week view.
* @param hour The hour to scroll to in 24-hour format. Supported values are 0-24.
*/
public void goToHour(double hour){
if (hour < 0)
throw new IllegalArgumentException("Cannot scroll to an hour of negative value.");
else if (hour > 24)
throw new IllegalArgumentException("Cannot scroll to an hour of value greater than 24.");
else if (hour * mHourHeight > mHourHeight * 24 - getHeight() + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)
throw new IllegalArgumentException("Cannot scroll to an hour which will result the calendar to go off the screen.");
int verticalOffset = (int) (mHourHeight * hour);
mCurrentOrigin.y = -verticalOffset;
invalidate();
}
// Interfaces.
public interface EventClickListener {
public void onEventClick(WeekViewEvent event, RectF eventRect);
}
public interface MonthChangeListener {
public List<WeekViewEvent> onMonthChange(int newYear, int newMonth);
}
public interface EventLongPressListener {
public void onEventLongPress(WeekViewEvent event, RectF eventRect);
}
// Helper methods.
/**
* Checks if an integer array contains a particular value.
* @param list The haystack.
* @param value The needle.
* @return True if the array contains the value. Otherwise returns false.
*/
private boolean containsValue(int[] list, int value) {
for (int i = 0; i < list.length; i++){
if (list[i] == value)
return true;
}
return false;
}
/**
* Converts an int (0-23) to time string (e.g. 12 PM).
* @param hour The time. Limit: 0-23.
* @return The string representation of the time.
*/
private String getTimeString(int hour) {
String amPm;
if (hour >= 0 && hour < 12) amPm = "AM";
else amPm = "PM";
if (hour == 0) hour = 12;
if (hour > 12) hour -= 12;
return String.format("%02d %s", hour, amPm);
}
/**
* Checks if two times are on the same day.
* @param dayOne The first day.
* @param dayTwo The second day.
* @return Whether the times are on the same day.
*/
private boolean isSameDay(Calendar dayOne, Calendar dayTwo) {
return dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR) && dayOne.get(Calendar.DAY_OF_YEAR) == dayTwo.get(Calendar.DAY_OF_YEAR);
}
/**
* Get the day name of a given date.
* @param date The date.
* @return The first the characters of the day name.
*/
private String getDayName(Calendar date) {
int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);
if (Calendar.MONDAY == dayOfWeek) return (mDayNameLength == LENGTH_SHORT ? "M" : "MON");
else if (Calendar.TUESDAY == dayOfWeek) return (mDayNameLength == LENGTH_SHORT ? "T" : "TUE");
else if (Calendar.WEDNESDAY == dayOfWeek) return (mDayNameLength == LENGTH_SHORT ? "W" : "WED");
else if (Calendar.THURSDAY == dayOfWeek) return (mDayNameLength == LENGTH_SHORT ? "T" : "THU");
else if (Calendar.FRIDAY == dayOfWeek) return (mDayNameLength == LENGTH_SHORT ? "F" : "FRI");
else if (Calendar.SATURDAY == dayOfWeek) return (mDayNameLength == LENGTH_SHORT ? "S" : "SAT");
else if (Calendar.SUNDAY == dayOfWeek) return (mDayNameLength == LENGTH_SHORT ? "S" : "SUN");
return "";
}
}
|
package com.infinityraider.boatifull.boatlinking;
import com.google.common.collect.ImmutableList;
import com.infinityraider.boatifull.entity.EntityBoatLink;
import com.infinityraider.boatifull.handler.ConfigurationHandler;
import com.infinityraider.infinitylib.utility.LogHelper;
import net.minecraft.entity.item.EntityBoat;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
import net.minecraftforge.oredict.OreDictionary;
import java.util.*;
public class BoatLinker implements IBoatLinker {
private static final BoatLinker INSTANCE = new BoatLinker();
public static BoatLinker getInstance() {
return INSTANCE;
}
public static int LINK_RANGE = 3;
private List<ItemStack> linkKeyItems;
private final Map<EntityPlayer, EntityBoat> linkingPlayerToBoat;
private final Map<EntityBoat, EntityPlayer> linkingBoatToPlayer;
private final Map<EntityBoat, EntityBoatLink> boatLinks;
private BoatLinker() {
this.linkingPlayerToBoat = new IdentityHashMap<>();
this.linkingBoatToPlayer = new IdentityHashMap<>();
this.boatLinks = new IdentityHashMap<>();
}
@Override
public ItemStack getDefaultKeyStack() {
return getLinkKeyStacks().get(0);
}
@Override
public List<ItemStack> getLinkKeyStacks() {
if(this.linkKeyItems == null) {
this.linkKeyItems = ImmutableList.copyOf(ConfigurationHandler.getInstance().getLinkKeyItems());
StringBuilder buffer = new StringBuilder();
buffer.append("Found boat linking items:");
for(ItemStack stack : this.linkKeyItems) {
buffer.append("\n").append(stack.getItem().getRegistryName().toString()).append(":").append(stack.getItemDamage());
}
LogHelper.debug(buffer.toString());
}
return this.linkKeyItems;
}
@Override
public boolean isValidLinkKey(ItemStack stack) {
if(stack == null) {
return false;
}
for(ItemStack linkStack : this.getLinkKeyStacks()) {
if(linkStack.getItem() == stack.getItem()) {
if(linkStack.getItemDamage() == OreDictionary.WILDCARD_VALUE || linkStack.getItemDamage() == stack.getItemDamage()) {
return true;
}
}
}
return false;
}
@Override
public EnumBoatLinkResult canStartBoatLink(EntityPlayer player, EntityBoat boat) {
if(linkingPlayerToBoat.containsKey(player)) {
return EnumBoatLinkResult.FAIL_PLAYER_ALREADY_LINKING;
}
if(linkingBoatToPlayer.containsKey(boat)) {
return EnumBoatLinkResult.FAIL_BOAT_ALREADY_LINKING;
}
return EnumBoatLinkResult.SUCCESS_START;
}
@Override
public boolean cancelBoatLink(EntityPlayer player) {
if(linkingPlayerToBoat.containsKey(player)) {
removeLinkingProgress(player);
return true;
}
return false;
}
@Override
public EnumBoatLinkResult startBoatLink(EntityPlayer player, EntityBoat boat) {
EnumBoatLinkResult result = canStartBoatLink(player, boat);
if(result.isOk()) {
linkingPlayerToBoat.put(player, boat);
linkingBoatToPlayer.put(boat, player);
}
return result;
}
@Override
public EnumBoatLinkResult canFinishBoatLink(EntityPlayer player, EntityBoat boat) {
if(linkingBoatToPlayer.containsKey(boat)) {
return EnumBoatLinkResult.FAIL_BOAT_ALREADY_LINKING;
}
if(!linkingPlayerToBoat.containsKey(player)) {
return EnumBoatLinkResult.FAIL_NOT_LINKING;
}
return canLinkBoats(linkingPlayerToBoat.get(player), boat);
}
@Override
public EnumBoatLinkResult finishBoatLink(EntityPlayer player, EntityBoat boat) {
EnumBoatLinkResult result = canFinishBoatLink(player, boat);
if(result.isOk()) {
EntityBoat leader = linkingPlayerToBoat.get(player);
linkingPlayerToBoat.remove(player);
linkingBoatToPlayer.remove(leader);
result = linkBoats(leader, boat, player.inventory.getCurrentItem());
}
return result;
}
@Override
public EnumBoatLinkResult canLinkBoats(EntityBoat leader, EntityBoat follower) {
IBoatLink followerLink = getBoatLink(follower);
if(!areBoatsCloseEnough(leader, follower)) {
return EnumBoatLinkResult.FAIL_TOO_FAR;
}
if(followerLink != null) {
return EnumBoatLinkResult.FAIL_ALREADY_HAS_LEADER;
}
if(checkForLinkLoopRecursive(leader, follower)) {
return EnumBoatLinkResult.FAIL_LINK_LOOP;
}
return EnumBoatLinkResult.SUCCESS_FINISH;
}
@Override
public boolean areBoatsCloseEnough(EntityBoat a, EntityBoat b) {
return a != b && a.getEntityWorld() == b.getEntityWorld() && a.getDistanceSqToEntity(b) <= LINK_RANGE * LINK_RANGE;
}
private boolean checkForLinkLoopRecursive(EntityBoat leader, EntityBoat follower) {
IBoatLink leaderLink = this.getBoatLink(leader);
if(leaderLink != null) {
EntityBoat leadingBoat = leaderLink.getLeader();
if(leadingBoat == null) {
return true;
} else if(leadingBoat == follower) {
return true;
}
return checkForLinkLoopRecursive(leadingBoat, follower);
}
return false;
}
@Override
public EnumBoatLinkResult linkBoats(EntityBoat leader, EntityBoat follower, ItemStack linkItem) {
EnumBoatLinkResult result = canLinkBoats(leader, follower);
if(result.isOk()) {
removeLinkingProgress(leader);
removeLinkingProgress(follower);
EntityBoatLink boatLink = new EntityBoatLink(leader, follower, linkItem);
this.boatLinks.put(follower, boatLink);
leader.getEntityWorld().spawnEntityInWorld(boatLink);
boatLink.mountFollower();
}
return result;
}
@Override
public void unlinkBoat(EntityBoat follower) {
if(boatLinks.containsKey(follower)) {
IBoatLink link = getBoatLink(follower);
boatLinks.remove(follower);
link.breakLink();
EntityItem item = new EntityItem(follower.getEntityWorld(), follower.posX, follower.posY, follower.posZ, link.getLinkItem());
follower.getEntityWorld().spawnEntityInWorld(item);
} else {
boatLinks.remove(follower);
}
}
@Override
public EntityBoatLink getBoatLink(EntityBoat boat) {
return this.boatLinks.get(boat);
}
@Override
public List<EntityBoat> getBoatsLinkedToBoat(EntityBoat boat) {
Iterator<Map.Entry<EntityBoat, EntityBoatLink>> iterator = this.boatLinks.entrySet().iterator();
List<EntityBoat> linkedBoats = new ArrayList<>();
while(iterator.hasNext()) {
Map.Entry<EntityBoat, EntityBoatLink> entry = iterator.next();
if(entry.getValue() == null || entry.getKey() == null) {
iterator.remove();
} else if(entry.getValue().getLeader() == boat) {
linkedBoats.add(entry.getKey());
}
}
return linkedBoats;
}
public boolean validateBoatLink(EntityBoatLink link) {
EntityBoat follower = link.getFollower();
if (follower == null) {
return false;
} else {
this.boatLinks.put(follower, link);
return true;
}
}
public void onBoatDeath(EntityBoat boat) {
if(linkingBoatToPlayer.containsKey(boat)) {
removeLinkingProgress(boat);
}
if(this.boatLinks.containsKey(boat)) {
this.unlinkBoat(boat);
}
getBoatsLinkedToBoat(boat).forEach(this::unlinkBoat);
}
private void removeLinkingProgress(EntityBoat boat) {
if(linkingBoatToPlayer.containsKey(boat)) {
linkingPlayerToBoat.remove(linkingBoatToPlayer.get(boat));
linkingBoatToPlayer.remove(boat);
}
}
private void removeLinkingProgress(EntityPlayer player) {
if(linkingPlayerToBoat.containsKey(player)) {
linkingBoatToPlayer.remove(linkingPlayerToBoat.get(player));
linkingPlayerToBoat.remove(player);
}
}
@SubscribeEvent
@SuppressWarnings("unused")
public void onPlayerDeath(LivingDeathEvent event) {
if(!event.getEntity().getEntityWorld().isRemote && event.getEntity() instanceof EntityPlayer) {
removeLinkingProgress((EntityPlayer) event.getEntity());
}
}
@SubscribeEvent
@SuppressWarnings("unused")
public void onPlayerDisconnect(PlayerEvent.PlayerLoggedOutEvent event) {
if(!event.player.getEntityWorld().isRemote) {
removeLinkingProgress(event.player);
}
}
}
|
package com.alamkanak.weekview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewCompat;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.widget.OverScroller;
import android.widget.Scroller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class WeekView extends View {
@Deprecated
public static final int LENGTH_SHORT = 1;
@Deprecated
public static final int LENGTH_LONG = 2;
private final Context mContext;
private Calendar mToday;
private Calendar mStartDate;
private Paint mTimeTextPaint;
private float mTimeTextWidth;
private float mTimeTextHeight;
private Paint mHeaderTextPaint;
private float mHeaderTextHeight;
private GestureDetectorCompat mGestureDetector;
private OverScroller mScroller;
private PointF mCurrentOrigin = new PointF(0f, 0f);
private Direction mCurrentScrollDirection = Direction.NONE;
private Paint mHeaderBackgroundPaint;
private float mWidthPerDay;
private Paint mDayBackgroundPaint;
private Paint mHourSeparatorPaint;
private float mHeaderMarginBottom;
private Paint mTodayBackgroundPaint;
private Paint mTodayHeaderTextPaint;
private Paint mEventBackgroundPaint;
private float mHeaderColumnWidth;
private List<EventRect> mEventRects;
private TextPaint mEventTextPaint;
private Paint mHeaderColumnBackgroundPaint;
private Scroller mStickyScroller;
private int mFetchedMonths[] = new int[3];
private boolean mRefreshEvents = false;
private float mDistanceY = 0;
private float mDistanceX = 0;
private Direction mCurrentFlingDirection = Direction.NONE;
// Attributes and their default values.
private int mHourHeight = 50;
private int mColumnGap = 10;
private int mFirstDayOfWeek = Calendar.MONDAY;
private int mTextSize = 12;
private int mHeaderColumnPadding = 10;
private int mHeaderColumnTextColor = Color.BLACK;
private int mNumberOfVisibleDays = 3;
private int mHeaderRowPadding = 10;
private int mHeaderRowBackgroundColor = Color.WHITE;
private int mDayBackgroundColor = Color.rgb(245, 245, 245);
private int mHourSeparatorColor = Color.rgb(230, 230, 230);
private int mTodayBackgroundColor = Color.rgb(239, 247, 254);
private int mHourSeparatorHeight = 2;
private int mTodayHeaderTextColor = Color.rgb(39, 137, 228);
private int mEventTextSize = 12;
private int mEventTextColor = Color.BLACK;
private int mEventPadding = 8;
private int mHeaderColumnBackgroundColor = Color.WHITE;
private int mDefaultEventColor;
private boolean mIsFirstDraw = true;
@Deprecated private int mDayNameLength = LENGTH_LONG;
private int mOverlappingEventGap = 0;
private int mEventMarginVertical = 0;
private float mXScrollingSpeed = 1f;
private Calendar mFirstVisibleDay;
private Calendar mLastVisibleDay;
// Listeners.
private EventClickListener mEventClickListener;
private EventLongPressListener mEventLongPressListener;
private MonthChangeListener mMonthChangeListener;
private EmptyViewClickListener mEmptyViewClickListener;
private EmptyViewLongPressListener mEmptyViewLongPressListener;
private DateTimeInterpreter mDateTimeInterpreter;
private final GestureDetector.SimpleOnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
mScroller.forceFinished(true);
mStickyScroller.forceFinished(true);
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (mCurrentScrollDirection == Direction.NONE) {
if (Math.abs(distanceX) > Math.abs(distanceY)){
mCurrentScrollDirection = Direction.HORIZONTAL;
mCurrentFlingDirection = Direction.HORIZONTAL;
}
else {
mCurrentFlingDirection = Direction.VERTICAL;
mCurrentScrollDirection = Direction.VERTICAL;
}
}
mDistanceX = distanceX;
mDistanceY = distanceY;
invalidate();
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
mScroller.forceFinished(true);
mStickyScroller.forceFinished(true);
if (mCurrentFlingDirection == Direction.HORIZONTAL){
mScroller.fling((int) mCurrentOrigin.x, 0, (int) (velocityX * mXScrollingSpeed), 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
}
else if (mCurrentFlingDirection == Direction.VERTICAL){
mScroller.fling(0, (int) mCurrentOrigin.y, 0, (int) velocityY, 0, 0, (int) -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 - getHeight()), 0);
}
ViewCompat.postInvalidateOnAnimation(WeekView.this);
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// If the tap was on an event then trigger the callback.
if (mEventRects != null && mEventClickListener != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventClickListener.onEventClick(event.originalEvent, event.rectF);
playSoundEffect(SoundEffectConstants.CLICK);
return super.onSingleTapConfirmed(e);
}
}
}
// If the tap was on in an empty space, then trigger the callback.
if (mEmptyViewClickListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
playSoundEffect(SoundEffectConstants.CLICK);
mEmptyViewClickListener.onEmptyViewClicked(selectedTime);
}
}
return super.onSingleTapConfirmed(e);
}
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
if (mEventLongPressListener != null && mEventRects != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventLongPressListener.onEventLongPress(event.originalEvent, event.rectF);
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return;
}
}
}
// If the tap was on in an empty space, then trigger the callback.
if (mEmptyViewLongPressListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
mEmptyViewLongPressListener.onEmptyViewLongPress(selectedTime);
}
}
}
};
private enum Direction {
NONE, HORIZONTAL, VERTICAL
}
public WeekView(Context context) {
this(context, null);
}
public WeekView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WeekView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// Hold references.
mContext = context;
// Get the attribute values (if any).
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.WeekView, 0, 0);
try {
mFirstDayOfWeek = a.getInteger(R.styleable.WeekView_firstDayOfWeek, mFirstDayOfWeek);
mHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourHeight, mHourHeight);
mTextSize = a.getDimensionPixelSize(R.styleable.WeekView_textSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, context.getResources().getDisplayMetrics()));
mHeaderColumnPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerColumnPadding, mHeaderColumnPadding);
mColumnGap = a.getDimensionPixelSize(R.styleable.WeekView_columnGap, mColumnGap);
mHeaderColumnTextColor = a.getColor(R.styleable.WeekView_headerColumnTextColor, mHeaderColumnTextColor);
mNumberOfVisibleDays = a.getInteger(R.styleable.WeekView_noOfVisibleDays, mNumberOfVisibleDays);
mHeaderRowPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerRowPadding, mHeaderRowPadding);
mHeaderRowBackgroundColor = a.getColor(R.styleable.WeekView_headerRowBackgroundColor, mHeaderRowBackgroundColor);
mDayBackgroundColor = a.getColor(R.styleable.WeekView_dayBackgroundColor, mDayBackgroundColor);
mHourSeparatorColor = a.getColor(R.styleable.WeekView_hourSeparatorColor, mHourSeparatorColor);
mTodayBackgroundColor = a.getColor(R.styleable.WeekView_todayBackgroundColor, mTodayBackgroundColor);
mHourSeparatorHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mHourSeparatorHeight);
mTodayHeaderTextColor = a.getColor(R.styleable.WeekView_todayHeaderTextColor, mTodayHeaderTextColor);
mEventTextSize = a.getDimensionPixelSize(R.styleable.WeekView_eventTextSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mEventTextSize, context.getResources().getDisplayMetrics()));
mEventTextColor = a.getColor(R.styleable.WeekView_eventTextColor, mEventTextColor);
mEventPadding = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mEventPadding);
mHeaderColumnBackgroundColor = a.getColor(R.styleable.WeekView_headerColumnBackground, mHeaderColumnBackgroundColor);
mDayNameLength = a.getInteger(R.styleable.WeekView_dayNameLength, mDayNameLength);
mOverlappingEventGap = a.getDimensionPixelSize(R.styleable.WeekView_overlappingEventGap, mOverlappingEventGap);
mEventMarginVertical = a.getDimensionPixelSize(R.styleable.WeekView_eventMarginVertical, mEventMarginVertical);
mXScrollingSpeed = a.getFloat(R.styleable.WeekView_xScrollingSpeed, mXScrollingSpeed);
} finally {
a.recycle();
}
init();
}
private void init() {
// Get the date today.
mToday = Calendar.getInstance();
mToday.set(Calendar.HOUR_OF_DAY, 0);
mToday.set(Calendar.MINUTE, 0);
mToday.set(Calendar.SECOND, 0);
// Scrolling initialization.
mGestureDetector = new GestureDetectorCompat(mContext, mGestureListener);
mScroller = new OverScroller(mContext);
mStickyScroller = new Scroller(mContext);
// Measure settings for time column.
mTimeTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTimeTextPaint.setTextAlign(Paint.Align.RIGHT);
mTimeTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setColor(mHeaderColumnTextColor);
Rect rect = new Rect();
mTimeTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mTimeTextWidth = mTimeTextPaint.measureText("00 PM");
mTimeTextHeight = rect.height();
mHeaderMarginBottom = mTimeTextHeight / 2;
// Measure settings for header row.
mHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mHeaderTextPaint.setColor(mHeaderColumnTextColor);
mHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mHeaderTextHeight = rect.height();
mHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
// Prepare header background paint.
mHeaderBackgroundPaint = new Paint();
mHeaderBackgroundPaint.setColor(mHeaderRowBackgroundColor);
// Prepare day background color paint.
mDayBackgroundPaint = new Paint();
mDayBackgroundPaint.setColor(mDayBackgroundColor);
// Prepare hour separator color paint.
mHourSeparatorPaint = new Paint();
mHourSeparatorPaint.setStyle(Paint.Style.STROKE);
mHourSeparatorPaint.setStrokeWidth(mHourSeparatorHeight);
mHourSeparatorPaint.setColor(mHourSeparatorColor);
// Prepare today background color paint.
mTodayBackgroundPaint = new Paint();
mTodayBackgroundPaint.setColor(mTodayBackgroundColor);
// Prepare today header text color paint.
mTodayHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTodayHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mTodayHeaderTextPaint.setTextSize(mTextSize);
mTodayHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
mTodayHeaderTextPaint.setColor(mTodayHeaderTextColor);
// Prepare event background color.
mEventBackgroundPaint = new Paint();
mEventBackgroundPaint.setColor(Color.rgb(174, 208, 238));
// Prepare header column background color.
mHeaderColumnBackgroundPaint = new Paint();
mHeaderColumnBackgroundPaint.setColor(mHeaderColumnBackgroundColor);
// Prepare event text size and color.
mEventTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
mEventTextPaint.setStyle(Paint.Style.FILL);
mEventTextPaint.setColor(mEventTextColor);
mEventTextPaint.setTextSize(mEventTextSize);
mStartDate = (Calendar) mToday.clone();
// Set default event color.
mDefaultEventColor = Color.parseColor("#9fc6e7");
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the header row.
drawHeaderRowAndEvents(canvas);
// Draw the time column and all the axes/separators.
drawTimeColumnAndAxes(canvas);
// Hide everything in the first cell (top left corner).
canvas.drawRect(0, 0, mTimeTextWidth + mHeaderColumnPadding * 2, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Hide anything that is in the bottom margin of the header row.
canvas.drawRect(mHeaderColumnWidth, mHeaderTextHeight + mHeaderRowPadding * 2, getWidth(), mHeaderRowPadding * 2 + mHeaderTextHeight + mHeaderMarginBottom + mTimeTextHeight/2 - mHourSeparatorHeight / 2, mHeaderColumnBackgroundPaint);
}
private void drawTimeColumnAndAxes(Canvas canvas) {
// Do not let the view go above/below the limit due to scrolling. Set the max and min limit of the scroll.
if (mCurrentScrollDirection == Direction.VERTICAL) {
if (mCurrentOrigin.y - mDistanceY > 0) mCurrentOrigin.y = 0;
else if (mCurrentOrigin.y - mDistanceY < -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 - getHeight())) mCurrentOrigin.y = -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 - getHeight());
else mCurrentOrigin.y -= mDistanceY;
}
// Draw the background color for the header column.
canvas.drawRect(0, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderColumnWidth, getHeight(), mHeaderColumnBackgroundPaint);
for (int i = 0; i < 24; i++) {
float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * i + mHeaderMarginBottom;
// Draw the text if its y position is not outside of the visible area. The pivot point of the text is the point at the bottom-right corner.
String time = getDateTimeInterpreter().interpretTime(i);
if (time == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null time");
if (top < getHeight()) canvas.drawText(time, mTimeTextWidth + mHeaderColumnPadding, top + mTimeTextHeight, mTimeTextPaint);
}
}
private void drawHeaderRowAndEvents(Canvas canvas) {
// Calculate the available width for each day.
mHeaderColumnWidth = mTimeTextWidth + mHeaderColumnPadding *2;
mWidthPerDay = getWidth() - mHeaderColumnWidth - mColumnGap * (mNumberOfVisibleDays - 1);
mWidthPerDay = mWidthPerDay/mNumberOfVisibleDays;
// If the week view is being drawn for the first time, then consider the first day of week.
if (mIsFirstDraw && mNumberOfVisibleDays >= 7) {
if (mToday.get(Calendar.DAY_OF_WEEK) != mFirstDayOfWeek) {
int difference = 7 + (mToday.get(Calendar.DAY_OF_WEEK) - mFirstDayOfWeek);
mCurrentOrigin.x += (mWidthPerDay + mColumnGap) * difference;
}
mIsFirstDraw = false;
}
// Consider scroll offset.
if (mCurrentScrollDirection == Direction.HORIZONTAL) mCurrentOrigin.x -= mDistanceX;
int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
float startFromPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps +
mHeaderColumnWidth;
float startPixel = startFromPixel;
// Prepare to iterate for each day.
Calendar day = (Calendar) mToday.clone();
day.add(Calendar.HOUR, 6);
// Prepare to iterate for each hour to draw the hour lines.
int lineCount = (int) ((getHeight() - mHeaderTextHeight - mHeaderRowPadding * 2 -
mHeaderMarginBottom) / mHourHeight) + 1;
lineCount = (lineCount) * (mNumberOfVisibleDays+1);
float[] hourLines = new float[lineCount * 4];
// Clear the cache for event rectangles.
if (mEventRects != null) {
for (EventRect eventRect: mEventRects) {
eventRect.rectF = null;
}
}
// Iterate through each day.
mFirstVisibleDay = (Calendar) mToday.clone();
mFirstVisibleDay.add(Calendar.DATE, leftDaysWithGaps);
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1;
dayNumber++) {
// Check if the day is today.
day = (Calendar) mToday.clone();
mLastVisibleDay = (Calendar) day.clone();
day.add(Calendar.DATE, dayNumber - 1);
mLastVisibleDay.add(Calendar.DATE, dayNumber - 2);
boolean sameDay = isSameDay(day, mToday);
// Get more events if necessary. We want to store the events 3 months beforehand. Get
// events only when it is the first iteration of the loop.
if (mEventRects == null || mRefreshEvents || (dayNumber == leftDaysWithGaps + 1 && mFetchedMonths[1] != day.get(Calendar.MONTH)+1 && day.get(Calendar.DAY_OF_MONTH) == 15)) {
getMoreEvents(day);
mRefreshEvents = false;
}
// Draw background color for each day.
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start> 0)
canvas.drawRect(start, mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom, startPixel + mWidthPerDay, getHeight(), sameDay ? mTodayBackgroundPaint : mDayBackgroundPaint);
// Prepare the separator lines for hours.
int i = 0;
for (int hourNumber = 0; hourNumber < 24; hourNumber++) {
float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * hourNumber + mTimeTextHeight/2 + mHeaderMarginBottom;
if (top > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom - mHourSeparatorHeight && top < getHeight() && startPixel + mWidthPerDay - start > 0){
hourLines[i * 4] = start;
hourLines[i * 4 + 1] = top;
hourLines[i * 4 + 2] = startPixel + mWidthPerDay;
hourLines[i * 4 + 3] = top;
i++;
}
}
// Draw the lines for hours.
canvas.drawLines(hourLines, mHourSeparatorPaint);
// Draw the events.
drawEvents(day, startPixel, canvas);
// In the next iteration, start from the next day.
startPixel += mWidthPerDay + mColumnGap;
}
// Draw the header background.
canvas.drawRect(0, 0, getWidth(), mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Draw the header row texts.
startPixel = startFromPixel;
for (int dayNumber=leftDaysWithGaps+1; dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1; dayNumber++) {
// Check if the day is today.
day = (Calendar) mToday.clone();
day.add(Calendar.DATE, dayNumber - 1);
boolean sameDay = isSameDay(day, mToday);
// Draw the day labels.
String dayLabel = getDateTimeInterpreter().interpretDate(day);
if (dayLabel == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null date");
canvas.drawText(dayLabel, startPixel + mWidthPerDay / 2, mHeaderTextHeight + mHeaderRowPadding, sameDay ? mTodayHeaderTextPaint : mHeaderTextPaint);
startPixel += mWidthPerDay + mColumnGap;
}
}
/**
* Get the time and date where the user clicked on.
* @param x The x position of the touch event.
* @param y The y position of the touch event.
* @return The time and date at the clicked position.
*/
private Calendar getTimeFromPoint(float x, float y){
int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
float startPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps +
mHeaderColumnWidth;
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1;
dayNumber++) {
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start> 0
&& x>start && x<startPixel + mWidthPerDay){
Calendar day = (Calendar) mToday.clone();
day.add(Calendar.DATE, dayNumber - 1);
float pixelsFromZero = y - mCurrentOrigin.y - mHeaderTextHeight
- mHeaderRowPadding * 2 - mTimeTextHeight/2 - mHeaderMarginBottom;
int hour = (int)(pixelsFromZero / mHourHeight);
int minute = (int) (60 * (pixelsFromZero - hour * mHourHeight) / mHourHeight);
day.add(Calendar.HOUR, hour);
day.set(Calendar.MINUTE, minute);
return day;
}
startPixel += mWidthPerDay + mColumnGap;
}
return null;
}
/**
* Draw all the events of a particular day.
* @param date The day.
* @param startFromPixel The left position of the day area. The events will never go any left from this value.
* @param canvas The canvas to draw upon.
*/
private void drawEvents(Calendar date, float startFromPixel, Canvas canvas) {
if (mEventRects != null && mEventRects.size() > 0) {
for (int i = 0; i < mEventRects.size(); i++) {
if (isSameDay(mEventRects.get(i).event.getStartTime(), date)) {
// Calculate top.
float top = mHourHeight * 24 * mEventRects.get(i).top / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 + mEventMarginVertical;
float originalTop = top;
if (top < mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2)
top = mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2;
// Calculate bottom.
float bottom = mEventRects.get(i).bottom;
bottom = mHourHeight * 24 * bottom / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 - mEventMarginVertical;
// Calculate left and right.
float left = startFromPixel + mEventRects.get(i).left * mWidthPerDay;
if (left < startFromPixel)
left += mOverlappingEventGap;
float originalLeft = left;
float right = left + mEventRects.get(i).width * mWidthPerDay;
if (right < startFromPixel + mWidthPerDay)
right -= mOverlappingEventGap;
if (left < mHeaderColumnWidth) left = mHeaderColumnWidth;
// Draw the event and the event name on top of it.
RectF eventRectF = new RectF(left, top, right, bottom);
if (bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 && left < right &&
eventRectF.right > mHeaderColumnWidth &&
eventRectF.left < getWidth() &&
eventRectF.bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom &&
eventRectF.top < getHeight() &&
left < right
) {
mEventRects.get(i).rectF = eventRectF;
mEventBackgroundPaint.setColor(mEventRects.get(i).event.getColor() == 0 ? mDefaultEventColor : mEventRects.get(i).event.getColor());
canvas.drawRect(mEventRects.get(i).rectF, mEventBackgroundPaint);
drawText(mEventRects.get(i).event.getName(), mEventRects.get(i).rectF, canvas, originalTop, originalLeft);
}
else
mEventRects.get(i).rectF = null;
}
}
}
}
/**
* Draw the name of the event on top of the event rectangle.
* @param text The text to draw.
* @param rect The rectangle on which the text is to be drawn.
* @param canvas The canvas to draw upon.
* @param originalTop The original top position of the rectangle. The rectangle may have some of its portion outside of the visible area.
* @param originalLeft The original left position of the rectangle. The rectangle may have some of its portion outside of the visible area.
*/
private void drawText(String text, RectF rect, Canvas canvas, float originalTop, float originalLeft) {
if (rect.right - rect.left - mEventPadding * 2 < 0) return;
// Get text dimensions
StaticLayout textLayout = new StaticLayout(text, mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
// Crop height
int availableHeight = (int) (rect.bottom - originalTop - mEventPadding * 2);
int lineHeight = textLayout.getHeight() / textLayout.getLineCount();
if (lineHeight < availableHeight && textLayout.getHeight() > rect.height() - mEventPadding * 2) {
int lineCount = textLayout.getLineCount();
int availableLineCount = (int) Math.floor(lineCount * availableHeight / textLayout.getHeight());
float widthAvailable = (rect.right - originalLeft - mEventPadding * 2) * availableLineCount;
textLayout = new StaticLayout(TextUtils.ellipsize(text, mEventTextPaint, widthAvailable, TextUtils.TruncateAt.END), mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
else if (lineHeight >= availableHeight) {
int width = (int) (rect.right - originalLeft - mEventPadding * 2);
textLayout = new StaticLayout(TextUtils.ellipsize(text, mEventTextPaint, width, TextUtils.TruncateAt.END), mEventTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, false);
}
// Draw text
canvas.save();
canvas.translate(originalLeft + mEventPadding, originalTop + mEventPadding);
textLayout.draw(canvas);
canvas.restore();
}
/**
* A class to hold reference to the events and their visual representation. An EventRect is
* actually the rectangle that is drawn on the calendar for a given event. There may be more
* than one rectangle for a single event (an event that expands more than one day). In that
* case two instances of the EventRect will be used for a single event. The given event will be
* stored in "originalEvent". But the event that corresponds to rectangle the rectangle
* instance will be stored in "event".
*/
private class EventRect {
public WeekViewEvent event;
public WeekViewEvent originalEvent;
public RectF rectF;
public float left;
public float width;
public float top;
public float bottom;
/**
* Create a new instance of event rect. An EventRect is actually the rectangle that is drawn
* on the calendar for a given event. There may be more than one rectangle for a single
* event (an event that expands more than one day). In that case two instances of the
* EventRect will be used for a single event. The given event will be stored in
* "originalEvent". But the event that corresponds to rectangle the rectangle instance will
* be stored in "event".
* @param event Represents the event which this instance of rectangle represents.
* @param originalEvent The original event that was passed by the user.
* @param rectF The rectangle.
*/
public EventRect(WeekViewEvent event, WeekViewEvent originalEvent, RectF rectF) {
this.event = event;
this.rectF = rectF;
this.originalEvent = originalEvent;
}
}
/**
* Gets more events of one/more month(s) if necessary. This method is called when the user is
* scrolling the week view. The week view stores the events of three months: the visible month,
* the previous month, the next month.
* @param day The day where the user is currently is.
*/
private void getMoreEvents(Calendar day) {
// Delete all events if its not current month +- 1.
deleteFarMonths(day);
// Get more events if the month is changed.
if (mEventRects == null)
mEventRects = new ArrayList<EventRect>();
if (mMonthChangeListener == null && !isInEditMode())
throw new IllegalStateException("You must provide a MonthChangeListener");
// If a refresh was requested then reset some variables.
if (mRefreshEvents) {
mEventRects.clear();
mFetchedMonths = new int[3];
}
// Get events of previous month.
int previousMonth = (day.get(Calendar.MONTH) == 0?12:day.get(Calendar.MONTH));
int nextMonth = (day.get(Calendar.MONTH)+2 == 13 ?1:day.get(Calendar.MONTH)+2);
int[] lastFetchedMonth = mFetchedMonths.clone();
if (mFetchedMonths[0] < 1 || mFetchedMonths[0] != previousMonth || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, previousMonth) && !isInEditMode()){
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange((previousMonth==12)?day.get(Calendar.YEAR)-1:day.get(Calendar.YEAR), previousMonth);
sortEvents(events);
for (WeekViewEvent event: events) {
cacheEvent(event);
}
}
mFetchedMonths[0] = previousMonth;
}
// Get events of this month.
if (mFetchedMonths[1] < 1 || mFetchedMonths[1] != day.get(Calendar.MONTH)+1 || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, day.get(Calendar.MONTH)+1) && !isInEditMode()) {
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange(day.get(Calendar.YEAR), day.get(Calendar.MONTH) + 1);
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
}
mFetchedMonths[1] = day.get(Calendar.MONTH)+1;
}
// Get events of next month.
if (mFetchedMonths[2] < 1 || mFetchedMonths[2] != nextMonth || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, nextMonth) && !isInEditMode()) {
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange(nextMonth == 1 ? day.get(Calendar.YEAR) + 1 : day.get(Calendar.YEAR), nextMonth);
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
}
mFetchedMonths[2] = nextMonth;
}
// Prepare to calculate positions of each events.
ArrayList<EventRect> tempEvents = new ArrayList<EventRect>(mEventRects);
mEventRects = new ArrayList<EventRect>();
Calendar dayCounter = (Calendar) day.clone();
dayCounter.add(Calendar.MONTH, -1);
dayCounter.set(Calendar.DAY_OF_MONTH, 1);
Calendar maxDay = (Calendar) day.clone();
maxDay.add(Calendar.MONTH, 1);
maxDay.set(Calendar.DAY_OF_MONTH, maxDay.getActualMaximum(Calendar.DAY_OF_MONTH));
// Iterate through each day to calculate the position of the events.
while (dayCounter.getTimeInMillis() <= maxDay.getTimeInMillis()) {
ArrayList<EventRect> eventRects = new ArrayList<EventRect>();
for (EventRect eventRect : tempEvents) {
if (isSameDay(eventRect.event.getStartTime(), dayCounter))
eventRects.add(eventRect);
}
computePositionOfEvents(eventRects);
dayCounter.add(Calendar.DATE, 1);
}
}
/**
* Cache the event for smooth scrolling functionality.
* @param event The event to cache.
*/
private void cacheEvent(WeekViewEvent event) {
if (!isSameDay(event.getStartTime(), event.getEndTime())) {
Calendar endTime = (Calendar) event.getStartTime().clone();
endTime.set(Calendar.HOUR_OF_DAY, 23);
endTime.set(Calendar.MINUTE, 59);
Calendar startTime = (Calendar) event.getEndTime().clone();
startTime.set(Calendar.HOUR_OF_DAY, 0);
startTime.set(Calendar.MINUTE, 0);
WeekViewEvent event1 = new WeekViewEvent(event.getId(), event.getName(), event.getStartTime(), endTime);
event1.setColor(event.getColor());
WeekViewEvent event2 = new WeekViewEvent(event.getId(), event.getName(), startTime, event.getEndTime());
event2.setColor(event.getColor());
mEventRects.add(new EventRect(event1, event, null));
mEventRects.add(new EventRect(event2, event, null));
}
else
mEventRects.add(new EventRect(event, event, null));
}
/**
* Sorts the events in ascending order.
* @param events The events to be sorted.
*/
private void sortEvents(List<WeekViewEvent> events) {
Collections.sort(events, new Comparator<WeekViewEvent>() {
@Override
public int compare(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
int comparator = start1 > start2 ? 1 : (start1 < start2 ? -1 : 0);
if (comparator == 0) {
long end1 = event1.getEndTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
comparator = end1 > end2 ? 1 : (end1 < end2 ? -1 : 0);
}
return comparator;
}
});
}
/**
* Calculates the left and right positions of each events. This comes handy specially if events
* are overlapping.
* @param eventRects The events along with their wrapper class.
*/
private void computePositionOfEvents(List<EventRect> eventRects) {
// Make "collision groups" for all events that collide with others.
List<List<EventRect>> collisionGroups = new ArrayList<List<EventRect>>();
for (EventRect eventRect : eventRects) {
boolean isPlaced = false;
outerLoop:
for (List<EventRect> collisionGroup : collisionGroups) {
for (EventRect groupEvent : collisionGroup) {
if (isEventsCollide(groupEvent.event, eventRect.event)) {
collisionGroup.add(eventRect);
isPlaced = true;
break outerLoop;
}
}
}
if (!isPlaced) {
List<EventRect> newGroup = new ArrayList<EventRect>();
newGroup.add(eventRect);
collisionGroups.add(newGroup);
}
}
for (List<EventRect> collisionGroup : collisionGroups) {
expandEventsToMaxWidth(collisionGroup);
}
}
/**
* Expands all the events to maximum possible width. The events will try to occupy maximum
* space available horizontally.
* @param collisionGroup The group of events which overlap with each other.
*/
private void expandEventsToMaxWidth(List<EventRect> collisionGroup) {
// Expand the events to maximum possible width.
List<List<EventRect>> columns = new ArrayList<List<EventRect>>();
columns.add(new ArrayList<EventRect>());
for (EventRect eventRect : collisionGroup) {
boolean isPlaced = false;
for (List<EventRect> column : columns) {
if (column.size() == 0) {
column.add(eventRect);
isPlaced = true;
}
else if (!isEventsCollide(eventRect.event, column.get(column.size()-1).event)) {
column.add(eventRect);
isPlaced = true;
break;
}
}
if (!isPlaced) {
List<EventRect> newColumn = new ArrayList<EventRect>();
newColumn.add(eventRect);
columns.add(newColumn);
}
}
// Calculate left and right position for all the events.
int maxRowCount = columns.get(0).size();
for (int i = 0; i < maxRowCount; i++) {
// Set the left and right values of the event.
float j = 0;
for (List<EventRect> column : columns) {
if (column.size() >= i+1) {
EventRect eventRect = column.get(i);
eventRect.width = 1f / columns.size();
eventRect.left = j / columns.size();
eventRect.top = eventRect.event.getStartTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getStartTime().get(Calendar.MINUTE);
eventRect.bottom = eventRect.event.getEndTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getEndTime().get(Calendar.MINUTE);
mEventRects.add(eventRect);
}
j++;
}
}
}
/**
* Checks if two events overlap.
* @param event1 The first event.
* @param event2 The second event.
* @return true if the events overlap.
*/
private boolean isEventsCollide(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long end1 = event1.getEndTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
return !((start1 >= end2) || (end1 <= start2));
}
/**
* Checks if time1 occurs after (or at the same time) time2.
* @param time1 The time to check.
* @param time2 The time to check against.
* @return true if time1 and time2 are equal or if time1 is after time2. Otherwise false.
*/
private boolean isTimeAfterOrEquals(Calendar time1, Calendar time2) {
return !(time1 == null || time2 == null) && time1.getTimeInMillis() >= time2.getTimeInMillis();
}
/**
* Deletes the events of the months that are too far away from the current month.
* @param currentDay The current day.
*/
private void deleteFarMonths(Calendar currentDay) {
if (mEventRects == null) return;
Calendar nextMonth = (Calendar) currentDay.clone();
nextMonth.add(Calendar.MONTH, 1);
nextMonth.set(Calendar.DAY_OF_MONTH, nextMonth.getActualMaximum(Calendar.DAY_OF_MONTH));
nextMonth.set(Calendar.HOUR_OF_DAY, 12);
nextMonth.set(Calendar.MINUTE, 59);
nextMonth.set(Calendar.SECOND, 59);
Calendar prevMonth = (Calendar) currentDay.clone();
prevMonth.add(Calendar.MONTH, -1);
prevMonth.set(Calendar.DAY_OF_MONTH, 1);
prevMonth.set(Calendar.HOUR_OF_DAY, 0);
prevMonth.set(Calendar.MINUTE, 0);
prevMonth.set(Calendar.SECOND, 0);
List<EventRect> newEvents = new ArrayList<EventRect>();
for (EventRect eventRect : mEventRects) {
boolean isFarMonth = eventRect.event.getStartTime().getTimeInMillis() > nextMonth.getTimeInMillis() || eventRect.event.getEndTime().getTimeInMillis() < prevMonth.getTimeInMillis();
if (!isFarMonth) newEvents.add(eventRect);
}
mEventRects.clear();
mEventRects.addAll(newEvents);
}
// Functions related to setting and getting the properties.
public void setOnEventClickListener (EventClickListener listener) {
this.mEventClickListener = listener;
}
public EventClickListener getEventClickListener() {
return mEventClickListener;
}
public MonthChangeListener getMonthChangeListener() {
return mMonthChangeListener;
}
public void setMonthChangeListener(MonthChangeListener monthChangeListener) {
this.mMonthChangeListener = monthChangeListener;
}
public EventLongPressListener getEventLongPressListener() {
return mEventLongPressListener;
}
public void setEventLongPressListener(EventLongPressListener eventLongPressListener) {
this.mEventLongPressListener = eventLongPressListener;
}
public void setEmptyViewClickListener(EmptyViewClickListener emptyViewClickListener){
this.mEmptyViewClickListener = emptyViewClickListener;
}
public EmptyViewClickListener getEmptyViewClickListener(){
return mEmptyViewClickListener;
}
public void setEmptyViewLongPressListener(EmptyViewLongPressListener emptyViewLongPressListener){
this.mEmptyViewLongPressListener = emptyViewLongPressListener;
}
public EmptyViewLongPressListener getEmptyViewLongPressListener(){
return mEmptyViewLongPressListener;
}
/**
* Get the interpreter which provides the text to show in the header column and the header row.
* @return The date, time interpreter.
*/
public DateTimeInterpreter getDateTimeInterpreter() {
if (mDateTimeInterpreter == null) {
mDateTimeInterpreter = new DateTimeInterpreter() {
@Override
public String interpretDate(Calendar date) {
SimpleDateFormat sdf;
sdf = mDayNameLength == LENGTH_SHORT ? new SimpleDateFormat("EEEEE") : new SimpleDateFormat("EEE");
try{
String dayName = sdf.format(date.getTime()).toUpperCase();
return String.format("%s %d/%02d", dayName, date.get(Calendar.MONTH) + 1, date.get(Calendar.DAY_OF_MONTH));
}catch (Exception e){
e.printStackTrace();
return "";
}
}
@Override
public String interpretTime(int hour) {
String amPm;
if (hour >= 0 && hour < 12) amPm = "AM";
else amPm = "PM";
if (hour == 0) hour = 12;
if (hour > 12) hour -= 12;
return String.format("%02d %s", hour, amPm);
}
};
}
return mDateTimeInterpreter;
}
/**
* Set the interpreter which provides the text to show in the header column and the header row.
* @param dateTimeInterpreter The date, time interpreter.
*/
public void setDateTimeInterpreter(DateTimeInterpreter dateTimeInterpreter){
this.mDateTimeInterpreter = dateTimeInterpreter;
}
/**
* Get the number of visible days in a week.
* @return The number of visible days in a week.
*/
public int getNumberOfVisibleDays() {
return mNumberOfVisibleDays;
}
/**
* Set the number of visible days in a week.
* @param numberOfVisibleDays The number of visible days in a week.
*/
public void setNumberOfVisibleDays(int numberOfVisibleDays) {
this.mNumberOfVisibleDays = numberOfVisibleDays;
mCurrentOrigin.x = 0;
mCurrentOrigin.y = 0;
invalidate();
}
public int getHourHeight() {
return mHourHeight;
}
public void setHourHeight(int hourHeight) {
mHourHeight = hourHeight;
invalidate();
}
public int getColumnGap() {
return mColumnGap;
}
public void setColumnGap(int columnGap) {
mColumnGap = columnGap;
invalidate();
}
public int getFirstDayOfWeek() {
return mFirstDayOfWeek;
}
/**
* Set the first day of the week. First day of the week is used only when the week view is first
* drawn. It does not of any effect after user starts scrolling horizontally.
* <p>
* <b>Note:</b> This method will only work if the week view is set to display more than 6 days at
* once.
* </p>
* @param firstDayOfWeek The supported values are {@link java.util.Calendar#SUNDAY},
* {@link java.util.Calendar#MONDAY}, {@link java.util.Calendar#TUESDAY},
* {@link java.util.Calendar#WEDNESDAY}, {@link java.util.Calendar#THURSDAY},
* {@link java.util.Calendar#FRIDAY}.
*/
public void setFirstDayOfWeek(int firstDayOfWeek) {
mFirstDayOfWeek = firstDayOfWeek;
invalidate();
}
public int getTextSize() {
return mTextSize;
}
public void setTextSize(int textSize) {
mTextSize = textSize;
mTodayHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setTextSize(mTextSize);
invalidate();
}
public int getHeaderColumnPadding() {
return mHeaderColumnPadding;
}
public void setHeaderColumnPadding(int headerColumnPadding) {
mHeaderColumnPadding = headerColumnPadding;
invalidate();
}
public int getHeaderColumnTextColor() {
return mHeaderColumnTextColor;
}
public void setHeaderColumnTextColor(int headerColumnTextColor) {
mHeaderColumnTextColor = headerColumnTextColor;
invalidate();
}
public int getHeaderRowPadding() {
return mHeaderRowPadding;
}
public void setHeaderRowPadding(int headerRowPadding) {
mHeaderRowPadding = headerRowPadding;
invalidate();
}
public int getHeaderRowBackgroundColor() {
return mHeaderRowBackgroundColor;
}
public void setHeaderRowBackgroundColor(int headerRowBackgroundColor) {
mHeaderRowBackgroundColor = headerRowBackgroundColor;
invalidate();
}
public int getDayBackgroundColor() {
return mDayBackgroundColor;
}
public void setDayBackgroundColor(int dayBackgroundColor) {
mDayBackgroundColor = dayBackgroundColor;
invalidate();
}
public int getHourSeparatorColor() {
return mHourSeparatorColor;
}
public void setHourSeparatorColor(int hourSeparatorColor) {
mHourSeparatorColor = hourSeparatorColor;
invalidate();
}
public int getTodayBackgroundColor() {
return mTodayBackgroundColor;
}
public void setTodayBackgroundColor(int todayBackgroundColor) {
mTodayBackgroundColor = todayBackgroundColor;
invalidate();
}
public int getHourSeparatorHeight() {
return mHourSeparatorHeight;
}
public void setHourSeparatorHeight(int hourSeparatorHeight) {
mHourSeparatorHeight = hourSeparatorHeight;
invalidate();
}
public int getTodayHeaderTextColor() {
return mTodayHeaderTextColor;
}
public void setTodayHeaderTextColor(int todayHeaderTextColor) {
mTodayHeaderTextColor = todayHeaderTextColor;
invalidate();
}
public int getEventTextSize() {
return mEventTextSize;
}
public void setEventTextSize(int eventTextSize) {
mEventTextSize = eventTextSize;
mEventTextPaint.setTextSize(mEventTextSize);
invalidate();
}
public int getEventTextColor() {
return mEventTextColor;
}
public void setEventTextColor(int eventTextColor) {
mEventTextColor = eventTextColor;
invalidate();
}
public int getEventPadding() {
return mEventPadding;
}
public void setEventPadding(int eventPadding) {
mEventPadding = eventPadding;
invalidate();
}
public int getHeaderColumnBackgroundColor() {
return mHeaderColumnBackgroundColor;
}
public void setHeaderColumnBackgroundColor(int headerColumnBackgroundColor) {
mHeaderColumnBackgroundColor = headerColumnBackgroundColor;
invalidate();
}
public int getDefaultEventColor() {
return mDefaultEventColor;
}
public void setDefaultEventColor(int defaultEventColor) {
mDefaultEventColor = defaultEventColor;
invalidate();
}
/**
* <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} and
* {@link #getDateTimeInterpreter()} instead.
* @return Either long or short day name is being used.
*/
@Deprecated
public int getDayNameLength() {
return mDayNameLength;
}
/**
* Set the length of the day name displayed in the header row. Example of short day names is
* 'M' for 'Monday' and example of long day names is 'Mon' for 'Monday'.
* <p>
* <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} instead.
* </p>
* @param length Supported values are {@link com.alamkanak.weekview.WeekView#LENGTH_SHORT} and
* {@link com.alamkanak.weekview.WeekView#LENGTH_LONG}.
*/
@Deprecated
public void setDayNameLength(int length) {
if (length != LENGTH_LONG && length != LENGTH_SHORT) {
throw new IllegalArgumentException("length parameter must be either LENGTH_LONG or LENGTH_SHORT");
}
this.mDayNameLength = length;
}
public int getOverlappingEventGap() {
return mOverlappingEventGap;
}
/**
* Set the gap between overlapping events.
* @param overlappingEventGap The gap between overlapping events.
*/
public void setOverlappingEventGap(int overlappingEventGap) {
this.mOverlappingEventGap = overlappingEventGap;
invalidate();
}
public int getEventMarginVertical() {
return mEventMarginVertical;
}
/**
* Set the top and bottom margin of the event. The event will release this margin from the top
* and bottom edge. This margin is useful for differentiation consecutive events.
* @param eventMarginVertical The top and bottom margin.
*/
public void setEventMarginVertical(int eventMarginVertical) {
this.mEventMarginVertical = eventMarginVertical;
invalidate();
}
/**
* Returns the first visible day in the week view.
* @return The first visible day in the week view.
*/
public Calendar getFirstVisibleDay() {
return mFirstVisibleDay;
}
/**
* Returns the last visible day in the week view.
* @return The last visible day in the week view.
*/
public Calendar getLastVisibleDay() {
return mLastVisibleDay;
}
/**
* Get the scrolling speed factor in horizontal direction.
* @return The speed factor in horizontal direction.
*/
public float getXScrollingSpeed() {
return mXScrollingSpeed;
}
/**
* Sets the speed for horizontal scrolling.
* @param xScrollingSpeed The new horizontal scrolling speed.
*/
public void setXScrollingSpeed(float xScrollingSpeed) {
this.mXScrollingSpeed = xScrollingSpeed;
}
// Functions related to scrolling.
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mCurrentScrollDirection == Direction.HORIZONTAL) {
float leftDays = Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap));
int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay+mColumnGap));
mStickyScroller.startScroll((int) mCurrentOrigin.x, 0, - nearestOrigin, 0);
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
mCurrentScrollDirection = Direction.NONE;
}
return mGestureDetector.onTouchEvent(event);
}
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.computeScrollOffset()) {
if (Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) < mWidthPerDay + mColumnGap && Math.abs(mScroller.getFinalX() - mScroller.getStartX()) != 0) {
mScroller.forceFinished(true);
float leftDays = Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap));
if(mScroller.getFinalX() < mScroller.getCurrX())
leftDays
else
leftDays++;
int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay+mColumnGap));
mStickyScroller.startScroll((int) mCurrentOrigin.x, 0, - nearestOrigin, 0);
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
else {
if (mCurrentFlingDirection == Direction.VERTICAL) mCurrentOrigin.y = mScroller.getCurrY();
else mCurrentOrigin.x = mScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
}
if (mStickyScroller.computeScrollOffset()) {
mCurrentOrigin.x = mStickyScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
}
// Public methods.
/**
* Show today on the week view.
*/
public void goToToday() {
Calendar today = Calendar.getInstance();
goToDate(today);
}
/**
* Show a specific day on the week view.
* @param date The date to show.
*/
public void goToDate(Calendar date) {
mScroller.forceFinished(true);
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
mRefreshEvents = true;
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
int dateDifference = (int) ((date.getTimeInMillis() - today.getTimeInMillis()) / (1000 * 60 * 60 * 24));
mCurrentOrigin.x = - dateDifference * (mWidthPerDay + mColumnGap);
invalidate();
}
/**
* Refreshes the view and loads the events again.
*/
public void notifyDatasetChanged(){
mRefreshEvents = true;
invalidate();
}
/**
* Vertically scroll to a specific hour in the week view.
* @param hour The hour to scroll to in 24-hour format. Supported values are 0-24.
*/
public void goToHour(double hour){
if (hour < 0)
throw new IllegalArgumentException("Cannot scroll to an hour of negative value.");
else if (hour > 24)
throw new IllegalArgumentException("Cannot scroll to an hour of value greater than 24.");
else if (hour * mHourHeight > mHourHeight * 24 - getHeight() + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)
throw new IllegalArgumentException("Cannot scroll to an hour which will result the calendar to go off the screen.");
int verticalOffset = (int) (mHourHeight * hour);
mCurrentOrigin.y = -verticalOffset;
invalidate();
}
/**
* Get the first hour that is visible on the screen.
* @return The first hour that is visible.
*/
public double getFirstVisibleHour(){
return -mCurrentOrigin.y / mHourHeight;
}
// Interfaces.
public interface EventClickListener {
public void onEventClick(WeekViewEvent event, RectF eventRect);
}
public interface MonthChangeListener {
public List<WeekViewEvent> onMonthChange(int newYear, int newMonth);
}
public interface EventLongPressListener {
public void onEventLongPress(WeekViewEvent event, RectF eventRect);
}
public interface EmptyViewClickListener {
public void onEmptyViewClicked(Calendar time);
}
public interface EmptyViewLongPressListener {
public void onEmptyViewLongPress(Calendar time);
}
// Helper methods.
/**
* Checks if an integer array contains a particular value.
* @param list The haystack.
* @param value The needle.
* @return True if the array contains the value. Otherwise returns false.
*/
private boolean containsValue(int[] list, int value) {
for (int i = 0; i < list.length; i++){
if (list[i] == value)
return true;
}
return false;
}
/**
* Checks if two times are on the same day.
* @param dayOne The first day.
* @param dayTwo The second day.
* @return Whether the times are on the same day.
*/
private boolean isSameDay(Calendar dayOne, Calendar dayTwo) {
return dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR) && dayOne.get(Calendar.DAY_OF_YEAR) == dayTwo.get(Calendar.DAY_OF_YEAR);
}
}
|
package com.mailgun.api.resources.instances;
import com.google.gson.Gson;
import com.mailgun.api.Email;
import com.mailgun.api.Endpoints;
import com.mailgun.api.MailGunClient;
import com.mailgun.api.MailGunResponse;
import com.mailgun.api.exceptions.MailGunException;
import com.mailgun.api.resources.InstanceResource;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import javax.ws.rs.core.MediaType;
public class MessageInstance extends InstanceResource {
MailGunResponse response;
Email email;
public MessageInstance(MailGunClient client, Email email) {
super(client);
this.response = new MailGunResponse();
this.email = email;
}
public void sendSimple() throws MailGunException {
MultivaluedMapImpl formData = new MultivaluedMapImpl();
formData.add("from", this.email.getFrom());
formData.add("to", this.email.getTo());
formData.add("subject", this.email.getSubject());
formData.add("text", "test");
ClientResponse response = this.getClient().getService().path(this.getResourceLocation()).
type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, formData);
this.parseResponse(response);
this.checkStatusCode(this.response);
}
public MailGunResponse sendMIME(MailGunClient client, Email email) {
// todo
return this.response;
}
@Override
protected String getResourceLocation() {
return Endpoints.MESSAGES; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
protected void parseResponse(ClientResponse response) {
Gson gson = new Gson();
this.response = gson.fromJson(response.getEntity(String.class), MailGunResponse.class);
this.response.setStatusCode(response.getStatus());
}
public MailGunResponse getResponse() {
return response;
}
public void setResponse(MailGunResponse mgr) {
this.response = mgr;
}
}
|
package com.alamkanak.weekview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v4.view.ViewCompat;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.HapticFeedbackConstants;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.widget.OverScroller;
import android.widget.Scroller;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class WeekView extends View {
@Deprecated
public static final int LENGTH_SHORT = 1;
@Deprecated
public static final int LENGTH_LONG = 2;
private final Context mContext;
private Calendar mToday;
private Calendar mStartDate;
private Paint mTimeTextPaint;
private float mTimeTextWidth;
private float mTimeTextHeight;
private Paint mHeaderTextPaint;
private float mHeaderTextHeight;
private GestureDetectorCompat mGestureDetector;
private OverScroller mScroller;
private PointF mCurrentOrigin = new PointF(0f, 0f);
private Direction mCurrentScrollDirection = Direction.NONE;
private Paint mHeaderBackgroundPaint;
private float mWidthPerDay;
private Paint mDayBackgroundPaint;
private Paint mHourSeparatorPaint;
private float mHeaderMarginBottom;
private Paint mTodayBackgroundPaint;
private Paint mTodayHeaderTextPaint;
private Paint mEventBackgroundPaint;
private float mHeaderColumnWidth;
private List<EventRect> mEventRects;
private TextPaint mEventTextPaint;
private Paint mHeaderColumnBackgroundPaint;
private Scroller mStickyScroller;
private int mFetchedMonths[] = new int[3];
private boolean mRefreshEvents = false;
private float mDistanceY = 0;
private float mDistanceX = 0;
private Direction mCurrentFlingDirection = Direction.NONE;
// Attributes and their default values.
private int mHourHeight = 50;
private int mColumnGap = 10;
private int mFirstDayOfWeek = Calendar.MONDAY;
private int mTextSize = 12;
private int mHeaderColumnPadding = 10;
private int mHeaderColumnTextColor = Color.BLACK;
private int mNumberOfVisibleDays = 3;
private int mHeaderRowPadding = 10;
private int mHeaderRowBackgroundColor = Color.WHITE;
private int mDayBackgroundColor = Color.rgb(245, 245, 245);
private int mHourSeparatorColor = Color.rgb(230, 230, 230);
private int mTodayBackgroundColor = Color.rgb(239, 247, 254);
private int mHourSeparatorHeight = 2;
private int mTodayHeaderTextColor = Color.rgb(39, 137, 228);
private int mEventTextSize = 12;
private int mEventTextColor = Color.BLACK;
private int mEventPadding = 8;
private int mHeaderColumnBackgroundColor = Color.WHITE;
private int mDefaultEventColor;
private boolean mIsFirstDraw = true;
@Deprecated private int mDayNameLength = LENGTH_LONG;
private int mOverlappingEventGap = 0;
private int mEventMarginVertical = 0;
private float mXScrollingSpeed = 1f;
private Calendar mFirstVisibleDay;
private Calendar mLastVisibleDay;
// Listeners.
private EventClickListener mEventClickListener;
private EventLongPressListener mEventLongPressListener;
private MonthChangeListener mMonthChangeListener;
private EmptyViewClickListener mEmptyViewClickListener;
private EmptyViewLongPressListener mEmptyViewLongPressListener;
private DateTimeInterpreter mDateTimeInterpreter;
private final GestureDetector.SimpleOnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDown(MotionEvent e) {
mScroller.forceFinished(true);
mStickyScroller.forceFinished(true);
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (mCurrentScrollDirection == Direction.NONE) {
if (Math.abs(distanceX) > Math.abs(distanceY)){
mCurrentScrollDirection = Direction.HORIZONTAL;
mCurrentFlingDirection = Direction.HORIZONTAL;
}
else {
mCurrentFlingDirection = Direction.VERTICAL;
mCurrentScrollDirection = Direction.VERTICAL;
}
}
mDistanceX = distanceX;
mDistanceY = distanceY;
invalidate();
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
mScroller.forceFinished(true);
mStickyScroller.forceFinished(true);
if (mCurrentFlingDirection == Direction.HORIZONTAL){
mScroller.fling((int) mCurrentOrigin.x, 0, (int) (velocityX * mXScrollingSpeed), 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
}
else if (mCurrentFlingDirection == Direction.VERTICAL){
mScroller.fling(0, (int) mCurrentOrigin.y, 0, (int) velocityY, 0, 0, (int) -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 - getHeight()), 0);
}
ViewCompat.postInvalidateOnAnimation(WeekView.this);
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// If the tap was on an event then trigger the callback.
if (mEventRects != null && mEventClickListener != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventClickListener.onEventClick(event.originalEvent, event.rectF);
playSoundEffect(SoundEffectConstants.CLICK);
return super.onSingleTapConfirmed(e);
}
}
}
// If the tap was on in an empty space, then trigger the callback.
if (mEmptyViewClickListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
playSoundEffect(SoundEffectConstants.CLICK);
mEmptyViewClickListener.onEmptyViewClicked(selectedTime);
}
}
return super.onSingleTapConfirmed(e);
}
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
if (mEventLongPressListener != null && mEventRects != null) {
List<EventRect> reversedEventRects = mEventRects;
Collections.reverse(reversedEventRects);
for (EventRect event : reversedEventRects) {
if (event.rectF != null && e.getX() > event.rectF.left && e.getX() < event.rectF.right && e.getY() > event.rectF.top && e.getY() < event.rectF.bottom) {
mEventLongPressListener.onEventLongPress(event.originalEvent, event.rectF);
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
return;
}
}
}
// If the tap was on in an empty space, then trigger the callback.
if (mEmptyViewLongPressListener != null && e.getX() > mHeaderColumnWidth && e.getY() > (mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)) {
Calendar selectedTime = getTimeFromPoint(e.getX(), e.getY());
if (selectedTime != null) {
performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
mEmptyViewLongPressListener.onEmptyViewLongPress(selectedTime);
}
}
}
};
private enum Direction {
NONE, HORIZONTAL, VERTICAL
}
public WeekView(Context context) {
this(context, null);
}
public WeekView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WeekView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// Hold references.
mContext = context;
// Get the attribute values (if any).
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.WeekView, 0, 0);
try {
mFirstDayOfWeek = a.getInteger(R.styleable.WeekView_firstDayOfWeek, mFirstDayOfWeek);
mHourHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourHeight, mHourHeight);
mTextSize = a.getDimensionPixelSize(R.styleable.WeekView_textSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, context.getResources().getDisplayMetrics()));
mHeaderColumnPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerColumnPadding, mHeaderColumnPadding);
mColumnGap = a.getDimensionPixelSize(R.styleable.WeekView_columnGap, mColumnGap);
mHeaderColumnTextColor = a.getColor(R.styleable.WeekView_headerColumnTextColor, mHeaderColumnTextColor);
mNumberOfVisibleDays = a.getInteger(R.styleable.WeekView_noOfVisibleDays, mNumberOfVisibleDays);
mHeaderRowPadding = a.getDimensionPixelSize(R.styleable.WeekView_headerRowPadding, mHeaderRowPadding);
mHeaderRowBackgroundColor = a.getColor(R.styleable.WeekView_headerRowBackgroundColor, mHeaderRowBackgroundColor);
mDayBackgroundColor = a.getColor(R.styleable.WeekView_dayBackgroundColor, mDayBackgroundColor);
mHourSeparatorColor = a.getColor(R.styleable.WeekView_hourSeparatorColor, mHourSeparatorColor);
mTodayBackgroundColor = a.getColor(R.styleable.WeekView_todayBackgroundColor, mTodayBackgroundColor);
mHourSeparatorHeight = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mHourSeparatorHeight);
mTodayHeaderTextColor = a.getColor(R.styleable.WeekView_todayHeaderTextColor, mTodayHeaderTextColor);
mEventTextSize = a.getDimensionPixelSize(R.styleable.WeekView_eventTextSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mEventTextSize, context.getResources().getDisplayMetrics()));
mEventTextColor = a.getColor(R.styleable.WeekView_eventTextColor, mEventTextColor);
mEventPadding = a.getDimensionPixelSize(R.styleable.WeekView_hourSeparatorHeight, mEventPadding);
mHeaderColumnBackgroundColor = a.getColor(R.styleable.WeekView_headerColumnBackground, mHeaderColumnBackgroundColor);
mDayNameLength = a.getInteger(R.styleable.WeekView_dayNameLength, mDayNameLength);
mOverlappingEventGap = a.getDimensionPixelSize(R.styleable.WeekView_overlappingEventGap, mOverlappingEventGap);
mEventMarginVertical = a.getDimensionPixelSize(R.styleable.WeekView_eventMarginVertical, mEventMarginVertical);
mXScrollingSpeed = a.getFloat(R.styleable.WeekView_xScrollingSpeed, mXScrollingSpeed);
} finally {
a.recycle();
}
init();
}
private void init() {
// Get the date today.
mToday = Calendar.getInstance();
mToday.set(Calendar.HOUR_OF_DAY, 0);
mToday.set(Calendar.MINUTE, 0);
mToday.set(Calendar.SECOND, 0);
// Scrolling initialization.
mGestureDetector = new GestureDetectorCompat(mContext, mGestureListener);
mScroller = new OverScroller(mContext);
mStickyScroller = new Scroller(mContext);
// Measure settings for time column.
mTimeTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTimeTextPaint.setTextAlign(Paint.Align.RIGHT);
mTimeTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setColor(mHeaderColumnTextColor);
Rect rect = new Rect();
mTimeTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mTimeTextWidth = mTimeTextPaint.measureText("00 PM");
mTimeTextHeight = rect.height();
mHeaderMarginBottom = mTimeTextHeight / 2;
// Measure settings for header row.
mHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mHeaderTextPaint.setColor(mHeaderColumnTextColor);
mHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.getTextBounds("00 PM", 0, "00 PM".length(), rect);
mHeaderTextHeight = rect.height();
mHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
// Prepare header background paint.
mHeaderBackgroundPaint = new Paint();
mHeaderBackgroundPaint.setColor(mHeaderRowBackgroundColor);
// Prepare day background color paint.
mDayBackgroundPaint = new Paint();
mDayBackgroundPaint.setColor(mDayBackgroundColor);
// Prepare hour separator color paint.
mHourSeparatorPaint = new Paint();
mHourSeparatorPaint.setStyle(Paint.Style.STROKE);
mHourSeparatorPaint.setStrokeWidth(mHourSeparatorHeight);
mHourSeparatorPaint.setColor(mHourSeparatorColor);
// Prepare today background color paint.
mTodayBackgroundPaint = new Paint();
mTodayBackgroundPaint.setColor(mTodayBackgroundColor);
// Prepare today header text color paint.
mTodayHeaderTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTodayHeaderTextPaint.setTextAlign(Paint.Align.CENTER);
mTodayHeaderTextPaint.setTextSize(mTextSize);
mTodayHeaderTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
mTodayHeaderTextPaint.setColor(mTodayHeaderTextColor);
// Prepare event background color.
mEventBackgroundPaint = new Paint();
mEventBackgroundPaint.setColor(Color.rgb(174, 208, 238));
// Prepare header column background color.
mHeaderColumnBackgroundPaint = new Paint();
mHeaderColumnBackgroundPaint.setColor(mHeaderColumnBackgroundColor);
// Prepare event text size and color.
mEventTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG);
mEventTextPaint.setStyle(Paint.Style.FILL);
mEventTextPaint.setColor(mEventTextColor);
mEventTextPaint.setTextSize(mEventTextSize);
mStartDate = (Calendar) mToday.clone();
// Set default event color.
mDefaultEventColor = Color.parseColor("#9fc6e7");
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// Draw the header row.
drawHeaderRowAndEvents(canvas);
// Draw the time column and all the axes/separators.
drawTimeColumnAndAxes(canvas);
// Hide everything in the first cell (top left corner).
canvas.drawRect(0, 0, mTimeTextWidth + mHeaderColumnPadding * 2, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Hide anything that is in the bottom margin of the header row.
canvas.drawRect(mHeaderColumnWidth, mHeaderTextHeight + mHeaderRowPadding * 2, getWidth(), mHeaderRowPadding * 2 + mHeaderTextHeight + mHeaderMarginBottom + mTimeTextHeight/2 - mHourSeparatorHeight / 2, mHeaderColumnBackgroundPaint);
}
private void drawTimeColumnAndAxes(Canvas canvas) {
// Do not let the view go above/below the limit due to scrolling. Set the max and min limit of the scroll.
if (mCurrentScrollDirection == Direction.VERTICAL) {
if (mCurrentOrigin.y - mDistanceY > 0) mCurrentOrigin.y = 0;
else if (mCurrentOrigin.y - mDistanceY < -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 - getHeight())) mCurrentOrigin.y = -(mHourHeight * 24 + mHeaderTextHeight + mHeaderRowPadding * 2 - getHeight());
else mCurrentOrigin.y -= mDistanceY;
}
// Draw the background color for the header column.
canvas.drawRect(0, mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderColumnWidth, getHeight(), mHeaderColumnBackgroundPaint);
for (int i = 0; i < 24; i++) {
float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * i + mHeaderMarginBottom;
// Draw the text if its y position is not outside of the visible area. The pivot point of the text is the point at the bottom-right corner.
String time = getDateTimeInterpreter().interpretTime(i);
if (time == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null time");
if (top < getHeight()) canvas.drawText(time, mTimeTextWidth + mHeaderColumnPadding, top + mTimeTextHeight, mTimeTextPaint);
}
}
private void drawHeaderRowAndEvents(Canvas canvas) {
// Calculate the available width for each day.
mHeaderColumnWidth = mTimeTextWidth + mHeaderColumnPadding *2;
mWidthPerDay = getWidth() - mHeaderColumnWidth - mColumnGap * (mNumberOfVisibleDays - 1);
mWidthPerDay = mWidthPerDay/mNumberOfVisibleDays;
// If the week view is being drawn for the first time, then consider the first day of week.
if (mIsFirstDraw && mNumberOfVisibleDays >= 7) {
if (mToday.get(Calendar.DAY_OF_WEEK) != mFirstDayOfWeek) {
int difference = 7 + (mToday.get(Calendar.DAY_OF_WEEK) - mFirstDayOfWeek);
mCurrentOrigin.x += (mWidthPerDay + mColumnGap) * difference;
}
mIsFirstDraw = false;
}
// Consider scroll offset.
if (mCurrentScrollDirection == Direction.HORIZONTAL) mCurrentOrigin.x -= mDistanceX;
int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
float startFromPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps +
mHeaderColumnWidth;
float startPixel = startFromPixel;
// Prepare to iterate for each day.
Calendar day = (Calendar) mToday.clone();
day.add(Calendar.HOUR, 6);
// Prepare to iterate for each hour to draw the hour lines.
int lineCount = (int) ((getHeight() - mHeaderTextHeight - mHeaderRowPadding * 2 -
mHeaderMarginBottom) / mHourHeight) + 1;
lineCount = (lineCount) * (mNumberOfVisibleDays+1);
float[] hourLines = new float[lineCount * 4];
// Clear the cache for event rectangles.
if (mEventRects != null) {
for (EventRect eventRect: mEventRects) {
eventRect.rectF = null;
}
}
// Iterate through each day.
mFirstVisibleDay = (Calendar) mToday.clone();
mFirstVisibleDay.add(Calendar.DATE, -(Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap))));
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1;
dayNumber++) {
// Check if the day is today.
day = (Calendar) mToday.clone();
mLastVisibleDay = (Calendar) day.clone();
day.add(Calendar.DATE, dayNumber - 1);
mLastVisibleDay.add(Calendar.DATE, dayNumber - 2);
boolean sameDay = isSameDay(day, mToday);
// Get more events if necessary. We want to store the events 3 months beforehand. Get
// events only when it is the first iteration of the loop.
if (mEventRects == null || mRefreshEvents || (dayNumber == leftDaysWithGaps + 1 && mFetchedMonths[1] != day.get(Calendar.MONTH)+1 && day.get(Calendar.DAY_OF_MONTH) == 15)) {
getMoreEvents(day);
mRefreshEvents = false;
}
// Draw background color for each day.
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start> 0)
canvas.drawRect(start, mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom, startPixel + mWidthPerDay, getHeight(), sameDay ? mTodayBackgroundPaint : mDayBackgroundPaint);
// Prepare the separator lines for hours.
int i = 0;
for (int hourNumber = 0; hourNumber < 24; hourNumber++) {
float top = mHeaderTextHeight + mHeaderRowPadding * 2 + mCurrentOrigin.y + mHourHeight * hourNumber + mTimeTextHeight/2 + mHeaderMarginBottom;
if (top > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight/2 + mHeaderMarginBottom - mHourSeparatorHeight && top < getHeight() && startPixel + mWidthPerDay - start > 0){
hourLines[i * 4] = start;
hourLines[i * 4 + 1] = top;
hourLines[i * 4 + 2] = startPixel + mWidthPerDay;
hourLines[i * 4 + 3] = top;
i++;
}
}
// Draw the lines for hours.
canvas.drawLines(hourLines, mHourSeparatorPaint);
// Draw the events.
drawEvents(day, startPixel, canvas);
// In the next iteration, start from the next day.
startPixel += mWidthPerDay + mColumnGap;
}
// Draw the header background.
canvas.drawRect(0, 0, getWidth(), mHeaderTextHeight + mHeaderRowPadding * 2, mHeaderBackgroundPaint);
// Draw the header row texts.
startPixel = startFromPixel;
for (int dayNumber=leftDaysWithGaps+1; dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1; dayNumber++) {
// Check if the day is today.
day = (Calendar) mToday.clone();
day.add(Calendar.DATE, dayNumber - 1);
boolean sameDay = isSameDay(day, mToday);
// Draw the day labels.
String dayLabel = getDateTimeInterpreter().interpretDate(day);
if (dayLabel == null)
throw new IllegalStateException("A DateTimeInterpreter must not return null date");
canvas.drawText(dayLabel, startPixel + mWidthPerDay / 2, mHeaderTextHeight + mHeaderRowPadding, sameDay ? mTodayHeaderTextPaint : mHeaderTextPaint);
startPixel += mWidthPerDay + mColumnGap;
}
}
/**
* Get the time and date where the user clicked on.
* @param x The x position of the touch event.
* @param y The y position of the touch event.
* @return The time and date at the clicked position.
*/
private Calendar getTimeFromPoint(float x, float y){
int leftDaysWithGaps = (int) -(Math.ceil(mCurrentOrigin.x / (mWidthPerDay + mColumnGap)));
float startPixel = mCurrentOrigin.x + (mWidthPerDay + mColumnGap) * leftDaysWithGaps +
mHeaderColumnWidth;
for (int dayNumber = leftDaysWithGaps + 1;
dayNumber <= leftDaysWithGaps + mNumberOfVisibleDays + 1;
dayNumber++) {
float start = (startPixel < mHeaderColumnWidth ? mHeaderColumnWidth : startPixel);
if (mWidthPerDay + startPixel - start> 0
&& x>start && x<startPixel + mWidthPerDay){
Calendar day = (Calendar) mToday.clone();
day.add(Calendar.DATE, dayNumber - 1);
float pixelsFromZero = y - mCurrentOrigin.y - mHeaderTextHeight
- mHeaderRowPadding * 2 - mTimeTextHeight/2 - mHeaderMarginBottom;
int hour = (int)(pixelsFromZero / mHourHeight);
int minute = (int) (60 * (pixelsFromZero - hour * mHourHeight) / mHourHeight);
day.add(Calendar.HOUR, hour);
day.set(Calendar.MINUTE, minute);
return day;
}
startPixel += mWidthPerDay + mColumnGap;
}
return null;
}
/**
* Draw all the events of a particular day.
* @param date The day.
* @param startFromPixel The left position of the day area. The events will never go any left from this value.
* @param canvas The canvas to draw upon.
*/
private void drawEvents(Calendar date, float startFromPixel, Canvas canvas) {
if (mEventRects != null && mEventRects.size() > 0) {
for (int i = 0; i < mEventRects.size(); i++) {
if (isSameDay(mEventRects.get(i).event.getStartTime(), date)) {
// Calculate top.
float top = mHourHeight * 24 * mEventRects.get(i).top / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 + mEventMarginVertical;
float originalTop = top;
if (top < mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2)
top = mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2;
// Calculate bottom.
float bottom = mEventRects.get(i).bottom;
bottom = mHourHeight * 24 * bottom / 1440 + mCurrentOrigin.y + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 - mEventMarginVertical;
// Calculate left and right.
float left = startFromPixel + mEventRects.get(i).left * mWidthPerDay;
if (left < startFromPixel)
left += mOverlappingEventGap;
float originalLeft = left;
float right = left + mEventRects.get(i).width * mWidthPerDay;
if (right < startFromPixel + mWidthPerDay)
right -= mOverlappingEventGap;
if (left < mHeaderColumnWidth) left = mHeaderColumnWidth;
// Draw the event and the event name on top of it.
RectF eventRectF = new RectF(left, top, right, bottom);
if (bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight/2 && left < right &&
eventRectF.right > mHeaderColumnWidth &&
eventRectF.left < getWidth() &&
eventRectF.bottom > mHeaderTextHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom &&
eventRectF.top < getHeight() &&
left < right
) {
mEventRects.get(i).rectF = eventRectF;
mEventBackgroundPaint.setColor(mEventRects.get(i).event.getColor() == 0 ? mDefaultEventColor : mEventRects.get(i).event.getColor());
canvas.drawRect(mEventRects.get(i).rectF, mEventBackgroundPaint);
drawText(mEventRects.get(i).event.getName(), mEventRects.get(i).rectF, canvas, originalTop, originalLeft);
}
else
mEventRects.get(i).rectF = null;
}
}
}
}
/**
* Draw the name of the event on top of the event rectangle.
* @param text The text to draw.
* @param rect The rectangle on which the text is to be drawn.
* @param canvas The canvas to draw upon.
* @param originalTop The original top position of the rectangle. The rectangle may have some of its portion outside of the visible area.
* @param originalLeft The original left position of the rectangle. The rectangle may have some of its portion outside of the visible area.
*/
private void drawText(String text, RectF rect, Canvas canvas, float originalTop, float originalLeft) {
if (rect.right - rect.left - mEventPadding * 2 < 0) return;
// Get text dimensions
StaticLayout textLayout = new StaticLayout(text, mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
// Crop height
int availableHeight = (int) (rect.bottom - originalTop - mEventPadding * 2);
int lineHeight = textLayout.getHeight() / textLayout.getLineCount();
if (lineHeight < availableHeight && textLayout.getHeight() > rect.height() - mEventPadding * 2) {
int lineCount = textLayout.getLineCount();
int availableLineCount = (int) Math.floor(lineCount * availableHeight / textLayout.getHeight());
float widthAvailable = (rect.right - originalLeft - mEventPadding * 2) * availableLineCount;
textLayout = new StaticLayout(TextUtils.ellipsize(text, mEventTextPaint, widthAvailable, TextUtils.TruncateAt.END), mEventTextPaint, (int) (rect.right - originalLeft - mEventPadding * 2), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
}
else if (lineHeight >= availableHeight) {
int width = (int) (rect.right - originalLeft - mEventPadding * 2);
textLayout = new StaticLayout(TextUtils.ellipsize(text, mEventTextPaint, width, TextUtils.TruncateAt.END), mEventTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 1.0f, false);
}
// Draw text
canvas.save();
canvas.translate(originalLeft + mEventPadding, originalTop + mEventPadding);
textLayout.draw(canvas);
canvas.restore();
}
/**
* A class to hold reference to the events and their visual representation. An EventRect is
* actually the rectangle that is drawn on the calendar for a given event. There may be more
* than one rectangle for a single event (an event that expands more than one day). In that
* case two instances of the EventRect will be used for a single event. The given event will be
* stored in "originalEvent". But the event that corresponds to rectangle the rectangle
* instance will be stored in "event".
*/
private class EventRect {
public WeekViewEvent event;
public WeekViewEvent originalEvent;
public RectF rectF;
public float left;
public float width;
public float top;
public float bottom;
/**
* Create a new instance of event rect. An EventRect is actually the rectangle that is drawn
* on the calendar for a given event. There may be more than one rectangle for a single
* event (an event that expands more than one day). In that case two instances of the
* EventRect will be used for a single event. The given event will be stored in
* "originalEvent". But the event that corresponds to rectangle the rectangle instance will
* be stored in "event".
* @param event Represents the event which this instance of rectangle represents.
* @param originalEvent The original event that was passed by the user.
* @param rectF The rectangle.
*/
public EventRect(WeekViewEvent event, WeekViewEvent originalEvent, RectF rectF) {
this.event = event;
this.rectF = rectF;
this.originalEvent = originalEvent;
}
}
/**
* Gets more events of one/more month(s) if necessary. This method is called when the user is
* scrolling the week view. The week view stores the events of three months: the visible month,
* the previous month, the next month.
* @param day The day where the user is currently is.
*/
private void getMoreEvents(Calendar day) {
// Delete all events if its not current month +- 1.
deleteFarMonths(day);
// Get more events if the month is changed.
if (mEventRects == null)
mEventRects = new ArrayList<EventRect>();
if (mMonthChangeListener == null && !isInEditMode())
throw new IllegalStateException("You must provide a MonthChangeListener");
// If a refresh was requested then reset some variables.
if (mRefreshEvents) {
mEventRects.clear();
mFetchedMonths = new int[3];
}
// Get events of previous month.
int previousMonth = (day.get(Calendar.MONTH) == 0?12:day.get(Calendar.MONTH));
int nextMonth = (day.get(Calendar.MONTH)+2 == 13 ?1:day.get(Calendar.MONTH)+2);
int[] lastFetchedMonth = mFetchedMonths.clone();
if (mFetchedMonths[0] < 1 || mFetchedMonths[0] != previousMonth || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, previousMonth) && !isInEditMode()){
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange((previousMonth==12)?day.get(Calendar.YEAR)-1:day.get(Calendar.YEAR), previousMonth);
sortEvents(events);
for (WeekViewEvent event: events) {
cacheEvent(event);
}
}
mFetchedMonths[0] = previousMonth;
}
// Get events of this month.
if (mFetchedMonths[1] < 1 || mFetchedMonths[1] != day.get(Calendar.MONTH)+1 || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, day.get(Calendar.MONTH)+1) && !isInEditMode()) {
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange(day.get(Calendar.YEAR), day.get(Calendar.MONTH) + 1);
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
}
mFetchedMonths[1] = day.get(Calendar.MONTH)+1;
}
// Get events of next month.
if (mFetchedMonths[2] < 1 || mFetchedMonths[2] != nextMonth || mRefreshEvents) {
if (!containsValue(lastFetchedMonth, nextMonth) && !isInEditMode()) {
List<WeekViewEvent> events = mMonthChangeListener.onMonthChange(nextMonth == 1 ? day.get(Calendar.YEAR) + 1 : day.get(Calendar.YEAR), nextMonth);
sortEvents(events);
for (WeekViewEvent event : events) {
cacheEvent(event);
}
}
mFetchedMonths[2] = nextMonth;
}
// Prepare to calculate positions of each events.
ArrayList<EventRect> tempEvents = new ArrayList<EventRect>(mEventRects);
mEventRects = new ArrayList<EventRect>();
Calendar dayCounter = (Calendar) day.clone();
dayCounter.add(Calendar.MONTH, -1);
dayCounter.set(Calendar.DAY_OF_MONTH, 1);
Calendar maxDay = (Calendar) day.clone();
maxDay.add(Calendar.MONTH, 1);
maxDay.set(Calendar.DAY_OF_MONTH, maxDay.getActualMaximum(Calendar.DAY_OF_MONTH));
// Iterate through each day to calculate the position of the events.
while (dayCounter.getTimeInMillis() <= maxDay.getTimeInMillis()) {
ArrayList<EventRect> eventRects = new ArrayList<EventRect>();
for (EventRect eventRect : tempEvents) {
if (isSameDay(eventRect.event.getStartTime(), dayCounter))
eventRects.add(eventRect);
}
computePositionOfEvents(eventRects);
dayCounter.add(Calendar.DATE, 1);
}
}
/**
* Cache the event for smooth scrolling functionality.
* @param event The event to cache.
*/
private void cacheEvent(WeekViewEvent event) {
if (!isSameDay(event.getStartTime(), event.getEndTime())) {
Calendar endTime = (Calendar) event.getStartTime().clone();
endTime.set(Calendar.HOUR_OF_DAY, 23);
endTime.set(Calendar.MINUTE, 59);
Calendar startTime = (Calendar) event.getEndTime().clone();
startTime.set(Calendar.HOUR_OF_DAY, 0);
startTime.set(Calendar.MINUTE, 0);
WeekViewEvent event1 = new WeekViewEvent(event.getId(), event.getName(), event.getStartTime(), endTime);
event1.setColor(event.getColor());
WeekViewEvent event2 = new WeekViewEvent(event.getId(), event.getName(), startTime, event.getEndTime());
event2.setColor(event.getColor());
mEventRects.add(new EventRect(event1, event, null));
mEventRects.add(new EventRect(event2, event, null));
}
else
mEventRects.add(new EventRect(event, event, null));
}
/**
* Sorts the events in ascending order.
* @param events The events to be sorted.
*/
private void sortEvents(List<WeekViewEvent> events) {
Collections.sort(events, new Comparator<WeekViewEvent>() {
@Override
public int compare(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
int comparator = start1 > start2 ? 1 : (start1 < start2 ? -1 : 0);
if (comparator == 0) {
long end1 = event1.getEndTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
comparator = end1 > end2 ? 1 : (end1 < end2 ? -1 : 0);
}
return comparator;
}
});
}
/**
* Calculates the left and right positions of each events. This comes handy specially if events
* are overlapping.
* @param eventRects The events along with their wrapper class.
*/
private void computePositionOfEvents(List<EventRect> eventRects) {
// Make "collision groups" for all events that collide with others.
List<List<EventRect>> collisionGroups = new ArrayList<List<EventRect>>();
for (EventRect eventRect : eventRects) {
boolean isPlaced = false;
outerLoop:
for (List<EventRect> collisionGroup : collisionGroups) {
for (EventRect groupEvent : collisionGroup) {
if (isEventsCollide(groupEvent.event, eventRect.event)) {
collisionGroup.add(eventRect);
isPlaced = true;
break outerLoop;
}
}
}
if (!isPlaced) {
List<EventRect> newGroup = new ArrayList<EventRect>();
newGroup.add(eventRect);
collisionGroups.add(newGroup);
}
}
for (List<EventRect> collisionGroup : collisionGroups) {
expandEventsToMaxWidth(collisionGroup);
}
}
/**
* Expands all the events to maximum possible width. The events will try to occupy maximum
* space available horizontally.
* @param collisionGroup The group of events which overlap with each other.
*/
private void expandEventsToMaxWidth(List<EventRect> collisionGroup) {
// Expand the events to maximum possible width.
List<List<EventRect>> columns = new ArrayList<List<EventRect>>();
columns.add(new ArrayList<EventRect>());
for (EventRect eventRect : collisionGroup) {
boolean isPlaced = false;
for (List<EventRect> column : columns) {
if (column.size() == 0) {
column.add(eventRect);
isPlaced = true;
}
else if (!isEventsCollide(eventRect.event, column.get(column.size()-1).event)) {
column.add(eventRect);
isPlaced = true;
break;
}
}
if (!isPlaced) {
List<EventRect> newColumn = new ArrayList<EventRect>();
newColumn.add(eventRect);
columns.add(newColumn);
}
}
// Calculate left and right position for all the events.
int maxRowCount = columns.get(0).size();
for (int i = 0; i < maxRowCount; i++) {
// Set the left and right values of the event.
float j = 0;
for (List<EventRect> column : columns) {
if (column.size() >= i+1) {
EventRect eventRect = column.get(i);
eventRect.width = 1f / columns.size();
eventRect.left = j / columns.size();
eventRect.top = eventRect.event.getStartTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getStartTime().get(Calendar.MINUTE);
eventRect.bottom = eventRect.event.getEndTime().get(Calendar.HOUR_OF_DAY) * 60 + eventRect.event.getEndTime().get(Calendar.MINUTE);
mEventRects.add(eventRect);
}
j++;
}
}
}
/**
* Checks if two events overlap.
* @param event1 The first event.
* @param event2 The second event.
* @return true if the events overlap.
*/
private boolean isEventsCollide(WeekViewEvent event1, WeekViewEvent event2) {
long start1 = event1.getStartTime().getTimeInMillis();
long end1 = event1.getEndTime().getTimeInMillis();
long start2 = event2.getStartTime().getTimeInMillis();
long end2 = event2.getEndTime().getTimeInMillis();
return !((start1 >= end2) || (end1 <= start2));
}
/**
* Checks if time1 occurs after (or at the same time) time2.
* @param time1 The time to check.
* @param time2 The time to check against.
* @return true if time1 and time2 are equal or if time1 is after time2. Otherwise false.
*/
private boolean isTimeAfterOrEquals(Calendar time1, Calendar time2) {
return !(time1 == null || time2 == null) && time1.getTimeInMillis() >= time2.getTimeInMillis();
}
/**
* Deletes the events of the months that are too far away from the current month.
* @param currentDay The current day.
*/
private void deleteFarMonths(Calendar currentDay) {
if (mEventRects == null) return;
Calendar nextMonth = (Calendar) currentDay.clone();
nextMonth.add(Calendar.MONTH, 1);
nextMonth.set(Calendar.DAY_OF_MONTH, nextMonth.getActualMaximum(Calendar.DAY_OF_MONTH));
nextMonth.set(Calendar.HOUR_OF_DAY, 12);
nextMonth.set(Calendar.MINUTE, 59);
nextMonth.set(Calendar.SECOND, 59);
Calendar prevMonth = (Calendar) currentDay.clone();
prevMonth.add(Calendar.MONTH, -1);
prevMonth.set(Calendar.DAY_OF_MONTH, 1);
prevMonth.set(Calendar.HOUR_OF_DAY, 0);
prevMonth.set(Calendar.MINUTE, 0);
prevMonth.set(Calendar.SECOND, 0);
List<EventRect> newEvents = new ArrayList<EventRect>();
for (EventRect eventRect : mEventRects) {
boolean isFarMonth = eventRect.event.getStartTime().getTimeInMillis() > nextMonth.getTimeInMillis() || eventRect.event.getEndTime().getTimeInMillis() < prevMonth.getTimeInMillis();
if (!isFarMonth) newEvents.add(eventRect);
}
mEventRects.clear();
mEventRects.addAll(newEvents);
}
// Functions related to setting and getting the properties.
public void setOnEventClickListener (EventClickListener listener) {
this.mEventClickListener = listener;
}
public EventClickListener getEventClickListener() {
return mEventClickListener;
}
public MonthChangeListener getMonthChangeListener() {
return mMonthChangeListener;
}
public void setMonthChangeListener(MonthChangeListener monthChangeListener) {
this.mMonthChangeListener = monthChangeListener;
}
public EventLongPressListener getEventLongPressListener() {
return mEventLongPressListener;
}
public void setEventLongPressListener(EventLongPressListener eventLongPressListener) {
this.mEventLongPressListener = eventLongPressListener;
}
public void setEmptyViewClickListener(EmptyViewClickListener emptyViewClickListener){
this.mEmptyViewClickListener = emptyViewClickListener;
}
public EmptyViewClickListener getEmptyViewClickListener(){
return mEmptyViewClickListener;
}
public void setEmptyViewLongPressListener(EmptyViewLongPressListener emptyViewLongPressListener){
this.mEmptyViewLongPressListener = emptyViewLongPressListener;
}
public EmptyViewLongPressListener getEmptyViewLongPressListener(){
return mEmptyViewLongPressListener;
}
/**
* Get the interpreter which provides the text to show in the header column and the header row.
* @return The date, time interpreter.
*/
public DateTimeInterpreter getDateTimeInterpreter() {
if (mDateTimeInterpreter == null) {
mDateTimeInterpreter = new DateTimeInterpreter() {
@Override
public String interpretDate(Calendar date) {
SimpleDateFormat sdf;
sdf = mDayNameLength == LENGTH_SHORT ? new SimpleDateFormat("EEEEE") : new SimpleDateFormat("EEE");
try{
String dayName = sdf.format(date.getTime()).toUpperCase();
return String.format("%s %d/%02d", dayName, date.get(Calendar.MONTH) + 1, date.get(Calendar.DAY_OF_MONTH));
}catch (Exception e){
e.printStackTrace();
return "";
}
}
@Override
public String interpretTime(int hour) {
String amPm;
if (hour >= 0 && hour < 12) amPm = "AM";
else amPm = "PM";
if (hour == 0) hour = 12;
if (hour > 12) hour -= 12;
return String.format("%02d %s", hour, amPm);
}
};
}
return mDateTimeInterpreter;
}
/**
* Set the interpreter which provides the text to show in the header column and the header row.
* @param dateTimeInterpreter The date, time interpreter.
*/
public void setDateTimeInterpreter(DateTimeInterpreter dateTimeInterpreter){
this.mDateTimeInterpreter = dateTimeInterpreter;
}
/**
* Get the number of visible days in a week.
* @return The number of visible days in a week.
*/
public int getNumberOfVisibleDays() {
return mNumberOfVisibleDays;
}
/**
* Set the number of visible days in a week.
* @param numberOfVisibleDays The number of visible days in a week.
*/
public void setNumberOfVisibleDays(int numberOfVisibleDays) {
this.mNumberOfVisibleDays = numberOfVisibleDays;
mCurrentOrigin.x = 0;
mCurrentOrigin.y = 0;
invalidate();
}
public int getHourHeight() {
return mHourHeight;
}
public void setHourHeight(int hourHeight) {
mHourHeight = hourHeight;
invalidate();
}
public int getColumnGap() {
return mColumnGap;
}
public void setColumnGap(int columnGap) {
mColumnGap = columnGap;
invalidate();
}
public int getFirstDayOfWeek() {
return mFirstDayOfWeek;
}
/**
* Set the first day of the week. First day of the week is used only when the week view is first
* drawn. It does not of any effect after user starts scrolling horizontally.
* <p>
* <b>Note:</b> This method will only work if the week view is set to display more than 6 days at
* once.
* </p>
* @param firstDayOfWeek The supported values are {@link java.util.Calendar#SUNDAY},
* {@link java.util.Calendar#MONDAY}, {@link java.util.Calendar#TUESDAY},
* {@link java.util.Calendar#WEDNESDAY}, {@link java.util.Calendar#THURSDAY},
* {@link java.util.Calendar#FRIDAY}.
*/
public void setFirstDayOfWeek(int firstDayOfWeek) {
mFirstDayOfWeek = firstDayOfWeek;
invalidate();
}
public int getTextSize() {
return mTextSize;
}
public void setTextSize(int textSize) {
mTextSize = textSize;
mTodayHeaderTextPaint.setTextSize(mTextSize);
mHeaderTextPaint.setTextSize(mTextSize);
mTimeTextPaint.setTextSize(mTextSize);
invalidate();
}
public int getHeaderColumnPadding() {
return mHeaderColumnPadding;
}
public void setHeaderColumnPadding(int headerColumnPadding) {
mHeaderColumnPadding = headerColumnPadding;
invalidate();
}
public int getHeaderColumnTextColor() {
return mHeaderColumnTextColor;
}
public void setHeaderColumnTextColor(int headerColumnTextColor) {
mHeaderColumnTextColor = headerColumnTextColor;
invalidate();
}
public int getHeaderRowPadding() {
return mHeaderRowPadding;
}
public void setHeaderRowPadding(int headerRowPadding) {
mHeaderRowPadding = headerRowPadding;
invalidate();
}
public int getHeaderRowBackgroundColor() {
return mHeaderRowBackgroundColor;
}
public void setHeaderRowBackgroundColor(int headerRowBackgroundColor) {
mHeaderRowBackgroundColor = headerRowBackgroundColor;
invalidate();
}
public int getDayBackgroundColor() {
return mDayBackgroundColor;
}
public void setDayBackgroundColor(int dayBackgroundColor) {
mDayBackgroundColor = dayBackgroundColor;
invalidate();
}
public int getHourSeparatorColor() {
return mHourSeparatorColor;
}
public void setHourSeparatorColor(int hourSeparatorColor) {
mHourSeparatorColor = hourSeparatorColor;
invalidate();
}
public int getTodayBackgroundColor() {
return mTodayBackgroundColor;
}
public void setTodayBackgroundColor(int todayBackgroundColor) {
mTodayBackgroundColor = todayBackgroundColor;
invalidate();
}
public int getHourSeparatorHeight() {
return mHourSeparatorHeight;
}
public void setHourSeparatorHeight(int hourSeparatorHeight) {
mHourSeparatorHeight = hourSeparatorHeight;
invalidate();
}
public int getTodayHeaderTextColor() {
return mTodayHeaderTextColor;
}
public void setTodayHeaderTextColor(int todayHeaderTextColor) {
mTodayHeaderTextColor = todayHeaderTextColor;
invalidate();
}
public int getEventTextSize() {
return mEventTextSize;
}
public void setEventTextSize(int eventTextSize) {
mEventTextSize = eventTextSize;
mEventTextPaint.setTextSize(mEventTextSize);
invalidate();
}
public int getEventTextColor() {
return mEventTextColor;
}
public void setEventTextColor(int eventTextColor) {
mEventTextColor = eventTextColor;
invalidate();
}
public int getEventPadding() {
return mEventPadding;
}
public void setEventPadding(int eventPadding) {
mEventPadding = eventPadding;
invalidate();
}
public int getHeaderColumnBackgroundColor() {
return mHeaderColumnBackgroundColor;
}
public void setHeaderColumnBackgroundColor(int headerColumnBackgroundColor) {
mHeaderColumnBackgroundColor = headerColumnBackgroundColor;
invalidate();
}
public int getDefaultEventColor() {
return mDefaultEventColor;
}
public void setDefaultEventColor(int defaultEventColor) {
mDefaultEventColor = defaultEventColor;
invalidate();
}
/**
* <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} and
* {@link #getDateTimeInterpreter()} instead.
* @return Either long or short day name is being used.
*/
@Deprecated
public int getDayNameLength() {
return mDayNameLength;
}
/**
* Set the length of the day name displayed in the header row. Example of short day names is
* 'M' for 'Monday' and example of long day names is 'Mon' for 'Monday'.
* <p>
* <b>Note:</b> Use {@link #setDateTimeInterpreter(DateTimeInterpreter)} instead.
* </p>
* @param length Supported values are {@link com.alamkanak.weekview.WeekView#LENGTH_SHORT} and
* {@link com.alamkanak.weekview.WeekView#LENGTH_LONG}.
*/
@Deprecated
public void setDayNameLength(int length) {
if (length != LENGTH_LONG && length != LENGTH_SHORT) {
throw new IllegalArgumentException("length parameter must be either LENGTH_LONG or LENGTH_SHORT");
}
this.mDayNameLength = length;
}
public int getOverlappingEventGap() {
return mOverlappingEventGap;
}
/**
* Set the gap between overlapping events.
* @param overlappingEventGap The gap between overlapping events.
*/
public void setOverlappingEventGap(int overlappingEventGap) {
this.mOverlappingEventGap = overlappingEventGap;
invalidate();
}
public int getEventMarginVertical() {
return mEventMarginVertical;
}
/**
* Set the top and bottom margin of the event. The event will release this margin from the top
* and bottom edge. This margin is useful for differentiation consecutive events.
* @param eventMarginVertical The top and bottom margin.
*/
public void setEventMarginVertical(int eventMarginVertical) {
this.mEventMarginVertical = eventMarginVertical;
invalidate();
}
/**
* Returns the first visible day in the week view.
* @return The first visible day in the week view.
*/
public Calendar getFirstVisibleDay() {
return mFirstVisibleDay;
}
/**
* Returns the last visible day in the week view.
* @return The last visible day in the week view.
*/
public Calendar getLastVisibleDay() {
return mLastVisibleDay;
}
/**
* Get the scrolling speed factor in horizontal direction.
* @return The speed factor in horizontal direction.
*/
public float getXScrollingSpeed() {
return mXScrollingSpeed;
}
/**
* Sets the speed for horizontal scrolling.
* @param xScrollingSpeed The new horizontal scrolling speed.
*/
public void setXScrollingSpeed(float xScrollingSpeed) {
this.mXScrollingSpeed = xScrollingSpeed;
}
// Functions related to scrolling.
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (mCurrentScrollDirection == Direction.HORIZONTAL) {
float leftDays = Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap));
int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay+mColumnGap));
mStickyScroller.startScroll((int) mCurrentOrigin.x, 0, - nearestOrigin, 0);
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
mCurrentScrollDirection = Direction.NONE;
}
return mGestureDetector.onTouchEvent(event);
}
@Override
public void computeScroll() {
super.computeScroll();
if (mScroller.computeScrollOffset()) {
if (Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) < mWidthPerDay + mColumnGap && Math.abs(mScroller.getFinalX() - mScroller.getStartX()) != 0) {
mScroller.forceFinished(true);
float leftDays = Math.round(mCurrentOrigin.x / (mWidthPerDay + mColumnGap));
if(mScroller.getFinalX() < mScroller.getCurrX())
leftDays
else
leftDays++;
int nearestOrigin = (int) (mCurrentOrigin.x - leftDays * (mWidthPerDay+mColumnGap));
mStickyScroller.startScroll((int) mCurrentOrigin.x, 0, - nearestOrigin, 0);
ViewCompat.postInvalidateOnAnimation(WeekView.this);
}
else {
if (mCurrentFlingDirection == Direction.VERTICAL) mCurrentOrigin.y = mScroller.getCurrY();
else mCurrentOrigin.x = mScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
}
if (mStickyScroller.computeScrollOffset()) {
mCurrentOrigin.x = mStickyScroller.getCurrX();
ViewCompat.postInvalidateOnAnimation(this);
}
}
// Public methods.
/**
* Show today on the week view.
*/
public void goToToday() {
Calendar today = Calendar.getInstance();
goToDate(today);
}
/**
* Show a specific day on the week view.
* @param date The date to show.
*/
public void goToDate(Calendar date) {
mScroller.forceFinished(true);
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
mRefreshEvents = true;
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
long day = 1000L * 60L * 60L * 24L;
long dateDifference = (date.getTimeInMillis()/day) - (today.getTimeInMillis()/day);
mCurrentOrigin.x = - dateDifference * (mWidthPerDay + mColumnGap);
invalidate();
}
/**
* Refreshes the view and loads the events again.
*/
public void notifyDatasetChanged(){
mRefreshEvents = true;
invalidate();
}
/**
* Vertically scroll to a specific hour in the week view.
* @param hour The hour to scroll to in 24-hour format. Supported values are 0-24.
*/
public void goToHour(double hour){
if (hour < 0)
throw new IllegalArgumentException("Cannot scroll to an hour of negative value.");
else if (hour > 24)
throw new IllegalArgumentException("Cannot scroll to an hour of value greater than 24.");
else if (hour * mHourHeight > mHourHeight * 24 - getHeight() + mHeaderTextHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom)
throw new IllegalArgumentException("Cannot scroll to an hour which will result the calendar to go off the screen.");
int verticalOffset = (int) (mHourHeight * hour);
mCurrentOrigin.y = -verticalOffset;
invalidate();
}
// Interfaces.
public interface EventClickListener {
public void onEventClick(WeekViewEvent event, RectF eventRect);
}
public interface MonthChangeListener {
public List<WeekViewEvent> onMonthChange(int newYear, int newMonth);
}
public interface EventLongPressListener {
public void onEventLongPress(WeekViewEvent event, RectF eventRect);
}
public interface EmptyViewClickListener {
public void onEmptyViewClicked(Calendar time);
}
public interface EmptyViewLongPressListener {
public void onEmptyViewLongPress(Calendar time);
}
// Helper methods.
/**
* Checks if an integer array contains a particular value.
* @param list The haystack.
* @param value The needle.
* @return True if the array contains the value. Otherwise returns false.
*/
private boolean containsValue(int[] list, int value) {
for (int i = 0; i < list.length; i++){
if (list[i] == value)
return true;
}
return false;
}
/**
* Checks if two times are on the same day.
* @param dayOne The first day.
* @param dayTwo The second day.
* @return Whether the times are on the same day.
*/
private boolean isSameDay(Calendar dayOne, Calendar dayTwo) {
return dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR) && dayOne.get(Calendar.DAY_OF_YEAR) == dayTwo.get(Calendar.DAY_OF_YEAR);
}
}
|
package com.mcjty.rftools.dimension;
import com.mcjty.rftools.RFTools;
import com.mcjty.rftools.dimension.world.GenericWorldProvider;
import com.mcjty.rftools.items.dimlets.KnownDimletConfiguration;
import com.mcjty.rftools.network.PacketHandler;
import com.mcjty.rftools.network.PacketRegisterDimensions;
import com.mcjty.varia.Coordinate;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import net.minecraft.world.WorldSavedData;
import net.minecraft.world.WorldServer;
import net.minecraft.world.gen.ChunkProviderServer;
import net.minecraftforge.common.DimensionManager;
import net.minecraftforge.common.util.Constants;
import java.util.HashMap;
import java.util.Map;
public class RfToolsDimensionManager extends WorldSavedData {
public static final String DIMMANAGER_NAME = "RFToolsDimensionManager";
private static RfToolsDimensionManager instance = null;
private final Map<Integer, DimensionDescriptor> dimensions = new HashMap<Integer, DimensionDescriptor>();
private final Map<DimensionDescriptor, Integer> dimensionToID = new HashMap<DimensionDescriptor, Integer>();
private final Map<Integer, DimensionInformation> dimensionInformation = new HashMap<Integer, DimensionInformation>();
public void syncFromServer(Map<Integer, DimensionDescriptor> dimensions, Map<DimensionDescriptor, Integer> dimensionToID, Map<Integer, DimensionInformation> dimensionInformation) {
System.out.println("RfToolsDimensionManager.syncFromServer");
this.dimensions.clear();
this.dimensions.putAll(dimensions);
this.dimensionToID.clear();
this.dimensionToID.putAll(dimensionToID);
this.dimensionInformation.clear();
this.dimensionInformation.putAll(dimensionInformation);
}
public RfToolsDimensionManager(String identifier) {
super(identifier);
}
public static void clearInstance() {
if (instance != null) {
instance.dimensions.clear();
instance.dimensionToID.clear();
instance.dimensionInformation.clear();
instance = null;
}
}
public static void unregisterDimensions() {
if (instance != null) {
RFTools.log("Cleaning up RFTools dimensions");
for (Map.Entry<Integer, DimensionDescriptor> me : instance.getDimensions().entrySet()) {
int id = me.getKey();
RFTools.log(" Dimension: " + id);
DimensionManager.unregisterDimension(id);
DimensionManager.unregisterProviderType(id);
}
instance.getDimensions().clear();
instance.dimensionToID.clear();
instance.dimensionInformation.clear();
}
}
public void save(World world) {
world.mapStorage.setData(DIMMANAGER_NAME, this);
markDirty();
syncDimInfoToClients(world);
}
/**
* Check if the client dimlet id's match with the server.
*/
public void checkDimletConfig(EntityPlayer player) {
if (!player.getEntityWorld().isRemote) {
// Send over dimlet configuration to the client so that the client can check that the id's match.
RFTools.log("Send validation data to the client");
Map<Integer, String> dimlets = new HashMap<Integer, String>(KnownDimletConfiguration.idToDisplayName);
PacketHandler.INSTANCE.sendTo(new PacketCheckDimletConfig(dimlets), (EntityPlayerMP) player);
}
}
public void checkDimletConfigFromServer(Map<Integer, String> dimlets) {
for (Map.Entry<Integer, String> entry : dimlets.entrySet()) {
int id = entry.getKey();
String name = entry.getValue();
if (!KnownDimletConfiguration.idToDisplayName.containsKey(id)) {
RFTools.logError("Dimlet id " + id + " (" + name + ") is missing on the client!");
RFTools.log("Dimlet id " + id + " (" + name + ") is missing on the client!");
} else if (!KnownDimletConfiguration.idToDisplayName.get(id).equals(name)) {
RFTools.logError("Dimlet id " + id + " (" + name + ") is mapped to another dimlet on the client: " + KnownDimletConfiguration.idToDisplayName.get(id) + "!");
RFTools.log("Dimlet id " + id + " (" + name + ") is mapped to another dimlet on the client: " + KnownDimletConfiguration.idToDisplayName.get(id) + "!");
}
}
for (Map.Entry<Integer, String> entry : KnownDimletConfiguration.idToDisplayName.entrySet()) {
int id = entry.getKey();
String name = entry.getValue();
if (!dimlets.containsKey(id)) {
RFTools.logError("Client has an invalid mapping for dimlet " + id + " (" + name + ")!");
RFTools.log("Client has an invalid mapping for dimlet " + id + " (" + name + ")!");
}
}
}
public void syncDimInfoToClients(World world) {
if (!world.isRemote) {
// Sync to clients.
RFTools.log("Sync dimension info to clients!");
PacketHandler.INSTANCE.sendToAll(new PacketSyncDimensionInfo(dimensions, dimensionToID, dimensionInformation));
}
}
public Map<Integer, DimensionDescriptor> getDimensions() {
return dimensions;
}
public void registerDimensions() {
RFTools.log("Registering RFTools dimensions");
for (Map.Entry<Integer, DimensionDescriptor> me : dimensions.entrySet()) {
int id = me.getKey();
RFTools.log(" Dimension: " + id);
registerDimensionToServerAndClient(id);
}
}
private void registerDimensionToServerAndClient(int id) {
DimensionManager.registerProviderType(id, GenericWorldProvider.class, false);
DimensionManager.registerDimension(id, id);
PacketHandler.INSTANCE.sendToAll(new PacketRegisterDimensions(id));
}
public static RfToolsDimensionManager getDimensionManager(World world) {
// if (world.isRemote) {
// return null;
if (instance != null) {
return instance;
}
instance = (RfToolsDimensionManager) world.mapStorage.loadData(RfToolsDimensionManager.class, DIMMANAGER_NAME);
if (instance == null) {
instance = new RfToolsDimensionManager(DIMMANAGER_NAME);
}
return instance;
}
public DimensionDescriptor getDimensionDescriptor(int id) {
return dimensions.get(id);
}
public Integer getDimensionID(DimensionDescriptor descriptor) {
return dimensionToID.get(descriptor);
}
public DimensionInformation getDimensionInformation(int id) {
return dimensionInformation.get(id);
}
/**
* Get a world for a dimension, possibly loading it from the configuration manager.
* @param id
* @return
*/
public World getWorldForDimension(int id) {
World w = DimensionManager.getWorld(id);
if (w == null) {
WorldServer worldServer = MinecraftServer.getServer().getConfigurationManager().getServerInstance().worldServerForDimension(id);
w = worldServer;
}
return w;
}
public void removeDimension(int id) {
DimensionDescriptor descriptor = dimensions.get(id);
dimensions.remove(id);
dimensionToID.remove(descriptor);
dimensionInformation.remove(id);
}
public int createNewDimension(World world, DimensionDescriptor descriptor, String name) {
int id = DimensionManager.getNextFreeDimId();
registerDimensionToServerAndClient(id);
RFTools.log("id = " + id + " for " + name + ", descriptor = " + descriptor.getDescriptionString());
dimensions.put(id, descriptor);
dimensionToID.put(descriptor, id);
DimensionInformation dimensionInfo = new DimensionInformation(name, descriptor, world.getSeed());
dimensionInformation.put(id, dimensionInfo);
save(world);
// Make sure world generation kicks in for at least one chunk so that our matter receiver
// is generated and registered.
WorldServer worldServerForDimension = MinecraftServer.getServer().worldServerForDimension(id);
ChunkProviderServer providerServer = worldServerForDimension.theChunkProviderServer;
if (!providerServer.chunkExists(0, 0)) {
try {
providerServer.loadChunk(0, 0);
providerServer.populate(providerServer, 0, 0);
providerServer.unloadChunksIfNotNearSpawn(0, 0);
} catch (Exception e) {
RFTools.logError("Something went wrong during creation of the dimension!");
e.printStackTrace();
// We catch this exception to make sure our dimension tab is at least ok.
}
}
return id;
}
@Override
public void readFromNBT(NBTTagCompound tagCompound) {
dimensions.clear();
dimensionToID.clear();
dimensionInformation.clear();
NBTTagList lst = tagCompound.getTagList("dimensions", Constants.NBT.TAG_COMPOUND);
for (int i = 0 ; i < lst.tagCount() ; i++) {
NBTTagCompound tc = lst.getCompoundTagAt(i);
int id = tc.getInteger("id");
DimensionDescriptor descriptor = new DimensionDescriptor(tc);
dimensions.put(id, descriptor);
dimensionToID.put(descriptor, id);
DimensionInformation dimensionInfo = new DimensionInformation(descriptor, tc);
dimensionInformation.put(id, dimensionInfo);
}
}
@Override
public void writeToNBT(NBTTagCompound tagCompound) {
NBTTagList lst = new NBTTagList();
for (Map.Entry<Integer,DimensionDescriptor> me : dimensions.entrySet()) {
NBTTagCompound tc = new NBTTagCompound();
Integer id = me.getKey();
tc.setInteger("id", id);
me.getValue().writeToNBT(tc);
DimensionInformation dimensionInfo = dimensionInformation.get(id);
dimensionInfo.writeToNBT(tc);
lst.appendTag(tc);
}
tagCompound.setTag("dimensions", lst);
}
}
|
package de.mrapp.android.util;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import java.io.File;
import java.lang.reflect.Constructor;
/**
* An utility class, which provides static methods, which allow to ensure, that variables and
* objects fulfill certain conditions. If a condition is not violated, an exception is thrown by
* each of these methods.
*
* @author Michael Rapp
* @since 1.0.0
*/
public final class Condition {
/**
* Creates a new utility class, which provides static methods, hwich allows to ensure, that
* variables and objects fulfill certain conditions.
*/
private Condition() {
}
/**
* Throws a specific runtime exception. The exception is instantiated using reflection and must
* provide a constructor, which expects exactly one {@link String} parameter. If instantiating
* the exception fails, a {@link RuntimeException} is thrown instead.
*
* @param exceptionMessage
* The message of the exception, which should be thrown, as a {@link String} or null, if
* the exception should not have a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, as an instance of the
* class {@link Class}. The class may not be null
*/
private static void throwException(@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
RuntimeException exception;
try {
Constructor<? extends RuntimeException> constructor =
exceptionClass.getConstructor(String.class);
exception = constructor.newInstance(exceptionMessage);
} catch (Exception e) {
exception = new RuntimeException(exceptionMessage);
}
throw exception;
}
/**
* Ensures that an object is not null. Otherwise a {@link NullPointerException} with a specific
* message is thrown.
*
* @param object
* The object, which should be checked, as an instance of the class {@link Object}
* @param exceptionMessage
* The message of the exception, which is thrown, if the given object is null, as a
* {@link String} or null, if the exception should not have a message
*/
public static void ensureNotNull(final Object object, @Nullable final String exceptionMessage) {
if (object == null) {
throw new NullPointerException(exceptionMessage);
}
}
/**
* Ensures that an object is not null. Otherwise a specific {@link RuntimeException} is thrown.
*
* @param object
* The object, which should be checked, as an instance of the class {@link Object}
* @param exceptionMessage
* The message of the exception, which is thrown, if the given object is null, as a
* {@link String} or null, if the exception should not have a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given object is
* null, as an instance of the class {@link Class}. The class may not be null
*/
public static void ensureNotNull(final Object object, @Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (object == null) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureNotEmpty(final CharSequence text,
@Nullable final String exceptionMessage) {
if (TextUtils.isEmpty(text)) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a text is not empty. Otherwise a specific {@link RuntimeException} is thrown.
*
* @param text
* The text, which should be checked, as an instance of the type {@link CharSequence}
* @param exceptionMessage
* The message of the exception, which is thrown, if the given text is empty, as a
* {@link String} or null, if the exception should not have a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given text is
* empty, as an instance of the class {@link Class}. The class may not be null
*/
public static void ensureNotEmpty(final CharSequence text,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (TextUtils.isEmpty(text)) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureAtLeast(final short value, final short referenceValue,
@Nullable final String exceptionMessage) {
if (value < referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Short} value is at least as great as a reference value. Otherwise a
* specific {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Short} value
* @param referenceValue
* The reference value, the given value must be at least as great as, as a {@link Short}
* value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is smaller as the
* reference value, as a {@link String} or null, if the exception should not have a
* message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* smaller as the reference value, as an instance of the class {@link Class}. The class
* may not be null
*/
public static void ensureAtLeast(final short value, final short referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value < referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureAtLeast(final int value, final int referenceValue,
@Nullable final String exceptionMessage) {
if (value < referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that an {@link Integer} value is at least as great as a reference value. Otherwise a
* specific {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as an {@link Integer} value
* @param referenceValue
* The reference value, the given value must be at least as great as, as an {@link
* Integer} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is smaller as the
* reference value, as a {@link String} or null, if the exception should not have a
* message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* smaller as the reference value, as an instance of the class {@link Class}. The class
* may not be null
*/
public static void ensureAtLeast(final int value, final int referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value < referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureAtLeast(final long value, final long referenceValue,
@Nullable final String exceptionMessage) {
if (value < referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Long} value is at least as great as a reference value. Otherwise a
* specific {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Long} value
* @param referenceValue
* The reference value, the given value must be at least as great as, as a {@link Long}
* value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is smaller as the
* reference value, as a {@link String} or null, if the exception should not have a
* message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* smaller as the reference value, as an instance of the class {@link Class}. The class
* may not be null
*/
public static void ensureAtLeast(final long value, final long referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value < referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureAtLeast(final float value, final float referenceValue,
@Nullable final String exceptionMessage) {
if (value < referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Float} value is at least as great as a reference value. Otherwise a
* specific {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Float} value
* @param referenceValue
* The reference value, the given value must be at least as great as, as a {@link Float}
* value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is smaller as the
* reference value, as a {@link String} or null, if the exception should not have a
* message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* smaller as the reference value, as an instance of the class {@link Class}. The class
* may not be null
*/
public static void ensureAtLeast(final float value, final float referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value < referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureAtLeast(final double value, final double referenceValue,
@Nullable final String exceptionMessage) {
if (value < referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Double} value is at least as great as a reference value. Otherwise a
* specific {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Double} value
* @param referenceValue
* The reference value, the given value must be at least as great as, as a {@link
* Double} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is smaller as the
* reference value, as a {@link String} or null, if the exception should not have a
* message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* smaller as the reference value, as an instance of the class {@link Class}. The class
* may not be null
*/
public static void ensureAtLeast(final double value, final double referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value < referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureAtMaximum(final short value, final short referenceValue,
@Nullable final String exceptionMessage) {
if (value > referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Short} value is at maximum as great as a reference value. Otherwise a
* specific {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Short} value
* @param referenceValue
* The reference value, the given value must be at maximum as great as, as a {@link
* Short} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is greater as the
* reference value, as a {@link String} or null, if the exception should not have a
* message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* greater as the reference value, as an instance of the class {@link Class}. The class
* may not be null
*/
public static void ensureAtMaximum(final short value, final short referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value > referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureAtMaximum(final int value, final int referenceValue,
@Nullable final String exceptionMessage) {
if (value > referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that an {@link Integer} value is at maximum as great as a reference value. Otherwise
* a specific {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as an {@link Integer} value
* @param referenceValue
* The reference value, the given value must be at maximum as great as, as a {@link
* Short} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is greater as the
* reference value, as a {@link String} or null, if the exception should not have a
* message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* greater as the reference value, as an instance of the class {@link Class}. The class
* may not be null
*/
public static void ensureAtMaximum(final int value, final int referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value > referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureAtMaximum(final long value, final long referenceValue,
@Nullable final String exceptionMessage) {
if (value > referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Long} value is at maximum as great as a reference value. Otherwise a
* specific {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Long} value
* @param referenceValue
* The reference value, the given value must be at maximum as great as, as a {@link
* Long} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is greater as the
* reference value, as a {@link String} or null, if the exception should not have a
* message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* greater as the reference value, as an instance of the class {@link Class}. The class
* may not be null
*/
public static void ensureAtMaximum(final long value, final long referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value > referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureAtMaximum(final float value, final float referenceValue,
@Nullable final String exceptionMessage) {
if (value > referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Float} value is at maximum as great as a reference value. Otherwise a
* specific {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Float} value
* @param referenceValue
* The reference value, the given value must be at maximum as great as, as a {@link
* Float} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is greater as the
* reference value, as a {@link String} or null, if the exception should not have a
* message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* greater as the reference value, as an instance of the class {@link Class}. The class
* may not be null
*/
public static void ensureAtMaximum(final float value, final float referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value > referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureAtMaximum(final double value, final double referenceValue,
@Nullable final String exceptionMessage) {
if (value > referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Double} value is at maximum as great as a reference value. Otherwise a
* specific {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Double} value
* @param referenceValue
* The reference value, the given value must be at maximum as great as, as a {@link
* Double} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is greater as the
* reference value, as a {@link String} or null, if the exception should not have a
* message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* greater as the reference value, as an instance of the class {@link Class}. The class
* may not be null
*/
public static void ensureAtMaximum(final double value, final double referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value > referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureGreater(final short value, final short referenceValue,
@Nullable final String exceptionMessage) {
if (value <= referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Short} value is greater as a reference value. Otherwise a specific
* {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Short} value
* @param referenceValue
* The reference value, the given value must be greater as, as a {@link Short} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is smaller or equal
* as the reference value, as a {@link String} or null, if the exception should not have
* a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* smaller or equal as the reference value, as an instance of the class {@link Class}.
* The class may not be null
*/
public static void ensureGreater(final short value, final short referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value <= referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureGreater(final int value, final int referenceValue,
@Nullable final String exceptionMessage) {
if (value <= referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that an {@link Integer} value is greater as a reference value. Otherwise a specific
* {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as an {@link Integer} value
* @param referenceValue
* The reference value, the given value must be greater as, as an {@link Integer} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is smaller or equal
* as the reference value, as a {@link String} or null, if the exception should not have
* a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* smaller or equal as the reference value, as an instance of the class {@link Class}.
* The class may not be null
*/
public static void ensureGreater(final int value, final int referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value <= referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureGreater(final long value, final long referenceValue,
@Nullable final String exceptionMessage) {
if (value <= referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Long} value is greater as a reference value. Otherwise a specific
* {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Long} value
* @param referenceValue
* The reference value, the given value must be greater as, as a {@link Long} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is smaller or equal
* as the reference value, as a {@link String} or null, if the exception should not have
* a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* smaller or equal as the reference value, as an instance of the class {@link Class}.
* The class may not be null
*/
public static void ensureGreater(final long value, final long referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value <= referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureGreater(final float value, final float referenceValue,
@Nullable final String exceptionMessage) {
if (value <= referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Float} value is greater as a reference value. Otherwise a specific
* {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Float} value
* @param referenceValue
* The reference value, the given value must be greater as, as a {@link Float} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is smaller or equal
* as the reference value, as a {@link String} or null, if the exception should not have
* a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* smaller or equal as the reference value, as an instance of the class {@link Class}.
* The class may not be null
*/
public static void ensureGreater(final float value, final float referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value <= referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureGreater(final double value, final double referenceValue,
@Nullable final String exceptionMessage) {
if (value <= referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Double} value is greater as a reference value. Otherwise a specific
* {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Double} value
* @param referenceValue
* The reference value, the given value must be greater as, as a {@link Double} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is smaller or equal
* as the reference value, as a {@link String} or null, if the exception should not have
* a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* smaller or equal as the reference value, as an instance of the class {@link Class}.
* The class may not be null
*/
public static void ensureGreater(final double value, final double referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value <= referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureSmaller(final short value, final short referenceValue,
@Nullable final String exceptionMessage) {
if (value >= referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Short} value is smaller as a reference value. Otherwise a specific
* {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Short} value
* @param referenceValue
* The reference value, the given value must be smaller as, as a {@link Short} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is greater or equal
* as the reference value, as a {@link String} or null, if the exception should not have
* a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* greater or equal as the reference value, as an instance of the class {@link Class}.
* The class may not be null
*/
public static void ensureSmaller(final short value, final short referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value >= referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureSmaller(final int value, final int referenceValue,
@Nullable final String exceptionMessage) {
if (value >= referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that an {@link Integer} value is smaller as a reference value. Otherwise a specific
* {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as an {@link Integer} value
* @param referenceValue
* The reference value, the given value must be smaller as, as an {@link Integer} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is greater or equal
* as the reference value, as a {@link String} or null, if the exception should not have
* a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* greater or equal as the reference value, as an instance of the class {@link Class}.
* The class may not be null
*/
public static void ensureSmaller(final int value, final int referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value >= referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureSmaller(final long value, final long referenceValue,
@Nullable final String exceptionMessage) {
if (value >= referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Long} value is smaller as a reference value. Otherwise a specific
* {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Long} value
* @param referenceValue
* The reference value, the given value must be smaller as, as a {@link Long} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is greater or equal
* as the reference value, as a {@link String} or null, if the exception should not have
* a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* greater or equal as the reference value, as an instance of the class {@link Class}.
* The class may not be null
*/
public static void ensureSmaller(final long value, final long referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value >= referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureSmaller(final float value, final float referenceValue,
@Nullable final String exceptionMessage) {
if (value >= referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Float} value is smaller as a reference value. Otherwise a specific
* {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Float} value
* @param referenceValue
* The reference value, the given value must be smaller as, as a {@link Float} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is greater or equal
* as the reference value, as a {@link String} or null, if the exception should not have
* a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* greater or equal as the reference value, as an instance of the class {@link Class}.
* The class may not be null
*/
public static void ensureSmaller(final float value, final float referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value >= referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureSmaller(final double value, final double referenceValue,
@Nullable final String exceptionMessage) {
if (value >= referenceValue) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a {@link Double} value is smaller as a reference value. Otherwise a specific
* {@link RuntimeException} is thrown.
*
* @param value
* The value, which should be checked, as a {@link Double} value
* @param referenceValue
* The reference value, the given value must be smaller as, as a {@link Double} value
* @param exceptionMessage
* The message of the exception, which is thrown, if the given value is greater or equal
* as the reference value, as a {@link String} or null, if the exception should not have
* a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given value is
* greater or equal as the reference value, as an instance of the class {@link Class}.
* The class may not be null
*/
public static void ensureSmaller(final double value, final double referenceValue,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (value >= referenceValue) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureFileExists(final File file, final String exceptionMessage) {
if (!file.exists()) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a specific file exists. Otherwise a specific {@link RuntimeException} is
* thrown.
*
* @param file
* The file, which should be checked, as an instance of the class {@link File}. The file
* may not be null
* @param exceptionMessage
* The message of the exception, which is thrown, if the given file does not exist, as a
* {@link String} or null, if the exception should not have a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given file does
* not exist, as an instance of the class {@link Class}. The class may not be null
*/
public static void ensureFileExists(@NonNull final File file,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (!file.exists()) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureFileIsDirectory(@NonNull final File file,
@Nullable final String exceptionMessage) {
if (!file.isDirectory()) {
throw new IllegalArgumentException(exceptionMessage);
}
}
/**
* Ensures, that a specific file is a directory. Otherwise a specific {@link RuntimeException}
* is thrown.
*
* @param file
* The file, which should be checked, as an instance of the class {@link File}. The file
* may not be null
* @param exceptionMessage
* The message of the exception, which is thrown, if the given file is not a directory,
* as a {@link String} or null, if the exception should not have a message
* @param exceptionClass
* The class of the runtime exception, which should be thrown, if the given file is not
* a directory, as an instance of the class {@link Class}. The class may not be null
*/
public static void ensureFileIsDirectory(@NonNull final File file,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (!file.isDirectory()) {
throwException(exceptionMessage, exceptionClass);
}
}
public static void ensureFileIsNoDirectory(@NonNull final File file,
@Nullable final String exceptionMessage) {
if (!file.isFile()) {
throw new IllegalArgumentException(exceptionMessage);
}
}
public static void ensureFileIsNoDirectory(@NonNull final File file,
@Nullable final String exceptionMessage,
@NonNull final Class<? extends RuntimeException> exceptionClass) {
if (!file.isFile()) {
throwException(exceptionMessage, exceptionClass);
}
}
}
|
package main.java.com.mindscapehq.android.raygun4android;
import java.io.*;
import java.lang.Thread.UncaughtExceptionHandler;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import com.google.gson.Gson;
import main.java.com.mindscapehq.android.raygun4android.messages.RaygunMessage;
import main.java.com.mindscapehq.android.raygun4android.messages.RaygunUserInfo;
/**
* User: Mindscape
* The official Raygun provider for Android. This is the main class that provides functionality
* for automatically sending exceptions to the Raygun service.
*
* You should call Init() on the static RaygunClient instance, passing in the current Context,
* instead of instantiating this class.
*/
public class RaygunClient
{
private static String _apiKey;
private static Context _context;
private static String _version;
private static Intent _service;
private static String _appContextIdentifier;
private static String _user;
private static RaygunUserInfo _userInfo;
private static RaygunUncaughtExceptionHandler _handler;
private static RaygunOnBeforeSend _onBeforeSend;
private static List _tags;
private static Map _userCustomData;
/**
* Initializes the Raygun client. This expects that you have placed the API key in your
* AndroidManifest.xml, in a <meta-data /> element.
* @param context The context of the calling Android activity.
*/
public static void Init(Context context) {
String apiKey = readApiKey(context);
Init(context, apiKey);
_appContextIdentifier = UUID.randomUUID().toString();
}
/**
* Initializes the Raygun client with the version of your application.
* This expects that you have placed the API key in your AndroidManifest.xml, in a <meta-data /> element.
* @param version The version of your application, format x.x.x.x, where x is a positive integer.
* @param context The context of the calling Android activity.
*/
public static void Init(String version, Context context) {
String apiKey = readApiKey(context);
Init(context, apiKey, version);
}
/**
* Initializes the Raygun client with your Android application's context and your
* Raygun API key. The version transmitted will be the value of the versionName attribute in your manifest element.
* @param context The Android context of your activity
* @param apiKey An API key that belongs to a Raygun application created in your dashboard
*/
public static void Init(Context context, String apiKey)
{
_apiKey = apiKey;
_context = context;
String version = null;
try
{
version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e)
{
Log.i("Raygun4Android", "Couldn't read version from calling package");
}
if (version != null)
{
_version = version;
}
else
{
_version = "Not provided";
}
}
/**
* Initializes the Raygun client with your Android application's context, your
* Raygun API key, and the version of your application
* @param context The Android context of your activity
* @param apiKey An API key that belongs to a Raygun application created in your dashboard
* @param version The version of your application, format x.x.x.x, where x is a positive integer.
*/
public static void Init(Context context, String apiKey, String version)
{
Init(context, apiKey);
_version = version;
}
/**
* Attaches a pre-built Raygun exception handler to the thread's DefaultUncaughtExceptionHandler.
* This automatically sends any exceptions that reaches it to the Raygun API.
*/
public static void AttachExceptionHandler() {
UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();
if (!(oldHandler instanceof RaygunUncaughtExceptionHandler))
{
_handler = new RaygunUncaughtExceptionHandler(oldHandler);
Thread.setDefaultUncaughtExceptionHandler(_handler);
}
}
/**
* Attaches a pre-built Raygun exception handler to the thread's DefaultUncaughtExceptionHandler.
* This automatically sends any exceptions that reaches it to the Raygun API.
* @param tags A list of tags that relate to the calling application's currently build or state.
* These will be appended to all exception messages sent to Raygun.
* @deprecated Call AttachExceptionHandler(), then SetTags(List) instead
*/
@Deprecated
public static void AttachExceptionHandler(List tags) {
UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();
if (!(oldHandler instanceof RaygunUncaughtExceptionHandler))
{
_handler = new RaygunUncaughtExceptionHandler(oldHandler, tags);
Thread.setDefaultUncaughtExceptionHandler(_handler);
}
}
/**
* Attaches a pre-built Raygun exception handler to the thread's DefaultUncaughtExceptionHandler.
* This automatically sends any exceptions that reaches it to the Raygun API.
* @param tags A list of tags that relate to the calling application's currently build or state.
* These will be appended to all exception messages sent to Raygun.
* @param userCustomData A set of key-value pairs that will be attached to each exception message
* sent to Raygun. This can contain any extra data relating to the calling
* application's state you would like to see.
* @deprecated Call AttachExceptionHandler(), then SetUserCustomData(Map) instead
*/
@Deprecated
public static void AttachExceptionHandler(List tags, Map userCustomData) {
UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();
if (!(oldHandler instanceof RaygunUncaughtExceptionHandler))
{
_handler = new RaygunUncaughtExceptionHandler(oldHandler, tags, userCustomData);
Thread.setDefaultUncaughtExceptionHandler(_handler);
}
}
/**
* Sends an exception-type object to Raygun.
* @param throwable The Throwable object that occurred in your application that will be sent to Raygun.
*/
public static void Send(Throwable throwable)
{
RaygunMessage msg = BuildMessage(throwable);
postCachedMessages();
if (_tags != null) {
msg.getDetails().setTags(_tags);
}
if (_userCustomData != null) {
msg.getDetails().setUserCustomData(_userCustomData);
}
if (_onBeforeSend != null) {
msg = _onBeforeSend.OnBeforeSend(msg);
if (msg == null) {
return;
}
}
spinUpService(_apiKey, new Gson().toJson(msg));
}
/**
* Sends an exception-type object to Raygun with a list of tags you specify.
* @param throwable The Throwable object that occurred in your application that will be sent to Raygun.
* @param tags A list of data that will be attached to the Raygun message and visible on the error in the dashboard.
* This could be a build tag, lifecycle state, debug/production version etc.
*/
public static void Send(Throwable throwable, List tags)
{
RaygunMessage msg = BuildMessage(throwable);
msg.getDetails().setTags(mergeTags(tags));
if (_userCustomData != null) {
msg.getDetails().setUserCustomData(_userCustomData);
}
if (_onBeforeSend != null) {
msg = _onBeforeSend.OnBeforeSend(msg);
if (msg == null) {
return;
}
}
postCachedMessages();
spinUpService(_apiKey, new Gson().toJson(msg));
}
/**
* Sends an exception-type object to Raygun with a list of tags you specify, and a set of
* custom data.
* @param throwable The Throwable object that occurred in your application that will be sent to Raygun.
* @param tags A list of data that will be attached to the Raygun message and visible on the error in the dashboard.
* This could be a build tag, lifecycle state, debug/production version etc.
* @param userCustomData A set of custom key-value pairs relating to your application and its current state. This is a bucket
* where you can attach any related data you want to see to the error.
*/
public static void Send(Throwable throwable, List tags, Map userCustomData)
{
RaygunMessage msg = BuildMessage(throwable);
msg.getDetails().setTags(mergeTags(tags));
msg.getDetails().setUserCustomData(mergeUserCustomData(userCustomData));
if (_onBeforeSend != null) {
msg = _onBeforeSend.OnBeforeSend(msg);
if (msg == null) {
return;
}
}
postCachedMessages();
spinUpService(_apiKey, new Gson().toJson(msg));
}
/**
* Raw post method that delivers a pre-built RaygunMessage to the Raygun API. You do not need to call this method
* directly unless you want to manually build your own message - for most purposes you should call Send().
* @param apiKey The API key of the app to deliver to
* @param jsonPayload The JSON representation of a RaygunMessage to be delivered over HTTPS.
* @return HTTP result code - 202 if successful, 403 if API key invalid, 400 if bad message (invalid properties)
*/
public static int Post(String apiKey, String jsonPayload)
{
try
{
if (validateApiKey(apiKey))
{
URL endpoint = new URL(RaygunSettings.getSettings().getApiEndpoint());
HttpURLConnection connection = (HttpURLConnection) endpoint.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("X-ApiKey", apiKey);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream outputStream = connection.getOutputStream();
outputStream.write(jsonPayload.toString().getBytes("UTF-8"));
outputStream.close();
int responseCode = connection.getResponseCode();
Log.d("Raygun4Android", "Exception message HTTP POST result: " + responseCode);
return responseCode;
}
}
catch (Exception e)
{
Log.e("Raygun4Android", "Couldn't post exception - " + e.getMessage());
e.printStackTrace();
}
return -1;
}
private static boolean hasInternetConnection()
{
ConnectivityManager cm = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
private static RaygunMessage BuildMessage(Throwable throwable)
{
try
{
RaygunMessage msg = RaygunMessageBuilder.New()
.SetEnvironmentDetails(_context)
.SetMachineName(Build.MODEL)
.SetExceptionDetails(throwable)
.SetClientDetails()
.SetAppContext(_appContextIdentifier)
.SetVersion(_version)
.SetNetworkInfo(_context)
.Build();
if (_version != null)
{
msg.getDetails().setVersion(_version);
}
if (_userInfo != null)
{
msg.getDetails().setUserContext(_userInfo, _context);
}
else if (_user != null)
{
msg.getDetails().setUserContext(_user);
}
else
{
msg.getDetails().setUserContext(_context);
}
return msg;
}
catch (Exception e)
{
Log.e("Raygun4Android", "Failed to build RaygunMessage - " + e);
}
return null;
}
private static String readApiKey(Context context)
{
try
{
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;
String apiKey = bundle.getString("com.mindscapehq.android.raygun4android.apikey");
return apiKey;
}
catch (PackageManager.NameNotFoundException e)
{
Log.e("Raygun4Android", "Couldn't read API key from your AndroidManifest.xml <meta-data /> element; cannot send: " + e.getMessage());
}
return null;
}
private static Boolean validateApiKey(String apiKey) throws Exception
{
if (apiKey.length() == 0)
{
Log.e("Raygun4Android", "API key has not been provided, exception will not be logged");
return false;
}
else
{
return true;
}
}
private static void postCachedMessages()
{
if (hasInternetConnection())
{
File[] fileList = _context.getCacheDir().listFiles();
for (File f : fileList)
{
try
{
String ext = getExtension(f.getName());
if (ext.equalsIgnoreCase("raygun"))
{
ObjectInputStream ois = null;
try
{
ois = new ObjectInputStream(new FileInputStream(f));
MessageApiKey messageApiKey = (MessageApiKey) ois.readObject();
spinUpService(messageApiKey.apiKey, messageApiKey.message);
f.delete();
}
finally
{
ois.close();
}
}
}
catch (FileNotFoundException e)
{
Log.e("Raygun4Android", "Error loading cached message from filesystem - " + e.getMessage());
} catch (IOException e)
{
Log.e("Raygun4Android", "Error reading cached message from filesystem - " + e.getMessage());
} catch (ClassNotFoundException e)
{
Log.e("Raygun4Android", "Error in cached message from filesystem - " + e.getMessage());
}
}
}
}
private static void spinUpService(String apiKey, String jsonPayload)
{
Intent intent;
if (_service == null)
{
intent = new Intent(_context, RaygunPostService.class);
intent.setAction("main.java.com.mindscapehq.android.raygun4android.RaygunClient.RaygunPostService");
intent.setPackage("main.java.com.mindscapehq.android.raygun4android.RaygunClient");
intent.setComponent(new ComponentName(_context, RaygunPostService.class));
}
else
{
intent = _service;
}
intent.putExtra("msg", jsonPayload);
intent.putExtra("apikey", apiKey);
_service = intent;
_context.startService(_service);
}
private static List mergeTags(List paramTags) {
if (_tags != null) {
List merged = new ArrayList(_tags);
merged.addAll(paramTags);
return merged;
} else {
return paramTags;
}
}
private static Map mergeUserCustomData(Map paramUserCustomData) {
if (_userCustomData != null) {
Map merged = new HashMap(_userCustomData);
merged.putAll(paramUserCustomData);
return merged;
} else {
return paramUserCustomData;
}
}
protected static String getExtension(String filename) {
if (filename == null)
{
return null;
}
int separator = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
int dotPos = filename.lastIndexOf(".");
int index = separator > dotPos ? -1 : dotPos;
if (index == -1)
{
return "";
}
else
{
return filename.substring(index + 1);
}
}
/**
* Sets the current user of your application. If user is an email address which is associated with a Gravatar,
* their picture will be displayed in the error view. If this is not called a random ID will be assigned.
* If the user context changes in your application (i.e log in/out), be sure to call this again with the
* updated user name/email address.
* @deprecated Call SetUser(RaygunUserInfo) instead
* @param user A user name or email address representing the current user
*/
@Deprecated
public static void SetUser(String user)
{
if (user != null && user.length() > 0)
{
_user = user;
}
}
public static void SetUser(RaygunUserInfo userInfo)
{
_userInfo = userInfo;
}
/**
* Manually stores the version of your application to be transmitted with each message, for version
* filtering. This is normally read from your AndroidManifest.xml (the versionName attribute on <manifest>)
* or passed in on Init(); this is only provided as a convenience.
* @param version The version of your application, format x.x.x.x, where x is a positive integer.
*/
public static void SetVersion(String version)
{
if (version != null)
{
_version = version;
}
}
public static RaygunUncaughtExceptionHandler GetExceptionHandler() {
return _handler;
}
public static String getApiKey()
{
return _apiKey;
}
public static List GetTags() {
return _tags;
}
public static void SetTags(List tags) {
_tags = tags;
}
public static Map GetUserCustomData() {
return _userCustomData;
}
public static void SetUserCustomData(Map userCustomData) {
_userCustomData = userCustomData;
}
public static void SetOnBeforeSend(RaygunOnBeforeSend onBeforeSend) { _onBeforeSend = onBeforeSend; }
public static class RaygunUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler
{
private UncaughtExceptionHandler _defaultHandler;
private List _tags;
private Map _userCustomData;
public RaygunUncaughtExceptionHandler(UncaughtExceptionHandler defaultHandler)
{
_defaultHandler = defaultHandler;
}
@Deprecated
public RaygunUncaughtExceptionHandler(UncaughtExceptionHandler defaultHandler, List tags)
{
_defaultHandler = defaultHandler;
_tags = tags;
}
@Deprecated
public RaygunUncaughtExceptionHandler(UncaughtExceptionHandler defaultHandler, List tags, Map userCustomData)
{
_defaultHandler = defaultHandler;
_tags = tags;
_userCustomData = userCustomData;
}
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
if (_userCustomData != null)
{
RaygunClient.Send(throwable, _tags, _userCustomData);
}
else if (_tags != null)
{
RaygunClient.Send(throwable, _tags);
}
else
{
RaygunClient.Send(throwable);
}
_defaultHandler.uncaughtException(thread, throwable);
}
}
}
|
package be.ibridge.kettle.test;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.exception.KettleXMLException;
import be.ibridge.kettle.core.util.EnvUtil;
import be.ibridge.kettle.job.JobEntryLoader;
import be.ibridge.kettle.trans.StepLoader;
import be.ibridge.kettle.trans.Trans;
import be.ibridge.kettle.trans.TransMeta;
public class Test3692
{
public static void main(String[] args) throws KettleXMLException
{
if (args.length==0)
{
System.err.println("Usage: Test3692 <transformation file> <nr of iterations>");
return;
}
// init...
EnvUtil.environmentInit();
StepLoader.getInstance().read();
JobEntryLoader.getInstance().read();
LogWriter log = LogWriter.getInstance(LogWriter.LOG_LEVEL_BASIC);
TransMeta transMeta = new TransMeta(args[0]);
int iterations = 10000;
if (args.length>1) Integer.parseInt(args[1]);
Trans trans = new Trans(log, transMeta);
for (int i=0;i<iterations;i++)
{
trans.execute(null);
}
}
}
|
package com.mmakowski.maven.plugins.specs2;
import java.io.File;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
/**
* Executes specs2 runner for all specifications in the current project. A thing
* wrapper for {@link Specs2Runner}, which is implemented in Scala.
*
* @author Maciek Makowski
* @requiresDependencyResolution test
* @goal run-specs
* @phase verify
* @since 1.0.0
*/
public class Specs2RunnerMojo extends AbstractMojo {
/** @parameter default-value="${project}" */
private MavenProject mavenProject;
/** @parameter default-value="${project.build.testOutputDirectory}" */
private File testClassesDirectory;
/** @parameter default-value="${project.build.outputDirectory}" */
private File classesDirectory;
public void execute() throws MojoExecutionException, MojoFailureException {
if (!(new Specs2Runner().runSpecs(getLog(), mavenProject, classesDirectory, testClassesDirectory).booleanValue()))
throw new MojoFailureException("there have been errors/failures");
}
}
|
package com.nincraft.modpackdownloader.handler;
import com.google.common.base.Strings;
import com.nincraft.modpackdownloader.container.ModLoader;
import com.nincraft.modpackdownloader.util.FileSystemHelper;
import com.nincraft.modpackdownloader.util.Reference;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
@Log4j2
public class ForgeHandler {
public static void downloadForge(String minecraftVersion, List<ModLoader> modLoaders) {
if (CollectionUtils.isEmpty(modLoaders) || Strings.isNullOrEmpty(minecraftVersion)) {
log.debug("No Forge or Minecraft version found in manifest, skipping");
return;
}
ModLoader modLoader = modLoaders.get(0);
String forgeVersion = modLoader.getId();
String folder = modLoader.getFolder();
String forgeId = forgeVersion.substring(forgeVersion.indexOf("-") + 1);
log.info(String.format("Downloading Forge version %s", forgeVersion));
if (modLoader.getDownloadInstaller() != null && modLoader.getDownloadInstaller()) {
downloadForgeFile(minecraftVersion, modLoader, folder, forgeId, Reference.forgeInstaller);
}
if (modLoader.getDownloadUniversal() != null && modLoader.getDownloadUniversal()) {
downloadForgeFile(minecraftVersion, modLoader, folder, forgeId, Reference.forgeUniversal);
}
}
private static void downloadForgeFile(String minecraftVersion, ModLoader modLoader, String folder, String forgeId, String fileType) {
String forgeFileName = "forge-" + minecraftVersion + "-" + forgeId;
String forgeURL = Reference.forgeURL + minecraftVersion + "-" + forgeId;
if (!minecraftVersion.startsWith("1.8")) {
forgeFileName += "-" + minecraftVersion;
forgeURL += "-" + minecraftVersion;
}
forgeFileName += fileType;
forgeURL += "/" + forgeFileName;
if (!FileSystemHelper.isInLocalRepo("forge", forgeFileName) || Reference.forceDownload) {
File downloadedFile;
if (modLoader.getRename() != null) {
downloadedFile = FileSystemHelper.getDownloadedFile(modLoader.getRename(), folder);
} else {
downloadedFile = FileSystemHelper.getDownloadedFile(forgeFileName, folder);
}
try {
FileUtils.copyURLToFile(new URL(forgeURL), downloadedFile);
} catch (final IOException e) {
log.error(String.format("Could not download %s.", forgeFileName), e.getMessage());
return;
}
FileSystemHelper.copyToLocalRepo("forge", downloadedFile);
} else {
FileSystemHelper.copyFromLocalRepo("forge", forgeFileName, folder);
}
log.info(String.format("Completed downloading Forge version %s", forgeFileName));
}
}
|
package com.publicuhc.ultrahardcore.commands;
import com.publicuhc.pluginframework.commands.annotation.CommandMethod;
import com.publicuhc.pluginframework.commands.annotation.RouteInfo;
import com.publicuhc.pluginframework.commands.requests.CommandRequest;
import com.publicuhc.pluginframework.commands.routes.RouteBuilder;
import com.publicuhc.pluginframework.configuration.Configurator;
import com.publicuhc.pluginframework.shaded.inject.Inject;
import com.publicuhc.pluginframework.translate.Translate;
import com.publicuhc.ultrahardcore.features.FeatureManager;
import com.publicuhc.ultrahardcore.features.IFeature;
import org.bukkit.ChatColor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FeatureCommand extends SimpleCommand {
public static final String FEATURE_LIST_PERMISSION = "UHC.feature.list";
public static final String FEATURE_TOGGLE_PERMISSION = "UHC.feature.toggle";
private final FeatureManager m_featureManager;
/**
* feature commands
* @param configManager the config manager
* @param translate the translator
* @param featureManager the feature manager
*/
@Inject
private FeatureCommand(Configurator configManager, Translate translate, FeatureManager featureManager){
super(configManager, translate);
m_featureManager = featureManager;
}
/**
* @param request request params
*/
@CommandMethod
public void featureCommand(CommandRequest request){
request.sendMessage(ChatColor.RED+"/feature list - List features");
request.sendMessage(ChatColor.RED + "/feature on <featureID> - turn feature on");
request.sendMessage(ChatColor.RED+"/feature off <featureID> - turn feature off");
}
/**
* Run whenever a /feature command is run and nothing else triggers
* @param builder the builder
*/
@RouteInfo
public void featureCommandDetails(RouteBuilder builder) {
builder.restrictCommand("feature").maxMatches(1);
}
/**
* List all the features and their status
* @param request request params
*/
@CommandMethod
public void featureListCommand(CommandRequest request){
List<IFeature> features = m_featureManager.getFeatures();
request.sendMessage(translate("features.loaded.header", request.getLocale(), "amount", String.valueOf(features.size())));
if (features.isEmpty()) {
request.sendMessage(translate("features.loaded.none", request.getLocale()));
}
for (IFeature feature : features) {
Map<String, String> vars = new HashMap<String, String>();
vars.put("id", feature.getFeatureID());
vars.put("desc", feature.getDescription());
request.sendMessage(translate(feature.isEnabled()?"features.loaded.on":"features.loaded.off", request.getLocale(), vars));
List<String> status = feature.getStatus();
if (status != null) {
for(String message : status) {
request.sendMessage(message);
}
}
}
}
/**
* Run on /feauture list
* @param builder the builder
*/
@RouteInfo
public void featureListCommandDetails(RouteBuilder builder) {
builder.restrictCommand("feature")
.restrictPermission(FEATURE_LIST_PERMISSION)
.restrictStartsWith("list");
}
/**
* Turn on a feature
* @param request request params
*/
@CommandMethod
public void featureOnCommand(CommandRequest request){
IFeature feature = m_featureManager.getFeatureByID(request.getArg(1));
if(null == feature){
request.sendMessage(translate("features.not_found", request.getLocale(), "id", request.getFirstArg()));
return;
}
if(feature.isEnabled()){
request.sendMessage(translate("features.already_enabled", request.getLocale()));
return;
}
if(!feature.enableFeature()){
request.sendMessage(translate("features.enabled_cancelled", request.getLocale()));
return;
}
request.sendMessage(translate("features.enabled", request.getLocale()));
}
/**
* Run on /feature on {name}
* @param builder the builder
*/
@RouteInfo
public void featureOnCommandDetails(RouteBuilder builder) {
builder.restrictCommand("feature")
.restrictPermission(FEATURE_TOGGLE_PERMISSION)
.restrictStartsWith("on")
.restrictArgumentCount(2, 2);
}
/**
* Toggle a feature off
* @param request request params
*/
@CommandMethod
public void featureOffCommand(CommandRequest request){
IFeature feature = m_featureManager.getFeatureByID(request.getArg(1));
if(null == feature){
request.sendMessage(translate("features.not_found", request.getLocale(), "id", request.getFirstArg()));
return;
}
if(!feature.isEnabled()){
request.sendMessage(translate("features.already_disabled", request.getLocale()));
return;
}
if(!feature.disableFeature()){
request.sendMessage(translate("features.disabled_cancelled", request.getLocale()));
return;
}
request.sendMessage(translate("features.disabled", request.getLocale()));
}
/**
* Run on /feature off {name}
* @param builder the builder
*/
@RouteInfo
public void featureOffCommandDetails(RouteBuilder builder) {
builder.restrictCommand("feature")
.restrictPermission(FEATURE_TOGGLE_PERMISSION)
.restrictStartsWith("off")
.restrictArgumentCount(2, 2);
}
@CommandMethod
public void featureToggleCommand(CommandRequest request) {
IFeature feature = m_featureManager.getFeatureByID(request.getArg(1));
if(null == feature){
request.sendMessage(translate("features.not_found", request.getLocale(), "id", request.getFirstArg()));
return;
}
if(feature.isEnabled()) {
feature.enableFeature();
request.sendMessage(translate("features.enabled", request.getLocale()));
} else {
feature.disableFeature();
request.sendMessage(translate("features.disabled", request.getLocale()));
}
}
@RouteInfo
public void featureToggleCommandDetails(RouteBuilder builder) {
builder.restrictCommand("feature")
.restrictPermission(FEATURE_TOGGLE_PERMISSION)
.restrictStartsWith("toggle")
.restrictArgumentCount(2, 2);
}
}
|
package com.qiniu.android.storage;
import com.qiniu.android.collect.ReportItem;
import com.qiniu.android.collect.UploadInfoReporter;
import com.qiniu.android.common.ZoneInfo;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.http.metrics.UploadRegionRequestMetrics;
import com.qiniu.android.http.request.RequestTransaction;
import com.qiniu.android.http.request.IUploadRegion;
import com.qiniu.android.http.request.handler.RequestProgressHandler;
import com.qiniu.android.utils.AsyncRun;
import com.qiniu.android.utils.Utils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.List;
import java.util.Map;
class PartsUpload extends BaseUpload {
PartsUploadPerformer uploadPerformer;
private ResponseInfo uploadDataErrorResponseInfo;
private JSONObject uploadDataErrorResponse;
protected PartsUpload(File file,
String key,
UpToken token,
UploadOptions option,
Configuration config,
Recorder recorder,
String recorderKey,
UpTaskCompletionHandler completionHandler) {
super(file, key, token, option, config, recorder, recorderKey, completionHandler);
}
@Override
protected void initData() {
super.initData();
if (config != null && config.resumeUploadVersion == Configuration.RESUME_UPLOAD_VERSION_V1) {
uploadPerformer = new PartsUploadPerformerV1(file, fileName, key, token, option, config, recorderKey);
} else {
uploadPerformer = new PartsUploadPerformerV2(file, fileName, key, token, option, config, recorderKey);
}
}
boolean isAllUploaded() {
if (uploadPerformer.fileInfo == null) {
return false;
} else {
return uploadPerformer.fileInfo.isAllUploaded();
}
}
private void setErrorResponse(ResponseInfo responseInfo, JSONObject response) {
if (responseInfo == null) {
return;
}
if (uploadDataErrorResponseInfo == null || responseInfo.statusCode != ResponseInfo.SDKInteriorError) {
uploadDataErrorResponseInfo = responseInfo;
if (response == null) {
uploadDataErrorResponse = responseInfo.response;
} else {
uploadDataErrorResponse = response;
}
}
}
@Override
protected int prepareToUpload() {
int code = super.prepareToUpload();
if (code != 0) {
return code;
}
if (uploadPerformer.currentRegion != null && uploadPerformer.currentRegion.isValid()) {
insertRegionAtFirst(uploadPerformer.currentRegion);
} else {
uploadPerformer.switchRegion(getCurrentRegion());
}
if (file == null || !uploadPerformer.canReadFile()) {
code = ResponseInfo.LocalIOError;
}
return code;
}
@Override
protected boolean switchRegion() {
boolean isSuccess = super.switchRegion();
if (isSuccess) {
uploadPerformer.switchRegion(getCurrentRegion());
}
return isSuccess;
}
@Override
protected boolean switchRegionAndUpload() {
reportBlock();
return super.switchRegionAndUpload();
}
@Override
protected void startToUpload() {
uploadDataErrorResponse = null;
uploadDataErrorResponseInfo = null;
// 1. upload
serverInit(new UploadFileCompleteHandler() {
@Override
public void complete(ResponseInfo responseInfo, JSONObject response) {
if (!responseInfo.isOK()) {
if (!switchRegionAndUploadIfNeededWithErrorResponse(responseInfo)) {
completeAction(responseInfo, response);
}
return;
}
uploadRestData(new UploadFileRestDataCompleteHandler() {
@Override
public void complete() {
if (!isAllUploaded()) {
if (!switchRegionAndUploadIfNeededWithErrorResponse(uploadDataErrorResponseInfo)) {
completeAction(uploadDataErrorResponseInfo, uploadDataErrorResponse);
}
return;
}
completeUpload(new UploadFileCompleteHandler() {
@Override
public void complete(ResponseInfo responseInfo, JSONObject response) {
if (shouldRemoveUploadInfoRecord(responseInfo)) {
uploadPerformer.removeUploadInfoRecord();
}
if (!responseInfo.isOK()) {
if (!switchRegionAndUploadIfNeededWithErrorResponse(responseInfo)) {
completeAction(responseInfo, response);
}
return;
}
AsyncRun.runInMain(new Runnable() {
@Override
public void run() {
option.progressHandler.progress(key, 1.0);
}
});
completeAction(responseInfo, response);
}
});
}
});
}
});
}
protected void uploadRestData(final UploadFileRestDataCompleteHandler completeHandler) {
performUploadRestData(completeHandler);
}
protected void performUploadRestData(final UploadFileRestDataCompleteHandler completeHandler) {
if (isAllUploaded()) {
completeHandler.complete();
return;
}
uploadNextDataCompleteHandler(new UploadFileDataCompleteHandler() {
@Override
public void complete(boolean stop, ResponseInfo responseInfo, JSONObject response) {
if (stop || (responseInfo != null && !responseInfo.isOK())) {
completeHandler.complete();
} else {
performUploadRestData(completeHandler);
}
}
});
}
protected void serverInit(final UploadFileCompleteHandler completeHandler) {
uploadPerformer.serverInit(new PartsUploadPerformer.PartsUploadPerformerCompleteHandler() {
@Override
public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics requestMetrics, JSONObject response) {
if (responseInfo != null && !responseInfo.isOK()) {
setErrorResponse(responseInfo, response);
}
addRegionRequestMetricsOfOneFlow(requestMetrics);
completeHandler.complete(responseInfo, response);
}
});
}
protected void uploadNextDataCompleteHandler(final UploadFileDataCompleteHandler completeHandler) {
uploadPerformer.uploadNextDataCompleteHandler(new PartsUploadPerformer.PartsUploadPerformerDataCompleteHandler() {
@Override
public void complete(boolean stop, ResponseInfo responseInfo, UploadRegionRequestMetrics requestMetrics, JSONObject response) {
if (responseInfo != null && !responseInfo.isOK()) {
setErrorResponse(responseInfo, response);
}
addRegionRequestMetricsOfOneFlow(requestMetrics);
completeHandler.complete(stop, responseInfo, response);
}
});
}
protected void completeUpload(final UploadFileCompleteHandler completeHandler) {
uploadPerformer.completeUpload(new PartsUploadPerformer.PartsUploadPerformerCompleteHandler() {
@Override
public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics requestMetrics, JSONObject response) {
if (responseInfo != null && !responseInfo.isOK()) {
setErrorResponse(responseInfo, response);
}
addRegionRequestMetricsOfOneFlow(requestMetrics);
completeHandler.complete(responseInfo, response);
}
});
}
@Override
protected void completeAction(ResponseInfo responseInfo, JSONObject response) {
reportBlock();
uploadPerformer.closeFile();
super.completeAction(responseInfo, response);
}
private boolean shouldRemoveUploadInfoRecord(ResponseInfo responseInfo) {
return responseInfo != null && (responseInfo.isOK() || responseInfo.statusCode == 612 || responseInfo.statusCode == 614 || responseInfo.statusCode == 701);
}
private void reportBlock() {
UploadRegionRequestMetrics metrics = getCurrentRegionRequestMetrics();
if (metrics == null) {
metrics = new UploadRegionRequestMetrics(null);
}
String currentZoneRegionId = null;
if (getCurrentRegion() != null && getCurrentRegion().getZoneInfo() != null && getCurrentRegion().getZoneInfo().regionId != null) {
currentZoneRegionId = getCurrentRegion().getZoneInfo().regionId;
}
String targetZoneRegionId = null;
if (getTargetRegion() != null && getTargetRegion().getZoneInfo() != null && getTargetRegion().getZoneInfo().regionId != null) {
targetZoneRegionId = getTargetRegion().getZoneInfo().regionId;
}
ReportItem item = new ReportItem();
item.setReport(ReportItem.LogTypeBlock, ReportItem.BlockKeyLogType);
item.setReport((Utils.currentTimestamp() / 1000), ReportItem.BlockKeyUpTime);
item.setReport(currentZoneRegionId, ReportItem.BlockKeyTargetRegionId);
item.setReport(targetZoneRegionId, ReportItem.BlockKeyCurrentRegionId);
item.setReport(metrics.totalElapsedTime(), ReportItem.BlockKeyTotalElapsedTime);
item.setReport(metrics.bytesSend(), ReportItem.BlockKeyBytesSent);
item.setReport(uploadPerformer.recoveredFrom, ReportItem.BlockKeyRecoveredFrom);
item.setReport(file.length(), ReportItem.BlockKeyFileSize);
item.setReport(Utils.getCurrentProcessID(), ReportItem.BlockKeyPid);
item.setReport(Utils.getCurrentThreadID(), ReportItem.BlockKeyTid);
item.setReport(1, ReportItem.BlockKeyUpApiVersion);
item.setReport(Utils.currentTimestamp(), ReportItem.BlockKeyClientTime);
UploadInfoReporter.getInstance().report(item, token.token);
}
protected interface UploadFileRestDataCompleteHandler {
void complete();
}
protected interface UploadFileCompleteHandler {
void complete(ResponseInfo responseInfo, JSONObject response);
}
protected interface UploadFileDataCompleteHandler {
void complete(boolean stop, ResponseInfo responseInfo, JSONObject response);
}
}
|
package cc.mallet.grmm.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.regex.Pattern;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import cc.mallet.grmm.types.*;
import gnu.trove.THashMap;
import bsh.Interpreter;
import bsh.EvalError;
/**
* $Id: ModelReader.java,v 1.1 2007/10/22 21:37:58 mccallum Exp $
*/
public class ModelReader {
private static THashMap allClasses;
static {
allClasses = new THashMap ();
// add new classes here
allClasses.put ("potts", PottsTableFactor.class);
allClasses.put ("unary", BoltzmannUnaryFactor.class);
allClasses.put ("binaryunary", BinaryUnaryFactor.class);
allClasses.put ("binarypair", BoltzmannPairFactor.class);
allClasses.put ("uniform", UniformFactor.class);
allClasses.put ("normal", UniNormalFactor.class);
allClasses.put ("beta", BetaFactor.class);
}
private THashMap name2var = new THashMap ();
public static Assignment readFromMatrix (VarSet vars, Reader in) throws IOException
{
Variable[] varr = vars.toVariableArray ();
Interpreter interpreter = new Interpreter ();
BufferedReader bIn = new BufferedReader (in);
Assignment assn = new Assignment ();
String line;
while ((line = bIn.readLine ()) != null) {
String[] fields = line.split ("\\s+");
Object[] vals = new Object [fields.length];
for (int i = 0; i < fields.length; i++) {
try {
vals[i] = interpreter.eval (fields[i]);
} catch (EvalError e) {
throw new RuntimeException ("Error reading line: "+line, e);
}
}
assn.addRow (varr, vals);
}
return assn;
}
public FactorGraph readModel (BufferedReader in) throws IOException
{
List factors = new ArrayList ();
String line;
while ((line = in.readLine ()) != null) {
try {
if (Pattern.matches ("^\\s*$", line)) { continue; }
String[] fields = line.split ("\\s+");
if (fields[0].equalsIgnoreCase ("VAR")) {
// a variable declaration
handleVariableDecl (fields);
} else {
// a factor line
Factor factor = factorFromLine (fields);
factors.add (factor);
}
} catch (Exception e) {
throw new RuntimeException ("Error reading line:\n"+line, e);
}
}
FactorGraph fg = new FactorGraph ();
for (Iterator it = factors.iterator (); it.hasNext ();) {
Factor factor = (Factor) it.next ();
fg.multiplyBy (factor);
}
return fg;
}
private void handleVariableDecl (String[] fields)
{
int colonIdx = findColon (fields);
if (fields.length != colonIdx + 2) throw new IllegalArgumentException ("Invalid syntax");
String numOutsString = fields[colonIdx+1];
int numOutcomes;
if (numOutsString.equalsIgnoreCase ("continuous")) {
numOutcomes = Variable.CONTINUOUS;
} else {
numOutcomes = Integer.parseInt (numOutsString);
}
for (int i = 0; i < colonIdx; i++) {
String name = fields[i];
Variable var = new Variable (numOutcomes);
var.setLabel (name);
name2var.put (name, var);
}
}
private int findColon (String[] fields)
{
for (int i = 0; i < fields.length; i++) {
if (fields[i].equals (":")) {
return i;
}
}
throw new IllegalArgumentException ("Invalid syntax.");
}
private Factor factorFromLine (String[] fields)
{
int idx = findTwiddle (fields);
return constructFactor (fields, idx);
}
private int findTwiddle (String[] fields)
{
for (int i = 0; i < fields.length; i++) {
if (fields[i].equals ("~")) {
return i;
}
}
return -1;
}
private Factor constructFactor (String[] fields, int idx)
{
Class factorClass = determineFactorClass (fields, idx);
Object[] args = determineFactorArgs (fields, idx);
Constructor factorCtor = findCtor (factorClass, args);
Factor factor;
try {
factor = (Factor) factorCtor.newInstance (args);
} catch (InstantiationException e) {
throw new RuntimeException (e);
} catch (IllegalAccessException e) {
throw new RuntimeException (e);
} catch (InvocationTargetException e) {
throw new RuntimeException (e);
}
return factor;
}
private Constructor findCtor (Class factorClass, Object[] args)
{
Class[] argClass = new Class[args.length];
for (int i = 0; i < args.length; i++) {
argClass[i] = args[i].getClass ();
// special case
if (argClass[i] == Double.class) { argClass[i] = double.class; }
}
try {
return factorClass.getDeclaredConstructor (argClass);
} catch (NoSuchMethodException e) {
StringBuffer buf = new StringBuffer("Invalid argments for factor "+factorClass+"\n");
buf.append ("Args were:\n");
for (int i = 0; i < args.length; i++) {
buf.append(args[i]);
buf.append(" ");
}
buf.append("\n");
for (int i = 0; i < args.length; i++) {
buf.append(args[i].getClass());
buf.append(" ");
}
buf.append("\n");
throw new RuntimeException (buf.toString());
}
}
private Class determineFactorClass (String[] fields, int twiddleIdx)
{
String factorName = fields [twiddleIdx + 1].toLowerCase ();
Class theClass = (Class) allClasses.get (factorName);
if (theClass != null) {
return theClass;
} else {
throw new RuntimeException ("Could not determine factor class from "+factorName);
}
}
private Object[] determineFactorArgs (String[] fields, int twiddleIdx)
{
List args = new ArrayList (fields.length);
for (int i = 0; i < twiddleIdx; i++) {
args.add (varFromName (fields[i], true));
}
for (int i = twiddleIdx+2; i < fields.length; i++) {
args.add (varFromName (fields[i], false));
}
return args.toArray ();
}
<<<<<<< /disk/scratch/umass/clone/mallet/src/cc/mallet/grmm/util/ModelReader.java
private static Pattern nbrRegex = Pattern.compile ("[+-]?\\d+(?:\\.\\d+)?(E[+-]\\d+)?");
=======
private static Pattern nbrRegex = Pattern.compile ("[+-]?\\d+(?:\\.\\d+)?");
>>>> /tmp/ModelReader.java~other.Tl9Fy2
private Object varFromName (String name, boolean preTwiddle)
{
if (nbrRegex.matcher(name).matches ()) {
return new Double (Double.parseDouble (name));
} else if (name2var.contains (name)) {
return name2var.get (name);
} else {
Variable var = (preTwiddle) ? new Variable (2) : new Variable (Variable.CONTINUOUS);
var.setLabel (name);
name2var.put (name, var);
return var;
}
}
}
|
package se.sics.mspsim.core;
public interface MSP430Constants {
public static final String VERSION = "0.85";
public static final int CLK_ACLK = 1;
public static final int CLK_SMCLK = 2;
// Instructions (full length)
public static final int RRC = 0x1000;
public static final int SWPB = 0x1080;
public static final int RRA = 0x1100;
public static final int SXT = 0x1180;
public static final int PUSH = 0x1200;
public static final int CALL = 0x1280;
public static final int RETI = 0x1300;
// Conditional Jumps [
public static final int JNE = 0x2000;
public static final int JEQ = 0x2400;
public static final int JNC = 0x2800;
public static final int JC = 0x2C00;
// Conditional Jumps & jumps...
public static final int JN = 0x3000;
public static final int JGE = 0x3400;
public static final int JL = 0x3800;
public static final int JMP = 0x3C00;
// Short ones...
public static final int MOV = 0x4;
public static final int ADD = 0x5;
public static final int ADDC = 0x6;
public static final int SUBC = 0x7;
public static final int SUB = 0x8;
public static final int CMP = 0x9;
public static final int DADD = 0xa;
public static final int BIT = 0xb;
public static final int BIC = 0xc;
public static final int BIS = 0xd;
public static final int XOR = 0xe;
public static final int AND = 0xf;
public static final String[] TWO_OPS = {
"-","-","-","-","MOV", "ADD", "ADDC", "SUBC", "SUB",
"CMP", "DADD", "BIT", "BIC", "BIS", "XOR", "AND"
};
public static final String[] REGISTER_NAMES = {
"PC", "SP", "SR", "CG1", "CG2"
};
public static final int PC = 0;
public static final int SP = 1;
public static final int SR = 2;
public static final int CG1 = 2;
public static final int CG2 = 3;
public static final int[][] CREG_VALUES = new int[][]{
{0, 0, 4, 8}, {0, 1, 2, 0xffff}
};
public static final int CARRY_B = 0;
public static final int ZERO_B = 1;
public static final int NEGATIVE_B = 2;
public static final int OVERFLOW_B = 8;
public static final int GIE_B = 3;
public static final int CARRY = 1;
public static final int ZERO = 2;
public static final int NEGATIVE = 4;
public static final int OVERFLOW = 1 << OVERFLOW_B;
public static final int GIE = 1 << GIE_B;
/* For the LPM management */
public static final int CPUOFF = 0x0010;
public static final int OSCOFF = 0x0020;
public static final int SCG0 = 0x0040;
public static final int SCG1 = 0x0080;
// #define C 0x0001
// #define Z 0x0002
// #define N 0x0004
// #define V 0x0100
// #define GIE 0x0008
// #define CPUOFF 0x0010
// #define OSCOFF 0x0020
// #define SCG0 0x0040
// #define SCG1 0x0080
public static final int AM_REG = 0;
public static final int AM_INDEX = 1;
public static final int AM_IND_REG = 2;
public static final int AM_IND_AUTOINC = 3;
public static final int CLKCAPTURE_NONE = 0;
public static final int CLKCAPTURE_UP = 1;
public static final int CLKCAPTURE_DWN = 2;
public static final int CLKCAPTURE_BOTH = 3;
public static final int DEBUGGING_LEVEL = 0;
}
|
package cellsociety_team08;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import javafx.scene.paint.Color;
public class ForagingAnts extends RuleSet{
private static int xPos;
private static int yPos;
private static Patch HOME_BASE; // = new Patch(xPos, yPos, false);
private List<String> orientationList = Arrays.asList("N", "NE", "E", "SE", "S", "SW", "W", "NW");
private String myOrientation;
private int antLimit = 10;
private int maxFoodPheromones = 10;
private int maxHomePheromones = 10;
private State[] myPossibleStates = new State[] {
new State("Home", 0, Color.BLUE, null), // index 0
new State("Ant", 1, Color.RED, null), // index 1
new State("Food", 2, Color.GREEN, null) // index 2
};
public ForagingAnts(String orientation, int x, int y) {
myOrientation = orientation;
xPos = x;
yPos = y;
HOME_BASE = new Patch(xPos, yPos, false);
}
public int getNumCells(Patch patch) {
int neighborCount = patch.numCells;
return neighborCount;
}
public int getNumNeighbors(List<Patch> neighborhood) {
int numNeighbors = 0;
for (Patch patch: neighborhood) {
numNeighbors += getNumCells(patch);
}
return numNeighbors;
}
public List<Patch> getBackNeighbors(Patch patch) {
List<Patch> backNeighbors = getNeighbors(patch);
List<Patch> forwardNeighbors = getForwardNeighbors(patch);
for (Patch p: backNeighbors) {
if (forwardNeighbors.contains(p)) backNeighbors.remove(p);
}
return backNeighbors;
}
public List<Patch> getForwardNeighbors(Patch patch) {
List<Patch> neighbors = getNeighbors(patch);
List<Patch> forwardNeighbors = new ArrayList<Patch>();
switch (myOrientation) {
case "N":
for (Patch p: neighbors) {
int row = p.myRow;
int col = p.myCol;
forwardNeighbors.add(myPatches[row + 1][col]);
forwardNeighbors.add(myPatches[row + 1][col + 1]);
forwardNeighbors.add(myPatches[row + 1][col - 1]);
}
case "NE":
for (Patch p: neighbors) {
int row = p.myRow;
int col = p.myCol;
forwardNeighbors.add(myPatches[row + 1][col + 1]);
forwardNeighbors.add(myPatches[row][col + 1]);
forwardNeighbors.add(myPatches[row + 1][col]);
}
case "E":
for (Patch p: neighbors) {
int row = p.myRow;
int col = p.myCol;
forwardNeighbors.add(myPatches[row][col + 1]);
forwardNeighbors.add(myPatches[row + 1][col + 1]);
forwardNeighbors.add(myPatches[row - 1][col + 1]);
}
case "SE":
for (Patch p: neighbors) {
int row = p.myRow;
int col = p.myCol;
forwardNeighbors.add(myPatches[row - 1][col + 1]);
forwardNeighbors.add(myPatches[row + 1][col]);
forwardNeighbors.add(myPatches[row - 1][col]);
}
case "S":
for (Patch p: neighbors) {
int row = p.myRow;
int col = p.myCol;
forwardNeighbors.add(myPatches[row - 1][col]);
forwardNeighbors.add(myPatches[row - 1][col + 1]);
forwardNeighbors.add(myPatches[row - 1][col - 1]);
}
case "SW":
for (Patch p: neighbors) {
int row = p.myRow;
int col = p.myCol;
forwardNeighbors.add(myPatches[row - 1][col - 1]);
forwardNeighbors.add(myPatches[row - 1][col]);
forwardNeighbors.add(myPatches[row][col - 1]);
}
case "W":
for (Patch p: neighbors) {
int row = p.myRow;
int col = p.myCol;
forwardNeighbors.add(myPatches[row][col - 1]);
forwardNeighbors.add(myPatches[row + 1][col - 1]);
forwardNeighbors.add(myPatches[row - 1][col - 1]);
}
case "NW":
for (Patch p: neighbors) {
int row = p.myRow;
int col = p.myCol;
forwardNeighbors.add(myPatches[row][col - 1]);
forwardNeighbors.add(myPatches[row + 1][col]);
forwardNeighbors.add(myPatches[row + 1][col - 1]);
}
default: break;
}
forwardNeighbors = getViableForwardNeighbors(forwardNeighbors);
return forwardNeighbors;
}
public List<Patch> getViableForwardNeighbors(List<Patch> forwardNeighbors) {
for (Patch patch: forwardNeighbors) {
if (getNumCells(patch) > antLimit) {
forwardNeighbors.remove(patch);
}
}
return forwardNeighbors;
}
@Override
public Patch getNext(Patch patch) {
// TODO Auto-generated method stub
List<Patch> forwardNeighbors = getForwardNeighbors(patch);
List<Patch> backNeighbors = getBackNeighbors(patch);
Patch nextPatch = patch;
double highPheromones = 0;
if (patch.myCell.getState() == myPossibleStates[0]) { //home base doesn't do anything except depreciate pheromone values
patch.foodPheromoneLevel
patch.homePheromoneLevel
return patch;
}
if (patch.myCell.getState() == myPossibleStates[2]) { //neither does food
patch.foodPheromoneLevel
patch.homePheromoneLevel
return patch;
}
if (!patch.myCell.hasFood ) {
//patch.myCell.foodDesire = 10;
if (forwardNeighbors.size() > 0) {
for (Patch p: forwardNeighbors) {
if (p.foodPheromoneLevel > highPheromones) {
highPheromones = p.foodPheromoneLevel;
nextPatch = p;
}
}
if (nextPatch == patch) { //if we didn't find a new patch
Random rand = new Random();
nextPatch = forwardNeighbors.get(rand.nextInt(forwardNeighbors.size()));
}
}
else {
for (Patch p: backNeighbors) {
if (p.foodPheromoneLevel > highPheromones) {
highPheromones = p.foodPheromoneLevel;
nextPatch = p;
}
}
if (nextPatch == patch) { //if we didn't find a new patch
Random rand = new Random();
nextPatch = backNeighbors.get(rand.nextInt(backNeighbors.size()));
}
}
patch.homePheromoneLevel = 10;
}
else { // cell has food
if (forwardNeighbors.size() > 0) {
for (Patch p: forwardNeighbors) {
if (p.homePheromoneLevel > highPheromones) {
highPheromones = p.homePheromoneLevel;
nextPatch = p;
}
}
if (nextPatch == patch) { //if we didn't find a new patch
Random rand = new Random();
nextPatch = forwardNeighbors.get(rand.nextInt(forwardNeighbors.size()));
}
}
for (Patch p: backNeighbors) {
if (p.homePheromoneLevel > highPheromones) {
highPheromones = p.homePheromoneLevel;
nextPatch = p;
}
}
if (nextPatch == patch) { //if we didn't find a new patch
Random rand = new Random();
nextPatch = backNeighbors.get(rand.nextInt(backNeighbors.size()));
}
patch.foodPheromoneLevel = 10;
}
nextPatch.myCell = patch.myCell;
if (nextPatch.myCell.getState().myIndex == 2) { //pick up food
nextPatch.myCell.hasFood = true;
}
if (nextPatch.myRow == HOME_BASE.myRow && nextPatch.myCol == HOME_BASE.myCol) { //drop food off at home base
nextPatch.myCell.hasFood = false;
}
patch.clear();
return nextPatch;
}
}
|
package com.techern.minecraft.igneousextras.blocks;
import com.techern.minecraft.IgneousExtrasMod;
import com.techern.minecraft.igneousextras.blocks.redstone.BlockBasicPressurePlate;
import com.techern.minecraft.igneousextras.blocks.stairs.BaseBlockStairs;
import com.techern.minecraft.igneousextras.blocks.stairs.ColoredBlockStairs;
import com.techern.minecraft.igneousextras.items.ItemColoredBlock;
import net.minecraft.block.*;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.EnumDyeColor;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
/**
* A class that contains every {@link net.minecraft.block.Block} added by the {@link com.techern.minecraft.IgneousExtrasMod}
*
* @since 0.0.1
*/
public class IABlocks {
/**
* The {@link CreativeTabs} for dyed blocks
*
* @since 0.0.1
*/
public static CreativeTabs DYED_BLOCKS_TAB = new CreativeTabs("dyed_blocks") {
@Override
public Item getTabIconItem() {
return Item.getItemFromBlock(DYED_COBBLESTONE);
}
};
/**
* The {@link CreativeTabs} for igneous stairs
*
* @since 0.0.1
*/
public static CreativeTabs STAIRS_TAB = new CreativeTabs("igneous_stairs") {
@Override
public Item getTabIconItem() {
return Item.getItemFromBlock(GRANITE_STAIRS);
}
};
/**
* The {@link CreativeTabs} for dyed igneous stirs
*
* @since 0.0.1
*/
public static CreativeTabs DYED_STAIRS_TAB = new CreativeTabs("dyed_igneous_stairs") {
@Override
public Item getTabIconItem() {
return Item.getItemFromBlock(WHITE_DYED_COBBLESTONE_STAIRS);
}
};
/**
* A {@link BlockColored} defining a {@link BlockDyedCobblestone}
*
* @since 0.0.1
*/
public static BlockColored DYED_COBBLESTONE = new BlockDyedCobblestone();
/**
* A {@link BlockColored} defining a mossy cobblestone {@link BlockDyedStone}
*
* @since 0.0.1
*/
public static BlockColored DYED_MOSSY_COBBLESTONE = new BlockDyedStone("dyed_mossy_cobblestone");
/**
* A {@link BlockColored} defining a {@link BlockDyedStone}
*
* @since 0.0.1
*/
public static BlockColored DYED_STONE = new BlockDyedStone("dyed_stone");
/**
* A {@link BlockColored} defining a granite {@link BlockDyedStone}
*
* @since 0.0.1
*/
public static BlockColored DYED_GRANITE = new BlockDyedStone("dyed_granite");
/**
* A {@link BlockColored} defining a smooth granite {@link BlockDyedStone}
*
* @since 0.0.1
*/
public static BlockColored DYED_SMOOTH_GRANITE = new BlockDyedStone("dyed_smooth_granite");
/**
* A {@link BlockColored} defining a diorite {@link BlockDyedStone}
*
* @since 0.0.1
*/
public static BlockColored DYED_DIORITE = new BlockDyedStone("dyed_diorite");
/**
* A {@link BlockColored} defining a smooth diorite {@link BlockDyedStone}
*
* @since 0.0.1
*/
public static BlockColored DYED_SMOOTH_DIORITE = new BlockDyedStone("dyed_smooth_diorite");
/**
* A {@link BlockColored} defining an andesite {@link BlockDyedStone}
*
* @since 0.0.1
*/
public static BlockColored DYED_ANDESITE = new BlockDyedStone("dyed_andesite");
/**
* A {@link BlockColored} defining a smooth andesite {@link BlockDyedStone}
*
* @since 0.0.1
*/
public static BlockColored DYED_SMOOTH_ANDESITE = new BlockDyedStone("dyed_smooth_andesite");
/**
* A {@link BlockStairs} defining stone stairs
*
* @since 0.0.1
*/
public static BlockStairs STONE_STAIRS = new BaseBlockStairs(Blocks.stone.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.STONE), "stone_stairs");
/**
* A {@link BlockStairs} defining mossy cobblestonje stairs
*
* @since 0.0.1
*/
public static BlockStairs MOSSY_COBBLESTONE_STAIRS = new BaseBlockStairs(Blocks.mossy_cobblestone.getDefaultState(), "mossy_cobblestone_stairs");
/**
* A {@link BlockStairs} defining granite stairs
*
* @since 0.0.1
*/
public static BlockStairs GRANITE_STAIRS = new BaseBlockStairs(Blocks.stone.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.GRANITE), "granite_stairs");
/**
* A {@link BlockStairs} defining polished granite stairs
*
* @since 0.0.1
*/
public static BlockStairs POLISHED_GRANITE_STAIRS = new BaseBlockStairs(Blocks.stone.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.GRANITE_SMOOTH), "polished_granite_stairs");
/**
* A {@link BlockStairs} defining diorite stairs
*
* @since 0.0.1
*/
public static BlockStairs DIORITE_STAIRS = new BaseBlockStairs(Blocks.stone.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.DIORITE), "diorite_stairs");
/**
* A {@link BlockStairs} defining polished diorite stairs
*
* @since 0.0.1
*/
public static BlockStairs POLISHED_DIORITE_STAIRS = new BaseBlockStairs(Blocks.stone.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.DIORITE_SMOOTH), "polished_diorite_stairs");
/**
* A {@link BlockStairs} defining andesite stairs
*
* @since 0.0.1
*/
public static BlockStairs ANDESITE_STAIRS = new BaseBlockStairs(Blocks.stone.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.ANDESITE), "andesite_stairs");
/**
* A {@link BlockStairs} defining polished andesite stairs
*
* @since 0.0.1
*/
public static BlockStairs POLISHED_ANDESITE_STAIRS = new BaseBlockStairs(Blocks.stone.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.ANDESITE_SMOOTH), "polished_andesite_stairs");
/**
* Lime coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIME_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.LIME), "lime_dyed_cobblestone_stairs");
/**
* Black coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLACK_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.BLACK), "black_dyed_cobblestone_stairs");
/**
* Blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLUE_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.BLUE), "blue_dyed_cobblestone_stairs");
/**
* Brown coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BROWN_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.BROWN), "brown_dyed_cobblestone_stairs");
/**
* Cyan coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs CYAN_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.CYAN), "cyan_dyed_cobblestone_stairs");
/**
* Gray coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GRAY_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.GRAY), "gray_dyed_cobblestone_stairs");
/**
* Green coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GREEN_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.GREEN), "green_dyed_cobblestone_stairs");
/**
* Light blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIGHT_BLUE_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.LIGHT_BLUE), "light_blue_dyed_cobblestone_stairs");
/**
* Magenta coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs MAGENTA_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.MAGENTA), "magenta_dyed_cobblestone_stairs");
/**
* Orange coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs ORANGE_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.ORANGE), "orange_dyed_cobblestone_stairs");
/**
* Pink coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PINK_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.PINK), "pink_dyed_cobblestone_stairs");
/**
* Purple coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PURPLE_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.PURPLE), "purple_dyed_cobblestone_stairs");
/**
* Red coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs RED_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.RED), "red_dyed_cobblestone_stairs");
/**
* Silver coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs SILVER_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.SILVER), "silver_dyed_cobblestone_stairs");
/**
* White coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs WHITE_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.WHITE), "white_dyed_cobblestone_stairs");
/**
* Yellow coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs YELLOW_DYED_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.YELLOW), "yellow_dyed_cobblestone_stairs");
/**
* Lime coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIME_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.LIME), "lime_dyed_mossy_cobblestone_stairs");
/**
* Black coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLACK_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.BLACK), "black_dyed_mossy_cobblestone_stairs");
/**
* Blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLUE_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.BLUE), "blue_dyed_mossy_cobblestone_stairs");
/**
* Brown coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BROWN_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.BROWN), "brown_dyed_mossy_cobblestone_stairs");
/**
* Cyan coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs CYAN_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.CYAN), "cyan_dyed_mossy_cobblestone_stairs");
/**
* Gray coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GRAY_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.GRAY), "gray_dyed_mossy_cobblestone_stairs");
/**
* Green coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GREEN_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.GREEN), "green_dyed_mossy_cobblestone_stairs");
/**
* Light blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIGHT_BLUE_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.LIGHT_BLUE), "light_blue_dyed_mossy_cobblestone_stairs");
/**
* Magenta coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs MAGENTA_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.MAGENTA), "magenta_dyed_mossy_cobblestone_stairs");
/**
* Orange coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs ORANGE_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.ORANGE), "orange_dyed_mossy_cobblestone_stairs");
/**
* Pink coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PINK_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.PINK), "pink_dyed_mossy_cobblestone_stairs");
/**
* Purple coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PURPLE_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.PURPLE), "purple_dyed_mossy_cobblestone_stairs");
/**
* Red coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs RED_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.RED), "red_dyed_mossy_cobblestone_stairs");
/**
* Silver coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs SILVER_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.SILVER), "silver_dyed_mossy_cobblestone_stairs");
/**
* White coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs WHITE_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.WHITE), "white_dyed_mossy_cobblestone_stairs");
/**
* Yellow coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs YELLOW_DYED_MOSSY_COBBLESTONE_STAIRS = new ColoredBlockStairs(DYED_MOSSY_COBBLESTONE.getDefaultState().withProperty(BlockDyedCobblestone.COLOR, EnumDyeColor.YELLOW), "yellow_dyed_mossy_cobblestone_stairs");
/**
* Lime coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIME_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.LIME), "lime_dyed_stone_stairs");
/**
* Black coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLACK_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BLACK), "black_dyed_stone_stairs");
/**
* Blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLUE_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BLUE), "blue_dyed_stone_stairs");
/**
* Brown coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BROWN_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BROWN), "brown_dyed_stone_stairs");
/**
* Cyan coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs CYAN_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.CYAN), "cyan_dyed_stone_stairs");
/**
* Gray coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GRAY_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.GRAY), "gray_dyed_stone_stairs");
/**
* Green coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GREEN_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.GREEN), "green_dyed_stone_stairs");
/**
* Light blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIGHT_BLUE_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.LIGHT_BLUE), "light_blue_dyed_stone_stairs");
/**
* Magenta coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs MAGENTA_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.MAGENTA), "magenta_dyed_stone_stairs");
/**
* Orange coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs ORANGE_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.ORANGE), "orange_dyed_stone_stairs");
/**
* Pink coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PINK_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.PINK), "pink_dyed_stone_stairs");
/**
* Purple coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PURPLE_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.PURPLE), "purple_dyed_stone_stairs");
/**
* Red coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs RED_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.RED), "red_dyed_stone_stairs");
/**
* Silver coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs SILVER_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.SILVER), "silver_dyed_stone_stairs");
/**
* White coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs WHITE_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.WHITE), "white_dyed_stone_stairs");
/**
* Yellow coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs YELLOW_DYED_STONE_STAIRS = new ColoredBlockStairs(DYED_STONE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.YELLOW), "yellow_dyed_stone_stairs");
/**
* Lime coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIME_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.LIME), "lime_dyed_andesite_stairs");
/**
* Black coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLACK_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BLACK), "black_dyed_andesite_stairs");
/**
* Blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLUE_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BLUE), "blue_dyed_andesite_stairs");
/**
* Brown coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BROWN_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BROWN), "brown_dyed_andesite_stairs");
/**
* Cyan coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs CYAN_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.CYAN), "cyan_dyed_andesite_stairs");
/**
* Gray coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GRAY_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.GRAY), "gray_dyed_andesite_stairs");
/**
* Green coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GREEN_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.GREEN), "green_dyed_andesite_stairs");
/**
* Light blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIGHT_BLUE_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.LIGHT_BLUE), "light_blue_dyed_andesite_stairs");
/**
* Magenta coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs MAGENTA_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.MAGENTA), "magenta_dyed_andesite_stairs");
/**
* Orange coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs ORANGE_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.ORANGE), "orange_dyed_andesite_stairs");
/**
* Pink coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PINK_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.PINK), "pink_dyed_andesite_stairs");
/**
* Purple coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PURPLE_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.PURPLE), "purple_dyed_andesite_stairs");
/**
* Red coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs RED_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.RED), "red_dyed_andesite_stairs");
/**
* Silver coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs SILVER_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.SILVER), "silver_dyed_andesite_stairs");
/**
* White coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs WHITE_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.WHITE), "white_dyed_andesite_stairs");
/**
* Yellow coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs YELLOW_DYED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.YELLOW), "yellow_dyed_andesite_stairs");
/**
* Lime coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIME_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.LIME), "lime_dyed_diorite_stairs");
/**
* Black coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLACK_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BLACK), "black_dyed_diorite_stairs");
/**
* Blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLUE_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BLUE), "blue_dyed_diorite_stairs");
/**
* Brown coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BROWN_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BROWN), "brown_dyed_diorite_stairs");
/**
* Cyan coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs CYAN_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.CYAN), "cyan_dyed_diorite_stairs");
/**
* Gray coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GRAY_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.GRAY), "gray_dyed_diorite_stairs");
/**
* Green coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GREEN_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.GREEN), "green_dyed_diorite_stairs");
/**
* Light blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIGHT_BLUE_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.LIGHT_BLUE), "light_blue_dyed_diorite_stairs");
/**
* Magenta coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs MAGENTA_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.MAGENTA), "magenta_dyed_diorite_stairs");
/**
* Orange coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs ORANGE_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.ORANGE), "orange_dyed_diorite_stairs");
/**
* Pink coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PINK_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.PINK), "pink_dyed_diorite_stairs");
/**
* Purple coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PURPLE_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.PURPLE), "purple_dyed_diorite_stairs");
/**
* Red coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs RED_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.RED), "red_dyed_diorite_stairs");
/**
* Silver coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs SILVER_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.SILVER), "silver_dyed_diorite_stairs");
/**
* White coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs WHITE_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.WHITE), "white_dyed_diorite_stairs");
/**
* Yellow coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs YELLOW_DYED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.YELLOW), "yellow_dyed_diorite_stairs");
/**
* Lime coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIME_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.LIME), "lime_dyed_granite_stairs");
/**
* Black coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLACK_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BLACK), "black_dyed_granite_stairs");
/**
* Blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLUE_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BLUE), "blue_dyed_granite_stairs");
/**
* Brown coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BROWN_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BROWN), "brown_dyed_granite_stairs");
/**
* Cyan coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs CYAN_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.CYAN), "cyan_dyed_granite_stairs");
/**
* Gray coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GRAY_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.GRAY), "gray_dyed_granite_stairs");
/**
* Green coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GREEN_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.GREEN), "green_dyed_granite_stairs");
/**
* Light blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIGHT_BLUE_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.LIGHT_BLUE), "light_blue_dyed_granite_stairs");
/**
* Magenta coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs MAGENTA_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.MAGENTA), "magenta_dyed_granite_stairs");
/**
* Orange coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs ORANGE_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.ORANGE), "orange_dyed_granite_stairs");
/**
* Pink coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PINK_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.PINK), "pink_dyed_granite_stairs");
/**
* Purple coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PURPLE_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.PURPLE), "purple_dyed_granite_stairs");
/**
* Red coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs RED_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.RED), "red_dyed_granite_stairs");
/**
* Silver coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs SILVER_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.SILVER), "silver_dyed_granite_stairs");
/**
* White coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs WHITE_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.WHITE), "white_dyed_granite_stairs");
/**
* Yellow coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs YELLOW_DYED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.YELLOW), "yellow_dyed_granite_stairs");
/**
* Lime coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIME_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.LIME), "lime_dyed_polished_andesite_stairs");
/**
* Black coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLACK_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BLACK), "black_dyed_polished_andesite_stairs");
/**
* Blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLUE_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BLUE), "blue_dyed_polished_andesite_stairs");
/**
* Brown coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BROWN_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BROWN), "brown_dyed_polished_andesite_stairs");
/**
* Cyan coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs CYAN_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.CYAN), "cyan_dyed_polished_andesite_stairs");
/**
* Gray coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GRAY_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.GRAY), "gray_dyed_polished_andesite_stairs");
/**
* Green coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GREEN_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.GREEN), "green_dyed_polished_andesite_stairs");
/**
* Light blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIGHT_BLUE_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.LIGHT_BLUE), "light_blue_dyed_polished_andesite_stairs");
/**
* Magenta coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs MAGENTA_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.MAGENTA), "magenta_dyed_polished_andesite_stairs");
/**
* Orange coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs ORANGE_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.ORANGE), "orange_dyed_polished_andesite_stairs");
/**
* Pink coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PINK_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.PINK), "pink_dyed_polished_andesite_stairs");
/**
* Purple coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PURPLE_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.PURPLE), "purple_dyed_polished_andesite_stairs");
/**
* Red coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs RED_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.RED), "red_dyed_polished_andesite_stairs");
/**
* Silver coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs SILVER_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.SILVER), "silver_dyed_polished_andesite_stairs");
/**
* White coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs WHITE_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.WHITE), "white_dyed_polished_andesite_stairs");
/**
* Yellow coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs YELLOW_DYED_POLISHED_ANDESITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_ANDESITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.YELLOW), "yellow_dyed_polished_andesite_stairs");
/**
* Lime coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIME_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.LIME), "lime_dyed_polished_diorite_stairs");
/**
* Black coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLACK_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BLACK), "black_dyed_polished_diorite_stairs");
/**
* Blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLUE_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BLUE), "blue_dyed_polished_diorite_stairs");
/**
* Brown coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BROWN_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BROWN), "brown_dyed_polished_diorite_stairs");
/**
* Cyan coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs CYAN_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.CYAN), "cyan_dyed_polished_diorite_stairs");
/**
* Gray coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GRAY_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.GRAY), "gray_dyed_polished_diorite_stairs");
/**
* Green coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GREEN_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.GREEN), "green_dyed_polished_diorite_stairs");
/**
* Light blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIGHT_BLUE_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.LIGHT_BLUE), "light_blue_dyed_polished_diorite_stairs");
/**
* Magenta coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs MAGENTA_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.MAGENTA), "magenta_dyed_polished_diorite_stairs");
/**
* Orange coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs ORANGE_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.ORANGE), "orange_dyed_polished_diorite_stairs");
/**
* Pink coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PINK_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.PINK), "pink_dyed_polished_diorite_stairs");
/**
* Purple coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PURPLE_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.PURPLE), "purple_dyed_polished_diorite_stairs");
/**
* Red coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs RED_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.RED), "red_dyed_polished_diorite_stairs");
/**
* Silver coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs SILVER_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.SILVER), "silver_dyed_polished_diorite_stairs");
/**
* White coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs WHITE_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.WHITE), "white_dyed_polished_diorite_stairs");
/**
* Yellow coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs YELLOW_DYED_POLISHED_DIORITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_DIORITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.YELLOW), "yellow_dyed_polished_diorite_stairs");
/**
* Lime coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIME_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.LIME), "lime_dyed_polished_granite_stairs");
/**
* Black coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLACK_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BLACK), "black_dyed_polished_granite_stairs");
/**
* Blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BLUE_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BLUE), "blue_dyed_polished_granite_stairs");
/**
* Brown coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs BROWN_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.BROWN), "brown_dyed_polished_granite_stairs");
/**
* Cyan coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs CYAN_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.CYAN), "cyan_dyed_polished_granite_stairs");
/**
* Gray coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GRAY_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.GRAY), "gray_dyed_polished_granite_stairs");
/**
* Green coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs GREEN_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.GREEN), "green_dyed_polished_granite_stairs");
/**
* Light blue coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs LIGHT_BLUE_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.LIGHT_BLUE), "light_blue_dyed_polished_granite_stairs");
/**
* Magenta coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs MAGENTA_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.MAGENTA), "magenta_dyed_polished_granite_stairs");
/**
* Orange coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs ORANGE_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.ORANGE), "orange_dyed_polished_granite_stairs");
/**
* Pink coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PINK_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.PINK), "pink_dyed_polished_granite_stairs");
/**
* Purple coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs PURPLE_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.PURPLE), "purple_dyed_polished_granite_stairs");
/**
* Red coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs RED_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.RED), "red_dyed_polished_granite_stairs");
/**
* Silver coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs SILVER_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.SILVER), "silver_dyed_polished_granite_stairs");
/**
* White coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs WHITE_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.WHITE), "white_dyed_polished_granite_stairs");
/**
* Yellow coloured {@link BlockStairs}
*
* @since 0.0.1
*/
public static BlockStairs YELLOW_DYED_POLISHED_GRANITE_STAIRS = new ColoredBlockStairs(DYED_SMOOTH_GRANITE.getDefaultState().withProperty(BlockDyedStone.COLOR, EnumDyeColor.YELLOW), "yellow_dyed_polished_granite_stairs");
/**
* A granite {@link BlockBasicPressurePlate}
*
* @since 0.0.2
*/
public static Block GRANITE_PRESSURE_PLATE = new BlockBasicPressurePlate(Material.rock, BlockPressurePlate.Sensitivity.EVERYTHING).setUnlocalizedName("granite_pressure_plate");
/**
* A polished granite {@link BlockBasicPressurePlate}
*
* @since 0.0.2
*/
public static Block POLISHED_GRANITE_PRESSURE_PLATE = new BlockBasicPressurePlate(Material.rock, BlockPressurePlate.Sensitivity.EVERYTHING).setUnlocalizedName("polished_granite_pressure_plate");
/**
* A diorite {@link BlockBasicPressurePlate}
*
* @since 0.0.2
*/
public static Block DIORITE_PRESSURE_PLATE = new BlockBasicPressurePlate(Material.rock, BlockPressurePlate.Sensitivity.EVERYTHING).setUnlocalizedName("diorite_pressure_plate");
/**
* A polished diorite {@link BlockBasicPressurePlate}
*
* @since 0.0.2
*/
public static Block POLISHED_DIORITE_PRESSURE_PLATE = new BlockBasicPressurePlate(Material.rock, BlockPressurePlate.Sensitivity.EVERYTHING).setUnlocalizedName("polished_diorite_pressure_plate");
/**
* A andesite {@link BlockBasicPressurePlate}
*
* @since 0.0.2
*/
public static Block ANDESITE_PRESSURE_PLATE = new BlockBasicPressurePlate(Material.rock, BlockPressurePlate.Sensitivity.EVERYTHING).setUnlocalizedName("andesite_pressure_plate");
/**
* A polished andesite {@link BlockBasicPressurePlate}
*
* @since 0.0.2
*/
public static Block POLISHED_ANDESITE_PRESSURE_PLATE = new BlockBasicPressurePlate(Material.rock, BlockPressurePlate.Sensitivity.EVERYTHING).setUnlocalizedName("polished_andesite_pressure_plate");
/**
* A cobblestone {@link BlockBasicPressurePlate}
*
* @since 0.0.2
*/
public static Block COBBLESTONE_PRESSURE_PLATE = new BlockBasicPressurePlate(Material.rock, BlockPressurePlate.Sensitivity.EVERYTHING).setUnlocalizedName("cobblestone_pressure_plate");
/**
* A mossy cobblestone {@link BlockBasicPressurePlate}
*
* @since 0.0.2
*/
public static Block MOSSY_COBBLESTONE_PRESSURE_PLATE = new BlockBasicPressurePlate(Material.rock, BlockPressurePlate.Sensitivity.EVERYTHING).setUnlocalizedName("mossy_cobblestone_pressure_plate");
/**
* A stone brick {@link BlockBasicPressurePlate}
*
* @since 0.0.2
*/
public static Block STONE_BRICK_PRESSURE_PLATE = new BlockBasicPressurePlate(Material.rock, BlockPressurePlate.Sensitivity.EVERYTHING).setUnlocalizedName("stone_brick_pressure_plate");
/**
* A cracked stone brick {@link BlockBasicPressurePlate}
*
* @since 0.0.2
*/
public static Block CRACKED_STONE_BRICK_PRESSURE_PLATE = new BlockBasicPressurePlate(Material.rock, BlockPressurePlate.Sensitivity.EVERYTHING).setUnlocalizedName("cracked_stone_brick_pressure_plate");
/**
* A chiseled stone brick {@link BlockBasicPressurePlate}
*
* @since 0.0.2
*/
public static Block CHISELED_STONE_BRICK_PRESSURE_PLATE = new BlockBasicPressurePlate(Material.rock, BlockPressurePlate.Sensitivity.EVERYTHING).setUnlocalizedName("chiseled_stone_brick_pressure_plate");
/**
* A mossy stone brick {@link BlockBasicPressurePlate}
*
* @since 0.0.2
*/
public static Block MOSSY_STONE_BRICK_PRESSURE_PLATE = new BlockBasicPressurePlate(Material.rock, BlockPressurePlate.Sensitivity.EVERYTHING).setUnlocalizedName("mossy_stone_brick_pressure_plate");
/**
* Registers the {@link net.minecraft.block.Block}s added by the {@link IgneousExtrasMod}
*
* @since 0.0.1
*/
@SuppressWarnings("deprecation")
public static void registerBlocks() {
//First, we'll register dyed blocks
if (IgneousExtrasMod.CONFIGURATION.get("ADDITIONAL_BLOCKS", "DYED_STONE_BLOCKS", true, "Enable the use of dyed stone blocks").getBoolean()) {
GameRegistry.registerBlock(DYED_COBBLESTONE, ItemColoredBlock.class, "dyed_cobblestone");
GameRegistry.registerBlock(DYED_MOSSY_COBBLESTONE, ItemColoredBlock.class, "dyed_mossy_cobblestone");
GameRegistry.registerBlock(DYED_STONE, ItemColoredBlock.class, "dyed_stone");
GameRegistry.registerBlock(DYED_GRANITE, ItemColoredBlock.class, "dyed_granite");
GameRegistry.registerBlock(DYED_SMOOTH_GRANITE, ItemColoredBlock.class, "dyed_smooth_granite");
GameRegistry.registerBlock(DYED_DIORITE, ItemColoredBlock.class, "dyed_diorite");
GameRegistry.registerBlock(DYED_SMOOTH_DIORITE, ItemColoredBlock.class, "dyed_smooth_diorite");
GameRegistry.registerBlock(DYED_ANDESITE, ItemColoredBlock.class, "dyed_andesite");
GameRegistry.registerBlock(DYED_SMOOTH_ANDESITE, ItemColoredBlock.class, "dyed_smooth_andesite");
}
if (IgneousExtrasMod.CONFIGURATION.get("ADDITIONAL_BLOCKS", "STAIRS", true, "Enable the use of additional stair blocks").getBoolean()) {
GameRegistry.registerBlock(STONE_STAIRS, "stone_stairs");
GameRegistry.registerBlock(MOSSY_COBBLESTONE_STAIRS, "mossy_cobblestone_stairs");
GameRegistry.registerBlock(GRANITE_STAIRS, "granite_stairs");
GameRegistry.registerBlock(POLISHED_GRANITE_STAIRS, "polished_granite_stairs");
GameRegistry.registerBlock(DIORITE_STAIRS, "diorite_stairs");
GameRegistry.registerBlock(POLISHED_DIORITE_STAIRS, "polished_diorite_stairs");
GameRegistry.registerBlock(ANDESITE_STAIRS, "andesite_stairs");
GameRegistry.registerBlock(POLISHED_ANDESITE_STAIRS, "polished_andesite_stairs");
//Okay, dyed blocks now!
if (IgneousExtrasMod.CONFIGURATION.get("ADDITIONAL_BLOCKS", "DYED_STONE_BLOCKS", true, "Enable the use of dyed stone blocks").getBoolean()) {
GameRegistry.registerBlock(WHITE_DYED_COBBLESTONE_STAIRS, "white_dyed_cobblestone_stairs");
GameRegistry.registerBlock(ORANGE_DYED_COBBLESTONE_STAIRS, "orange_dyed_cobblestone_stairs");
GameRegistry.registerBlock(MAGENTA_DYED_COBBLESTONE_STAIRS, "magenta_dyed_cobblestone_stairs");
GameRegistry.registerBlock(LIGHT_BLUE_DYED_COBBLESTONE_STAIRS, "light_blue_dyed_cobblestone_stairs");
GameRegistry.registerBlock(YELLOW_DYED_COBBLESTONE_STAIRS, "yellow_dyed_cobblestone_stairs");
GameRegistry.registerBlock(LIME_DYED_COBBLESTONE_STAIRS, "lime_dyed_cobblestone_stairs");
GameRegistry.registerBlock(PINK_DYED_COBBLESTONE_STAIRS, "pink_dyed_cobblestone_stairs");
GameRegistry.registerBlock(GRAY_DYED_COBBLESTONE_STAIRS, "gray_dyed_cobblestone_stairs");
GameRegistry.registerBlock(SILVER_DYED_COBBLESTONE_STAIRS, "silver_dyed_cobblestone_stairs");
GameRegistry.registerBlock(CYAN_DYED_COBBLESTONE_STAIRS, "cyan_dyed_cobblestone_stairs");
GameRegistry.registerBlock(PURPLE_DYED_COBBLESTONE_STAIRS, "purple_dyed_cobblestone_stairs");
GameRegistry.registerBlock(BLUE_DYED_COBBLESTONE_STAIRS, "blue_dyed_cobblestone_stairs");
GameRegistry.registerBlock(BROWN_DYED_COBBLESTONE_STAIRS, "brown_dyed_cobblestone_stairs");
GameRegistry.registerBlock(GREEN_DYED_COBBLESTONE_STAIRS, "green_dyed_cobblestone_stairs");
GameRegistry.registerBlock(RED_DYED_COBBLESTONE_STAIRS, "red_dyed_cobblestone_stairs");
GameRegistry.registerBlock(BLACK_DYED_COBBLESTONE_STAIRS, "black_dyed_cobblestone_stairs");
GameRegistry.registerBlock(WHITE_DYED_MOSSY_COBBLESTONE_STAIRS, "white_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(ORANGE_DYED_MOSSY_COBBLESTONE_STAIRS, "orange_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(MAGENTA_DYED_MOSSY_COBBLESTONE_STAIRS, "magenta_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(LIGHT_BLUE_DYED_MOSSY_COBBLESTONE_STAIRS, "light_blue_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(YELLOW_DYED_MOSSY_COBBLESTONE_STAIRS, "yellow_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(LIME_DYED_MOSSY_COBBLESTONE_STAIRS, "lime_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(PINK_DYED_MOSSY_COBBLESTONE_STAIRS, "pink_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(GRAY_DYED_MOSSY_COBBLESTONE_STAIRS, "gray_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(SILVER_DYED_MOSSY_COBBLESTONE_STAIRS, "silver_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(CYAN_DYED_MOSSY_COBBLESTONE_STAIRS, "cyan_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(PURPLE_DYED_MOSSY_COBBLESTONE_STAIRS, "purple_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(BLUE_DYED_MOSSY_COBBLESTONE_STAIRS, "blue_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(BROWN_DYED_MOSSY_COBBLESTONE_STAIRS, "brown_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(GREEN_DYED_MOSSY_COBBLESTONE_STAIRS, "green_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(RED_DYED_MOSSY_COBBLESTONE_STAIRS, "red_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(BLACK_DYED_MOSSY_COBBLESTONE_STAIRS, "black_dyed_mossy_cobblestone_stairs");
GameRegistry.registerBlock(WHITE_DYED_STONE_STAIRS, "white_dyed_stone_stairs");
GameRegistry.registerBlock(ORANGE_DYED_STONE_STAIRS, "orange_dyed_stone_stairs");
GameRegistry.registerBlock(MAGENTA_DYED_STONE_STAIRS, "magenta_dyed_stone_stairs");
GameRegistry.registerBlock(LIGHT_BLUE_DYED_STONE_STAIRS, "light_blue_dyed_stone_stairs");
GameRegistry.registerBlock(YELLOW_DYED_STONE_STAIRS, "yellow_dyed_stone_stairs");
GameRegistry.registerBlock(LIME_DYED_STONE_STAIRS, "lime_dyed_stone_stairs");
GameRegistry.registerBlock(PINK_DYED_STONE_STAIRS, "pink_dyed_stone_stairs");
GameRegistry.registerBlock(GRAY_DYED_STONE_STAIRS, "gray_dyed_stone_stairs");
GameRegistry.registerBlock(SILVER_DYED_STONE_STAIRS, "silver_dyed_stone_stairs");
GameRegistry.registerBlock(CYAN_DYED_STONE_STAIRS, "cyan_dyed_stone_stairs");
GameRegistry.registerBlock(PURPLE_DYED_STONE_STAIRS, "purple_dyed_stone_stairs");
GameRegistry.registerBlock(BLUE_DYED_STONE_STAIRS, "blue_dyed_stone_stairs");
GameRegistry.registerBlock(BROWN_DYED_STONE_STAIRS, "brown_dyed_stone_stairs");
GameRegistry.registerBlock(GREEN_DYED_STONE_STAIRS, "green_dyed_stone_stairs");
GameRegistry.registerBlock(RED_DYED_STONE_STAIRS, "red_dyed_stone_stairs");
GameRegistry.registerBlock(BLACK_DYED_STONE_STAIRS, "black_dyed_stone_stairs");
//Ugh
GameRegistry.registerBlock(WHITE_DYED_ANDESITE_STAIRS, "white_dyed_andesite_stairs");
GameRegistry.registerBlock(ORANGE_DYED_ANDESITE_STAIRS, "orange_dyed_andesite_stairs");
GameRegistry.registerBlock(MAGENTA_DYED_ANDESITE_STAIRS, "magenta_dyed_andesite_stairs");
GameRegistry.registerBlock(LIGHT_BLUE_DYED_ANDESITE_STAIRS, "light_blue_dyed_andesite_stairs");
GameRegistry.registerBlock(YELLOW_DYED_ANDESITE_STAIRS, "yellow_dyed_andesite_stairs");
GameRegistry.registerBlock(LIME_DYED_ANDESITE_STAIRS, "lime_dyed_andesite_stairs");
GameRegistry.registerBlock(PINK_DYED_ANDESITE_STAIRS, "pink_dyed_andesite_stairs");
GameRegistry.registerBlock(GRAY_DYED_ANDESITE_STAIRS, "gray_dyed_andesite_stairs");
GameRegistry.registerBlock(SILVER_DYED_ANDESITE_STAIRS, "silver_dyed_andesite_stairs");
GameRegistry.registerBlock(CYAN_DYED_ANDESITE_STAIRS, "cyan_dyed_andesite_stairs");
GameRegistry.registerBlock(PURPLE_DYED_ANDESITE_STAIRS, "purple_dyed_andesite_stairs");
GameRegistry.registerBlock(BLUE_DYED_ANDESITE_STAIRS, "blue_dyed_andesite_stairs");
GameRegistry.registerBlock(BROWN_DYED_ANDESITE_STAIRS, "brown_dyed_andesite_stairs");
GameRegistry.registerBlock(GREEN_DYED_ANDESITE_STAIRS, "green_dyed_andesite_stairs");
GameRegistry.registerBlock(RED_DYED_ANDESITE_STAIRS, "red_dyed_andesite_stairs");
GameRegistry.registerBlock(BLACK_DYED_ANDESITE_STAIRS, "black_dyed_andesite_stairs");
GameRegistry.registerBlock(WHITE_DYED_DIORITE_STAIRS, "white_dyed_diorite_stairs");
GameRegistry.registerBlock(ORANGE_DYED_DIORITE_STAIRS, "orange_dyed_diorite_stairs");
GameRegistry.registerBlock(MAGENTA_DYED_DIORITE_STAIRS, "magenta_dyed_diorite_stairs");
GameRegistry.registerBlock(LIGHT_BLUE_DYED_DIORITE_STAIRS, "light_blue_dyed_diorite_stairs");
GameRegistry.registerBlock(YELLOW_DYED_DIORITE_STAIRS, "yellow_dyed_diorite_stairs");
GameRegistry.registerBlock(LIME_DYED_DIORITE_STAIRS, "lime_dyed_diorite_stairs");
GameRegistry.registerBlock(PINK_DYED_DIORITE_STAIRS, "pink_dyed_diorite_stairs");
GameRegistry.registerBlock(GRAY_DYED_DIORITE_STAIRS, "gray_dyed_diorite_stairs");
GameRegistry.registerBlock(SILVER_DYED_DIORITE_STAIRS, "silver_dyed_diorite_stairs");
GameRegistry.registerBlock(CYAN_DYED_DIORITE_STAIRS, "cyan_dyed_diorite_stairs");
GameRegistry.registerBlock(PURPLE_DYED_DIORITE_STAIRS, "purple_dyed_diorite_stairs");
GameRegistry.registerBlock(BLUE_DYED_DIORITE_STAIRS, "blue_dyed_diorite_stairs");
GameRegistry.registerBlock(BROWN_DYED_DIORITE_STAIRS, "brown_dyed_diorite_stairs");
GameRegistry.registerBlock(GREEN_DYED_DIORITE_STAIRS, "green_dyed_diorite_stairs");
GameRegistry.registerBlock(RED_DYED_DIORITE_STAIRS, "red_dyed_diorite_stairs");
GameRegistry.registerBlock(BLACK_DYED_DIORITE_STAIRS, "black_dyed_diorite_stairs");
GameRegistry.registerBlock(WHITE_DYED_GRANITE_STAIRS, "white_dyed_granite_stairs");
GameRegistry.registerBlock(ORANGE_DYED_GRANITE_STAIRS, "orange_dyed_granite_stairs");
GameRegistry.registerBlock(MAGENTA_DYED_GRANITE_STAIRS, "magenta_dyed_granite_stairs");
GameRegistry.registerBlock(LIGHT_BLUE_DYED_GRANITE_STAIRS, "light_blue_dyed_granite_stairs");
GameRegistry.registerBlock(YELLOW_DYED_GRANITE_STAIRS, "yellow_dyed_granite_stairs");
GameRegistry.registerBlock(LIME_DYED_GRANITE_STAIRS, "lime_dyed_granite_stairs");
GameRegistry.registerBlock(PINK_DYED_GRANITE_STAIRS, "pink_dyed_granite_stairs");
GameRegistry.registerBlock(GRAY_DYED_GRANITE_STAIRS, "gray_dyed_granite_stairs");
GameRegistry.registerBlock(SILVER_DYED_GRANITE_STAIRS, "silver_dyed_granite_stairs");
GameRegistry.registerBlock(CYAN_DYED_GRANITE_STAIRS, "cyan_dyed_granite_stairs");
GameRegistry.registerBlock(PURPLE_DYED_GRANITE_STAIRS, "purple_dyed_granite_stairs");
GameRegistry.registerBlock(BLUE_DYED_GRANITE_STAIRS, "blue_dyed_granite_stairs");
GameRegistry.registerBlock(BROWN_DYED_GRANITE_STAIRS, "brown_dyed_granite_stairs");
GameRegistry.registerBlock(GREEN_DYED_GRANITE_STAIRS, "green_dyed_granite_stairs");
GameRegistry.registerBlock(RED_DYED_GRANITE_STAIRS, "red_dyed_granite_stairs");
GameRegistry.registerBlock(BLACK_DYED_GRANITE_STAIRS, "black_dyed_granite_stairs");
GameRegistry.registerBlock(WHITE_DYED_POLISHED_ANDESITE_STAIRS, "white_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(ORANGE_DYED_POLISHED_ANDESITE_STAIRS, "orange_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(MAGENTA_DYED_POLISHED_ANDESITE_STAIRS, "magenta_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(LIGHT_BLUE_DYED_POLISHED_ANDESITE_STAIRS, "light_blue_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(YELLOW_DYED_POLISHED_ANDESITE_STAIRS, "yellow_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(LIME_DYED_POLISHED_ANDESITE_STAIRS, "lime_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(PINK_DYED_POLISHED_ANDESITE_STAIRS, "pink_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(GRAY_DYED_POLISHED_ANDESITE_STAIRS, "gray_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(SILVER_DYED_POLISHED_ANDESITE_STAIRS, "silver_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(CYAN_DYED_POLISHED_ANDESITE_STAIRS, "cyan_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(PURPLE_DYED_POLISHED_ANDESITE_STAIRS, "purple_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(BLUE_DYED_POLISHED_ANDESITE_STAIRS, "blue_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(BROWN_DYED_POLISHED_ANDESITE_STAIRS, "brown_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(GREEN_DYED_POLISHED_ANDESITE_STAIRS, "green_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(RED_DYED_POLISHED_ANDESITE_STAIRS, "red_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(BLACK_DYED_POLISHED_ANDESITE_STAIRS, "black_dyed_polished_andesite_stairs");
GameRegistry.registerBlock(WHITE_DYED_POLISHED_DIORITE_STAIRS, "white_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(ORANGE_DYED_POLISHED_DIORITE_STAIRS, "orange_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(MAGENTA_DYED_POLISHED_DIORITE_STAIRS, "magenta_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(LIGHT_BLUE_DYED_POLISHED_DIORITE_STAIRS, "light_blue_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(YELLOW_DYED_POLISHED_DIORITE_STAIRS, "yellow_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(LIME_DYED_POLISHED_DIORITE_STAIRS, "lime_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(PINK_DYED_POLISHED_DIORITE_STAIRS, "pink_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(GRAY_DYED_POLISHED_DIORITE_STAIRS, "gray_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(SILVER_DYED_POLISHED_DIORITE_STAIRS, "silver_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(CYAN_DYED_POLISHED_DIORITE_STAIRS, "cyan_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(PURPLE_DYED_POLISHED_DIORITE_STAIRS, "purple_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(BLUE_DYED_POLISHED_DIORITE_STAIRS, "blue_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(BROWN_DYED_POLISHED_DIORITE_STAIRS, "brown_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(GREEN_DYED_POLISHED_DIORITE_STAIRS, "green_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(RED_DYED_POLISHED_DIORITE_STAIRS, "red_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(BLACK_DYED_POLISHED_DIORITE_STAIRS, "black_dyed_polished_diorite_stairs");
GameRegistry.registerBlock(WHITE_DYED_POLISHED_GRANITE_STAIRS, "white_dyed_polished_granite_stairs");
GameRegistry.registerBlock(ORANGE_DYED_POLISHED_GRANITE_STAIRS, "orange_dyed_polished_granite_stairs");
GameRegistry.registerBlock(MAGENTA_DYED_POLISHED_GRANITE_STAIRS, "magenta_dyed_polished_granite_stairs");
GameRegistry.registerBlock(LIGHT_BLUE_DYED_POLISHED_GRANITE_STAIRS, "light_blue_dyed_polished_granite_stairs");
GameRegistry.registerBlock(YELLOW_DYED_POLISHED_GRANITE_STAIRS, "yellow_dyed_polished_granite_stairs");
GameRegistry.registerBlock(LIME_DYED_POLISHED_GRANITE_STAIRS, "lime_dyed_polished_granite_stairs");
GameRegistry.registerBlock(PINK_DYED_POLISHED_GRANITE_STAIRS, "pink_dyed_polished_granite_stairs");
GameRegistry.registerBlock(GRAY_DYED_POLISHED_GRANITE_STAIRS, "gray_dyed_polished_granite_stairs");
GameRegistry.registerBlock(SILVER_DYED_POLISHED_GRANITE_STAIRS, "silver_dyed_polished_granite_stairs");
GameRegistry.registerBlock(CYAN_DYED_POLISHED_GRANITE_STAIRS, "cyan_dyed_polished_granite_stairs");
GameRegistry.registerBlock(PURPLE_DYED_POLISHED_GRANITE_STAIRS, "purple_dyed_polished_granite_stairs");
GameRegistry.registerBlock(BLUE_DYED_POLISHED_GRANITE_STAIRS, "blue_dyed_polished_granite_stairs");
GameRegistry.registerBlock(BROWN_DYED_POLISHED_GRANITE_STAIRS, "brown_dyed_polished_granite_stairs");
GameRegistry.registerBlock(GREEN_DYED_POLISHED_GRANITE_STAIRS, "green_dyed_polished_granite_stairs");
GameRegistry.registerBlock(RED_DYED_POLISHED_GRANITE_STAIRS, "red_dyed_polished_granite_stairs");
GameRegistry.registerBlock(BLACK_DYED_POLISHED_GRANITE_STAIRS, "black_dyed_polished_granite_stairs");
}
}
//Now register pressure plates
if (IgneousExtrasMod.CONFIGURATION.get("ADDITIONAL_BLOCKS", "PRESSURE_PLATES", true, "Enable the use of additional pressure plates").getBoolean()) {
GameRegistry.registerBlock(COBBLESTONE_PRESSURE_PLATE, "cobblestone_pressure_plate");
GameRegistry.registerBlock(MOSSY_COBBLESTONE_PRESSURE_PLATE, "mossy_cobblestone_pressure_plate");
GameRegistry.registerBlock(GRANITE_PRESSURE_PLATE, "granite_pressure_plate");
GameRegistry.registerBlock(POLISHED_GRANITE_PRESSURE_PLATE, "polished_granite_pressure_plate");
GameRegistry.registerBlock(DIORITE_PRESSURE_PLATE, "diorite_pressure_plate");
GameRegistry.registerBlock(POLISHED_DIORITE_PRESSURE_PLATE, "polished_diorite_pressure_plate");
GameRegistry.registerBlock(ANDESITE_PRESSURE_PLATE, "andesite_pressure_plate");
GameRegistry.registerBlock(POLISHED_ANDESITE_PRESSURE_PLATE, "polished_andesite_pressure_plate");
GameRegistry.registerBlock(STONE_BRICK_PRESSURE_PLATE, "stone_brick_pressure_plate");
GameRegistry.registerBlock(CRACKED_STONE_BRICK_PRESSURE_PLATE, "cracked_stone_brick_pressure_plate");
GameRegistry.registerBlock(CHISELED_STONE_BRICK_PRESSURE_PLATE, "chiseled_stone_brick_pressure_plate");
GameRegistry.registerBlock(MOSSY_STONE_BRICK_PRESSURE_PLATE, "mossy_stone_brick_pressure_plate");
}
if (IgneousExtrasMod.CONFIGURATION.get("ADDITIONAL_BLOCKS", "DYED_STONE_BLOCKS", true, "Enable the use of dyed stone blocks").getBoolean()) {
//Now we register meshes for coloured blocks in this loop
for (EnumDyeColor color : EnumDyeColor.values()) {
//Start off with dyed cobblestone
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(DYED_COBBLESTONE), color.getMetadata(), "dyed_cobblestone", "color=" + color.getName());
//Then dyed mossy cobblestone
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(DYED_MOSSY_COBBLESTONE), color.getMetadata(), "dyed_mossy_cobblestone", "color=" + color.getName());
//Then dyed stone
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(DYED_STONE), color.getMetadata(), "dyed_stone", "color=" + color.getName());
//Then dyed granite
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(DYED_GRANITE), color.getMetadata(), "dyed_granite", "color=" + color.getName());
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(DYED_SMOOTH_GRANITE), color.getMetadata(), "dyed_smooth_granite", "color=" + color.getName());
//Then dyed diorite
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(DYED_DIORITE), color.getMetadata(), "dyed_diorite", "color=" + color.getName());
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(DYED_SMOOTH_DIORITE), color.getMetadata(), "dyed_smooth_diorite", "color=" + color.getName());
//Then dyed andesite
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(DYED_ANDESITE), color.getMetadata(), "dyed_andesite", "color=" + color.getName());
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(DYED_SMOOTH_ANDESITE), color.getMetadata(), "dyed_smooth_andesite", "color=" + color.getName());
}
}
if (IgneousExtrasMod.CONFIGURATION.get("ADDITIONAL_BLOCKS", "STAIRS", true, "Enable the use of additional stair blocks").getBoolean()) {
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(STONE_STAIRS), 0, "stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(MOSSY_COBBLESTONE_STAIRS), 0, "mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GRANITE_STAIRS), 0, "granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(POLISHED_GRANITE_STAIRS), 0, "polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(DIORITE_STAIRS), 0, "diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(POLISHED_DIORITE_STAIRS), 0, "polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(ANDESITE_STAIRS), 0, "andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(POLISHED_ANDESITE_STAIRS), 0, "polished_andesite_stairs", "inventory");
//Now begin the dyed versions
if (IgneousExtrasMod.CONFIGURATION.get("ADDITIONAL_BLOCKS", "DYED_STONE_BLOCKS", true, "Enable the use of dyed stone blocks").getBoolean()) {
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(WHITE_DYED_COBBLESTONE_STAIRS), 0, "white_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(ORANGE_DYED_COBBLESTONE_STAIRS), 0, "orange_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(MAGENTA_DYED_COBBLESTONE_STAIRS), 0, "magenta_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIGHT_BLUE_DYED_COBBLESTONE_STAIRS), 0, "light_blue_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(YELLOW_DYED_COBBLESTONE_STAIRS), 0, "yellow_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIME_DYED_COBBLESTONE_STAIRS), 0, "lime_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PINK_DYED_COBBLESTONE_STAIRS), 0, "pink_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GRAY_DYED_COBBLESTONE_STAIRS), 0, "gray_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(SILVER_DYED_COBBLESTONE_STAIRS), 0, "silver_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(CYAN_DYED_COBBLESTONE_STAIRS), 0, "cyan_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PURPLE_DYED_COBBLESTONE_STAIRS), 0, "purple_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLUE_DYED_COBBLESTONE_STAIRS), 0, "blue_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BROWN_DYED_COBBLESTONE_STAIRS), 0, "brown_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GREEN_DYED_COBBLESTONE_STAIRS), 0, "green_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(RED_DYED_COBBLESTONE_STAIRS), 0, "red_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLACK_DYED_COBBLESTONE_STAIRS), 0, "black_dyed_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(WHITE_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "white_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(ORANGE_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "orange_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(MAGENTA_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "magenta_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIGHT_BLUE_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "light_blue_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(YELLOW_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "yellow_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIME_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "lime_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PINK_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "pink_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GRAY_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "gray_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(SILVER_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "silver_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(CYAN_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "cyan_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PURPLE_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "purple_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLUE_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "blue_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BROWN_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "brown_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GREEN_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "green_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(RED_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "red_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLACK_DYED_MOSSY_COBBLESTONE_STAIRS), 0, "black_dyed_mossy_cobblestone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(WHITE_DYED_STONE_STAIRS), 0, "white_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(ORANGE_DYED_STONE_STAIRS), 0, "orange_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(MAGENTA_DYED_STONE_STAIRS), 0, "magenta_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIGHT_BLUE_DYED_STONE_STAIRS), 0, "light_blue_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(YELLOW_DYED_STONE_STAIRS), 0, "yellow_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIME_DYED_STONE_STAIRS), 0, "lime_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PINK_DYED_STONE_STAIRS), 0, "pink_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GRAY_DYED_STONE_STAIRS), 0, "gray_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(SILVER_DYED_STONE_STAIRS), 0, "silver_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(CYAN_DYED_STONE_STAIRS), 0, "cyan_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PURPLE_DYED_STONE_STAIRS), 0, "purple_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLUE_DYED_STONE_STAIRS), 0, "blue_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BROWN_DYED_STONE_STAIRS), 0, "brown_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GREEN_DYED_STONE_STAIRS), 0, "green_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(RED_DYED_STONE_STAIRS), 0, "red_dyed_stone_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLACK_DYED_STONE_STAIRS), 0, "black_dyed_stone_stairs", "inventory");
//I repeat; ugh
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(WHITE_DYED_ANDESITE_STAIRS), 0, "white_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(ORANGE_DYED_ANDESITE_STAIRS), 0, "orange_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(MAGENTA_DYED_ANDESITE_STAIRS), 0, "magenta_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIGHT_BLUE_DYED_ANDESITE_STAIRS), 0, "light_blue_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(YELLOW_DYED_ANDESITE_STAIRS), 0, "yellow_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIME_DYED_ANDESITE_STAIRS), 0, "lime_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PINK_DYED_ANDESITE_STAIRS), 0, "pink_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GRAY_DYED_ANDESITE_STAIRS), 0, "gray_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(SILVER_DYED_ANDESITE_STAIRS), 0, "silver_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(CYAN_DYED_ANDESITE_STAIRS), 0, "cyan_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PURPLE_DYED_ANDESITE_STAIRS), 0, "purple_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLUE_DYED_ANDESITE_STAIRS), 0, "blue_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BROWN_DYED_ANDESITE_STAIRS), 0, "brown_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GREEN_DYED_ANDESITE_STAIRS), 0, "green_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(RED_DYED_ANDESITE_STAIRS), 0, "red_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLACK_DYED_ANDESITE_STAIRS), 0, "black_dyed_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(WHITE_DYED_DIORITE_STAIRS), 0, "white_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(ORANGE_DYED_DIORITE_STAIRS), 0, "orange_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(MAGENTA_DYED_DIORITE_STAIRS), 0, "magenta_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIGHT_BLUE_DYED_DIORITE_STAIRS), 0, "light_blue_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(YELLOW_DYED_DIORITE_STAIRS), 0, "yellow_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIME_DYED_DIORITE_STAIRS), 0, "lime_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PINK_DYED_DIORITE_STAIRS), 0, "pink_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GRAY_DYED_DIORITE_STAIRS), 0, "gray_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(SILVER_DYED_DIORITE_STAIRS), 0, "silver_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(CYAN_DYED_DIORITE_STAIRS), 0, "cyan_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PURPLE_DYED_DIORITE_STAIRS), 0, "purple_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLUE_DYED_DIORITE_STAIRS), 0, "blue_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BROWN_DYED_DIORITE_STAIRS), 0, "brown_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GREEN_DYED_DIORITE_STAIRS), 0, "green_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(RED_DYED_DIORITE_STAIRS), 0, "red_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLACK_DYED_DIORITE_STAIRS), 0, "black_dyed_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(WHITE_DYED_GRANITE_STAIRS), 0, "white_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(ORANGE_DYED_GRANITE_STAIRS), 0, "orange_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(MAGENTA_DYED_GRANITE_STAIRS), 0, "magenta_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIGHT_BLUE_DYED_GRANITE_STAIRS), 0, "light_blue_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(YELLOW_DYED_GRANITE_STAIRS), 0, "yellow_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIME_DYED_GRANITE_STAIRS), 0, "lime_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PINK_DYED_GRANITE_STAIRS), 0, "pink_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GRAY_DYED_GRANITE_STAIRS), 0, "gray_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(SILVER_DYED_GRANITE_STAIRS), 0, "silver_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(CYAN_DYED_GRANITE_STAIRS), 0, "cyan_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PURPLE_DYED_GRANITE_STAIRS), 0, "purple_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLUE_DYED_GRANITE_STAIRS), 0, "blue_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BROWN_DYED_GRANITE_STAIRS), 0, "brown_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GREEN_DYED_GRANITE_STAIRS), 0, "green_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(RED_DYED_GRANITE_STAIRS), 0, "red_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLACK_DYED_GRANITE_STAIRS), 0, "black_dyed_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(WHITE_DYED_POLISHED_ANDESITE_STAIRS), 0, "white_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(ORANGE_DYED_POLISHED_ANDESITE_STAIRS), 0, "orange_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(MAGENTA_DYED_POLISHED_ANDESITE_STAIRS), 0, "magenta_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIGHT_BLUE_DYED_POLISHED_ANDESITE_STAIRS), 0, "light_blue_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(YELLOW_DYED_POLISHED_ANDESITE_STAIRS), 0, "yellow_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIME_DYED_POLISHED_ANDESITE_STAIRS), 0, "lime_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PINK_DYED_POLISHED_ANDESITE_STAIRS), 0, "pink_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GRAY_DYED_POLISHED_ANDESITE_STAIRS), 0, "gray_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(SILVER_DYED_POLISHED_ANDESITE_STAIRS), 0, "silver_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(CYAN_DYED_POLISHED_ANDESITE_STAIRS), 0, "cyan_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PURPLE_DYED_POLISHED_ANDESITE_STAIRS), 0, "purple_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLUE_DYED_POLISHED_ANDESITE_STAIRS), 0, "blue_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BROWN_DYED_POLISHED_ANDESITE_STAIRS), 0, "brown_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GREEN_DYED_POLISHED_ANDESITE_STAIRS), 0, "green_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(RED_DYED_POLISHED_ANDESITE_STAIRS), 0, "red_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLACK_DYED_POLISHED_ANDESITE_STAIRS), 0, "black_dyed_polished_andesite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(WHITE_DYED_POLISHED_DIORITE_STAIRS), 0, "white_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(ORANGE_DYED_POLISHED_DIORITE_STAIRS), 0, "orange_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(MAGENTA_DYED_POLISHED_DIORITE_STAIRS), 0, "magenta_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIGHT_BLUE_DYED_POLISHED_DIORITE_STAIRS), 0, "light_blue_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(YELLOW_DYED_POLISHED_DIORITE_STAIRS), 0, "yellow_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIME_DYED_POLISHED_DIORITE_STAIRS), 0, "lime_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PINK_DYED_POLISHED_DIORITE_STAIRS), 0, "pink_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GRAY_DYED_POLISHED_DIORITE_STAIRS), 0, "gray_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(SILVER_DYED_POLISHED_DIORITE_STAIRS), 0, "silver_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(CYAN_DYED_POLISHED_DIORITE_STAIRS), 0, "cyan_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PURPLE_DYED_POLISHED_DIORITE_STAIRS), 0, "purple_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLUE_DYED_POLISHED_DIORITE_STAIRS), 0, "blue_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BROWN_DYED_POLISHED_DIORITE_STAIRS), 0, "brown_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GREEN_DYED_POLISHED_DIORITE_STAIRS), 0, "green_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(RED_DYED_POLISHED_DIORITE_STAIRS), 0, "red_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLACK_DYED_POLISHED_DIORITE_STAIRS), 0, "black_dyed_polished_diorite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(WHITE_DYED_POLISHED_GRANITE_STAIRS), 0, "white_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(ORANGE_DYED_POLISHED_GRANITE_STAIRS), 0, "orange_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(MAGENTA_DYED_POLISHED_GRANITE_STAIRS), 0, "magenta_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIGHT_BLUE_DYED_POLISHED_GRANITE_STAIRS), 0, "light_blue_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(YELLOW_DYED_POLISHED_GRANITE_STAIRS), 0, "yellow_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(LIME_DYED_POLISHED_GRANITE_STAIRS), 0, "lime_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PINK_DYED_POLISHED_GRANITE_STAIRS), 0, "pink_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GRAY_DYED_POLISHED_GRANITE_STAIRS), 0, "gray_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(SILVER_DYED_POLISHED_GRANITE_STAIRS), 0, "silver_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(CYAN_DYED_POLISHED_GRANITE_STAIRS), 0, "cyan_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(PURPLE_DYED_POLISHED_GRANITE_STAIRS), 0, "purple_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLUE_DYED_POLISHED_GRANITE_STAIRS), 0, "blue_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BROWN_DYED_POLISHED_GRANITE_STAIRS), 0, "brown_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GREEN_DYED_POLISHED_GRANITE_STAIRS), 0, "green_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(RED_DYED_POLISHED_GRANITE_STAIRS), 0, "red_dyed_polished_granite_stairs", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(BLACK_DYED_POLISHED_GRANITE_STAIRS), 0, "black_dyed_polished_granite_stairs", "inventory");
}
}
if (IgneousExtrasMod.CONFIGURATION.get("ADDITIONAL_BLOCKS", "PRESSURE_PLATES", true, "Enable the use of additional pressure plates").getBoolean()) {
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(COBBLESTONE_PRESSURE_PLATE), 0, "cobblestone_pressure_plate", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(MOSSY_COBBLESTONE_PRESSURE_PLATE), 0, "mossy_cobblestone_pressure_plate", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(GRANITE_PRESSURE_PLATE), 0, "granite_pressure_plate", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(POLISHED_GRANITE_PRESSURE_PLATE), 0, "polished_granite_pressure_plate", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(DIORITE_PRESSURE_PLATE), 0, "diorite_pressure_plate", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(POLISHED_DIORITE_PRESSURE_PLATE), 0, "polished_diorite_pressure_plate", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(ANDESITE_PRESSURE_PLATE), 0, "andesite_pressure_plate", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(POLISHED_ANDESITE_PRESSURE_PLATE), 0, "polished_andesite_pressure_plate", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(STONE_BRICK_PRESSURE_PLATE), 0, "stone_brick_pressure_plate", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(CHISELED_STONE_BRICK_PRESSURE_PLATE), 0, "chiseled_stone_brick_pressure_plate", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(CRACKED_STONE_BRICK_PRESSURE_PLATE), 0, "cracked_stone_brick_pressure_plate", "inventory");
IgneousExtrasMod.PROXY.registerItemModelMesher(Item.getItemFromBlock(MOSSY_STONE_BRICK_PRESSURE_PLATE), 0, "mossy_stone_brick_pressure_plate", "inventory");
}
}
/**
* Registers recipes for {@link net.minecraft.block.Block}s added by the {@link IgneousExtrasMod}
*
* @since 0.0.1
*/
public static void registerRecipes() {
if (IgneousExtrasMod.CONFIGURATION.get("ADDITIONAL_BLOCKS", "DYED_STONE_BLOCKS", true, "Enable the use of dyed stone blocks").getBoolean()) {
registerSingleDyeBlockRecipeCombination(Blocks.cobblestone, DYED_COBBLESTONE);
registerSingleDyeBlockRecipeCombination(Blocks.mossy_cobblestone, DYED_MOSSY_COBBLESTONE);
registerSingleDyeBlockRecipeCombination(Blocks.stone, 0, DYED_STONE);
registerSingleDyeBlockRecipeCombination(Blocks.stone, 1, DYED_GRANITE);
registerSingleDyeBlockRecipeCombination(Blocks.stone, 2, DYED_SMOOTH_GRANITE);
registerSingleDyeBlockRecipeCombination(Blocks.stone, 3, DYED_DIORITE);
registerSingleDyeBlockRecipeCombination(Blocks.stone, 4, DYED_SMOOTH_DIORITE);
registerSingleDyeBlockRecipeCombination(Blocks.stone, 5, DYED_ANDESITE);
registerSingleDyeBlockRecipeCombination(Blocks.stone, 6, DYED_SMOOTH_ANDESITE);
}
if (IgneousExtrasMod.CONFIGURATION.get("ADDITIONAL_BLOCKS", "STAIRS", true, "Enable the use of additional stair blocks").getBoolean()) {
registerStairsRecipe(Blocks.stone, 0, STONE_STAIRS);
registerStairsRecipe(Blocks.mossy_cobblestone, 0, MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(Blocks.stone, 1, GRANITE_STAIRS);
registerStairsRecipe(Blocks.stone, 2, POLISHED_GRANITE_STAIRS);
registerStairsRecipe(Blocks.stone, 3, DIORITE_STAIRS);
registerStairsRecipe(Blocks.stone, 4, POLISHED_DIORITE_STAIRS);
registerStairsRecipe(Blocks.stone, 5, ANDESITE_STAIRS);
registerStairsRecipe(Blocks.stone, 6, POLISHED_ANDESITE_STAIRS);
//Now dyed variants
if (IgneousExtrasMod.CONFIGURATION.get("ADDITIONAL_BLOCKS", "DYED_STONE_BLOCKS", true, "Enable the use of dyed stone blocks").getBoolean()) {
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.WHITE.getMetadata(), WHITE_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.ORANGE.getMetadata(), ORANGE_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.MAGENTA.getMetadata(), MAGENTA_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.LIGHT_BLUE.getMetadata(), LIGHT_BLUE_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.YELLOW.getMetadata(), YELLOW_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.LIME.getMetadata(), LIME_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.PINK.getMetadata(), PINK_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.GRAY.getMetadata(), GRAY_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.SILVER.getMetadata(), SILVER_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.CYAN.getMetadata(), CYAN_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.PURPLE.getMetadata(), PURPLE_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.BLUE.getMetadata(), BLUE_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.BROWN.getMetadata(), BROWN_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.GREEN.getMetadata(), GREEN_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.RED.getMetadata(), RED_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_COBBLESTONE, EnumDyeColor.BLACK.getMetadata(), BLACK_DYED_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.WHITE.getMetadata(), WHITE_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.ORANGE.getMetadata(), ORANGE_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.MAGENTA.getMetadata(), MAGENTA_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.LIGHT_BLUE.getMetadata(), LIGHT_BLUE_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.YELLOW.getMetadata(), YELLOW_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.LIME.getMetadata(), LIME_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.PINK.getMetadata(), PINK_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.GRAY.getMetadata(), GRAY_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.SILVER.getMetadata(), SILVER_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.CYAN.getMetadata(), CYAN_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.PURPLE.getMetadata(), PURPLE_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.BLUE.getMetadata(), BLUE_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.BROWN.getMetadata(), BROWN_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.GREEN.getMetadata(), GREEN_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.RED.getMetadata(), RED_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_MOSSY_COBBLESTONE, EnumDyeColor.BLACK.getMetadata(), BLACK_DYED_MOSSY_COBBLESTONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.WHITE.getMetadata(), WHITE_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.ORANGE.getMetadata(), ORANGE_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.MAGENTA.getMetadata(), MAGENTA_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.LIGHT_BLUE.getMetadata(), LIGHT_BLUE_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.YELLOW.getMetadata(), YELLOW_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.LIME.getMetadata(), LIME_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.PINK.getMetadata(), PINK_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.GRAY.getMetadata(), GRAY_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.SILVER.getMetadata(), SILVER_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.CYAN.getMetadata(), CYAN_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.PURPLE.getMetadata(), PURPLE_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.BLUE.getMetadata(), BLUE_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.BROWN.getMetadata(), BROWN_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.GREEN.getMetadata(), GREEN_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.RED.getMetadata(), RED_DYED_STONE_STAIRS);
registerStairsRecipe(DYED_STONE, EnumDyeColor.BLACK.getMetadata(), BLACK_DYED_STONE_STAIRS);
//<h1>UGHHHHH</h1>
//Maybe I should have skipped dyed stone... But oh well
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.WHITE.getMetadata(), WHITE_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.ORANGE.getMetadata(), ORANGE_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.MAGENTA.getMetadata(), MAGENTA_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.LIGHT_BLUE.getMetadata(), LIGHT_BLUE_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.YELLOW.getMetadata(), YELLOW_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.LIME.getMetadata(), LIME_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.PINK.getMetadata(), PINK_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.GRAY.getMetadata(), GRAY_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.SILVER.getMetadata(), SILVER_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.CYAN.getMetadata(), CYAN_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.PURPLE.getMetadata(), PURPLE_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.BLUE.getMetadata(), BLUE_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.BROWN.getMetadata(), BROWN_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.GREEN.getMetadata(), GREEN_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.RED.getMetadata(), RED_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_ANDESITE, EnumDyeColor.BLACK.getMetadata(), BLACK_DYED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.WHITE.getMetadata(), WHITE_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.ORANGE.getMetadata(), ORANGE_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.MAGENTA.getMetadata(), MAGENTA_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.LIGHT_BLUE.getMetadata(), LIGHT_BLUE_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.YELLOW.getMetadata(), YELLOW_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.LIME.getMetadata(), LIME_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.PINK.getMetadata(), PINK_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.GRAY.getMetadata(), GRAY_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.SILVER.getMetadata(), SILVER_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.CYAN.getMetadata(), CYAN_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.PURPLE.getMetadata(), PURPLE_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.BLUE.getMetadata(), BLUE_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.BROWN.getMetadata(), BROWN_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.GREEN.getMetadata(), GREEN_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.RED.getMetadata(), RED_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_DIORITE, EnumDyeColor.BLACK.getMetadata(), BLACK_DYED_DIORITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.WHITE.getMetadata(), WHITE_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.ORANGE.getMetadata(), ORANGE_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.MAGENTA.getMetadata(), MAGENTA_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.LIGHT_BLUE.getMetadata(), LIGHT_BLUE_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.YELLOW.getMetadata(), YELLOW_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.LIME.getMetadata(), LIME_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.PINK.getMetadata(), PINK_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.GRAY.getMetadata(), GRAY_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.SILVER.getMetadata(), SILVER_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.CYAN.getMetadata(), CYAN_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.PURPLE.getMetadata(), PURPLE_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.BLUE.getMetadata(), BLUE_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.BROWN.getMetadata(), BROWN_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.GREEN.getMetadata(), GREEN_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.RED.getMetadata(), RED_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_GRANITE, EnumDyeColor.BLACK.getMetadata(), BLACK_DYED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.WHITE.getMetadata(), WHITE_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.ORANGE.getMetadata(), ORANGE_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.MAGENTA.getMetadata(), MAGENTA_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.LIGHT_BLUE.getMetadata(), LIGHT_BLUE_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.YELLOW.getMetadata(), YELLOW_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.LIME.getMetadata(), LIME_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.PINK.getMetadata(), PINK_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.GRAY.getMetadata(), GRAY_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.SILVER.getMetadata(), SILVER_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.CYAN.getMetadata(), CYAN_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.PURPLE.getMetadata(), PURPLE_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.BLUE.getMetadata(), BLUE_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.BROWN.getMetadata(), BROWN_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.GREEN.getMetadata(), GREEN_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.RED.getMetadata(), RED_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_ANDESITE, EnumDyeColor.BLACK.getMetadata(), BLACK_DYED_POLISHED_ANDESITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.WHITE.getMetadata(), WHITE_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.ORANGE.getMetadata(), ORANGE_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.MAGENTA.getMetadata(), MAGENTA_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.LIGHT_BLUE.getMetadata(), LIGHT_BLUE_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.YELLOW.getMetadata(), YELLOW_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.LIME.getMetadata(), LIME_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.PINK.getMetadata(), PINK_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.GRAY.getMetadata(), GRAY_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.SILVER.getMetadata(), SILVER_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.CYAN.getMetadata(), CYAN_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.PURPLE.getMetadata(), PURPLE_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.BLUE.getMetadata(), BLUE_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.BROWN.getMetadata(), BROWN_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.GREEN.getMetadata(), GREEN_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.RED.getMetadata(), RED_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_DIORITE, EnumDyeColor.BLACK.getMetadata(), BLACK_DYED_POLISHED_DIORITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.WHITE.getMetadata(), WHITE_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.ORANGE.getMetadata(), ORANGE_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.MAGENTA.getMetadata(), MAGENTA_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.LIGHT_BLUE.getMetadata(), LIGHT_BLUE_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.YELLOW.getMetadata(), YELLOW_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.LIME.getMetadata(), LIME_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.PINK.getMetadata(), PINK_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.GRAY.getMetadata(), GRAY_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.SILVER.getMetadata(), SILVER_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.CYAN.getMetadata(), CYAN_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.PURPLE.getMetadata(), PURPLE_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.BLUE.getMetadata(), BLUE_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.BROWN.getMetadata(), BROWN_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.GREEN.getMetadata(), GREEN_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.RED.getMetadata(), RED_DYED_POLISHED_GRANITE_STAIRS);
registerStairsRecipe(DYED_SMOOTH_GRANITE, EnumDyeColor.BLACK.getMetadata(), BLACK_DYED_POLISHED_GRANITE_STAIRS);
}
}
if (IgneousExtrasMod.CONFIGURATION.get("ADDITIONAL_BLOCKS", "PRESSURE_PLATES", true, "Enable the use of additional pressure plates").getBoolean()) {
registerPressurePlateRecipe(Blocks.cobblestone, 0, COBBLESTONE_PRESSURE_PLATE);
registerPressurePlateRecipe(Blocks.mossy_cobblestone, 0, MOSSY_COBBLESTONE_PRESSURE_PLATE);
registerPressurePlateRecipe(Blocks.stone, BlockStone.EnumType.GRANITE.getMetadata(), GRANITE_PRESSURE_PLATE);
registerPressurePlateRecipe(Blocks.stone, BlockStone.EnumType.GRANITE_SMOOTH.getMetadata(), POLISHED_GRANITE_PRESSURE_PLATE);
registerPressurePlateRecipe(Blocks.stone, BlockStone.EnumType.ANDESITE.getMetadata(), ANDESITE_PRESSURE_PLATE);
registerPressurePlateRecipe(Blocks.stone, BlockStone.EnumType.ANDESITE_SMOOTH.getMetadata(), POLISHED_ANDESITE_PRESSURE_PLATE);
registerPressurePlateRecipe(Blocks.stone, BlockStone.EnumType.DIORITE.getMetadata(), DIORITE_PRESSURE_PLATE);
registerPressurePlateRecipe(Blocks.stone, BlockStone.EnumType.DIORITE_SMOOTH.getMetadata(), POLISHED_DIORITE_PRESSURE_PLATE);
registerPressurePlateRecipe(Blocks.stonebrick, BlockStoneBrick.EnumType.DEFAULT.getMetadata(), STONE_BRICK_PRESSURE_PLATE);
registerPressurePlateRecipe(Blocks.stonebrick, BlockStoneBrick.EnumType.CHISELED.getMetadata(), CHISELED_STONE_BRICK_PRESSURE_PLATE);
registerPressurePlateRecipe(Blocks.stonebrick, BlockStoneBrick.EnumType.CRACKED.getMetadata(), CRACKED_STONE_BRICK_PRESSURE_PLATE);
registerPressurePlateRecipe(Blocks.stonebrick, BlockStoneBrick.EnumType.MOSSY.getMetadata(), MOSSY_STONE_BRICK_PRESSURE_PLATE);
}
//TODO: Add recipes for items second
}
/**
* Registers a {@link BlockStairs} recipe
*
* @param baseBlock The base block to be consumed
* @param stairBlock The stair block to be returned
* @since 0.0.1
*/
public static void registerStairsRecipe(Block baseBlock, Block stairBlock) {
registerStairsRecipe(baseBlock, 0, stairBlock);
}
/**
* Registers a {@link BlockStairs} recipe
*
* @param baseBlock The base block to be consumed
* @param baseBlockMetadata The required metadata value of the base block
* @param stairBlock The stair block to be returned
* @since 0.0.1
*/
public static void registerStairsRecipe(Block baseBlock, int baseBlockMetadata, Block stairBlock) {
ItemStack input = new ItemStack(baseBlock, 1, baseBlockMetadata);
ItemStack output = new ItemStack(stairBlock, 4, 0);
GameRegistry.addShapedRecipe(output, " I", " II", "III", 'I', input);
GameRegistry.addShapedRecipe(output, "I ", "II ", "III", 'I', input);
}
/**
* Registers a {@link BlockPressurePlate} recipe
*
* @param baseBlock The base block to be consumed
* @param baseBlockMetadata The required metadata value of the base block
* @param plateBlock The plate block to be returned
* @since 0.0.2
*/
public static void registerPressurePlateRecipe(Block baseBlock, int baseBlockMetadata, Block plateBlock) {
ItemStack input = new ItemStack(baseBlock, 1, baseBlockMetadata);
ItemStack output = new ItemStack(plateBlock, 1, 0);
GameRegistry.addShapedRecipe(output, "II", 'I', input);
}
/**
* Registers all dye variant recipes for a single input {@link Block}
*
* @param blockToConsume The {@link Block} to consume
* @param blockToReturn The {@link Block} to return
*
* @since 0.0.1
*/
public static void registerSingleDyeBlockRecipeCombination(Block blockToConsume, Block blockToReturn) {
registerSingleDyeBlockRecipeCombination(blockToConsume, 0, blockToReturn);
}
/**
* Registers all dye variant recipes for a single input {@link Block}
*
* @param blockToConsume The {@link Block} to consume
* @param consumptionMetadata The metadata of the block being consumed
* @param blockToReturn The {@link Block} to return
*
* @since 0.0.1
*/
public static void registerSingleDyeBlockRecipeCombination(Block blockToConsume, int consumptionMetadata, Block blockToReturn) {
ItemStack dye;
ItemStack water = new ItemStack(Items.water_bucket, 1);
for (EnumDyeColor color : EnumDyeColor.values()) {
dye = new ItemStack(Items.dye, 1, color.getDyeDamage());
ItemStack input = new ItemStack(blockToConsume, 1, consumptionMetadata);
ItemStack output = new ItemStack(blockToReturn, 8, color.getMetadata());
GameRegistry.addShapedRecipe(output, "III", "IDI", "III", 'I', input, 'D', dye);
GameRegistry.addShapedRecipe(new ItemStack(blockToConsume, 8, consumptionMetadata),
"OOO", "OWO", "OOO",
'W', water, 'O', new ItemStack(blockToReturn, 1, color.getMetadata()));
}
}
}
|
package com.nhl.link.move.unit;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.datasource.DataSourceBuilder;
import org.apache.cayenne.datasource.PoolingDataSource;
import org.apache.cayenne.query.SQLExec;
import org.apache.cayenne.query.SQLSelect;
import org.apache.cayenne.query.SQLTemplate;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
public abstract class DerbySrcTest {
protected static CayenneDerbyStack srcStack;
protected static PoolingDataSource srcDataSource;
@BeforeClass
public static void startSrc() {
srcStack = new CayenneDerbyStack("derbysrc", "cayenne-linketl-tests-sources.xml");
srcDataSource = DataSourceBuilder.url("jdbc:derby:" + srcStack.getDerbyPath() + ";create=true")
.driver("org.apache.derby.jdbc.EmbeddedDriver").userName("sa").pool(1, 10).build();
}
@AfterClass
public static void shutdownSrc() {
srcStack.shutdown();
try {
srcDataSource.close();
} catch (Exception e) {
}
srcDataSource = null;
}
@Before
public void deleteSourceData() {
ObjectContext context = srcStack.newContext();
// first query in a test set will also load the schema...
context.performGenericQuery(new SQLTemplate(Object.class, "DELETE from utest.etl1"));
context.performGenericQuery(new SQLTemplate(Object.class, "DELETE from utest.etl3"));
context.performGenericQuery(new SQLTemplate(Object.class, "DELETE from utest.etl2"));
context.performGenericQuery(new SQLTemplate(Object.class, "DELETE from utest.etl4"));
context.performGenericQuery(new SQLTemplate(Object.class, "DELETE from utest.etl5"));
}
protected void srcRunSql(String sql, Object... params) {
SQLExec.query(sql).paramsArray(params).execute(srcStack.newContext());
}
protected int srcScalar(String sql) {
ObjectContext context = srcStack.newContext();
SQLSelect<Integer> query = SQLSelect.scalarQuery(Integer.class, sql);
return query.selectOne(context).intValue();
}
}
|
package ch.ntb.inf.deep.linker;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import ch.ntb.inf.deep.classItems.Array;
import ch.ntb.inf.deep.classItems.Class;
import ch.ntb.inf.deep.classItems.DataItem;
import ch.ntb.inf.deep.classItems.ICclassFileConsts;
import ch.ntb.inf.deep.classItems.ICdescAndTypeConsts;
import ch.ntb.inf.deep.classItems.Item;
import ch.ntb.inf.deep.classItems.Method;
import ch.ntb.inf.deep.classItems.StdConstant;
import ch.ntb.inf.deep.classItems.StringLiteral;
import ch.ntb.inf.deep.classItems.Type;
import ch.ntb.inf.deep.config.Configuration;
import ch.ntb.inf.deep.config.Device;
import ch.ntb.inf.deep.config.IAttributes;
import ch.ntb.inf.deep.config.Segment;
import ch.ntb.inf.deep.host.ErrorReporter;
import ch.ntb.inf.deep.host.StdStreams;
import ch.ntb.inf.deep.strings.HString;
public class Linker32 implements ICclassFileConsts, ICdescAndTypeConsts, IAttributes {
public static final byte slotSize = 4; // 4 bytes
static{
assert (slotSize & (slotSize-1)) == 0; // assert: slotSize == power of 2
}
private static final boolean dbg = true; // enable/disable debugging outputs for the linker
// Constant block:
public static final int cblkConstBlockSizeOffset = 0;
public static final int cblkCodeBaseOffset = 1 * 4;
public static final int cblkCodeSizeOffset = 2 * 4;
public static final int cblkVarBaseOffset = 3 * 4;
public static final int cblkVarSizeOffset = 4 * 4;
public static final int cblkClinitAddrOffset = 5 * 4;
public static final int cblkNofPtrsOffset = 6 * 4;
public static final int cblkPtrAddr0Offset = 7 * 4;
// Class/type descriptor:
public static final int tdMethTabOffset = 2 * 4;
public static final int tdExtensionLevelOffset = 1 * 4;
public static final int tdSizeOffset = 0;
public static final int tdClassNameAddrOffset = 1 * 4;
public static final int tdBaseClass0Offset = 2 * 4;
public static final int tdConstantSize = 3 * 4;
public static final int tblkConstantSize = 8 * 4;
//public static final int tdSizeForArrays = 5 * 4;
// System table:
public static final int stStackOffset = 1 * 4;
public static final int stHeepOffset = 2 * 4;
public static final int stKernelClinitAddr = 3 * 4;
public static final int stConstantSize = 8 * 4;
// String pool:
public static final int stringHeaderConstSize = 3 * 4; // byte
public static final int spTagIndex = 1;
public static final int spTagOffset = spTagIndex * 4;
public static int stringHeaderSize = -1; // byte
public static Class stringClass;
// Error reporter and stdout:
private static final ErrorReporter reporter = ErrorReporter.reporter;
private static PrintStream vrb = StdStreams.vrb;
// Target image
public static TargetMemorySegment targetImage;
// System table
private static int systemTableSize;
private static BlockItem systemTable;
private static Segment[] sysTabSegments;
// Global constants
private static BlockItem globalConstantTable;
private static int globalConstantTableOffset = -1;
private static Segment globalConstantTableSegment;
public static void init() {
if(dbg) vrb.println("[LINKER] START: Initializing:");
if(dbg) vrb.print(" Setting size of string header: ");
stringHeaderSize = stringHeaderConstSize + Type.wktObject.getObjectSize();
if(dbg) vrb.println(stringHeaderSize + " byte");
if(dbg) vrb.println(" Looking for segments for the system table: ");
sysTabSegments = Configuration.getSysTabSegments();
if(sysTabSegments != null && sysTabSegments.length > 0) {
if(dbg) {
for(int i = 0; i < sysTabSegments.length; i++) {
vrb.println(" -> found: " + sysTabSegments[i].getName());
}
}
}
else {
reporter.error(702, "No segment(s) for the systemtable defined!");
}
if(dbg) vrb.println(" Deleting old target image... ");
targetImage = null;
if(dbg) vrb.println("[LINKER] END: Initializing.\n");
}
public static void createConstantBlock(Class clazz) {
if(dbg) vrb.println("[LINKER] START: Preparing constant block for class \"" + clazz.name +"\":");
// Header
if(dbg) vrb.println(" Creating header");
clazz.constantBlock = new FixedValueItem("constBlockSize");
clazz.codeBase = new FixedValueItem("codeBase");
clazz.codeBase.append(new FixedValueItem("codeSize"));
clazz.constantBlock.append(clazz.codeBase);
clazz.varBase = new FixedValueItem("varBase");
clazz.varBase.append(new FixedValueItem("varSize"));
clazz.constantBlock.append(clazz.varBase);
Method classConstructor = clazz.getClassConstructor();
if(classConstructor != null) {
clazz.constantBlock.append(new AddressItem(classConstructor));
}
else {
clazz.constantBlock.append(new FixedValueItem("<clinit>", -1));
}
// Pointer list
if(dbg) vrb.println(" Creating pointer list");
clazz.ptrList = new FixedValueItem("nofPtrs");
int ptrCounter = 0;
if(clazz.nofClassRefs > 0) {
Item field = clazz.classFields;
while(field != null) {
if((field.accAndPropFlags & (1 << dpfConst)) == 0 && (field.accAndPropFlags & (1 << apfStatic)) != 0 && (((Type)field.type).category == tcRef || ((Type)field.type).category == tcArray )) {
clazz.ptrList.append(new AddressItem(field));
ptrCounter++;
}
field = field.next;
}
assert ptrCounter == clazz.nofClassRefs : "[Error] Number of added pointers (" + ptrCounter + ") not equal to number of pointers in class (" + clazz.nofClassRefs + ")!";
}
((FixedValueItem)clazz.ptrList).setValue(ptrCounter);
clazz.constantBlock.append(clazz.ptrList);
// Type descriptor: size and extension level
if(dbg) vrb.println(" Creating type descriptor");
if(dbg) vrb.println(" - Beginning with size");
clazz.typeDescriptor = new FixedValueItem("size");
if(dbg) vrb.println(" - Inserting the extension level");
clazz.typeDescriptor.insertBefore(new FixedValueItem("extensionLevel", clazz.extensionLevel));
// Type descriptor: create method table
// Item cm;
if(dbg) vrb.println(" - Inserting method table:");
/* for(int i = 0; i < clazz.methTabLength; i++) {
cm = clazz.getMethod(i);
assert cm != null : "[Error] No method with index " + i + " found!";
if(dbg) vrb.println(" > " + cm.name);
clazz.typeDescriptor.getHead().insertBefore(new AddressItem(cm));
}*/
for(int i = 0; i < clazz.methTabLength; i++) {
clazz.typeDescriptor.getHead().insertBefore(new AddressItem(clazz.extMethTable[i]));
}
// Type descriptor: insert class name address
if(dbg) vrb.println(" - Inserting class name address");
clazz.typeDescriptor.insertAfter(new FixedValueItem("classNameAddr", 0x12345678));
// Type descriptor: create type table (base classes and interfaces)
// if(dbg) vrb.println(" - Inserting base classes and interfaces");
// int typeTableSize = 1;
// Class baseClass = (Class)clazz.type;
// AddressItem typeTable = new AddressItem(clazz);
// while(baseClass != null) {
// typeTable.getHead().insertBefore(new AddressItem(baseClass));
// typeTableSize++;
// baseClass = (Class)baseClass.type;
// AddressItem currentElement = (AddressItem)typeTable.getTail();
// Class currentClass;
// while(currentElement != null) {
// currentClass = (Class)currentElement.itemRef;
// for(int i = 0; i < currentClass.nofInterfaces; i++) {
// currentElement.insertAfter(new AddressItem(currentClass.interfaces[i]));
// typeTableSize++;
// currentElement = (AddressItem)currentElement.prev;
// while(typeTableSize < Class.maxExtensionLevelStdClasses * 2 + 1) { // TODO @Martin: This works only for a few cases -> improve this
// typeTable.append(new FixedValueItem("padding", 0));
// typeTableSize++;
if(dbg) vrb.println(" - Inserting base classes");
Class baseClass = (Class)clazz.type;
AddressItem typeTable = new AddressItem(clazz);
for(int i = 0; i < Class.maxExtensionLevelStdClasses; i++) {
if(baseClass != null) {
typeTable.getHead().insertBefore(new AddressItem(baseClass));
baseClass = (Class)baseClass.type;
}
else {
typeTable.getTail().insertAfter(new FixedValueItem("padding", 0));
}
}
clazz.typeDescriptor.append(typeTable.getHead());
// Type descriptor: add interface table
if(clazz.extMethTable.length > clazz.methTabLength) {
if(dbg) vrb.println(" - Inserting interface table");
int counter = clazz.methTabLength;
if(dbg) vrb.println(" + clazz.extMethTable[" + counter + "]: " + clazz.extMethTable[counter].name);
AddressItem interfaceTable = new AddressItem(clazz.extMethTable[counter++]);
int id, bmo;
//vrb.println(" ==> ifaceTAbLength = " + clazz.ifaceTabLength + "; nofInterfaces = " + clazz.nofInterfaces);
while(counter < clazz.extMethTable.length && (clazz.extMethTable[counter].index >>> 16) >= 0) {
// id = clazz.extMethTable[counter].index >>> 16;
// bmo = clazz.extMethTable[counter].index & 0xFFFF;
// if(bmo > clazz.methTabLength) {
// bmo = -bmo * 4; // TODO @Martin: fix offset (bmo = -(maxExtensionLevelStdClass + 4 + ifaceTabLength + 4 * bmo))
// else {
// bmo = tdMethTabOffset + bmo * 4;
id = 0;
bmo = 0;
if(dbg) vrb.println(" + clazz.extMethTable[" + counter + "]: ID = " + id + "; bmo = " + bmo);
interfaceTable.append(new InterfaceItem(clazz.extMethTable[counter].owner.name, (short)id, (short)bmo));
counter++;
}
while(counter < clazz.extMethTable.length) {
interfaceTable.append(new AddressItem(clazz.extMethTable[counter++]));
}
clazz.typeDescriptor.append(interfaceTable.getHead());
}
// calculate type descriptor size
clazz.typeDescriptorSize = clazz.typeDescriptor.getBlockSize();
// add type descriptor to constant block
clazz.constantBlock.append(clazz.typeDescriptor.getHead());
// create string pool
if(dbg) vrb.println(" Creating string pool");
if(clazz.constPool != null) {
Item cpe;
for(int i = 0; i < clazz.constPool.length; i++) {
cpe = clazz.constPool[i];
if(cpe.type == Type.wellKnownTypes[txString] && (cpe.accAndPropFlags & (1 << dpfConst)) != 0) { // TODO @Martin is checking the const flag necessary?
if(clazz.stringPool == null) clazz.stringPool = new StringItem(cpe);
else clazz.stringPool.append(new StringItem(cpe));
}
}
}
if(clazz.stringPool != null) {
clazz.stringPoolSize = clazz.stringPool.getBlockSize();
clazz.constantBlock.append(clazz.stringPool);
}
// create constant pool
if(dbg) vrb.println(" Creating constant pool");
if(clazz.constPool != null) {
Item cpe;
for(int i = 0; i < clazz.constPool.length; i++) {
cpe = clazz.constPool[i];
if(checkConstantPoolType(cpe)) {
if(clazz.constantPool == null) clazz.constantPool = new ConstantItem(cpe);
else clazz.constantPool.append(new ConstantItem(cpe));
}
}
}
if(clazz.constantPool != null) {
clazz.constantPoolSize = clazz.constantPool.getBlockSize();
clazz.constantBlock.append(clazz.constantPool);
}
// calculate checksum
if(dbg) vrb.println(" Calculating checksum");
clazz.constantBlockChecksum = new FixedValueItem("fcs", 0); // TODO @Martin calculate checksum here...
clazz.constantBlock.append(clazz.constantBlockChecksum);
// Calculating size of constant block
((FixedValueItem)clazz.constantBlock).setValue(clazz.constantBlock.getBlockSize());
// Calculating indexes and offsets for the string- and constant pool
int offset, index;
if(clazz.stringPool != null) {
if(dbg) vrb.println(" Calculating indexes and offsets for the string pool entries");
BlockItem s = clazz.stringPool;
offset = 0; index = 0;
while(s != clazz.constantPool && s != clazz.constantBlockChecksum) {
((StringItem)s).setIndex(index);
((StringItem)s).setOffset(offset);
index++;
offset += s.getItemSize();
s = s.next;
}
}
if(clazz.constantPool != null) {
if(dbg) vrb.println(" Calculating indexes and offsets for the constant pool entries");
BlockItem c = clazz.constantPool;
offset = 0; index = 0;
while(c != clazz.constantBlockChecksum) {
((ConstantItem)c).setIndex(index);
((ConstantItem)c).setOffset(offset);
index++;
offset += c.getItemSize();
c = c.next;
}
}
// Calculating type descriptor offset
BlockItem i = clazz.constantBlock;
offset = 0;
while(i != clazz.typeDescriptor) {
offset += i.getItemSize();
i = i.next;
}
clazz.typeDescriptorOffset = offset;
if(dbg) vrb.println("\n[LINKER] END: Preparing constant block for class \"" + clazz.name +"\"\n");
}
public static void createTypeDescriptor(Array array) {
if(dbg) vrb.println("[LINKER] START: Creating type descriptor for array \"" + array.name +"\":");
if(dbg) vrb.println(" Element type: " + array.componentType.name);
if(dbg) vrb.println(" Element size: " + array.componentType.sizeInBits / 8 + " byte (" + array.componentType.sizeInBits + " bit)");
if(dbg) vrb.println(" Dimension: " + array.dimension);
// Extentsion level
array.typeDescriptor = new FixedValueItem("extensionLevel", 1); // the base type of an array is always object!
// Array dimension, component size and array type flag
byte arrayOfPrimitives = 0;
if(array.componentType.category == tcPrimitive) arrayOfPrimitives = 1;
array.typeDescriptor.append(new FixedValueItem("dimension/size", ((arrayOfPrimitives << 31) | array.dimension << 16) | (array.componentType.sizeInBits / 8)));
// Array name address
array.typeDescriptor.append(new FixedValueItem("arrayNameAddr", 0x12345678));
// List of type descriptors of arrays with the same component type
String arrayName; Item lowDimArray;
for(int i = array.dimension; i > 0; i
arrayName = array.name.substring(array.dimension - i).toString();
lowDimArray = Type.classList.getItemByName(arrayName);
if(lowDimArray != null) {
array.typeDescriptor.append(new AddressItem("arrayTD[" + i + "]: ", lowDimArray));
}
else {
array.typeDescriptor.append(new FixedValueItem("arrayTD[" + i + "]: <not available> (" + arrayName + ")", -1));
// TODO @Martin: insert warning or error!
}
}
// Component type
if(array.componentType.category == tcPrimitive) {
array.typeDescriptor.append(new FixedValueItem("arrayComponentTD: <primitive> (" + array.componentType.name + ")", 0));
}
else {
array.typeDescriptor.append(new AddressItem("arrayComponentTD: ", array.componentType));
}
if(dbg) vrb.println("[LINKER] END: Creating type descriptor for array \"" + array.name +"\"\n");
}
public static void createGlobalConstantTable() {
if(dbg) vrb.println("[LINKER] START: Creating global constant table:\n");
int offset = 0, index = 0;
ConstantItem constant = (ConstantItem)globalConstantTable;
while(constant != null) {
constant.setIndex(index);
constant.setOffset(offset);
constant.setAddress(globalConstantTableSegment.getBaseAddress() + globalConstantTableOffset + offset);
index++;
offset += constant.getItemSize();
constant = (ConstantItem)constant.next;
}
if(dbg) vrb.println("[LINKER] END: Creating global constant table\n");
}
public static void calculateCodeSizeAndOffsets(Class clazz) {
if(dbg) vrb.println("[LINKER] START: Calculating code size for class \"" + clazz.name +"\":\n");
// machine code size
if(dbg) vrb.print(" 1) Code:");
Method m = (Method)clazz.methods;
int codeSize = 0; // machine code size for the hole class
while(m != null) {
if(m.machineCode != null) {
if(m.offset < 0) { // offset not given by configuration
m.offset = codeSize;
codeSize += m.machineCode.iCount * 4; // iCount = number of instructions!
}
else { // offset given by configuration
if(codeSize < m.machineCode.iCount * 4 + m.offset) codeSize = m.offset + m.machineCode.iCount * 4;
}
if(dbg) vrb.println(" > " + m.name + ": codeSize = " + m.machineCode.iCount * 4 + " byte");
}
m = (Method)m.next;
}
((FixedValueItem)clazz.codeBase.next).setValue(codeSize);
if(dbg) vrb.println(" Total code size: " + codeSize + " byte");
if(dbg) vrb.println("\n[LINKER] END: Calculating code size for class \"" + clazz.name +"\"\n");
}
public static void createSystemTable() {
if(dbg) vrb.println("[LINKER] START: Create system table:\n");
// Number of stacks, heaps and classes
int nofStacks = Configuration.getNumberOfStacks();
int nofHeaps = Configuration.getNumberOfHeaps();
if(dbg) vrb.println(" Number of stacks: " + nofStacks);
if(dbg) vrb.println(" Number of heaps: " + nofHeaps);
if(dbg) vrb.println(" Number of classes: " + Type.nofClasses);
// Find the kernel
HString kernelClassName = Configuration.getKernelClassname();
if(kernelClassName == null) {
kernelClassName = HString.getHString("<undefined>");
reporter.error(740, "kernel class not set");
}
Item kernelClass = Type.classList.getItemByName(kernelClassName.toString());
Item kernelClinit = null;
int kernelClinitAddr = -1;
if(kernelClass != null) {
kernelClinit = ((Class)kernelClass).getClassConstructor();
if(kernelClinit != null) {
kernelClinitAddr = kernelClinit.address;
}
else {
reporter.error(730, kernelClassName.toString() + ".<clinit>");
}
}
else {
reporter.error(702, kernelClassName.toString());
}
if(dbg) vrb.println(" Kernel class: " + kernelClass.name);
if(dbg) vrb.println(" -> Clinit Addr.: " + kernelClinitAddr);
// Create the system table
systemTable = new FixedValueItem("classConstOffset", (7 + 2 * nofStacks + 2 * nofHeaps) * 4);
systemTable.append(new FixedValueItem("stackOffset", 5));
systemTable.append(new FixedValueItem("heapOffset", 5 + 2 * nofStacks));
systemTable.append(new AddressItem("kernelClinitAddr: " + kernelClassName + ".",kernelClinit));
systemTable.append(new FixedValueItem("nofStacks", nofStacks));
for(int i = 0; i < nofStacks; i++) { // reference to each stack and the size of each stack
systemTable.append(new AddressItem("baseStack" + i + ": ", Configuration.getStackSegments()[i])); // base address
systemTable.append(new FixedValueItem("sizeStack" + i, Configuration.getStackSegments()[i].getSize()));
}
systemTable.append(new FixedValueItem("nofHeaps", nofHeaps));
for(int i = 0; i < nofHeaps; i++) { //reference to each heap and the size of each heap
systemTable.append(new AddressItem("baseHeap" + i + ": ", Configuration.getHeapSegments()[i])); // base address
systemTable.append(new FixedValueItem("sizeHeap" + i, Configuration.getHeapSegments()[i].getSize()));
}
systemTable.append(new FixedValueItem("nofClasses", Class.nofInitClasses + Class.nofNonInitClasses));
Class clazz = Class.initClasses; int i = 0;
while(clazz != null) { // reference to the constant block of each class with a class constructor (clinit)
if( clazz instanceof Class && ((clazz.accAndPropFlags & (1 << apfInterface)) == 0)) {
systemTable.append(new ConstantBlockItem("constBlkBaseClass" + i + ": ", clazz));
i++;
}
clazz = clazz.nextClass;
}
clazz = Class.nonInitClasses;
while(clazz != null) { // reference to the constant block of each class without a class constructor (no clinit)
if( clazz instanceof Class && ((clazz.accAndPropFlags & (1 << apfInterface)) == 0)) {
systemTable.append(new ConstantBlockItem("constBlkBaseClass" + i + ": ", clazz));
i++;
}
clazz = clazz.nextClass;
}
systemTable.append(new FixedValueItem("endOfSystemTable", 0));
systemTableSize = systemTable.getBlockSize();
if(dbg) vrb.println(" Size of the system table: " + systemTableSize + " byte (0x" + Integer.toHexString(systemTableSize) + ")");
if(dbg) vrb.println("[LINKER] END: Create system table.\n");
}
public static void freezeMemoryMap() {
if(dbg) vrb.println("[LINKER] START: Freeze memory map:\n");
// 1) Set a segment for the code, the static fields and the constant block for each class
Item item = Type.classList;
Segment s;
while(item != null) {
// Code
if(item instanceof Class && ((item.accAndPropFlags & (1 << apfInterface)) == 0)){
Class c = (Class)item;
s = Configuration.getCodeSegmentOf(c.name);
if(dbg) vrb.println(" Proceeding Class " + c.name);
if(s == null) reporter.error(710, "Can't get a memory segment for the code of class " + c.name + "!\n");
else {
int codeSize = ((FixedValueItem)c.codeBase.next).getValue();
if(s.subSegments != null) s = getFirstFittingSegment(s.subSegments, atrCode, codeSize);
c.codeOffset = s.getUsedSize();
if(codeSize > 0) s.addToUsedSize(roundUpToNextWord(codeSize));
c.codeSegment = s;
if(dbg) {
vrb.println(" Code-Segment: " + c.codeSegment.getName());
vrb.println(" Code-Offset: " + Integer.toHexString(c.codeOffset));
}
}
// Var
s = Configuration.getVarSegmentOf(c.name);
if(s == null) reporter.error(710, "Can't get a memory segment for the static variables of class " + c.name + "!\n");
else {
if(s.subSegments != null) s = getFirstFittingSegment(s, atrVar, c.classFieldsSize);
c.varOffset = s.getUsedSize();
if(c.classFieldsSize > 0) s.addToUsedSize(roundUpToNextWord(c.classFieldsSize));
c.varSegment = s;
if(dbg) vrb.println(" Var-Segment: " + c.varSegment.getName());
}
// Const
s = Configuration.getConstSegmentOf(c.name);
if(s == null) reporter.error(710, "Can't get a memory segment for the constant block of class " + c.name + "!\n");
else {
int constBlockSize = ((FixedValueItem)c.constantBlock).getValue();
if(s.subSegments != null) s = getFirstFittingSegment(s, atrConst, constBlockSize);
c.constOffset = s.getUsedSize();
if(constBlockSize > 0) s.addToUsedSize(roundUpToNextWord(constBlockSize));
c.constSegment = s;
if(dbg) vrb.println(" Const-Segment: " + c.constSegment.getName());
}
}
else if(item instanceof Array) {
Array a = (Array)item;
s = Configuration.getDefaultConstSegment();
if(dbg) vrb.println(" Proceeding Array " + a.name);
if(s == null) reporter.error(710, "Can't get a memory segment for the typedecriptor of array " + a.name + "!\n");
else {
if(s.subSegments != null) s = getFirstFittingSegment(s, atrConst, a.typeDescriptor.getBlockSize());
a.offset = roundUpToNextWord(s.getUsedSize()); // TODO check if this is correct!!!
s.addToUsedSize(a.typeDescriptor.getBlockSize());
a.segment = s;
if(dbg) vrb.println(" Segment for type descriptor: " + a.segment.getName());
}
}
else {
if(dbg) vrb.println("+++++++++++++++ The following item in classlist is neither a class nor an array: " + item.name); // it should be an interface...
}
item = item.next;
}
//Segment[] sysTabs = Configuration.getSysTabSegments(); // TODO @Martin: implement this for more than one system table!
if(sysTabSegments != null && sysTabSegments.length > 0) {
for(int i = 0; i < sysTabSegments.length; i++) {
sysTabSegments[i].addToUsedSize(systemTableSize);
}
}
else reporter.error(710, "No segment(s) defined for the system table!");
s = Configuration.getDefaultConstSegment();
if(dbg) vrb.println(" Proceeding global constant table");
if(s == null) reporter.error(710, "Can't get a memory segment for the global constant table!\n");
else {
if(s.subSegments != null) s = getFirstFittingSegment(s, atrConst, globalConstantTable.getBlockSize());
globalConstantTableOffset = roundUpToNextWord(s.getUsedSize());
s.addToUsedSize(globalConstantTable.getBlockSize());
globalConstantTableSegment = s;
if(dbg) vrb.println(" Segment for global constant table: " + globalConstantTableSegment.getName());
}
// 2) Check and set the size for each used segment
Device d = Configuration.getFirstDevice();
while(d != null) {
if(d.lastSegment != null) setSegmentSize(d.lastSegment);
d = d.next;
}
// 3) Set base addresses for each used segment
d = Configuration.getFirstDevice();
//usedSegments = new Segment[nOfUsedSegments];
while(d != null) {
if(dbg) vrb.println("Start setting base addresses for segments in device \"" + d.getName() +"\":");
//StdStreams.vrb.println("Device: " + d.getName() + "\n");
if(d.segments != null) setBaseAddress(d.segments, d.getbaseAddress());
if(dbg) vrb.println("End setting base addresses for segments in device \"" + d.getName() +"\":\n");
d = d.next;
}
if(dbg) vrb.println("[LINKER] END: Freeze memory map.");
}
public static void calculateAbsoluteAddresses(Class clazz) {
if(dbg) vrb.println("\n[LINKER] START: Calculating absolute addresses for class \"" + clazz.name +"\":\n");
int varBase = clazz.varSegment.getBaseAddress() + clazz.varOffset;
int codeBase = clazz.codeSegment.getBaseAddress() + clazz.codeOffset;
int constBlockBase = clazz.constSegment.getBaseAddress() + clazz.constOffset;
int classDescriptorBase = constBlockBase + cblkNofPtrsOffset + (clazz.nofClassRefs + 1) * slotSize;
int stringPoolBase = classDescriptorBase + clazz.typeDescriptorSize;
int constPoolBase = stringPoolBase + clazz.stringPoolSize;
if(dbg) {
vrb.println(" Code base: 0x" + Integer.toHexString(codeBase));
vrb.println(" Var base: 0x" + Integer.toHexString(varBase));
vrb.println(" Const segment base address: 0x" + Integer.toHexString(clazz.constSegment.getBaseAddress()));
vrb.println(" Const offset: 0x" + Integer.toHexString(clazz.constOffset));
vrb.println(" Const block base address: 0x" + Integer.toHexString(constBlockBase));
vrb.println(" Number of class refereces: " + clazz.nofClassRefs);
vrb.println(" Class descriptor base: 0x" + Integer.toHexString(classDescriptorBase));
vrb.println(" String pool base: 0x" + Integer.toHexString(stringPoolBase));
vrb.println(" Const pool base: 0x" + Integer.toHexString(constPoolBase));
}
// Class/static fields
if(clazz.nofClassFields > 0) {
Item field = clazz.classFields; // class fields and constant fields
if(dbg) vrb.println(" Static fields:");
while(field != null) {
if((field.accAndPropFlags & (1 << dpfConst)) != 0) { // constant field // TODO @Martin If-Teil sollte eigentlich ueberhaupt nicht notwendig sein, da konstante Referenzen das Const-Flag gar nicht gesetzt haben -> If-Teil entfernen?
if(((Type)field.type).category == tcRef) { // reference but not literal string
if(varBase != -1 && field.offset != -1) field.address = varBase + field.offset;
}
}
else { // non constant field -> var section
if(varBase != -1 && field.offset != -1) field.address = varBase + field.offset;
else {
if(varBase == -1) reporter.error(724, "varBase of class " + clazz.name + " not set");
if(field.offset == -1) reporter.error(721, "offset of field " + field.name + " in class " + clazz.name + " not set!");
}
}
if(dbg) vrb.print(" > " + field.name + ": Offset = 0x" + Integer.toHexString(field.offset) + ", Index = 0x" + Integer.toHexString(field.index) + ", Address = 0x" + Integer.toHexString(field.address) + "\n");
field = field.next;
}
}
// Methods
if(clazz.nofMethods > 0) {
Method method = (Method)clazz.methods;
if(dbg) vrb.println(" Methods:");
while(method != null) {
if((method.accAndPropFlags & (1 << dpfExcHnd)) != 0) { // TODO @Martin: fix this hack!!!
if(method.offset != -1) method.address = clazz.codeSegment.getBaseAddress() + method.offset;
// else reporter.error(9999, "Error while calculating absolute address of fix set method " + method.name + ". Offset: " + method.offset + ", Segment: " + clazz.codeSegment.getName() + ", Base address of Segment: " + clazz.codeSegment.getBaseAddress());
}
else {
if(codeBase != -1 && method.offset != -1) method.address = codeBase + method.offset;
// else reporter.error(9999, "Error while calculating absolute address of method " + method.name + ". Offset: " + method.offset + ", Codebase of Class " + clazz.name + ": " + codeBase);
}
if(dbg) vrb.print(" > " + method.name + ": Offset = 0x" + Integer.toHexString(method.offset) + ", Index = 0x" + Integer.toHexString(method.index) + ", Address = 0x" + Integer.toHexString(method.address) + "\n");
method = (Method)method.next;
}
}
// Constants
if(clazz.constPool != null && clazz.constPool.length > 0) {
Item cpe;
if(dbg) vrb.println(" Constant pool:");
for(int i = 0; i < clazz.constPool.length; i++) {
cpe = clazz.constPool[i];
if(cpe instanceof StdConstant && (cpe.type == Type.wellKnownTypes[txFloat] || cpe.type == Type.wellKnownTypes[txDouble])) { // constant float or double value -> constant pool
if(cpe.offset != -1) cpe.address = constPoolBase + cpe.offset;
else reporter.error(721, "Class pool entry #" + i + " (" + cpe.type.name + ")");
}
else if(cpe instanceof StringLiteral) { // string literal -> string pool
if(cpe.offset != -1) cpe.address = stringPoolBase + cpe.offset + 8;
else reporter.error(721, "Class pool entry #" + i + " (" + cpe.type.name + ")");
}
if(dbg) {
if(cpe.type != null) vrb.print(" - #" + i + ": Type = " + cpe.type.name + ", Offset = 0x" + Integer.toHexString(cpe.offset) + ", Index = 0x" + Integer.toHexString(cpe.index) + ", Address = 0x" + Integer.toHexString(cpe.address) + "\n");
else vrb.print(" - #" + i + ": Type = <unknown>, Offset = 0x" + Integer.toHexString(cpe.offset) + ", Index = 0x" + Integer.toHexString(cpe.index) + ", Address = 0x" + Integer.toHexString(cpe.address) + "\n");
}
}
}
// type descriptor
clazz.address = clazz.constSegment.getBaseAddress() + clazz.constOffset + clazz.typeDescriptorOffset;
if(dbg) vrb.println("\n[LINKER] END: Calculating absolute addresses for class \"" + clazz.name +"\"\n");
}
public static void calculateAbsoluteAddresses(Array array) {
// TODO@Martin: merge this with calculateAbsoluteAddresses(Class clazz)
array.address = array.segment.getBaseAddress() + array.offset + 4;
}
public static void updateConstantBlock(Class clazz) {
if(dbg) vrb.println("[LINKER] START: Updating constant block for class \"" + clazz.name +"\":\n");
if(dbg) vrb.println(" Inserting code base");
((FixedValueItem)clazz.codeBase).setValue(clazz.codeSegment.getBaseAddress() + clazz.codeOffset); // codeBase
// codeSize already set...
if(dbg) vrb.println(" Inserting var base");
((FixedValueItem)clazz.varBase).setValue(clazz.varSegment.getBaseAddress() + clazz.varOffset); // varBase
if(dbg) vrb.println(" Inserting var size");
((FixedValueItem)clazz.varBase.next).setValue(clazz.classFieldsSize); // varSize
if(dbg) vrb.println(" Inserting object size");
((FixedValueItem)clazz.typeDescriptor).setValue(clazz.objectSize); // size
if(dbg) vrb.println("\n[LINKER] END: Updating constant block for class \"" + clazz.name +"\"\n");
}
public static void generateTargetImage() {
if(dbg) vrb.println("[LINKER] START: Generating target image:\n");
Item item = Type.classList;
Method m;
while(item != null) {
if (item instanceof Class && ((item.accAndPropFlags & (1 << apfInterface)) == 0)) {
Class clazz = (Class)item;
if(dbg) vrb.println(" Proceeding class \"" + clazz.name + "\":");
// code
m = (Method)clazz.methods;
if(dbg) vrb.println(" 1) Code:");
while(m != null) {
if(m.machineCode != null) {
if(dbg) vrb.println(" > Method \"" + m.name + "\":");
addTargetMemorySegment(new TargetMemorySegment(clazz.codeSegment, m.address, m.machineCode.instructions, m.machineCode.iCount));
}
m = (Method)m.next;
}
// consts
if(dbg) vrb.println(" 2) Constantblock:");
addTargetMemorySegment(new TargetMemorySegment(clazz.constSegment, clazz.constSegment.getBaseAddress() + clazz.constOffset, clazz.constantBlock));
}
else if(item instanceof Array){
Array array = (Array)item;
if(dbg) vrb.println(" Proceeding array \"" + array.name + "\":");
addTargetMemorySegment(new TargetMemorySegment(array.segment, array.segment.getBaseAddress() + array.offset, array.typeDescriptor));
}
item = item.next;
}
if(dbg) vrb.println(" Proceeding system table(s):");
Segment[] s = Configuration.getSysTabSegments();
if(dbg) vrb.println(" > Address: 0x" + Integer.toHexString(s[0].getBaseAddress()));
for(int i = 0; i < sysTabSegments.length; i++) {
addTargetMemorySegment(new TargetMemorySegment(s[i], s[i].getBaseAddress(), systemTable)); // TODO@Martin: Implement additive system table for ram/flash boot
}
if(dbg) vrb.println(" Proceeding global constant table:");
addTargetMemorySegment(new TargetMemorySegment(globalConstantTableSegment, globalConstantTableSegment.getBaseAddress() + globalConstantTableOffset, globalConstantTable));
if(dbg) vrb.println("[LINKER] END: Generating target image\n");
}
public static void writeTargetImageToFile(String fileName) throws IOException {
if(dbg) vrb.println("[LINKER] START: Writing target image to file: \"" + fileName +"\":\n");
FileOutputStream timFile = new FileOutputStream(fileName); // TODO @Martin: use DataOutputStream!
timFile.write("#dtim-0\n".getBytes()); // Header (8 Byte)
TargetMemorySegment tms = targetImage;
int i = 0;
while(tms != null) {
if(dbg) vrb.println("TMS #" + i + ": Startaddress = 0x" + Integer.toHexString(tms.startAddress) + ", Size = 0x" + Integer.toHexString(tms.data.length * 4));
timFile.write(getBytes(tms.startAddress));
timFile.write(getBytes(tms.data.length*4));
for(int j = 0; j < tms.data.length; j++) {
timFile.write(getBytes(tms.data[j]));
}
i++;
tms = tms.next;
}
timFile.close();
if(dbg) vrb.println("[LINKER] END: Writing target image to file.\n");
}
public static void writeCommandTableToFile(String fileName) throws IOException {
if(dbg) vrb.println("[LINKER] START: Writing command table to file: \"" + fileName +"\":\n");
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date buildTime = new Date();
BufferedWriter tctFile = new BufferedWriter(new FileWriter(fileName));
tctFile.write("#dtct-0\n");
tctFile.write("#File created: " + f.format(buildTime));
tctFile.write("\n\n");
DataItem cmdAddrField;
int cmdAddr = -1;
Class kernel = (Class)Type.classList.getItemByName(Configuration.getKernelClassname().toString());
if(kernel != null) {
if(dbg) vrb.println(" Kernel: " + kernel.name);
cmdAddrField = (DataItem)kernel.classFields.getItemByName("cmdAddr");
if(cmdAddrField != null) {
if(dbg) vrb.println(" cmdAddrField: " + cmdAddrField.name + "@" + cmdAddrField.address);
cmdAddr = cmdAddrField.address;
}
else reporter.error(790, "Field cmdAddrField in the Kernel not set");
}
else reporter.error(701, "Kernel (" + Configuration.getKernelClassname() + ")");
tctFile.write("cmdAddr@");
tctFile.write(String.valueOf(cmdAddr));
tctFile.write("\n\n");
Item clazz = Type.classList;
Method method;
while(clazz != null) {
if(clazz instanceof Class) {
if(dbg) vrb.println(" Proceeding class \"" + clazz.name + "\"");
method = (Method)((Class)clazz).methods;
tctFile.write('>');
tctFile.write(clazz.name.toString());
tctFile.write('@');
tctFile.write(String.valueOf(clazz.address));
tctFile.write(" {\n");
while(method != null) {
if((method.accAndPropFlags & (1 << dpfCommand)) != 0) {
if(dbg) vrb.println("\t\"" + method.name + "\" added");
tctFile.write("\t!");
tctFile.write(method.name.toString());
tctFile.write('@');
tctFile.write(String.valueOf(method.address));
tctFile.write('\n');
}
method = (Method)method.next;
}
tctFile.write("}\n\n");
}
clazz = clazz.next;
}
tctFile.close();
vrb.println("Command table written to \"" + fileName + "\"");
if(dbg) vrb.println("[LINKER] END: Writing command table to file.");
}
public static void addGlobalConstant(StdConstant gconst) {
if(globalConstantTable == null) {
globalConstantTable = new ConstantItem(gconst);
}
else {
globalConstantTable.append(new ConstantItem(gconst));
}
}
private static byte[] getBytes(int number) {
byte[] barray = new byte[4];
for (int i = 0; i < 4; ++i) {
int shift = i << 3;
barray[3-i] = (byte)((number & (0xff << shift)) >>> shift);
}
return barray;
}
private static void setBaseAddress(Segment s, int baseAddress) {
//descend
if(s.subSegments != null) setBaseAddress(s.subSegments, baseAddress);
//set baseaddress
if((s.getSize() > 0 && s.getUsedSize() > 0) || ((s.getAttributes() & ((1 << atrStack) | (1 << atrHeap) | (1 << atrSysTab))) != 0)){
if(s.getBaseAddress() == -1) s.setBaseAddress(baseAddress);
// s.tms = new TargetMemorySegment(s.getBaseAddress(), s.getSize());
if(dbg) vrb.println("\t Segment "+s.getName() +" address = "+ Integer.toHexString(baseAddress) + ", size = " + s.getSize());
}
// traverse from left to right
if(s.next != null) setBaseAddress(s.next, s.getSize()+ baseAddress);
}
private static Segment getFirstFittingSegment(Segment s, byte contentAttribute, int requiredSize) {
Segment t = s;
while(t != null) {
if((t.getAttributes() & (1 << contentAttribute)) != 0) {
if(t.subSegments != null) t = getFirstFittingSegment(t.subSegments, contentAttribute, requiredSize);
if(t.getSize() <= 0 || t.getSize() - t.getUsedSize() > requiredSize) return t;
}
t = t.next;
}
return null;
}
private static void setSegmentSize(Segment s) {
if(s.lastSubSegment != null) {
setSegmentSize(s.lastSubSegment);
}
if(s.getSize() <= 0) {
s.setSize(roundUpToNextWord(s.getUsedSize()));
}
else if(s.getSize() < s.getUsedSize()) {
reporter.error(711, "Segment " + s.getName() + " is too small! Size is manually set to " + s.getSize() + " byte, but required size is " + s.getUsedSize() + " byte!\n");
}
// StdStreams.vrb.println(" Segment " + s.getName() + ": size = " + s.getSize() + "byte!\n");
if(s.prev != null) {
setSegmentSize(s.prev);
}
}
protected static int roundUpToNextWord(int val) {
return (val + (slotSize - 1)) & -slotSize;
}
private static void addTargetMemorySegment(TargetMemorySegment tms) {
if(targetImage == null) {
if(dbg) vrb.println(" >>>> Adding target memory segment #" + tms.id);
targetImage = tms;
}
else {
TargetMemorySegment current = targetImage;
if(current.startAddress < tms.startAddress) {
while(current.next != null && tms.startAddress > current.next.startAddress) {
current = current.next;
}
tms.next = current.next;
current.next = tms;
}
else {
tms.next = current;
targetImage = tms;
}
}
}
private static boolean checkConstantPoolType(Item item) {
// TODO @Martin: Make this configurable...
return item instanceof StdConstant && ((item.type == Type.wellKnownTypes[txFloat] || item.type == Type.wellKnownTypes[txDouble]));
}
private static int getNofInterfacesWithMethods(Class c) {
int counter = 0;
Class baseClass = (Class)c.type;
while(baseClass != null) {
counter += getNofInterfacesWithMethods(baseClass);
baseClass = (Class)baseClass.type;
}
if(c.nofInterfaces > 0) {
for(int i = 0; i < c.interfaces.length; i++) {
if(c.interfaces[i].nofMethods > 0) counter++;
}
}
return counter;
}
// private static void extendInterfaceTable(Class c, BlockItem it) {
// Class baseClass = (Class)c.type;
// while(baseClass != null) {
// extendInterfaceTable(baseClass, it);
// baseClass = (Class)baseClass.type;
// if(c.interfaces != null && c.interfaces.length > 0) {
// if(dbg) vrb.println(" - Inserting interfaces:");
// for(int i = 0; i < c.interfaces.length; i++) {
// if(dbg) vrb.println(" > " + c.interfaces[i].name);
// it.getHead().insertBefore(new InterfaceItem(c.interfaces[i].name, c.interfaces[i], -1));
public static void printSystemTable() {
vrb.println("Size: " + systemTableSize + " byte");
systemTable.printList();
}
public static void printTargetImage() {
TargetMemorySegment tms = targetImage;
while(tms != null) {
vrb.print(tms);
tms = tms.next;
}
}
public static void printTargetImageSegmentList() {
vrb.println("ID\tstart address\tsize (byte)");
TargetMemorySegment tms = targetImage;
while(tms != null) {
vrb.println("#" + tms.id + "\t[" + String.format("[0x%08X]", tms.startAddress) + "]\t" + tms.data.length * 4);
tms = tms.next;
}
}
public static void printClassList() {
printClassList(true, true, true, true);
}
public static void printClassList(boolean printMethods, boolean printFields, boolean printConstantFields, boolean printConstantBlock) {
Method m;
Item f;
int cc = 0, mc = 0, fc = 0;
Item item = Type.classList;
while(item != null) {
if (item instanceof Class && ((item.accAndPropFlags & (1 << apfInterface)) == 0)) {
Class c = (Class)item;
vrb.println("CLASS: " + c.name + " (
vrb.println("Number of class methods: " + c.nofClassMethods);
vrb.println("Number of instance methods: " + c.nofInstMethods);
vrb.println("Number of class fields: " + c.nofClassFields);
vrb.println("Number of instance fields: " + c.nofInstFields);
vrb.println("Number of interfaces: " + c.nofInterfaces);
vrb.println("Number of base classes: " + c.extensionLevel);
vrb.println("Number of references: " + c.nofClassRefs);
vrb.println("Max extension level: " + Class.maxExtensionLevelStdClasses);
vrb.println("Machine code size: " + ((FixedValueItem)c.codeBase.next).getValue() + " byte");
vrb.println("Constant block size: " + ((FixedValueItem)c.constantBlock).getValue() + " byte");
vrb.println("Class fields size: " + c.classFieldsSize + " byte");
vrb.println("Code offset: 0x" + Integer.toHexString(c.codeOffset));
vrb.println("Var offset: 0x" + Integer.toHexString(c.varOffset));
vrb.println("Const offset: 0x" + Integer.toHexString(c.constOffset));
vrb.println("Code segment: " + c.codeSegment.getFullName() + " (Base address: 0x" + Integer.toHexString(c.codeSegment.getBaseAddress()) + ", size: " + c.codeSegment.getSize() + " byte)");
vrb.println("Var segment: " + c.varSegment.getFullName() + " (Base address: 0x" + Integer.toHexString(c.varSegment.getBaseAddress()) + ", size: " + c.varSegment.getSize() + " byte)");
vrb.println("Const segment: " + c.constSegment.getFullName() + " (Base address: 0x" + Integer.toHexString(c.constSegment.getBaseAddress()) + ", size: " + c.constSegment.getSize() + " byte)");
vrb.println("Type descriptor address: 0x" + Integer.toHexString(c.address));
vrb.println("Constant block base address: 0x" + Integer.toHexString(c.constSegment.getBaseAddress() + c.constOffset));
vrb.println("Code base address: 0x" + Integer.toHexString(c.codeSegment.getBaseAddress() + c.codeOffset));
vrb.println("Class field base address: 0x" + Integer.toHexString(c.varSegment.getBaseAddress() + c.varOffset));
if(printMethods) {
vrb.println("Methods:");
m = (Method)c.methods;
mc = 0;
if(m == null) vrb.println("> No methods in this class");
else {
while(m != null) {
vrb.println("> Method #" + mc++ + ": " + m.name + m.methDescriptor);
vrb.println(" Flags: 0x" + Integer.toHexString(m.accAndPropFlags));
if((m.accAndPropFlags & ((1 << dpfNew) | (1 << dpfUnsafe) | (1 << dpfSysPrimitive) | (1 << dpfSynthetic))) != 0) {
if((m.accAndPropFlags & (1 << dpfNew)) != 0) {
vrb.println(" Special: New");
}
if((m.accAndPropFlags & (1 << dpfUnsafe)) != 0) {
vrb.println(" Special: Unsafe");
}
if((m.accAndPropFlags & (1 << dpfSysPrimitive)) != 0) {
vrb.println(" Special: System primitive");
}
if((m.accAndPropFlags & (1 << dpfSynthetic)) != 0) {
vrb.println(" Special: Synthetic");
}
vrb.println(" Static: yes");
}
else {
if((m.accAndPropFlags & (1 << apfStatic)) != 0) vrb.println(" Static: yes"); else vrb.println(" Static: no");
}
vrb.println(" address: 0x" + Integer.toHexString(m.address));
vrb.println(" offset: 0x" + Integer.toHexString(m.offset));
vrb.println(" index: 0x" + Integer.toHexString(m.index));
if(m.machineCode != null)
vrb.println(" Code size: 0x" + Integer.toHexString(m.machineCode.iCount * 4) + " (" + m.machineCode.iCount * 4 +" byte)");
m = (Method)m.next;
}
}
}
if(printFields) {
vrb.println("Fields:");
f = c.instFields;
fc = 0;
if(f == null) vrb.println(" No fields in this class");
else {
while(f != null) {
if(printConstantFields || (f.accAndPropFlags & (1 << dpfConst)) == 0) { // printConstantsField || !constant
vrb.println("> Field #" + fc++ + ": " + f.name);
vrb.println(" Type: " + f.type.name);
vrb.println(" Flags: 0x" + Integer.toHexString(f.accAndPropFlags));
if((f.accAndPropFlags & (1 << apfStatic)) != 0) vrb.println(" Static: yes"); else vrb.println(" Static: no");
if((f.accAndPropFlags & (1 << dpfConst)) != 0) vrb.println(" Constant: yes"); else vrb.println(" Constant: no");
vrb.println(" address: 0x" + Integer.toHexString(f.address));
vrb.println(" offset: 0x" + Integer.toHexString(f.offset));
vrb.println(" index: 0x" + Integer.toHexString(f.index));
}
f = f.next;
}
}
}
if(printConstantBlock) {
vrb.println("Constant block:");
c.printConstantBlock();
}
vrb.println("
}
else if(item instanceof Array) {
Array a = (Array)item;
vrb.println("ARRAY: " + a.name);
vrb.println("Component type: " + a.componentType.name);
//vrb.println("Check type: " + a.checkType.name);
vrb.println("Type descriptor:");
a.typeDescriptor.printList();
vrb.println("
}
item = item.next;
}
}
public static void printGlobalConstantTable() {
vrb.println("Size: " + globalConstantTable.getBlockSize() + " byte");
globalConstantTable.printList();
}
}
|
package se.leiflandia.lroi;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.Intent;
import com.google.gson.JsonElement;
import org.apache.http.HttpStatus;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import se.leiflandia.lroi.auth.AccountAuthenticator;
import se.leiflandia.lroi.auth.ApiAuthInterceptor;
import se.leiflandia.lroi.auth.ApiAuthenticator;
import se.leiflandia.lroi.auth.model.AccessToken;
import se.leiflandia.lroi.auth.model.ChangePasswordRequest;
import se.leiflandia.lroi.auth.model.ClientCredentials;
import se.leiflandia.lroi.auth.model.ResetPassword;
import se.leiflandia.lroi.auth.model.RevocationRequest;
import se.leiflandia.lroi.auth.model.DUser;
import se.leiflandia.lroi.auth.model.UserCredentials;
import se.leiflandia.lroi.network.AuthApi;
import se.leiflandia.lroi.network.PasswordChangeFailure;
import se.leiflandia.lroi.network.PasswordResetFailure;
import se.leiflandia.lroi.network.SigninFailure;
import se.leiflandia.lroi.network.SignoutFailure;
import se.leiflandia.lroi.network.SignupFailure;
import se.leiflandia.lroi.ui.AbstractLoginActivity;
import se.leiflandia.lroi.utils.AuthUtils;
import se.leiflandia.lroi.utils.Callback;
import se.leiflandia.lroi.utils.Utils;
/**
* Class used to interface with the auth service.
*/
public class AuthAdapter {
private final AuthApi api;
private final Context applicationContext;
private final String authTokenType;
private final String accountType;
private final AccountManager accountManager;
private final ClientCredentials clientCredentials;
private final AccountAuthenticator accountAuthenticator;
private final Class<? extends AbstractLoginActivity> loginActivityClass;
public AuthAdapter(Builder builder) {
this.api = builder.api;
this.applicationContext = builder.applicationContext;
this.authTokenType = builder.authTokenType;
this.accountType = builder.accountType;
this.accountManager = builder.accountManager;
this.clientCredentials = builder.clientCredentials;
this.loginActivityClass = builder.loginActivityClass;
accountAuthenticator = new AccountAuthenticator(applicationContext, api, loginActivityClass,
authTokenType, clientCredentials, accountType);
}
/**
* Asynchronous request to sign up a new user. A signed up user might have to validate the email
* adress before signing in.
*
* @param user the user to sign in
* @param callback callback to handle success or error
*/
public void signup(final DUser user, final Callback<DUser, SignupFailure> callback) {
getApi().signup(user, new retrofit.Callback<String>() {
@Override
public void success(String id, Response response) {
callback.success(user);
}
@Override
public void failure(RetrofitError error) {
SignupFailure kind;
switch (error.getKind()) {
case NETWORK:
kind = SignupFailure.NETWORK;
break;
case HTTP:
int status = error.getResponse().getStatus();
if (status == HttpStatus.SC_CONFLICT) {
kind = SignupFailure.CONFLICT;
} else if (status == HttpStatus.SC_BAD_REQUEST) {
kind = SignupFailure.BAD_REQUEST;
} else {
kind = SignupFailure.UNEXPECTED;
}
default:
kind = SignupFailure.UNEXPECTED;
}
callback.failure(kind);
}
});
}
/**
* Asynchronous request to sign in user. This includes: 1) asynchronous network request to
* authorize at the server, then if 1 is successful 2) creating a new account in the Android
* account manager if neccessary (main thread), 3) storing the access and refresh tokens locally
* using the account manager (main thread). The refresh token is stored as the password for the
* account.
*
* @param credentials user credentials
* @param callback callback to handle success or error, supplies the user name on success.
*/
public void signin(final UserCredentials credentials, final Callback<String, SigninFailure> callback) {
getApi().authorize(credentials, new retrofit.Callback<AccessToken>() {
@Override
public void success(AccessToken token, Response response) {
AuthUtils.setAuthorizedAccount(
getApplicationContext(),
credentials,
token,
getAuthTokenType(),
getAccountType()
);
callback.success(credentials.getUsername());
}
@Override
public void failure(RetrofitError error) {
SigninFailure kind;
switch (error.getKind()) {
case NETWORK:
kind = SigninFailure.NETWORK;
break;
case HTTP:
int status = error.getResponse().getStatus();
if (status == HttpStatus.SC_BAD_REQUEST) {
kind = SigninFailure.BAD_CREDENTIALS;
} else {
kind = SigninFailure.UNEXPECTED;
}
break;
default:
kind = SigninFailure.UNEXPECTED;
}
callback.failure(kind);
}
});
}
/**
* Tries to sign out the current active account. Will always succeed except if
* failOnNetworkError is set to true, then it will fail if the network request to sign out is
* unsuccessful. Will succeed if the account is null or not exist.
*
* @param failOnNetworkError if true the sign out will be cancelled on network errors
* @param callback callback
*/
public void signout(final boolean failOnNetworkError, final Callback<Void, SignoutFailure> callback) {
Account account = AuthUtils.getActiveAccount(getApplicationContext(), getAccountType());
if (account == null) {
callback.success(null);
return;
}
RevocationRequest req = new RevocationRequest(getClientCredentials(), getAccountManager().getPassword(account), "refresh_token");
getApi().revoke(req, new retrofit.Callback<String>() {
@Override
public void success(String s, Response response) {
AuthUtils.removeActiveAccount(getApplicationContext(), getAccountType());
callback.success(null);
}
@Override
public void failure(RetrofitError error) {
if (failOnNetworkError) {
callback.failure(SignoutFailure.NETWORK);
} else {
AuthUtils.removeActiveAccount(getApplicationContext(), getAccountType());
callback.success(null);
}
}
});
}
public void changePassword(final ChangePasswordRequest request, final Callback<Void, PasswordChangeFailure> callback) {
/* TODO
This request don't include the ApiAuthenticator and will fail if the access token is
invalid (because I'm lazy). This is not neccessary since we can try to refresh the auth
token instead.
*/
String token = accountManager.peekAuthToken(getActiveAccount(), getAuthTokenType());
getApi().changePassword(ApiAuthInterceptor.authHeaderValue(token), request, new retrofit.Callback<JsonElement>() {
@Override
public void success(JsonElement jsonElement, Response response) {
callback.success(null);
}
@Override
public void failure(RetrofitError error) {
switch (error.getKind()) {
case NETWORK:
callback.failure(PasswordChangeFailure.NETWORK);
break;
case HTTP:
if (error.getResponse().getStatus() == HttpStatus.SC_UNAUTHORIZED) {
callback.failure(PasswordChangeFailure.BAD_CREDENTIALS);
} else if (error.getResponse().getStatus() == HttpStatus.SC_FORBIDDEN) {
callback.failure(PasswordChangeFailure.INVALID_ACCESS_TOKEN);
} else {
callback.failure(PasswordChangeFailure.UNEXPECTED);
}
break;
default:
callback.failure(PasswordChangeFailure.UNEXPECTED);
}
}
});
}
public void passwordReset(final ResetPassword request, final Callback<Void, PasswordResetFailure> callback) {
getApi().resetPassword(request, new retrofit.Callback<JsonElement>() {
@Override
public void success(JsonElement jsonElement, Response response) {
callback.success(null);
}
@Override
public void failure(RetrofitError error) {
switch (error.getKind()) {
case NETWORK:
callback.failure(PasswordResetFailure.NETWORK);
break;
default:
callback.failure(PasswordResetFailure.UNEXPECTED);
break;
}
}
});
}
public boolean isSignedIn() {
return AuthUtils.hasActiveAccount(getApplicationContext(), getAccountType());
}
public Account getActiveAccount() {
return AuthUtils.getActiveAccount(getApplicationContext(), getAccountType());
}
public AccountAuthenticator getAccountAuthenticator() {
return accountAuthenticator;
}
public ApiAuthInterceptor createAuthInterceptor() {
return new ApiAuthInterceptor(getApplicationContext(), getAccountManager(), getAccountType(), getAccountType());
}
public ApiAuthenticator createApiAuthenticator() {
return new ApiAuthenticator(getApplicationContext(), getAuthTokenType(), getAccountType());
}
private AuthApi getApi() {
return api;
}
private Context getApplicationContext() {
return applicationContext;
}
public String getAuthTokenType() {
return authTokenType;
}
public String getAccountType() {
return accountType;
}
private AccountManager getAccountManager() {
return accountManager;
}
public ClientCredentials getClientCredentials() {
return clientCredentials;
}
public UserCredentials createPasswordUserCredentials(String username, String password) {
return new UserCredentials(getClientCredentials(), username, password, "password");
}
public Class<? extends AbstractLoginActivity> getLoginActivityClass() {
return loginActivityClass;
}
public Intent getLoginActivityIntent(Context context) {
return AbstractLoginActivity.createIntent(context, getLoginActivityClass(), getAccountType(), getAuthTokenType());
}
public static class Builder {
private AuthApi api;
private Context applicationContext;
private String authTokenType;
private String accountType;
private AccountManager accountManager;
private ClientCredentials clientCredentials;
private String endpoint;
private RestAdapter.LogLevel retrofitLogLevel = RestAdapter.LogLevel.NONE;
public Class<? extends AbstractLoginActivity> loginActivityClass;
public Builder() { }
public Builder setApi(AuthApi api) {
this.api = api;
return this;
}
public Builder setApplicationContext(Context applicationContext) {
this.applicationContext = applicationContext;
return this;
}
public Builder setAuthTokenType(String authTokenType) {
this.authTokenType = authTokenType;
return this;
}
public Builder setAccountType(String accountType) {
this.accountType = accountType;
return this;
}
public Builder setAccountManager(AccountManager accountManager) {
this.accountManager = accountManager;
return this;
}
public Builder setClientCredentials(ClientCredentials clientCredentials) {
this.clientCredentials = clientCredentials;
return this;
}
public Builder setLoginActivityClass(Class<? extends AbstractLoginActivity> loginActivityClass) {
this.loginActivityClass = loginActivityClass;
return this;
}
public Builder setRetrofitLogLevel(RestAdapter.LogLevel level) {
retrofitLogLevel = level;
return this;
}
/**
* Set endpoint for the auth api. Not required if an AuthApi is provided, otherwise
* required.
*/
public Builder setEndpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
public AuthAdapter build() {
if (api == null && endpoint != null) {
api = defaultApi(endpoint);
} else if (api != null && endpoint != null) {
throw new IllegalArgumentException("You need to set either an AuthApi or an endpoint string.");
}
if (accountManager == null && applicationContext != null) {
accountManager = AccountManager.get(applicationContext);
}
Utils.checkNotNull(api);
Utils.checkNotNull(applicationContext);
Utils.checkNotNull(authTokenType);
Utils.checkNotNull(accountType);
Utils.checkNotNull(accountManager);
Utils.checkNotNull(clientCredentials);
Utils.checkNotNull(loginActivityClass);
return new AuthAdapter(this);
}
private AuthApi defaultApi(String endpoint) {
return new RestAdapter.Builder()
.setEndpoint(endpoint)
.setLogLevel(retrofitLogLevel)
.build()
.create(AuthApi.class);
}
}
}
|
package com.tinkerpop.blueprints.pgm.impls.neo4j;
import com.tinkerpop.blueprints.pgm.Edge;
import com.tinkerpop.blueprints.pgm.Graph;
import com.tinkerpop.blueprints.pgm.Index;
import com.tinkerpop.blueprints.pgm.Vertex;
import com.tinkerpop.blueprints.pgm.impls.neo4j.util.Neo4jGraphEdgeIterable;
import com.tinkerpop.blueprints.pgm.impls.neo4j.util.Neo4jVertexIterable;
import org.neo4j.graphdb.*;
import org.neo4j.index.Isolation;
import org.neo4j.index.lucene.LuceneIndexService;
import org.neo4j.kernel.EmbeddedGraphDatabase;
import org.neo4j.kernel.impl.transaction.TransactionFailureException;
import java.io.File;
import java.util.Map;
public class Neo4jGraph implements Graph {
private GraphDatabaseService neo;
private String directory;
private Neo4jIndex index;
private Transaction tx;
private boolean automaticTransactions = true;
public Neo4jGraph(final String directory) {
this(directory, null);
}
public GraphDatabaseService getGraphDatabaseService() {
return this.neo;
}
public Neo4jGraph(final String directory, Map<String, String> configuration) {
this.directory = directory;
if (null != configuration)
this.neo = new EmbeddedGraphDatabase(this.directory, configuration);
else
this.neo = new EmbeddedGraphDatabase(this.directory);
LuceneIndexService indexService = new LuceneIndexService(neo);
indexService.setIsolation(Isolation.SAME_TX);
this.index = new Neo4jIndex(indexService, this);
if (this.automaticTransactions) {
this.tx = neo.beginTx();
}
}
public Index getIndex() {
return this.index;
}
public Vertex addVertex(final Object id) {
Vertex vertex = new Neo4jVertex(neo.createNode(), this);
this.stopStartTransaction();
return vertex;
}
public Vertex getVertex(final Object id) {
if (null == id)
return null;
try {
Long longId = Double.valueOf(id.toString()).longValue();
Node node = this.neo.getNodeById(longId);
return new Neo4jVertex(node, this);
} catch (NotFoundException e) {
return null;
} catch (NumberFormatException e) {
throw new RuntimeException("Neo vertex ids must be convertible to a long value");
}
}
public Iterable<Vertex> getVertices() {
return new Neo4jVertexIterable(this.neo.getAllNodes(), this);
}
public Iterable<Edge> getEdges() {
return new Neo4jGraphEdgeIterable(this.neo.getAllNodes(), this);
}
public void removeVertex(final Vertex vertex) {
Long id = (Long) vertex.getId();
Node node = neo.getNodeById(id);
if (null != node) {
for (String key : vertex.getPropertyKeys()) {
this.index.remove(key, vertex.getProperty(key), vertex);
}
for (Edge edge : vertex.getInEdges()) {
this.removeEdge(edge);
}
for (Edge edge : vertex.getOutEdges()) {
this.removeEdge(edge);
}
node.delete();
this.stopStartTransaction();
}
}
public Edge addEdge(final Object id, final Vertex outVertex, final Vertex inVertex, final String label) {
Node outNode = (Node) ((Neo4jVertex) outVertex).getRawElement();
Node inNode = (Node) ((Neo4jVertex) inVertex).getRawElement();
Relationship relationship = outNode.createRelationshipTo(inNode, DynamicRelationshipType.withName(label));
this.stopStartTransaction();
return new Neo4jEdge(relationship, this);
}
public void removeEdge(Edge edge) {
((Relationship) ((Neo4jEdge) edge).getRawElement()).delete();
this.stopStartTransaction();
}
protected void stopStartTransaction() {
if (this.automaticTransactions) {
if (null != tx) {
this.tx.success();
this.tx.finish();
this.tx = neo.beginTx();
} else {
throw new RuntimeException("There is no active transaction to stop");
}
}
}
public void startTransaction() {
if (this.automaticTransactions)
throw new RuntimeException("Turn off automatic transactions to use manual transaction handling");
this.tx = neo.beginTx();
}
public void stopTransaction(boolean success) {
if (this.automaticTransactions)
throw new RuntimeException("Turn off automatic transactions to use manual transaction handling");
if (success) {
this.tx.success();
} else {
this.tx.failure();
}
this.tx.finish();
}
public void setAutoTransactions(boolean automatic) {
this.automaticTransactions = automatic;
if (null != this.tx) {
this.tx.success();
this.tx.finish();
}
}
public void shutdown() {
if (this.automaticTransactions) {
try {
this.tx.success();
this.tx.finish();
} catch (TransactionFailureException e) {
}
}
this.neo.shutdown();
this.index.shutdown();
}
public void clear() {
this.shutdown();
deleteGraphDirectory(new File(this.directory));
this.neo = new EmbeddedGraphDatabase(this.directory);
LuceneIndexService indexService = new LuceneIndexService(neo);
indexService.setIsolation(Isolation.SAME_TX);
this.index = new Neo4jIndex(indexService, this);
this.tx = neo.beginTx();
this.removeVertex(this.getVertex(0));
this.stopStartTransaction();
}
private static void deleteGraphDirectory(final File directory) {
if (directory.exists()) {
for (File file : directory.listFiles()) {
if (file.isDirectory()) {
deleteGraphDirectory(file);
}
file.delete();
}
}
}
public String toString() {
return "neo4jgraph[" + this.directory + "]";
}
}
|
package org.jboss.as.logging;
import org.jboss.as.controller.CaseParameterCorrector;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.operations.validation.EnumValidator;
import org.jboss.as.controller.operations.validation.IntRangeValidator;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.as.logging.handlers.console.Target;
import org.jboss.as.logging.validators.FileValidator;
import org.jboss.as.logging.validators.LogLevelValidator;
import org.jboss.as.logging.validators.SizeValidator;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
import org.jboss.logmanager.handlers.AsyncHandler.OverflowAction;
/**
* @author Emanuel Muckenhuber
*/
public interface CommonAttributes {
SimpleAttributeDefinition ACCEPT = SimpleAttributeDefinitionBuilder.create("accept", ModelType.BOOLEAN, true).
setDefaultValue(new ModelNode().set(true)).
build();
SimpleAttributeDefinition APPEND = SimpleAttributeDefinitionBuilder.create("append", ModelType.BOOLEAN, true).
setDefaultValue(new ModelNode().set(true)).
setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES).
build();
String ASYNC_HANDLER = "async-handler";
SimpleAttributeDefinition AUTOFLUSH = SimpleAttributeDefinitionBuilder.create("autoflush", ModelType.BOOLEAN, true).
setDefaultValue(new ModelNode().set(true)).
build();
SimpleAttributeDefinition CATEGORY = SimpleAttributeDefinitionBuilder.create("category", ModelType.STRING).build();
SimpleAttributeDefinition CHANGE_LEVEL = SimpleAttributeDefinitionBuilder.create("change-level", ModelType.STRING, true).
setCorrector(CaseParameterCorrector.TO_UPPER).
setValidator(new LogLevelValidator(true)).
build();
SimpleAttributeDefinition CLASS = SimpleAttributeDefinitionBuilder.create("class", ModelType.STRING).build();
String CONSOLE_HANDLER = "console-handler";
String CUSTOM_HANDLER = "custom-handler";
SimpleAttributeDefinition DENY = SimpleAttributeDefinitionBuilder.create("deny", ModelType.BOOLEAN, true).
setDefaultValue(new ModelNode().set(true)).
build();
SimpleAttributeDefinition ENCODING = SimpleAttributeDefinitionBuilder.create("encoding", ModelType.STRING, true).build();
SimpleAttributeDefinition FILE = SimpleAttributeDefinitionBuilder.create("file", ModelType.OBJECT, true).
setCorrector(FileCorrector.INSTANCE).
setValidator(new FileValidator()).
build();
String FILE_HANDLER = "file-handler";
SimpleAttributeDefinition FILE_NAME = SimpleAttributeDefinitionBuilder.create("file-name", ModelType.STRING).build();
SimpleAttributeDefinition FORMATTER = SimpleAttributeDefinitionBuilder.create("formatter", ModelType.STRING, true).
setDefaultValue(new ModelNode().set("%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n")).
build();
SimpleAttributeDefinition HANDLER = SimpleAttributeDefinitionBuilder.create("handler", ModelType.STRING).build();
LogHandlerListAttributeDefinition HANDLERS = LogHandlerListAttributeDefinition.Builder.of("handlers", HANDLER).
setAllowNull(true).
build();
SimpleAttributeDefinition LEVEL = SimpleAttributeDefinitionBuilder.create("level", ModelType.STRING, true).
setCorrector(CaseParameterCorrector.TO_UPPER).
setValidator(new LogLevelValidator(true)).
build();
String LOGGER = "logger";
SimpleAttributeDefinition MATCH = SimpleAttributeDefinitionBuilder.create("match", ModelType.STRING, true).build();
SimpleAttributeDefinition MAX_BACKUP_INDEX = SimpleAttributeDefinitionBuilder.create("max-backup-index", ModelType.INT).
setDefaultValue(new ModelNode().set(1)).
setValidator(new IntRangeValidator(1, true)).
build();
SimpleAttributeDefinition MAX_INCLUSIVE = SimpleAttributeDefinitionBuilder.create("max-inclusive", ModelType.BOOLEAN).
setDefaultValue(new ModelNode().set(true)).
build();
SimpleAttributeDefinition MAX_LEVEL = SimpleAttributeDefinitionBuilder.create("max-level", ModelType.STRING).
setCorrector(CaseParameterCorrector.TO_UPPER).
setValidator(new LogLevelValidator(true)).
build();
SimpleAttributeDefinition MIN_INCLUSIVE = SimpleAttributeDefinitionBuilder.create("min-inclusive", ModelType.BOOLEAN).
setDefaultValue(new ModelNode().set(true)).
build();
SimpleAttributeDefinition MIN_LEVEL = SimpleAttributeDefinitionBuilder.create("min-level", ModelType.STRING).
setCorrector(CaseParameterCorrector.TO_UPPER).
setValidator(new LogLevelValidator(true)).
build();
SimpleAttributeDefinition MODULE = SimpleAttributeDefinitionBuilder.create("module", ModelType.STRING).build();
SimpleAttributeDefinition NAME = SimpleAttributeDefinitionBuilder.create("name", ModelType.STRING).build();
SimpleAttributeDefinition VALUE = SimpleAttributeDefinitionBuilder.create("value", ModelType.STRING).build();
SimpleAttributeDefinition NEW_LEVEL = SimpleAttributeDefinitionBuilder.create("new-level", ModelType.STRING).
setCorrector(CaseParameterCorrector.TO_UPPER).
setValidator(new LogLevelValidator(true)).
build();
SimpleAttributeDefinition OVERFLOW_ACTION = SimpleAttributeDefinitionBuilder.create("overflow-action", ModelType.STRING).
setDefaultValue(new ModelNode().set(OverflowAction.BLOCK.name())).
setValidator(EnumValidator.create(OverflowAction.class, false, false)).
build();
SimpleAttributeDefinition PATH = SimpleAttributeDefinitionBuilder.create("path", ModelType.STRING).build();
SimpleAttributeDefinition PATTERN = SimpleAttributeDefinitionBuilder.create("pattern", ModelType.STRING).build();
String PATTERN_FORMATTER = "pattern-formatter";
String PERIODIC_ROTATING_FILE_HANDLER = "periodic-rotating-file-handler";
SimpleAttributeDefinition PROPERTY = SimpleAttributeDefinitionBuilder.create("property", ModelType.PROPERTY).build();
String PROPERTIES = "properties";
SimpleAttributeDefinition QUEUE_LENGTH = SimpleAttributeDefinitionBuilder.create("queue-length", ModelType.INT).
setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES).
setValidator(new IntRangeValidator(1, false)).
build();
SimpleAttributeDefinition RELATIVE_TO = SimpleAttributeDefinitionBuilder.create("relative-to", ModelType.STRING, true).build();
SimpleAttributeDefinition REPLACEMENT = SimpleAttributeDefinitionBuilder.create("replacement", ModelType.STRING).build();
SimpleAttributeDefinition REPLACE_ALL = SimpleAttributeDefinitionBuilder.create("replace-all", ModelType.BOOLEAN).
setDefaultValue(new ModelNode().set(true)).
build();
String ROOT_LOGGER = "root-logger";
String ROOT_LOGGER_NAME = "ROOT";
SimpleAttributeDefinition ROTATE_SIZE = SimpleAttributeDefinitionBuilder.create("rotate-size", ModelType.STRING).
setDefaultValue(new ModelNode().set("2m")).
setValidator(new SizeValidator()).
build();
String SIZE_ROTATING_FILE_HANDLER = "size-rotating-file-handler";
LogHandlerListAttributeDefinition SUBHANDLERS = LogHandlerListAttributeDefinition.Builder.of("subhandlers", HANDLER).
setAllowNull(true).
build();
SimpleAttributeDefinition SUFFIX = SimpleAttributeDefinitionBuilder.create("suffix", ModelType.STRING).build();
SimpleAttributeDefinition TARGET = SimpleAttributeDefinitionBuilder.create("target", ModelType.STRING, true).
setDefaultValue(new ModelNode().set(Target.SYSTEM_OUT.toString())).
setValidator(EnumValidator.create(Target.class, false, false)).
build();
SimpleAttributeDefinition USE_PARENT_HANDLERS = SimpleAttributeDefinitionBuilder.create("use-parent-handlers", ModelType.BOOLEAN, true).
setDefaultValue(new ModelNode().set(true)).
build();
// Global object types
ObjectTypeAttributeDefinition LEVEL_RANGE = ObjectTypeAttributeDefinition.Builder.of("level-range", MIN_LEVEL, MIN_INCLUSIVE, MAX_LEVEL, MAX_INCLUSIVE).
setSuffix("filter.level-range").build();
ObjectTypeAttributeDefinition REPLACE = ObjectTypeAttributeDefinition.Builder.of("replace", PATTERN, REPLACEMENT, REPLACE_ALL).
setSuffix("filter.replace").build();
ObjectTypeAttributeDefinition NOT = ObjectTypeAttributeDefinition.Builder.of("not", ACCEPT, CHANGE_LEVEL, DENY, LEVEL, LEVEL_RANGE, MATCH, REPLACE).
setSuffix("filter").build();
ObjectTypeAttributeDefinition ALL = ObjectTypeAttributeDefinition.Builder.of("all", ACCEPT, CHANGE_LEVEL, DENY, LEVEL, LEVEL_RANGE, MATCH, NOT, REPLACE).
setSuffix("filter").build();
ObjectTypeAttributeDefinition ANY = ObjectTypeAttributeDefinition.Builder.of("any", ACCEPT, CHANGE_LEVEL, DENY, LEVEL, LEVEL_RANGE, MATCH, NOT, REPLACE).
setSuffix("filter").build();
ObjectTypeAttributeDefinition FILTER = ObjectTypeAttributeDefinition.Builder.of("filter", ALL, ANY, ACCEPT, CHANGE_LEVEL, DENY, LEVEL, LEVEL_RANGE, MATCH, NOT, REPLACE).
setSuffix("filter").build();
}
|
package com.esotericsoftware.kryo.serializers;
import com.esotericsoftware.kryo.KryoTestCase;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.serializers.GenericsTest.A.DontPassToSuper;
import com.esotericsoftware.kryo.serializers.GenericsTest.ClassWithMap.MapKey;
import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.util.*;
import org.junit.Before;
import org.junit.Test;
public class GenericsTest extends KryoTestCase {
{
supportsCopy = true;
}
@Before
public void setUp () throws Exception {
super.setUp();
}
@Test
public void testGenericClassWithGenericFields () {
kryo.setReferences(true);
kryo.setRegistrationRequired(false);
kryo.register(BaseGeneric.class);
List list = Arrays.asList(new SerializableObjectFoo("one"), new SerializableObjectFoo("two"),
new SerializableObjectFoo("three"));
BaseGeneric<SerializableObjectFoo> bg1 = new BaseGeneric(list);
roundTrip(117, bg1);
}
@Test
public void testNonGenericClassWithGenericSuperclass () {
kryo.setReferences(true);
kryo.setRegistrationRequired(false);
kryo.register(BaseGeneric.class);
kryo.register(ConcreteClass.class);
List list = Arrays.asList(new SerializableObjectFoo("one"), new SerializableObjectFoo("two"),
new SerializableObjectFoo("three"));
ConcreteClass cc1 = new ConcreteClass(list);
roundTrip(117, cc1);
}
@Test
public void testDifferentTypeArguments () {
LongHolder o1 = new LongHolder(1L);
LongListHolder o2 = new LongListHolder(Arrays.asList(1L));
kryo.setRegistrationRequired(false);
Output buffer = new Output(512, 4048);
kryo.writeClassAndObject(buffer, o1);
kryo.writeClassAndObject(buffer, o2);
}
@Test
public void testSuperGenerics () {
kryo.register(SuperGenerics.Root.class);
kryo.register(SuperGenerics.Value.class);
Output output = new Output(2048, -1);
SuperGenerics.Root root = new SuperGenerics.Root();
root.rootSuperField = new SuperGenerics.Value();
kryo.writeObject(output, root);
output.flush();
Input input = new Input(output.getBuffer(), 0, output.position());
kryo.readObject(input, SuperGenerics.Root.class);
}
@Test
public void testMapTypeParams () {
ClassWithMap hasMap = new ClassWithMap();
MapKey key = new MapKey();
key.field1 = "foo";
key.field2 = "bar";
HashSet set = new HashSet();
set.add("one");
set.add("two");
hasMap.values.put(key, set);
kryo.register(ClassWithMap.class);
kryo.register(MapKey.class);
kryo.register(HashMap.class);
kryo.register(HashSet.class);
roundTrip(18, hasMap);
}
@Test
public void testNotPassingToSuper () {
kryo.register(DontPassToSuper.class);
kryo.copy(new DontPassToSuper());
}
@Test
public void testFieldWithGenericInterface () {
final Holder<?> holder = new ClassArrayHolder(new Class[] {});
ClassWithGenericInterfaceField o = new ClassWithGenericInterfaceField(holder);
kryo.setRegistrationRequired(false);
kryo.register(SerializedLambda.class);
kryo.register(ClosureSerializer.Closure.class, new ClosureSerializer());
roundTrip(153, o);
}
@Test
public void testFieldWithGenericArrayType() {
ClassArrayHolder o = new ClassArrayHolder(new Class[] {});
kryo.setRegistrationRequired(false);
roundTrip(70, o);
}
@Test
public void testClassWithMultipleGenericTypes() {
HolderWithAdditionalGenericType<String, Integer> o = new HolderWithAdditionalGenericType<>(1);
kryo.setRegistrationRequired(false);
roundTrip(87, o);
}
@Test
public void testClassHierarchyWithChangingGenericTypeVariables () {
ClassHierarchyWithChangingTypeVariableNames.A<?> o = new ClassHierarchyWithChangingTypeVariableNames.A<>(Enum.class);
kryo.setRegistrationRequired(false);
roundTrip(131, o);
}
@Test
public void testClassHierarchyWithMultipleTypeVariables () {
ClassHierarchyWithMultipleTypeVariables.A<Integer, ?> o = new ClassHierarchyWithMultipleTypeVariables.A<>(Enum.class);
kryo.setRegistrationRequired(false);
roundTrip(110, o);
}
private interface Holder<V> {
V getValue ();
}
static private abstract class AbstractValueHolder<V> implements Holder<V> {
private final V value;
AbstractValueHolder (V value) {
this.value = value;
}
public V getValue () {
return value;
}
@Override
public boolean equals (Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final AbstractValueHolder<?> that = (AbstractValueHolder<?>)o;
return Objects.deepEquals(value, that.value);
}
}
static private abstract class AbstractValueListHolder<V> extends AbstractValueHolder<List<V>> {
AbstractValueListHolder (List<V> value) {
super(value);
}
}
static private class LongHolder extends AbstractValueHolder<Long> {
LongHolder (Long value) {
super(value);
}
}
static private class LongListHolder extends AbstractValueListHolder<Long> {
LongListHolder (java.util.List<Long> value) {
super(value);
}
}
static class ClassArrayHolder extends AbstractValueHolder<Class<?>[]> {
/** Kryo Constructor */
ClassArrayHolder () {
super(null);
}
ClassArrayHolder (Class<?>[] value) {
super(value);
}
}
static class HolderWithAdditionalGenericType<BT, OT> extends AbstractValueHolder<OT> {
private BT value;
/** Kryo Constructor */
HolderWithAdditionalGenericType () {
super(null);
}
HolderWithAdditionalGenericType(OT value) {
super(value);
}
@Override
public boolean equals (Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
final HolderWithAdditionalGenericType<?, ?> that = (HolderWithAdditionalGenericType<?, ?>)o;
return Objects.equals(value, that.value);
}
}
// A simple serializable class.
static private class SerializableObjectFoo implements Serializable {
String name;
SerializableObjectFoo (String name) {
this.name = name;
}
public SerializableObjectFoo () {
name = "Default";
}
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
SerializableObjectFoo other = (SerializableObjectFoo)obj;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
return true;
}
}
static private class BaseGeneric<T extends Serializable> {
// The type of this field cannot be derived from the context.
// Therefore, Kryo should consider it to be Object.
private final List<T> listPayload;
/** Kryo Constructor */
protected BaseGeneric () {
super();
this.listPayload = null;
}
protected BaseGeneric (final List<T> listPayload) {
super();
// Defensive copy, listPayload is mutable
this.listPayload = new ArrayList(listPayload);
}
public final List<T> getPayload () {
return this.listPayload;
}
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
BaseGeneric other = (BaseGeneric)obj;
if (listPayload == null) {
if (other.listPayload != null) return false;
} else if (!listPayload.equals(other.listPayload)) return false;
return true;
}
}
// This is a non-generic class with a generic superclass.
static private class ConcreteClass2 extends BaseGeneric<SerializableObjectFoo> {
/** Kryo Constructor */
ConcreteClass2 () {
super();
}
public ConcreteClass2 (final List listPayload) {
super(listPayload);
}
}
static private class ConcreteClass1 extends ConcreteClass2 {
/** Kryo Constructor */
ConcreteClass1 () {
super();
}
public ConcreteClass1 (final List listPayload) {
super(listPayload);
}
}
static private class ConcreteClass extends ConcreteClass1 {
/** Kryo Constructor */
ConcreteClass () {
super();
}
public ConcreteClass (final List listPayload) {
super(listPayload);
}
}
static public class SuperGenerics {
static public class RootSuper<RS> {
public ValueSuper<RS> rootSuperField;
}
static public class Root extends RootSuper<String> {
}
static public class ValueSuper<VS> extends ValueSuperSuper<Integer> {
VS superField;
}
static public class ValueSuperSuper<VSS> {
VSS superSuperField;
}
static public class Value extends ValueSuper<String> {
}
}
static public class ClassWithMap {
public final Map<MapKey, Set<String>> values = new HashMap();
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ClassWithMap other = (ClassWithMap)obj;
if (values == null) {
if (other.values != null) return false;
} else if (!values.toString().equals(other.values.toString())) return false;
return true;
}
static public class MapKey {
public String field1, field2;
public String toString () {
return field1 + ":" + field2;
}
}
}
static public class A<X> {
static public class B<Y> extends A {
}
static public class DontPassToSuper<Z> extends B {
B<Z> b;
}
}
static class ClassWithGenericInterfaceField {
Holder<?> input;
/** Kryo Constructor */
ClassWithGenericInterfaceField () {
}
ClassWithGenericInterfaceField (Holder<?> holder) {
input = holder;
}
@Override
public boolean equals (Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final ClassWithGenericInterfaceField that = (ClassWithGenericInterfaceField)o;
return Objects.equals(input, that.input);
}
}
static class ClassHierarchyWithChangingTypeVariableNames {
static final class A<T> extends B<T> {
T d;
/** Kryo Constructor */
A () {
}
A (T d) {
this.d = d;
}
@Override
public boolean equals (Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final A<?> a = (A<?>)o;
return Objects.equals(d, a.d);
}
}
static class B<E> extends C<E> {
}
static class C<E> {
}
}
static class ClassHierarchyWithMultipleTypeVariables {
static class A<T, S> extends B<T> {
Class<S> s;
/** Kryo Constructor */
A () {
}
A (Class<S> s) {
this.s = s;
}
@Override
public boolean equals (Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final A<?, ?> a = (A<?, ?>)o;
return Objects.equals(s, a.s);
}
}
static class B<T> extends C<T> {
}
public static class C<T> {
}
}
}
|
package org.ktunaxa.referral.client.gui;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.geomajas.gwt.client.command.AbstractCommandCallback;
import org.geomajas.gwt.client.command.GwtCommand;
import org.geomajas.gwt.client.command.GwtCommandDispatcher;
import org.geomajas.gwt.client.util.Html;
import org.geomajas.gwt.client.util.HtmlBuilder;
import org.geomajas.layer.feature.Feature;
import org.ktunaxa.bpm.KtunaxaBpmConstant;
import org.ktunaxa.referral.client.referral.event.CurrentReferralChangedEvent;
import org.ktunaxa.referral.client.referral.event.CurrentReferralChangedHandler;
import org.ktunaxa.referral.client.security.UserContext;
import org.ktunaxa.referral.client.widget.AbstractCollapsibleListBlock;
import org.ktunaxa.referral.server.command.dto.AssignTaskRequest;
import org.ktunaxa.referral.server.command.dto.GetReferralResponse;
import org.ktunaxa.referral.server.dto.TaskDto;
import com.smartgwt.client.types.Cursor;
import com.smartgwt.client.types.VerticalAlignment;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.HTMLFlow;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.LayoutSpacer;
/**
* Implementation of the CollapsableBlock abstraction that handles {@link TaskDto} type objects. Instances of this
* class will form the list of tasks on task tabs. Each block can collapse and expand. When collapsed only the
* task title is visible.
*
* @author Pieter De Graef
* @author Joachim Van der Auwera
*/
public class TaskBlock extends AbstractCollapsibleListBlock<TaskDto> {
private static final String BLOCK_STYLE = "taskBlock";
private static final String BLOCK_CONTENT_STYLE = "taskBlockContent";
private static final String BLOCK_CONTENT_TABLE_STYLE = "taskBlockContentTable";
private static final String TITLE_STYLE = "taskBlockTitle";
private static final String BLOCK_STYLE_COLLAPSED = "taskBlockCollapsed";
private static final String TITLE_STYLE_COLLAPSED = "taskBlockTitleCollapsed";
private static final String STYLE_VARIABLE_NAME = "text-align:right; width:120px";
private static final String STYLE_VARIABLE_VALUE = "text-align:left";
private static final String IMAGE_MINIMIZE = "[ISOMORPHIC]/skins/ActivitiBlue/images/headerIcons/minimize.gif";
private static final String IMAGE_MAXIMIZE = "[ISOMORPHIC]/skins/ActivitiBlue/images/headerIcons/maximize.gif";
private static final String IMAGE_CLAIM = "[ISOMORPHIC]/images/task/claim.png";
private static final String IMAGE_START = "[ISOMORPHIC]/images/task/start.png";
private static final String IMAGE_ASSIGN = "[ISOMORPHIC]/images/task/assign.png";
private HLayout title;
private HTMLFlow content;
private Img titleImage = new Img(IMAGE_MINIMIZE, 16, 16);
private IButton startButton = new IButton();
private IButton claimButton = new IButton();
private boolean needToDisplayCurrentTask;
// Constructors:
public TaskBlock(TaskDto task) {
super(task);
buildGui(task);
MapLayout.getInstance().addCurrentReferralChangedHandler(new CurrentReferralChangedHandler() {
public void onCurrentReferralChanged(CurrentReferralChangedEvent event) {
if (needToDisplayCurrentTask) {
MapLayout.getInstance().focusCurrentTask();
}
needToDisplayCurrentTask = false;
}
});
}
// CollapsableBlock implementation:
/** Expand the task block, displaying everything. */
public void expand() {
setStyleName(BLOCK_STYLE);
title.setStyleName(TITLE_STYLE);
titleImage.setSrc(IMAGE_MINIMIZE);
content.setVisible(true);
}
/** Collapse the task block, leaving only the title visible. */
public void collapse() {
setStyleName(BLOCK_STYLE_COLLAPSED);
title.setStyleName(TITLE_STYLE_COLLAPSED);
titleImage.setSrc(IMAGE_MAXIMIZE);
content.setVisible(false);
}
/**
* Search the task for a given text string. This method will search through the title, content, checkedContent
* and name of the user.
*
* @param text
* The text to search for
* @return Returns true if the text has been found somewhere.
*/
public boolean containsText(String text) {
if (text != null) {
String lcText = text.toLowerCase();
String compare;
compare = getObject().getName();
if (compare != null && compare.toLowerCase().contains(lcText)) {
return true;
}
compare = getObject().getDescription();
if (compare != null && compare.toLowerCase().contains(lcText)) {
return true;
}
}
return false;
}
public Button getEditButton() {
return null;
}
// Private methods:
private void buildGui(TaskDto task) {
Map<String, String> variables = task.getVariables();
setStyleName(BLOCK_STYLE);
title = new HLayout(LayoutConstant.MARGIN_LARGE);
title.setSize(LayoutConstant.BLOCK_TITLE_WIDTH, LayoutConstant.BLOCK_TITLE_HEIGHT);
title.setLayoutLeftMargin(LayoutConstant.MARGIN_LARGE);
title.setStyleName(TITLE_STYLE);
title.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
if (content.isVisible()) {
collapse();
} else {
expand();
}
}
});
title.setCursor(Cursor.HAND);
titleImage.setLayoutAlign(VerticalAlignment.CENTER);
title.addMember(titleImage);
HTMLFlow titleText = new HTMLFlow("<div class='taskBlockTitleText'>" +
variables.get(KtunaxaBpmConstant.VAR_REFERRAL_ID) +
": " + HtmlBuilder.htmlEncode(task.getName()) +
"</div>");
titleText.setSize(LayoutConstant.BLOCK_TITLE_WIDTH, LayoutConstant.BLOCK_TITLE_HEIGHT);
title.addMember(titleText);
addMember(title);
HLayout infoLayout = new HLayout(LayoutConstant.MARGIN_SMALL);
infoLayout.setLayoutRightMargin(LayoutConstant.MARGIN_SMALL);
infoLayout.setLayoutTopMargin(LayoutConstant.MARGIN_SMALL);
HTMLFlow info = new HTMLFlow(
HtmlBuilder.divClassHtmlContent("taskBlockInfo",
HtmlBuilder.htmlEncode(task.getDescription()) +
"<br />Referral: " +
HtmlBuilder.tagClass(Html.Tag.SPAN, "taskBlockInfoBold",
variables.get(KtunaxaBpmConstant.VAR_REFERRAL_NAME))));
info.setSize(LayoutConstant.BLOCK_INFO_WIDTH, LayoutConstant.BLOCK_INFO_HEIGHT);
infoLayout.addMember(info);
infoLayout.addMember(new LayoutSpacer());
final String me = UserContext.getInstance().getUser();
startButton.setIcon(IMAGE_START);
startButton.setShowDisabledIcon(true);
startButton.setIconWidth(LayoutConstant.ICON_BUTTON_LARGE_ICON_WIDTH);
startButton.setIconHeight(LayoutConstant.ICON_BUTTON_LARGE_ICON_HEIGHT);
startButton.setWidth(LayoutConstant.ICON_BUTTON_LARGE_WIDTH);
startButton.setHeight(LayoutConstant.ICON_BUTTON_LARGE_HEIGHT);
startButton.setPrompt("Start");
startButton.setHoverWidth(LayoutConstant.ICON_BUTTON_LARGE_HOVER_WIDTH);
startButton.setLayoutAlign(VerticalAlignment.CENTER);
startButton.setShowRollOver(false);
setStartButtonStatus(task);
startButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent clickEvent) {
assign(getObject(), me, true);
}
});
infoLayout.addMember(startButton);
IButton assignButton = new IButton();
assignButton.setIcon(IMAGE_ASSIGN);
assignButton.setShowDisabledIcon(true);
assignButton.setIconWidth(LayoutConstant.ICON_BUTTON_LARGE_ICON_WIDTH);
assignButton.setIconHeight(LayoutConstant.ICON_BUTTON_LARGE_ICON_HEIGHT);
assignButton.setWidth(LayoutConstant.ICON_BUTTON_LARGE_WIDTH);
assignButton.setHeight(LayoutConstant.ICON_BUTTON_LARGE_HEIGHT);
assignButton.setPrompt("Assign");
assignButton.setHoverWidth(LayoutConstant.ICON_BUTTON_LARGE_HOVER_WIDTH);
assignButton.setLayoutAlign(VerticalAlignment.CENTER);
assignButton.setShowRollOver(false);
if (!UserContext.getInstance().isReferralAdmin()) {
// disable when already assigned
assignButton.setDisabled(true);
}
assignButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent clickEvent) {
SC.say("assign task, temp to KtBpmAdmin " + getObject().getId());
// @todo select user
assign(getObject(), me, false); // @todo assign selected user
}
});
infoLayout.addMember(assignButton);
claimButton.setIcon(IMAGE_CLAIM);
claimButton.setShowDisabledIcon(true);
claimButton.setIconWidth(LayoutConstant.ICON_BUTTON_LARGE_ICON_WIDTH);
claimButton.setIconHeight(LayoutConstant.ICON_BUTTON_LARGE_ICON_HEIGHT);
claimButton.setWidth(LayoutConstant.ICON_BUTTON_LARGE_WIDTH);
claimButton.setHeight(LayoutConstant.ICON_BUTTON_LARGE_HEIGHT);
claimButton.setPrompt("Claim");
claimButton.setHoverWidth(LayoutConstant.ICON_BUTTON_LARGE_HOVER_WIDTH);
claimButton.setLayoutAlign(VerticalAlignment.CENTER);
claimButton.setShowRollOver(false);
claimButton.setDisabled(task.isHistory() | (null != task.getAssignee()));
claimButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent clickEvent) {
assign(getObject(), me, false);
}
});
infoLayout.addMember(claimButton);
addMember(infoLayout);
List<String> rows = new ArrayList<String>();
String engagementLevel = variables.get(KtunaxaBpmConstant.VAR_ENGAGEMENT_LEVEL);
if (task.isHistory()) {
rows.add(HtmlBuilder.trHtmlContent(new String[] {
HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "Assignee: "),
HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, task.getAssignee())
}));
rows.add(HtmlBuilder.trHtmlContent(new String[] {
HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "Started: "),
HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, task.getStartTime() + "")
}));
rows.add(HtmlBuilder.trHtmlContent(new String[] {
HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "Assignee: "),
HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, task.getEndTime() + "")
}));
} else {
rows.add(HtmlBuilder.trHtmlContent(new String[] {
HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "Assignee: "),
HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, task.getAssignee())
}));
rows.add(HtmlBuilder.trHtmlContent(new String[] {
HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "Created: "),
HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, task.getCreateTime() + "")
}));
rows.add(HtmlBuilder
.trHtmlContent(new String[] {
HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "Completion deadline: "),
HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE,
variables.get(KtunaxaBpmConstant.VAR_COMPLETION_DEADLINE))
}));
rows.add(HtmlBuilder.trHtmlContent(new String[] {
HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "E-mail: "),
HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, variables.get(KtunaxaBpmConstant.VAR_EMAIL))
}));
}
if (null != engagementLevel) {
String engagementContent = engagementLevel + " (prov " +
variables.get(KtunaxaBpmConstant.VAR_PROVINCE_ENGAGEMENT_LEVEL) + ")";
rows.add(HtmlBuilder.trHtmlContent(new String[] {
HtmlBuilder.tdStyle(STYLE_VARIABLE_NAME, "Engagement level: "),
HtmlBuilder.tdStyle(STYLE_VARIABLE_VALUE, engagementContent)
}));
}
// Simple 'list to array' code block. Exact array.length unknown until after
// the engagementLEvel has been checked for null.
String[] array = new String[rows.size()];
for (int i = 0; i < array.length; i++) {
array[i] = rows.get(i);
}
String htmlContent = HtmlBuilder.tableClassHtmlContent(BLOCK_CONTENT_TABLE_STYLE, array);
content = new HTMLFlow(htmlContent);
content.setStyleName(BLOCK_CONTENT_STYLE);
content.setWidth100();
addMember(content);
}
private void setClaimButtonStatus(TaskDto task) {
// disable when history or already assigned
claimButton.setDisabled(task.isHistory() | (null != task.getAssignee()));
}
private void setStartButtonStatus(TaskDto task) {
String me = UserContext.getInstance().getUser();
// disable when history or assigned to someone else
startButton.setDisabled(task.isHistory() | (null != task.getAssignee() && !me.equals(task.getAssignee())));
}
private void assign(final TaskDto task, final String assignee, final boolean start) {
AssignTaskRequest request = new AssignTaskRequest();
request.setTaskId(task.getId());
request.setAssignee(assignee);
GwtCommand command = new GwtCommand(AssignTaskRequest.COMMAND);
command.setCommandRequest(request);
GwtCommandDispatcher.getInstance().execute(command, new AbstractCommandCallback<GetReferralResponse>() {
public void execute(GetReferralResponse response) {
setStartButtonStatus(task);
setClaimButtonStatus(task);
if (start) {
start(task, response.getReferral());
} else {
MapLayout.getInstance().focusBpm();
}
}
});
}
private void start(TaskDto task, Feature referral) {
MapLayout mapLayout = MapLayout.getInstance();
needToDisplayCurrentTask = true;
mapLayout.setReferralAndTask(referral, task);
}
}
|
package cgeo.geocaching.storage.extension;
import cgeo.geocaching.storage.ContentStorage;
import cgeo.geocaching.storage.DataStore;
import cgeo.geocaching.storage.LocalStorage;
import cgeo.geocaching.utils.FileNameCreator;
import cgeo.geocaching.utils.FileUtils;
import cgeo.geocaching.utils.Log;
import android.app.Activity;
import android.net.Uri;
import androidx.annotation.NonNull;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.io.IOUtils;
public class Trackfiles extends DataStore.DBExtension {
private static final DataStore.DBExtensionType type = DataStore.DBExtensionType.DBEXTENSION_TRACKFILES;
private Trackfiles(final DataStore.DBExtension copyFrom) {
super(copyFrom);
}
public static Uri getUriFromKey(final String key) {
return Uri.fromFile(new File(LocalStorage.getTrackfilesDir(), key));
}
public String getFilename() {
return key;
}
public String getDisplayname() {
return string1;
}
public boolean isHidden() {
return long1 != 0;
}
/** to be called by Tracks only, not intended for direct usage */
public static String createTrackfile(final Activity activity, final Uri uri) {
// copy file to c:geo internal storage
final String fn = FileNameCreator.TRACKFILE.createName();
final Uri targetUri = Uri.fromFile(new File(LocalStorage.getTrackfilesDir(), fn));
try {
IOUtils.copy(
activity.getContentResolver().openInputStream(uri),
activity.getContentResolver().openOutputStream(targetUri));
} catch (IOException ioe) {
Log.e("Problem copying trackfile from '" + uri.getLastPathSegment() + "' to '" + targetUri + "'", ioe);
}
// add entry to list of trackfiles
removeAll(type, fn);
add(type, fn, 0, 0, 0, 0, ContentStorage.get().getName(uri), "", "", "");
return fn;
}
/** to be called by Tracks only, not intended for direct usage */
public static void removeTrackfile(@NonNull final String filename) {
removeAll(type, filename);
FileUtils.delete(new File(LocalStorage.getTrackfilesDir(), filename));
}
/** to be called by Tracks only, not intended for direct usage */
public static ArrayList<Trackfiles> getTrackfiles() {
final ArrayList<Trackfiles> result = new ArrayList<>();
for (DataStore.DBExtension item : getAll(type, null)) {
result.add(new Trackfiles(item));
}
return result;
}
public static void hide(@NonNull final String filename, final boolean hide) {
final DataStore.DBExtension itemRaw = load(type, filename);
if (itemRaw != null) {
final Trackfiles item = new Trackfiles(itemRaw);
if (item.isHidden() != hide) {
item.long1 = hide ? 1 : 0;
removeAll(type, filename);
add(type, item.key, item.long1, item.long2, item.long3, item.long4, item.string1, item.string2, item.string3, item.string4);
}
}
}
}
|
package de.exciteproject.refext.train;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import de.exciteproject.refext.ReferenceExtractor;
import de.exciteproject.refext.extract.ReferenceLineAnnotation;
import de.exciteproject.refext.util.FileUtils;
import pl.edu.icm.cermine.exception.AnalysisException;
/**
* Simplified annotator for generating training data. Does not handle
* footers/headers that appear inside a reference string.
*/
public class TrainingDataAnnotator {
public static void main(String[] args) throws AnalysisException, IOException {
File crfModelFile = new File(args[0]);
File inputDir = new File(args[1]);
File outputDir = new File(args[2]);
if (!outputDir.exists()) {
outputDir.mkdirs();
}
TrainingDataAnnotator trainingDataAnnotator = new TrainingDataAnnotator(crfModelFile);
List<File> inputFiles = FileUtils.asList(inputDir);
for (File inputFile : inputFiles) {
String subDirectories = inputFile.getParentFile().getAbsolutePath().replace("\\", "/")
.replaceFirst(inputDir.getAbsolutePath().replace("\\", "/"), "");
//File currentOutputDirectory = new File(outputDir.getAbsolutePath() + File.separator + subDirectories);
File currentOutputDirectory = new File(outputDir.getAbsolutePath());
String outputFileName = FilenameUtils.removeExtension(inputFile.getName()) + ".csv";
File outputFile = new File(currentOutputDirectory + File.separator + outputFileName);
// skip computation if outputFile already exists
if (outputFile.exists()) {
continue;
}
if (!currentOutputDirectory.exists()) {
currentOutputDirectory.mkdirs();
}
List<String> annotatedText = trainingDataAnnotator.annotateText(inputFile);
Files.write(Paths.get(outputFile.getAbsolutePath()), annotatedText, Charset.defaultCharset());
//Files.write(Paths.get(outputFile.getAbsolutePath().replace("\\", "/")), annotatedText, Charset.defaultCharset());
}
}
private ReferenceExtractor referenceExtractor;
public TrainingDataAnnotator(File crfModelFile) throws AnalysisException {
this.referenceExtractor = new ReferenceExtractor(crfModelFile);
}
public List<String> annotateText(File layoutFile) throws IOException, AnalysisException {
List<ReferenceLineAnnotation> annotatedLines = this.referenceExtractor.annotateLinesFromLayoutFile(layoutFile,
Charset.defaultCharset());
List<String> xmlAnnotatedLines = new ArrayList<String>();
for (int i = 0; i < annotatedLines.size(); i++) {
boolean addStartTag = false;
boolean addEndTag = false;
// System.out.println(annotatedLines.get(i));
String thisAnnotation = this.getAnnotation(annotatedLines, i);
String nextAnnotation = this.getAnnotation(annotatedLines, i + 1);
if (thisAnnotation.equals("B-REF")) {
addStartTag = true;
if (!nextAnnotation.equals("I-REF")) {
addEndTag = true;
}
} else {
if (thisAnnotation.equals("I-REF")) {
if (!nextAnnotation.equals("I-REF")) {
addEndTag = true;
}
}
}
String thisLine = this.getLine(annotatedLines, i);
if (addStartTag) {
thisLine = "<ref>" + thisLine;
}
if (addEndTag) {
thisLine = thisLine + "</ref>";
}
xmlAnnotatedLines.add(thisLine);
}
return xmlAnnotatedLines;
}
private String getAnnotation(List<ReferenceLineAnnotation> annotatedLines, int index) {
if (annotatedLines.size() <= index) {
return "";
} else {
return annotatedLines.get(index).getBestAnnotation();
}
}
private String getLine(List<ReferenceLineAnnotation> annotatedLines, int index) {
if (annotatedLines.size() <= index) {
return "";
} else {
return annotatedLines.get(index).getLine();
}
}
}
|
package org.jvnet.hudson.test;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.model.FreeStyleProject;
import hudson.model.Hudson;
import hudson.model.Item;
import junit.framework.TestCase;
import org.jvnet.hudson.test.HudsonHomeLoader.CopyExisting;
import org.jvnet.hudson.test.recipes.Recipe;
import org.jvnet.hudson.test.recipes.Recipe.Runner;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.security.HashUserRealm;
import org.mortbay.jetty.security.UserRealm;
import org.mortbay.jetty.webapp.Configuration;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.jetty.webapp.WebXmlConfiguration;
import org.xml.sax.SAXException;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Base class for all Hudson test cases.
*
* @author Kohsuke Kawaguchi
*/
public abstract class HudsonTestCase extends TestCase {
protected Hudson hudson;
protected final TestEnvironment env = new TestEnvironment();
protected HudsonHomeLoader homeLoader = HudsonHomeLoader.NEW;
/**
* TCP/IP port that the server is listening on.
*/
protected int localPort;
protected Server server;
/**
* Where in the {@link Server} is Hudson deploed?
*/
protected String contextPath = "/";
/**
* {@link Runnable}s to be invoked at {@link #tearDown()}.
*/
protected List<LenientRunnable> tearDowns = new ArrayList<LenientRunnable>();
protected HudsonTestCase(String name) {
super(name);
}
protected HudsonTestCase() {
}
protected void setUp() throws Exception {
env.pin();
recipe();
hudson = newHudson();
hudson.servletContext.setAttribute("app",hudson);
}
protected void tearDown() throws Exception {
for (LenientRunnable r : tearDowns)
r.run();
hudson.cleanUp();
env.dispose();
server.stop();
}
protected Hudson newHudson() throws Exception {
return new Hudson(homeLoader.allocate(), createWebServer());
}
/**
* Prepares a webapp hosting environment to get {@link ServletContext} implementation
* that we need for testing.
*/
protected ServletContext createWebServer() throws Exception {
server = new Server();
WebAppContext context = new WebAppContext(WarExploder.EXPLODE_DIR.getPath(), contextPath);
context.setClassLoader(getClass().getClassLoader());
context.setConfigurations(new Configuration[]{new WebXmlConfiguration(),new NoListenerConfiguration()});
server.setHandler(context);
SocketConnector connector = new SocketConnector();
server.addConnector(connector);
server.addUserRealm(configureUserRealm());
server.start();
localPort = connector.getLocalPort();
return context.getServletContext();
}
/**
* Configures a security realm for a test.
*/
protected UserRealm configureUserRealm() {
HashUserRealm realm = new HashUserRealm();
realm.setName("default"); // this is the magic realm name to make it effective on everywhere
realm.put("alice","alice");
realm.put("bob","bob");
realm.put("charlie","charlie");
realm.addUserToRole("alice","female");
realm.addUserToRole("bob","male");
realm.addUserToRole("charlie","male");
return realm;
}
// Convenience methods
protected FreeStyleProject createFreeStyleProject() throws IOException {
return createFreeStyleProject("test");
}
protected FreeStyleProject createFreeStyleProject(String name) throws IOException {
return (FreeStyleProject)hudson.createProject(FreeStyleProject.DESCRIPTOR,name);
}
// recipe methods. Control the test environments.
/**
* Called during the {@link #setUp()} to give a test case an opportunity to
* control the test environment in which Hudson is run.
*
* <p>
* From here, call a series of {@code withXXX} methods.
*/
protected void recipe() throws Exception {
// look for recipe meta-annotation
Method runMethod= getClass().getMethod(getName());
for( final Annotation a : runMethod.getAnnotations() ) {
Recipe r = a.annotationType().getAnnotation(Recipe.class);
if(r==null) continue;
final Runner runner = r.value().newInstance();
tearDowns.add(new LenientRunnable() {
public void run() throws Exception {
runner.tearDown(HudsonTestCase.this,a);
}
});
runner.setup(this,a);
}
}
public HudsonTestCase withNewHome() {
homeLoader = HudsonHomeLoader.NEW;
return this;
}
public HudsonTestCase withExistingHome(File source) {
homeLoader = new CopyExisting(source);
return this;
}
public HudsonTestCase withPresetData(String name) {
name = "/" + name + ".zip";
URL res = getClass().getResource(name);
if(res==null) throw new IllegalArgumentException("No such data set found: "+name);
homeLoader = new CopyExisting(res);
return this;
}
/**
* Extends {@link com.gargoylesoftware.htmlunit.WebClient} and provide convenience methods
* for accessing Hudson.
*/
public class WebClient extends com.gargoylesoftware.htmlunit.WebClient {
public WebClient() {
setJavaScriptEnabled(false);
}
public HtmlPage getPage(Item item) throws IOException, SAXException {
return (HtmlPage)getPage("http://localhost:"+localPort+contextPath+item.getUrl());
}
}
}
|
package dk.statsbiblioteket.newspaper.md5checker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import dk.statsbiblioteket.medieplatform.autonomous.RunnableComponent;
import dk.statsbiblioteket.medieplatform.autonomous.AutonomousComponentUtils;
import java.util.Map;
import java.util.Properties;
/** This is a sample component to serve as a guide to developers */
public class MD5Checker {
private static Logger log = LoggerFactory.getLogger(MD5Checker.class);
/**
* The class must have a main method, so it can be started as a command line tool
*
* @param args the arguments.
*
* @throws Exception
* @see AutonomousComponentUtils#parseArgs(String[])
*/
public static void main(String[] args)
throws
Exception {
log.info("Starting with args {}", args);
//Parse the args to a properties construct
Properties properties = AutonomousComponentUtils.parseArgs(args);
//make a new runnable component from the properties
RunnableComponent component = new MD5CheckerComponent(properties);
Map<String, Boolean> result = AutonomousComponentUtils.startAutonomousComponent(properties, component);
AutonomousComponentUtils.printResults(result);
}
}
|
package edu.columbia.tjw.item.fit.curve;
import edu.columbia.tjw.item.*;
import edu.columbia.tjw.item.fit.PackedParameters;
import edu.columbia.tjw.item.fit.ParamFittingGrid;
import edu.columbia.tjw.item.fit.ReducedParameterVector;
import edu.columbia.tjw.item.optimize.*;
public final class PackedCurveFunction<S extends ItemStatus<S>, R extends ItemRegressor<R>, T extends ItemCurveType<T>>
extends ThreadedMultivariateFunction implements MultivariateDifferentiableFunction
{
private final CurveParamsFitter<S, R, T> _curveFitter;
private final ItemParameters<S, R, T> _unchangedParams;
private final ItemParameters<S, R, T> _initParams;
private final PackedParameters<S, R, T> _packed;
private final ParamFittingGrid<S, R, T> _grid;
private final double _origIntercept;
private ItemModel<S, R, T> _updatedModel;
public PackedCurveFunction(final ItemSettings settings_, final ItemCurveParams<R, T> curveParams_, final S toStatus_, final ItemParameters<S, R, T> initParams_,
final ParamFittingGrid<S, R, T> grid_, final CurveParamsFitter<S, R, T> curveFitter_, final boolean subtractStarting_)
{
super(settings_.getThreadBlockSize(), settings_.getUseThreading());
//N.B: We need to rebuild the curve params so that we don't end up with ItemParams where a curve being calibrated is
// shared with a pre-existing item because they point to the same physical instance.
final double[] curveVector = new double[curveParams_.size()];
curveParams_.extractPoint(curveVector);
final ItemCurveParams<R, T> repacked = new ItemCurveParams<>(curveParams_, curveParams_.getCurve(0).getCurveType().getFactory(), curveVector);
_unchangedParams = initParams_;
_curveFitter = curveFitter_;
_initParams = initParams_.addBeta(repacked, toStatus_);
_updatedModel = new ItemModel<>(_initParams);
_grid = new ParamFittingGrid<>(_initParams, grid_.getUnderlying());
final int entryIndex = _initParams.getEntryCount() - 1;//_initParams.getEntryIndex(curveParams_);
final int interceptIndex = _initParams.getInterceptIndex();
final int toTransition = _initParams.getToIndex(toStatus_);
final PackedParameters<S, R, T> rawPacked = _initParams.generatePacked();
final boolean[] keep = new boolean[rawPacked.size()];
_origIntercept = initParams_.getBeta(toTransition, _initParams.getInterceptIndex());
for (int i = 0; i < rawPacked.size(); i++)
{
final int currentEntry = rawPacked.getEntry(i);
if (rawPacked.betaIsFrozen(i))
{
continue;
}
if (currentEntry == interceptIndex && toTransition == rawPacked.getTransition(i))
{
keep[i] = true;
continue;
}
if (currentEntry != entryIndex)
{
continue;
}
keep[i] = true;
}
_packed = new ReducedParameterVector<>(keep, rawPacked);
if (_packed.size() != curveParams_.size())
{
throw new IllegalStateException("Impossible.");
}
}
@Override
public int dimension()
{
return _packed.size();
}
@Override
public int resultSize(int start_, int end_)
{
final int size = (end_ - start_);
return size;
}
@Override
public int numRows()
{
return _grid.size();
}
@Override
protected void prepare(MultivariatePoint input_)
{
final int dimension = this.dimension();
boolean changed = false;
for (int i = 0; i < dimension; i++)
{
double value = input_.getElement(i);
if (i == 0)
{
// Intercept term
value += _origIntercept;
}
if (value != _packed.getParameter(i))
{
_packed.setParameter(i, value);
changed = true;
}
}
if (!changed)
{
return;
}
final ItemParameters<S, R, T> updated = _packed.generateParams();
_updatedModel = new ItemModel<>(updated);
}
public ItemParameters<S, R, T> getParams()
{
return _updatedModel.getParams();
}
public ItemParameters<S, R, T> getInitParams()
{
return _unchangedParams;
}
public double calcValue(final int index_)
{
final ItemModel<S, R, T> localModel = _updatedModel.clone();
return localModel.logLikelihood(_grid, index_);
}
public double[] calcGradient(final int index_)
{
final ItemModel<S, R, T> localModel = _updatedModel.clone();
final double[] gradient = new double[_packed.size()];
localModel.computeGradient(this._grid, _packed, index_, gradient, null);
return gradient;
}
@Override
protected void evaluate(int start_, int end_, EvaluationResult result_)
{
if (start_ == end_)
{
return;
}
final ItemModel<S, R, T> localModel = _updatedModel.clone();
for (int i = start_; i < end_; i++)
{
final double ll = localModel.logLikelihood(_grid, i);
result_.add(ll, result_.getHighWater(), i + 1);
}
result_.setHighRow(end_);
}
@Override
protected MultivariateGradient evaluateDerivative(int start_, int end_, MultivariatePoint input_, EvaluationResult result_)
{
final double[] itemDeriv = new double[_packed.size()];
final double[] totalDeriv = new double[_packed.size()];
final ItemModel<S, R, T> localModel = _updatedModel.clone();
for (int i = start_; i < end_; i++)
{
localModel.computeGradient(this._grid, _packed, i, itemDeriv, null);
for (int w = 0; w < itemDeriv.length; w++)
{
if (Double.isNaN(itemDeriv[w]) || Double.isInfinite(itemDeriv[w]))
{
System.out.println("Unexpected.");
localModel.computeGradient(this._grid, _packed, i, itemDeriv, null);
}
totalDeriv[w] += itemDeriv[w];
}
}
final int count = (end_ - start_);
//N.B: we are computing the negative log likelihood.
final double invCount = 1.0 / count;
for (int i = 0; i < totalDeriv.length; i++)
{
totalDeriv[i] = totalDeriv[i] * invCount;
}
final MultivariatePoint der = new MultivariatePoint(totalDeriv);
final MultivariateGradient grad = new MultivariateGradient(input_, der, null, 0.0);
return grad;
}
}
|
package org.openhab.habdroid.model;
import android.graphics.Color;
import android.util.Log;
import com.crittercism.app.Crittercism;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This is a class to hold basic information about openHAB Item.
*/
public class OpenHABItem {
private String name;
private String type;
private String groupType;
private String state = "";
private String link;
private final static String TAG = OpenHABItem.class.getSimpleName();
private final static Pattern HSB_PATTERN = Pattern.compile("^\\d+,\\d+,(\\d+)$");
public OpenHABItem(Node startNode) {
if (startNode.hasChildNodes()) {
NodeList childNodes = startNode.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i ++) {
Node childNode = childNodes.item(i);
if (childNode.getNodeName().equals("type")) {
this.setType(childNode.getTextContent());
} else if (childNode.getNodeName().equals("groupType")) {
this.setGroupType(childNode.getTextContent());
} else if (childNode.getNodeName().equals("name")) {
this.setName(childNode.getTextContent());
} else if (childNode.getNodeName().equals("state")) {
if (childNode.getTextContent().equals("Uninitialized")) {
this.setState(null);
} else {
this.setState(childNode.getTextContent());
}
} else if (childNode.getNodeName().equals("link")) {
this.setLink(childNode.getTextContent());
}
}
}
}
public OpenHABItem(JSONObject jsonObject) {
try {
if (jsonObject.has("type"))
this.setType(jsonObject.getString("type"));
if (jsonObject.has("groupType"))
this.setGroupType(jsonObject.getString("groupType"));
if (jsonObject.has("name"))
this.setName(jsonObject.getString("name"));
if (jsonObject.has("state")) {
if (jsonObject.getString("state").equals("NULL") || jsonObject.getString("state").equals("UNDEF")) {
this.setState(null);
} else {
this.setState(jsonObject.getString("state"));
}
}
if (jsonObject.has("link"))
this.setLink(jsonObject.getString("link"));
} catch (JSONException e) {
e.printStackTrace();
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getGroupType() {
return groupType;
}
public void setGroupType(String groupType) {
this.groupType = groupType;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public boolean getStateAsBoolean() {
// For uninitialized/null state return false
if (state == null) {
return false;
}
// If state is ON for switches return True
if (state.equals("ON")) {
return true;
}
Matcher hsbMatcher = HSB_PATTERN.matcher(state);
if(hsbMatcher.find()) {
String brightness = hsbMatcher.group(1);
return isValueDecimalIntegerAndGreaterThanZero(brightness);
}
return isValueDecimalIntegerAndGreaterThanZero(state);
}
private Boolean isValueDecimalIntegerAndGreaterThanZero(String value) {
try {
int decimalValue = Integer.valueOf(value);
return decimalValue > 0;
} catch (NumberFormatException e) {
return false;
}
}
public Float getStateAsFloat() {
// For uninitialized/null state return zero
if (state == null) {
return new Float(0);
}
if ("ON".equals(state)) {
return new Float(100);
}
if ("OFF".equals(state)) {
return new Float(0);
}
try {
Float result = Float.parseFloat(state);
} catch (NumberFormatException e) {
if (e != null) {
Crittercism.logHandledException(e);
Log.e(TAG, e.getMessage());
}
}
return Float.parseFloat(state);
}
public float[] getStateAsHSV() {
if (state == null) {
float[] result = {0, 0, 0};
return result;
}
String[] stateSplit = state.split(",");
if (stateSplit.length == 3) { // We need exactly 3 numbers to operate this
float[] result = {Float.parseFloat(stateSplit[0]), Float.parseFloat(stateSplit[1])/100, Float.parseFloat(stateSplit[2])/100};
return result;
} else {
float[] result = {0, 0, 0};
return result;
}
}
public int getStateAsColor() {
return Color.HSVToColor(getStateAsHSV());
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
|
package edu.msudenver.cs3250.group6.msubanner.entities;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
/**
* Persistent Days Class
*/
public class Days {
/**
* Days
*/
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private String id;
/**
* ArrayList of Day enums
*/
private HashMap<Integer,String> dayList = new HashMap<Integer,String>();
/**
* Valid Day to populate dayList
*/
public enum Day {
SUNDAY(1, "Sunday"),
MONDAY(2, "Monday" ),
TUESDAY(3, "Tuesday"),
WEDNESDAY(4, "Wednesday"),
THURSDAY(5, "Thursday"),
FRIDAY(6, "Friday"),
SATURDAY(7, "Saturday");
private int dayNum;
private String dayName;
/**
* Constructor for Day
*
* @param dayName the name of the day
* @param dayNum the number value of the day
*/
Day(int dayNum, final String dayName) {
this.dayNum = dayNum;
this.dayName = dayName;
}
}
/**
* Sets the id of an Days instance.
*
* @param id
*/
public void setId(String id) {
this.id = id;
}
/**
* Returns the id of the Days
*
* @return String id number of the Days
*/
public String getId() { return id; }
/**
* Adds an association of number to day to the dayList HashMap
*
* @param dayToAdd
*/
public void addToDayList(String dayToAdd) {
if(dayToAdd.equals(Day.SUNDAY.dayName)) {
dayList.put(Day.SUNDAY.dayNum, Day.SUNDAY.dayName);
}
else if(dayToAdd.equals(Day.MONDAY.dayName)) {
dayList.put(Day.MONDAY.dayNum, Day.MONDAY.dayName);
}
else if(dayToAdd.equals(Day.TUESDAY.dayName)) {
dayList.put(Day.TUESDAY.dayNum, Day.TUESDAY.dayName);
}
else if(dayToAdd.equals(Day.WEDNESDAY.dayName)) {
dayList.put(Day.WEDNESDAY.dayNum, Day.WEDNESDAY.dayName);
}
else if(dayToAdd.equals(Day.THURSDAY.dayName)) {
dayList.put(Day.THURSDAY.dayNum, Day.THURSDAY.dayName);
}
else if(dayToAdd.equals(Day.FRIDAY.dayName)) {
dayList.put(Day.FRIDAY.dayNum, Day.FRIDAY.dayName);
}
else if(dayToAdd.equals(Day.SATURDAY.dayName)) {
dayList.put(Day.SATURDAY.dayNum, Day.SATURDAY.dayName);
}
else {
System.out.println("Console Warning: Invalid input '"+ dayToAdd +"', Days.addToDayList() expected a capitalized day name, ie. Monday, Tuesday, etc");
}
}
/**
* Removes an association of number to day to the dayList HashMap
*
* @param dayToRemove
*/
public void removeDayFromList(String dayToRemove) {
if(dayToRemove.equals(Day.SUNDAY.dayName)) {
dayList.remove(Day.SUNDAY.dayNum);
}
else if(dayToRemove.equals(Day.MONDAY.dayName)) {
dayList.remove(Day.MONDAY.dayNum);
}
else if(dayToRemove.equals(Day.TUESDAY.dayName)) {
dayList.remove(Day.TUESDAY.dayNum);
}
else if(dayToRemove.equals(Day.WEDNESDAY.dayName)) {
dayList.remove(Day.WEDNESDAY.dayNum);
}
else if(dayToRemove.equals(Day.THURSDAY.dayName)) {
dayList.remove(Day.THURSDAY.dayNum);
}
else if(dayToRemove.equals(Day.FRIDAY.dayName)) {
dayList.remove(Day.FRIDAY.dayNum);
}
else if(dayToRemove.equals(Day.SATURDAY.dayName)) {
dayList.remove(Day.SATURDAY.dayNum);
}
else {
System.out.println("Console Warning: Invalid input '"+ dayToRemove +"', Days.removeDayFromList() expected a capitalized day name, ie. Monday, Tuesday, etc");
}
}
/**
* Returns a HashMap of Day values
*
* @return HashMap of Day values
*/
public HashMap<Integer,String> getDayList() {
return dayList;
}
public boolean hasConflict(HashMap<Integer,String> mapToCompare) {
if(mapToCompare.size() >= 4 && this.dayList.size() >= 4) {
return true;
}
Set<Integer> set1 = new HashSet<>();
set1.addAll(this.dayList.keySet());
Set<Integer> set2 = new HashSet<>();
set2.addAll(mapToCompare.keySet());
set1.removeAll(set2);
if(set1.size() != this.dayList.keySet().size()) {
return true;
}
else {
return false;
}
}
}
|
package edu.virginia.psyc.pi.security;
import edu.virginia.psyc.pi.persistence.ParticipantDAO;
import edu.virginia.psyc.pi.persistence.ParticipantRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.security.provisioning.UserDetailsManager;
import javax.sql.DataSource;
import java.util.List;
@Configuration
@EnableWebMvcSecurity // The enables the CRF Token in LimeLeaf forms.
@EnableWebSecurity
@Order(0) // so that it is used before the default one in Spring Boot
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final Logger LOG = LoggerFactory.getLogger(SecurityConfiguration.class);
@Autowired
private ParticipantRepository participantRepository;
/**
* Checks database for user details
*/
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(new UserDetailsService() {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
List<ParticipantDAO> participants = participantRepository.findByEmail(username);
if(participants.size() > 0) {
LOG.info("Participant Found:" + participants.get(0));
return participants.get(0);
} else return null;
}
}).passwordEncoder(new StandardPasswordEncoder());
/**
auth
.inMemoryAuthentication()
.withUser("user") // #1
.password("password")
.roles("USER")
.and()
.withUser("admin") // #2
.password("password")
.roles("ADMIN", "USER");
**/
}
@Override
/**
* Restrict access to admin endpoints to users with admin roles,
* and restrict access to user detail endpoints to participants.
*/
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(
.antMatchers("/user/**").hasRole("USER");
}
**/
/**
* Poke a hole completely through to allow posting to the data endpoint
* as we don't have security settings built into the PiPlayer and I'm not
* certain their really need to be.
* @param webSecurity
* @throws Exception
*/
@Override
public void configure(WebSecurity webSecurity) throws Exception
{
webSecurity
.ignoring()
// All of Spring Security will ignore the requests
|
package org.codehaus.modello.model;
import org.codehaus.modello.ModelloRuntimeException;
import org.codehaus.modello.metadata.ModelMetadata;
import org.codehaus.modello.plugin.model.ModelClassMetadata;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @author <a href="mailto:[email protected]">Jason van Zyl</a>
* @author <a href="mailto:[email protected]">Emmanuel Venisse</a>
* @version $Id$
*/
public class Model
extends BaseElement
{
private String id;
private List classes = new ArrayList();
private List defaults = new ArrayList();
private List interfaces = new ArrayList();
private transient Map classMap = new HashMap();
private transient Map defaultMap = new HashMap();
private transient Map interfaceMap = new HashMap();
private VersionDefinition versionDefinition;
public Model()
{
super( true );
}
public String getId()
{
return id;
}
public void setId( String id )
{
this.id = id;
}
public VersionDefinition getVersionDefinition()
{
return versionDefinition;
}
public void setVersionDefinition( VersionDefinition versionDefinition )
{
this.versionDefinition = versionDefinition;
}
public ModelMetadata getMetadata( String key )
{
return (ModelMetadata) getMetadata( ModelMetadata.class, key );
}
public String getRoot( Version version )
{
List classes = getClasses( version );
String className = null;
for ( Iterator i = classes.iterator(); i.hasNext(); )
{
ModelClass currentClass = (ModelClass) i.next();
ModelClassMetadata metadata = null;
try
{
metadata = (ModelClassMetadata) currentClass.getMetadata( ModelClassMetadata.ID );
}
catch ( Exception e )
{
}
if ( metadata != null && metadata.isRootElement() )
{
if ( className == null )
{
className = currentClass.getName();
}
else
{
throw new ModelloRuntimeException(
"There are more than one class as root element for this version " + version + "." );
}
}
}
if ( className == null )
{
throw new ModelloRuntimeException( "There aren't root element for version " + version + "." );
}
return className;
}
/**
* @deprecated This shouldn't be used, anything querying the model should read the
* package of the class. Use getDefaultPackageName(..).
*/
public String getPackageName( boolean withVersion, Version version )
{
return getDefaultPackageName( withVersion, version );
}
public List getAllClasses()
{
return classes;
}
public List getClasses( Version version )
{
ArrayList classList = new ArrayList();
for ( Iterator i = classes.iterator(); i.hasNext(); )
{
ModelClass currentClass = (ModelClass) i.next();
if ( version.inside( currentClass.getVersionRange() ) )
{
classList.add( currentClass );
}
}
return classList;
}
public ModelClass getClass( String type, Version version )
{
return getClass( type, new VersionRange( version ) );
}
public ModelClass getClass( String type, VersionRange versionRange )
{
ModelClass value = getModelClass( type, versionRange );
if ( value != null )
{
return value;
}
throw new ModelloRuntimeException(
"There is no class '" + type + "' in the version range '" + versionRange.toString() + "'." );
}
public boolean hasClass( String type, Version version )
{
ModelClass value = getModelClass( type, new VersionRange( version ) );
return value != null;
}
private ModelClass getModelClass( String type, VersionRange versionRange )
{
ArrayList classList = (ArrayList) classMap.get( type );
ModelClass value = null;
if ( classList != null )
{
for ( Iterator i = classList.iterator(); i.hasNext() && value == null; )
{
ModelClass modelClass = (ModelClass) i.next();
if ( versionRange.getFromVersion().inside( modelClass.getVersionRange() ) &&
versionRange.getToVersion().inside( modelClass.getVersionRange() ) )
{
value = modelClass;
}
}
}
return value;
}
public void addClass( ModelClass modelClass )
{
if ( classMap.containsKey( modelClass.getName() ) )
{
ArrayList classList = (ArrayList) classMap.get( modelClass.getName() );
for ( Iterator i = classList.iterator(); i.hasNext(); )
{
ModelClass currentClass = (ModelClass) i.next();
if ( VersionUtil.isInConflict( modelClass.getVersionRange(), currentClass.getVersionRange() ) )
{
throw new ModelloRuntimeException( "Duplicate class: " + modelClass.getName() + "." );
}
}
}
else
{
ArrayList classList = new ArrayList();
classMap.put( modelClass.getName(), classList );
}
getAllClasses().add( modelClass );
( (ArrayList) classMap.get( modelClass.getName() ) ).add( modelClass );
}
// Defaults
public List getDefaults()
{
return defaults;
}
public ModelDefault getDefault( String key )
throws ModelValidationException
{
ModelDefault modelDefault = (ModelDefault) defaultMap.get( key );
if ( modelDefault == null )
{
modelDefault = ModelDefault.getDefault( key );
}
return modelDefault;
}
public void addDefault( ModelDefault modelDefault )
{
if ( defaultMap.containsKey( modelDefault.getKey() ) )
{
throw new ModelloRuntimeException( "Duplicate default: " + modelDefault.getKey() + "." );
}
getDefaults().add( modelDefault );
defaultMap.put( modelDefault.getKey(), modelDefault );
}
public String getDefaultPackageName( boolean withVersion, Version version )
{
String packageName;
try
{
packageName = getDefault( ModelDefault.PACKAGE ).getValue();
}
catch ( ModelValidationException mve )
{
packageName = ModelDefault.PACKAGE_VALUE;
}
if ( withVersion )
{
packageName += "." + version.toString( "v", "_" );
}
return packageName;
}
public List getAllInterfaces()
{
return interfaces;
}
public List getInterfaces( Version version )
{
ArrayList interfaceList = new ArrayList();
for ( Iterator i = interfaces.iterator(); i.hasNext(); )
{
ModelInterface currentInterface = (ModelInterface) i.next();
if ( version.inside( currentInterface.getVersionRange() ) )
{
interfaceList.add( currentInterface );
}
}
return interfaceList;
}
public ModelInterface getInterface( String type, Version version )
{
return getInterface( type, new VersionRange( version ) );
}
public ModelInterface getInterface( String type, VersionRange versionRange )
{
ArrayList interfaceList = (ArrayList) interfaceMap.get( type );
if ( interfaceList != null )
{
for ( Iterator i = interfaceList.iterator(); i.hasNext(); )
{
ModelInterface modelInterface = (ModelInterface) i.next();
if ( versionRange.getFromVersion().inside( modelInterface.getVersionRange() ) &&
versionRange.getToVersion().inside( modelInterface.getVersionRange() ) )
{
return modelInterface;
}
}
}
throw new ModelloRuntimeException(
"There is no interface '" + type + "' in the version range '" + versionRange.toString() + "'." );
}
public void addInterface( ModelInterface modelInterface )
{
if ( interfaceMap.containsKey( modelInterface.getName() ) )
{
ArrayList interfaceList = (ArrayList) interfaceMap.get( modelInterface.getName() );
for ( Iterator i = interfaceList.iterator(); i.hasNext(); )
{
ModelInterface currentInterface = (ModelInterface) i.next();
if ( VersionUtil.isInConflict( modelInterface.getVersionRange(), currentInterface.getVersionRange() ) )
{
throw new ModelloRuntimeException( "Duplicate interface: " + modelInterface.getName() + "." );
}
}
}
else
{
ArrayList interfaceList = new ArrayList();
interfaceMap.put( modelInterface.getName(), interfaceList );
}
getAllInterfaces().add( modelInterface );
( (ArrayList) interfaceMap.get( modelInterface.getName() ) ).add( modelInterface );
}
public void initialize()
{
for ( Iterator i = classes.iterator(); i.hasNext(); )
{
ModelClass modelClass = (ModelClass) i.next();
modelClass.initialize( this );
}
for ( Iterator i = interfaces.iterator(); i.hasNext(); )
{
ModelInterface modelInterface = (ModelInterface) i.next();
modelInterface.initialize( this );
}
}
public void validateElement()
{
}
}
|
package edu.wright.hendrix11.familyTree.bean;
import edu.wright.hendrix11.familyTree.dataBean.PersonDataBean;
import edu.wright.hendrix11.familyTree.entity.Person;
import edu.wright.hendrix11.familyTree.entity.event.Birth;
import edu.wright.hendrix11.familyTree.entity.event.Death;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Joe Hendrix
*/
@Named
@ViewScoped
public class IndividualBean implements Serializable
{
private static final Logger LOG = Logger.getLogger(IndividualBean.class.getName());
@EJB
private PersonDataBean personDataBean;
private Person person;
private Person tempPerson;
@PostConstruct
public void initialize()
{
person = personDataBean.findFirst();
tempPerson = new Person();
tempPerson.setName(person.getName());
tempPerson.setGender(person.getGender());
if ( person.getBirth() != null )
tempPerson.setBirth(person.getBirth());
else
tempPerson.setBirth(new Birth());
if ( person.getDeath() != null )
tempPerson.setDeath(person.getDeath());
else
tempPerson.setDeath(new Death());
}
/**
* Returns the id of the current {@link Person}.
*
* @return the id of the current {@link Person}
*
* @see edu.wright.hendrix11.familyTree.entity.Person#getId()
*/
public int getPersonId()
{
return person.getId();
}
/**
* Sets the current {@link Person} based on the {@code personId}.
*
* @param personId the id of the {@link Person} to be set
*
* @see edu.wright.hendrix11.familyTree.dataBean.PersonDataBean
*/
public void setPersonId(int personId)
{
person = personDataBean.find(personId);
}
/**
* Returns the currently set person.
*
* @return the currently set person
*/
public Person getPerson()
{
return person;
}
/**
* Sets the person to be viewed.
*
* @param person the person to be viewed
*/
public void setPerson(Person person)
{
this.person = person;
}
/**
* @return
*/
public Person getTempPerson()
{
return tempPerson;
}
/**
* @param tempPerson
*/
public void setTempPerson(Person tempPerson)
{
this.tempPerson = tempPerson;
}
public void updatePerson()
{
LOG.log(Level.SEVERE, "Still developing!! " + tempPerson.getName());
person.setName(tempPerson.getName());
person.setGender(tempPerson.getGender());
personDataBean.update(person);
}
}
|
package fi.helsinki.cs.tmc.cli.command;
import fi.helsinki.cs.tmc.cli.Application;
import fi.helsinki.cs.tmc.core.TmcCore;
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.Exercise;
import fi.helsinki.cs.tmc.core.domain.ProgressObserver;
import java.util.List;
import java.util.concurrent.Callable;
public class ListExercisesCommand implements Command {
private Application app;
public ListExercisesCommand(Application app) {
this.app = app;
}
@Override
public String getDescription() {
return "List the exercises for a specific course";
}
@Override
public String getName() {
return "list-exercises";
}
@Override
public void run(String[] args) {
Callable<List<Course>> callable;
List<Course> courses;
TmcCore core;
List<Exercise> exercises;
Course course = null;
if( args.length == 0 ) {
return;
}
core = this.app.getTmcCore();
callable = core.listCourses(ProgressObserver.NULL_OBSERVER);
try {
courses = callable.call();
} catch (Exception e) {
return;
}
for (Course item : courses) {
if (item.getName().equals(args[0])) {
course = item;
}
}
try {
course = core.getCourseDetails(ProgressObserver.NULL_OBSERVER, course).call();
} catch (Exception e) {
return;
}
exercises = course.getExercises();
for (Exercise exercise : exercises) {
System.out.println(exercise.getName());
}
}
}
|
package graphql.execution;
import graphql.ExceptionWhileDataFetching;
import graphql.PublicApi;
import graphql.language.SourceLocation;
import graphql.util.LogKit;
import org.slf4j.Logger;
import java.util.concurrent.CompletionException;
/**
* The standard handling of data fetcher error involves placing a {@link ExceptionWhileDataFetching} error
* into the error collection
*/
@PublicApi
public class SimpleDataFetcherExceptionHandler implements DataFetcherExceptionHandler {
private static final Logger logNotSafe = LogKit.getNotPrivacySafeLogger(SimpleDataFetcherExceptionHandler.class);
@Override
public DataFetcherExceptionHandlerResult onException(DataFetcherExceptionHandlerParameters handlerParameters) {
Throwable exception = unwrap(handlerParameters.getException());
SourceLocation sourceLocation = handlerParameters.getSourceLocation();
ResultPath path = handlerParameters.getPath();
ExceptionWhileDataFetching error = new ExceptionWhileDataFetching(path, exception, sourceLocation);
logException(error, exception);
return DataFetcherExceptionHandlerResult.newResult().error(error).build();
}
/**
* Called to log the exception - a subclass could choose to something different in logging terms
* @param error the graphql error
* @param exception the exception that happened
*/
protected void logException(ExceptionWhileDataFetching error, Throwable exception) {
logNotSafe.warn(error.getMessage(), exception);
}
/**
* Called to unwrap an exception to a more suitable cause if required.
*
* @param exception the exception to unwrap
*
* @return the suitable exception
*/
protected Throwable unwrap(Throwable exception) {
if (exception.getCause() != null) {
if (exception instanceof CompletionException) {
return exception.getCause();
}
}
return exception;
}
}
|
package hu.sztaki.ilab.longneck.process.constraint;
import java.util.List;
public class CdvLogic {
private int[] coeffs;
private int mod;
public void setMod(int mod) {
this.mod = mod;
}
public void setCoeffs(List<Integer> coeffs) {
this.coeffs = new int[coeffs.size()];
for (int i = 0; i < coeffs.size(); ++i) {
this.coeffs[i] = coeffs.get(i);
}
}
public boolean check(String value) {
if (value==null)
return false;
if (value.length() != coeffs.length)
return false;
int checkSum = 0;
for (int i = 0; i < coeffs.length; ++i) {
int digit = (int) value.charAt(i) - 48;
if (digit < 0 || digit > 9)
return false;
checkSum += digit * coeffs[i];
}
checkSum %= mod;
return (checkSum == 0) ? true : false;
}
}
|
package hudson.plugins.analysis.collector;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.Result;
import hudson.plugins.analysis.core.AbstractResultAction;
import hudson.plugins.analysis.core.BuildResult;
import hudson.plugins.analysis.core.HealthAwarePublisher;
import hudson.plugins.analysis.core.ParserResult;
import hudson.plugins.analysis.util.PluginLogger;
import hudson.plugins.analysis.util.model.FileAnnotation;
import hudson.plugins.checkstyle.CheckStyleResultAction;
import hudson.plugins.dry.DryResultAction;
import hudson.plugins.findbugs.FindBugsResultAction;
import hudson.plugins.pmd.PmdResultAction;
import hudson.plugins.tasks.TasksResultAction;
import hudson.plugins.warnings.WarningsResultAction;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import org.kohsuke.stapler.DataBoundConstructor;
/**
* Collects the results of the various analysis plug-ins.
*
* @author Ulli Hafner
*/
// CHECKSTYLE:COUPLING-OFF
public class AnalysisPublisher extends HealthAwarePublisher {
/** Unique ID of this class. */
private static final long serialVersionUID = 5512072640635006098L;
/**
* Creates a new instance of {@link AnalysisPublisher}.
*
* @param threshold
* Annotation threshold to be reached if a build should be
* considered as unstable.
* @param newThreshold
* New annotations threshold to be reached if a build should be
* considered as unstable.
* @param failureThreshold
* Annotation threshold to be reached if a build should be
* considered as failure.
* @param newFailureThreshold
* New annotations threshold to be reached if a build should be
* considered as failure.
* @param healthy
* Report health as 100% when the number of annotations is less
* than this value
* @param unHealthy
* Report health as 0% when the number of annotations is greater
* than this value
* @param thresholdLimit
* determines which warning priorities should be considered when
* evaluating the build stability and health
* @param defaultEncoding
* the default encoding to be used when reading and parsing files
*/
// CHECKSTYLE:OFF
@SuppressWarnings("PMD.ExcessiveParameterList")
@DataBoundConstructor
public AnalysisPublisher(final String threshold, final String newThreshold,
final String failureThreshold, final String newFailureThreshold,
final String healthy, final String unHealthy, final String thresholdLimit,
final String defaultEncoding, final boolean useDeltaValues) {
super(threshold, newThreshold, failureThreshold, newFailureThreshold,
healthy, unHealthy, thresholdLimit, defaultEncoding, useDeltaValues, "ANALYSIS-COLLECTOR");
}
// CHECKSTYLE:ON
/**
* Initializes the plug-ins that should participate in the results of this
* analysis collector.
*
* @return the plug-in actions to read the results from
*/
private ArrayList<Class<? extends AbstractResultAction<? extends BuildResult>>> getParticipatingPlugins() {
ArrayList<Class<? extends AbstractResultAction<? extends BuildResult>>> pluginResults;
pluginResults = new ArrayList<Class<? extends AbstractResultAction<? extends BuildResult>>>();
if (AnalysisDescriptor.isCheckStyleInstalled()) {
pluginResults.add(CheckStyleResultAction.class);
}
if (AnalysisDescriptor.isDryInstalled()) {
pluginResults.add(DryResultAction.class);
}
if (AnalysisDescriptor.isFindBugsInstalled()) {
pluginResults.add(FindBugsResultAction.class);
}
if (AnalysisDescriptor.isPmdInstalled()) {
pluginResults.add(PmdResultAction.class);
}
if (AnalysisDescriptor.isOpenTasksInstalled()) {
pluginResults.add(TasksResultAction.class);
}
if (AnalysisDescriptor.isWarningsInstalled()) {
pluginResults.add(WarningsResultAction.class);
}
return pluginResults;
}
/** {@inheritDoc} */
@Override
public Action getProjectAction(final AbstractProject<?, ?> project) {
return new AnalysisProjectAction(project);
}
/** {@inheritDoc} */
@Override
public BuildResult perform(final AbstractBuild<?, ?> build, final PluginLogger logger) throws InterruptedException, IOException {
ParserResult overallResult = new ParserResult();
for (Class<? extends AbstractResultAction<? extends BuildResult>> result : getParticipatingPlugins()) {
AbstractResultAction<? extends BuildResult> action = build.getAction(result);
if (action != null) {
BuildResult actualResult = action.getResult();
Collection<FileAnnotation> annotactualResultations = actualResult.getAnnotations();
overallResult.addAnnotations(annotactualResultations);
}
}
AnalysisResult result = new AnalysisResult(build, getDefaultEncoding(), overallResult);
build.getActions().add(new AnalysisResultAction(build, this, result));
return result;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override
public BuildStepDescriptor<Publisher> getDescriptor() {
return super.getDescriptor();
}
/** {@inheritDoc} */
@Override
protected boolean canContinue(final Result result) {
return true;
}
}
|
package i5.las2peer.webConnector;
import i5.las2peer.execution.NoSuchServiceException;
import i5.las2peer.execution.NoSuchServiceMethodException;
import i5.las2peer.execution.ServiceInvocationException;
import i5.las2peer.p2p.AgentNotKnownException;
import i5.las2peer.p2p.Node;
import i5.las2peer.p2p.TimeoutException;
import i5.las2peer.restMapper.RESTMapper;
import i5.las2peer.restMapper.data.InvocationData;
import i5.las2peer.restMapper.data.Pair;
import i5.las2peer.restMapper.exceptions.NoMethodFoundException;
import i5.las2peer.restMapper.exceptions.NotSupportedUriPathException;
import i5.las2peer.security.L2pSecurityException;
import i5.las2peer.security.Mediator;
import i5.las2peer.security.PassphraseAgent;
import i5.las2peer.security.UserAgent;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import net.minidev.json.JSONObject;
import rice.p2p.util.Base64;
import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.oauth2.sdk.http.HTTPRequest;
import com.nimbusds.oauth2.sdk.http.HTTPRequest.Method;
import com.nimbusds.oauth2.sdk.http.HTTPResponse;
import com.nimbusds.openid.connect.sdk.UserInfoErrorResponse;
import com.nimbusds.openid.connect.sdk.UserInfoResponse;
import com.nimbusds.openid.connect.sdk.UserInfoSuccessResponse;
import com.nimbusds.openid.connect.sdk.claims.UserInfo;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
/**
* A HttpServer RequestHandler for handling requests to the LAS2peer Web Connector.
* Each request will be distributed to its corresponding session.
*/
public class WebConnectorRequestHandler implements HttpHandler {
private static final String AUTHENTICATION_FIELD = "Authorization";
private WebConnector connector;
private Node l2pNode;
public static final int STATUS_CONTINUE = 100; // Continue (Http/1.1)
public static final int STATUS_SWITCHING = 101; // Switching Protocols (Http/1.1)
// 2XX ? Success
public static final int STATUS_OK = 200;
public static final int STATUS_CREATED = 201; // Created
public static final int STATUS_ACCEPTED = 202; // Accepted
public static final int STATUS_NON_AUTH = 203; // Non-Authoritative Information (HTTP/1.1)
public static final int STATUS_NO_CONTENT = 204; // No Content
public static final int STATUS_RESET_CONTENT = 205; // Reset Content (HTTP/1.1)
public static final int STATUS_PARTIAL_CONTENT = 206; // Partial Content (HTTP/1.1)
// 3XX ? Redirection ? the requested document is to be found at some other location
public static final int STATUS_MULTIPLE_CHOICES = 300; // Multiple Choices (HTTP/1.1)
public static final int STATUS_MOVED_PERM = 301; // Moved Permanently
public static final int STATUS_FOUND = 302; // Found
public static final int STATUS_SEE_OTHER = 303; // See Other (HTTP/1.1)
public static final int STATUS_NOT_MODIFIED = 304; // Not Modified
public static final int STATUS_USE_PROXY = 305; // Use Proxy (HTTP/1.1)
public static final int STATUS_TEMP_REDIRECT = 307; // Temporary Redirect (HTTP/1.1)
// 4XX ? Error of the client - e.g. errornous requests
public static final int STATUS_BAD_REQUEST = 400; // Bad Request
public static final int STATUS_UNAUTHORIZED = 401; // Unauthorized
public static final int STATUS_PAYMENT_REQUIRED = 402; // Payment Required (Unused) (HTTP/1.1)
public static final int STATUS_FORBIDDEN = 403; // Forbidden
public static final int STATUS_NOT_FOUND = 404; // Not Found
public static final int STATUS_METHOD_NOT_ALLOWED = 405; // Method Not Allowed (HTTP/1.1)
public static final int STATUS_NOT_ACCEPTABLE = 406; // Not Acceptable (HTTP/1.1)
public static final int STATUS_PROXY_AUTH_REQUIRED = 407; // Proxy Authentication Required (HTTP/1.1)
public static final int STATUS_REQUEST_TIMEOUT = 408; // Request Timeout (HTTP/1.1)
public static final int STATUS_CONFLICT = 409; // Conflict (HTTP/1.1)
public static final int STATUS_GONE = 410; // Gone (HTTP/1.1)
public static final int STATUS_LENGTH_REQUIRED = 411; // Length Required (HTTP/1.1)
public static final int STATUS_PRECONDITION_FAILED = 412; // Precondition Failed (HTTP/1.1)
public static final int STATUS_REQUEST_ENTITY_TOO_LONG = 413; // Request Entity Too Long (HTTP/1.1)
public static final int STATUS_REQUEST_URI_TOO_LONG = 414; // Request-URI Too Long (HTTP/1.1)
public static final int STATUS_UNSUPPORTED_MEDIA_TYPE = 415; // Unsupported Media Type (HTTP/1.1)
public static final int STATUS_REQUEST_RANGE_NOT_SATISFIABLE = 416; // Requested Range Not Satisfiable (HTTP/1.1)
public static final int STATUS_EXPECTATION_FAILED = 417; // Expectation Failed (HTTP/1.1)
// 5XX ? Error of the server
public static final int STATUS_INTERNAL_SERVER_ERROR = 500; // Internal Server Error
public static final int STATUS_NOT_IMPLEMENTED = 501; // Not Implemented
public static final int STATUS_BAD_GATEWAY = 502; // Bad Gateway
public static final int STATUS_SERVICE_UNAVAILABLE = 503; // Service Unavailable
public static final int STATUS_GATEWAY_TIMEOUT = 504; // Gateway Timeout (HTTP/1.1)
public static final int STATUS_HTTP_VERSION_NOT_SUPPORTED = 505; // HTTP Version Not Supported (HTTP/1.1)
/** HTTP Status Messages **/
public static final String CODE_202_MESSAGE = "OK";
public static final String CODE_404_MESSAGE = "forbidden";
public static final String CODE_500_MESSAGE = "Internal Server Error";
public WebConnectorRequestHandler(WebConnector connector) {
this.connector = connector;
l2pNode = connector.getL2pNode();
}
/**
* set the connector handling this request processor
* @param connector
*/
public void setConnector(WebConnector connector) {
this.connector = connector;
l2pNode = connector.getL2pNode();
}
/**
* Logs in a las2peer user
*
* @param request
* @param response
* @return -1 if no successful login else userId
* @throws UnsupportedEncodingException
*/
private PassphraseAgent authenticate(HttpExchange exchange) throws UnsupportedEncodingException {
final int BASIC_PREFIX_LENGTH = "BASIC ".length();
String userPass = "";
String username = "";
String password = "";
// Default authentication:
// check for authentication information in header
if (exchange.getRequestHeaders().containsKey(AUTHENTICATION_FIELD)
&& (exchange.getRequestHeaders().getFirst(AUTHENTICATION_FIELD).length() > BASIC_PREFIX_LENGTH)) {
// looks like: Authentication Basic <Byte64(name:pass)>
userPass = exchange.getRequestHeaders().getFirst(AUTHENTICATION_FIELD).substring(BASIC_PREFIX_LENGTH);
userPass = new String(Base64.decode(userPass), "UTF-8");
int separatorPos = userPass.indexOf(':');
// get username and password
username = userPass.substring(0, separatorPos);
password = userPass.substring(separatorPos + 1);
return login(username, password, exchange);
}
// OpenID Connect authentication:
// check for access token in query parameter
// IMPORTANT NOTE: doing the same thing with authorization header and bearer token results in client-side
// cross-domain errors despite correct config for CORS in LAS2peer Web Connector!
else if (connector.oidcProviderInfo != null && exchange.getRequestURI().getRawQuery() != null
&& exchange.getRequestURI().getRawQuery().contains("access_token=")) {
String[] params = exchange.getRequestURI().getRawQuery().split("&");
String token = "";
for (int i = 0; i < params.length; i++) {
String[] keyval = params[i].split("=");
if (keyval[0].equals("access_token")) {
token = keyval[1];
}
}
// send request to OpenID Connect user info endpoint to retrieve complete user information
// in exchange for access token.
HTTPRequest hrq;
HTTPResponse hrs;
try {
URI userinfoEndpointUri = new URI(
(String) ((JSONObject) connector.oidcProviderInfo.get("config")).get("userinfo_endpoint"));
hrq = new HTTPRequest(Method.GET, userinfoEndpointUri.toURL());
hrq.setAuthorization("Bearer " + token);
// TODO: process all error cases that can happen (in particular invalid tokens)
hrs = hrq.send();
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
sendStringResponse(exchange, STATUS_INTERNAL_SERVER_ERROR,
"Unexpected authentication error: " + e.getMessage());
return null;
}
// process response from OpenID Connect user info endpoint
UserInfoResponse userInfoResponse;
try {
userInfoResponse = UserInfoResponse.parse(hrs);
} catch (ParseException e) {
sendStringResponse(exchange, STATUS_INTERNAL_SERVER_ERROR,
"Couldn't parse UserInfo response: " + e.getMessage());
return null;
}
// failed request for OpenID Connect user info will result in no agent being returned.
if (userInfoResponse instanceof UserInfoErrorResponse) {
UserInfoErrorResponse uier = (UserInfoErrorResponse) userInfoResponse;
sendStringResponse(exchange, STATUS_UNAUTHORIZED, "Open ID Connect UserInfo request failed! Cause: "
+ uier.getErrorObject().getDescription());
return null;
}
// In case of successful request, map OpenID Connect user info to intern
UserInfo userInfo = ((UserInfoSuccessResponse) userInfoResponse).getUserInfo();
try {
JSONObject ujson = userInfo.toJSONObject();
// response.println("User Info: " + userInfo.toJSONObject());
String sub = (String) ujson.get("sub");
long oidcAgentId = hash(sub);
username = oidcAgentId + "";
password = sub;
PassphraseAgent pa;
try {
pa = (PassphraseAgent) l2pNode.getAgent(oidcAgentId);
pa.unlockPrivateKey(password);
if (pa instanceof UserAgent) {
UserAgent ua = (UserAgent) pa;
ua.setUserData(ujson.toJSONString());
return ua;
}
return pa;
} catch (AgentNotKnownException e) {
UserAgent oidcAgent;
try {
// here, we choose the OpenID Connect
// TODO: choose other scheme for generating agent password.
oidcAgent = UserAgent.createUserAgent(oidcAgentId, sub);
oidcAgent.unlockPrivateKey(ujson.get("sub").toString());
oidcAgent.setEmail((String) ujson.get("email"));
oidcAgent.setLoginName((String) ujson.get("preferred_username"));
oidcAgent.setUserData(ujson.toJSONString());
l2pNode.storeAgent(oidcAgent);
oidcAgent.unlockPrivateKey(password);
return oidcAgent;
} catch (Exception e1) {
return null;
}
}
} catch (L2pSecurityException e) {
e.printStackTrace();
sendStringResponse(exchange, STATUS_UNAUTHORIZED, e.getMessage());
}
}
// no information? check if there is a default account for login
else if (connector.defaultLoginUser.length() > 0) {
return login(connector.defaultLoginUser, connector.defaultLoginPassword, exchange);
} else {
sendUnauthorizedResponse(exchange, null, exchange.getRemoteAddress() + ": No Authentication provided!");
}
return null;
}
private PassphraseAgent login(String username, String password, HttpExchange exchange) {
try {
long userId;
PassphraseAgent userAgent;
if (username.matches("-?[0-9].*")) {// username is id?
try {
userId = Long.valueOf(username);
} catch (NumberFormatException e) {
throw new L2pSecurityException("The given user does not contain a valid agent id!");
}
} else {// username is string
userId = l2pNode.getAgentIdForLogin(username);
}
// keep track of active requests
synchronized (this.connector) {
if (this.connector.getOpenUserRequests().containsKey(userId)) {
Integer numReq = this.connector.getOpenUserRequests().get(userId);
this.connector.getOpenUserRequests().put(userId, numReq + 1);
// System.out.println("### numreq " +numReq);
} else {
this.connector.getOpenUserRequests().put(userId, 1);
// System.out.println("### numreq 0" );
}
}
userAgent = (PassphraseAgent) l2pNode.getAgent(userId);
/* if ( ! (userAgent instanceof PassphraseAgent ))
throw new L2pSecurityException ("Agent is not passphrase protected!");*/
userAgent.unlockPrivateKey(password);
return userAgent;
} catch (AgentNotKnownException e) {
sendUnauthorizedResponse(exchange, null, exchange.getRemoteAddress() + ": login denied for user "
+ username);
} catch (L2pSecurityException e) {
sendUnauthorizedResponse(exchange, null, exchange.getRemoteAddress()
+ ": unauth access - prob. login problems");
} catch (Exception e) {
sendUnauthorizedResponse(exchange, null, exchange.getRemoteAddress()
+ ": something went horribly wrong. Check your request for correctness.");
}
return null;
}
/**
* Delegates the request data to a service method, which then decides what to do with it (maps it internally)
*
* @param request
* @param response
* @return
*/
private boolean invoke(PassphraseAgent userAgent, HttpExchange exchange) {
// internal server error unless otherwise specified (errors might occur)
// int responseCode = STATUS_INTERNAL_SERVER_ERROR;
String[] requestSplit = exchange.getRequestURI().getPath().split("/", 2);
// first: empty (string starts with '/')
// second: URI
String uri = "";
try {
if (requestSplit.length >= 2) {
int varsstart = requestSplit[1].indexOf('?');
if (varsstart > 0) {
uri = requestSplit[1].substring(0, varsstart);
} else {
uri = requestSplit[1];
}
}
// http body
InputStream is = exchange.getRequestBody();
java.util.Scanner s = new Scanner(is);
s.useDelimiter("\\A");
String content = s.hasNext() ? s.next() : "";
s.close();
// http method
String httpMethod = exchange.getRequestMethod();
// extract all get variables from the query
ArrayList<Pair<String>> variablesList = new ArrayList<Pair<String>>();
String query = exchange.getRequestURI().getQuery();
if (query != null) {
for (String param : query.split("&")) {
String pair[] = param.split("=");
if (pair.length > 1) {
variablesList.add(new Pair<String>(pair[0], pair[1]));
} else {
variablesList.add(new Pair<String>(pair[0], ""));
}
}
}
@SuppressWarnings("unchecked")
Pair<String>[] variables = variablesList.toArray(new Pair[variablesList.size()]);
// extract all header fields from the query
ArrayList<Pair<String>> headersList = new ArrayList<Pair<String>>();
// default values
String acceptHeader = "*/*";
String contentTypeHeader = "text/plain";
Set<Entry<String, List<String>>> entries = exchange.getRequestHeaders().entrySet();
for (Entry<String, List<String>> entry : entries) {
String key = entry.getKey();
// TODO this only returns the first header value for this key
String value = entry.getValue().get(0).trim();
headersList.add(new Pair<String>(key, value));
// fetch MIME types
if (key.toLowerCase().equals("accept") && !value.isEmpty()) {
acceptHeader = value;
} else if (key.toLowerCase().equals("content-type") && !value.isEmpty()) {
contentTypeHeader = value;
}
}
@SuppressWarnings("unchecked")
Pair<String>[] headers = headersList.toArray(new Pair[headersList.size()]);
Serializable result = "";
Mediator mediator = l2pNode.getOrRegisterLocalMediator(userAgent);
boolean gotResult = false;
String returnMIMEType = "text/plain";
StringBuilder warnings = new StringBuilder();
InvocationData[] invocation = RESTMapper.parse(this.connector.getMappingTree(), httpMethod, uri, variables,
content, contentTypeHeader, acceptHeader, headers, warnings);
if (invocation.length == 0) {
if (warnings.length() > 0) {
sendStringResponse(exchange, STATUS_NOT_FOUND, warnings.toString().replaceAll("\n", " "));
} else {
sendResponse(exchange, STATUS_NOT_FOUND, 0);
// otherwise the client waits till the timeout for an answer
exchange.getResponseBody().close();
}
return false;
}
for (int i = 0; i < invocation.length; i++) {
try {
result = mediator.invoke(invocation[i].getServiceName(), invocation[i].getMethodName(),
invocation[i].getParameters(), connector.preferLocalServices());// invoke service method
gotResult = true;
returnMIMEType = invocation[i].getMIME();
break;
} catch (NoSuchServiceException | TimeoutException e) {
sendNoSuchService(exchange, invocation[i].getServiceName());
} catch (NoSuchServiceMethodException e) {
sendNoSuchMethod(exchange);
} catch (L2pSecurityException e) {
sendSecurityProblems(exchange, e);
} catch (ServiceInvocationException e) {
if (e.getCause() == null) {
sendResultInterpretationProblems(exchange);
} else {
sendInvocationException(exchange, e);
}
} catch (InterruptedException e) {
sendInvocationInterrupted(exchange);
}
}
if (gotResult) {
sendInvocationSuccess(result, returnMIMEType, exchange);
}
return true;
} catch (NoMethodFoundException | NotSupportedUriPathException e) {
sendNoSuchMethod(exchange);
} catch (Exception e) {
connector.logError("Error occured:" + exchange.getRequestURI().getPath() + " " + e.getMessage());
}
return false;
}
/**
* Logs the user out
*
* @param userAgent
*/
private void logout(PassphraseAgent userAgent) {
long userId = userAgent.getId();
// synchronize across multiple threads
synchronized (this.connector) {
if (this.connector.getOpenUserRequests().containsKey(userId)) {
Integer numReq = this.connector.getOpenUserRequests().get(userId);
if (numReq <= 1) {
this.connector.getOpenUserRequests().remove(userId);
try {
l2pNode.unregisterAgent(userAgent);
userAgent.lockPrivateKey();
// System.out.println("+++ logout");
} catch (Exception e) {
e.printStackTrace();
}
} else {
this.connector.getOpenUserRequests().put(userId, numReq - 1);
}
} else {
try {
l2pNode.unregisterAgent(userAgent);
userAgent.lockPrivateKey();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* Handles a request (login, invoke)
*/
@Override
public void handle(HttpExchange exchange) throws IOException {
exchange.getResponseHeaders().set("Server-Name", "LAS2peer WebConnector");
// check for an OPTIONS request and auto answer it
// XXX this should become a default reply for OPTIONS-requests,
// but should be also be available to service developers
if (exchange.getRequestMethod().toLowerCase().equals("options")) {
// TODO set allow header
sendResponse(exchange, STATUS_OK, 0);
// otherwise the client waits till the timeout for an answer
exchange.getResponseBody().close();
} else {
PassphraseAgent userAgent;
if ((userAgent = authenticate(exchange)) != null) {
invoke(userAgent, exchange);
logout(userAgent);
}
// otherwise the client waits till the timeout for an answer, if an error occurred
exchange.getResponseBody().close();
}
}
// helper function to create long hash from string
public static long hash(String string) {
long h = 1125899906842597L; // prime
int len = string.length();
for (int i = 0; i < len; i++) {
h = 31 * h + string.charAt(i);
}
return h;
}
/**
* send a notification, that the requested service does not exists
* @param request
* @param response
* @param service
*/
private void sendNoSuchService(HttpExchange exchange, String service) {
connector.logError("Service not found: " + service);
sendStringResponse(exchange, STATUS_SERVICE_UNAVAILABLE,
"The service you requested is not known to this server!");
}
/**
* send a notification, that the requested method does not exists at the requested service
* @param request
* @param response
*/
private void sendNoSuchMethod(HttpExchange exchange) {
connector.logError("Invocation request " + exchange.getRequestURI().getPath() + " for unknown service method");
sendStringResponse(exchange, STATUS_NOT_FOUND, "The method you requested is not known to this service!");
}
/**
* send a notification, that security problems occurred during the requested service method
* @param request
* @param response
* @param e
*/
private void sendSecurityProblems(HttpExchange exchange, L2pSecurityException e) {
connector.logError("Security exception in invocation request " + exchange.getRequestURI().getPath());
sendStringResponse(exchange, STATUS_FORBIDDEN, "You don't have access to the method you requested");
if (System.getProperty("http-connector.printSecException") != null
&& System.getProperty("http-connector.printSecException").equals("true")) {
e.printStackTrace();
}
}
/**
* send a notification, that the result of the service invocation is
* not transportable
*
* @param request
* @param response
*/
private void sendResultInterpretationProblems(HttpExchange exchange) {
connector.logError("Exception while processing RMI: " + exchange.getRequestURI().getPath());
// result interpretation problems
sendStringResponse(exchange, STATUS_INTERNAL_SERVER_ERROR, "The result of the method call is not transferable!");
}
/**
* send a notification about an exception which occurred inside the requested service method
*
* @param request
* @param response
* @param e
*/
private void sendInvocationException(HttpExchange exchange, ServiceInvocationException e) {
connector.logError("Exception while processing RMI: " + exchange.getRequestURI().getPath());
// internal exception in service method
Object[] ret = new Object[4];
ret[0] = "Exception during RMI invocation!";
ret[1] = e.getCause().getCause().getClass().getCanonicalName();
ret[2] = e.getCause().getCause().getMessage();
ret[3] = e.getCause().getCause();
String code = ret[0] + "\n" + ret[1] + "\n" + ret[2] + "\n" + ret[3];
sendStringResponse(exchange, STATUS_INTERNAL_SERVER_ERROR, code);
}
/**
* send a notification, that the processing of the invocation has been interrupted
*
* @param request
* @param response
*/
private void sendInvocationInterrupted(HttpExchange exchange) {
connector.logError("Invocation has been interrupted!");
sendStringResponse(exchange, STATUS_INTERNAL_SERVER_ERROR, "The invoction has been interrupted!");
}
/**
*
* @param result
* @param contentType
* @param response
*/
private void sendInvocationSuccess(Serializable result, String contentType, HttpExchange exchange) {
try {
if (result != null) {
String msg = null;
int statusCode = STATUS_OK;
exchange.getResponseHeaders().set("content-type", contentType);
if (result instanceof i5.las2peer.restMapper.HttpResponse) {
i5.las2peer.restMapper.HttpResponse res = (i5.las2peer.restMapper.HttpResponse) result;
Pair<String>[] headers = res.listHeaders();
for (Pair<String> header : headers) {
exchange.getResponseHeaders().set(header.getOne(), header.getTwo());
}
statusCode = res.getStatus();
msg = res.getResult();
} else {
msg = RESTMapper.castToString(result);
}
if (msg != null) {
byte[] content = msg.getBytes();
sendResponse(exchange, statusCode, content.length);
OutputStream os = exchange.getResponseBody();
os.write(content);
os.close();
} else {
sendResponse(exchange, STATUS_NO_CONTENT, 0);
}
} else {
sendResponse(exchange, STATUS_NO_CONTENT, 0);
}
} catch (IOException e) {
connector.logMessage(e.getMessage());
}
}
/**
* send a message about an unauthorized request
* @param response
* @param logMessage
*/
private void sendUnauthorizedResponse(HttpExchange exchange, String answerMessage, String logMessage) {
connector.logMessage(logMessage);
exchange.getResponseHeaders().set("WWW-Authenticate", "Basic realm=\"LAS2peer WebConnector\"");
if (answerMessage != null) {
sendStringResponse(exchange, STATUS_UNAUTHORIZED, answerMessage);
} else {
try {
sendResponse(exchange, STATUS_UNAUTHORIZED, 0);
// otherwise the client waits till the timeout for an answer
exchange.getResponseBody().close();
} catch (IOException e) {
connector.logMessage(e.getMessage());
}
}
}
/**
* send a response that an internal error occurred
*
* @param response
* @param answerMessage
* @param logMessage
*/
private void sendInternalErrorResponse(HttpExchange exchange, String answerMessage, String logMessage) {
connector.logMessage(logMessage);
sendStringResponse(exchange, STATUS_INTERNAL_SERVER_ERROR, answerMessage);
}
private void sendStringResponse(HttpExchange exchange, int responseCode, String response) {
byte[] content = response.getBytes();
exchange.getResponseHeaders().set("content-type", "text/plain");
try {
sendResponse(exchange, responseCode, content.length);
OutputStream os = exchange.getResponseBody();
os.write(content);
os.close();
} catch (IOException e) {
connector.logMessage(e.getMessage());
}
}
private void sendResponse(HttpExchange exchange, int responseCode, long contentLength) throws IOException {
// add configured headers
if (connector.enableCrossOriginResourceSharing) {
exchange.getResponseHeaders().add("Access-Control-Allow-Origin", connector.crossOriginResourceDomain);
exchange.getResponseHeaders().add("Access-Control-Max-Age",
String.valueOf(connector.crossOriginResourceMaxAge));
}
exchange.sendResponseHeaders(responseCode, contentLength);
}
}
|
package io.github.flibio.utils.commands;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.block.tileentity.CommandBlock;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.source.CommandBlockSource;
import org.spongepowered.api.command.source.ConsoleSource;
import org.spongepowered.api.command.source.ProxySource;
import org.spongepowered.api.command.source.RconSource;
import org.spongepowered.api.command.source.RemoteSource;
import org.spongepowered.api.command.source.SignSource;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.command.spec.CommandSpec.Builder;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.vehicle.minecart.CommandBlockMinecart;
import org.spongepowered.api.text.serializer.TextSerializers;
public abstract class BaseCommandExecutor<T extends CommandSource> implements CommandExecutor {
public boolean async = false;
private Class<T> type;
public Object plugin;
public String invalidSource;
@SuppressWarnings("unchecked")
public BaseCommandExecutor() {
Class<?> rClass = GenericHelper.findSubClassParameterType(this, BaseCommandExecutor.class, 0);
this.type = (Class<T>) rClass;
}
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
if (!compareType(src)) {
return CommandResult.empty();
} else {
@SuppressWarnings("unchecked")
T tSrc = (T) src;
if (async) {
Sponge.getScheduler().createTaskBuilder().execute(r -> {
run(tSrc, args);
}).async().submit(plugin);
} else {
run(tSrc, args);
}
return CommandResult.success();
}
}
/**
* Gets the CommandSpec builder. All changes to the CommandSpec should be
* made before returning the builder.
*
* @return The CommandSpec builder, with user changes already made.
*/
public abstract Builder getCommandSpecBuilder();
/**
* Runs the command for the given source.
*
* @param src The CommandSource.
* @param args The command arguments.
*/
public abstract void run(T src, CommandContext args);
/**
* Gets the built CommandSpec.
*
* @return The built CommandSpec.
*/
public CommandSpec getCommandSpec() {
return this.getCommandSpecBuilder().build();
}
private boolean compareType(CommandSource src) {
if (type.equals(CommandBlock.class) && !(src instanceof CommandBlock)) {
src.sendMessage(TextSerializers.FORMATTING_CODE.deserialize(invalidSource.replaceAll("\\{sourcetype\\}", "command block")));
return false;
} else if (type.equals(CommandBlockMinecart.class) && !(src instanceof CommandBlockMinecart)) {
src.sendMessage(TextSerializers.FORMATTING_CODE.deserialize(invalidSource.replaceAll("\\{sourcetype\\}", "command block minecart")));
return false;
} else if (type.equals(CommandBlockSource.class) && !(src instanceof CommandBlockSource)) {
src.sendMessage(TextSerializers.FORMATTING_CODE.deserialize(invalidSource.replaceAll("\\{sourcetype\\}", "solid command block")));
return false;
} else if (type.equals(ConsoleSource.class) && !(src instanceof ConsoleSource)) {
src.sendMessage(TextSerializers.FORMATTING_CODE.deserialize(invalidSource.replaceAll("\\{sourcetype\\}", "console")));
return false;
} else if (type.equals(Player.class) && !(src instanceof Player)) {
src.sendMessage(TextSerializers.FORMATTING_CODE.deserialize(invalidSource.replaceAll("\\{sourcetype\\}", "player")));
return false;
} else if (type.equals(ProxySource.class) && !(src instanceof ProxySource)) {
src.sendMessage(TextSerializers.FORMATTING_CODE.deserialize(invalidSource.replaceAll("\\{sourcetype\\}", "proxy source")));
return false;
} else if (type.equals(RconSource.class) && !(src instanceof RconSource)) {
src.sendMessage(TextSerializers.FORMATTING_CODE.deserialize(invalidSource.replaceAll("\\{sourcetype\\}", "rcon client")));
return false;
} else if (type.equals(RemoteSource.class) && !(src instanceof RemoteSource)) {
src.sendMessage(TextSerializers.FORMATTING_CODE.deserialize(invalidSource.replaceAll("\\{sourcetype\\}", "remote source")));
return false;
} else if (type.equals(SignSource.class) && !(src instanceof SignSource)) {
src.sendMessage(TextSerializers.FORMATTING_CODE.deserialize(invalidSource.replaceAll("\\{sourcetype\\}", "sign source")));
return false;
} else {
return true;
}
}
}
|
package io.github.lukehutch.fastclasspathscanner;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.github.lukehutch.fastclasspathscanner.json.JSONDeserializer;
import io.github.lukehutch.fastclasspathscanner.json.JSONSerializer;
import io.github.lukehutch.fastclasspathscanner.utils.ClassLoaderAndModuleFinder;
import io.github.lukehutch.fastclasspathscanner.utils.JarUtils;
import io.github.lukehutch.fastclasspathscanner.utils.JarfileMetadataReader;
import io.github.lukehutch.fastclasspathscanner.utils.LogNode;
import io.github.lukehutch.fastclasspathscanner.utils.NestedJarHandler;
/** The result of a scan. */
public class ScanResult {
/** The scan spec. */
final ScanSpec scanSpec;
/** The order of raw classpath elements. */
private final List<String> rawClasspathEltOrderStrs;
/** The order of classpath elements, after inner jars have been extracted to temporary files, etc. */
private final List<ClasspathElement> classpathOrder;
/** A list of all files that were found in whitelisted packages. */
private ResourceList allResources;
/**
* The default order in which ClassLoaders are called to load classes. Used when a specific class does not have
* a record of which ClassLoader provided the URL used to locate the class (e.g. if the class is found using
* java.class.path).
*/
private final ClassLoader[] envClassLoaderOrder;
/** The nested jar handler instance. */
private final NestedJarHandler nestedJarHandler;
/**
* The file, directory and jarfile resources timestamped during a scan, along with their timestamp at the time
* of the scan. For jarfiles, the timestamp represents the timestamp of all files within the jar. May be null,
* if this ScanResult object is the result of a call to FastClasspathScanner#getUniqueClasspathElementsAsync().
*/
private final Map<File, Long> fileToLastModified;
/**
* The class graph builder. May be null, if this ScanResult object is the result of a call to
* FastClasspathScanner#getUniqueClasspathElementsAsync().
*/
private final Map<String, ClassInfo> classNameToClassInfo;
/** The log. */
private final LogNode log;
/** The result of a scan. Make sure you call complete() after calling the constructor. */
ScanResult(final ScanSpec scanSpec, final List<ClasspathElement> classpathOrder,
final List<String> rawClasspathEltOrderStrs, final ClassLoader[] envClassLoaderOrder,
final Map<String, ClassInfo> classNameToClassInfo, final Map<File, Long> fileToLastModified,
final NestedJarHandler nestedJarHandler, final LogNode log) {
this.scanSpec = scanSpec;
this.rawClasspathEltOrderStrs = rawClasspathEltOrderStrs;
this.classpathOrder = classpathOrder;
for (final ClasspathElement classpathElt : classpathOrder) {
if (classpathElt.fileMatches != null) {
if (allResources == null) {
allResources = new ResourceList();
}
allResources.addAll(classpathElt.fileMatches);
}
}
this.envClassLoaderOrder = envClassLoaderOrder;
this.fileToLastModified = fileToLastModified;
this.classNameToClassInfo = classNameToClassInfo;
this.nestedJarHandler = nestedJarHandler;
this.log = log;
// Add backrefs from info objects back to this ScanResult
if (classNameToClassInfo != null) {
for (final ClassInfo classInfo : classNameToClassInfo.values()) {
classInfo.setScanResult(this);
}
}
}
/**
* Returns the list of File objects for unique classpath elements (directories or jarfiles), in classloader
* resolution order.
*
* @return The unique classpath elements.
*/
public List<File> getClasspathFiles() {
final List<File> classpathElementOrderFiles = new ArrayList<>();
for (final ClasspathElement classpathElement : classpathOrder) {
final ModuleRef modRef = classpathElement.getClasspathElementModuleRef();
if (modRef != null) {
if (!modRef.isSystemModule()) {
// Add module files when they don't have a "jrt:/" scheme
final File moduleLocationFile = modRef.getLocationFile();
if (moduleLocationFile != null) {
classpathElementOrderFiles.add(moduleLocationFile);
}
}
} else {
classpathElementOrderFiles.add(classpathElement.getClasspathElementFile(log));
}
}
return classpathElementOrderFiles;
}
/**
* Returns all unique directories or zip/jarfiles on the classpath, in classloader resolution order, as a
* classpath string, delineated with the standard path separator character.
*
* @return a the unique directories and jarfiles on the classpath, in classpath resolution order, as a path
* string.
*/
public String getClasspath() {
return JarUtils.pathElementsToPathStr(getClasspathFiles());
}
/**
* Returns the list of unique classpath element paths as URLs, in classloader resolution order.
*
* @return The unique classpath element URLs.
*/
public List<URL> getClasspathURLs() {
final List<URL> classpathElementOrderURLs = new ArrayList<>();
for (final ClasspathElement classpathElement : classpathOrder) {
final ModuleRef modRef = classpathElement.getClasspathElementModuleRef();
if (modRef != null) {
// Add module URLs whether or not they have a "jrt:/" scheme
try {
classpathElementOrderURLs.add(modRef.getLocation().toURL());
} catch (final MalformedURLException e) {
// Skip malformed URLs (shouldn't happen)
}
} else {
try {
classpathElementOrderURLs.add(classpathElement.getClasspathElementFile(log).toURI().toURL());
} catch (final MalformedURLException e) {
// Shouldn't happen
}
}
}
return classpathElementOrderURLs;
}
/** Returns {@ModuleRef} references for all the visible modules. */
public List<ModuleRef> getModules() {
final List<ModuleRef> moduleRefs = new ArrayList<>();
for (final ClasspathElement classpathElement : classpathOrder) {
final ModuleRef moduleRef = classpathElement.getClasspathElementModuleRef();
if (moduleRef != null) {
moduleRefs.add(moduleRef);
}
}
return moduleRefs;
}
/** Get a list of all resources (including classfiles and non-classfiles) found in whitelisted packages. */
public ResourceList getAllResources() {
if (allResources == null || allResources.isEmpty()) {
return new ResourceList(1);
} else {
return allResources;
}
}
/**
* Get a list of all resources found in whitelisted packages that have the given path, relative to the package
* root of the classpath element. May match several resources, up to one per classpath element.
*/
public ResourceList getResourcesWithPath(final String resourcePath) {
if (allResources == null || allResources.isEmpty()) {
return new ResourceList(1);
} else {
String path = resourcePath;
while (path.startsWith("/")) {
path = path.substring(1);
}
final ResourceList filteredResources = new ResourceList();
for (final Resource classpathResource : allResources) {
if (classpathResource.getPath().equals(path)) {
filteredResources.add(classpathResource);
}
}
return filteredResources;
}
}
/** Get a list of all resources found in whitelisted packages that have the requested leafname. */
public ResourceList getResourcesWithLeafName(final String leafName) {
if (allResources == null || allResources.isEmpty()) {
return new ResourceList(1);
} else {
final ResourceList filteredResources = new ResourceList();
for (final Resource classpathResource : allResources) {
final String relativePath = classpathResource.getPath();
final int lastSlashIdx = relativePath.lastIndexOf('/');
if (relativePath.substring(lastSlashIdx + 1).equals(leafName)) {
filteredResources.add(classpathResource);
}
}
return filteredResources;
}
}
/**
* Get a list of all resources found in whitelisted packages that have the requested extension (e.g. "xml" to
* match all resources ending in ".xml").
*/
public ResourceList getResourcesWithExtension(final String extension) {
if (allResources == null || allResources.isEmpty()) {
return new ResourceList(1);
} else {
String bareExtension = extension;
while (bareExtension.startsWith(".")) {
bareExtension = bareExtension.substring(1);
}
final ResourceList filteredResources = new ResourceList();
for (final Resource classpathResource : allResources) {
final String relativePath = classpathResource.getPath();
final int lastSlashIdx = relativePath.lastIndexOf('/');
final int lastDotIdx = relativePath.lastIndexOf('.');
if (lastDotIdx > lastSlashIdx) {
if (relativePath.substring(lastDotIdx + 1).equalsIgnoreCase(bareExtension)) {
filteredResources.add(classpathResource);
}
}
}
return filteredResources;
}
}
/**
* Get a list of all resources found in whitelisted packages that have a path, relative to the classpath package
* root, matching the requested pattern.
*/
public ResourceList getResourcesMatchingPattern(final Pattern pattern) {
if (allResources == null || allResources.isEmpty()) {
return new ResourceList(1);
} else {
final ResourceList filteredResources = new ResourceList();
for (final Resource classpathResource : allResources) {
final String relativePath = classpathResource.getPath();
if (pattern.matcher(relativePath).matches()) {
filteredResources.add(classpathResource);
}
}
return filteredResources;
}
}
/**
* Determine whether the classpath contents have been modified since the last scan. Checks the timestamps of
* files and jarfiles encountered during the previous scan to see if they have changed. Does not perform a full
* scan, so cannot detect the addition of directories that newly match whitelist criteria -- you need to perform
* a full scan to detect those changes.
*
* @return true if the classpath contents have been modified since the last scan.
*/
public boolean classpathContentsModifiedSinceScan() {
if (fileToLastModified == null) {
return true;
} else {
for (final Entry<File, Long> ent : fileToLastModified.entrySet()) {
if (ent.getKey().lastModified() != ent.getValue()) {
return true;
}
}
return false;
}
}
/**
* Find the maximum last-modified timestamp of any whitelisted file/directory/jarfile encountered during the
* scan. Checks the current timestamps, so this should increase between calls if something changes in
* whitelisted paths. Assumes both file and system timestamps were generated from clocks whose time was
* accurate. Ignores timestamps greater than the system time.
*
* <p>
* This method cannot in general tell if classpath has changed (or modules have been added or removed) if it is
* run twice during the same runtime session.
*
* @return the maximum last-modified time for whitelisted files/directories/jars encountered during the scan.
*/
public long classpathContentsLastModifiedTime() {
long maxLastModifiedTime = 0L;
if (fileToLastModified != null) {
final long currTime = System.currentTimeMillis();
for (final long timestamp : fileToLastModified.values()) {
if (timestamp > maxLastModifiedTime && timestamp < currTime) {
maxLastModifiedTime = timestamp;
}
}
}
return maxLastModifiedTime;
}
// Classes
/**
* Get the ClassInfo object for the named class, or null if no class of the requested name was found in a
* whitelisted/non-blacklisted package during scanning.
*
* @return The ClassInfo object for the named class, or null if the class was not found.
*/
public ClassInfo getClassInfo(final String className) {
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call FastClasspathScanner#enableClassInfo() before #scan()");
}
return classNameToClassInfo.get(className);
}
/**
* Get all classes, interfaces and annotations found during the scan.
*
* @return A list of all whitelisted classes found during the scan, or the empty list if none.
*/
public ClassInfoList getAllClasses() {
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call FastClasspathScanner#enableClassInfo() before #scan()");
}
return ClassInfo.getAllClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get all standard (non-interface/non-annotation) classes found during the scan.
*
* @return A list of all whitelisted standard classes found during the scan, or the empty list if none.
*/
public ClassInfoList getAllStandardClasses() {
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call FastClasspathScanner#enableClassInfo() before #scan()");
}
return ClassInfo.getAllStandardClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get all subclasses of the named superclass.
*
* @param superclassName
* The name of the superclass.
* @return A list of subclasses of the named superclass, or the empty list if none.
*/
public ClassInfoList getSubclasses(final String superclassName) {
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call FastClasspathScanner#enableClassInfo() before #scan()");
}
final ClassInfo superclass = classNameToClassInfo.get(superclassName);
return superclass == null ? ClassInfoList.EMPTY_LIST : superclass.getSubclasses();
}
/**
* Get superclasses of the named subclass.
*
* @param subclassName
* The name of the subclass.
* @return A list of superclasses of the named subclass, or the empty list if none.
*/
public ClassInfoList getSuperclasses(final String subclassName) {
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call FastClasspathScanner#enableClassInfo() before #scan()");
}
final ClassInfo subclass = classNameToClassInfo.get(subclassName);
return subclass == null ? ClassInfoList.EMPTY_LIST : subclass.getSuperclasses();
}
/**
* Get classes that have a method with an annotation of the named type.
*
* @param methodAnnotationName
* the name of the method annotation.
* @return A list of classes with a method that has an annotation of the named type, or the empty list if none.
*/
public ClassInfoList getClassesWithMethodAnnotation(final String methodAnnotationName) {
if (!scanSpec.enableClassInfo || !scanSpec.enableMethodInfo || !scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException(
"Please call FastClasspathScanner#enableClassInfo(), #enableMethodInfo(), "
+ "and #enableAnnotationInfo() before #scan()");
}
final ClassInfo classInfo = classNameToClassInfo.get(methodAnnotationName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithMethodAnnotation();
}
/**
* Get classes that have a field with an annotation of the named type.
*
* @param fieldAnnotationName
* the name of the field annotation.
* @return A list of classes that have a field with an annotation of the named type, or the empty list if none.
*/
public ClassInfoList getClassesWithFieldAnnotation(final String fieldAnnotationName) {
if (!scanSpec.enableClassInfo || !scanSpec.enableFieldInfo || !scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException(
"Please call FastClasspathScanner#enableClassInfo(), #enableFieldInfo(), "
+ "and #enableAnnotationInfo() before #scan()");
}
final ClassInfo classInfo = classNameToClassInfo.get(fieldAnnotationName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithFieldAnnotation();
}
// Interfaces
/**
* Get all interface classes found during the scan (not including annotations, which are also technically
* interfaces). See also {@link #getAllInterfacesAndAnnotations()}.
*
* @return A list of all whitelisted interfaces found during the scan, or the empty list if none.
*/
public ClassInfoList getAllInterfaces() {
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call FastClasspathScanner#enableClassInfo() before #scan()");
}
return ClassInfo.getAllImplementedInterfaceClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get all interfaces implemented by the named class or by one of its superclasses, if this is a standard class,
* or the superinterfaces extended by this interface, if this is an interface.
*
* @param className
* The class name.
* @return A list of interfaces implemented by the named class (or superinterfaces extended by the named
* interface), or the empty list if none.
*/
public ClassInfoList getInterfaces(final String className) {
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call FastClasspathScanner#enableClassInfo() before #scan()");
}
final ClassInfo classInfo = classNameToClassInfo.get(className);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getInterfaces();
}
/**
* Get all classes that implement (or have superclasses that implement) the named interface (or one of its
* subinterfaces).
*
* @param interfaceName
* The interface name.
* @return A list of all classes that implement the named interface, or the empty list if none.
*/
public ClassInfoList getClassesImplementing(final String interfaceName) {
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call FastClasspathScanner#enableClassInfo() before #scan()");
}
final ClassInfo classInfo = classNameToClassInfo.get(interfaceName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesImplementing();
}
// Annotations
/**
* Get all annotation classes found during the scan. See also {@link #getAllInterfacesAndAnnotations()}.
*
* @return A list of all annotation classes found during the scan, or the empty list if none.
*/
public ClassInfoList getAllAnnotations() {
if (!scanSpec.enableClassInfo || !scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException(
"Please call FastClasspathScanner#enableClassInfo() and #enableAnnotationInfo() "
+ "before #scan()");
}
return ClassInfo.getAllAnnotationClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get all interface or annotation classes found during the scan. (Annotations are technically interfaces, and
* they can be implemented.)
*
* @return A list of all whitelisted interfaces found during the scan, or the empty list if none.
*/
public ClassInfoList getAllInterfacesAndAnnotations() {
if (!scanSpec.enableClassInfo || !scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException(
"Please call FastClasspathScanner#enableClassInfo() and #enableAnnotationInfo() "
+ "before #scan()");
}
return ClassInfo.getAllInterfacesOrAnnotationClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get classes with the named class annotation or meta-annotation.
*
* @param annotationName
* The name of the class annotation or meta-annotation.
* @return A list of all non-annotation classes that were found with the named class annotation during the scan,
* or the empty list if none.
*/
public ClassInfoList getClassesWithAnnotation(final String annotationName) {
if (!scanSpec.enableClassInfo || !scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException(
"Please call FastClasspathScanner#enableClassInfo() and #enableAnnotationInfo() "
+ "before #scan()");
}
final ClassInfo classInfo = classNameToClassInfo.get(annotationName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithAnnotation();
}
/**
* Get annotations on the named class. This only returns the annotating classes; to read annotation parameters,
* call {@link #getClassInfo(String)} to get the {@link ClassInfo} object for the named class, then if the
* {@link ClassInfo} object is non-null, call {@link ClassInfo#getAnnotationInfo()} to get detailed annotation
* info.
*
* @param className
* The name of the class.
* @return A list of all annotation classes that were found with the named class annotation during the scan, or
* the empty list if none.
*/
public ClassInfoList getAnnotationsOnClass(final String className) {
if (!scanSpec.enableClassInfo || !scanSpec.enableAnnotationInfo) {
throw new IllegalArgumentException(
"Please call FastClasspathScanner#enableClassInfo() and #enableAnnotationInfo() "
+ "before #scan()");
}
final ClassInfo classInfo = classNameToClassInfo.get(className);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getAnnotations();
}
private Class<?> loadClass(final String className, final ClassLoader classLoader, final LogNode log)
throws IllegalArgumentException {
try {
return Class.forName(className, scanSpec.initializeLoadedClasses, classLoader);
} catch (final ClassNotFoundException e) {
return null;
} catch (final Throwable e) {
throw new IllegalArgumentException("Exception while loading class " + className, e);
}
}
Class<?> loadClass(final String className, final boolean returnNullIfClassNotFound, final LogNode log)
throws IllegalArgumentException {
if (className == null || className.isEmpty()) {
throw new IllegalArgumentException("Cannot load class -- class names cannot be null or empty");
}
// Try loading class via each classloader in turn
final ClassInfo classInfo = classNameToClassInfo.get(className);
final ClassLoader[] classLoadersForClass = classInfo != null ? classInfo.classLoaders : envClassLoaderOrder;
if (classLoadersForClass != null) {
for (final ClassLoader classLoader : classLoadersForClass) {
final Class<?> classRef = loadClass(className, classLoader, log);
if (classRef != null) {
return classRef;
}
}
}
// Try with null (bootstrap) ClassLoader
final Class<?> classRef = loadClass(className, /* classLoader = */ null, log);
if (classRef != null) {
return classRef;
}
// If this class came from a jarfile with a package root (e.g. a Spring-Boot jar, with packages rooted
// at BOOT-INF/classes), then the problem is probably that the jarfile was on the classpath, but the
// scanner is not running inside the jar itself, so the necessary ClassLoader for the jar is not
// available. Unzip the jar starting from the package root, and create a URLClassLoader to load classes
// from the unzipped jar. (This is only done once per jar and package root, using the singleton pattern.)
if (classInfo != null && nestedJarHandler != null) {
try {
ClassLoader customClassLoader = null;
if (classInfo.classpathElementFile.isDirectory()) {
// Should not happen, but we should handle this anyway -- create a URLClassLoader for the dir
customClassLoader = new URLClassLoader(
new URL[] { classInfo.classpathElementFile.toURI().toURL() });
} else {
// Get the outermost jar containing this jarfile, so that if a lib jar was extracted during
// scanning, we obtain the classloader from the outer jar. This is needed so that package roots
// and lib jars are loaded from the same classloader.
final File outermostJar = nestedJarHandler.getOutermostJar(classInfo.classpathElementFile);
// Get jarfile metadata for classpath element jarfile
final JarfileMetadataReader jarfileMetadataReader =
nestedJarHandler.getJarfileMetadataReader(outermostJar, "", log);
// Create a custom ClassLoader for the jarfile. This might be time consuming, as it could
// trigger the extraction of all classes (for a classpath root other than ""), and/or any
// lib jars (e.g. in BOOT-INF/lib).
customClassLoader = jarfileMetadataReader.getCustomClassLoader(nestedJarHandler, log);
}
if (customClassLoader != null) {
final Class<?> classRefFromCustomClassLoader = loadClass(className, customClassLoader, log);
if (classRefFromCustomClassLoader != null) {
return classRefFromCustomClassLoader;
}
} else {
if (log != null) {
log.log("Unable to create custom classLoader to load class " + className);
}
}
} catch (final Throwable e) {
if (log != null) {
log.log("Exception while trying to load class " + className + " : " + e);
}
}
}
// Could not load class
if (!returnNullIfClassNotFound) {
throw new IllegalArgumentException("No classloader was able to load class " + className);
} else {
if (log != null) {
log.log("No classloader was able to load class " + className);
}
return null;
}
}
public Class<?> loadClass(final String className, final boolean ignoreExceptions)
throws IllegalArgumentException {
try {
return loadClass(className, /* returnNullIfClassNotFound = */ ignoreExceptions, log);
} catch (final Throwable e) {
if (ignoreExceptions) {
return null;
} else {
throw new IllegalArgumentException("Could not load class " + className, e);
}
} finally {
// Manually flush log, since this method is called after scanning is complete
if (log != null) {
log.flush();
}
}
}
<T> Class<T> loadClass(final String className, final Class<T> classType, final boolean ignoreExceptions)
throws IllegalArgumentException {
try {
if (classType == null) {
if (ignoreExceptions) {
return null;
} else {
throw new IllegalArgumentException("classType parameter cannot be null");
}
}
final Class<?> loadedClass = loadClass(className, /* returnNullIfClassNotFound = */ ignoreExceptions,
log);
if (loadedClass != null && !classType.isAssignableFrom(loadedClass)) {
if (ignoreExceptions) {
return null;
} else {
throw new IllegalArgumentException(
"Loaded class " + loadedClass.getName() + " cannot be cast to " + classType.getName());
}
}
@SuppressWarnings("unchecked")
final Class<T> castClass = (Class<T>) loadedClass;
return castClass;
} catch (final Throwable e) {
if (ignoreExceptions) {
return null;
} else {
throw new IllegalArgumentException("Could not load class " + className, e);
}
} finally {
// Manually flush log, since this method is called after scanning is complete
if (log != null) {
log.flush();
}
}
}
/** The current serialization format. */
private static final String CURRENT_SERIALIZATION_FORMAT = "4";
/** A class to hold a serialized ScanResult along with the ScanSpec that was used to scan. */
private static class SerializationFormat {
public String serializationFormat;
public ScanSpec scanSpec;
public List<String> classpath;
public List<ClassInfo> classInfo;
@SuppressWarnings("unused")
public SerializationFormat() {
}
public SerializationFormat(final String serializationFormat, final ScanSpec scanSpec,
final List<ClassInfo> classInfo, final List<String> classpath) {
this.serializationFormat = serializationFormat;
this.scanSpec = scanSpec;
this.classpath = classpath;
this.classInfo = classInfo;
}
}
/** Deserialize a ScanResult from previously-saved JSON. */
public static ScanResult fromJSON(final String json) {
final Matcher matcher = Pattern.compile("\\{[\\n\\r ]*\"serializationFormat\"[ ]?:[ ]?\"([^\"]+)\"")
.matcher(json);
if (!matcher.find()) {
throw new IllegalArgumentException("JSON is not in correct format");
}
if (!CURRENT_SERIALIZATION_FORMAT.equals(matcher.group(1))) {
throw new IllegalArgumentException(
"JSON was serialized in a different format from the format used by the current version of "
+ "FastClasspathScanner -- please serialize and deserialize your ScanResult using "
+ "the same version of FastClasspathScanner");
}
// Deserialize the JSON
final SerializationFormat deserialized = JSONDeserializer.deserializeObject(SerializationFormat.class,
json);
if (!deserialized.serializationFormat.equals(CURRENT_SERIALIZATION_FORMAT)) {
// Probably the deserialization failed before now anyway, if fields have changed, etc.
throw new IllegalArgumentException("JSON was serialized by newer version of FastClasspathScanner");
}
// Get the classpath that produced the serialized JSON, and extract inner jars, download remote jars, etc.
final List<URL> urls = new FastClasspathScanner().overrideClasspath(deserialized.classpath)
.getClasspathURLs();
// Define a custom URLClassLoader with the result that delegates to the first environment classloader
final ClassLoader[] envClassLoaderOrder = new ClassLoaderAndModuleFinder(deserialized.scanSpec,
/* log = */ null).getClassLoaders();
final ClassLoader parentClassLoader = envClassLoaderOrder == null || envClassLoaderOrder.length == 0 ? null
: envClassLoaderOrder[0];
final URLClassLoader urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]),
parentClassLoader);
final ClassLoader[] classLoaderOrder = new ClassLoader[] { urlClassLoader };
// Index ClassInfo objects by name, and set the classLoaders field of each one, for classloading
final Map<String, ClassInfo> classNameToClassInfo = new HashMap<>();
for (final ClassInfo ci : deserialized.classInfo) {
ci.classLoaders = classLoaderOrder;
classNameToClassInfo.put(ci.getName(), ci);
}
// Produce a new ScanResult
final ScanResult scanResult = new ScanResult(deserialized.scanSpec,
/* classpathOrder = */ Collections.<ClasspathElement> emptyList(), deserialized.classpath,
classLoaderOrder, classNameToClassInfo, /* fileToLastModified = */ null,
/* nestedJarHandler = */ null, /* log = */ null);
return scanResult;
}
/**
* Serialize a ScanResult to JSON.
*
* @param indentWidth
* If greater than 0, JSON will be formatted (indented), otherwise it will be minified (un-indented).
*/
public String toJSON(final int indentWidth) {
if (!scanSpec.enableClassInfo) {
throw new IllegalArgumentException("Please call FastClasspathScanner#enableClassInfo() before #scan()");
}
final List<ClassInfo> allClassInfo = new ArrayList<>(classNameToClassInfo.values());
Collections.sort(allClassInfo);
return JSONSerializer.serializeObject(new SerializationFormat(CURRENT_SERIALIZATION_FORMAT, scanSpec,
allClassInfo, rawClasspathEltOrderStrs), indentWidth, false);
}
/** Serialize a ScanResult to minified (un-indented) JSON. */
public String toJSON() {
return toJSON(0);
}
void removeTemporaryFiles(final LogNode log) {
if (allResources != null) {
for (final Resource classpathResource : allResources) {
classpathResource.close();
}
allResources = null;
}
if (nestedJarHandler != null) {
nestedJarHandler.close(log);
}
}
public void removeTemporaryFiles() {
removeTemporaryFiles(null);
}
@Override
protected void finalize() throws Throwable {
// NestedJarHandler also adds a runtime shutdown hook, since finalizers are not reliable
removeTemporaryFiles();
}
}
|
package io.usethesource.vallang.random;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import io.usethesource.vallang.IInteger;
import io.usethesource.vallang.IListWriter;
import io.usethesource.vallang.IMapWriter;
import io.usethesource.vallang.ISetWriter;
import io.usethesource.vallang.IValue;
import io.usethesource.vallang.IValueFactory;
import io.usethesource.vallang.random.util.RandomUtil;
import io.usethesource.vallang.type.DefaultTypeVisitor;
import io.usethesource.vallang.type.ITypeVisitor;
import io.usethesource.vallang.type.Type;
import io.usethesource.vallang.type.TypeFactory;
import io.usethesource.vallang.type.TypeStore;
/**
* A generator of RandomValues, based on Wietse Venema's Cobra generator in the rascal project
* @author Davy Landman
*
*/
public class RandomValueGenerator implements ITypeVisitor<IValue, RuntimeException> {
protected final IValueFactory vf;
protected final Random random;
protected final int maxDepth;
protected final RandomTypeGenerator rt;
protected int currentDepth;
protected TypeStore currentStore;
protected Map<Type, Type> typeParameters;
public RandomValueGenerator(IValueFactory vf, Random random, int maxDepth) {
if (maxDepth <= 0) {
throw new IllegalArgumentException("maxDepth is supposed to be 1 or higher");
}
this.vf = vf;
this.random = random;
this.maxDepth = maxDepth;
this.rt = new RandomTypeGenerator(random);
this.currentStore = null;
this.currentDepth = -1;
this.typeParameters = null;
}
/**
* Generate a new random value of a given type
* @param type which type to generate
* @param store corresponding reified type store that contains the type and all constructors available in this type
* @param typeParameters a map of the bound type parameters
* @return a new IValue corresponding to this type
*/
public IValue generate(Type type, TypeStore store, Map<Type, Type> typeParameters) {
if (currentDepth != -1 || currentStore != null || this.typeParameters != null) {
throw new IllegalStateException("Don't call this method in a nested scenario, RandomValueGenerator's should only be re-used sequentually");
}
currentDepth = 0;
currentStore = store;
this.typeParameters = typeParameters;
try {
return type.accept(this);
} finally {
currentDepth = -1;
currentStore = null;
this.typeParameters = null;
}
}
protected IValue continueGenerating(Type tp) {
return tp.accept(this);
}
protected IValue generateOneDeeper(Type tp) {
try {
currentDepth++;
return tp.accept(this);
}
finally {
currentDepth
}
}
@Override
public IValue visitReal(Type type) throws RuntimeException {
if (random.nextDouble() > 0.6) {
return vf.real(random.nextDouble());
}
if (random.nextDouble() > 0.6) {
return vf.real(-random.nextDouble());
}
if (random.nextDouble() > 0.9) {
BigDecimal r = new BigDecimal(random.nextDouble());
r = r.multiply(new BigDecimal(random.nextInt()).add(new BigDecimal(1000)));
return vf.real(r.toString());
}
return vf.real(0.0);
}
@Override
public IValue visitInteger(Type type) throws RuntimeException {
if (random.nextFloat() > 0.6) {
return vf.integer(random.nextInt());
}
if (random.nextFloat() > 0.6) {
return vf.integer(random.nextInt(10));
}
if (random.nextFloat() > 0.6) {
return vf.integer(-random.nextInt(10));
}
if (random.nextFloat() > 0.9) {
// sometimes, a very huge number
IInteger result = vf.integer(random.nextLong());
do {
result = result.multiply(vf.integer(random.nextLong()));
}
while (random.nextFloat() > 0.4);
return result.add(vf.integer(random.nextInt()));
}
return vf.integer(0);
}
@Override
public IValue visitRational(Type type) throws RuntimeException {
int b = 0;
while (b == 0) {
b = random.nextInt();
}
return vf.rational(random.nextInt(), b);
}
@Override
public IValue visitNumber(Type type) throws RuntimeException {
switch (random.nextInt(3)) {
case 0:
return this.visitInteger(type);
case 1:
return this.visitReal(type);
default:
return this.visitRational(type);
}
}
@Override
public IValue visitBool(Type type) throws RuntimeException {
return vf.bool(random.nextBoolean());
}
@Override
public IValue visitDateTime(Type type) throws RuntimeException {
Calendar cal = Calendar.getInstance();
try {
int milliOffset = random.nextInt(1000) * (random.nextBoolean() ? -1 : 1);
cal.roll(Calendar.MILLISECOND, milliOffset);
int second = random.nextInt(60) * (random.nextBoolean() ? -1 : 1);
cal.roll(Calendar.SECOND, second);
int minute = random.nextInt(60) * (random.nextBoolean() ? -1 : 1);
cal.roll(Calendar.MINUTE, minute);
int hour = random.nextInt(60) * (random.nextBoolean() ? -1 : 1);
cal.roll(Calendar.HOUR_OF_DAY, hour);
int day = random.nextInt(30) * (random.nextBoolean() ? -1 : 1);
cal.roll(Calendar.DAY_OF_MONTH, day);
int month = random.nextInt(12) * (random.nextBoolean() ? -1 : 1);
cal.roll(Calendar.MONTH, month);
// make sure we do not go over the 4 digit year limit, which breaks things
int year = random.nextInt(5000) * (random.nextBoolean() ? -1 : 1);
// make sure we don't go into negative territory
if (cal.get(Calendar.YEAR) + year < 1)
cal.add(Calendar.YEAR, 1);
else
cal.add(Calendar.YEAR, year);
return vf.datetime(cal.getTimeInMillis());
}
catch (IllegalArgumentException e) {
// this may happen if the generated random time does
// not exist due to timezone shifting or due to historical
// calendar standardization changes
// So, we just try again until we hit a better random date
return visitDateTime(type);
// of continued failure before we run out of stack are low.
}
}
private boolean oneEvery(int n) {
return random.nextInt(n) == 0;
}
@Override
public IValue visitSourceLocation(Type type) throws RuntimeException {
try {
String scheme = "tmp";
String authority = "";
String path = "";
String query = "";
String fragment = "";
while (!oneEvery(3)) {
path += "/" + (random.nextDouble() < 0.9 ? RandomUtil.stringAlphaNumeric(random, 1 + random.nextInt(5)) : RandomUtil.string(random, 1 + random.nextInt(5)));
}
if (path.isEmpty()) {
path = "/";
}
if (oneEvery(4)) {
authority = RandomUtil.stringAlphaNumeric(random, 1 + random.nextInt(6));
}
if (oneEvery(30)) {
while (!oneEvery(3)) {
if (!query.isEmpty()) {
query += "&";
}
query += RandomUtil.stringAlpha(random, 1 + random.nextInt(4)) + "=" + RandomUtil.stringAlphaNumeric(random, 1 + random.nextInt(4));
}
}
if (oneEvery(30)) {
fragment = RandomUtil.stringAlphaNumeric(random, 1 + random.nextInt(5));
}
return vf.sourceLocation(scheme, authority, path, query, fragment);
} catch (URISyntaxException e) {
try {
return vf.sourceLocation("tmp", "", "/");
}
catch (URISyntaxException e1) {
throw new RuntimeException("fallback source location should always be correct");
}
}
}
@Override
public IValue visitString(Type type) throws RuntimeException {
if (random.nextBoolean() || currentDepth >= maxDepth) {
return vf.string("");
}
return vf.string(RandomUtil.string(random, 1 + random.nextInt(maxDepth - currentDepth + 3)));
}
@Override
public IValue visitList(Type type) throws RuntimeException {
IListWriter result = vf.listWriter();
if (currentDepth < maxDepth) {
while (!oneEvery(Math.min(4, maxDepth - currentDepth))) {
result.append(generateOneDeeper(type.getElementType()));
}
}
return result.done();
}
@Override
public IValue visitMap(Type type) throws RuntimeException {
IMapWriter result = vf.mapWriter();
if (currentDepth < maxDepth) {
while (!oneEvery(Math.min(4, maxDepth - currentDepth))) {
result.put(generateOneDeeper(type.getKeyType()),generateOneDeeper(type.getValueType()));
}
}
return result.done();
}
@Override
public IValue visitSet(Type type) throws RuntimeException {
ISetWriter result = vf.setWriter();
if (currentDepth < maxDepth) {
while (!oneEvery(Math.min(4, maxDepth - currentDepth))) {
result.insert(generateOneDeeper(type.getElementType()));
}
}
return result.done();
}
@Override
public IValue visitTuple(Type type) throws RuntimeException {
IValue[] elems = new IValue[type.getArity()];
for (int i = 0; i < elems.length; i++) {
elems[i] = generateOneDeeper(type.getFieldType(i));
}
return vf.tuple(elems);
}
@Override
public IValue visitNode(Type type) throws RuntimeException {
String name = random.nextBoolean() ? RandomUtil.string(random, 1 + random.nextInt(5)) : RandomUtil.stringAlpha(random, random.nextInt(5));
int arity = currentDepth >= maxDepth ? 0 : random.nextInt(5);
IValue[] args = new IValue[arity];
for (int i = 0; i < arity; i++) {
args[i] = generateOneDeeper(TypeFactory.getInstance().valueType());
}
if (oneEvery(4) && currentDepth < maxDepth) {
int kwArity = 1 + random.nextInt(4);
Map<String, IValue> kwParams = new HashMap<>(kwArity);
for (int i = 0; i < kwArity; i++) {
String kwName = "";
while (kwName.isEmpty()) {
// names have to start with alpha character
kwName = RandomUtil.stringAlpha(random, 3);
}
kwName += RandomUtil.stringAlphaNumeric(random, 4);
kwParams.put(kwName, generateOneDeeper(TypeFactory.getInstance().valueType()));
}
// normally they are kw params, but sometimes they are annotations
if (oneEvery(10)) {
return vf.node(name, kwParams, args);
}
return vf.node(name, args, kwParams);
}
return vf.node(name, args);
}
private Type pickRandom(Collection<Type> types) {
int nth = random.nextInt(types.size());
int index = 0;
for (Type t: types) {
if (index == nth) {
return t;
}
index++;
}
throw new AssertionError("Dead code");
}
/**
* Find out if the arguments to the constructor contain ADTs or if they contain types that don't increase nesting
*/
private boolean alwaysIncreasesDepth(Type constructor) {
for (int i = 0; i < constructor.getArity(); i++) {
if (constructor.getFieldType(i).isAbstractData()) {
return true;
}
}
return false;
}
@Override
public IValue visitAbstractData(Type type) throws RuntimeException {
Set<Type> candidates = currentStore.lookupAlternatives(type);
if (candidates.isEmpty()) {
throw new UnsupportedOperationException("The "+type+" ADT has no constructors in the type store");
}
Type constructor = pickRandom(candidates);
if (currentDepth >= maxDepth) {
// find the constructor that does not add depth
Iterator<Type> it = candidates.iterator();
while (alwaysIncreasesDepth(constructor) && it.hasNext()) {
constructor = it.next();
}
}
return continueGenerating(constructor);
}
@SuppressWarnings("deprecation")
@Override
public IValue visitConstructor(Type type) throws RuntimeException {
Map<String, Type> kwParamsType = currentStore.getKeywordParameters(type);
Map<String, Type> annoType = currentStore.getAnnotations(type);
if (type.getArity() == 0 && kwParamsType.size() == 0 && annoType.size() == 0) {
return vf.constructor(type);
}
IValue[] args = new IValue[type.getArity()];
for (int i = 0; i < args.length; i++) {
args[i] = generateOneDeeper(type.getFieldType(i));
}
if (kwParamsType.size() > 0 && oneEvery(3)) {
return vf.constructor(type, args, generateMappedArgs(kwParamsType));
}
if (annoType.size() > 0 && oneEvery(5)) {
return vf.constructor(type, generateMappedArgs(annoType), args);
}
return vf.constructor(type, args);
}
private Map<String, IValue> generateMappedArgs(Map<String, Type> types) {
Map<String, IValue> result = new HashMap<>();
for (Entry<String,Type> tp : types.entrySet()) {
if (random.nextBoolean()) {
continue;
}
result.put(tp.getKey(), generateOneDeeper(tp.getValue()));
}
return result;
}
@Override
public IValue visitValue(Type type) throws RuntimeException {
if (oneEvery(7) && !currentStore.getAbstractDataTypes().isEmpty()) {
return continueGenerating(pickRandom(currentStore.getAbstractDataTypes()));
}
return continueGenerating(rt.next(maxDepth - currentDepth));
}
@Override
public IValue visitParameter(Type parameterType) throws RuntimeException {
Type type = typeParameters.get(parameterType);
if(type == null){
throw new IllegalArgumentException("Unbound type parameter " + parameterType);
}
return continueGenerating(type);
}
@Override
public IValue visitAlias(Type type) throws RuntimeException {
return continueGenerating(type.getAliased());
}
@Override
public IValue visitExternal(Type type) throws RuntimeException {
throw new RuntimeException("External type (" + type + ") not supported, use inheritance to add it");
}
@Override
public IValue visitVoid(Type type) throws RuntimeException {
throw new RuntimeException("Void has no values");
}
}
|
package mcjty.deepresonance.blocks.generator;
import mcjty.deepresonance.blocks.GenericDRBlock;
import mcjty.lib.container.EmptyContainer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import mcjty.deepresonance.DeepResonance;
import mcjty.deepresonance.client.ClientHandler;
import mcjty.deepresonance.generatornetwork.DRGeneratorNetwork;
import mcjty.deepresonance.network.PacketGetGeneratorInfo;
import mcjty.lib.container.GenericBlock;
import mcjty.lib.varia.BlockTools;
import mcp.mobius.waila.api.IWailaConfigHandler;
import mcp.mobius.waila.api.IWailaDataAccessor;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.util.EnumFacing;
import org.lwjgl.input.Keyboard;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
public class GeneratorBlock extends GenericDRBlock<GeneratorTileEntity, EmptyContainer> {
public static final int META_ON = 1;
public static final int META_OFF = 0;
public static final int META_HASUPPER = 2;
public static final int META_HASLOWER = 4;
public static int tooltipEnergy = 0;
public static int tooltipRefCount = 0;
public static int tooltipRfPerTick = 0;
private static long lastTime = 0;
public GeneratorBlock() {
super(Material.iron, GeneratorTileEntity.class, EmptyContainer.class, "generator", false);
}
@Override
public boolean isHorizRotation() {
return true;
}
@Override
public int getGuiID() {
return -1;
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean whatIsThis) {
super.addInformation(itemStack, player, list, whatIsThis);
NBTTagCompound tagCompound = itemStack.getTagCompound();
if (tagCompound != null) {
list.add(EnumChatFormatting.YELLOW + "Energy: " + tagCompound.getInteger("energy"));
}
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) {
list.add("Part of a generator multi-block.");
list.add("You can place these in any configuration.");
} else {
list.add(EnumChatFormatting.WHITE + ClientHandler.getShiftMessage());
}
}
@Override
@SideOnly(Side.CLIENT)
public List<String> getWailaBody(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
TileEntity tileEntity = accessor.getTileEntity();
if (tileEntity instanceof GeneratorTileEntity) {
GeneratorTileEntity generatorTileEntity = (GeneratorTileEntity) tileEntity;
currenttip.add(EnumChatFormatting.GREEN + "ID: " + new DecimalFormat("#.##").format(generatorTileEntity.getNetworkId()));
if (System.currentTimeMillis() - lastTime > 250) {
lastTime = System.currentTimeMillis();
DeepResonance.networkHandler.getNetworkWrapper().sendToServer(new PacketGetGeneratorInfo(generatorTileEntity.getNetworkId()));
}
currenttip.add(EnumChatFormatting.GREEN + "Energy: " + tooltipEnergy + "/" + (tooltipRefCount*GeneratorConfiguration.rfPerGeneratorBlock) + " RF");
currenttip.add(EnumChatFormatting.YELLOW + Integer.toString(tooltipRfPerTick) + " RF/t");
}
return currenttip;
}
/*private void updateMeta(World world, int x, int y, int z) {
int meta = world.getBlockMetadata(x, y, z) & BlockTools.MASK_REDSTONE_IN;
if (world.getBlock(x, y+1, z) == GeneratorSetup.generatorBlock) {
meta |= META_HASUPPER;
}
if (world.getBlock(x, y-1, z) == GeneratorSetup.generatorBlock) {
meta |= META_HASLOWER;
}
world.setBlockMetadataWithNotify(x, y, z, meta, 3);
}
@Override
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityLivingBase, ItemStack itemStack) {
super.onBlockPlacedBy(world, x, y, z, entityLivingBase, itemStack);
if (!world.isRemote) {
updateMeta(world, x, y, z);
if (world.getBlock(x, y+1, z) == GeneratorSetup.generatorBlock) {
updateMeta(world, x, y+1, z);
}
if (world.getBlock(x, y-1, z) == GeneratorSetup.generatorBlock) {
updateMeta(world, x, y-1, z);
}
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof GeneratorTileEntity) {
((GeneratorTileEntity) te).addBlockToNetwork();
DRGeneratorNetwork.Network network = ((GeneratorTileEntity) te).getNetwork();
if (network != null) {
NBTTagCompound tagCompound = itemStack.getTagCompound();
network.setEnergy(network.getEnergy() + (tagCompound == null ? 0 : tagCompound.getInteger("energy")));
DRGeneratorNetwork generatorNetwork = DRGeneratorNetwork.getChannels(world);
generatorNetwork.save(world);
}
}
}
}
@Override
public ArrayList<ItemStack> getDrops(World world, int x, int y, int z, int metadata, int fortune) {
ArrayList<ItemStack> drops = super.getDrops(world, x, y, z, metadata, fortune);
if (!world.isRemote) {
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof GeneratorTileEntity) {
DRGeneratorNetwork.Network network = ((GeneratorTileEntity) te).getNetwork();
if (network != null) {
int energy = network.getEnergy() / network.getGeneratorBlocks();
if (!drops.isEmpty()) {
NBTTagCompound tagCompound = drops.get(0).getTagCompound();
if (tagCompound == null) {
tagCompound = new NBTTagCompound();
drops.get(0).setTagCompound(tagCompound);
}
tagCompound.setInteger("energy", energy);
}
}
}
}
return drops;
}
@Override
public void breakBlock(World world, int x, int y, int z, Block block, int meta) {
if (!world.isRemote) {
TileEntity te = world.getTileEntity(x, y, z);
if (te instanceof GeneratorTileEntity) {
DRGeneratorNetwork.Network network = ((GeneratorTileEntity) te).getNetwork();
if (network != null) {
int energy = network.getEnergy() / network.getGeneratorBlocks();
network.setEnergy(network.getEnergy() - energy);
}
((GeneratorTileEntity) te).removeBlockFromNetwork();
}
}
super.breakBlock(world, x, y, z, block, meta);
if (!world.isRemote) {
if (world.getBlock(x, y+1, z) == GeneratorSetup.generatorBlock) {
updateMeta(world, x, y+1, z);
}
if (world.getBlock(x, y-1, z) == GeneratorSetup.generatorBlock) {
updateMeta(world, x, y - 1, z);
}
}
}*/
}
|
package me.konsolas.conditionalcommands;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ConditionalCommands extends JavaPlugin {
private static final Pattern SPLIT_PATTERN = Pattern.compile("/([0-9]*)/");
public void onEnable() {
getLogger().info("Initializing placeholders...");
for (Placeholders placeholder : Placeholders.values()) {
placeholder.getPlaceholder().init(this);
}
getLogger().info("Ready.");
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length == 0 || (args.length > 1 && args.length < 5)) {
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] > Incorrect number of arguments.");
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] >" + ChatColor.GREEN + " /cc help");
return false;
}
if (args.length == 1) {
if (args[0].equals("help")) {
sender.sendMessage(ChatColor.GOLD + "
sender.sendMessage(ChatColor.GREEN + " /cc help");
sender.sendMessage(ChatColor.GREEN + " /cc <player> unless \"" + ChatColor.LIGHT_PURPLE + "condition" + ChatColor.GREEN + "\" do \"" + ChatColor.LIGHT_PURPLE + "command" + ChatColor.GREEN + "\"");
sender.sendMessage(ChatColor.GREEN + " /cc <player> if \"" + ChatColor.LIGHT_PURPLE + "condition" + ChatColor.GREEN + "\" do \"" + ChatColor.LIGHT_PURPLE + "command" + ChatColor.GREEN + "\"");
sender.sendMessage(ChatColor.GRAY + "e.g.");
sender.sendMessage(ChatColor.GREEN + " /cc konsolas unless -ping->100|-tps-<10.0 do kick konsolas");
sender.sendMessage(ChatColor.GRAY + "Please note that conditions cannot include any spaces.");
sender.sendMessage(ChatColor.GOLD + "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
} else {
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] > Incorrect subcommand.");
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] >" + ChatColor.GREEN + " /cc help");
}
return false;
}
// Sub command
String action = args[1];
// Get the player
Player placeholderFor = Bukkit.getPlayer(args[0]);
if (placeholderFor == null) {
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] > Not dispatching command because " + args[0] + " is not online...");
return true;
}
// Get the condition
String modifiedStr = args[2];
for (Placeholders placeholder : Placeholders.values()) {
if (placeholder.getPlaceholder().shouldApply(modifiedStr)) {
try {
modifiedStr = placeholder.getPlaceholder().doSubstitution(modifiedStr, placeholderFor);
} catch (Exception ex) {
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] > Failed to apply a placeholder: " + ex.getMessage());
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] >" + ChatColor.GREEN + " /cc help");
getLogger().severe("An error occurred whilst applying a placeholder.");
ex.printStackTrace();
return false;
}
}
}
// Get the command
StringBuilder command = new StringBuilder();
for (int i = 4; i < args.length; i++) {
command.append(args[i]).append(' ');
}
// Make sure there's a 'do' third.
if (!args[3].equals("do")) {
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] > Missing 'do' clause. Make sure the condition has no spaces.");
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] >" + ChatColor.GREEN + " /cc help");
return false;
}
// Parse the expression
Expression expression;
try {
expression = new Expression(modifiedStr);
} catch (Expression.ParseException ex) {
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] > Failed to parse \"" + modifiedStr + "\": " + ex.getClass().getSimpleName() + ": " + ex.getMessage());
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] > Roughly translated, that means you spelt something wrong or made a syntax error in the condition.");
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] >" + ChatColor.GREEN + " /cc help");
return false;
}
getLogger().info("Successfully parsed expression: " + expression.toString());
switch (action) {
case "unless":
if (!expression.evaluate()) {
dispatchCommand(sender, command.toString());
} else {
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] > Not dispatching command because \"" + args[2] + "\" evaluated to true");
}
break;
case "if":
if (expression.evaluate()) {
dispatchCommand(sender, command.toString());
} else {
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] > Not dispatching command because \"" + args[2] + "\" evaluated to false");
}
break;
default:
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] > Incorrect subcommand.");
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] >" + ChatColor.GREEN + " /cc help");
return false;
}
return true;
}
private void dispatchCommand(final CommandSender sender, String command) {
// Delayed/multi command syntax.
Matcher matcher = SPLIT_PATTERN.matcher(command);
if (!matcher.find()) {
protectedDispatch(sender, command);
} else {
try {
int delay, cmdStart, cmdEnd;
do {
delay = Integer.parseInt(matcher.group(1));
cmdStart = matcher.end();
if (!matcher.find()) {
cmdEnd = command.length();
} else {
cmdEnd = matcher.start();
}
final String cmd = command.substring(cmdStart, cmdEnd).trim();
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] > Will dispatch command \"" + cmd + "\" in " + delay + " ticks");
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@Override
public void run() {
protectedDispatch(sender, cmd);
}
}, delay);
} while (cmdEnd != command.length());
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] > Invalid delay in the format /<delay>/: " + e.getMessage());
}
}
}
private void protectedDispatch(CommandSender sender, String command) {
try {
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] > Dispatching command \"" + command + "\"");
this.getServer().dispatchCommand(sender, command);
} catch (CommandException ex) {
sender.sendMessage(ChatColor.GOLD + "[ConditionalCommands] > An error occurred whilst executing the command. The stack trace has been printed to the console.");
this.getLogger().warning("Failed to execute command. THIS IS NOT AN ERROR WITH CONDITIONALCOMMANDS!");
ex.printStackTrace();
}
}
}
|
package me.modmuss50.rebornstorage.blocks;
import com.google.common.collect.Lists;
import com.raoulvdberge.refinedstorage.api.network.node.INetworkNode;
import com.raoulvdberge.refinedstorage.api.network.node.INetworkNodeManager;
import com.raoulvdberge.refinedstorage.apiimpl.API;
import me.modmuss50.rebornstorage.client.CreativeTabRebornStorage;
import me.modmuss50.rebornstorage.lib.ModInfo;
import me.modmuss50.rebornstorage.packet.PacketGui;
import me.modmuss50.rebornstorage.tiles.TileMultiCrafter;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import reborncore.common.blocks.PropertyString;
import reborncore.common.multiblock.BlockMultiblockBase;
import reborncore.common.util.ArrayUtils;
import reborncore.common.util.ChatUtils;
import java.util.List;
public class BlockMultiCrafter extends BlockMultiblockBase {
public static final String[] types = new String[] { "frame", "heat", "cpu", "storage" };
private static final List<String> typesList = Lists.newArrayList(ArrayUtils.arrayToLowercase(types));
public static final PropertyString VARIANTS = new PropertyString("type", types);
public BlockMultiCrafter() {
super(Material.IRON);
setCreativeTab(CreativeTabRebornStorage.INSTANCE);
setUnlocalizedName(ModInfo.MOD_ID + ".multicrafter");
this.setDefaultState(this.getStateFromMeta(0));
setHardness(2F);
}
@Override
public TileEntity createNewTileEntity(World worldIn, int meta) {
return new TileMultiCrafter();
}
@Override
public boolean onBlockActivated(World worldIn,
BlockPos pos,
IBlockState state,
EntityPlayer playerIn,
EnumHand hand,
EnumFacing side,
float hitX,
float hitY,
float hitZ) {
TileMultiCrafter tile = (TileMultiCrafter) worldIn.getTileEntity(pos);
if (tile.getMultiblockController() != null) {
if (!tile.getMultiblockController().isAssembled()) {
if (tile.getMultiblockController().getLastValidationException() != null) {
if (worldIn.isRemote && playerIn.getHeldItem(EnumHand.MAIN_HAND).isEmpty()) {
ChatUtils.sendNoSpamMessages(42, new TextComponentString(tile.getMultiblockController().getLastValidationException().getMessage()));
}
return false;
}
} else if (!worldIn.isRemote) {
new PacketGui(tile.getValidLastPage(), pos).openGUI(playerIn);
return true;
}
return true;
}
return super.onBlockActivated(worldIn, pos, state, playerIn, hand, side, hitX, hitY, hitZ);
}
@Override
public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) {
super.onBlockPlacedBy(world, pos, state, placer, stack);
if (!world.isRemote) {
API.instance().discoverNode(world, pos);
}
}
@Override
public IBlockState getStateFromMeta(int meta) {
return getBlockState().getBaseState().withProperty(VARIANTS, typesList.get(meta));
}
@Override
public int getMetaFromState(IBlockState state) {
return typesList.indexOf(state.getValue(VARIANTS));
}
@Override
protected BlockStateContainer createBlockState() {
return new BlockStateContainer(this, VARIANTS);
}
@Override
@SideOnly(Side.CLIENT)
public void getSubBlocks(CreativeTabs creativeTabs, NonNullList<ItemStack> list) {
for (int meta = 0; meta < types.length; meta++) {
list.add(new ItemStack(this, 1, meta));
}
}
@Override
public int damageDropped(IBlockState state) {
return getMetaFromState(state);
}
@Override
public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) {
return new ItemStack(this, 1, getMetaFromState(state));
}
@Override
public void breakBlock(World worldIn, BlockPos pos, IBlockState state) {
TileEntity tileentity = worldIn.getTileEntity(pos);
if (tileentity instanceof TileMultiCrafter) {
TileMultiCrafter tile = (TileMultiCrafter) tileentity;
if (tile.getNode().patterns != null) {
for (int i = 0; i < tile.getNode().patterns.getSlots(); i++) {
ItemStack stack = tile.getNode().patterns.getStackInSlot(i);
if (!stack.isEmpty()) {
InventoryHelper.spawnItemStack(worldIn, pos.getX(), pos.getY(), pos.getZ(), stack.copy());
}
}
}
}
INetworkNodeManager manager = API.instance().getNetworkNodeManager(worldIn);
INetworkNode node = manager.getNode(pos);
manager.removeNode(pos);
manager.markForSaving();
if (node.getNetwork() != null) {
node.getNetwork().getNodeGraph().rebuild();
}
worldIn.removeTileEntity(pos);
super.breakBlock(worldIn, pos, state);
}
}
|
package me.st28.flexseries.flexlib.plugin.module;
import me.st28.flexseries.flexlib.log.LogHelper;
import me.st28.flexseries.flexlib.player.data.DataProviderDescriptor;
import me.st28.flexseries.flexlib.player.PlayerManager;
import me.st28.flexseries.flexlib.player.data.PlayerDataProvider;
import me.st28.flexseries.flexlib.plugin.FlexPlugin;
import me.st28.flexseries.flexlib.storage.flatfile.YamlFileManager;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.Listener;
import java.io.File;
import java.io.InputStreamReader;
/**
* Handles a feature of a {@link FlexPlugin}.
*
* @param <T> The {@link FlexPlugin} that owns this module.
*/
public abstract class FlexModule<T extends FlexPlugin> {
private ModuleStatus status = ModuleStatus.PENDING;
protected final T plugin;
protected final String name;
protected final String description;
protected final ModuleDescriptor descriptor;
private File dataFolder;
private YamlFileManager configFile;
public FlexModule(T plugin, String name, String description, ModuleDescriptor descriptor) {
Validate.notNull(plugin, "Plugin cannot be null.");
Validate.notNull(name, "Name cannot be null.");
Validate.notNull(descriptor, "Descriptor cannot be null.");
this.plugin = plugin;
this.name = name;
if (description == null) {
this.description = "(no description set)";
} else {
this.description = description;
}
this.descriptor = descriptor;
if (this instanceof PlayerDataProvider) {
descriptor.addHardDependency(new ModuleReference("FlexLib", "players"));
}
descriptor.lock();
}
/**
* @return the {@link ModuleStatus} of this module.
*/
public final ModuleStatus getStatus() {
return status;
}
/**
* <b>Internal code</b> - should never be called outside of FlexLib.
*/
public final void setStatus(ModuleStatus status) {
this.status = status;
}
/**
* @return the {@link FlexPlugin} that owns this module.
*/
public final T getPlugin() {
return plugin;
}
/**
* @return the name of this module.
*/
public final String getName() {
return name;
}
/**
* @return the description of this module.
*/
public final String getDescription() {
return description;
}
/**
* @return the {@link ModuleDescriptor} for this module.
*/
public final ModuleDescriptor getDescriptor() {
return descriptor;
}
/**
* @return the data folder for this module. Will be created if it doesn't already exist.
*/
public final File getDataFolder() {
if (!dataFolder.exists()) {
dataFolder.mkdirs();
}
return dataFolder;
}
/**
* @return the configuration file for this module.
*/
public final FileConfiguration getConfig() {
if (configFile == null) {
throw new UnsupportedOperationException("This module does not have a configuration file.");
}
return configFile.getConfig();
}
/**
* Reloads the configuration file for this module.
*/
public final void reloadConfig() {
if (configFile != null) {
try {
configFile.reload();
FileConfiguration config = configFile.getConfig();
config.addDefaults(YamlConfiguration.loadConfiguration(new InputStreamReader(plugin.getResource("modules/" + name + "/config.yml"))));
config.options().copyDefaults(true);
configFile.save();
configFile.reload();
} catch (Exception ex) {
LogHelper.severe(this, "An exception occurred while reloading the configuration file.", ex);
}
}
}
/**
* Saves the module's configuration file.
*/
public final void saveConfig() {
if (configFile != null) {
configFile.save();
}
}
/**
* Registers this module as a {@link PlayerDataProvider} with the {@link PlayerManager}.
*
* @return True if successfully registered.<br />
* False if already registered.
*/
protected final boolean registerPlayerDataProvider(DataProviderDescriptor descriptor) {
Validate.isTrue(this instanceof PlayerDataProvider, "This module must implement PlayerDataProvider.");
Validate.notNull(descriptor, "Descriptor cannot be null.");
return FlexPlugin.getGlobalModule(PlayerManager.class).registerDataProvider((PlayerDataProvider) this, descriptor);
}
public final void onEnable() {
status = ModuleStatus.LOADING;
dataFolder = new File(plugin.getDataFolder() + File.separator + name);
if (plugin.getResource("modules/" + name + "/config.yml") != null) {
configFile = new YamlFileManager(plugin.getDataFolder() + File.separator + "config-" + name + ".yml");
} else {
configFile = null;
}
reloadConfig();
try {
handleEnable();
} catch (Exception ex) {
status = ModuleStatus.DISABLED_ERROR;
throw new RuntimeException("An exception occurred while enabling module '" + name + "'", ex);
}
try {
handleReload();
} catch (Exception ex) {
status = ModuleStatus.ENABLED_ERROR;
throw new RuntimeException("An exception occurred while reloading module '" + name + "'", ex);
}
if (this instanceof Listener) {
Bukkit.getPluginManager().registerEvents((Listener) this, plugin);
}
status = ModuleStatus.ENABLED;
}
public final void onReload() {
status = ModuleStatus.RELOADING;
reloadConfig();
try {
handleReload();
} catch (Exception ex) {
status = ModuleStatus.ENABLED_ERROR;
throw new RuntimeException("An exception occurred while reloading module '" + name + "'", ex);
}
status = ModuleStatus.ENABLED;
}
public final void onSave(boolean async) {
try {
handleSave(async);
} catch (Exception ex) {
LogHelper.severe(this, "An exception occurred while saving module '" + name + "'", ex);
}
saveConfig();
}
public final void onDisable() {
status = ModuleStatus.UNLOADING;
onSave(false);
try {
handleDisable();
} catch (Exception ex) {
status = ModuleStatus.DISABLED_ERROR;
throw new RuntimeException("An exception occurred while disabling module '" + name + "'", ex);
}
status = ModuleStatus.DISABLED;
}
/**
* Handles custom enable tasks. This will only be called once.
*/
protected void handleEnable() {}
/**
* Handles custom reload tasks.
*/
protected void handleReload() {}
/**
* Handles custom module save tasks.
*
* @param async If true, should save asynchronously (where applicable).
*/
protected void handleSave(boolean async) {}
/**
* Handles custom module disable tasks. This will only be called once.<br />
* {@link #handleSave(boolean)} will be called automatically, so this should not call it again.
*/
protected void handleDisable() {}
}
|
package microsoft.exchange.webservices.data;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.FutureTask;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* Represents a binding to the Exchange Web Services.
*/
public final class ExchangeService extends ExchangeServiceBase implements
IAutodiscoverRedirectionUrl {
/** The url. */
private URI url;
/** The preferred culture. */
private Locale preferredCulture;
/** The DateTimePrecision */
private DateTimePrecision dateTimePrecision = DateTimePrecision.Default;
/** The impersonated user id. */
private ImpersonatedUserId impersonatedUserId;
// private Iterator<ItemId> Iterator;
/** The file attachment content handler. */
private IFileAttachmentContentHandler fileAttachmentContentHandler;
/** The unified messaging. */
private UnifiedMessaging unifiedMessaging;
// private boolean exchange2007CompatibilityMode;
private boolean enableScpLookup = true;
private boolean exchange2007CompatibilityMode;
/**
* Create response object.
*
* @param responseObject
* the response object
* @param parentFolderId
* the parent folder id
* @param messageDisposition
* the message disposition
* @return The list of items created or modified as a result of the
* "creation" of the response object.
* @throws Exception
* the exception
*/
protected List<Item> internalCreateResponseObject(
ServiceObject responseObject, FolderId parentFolderId,
MessageDisposition messageDisposition) throws Exception {
CreateResponseObjectRequest request = new CreateResponseObjectRequest(
this, ServiceErrorHandling.ThrowOnError);
Collection<ServiceObject> serviceList = new ArrayList();
serviceList.add(responseObject);
request.setParentFolderId(parentFolderId);
request.setItems(serviceList);
request.setMessageDisposition(messageDisposition);
ServiceResponseCollection<CreateResponseObjectResponse> responses = request
.execute();
return responses.getResponseAtIndex(0).getItems();
}
/**
* Creates a folder. Calling this method results in a call to EWS.
*
* @param folder
* The folder.
* @param parentFolderId
* The parent folder Id
* @throws Exception
* the exception
*/
protected void createFolder(Folder folder, FolderId parentFolderId)
throws Exception {
CreateFolderRequest request = new CreateFolderRequest(this,
ServiceErrorHandling.ThrowOnError);
List<Folder> folArry = new ArrayList<Folder>();
folArry.add(folder);
request.setFolders(folArry);
request.setParentFolderId(parentFolderId);
request.execute();
}
/**
* Updates a folder.
*
* @param folder
* The folder.
* @throws Exception
* the exception
*/
protected void updateFolder(Folder folder) throws Exception {
UpdateFolderRequest request = new UpdateFolderRequest(this,
ServiceErrorHandling.ThrowOnError);
request.getFolders().add(folder);
request.execute();
}
/**
* Copies a folder. Calling this method results in a call to EWS.
*
* @param folderId
* The folderId.
* @param destinationFolderId
* The destination folder id.
* @return the folder
* @throws Exception
* the exception
*/
protected Folder copyFolder(FolderId folderId, FolderId destinationFolderId)
throws Exception {
CopyFolderRequest request = new CopyFolderRequest(this,
ServiceErrorHandling.ThrowOnError);
request.setDestinationFolderId(destinationFolderId);
request.getFolderIds().add(folderId);
ServiceResponseCollection<MoveCopyFolderResponse> responses = request
.execute();
return responses.getResponseAtIndex(0).getFolder();
}
/**
* Move a folder.
*
* @param folderId
* The folderId.
* @param destinationFolderId
* The destination folder id.
* @return the folder
* @throws Exception
* the exception
*/
protected Folder moveFolder(FolderId folderId, FolderId destinationFolderId)
throws Exception {
MoveFolderRequest request = new MoveFolderRequest(this,
ServiceErrorHandling.ThrowOnError);
request.setDestinationFolderId(destinationFolderId);
request.getFolderIds().add(folderId);
ServiceResponseCollection<MoveCopyFolderResponse> responses = request
.execute();
return responses.getResponseAtIndex(0).getFolder();
}
/**
* Finds folders.
*
* @param parentFolderIds
* The parent folder ids.
* @param searchFilter
* The search filter. Available search filter classes include
* SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and
* SearchFilter.SearchFilterCollection
* @param view
* The view controlling the number of folders returned.
* @param errorHandlingMode
* Indicates the type of error handling should be done.
* @return Collection of service responses.
* @throws Exception
* the exception
*/
private ServiceResponseCollection<FindFolderResponse> internalFindFolders(
Iterable<FolderId> parentFolderIds, SearchFilter searchFilter,
FolderView view, ServiceErrorHandling errorHandlingMode)
throws Exception {
FindFolderRequest request = new FindFolderRequest(this,
errorHandlingMode);
request.getParentFolderIds().addRangeFolderId(parentFolderIds);
request.setSearchFilter(searchFilter);
request.setView(view);
return request.execute();
}
/**
* Obtains a list of folders by searching the sub-folders of the specified
* folder.
*
* @param parentFolderId
* The Id of the folder in which to search for folders.
* @param searchFilter
* The search filter. Available search filter classes include
* SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and
* SearchFilter.SearchFilterCollection
* @param view
* The view controlling the number of folders returned.
* @return An object representing the results of the search operation.
* @throws Exception
* the exception
*/
public FindFoldersResults findFolders(FolderId parentFolderId,
SearchFilter searchFilter, FolderView view) throws Exception {
EwsUtilities.validateParam(parentFolderId, "parentFolderId");
EwsUtilities.validateParam(view, "view");
EwsUtilities.validateParamAllowNull(searchFilter, "searchFilter");
List<FolderId> folderIdArray = new ArrayList<FolderId>();
folderIdArray.add(parentFolderId);
ServiceResponseCollection<FindFolderResponse> responses = this
.internalFindFolders(folderIdArray, searchFilter, view,
ServiceErrorHandling.ThrowOnError);
return responses.getResponseAtIndex(0).getResults();
}
/**
* Obtains a list of folders by searching the sub-folders of the specified
* folder.
*
* @param parentFolderId
* The Id of the folder in which to search for folders.
* @param view
* The view controlling the number of folders returned.
* @return An object representing the results of the search operation.
* @throws Exception
* the exception
*/
public FindFoldersResults findFolders(FolderId parentFolderId,
FolderView view) throws Exception {
EwsUtilities.validateParam(parentFolderId, "parentFolderId");
EwsUtilities.validateParam(view, "view");
List<FolderId> folderIdArray = new ArrayList<FolderId>();
folderIdArray.add(parentFolderId);
ServiceResponseCollection<FindFolderResponse> responses = this
.internalFindFolders(folderIdArray, null, /* searchFilter */
view, ServiceErrorHandling.ThrowOnError);
return responses.getResponseAtIndex(0).getResults();
}
/**
* Obtains a list of folders by searching the sub-folders of the specified
* folder.
*
* @param parentFolderName
* The name of the folder in which to search for folders.
* @param searchFilter
* The search filter. Available search filter classes include
* SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and
* SearchFilter.SearchFilterCollection
* @param view
* The view controlling the number of folders returned.
* @return An object representing the results of the search operation.
* @throws Exception
* the exception
*/
public FindFoldersResults findFolders(WellKnownFolderName parentFolderName,
SearchFilter searchFilter, FolderView view) throws Exception {
return this.findFolders(new FolderId(parentFolderName), searchFilter,
view);
}
/**
* Obtains a list of folders by searching the sub-folders of the specified
* folder.
*
* @param parentFolderName
* the parent folder name
* @param view
* the view
* @return An object representing the results of the search operation.
* @throws Exception
* the exception
*/
public FindFoldersResults findFolders(WellKnownFolderName parentFolderName,
FolderView view) throws Exception {
return this.findFolders(new FolderId(parentFolderName), view);
}
/**
* Load specified properties for a folder.
*
* @param folder
* The folder
* @param propertySet
* The property set
* @throws Exception
* the exception
*/
protected void loadPropertiesForFolder(Folder folder,
PropertySet propertySet) throws Exception {
EwsUtilities.validateParam(folder, "folder");
EwsUtilities.validateParam(propertySet, "propertySet");
GetFolderRequestForLoad request = new GetFolderRequestForLoad(this,
ServiceErrorHandling.ThrowOnError);
request.getFolderIds().add(folder);
request.setPropertySet(propertySet);
request.execute();
}
/**
* Binds to a folder.
*
* @param folderId
* the folder id
* @param propertySet
* the property set
* @return Folder
* @throws Exception
* the exception
*/
protected Folder bindToFolder(FolderId folderId, PropertySet propertySet)
throws Exception {
EwsUtilities.validateParam(folderId, "folderId");
EwsUtilities.validateParam(propertySet, "propertySet");
GetFolderRequest request = new GetFolderRequest(this,
ServiceErrorHandling.ThrowOnError);
request.getFolderIds().add(folderId);
request.setPropertySet(propertySet);
ServiceResponseCollection<GetFolderResponse> responses = request
.execute();
return responses.getResponseAtIndex(0).getFolder();
}
/**
* Binds to folder.
*
* @param <TFolder>
* The type of the folder.
* @param cls
* Folder class
* @param folderId
* The folder id.
* @param propertySet
* The property set.
* @return Folder
* @throws Exception
* the exception
*/
protected <TFolder extends Folder> TFolder bindToFolder(Class<TFolder> cls,
FolderId folderId, PropertySet propertySet) throws Exception {
Folder result = this.bindToFolder(folderId, propertySet);
if (cls.isAssignableFrom(result.getClass())) {
return (TFolder) result;
} else {
throw new ServiceLocalException(String.format(Strings.FolderTypeNotCompatible,
result.getClass().getName(), cls.getName()));
}
}
/**
* Deletes a folder. Calling this method results in a call to EWS.
*
* @param folderId
* The folder id
* @param deleteMode
* The delete mode
* @throws Exception
* the exception
*/
protected void deleteFolder(FolderId folderId, DeleteMode deleteMode)
throws Exception {
EwsUtilities.validateParam(folderId, "folderId");
DeleteFolderRequest request = new DeleteFolderRequest(this,
ServiceErrorHandling.ThrowOnError);
request.getFolderIds().add(folderId);
request.setDeleteMode(deleteMode);
request.execute();
}
/**
* Empties a folder. Calling this method results in a call to EWS.
*
* @param folderId
* The folder id
* @param deleteMode
* The delete mode
* @param deleteSubFolders
* if set to <c>true</c> empty folder should also delete sub
* folders.
* @throws Exception
* the exception
*/
protected void emptyFolder(FolderId folderId, DeleteMode deleteMode,
boolean deleteSubFolders) throws Exception {
EwsUtilities.validateParam(folderId, "folderId");
EmptyFolderRequest request = new EmptyFolderRequest(this,
ServiceErrorHandling.ThrowOnError);
request.getFolderIds().add(folderId);
request.setDeleteMode(deleteMode);
request.setDeleteSubFolders(deleteSubFolders);
request.execute();
}
/**
* Creates multiple items in a single EWS call. Supported item classes are
* EmailMessage, Appointment, Contact, PostItem, Task and Item. CreateItems
* does not support items that have unsaved attachments.
*
* @param items
* the items
* @param parentFolderId
* the parent folder id
* @param messageDisposition
* the message disposition
* @param sendInvitationsMode
* the send invitations mode
* @param errorHandling
* the error handling
* @return A ServiceResponseCollection providing creation results for each
* of the specified items.
* @throws Exception
* the exception
*/
private ServiceResponseCollection<ServiceResponse> internalCreateItems(
Collection<Item> items, FolderId parentFolderId,
MessageDisposition messageDisposition,
SendInvitationsMode sendInvitationsMode,
ServiceErrorHandling errorHandling) throws Exception {
CreateItemRequest request = new CreateItemRequest(this, errorHandling);
request.setParentFolderId(parentFolderId);
request.setItems(items);
request.setMessageDisposition(messageDisposition);
request.setSendInvitationsMode(sendInvitationsMode);
return request.execute();
}
/**
* Creates multiple items in a single EWS call. Supported item classes are
* EmailMessage, Appointment, Contact, PostItem, Task and Item. CreateItems
* does not support items that have unsaved attachments.
*
* @param items
* the items
* @param parentFolderId
* the parent folder id
* @param messageDisposition
* the message disposition
* @param sendInvitationsMode
* the send invitations mode
* @return A ServiceResponseCollection providing creation results for each
* of the specified items.
* @throws Exception
* the exception
*/
public ServiceResponseCollection<ServiceResponse> createItems(
Collection<Item> items, FolderId parentFolderId,
MessageDisposition messageDisposition,
SendInvitationsMode sendInvitationsMode) throws Exception {
// All items have to be new.
if (!EwsUtilities.trueForAll(items, new IPredicate<Item>() {
@Override
public boolean predicate(Item obj) throws ServiceLocalException {
return obj.isNew();
}
})) {
throw new ServiceValidationException(
Strings.CreateItemsDoesNotHandleExistingItems);
}
// E14:298274 Make sure that all items do *not* have unprocessed
// attachments.
if (!EwsUtilities.trueForAll(items, new IPredicate<Item>() {
@Override
public boolean predicate(Item obj) throws ServiceLocalException {
return !obj.hasUnprocessedAttachmentChanges();
}
})) {
throw new ServiceValidationException(
Strings.CreateItemsDoesNotAllowAttachments);
}
return this.internalCreateItems(items, parentFolderId,
messageDisposition, sendInvitationsMode,
ServiceErrorHandling.ReturnErrors);
}
/**
* Creates an item. Calling this method results in a call to EWS.
*
* @param item
* the item
* @param parentFolderId
* the parent folder id
* @param messageDisposition
* the message disposition
* @param sendInvitationsMode
* the send invitations mode
* @throws Exception
* the exception
*/
protected void createItem(Item item, FolderId parentFolderId,
MessageDisposition messageDisposition,
SendInvitationsMode sendInvitationsMode) throws Exception {
ArrayList<Item> items = new ArrayList<Item>();
items.add(item);
internalCreateItems(items, parentFolderId, messageDisposition,
sendInvitationsMode, ServiceErrorHandling.ThrowOnError);
}
/**
* Updates multiple items in a single EWS call. UpdateItems does not
* support items that have unsaved attachments.
*
* @param items
* the items
* @param savedItemsDestinationFolderId
* the saved items destination folder id
* @param conflictResolution
* the conflict resolution
* @param messageDisposition
* the message disposition
* @param sendInvitationsOrCancellationsMode
* the send invitations or cancellations mode
* @param errorHandling
* the error handling
* @return A ServiceResponseCollection providing update results for each of
* the specified items.
* @throws Exception
* the exception
*/
private ServiceResponseCollection<UpdateItemResponse> internalUpdateItems(
Iterable<Item> items,
FolderId savedItemsDestinationFolderId,
ConflictResolutionMode conflictResolution,
MessageDisposition messageDisposition,
SendInvitationsOrCancellationsMode sendInvitationsOrCancellationsMode,
ServiceErrorHandling errorHandling) throws Exception {
UpdateItemRequest request = new UpdateItemRequest(this, errorHandling);
request.getItems().addAll((Collection<? extends Item>) items);
request.setSavedItemsDestinationFolder(savedItemsDestinationFolderId);
request.setMessageDisposition(messageDisposition);
request.setConflictResolutionMode(conflictResolution);
request
.setSendInvitationsOrCancellationsMode(sendInvitationsOrCancellationsMode);
return request.execute();
}
/**
* Updates multiple items in a single EWS call. UpdateItems does not
* support items that have unsaved attachments.
*
* @param items
* the items
* @param savedItemsDestinationFolderId
* the saved items destination folder id
* @param conflictResolution
* the conflict resolution
* @param messageDisposition
* the message disposition
* @param sendInvitationsOrCancellationsMode
* the send invitations or cancellations mode
* @return A ServiceResponseCollection providing update results for each of
* the specified items.
* @throws Exception
* the exception
*/
public ServiceResponseCollection<UpdateItemResponse> updateItems(
Iterable<Item> items,
FolderId savedItemsDestinationFolderId,
ConflictResolutionMode conflictResolution,
MessageDisposition messageDisposition,
SendInvitationsOrCancellationsMode sendInvitationsOrCancellationsMode)
throws Exception {
// All items have to exist on the server (!new) and modified (dirty)
if (!EwsUtilities.trueForAll(items, new IPredicate<Item>() {
@Override
public boolean predicate(Item obj) throws ServiceLocalException {
return (!obj.isNew() && obj.isDirty());
}
})) {
throw new ServiceValidationException(
Strings.UpdateItemsDoesNotSupportNewOrUnchangedItems);
}
// E14:298274 Make sure that all items do *not* have unprocessed
// attachments.
if (!EwsUtilities.trueForAll(items, new IPredicate<Item>() {
@Override
public boolean predicate(Item obj) throws ServiceLocalException {
return !obj.hasUnprocessedAttachmentChanges();
}
})) {
throw new ServiceValidationException(
Strings.UpdateItemsDoesNotAllowAttachments);
}
return this.internalUpdateItems(items, savedItemsDestinationFolderId,
conflictResolution, messageDisposition,
sendInvitationsOrCancellationsMode,
ServiceErrorHandling.ReturnErrors);
}
/**
* Updates an item.
*
* @param item
* the item
* @param savedItemsDestinationFolderId
* the saved items destination folder id
* @param conflictResolution
* the conflict resolution
* @param messageDisposition
* the message disposition
* @param sendInvitationsOrCancellationsMode
* the send invitations or cancellations mode
* @return A ServiceResponseCollection providing deletion results for each
* of the specified item Ids.
* @throws Exception
* the exception
*/
protected Item updateItem(
Item item,
FolderId savedItemsDestinationFolderId,
ConflictResolutionMode conflictResolution,
MessageDisposition messageDisposition,
SendInvitationsOrCancellationsMode sendInvitationsOrCancellationsMode)
throws Exception {
List<Item> itemIdArray = new ArrayList<Item>();
itemIdArray.add(item);
ServiceResponseCollection<UpdateItemResponse> responses = this
.internalUpdateItems(itemIdArray,
savedItemsDestinationFolderId, conflictResolution,
messageDisposition, sendInvitationsOrCancellationsMode,
ServiceErrorHandling.ThrowOnError);
return responses.getResponseAtIndex(0).getReturnedItem();
}
/**
* Send item.
*
* @param item
* the item
* @param savedCopyDestinationFolderId
* the saved copy destination folder id
* @throws Exception
* the exception
*/
protected void sendItem(Item item, FolderId savedCopyDestinationFolderId)
throws Exception {
SendItemRequest request = new SendItemRequest(this,
ServiceErrorHandling.ThrowOnError);
List<Item> itemIdArray = new ArrayList<Item>();
itemIdArray.add(item);
request.setItems(itemIdArray);
request.setSavedCopyDestinationFolderId(savedCopyDestinationFolderId);
request.execute();
}
/**
* Copies multiple items in a single call to EWS.
*
* @param itemIds
* the item ids
* @param destinationFolderId
* the destination folder id
* @param returnNewItemIds
* Flag indicating whether service should return new ItemIds or
* not.
* @param errorHandling
* the error handling
* @return A ServiceResponseCollection providing copy results for each of
* the specified item Ids.
* @throws Exception
* the exception
*/
private ServiceResponseCollection<MoveCopyItemResponse> internalCopyItems(
Iterable<ItemId> itemIds, FolderId destinationFolderId,
Boolean returnNewItemIds, ServiceErrorHandling errorHandling)
throws Exception {
CopyItemRequest request = new CopyItemRequest(this, errorHandling);
request.getItemIds().addRange(itemIds);
request.setDestinationFolderId(destinationFolderId);
request.setReturnNewItemIds(returnNewItemIds);
return request.execute();
}
/**
* Copies multiple items in a single call to EWS.
*
* @param itemIds
* the item ids
* @param destinationFolderId
* the destination folder id
* @return A ServiceResponseCollection providing copy results for each of
* the specified item Ids.
* @throws Exception
* the exception
*/
public ServiceResponseCollection<MoveCopyItemResponse> copyItems(
Iterable<ItemId> itemIds, FolderId destinationFolderId)
throws Exception {
return this.internalCopyItems(itemIds, destinationFolderId, null,
ServiceErrorHandling.ReturnErrors);
}
/**
* Copies multiple items in a single call to EWS.
*
* @param itemIds
* The Ids of the items to copy.
* @param destinationFolderId
* The Id of the folder to copy the items to.
* @param returnNewItemIds
* Flag indicating whether service should return new ItemIds or
* not.
* @return A ServiceResponseCollection providing copy results for each of
* the specified item Ids.
* @throws Exception
*/
public ServiceResponseCollection<MoveCopyItemResponse> copyItems(
Iterable<ItemId> itemIds, FolderId destinationFolderId,
boolean returnNewItemIds) throws Exception {
EwsUtilities.validateMethodVersion(this,
ExchangeVersion.Exchange2010_SP1, "CopyItems");
return this.internalCopyItems(itemIds, destinationFolderId,
returnNewItemIds, ServiceErrorHandling.ReturnErrors);
}
/**
* Copies an item. Calling this method results in a call to EWS.
*
* @param itemId
* The Id of the item to copy.
* @param destinationFolderId
* The folder in which to save sent messages, meeting invitations
* or cancellations. If null, the message, meeting invitation or
* cancellation is saved in the Sent Items folder
* @return The copy of the item.
* @throws Exception
* the exception
*/
protected Item copyItem(ItemId itemId, FolderId destinationFolderId)
throws Exception {
List<ItemId> itemIdArray = new ArrayList<ItemId>();
itemIdArray.add(itemId);
return this.internalCopyItems(itemIdArray, destinationFolderId, null,
ServiceErrorHandling.ThrowOnError).getResponseAtIndex(0)
.getItem();
}
/**
* Moves multiple items in a single call to EWS.
*
* @param itemIds
* the item ids
* @param destinationFolderId
* the destination folder id
* @param returnNewItemIds
* Flag indicating whether service should return new ItemIds or
* not.
* @param errorHandling
* the error handling
* @return A ServiceResponseCollection providing copy results for each of
* the specified item Ids.
* @throws Exception
* the exception
*/
private ServiceResponseCollection<MoveCopyItemResponse> internalMoveItems(
Iterable<ItemId> itemIds, FolderId destinationFolderId,
Boolean returnNewItemIds, ServiceErrorHandling errorHandling)
throws Exception {
MoveItemRequest request = new MoveItemRequest(this, errorHandling);
request.getItemIds().addRange(itemIds);
request.setDestinationFolderId(destinationFolderId);
request.setReturnNewItemIds(returnNewItemIds);
return request.execute();
}
/**
* Moves multiple items in a single call to EWS.
*
* @param itemIds
* the item ids
* @param destinationFolderId
* the destination folder id
* @return A ServiceResponseCollection providing copy results for each of
* the specified item Ids.
* @throws Exception
* the exception
*/
public ServiceResponseCollection<MoveCopyItemResponse> moveItems(
Iterable<ItemId> itemIds, FolderId destinationFolderId)
throws Exception {
return this.internalMoveItems(itemIds, destinationFolderId, null,
ServiceErrorHandling.ReturnErrors);
}
/**
* Moves multiple items in a single call to EWS.
*
* @param itemIds
* The Ids of the items to move.
* @param destinationFolderId
* The Id of the folder to move the items to.
* @param returnNewItemIds
* Flag indicating whether service should return new ItemIds or
* not.
* @return A ServiceResponseCollection providing copy results for each of
* the specified item Ids.
* @throws Exception
*/
public ServiceResponseCollection<MoveCopyItemResponse> moveItems(
Iterable<ItemId> itemIds, FolderId destinationFolderId,
boolean returnNewItemIds) throws Exception {
EwsUtilities.validateMethodVersion(this,
ExchangeVersion.Exchange2010_SP1, "MoveItems");
return this.internalMoveItems(itemIds, destinationFolderId,
returnNewItemIds, ServiceErrorHandling.ReturnErrors);
}
/**
* Copies multiple items in a single call to EWS.
*
* @param itemId
* the item id
* @param destinationFolderId
* the destination folder id
* @return A ServiceResponseCollection providing copy results for each of
* the specified item Ids.
* @throws Exception
* the exception
*/
protected Item moveItem(ItemId itemId, FolderId destinationFolderId)
throws Exception {
List<ItemId> itemIdArray = new ArrayList<ItemId>();
itemIdArray.add(itemId);
return this.internalMoveItems(itemIdArray, destinationFolderId, null,
ServiceErrorHandling.ThrowOnError).getResponseAtIndex(0)
.getItem();
}
/**
* Finds items.
*
* @param <TItem>
* The type of item
* @param parentFolderIds
* The parent folder ids.
* @param searchFilter
* The search filter. Available search filter classes include
* SearchFilter.IsEqualTo, SearchFilter.ContainsSubstring and
* SearchFilter.SearchFilterCollection
* @param queryString
* the query string
* @param view
* The view controlling the number of folders returned.
* @param groupBy
* The group by.
* @param errorHandlingMode
* Indicates the type of error handling should be done.
* @return Service response collection.
* @throws Exception
* the exception
*/
protected <TItem extends Item> ServiceResponseCollection<FindItemResponse<TItem>> findItems(
Iterable<FolderId> parentFolderIds, SearchFilter searchFilter,
String queryString, ViewBase view, Grouping groupBy,
ServiceErrorHandling errorHandlingMode) throws Exception {
EwsUtilities.validateParamCollection(parentFolderIds.iterator(),
"parentFolderIds");
EwsUtilities.validateParam(view, "view");
EwsUtilities.validateParamAllowNull(groupBy, "groupBy");
EwsUtilities.validateParamAllowNull(queryString, "queryString");
EwsUtilities.validateParamAllowNull(searchFilter, "searchFilter");
FindItemRequest<TItem> request = new FindItemRequest<TItem>(this,
errorHandlingMode);
request.getParentFolderIds().addRangeFolderId(parentFolderIds);
request.setSearchFilter(searchFilter);
request.setQueryString(queryString);
request.setView(view);
request.setGroupBy(groupBy);
return request.execute();
}
/**
* Obtains a list of items by searching the contents of a specific folder.
* Calling this method results in a call to EWS.
*
* @param parentFolderId
* the parent folder id
* @param queryString
* the query string
* @param view
* the view
* @return An object representing the results of the search operation.
* @throws Exception
* the exception
*/
@SuppressWarnings("unchecked")
public FindItemsResults<Item> findItems(FolderId parentFolderId,
String queryString, ItemView view) throws Exception {
EwsUtilities.validateParamAllowNull(queryString, "queryString");
List folderIdArray = new ArrayList();
folderIdArray.add(parentFolderId);
ServiceResponseCollection<FindItemResponse<Item>> responses = this
.findItems(folderIdArray, null, /* searchFilter */
queryString, view, null, /* groupBy */
ServiceErrorHandling.ThrowOnError);
return responses.getResponseAtIndex(0).getResults();
}
/**
* Obtains a list of items by searching the contents of a specific folder.
* Calling this method results in a call to EWS.
*
* @param parentFolderId
* the parent folder id
* @param searchFilter
* the search filter
* @param view
* the view
* @return An object representing the results of the search operation.
* @throws Exception
* the exception
*/
@SuppressWarnings("unchecked")
public FindItemsResults<Item> findItems(FolderId parentFolderId,
SearchFilter searchFilter, ItemView view) throws Exception {
EwsUtilities.validateParamAllowNull(searchFilter, "searchFilter");
List folderIdArray = new ArrayList();
folderIdArray.add(parentFolderId);
ServiceResponseCollection<FindItemResponse<Item>> responses = this
.findItems(folderIdArray, searchFilter, null, /* queryString */
view, null, /* groupBy */
ServiceErrorHandling.ThrowOnError);
return responses.getResponseAtIndex(0).getResults();
}
/**
* Obtains a list of items by searching the contents of a specific folder.
* Calling this method results in a call to EWS.
*
* @param parentFolderId
* the parent folder id
* @param view
* the view
* @return An object representing the results of the search operation.
* @throws Exception
* the exception
*/
@SuppressWarnings("unchecked")
public FindItemsResults<Item> findItems(FolderId parentFolderId,
ItemView view) throws Exception {
List folderIdArray = new ArrayList();
folderIdArray.add(parentFolderId);
ServiceResponseCollection<FindItemResponse<Item>> responses = this
.findItems(folderIdArray, null, /* searchFilter */
null, /* queryString */
view, null, /* groupBy */
ServiceErrorHandling.ThrowOnError);
return responses.getResponseAtIndex(0).getResults();
}
/**
* Obtains a list of items by searching the contents of a specific folder.
* Calling this method results in a call to EWS.
*
* @param parentFolderName
* the parent folder name
* @param queryString
* the query string
* @param view
* the view
* @return An object representing the results of the search operation.
* @throws Exception
* the exception
*/
public FindItemsResults<Item> findItems(
WellKnownFolderName parentFolderName, String queryString,
ItemView view) throws Exception {
return this
.findItems(new FolderId(parentFolderName), queryString, view);
}
/**
* Obtains a list of items by searching the contents of a specific folder.
* Calling this method results in a call to EWS.
*
* @param parentFolderName
* the parent folder name
* @param searchFilter
* the search filter
* @param view
* the view
* @return An object representing the results of the search operation.
* @throws Exception
* the exception
*/
public FindItemsResults<Item> findItems(
WellKnownFolderName parentFolderName, SearchFilter searchFilter,
ItemView view) throws Exception {
return this.findItems(new FolderId(parentFolderName), searchFilter,
view);
}
/**
* Obtains a list of items by searching the contents of a specific folder.
* Calling this method results in a call to EWS.
*
* @param parentFolderName
* the parent folder name
* @param view
* the view
* @return An object representing the results of the search operation.
* @throws Exception
* the exception
*/
public FindItemsResults<Item> findItems(
WellKnownFolderName parentFolderName, ItemView view)
throws Exception {
return this.findItems(new FolderId(parentFolderName),
(SearchFilter) null, view);
}
/**
* Obtains a grouped list of items by searching the contents of a specific
* folder. Calling this method results in a call to EWS.
*
* @param parentFolderId
* the parent folder id
* @param queryString
* the query string
* @param view
* the view
* @param groupBy
* the group by
* @return A list of items containing the contents of the specified folder.
* @throws Exception
* the exception
*/
public GroupedFindItemsResults<Item> findItems(FolderId parentFolderId,
String queryString, ItemView view, Grouping groupBy)
throws Exception {
EwsUtilities.validateParam(groupBy, "groupBy");
EwsUtilities.validateParamAllowNull(queryString, "queryString");
List<FolderId> folderIdArray = new ArrayList<FolderId>();
folderIdArray.add(parentFolderId);
ServiceResponseCollection<FindItemResponse<Item>> responses = this
.findItems(folderIdArray, null, /* searchFilter */
queryString, view, groupBy, ServiceErrorHandling.ThrowOnError);
return responses.getResponseAtIndex(0).getGroupedFindResults();
}
/**
* Obtains a grouped list of items by searching the contents of a specific
* folder. Calling this method results in a call to EWS.
*
* @param parentFolderId
* the parent folder id
* @param searchFilter
* the search filter
* @param view
* the view
* @param groupBy
* the group by
* @return A list of items containing the contents of the specified folder.
* @throws Exception
* the exception
*/
public GroupedFindItemsResults<Item> findItems(FolderId parentFolderId,
SearchFilter searchFilter, ItemView view, Grouping groupBy)
throws Exception {
EwsUtilities.validateParam(groupBy, "groupBy");
EwsUtilities.validateParamAllowNull(searchFilter, "searchFilter");
List<FolderId> folderIdArray = new ArrayList<FolderId>();
folderIdArray.add(parentFolderId);
ServiceResponseCollection<FindItemResponse<Item>> responses = this
.findItems(folderIdArray, searchFilter, null, /* queryString */
view, groupBy, ServiceErrorHandling.ThrowOnError);
return responses.getResponseAtIndex(0).getGroupedFindResults();
}
/**
* Obtains a grouped list of items by searching the contents of a specific
* folder. Calling this method results in a call to EWS.
*
* @param parentFolderId
* the parent folder id
* @param view
* the view
* @param groupBy
* the group by
* @return A list of items containing the contents of the specified folder.
* @throws Exception
* the exception
*/
public GroupedFindItemsResults<Item> findItems(FolderId parentFolderId,
ItemView view, Grouping groupBy) throws Exception {
EwsUtilities.validateParam(groupBy, "groupBy");
List<FolderId> folderIdArray = new ArrayList<FolderId>();
folderIdArray.add(parentFolderId);
ServiceResponseCollection<FindItemResponse<Item>> responses = this
.findItems(folderIdArray, null, /* searchFilter */
null, /* queryString */
view, groupBy, ServiceErrorHandling.ThrowOnError);
return responses.getResponseAtIndex(0).getGroupedFindResults();
}
/**
* Obtains a grouped list of items by searching the contents of a specific
* folder. Calling this method results in a call to EWS.
*
* @param <TItem>
* the generic type
* @param cls
* the cls
* @param parentFolderId
* the parent folder id
* @param searchFilter
* the search filter
* @param view
* the view
* @param groupBy
* the group by
* @return A list of items containing the contents of the specified folder.
* @throws Exception
* the exception
*/
protected <TItem extends Item> ServiceResponseCollection<FindItemResponse<TItem>> findItems(
Class<TItem> cls, FolderId parentFolderId,
SearchFilter searchFilter, ViewBase view, Grouping groupBy)
throws Exception {
List<FolderId> folderIdArray = new ArrayList<FolderId>();
folderIdArray.add(parentFolderId);
return this.findItems(folderIdArray, searchFilter, null, /* queryString */
view, groupBy, ServiceErrorHandling.ThrowOnError);
}
/**
* Obtains a grouped list of items by searching the contents of a specific
* folder. Calling this method results in a call to EWS.
*
* @param parentFolderName
* the parent folder name
* @param queryString
* the query string
* @param view
* the view
* @param groupBy
* the group by
* @return A collection of grouped items containing the contents of the
* specified.
* @throws Exception
* the exception
*/
public GroupedFindItemsResults<Item> findItems(
WellKnownFolderName parentFolderName, String queryString,
ItemView view, Grouping groupBy) throws Exception {
EwsUtilities.validateParam(groupBy, "groupBy");
return this.findItems(new FolderId(parentFolderName), queryString,
view, groupBy);
}
/**
* Obtains a grouped list of items by searching the contents of a specific
* folder. Calling this method results in a call to EWS.
*
* @param parentFolderName
* the parent folder name
* @param searchFilter
* the search filter
* @param view
* the view
* @param groupBy
* the group by
* @return A collection of grouped items containing the contents of the
* specified.
* @throws Exception
* the exception
*/
public GroupedFindItemsResults<Item> findItems(
WellKnownFolderName parentFolderName, SearchFilter searchFilter,
ItemView view, Grouping groupBy) throws Exception {
return this.findItems(new FolderId(parentFolderName), searchFilter,
view, groupBy);
}
/**
* Obtains a list of appointments by searching the contents of a specific
* folder. Calling this method results in a call to EWS.
*
* @param parentFolderId
* the parent folder id
* @param calendarView
* the calendar view
* @return A collection of appointments representing the contents of the
* specified folder.
* @throws Exception
* the exception
*/
public FindItemsResults<Appointment> findAppointments(
FolderId parentFolderId, CalendarView calendarView)
throws Exception {
List<FolderId> folderIdArray = new ArrayList<FolderId>();
folderIdArray.add(parentFolderId);
ServiceResponseCollection<FindItemResponse<Appointment>> response = this
.findItems(folderIdArray, null, /* searchFilter */
null /* queryString */, calendarView, null, /* groupBy */
ServiceErrorHandling.ThrowOnError);
return response.getResponseAtIndex(0).getResults();
}
/**
* Obtains a list of appointments by searching the contents of a specific
* folder. Calling this method results in a call to EWS.
*
* @param parentFolderName
* the parent folder name
* @param calendarView
* the calendar view
* @return A collection of appointments representing the contents of the
* specified folder.
* @throws Exception
* the exception
*/
public FindItemsResults<Appointment> findAppointments(
WellKnownFolderName parentFolderName, CalendarView calendarView)
throws Exception {
return this.findAppointments(new FolderId(parentFolderName),
calendarView);
}
/**
* Loads the properties of multiple items in a single call to EWS.
*
* @param items
* the items
* @param propertySet
* the property set
* @return A ServiceResponseCollection providing results for each of the
* specified items.
* @throws Exception
* the exception
*/
public ServiceResponseCollection<ServiceResponse> loadPropertiesForItems(
Iterable<Item> items, PropertySet propertySet) throws Exception {
EwsUtilities.validateParamCollection(items.iterator(), "items");
EwsUtilities.validateParam(propertySet, "propertySet");
return this.internalLoadPropertiesForItems(items, propertySet,
ServiceErrorHandling.ReturnErrors);
}
/**
* Loads the properties of multiple items in a single call to EWS.
*
* @param items
* the items
* @param propertySet
* the property set
* @param errorHandling
* the error handling
* @return A ServiceResponseCollection providing results for each of the
* specified items.
* @throws Exception
* the exception
*/
ServiceResponseCollection<ServiceResponse> internalLoadPropertiesForItems(
Iterable<Item> items, PropertySet propertySet,
ServiceErrorHandling errorHandling) throws Exception {
GetItemRequestForLoad request = new GetItemRequestForLoad(this,
errorHandling);
// return null;
request.getItemIds().addRangeItem(items);
request.setPropertySet(propertySet);
return request.execute();
}
/**
* Binds to multiple items in a single call to EWS.
*
* @param itemIds
* the item ids
* @param propertySet
* the property set
* @param errorHandling
* the error handling
* @return A ServiceResponseCollection providing results for each of the
* specified item Ids.
* @throws Exception
* the exception
*/
private ServiceResponseCollection<GetItemResponse> internalBindToItems(
Iterable<ItemId> itemIds, PropertySet propertySet,
ServiceErrorHandling errorHandling) throws Exception {
GetItemRequest request = new GetItemRequest(this, errorHandling);
request.getItemIds().addRange(itemIds);
request.setPropertySet(propertySet);
return request.execute();
}
/**
* Binds to multiple items in a single call to EWS.
*
* @param itemIds
* the item ids
* @param propertySet
* the property set
* @return A ServiceResponseCollection providing results for each of the
* specified item Ids.
* @throws Exception
* the exception
*/
public ServiceResponseCollection<GetItemResponse> bindToItems(
Iterable<ItemId> itemIds, PropertySet propertySet) throws Exception {
EwsUtilities.validateParamCollection(itemIds.iterator(), "itemIds");
EwsUtilities.validateParam(propertySet, "propertySet");
return this.internalBindToItems(itemIds, propertySet,
ServiceErrorHandling.ReturnErrors);
}
/**
* Binds to multiple items in a single call to EWS.
*
* @param itemId
* the item id
* @param propertySet
* the property set
* @return A ServiceResponseCollection providing results for each of the
* specified item Ids.
* @throws Exception
* the exception
*/
protected Item bindToItem(ItemId itemId, PropertySet propertySet)
throws Exception {
EwsUtilities.validateParam(itemId, "itemId");
EwsUtilities.validateParam(propertySet, "propertySet");
List<ItemId> itmLst = new ArrayList<ItemId>();
itmLst.add(itemId);
ServiceResponseCollection<GetItemResponse> responses = this
.internalBindToItems(itmLst, propertySet,
ServiceErrorHandling.ThrowOnError);
return responses.getResponseAtIndex(0).getItem();
}
/**
* Bind to item.
*
* @param <TItem>
* The type of the item.
* @param c
* the c
* @param itemId
* the item id
* @param propertySet
* the property set
* @return the t item
* @throws Exception
* the exception
*/
protected <TItem extends Item> TItem bindToItem(Class<TItem> c,
ItemId itemId, PropertySet propertySet) throws Exception {
Item result = this.bindToItem(itemId, propertySet);
if (c.isAssignableFrom(result.getClass())) {
return (TItem) result;
} else {
throw new ServiceLocalException(String.format(
Strings.ItemTypeNotCompatible, result.getClass().getName(),
c.getName()));
}
}
/**
* Deletes multiple items in a single call to EWS.
*
* @param itemIds
* the item ids
* @param deleteMode
* the delete mode
* @param sendCancellationsMode
* the send cancellations mode
* @param affectedTaskOccurrences
* the affected task occurrences
* @param errorHandling
* the error handling
* @return A ServiceResponseCollection providing deletion results for each
* of the specified item Ids.
* @throws Exception
* the exception
*/
private ServiceResponseCollection<ServiceResponse> internalDeleteItems(
Iterable<ItemId> itemIds, DeleteMode deleteMode,
SendCancellationsMode sendCancellationsMode,
AffectedTaskOccurrence affectedTaskOccurrences,
ServiceErrorHandling errorHandling) throws Exception {
DeleteItemRequest request = new DeleteItemRequest(this, errorHandling);
request.getItemIds().addRange(itemIds);
request.setDeleteMode(deleteMode);
request.setSendCancellationsMode(sendCancellationsMode);
request.setAffectedTaskOccurrences(affectedTaskOccurrences);
return request.execute();
}
/**
* Deletes multiple items in a single call to EWS.
*
* @param itemIds
* the item ids
* @param deleteMode
* the delete mode
* @param sendCancellationsMode
* the send cancellations mode
* @param affectedTaskOccurrences
* the affected task occurrences
* @return A ServiceResponseCollection providing deletion results for each
* of the specified item Ids.
* @throws Exception
* the exception
*/
public ServiceResponseCollection<ServiceResponse> deleteItems(
Iterable<ItemId> itemIds, DeleteMode deleteMode,
SendCancellationsMode sendCancellationsMode,
AffectedTaskOccurrence affectedTaskOccurrences) throws Exception {
EwsUtilities.validateParamCollection(itemIds.iterator(), "itemIds");
return this.internalDeleteItems(itemIds, deleteMode,
sendCancellationsMode, affectedTaskOccurrences,
ServiceErrorHandling.ReturnErrors);
}
/**
* Deletes an item. Calling this method results in a call to EWS.
*
* @param itemId
* the item id
* @param deleteMode
* the delete mode
* @param sendCancellationsMode
* the send cancellations mode
* @param affectedTaskOccurrences
* the affected task occurrences
* @throws Exception
* the exception
*/
protected void deleteItem(ItemId itemId, DeleteMode deleteMode,
SendCancellationsMode sendCancellationsMode,
AffectedTaskOccurrence affectedTaskOccurrences) throws Exception {
List<ItemId> itemIdArray = new ArrayList<ItemId>();
itemIdArray.add(itemId);
EwsUtilities.validateParam(itemId, "itemId");
this.internalDeleteItems(itemIdArray, deleteMode,
sendCancellationsMode, affectedTaskOccurrences,
ServiceErrorHandling.ThrowOnError);
}
/**
* Gets an attachment.
*
* @param attachments
* the attachments
* @param bodyType
* the body type
* @param additionalProperties
* the additional properties
* @param errorHandling
* the error handling
* @throws Exception
* the exception
*/
private ServiceResponseCollection<GetAttachmentResponse> internalGetAttachments(
Iterable<Attachment> attachments, BodyType bodyType,
Iterable<PropertyDefinitionBase> additionalProperties,
ServiceErrorHandling errorHandling) throws Exception {
GetAttachmentRequest request = new GetAttachmentRequest(this,
errorHandling);
Iterator it = attachments.iterator();
while (it.hasNext()) {
((ArrayList) request.getAttachments()).add(it.next());
}
request.setBodyType(bodyType);
List propsArray = new ArrayList();
propsArray.add(additionalProperties);
if (additionalProperties != null) {
request.getAdditionalProperties().addAll(propsArray);
}
return request.execute();
}
/**
* Gets attachments.
*
* @param attachments
* the attachments
* @param bodyType
* the body type
* @param additionalProperties
* the additional properties
* @return Service response collection.
* @throws Exception
*/
protected ServiceResponseCollection<GetAttachmentResponse> getAttachments(
Attachment[] attachments, BodyType bodyType,
Iterable<PropertyDefinitionBase> additionalProperties)
throws Exception {
List<Attachment> attList = new ArrayList<Attachment>();
for (Attachment attachment : attachments) {
attList.add(attachment);
}
return this.internalGetAttachments(attList, bodyType,
additionalProperties, ServiceErrorHandling.ReturnErrors);
}
/**
* Gets the attachment.
*
* @param attachment
* the attachment
* @param bodyType
* the body type
* @param additionalProperties
* the additional properties
* @throws Exception
* the exception
*/
protected void getAttachment(Attachment attachment, BodyType bodyType,
Iterable<PropertyDefinitionBase> additionalProperties)
throws Exception {
List<Attachment> attachmentArray = new ArrayList<Attachment>();
attachmentArray.add(attachment);
this.internalGetAttachments(attachmentArray, bodyType,
additionalProperties, ServiceErrorHandling.ThrowOnError);
}
/**
* Creates attachments.
*
* @param parentItemId
* the parent item id
* @param attachments
* the attachments
* @return Service response collection.
* @throws ServiceResponseException
* the service response exception
* @throws Exception
* the exception
*/
protected ServiceResponseCollection<CreateAttachmentResponse> createAttachments(
String parentItemId, Iterable<Attachment> attachments)
throws ServiceResponseException, Exception {
CreateAttachmentRequest request = new CreateAttachmentRequest(this,
ServiceErrorHandling.ReturnErrors);
request.setParentItemId(parentItemId);
/*
* if (null != attachments) { while (attachments.hasNext()) {
* request.getAttachments().add(attachments.next()); } }
*/
request.getAttachments().addAll(
(Collection<? extends Attachment>) attachments);
return request.execute();
}
/**
* Deletes attachments.
*
* @param attachments
* the attachments
* @return the service response collection
* @throws ServiceResponseException
* the service response exception
* @throws Exception
* the exception
*/
protected ServiceResponseCollection<DeleteAttachmentResponse> deleteAttachments(
Iterable<Attachment> attachments) throws ServiceResponseException,
Exception {
DeleteAttachmentRequest request = new DeleteAttachmentRequest(this,
ServiceErrorHandling.ReturnErrors);
request.getAttachments().addAll(
(Collection<? extends Attachment>) attachments);
return request.execute();
}
/**
* Finds contacts in the user's Contacts folder and the Global Address
* List (in that order) that have names that match the one passed as a
* parameter. Calling this method results in a call to EWS.
*
* @param nameToResolve
* the name to resolve
* @return A collection of name resolutions whose names match the one passed
* as a parameter.
* @throws Exception
* the exception
*/
public NameResolutionCollection resolveName(String nameToResolve)
throws Exception {
return this.resolveName(nameToResolve,
ResolveNameSearchLocation.ContactsThenDirectory, false);
}
/**
* Finds contacts in the user's Contacts folder and the Global Address
* List (in that order) that have names that match the one passed as a
* parameter. Calling this method results in a call to EWS.
*
* @param nameToResolve
* the name to resolve
* @param parentFolderIds
* the parent folder ids
* @param searchScope
* the search scope
* @param returnContactDetails
* the return contact details
* @return A collection of name resolutions whose names match the one passed
* as a parameter.
* @throws Exception
* the exception
*/
public NameResolutionCollection resolveName(String nameToResolve,
Iterable<FolderId> parentFolderIds,
ResolveNameSearchLocation searchScope, boolean returnContactDetails)
throws Exception {
return resolveName(nameToResolve, parentFolderIds, searchScope,
returnContactDetails, null);
}
/**
* Finds contacts in the Global Address List and/or in specific contact
* folders that have names that match the one passed as a parameter. Calling
* this method results in a call to EWS.
*
* @param nameToResolve
* The name to resolve.
*@param parentFolderIds
* The Ids of the contact folders in which to look for matching
* contacts.
*@param searchScope
* The scope of the search.
*@param returnContactDetails
* Indicates whether full contact information should be returned
* for each of the found contacts.
*@param contactDataPropertySet
* The property set for the contact details
* @throws Exception
* @return A collection of name resolutions whose names match the one
* passed as a parameter.
*/
public NameResolutionCollection resolveName(String nameToResolve,
Iterable<FolderId> parentFolderIds,
ResolveNameSearchLocation searchScope,
boolean returnContactDetails, PropertySet contactDataPropertySet)
throws Exception {
if (contactDataPropertySet != null) {
EwsUtilities.validateMethodVersion(this,
ExchangeVersion.Exchange2010_SP1, "ResolveName");
}
EwsUtilities.validateParam(nameToResolve, "nameToResolve");
if (parentFolderIds != null) {
EwsUtilities.validateParamCollection(parentFolderIds.iterator(),
"parentFolderIds");
}
ResolveNamesRequest request = new ResolveNamesRequest(this);
request.setNameToResolve(nameToResolve);
request.setReturnFullContactData(returnContactDetails);
request.getParentFolderIds().addRangeFolderId(parentFolderIds);
request.setSearchLocation(searchScope);
request.setContactDataPropertySet(contactDataPropertySet);
return request.execute().getResponseAtIndex(0).getResolutions();
}
/**
* Finds contacts in the Global Address List that have names that match the
* one passed as a parameter. Calling this method results in a call to EWS.
*
* @param nameToResolve
* The name to resolve.
*@param searchScope
* The scope of the search.
*@param returnContactDetails
* Indicates whether full contact information should be returned
* for each of the found contacts.
*@param contactDataPropertySet
* The property set for the contact details
* @throws Exception
* @return A collection of name resolutions whose names match the one
* passed as a parameter.
*/
public NameResolutionCollection resolveName(String nameToResolve,
ResolveNameSearchLocation searchScope,
boolean returnContactDetails, PropertySet contactDataPropertySet)
throws Exception {
return this.resolveName(nameToResolve, null, searchScope,
returnContactDetails, contactDataPropertySet);
}
/**
* Finds contacts in the user's Contacts folder and the Global Address
* List (in that order) that have names that match the one passed as a
* parameter. Calling this method results in a call to EWS.
*
* @param nameToResolve
* the name to resolve
* @param searchScope
* the search scope
* @param returnContactDetails
* the return contact details
* @return A collection of name resolutions whose names match the one passed
* as a parameter.
* @throws Exception
* the exception
*/
public NameResolutionCollection resolveName(String nameToResolve,
ResolveNameSearchLocation searchScope, boolean returnContactDetails)
throws Exception {
return this.resolveName(nameToResolve, null, searchScope,
returnContactDetails);
}
/**
* Expands a group by retrieving a list of its members. Calling this
* method results in a call to EWS.
*
* @param emailAddress
* the email address
* @return URL of the Exchange Web Services.
* @throws Exception
* the exception
*/
public ExpandGroupResults expandGroup(EmailAddress emailAddress)
throws Exception {
EwsUtilities.validateParam(emailAddress, "emailAddress");
ExpandGroupRequest request = new ExpandGroupRequest(this);
request.setEmailAddress(emailAddress);
return request.execute().getResponseAtIndex(0).getMembers();
}
/**
* Expands a group by retrieving a list of its members. Calling this
* method results in a call to EWS.
*
* @param groupId
* the group id
* @return An ExpandGroupResults containing the members of the group.
* @throws Exception
* the exception
*/
public ExpandGroupResults expandGroup(ItemId groupId) throws Exception {
EwsUtilities.validateParam(groupId, "groupId");
EmailAddress emailAddress = new EmailAddress();
emailAddress.setId(groupId);
return this.expandGroup(emailAddress);
}
/**
* Expands a group by retrieving a list of its members. Calling this
* method results in a call to EWS.
*
* @param smtpAddress
* the smtp address
* @return An ExpandGroupResults containing the members of the group.
* @throws Exception
* the exception
*/
public ExpandGroupResults expandGroup(String smtpAddress) throws Exception {
EwsUtilities.validateParam(smtpAddress, "smtpAddress");
return this.expandGroup(new EmailAddress(smtpAddress));
}
/**
* Expands a group by retrieving a list of its members. Calling this
* method results in a call to EWS.
*
* @param address
* the address
* @param routingType
* the routing type
* @return An ExpandGroupResults containing the members of the group.
* @throws Exception
* the exception
*/
public ExpandGroupResults expandGroup(String address, String routingType)
throws Exception {
EwsUtilities.validateParam(address, "address");
EwsUtilities.validateParam(routingType, "routingType");
EmailAddress emailAddress = new EmailAddress(address);
emailAddress.setRoutingType(routingType);
return this.expandGroup(emailAddress);
}
/**
* Get the password expiration date
*
* @param mailboxSmtpAddress
* The e-mail address of the user.
* @throws Exception
* @return The password expiration date
*/
public Date getPasswordExpirationDate(String mailboxSmtpAddress)
throws Exception {
GetPasswordExpirationDateRequest request = new GetPasswordExpirationDateRequest(
this);
request.setMailboxSmtpAddress(mailboxSmtpAddress);
return request.execute().getPasswordExpirationDate();
}
/**
* Subscribes to pull notifications. Calling this method results in a call
* to EWS.
*
* @param folderIds
* The Ids of the folder to subscribe to
* @param timeout
* The timeout, in minutes, after which the subscription expires.
* Timeout must be between 1 and 1440.
* @param watermark
* An optional watermark representing a previously opened
* subscription.
* @param eventTypes
* The event types to subscribe to.
* @return A PullSubscription representing the new subscription.
* @throws Exception
*/
public PullSubscription subscribeToPullNotifications(
Iterable<FolderId> folderIds, int timeout, String watermark,
EventType... eventTypes) throws Exception {
EwsUtilities.validateParamCollection(folderIds.iterator(), "folderIds");
return this.buildSubscribeToPullNotificationsRequest(folderIds,
timeout, watermark, eventTypes).execute().getResponseAtIndex(0)
.getSubscription();
}
/**
* Begins an asynchronous request to subscribes to pull notifications.
* Calling this method results in a call to EWS.
*
* @param callback
* The AsyncCallback delegate.
* @param state
* An object that contains state information for this request.
* @param folderIds
* The Ids of the folder to subscribe to.
* @param timeout
* The timeout, in minutes, after which the subscription expires.
* Timeout must be between 1 and 1440.
* @param watermark
* An optional watermark representing a previously opened
* subscription.
* @param eventTypes
* The event types to subscribe to.
* @throws Exception
* @return An IAsyncResult that references the asynchronous request.
*/
public AsyncRequestResult beginSubscribeToPullNotifications(
AsyncCallback callback, Object state, Iterable<FolderId> folderIds,
int timeout, String watermark, EventType... eventTypes)
throws Exception {
EwsUtilities.validateParamCollection(folderIds.iterator(), "folderIds");
return this.buildSubscribeToPullNotificationsRequest(folderIds,
timeout, watermark, eventTypes).beginExecute(callback, null);
}
/**
* Subscribes to pull notifications on all folders in the authenticated
* user's mailbox. Calling this method results in a call to EWS.
*
* @param timeout
* the timeout
* @param watermark
* the watermark
* @param eventTypes
* the event types
* @return A PullSubscription representing the new subscription.
* @throws Exception
* the exception
*/
public PullSubscription subscribeToPullNotificationsOnAllFolders(
int timeout, String watermark, EventType... eventTypes)
throws Exception {
EwsUtilities.validateMethodVersion(this, ExchangeVersion.Exchange2010,
"SubscribeToPullNotificationsOnAllFolders");
return this.buildSubscribeToPullNotificationsRequest(null, timeout,
watermark, eventTypes).execute().getResponseAtIndex(0)
.getSubscription();
}
/**
* Begins an asynchronous request to subscribe to pull notifications on all
* folders in the authenticated user's mailbox. Calling this method results
* in a call to EWS.
*
* @param callback
* The AsyncCallback delegate.
* @param state
* An object that contains state information for this request.
* @param timeout
* The timeout, in minutes, after which the subscription expires.
* Timeout must be between 1 and 1440.
* @param watermark
* An optional watermark representing a previously opened
* subscription.
* @param eventTypes
* The event types to subscribe to.
* @throws Exception
* @return An IAsyncResult that references the asynchronous request.
*/
public IAsyncResult beginSubscribeToPullNotificationsOnAllFolders(AsyncCallback callback,Object state,
int timeout,
String watermark, EventType... eventTypes) throws Exception {
EwsUtilities.validateMethodVersion(this, ExchangeVersion.Exchange2010,
"BeginSubscribeToPullNotificationsOnAllFolders");
return this.buildSubscribeToPullNotificationsRequest(null, timeout,
watermark, eventTypes).beginExecute(null,null);
}
/**
* Ends an asynchronous request to subscribe to pull notifications in the
* authenticated user's mailbox.
*
* @param asyncResult
* An IAsyncResult that references the asynchronous request.
* @throws Exception
* @return A PullSubscription representing the new subscription.
*/
public PullSubscription endSubscribeToPullNotifications(
IAsyncResult asyncResult) throws Exception {
SubscribeToPullNotificationsRequest request = AsyncRequestResult
.extractServiceRequest(this, asyncResult);
return request.endExecute(asyncResult).getResponseAtIndex(0)
.getSubscription();
}
/**
* Builds a request to subscribe to pull notifications in the
* authenticated user's mailbox.
*
* @param folderIds
* The Ids of the folder to subscribe to.
* @param timeout
* The timeout, in minutes, after which the subscription expires.
* Timeout must be between 1 and 1440
* @param watermark
* An optional watermark representing a previously opened
* subscription
* @param eventTypes
* The event types to subscribe to
* @return A request to subscribe to pull notifications in the authenticated
* user's mailbox
* @throws Exception
* the exception
*/
private SubscribeToPullNotificationsRequest buildSubscribeToPullNotificationsRequest(
Iterable<FolderId> folderIds, int timeout, String watermark,
EventType... eventTypes) throws Exception {
if (timeout < 1 || timeout > 1440) {
throw new IllegalArgumentException("timeout", new Throwable(
Strings.TimeoutMustBeBetween1And1440));
}
EwsUtilities.validateParamCollection(eventTypes, "eventTypes");
SubscribeToPullNotificationsRequest request = new SubscribeToPullNotificationsRequest(
this);
if (folderIds != null) {
request.getFolderIds().addRangeFolderId(folderIds);
}
request.setTimeOut(timeout);
for (EventType event : eventTypes) {
request.getEventTypes().add(event);
}
request.setWatermark(watermark);
return request;
}
/**
* Unsubscribes from a pull subscription. Calling this method results in a
* call to EWS.
*
* @param subscriptionId
* the subscription id
* @throws Exception
* the exception
*/
protected void unsubscribe(String subscriptionId) throws Exception {
this.buildUnsubscribeRequest(subscriptionId).execute();
}
/**
* Begins an asynchronous request to unsubscribe from a subscription.
* Calling this method results in a call to EWS.
*
* @param callback
* The AsyncCallback delegate.
* @param state
* An object that contains state information for this request.
* @param subscriptionId
* The Id of the pull subscription to unsubscribe from.
* @throws Exception
* @return An IAsyncResult that references the asynchronous request.
**/
protected IAsyncResult beginUnsubscribe(AsyncCallback callback,Object state,String subscriptionId) throws Exception {
return this.buildUnsubscribeRequest(subscriptionId).beginExecute(
callback,null);
}
/**
* Ends an asynchronous request to unsubscribe from a subscription.
*
*@param asyncResult
* An IAsyncResult that references the asynchronous request.
* @throws Exception
**/
protected void endUnsubscribe(IAsyncResult asyncResult) throws Exception
{
UnsubscribeRequest request = AsyncRequestResult.extractServiceRequest(this, asyncResult);
request.endExecute(asyncResult);
}
/**
* Buids a request to unsubscribe from a subscription.
*
* @param subscriptionId
* The id of the subscription for which to get the events
* @return A request to unsubscripbe from a subscription
* @throws Exception
*/
private UnsubscribeRequest buildUnsubscribeRequest(String subscriptionId)
throws Exception {
EwsUtilities.validateParam(subscriptionId, "subscriptionId");
UnsubscribeRequest request = new UnsubscribeRequest(this);
request.setSubscriptionId(subscriptionId);
return request;
}
/**
* Retrieves the latests events associated with a pull subscription.
* Calling this method results in a call to EWS.
*
* @param subscriptionId
* the subscription id
* @param waterMark
* the water mark
* @return A GetEventsResults containing a list of events associated with
* the subscription.
* @throws Exception
* the exception
*/
protected GetEventsResults getEvents(String subscriptionId, String waterMark)
throws Exception {
return this.buildGetEventsRequest(subscriptionId, waterMark).execute()
.getResponseAtIndex(0).getResults();
}
/**
* Begins an asynchronous request to retrieve the latest events associated
* with a pull subscription. Calling this method results in a call to EWS.
*
*@param callback
* The AsyncCallback delegate.
*@param state
* An object that contains state information for this request.
* @param subscriptionId
* The id of the pull subscription for which to get the events
* @param watermark
* The watermark representing the point in time where to start
* receiving events
* @return An IAsynResult that references the asynchronous request
* @throws Exception
*/
protected IAsyncResult beginGetEvents(AsyncCallback callback, Object state,
String subscriptionId, String watermark) throws Exception {
return this.buildGetEventsRequest(subscriptionId, watermark)
.beginExecute(callback, null);
}
/**
* Ends an asynchronous request to retrieve the latest events associated
* with a pull subscription.
*
* @param asyncResult
* An IAsyncResult that references the asynchronous request.
* @throws Exception
* @return A GetEventsResults containing a list of events associated with
* the subscription.
*/
protected GetEventsResults endGetEvents(IAsyncResult asyncResult) throws Exception
{
GetEventsRequest request = AsyncRequestResult.extractServiceRequest(this,asyncResult);
return request.endExecute(asyncResult).getResponseAtIndex(0).getResults();
}
/**
* Builds a request to retrieve the letest events associated with a pull
* subscription
*
* @param subscriptionId
* The Id of the pull subscription for which to get the events
* @param watermark
* The watermark representing the point in time where to start
* receiving events
* @return An request to retrieve the latest events associated with a pull
* subscription
* @throws Exception
*/
private GetEventsRequest buildGetEventsRequest(String subscriptionId,
String watermark) throws Exception {
EwsUtilities.validateParam(subscriptionId, "subscriptionId");
EwsUtilities.validateParam(watermark, "watermark");
GetEventsRequest request = new GetEventsRequest(this);
request.setSubscriptionId(subscriptionId);
request.setWatermark(watermark);
return request;
}
/**
* Subscribes to push notifications. Calling this method results in a call
* to EWS.
*
* @param folderIds
* the folder ids
* @param url
* the url
* @param frequency
* the frequency
* @param watermark
* the watermark
* @param eventTypes
* the event types
* @return A PushSubscription representing the new subscription.
* @throws Exception
* the exception
*/
public PushSubscription subscribeToPushNotifications(
Iterable<FolderId> folderIds, URI url, int frequency,
String watermark, EventType... eventTypes) throws Exception {
EwsUtilities.validateParamCollection(folderIds.iterator(), "folderIds");
return this.buildSubscribeToPushNotificationsRequest(folderIds, url,
frequency, watermark, eventTypes).execute().getResponseAtIndex(
0).getSubscription();
}
/**
* Begins an asynchronous request to subscribe to push notifications.
* Calling this method results in a call to EWS.
*
* @param callback
* The asynccallback delegate
* @param state
* An object that contains state information for this request
* @param folderIds
* The ids of the folder to subscribe
* @param url
* the url of web service endpoint the exchange server should
* @param frequency
* the frequency,in minutes at which the exchange server should
* contact the web Service endpoint. Frequency must be between 1
* and 1440.
* @param watermark
* An optional watermark representing a previously opened
* subscription
* @param eventTypes
* The event types to subscribe to.
* @return An IAsyncResult that references the asynchronous request.
* @throws Exception
*/
public IAsyncResult beginSubscribeToPushNotifications(
AsyncCallback callback, Object state, Iterable<FolderId> folderIds,
URI url, int frequency, String watermark, EventType... eventTypes)
throws Exception {
EwsUtilities.validateParamCollection(folderIds.iterator(), "folderIds");
return this.buildSubscribeToPushNotificationsRequest(folderIds, url,
frequency, watermark, eventTypes).beginExecute(callback, null);
}
/**
* Subscribes to push notifications on all folders in the authenticated
* user's mailbox. Calling this method results in a call to EWS.
*
* @param url
* the url
* @param frequency
* the frequency
* @param watermark
* the watermark
* @param eventTypes
* the event types
* @return A PushSubscription representing the new subscription.
* @throws Exception
* the exception
*/
public PushSubscription subscribeToPushNotificationsOnAllFolders(URI url,
int frequency, String watermark, EventType... eventTypes)
throws Exception {
EwsUtilities.validateMethodVersion(this, ExchangeVersion.Exchange2010,
"SubscribeToPushNotificationsOnAllFolders");
return this.buildSubscribeToPushNotificationsRequest(null, url,
frequency, watermark, eventTypes).execute().getResponseAtIndex(
0).getSubscription();
}
/**
* Begins an asynchronous request to subscribe to push notifications on all
* folders in the authenticated user's mailbox. Calling this method results
* in a call to EWS.
*
* @param callback
* The asynccallback delegate
* @param state
* An object that contains state inforamtion for this request
* @param url
* the url
* @param frequency
* the frequency,in minutes at which the exchange server should
* contact the web Service endpoint. Frequency must be between 1
* and 1440.
* @param watermark
* An optional watermark representing a previously opened
* subscription
* @param eventTypes
* The event types to subscribe to.
* @return An IAsyncResult that references the asynchronous request.
* @throws Exception
*/
public IAsyncResult beginSubscribeToPushNotificationsOnAllFolders(
AsyncCallback callback, Object state, URI url, int frequency,
String watermark, EventType... eventTypes) throws Exception {
EwsUtilities.validateMethodVersion(this, ExchangeVersion.Exchange2010,
"BeginSubscribeToPushNotificationsOnAllFolders");
return this.buildSubscribeToPushNotificationsRequest(null, url,
frequency, watermark, eventTypes).beginExecute(callback, null);
}
/**
* Ends an asynchronous request to subscribe to push notifications in the
* authenticated user's mailbox.
*
* @param asyncResult
* An IAsyncResult that references the asynchronous request.
* @return A PushSubscription representing the new subscription
* @throws Exception
*/
public PushSubscription endSubscribeToPushNotifications(
IAsyncResult asyncResult) throws Exception {
SubscribeToPushNotificationsRequest request = AsyncRequestResult
.extractServiceRequest(this, asyncResult);
return request.endExecute(asyncResult).getResponseAtIndex(0)
.getSubscription();
}
/**
* Builds an request to request to subscribe to push notifications in the
* authenticated user's mailbox.
*
* @param folderIds
* the folder ids
* @param url
* the url
* @param frequency
* the frequency
* @param watermark
* the watermark
* @param eventTypes
* the event types
* @return A request to request to subscribe to push notifications in the
* authenticated user's mailbox.
* @throws Exception
* the exception
*/
private SubscribeToPushNotificationsRequest buildSubscribeToPushNotificationsRequest(
Iterable<FolderId> folderIds, URI url, int frequency,
String watermark, EventType[] eventTypes) throws Exception {
EwsUtilities.validateParam(url, "url");
if (frequency < 1 || frequency > 1440) {
throw new ArgumentOutOfRangeException("frequency",
Strings.FrequencyMustBeBetween1And1440);
}
EwsUtilities.validateParamCollection(eventTypes, "eventTypes");
SubscribeToPushNotificationsRequest request = new SubscribeToPushNotificationsRequest(
this);
if (folderIds != null) {
request.getFolderIds().addRangeFolderId(folderIds);
}
request.setUrl(url);
request.setFrequency(frequency);
for (EventType event : eventTypes) {
request.getEventTypes().add(event);
}
request.setWatermark(watermark);
return request;
}
/**
* Subscribes to streaming notifications. Calling this method results in a
* call to EWS.
*
* @param folderIds
* The Ids of the folder to subscribe to.
* @param eventTypes
* The event types to subscribe to.
* @return A StreamingSubscription representing the new subscription
* @throws Exception
*/
public StreamingSubscription subscribeToStreamingNotifications(
Iterable<FolderId> folderIds, EventType... eventTypes)
throws Exception {
EwsUtilities.validateMethodVersion(this,
ExchangeVersion.Exchange2010_SP1,
"SubscribeToStreamingNotifications");
EwsUtilities.validateParamCollection(folderIds.iterator(), "folderIds");
return this.buildSubscribeToStreamingNotificationsRequest(folderIds,
eventTypes).execute().getResponseAtIndex(0).getSubscription();
}
/**
* Subscribes to streaming notifications on all folders in the authenticated
* user's mailbox. Calling this method results in a call to EWS.
*
* @param eventTypes
* The event types to subscribe to.
* @return A StreamingSubscription representing the new subscription.
* @throws Exception
*/
public StreamingSubscription subscribeToStreamingNotificationsOnAllFolders(
EventType... eventTypes) throws Exception {
EwsUtilities.validateMethodVersion(this,
ExchangeVersion.Exchange2010_SP1,
"SubscribeToStreamingNotificationsOnAllFolders");
return this.buildSubscribeToStreamingNotificationsRequest(null,
eventTypes).execute().getResponseAtIndex(0).getSubscription();
}
/*
* Subscribes to streaming notifications. Calling this method results in a
* call to EWS.
*
* @param folderIds
* The Ids of the folder to subscribe to.
* @param eventTypes
* The event types to subscribe to.
* @return A StreamingSubscription representing the new subscription.
* @throws Exception
public StreamingSubscription subscribeToStreamingNotifications(
Iterable<FolderId> folderIds, EventType... eventTypes)
throws Exception {
EwsUtilities.validateMethodVersion(this,
ExchangeVersion.Exchange2010_SP1,
"SubscribeToStreamingNotifications");
EwsUtilities.validateParamCollection(folderIds.iterator(), "folderIds");
return this.buildSubscribeToStreamingNotificationsRequest(folderIds,
eventTypes).execute().getResponseAtIndex(0).getSubscription();
}*/
/**
* Begins an asynchronous request to subscribe to streaming notifications.
* Calling this method results in a call to EWS.
*
* @param callback
* The AsyncCallback delegate
* @param state
* An object that contains state information for this request.
* @param folderIds
* The Ids of the folder to subscribe to.
* @param eventTypes
* The event types to subscribe to.
* @return An IAsyncResult that references the asynchronous request
* @throws Exception
*/
public IAsyncResult beginSubscribeToStreamingNotifications(AsyncCallback callback,Object state,
Iterable<FolderId> folderIds,
EventType... eventTypes) throws Exception {
EwsUtilities.validateMethodVersion(this,
ExchangeVersion.Exchange2010_SP1,
"BeginSubscribeToStreamingNotifications");
EwsUtilities.validateParamCollection(folderIds.iterator(), "folderIds");
return this.buildSubscribeToStreamingNotificationsRequest(folderIds,
eventTypes).beginExecute(callback,null);
}
/**
* Subscribes to streaming notifications on all folders in the authenticated
* user's mailbox. Calling this method results in a call to EWS.
*
*@param eventTypes
* The event types to subscribe to. @ returns A
* StreamingSubscription representing the new subscription.
* @throws Exception
* @throws Exception
**/
/*public StreamingSubscription SubscribeToStreamingNotificationsOnAllFolders(
EventType... eventTypes) throws Exception, Exception {
EwsUtilities.validateMethodVersion(this,
ExchangeVersion.Exchange2010_SP1,
"SubscribeToStreamingNotificationsOnAllFolders");
return this.BuildSubscribeToStreamingNotificationsRequest(null,
eventTypes).execute().getResponseAtIndex(0).getSubscription();
}*/
/**
* Begins an asynchronous request to subscribe to streaming notifications on
* all folders in the authenticated user's mailbox. Calling this method
* results in a call to EWS.
*
* @param callback
* The AsyncCallback delegate
* @param state
* An object that contains state information for this request.
* @throws Exception
* @return An IAsyncResult that references the asynchronous request.
**/
public IAsyncResult beginSubscribeToStreamingNotificationsOnAllFolders(AsyncCallback callback,Object state,
EventType... eventTypes) throws Exception {
EwsUtilities.validateMethodVersion(this,
ExchangeVersion.Exchange2010_SP1,
"BeginSubscribeToStreamingNotificationsOnAllFolders");
return this.buildSubscribeToStreamingNotificationsRequest(null,
eventTypes).beginExecute(callback,null);
}
/**
* Ends an asynchronous request to subscribe to push notifications in the
* authenticated user's mailbox.
*
* @param asyncResult
* An IAsyncResult that references the asynchronous request.
* @return A streamingSubscription representing the new subscription
* @throws Exception
* @throws IndexOutOfBoundsException
*/
public StreamingSubscription endSubscribeToStreamingNotifications(IAsyncResult asyncResult) throws IndexOutOfBoundsException, Exception
{
EwsUtilities.validateMethodVersion(
this,
ExchangeVersion.Exchange2010_SP1,
"EndSubscribeToStreamingNotifications");
SubscribeToStreamingNotificationsRequest request = AsyncRequestResult.extractServiceRequest(this, asyncResult);
// SubscribeToStreamingNotificationsRequest request = AsyncRequestResult.extractServiceRequest<SubscribeToStreamingNotificationsRequest>(this, asyncResult);
return request.endExecute(asyncResult).getResponseAtIndex(0).getSubscription();
}
/**
* Builds request to subscribe to streaming notifications in the
* authenticated user's mailbox.
*
* @param folderIds
* The Ids of the folder to subscribe to.
* @param eventTypes
* The event types to subscribe to.
* @return A request to subscribe to streaming notifications in the
* authenticated user's mailbox
* @throws Exception
*/
private SubscribeToStreamingNotificationsRequest buildSubscribeToStreamingNotificationsRequest(
Iterable<FolderId> folderIds, EventType[] eventTypes) throws Exception {
EwsUtilities.validateParamCollection(eventTypes, "eventTypes");
SubscribeToStreamingNotificationsRequest request = new SubscribeToStreamingNotificationsRequest(
this);
if (folderIds != null) {
request.getFolderIds().addRangeFolderId(folderIds);
}
for (EventType event : eventTypes) {
request.getEventTypes().add(event);
}
return request;
}
/**
* Synchronizes the items of a specific folder. Calling this method
* results in a call to EWS.
*
* @param syncFolderId
* The Id of the folder containing the items to synchronize with.
* @param propertySet
* The set of properties to retrieve for synchronized items.
* @param ignoredItemIds
* The optional list of item Ids that should be ignored.
* @param maxChangesReturned
* The maximum number of changes that should be returned.
* @param syncScope
* The sync scope identifying items to include in the
* ChangeCollection.
* @param syncState
* The optional sync state representing the point in time when to
* start the synchronization.
* @return A ChangeCollection containing a list of changes that occurred in
* the specified folder.
* @throws Exception
* the exception
*/
public ChangeCollection<ItemChange> syncFolderItems(FolderId syncFolderId,
PropertySet propertySet, Iterable<ItemId> ignoredItemIds,
int maxChangesReturned, SyncFolderItemsScope syncScope,
String syncState) throws Exception {
return this.buildSyncFolderItemsRequest(syncFolderId, propertySet,
ignoredItemIds, maxChangesReturned, syncScope, syncState)
.execute().getResponseAtIndex(0).getChanges();
}
/**
* Begins an asynchronous request to synchronize the items of a specific
* folder. Calling this method results in a call to EWS.
*
* @param callback
* The AsyncCallback delegate
* @param state
* An object that contains state information for this request
* @param syncFolderId
* The Id of the folder containing the items to synchronize with
* @param propertySet
* The set of properties to retrieve for synchronized items.
* @param ignoredItemIds
* The optional list of item Ids that should be ignored.
* @param maxChangesReturned
* The maximum number of changes that should be returned.
* @param syncScope
* The sync scope identifying items to include in the
* ChangeCollection
* @param syncState
* The optional sync state representing the point in time when to
* start the synchronization
* @return An IAsyncResult that references the asynchronous request.
* @throws Exception
*/
public IAsyncResult beginSyncFolderItems( AsyncCallback callback,Object state,FolderId syncFolderId, PropertySet propertySet,
Iterable<ItemId> ignoredItemIds, int maxChangesReturned,
SyncFolderItemsScope syncScope, String syncState) throws Exception {
return this.buildSyncFolderItemsRequest(syncFolderId, propertySet,
ignoredItemIds, maxChangesReturned, syncScope, syncState)
.beginExecute(callback,null);
}
/**
* Ends an asynchronous request to synchronize the items of a specific
* folder.
*
* @param asyncResult
* An IAsyncResult that references the asynchronous request.
* @throws Exception
* @return A ChangeCollection containing a list of changes that occurred in
* the specified folder.
*/
public ChangeCollection<ItemChange> endSyncFolderItems(IAsyncResult asyncResult) throws Exception
{
SyncFolderItemsRequest request = AsyncRequestResult.extractServiceRequest(this,asyncResult);
return request.endExecute(asyncResult).getResponseAtIndex(0).getChanges();
}
/**
* Builds a request to synchronize the items of a specific folder.
*
* @param syncFolderId
* The Id of the folder containing the items to synchronize with
* @param propertySet
* The set of properties to retrieve for synchronized items.
* @param ignoredItemIds
* The optional list of item Ids that should be ignored
* @param maxChangesReturned
* The maximum number of changes that should be returned.
* @param syncScope
* The sync scope identifying items to include in the
* ChangeCollection.
* @param syncState
* The optional sync state representing the point in time when to
* start the synchronization.
* @return A request to synchronize the items of a specific folder.
* @throws Exception
*/
private SyncFolderItemsRequest buildSyncFolderItemsRequest(
FolderId syncFolderId, PropertySet propertySet,
Iterable<ItemId> ignoredItemIds, int maxChangesReturned,
SyncFolderItemsScope syncScope, String syncState) throws Exception {
EwsUtilities.validateParam(syncFolderId, "syncFolderId");
EwsUtilities.validateParam(propertySet, "propertySet");
SyncFolderItemsRequest request = new SyncFolderItemsRequest(this);
request.setSyncFolderId(syncFolderId);
request.setPropertySet(propertySet);
if (ignoredItemIds != null) {
request.getIgnoredItemIds().addRange(ignoredItemIds);
}
request.setMaxChangesReturned(maxChangesReturned);
request.setSyncScope(syncScope);
request.setSyncState(syncState);
return request;
}
/**
* Synchronizes the sub-folders of a specific folder. Calling this method
* results in a call to EWS.
*
* @param syncFolderId
* the sync folder id
* @param propertySet
* the property set
* @param syncState
* the sync state
* @return A ChangeCollection containing a list of changes that occurred in
* the specified folder.
* @throws Exception
* the exception
*/
public ChangeCollection<FolderChange> syncFolderHierarchy(
FolderId syncFolderId, PropertySet propertySet, String syncState)
throws Exception {
return this.buildSyncFolderHierarchyRequest(syncFolderId, propertySet,
syncState).execute().getResponseAtIndex(0).getChanges();
}
/**
* Begins an asynchronous request to synchronize the sub-folders of a
* specific folder. Calling this method results in a call to EWS.
*
* @param callback
* The AsyncCallback delegate
* @param state
* An object that contains state information for this request.
* @param syncFolderId
* The Id of the folder containing the items to synchronize with.
* A null value indicates the root folder of the mailbox.
* @param propertySet
* The set of properties to retrieve for synchronized items.
* @param syncState
* The optional sync state representing the point in time when to
* start the synchronization.
* @return An IAsyncResult that references the asynchronous request
* @throws Exception
*/
public IAsyncResult beginSyncFolderHierarchy(AsyncCallback callback,Object state, FolderId syncFolderId, PropertySet propertySet,
String syncState) throws Exception {
return this.buildSyncFolderHierarchyRequest(syncFolderId, propertySet,
syncState).beginExecute(callback,null);
}
/**
* Synchronizes the entire folder hierarchy of the mailbox this Service is
* connected to. Calling this method results in a call to EWS.
*
* @param propertySet
* The set of properties to retrieve for synchronized items.
* @param syncState
* The optional sync state representing the point in time when to
* start the synchronization.
* @return A ChangeCollection containing a list of changes that occurred in
* the specified folder.
* @throws Exception
*/
public ChangeCollection<FolderChange> syncFolderHierarchy(
PropertySet propertySet, String syncState)
throws Exception {
return this.syncFolderHierarchy(null, propertySet, syncState);
}
/*
* Begins an asynchronous request to synchronize the entire folder hierarchy
* of the mailbox this Service is connected to. Calling this method results
* in a call to EWS
*
* @param callback
* The AsyncCallback delegate
* @param state
* An object that contains state information for this request.
* @param propertySet
* The set of properties to retrieve for synchronized items.
* @param syncState
* The optional sync state representing the point in time when to
* start the synchronization.
* @return An IAsyncResult that references the asynchronous request
* @throws Exception
public IAsyncResult beginSyncFolderHierarchy(FolderId syncFolderId, PropertySet propertySet, String syncState) throws Exception {
return this.beginSyncFolderHierarchy(null,null, null,
propertySet, syncState);
}*/
/**
* Ends an asynchronous request to synchronize the specified folder
* hierarchy of the mailbox this Service is connected to.
*
* @param asyncResult
* An IAsyncResult that references the asynchronous request.
* @throws Exception
* @return A ChangeCollection containing a list of changes that occurred in
* the specified folder.
**/
public ChangeCollection<FolderChange> endSyncFolderHierarchy(IAsyncResult asyncResult) throws Exception
{
SyncFolderHierarchyRequest request = AsyncRequestResult.extractServiceRequest(this, asyncResult);
return request.endExecute(asyncResult).getResponseAtIndex(0).getChanges();
}
/**
* Builds a request to synchronize the specified folder hierarchy of the
* mailbox this Service is connected to.
*
* @param syncFolderId
* The Id of the folder containing the items to synchronize with.
* A null value indicates the root folder of the mailbox.
* @param propertySet
* The set of properties to retrieve for synchronized items.
* @param syncState
* The optional sync state representing the point in time when to
* start the synchronization.
* @return A request to synchronize the specified folder hierarchy of the
* mailbox this Service is connected to
* @throws Exception
*/
private SyncFolderHierarchyRequest buildSyncFolderHierarchyRequest(
FolderId syncFolderId, PropertySet propertySet, String syncState)
throws Exception {
EwsUtilities.validateParamAllowNull(syncFolderId, "syncFolderId"); // Null
// syncFolderId
// allowed
EwsUtilities.validateParam(propertySet, "propertySet");
SyncFolderHierarchyRequest request = new SyncFolderHierarchyRequest(
this);
request.setPropertySet(propertySet);
request.setSyncFolderId(syncFolderId);
request.setSyncState(syncState);
return request;
}
// Availability operations
/**
* Gets Out of Office (OOF) settings for a specific user. Calling this
* method results in a call to EWS.
*
* @param smtpAddress
* the smtp address
* @return An OofSettings instance containing OOF information for the
* specified user.
* @throws Exception
* the exception
*/
public OofSettings getUserOofSettings(String smtpAddress) throws Exception {
EwsUtilities.validateParam(smtpAddress, "smtpAddress");
GetUserOofSettingsRequest request = new GetUserOofSettingsRequest(this);
request.setSmtpAddress(smtpAddress);
return request.execute().getOofSettings();
}
/**
* Sets Out of Office (OOF) settings for a specific user. Calling this
* method results in a call to EWS.
*
* @param smtpAddress
* the smtp address
* @param oofSettings
* the oof settings
* @throws Exception
* the exception
*/
public void setUserOofSettings(String smtpAddress, OofSettings oofSettings)
throws Exception {
EwsUtilities.validateParam(smtpAddress, "smtpAddress");
EwsUtilities.validateParam(oofSettings, "oofSettings");
SetUserOofSettingsRequest request = new SetUserOofSettingsRequest(this);
request.setSmtpAddress(smtpAddress);
request.setOofSettings(oofSettings);
request.execute();
}
/**
* Gets detailed information about the availability of a set of users,
* rooms, and resources within a specified time window.
*
* @param attendees
* the attendees
* @param timeWindow
* the time window
* @param requestedData
* the requested data
* @param options
* the options
* @return The availability information for each user appears in a unique
* FreeBusyResponse object. The order of users in the request
* determines the order of availability data for each user in the
* response.
* @throws Exception
* the exception
*/
public GetUserAvailabilityResults getUserAvailability(
Iterable<AttendeeInfo> attendees, TimeWindow timeWindow,
AvailabilityData requestedData, AvailabilityOptions options)
throws Exception {
EwsUtilities.validateParamCollection(attendees.iterator(), "attendees");
EwsUtilities.validateParam(timeWindow, "timeWindow");
EwsUtilities.validateParam(options, "options");
GetUserAvailabilityRequest request = new GetUserAvailabilityRequest(
this);
request.setAttendees(attendees);
request.setTimeWindow(timeWindow);
request.setRequestedData(requestedData);
request.setOptions(options);
return request.execute();
}
/**
* Gets detailed information about the availability of a set of users,
* rooms, and resources within a specified time window.
*
* @param attendees
* the attendees
* @param timeWindow
* the time window
* @param requestedData
* the requested data
* @return The availability information for each user appears in a unique
* FreeBusyResponse object. The order of users in the request
* determines the order of availability data for each user in the
* response.
* @throws Exception
* the exception
*/
public GetUserAvailabilityResults getUserAvailability(
Iterable<AttendeeInfo> attendees, TimeWindow timeWindow,
AvailabilityData requestedData) throws Exception {
return this.getUserAvailability(attendees, timeWindow, requestedData,
new AvailabilityOptions());
}
/**
* Retrieves a collection of all room lists in the organization.
*
* @return An EmailAddressCollection containing all the room lists in the
* organization
* @throws Exception
* the exception
*/
public EmailAddressCollection getRoomLists() throws Exception {
GetRoomListsRequest request = new GetRoomListsRequest(this);
return request.execute().getRoomLists();
}
/**
* Retrieves a collection of all room lists in the specified room list in
* the organization.
*
* @param emailAddress
* the email address
* @return A collection of EmailAddress objects representing all the rooms
* within the specifed room list.
* @throws Exception
* the exception
*/
public Collection<EmailAddress> getRooms(EmailAddress emailAddress)
throws Exception {
EwsUtilities.validateParam(emailAddress, "emailAddress");
GetRoomsRequest request = new GetRoomsRequest(this);
request.setRoomList(emailAddress);
return request.execute().getRooms();
}
// region Conversation
/**
* Retrieves a collection of all Conversations in the specified Folder.
*
* @param view
* The view controlling the number of conversations returned.
* @param filter
* The search filter. Only search filter class supported
* SearchFilter.IsEqualTo
* @param folderId
* The Id of the folder in which to search for conversations.
* @throws Exception
*/
private Collection<Conversation> findConversation(
ConversationIndexedItemView view, SearchFilter.IsEqualTo filter,
FolderId folderId) throws Exception {
EwsUtilities.validateParam(view, "view");
EwsUtilities.validateParamAllowNull(filter, "filter");
EwsUtilities.validateParam(folderId, "folderId");
EwsUtilities.validateMethodVersion(this,
ExchangeVersion.Exchange2010_SP1, "FindConversation");
FindConversationRequest request = new FindConversationRequest(this);
request.setIndexedItemView(view);
request.setConversationViewFilter(filter);
request.setFolderId(new FolderIdWrapper(folderId));
return request.execute().getConversations();
}
/**
* Retrieves a collection of all Conversations in the specified Folder.
*
* @param view
* The view controlling the number of conversations returned.
* @param folderId
* The Id of the folder in which to search for conversations.
* @throws Exception
*/
public Collection<Conversation> findConversation(
ConversationIndexedItemView view, FolderId folderId)
throws Exception {
return this.findConversation(view, null, folderId);
}
/**
* Applies ConversationAction on the specified conversation.
*
* @param actionType
* ConversationAction
* @param conversationIds
* The conversation ids.
* @param processRightAway
* True to process at once . This is blocking and false to let
* the Assitant process it in the back ground
* @param categories
* Catgories that need to be stamped can be null or empty
* @param enableAlwaysDelete
* True moves every current and future messages in the
* conversation to deleted items folder. False stops the alwasy
* delete action. This is applicable only if the action is
* AlwaysDelete
* @param destinationFolderId
* Applicable if the action is AlwaysMove. This moves every
* current message and future message in the conversation to the
* specified folder. Can be null if tis is then it stops the
* always move action
* @param errorHandlingMode
* The error handling mode.
* @throws Exception
*/
private ServiceResponseCollection<ServiceResponse> applyConversationAction(
ConversationActionType actionType,
Iterable<ConversationId> conversationIds, boolean processRightAway,
StringList categories, boolean enableAlwaysDelete,
FolderId destinationFolderId, ServiceErrorHandling errorHandlingMode)
throws Exception {
EwsUtilities.EwsAssert(
actionType == ConversationActionType.AlwaysCategorize
|| actionType == ConversationActionType.AlwaysMove
|| actionType == ConversationActionType.AlwaysDelete,
"ApplyConversationAction", "Invalic actionType");
EwsUtilities.validateParam(conversationIds, "conversationId");
EwsUtilities.validateMethodVersion(this,
ExchangeVersion.Exchange2010_SP1, "ApplyConversationAction");
ApplyConversationActionRequest request = new ApplyConversationActionRequest(
this, errorHandlingMode);
ConversationAction action = new ConversationAction();
for (ConversationId conversationId : conversationIds) {
action.setAction(actionType);
action.setConversationId(conversationId);
action.setProcessRightAway(processRightAway);
action.setCategories(categories);
action.setEnableAlwaysDelete(enableAlwaysDelete);
action
.setDestinationFolderId(destinationFolderId != null ? new FolderIdWrapper(
destinationFolderId)
: null);
request.getConversationActions().add(action);
}
return request.execute();
}
/**
* Applies one time conversation action on items in specified folder inside
* the conversation.
*
* @param actionType
* The action
* @param idTimePairs
* The id time pairs.
* @param contextFolderId
* The context folder id.
* @param destinationFolderId
* The destination folder id.
* @param deleteType
* Type of the delete.
* @param isRead
* The is read.
* @param errorHandlingMode
* The error handling mode.
* @throws Exception
*/
private ServiceResponseCollection<ServiceResponse> applyConversationOneTimeAction(
ConversationActionType actionType,
Iterable<HashMap<ConversationId, Date>> idTimePairs,
FolderId contextFolderId, FolderId destinationFolderId,
DeleteMode deleteType, Boolean isRead,
ServiceErrorHandling errorHandlingMode) throws Exception {
EwsUtilities.EwsAssert(actionType == ConversationActionType.Move
|| actionType == ConversationActionType.Delete
|| actionType == ConversationActionType.SetReadState
|| actionType == ConversationActionType.Copy,
"ApplyConversationOneTimeAction", "Invalid actionType");
EwsUtilities.validateParamCollection(idTimePairs.iterator(),
"idTimePairs");
EwsUtilities.validateMethodVersion(this,
ExchangeVersion.Exchange2010_SP1, "ApplyConversationAction");
ApplyConversationActionRequest request = new ApplyConversationActionRequest(
this, errorHandlingMode);
for (HashMap<ConversationId, Date> idTimePair : idTimePairs) {
ConversationAction action = new ConversationAction();
action.setAction(actionType);
action.setConversationId(idTimePair.keySet().iterator().next());
action
.setContextFolderId(contextFolderId != null ? new FolderIdWrapper(
contextFolderId)
: null);
action
.setDestinationFolderId(destinationFolderId != null ? new FolderIdWrapper(
destinationFolderId)
: null);
action.setConversationLastSyncTime(idTimePair.values().iterator()
.next());
action.setIsRead(isRead);
action.setDeleteType(deleteType);
request.getConversationActions().add(action);
}
return request.execute();
}
/**
* Sets up a conversation so that any item received within that conversation
* is always categorized. Calling this method results in a call to EWS.
*
* @param conversationId
* The id of the conversation.
* @param categories
* The categories that should be stamped on items in the
* conversation.
* @param processSynchronously
* Indicates whether the method should return only once enabling
* this rule and stamping existing items in the conversation is
* completely done. If processSynchronously is false, the method
* returns immediately.
* @throws Exception
*/
public ServiceResponseCollection<ServiceResponse> enableAlwaysCategorizeItemsInConversations(
Iterable<ConversationId> conversationId,
Iterable<String> categories, boolean processSynchronously)
throws Exception {
EwsUtilities.validateParamCollection(categories.iterator(),
"categories");
return this.applyConversationAction(
ConversationActionType.AlwaysCategorize, conversationId,
processSynchronously, new StringList(categories), false, null,
ServiceErrorHandling.ReturnErrors);
}
/**
* Sets up a conversation so that any item received within that conversation
* is no longer categorized. Calling this method results in a call to EWS.
*
* @param conversationId
* The id of the conversation.
* @param processSynchronously
* Indicates whether the method should return only once enabling
* this rule and stamping existing items in the conversation is
* completely done. If processSynchronously is false, the method
* returns immediately.
* @throws Exception
*/
public ServiceResponseCollection<ServiceResponse> disableAlwaysCategorizeItemsInConversations(
Iterable<ConversationId> conversationId,
boolean processSynchronously) throws Exception {
return this.applyConversationAction(
ConversationActionType.AlwaysCategorize, conversationId,
processSynchronously, null, false, null,
ServiceErrorHandling.ReturnErrors);
}
/**
* Sets up a conversation so that any item received within that conversation
* is always moved to Deleted Items folder. Calling this method results in a
* call to EWS.
*
* @param conversationId
* The id of the conversation.
* @param processSynchronously
* Indicates whether the method should return only once enabling
* this rule and stamping existing items in the conversation is
* completely done. If processSynchronously is false, the method
* returns immediately.
* @throws Exception
*/
public ServiceResponseCollection<ServiceResponse> enableAlwaysDeleteItemsInConversations(
Iterable<ConversationId> conversationId,
boolean processSynchronously) throws Exception {
return this.applyConversationAction(
ConversationActionType.AlwaysDelete, conversationId,
processSynchronously, null, true, null,
ServiceErrorHandling.ReturnErrors);
}
/**
* Sets up a conversation so that any item received within that conversation
* is no longer moved to Deleted Items folder. Calling this method results
* in a call to EWS.
*
* @param conversationId
* The id of the conversation.
* @param processSynchronously
* Indicates whether the method should return only once enabling
* this rule and stamping existing items in the conversation is
* completely done. If processSynchronously is false, the method
* returns immediately.
* @throws Exception
*/
public ServiceResponseCollection<ServiceResponse> disableAlwaysDeleteItemsInConversations(
Iterable<ConversationId> conversationId,
boolean processSynchronously) throws Exception {
return this.applyConversationAction(
ConversationActionType.AlwaysDelete, conversationId,
processSynchronously, null, false, null,
ServiceErrorHandling.ReturnErrors);
}
/**
* Sets up a conversation so that any item received within that conversation
* is always moved to a specific folder. Calling this method results in a
* call to EWS.
*
* @param conversationId
* The Id of the folder to which conversation items should be
* moved.
* @param destinationFolderId
* The Id of the destination folder.
* @param processSynchronously
* Indicates whether the method should return only once enabling
* this rule and stamping existing items in the conversation is
* completely done. If processSynchronously is false, the method
* returns immediately.
* @throws Exception
*/
public ServiceResponseCollection<ServiceResponse> enableAlwaysMoveItemsInConversations(
Iterable<ConversationId> conversationId,
FolderId destinationFolderId, boolean processSynchronously)
throws Exception {
EwsUtilities.validateParam(destinationFolderId, "destinationFolderId");
return this.applyConversationAction(ConversationActionType.AlwaysMove,
conversationId, processSynchronously, null, false,
destinationFolderId, ServiceErrorHandling.ReturnErrors);
}
/**
* Sets up a conversation so that any item received within that conversation
* is no longer moved to a specific folder. Calling this method results in a
* call to EWS.
*
* @param conversationIds
* The conversation ids.
* @param processSynchronously
* Indicates whether the method should return only once disabling
* this rule is completely done. If processSynchronously is
* false, the method returns immediately.
* @throws Exception
*/
public ServiceResponseCollection<ServiceResponse> disableAlwaysMoveItemsInConversations(
Iterable<ConversationId> conversationIds,
boolean processSynchronously) throws Exception {
return this.applyConversationAction(ConversationActionType.AlwaysMove,
conversationIds, processSynchronously, null, false, null,
ServiceErrorHandling.ReturnErrors);
}
/**
* Moves the items in the specified conversation to the specified
* destination folder. Calling this method results in a call to EWS.
*
* @param idLastSyncTimePairs
* The pairs of Id of conversation whose items should be moved
* and the dateTime conversation was last synced (Items received
* after that dateTime will not be moved).
* @param contextFolderId
* The Id of the folder that contains the conversation.
* @param destinationFolderId
* The Id of the destination folder.
* @throws Exception
*/
public ServiceResponseCollection<ServiceResponse> moveItemsInConversations(
Iterable<HashMap<ConversationId, Date>> idLastSyncTimePairs,
FolderId contextFolderId, FolderId destinationFolderId)
throws Exception {
EwsUtilities.validateParam(destinationFolderId, "destinationFolderId");
return this.applyConversationOneTimeAction(ConversationActionType.Move,
idLastSyncTimePairs, contextFolderId, destinationFolderId,
null, null, ServiceErrorHandling.ReturnErrors);
}
/**
* Copies the items in the specified conversation to the specified
* destination folder. Calling this method results in a call to EWS.
*
* @param idLastSyncTimePairs
* The pairs of Id of conversation whose items should be copied
* and the dateTime conversation was last synced (Items received
* after that dateTime will not be copied).
* @param contextFolderId
* The context folder id.
* @param destinationFolderId
* The destination folder id.
* @throws Exception
*/
public ServiceResponseCollection<ServiceResponse> copyItemsInConversations(
Iterable<HashMap<ConversationId, Date>> idLastSyncTimePairs,
FolderId contextFolderId, FolderId destinationFolderId)
throws Exception {
EwsUtilities.validateParam(destinationFolderId, "destinationFolderId");
return this.applyConversationOneTimeAction(ConversationActionType.Copy,
idLastSyncTimePairs, contextFolderId, destinationFolderId,
null, null, ServiceErrorHandling.ReturnErrors);
}
/**
* Deletes the items in the specified conversation. Calling this method
* results in a call to EWS.
*
* @param idLastSyncTimePairs
* The pairs of Id of conversation whose items should be deleted
* and the date and time conversation was last synced (Items
* received after that date will not be deleted). conversation
* was last synced (Items received after that dateTime will not
* be copied).
* @param contextFolderId
* The Id of the folder that contains the conversation.
* @param deleteMode
* The deletion mode
* @throws Exception
*/
public ServiceResponseCollection<ServiceResponse> deleteItemsInConversations(
Iterable<HashMap<ConversationId, Date>> idLastSyncTimePairs,
FolderId contextFolderId, DeleteMode deleteMode) throws Exception {
return this.applyConversationOneTimeAction(
ConversationActionType.Delete, idLastSyncTimePairs,
contextFolderId, null, deleteMode, null,
ServiceErrorHandling.ReturnErrors);
}
/**
* Sets the read state for items in conversation. Calling this mehtod would
* result in call to EWS.
*
* @param idLastSyncTimePairs
* The pairs of Id of conversation whose items should read state
* set and the date and time conversation was last synced (Items
* received after that date will not have their read state set).
* was last synced (Items received after that date will not be
* deleted). conversation was last synced (Items received after
* that dateTime will not be copied).
* @param contextFolderId
* The Id of the folder that contains the conversation.
* @param isRead
* if set to <c>true</c>, conversation items are marked as read;
* otherwise they are marked as unread.
* @throws Exception
*/
public ServiceResponseCollection<ServiceResponse> setReadStateForItemsInConversations(
Iterable<HashMap<ConversationId, Date>> idLastSyncTimePairs,
FolderId contextFolderId, boolean isRead) throws Exception {
return this.applyConversationOneTimeAction(
ConversationActionType.SetReadState, idLastSyncTimePairs,
contextFolderId, null, null, isRead,
ServiceErrorHandling.ReturnErrors);
}
// Id conversion operations
/**
* Converts multiple Ids from one format to another in a single call to
* EWS.
*
* @param ids
* the ids
* @param destinationFormat
* the destination format
* @param errorHandling
* the error handling
* @return A ServiceResponseCollection providing conversion results for each
* specified Ids.
* @throws Exception
* the exception
*/
private ServiceResponseCollection<ConvertIdResponse> internalConvertIds(
Iterable<AlternateIdBase> ids, IdFormat destinationFormat,
ServiceErrorHandling errorHandling) throws Exception {
EwsUtilities.validateParamCollection(ids.iterator(), "ids");
ConvertIdRequest request = new ConvertIdRequest(this, errorHandling);
request.getIds().addAll((Collection<? extends AlternateIdBase>) ids);
request.setDestinationFormat(destinationFormat);
return request.execute();
}
/**
* Converts multiple Ids from one format to another in a single call to
* EWS.
*
* @param ids
* the ids
* @param destinationFormat
* the destination format
* @return A ServiceResponseCollection providing conversion results for each
* specified Ids.
* @throws Exception
* the exception
*/
public ServiceResponseCollection<ConvertIdResponse> convertIds(
Iterable<AlternateIdBase> ids, IdFormat destinationFormat)
throws Exception {
EwsUtilities.validateParamCollection(ids.iterator(), "ids");
return this.internalConvertIds(ids, destinationFormat,
ServiceErrorHandling.ReturnErrors);
}
/**
* Converts Id from one format to another in a single call to EWS.
*
* @param id
* the id
* @param destinationFormat
* the destination format
* @return The converted Id.
* @throws Exception
* the exception
*/
public AlternateIdBase convertId(AlternateIdBase id,
IdFormat destinationFormat) throws Exception {
EwsUtilities.validateParam(id, "id");
List alternateIdBaseArray = new ArrayList();
alternateIdBaseArray.add(id);
ServiceResponseCollection<ConvertIdResponse> responses = this
.internalConvertIds(alternateIdBaseArray, destinationFormat,
ServiceErrorHandling.ThrowOnError);
return responses.getResponseAtIndex(0).getConvertedId();
}
/**
* Adds delegates to a specific mailbox. Calling this method results in a
* call to EWS.
*
* @param mailbox
* the mailbox
* @param meetingRequestsDeliveryScope
* the meeting requests delivery scope
* @param delegateUsers
* the delegate users
* @return A collection of DelegateUserResponse objects providing the
* results of the operation.
* @throws Exception
* the exception
*/
public Collection<DelegateUserResponse> addDelegates(Mailbox mailbox,
MeetingRequestsDeliveryScope meetingRequestsDeliveryScope,
DelegateUser... delegateUsers) throws Exception {
ArrayList<DelegateUser> delUser = new ArrayList<DelegateUser>();
for (DelegateUser user : delegateUsers) {
delUser.add(user);
}
return this
.addDelegates(mailbox, meetingRequestsDeliveryScope, delUser);
}
/**
* Adds delegates to a specific mailbox. Calling this method results in a
* call to EWS.
*
* @param mailbox
* the mailbox
* @param meetingRequestsDeliveryScope
* the meeting requests delivery scope
* @param delegateUsers
* the delegate users
* @return A collection of DelegateUserResponse objects providing the
* results of the operation.
* @throws Exception
* the exception
*/
public Collection<DelegateUserResponse> addDelegates(Mailbox mailbox,
MeetingRequestsDeliveryScope meetingRequestsDeliveryScope,
Iterable<DelegateUser> delegateUsers) throws Exception {
EwsUtilities.validateParam(mailbox, "mailbox");
EwsUtilities.validateParamCollection(delegateUsers.iterator(),
"delegateUsers");
AddDelegateRequest request = new AddDelegateRequest(this);
request.setMailbox(mailbox);
for (DelegateUser user : delegateUsers) {
request.getDelegateUsers().add(user);
}
request.setMeetingRequestsDeliveryScope(meetingRequestsDeliveryScope);
DelegateManagementResponse response = request.execute();
return response.getDelegateUserResponses();
}
/**
* Updates delegates on a specific mailbox. Calling this method results in
* a call to EWS.
*
* @param mailbox
* the mailbox
* @param meetingRequestsDeliveryScope
* the meeting requests delivery scope
* @param delegateUsers
* the delegate users
* @return A collection of DelegateUserResponse objects providing the
* results of the operation.
* @throws Exception
* the exception
*/
public Collection<DelegateUserResponse> updateDelegates(Mailbox mailbox,
MeetingRequestsDeliveryScope meetingRequestsDeliveryScope,
DelegateUser... delegateUsers) throws Exception {
ArrayList<DelegateUser> delUser = new ArrayList<DelegateUser>();
for (DelegateUser user : delegateUsers) {
delUser.add(user);
}
return this.updateDelegates(mailbox, meetingRequestsDeliveryScope,
delUser);
}
/**
* Updates delegates on a specific mailbox. Calling this method results in
* a call to EWS.
*
* @param mailbox
* the mailbox
* @param meetingRequestsDeliveryScope
* the meeting requests delivery scope
* @param delegateUsers
* the delegate users
* @return A collection of DelegateUserResponse objects providing the
* results of the operation.
* @throws Exception
* the exception
*/
public Collection<DelegateUserResponse> updateDelegates(Mailbox mailbox,
MeetingRequestsDeliveryScope meetingRequestsDeliveryScope,
Iterable<DelegateUser> delegateUsers) throws Exception {
EwsUtilities.validateParam(mailbox, "mailbox");
EwsUtilities.validateParamCollection(delegateUsers.iterator(),
"delegateUsers");
UpdateDelegateRequest request = new UpdateDelegateRequest(this);
request.setMailbox(mailbox);
ArrayList<DelegateUser> delUser = new ArrayList<DelegateUser>();
for (DelegateUser user : delegateUsers) {
delUser.add(user);
}
request.getDelegateUsers().addAll(delUser);
request.setMeetingRequestsDeliveryScope(meetingRequestsDeliveryScope);
DelegateManagementResponse response = request.execute();
return response.getDelegateUserResponses();
}
/**
* Removes delegates on a specific mailbox. Calling this method results in
* a call to EWS.
*
* @param mailbox
* the mailbox
* @param userIds
* the user ids
* @return A collection of DelegateUserResponse objects providing the
* results of the operation.
* @throws Exception
* the exception
*/
public Collection<DelegateUserResponse> removeDelegates(Mailbox mailbox,
UserId... userIds) throws Exception {
ArrayList<UserId> delUser = new ArrayList<UserId>();
for (UserId user : userIds) {
delUser.add(user);
}
return this.removeDelegates(mailbox, delUser);
}
/**
* Removes delegates on a specific mailbox. Calling this method results in
* a call to EWS.
*
* @param mailbox
* the mailbox
* @param userIds
* the user ids
* @return A collection of DelegateUserResponse objects providing the
* results of the operation.
* @throws Exception
* the exception
*/
public Collection<DelegateUserResponse> removeDelegates(Mailbox mailbox,
Iterable<UserId> userIds) throws Exception {
EwsUtilities.validateParam(mailbox, "mailbox");
EwsUtilities.validateParamCollection(userIds.iterator(), "userIds");
RemoveDelegateRequest request = new RemoveDelegateRequest(this);
request.setMailbox(mailbox);
ArrayList<UserId> delUser = new ArrayList<UserId>();
for (UserId user : userIds) {
delUser.add(user);
}
request.getUserIds().addAll(delUser);
DelegateManagementResponse response = request.execute();
return response.getDelegateUserResponses();
}
public DelegateInformation getDelegates(Mailbox mailbox,
boolean includePermissions, UserId... userIds) throws Exception {
ArrayList<UserId> delUser = new ArrayList<UserId>();
for (UserId user : userIds) {
delUser.add(user);
}
return this.getDelegates(mailbox, includePermissions, delUser);
}
public DelegateInformation getDelegates(Mailbox mailbox,
boolean includePermissions, Iterable<UserId> userIds)
throws Exception {
EwsUtilities.validateParam(mailbox, "mailbox");
GetDelegateRequest request = new GetDelegateRequest(this);
request.setMailbox(mailbox);
ArrayList<UserId> delUser = new ArrayList<UserId>();
for (UserId user : userIds) {
delUser.add(user);
}
request.getUserIds().addAll(delUser);
request.setIncludePermissions(includePermissions);
GetDelegateResponse response = request.execute();
DelegateInformation delegateInformation = new DelegateInformation(
(List<DelegateUserResponse>) response
.getDelegateUserResponses(), response
.getMeetingRequestsDeliveryScope());
return delegateInformation;
}
/**
* Creates the user configuration.
*
* @param userConfiguration
* the user configuration
* @throws Exception
* the exception
*/
protected void createUserConfiguration(UserConfiguration userConfiguration)
throws Exception {
EwsUtilities.validateParam(userConfiguration, "userConfiguration");
CreateUserConfigurationRequest request = new CreateUserConfigurationRequest(
this);
request.setUserConfiguration(userConfiguration);
request.execute();
}
/**
* Creates a UserConfiguration.
*
* @param name
* the name
* @param parentFolderId
* the parent folder id
* @throws Exception
* the exception
*/
protected void deleteUserConfiguration(String name, FolderId parentFolderId)
throws Exception {
EwsUtilities.validateParam(name, "name");
EwsUtilities.validateParam(parentFolderId, "parentFolderId");
DeleteUserConfigurationRequest request = new DeleteUserConfigurationRequest(
this);
request.setName(name);
request.setParentFolderId(parentFolderId);
request.execute();
}
/**
* Creates a UserConfiguration.
*
* @param name
* the name
* @param parentFolderId
* the parent folder id
* @param properties
* the properties
* @return the user configuration
* @throws Exception
* the exception
*/
protected UserConfiguration getUserConfiguration(String name,
FolderId parentFolderId, UserConfigurationProperties properties)
throws Exception {
EwsUtilities.validateParam(name, "name");
EwsUtilities.validateParam(parentFolderId, "parentFolderId");
GetUserConfigurationRequest request = new GetUserConfigurationRequest(
this);
request.setName(name);
request.setParentFolderId(parentFolderId);
request.setProperties(EnumSet.of(properties));
return request.execute().getResponseAtIndex(0).getUserConfiguration();
}
/**
* Loads the properties of the specified userConfiguration.
*
* @param userConfiguration
* the user configuration
* @param properties
* the properties
* @throws Exception
* the exception
*/
protected void loadPropertiesForUserConfiguration(
UserConfiguration userConfiguration,
UserConfigurationProperties properties) throws Exception {
EwsUtilities.EwsAssert(userConfiguration != null,
"ExchangeService.LoadPropertiesForUserConfiguration",
"userConfiguration is null");
GetUserConfigurationRequest request = new GetUserConfigurationRequest(
this);
request.setUserConfiguration(userConfiguration);
request.setProperties(EnumSet.of(properties));
request.execute();
}
/**
* Updates a UserConfiguration.
*
* @param userConfiguration
* the user configuration
* @throws Exception
* the exception
*/
protected void updateUserConfiguration(UserConfiguration userConfiguration)
throws Exception {
EwsUtilities.validateParam(userConfiguration, "userConfiguration");
UpdateUserConfigurationRequest request = new UpdateUserConfigurationRequest(
this);
request.setUserConfiguration(userConfiguration);
request.execute();
}
// region InboxRule operations
/**
* Retrieves inbox rules of the authenticated user.
*
* @return A RuleCollection object containing the authenticated users inbox
* rules.
* @throws Exception
*/
public RuleCollection getInboxRules() throws Exception {
GetInboxRulesRequest request = new GetInboxRulesRequest(this);
return request.execute().getRules();
}
/**
* Retrieves the inbox rules of the specified user.
*
* @param mailboxSmtpAddress
* The SMTP address of the user whose inbox rules should be
* retrieved
* @return A RuleCollection object containing the inbox rules of the
* specified user.
* @throws Exception
*/
public RuleCollection getInboxRules(String mailboxSmtpAddress)
throws Exception {
EwsUtilities.validateParam(mailboxSmtpAddress, "MailboxSmtpAddress");
GetInboxRulesRequest request = new GetInboxRulesRequest(this);
request.setmailboxSmtpAddress(mailboxSmtpAddress);
return request.execute().getRules();
}
/**
* Updates the authenticated user's inbox rules by applying the specified
* operations.
*
* @param operations
* The operations that should be applied to the user's inbox
* rules.
* @param removeOutlookRuleBlob
* Indicate whether or not to remove Outlook Rule Blob.
* @throws Exception
*/
public void updateInboxRules(Iterable<RuleOperation> operations,
boolean removeOutlookRuleBlob) throws Exception {
UpdateInboxRulesRequest request = new UpdateInboxRulesRequest(this);
request.setInboxRuleOperations(operations);
request.setRemoveOutlookRuleBlob(removeOutlookRuleBlob);
request.execute();
}
/**
* Updates the authenticated user's inbox rules by applying the specified
* operations.
*
* @param operations
* The operations that should be applied to the user's inbox
* rules.
* @param removeOutlookRuleBlob
* Indicate whether or not to remove Outlook Rule Blob.
* @param mailboxSmtpAddress
* The SMTP address of the user whose inbox rules should be
* retrieved
* @throws Exception
*/
public void updateInboxRules(Iterable<RuleOperation> operations,
boolean removeOutlookRuleBlob, String mailboxSmtpAddress)
throws Exception {
UpdateInboxRulesRequest request = new UpdateInboxRulesRequest(this);
request.setInboxRuleOperations(operations);
request.setRemoveOutlookRuleBlob(removeOutlookRuleBlob);
request.setMailboxSmtpAddress(mailboxSmtpAddress);
request.execute();
}
/**
* Default implementation of AutodiscoverRedirectionUrlValidationCallback.
* Always returns true indicating that the URL can be used.
*
* @param redirectionUrl
* the redirection url
* @return Returns true.
* @throws AutodiscoverLocalException
* the autodiscover local exception
*/
private boolean defaultAutodiscoverRedirectionUrlValidationCallback(
String redirectionUrl) throws AutodiscoverLocalException {
throw new AutodiscoverLocalException(String.format(
Strings.AutodiscoverRedirectBlocked, redirectionUrl));
}
/**
* Initializes the Url property to the Exchange Web Services URL for the
* specified e-mail address by calling the Autodiscover service.
*
* @param emailAddress
* the email address
* @throws Exception
* the exception
*/
public void autodiscoverUrl(String emailAddress) throws Exception {
this.autodiscoverUrl(emailAddress, this);
}
/**
* Initializes the Url property to the Exchange Web Services URL for the
* specified e-mail address by calling the Autodiscover service.
*
* @param emailAddress
* the email address to use.
* @param validateRedirectionUrlCallback
* The callback used to validate redirection URL
* @throws Exception
* the exception
*/
public void autodiscoverUrl(String emailAddress,
IAutodiscoverRedirectionUrl validateRedirectionUrlCallback)
throws Exception {
URI exchangeServiceUrl = null;
if (this.getRequestedServerVersion().ordinal() > ExchangeVersion.Exchange2007_SP1
.ordinal()) {
try {
exchangeServiceUrl = this.getAutodiscoverUrl(emailAddress, this
.getRequestedServerVersion(),
validateRedirectionUrlCallback);
this.setUrl(this
.adjustServiceUriFromCredentials(exchangeServiceUrl));
return;
} catch (AutodiscoverLocalException ex) {
this.traceMessage(TraceFlags.AutodiscoverResponse, String
.format("Autodiscover service call "
+ "failed with error '%s'. "
+ "Will try legacy service", ex.getMessage()));
} catch (ServiceRemoteException ex) {
// E14:321785 -- Special case: if
// the caller's account is locked
// we want to return this exception, not continue.
if (ex instanceof AccountIsLockedException) {
throw new AccountIsLockedException(ex.getMessage(),
exchangeServiceUrl, ex);
}
this.traceMessage(TraceFlags.AutodiscoverResponse, String
.format("Autodiscover service call "
+ "failed with error '%s'. "
+ "Will try legacy service", ex.getMessage()));
}
}
// Try legacy Autodiscover provider
exchangeServiceUrl = this.getAutodiscoverUrl(emailAddress,
ExchangeVersion.Exchange2007_SP1,
validateRedirectionUrlCallback);
this.setUrl(this.adjustServiceUriFromCredentials(exchangeServiceUrl));
}
/**
* Autodiscover will always return the "plain" EWS endpoint URL but if the
* client is using WindowsLive credentials, ExchangeService needs to use the
* WS-Security endpoint.
*
* @param uri
* the uri
* @return Adjusted URL.
* @throws Exception
*/
private URI adjustServiceUriFromCredentials(URI uri)
throws Exception {
return (this.getCredentials() != null) ? this.getCredentials()
.adjustUrl(uri) : uri;
}
/**
* Gets the autodiscover url.
*
* @param emailAddress
* the email address
* @param requestedServerVersion
* the Exchange version
* @param validateRedirectionUrlCallback
* the validate redirection url callback
* @return the autodiscover url
* @throws Exception
* the exception
*/
private URI getAutodiscoverUrl(String emailAddress,
ExchangeVersion requestedServerVersion,
IAutodiscoverRedirectionUrl validateRedirectionUrlCallback)
throws Exception {
AutodiscoverService autodiscoverService = new AutodiscoverService(this,
requestedServerVersion);
autodiscoverService
.setRedirectionUrlValidationCallback(validateRedirectionUrlCallback);
autodiscoverService.setEnableScpLookup(this.getEnableScpLookup());
GetUserSettingsResponse response = autodiscoverService.getUserSettings(
emailAddress, UserSettingName.InternalEwsUrl,
UserSettingName.ExternalEwsUrl);
switch (response.getErrorCode()) {
case NoError:
return this.getEwsUrlFromResponse(response, autodiscoverService
.isExternal().TRUE);
case InvalidUser:
throw new ServiceRemoteException(String.format(Strings.InvalidUser,
emailAddress));
case InvalidRequest:
throw new ServiceRemoteException(String.format(
Strings.InvalidAutodiscoverRequest, response
.getErrorMessage()));
default:
this.traceMessage(TraceFlags.AutodiscoverConfiguration, String
.format("No EWS Url returned for user %s, "
+ "error code is %s", emailAddress, response
.getErrorCode()));
throw new ServiceRemoteException(response.getErrorMessage());
}
}
private URI getEwsUrlFromResponse(GetUserSettingsResponse response,
boolean isExternal) throws URISyntaxException,
AutodiscoverLocalException {
String uriString;
// Bug E14:59063 -- Figure out which URL to use: Internal or External.
// Bug E14:67646 -- AutoDiscover may not return an external protocol.
// First try external, then internal.
// Bug E14:82650 -- Either protocol
// may be returned without a configured URL.
OutParam<String> outParam = new OutParam<String>();
if ((isExternal && response.tryGetSettingValue(String.class,
UserSettingName.ExternalEwsUrl, outParam))) {
uriString = outParam.getParam();
if (!(uriString == null || uriString.isEmpty())) {
return new URI(uriString);
}
}
if ((response.tryGetSettingValue(String.class,
UserSettingName.InternalEwsUrl, outParam) || response
.tryGetSettingValue(String.class,
UserSettingName.ExternalEwsUrl, outParam))) {
uriString = outParam.getParam();
if (!(uriString == null || uriString.isEmpty())) {
return new URI(uriString);
}
}
// If Autodiscover doesn't return an
// internal or external EWS URL, throw an exception.
throw new AutodiscoverLocalException(
Strings.AutodiscoverDidNotReturnEwsUrl);
}
// region Diagnostic Method -- Only used by test
/**
* Executes the diagnostic method.
*
* @param verb
* The verb.
* @param parameter
* The parameter.
* @throws Exception
*/
protected Document executeDiagnosticMethod(String verb, Node parameter)
throws Exception {
ExecuteDiagnosticMethodRequest request = new ExecuteDiagnosticMethodRequest(
this);
request.setVerb(verb);
request.setParameter(parameter);
return request.execute().getResponseAtIndex(0).getReturnValue();
}
// endregion
// region Validation
/**
* Validates this instance.
*
* @throws ServiceLocalException
* the service local exception
*/
@Override
protected void validate() throws ServiceLocalException {
super.validate();
if (this.getUrl() == null) {
throw new ServiceLocalException(Strings.ServiceUrlMustBeSet);
}
}
// region Constructors
/**
* Initializes a new instance of the <see cref="ExchangeService"/> class,
* targeting the specified version of EWS and scoped to the to the system's
* current time zone.
*/
public ExchangeService() {
super();
}
/**
* Initializes a new instance of the <see cref="ExchangeService"/> class,
* targeting the specified version of EWS and scoped to the system's current
* time zone.
*
* @param requestedServerVersion
* the requested server version
*/
public ExchangeService(ExchangeVersion requestedServerVersion) {
super(requestedServerVersion);
}
/**
* Initializes a new instance of the <see cref="ExchangeService"/> class,
* targeting the specified version of EWS and scoped to the to the specified
* time zone.
*
* @param requestedServerVersion
* The version of EWS that the service targets.
* @param timeZone
* The time zone to which the service is scoped.
*/
public ExchangeService(ExchangeVersion requestedServerVersion,
TimeZone timeZone) {
super(requestedServerVersion, timeZone);
}
// Utilities
/**
* Prepare http web request.
*
* @return the http web request
* @throws ServiceLocalException
* the service local exception
* @throws java.net.URISyntaxException
* the uRI syntax exception
*/
protected HttpWebRequest prepareHttpWebRequest()
throws ServiceLocalException, URISyntaxException {
try {
this. url = this.adjustServiceUriFromCredentials(this.getUrl());
} catch (Exception e) {
e.printStackTrace();
}
return this.prepareHttpWebRequestForUrl(url, this
.getAcceptGzipEncoding(), true);
}
/**
* Processes an HTTP error response.
*
* @param httpWebResponse
* The HTTP web response.
* @param webException
* The web exception
* @throws Exception
*/
@Override
protected void processHttpErrorResponse(HttpWebRequest httpWebResponse,
Exception webException) throws Exception {
this.internalProcessHttpErrorResponse(httpWebResponse, webException,
TraceFlags.EwsResponseHttpHeaders, TraceFlags.EwsResponse);
}
// Properties
/**
* Gets the URL of the Exchange Web Services.
*
* @return URL of the Exchange Web Services.
*/
public URI getUrl() {
return url;
}
/**
* Sets the URL of the Exchange Web Services.
*
* @param url
* URL of the Exchange Web Services.
*/
public void setUrl(URI url) {
this.url = url;
}
/**
* Gets the impersonated user id.
*
* @return the impersonated user id
*/
public ImpersonatedUserId getImpersonatedUserId() {
return impersonatedUserId;
}
/**
* Sets the impersonated user id.
*
* @param impersonatedUserId
* the new impersonated user id
*/
public void setImpersonatedUserId(ImpersonatedUserId impersonatedUserId) {
this.impersonatedUserId = impersonatedUserId;
}
/**
* Gets the preferred culture.
*
* @return the preferred culture
*/
public Locale getPreferredCulture() {
return preferredCulture;
}
/**
* Sets the preferred culture.
*
* @param preferredCulture
* the new preferred culture
*/
public void setPreferredCulture(Locale preferredCulture) {
this.preferredCulture = preferredCulture;
}
/**
* Gets the DateTime precision for DateTime values returned from Exchange
* Web Services.
*
* @return the DateTimePrecision
*/
public DateTimePrecision getDateTimePrecision() {
return this.dateTimePrecision;
}
/**
* Sets the DateTime precision for DateTime values
* Web Services.
*/
public void setDateTimePrecision(DateTimePrecision d) {
this.dateTimePrecision = d;
}
/**
* Sets the DateTime precision for DateTime values returned from Exchange
* Web Services.
*
* @param dateTimePrecision
* the new DateTimePrecision
*/
public void setPreferredCulture(DateTimePrecision dateTimePrecision) {
this.dateTimePrecision = dateTimePrecision;
}
/**
* Gets the file attachment content handler.
*
* @return the file attachment content handler
*/
public IFileAttachmentContentHandler getFileAttachmentContentHandler() {
return this.fileAttachmentContentHandler;
}
/**
* Sets the file attachment content handler.
*
* @param fileAttachmentContentHandler
* the new file attachment content handler
*/
public void setFileAttachmentContentHandler(
IFileAttachmentContentHandler fileAttachmentContentHandler) {
this.fileAttachmentContentHandler = fileAttachmentContentHandler;
}
/*
* Gets the time zone this service is scoped to.
*
* @return the unified messaging
*
public TimeZone getTimeZone() { return super.getTimeZone(); }
*/
/**
* Provides access to the Unified Messaging functionalities.
*
* @return the unified messaging
*/
public UnifiedMessaging getUnifiedMessaging() {
if (this.unifiedMessaging == null) {
this.unifiedMessaging = new UnifiedMessaging(this);
}
return this.unifiedMessaging;
}
/**
* Gets or sets a value indicating whether the AutodiscoverUrl method should
* perform SCP (Service Connection Point) record lookup when determining the
* Autodiscover service URL.
*
* @return enable scp lookup flag.
*/
public boolean getEnableScpLookup() {
return this.enableScpLookup;
}
public void setEnableScpLookup(boolean value) {
this.enableScpLookup = value;
}
/**
* Gets or sets a value indicating whether Exchange2007 compatibility mode
* is enabled. <remarks> In order to support E12 servers, the
* Exchange2007CompatibilityMode property can be used to indicate that we
* should use "Exchange2007" as the server version String rather than
* Exchange2007_SP1. </remarks>
*/
protected boolean getExchange2007CompatibilityMode() {
return this.exchange2007CompatibilityMode;
}
protected void setExchange2007CompatibilityMode(boolean value) {
this.exchange2007CompatibilityMode = value;
}
/**
* Retrieves the definitions of the specified server-side time zones.
*
* @param timeZoneIds
* the time zone ids
* @return A Collection containing the definitions of the specified time
* zones.
*/
public Collection<TimeZoneDefinition> getServerTimeZones(
Iterable<String> timeZoneIds) {
Date today = new Date();
Collection<TimeZoneDefinition> timeZoneList = new ArrayList<TimeZoneDefinition>();
for (String timeZoneId : timeZoneIds) {
TimeZoneDefinition timeZoneDefinition = new TimeZoneDefinition();
timeZoneList.add(timeZoneDefinition);
TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
timeZoneDefinition.id = timeZone.getID();
timeZoneDefinition.name = timeZone.getDisplayName(timeZone
.inDaylightTime(today), TimeZone.LONG);
/*
* String shortName =
* timeZone.getDisplayName(timeZone.inDaylightTime(today),
* TimeZone.SHORT); String longName =
* timeZone.getDisplayName(timeZone.inDaylightTime(today),
* TimeZone.LONG); int rawOffset = timeZone.getRawOffset(); int hour
* = rawOffset / (60*60*1000); int min = Math.abs(rawOffset /
* (60*1000)) % 60; boolean hasDST = timeZone.useDaylightTime();
* boolean inDST = timeZone.inDaylightTime(today);
*/
}
return timeZoneList;
}
/**
* Retrieves the definitions of all server-side time zones.
*
* @return A Collection containing the definitions of the specified time
* zones.
*/
public Collection<TimeZoneDefinition> getServerTimeZones() {
Date today = new Date();
Collection<TimeZoneDefinition> timeZoneList = new ArrayList<TimeZoneDefinition>();
for (String timeZoneId : TimeZone.getAvailableIDs()) {
TimeZoneDefinition timeZoneDefinition = new TimeZoneDefinition();
timeZoneList.add(timeZoneDefinition);
TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
timeZoneDefinition.id = timeZone.getID();
timeZoneDefinition.name = timeZone.getDisplayName(timeZone
.inDaylightTime(today), TimeZone.LONG);
}
return timeZoneList;
}
/*
* (non-Javadoc)
*
* @seemicrosoft.exchange.webservices.AutodiscoverRedirectionUrlInterface#
* autodiscoverRedirectionUrlValidationCallback(java.lang.String)
*/
public boolean autodiscoverRedirectionUrlValidationCallback(
String redirectionUrl) throws AutodiscoverLocalException {
return defaultAutodiscoverRedirectionUrlValidationCallback(redirectionUrl);
}
}
|
package net.spy.memcached.spring;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.ConnectionFactoryBuilder.Locator;
import net.spy.memcached.ConnectionFactoryBuilder.Protocol;
import net.spy.memcached.ConnectionObserver;
import net.spy.memcached.FailureMode;
import net.spy.memcached.HashAlgorithm;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.OperationFactory;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.ops.OperationQueueFactory;
import net.spy.memcached.transcoders.Transcoder;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
/**
* A Spring {@link FactoryBean} creating {@link MemcachedClient} instances.
* <p>
* Usage example:
*
* <pre>
* {@code
* <bean id="memcachedClient"
* class="net.spy.memcached.utils.MemcachedClientFactoryBean">
* <property name="servers" value="${pajamas.remoteHosts}"/>
* <property name="protocol" value="${pajamas.client.protocol}"/>
* <property name="transcoder"/>
* <bean class="net.rubyeye.xmemcached.transcoders.SerializingTranscoder"/>
* <property name="hashAlg" value="${pajamas.client.hashAlg}"/>
* <property name="locatorType" value="${pajamas.client.locatorType}"/>
* }
* </pre>
* </p>
*
* @author Eran Harel
*/
@SuppressWarnings("rawtypes")
public class MemcachedClientFactoryBean implements FactoryBean,
InitializingBean, DisposableBean {
private final ConnectionFactoryBuilder connectionFactoryBuilder =
new ConnectionFactoryBuilder();
private String servers;
private long shutdownTimeoutSeconds = 0;
private MemcachedClient client;
@Override
public Object getObject() throws Exception {
return client;
}
@Override
public Class<?> getObjectType() {
return MemcachedClient.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public void afterPropertiesSet() throws Exception {
client = new MemcachedClient(connectionFactoryBuilder.build(),
AddrUtil.getAddresses(servers));
}
@Override
public void destroy() throws Exception {
if(shutdownTimeoutSeconds > 0) {
client.shutdown(shutdownTimeoutSeconds, TimeUnit.SECONDS);
} else {
client.shutdown();
}
}
public void setServers(final String newServers) {
this.servers = newServers;
}
public void setAuthDescriptor(final AuthDescriptor to) {
connectionFactoryBuilder.setAuthDescriptor(to);
}
public void setDaemon(final boolean d) {
connectionFactoryBuilder.setDaemon(d);
}
public void setFailureMode(final FailureMode fm) {
connectionFactoryBuilder.setFailureMode(fm);
}
public void setHashAlg(final HashAlgorithm to) {
connectionFactoryBuilder.setHashAlg(to);
}
public void setInitialObservers(final Collection<ConnectionObserver> obs) {
connectionFactoryBuilder.setInitialObservers(obs);
}
public void setLocatorType(final Locator l) {
connectionFactoryBuilder.setLocatorType(l);
}
public void setMaxReconnectDelay(final long to) {
connectionFactoryBuilder.setMaxReconnectDelay(to);
}
public void setOpFact(final OperationFactory f) {
connectionFactoryBuilder.setOpFact(f);
}
public void setOpQueueFactory(final OperationQueueFactory q) {
connectionFactoryBuilder.setOpQueueFactory(q);
}
public void setOpQueueMaxBlockTime(final long t) {
connectionFactoryBuilder.setOpQueueMaxBlockTime(t);
}
public void setOpTimeout(final long t) {
connectionFactoryBuilder.setOpTimeout(t);
}
public void setProtocol(final Protocol prot) {
connectionFactoryBuilder.setProtocol(prot);
}
public void setReadBufferSize(final int to) {
connectionFactoryBuilder.setReadBufferSize(to);
}
public void setReadOpQueueFactory(final OperationQueueFactory q) {
connectionFactoryBuilder.setReadOpQueueFactory(q);
}
public void setShouldOptimize(final boolean o) {
connectionFactoryBuilder.setShouldOptimize(o);
}
public void setTimeoutExceptionThreshold(final int to) {
connectionFactoryBuilder.setTimeoutExceptionThreshold(to);
}
public void setTranscoder(final Transcoder<Object> t) {
connectionFactoryBuilder.setTranscoder(t);
}
public void setUseNagleAlgorithm(final boolean to) {
connectionFactoryBuilder.setUseNagleAlgorithm(to);
}
public void setWriteOpQueueFactory(final OperationQueueFactory q) {
connectionFactoryBuilder.setWriteOpQueueFactory(q);
}
/**
* The number of seconds to wait for connections to finish before shutting
* down the client.
*/
public void setShutdownTimeoutSeconds(long shutdownTimeoutSeconds) {
this.shutdownTimeoutSeconds = shutdownTimeoutSeconds;
}
}
|
package org.csanchez.jenkins.plugins.kubernetes;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import io.fabric8.kubernetes.client.utils.Serialization;
import org.apache.commons.lang.StringUtils;
import org.csanchez.jenkins.plugins.kubernetes.model.TemplateEnvVar;
import org.csanchez.jenkins.plugins.kubernetes.pod.retention.PodRetention;
import org.csanchez.jenkins.plugins.kubernetes.pod.yaml.YamlMergeStrategy;
import org.csanchez.jenkins.plugins.kubernetes.volumes.PodVolume;
import org.csanchez.jenkins.plugins.kubernetes.volumes.workspace.WorkspaceVolume;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import hudson.Extension;
import hudson.Util;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.model.DescriptorVisibilityFilter;
import hudson.model.Label;
import hudson.model.Node;
import hudson.model.Saveable;
import hudson.model.labels.LabelAtom;
import hudson.slaves.NodeProperty;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.KubernetesClient;
import jenkins.model.Jenkins;
/**
* Kubernetes Pod Template
*
* @author <a href="mailto:[email protected]">Nicolas De Loof</a>
*/
public class PodTemplate extends AbstractDescribableImpl<PodTemplate> implements Serializable, Saveable {
private static final long serialVersionUID = 3285310269140845583L;
private static final String FALLBACK_ARGUMENTS = "${computer.jnlpmac} ${computer.name}";
private static final String DEFAULT_ID = "jenkins/slave-default";
private static final Logger LOGGER = Logger.getLogger(PodTemplate.class.getName());
/**
* Connection timeout expiration in seconds, default to 100 seconds
*/
public static final Integer DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT = Integer
.getInteger(PodTemplate.class.getName() + ".connectionTimeout", 100);
private String inheritFrom;
private String name;
private String namespace;
private String image;
private boolean privileged;
private boolean capOnlyOnAlivePods;
private boolean alwaysPullImage;
private String command;
private String args;
private String remoteFs;
private int instanceCap = Integer.MAX_VALUE;
private int slaveConnectTimeout = DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT;
private int idleMinutes;
private int activeDeadlineSeconds;
private String label;
private String serviceAccount;
private String nodeSelector;
private Node.Mode nodeUsageMode = Node.Mode.EXCLUSIVE;
private String resourceRequestCpu;
private String resourceRequestMemory;
private String resourceLimitCpu;
private String resourceLimitMemory;
private boolean customWorkspaceVolumeEnabled;
private WorkspaceVolume workspaceVolume;
private final List<PodVolume> volumes = new ArrayList<PodVolume>();
private List<ContainerTemplate> containers = new ArrayList<ContainerTemplate>();
private List<TemplateEnvVar> envVars = new ArrayList<>();
private List<PodAnnotation> annotations = new ArrayList<PodAnnotation>();
private List<PodImagePullSecret> imagePullSecrets = new ArrayList<PodImagePullSecret>();
private PodTemplateToolLocation nodeProperties;
/**
* @deprecated Stored as a list of yaml fragments
*/
@Deprecated
private transient String yaml;
private List<String> yamls = new ArrayList<>();
public YamlMergeStrategy getYamlMergeStrategy() {
return yamlMergeStrategy;
}
@DataBoundSetter
public void setYamlMergeStrategy(YamlMergeStrategy yamlMergeStrategy) {
this.yamlMergeStrategy = yamlMergeStrategy;
}
private YamlMergeStrategy yamlMergeStrategy = YamlMergeStrategy.defaultStrategy();
public Pod getYamlsPod() {
return yamlMergeStrategy.merge(getYamls());
}
private Boolean showRawYaml;
@CheckForNull
private PodRetention podRetention = PodRetention.getPodTemplateDefault();
@DataBoundConstructor
public PodTemplate() {
}
public PodTemplate(PodTemplate from) {
this.setAnnotations(from.getAnnotations());
this.setContainers(from.getContainers());
this.setImagePullSecrets(from.getImagePullSecrets());
this.setInstanceCap(from.getInstanceCap());
this.setLabel(from.getLabel());
this.setName(from.getName());
this.setNamespace(from.getNamespace());
this.setInheritFrom(from.getInheritFrom());
this.setNodeSelector(from.getNodeSelector());
this.setNodeUsageMode(from.getNodeUsageMode());
this.setServiceAccount(from.getServiceAccount());
this.setSlaveConnectTimeout(from.getSlaveConnectTimeout());
this.setActiveDeadlineSeconds(from.getActiveDeadlineSeconds());
this.setVolumes(from.getVolumes());
this.setWorkspaceVolume(from.getWorkspaceVolume());
this.setYamls(from.getYamls());
this.setShowRawYaml(from.isShowRawYaml());
this.setNodeProperties(from.getNodeProperties());
this.setPodRetention(from.getPodRetention());
}
@Deprecated
public PodTemplate(String image, List<? extends PodVolume> volumes) {
this(null, image, volumes);
}
@Deprecated
PodTemplate(String name, String image, List<? extends PodVolume> volumes) {
this(name, volumes, Collections.emptyList());
if (image != null) {
getContainers().add(new ContainerTemplate(name, image));
}
}
@Restricted(NoExternalUse.class) // testing only
PodTemplate(String name, List<? extends PodVolume> volumes, List<? extends ContainerTemplate> containers) {
this.name = name;
this.volumes.addAll(volumes);
this.containers.addAll(containers);
}
private Optional<ContainerTemplate> getFirstContainer() {
return Optional.ofNullable(getContainers().isEmpty() ? null : getContainers().get(0));
}
public String getInheritFrom() {
return inheritFrom;
}
@DataBoundSetter
public void setInheritFrom(String inheritFrom) {
this.inheritFrom = inheritFrom;
}
@DataBoundSetter
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getNamespace() {
return namespace;
}
@DataBoundSetter
public void setNamespace(String namespace) {
this.namespace = namespace;
}
@Deprecated
public String getImage() {
return getFirstContainer().map(ContainerTemplate::getImage).orElse(null);
}
@Deprecated
@DataBoundSetter
public void setCommand(String command) {
getFirstContainer().ifPresent((i) -> i.setCommand(command));
}
@Deprecated
public String getCommand() {
return getFirstContainer().map(ContainerTemplate::getCommand).orElse(null);
}
@Deprecated
@DataBoundSetter
public void setArgs(String args) {
getFirstContainer().ifPresent((i) -> i.setArgs(args));
}
@Deprecated
public String getArgs() {
return getFirstContainer().map(ContainerTemplate::getArgs).orElse(null);
}
public String getDisplayName() {
return "Kubernetes Pod Template";
}
@DataBoundSetter
@Deprecated
public void setRemoteFs(String remoteFs) {
getFirstContainer().ifPresent((i) -> i.setWorkingDir(remoteFs));
}
@Deprecated
public String getRemoteFs() {
return getFirstContainer().map(ContainerTemplate::getWorkingDir).orElse(null);
}
public void setInstanceCap(int instanceCap) {
if (instanceCap < 0) {
this.instanceCap = Integer.MAX_VALUE;
} else {
this.instanceCap = instanceCap;
}
}
public int getInstanceCap() {
return instanceCap;
}
public void setSlaveConnectTimeout(int slaveConnectTimeout) {
if (slaveConnectTimeout <= 0) {
LOGGER.log(Level.WARNING, "Agent -> Jenkins connection timeout " +
"cannot be <= 0. Falling back to the default value: " +
DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT);
this.slaveConnectTimeout = DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT;
} else {
this.slaveConnectTimeout = slaveConnectTimeout;
}
}
public int getSlaveConnectTimeout() {
if (slaveConnectTimeout == 0)
return DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT;
return slaveConnectTimeout;
}
@DataBoundSetter
public void setInstanceCapStr(String instanceCapStr) {
if (StringUtils.isBlank(instanceCapStr)) {
setInstanceCap(Integer.MAX_VALUE);
} else {
setInstanceCap(Integer.parseInt(instanceCapStr));
}
}
public String getInstanceCapStr() {
if (getInstanceCap() == Integer.MAX_VALUE) {
return "";
} else {
return String.valueOf(instanceCap);
}
}
@DataBoundSetter
public void setSlaveConnectTimeoutStr(String slaveConnectTimeoutStr) {
if (StringUtils.isBlank(slaveConnectTimeoutStr)) {
setSlaveConnectTimeout(DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT);
} else {
setSlaveConnectTimeout(Integer.parseInt(slaveConnectTimeoutStr));
}
}
public String getSlaveConnectTimeoutStr() {
return String.valueOf(slaveConnectTimeout);
}
public void setIdleMinutes(int i) {
this.idleMinutes = i;
}
public int getIdleMinutes() {
return idleMinutes;
}
public void setActiveDeadlineSeconds(int i) {
this.activeDeadlineSeconds = i;
}
public int getActiveDeadlineSeconds() {
return activeDeadlineSeconds;
}
@DataBoundSetter
public void setIdleMinutesStr(String idleMinutes) {
if (StringUtils.isBlank(idleMinutes)) {
setIdleMinutes(0);
} else {
setIdleMinutes(Integer.parseInt(idleMinutes));
}
}
public String getIdleMinutesStr() {
if (getIdleMinutes() == 0) {
return "";
} else {
return String.valueOf(idleMinutes);
}
}
@DataBoundSetter
public void setActiveDeadlineSecondsStr(String activeDeadlineSeconds) {
if (StringUtils.isBlank(activeDeadlineSeconds)) {
setActiveDeadlineSeconds(0);
} else {
setActiveDeadlineSeconds(Integer.parseInt(activeDeadlineSeconds));
}
}
public String getActiveDeadlineSecondsStr() {
if (getActiveDeadlineSeconds() == 0) {
return "";
} else {
return String.valueOf(activeDeadlineSeconds);
}
}
public Set<LabelAtom> getLabelSet() {
return Label.parse(label);
}
public Map<String, String> getLabelsMap() {
Set<LabelAtom> labelSet = getLabelSet();
ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String> builder();
if (!labelSet.isEmpty()) {
for (LabelAtom label : labelSet) {
builder.put(label == null ? DEFAULT_ID : "jenkins/" + label.getName(), "true");
}
}
return builder.build();
}
@DataBoundSetter
public void setLabel(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
@DataBoundSetter
public void setNodeSelector(String nodeSelector) {
this.nodeSelector = nodeSelector;
}
public String getNodeSelector() {
return nodeSelector;
}
@DataBoundSetter
public void setNodeUsageMode(Node.Mode nodeUsageMode) {
this.nodeUsageMode = nodeUsageMode;
}
@DataBoundSetter
public void setNodeUsageMode(String nodeUsageMode) {
this.nodeUsageMode = Node.Mode.valueOf(nodeUsageMode);
}
public Node.Mode getNodeUsageMode() {
return nodeUsageMode;
}
@Deprecated
@DataBoundSetter
public void setPrivileged(boolean privileged) {
getFirstContainer().ifPresent((i) -> i.setPrivileged(privileged));
}
@Deprecated
public boolean isPrivileged() {
return getFirstContainer().map(ContainerTemplate::isPrivileged).orElse(false);
}
public String getServiceAccount() {
return serviceAccount;
}
@DataBoundSetter
public void setServiceAccount(String serviceAccount) {
this.serviceAccount = Util.fixEmpty(serviceAccount);
}
@Deprecated
@DataBoundSetter
public void setAlwaysPullImage(boolean alwaysPullImage) {
getFirstContainer().ifPresent((i) -> i.setAlwaysPullImage(alwaysPullImage));
}
@Deprecated
public boolean isAlwaysPullImage() {
return getFirstContainer().map(ContainerTemplate::isAlwaysPullImage).orElse(false);
}
@DataBoundSetter
@Deprecated
public void setCapOnlyOnAlivePods(boolean capOnlyOnAlivePods) {
this.capOnlyOnAlivePods = capOnlyOnAlivePods;
}
@Deprecated
public boolean isCapOnlyOnAlivePods() {
return capOnlyOnAlivePods;
}
public List<TemplateEnvVar> getEnvVars() {
if (envVars == null) {
return Collections.emptyList();
}
return envVars;
}
public void addEnvVars(List<TemplateEnvVar> envVars) {
if (envVars != null) {
this.envVars.addAll(envVars);
}
}
@DataBoundSetter
public void setEnvVars(List<TemplateEnvVar> envVars) {
if (envVars != null) {
this.envVars.clear();
this.addEnvVars(envVars);
}
}
public List<PodAnnotation> getAnnotations() {
if (annotations == null) {
return Collections.emptyList();
}
return annotations;
}
public void addAnnotations(List<PodAnnotation> annotations) {
this.annotations.addAll(annotations);
}
@DataBoundSetter
public void setAnnotations(List<PodAnnotation> annotations) {
if (annotations != null) {
this.annotations = new ArrayList<PodAnnotation>();
this.addAnnotations(annotations);
}
}
public List<PodImagePullSecret> getImagePullSecrets() {
return imagePullSecrets == null ? Collections.emptyList() : imagePullSecrets;
}
public void addImagePullSecrets(List<PodImagePullSecret> imagePullSecrets) {
this.imagePullSecrets.addAll(imagePullSecrets);
}
@DataBoundSetter
public void setImagePullSecrets(List<PodImagePullSecret> imagePullSecrets) {
if (imagePullSecrets != null) {
this.imagePullSecrets.clear();
this.addImagePullSecrets(imagePullSecrets);
}
}
@DataBoundSetter
public void setNodeProperties(List<? extends NodeProperty<?>> properties) {
this.getNodeProperties().clear();
this.getNodeProperties().addAll(properties);
}
@Nonnull
public PodTemplateToolLocation getNodeProperties(){
if( this.nodeProperties == null)
this.nodeProperties = new PodTemplateToolLocation(this);
return nodeProperties;
}
@Deprecated
public String getResourceRequestMemory() {
return getFirstContainer().map(ContainerTemplate::getResourceRequestMemory).orElse(null);
}
@Deprecated
@DataBoundSetter
public void setResourceRequestMemory(String resourceRequestMemory) {
getFirstContainer().ifPresent((i) -> i.setResourceRequestMemory(resourceRequestMemory));
}
@Deprecated
public String getResourceLimitCpu() {
return getFirstContainer().map(ContainerTemplate::getResourceLimitCpu).orElse(null);
}
@Deprecated
@DataBoundSetter
public void setResourceLimitCpu(String resourceLimitCpu) {
getFirstContainer().ifPresent((i) -> i.setResourceLimitCpu(resourceLimitCpu));
}
@Deprecated
public String getResourceLimitMemory() {
return getFirstContainer().map(ContainerTemplate::getResourceLimitMemory).orElse(null);
}
@Deprecated
@DataBoundSetter
public void setResourceLimitMemory(String resourceLimitMemory) {
getFirstContainer().ifPresent((i) -> i.setResourceLimitMemory(resourceLimitMemory));
}
@Deprecated
public String getResourceRequestCpu() {
return getFirstContainer().map(ContainerTemplate::getResourceRequestCpu).orElse(null);
}
@Deprecated
@DataBoundSetter
public void setResourceRequestCpu(String resourceRequestCpu) {
getFirstContainer().ifPresent((i) -> i.setResourceRequestCpu(resourceRequestCpu));
}
@DataBoundSetter
public void setVolumes(@Nonnull List<PodVolume> items) {
synchronized (this.volumes) {
this.volumes.clear();
this.volumes.addAll(items);
}
}
@Nonnull
public List<PodVolume> getVolumes() {
if (volumes == null) {
return Collections.emptyList();
}
return volumes;
}
public boolean isCustomWorkspaceVolumeEnabled() {
return customWorkspaceVolumeEnabled;
}
@DataBoundSetter
public void setCustomWorkspaceVolumeEnabled(boolean customWorkspaceVolumeEnabled) {
this.customWorkspaceVolumeEnabled = customWorkspaceVolumeEnabled;
}
public WorkspaceVolume getWorkspaceVolume() {
return workspaceVolume;
}
@DataBoundSetter
public void setWorkspaceVolume(WorkspaceVolume workspaceVolume) {
this.workspaceVolume = workspaceVolume;
}
@DataBoundSetter
public void setContainers(@Nonnull List<ContainerTemplate> items) {
synchronized (this.containers) {
this.containers.clear();
this.containers.addAll(items);
}
}
@Nonnull
public List<ContainerTemplate> getContainers() {
if (containers == null) {
return Collections.emptyList();
}
return containers;
}
/**
* @return The first yaml fragment for this pod template
*/
@Restricted(NoExternalUse.class) // Tests and UI
public String getYaml() {
return yamls == null || yamls.isEmpty() ? null : yamls.get(0);
}
@DataBoundSetter
public void setYaml(String yaml) {
String trimmed = Util.fixEmpty(yaml);
if (trimmed != null) {
this.yamls = Collections.singletonList(yaml);
} else {
this.yamls = Collections.emptyList();
}
}
@Nonnull
public List<String> getYamls() {
if (yamls ==null) {
return Collections.emptyList();
}
return yamls;
}
public void setYamls(List<String> yamls) {
if (yamls != null) {
List<String> ys = new ArrayList<>();
for (String y : yamls) {
String trimmed = Util.fixEmpty(y);
if (trimmed != null) {
ys.add(trimmed);
}
}
this.yamls = ys;
} else {
this.yamls = Collections.emptyList();
}
}
public PodRetention getPodRetention() {
return podRetention;
}
@DataBoundSetter
public void setPodRetention(PodRetention podRetention) {
if (podRetention == null) {
podRetention = PodRetention.getPodTemplateDefault();
}
this.podRetention = podRetention;
}
protected Object readResolve() {
if (containers == null) {
// upgrading from 0.8
containers = new ArrayList<>();
ContainerTemplate containerTemplate = new ContainerTemplate(KubernetesCloud.JNLP_NAME, this.image);
containerTemplate.setCommand(command);
containerTemplate.setArgs(Strings.isNullOrEmpty(args) ? FALLBACK_ARGUMENTS : args);
containerTemplate.setPrivileged(privileged);
containerTemplate.setAlwaysPullImage(alwaysPullImage);
containerTemplate.setEnvVars(envVars);
containerTemplate.setResourceRequestMemory(resourceRequestMemory);
containerTemplate.setResourceLimitCpu(resourceLimitCpu);
containerTemplate.setResourceLimitMemory(resourceLimitMemory);
containerTemplate.setResourceRequestCpu(resourceRequestCpu);
containerTemplate.setWorkingDir(remoteFs);
containers.add(containerTemplate);
}
if (podRetention == null) {
// various legacy paths for injecting pod templates can
// bypass the defaulting paths and the
// value can still be null, so check for it here so
// as to not blow up things like termination path
podRetention = PodRetention.getPodTemplateDefault();
}
if (annotations == null) {
annotations = new ArrayList<>();
}
if (yamls == null) {
yamls = new ArrayList<>();
}
if (yaml != null) {
yamls.add(yaml);
yaml = null;
}
// JENKINS-57116 remove empty items from yamls
if (!yamls.isEmpty() && StringUtils.isBlank(yamls.get(0))) {
setYamls(yamls);
}
if (showRawYaml == null) {
showRawYaml = Boolean.TRUE;
}
if (yamlMergeStrategy == null) {
yamlMergeStrategy = YamlMergeStrategy.defaultStrategy();
}
return this;
}
@Deprecated
public Pod build(KubernetesClient client, KubernetesSlave slave) {
return build(slave);
}
/**
* Build a Pod object from a PodTemplate
*
* @param slave
*/
public Pod build(KubernetesSlave slave) {
return new PodTemplateBuilder(this).withSlave(slave).build();
}
/**
* Use getDescriptionForLogging(KubernetesSlave) instead
* @deprecated Use {@link #getDescriptionForLogging(KubernetesSlave)} instead
*/
@Deprecated
public String getDescriptionForLogging() {
return getDescriptionForLogging(null);
}
public String getDescriptionForLogging(KubernetesSlave slave) {
return String.format("Agent specification [%s] (%s): %n%s",
getDisplayName(),
getLabel(),
getContainersDescriptionForLogging(slave));
}
public boolean isShowRawYaml() {
return showRawYaml == null ? true : showRawYaml.booleanValue();
}
@DataBoundSetter
public void setShowRawYaml(boolean showRawYaml) {
this.showRawYaml = Boolean.valueOf(showRawYaml);
}
private String getContainersDescriptionForLogging(KubernetesSlave slave) {
if (slave != null && isShowRawYaml()) {
return Serialization.asYaml(build(slave));
} else {
return StringUtils.EMPTY;
}
}
private void optionalField(StringBuilder builder, String label, String value) {
if (StringUtils.isNotBlank(value)) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(label).append(": ").append(value);
}
}
/**
* Empty implementation of Saveable interface. This interface is used for DescribableList implementation
*/
@Override
public void save() { }
@Extension
public static class DescriptorImpl extends Descriptor<PodTemplate> {
@Override
public String getDisplayName() {
return "Kubernetes Pod Template";
}
@SuppressWarnings("unused") // Used by jelly
@Restricted(DoNotUse.class) // Used by jelly
public List<? extends Descriptor> getEnvVarsDescriptors() {
return DescriptorVisibilityFilter.apply(null, Jenkins.getInstance().getDescriptorList(TemplateEnvVar.class));
}
@SuppressWarnings("unused") // Used by jelly
@Restricted(DoNotUse.class) // Used by jelly
public Descriptor getDefaultPodRetention() {
Jenkins jenkins = Jenkins.getInstanceOrNull();
if (jenkins == null) {
return null;
}
return jenkins.getDescriptor(PodRetention.getPodTemplateDefault().getClass());
}
@SuppressWarnings("unused") // Used by jelly
@Restricted(DoNotUse.class) // Used by jelly
public YamlMergeStrategy getDefaultYamlMergeStrategy() {
return YamlMergeStrategy.defaultStrategy();
}
}
@Override
public String toString() {
return "PodTemplate{" +
(inheritFrom == null ? "" : "inheritFrom='" + inheritFrom + '\'') +
(name == null ? "" : ", name='" + name + '\'') +
(namespace == null ? "" : ", namespace='" + namespace + '\'') +
(image == null ? "" : ", image='" + image + '\'') +
(!privileged ? "" : ", privileged=" + privileged) +
(!alwaysPullImage ? "" : ", alwaysPullImage=" + alwaysPullImage) +
(command == null ? "" : ", command='" + command + '\'') +
(args == null ? "" : ", args='" + args + '\'') +
(remoteFs == null ? "" : ", remoteFs='" + remoteFs + '\'') +
(instanceCap == Integer.MAX_VALUE ? "" : ", instanceCap=" + instanceCap) +
(slaveConnectTimeout == DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT ? "" : ", slaveConnectTimeout=" + slaveConnectTimeout) +
(idleMinutes == 0 ? "" : ", idleMinutes=" + idleMinutes) +
(activeDeadlineSeconds == 0 ? "" : ", activeDeadlineSeconds=" + activeDeadlineSeconds) +
(label == null ? "" : ", label='" + label + '\'') +
(serviceAccount == null ? "" : ", serviceAccount='" + serviceAccount + '\'') +
(nodeSelector == null ? "" : ", nodeSelector='" + nodeSelector + '\'') +
(nodeUsageMode == null ? "" : ", nodeUsageMode=" + nodeUsageMode) +
(resourceRequestCpu == null ? "" : ", resourceRequestCpu='" + resourceRequestCpu + '\'') +
(resourceRequestMemory == null ? "" : ", resourceRequestMemory='" + resourceRequestMemory + '\'') +
(resourceLimitCpu == null ? "" : ", resourceLimitCpu='" + resourceLimitCpu + '\'') +
(resourceLimitMemory == null ? "" : ", resourceLimitMemory='" + resourceLimitMemory + '\'') +
(!customWorkspaceVolumeEnabled ? "" : ", customWorkspaceVolumeEnabled=" + customWorkspaceVolumeEnabled) +
(workspaceVolume == null ? "" : ", workspaceVolume=" + workspaceVolume) +
(volumes == null || volumes.isEmpty() ? "" : ", volumes=" + volumes) +
(containers == null || containers.isEmpty() ? "" : ", containers=" + containers) +
(envVars == null || envVars.isEmpty() ? "" : ", envVars=" + envVars) +
(annotations == null || annotations.isEmpty() ? "" : ", annotations=" + annotations) +
(imagePullSecrets == null || imagePullSecrets.isEmpty() ? "" : ", imagePullSecrets=" + imagePullSecrets) +
(nodeProperties == null || nodeProperties.isEmpty() ? "" : ", nodeProperties=" + nodeProperties) +
(yamls == null || yamls.isEmpty() ? "" : ", yamls=" + yamls) +
'}';
}
}
|
package org.csanchez.jenkins.plugins.kubernetes;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import com.google.common.annotations.VisibleForTesting;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.model.DescriptorVisibilityFilter;
import hudson.model.Label;
import hudson.model.Node;
import hudson.model.Saveable;
import hudson.model.TaskListener;
import org.apache.commons.lang.StringUtils;
import org.csanchez.jenkins.plugins.kubernetes.model.TemplateEnvVar;
import org.csanchez.jenkins.plugins.kubernetes.pod.retention.PodRetention;
import org.csanchez.jenkins.plugins.kubernetes.pod.yaml.YamlMergeStrategy;
import org.csanchez.jenkins.plugins.kubernetes.volumes.PodVolume;
import org.csanchez.jenkins.plugins.kubernetes.volumes.workspace.WorkspaceVolume;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import hudson.Extension;
import hudson.Util;
import hudson.model.labels.LabelAtom;
import hudson.slaves.NodeProperty;
import hudson.util.XStream2;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.KubernetesClient;
import java.io.StringReader;
import jenkins.model.Jenkins;
/**
* Kubernetes Pod Template
*
* @author <a href="mailto:[email protected]">Nicolas De Loof</a>
*/
public class PodTemplate extends AbstractDescribableImpl<PodTemplate> implements Serializable, Saveable {
private static final long serialVersionUID = 3285310269140845583L;
private static final String FALLBACK_ARGUMENTS = "${computer.jnlpmac} ${computer.name}";
private static final String DEFAULT_ID = "jenkins/slave-default";
private static final Logger LOGGER = Logger.getLogger(PodTemplate.class.getName());
/**
* Connection timeout expiration in seconds, default to 100 seconds
*/
public static final Integer DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT = Integer
.getInteger(PodTemplate.class.getName() + ".connectionTimeout", 100);
private String inheritFrom;
private String name;
private String namespace;
private String image;
private boolean privileged;
private Long runAsUser;
private Long runAsGroup;
private boolean capOnlyOnAlivePods;
private boolean alwaysPullImage;
private String command;
private String args;
private String remoteFs;
private int instanceCap = Integer.MAX_VALUE;
private int slaveConnectTimeout = DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT;
private int idleMinutes;
private int activeDeadlineSeconds;
private String label;
private String serviceAccount;
private String nodeSelector;
private Node.Mode nodeUsageMode = Node.Mode.EXCLUSIVE;
private String resourceRequestCpu;
private String resourceRequestMemory;
private String resourceLimitCpu;
private String resourceLimitMemory;
private Boolean hostNetwork;
private WorkspaceVolume workspaceVolume = WorkspaceVolume.getDefault();
private final List<PodVolume> volumes = new ArrayList<PodVolume>();
private List<ContainerTemplate> containers = new ArrayList<ContainerTemplate>();
private List<TemplateEnvVar> envVars = new ArrayList<>();
private List<PodAnnotation> annotations = new ArrayList<PodAnnotation>();
private List<PodImagePullSecret> imagePullSecrets = new ArrayList<PodImagePullSecret>();
private PodTemplateToolLocation nodeProperties;
/**
* Persisted yaml fragment
*/
private String yaml;
/**
* List of yaml fragments used for transient pod templates. Never persisted
*/
private transient List<String> yamls;
public YamlMergeStrategy getYamlMergeStrategy() {
return yamlMergeStrategy;
}
@DataBoundSetter
public void setYamlMergeStrategy(YamlMergeStrategy yamlMergeStrategy) {
this.yamlMergeStrategy = yamlMergeStrategy;
}
private YamlMergeStrategy yamlMergeStrategy = YamlMergeStrategy.defaultStrategy();
public Pod getYamlsPod() {
return yamlMergeStrategy.merge(getYamls());
}
private Boolean showRawYaml;
/**
* Listener of the run that created this pod template, if applicable
*/
@CheckForNull
private transient TaskListener listener;
@CheckForNull
private PodRetention podRetention = PodRetention.getPodTemplateDefault();
@DataBoundConstructor
public PodTemplate() {
}
public PodTemplate(PodTemplate from) {
XStream2 xs = new XStream2();
xs.unmarshal(XStream2.getDefaultDriver().createReader(new StringReader(xs.toXML(from))), this);
this.yamls = from.yamls;
}
@Deprecated
public PodTemplate(String image, List<? extends PodVolume> volumes) {
this(null, image, volumes);
}
@Deprecated
PodTemplate(String name, String image, List<? extends PodVolume> volumes) {
this(name, volumes, Collections.emptyList());
if (image != null) {
getContainers().add(new ContainerTemplate(name, image));
}
}
@Restricted(NoExternalUse.class) // testing only
PodTemplate(String name, List<? extends PodVolume> volumes, List<? extends ContainerTemplate> containers) {
this.name = name;
this.volumes.addAll(volumes);
this.containers.addAll(containers);
}
private Optional<ContainerTemplate> getFirstContainer() {
return Optional.ofNullable(getContainers().isEmpty() ? null : getContainers().get(0));
}
public String getInheritFrom() {
return inheritFrom;
}
@DataBoundSetter
public void setInheritFrom(String inheritFrom) {
this.inheritFrom = inheritFrom;
}
@DataBoundSetter
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getNamespace() {
return namespace;
}
@DataBoundSetter
public void setNamespace(String namespace) {
this.namespace = namespace;
}
@Deprecated
public String getImage() {
return getFirstContainer().map(ContainerTemplate::getImage).orElse(null);
}
@Deprecated
@DataBoundSetter
public void setCommand(String command) {
getFirstContainer().ifPresent((i) -> i.setCommand(command));
}
@Deprecated
public String getCommand() {
return getFirstContainer().map(ContainerTemplate::getCommand).orElse(null);
}
@Deprecated
@DataBoundSetter
public void setArgs(String args) {
getFirstContainer().ifPresent((i) -> i.setArgs(args));
}
@Deprecated
public String getArgs() {
return getFirstContainer().map(ContainerTemplate::getArgs).orElse(null);
}
public String getDisplayName() {
return "Kubernetes Pod Template";
}
@DataBoundSetter
@Deprecated
public void setRemoteFs(String remoteFs) {
getFirstContainer().ifPresent((i) -> i.setWorkingDir(remoteFs));
}
@Deprecated
public String getRemoteFs() {
return getFirstContainer().map(ContainerTemplate::getWorkingDir).orElse(ContainerTemplate.DEFAULT_WORKING_DIR);
}
public void setInstanceCap(int instanceCap) {
if (instanceCap < 0) {
this.instanceCap = Integer.MAX_VALUE;
} else {
this.instanceCap = instanceCap;
}
}
public int getInstanceCap() {
return instanceCap;
}
public void setSlaveConnectTimeout(int slaveConnectTimeout) {
if (slaveConnectTimeout <= 0) {
LOGGER.log(Level.WARNING, "Agent -> Jenkins connection timeout " +
"cannot be <= 0. Falling back to the default value: " +
DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT);
this.slaveConnectTimeout = DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT;
} else {
this.slaveConnectTimeout = slaveConnectTimeout;
}
}
public int getSlaveConnectTimeout() {
if (slaveConnectTimeout == 0)
return DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT;
return slaveConnectTimeout;
}
@DataBoundSetter
public void setInstanceCapStr(String instanceCapStr) {
if (StringUtils.isBlank(instanceCapStr)) {
setInstanceCap(Integer.MAX_VALUE);
} else {
setInstanceCap(Integer.parseInt(instanceCapStr));
}
}
public String getInstanceCapStr() {
if (getInstanceCap() == Integer.MAX_VALUE) {
return "";
} else {
return String.valueOf(instanceCap);
}
}
@DataBoundSetter
public void setSlaveConnectTimeoutStr(String slaveConnectTimeoutStr) {
if (StringUtils.isBlank(slaveConnectTimeoutStr)) {
setSlaveConnectTimeout(DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT);
} else {
setSlaveConnectTimeout(Integer.parseInt(slaveConnectTimeoutStr));
}
}
public String getSlaveConnectTimeoutStr() {
return String.valueOf(slaveConnectTimeout);
}
public void setIdleMinutes(int i) {
this.idleMinutes = i;
}
public int getIdleMinutes() {
return idleMinutes;
}
public void setActiveDeadlineSeconds(int i) {
this.activeDeadlineSeconds = i;
}
public int getActiveDeadlineSeconds() {
return activeDeadlineSeconds;
}
@DataBoundSetter
public void setIdleMinutesStr(String idleMinutes) {
if (StringUtils.isBlank(idleMinutes)) {
setIdleMinutes(0);
} else {
setIdleMinutes(Integer.parseInt(idleMinutes));
}
}
public String getIdleMinutesStr() {
if (getIdleMinutes() == 0) {
return "";
} else {
return String.valueOf(idleMinutes);
}
}
@DataBoundSetter
public void setActiveDeadlineSecondsStr(String activeDeadlineSeconds) {
if (StringUtils.isBlank(activeDeadlineSeconds)) {
setActiveDeadlineSeconds(0);
} else {
setActiveDeadlineSeconds(Integer.parseInt(activeDeadlineSeconds));
}
}
public String getActiveDeadlineSecondsStr() {
if (getActiveDeadlineSeconds() == 0) {
return "";
} else {
return String.valueOf(activeDeadlineSeconds);
}
}
public Set<LabelAtom> getLabelSet() {
return Label.parse(label);
}
public Map<String, String> getLabelsMap() {
Set<LabelAtom> labelSet = getLabelSet();
ImmutableMap.Builder<String, String> builder = ImmutableMap.<String, String> builder();
if (!labelSet.isEmpty()) {
for (LabelAtom label : labelSet) {
builder.put(label == null ? DEFAULT_ID : "jenkins/" + label.getName(), "true");
}
}
return builder.build();
}
@DataBoundSetter
public void setLabel(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
@DataBoundSetter
public void setNodeSelector(String nodeSelector) {
this.nodeSelector = nodeSelector;
}
public String getNodeSelector() {
return nodeSelector;
}
@DataBoundSetter
public void setNodeUsageMode(Node.Mode nodeUsageMode) {
this.nodeUsageMode = nodeUsageMode;
}
@DataBoundSetter
public void setNodeUsageMode(String nodeUsageMode) {
this.nodeUsageMode = Node.Mode.valueOf(nodeUsageMode);
}
public Node.Mode getNodeUsageMode() {
return nodeUsageMode;
}
@Deprecated
@DataBoundSetter
public void setPrivileged(boolean privileged) {
getFirstContainer().ifPresent((i) -> i.setPrivileged(privileged));
}
@Deprecated
public boolean isPrivileged() {
return getFirstContainer().map(ContainerTemplate::isPrivileged).orElse(false);
}
@DataBoundSetter
public void setRunAsUser(String runAsUser) {
this.runAsUser = PodTemplateUtils.parseLong(runAsUser);
}
public String getRunAsUser() {
return runAsUser == null ? null : runAsUser.toString();
}
public Long getRunAsUserAsLong() {
return runAsUser;
}
@DataBoundSetter
public void setRunAsGroup(String runAsGroup) {
this.runAsGroup = PodTemplateUtils.parseLong(runAsGroup);
}
public String getRunAsGroup() {
return runAsGroup == null ? null : runAsGroup.toString();
}
public Long getRunAsGroupAsLong() {
return runAsGroup;
}
@DataBoundSetter
public void setHostNetwork(Boolean hostNetwork) {
this.hostNetwork = hostNetwork;
}
public Boolean isHostNetwork() {
return hostNetwork;
}
public boolean isHostNetworkSet() {
return hostNetwork != null;
}
public String getServiceAccount() {
return serviceAccount;
}
@DataBoundSetter
public void setServiceAccount(String serviceAccount) {
this.serviceAccount = Util.fixEmpty(serviceAccount);
}
@Deprecated
@DataBoundSetter
public void setAlwaysPullImage(boolean alwaysPullImage) {
getFirstContainer().ifPresent((i) -> i.setAlwaysPullImage(alwaysPullImage));
}
@Deprecated
public boolean isAlwaysPullImage() {
return getFirstContainer().map(ContainerTemplate::isAlwaysPullImage).orElse(false);
}
@DataBoundSetter
@Deprecated
public void setCapOnlyOnAlivePods(boolean capOnlyOnAlivePods) {
this.capOnlyOnAlivePods = capOnlyOnAlivePods;
}
@Deprecated
public boolean isCapOnlyOnAlivePods() {
return capOnlyOnAlivePods;
}
public List<TemplateEnvVar> getEnvVars() {
if (envVars == null) {
return Collections.emptyList();
}
return envVars;
}
public void addEnvVars(List<TemplateEnvVar> envVars) {
if (envVars != null) {
this.envVars.addAll(envVars);
}
}
@DataBoundSetter
public void setEnvVars(List<TemplateEnvVar> envVars) {
if (envVars != null) {
this.envVars.clear();
this.addEnvVars(envVars);
}
}
public List<PodAnnotation> getAnnotations() {
if (annotations == null) {
return Collections.emptyList();
}
return annotations;
}
public void addAnnotations(List<PodAnnotation> annotations) {
this.annotations.addAll(annotations);
}
@DataBoundSetter
public void setAnnotations(List<PodAnnotation> annotations) {
if (annotations != null) {
this.annotations = new ArrayList<PodAnnotation>();
this.addAnnotations(annotations);
}
}
public List<PodImagePullSecret> getImagePullSecrets() {
return imagePullSecrets == null ? Collections.emptyList() : imagePullSecrets;
}
public void addImagePullSecrets(List<PodImagePullSecret> imagePullSecrets) {
this.imagePullSecrets.addAll(imagePullSecrets);
}
@DataBoundSetter
public void setImagePullSecrets(List<PodImagePullSecret> imagePullSecrets) {
if (imagePullSecrets != null) {
this.imagePullSecrets.clear();
this.addImagePullSecrets(imagePullSecrets);
}
}
@DataBoundSetter
public void setNodeProperties(List<? extends NodeProperty<?>> properties) {
this.getNodeProperties().clear();
this.getNodeProperties().addAll(properties);
}
@Nonnull
public PodTemplateToolLocation getNodeProperties(){
if( this.nodeProperties == null)
this.nodeProperties = new PodTemplateToolLocation(this);
return nodeProperties;
}
@Deprecated
public String getResourceRequestMemory() {
return getFirstContainer().map(ContainerTemplate::getResourceRequestMemory).orElse(null);
}
@Deprecated
@DataBoundSetter
public void setResourceRequestMemory(String resourceRequestMemory) {
getFirstContainer().ifPresent((i) -> i.setResourceRequestMemory(resourceRequestMemory));
}
@Deprecated
public String getResourceLimitCpu() {
return getFirstContainer().map(ContainerTemplate::getResourceLimitCpu).orElse(null);
}
@Deprecated
@DataBoundSetter
public void setResourceLimitCpu(String resourceLimitCpu) {
getFirstContainer().ifPresent((i) -> i.setResourceLimitCpu(resourceLimitCpu));
}
@Deprecated
public String getResourceLimitMemory() {
return getFirstContainer().map(ContainerTemplate::getResourceLimitMemory).orElse(null);
}
@Deprecated
@DataBoundSetter
public void setResourceLimitMemory(String resourceLimitMemory) {
getFirstContainer().ifPresent((i) -> i.setResourceLimitMemory(resourceLimitMemory));
}
@Deprecated
public String getResourceRequestCpu() {
return getFirstContainer().map(ContainerTemplate::getResourceRequestCpu).orElse(null);
}
@Deprecated
@DataBoundSetter
public void setResourceRequestCpu(String resourceRequestCpu) {
getFirstContainer().ifPresent((i) -> i.setResourceRequestCpu(resourceRequestCpu));
}
@DataBoundSetter
public void setVolumes(@Nonnull List<PodVolume> items) {
synchronized (this.volumes) {
this.volumes.clear();
this.volumes.addAll(items);
}
}
@Nonnull
public List<PodVolume> getVolumes() {
if (volumes == null) {
return Collections.emptyList();
}
return volumes;
}
@Nonnull
public WorkspaceVolume getWorkspaceVolume() {
return workspaceVolume;
}
@DataBoundSetter
public void setWorkspaceVolume(WorkspaceVolume workspaceVolume) {
this.workspaceVolume = workspaceVolume;
}
@DataBoundSetter
public void setContainers(@Nonnull List<ContainerTemplate> items) {
synchronized (this.containers) {
this.containers.clear();
this.containers.addAll(items);
}
}
@Nonnull
public List<ContainerTemplate> getContainers() {
if (containers == null) {
return Collections.emptyList();
}
return containers;
}
/**
* @return The persisted yaml fragment
*/
@Restricted(NoExternalUse.class) // Tests and UI
public String getYaml() {
return yaml;
}
@DataBoundSetter
public void setYaml(String yaml) {
this.yaml = Util.fixEmpty(yaml);
}
@Nonnull
public List<String> getYamls() {
if (yamls == null || yamls.isEmpty()) {
if (yaml != null) {
return Collections.singletonList(yaml);
} else {
return Collections.emptyList();
}
}
return yamls;
}
@VisibleForTesting
@Restricted(NoExternalUse.class)
List<String> _getYamls() {
return yamls;
}
public void setYamls(List<String> yamls) {
if (yamls != null) {
List<String> ys = new ArrayList<>();
for (String y : yamls) {
String trimmed = Util.fixEmpty(y);
if (trimmed != null) {
ys.add(trimmed);
}
}
this.yamls = ys;
} else {
this.yamls = Collections.emptyList();
}
}
public PodRetention getPodRetention() {
return podRetention;
}
@DataBoundSetter
public void setPodRetention(PodRetention podRetention) {
if (podRetention == null) {
podRetention = PodRetention.getPodTemplateDefault();
}
this.podRetention = podRetention;
}
@Nonnull
public TaskListener getListener() {
return listener == null ? TaskListener.NULL : listener;
}
public void setListener(@CheckForNull TaskListener listener) {
this.listener = listener;
}
protected Object readResolve() {
if (containers == null) {
// upgrading from 0.8
containers = new ArrayList<>();
ContainerTemplate containerTemplate = new ContainerTemplate(KubernetesCloud.JNLP_NAME, this.image);
containerTemplate.setCommand(command);
containerTemplate.setArgs(Strings.isNullOrEmpty(args) ? FALLBACK_ARGUMENTS : args);
containerTemplate.setPrivileged(privileged);
containerTemplate.setRunAsUser(getRunAsUser());
containerTemplate.setRunAsGroup(getRunAsGroup());
containerTemplate.setAlwaysPullImage(alwaysPullImage);
containerTemplate.setEnvVars(envVars);
containerTemplate.setResourceRequestMemory(resourceRequestMemory);
containerTemplate.setResourceLimitCpu(resourceLimitCpu);
containerTemplate.setResourceLimitMemory(resourceLimitMemory);
containerTemplate.setResourceRequestCpu(resourceRequestCpu);
containerTemplate.setWorkingDir(remoteFs);
containers.add(containerTemplate);
}
if (podRetention == null) {
// various legacy paths for injecting pod templates can
// bypass the defaulting paths and the
// value can still be null, so check for it here so
// as to not blow up things like termination path
podRetention = PodRetention.getPodTemplateDefault();
}
if (workspaceVolume == null) {
workspaceVolume = WorkspaceVolume.getDefault();
}
if (annotations == null) {
annotations = new ArrayList<>();
}
// Sanitize empty values
yaml = Util.fixEmpty(yaml);
if (yamls != null) {
// JENKINS-57116 Sanitize empty values
setYamls(yamls);
// Migration from storage in yamls field
if (!yamls.isEmpty()) {
if (yamls.size() > 1) {
LOGGER.log(Level.WARNING, "Found several persisted YAML fragments in pod template " + name + ". Only the first fragment will be considered, others will be ignored.");
}
yaml = yamls.get(0);
}
yamls = null;
}
if (yamlMergeStrategy == null) {
yamlMergeStrategy = YamlMergeStrategy.defaultStrategy();
}
return this;
}
@Deprecated
public Pod build(KubernetesClient client, KubernetesSlave slave) {
return build(slave);
}
/**
* Build a Pod object from a PodTemplate
*
* @param slave
*/
public Pod build(KubernetesSlave slave) {
return new PodTemplateBuilder(this).withSlave(slave).build();
}
/**
* @deprecated Use {@code Serialization.asYaml(build(KubernetesSlave))} instead.
*/
@Deprecated
public String getDescriptionForLogging() {
return String.format("Agent specification [%s] (%s): %n%s",
getDisplayName(),
getLabel(),
getContainersDescriptionForLogging());
}
boolean isShowRawYamlSet() {
return showRawYaml != null;
}
public boolean isShowRawYaml() {
return isShowRawYamlSet() ? showRawYaml.booleanValue() : true;
}
@DataBoundSetter
public void setShowRawYaml(boolean showRawYaml) {
this.showRawYaml = Boolean.valueOf(showRawYaml);
}
private String getContainersDescriptionForLogging() {
List<ContainerTemplate> containers = getContainers();
StringBuilder sb = new StringBuilder();
for (ContainerTemplate ct : containers) {
sb.append("* [").append(ct.getName()).append("] ").append(ct.getImage());
StringBuilder optional = new StringBuilder();
optionalField(optional, "resourceRequestCpu", ct.getResourceRequestCpu());
optionalField(optional, "resourceRequestMemory", ct.getResourceRequestMemory());
optionalField(optional, "resourceLimitCpu", ct.getResourceLimitCpu());
optionalField(optional, "resourceLimitMemory", ct.getResourceLimitMemory());
if (optional.length() > 0) {
sb.append("(").append(optional).append(")");
}
sb.append("\n");
}
if (isShowRawYaml()) {
for (String yaml : getYamls()) {
sb.append("yaml:\n")
.append(yaml)
.append("\n");
}
}
return sb.toString();
}
private void optionalField(StringBuilder builder, String label, String value) {
if (StringUtils.isNotBlank(value)) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(label).append(": ").append(value);
}
}
/**
* Empty implementation of Saveable interface. This interface is used for DescribableList implementation
*/
@Override
public void save() { }
@Extension
public static class DescriptorImpl extends Descriptor<PodTemplate> {
@Override
public String getDisplayName() {
return "Kubernetes Pod Template";
}
@SuppressWarnings("unused") // Used by jelly
@Restricted(DoNotUse.class) // Used by jelly
public List<? extends Descriptor> getEnvVarsDescriptors() {
return DescriptorVisibilityFilter.apply(null, Jenkins.getInstance().getDescriptorList(TemplateEnvVar.class));
}
@SuppressWarnings("unused") // Used by jelly
@Restricted(DoNotUse.class) // Used by jelly
public WorkspaceVolume getDefaultWorkspaceVolume() {
return WorkspaceVolume.getDefault();
}
@SuppressWarnings("unused") // Used by jelly
@Restricted(DoNotUse.class) // Used by jelly
public Descriptor getDefaultPodRetention() {
return Jenkins.get().getDescriptor(PodRetention.getPodTemplateDefault().getClass());
}
@SuppressWarnings("unused") // Used by jelly
@Restricted(DoNotUse.class) // Used by jelly
public YamlMergeStrategy getDefaultYamlMergeStrategy() {
return YamlMergeStrategy.defaultStrategy();
}
}
@Override
public String toString() {
return "PodTemplate{" +
(inheritFrom == null ? "" : "inheritFrom='" + inheritFrom + '\'') +
(name == null ? "" : ", name='" + name + '\'') +
(namespace == null ? "" : ", namespace='" + namespace + '\'') +
(image == null ? "" : ", image='" + image + '\'') +
(!privileged ? "" : ", privileged=" + privileged) +
(runAsUser == null ? "" : ", runAsUser=" + runAsUser) +
(runAsGroup == null ? "" : ", runAsGroup=" + runAsGroup) +
(!isHostNetworkSet() ? "" : ", hostNetwork=" + hostNetwork) +
(!alwaysPullImage ? "" : ", alwaysPullImage=" + alwaysPullImage) +
(command == null ? "" : ", command='" + command + '\'') +
(args == null ? "" : ", args='" + args + '\'') +
(remoteFs == null ? "" : ", remoteFs='" + remoteFs + '\'') +
(instanceCap == Integer.MAX_VALUE ? "" : ", instanceCap=" + instanceCap) +
(slaveConnectTimeout == DEFAULT_SLAVE_JENKINS_CONNECTION_TIMEOUT ? "" : ", slaveConnectTimeout=" + slaveConnectTimeout) +
(idleMinutes == 0 ? "" : ", idleMinutes=" + idleMinutes) +
(activeDeadlineSeconds == 0 ? "" : ", activeDeadlineSeconds=" + activeDeadlineSeconds) +
(label == null ? "" : ", label='" + label + '\'') +
(serviceAccount == null ? "" : ", serviceAccount='" + serviceAccount + '\'') +
(nodeSelector == null ? "" : ", nodeSelector='" + nodeSelector + '\'') +
(nodeUsageMode == null ? "" : ", nodeUsageMode=" + nodeUsageMode) +
(resourceRequestCpu == null ? "" : ", resourceRequestCpu='" + resourceRequestCpu + '\'') +
(resourceRequestMemory == null ? "" : ", resourceRequestMemory='" + resourceRequestMemory + '\'') +
(resourceLimitCpu == null ? "" : ", resourceLimitCpu='" + resourceLimitCpu + '\'') +
(resourceLimitMemory == null ? "" : ", resourceLimitMemory='" + resourceLimitMemory + '\'') +
", workspaceVolume=" + workspaceVolume +
(volumes == null || volumes.isEmpty() ? "" : ", volumes=" + volumes) +
(containers == null || containers.isEmpty() ? "" : ", containers=" + containers) +
(envVars == null || envVars.isEmpty() ? "" : ", envVars=" + envVars) +
(annotations == null || annotations.isEmpty() ? "" : ", annotations=" + annotations) +
(imagePullSecrets == null || imagePullSecrets.isEmpty() ? "" : ", imagePullSecrets=" + imagePullSecrets) +
(nodeProperties == null || nodeProperties.isEmpty() ? "" : ", nodeProperties=" + nodeProperties) +
(yamls == null || yamls.isEmpty() ? "" : ", yamls=" + yamls) +
'}';
}
}
|
package org.minimalj.frontend.form.element;
import java.lang.annotation.Annotation;
import org.minimalj.model.annotation.Size;
import org.minimalj.model.properties.VirtualProperty;
/**
* Produces an empty padding field in forms. Please don't overuse this or
* try to be clever on layouting.
*
*/
public class EmptyFormElement extends TextFormElement {
private static final EmptyProperty EMPTY_PROPERTY = new EmptyProperty();
public EmptyFormElement() {
super(EMPTY_PROPERTY);
}
@Override
public String getCaption() {
return null;
}
private static class EmptyProperty extends VirtualProperty implements Size {
@Override
public String getName() {
return ""; // null could cause NPE
}
@Override
public Class<?> getClazz() {
return null;
}
@Override
public Object getValue(Object object) {
return null;
}
@Override
public void setValue(Object object, Object value) {
// ignored
}
@Override
public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
if (annotationClass == Size.class) {
return (T) this;
}
return super.getAnnotation(annotationClass);
}
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
@Override
public int value() {
return 0;
}
}
}
|
package org.nebulostore.dfuntesting;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.LinkedList;
import java.util.NoSuchElementException;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Factory of {@link LocalEnvironment}.
*
* This factory uses {@link Configuration} to specify environment configuration.
* Configuration uses following fields:
* <ul>
* <li> environment-count - Number of local environments to create. </li>
* <li> dir-prefix - Temporary directory prefix used for creating local
* environment in system's temporary directory. </li>
* </ul>
*
* @author Grzegorz Milka
*/
public class LocalEnvironmentFactory implements EnvironmentFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(LocalEnvironmentFactory.class);
private static final String XML_ENV_CNT_FIELD = "environment-count";
private static final String XML_ENV_DIR_FIELD = "dir-prefix";
private static final String ENV_CONFIG_ROOT_DIR = "root-dir";
private static final String DEFAULT_DIR_PREFIX = "dfuntesting";
private final Configuration mConfig;
public LocalEnvironmentFactory(Configuration config) {
mConfig = config;
}
@Override
public Collection<Environment> createEnvironments() throws IOException {
LOGGER.info("createEnvironments()");
int count = mConfig.getInteger(XML_ENV_CNT_FIELD, 0);
if (count <= 0) {
throw new IllegalArgumentException(
"Number of environments has not been provided or was invalid.");
}
String dirPrefix = mConfig.getString(XML_ENV_DIR_FIELD, DEFAULT_DIR_PREFIX);
Collection<Environment> environments = new LinkedList<>();
for (int envIdx = 0; envIdx < count; ++envIdx) {
Path tempDirPath;
tempDirPath = Files.createTempDirectory(dirPrefix);
LocalEnvironment env = new LocalEnvironment(envIdx, tempDirPath);
env.setProperty(ENV_CONFIG_ROOT_DIR, tempDirPath);
environments.add(env);
}
return environments;
}
@Override
public void destroyEnvironments(Collection<Environment> envs) {
LOGGER.info("destroyEnvironments()");
for (Environment env: envs) {
Path dirPath;
try {
dirPath = (Path) env.getProperty(ENV_CONFIG_ROOT_DIR);
} catch (ClassCastException | NoSuchElementException e) {
LOGGER.error("Could not destroy environment.", e);
continue;
}
FileUtils.deleteQuietly(dirPath.toFile());
}
}
}
|
package ceylon.language;
import static com.redhat.ceylon.compiler.java.Util.toInt;
import static com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor.intersection;
import static java.lang.System.arraycopy;
import static java.util.Arrays.copyOfRange;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import ceylon.language.impl.BaseIterable;
import ceylon.language.impl.BaseIterator;
import ceylon.language.impl.BaseList;
import ceylon.language.impl.rethrow_;
import ceylon.language.meta.declaration.ClassDeclaration;
import ceylon.language.meta.declaration.GenericDeclaration;
import ceylon.language.meta.declaration.ValueDeclaration;
import ceylon.language.serialization.Deconstructed;
import ceylon.language.serialization.Deconstructor;
import com.redhat.ceylon.compiler.java.Util;
import com.redhat.ceylon.compiler.java.language.AbstractArrayIterable;
import com.redhat.ceylon.compiler.java.metadata.Annotation;
import com.redhat.ceylon.compiler.java.metadata.Annotations;
import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Class;
import com.redhat.ceylon.compiler.java.metadata.Defaulted;
import com.redhat.ceylon.compiler.java.metadata.FunctionalParameter;
import com.redhat.ceylon.compiler.java.metadata.Ignore;
import com.redhat.ceylon.compiler.java.metadata.Name;
import com.redhat.ceylon.compiler.java.metadata.SatisfiedTypes;
import com.redhat.ceylon.compiler.java.metadata.Transient;
import com.redhat.ceylon.compiler.java.metadata.TypeInfo;
import com.redhat.ceylon.compiler.java.metadata.TypeParameter;
import com.redhat.ceylon.compiler.java.metadata.TypeParameters;
import com.redhat.ceylon.compiler.java.runtime.metamodel.Metamodel;
import com.redhat.ceylon.compiler.java.runtime.model.TypeDescriptor;
import com.redhat.ceylon.compiler.java.runtime.serialization.$Serialization$;
import com.redhat.ceylon.compiler.java.runtime.serialization.Serializable;
@Ceylon(major = 7)
@Class(extendsType="ceylon.language::Basic")
@TypeParameters(@TypeParameter(value = "Element"))
@SatisfiedTypes({
"ceylon.language::List<Element>",
"ceylon.language::Ranged<ceylon.language::Integer,Element,ceylon.language::Array<Element>>"
})
public final class Array<Element>
extends BaseList<Element>
implements List<Element>, Serializable {
private static final Finished FIN = finished_.get_();
private static final java.lang.Object[] EMPTY_ARRAY = new java.lang.Object[0];
private static final java.lang.String[] EMPTY_STRING_ARRAY = new java.lang.String[0];
private static final boolean[] EMPTY_BOOLEAN_ARRAY = new boolean[0];
private static final int[] EMPTY_INT_ARRAY = new int[0];
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
private static final double[] EMPTY_DOUBLE_ARRAY = new double[0];
private static final long[] EMPTY_LONG_ARRAY = new long[0];
/** The array, could be Object[], int[], boolean[] etc. Never null. */
private final java.lang.Object array;
/** The array if it's an Object[], otherwise null */
private final java.lang.Object[] objectArray;
/** The array if it's a String[], otherwise null */
private final java.lang.String[] stringArray;
/** The array if it's a long[], otherwise null */
private final long[] longArray;
/** The array if it's a double[], otherwise null */
private final double[] doubleArray;
/** The array if it's a boolean[], otherwise null */
private final boolean[] booleanArray;
/** The array if it's an int[], otherwise null */
private final int[] intArray;
/** The array if it's a byte[], otherwise null */
private final byte[] byteArray;
/** The array.length, cached for speed */
private final int size;
/** The reified element type */
private final TypeDescriptor $reifiedElement;
/** The element type, for switching */
private final ArrayType elementType;
@Ignore
public Array(final TypeDescriptor $reifiedElement,
int size, Element element) {
this($reifiedElement,
createArrayWithElement($reifiedElement, size, element));
}
public Array(@Ignore final TypeDescriptor $reifiedElement,
@Name("elements")
@TypeInfo("ceylon.language::Iterable<Element,ceylon.language::Null>")
final ceylon.language.Iterable<? extends Element,?> elements) {
this($reifiedElement,
createArrayFromIterable($reifiedElement, elements));
}
@SuppressWarnings("unchecked")
private static <Element> java.lang.Object createArrayFromIterable(
final TypeDescriptor $reifiedElement,
final Iterable<? extends Element,?> elements) {
if (elements instanceof List) {
return createArrayFromList($reifiedElement, (List<? extends Element>) elements);
}
final ArrayList<Element> list = new ArrayList<Element>();
Iterator<?> iterator = elements.iterator();
java.lang.Object elem;
while ((elem=iterator.next())!=FIN) {
list.add((Element) elem);
}
final int size = list.size();
switch (elementType($reifiedElement)) {
case CeylonString:
//note: we don't unbox strings in an Array<String?>
// because it would break javaObjectArray()
java.lang.String[] stringArray = new java.lang.String[size];
for (int i=0; i<size; i++) {
String string = (String) list.get(i);
stringArray[i] = string==null ? null : string.value;
}
return stringArray;
case CeylonInteger:
long[] longPrecisionArray = new long[size];
for (int i=0; i<size; i++) {
longPrecisionArray[i] = ((Integer) list.get(i)).value;
}
return longPrecisionArray;
case CeylonFloat:
double[] doublePrecisionArray = new double[size];
for (int i=0; i<size; i++) {
doublePrecisionArray[i] = ((Float) list.get(i)).value;
}
return doublePrecisionArray;
case CeylonCharacter:
int[] codepointArray = new int[size];
for (int i=0; i<size; i++) {
codepointArray[i] = ((Character) list.get(i)).codePoint;
}
return codepointArray;
case CeylonBoolean:
boolean[] boolArray = new boolean[size];
for (int i=0; i<size; i++) {
boolArray[i] = ((Boolean) list.get(i)).booleanValue();
}
return boolArray;
case CeylonByte:
byte[] bitsArray = new byte[size];
for (int i=0; i<size; i++) {
bitsArray[i] = ((Byte) list.get(i)).value;
}
return bitsArray;
case JavaBoolean:
boolean[] booleanArray = new boolean[size];
for (int i=0; i<size; i++) {
booleanArray[i] = (java.lang.Boolean) list.get(i);
}
return booleanArray;
case JavaCharacter:
char[] charArray = new char[size];
for (int i=0; i<size; i++) {
charArray[i] = (java.lang.Character) list.get(i);
}
return charArray;
case JavaFloat:
float[] floatArray = new float[size];
for (int i=0; i<size; i++) {
floatArray[i] = (java.lang.Float) list.get(i);
}
return floatArray;
case JavaDouble:
double[] doubleArray = new double[size];
for (int i=0; i<size; i++) {
doubleArray[i] = (java.lang.Double) list.get(i);
}
return doubleArray;
case JavaByte:
byte[] byteArray = new byte[size];
for (int i=0; i<size; i++) {
byteArray[i] = (java.lang.Byte) list.get(i);
}
return byteArray;
case JavaShort:
short[] shortArray = new short[size];
for (int i=0; i<size; i++) {
shortArray[i] = (java.lang.Short) list.get(i);
}
return shortArray;
case JavaInteger:
int[] intArray = new int[size];
for (int i=0; i<size; i++) {
intArray[i] = (java.lang.Integer) list.get(i);
}
return intArray;
case JavaLong:
long[] longArray = new long[size];
for (int i=0; i<size; i++) {
longArray[i] =(java.lang.Long) list.get(i);
}
return longArray;
default:
java.lang.Class<?> clazz =
$reifiedElement.getArrayElementClass();
java.lang.Object[] array = (java.lang.Object[])
java.lang.reflect.Array.newInstance(clazz, size);
for (int i=0; i<size; i++) {
array[i] = list.get(i);
}
return array;
}
}
private static <Element> java.lang.Object createArrayFromList(
final TypeDescriptor $reifiedElement,
final List<? extends Element> elements) {
if (elements instanceof Array) {
return createArrayFromArray($reifiedElement,
(Array<? extends Element>) elements);
}
int size = Util.toInt(elements.getSize());
if (elements instanceof ceylon.language.String
&& !$reifiedElement.containsNull()) {
int[] array = new int[size];
java.lang.String string = elements.toString();
for (int i=0, offset = 0; i<size; i++) {
int codePoint = string.codePointAt(offset);
offset += java.lang.Character.charCount(codePoint);
array[i] = codePoint;
}
return array;
}
switch (elementType($reifiedElement)) {
case CeylonString:
//note: we don't unbox strings in an Array<String?>
// because it would break javaObjectArray()
java.lang.String[] stringArray = new java.lang.String[size];
for (int i=0; i<size; i++) {
String string = (String) elements.getFromFirst(i);
stringArray[i] = string==null ? null : string.value;
}
return stringArray;
case CeylonInteger:
long[] longPrecisionArray = new long[size];
for (int i=0; i<size; i++) {
Integer e = (Integer) elements.getFromFirst(i);
longPrecisionArray[i] = e.value;
}
return longPrecisionArray;
case CeylonFloat:
double[] doublePrecisionArray = new double[size];
for (int i=0; i<size; i++) {
Float e = (Float) elements.getFromFirst(i);
doublePrecisionArray[i] = e.value;
}
return doublePrecisionArray;
case CeylonCharacter:
int[] codepointArray = new int[size];
for (int i=0; i<size; i++) {
Character e = (Character) elements.getFromFirst(i);
codepointArray[i] = e.codePoint;
}
return codepointArray;
case CeylonBoolean:
boolean[] boolArray = new boolean[size];
for (int i=0; i<size; i++) {
Boolean e = (Boolean) elements.getFromFirst(i);
boolArray[i] = e.booleanValue();
}
return boolArray;
case CeylonByte:
byte[] bitsArray = new byte[size];
for (int i=0; i<size; i++) {
Byte e = (Byte) elements.getFromFirst(i);
bitsArray[i] = e.value;
}
return bitsArray;
case JavaBoolean:
boolean[] booleanArray = new boolean[size];
for (int i=0; i<size; i++) {
booleanArray[i] = (java.lang.Boolean)
elements.getFromFirst(i);
}
return booleanArray;
case JavaCharacter:
char[] charArray = new char[size];
for (int i=0; i<size; i++) {
charArray[i] = (java.lang.Character)
elements.getFromFirst(i);
}
return charArray;
case JavaFloat:
float[] floatArray = new float[size];
for (int i=0; i<size; i++) {
floatArray[i] = (java.lang.Float)
elements.getFromFirst(i);
}
return floatArray;
case JavaDouble:
double[] doubleArray = new double[size];
for (int i=0; i<size; i++) {
doubleArray[i] = (java.lang.Double)
elements.getFromFirst(i);
}
return doubleArray;
case JavaByte:
byte[] byteArray = new byte[size];
for (int i=0; i<size; i++) {
byteArray[i] = (java.lang.Byte)
elements.getFromFirst(i);
}
return byteArray;
case JavaShort:
short[] shortArray = new short[size];
for (int i=0; i<size; i++) {
shortArray[i] = (java.lang.Short)
elements.getFromFirst(i);
}
return shortArray;
case JavaInteger:
int[] intArray = new int[size];
for (int i=0; i<size; i++) {
intArray[i] = (java.lang.Integer)
elements.getFromFirst(i);
}
return intArray;
case JavaLong:
long[] longArray = new long[size];
for (int i=0; i<size; i++) {
longArray[i] = (java.lang.Long)
elements.getFromFirst(i);
}
return longArray;
default:
java.lang.Class<?> clazz =
$reifiedElement.getArrayElementClass();
java.lang.Object[] objectArray = (java.lang.Object[])
java.lang.reflect.Array.newInstance(clazz, size);
for (int i=0; i<size; i++) {
objectArray[i] = elements.getFromFirst(i);
}
return objectArray;
}
}
private static <Element> java.lang.Object createArrayFromArray(
final TypeDescriptor $reifiedElement,
final Array<? extends Element> elements) {
final int size = Util.toInt(elements.getSize());
final java.lang.Class<?> clazz =
$reifiedElement.getArrayElementClass();
switch (elementType($reifiedElement)) {
case CeylonString:
//note: we don't unbox strings in an Array<String?>
// because it would break javaObjectArray()
java.lang.String[] stringArray = new java.lang.String[size];
arraycopy(elements.array, 0, stringArray, 0, size);
return stringArray;
case CeylonInteger:
long[] longPrecisionArray = new long[size];
arraycopy(elements.array, 0, longPrecisionArray, 0, size);
return longPrecisionArray;
case CeylonFloat:
double[] doublePrecisionArray = new double[size];
arraycopy(elements.array, 0, doublePrecisionArray, 0, size);
return doublePrecisionArray;
case CeylonCharacter:
int[] codepointArray = new int[size];
arraycopy(elements.array, 0, codepointArray, 0, size);
return codepointArray;
case CeylonBoolean:
boolean[] boolArray = new boolean[size];
arraycopy(elements.array, 0, boolArray, 0, size);
return boolArray;
case CeylonByte:
byte[] bitsArray = new byte[size];
arraycopy(elements.array, 0, bitsArray, 0, size);
return bitsArray;
case JavaBoolean:
boolean[] booleanArray = new boolean[size];
arraycopy(elements.array, 0, booleanArray, 0, size);
return booleanArray;
case JavaCharacter:
char[] charArray = new char[size];
arraycopy(elements.array, 0, charArray, 0, size);
return charArray;
case JavaFloat:
float[] floatArray = new float[size];
arraycopy(elements.array, 0, floatArray, 0, size);
return floatArray;
case JavaDouble:
double[] doubleArray = new double[size];
arraycopy(elements.array, 0, doubleArray, 0, size);
return doubleArray;
case JavaByte:
byte[] byteArray = new byte[size];
arraycopy(elements.array, 0, byteArray, 0, size);
return byteArray;
case JavaShort:
short[] shortArray = new short[size];
arraycopy(elements.array, 0, shortArray, 0, size);
return shortArray;
case JavaInteger:
int[] intArray = new int[size];
arraycopy(elements.array, 0, intArray, 0, size);
return intArray;
case JavaLong:
long[] longArray = new long[size];
arraycopy(elements.array, 0, longArray, 0, size);
return longArray;
default:
java.lang.Object[] objectArray = (java.lang.Object[])
java.lang.reflect.Array.newInstance(clazz, size);
java.lang.Object otherArray = elements.array;
if (otherArray.getClass()==objectArray.getClass()) {
arraycopy(otherArray, 0, objectArray, 0, size);
}
else {
for (int i=0; i<size; i++) {
objectArray[i] = elements.getFromFirst(i);
}
}
return objectArray;
}
}
private static <Element> java.lang.Object createArrayWithElement(
final TypeDescriptor $reifiedElement,
final int size, final Element element) {
switch (elementType($reifiedElement)) {
case CeylonInteger:
long[] longPrecisionArray = new long[size];
if (element!=null) {
long value = ((Integer) element).value;
if (value!=0l) Arrays.fill(longPrecisionArray, value);
}
return longPrecisionArray;
case JavaLong:
long[] longArray = new long[size];
if (element!=null) {
long longValue = (java.lang.Long) element;
if (longValue!=0l) Arrays.fill(longArray, longValue);
}
return longArray;
case CeylonFloat:
double[] doublePrecisionArray = new double[size];
if (element!=null) {
double value = ((Float) element).value;
if (value!=0.0d) Arrays.fill(doublePrecisionArray, value);
}
return doublePrecisionArray;
case JavaDouble:
double[] doubleArray = new double[size];
if (element!=null) {
double value = (java.lang.Double) element;
if (value!=0.0d) Arrays.fill(doubleArray, value);
}
return doubleArray;
case CeylonCharacter:
int[] codepointArray = new int[size];
if (element!=null) {
int value = ((Character) element).codePoint;
if (value!=0) Arrays.fill(codepointArray, value);
}
return codepointArray;
case JavaInteger:
int[] intArray = new int[size];
if (element!=null) {
int intValue = (java.lang.Integer) element;
if (intValue!=0) Arrays.fill(intArray, intValue);
}
return intArray;
case CeylonByte:
byte[] byteArray = new byte[size];
if (element!=null) {
byte value = ((Byte) element).value;
if (value!=0) Arrays.fill(byteArray, value);
}
return byteArray;
case JavaByte:
byte[] bitsArray = new byte[size];
byte value = (java.lang.Byte) element;
if (value!=0) Arrays.fill(bitsArray, value);
return bitsArray;
case CeylonBoolean:
boolean[] boolArray = new boolean[size];
if (element!=null) {
boolean boolValue = ((Boolean) element).booleanValue();
if (boolValue!=false) Arrays.fill(boolArray, boolValue);
}
return boolArray;
case JavaBoolean:
boolean[] booleanArray = new boolean[size];
if (element!=null) {
boolean booleanValue = (java.lang.Boolean) element;
if (booleanValue!=false) Arrays.fill(booleanArray, booleanValue);
}
return booleanArray;
case JavaCharacter:
char[] charArray = new char[size];
if (element!=null) {
char charValue = (java.lang.Character) element;
if (charValue!=0) Arrays.fill(charArray, charValue);
}
return charArray;
case JavaShort:
short[] shortArray = new short[size];
if (element!=null) {
short shortValue = (java.lang.Short) element;
if (shortValue!=0) Arrays.fill(shortArray, shortValue);
}
return shortArray;
case JavaFloat:
float[] floatArray = new float[size];
if (element!=null) {
float floatValue = (java.lang.Float) element;
if (floatValue!=0.0f) Arrays.fill(floatArray, floatValue);
}
return floatArray;
case CeylonString:
//note: we don't unbox strings in an Array<String?>
// because it would break javaObjectArray()
java.lang.String[] stringArray = new java.lang.String[size];
if (element!=null) {
String string = (String) element;
Arrays.fill(stringArray, string.value);
}
return stringArray;
default:
java.lang.Class<?> elementClass =
$reifiedElement.getArrayElementClass();
java.lang.Object[] objectArray = (java.lang.Object[])
java.lang.reflect.Array.newInstance(elementClass, size);
if (element!=null) {
Arrays.fill(objectArray, element);
}
return objectArray;
}
}
@Ignore
private Array(@Ignore TypeDescriptor $reifiedElement, java.lang.Object array) {
super($reifiedElement);
this.$reifiedElement = $reifiedElement;
assert(array.getClass().isArray());
elementType = elementType($reifiedElement);
switch(elementType) {
case Other:
objectArray = (java.lang.Object[]) array;
size = objectArray.length;
longArray = null;
doubleArray = null;
intArray = null;
booleanArray = null;
byteArray = null;
stringArray = null;
break;
case CeylonInteger:
if (array==EMPTY_ARRAY)
array = EMPTY_LONG_ARRAY;
longArray = (long[]) array;
size = longArray.length;
objectArray = null;
doubleArray = null;
intArray = null;
booleanArray = null;
byteArray = null;
stringArray = null;
break;
case CeylonFloat:
if (array==EMPTY_ARRAY)
array = EMPTY_DOUBLE_ARRAY;
doubleArray = (double[]) array;
size = doubleArray.length;
objectArray = null;
longArray = null;
intArray = null;
booleanArray = null;
byteArray = null;
stringArray = null;
break;
case CeylonByte:
if (array==EMPTY_ARRAY)
array = EMPTY_BYTE_ARRAY;
byteArray = (byte[]) array;
intArray = null;
size = byteArray.length;
objectArray = null;
longArray = null;
doubleArray = null;
booleanArray = null;
stringArray = null;
break;
case CeylonCharacter:
if (array==EMPTY_ARRAY)
array = EMPTY_INT_ARRAY;
intArray = (int[]) array;
size = intArray.length;
objectArray = null;
longArray = null;
doubleArray = null;
booleanArray = null;
byteArray = null;
stringArray = null;
break;
case CeylonBoolean:
if (array==EMPTY_ARRAY)
array = EMPTY_BOOLEAN_ARRAY;
booleanArray = (boolean[]) array;
size = booleanArray.length;
objectArray = null;
longArray = null;
doubleArray = null;
intArray = null;
byteArray = null;
stringArray = null;
break;
case CeylonString:
if (array==EMPTY_ARRAY)
array = EMPTY_STRING_ARRAY;
stringArray = (java.lang.String[]) array;
size = stringArray.length;
objectArray = null;
longArray = null;
doubleArray = null;
intArray = null;
byteArray = null;
booleanArray = null;
break;
default:
this.size = java.lang.reflect.Array.getLength(array);
objectArray = null;
longArray = null;
doubleArray = null;
booleanArray = null;
intArray = null;
byteArray = null;
stringArray = null;
}
this.array = array;
}
@Ignore
public static <T> Array<T> instance(T[] array) {
if (array == null) {
return null;
}
java.lang.Class<?> componentType = array.getClass().getComponentType();
TypeDescriptor optionalType = TypeDescriptor.union(Null.$TypeDescriptor$,
TypeDescriptor.klass(componentType));
return new Array<T>(optionalType, array);
}
private static final TypeDescriptor CHAR_TYPE =
TypeDescriptor.klass(java.lang.Character.class);
@Ignore
public static Array<java.lang.Character> instance(char[] array) {
if (array == null) {
return null;
}
return new Array<java.lang.Character>(CHAR_TYPE, array);
}
private static final TypeDescriptor BYTE_TYPE =
TypeDescriptor.klass(java.lang.Byte.class);
@Ignore
public static Array<java.lang.Byte> instance(byte[] array) {
if (array == null) {
return null;
}
return new Array<java.lang.Byte>(BYTE_TYPE, array);
}
private static final TypeDescriptor SHORT_TYPE =
TypeDescriptor.klass(java.lang.Short.class);
@Ignore
public static Array<java.lang.Short> instance(short[] array) {
if (array == null) {
return null;
}
return new Array<java.lang.Short>(SHORT_TYPE, array);
}
private static final TypeDescriptor INT_TYPE =
TypeDescriptor.klass(java.lang.Integer.class);
@Ignore
public static Array<java.lang.Integer> instance(int[] array) {
if (array == null) {
return null;
}
return new Array<java.lang.Integer>(INT_TYPE, array);
}
private static final TypeDescriptor LONG_TYPE =
TypeDescriptor.klass(java.lang.Long.class);
@Ignore
public static Array<java.lang.Long> instance(long[] array) {
if (array == null) {
return null;
}
return new Array<java.lang.Long>(LONG_TYPE, array);
}
private static final TypeDescriptor FLOAT_TYPE =
TypeDescriptor.klass(java.lang.Float.class);
@Ignore
public static Array<java.lang.Float> instance(float[] array) {
if (array == null) {
return null;
}
return new Array<java.lang.Float>(FLOAT_TYPE, array);
}
private static final TypeDescriptor DOUBLE_TYPE =
TypeDescriptor.klass(java.lang.Double.class);
@Ignore
public static Array<java.lang.Double> instance(double[] array) {
if (array == null) {
return null;
}
return new Array<java.lang.Double>(DOUBLE_TYPE, array);
}
private static final TypeDescriptor BOOLEAN_TYPE =
TypeDescriptor.klass(java.lang.Boolean.class);
@Ignore
public static Array<java.lang.Boolean> instance(boolean[] array) {
if (array == null) {
return null;
}
return new Array<java.lang.Boolean>(BOOLEAN_TYPE, array);
}
@Ignore
public static Array<Float> instanceForFloats(double[] array) {
if (array == null) {
return null;
}
return new Array<Float>(Float.$TypeDescriptor$, array);
}
@Ignore
public static Array<Boolean> instanceForBooleans(boolean[] array) {
if (array == null) {
return null;
}
return new Array<Boolean>(Boolean.$TypeDescriptor$, array);
}
@Ignore
public static Array<Byte> instanceForBytes(byte[] array) {
if (array == null) {
return null;
}
return new Array<Byte>(Byte.$TypeDescriptor$, array);
}
@Ignore
public static Array<Character> instanceForCodePoints(int[] array) {
if (array == null) {
return null;
}
return new Array<Character>(Character.$TypeDescriptor$, array);
}
@Ignore
public static Array<Integer> instanceForIntegers(long[] array) {
if (array == null) {
return null;
}
return new Array<Integer>(Integer.$TypeDescriptor$, array);
}
@Override
public Array<Element> spanFrom(@Name("from") Integer from) {
return span(from, Integer.instance(size));
}
@Override
public Array<Element> spanTo(@Name("to") Integer to) {
return span(Integer.instance(0), to);
}
@Override
public Array<Element> span(@Name("from") Integer from,
@Name("to") Integer to) {
long fromIndex = from.longValue(); //inclusive
long toIndex = to.longValue(); //inclusive
boolean revert = toIndex < fromIndex;
if (revert) {
long swap = toIndex;
toIndex = fromIndex;
fromIndex = swap;
}
if (fromIndex<0) {
fromIndex = 0;
}
if (toIndex>=size) {
toIndex = size-1;
}
if (fromIndex>=size || toIndex<0 || toIndex<fromIndex) {
return new Array<Element>($reifiedElement, EMPTY_ARRAY);
}
else {
int resultFromIndex = toInt(fromIndex); //inclusive
int resultToIndex = toInt(toIndex+1); //exclusive
java.lang.Object newArray;
if (array instanceof char[]) {
char[] copy = copyOfRange((char[])array,
resultFromIndex, resultToIndex);
if (revert) {
for (int i = 0; i<copy.length/2; i++) {
char temp = copy[i];
copy[i] = copy[copy.length-1-i];
copy[copy.length-1-i] = temp;
}
}
newArray = copy;
}
else if (array instanceof byte[]) {
byte[] copy = copyOfRange((byte[])array,
resultFromIndex, resultToIndex);
if (revert) {
for (int i = 0; i<copy.length/2; i++) {
byte temp = copy[i];
copy[i] = copy[copy.length-1-i];
copy[copy.length-1-i] = temp;
}
}
newArray = copy;
}
else if (array instanceof short[]) {
short[] copy = copyOfRange((short[])array,
resultFromIndex, resultToIndex);
if (revert) {
for (int i = 0; i<copy.length/2; i++) {
short temp = copy[i];
copy[i] = copy[copy.length-1-i];
copy[copy.length-1-i] = temp;
}
}
newArray = copy;
}
else if (array instanceof int[]) {
int[] copy = copyOfRange((int[])array,
resultFromIndex, resultToIndex);
if (revert) {
for (int i = 0; i<copy.length/2; i++) {
int temp = copy[i];
copy[i] = copy[copy.length-1-i];
copy[copy.length-1-i] = temp;
}
}
newArray = copy;
}
else if (array instanceof long[]) {
long[] copy = copyOfRange((long[])array,
resultFromIndex, resultToIndex);
if (revert) {
for (int i = 0; i<copy.length/2; i++) {
long temp = copy[i];
copy[i] = copy[copy.length-1-i];
copy[copy.length-1-i] = temp;
}
}
newArray = copy;
}
else if (array instanceof float[]) {
float[] copy = copyOfRange((float[])array,
resultFromIndex, resultToIndex);
if (revert) {
for (int i = 0; i<copy.length/2; i++) {
float temp = copy[i];
copy[i] = copy[copy.length-1-i];
copy[copy.length-1-i] = temp;
}
}
newArray = copy;
}
else if (array instanceof double[]) {
double[] copy = copyOfRange((double[])array,
resultFromIndex, resultToIndex);
if (revert) {
for (int i = 0; i<copy.length/2; i++) {
double temp = copy[i];
copy[i] = copy[copy.length-1-i];
copy[copy.length-1-i] = temp;
}
}
newArray = copy;
}
else if (array instanceof boolean[]) {
boolean[] copy = copyOfRange((boolean[])array,
resultFromIndex, resultToIndex);
if (revert) {
for (int i = 0; i<copy.length/2; i++) {
boolean temp = copy[i];
copy[i] = copy[copy.length-1-i];
copy[copy.length-1-i] = temp;
}
}
newArray = copy;
}
else {
java.lang.Object[] copy =
copyOfRange((java.lang.Object[])array,
resultFromIndex, resultToIndex);
if (revert) {
for (int i = 0; i<copy.length/2; i++) {
java.lang.Object temp = copy[i];
copy[i] = copy[copy.length-1-i];
copy[copy.length-1-i] = temp;
}
}
newArray = copy;
}
return new Array<Element>($reifiedElement, newArray);
}
}
@Override
public Array<Element> measure(@Name("from") Integer from,
@Name("length") long length) {
long fromIndex = from.longValue(); //inclusive
long toIndex = fromIndex + length; //exclusive
if (fromIndex<0) {
fromIndex=0;
}
if (toIndex > size) {
toIndex = size;
}
if (fromIndex>=size || toIndex<=0) {
return new Array<Element>($reifiedElement, EMPTY_ARRAY);
}
else {
int resultToIndex = toInt(toIndex);
int resultFromIndex = toInt(fromIndex);
java.lang.Object newArray;
if (array instanceof char[]) {
newArray = copyOfRange((char[])array,
resultFromIndex, resultToIndex);
}
else if (array instanceof byte[]) {
newArray = copyOfRange((byte[])array,
resultFromIndex, resultToIndex);
}
else if (array instanceof short[]) {
newArray = copyOfRange((short[])array,
resultFromIndex, resultToIndex);
}
else if (array instanceof int[]) {
newArray = copyOfRange((int[])array,
resultFromIndex, resultToIndex);
}
else if (array instanceof long[]) {
newArray = copyOfRange((long[])array,
resultFromIndex, resultToIndex);
}
else if (array instanceof float[]) {
newArray = copyOfRange((float[])array,
resultFromIndex, resultToIndex);
}
else if (array instanceof double[]) {
newArray = copyOfRange((double[])array,
resultFromIndex, resultToIndex);
}
else if (array instanceof boolean[]) {
newArray = copyOfRange((boolean[])array,
resultFromIndex, resultToIndex);
}
else {
newArray = copyOfRange((java.lang.Object[])array,
resultFromIndex, resultToIndex);
}
return new Array<Element>($reifiedElement, newArray);
}
}
@Override
@TypeInfo("ceylon.language::Null|ceylon.language::Integer")
public Integer getLastIndex() {
return getEmpty() ? null : Integer.instance(size - 1);
}
@Override
public boolean getEmpty() {
return size == 0;
}
@Override
public long getSize() {
return size;
}
@Override
public boolean defines(@Name("index") Integer key) {
long ind = key.longValue();
return ind >= 0 && ind < size;
}
@Ignore
private final class CoalescedArrayIterator
extends BaseIterator<Element> {
private int index = 0;
// ok to cast here, since we know the size must fit in an int
CoalescedArrayIterator(TypeDescriptor $reified$Element) {
super($reified$Element);
}
@Override
public java.lang.Object next() {
if (index<size) {
Element result;
boolean isNull;
do {
result = unsafeItem(index++);
isNull = result==null;
}
while (isNull && index<size);
return isNull ? FIN : result;
}
else {
return FIN;
}
}
@Override
public java.lang.String toString() {
return Array.this.toString() + ".coalesced.iterator()";
}
}
@Ignore
private final class CoalescedArrayIterable
extends BaseIterable<Element, java.lang.Object>
implements Iterable<Element, java.lang.Object> {
private final TypeDescriptor $reifiedElement;
CoalescedArrayIterable(TypeDescriptor $reifiedElement) {
super($reifiedElement, Null.$TypeDescriptor$);
this.$reifiedElement = $reifiedElement;
}
@Override
public Iterator<? extends Element> iterator() {
return new CoalescedArrayIterator($reifiedElement);
}
}
@Override
@TypeInfo("ceylon.language::Iterable<Element&ceylon.language::Object,ceylon.language::Null>")
public Iterable<? extends Element, ? extends java.lang.Object> getCoalesced() {
return new CoalescedArrayIterable(intersection($reifiedElement, Object.$TypeDescriptor$));
}
@Ignore
private final class ArrayIterator extends BaseIterator<Element> {
private int index = 0;
// ok to cast here, since we know the size must fit in an int
private ArrayIterator(TypeDescriptor $reified$Element) {
super($reified$Element);
}
@Override
public java.lang.Object next() {
if (index<size) {
return unsafeItem(index++);
}
else {
return FIN;
}
}
@Override
public java.lang.String toString() {
return Array.this.toString() + ".iterator()";
}
}
@Ignore
final class ArrayIterable
extends AbstractArrayIterable<Element, java.lang.Object> {
ArrayIterable() {
// ok to cast here, since we know the size must fit in an int
super($reifiedElement, array, (int)size);
}
protected ArrayIterable(java.lang.Object array, int start,
int len, int step) {
super($reifiedElement, array, start, len, step);
}
@Override
protected ArrayIterable newInstance(java.lang.Object array,
int start, int len, int step) {
return new ArrayIterable(array, start, len, step);
}
@Override
protected Element get(java.lang.Object array, int index) {
return unsafeItem(index);
}
/**
* If this is an Iterable over an {@code Array<Character>}
* (wrapping a {@code int[]}) with unit step size, then
* returns a String of those codepoints.
* Otherwise returns null.
*/
@Ignore
java.lang.String stringValue() {
if (array instanceof int[]
&& step == 1) {
// ok to cast here, since we know the size must fit in an int
return new java.lang.String((int[])array, start,
(int)this.getSize());
}
return null;
}
}
@Override
public Iterator<Element> iterator() {
return new ArrayIterator($reifiedElement);
}
// @Override
// @TypeInfo("ceylon.language::Null|Element")
// public Element get(@Name("index") Integer key) {
// return getFromFirst(key.longValue());
@Override
@TypeInfo("ceylon.language::Null|Element")
public Element getFromLast(@Name("index") long index) {
if (index < 0 || index >= size) {
return null;
}
else {
//typecast is safe because we just checked
return unsafeItem(size-1-(int) index);
}
}
@Override
@TypeInfo("ceylon.language::Null|Element")
@SuppressWarnings("unchecked")
public Element getFromFirst(@Name("index") long index) {
if (index < 0 || index >= size) {
return null;
}
else {
//typecast is safe because we just checked
int i = (int) index;
if (objectArray!=null)
return (Element) objectArray[i];
else if (longArray!=null)
return (Element) Integer.instance(longArray[i]);
else if (doubleArray!=null)
return (Element) Float.instance(doubleArray[i]);
else if (byteArray!=null)
return (Element) Byte.instance(byteArray[i]);
else if (booleanArray!=null)
return (Element) Boolean.instance(booleanArray[i]);
else if (intArray!=null)
return (Element) Character.instance(intArray[i]);
else if (stringArray!=null)
return (Element) String.instance(stringArray[i]);
else
return getJavaItem(i);
}
}
// Used by the jvm backend code to avoid boxing the index
@SuppressWarnings("unchecked")
@Ignore
public final Element unsafeItem(int index) {
if (objectArray!=null)
return (Element) objectArray[index];
else if (longArray!=null)
return (Element) Integer.instance(longArray[index]);
else if (doubleArray!=null)
return (Element) Float.instance(doubleArray[index]);
else if (byteArray!=null)
return (Element) Byte.instance(byteArray[index]);
else if (booleanArray!=null)
return (Element) Boolean.instance(booleanArray[index]);
else if (intArray!=null)
return (Element) Character.instance(intArray[index]);
else if (stringArray!=null)
return (Element) String.instance(stringArray[index]);
else
return getJavaItem(index);
}
@SuppressWarnings("unchecked")
private Element getJavaItem(int index) throws AssertionError {
switch (elementType) {
case JavaLong:
return (Element) (java.lang.Long) ((long[])array)[index];
case JavaDouble:
return (Element) (java.lang.Double) ((double[])array)[index];
case JavaInteger:
return (Element) (java.lang.Integer) ((int[])array)[index];
case JavaByte:
return (Element) (java.lang.Byte) ((byte[])array)[index];
case JavaBoolean:
return (Element) (java.lang.Boolean) ((boolean[])array)[index];
case JavaCharacter:
return (Element) (java.lang.Character) ((char[])array)[index];
case JavaShort:
return (Element) (java.lang.Short) ((short[])array)[index];
case JavaFloat:
return (Element) (java.lang.Float) ((float[])array)[index];
case JavaString:
return (Element) ((java.lang.String[])array)[index];
default:
throw new AssertionError("unknown element type");
}
}
public void set(
@Name("index") @TypeInfo("ceylon.language::Integer") long index,
@Name("element") @TypeInfo("Element") Element element) {
if (index<0) {
throw new AssertionError("array index " + index +
" may not be negative");
}
else if (index>=size) {
throw new AssertionError("array index " + index +
" must be less than size of array " + size);
}
else {
int idx = (int) index; //typecast is safe 'cos we just checked above
if (objectArray!=null)
objectArray[idx] = element;
else if (longArray!=null)
longArray[idx] = ((Integer) element).value;
else if (doubleArray!=null)
doubleArray[idx] = ((Float) element).value;
else if (byteArray!=null)
byteArray[idx] = ((Byte) element).value;
else if (booleanArray!=null)
booleanArray[idx] = ((Boolean) element).booleanValue();
else if (intArray!=null)
intArray[idx] = ((Character) element).codePoint;
else if (stringArray!=null)
stringArray[idx] = ((String) element).value;
else
setJavaItem(element, idx);
}
}
private void setJavaItem(Element element, int idx) throws AssertionError {
switch (elementType) {
case JavaLong:
((long[]) array)[idx] = (java.lang.Long) element;
break;
case JavaDouble:
((double[]) array)[idx] = (java.lang.Double) element;
break;
case JavaInteger:
((int[]) array)[idx] = (java.lang.Integer) element;
break;
case JavaByte:
((byte[]) array)[idx] = (java.lang.Byte) element;
break;
case JavaBoolean:
((boolean[]) array)[idx] = (java.lang.Boolean) element;
break;
case JavaCharacter:
((char[]) array)[idx] = (java.lang.Character) element;
break;
case JavaShort:
((short[]) array)[idx] = (java.lang.Short) element;
break;
case JavaFloat:
((float[]) array)[idx] = (java.lang.Float) element;
break;
case JavaString:
((java.lang.String[]) array)[idx] = (java.lang.String) element;
break;
default:
throw new AssertionError("unknown element type");
}
}
@Override
public Array<Element> $clone() {
return new Array<Element>($reifiedElement, copyArray());
}
private java.lang.Object copyArray() {
if (array instanceof java.lang.Object[]) {
return Arrays.copyOf((java.lang.Object[]) array,
((java.lang.Object[]) array).length);
}
else if (array instanceof long[]) {
return Arrays.copyOf((long[]) array,
((long[]) array).length);
}
else if (array instanceof double[]) {
return Arrays.copyOf((double[]) array,
((double[]) array).length);
}
else if (array instanceof boolean[]) {
return Arrays.copyOf((boolean[]) array,
((boolean[]) array).length);
}
else if (array instanceof int[]) {
return Arrays.copyOf((int[]) array,
((int[]) array).length);
}
else if (array instanceof byte[]) {
return Arrays.copyOf((byte[]) array,
((byte[]) array).length);
}
else if (array instanceof short[]) {
return Arrays.copyOf((short[]) array,
((short[]) array).length);
}
else if (array instanceof float[]) {
return Arrays.copyOf((float[]) array,
((float[]) array).length);
}
else if (array instanceof char[]) {
return Arrays.copyOf((char[]) array,
((char[]) array).length);
}
else {
throw new AssertionError("impossible array type");
}
}
@Ignore
public java.lang.Object toArray() {
return array;
}
@Override
public boolean contains(@Name("element")
@TypeInfo("ceylon.language::Object")
java.lang.Object element) {
// FIXME Very inefficient for primitive types due to boxing
for (int i=0; i<size; i++) {
Element elem = getFromFirst(i);
if (elem != null && elem.equals(element)) {
return true;
}
}
return false;
}
@Override
public long count(@Name("selecting")@FunctionalParameter("(element)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Boolean,ceylon.language::Tuple<Element,Element,ceylon.language::Empty>>")
Callable<? extends Boolean> selecting) {
// FIXME Very inefficient for primitive types due to boxing
int count=0;
for (int i=0; i<size; i++) {
Element elem = getFromFirst(i);
if (elem != null && selecting.$call$(elem).booleanValue()) {
count++;
}
}
return count;
}
@Override
@Annotations({ @Annotation("actual") })
@TypeInfo("ceylon.language::Null|Element")
public Element getFirst() {
if (size>0) {
return unsafeItem(0);
}
else {
return null;
}
}
@Override
@Annotations({ @Annotation("actual") })
@TypeInfo("ceylon.language::Null|Element")
public Element getLast() {
return size > 0 ? unsafeItem(size-1) : null;
}
@SuppressWarnings("unchecked")
@Override
@TypeInfo("ceylon.language::Sequential<Element>")
public Sequential<? extends Element>
sort(@Name("comparing") @FunctionalParameter("(x,y)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Comparison,ceylon.language::Tuple<Element,Element,ceylon.language::Tuple<Element,Element,ceylon.language::Empty>>>")
Callable<? extends Comparison> comparing) {
if (getEmpty()) {
return (Sequential<? extends Element>) empty_.get_();
}
Array<Element> clone = $clone();
clone.sortInPlace(comparing);
return new ArraySequence<Element>($reifiedElement, clone);
}
/*@SuppressWarnings("unchecked")
@TypeInfo("ceylon.language::Sequential<Element>")
public Sequential<? extends Element>
reverse() {
if (getEmpty()) {
return (Sequential<? extends Element>) empty_.get_();
}
Array<Element> clone = $clone();
clone.reverseInPlace();
return new ArraySequence<Element>($reifiedElement, clone);
}*/
@Override
@Annotations({ @Annotation("actual") })
@TypeInfo("ceylon.language::Iterable<Element,ceylon.language::Null>")
public Iterable<? extends Element, ?>
skip(@Name("skipping") long skipping) {
int intSkip = toInt(skipping);
// ok to cast here, since we know the size must fit in an int
int length = (int) size;
if (skipping <= 0) {
return this;
}
return new ArrayIterable(this.array, intSkip,
Math.max(0, length-intSkip), 1);
}
@Override
@Annotations({ @Annotation("actual") })
@TypeInfo("ceylon.language::Iterable<Element,ceylon.language::Null>")
public Iterable<? extends Element, ?>
take(@Name("taking") long taking) {
// ok to cast here, since we know the size must fit in an int
int length = (int)size;
if (taking >= length) {
return this;
}
return new ArrayIterable(this.array, 0,
Math.max(toInt(taking), 0), 1);
}
@Override
@Annotations({ @Annotation("actual") })
@TypeInfo("ceylon.language::Iterable<Element,ceylon.language::Null>")
public Iterable<? extends Element, ?>
by(@Name("step") long step) {
if (step <= 0) {
throw new AssertionError("step size must be greater than zero");
}
else if (step == 1) {
return this;
}
return new ArrayIterable(array, 0,
toInt((size+step-1)/step),
toInt(step));
}
@SuppressWarnings("unchecked")
@Override
@TypeInfo("ceylon.language::Sequential<Element>")
public Sequential<? extends Element> sequence() {
if (getEmpty()) {
return (Sequential<? extends Element>) empty_.get_();
}
else {
return new ArraySequence<Element>($reifiedElement,
new Array<Element>($reifiedElement, copyArray()));
}
}
@Ignore
public int copyTo$sourcePosition(Element[] destination){
return 0;
}
@Ignore
public int copyTo$destinationPosition(Element[] destination,
int sourcePosition){
return 0;
}
@Ignore
public int copyTo$length(Element[] destination,
int sourcePosition, int destinationPosition){
return java.lang.reflect.Array.getLength(array)-sourcePosition;
}
@Ignore
public void copyTo(Array<Element> destination){
copyTo(destination, 0, 0);
}
@Ignore
public void copyTo(Array<Element> destination, int sourcePosition){
copyTo(destination, sourcePosition, 0);
}
@Ignore
public void copyTo(Array<Element> destination,
int sourcePosition, int destinationPosition){
copyTo(destination, sourcePosition, destinationPosition,
java.lang.reflect.Array.getLength(array)-sourcePosition);
}
public void copyTo(@Name("destination") Array<Element> destination,
@Name("sourcePosition") @Defaulted int sourcePosition,
@Name("destinationPosition") @Defaulted int destinationPosition,
@Name("length") @Defaulted int length){
arraycopy(array, sourcePosition, destination.array,
destinationPosition, length);
}
@Override
@Ignore
public TypeDescriptor $getType$() {
return TypeDescriptor.klass(Array.class, $reifiedElement);
}
public void reverseInPlace() {
if (array instanceof java.lang.Object[]) {
for (int index=0; index<size/2; index++) {
java.lang.Object[] arr = (java.lang.Object[]) array;
java.lang.Object swap = arr[index];
int indexFromLast = size-index-1;
arr[index] = arr[indexFromLast];
arr[indexFromLast] = swap;
}
}
else if (array instanceof long[]) {
for (int index=0; index<size/2; index++) {
long[] arr = (long[]) array;
long swap = arr[index];
int indexFromLast = size-index-1;
arr[index] = arr[indexFromLast];
arr[indexFromLast] = swap;
}
}
else if (array instanceof int[]) {
for (int index=0; index<size/2; index++) {
int[] arr = (int[]) array;
int swap = arr[index];
int indexFromLast = size-index-1;
arr[index] = arr[indexFromLast];
arr[indexFromLast] = swap;
}
}
else if (array instanceof short[]) {
for (int index=0; index<size/2; index++) {
short[] arr = (short[]) array;
short swap = arr[index];
int indexFromLast = size-index-1;
arr[index] = arr[indexFromLast];
arr[indexFromLast] = swap;
}
}
else if (array instanceof byte[]) {
for (int index=0; index<size/2; index++) {
byte[] arr = (byte[]) array;
byte swap = arr[index];
int indexFromLast = size-index-1;
arr[index] = arr[indexFromLast];
arr[indexFromLast] = swap;
}
}
else if (array instanceof double[]) {
for (int index=0; index<size/2; index++) {
double[] arr = (double[]) array;
double swap = arr[index];
int indexFromLast = size-index-1;
arr[index] = arr[indexFromLast];
arr[indexFromLast] = swap;
}
}
else if (array instanceof float[]) {
for (int index=0; index<size/2; index++) {
float[] arr = (float[]) array;
float swap = arr[index];
int indexFromLast = size-index-1;
arr[index] = arr[indexFromLast];
arr[indexFromLast] = swap;
}
}
else if (array instanceof boolean[]) {
for (int index=0; index<size/2; index++) {
boolean[] arr = (boolean[]) array;
boolean swap = arr[index];
int indexFromLast = size-index-1;
arr[index] = arr[indexFromLast];
arr[indexFromLast] = swap;
}
}
else if (array instanceof char[]) {
for (int index=0; index<size/2; index++) {
char[] arr = (char[]) array;
char swap = arr[index];
int indexFromLast = size-index-1;
arr[index] = arr[indexFromLast];
arr[indexFromLast] = swap;
}
}
else {
throw new AssertionError("illegal array type");
}
}
public void sortInPlace(
@Name("comparing") @FunctionalParameter("(x,y)")
@TypeInfo("ceylon.language::Callable<ceylon.language::Comparison,ceylon.language::Tuple<Element,Element,ceylon.language::Tuple<Element,Element,ceylon.language::Empty>>>")
final Callable<? extends Comparison> comparing) {
java.util.List<Element> list =
new java.util.AbstractList<Element>() {
@Override
public Element get(int index) {
return unsafeItem(index);
}
@Override
public Element set(int index, Element element) {
// Strictly this method should return the element that was at
// the given index, but that might require even more boxing
// and in practice the return value
// doesn't seem to be used by the sorting algorithm
Array.this.set(index, element);
return null;
}
@Override
public int size() {
return (int)size;
}
@Override
public java.lang.Object[] toArray() {
if (array instanceof java.lang.Object[] &&
!(array instanceof java.lang.String[])) {
return (java.lang.Object[]) array;
}
else {
int size = size();
java.lang.Object[] result =
new java.lang.Object[size];
for (int i=0; i<size; i++) {
result[i] = unsafeItem(i);
}
return result;
}
}
};
Comparator<Element> comparator =
new Comparator<Element>() {
public int compare(Element x, Element y) {
Comparison result = comparing.$call$(x, y);
if (result==larger_.get_()) return 1;
if (result==smaller_.get_()) return -1;
return 0;
}
};
Collections.<Element>sort(list, comparator);
}
private enum ArrayType {
CeylonInteger,
JavaLong,
CeylonFloat,
JavaDouble,
CeylonCharacter,
JavaInteger,
CeylonByte,
JavaByte,
CeylonBoolean,
JavaBoolean,
JavaCharacter,
JavaShort,
JavaFloat,
CeylonString,
JavaString,
Other
}
private static ArrayType elementType(TypeDescriptor $reifiedElement) {
if ($reifiedElement.containsNull()) {
return ArrayType.Other;
}
java.lang.Class<?> arrayElementClass =
$reifiedElement.getArrayElementClass();
if (arrayElementClass == Integer.class) {
return ArrayType.CeylonInteger;
}
else if (arrayElementClass == java.lang.Long.class) {
return ArrayType.JavaLong;
}
else if (arrayElementClass == Float.class) {
return ArrayType.CeylonFloat;
}
else if (arrayElementClass == java.lang.Double.class) {
return ArrayType.JavaDouble;
}
else if (arrayElementClass == Character.class) {
return ArrayType.CeylonCharacter;
}
else if (arrayElementClass == java.lang.Integer.class) {
return ArrayType.JavaInteger;
}
else if (arrayElementClass == Byte.class) {
return ArrayType.CeylonByte;
}
else if (arrayElementClass == java.lang.Byte.class) {
return ArrayType.JavaByte;
}
else if (arrayElementClass == Boolean.class) {
return ArrayType.CeylonBoolean;
}
else if (arrayElementClass == java.lang.Boolean.class) {
return ArrayType.JavaBoolean;
}
else if (arrayElementClass == java.lang.Character.class) {
return ArrayType.JavaCharacter;
}
else if (arrayElementClass == java.lang.Short.class) {
return ArrayType.JavaShort;
}
else if (arrayElementClass == java.lang.Float.class) {
return ArrayType.JavaFloat;
}
else if (arrayElementClass == String.class) {
return ArrayType.CeylonString;
}
else if (arrayElementClass == java.lang.String.class) {
return ArrayType.JavaString;
}
else {
return ArrayType.Other;
}
}
@Override
public boolean equals(
@Name("that")
java.lang.Object that) {
// overridden so the native model is identical to the ceylon model
return super.equals(that);
}
@Override
@Transient
public int hashCode() {
// overridden so the native model is identical to the ceylon model
return super.hashCode();
}
@Ignore
public Array($Serialization$ ignored, TypeDescriptor $reifiedElement) {
super(ignored, $reifiedElement);
this.$reifiedElement = $reifiedElement;
this.elementType = elementType($reifiedElement);
array = null;
objectArray = null;
longArray = null;
intArray = null;
doubleArray = null;
booleanArray = null;
byteArray = null;
stringArray = null;
size = 0;
}
@Ignore
@Override
public void $serialize$(Callable<? extends Deconstructor> deconstructor) {
Deconstructor dtor = deconstructor.$call$(ceylon.language.meta.typeLiteral_.typeLiteral($getType$()));
ceylon.language.meta.declaration.TypeParameter elementTypeParameter = ((GenericDeclaration)Metamodel.getOrCreateMetamodel(Array.class)).getTypeParameterDeclaration("Element");
dtor.putTypeArgument(elementTypeParameter, Metamodel.getAppliedMetamodel(this.$reifiedElement));
ValueDeclaration sizeAttribute = (ValueDeclaration)((ClassDeclaration)Metamodel.getOrCreateMetamodel(Array.class)).getMemberDeclaration(ceylon.language.meta.declaration.ValueDeclaration.$TypeDescriptor$, "size");
dtor.putValue(Integer.$TypeDescriptor$,
sizeAttribute,
Integer.instance(getSize()));
for (int ii = 0; ii < getSize(); ii++) {
dtor.<Element>putElement(this.$reifiedElement, ii, unsafeItem(ii));
}
}
@Ignore
@Override
public void $deserialize$(Deconstructed dted) {
try {
//ceylon.language.meta.declaration.TypeParameter elementTypeParameter = ((GenericDeclaration)Metamodel.getOrCreateMetamodel(Array.class)).getTypeParameterDeclaration("Element");
//TypeDescriptor reifiedElement = Metamodel.getTypeDescriptor(dted.getTypeArgument(elementTypeParameter));
//Util.setter(MethodHandles.lookup(), "$reifiedElement").invokeExact(this, reifiedElement);
ValueDeclaration sizeAttribute = (ValueDeclaration)((ClassDeclaration)Metamodel.getOrCreateMetamodel(Array.class)).getMemberDeclaration(ceylon.language.meta.declaration.ValueDeclaration.$TypeDescriptor$, "size");
Integer size = (Integer)dted.getValue(Integer.$TypeDescriptor$, sizeAttribute);
Util.setter(MethodHandles.lookup(), "size").invokeExact(this, Util.toInt(size.value));
java.lang.Object a = createArrayWithElement(this.$reifiedElement, Util.toInt(size.value), (Element)null);
Util.setter(MethodHandles.lookup(), "array").invokeExact(this, a);
switch (this.elementType) {
case Other:
Util.setter(MethodHandles.lookup(), "objectArray").invoke(this, a);
break;
case CeylonInteger:
Util.setter(MethodHandles.lookup(), "longArray").invoke(this, a);
break;
case CeylonFloat:
Util.setter(MethodHandles.lookup(), "doubleArray").invoke(this, a);
break;
case CeylonByte:
Util.setter(MethodHandles.lookup(), "byteArray").invoke(this, a);
break;
case CeylonCharacter:
Util.setter(MethodHandles.lookup(), "intArray").invoke(this, a);
break;
case CeylonBoolean:
Util.setter(MethodHandles.lookup(), "booleanArray").invoke(this, a);
break;
case CeylonString:
Util.setter(MethodHandles.lookup(), "stringArray").invoke(this, a);
break;
default:
// nothing to do
}
for (int ii = 0; ii < size.value; ii++) {
java.lang.Object elementValOrRef = dted.<Element>getElement(this.$reifiedElement, ii);
Element element;
if (elementValOrRef instanceof ceylon.language.serialization.Reference) {
element = (Element)((com.redhat.ceylon.compiler.java.runtime.serialization.$InstanceLeaker$)elementValOrRef).$leakInstance$();
} else {
element = (Element)elementValOrRef;
}
set(ii, element);
}
} catch (java.lang.Throwable e) {
rethrow_.rethrow(e);
}
}
}
|
package se.su.it.cognos.cognosshibauth.config;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ConfigHandler {
private static ConfigHandler _instance = null;
private static String CONFIG_FILENAME = "shib_auth.xml";
private Logger LOG = Logger.getLogger(ConfigHandler.class.getName());
private XMLConfiguration config = new XMLConfiguration();
private String headerRemoteUser = "REMOTE_USER";
private String headerGivenName = "";
private String headerSurname = "";
private String headerEmail = "";
private String headerBusinessPhone = "";
private String headerHomePhone = "";
private String headerMobilePhone = "";
private String headerFaxPhone = "";
private String headerPagerPhone = "";
private String headerPostalAddress = "";
protected ConfigHandler() {
config.setFileName(CONFIG_FILENAME);
try {
config.load();
} catch (ConfigurationException e) {
LOG.log(Level.SEVERE, "Failed to load configuration from file \"" + config.getFileName() + "\".");
}
config.setReloadingStrategy(new FileChangedReloadingStrategy());
load_header_values();
}
public static ConfigHandler instance() {
if(_instance == null) {
_instance = new ConfigHandler();
}
return _instance;
}
private void load_header_values() {
headerRemoteUser = config.getString("headers.remote_user", headerRemoteUser);
headerGivenName = config.getString("headers.given_name", headerGivenName);
headerSurname = config.getString("headers.surname", headerSurname);
headerEmail = config.getString("headers.email", headerEmail);
headerBusinessPhone = config.getString("headers.business_phone", headerBusinessPhone);
headerHomePhone = config.getString("headers.home_phone", headerHomePhone);
headerMobilePhone = config.getString("headers.mobile_phone", headerMobilePhone);
headerFaxPhone = config.getString("headers.fax_phone", headerFaxPhone);
headerPagerPhone = config.getString("headers.pager_phone", headerPagerPhone);
headerPostalAddress = config.getString("headers.postal_address", headerPostalAddress);
}
public String getHeaderRemoteUser() {
return headerRemoteUser;
}
public String getHeaderGivenName() {
return headerGivenName;
}
public String getHeaderSurname() {
return headerSurname;
}
public String getHeaderEmail() {
return headerEmail;
}
public String getHeaderBusinessPhone() {
return headerBusinessPhone;
}
public String getHeaderHomePhone() {
return headerHomePhone;
}
public String getHeaderMobilePhone() {
return headerMobilePhone;
}
public String getHeaderFaxPhone() {
return headerFaxPhone;
}
public String getHeaderPagerPhone() {
return headerPagerPhone;
}
public String getHeaderPostalAddress() {
return headerPostalAddress;
}
}
|
package fr.lip6.move.pnml2bpn;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import fr.lip6.move.pnml2bpn.exceptions.PNMLImportExportException;
import fr.lip6.move.pnml2bpn.export.PNML2BPNFactory;
import fr.lip6.move.pnml2bpn.export.PNMLExporter;
/**
* Main class for command-line invocation.
*
* @author lom
*
*/
public final class MainPNML2BPN {
private static final String BPN_EXT = ".bpn";
private static final String PNML_EXT = ".pnml";
private static final String PNML2BPN_DEBUG = "PNML2BPN_DEBUG";
private static final String CAMI_TMP_DELETE = "cami.tmp.delete";
private static final String FORCE_BPN_GENERATION = "force.bpn.generation";
private static final String BOUNDS_CHECKING = "bounds.checking";
private static boolean isDebug;
private static List<String> pathDest;
private static List<String> pathSrc;
private static PNMLFilenameFilter pff;
private static DirFileFilter dff;
private static boolean isCamiTmpDelete;
private static boolean isForceBPNGen;
private static boolean isBoundsChecking;
private MainPNML2BPN() {
super();
}
/**
* @param args
*/
public static void main(String[] args) {
org.slf4j.Logger myLog = LoggerFactory.getLogger(MainPNML2BPN.class
.getCanonicalName());
StringBuilder msg = new StringBuilder();
if (args.length < 1) {
myLog.error("At least the path to one PNML P/T file is expected. You may provide a file, a directory, or a mix of several of these.");
return;
}
// Debug mode?
checkDebugMode(myLog, msg);
// Keep Cami property
checkCamiKeepingMode(myLog, msg);
// Force BPN generation property
checkForceBPNGenMode(myLog, msg);
// Bounds checking property
checkBoundsCheckingMode(myLog, msg);
try {
extractSrcDestPaths(args);
} catch (IOException e1) {
myLog.error("Could not successfully extract all source files paths. See log.");
myLog.error(e1.getMessage());
if (MainPNML2BPN.isDebug) {
e1.printStackTrace();
}
}
long startTime = System.nanoTime();
PNMLExporter pe = new PNML2BPNFactory().createExporter();
org.slf4j.Logger jr = LoggerFactory.getLogger(pe.getClass()
.getCanonicalName());
// TODO : optimize with threads
boolean error = false;
for (int i = 0; i < pathSrc.size(); i++) {
try {
pe.exportPNML(new File(pathSrc.get(i)),
new File(pathDest.get(i)), jr);
} catch (PNMLImportExportException | InterruptedException
| IOException e) {
myLog.error(e.getMessage());
MainPNML2BPN.printStackTrace(e);
error |= true;
}
}
long endTime = System.nanoTime();
if (!error) {
msg.append("Finished successfully.");
myLog.info(msg.toString());
} else {
msg.append("Finished in error.");
if (!MainPNML2BPN.isDebug) {
msg.append(
" Activate debug mode to print stacktraces, like so: export ")
.append(PNML2BPN_DEBUG).append("=true");
}
myLog.error(msg.toString());
}
msg = null;
myLog.info("PNML to BPN took {} seconds.",
(endTime - startTime) / 1.0e9);
LoggerContext loggerContext = (LoggerContext) LoggerFactory
.getILoggerFactory();
loggerContext.stop();
if (error) {
System.exit(-1);
}
}
private static void checkBoundsCheckingMode(org.slf4j.Logger myLog,
StringBuilder msg) {
String boundsChecking = System.getProperty(BOUNDS_CHECKING);
if (boundsChecking != null && Boolean.valueOf(boundsChecking)) {
isBoundsChecking = true;
myLog.warn("Bounds checking enabled.");
} else if (boundsChecking == null) {
isBoundsChecking = true;
msg.append(
"Bounds checking not set. Default is true. If you want to disable bounds checking, then invoke this program with ")
.append(BOUNDS_CHECKING)
.append(" property like so: java -D")
.append(BOUNDS_CHECKING)
.append("=false [JVM OPTIONS] -jar ...");
myLog.warn(msg.toString());
msg.delete(0, msg.length());
} else {
isBoundsChecking = false;
myLog.warn("Bounds checking disabled.");
}
}
/**
* @param myLog
* @param msg
*/
private static void checkForceBPNGenMode(org.slf4j.Logger myLog,
StringBuilder msg) {
String forceBpnGen = System.getProperty(FORCE_BPN_GENERATION);
if (forceBpnGen != null && Boolean.valueOf(forceBpnGen)) {
isForceBPNGen = true;
} else {
isForceBPNGen = false;
msg.append(
"Forcing BPN generation not set. Default is false. If you want to force BPN generation for non 1-Safe nets, then invoke this program with ")
.append(FORCE_BPN_GENERATION)
.append(" property like so: java -D")
.append(FORCE_BPN_GENERATION)
.append("=true [JVM OPTIONS] -jar ...");
myLog.warn(msg.toString());
msg.delete(0, msg.length());
}
}
/**
* @param myLog
* @param msg
*/
private static void checkCamiKeepingMode(org.slf4j.Logger myLog,
StringBuilder msg) {
String remove = System.getProperty(CAMI_TMP_DELETE);
if (remove != null && !Boolean.valueOf(remove)) {
isCamiTmpDelete = false;
} else {
isCamiTmpDelete = true;
msg.append(
"Keeping temporary Cami file property not set. If you want to keep temporary Cami file then invoke this program with ")
.append(CAMI_TMP_DELETE)
.append(" property like so: java -D")
.append(CAMI_TMP_DELETE)
.append("=false [JVM OPTIONS] -jar ...");
myLog.warn(msg.toString());
msg.delete(0, msg.length());
}
}
/**
* @param myLog
* @param msg
*/
private static void checkDebugMode(org.slf4j.Logger myLog, StringBuilder msg) {
String debug = System.getenv(PNML2BPN_DEBUG);
if ("true".equalsIgnoreCase(debug)) {
setDebug(true);
} else {
setDebug(false);
msg.append(
"Debug mode not set. If you want to activate the debug mode (print stackstaces in case of errors), then set the ")
.append(PNML2BPN_DEBUG)
.append(" environnement variable like so: export ")
.append(PNML2BPN_DEBUG).append("=true.");
myLog.warn(msg.toString());
msg.delete(0, msg.length());
}
}
/**
* Extracts PNML files (scans directories recursively) from command-line
* arguments.
*
* @param args
* @throws IOException
*/
private static void extractSrcDestPaths(String[] args) throws IOException {
pathDest = new ArrayList<String>();
pathSrc = new ArrayList<String>();
File srcf;
File[] srcFiles;
pff = new PNMLFilenameFilter();
dff = new DirFileFilter();
for (String s : args) {
srcf = new File(s);
if (srcf.isFile()) {
pathSrc.add(s);
pathDest.add(s.replaceAll(PNML_EXT, BPN_EXT));
} else if (srcf.isDirectory()) {
srcFiles = extractSrcFiles(srcf, pff, dff);
for (File f : srcFiles) {
pathSrc.add(f.getCanonicalPath());
pathDest.add(f.getCanonicalPath().replaceAll(PNML_EXT,
BPN_EXT));
}
}
}
}
private static File[] extractSrcFiles(File srcf, PNMLFilenameFilter pff,
DirFileFilter dff) {
List<File> res = new ArrayList<File>();
// filter PNML files
File[] pfiles = srcf.listFiles(pff);
res.addAll(Arrays.asList(pfiles));
// filter directories
pfiles = srcf.listFiles(dff);
for (File f : pfiles) {
res.addAll(Arrays.asList(extractSrcFiles(f, pff, dff)));
}
return res.toArray(new File[0]);
}
private static final class PNMLFilenameFilter implements FilenameFilter {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(PNML_EXT);
}
}
private static final class DirFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
}
/**
* Returns true if debug mode is set.
*
* @return
*/
public static boolean isDebug() {
return isDebug;
}
/**
* Sets the debug mode according to parameter: enable (true) or disable
* (false).
*
* @param isDebug
*/
public static synchronized void setDebug(boolean isDebug) {
MainPNML2BPN.isDebug = isDebug;
}
/**
* Returns true if temporary Cami file should be deleted, false otherwise.
*
* @return
*/
public static synchronized boolean isCamiTmpDelete() {
return isCamiTmpDelete;
}
/**
* Returns true if BPN generation is forced, even if the net is not 1-safe.
*
* @return
*/
public static synchronized boolean isForceBPNGen() {
return isForceBPNGen;
}
/**
* Returns true if bounds checking is enabled (default), false otherwise.
*
* @return
*/
public static synchronized boolean isBoundsChecking() {
return isBoundsChecking;
}
/**
* Prints the stack trace of the exception passed as parameter.
*
* @param e
*/
public static synchronized void printStackTrace(Exception e) {
if (MainPNML2BPN.isDebug) {
e.printStackTrace();
}
}
}
|
package hex.generic;
import hex.ModelCategory;
import hex.glm.GLM;
import hex.glm.GLMModel;
import hex.tree.drf.DRF;
import hex.tree.drf.DRFModel;
import hex.tree.gbm.GBM;
import hex.tree.gbm.GBMModel;
import hex.tree.isofor.IsolationForest;
import hex.tree.isofor.IsolationForestModel;
import org.junit.Before;
import org.junit.Test;
import water.*;
import water.fvec.Frame;
import java.io.*;
import java.util.ArrayList;
import static hex.genmodel.utils.DistributionFamily.AUTO;
import static org.junit.Assert.*;
public class GenericModelTest extends TestUtil {
@Before
public void setUp() {
TestUtil.stall_till_cloudsize(1);
}
@Test
public void testJavaScoring_gbm_binomial() throws Exception {
Key mojo = null;
GBMModel model = null;
GenericModel genericModel = null;
Frame trainingFrame = null;
Frame testFrame = null;
Frame predictions = null;
try {
// Create new GBM model
trainingFrame = parse_test_file("./smalldata/testng/airlines_train.csv");
testFrame = parse_test_file("./smalldata/testng/airlines_test.csv");
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = trainingFrame._key;
parms._distribution = AUTO;
parms._response_column = "IsDepDelayed";
parms._ntrees = 1;
GBM job = new GBM(parms);
model = job.trainModel().get();
assertEquals(model._output.getModelCategory(), ModelCategory.Binomial);
final ByteArrayOutputStream originalModelMojo = new ByteArrayOutputStream();
final File originalModelMojoFile = File.createTempFile("mojo", "zip");
model.getMojo().writeTo(originalModelMojo);
model.getMojo().writeTo(new FileOutputStream(originalModelMojoFile));
mojo = importMojo(originalModelMojoFile.getAbsolutePath());
final GenericModelParameters genericModelParameters = new GenericModelParameters();
genericModelParameters._model_key = mojo;
final Generic generic = new Generic(genericModelParameters);
genericModel = generic.trainModel().get();
predictions = genericModel.score(testFrame);
final boolean equallyScored = genericModel.testJavaScoring(testFrame, predictions, 0);
assertTrue(equallyScored);
} finally {
if (model != null) model.remove();
if (mojo != null) mojo.remove();
if (genericModel != null) genericModel.remove();
if (trainingFrame != null) trainingFrame.remove();
if (testFrame != null) testFrame.remove();
if (predictions != null) predictions.remove();
}
}
@Test
public void testJavaScoring_drf_binomial() throws Exception {
Key mojo = null;
DRFModel model = null;
GenericModel genericModel = null;
Frame trainingFrame = null;
Frame testFrame = null;
Frame predictions = null;
try {
trainingFrame = parse_test_file("./smalldata/testng/airlines_train.csv");
testFrame = parse_test_file("./smalldata/testng/airlines_test.csv");
DRFModel.DRFParameters parms = new DRFModel.DRFParameters();
parms._train = trainingFrame._key;
parms._distribution = AUTO;
parms._response_column = "IsDepDelayed";
parms._ntrees = 1;
DRF job = new DRF(parms);
model = job.trainModel().get();
assertEquals(model._output.getModelCategory(), ModelCategory.Binomial);
final ByteArrayOutputStream originalModelMojo = new ByteArrayOutputStream();
final File originalModelMojoFile = File.createTempFile("mojo", "zip");
model.getMojo().writeTo(originalModelMojo);
model.getMojo().writeTo(new FileOutputStream(originalModelMojoFile));
mojo = importMojo(originalModelMojoFile.getAbsolutePath());
final GenericModelParameters genericModelParameters = new GenericModelParameters();
genericModelParameters._model_key = mojo;
final Generic generic = new Generic(genericModelParameters);
genericModel = generic.trainModel().get();
predictions = genericModel.score(testFrame);
assertEquals(2691, predictions.numRows());
final boolean equallyScored = genericModel.testJavaScoring(testFrame, predictions, 0);
assertTrue(equallyScored);
} finally {
if (model != null) model.remove();
if (mojo != null) mojo.remove();
if (genericModel != null) genericModel.remove();
if (trainingFrame != null) trainingFrame.remove();
if (testFrame != null) testFrame.remove();
if (predictions != null) predictions.remove();
}
}
@Test
public void testJavaScoring_irf_binomial() throws Exception {
Key mojo = null;
IsolationForestModel model = null;
GenericModel genericModel = null;
Frame trainingFrame = null;
Frame testFrame = null;
Frame predictions = null;
try {
trainingFrame = parse_test_file("./smalldata/testng/airlines_train.csv");
testFrame = parse_test_file("./smalldata/testng/airlines_test.csv");
IsolationForestModel.IsolationForestParameters parms = new IsolationForestModel.IsolationForestParameters();
parms._train = trainingFrame._key;
parms._distribution = AUTO;
parms._response_column = "IsDepDelayed";
parms._ntrees = 1;
IsolationForest job = new IsolationForest(parms);
model = job.trainModel().get();
assertEquals(model._output.getModelCategory(), ModelCategory.AnomalyDetection);
final ByteArrayOutputStream originalModelMojo = new ByteArrayOutputStream();
final File originalModelMojoFile = File.createTempFile("mojo", "zip");
model.getMojo().writeTo(originalModelMojo);
model.getMojo().writeTo(new FileOutputStream(originalModelMojoFile));
mojo = importMojo(originalModelMojoFile.getAbsolutePath());
final GenericModelParameters genericModelParameters = new GenericModelParameters();
genericModelParameters._model_key = mojo;
final Generic generic = new Generic(genericModelParameters);
genericModel = generic.trainModel().get();
predictions = genericModel.score(testFrame);
assertEquals(2691, predictions.numRows());
final boolean equallyScored = genericModel.testJavaScoring(testFrame, predictions, 0);
assertTrue(equallyScored);
} finally {
if (model != null) model.remove();
if (mojo != null) mojo.remove();
if (genericModel != null) genericModel.remove();
if (trainingFrame != null) trainingFrame.remove();
if (testFrame != null) testFrame.remove();
if (predictions != null) predictions.remove();
}
}
@Test
public void testJavaScoring_gbm_regression() throws Exception {
Key mojo = null;
GBMModel model = null;
GenericModel genericModel = null;
Frame trainingFrame = null;
Frame testFrame = null;
Frame predictions = null;
try {
trainingFrame = parse_test_file("./smalldata/testng/airlines_train.csv");
testFrame = parse_test_file("./smalldata/testng/airlines_test.csv");
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = trainingFrame._key;
parms._distribution = AUTO;
parms._response_column = "Distance";
parms._ntrees = 1;
GBM job = new GBM(parms);
model = job.trainModel().get();
assertEquals(model._output.getModelCategory(), ModelCategory.Regression);
final ByteArrayOutputStream originalModelMojo = new ByteArrayOutputStream();
final File originalModelMojoFile = File.createTempFile("mojo", "zip");
model.getMojo().writeTo(originalModelMojo);
model.getMojo().writeTo(new FileOutputStream(originalModelMojoFile));
mojo = importMojo(originalModelMojoFile.getAbsolutePath());
final GenericModelParameters genericModelParameters = new GenericModelParameters();
genericModelParameters._model_key = mojo;
final Generic generic = new Generic(genericModelParameters);
genericModel = generic.trainModel().get();
predictions = genericModel.score(testFrame);
assertEquals(2691, predictions.numRows());
final boolean equallyScored = genericModel.testJavaScoring(testFrame, predictions, 0);
assertTrue(equallyScored);
} finally {
if (model != null) model.remove();
if (mojo != null) mojo.remove();
if (genericModel != null) genericModel.remove();
if (trainingFrame != null) trainingFrame.remove();
if (testFrame != null) testFrame.remove();
if (predictions != null) predictions.remove();
}
}
@Test
public void testJavaScoring_drf_regression() throws Exception {
Key mojo = null;
DRFModel model = null;
GenericModel genericModel = null;
Frame trainingFrame = null;
Frame testFrame = null;
Frame predictions = null;
try {
trainingFrame = parse_test_file("./smalldata/testng/airlines_train.csv");
testFrame = parse_test_file("./smalldata/testng/airlines_test.csv");
DRFModel.DRFParameters parms = new DRFModel.DRFParameters();
parms._train = trainingFrame._key;
parms._distribution = AUTO;
parms._response_column = "Distance";
parms._ntrees = 1;
DRF job = new DRF(parms);
model = job.trainModel().get();
assertEquals(model._output.getModelCategory(), ModelCategory.Regression);
final ByteArrayOutputStream originalModelMojo = new ByteArrayOutputStream();
final File originalModelMojoFile = File.createTempFile("mojo", "zip");
model.getMojo().writeTo(originalModelMojo);
model.getMojo().writeTo(new FileOutputStream(originalModelMojoFile));
mojo = importMojo(originalModelMojoFile.getAbsolutePath());
final GenericModelParameters genericModelParameters = new GenericModelParameters();
genericModelParameters._model_key = mojo;
final Generic generic = new Generic(genericModelParameters);
genericModel = generic.trainModel().get();
predictions = genericModel.score(testFrame);
assertEquals(2691, predictions.numRows());
final boolean equallyScored = genericModel.testJavaScoring(testFrame, predictions, 0);
assertTrue(equallyScored);
} finally {
if (model != null) model.remove();
if (mojo != null) mojo.remove();
if (genericModel != null) genericModel.remove();
if (trainingFrame != null) trainingFrame.remove();
if (testFrame != null) testFrame.remove();
if (predictions != null) predictions.remove();
}
}
@Test
public void testJavaScoring_irf_numerical() throws Exception {
Key mojo = null;
IsolationForestModel model = null;
GenericModel genericModel = null;
Frame trainingFrame = null;
Frame testFrame = null;
Frame predictions = null;
try {
trainingFrame = parse_test_file("./smalldata/testng/airlines_train.csv");
testFrame = parse_test_file("./smalldata/testng/airlines_test.csv");
IsolationForestModel.IsolationForestParameters parms = new IsolationForestModel.IsolationForestParameters();
parms._train = trainingFrame._key;
parms._distribution = AUTO;
parms._response_column = "Distance";
parms._ntrees = 1;
IsolationForest job = new IsolationForest(parms);
model = job.trainModel().get();
assertEquals(model._output.getModelCategory(), ModelCategory.AnomalyDetection);
final ByteArrayOutputStream originalModelMojo = new ByteArrayOutputStream();
final File originalModelMojoFile = File.createTempFile("mojo", "zip");
model.getMojo().writeTo(originalModelMojo);
model.getMojo().writeTo(new FileOutputStream(originalModelMojoFile));
mojo = importMojo(originalModelMojoFile.getAbsolutePath());
final GenericModelParameters genericModelParameters = new GenericModelParameters();
genericModelParameters._model_key = mojo;
final Generic generic = new Generic(genericModelParameters);
genericModel = generic.trainModel().get();
predictions = genericModel.score(testFrame);
assertEquals(2691, predictions.numRows());
final boolean equallyScored = genericModel.testJavaScoring(testFrame, predictions, 0);
assertTrue(equallyScored);
} finally {
if (model != null) model.remove();
if (mojo != null) mojo.remove();
if (genericModel != null) genericModel.remove();
if (trainingFrame != null) trainingFrame.remove();
if (testFrame != null) testFrame.remove();
if (predictions != null) predictions.remove();
}
}
@Test
public void testJavaScoring_glm() throws Exception {
Key mojo = null;
GLMModel model = null;
GenericModel genericModel = null;
Frame trainingFrame = null;
Frame testFrame = null;
Frame predictions = null;
try {
trainingFrame = parse_test_file("./smalldata/testng/airlines_train.csv");
testFrame = parse_test_file("./smalldata/testng/airlines_test.csv");
GLMModel.GLMParameters parms = new GLMModel.GLMParameters();
parms._train = trainingFrame._key;
parms._distribution = AUTO;
parms._response_column = "Distance";
GLM job = new GLM(parms);
model = job.trainModel().get();
assertEquals(model._output.getModelCategory(), ModelCategory.Regression);
final ByteArrayOutputStream originalModelMojo = new ByteArrayOutputStream();
final File originalModelMojoFile = File.createTempFile("mojo", "zip");
model.getMojo().writeTo(originalModelMojo);
model.getMojo().writeTo(new FileOutputStream(originalModelMojoFile));
mojo = importMojo(originalModelMojoFile.getAbsolutePath());
final GenericModelParameters genericModelParameters = new GenericModelParameters();
genericModelParameters._model_key = mojo;
final Generic generic = new Generic(genericModelParameters);
genericModel = generic.trainModel().get();
predictions = genericModel.score(testFrame);
assertEquals(2691, predictions.numRows());
final boolean equallyScored = genericModel.testJavaScoring(testFrame, predictions, 0);
assertTrue(equallyScored);
} finally {
if (model != null) model.remove();
if (mojo != null) mojo.remove();
if (genericModel != null) genericModel.remove();
if (trainingFrame != null) trainingFrame.remove();
if (testFrame != null) testFrame.remove();
if (predictions != null) predictions.remove();
}
}
@Test
public void testJavaScoring_gbm_multinomial() throws Exception {
Key mojo = null;
GBMModel model = null;
GenericModel genericModel = null;
Frame trainingFrame = null;
Frame testFrame = null;
Frame predictions = null;
try {
// Create new GBM model
trainingFrame = parse_test_file("./smalldata/testng/airlines_train.csv");
testFrame = parse_test_file("./smalldata/testng/airlines_test.csv");
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = trainingFrame._key;
parms._distribution = AUTO;
parms._response_column = "Origin";
parms._ntrees = 1;
GBM job = new GBM(parms);
model = job.trainModel().get();
assertEquals(model._output.getModelCategory(), ModelCategory.Multinomial);
final ByteArrayOutputStream originalModelMojo = new ByteArrayOutputStream();
final File originalModelMojoFile = File.createTempFile("mojo", "zip");
model.getMojo().writeTo(originalModelMojo);
model.getMojo().writeTo(new FileOutputStream(originalModelMojoFile));
mojo = importMojo(originalModelMojoFile.getAbsolutePath());
final GenericModelParameters genericModelParameters = new GenericModelParameters();
genericModelParameters._model_key = mojo;
final Generic generic = new Generic(genericModelParameters);
genericModel = generic.trainModel().get();
predictions = genericModel.score(testFrame);
assertEquals(2691, predictions.numRows());
final boolean equallyScored = genericModel.testJavaScoring(testFrame, predictions, 0);
assertTrue(equallyScored);
} finally {
if (model != null) model.remove();
if (mojo != null) mojo.remove();
if (genericModel != null) genericModel.remove();
if (trainingFrame != null) trainingFrame.remove();
if (testFrame != null) testFrame.remove();
if (predictions != null) predictions.remove();
}
}
@Test
public void testJavaScoring_drf_multinomial() throws Exception {
Key mojo = null;
DRFModel model = null;
GenericModel genericModel = null;
Frame trainingFrame = null;
Frame testFrame = null;
Frame predictions = null;
try {
trainingFrame = parse_test_file("./smalldata/testng/airlines_train.csv");
testFrame = parse_test_file("./smalldata/testng/airlines_test.csv");
DRFModel.DRFParameters parms = new DRFModel.DRFParameters();
parms._train = trainingFrame._key;
parms._distribution = AUTO;
parms._response_column = "Origin";
parms._ntrees = 1;
DRF job = new DRF(parms);
model = job.trainModel().get();
assertEquals(model._output.getModelCategory(), ModelCategory.Multinomial);
final ByteArrayOutputStream originalModelMojo = new ByteArrayOutputStream();
final File originalModelMojoFile = File.createTempFile("mojo", "zip");
model.getMojo().writeTo(originalModelMojo);
model.getMojo().writeTo(new FileOutputStream(originalModelMojoFile));
mojo = importMojo(originalModelMojoFile.getAbsolutePath());
final GenericModelParameters genericModelParameters = new GenericModelParameters();
genericModelParameters._model_key = mojo;
final Generic generic = new Generic(genericModelParameters);
genericModel = generic.trainModel().get();
predictions = genericModel.score(testFrame);
assertEquals(2691, predictions.numRows());
final boolean equallyScored = genericModel.testJavaScoring(testFrame, predictions, 0);
assertTrue(equallyScored);
} finally {
if (model != null) model.remove();
if (mojo != null) mojo.remove();
if (genericModel != null) genericModel.remove();
if (trainingFrame != null) trainingFrame.remove();
if (testFrame != null) testFrame.remove();
if (predictions != null) predictions.remove();
}
}
@Test
public void testJavaScoring_irf_multinomial() throws Exception {
Key mojo = null;
IsolationForestModel model = null;
GenericModel genericModel = null;
Frame trainingFrame = null;
Frame testFrame = null;
Frame predictions = null;
try {
trainingFrame = parse_test_file("./smalldata/testng/airlines_train.csv");
testFrame = parse_test_file("./smalldata/testng/airlines_test.csv");
IsolationForestModel.IsolationForestParameters parms = new IsolationForestModel.IsolationForestParameters();
parms._train = trainingFrame._key;
parms._distribution = AUTO;
parms._response_column = "Origin";
parms._ntrees = 1;
IsolationForest job = new IsolationForest(parms);
model = job.trainModel().get();
assertEquals(model._output.getModelCategory(), ModelCategory.AnomalyDetection);
final ByteArrayOutputStream originalModelMojo = new ByteArrayOutputStream();
final File originalModelMojoFile = File.createTempFile("mojo", "zip");
model.getMojo().writeTo(originalModelMojo);
model.getMojo().writeTo(new FileOutputStream(originalModelMojoFile));
mojo = importMojo(originalModelMojoFile.getAbsolutePath());
final GenericModelParameters genericModelParameters = new GenericModelParameters();
genericModelParameters._model_key = mojo;
final Generic generic = new Generic(genericModelParameters);
genericModel = generic.trainModel().get();
predictions = genericModel.score(testFrame);
assertEquals(2691, predictions.numRows());
final boolean equallyScored = genericModel.testJavaScoring(testFrame, predictions, 0);
assertTrue(equallyScored);
} finally {
if (model != null) model.remove();
if (mojo != null) mojo.remove();
if (genericModel != null) genericModel.remove();
if (trainingFrame != null) trainingFrame.remove();
if (testFrame != null) testFrame.remove();
if (predictions != null) predictions.remove();
}
}
/**
* Create a GBM model and writes a MOJO into a temporary zip file. Then, it creates a Generic model out of that
* temporary zip file and re-downloads the underlying MOJO again. The byte arrays representing both MOJOs are tested
* to be the same.
*
*/
@Test
public void downloadable_mojo_gbm() throws IOException {
GBMModel gbm = null;
Key mojo = null;
GenericModel genericModel = null;
Frame trainingFrame = null;
try {
// Create new GBM model
trainingFrame = parse_test_file("./smalldata/gbm_test/Mfgdata_gaussian_GBM_testing.csv");
GBMModel.GBMParameters parms = new GBMModel.GBMParameters();
parms._train = trainingFrame._key;
parms._distribution = AUTO;
parms._response_column = trainingFrame._names[1];
parms._ntrees = 1;
GBM job = new GBM(parms);
gbm = job.trainModel().get();
final ByteArrayOutputStream originalModelMojo = new ByteArrayOutputStream();
final File originalModelMojoFile = File.createTempFile("mojo", "zip");
gbm.getMojo().writeTo(originalModelMojo);
gbm.getMojo().writeTo(new FileOutputStream(originalModelMojoFile));
mojo = importMojo(originalModelMojoFile.getAbsolutePath());
// Create Generic model from given imported MOJO
final GenericModelParameters genericModelParameters = new GenericModelParameters();
genericModelParameters._model_key = mojo;
final Generic generic = new Generic(genericModelParameters);
genericModel = generic.trainModel().get();
// Compare the two MOJOs byte-wise
ByteArrayOutputStream genericModelMojo = new ByteArrayOutputStream();
genericModel.getMojo().writeTo(genericModelMojo);
assertArrayEquals(genericModelMojo.toByteArray(), genericModelMojo.toByteArray());
} finally {
if(gbm != null) gbm.remove();
if (mojo != null) mojo.remove();
if (genericModel != null) genericModel.remove();
if (trainingFrame != null) trainingFrame.remove();
}
}
/**
* Create a DRF model and writes a MOJO into a temporary zip file. Then, it creates a Generic model out of that
* temporary zip file and re-downloads the underlying MOJO again. The byte arrays representing both MOJOs are tested
* to be the same.
*
*/
@Test
public void downloadable_mojo_drf() throws IOException {
DRFModel originalModel = null;
Key mojo = null;
GenericModel genericModel = null;
Frame trainingFrame = null;
try {
// Create new DRF model
trainingFrame = parse_test_file("./smalldata/gbm_test/Mfgdata_gaussian_GBM_testing.csv");
DRFModel.DRFParameters parms = new DRFModel.DRFParameters();
parms._train = trainingFrame._key;
parms._distribution = AUTO;
parms._response_column = trainingFrame._names[1];
parms._ntrees = 1;
DRF job = new DRF(parms);
originalModel = job.trainModel().get();
final ByteArrayOutputStream originalModelMojo = new ByteArrayOutputStream();
final File originalModelMojoFile = File.createTempFile("mojo", "zip");
originalModel.getMojo().writeTo(originalModelMojo);
originalModel.getMojo().writeTo(new FileOutputStream(originalModelMojoFile));
mojo = importMojo(originalModelMojoFile.getAbsolutePath());
// Create Generic model from given imported MOJO
final GenericModelParameters genericModelParameters = new GenericModelParameters();
genericModelParameters._model_key = mojo;
final Generic generic = new Generic(genericModelParameters);
genericModel = generic.trainModel().get();
// Compare the two MOJOs byte-wise
ByteArrayOutputStream genericModelMojo = new ByteArrayOutputStream();
genericModel.getMojo().writeTo(genericModelMojo);
assertArrayEquals(genericModelMojo.toByteArray(), genericModelMojo.toByteArray());
} finally {
if(originalModel != null) originalModel.remove();
if (mojo != null) mojo.remove();
if (genericModel != null) genericModel.remove();
if (trainingFrame != null) trainingFrame.remove();
}
}
/**
* Create an IRF model and writes a MOJO into a temporary zip file. Then, it creates a Generic model out of that
* temporary zip file and re-downloads the underlying MOJO again. The byte arrays representing both MOJOs are tested
* to be the same.
*
*/
@Test
public void downloadable_mojo_irf() throws IOException {
IsolationForestModel originalModel = null;
Key mojo = null;
GenericModel genericModel = null;
Frame trainingFrame = null;
try {
// Create new IRF model
trainingFrame = parse_test_file("./smalldata/gbm_test/Mfgdata_gaussian_GBM_testing.csv");
IsolationForestModel.IsolationForestParameters parms = new IsolationForestModel.IsolationForestParameters();
parms._train = trainingFrame._key;
parms._distribution = AUTO;
parms._response_column = trainingFrame._names[1];
parms._ntrees = 1;
IsolationForest job = new IsolationForest(parms);
originalModel = job.trainModel().get();
final ByteArrayOutputStream originalModelMojo = new ByteArrayOutputStream();
final File originalModelMojoFile = File.createTempFile("mojo", "zip");
originalModel.getMojo().writeTo(originalModelMojo);
originalModel.getMojo().writeTo(new FileOutputStream(originalModelMojoFile));
mojo = importMojo(originalModelMojoFile.getAbsolutePath());
// Create Generic model from given imported MOJO
final GenericModelParameters genericModelParameters = new GenericModelParameters();
genericModelParameters._model_key = mojo;
final Generic generic = new Generic(genericModelParameters);
genericModel = generic.trainModel().get();
// Compare the two MOJOs byte-wise
ByteArrayOutputStream genericModelMojo = new ByteArrayOutputStream();
genericModel.getMojo().writeTo(genericModelMojo);
assertArrayEquals(genericModelMojo.toByteArray(), genericModelMojo.toByteArray());
} finally {
if(originalModel != null) originalModel.remove();
if (mojo != null) mojo.remove();
if (genericModel != null) genericModel.remove();
if (trainingFrame != null) trainingFrame.remove();
}
}
/**
* Create a GLM model and writes a MOJO into a temporary zip file. Then, it creates a Generic model out of that
* temporary zip file and re-downloads the underlying MOJO again. The byte arrays representing both MOJOs are tested
* to be the same.
*
*/
@Test
public void downloadable_mojo_glm() throws IOException {
GLMModel originalModel = null;
Key mojo = null;
GenericModel genericModel = null;
Frame trainingFrame = null;
try {
// Create new DRF model
trainingFrame = parse_test_file("./smalldata/gbm_test/Mfgdata_gaussian_GBM_testing.csv");
GLMModel.GLMParameters parms = new GLMModel.GLMParameters();
parms._train = trainingFrame._key;
parms._distribution = AUTO;
parms._response_column = trainingFrame._names[1];
GLM job = new GLM(parms);
originalModel = job.trainModel().get();
final ByteArrayOutputStream originalModelMojo = new ByteArrayOutputStream();
final File originalModelMojoFile = File.createTempFile("mojo", "zip");
originalModel.getMojo().writeTo(originalModelMojo);
originalModel.getMojo().writeTo(new FileOutputStream(originalModelMojoFile));
mojo = importMojo(originalModelMojoFile.getAbsolutePath());
// Create Generic model from given imported MOJO
final GenericModelParameters genericModelParameters = new GenericModelParameters();
genericModelParameters._model_key = mojo;
final Generic generic = new Generic(genericModelParameters);
genericModel = generic.trainModel().get();
// Compare the two MOJOs byte-wise
ByteArrayOutputStream genericModelMojo = new ByteArrayOutputStream();
genericModel.getMojo().writeTo(genericModelMojo);
assertArrayEquals(genericModelMojo.toByteArray(), genericModelMojo.toByteArray());
} finally {
if(originalModel != null) originalModel.remove();
if (mojo != null) mojo.remove();
if (genericModel != null) genericModel.remove();
if (trainingFrame != null) trainingFrame.remove();
}
}
private Key<Frame> importMojo(final String mojoAbsolutePath) {
final ArrayList<String> keys = new ArrayList<>(1);
H2O.getPM().importFiles(mojoAbsolutePath, "", new ArrayList<String>(), keys, new ArrayList<String>(),
new ArrayList<String>());
assertEquals(1, keys.size());
return DKV.get(keys.get(0))._key;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.micromanager;
import javax.swing.JOptionPane;
import mmcorej.CMMCore;
import org.micromanager.api.ScriptInterface;
import org.micromanager.utils.ReportingUtils;
/**
*
* @author karlhoover
*/
public class ReportProblemDialog extends javax.swing.JDialog {
String reportPreamble_;
CMMCore core_;
private ScriptInterface parent_;
MMOptions mmoptions_;
/** Creates new form ReportProblemDialog */
public ReportProblemDialog(CMMCore c, ScriptInterface parentMMGUI, MMOptions mmoptions) {
super();
initComponents();
reportPreamble_ = "";
core_ = c;
parent_ = parentMMGUI;
mmoptions_ = mmoptions;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
descriptionPane_ = new javax.swing.JEditorPane();
cancelButton_ = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
stepInstructions_ = new javax.swing.JTextPane();
jLabel1 = new javax.swing.JLabel();
name_ = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
organization_ = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
emailText_ = new javax.swing.JTextField();
clearButton_ = new javax.swing.JButton();
sendButton_ = new javax.swing.JButton();
setTitle("Report Problem Dialog");
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
public void componentHidden(java.awt.event.ComponentEvent evt) {
formComponentHidden(evt);
}
});
descriptionPane_.setFont(new java.awt.Font("Lucida Sans Unicode", 0, 10));
jScrollPane2.setViewportView(descriptionPane_);
cancelButton_.setText("Cancel");
cancelButton_.setToolTipText("Quit the Problem Report procedure.");
cancelButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButton_ActionPerformed(evt);
}
});
stepInstructions_.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
stepInstructions_.setEditable(false);
stepInstructions_.setFont(new java.awt.Font("Lucida Sans Unicode", 0, 12));
jScrollPane1.setViewportView(stepInstructions_);
jLabel1.setText("Problem Description");
name_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
name_ActionPerformed(evt);
}
});
name_.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
name_PropertyChange(evt);
}
});
jLabel2.setText("Name");
jLabel3.setText("Organization");
organization_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
organization_ActionPerformed(evt);
}
});
organization_.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
organization_PropertyChange(evt);
}
});
jLabel4.setText("e-mail");
emailText_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
emailText_ActionPerformed(evt);
}
});
emailText_.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
emailText_PropertyChange(evt);
}
});
clearButton_.setText("Restart Log!");
clearButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearButton_ActionPerformed(evt);
}
});
sendButton_.setText("Send");
sendButton_.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sendButton_ActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jLabel2)
.add(102, 102, 102)
.add(name_, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 546, Short.MAX_VALUE))
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 684, Short.MAX_VALUE))
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel3)
.add(jLabel4))
.add(57, 57, 57)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(emailText_, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 546, Short.MAX_VALUE)
.add(organization_, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 546, Short.MAX_VALUE)))
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jLabel1)
.add(14, 14, 14)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE))
.add(layout.createSequentialGroup()
.add(88, 88, 88)
.add(cancelButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 140, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(52, 52, 52)
.add(clearButton_)
.add(69, 69, 69)
.add(sendButton_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 145, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel2)
.add(name_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel3)
.add(organization_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel4)
.add(emailText_, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 153, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(69, 69, 69)
.add(jLabel1)))
.add(18, 18, 18)
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 61, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(sendButton_)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(cancelButton_)
.add(clearButton_)))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
InitializeDialog();
}//GEN-LAST:event_formComponentShown
/*
private boolean userInputValid() {
boolean result = false;
String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
if (emailText_.getText().matches(EMAIL_REGEX)) {
if (0 < name_.getText().length()) {
if (0 < organization_.getText().length()) {
result = true;
}
}
}
return result;
}
*/
private void BuildAndSendReport() {
reportPreamble_ = "#User Name:" + name_.getText();
reportPreamble_ += ("\n#Organization: " + organization_.getText());
reportPreamble_ += ("\n#User e-mail: " + emailText_.getText());
reportPreamble_ += ("\n#User Description: " + descriptionPane_.getText());
descriptionPane_.setEnabled(false);
descriptionPane_.setEditable(false);
sendButton_.setEnabled(false);
stepInstructions_.setText("Sending...");
ProblemReportSender p = new ProblemReportSender(reportPreamble_, core_);
String result = p.Send();
if (0 < result.length()) {
ReportingUtils.logError(result);
stepInstructions_.setText("There was a problem sending the report, please verify your internet connection.");
} else {
stepInstructions_.setText("The report was successfully submitted to micro-manager.org");
}
}
private void cancelButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButton_ActionPerformed
FinishDialog();
this.setVisible(false);
}//GEN-LAST:event_cancelButton_ActionPerformed
private void name_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_name_ActionPerformed
}//GEN-LAST:event_name_ActionPerformed
private void name_PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_name_PropertyChange
}//GEN-LAST:event_name_PropertyChange
private void clearButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearButton_ActionPerformed
// user wishes to clear the log file..
core_.clearLog();
core_.logMessage("MM Studio version: " + parent_.getVersion());
core_.logMessage(core_.getVersionInfo());
core_.logMessage(core_.getAPIVersionInfo());
core_.logMessage("Operating System: " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
stepInstructions_.setText("The system is now capturing a 'debug' level log file. Operate the system until you've duplicated the problem. When you're successful, "
+ " press Send to send your information, problem description, system configuration, and log to micro-manager.org.");
descriptionPane_.setEnabled(true);
descriptionPane_.setEditable(true);
sendButton_.setEnabled(true);
}//GEN-LAST:event_clearButton_ActionPerformed
private void formComponentHidden(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentHidden
FinishDialog();
}//GEN-LAST:event_formComponentHidden
private void sendButton_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendButton_ActionPerformed
// This regex does not allow addresses with dashes in them
//String EMAIL_REGEX = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";
// simpler, and seems to work:
//String EMAIL_REGEX = "[\\w-]+@([\\w-]+\\.)+[\\w-]+";
String EMAIL_REGEX = "(?i)[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
if (emailText_.getText().matches(EMAIL_REGEX)) {
if (0 < name_.getText().length()) {
if (0 < organization_.getText().length()) {
int result = JOptionPane.showConfirmDialog(null, "Did you restart the log and reproduce the problem?",
"Really send?", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
BuildAndSendReport();
}
} else {
ReportingUtils.showMessage("Please provide your Organization name.");
organization_.requestFocus();
}
} else {
ReportingUtils.showMessage("Please provide your name.");
name_.requestFocus();
}
} else {
ReportingUtils.showMessage("Please provide a valid e-mail.");
emailText_.requestFocus();
}
}//GEN-LAST:event_sendButton_ActionPerformed
private void emailText_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_emailText_ActionPerformed
}//GEN-LAST:event_emailText_ActionPerformed
private void organization_ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_organization_ActionPerformed
}//GEN-LAST:event_organization_ActionPerformed
private void organization_PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_organization_PropertyChange
}//GEN-LAST:event_organization_PropertyChange
private void emailText_PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_emailText_PropertyChange
}//GEN-LAST:event_emailText_PropertyChange
void FinishDialog() {
sendButton_.setEnabled(true);
descriptionPane_.setEnabled(true);
descriptionPane_.setEditable(true);
core_.enableDebugLog(mmoptions_.debugLogEnabled_);
}
void InitializeDialog() {
this.setLocation(100, 100);
stepInstructions_.setText("Please press the \"Restart Log!\" button first. Reproduce the problem, "
+ "then press \"Send\". \n\n ");
stepInstructions_.setBackground(this.getBackground());
MMStudioMainFrame.getInstance().addMMBackgroundListener(stepInstructions_);
descriptionPane_.setText("");
descriptionPane_.setVisible(true);
descriptionPane_.setEditable(true);
descriptionPane_.setEnabled(true);
descriptionPane_.requestFocus();
core_.enableDebugLog(true);
cancelButton_.setVisible(true);
sendButton_.setEnabled(true);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelButton_;
private javax.swing.JButton clearButton_;
private javax.swing.JEditorPane descriptionPane_;
private javax.swing.JTextField emailText_;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextField name_;
private javax.swing.JTextField organization_;
private javax.swing.JButton sendButton_;
private javax.swing.JTextPane stepInstructions_;
// End of variables declaration//GEN-END:variables
}
|
package org.modmine.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import org.intermine.api.InterMineAPI;
import org.intermine.api.bag.BagQueryRunner;
import org.intermine.api.profile.Profile;
import org.intermine.api.query.WebResultsExecutor;
import org.intermine.api.results.WebResults;
import org.intermine.api.util.NameUtil;
import org.intermine.metadata.Model;
import org.intermine.model.bio.Submission;
import org.intermine.objectstore.ObjectStore;
import org.intermine.pathquery.Constraints;
import org.intermine.pathquery.PathQuery;
import org.intermine.util.StringUtil;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.bag.BagHelper;
import org.intermine.web.logic.config.WebConfig;
import org.intermine.web.logic.export.http.TableExporterFactory;
import org.intermine.web.logic.export.http.TableHttpExporter;
import org.intermine.web.logic.query.QueryMonitorTimeout;
import org.intermine.web.logic.results.PagedTable;
import org.intermine.web.logic.session.SessionMethods;
import org.intermine.web.struts.ForwardParameters;
import org.intermine.web.struts.InterMineAction;
/**
* Generate queries for overlaps of submission features and overlaps with gene flanking regions.
* @author Richard Smith
*
*/
public class FeaturesAction extends InterMineAction
{
/**
* Action for creating a bag of InterMineObjects or Strings from identifiers in text field.
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws
* an exception
*/
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
@SuppressWarnings("unused") HttpServletResponse response)
throws Exception {
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
ObjectStore os = im.getObjectStore();
Model model = im.getModel();
String type = (String) request.getParameter("type");
String featureType = (String) request.getParameter("feature");
String action = (String) request.getParameter("action");
String dccId = null;
String experimentName = null;
PathQuery q = new PathQuery(model);
if (type.equals("experiment")) {
experimentName = (String) request.getParameter("experiment");
DisplayExperiment exp = MetadataCache.getExperimentByName(os, experimentName);
q.addView(featureType + ".primaryIdentifier");
q.addView(featureType + ".score");
q.addView(featureType + ".chromosome.primaryIdentifier");
q.addView(featureType + ".chromosomeLocation.start");
q.addView(featureType + ".chromosomeLocation.end");
q.addView(featureType + ".chromosomeLocation.strand");
q.addView(featureType + ".submissions:experimentalFactors.type");
q.addView(featureType + ".submissions:experimentalFactors.name");
q.addConstraint(featureType + ".submissions.experiment.name",
Constraints.eq(experimentName));
q.addOrderBy(featureType + ".chromosome.primaryIdentifier");
q.addOrderBy(featureType + ".chromosomeLocation.start");
String ef = getFactors(exp);
String description = "All " + featureType + " features generated by experiment '"
+ exp.getName() + "' in " + StringUtil.prettyList(exp.getOrganisms())
+ " (" + exp.getPi() + ")." + ef;
q.setDescription(description);
} else if (type.equals("submission")) {
dccId = (String) request.getParameter("submission");
Submission sub = MetadataCache.getSubmissionByDccId(os, new Integer(dccId));
q.addView(featureType + ".primaryIdentifier");
q.addView(featureType + ".score");
q.addView(featureType + ".chromosome.primaryIdentifier");
q.addView(featureType + ".chromosomeLocation.start");
q.addView(featureType + ".chromosomeLocation.end");
q.addView(featureType + ".chromosomeLocation.strand");
q.addView(featureType + ".submissions:experimentalFactors.type");
q.addView(featureType + ".submissions:experimentalFactors.name");
q.addConstraint(featureType + ".submissions.DCCid", Constraints.eq(new Integer(dccId)));
q.addOrderBy(featureType + ".chromosome.primaryIdentifier");
q.addOrderBy(featureType + ".chromosomeLocation.start");
String experimentType = "";
if (sub.getExperimentType() != null) {
experimentType = StringUtil.indefiniteArticle(sub.getExperimentType())
+ " " + sub.getExperimentType() + " experiment in";
}
String efSub = "";
if (SubmissionHelper.getExperimentalFactorString(sub).length() > 1){
efSub = " using " + SubmissionHelper.getExperimentalFactorString(sub);
}
String description = "All " + featureType + " features generated by submission " + dccId
+ ", " + experimentType + " "
+ sub.getOrganism().getShortName() + efSub
+ " (" + sub.getProject().getSurnamePI() + ").";
q.setDescription(description);
}
if (action.equals("results")) {
QueryMonitorTimeout clientState = new QueryMonitorTimeout(
Constants.QUERY_TIMEOUT_SECONDS * 1000);
MessageResources messages =
(MessageResources) request.getAttribute(Globals.MESSAGES_KEY);
String qid = SessionMethods.startQuery(clientState, session, messages,
false, q);
Thread.sleep(200);
return new ForwardParameters(mapping.findForward("waiting"))
.addParameter("qid", qid)
.forward();
} else if (action.equals("export")) {
String format = request.getParameter("format");
Profile profile = SessionMethods.getProfile(session);
WebResultsExecutor executor = im.getWebResultsExecutor(profile);
PagedTable pt = new PagedTable(executor.execute(q));
if (pt.getWebTable() instanceof WebResults) {
((WebResults) pt.getWebTable()).goFaster();
}
WebConfig webConfig = SessionMethods.getWebConfig(request);
TableExporterFactory factory = new TableExporterFactory(webConfig);
TableHttpExporter exporter = factory.getExporter(format);
if (exporter == null) {
throw new RuntimeException("unknown export format: " + format);
}
exporter.export(pt, request, response, null);
// If null is returned then no forwarding is performed and
// to the output is not flushed any jsp output, so user
// will get only required export data
return null;
} else if (action.equals("list")) {
// need to select just id of featureType to create list
q.setView(featureType + ".id");
Profile profile = (Profile) session.getAttribute(Constants.PROFILE);
BagQueryRunner bagQueryRunner = im.getBagQueryRunner();
String bagName = (dccId != null ? "submission_" + dccId : experimentName)
+ "_" + featureType + "_features";
bagName = NameUtil.generateNewName(profile.getSavedBags().keySet(), bagName);
BagHelper.createBagFromPathQuery(q, bagName, q.getDescription(), featureType, profile,
os, bagQueryRunner);
ForwardParameters forwardParameters =
new ForwardParameters(mapping.findForward("bagDetails"));
return forwardParameters.addParameter("bagName", bagName).forward();
}
return null;
}
private String getFactors(DisplayExperiment exp) {
String ef = "";
if (exp.getFactorTypes().size() == 1){
ef = "Experimental factor is the " + StringUtil.prettyList(exp.getFactorTypes())
+ " used." ;
}
if (exp.getFactorTypes().size() > 1){
ef = "Experimental factors are the " + StringUtil.prettyList(exp.getFactorTypes())
+ " used." ;
}
return ef;
}
}
|
package org.eddy.pipeline.command;
import org.eddy.captcha.CaptchaUtil;
import org.eddy.config.DingConfig;
import org.eddy.config.HostConfig;
import org.eddy.http.HttpRequest;
import org.eddy.im.DingMsgSender;
import org.eddy.im.MarkDownUtil;
import org.eddy.pipeline.CoordinateUtil;
import org.eddy.pipeline.Pipeline;
import org.eddy.solve.Ticket;
import org.eddy.util.JsonUtil;
import org.eddy.util.OrderUtil;
import org.eddy.util.PassengerUtil;
import org.eddy.util.TicketUtil;
import org.eddy.web.TrainQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
public enum Command {
INIT {
@Override
public void execute(String pipeline, Object param) {
HttpRequest.init();
HttpRequest.auth();
String url = CaptchaUtil.saveImage((String) param, HttpRequest.loginCaptchaImage());
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent("", url, pipeline), DingConfig.token);
}
},
LOGIN {
@Override
public void execute(String pipeline, Object param) {
HttpRequest.checkRandCode(CoordinateUtil.computeCoordinate((Integer[]) param));
String result = HttpRequest.login(CoordinateUtil.computeCoordinate((Integer[]) param));
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(result, pipeline), DingConfig.token);
String uamtkResult = HttpRequest.uamtk();
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(uamtkResult), DingConfig.token);
String authClientResult = HttpRequest.authClient();
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(authClientResult, "", HostConfig.domain + "/web/tranBegin", pipeline), DingConfig.token);
}
},
REFRESH_LOGIN_CAPTCHA {
@Override
public void execute(String pipeline, Object param) {
String url = CaptchaUtil.saveImage((String) param, HttpRequest.refreshLoginCaptchaImage());
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent("", url, pipeline), DingConfig.token);
}
},
START_CHOOSE_TRAIN {
@Override
public void execute(String pipeline, Object param) {
String passengers = String.join(",", PassengerUtil.parsePassengerName(HttpRequest.getPassengers()));
// DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(passengers), DingConfig.token);
try {
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(passengers, "", HostConfig.domain + "/web/train?passengers=" + URLEncoder.encode(passengers, "UTF-8"), pipeline), DingConfig.token);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
},
TICKET_QUERY {
@Override
public void execute(String pipeline, Object param) {
TrainQuery query = (TrainQuery) param;
if ((query.getALong().get() | 1) == 1) {
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(query.toString()), DingConfig.token);
}
String ticket = HttpRequest.ticketQuery(query);
List<Ticket> tickets = TicketUtil.genTickets(ticket);
Ticket tr = TicketUtil.findTicket(tickets, query);
if (null == tr) {
try {
Thread.sleep(3_000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
continueQuery(pipeline, param);
return;
}
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(tr.toString()), DingConfig.token);
String result = HttpRequest.checkUser();
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(result), DingConfig.token);
result = HttpRequest.submitOrderRequest(tr, query);
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(result), DingConfig.token);
HttpRequest.initDc();
result = HttpRequest.checkOrderInfo(query);
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(result), DingConfig.token);
if (JsonUtil.needPassCode(result)) {
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(""), DingConfig.token);
goConfirm(pipeline, param);
} else {
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(", "), DingConfig.token);
}
}
private void continueQuery(String pipeline, Object param) {
CommandNotify notify = new CommandNotify();
notify.setPipeline(pipeline);
notify.setArg(param);
notify.setCommand(this);
Pipeline.putNotify(notify);
}
private void goConfirm(String pipeline, Object param) {
CommandNotify notify = new CommandNotify();
notify.setPipeline(pipeline);
notify.setArg(param);
notify.setCommand(Command.CONFIRM);
Pipeline.putNotify(notify);
}
},
CONFIRM {
@Override
public void execute(String pipeline, Object param) {
TrainQuery query = (TrainQuery) param;
String ticket = HttpRequest.ticketQuery(query);
List<Ticket> tickets = TicketUtil.genTickets(ticket);
Ticket tr = TicketUtil.findTicket(tickets, query);
String result = HttpRequest.getQueueCount(tr, query);
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(result), DingConfig.token);
result = HttpRequest.confirmSingleForQueue(tr, query);
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(result), DingConfig.token);
result = HttpRequest.queryOrderWaitTime();
result = OrderUtil.findOrder(result);
DingMsgSender.markdown.sendMsg(MarkDownUtil.createContent(result), DingConfig.token);
}
},
STOP {
@Override
public void execute(String pipeline, Object param) {
super.execute(pipeline, param);
}
};
public void execute(String pipeline, Object param) {
throw new RuntimeException("unsupported");
}
private static final Logger logger = LoggerFactory.getLogger(Command.class);
}
|
package com.intellij.psi.impl.source.parsing;
import com.intellij.lang.ASTNode;
import com.intellij.lexer.JavaLexer;
import com.intellij.lexer.JavaWithJspTemplateDataLexer;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.JavaTokenType;
import com.intellij.psi.impl.source.Constants;
import com.intellij.psi.impl.source.ParsingContext;
import com.intellij.psi.impl.source.tree.*;
import com.intellij.psi.impl.source.tree.java.ModifierListElement;
import com.intellij.psi.tree.IChameleonElementType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.xml.XmlElementType;
import com.intellij.util.CharTable;
public class ParseUtil implements Constants {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.parsing.ParseUtil");
public static final Key<String> UNCLOSED_ELEMENT_PROPERTY = Key.create("UNCLOSED_ELEMENT_PROPERTY");
public static boolean isStrongWhitespaceHolder(IElementType type){
return type == XmlElementType.XML_TEXT;
}
public static TreeElement createTokenElement(Lexer lexer, CharTable table) {
IElementType tokenType = lexer.getTokenType();
if (tokenType == null) return null;
if (tokenType == JavaTokenType.DOC_COMMENT) {
LeafElement chameleon = Factory.createLeafElement(JavaDocElementType.DOC_COMMENT, lexer.getBuffer(), lexer.getTokenStart(),
lexer.getTokenEnd(), lexer.getState(), table);
return chameleon;
}
else {
final LeafElement leafElement = Factory.createLeafElement(tokenType, lexer.getBuffer(), lexer.getTokenStart(), lexer.getTokenEnd(),
lexer.getState(), table);
leafElement.setState(lexer.getState());
return leafElement;
}
}
public static String getTokenText(Lexer lexer) {
return StringFactory.createStringFromConstantArray(lexer.getBuffer(), lexer.getTokenStart(),
lexer.getTokenEnd() - lexer.getTokenStart());
}
public static interface TokenProcessor {
TreeElement process(Lexer lexer, ParsingContext context);
boolean isTokenValid(IElementType tokenType);
}
public static abstract class DefaultWhiteSpaceTokenProcessorImpl implements TokenProcessor {
public boolean isTokenValid(IElementType tokenType) {
return tokenType != null && isInSet(tokenType);
}
public TreeElement process(Lexer lexer, ParsingContext context) {
TreeElement first = null;
TreeElement last = null;
while (isTokenValid(lexer.getTokenType())) {
TreeElement tokenElement = ParseUtil.createTokenElement(lexer, context.getCharTable());
IElementType type = lexer.getTokenType();
if (!isInSet(type)) {
LOG.error("Missed token should be white space or comment:" + tokenElement);
throw new RuntimeException();
}
if (last != null) {
last.setTreeNext(tokenElement);
tokenElement.setTreePrev(last);
last = tokenElement;
}
else {
first = last = tokenElement;
}
lexer.advance();
}
return first;
}
protected abstract boolean isInSet(final IElementType type);
}
public static class WhiteSpaceAndCommentsProcessor implements TokenProcessor {
public static final TokenProcessor INSTANCE = new WhiteSpaceAndCommentsProcessor();
private WhiteSpaceAndCommentsProcessor() {
}
public TreeElement process(Lexer lexer, ParsingContext context) {
TreeElement first = null;
TreeElement last = null;
while (isTokenValid(lexer.getTokenType())) {
TreeElement tokenElement = ParseUtil.createTokenElement(lexer, context.getCharTable());
IElementType type = lexer.getTokenType();
if (!WHITE_SPACE_OR_COMMENT_BIT_SET.isInSet(type)) {
LOG.error("Missed token should be white space or comment:" + tokenElement);
throw new RuntimeException();
}
if (last != null) {
last.setTreeNext(tokenElement);
tokenElement.setTreePrev(last);
last = tokenElement;
}
else {
first = last = tokenElement;
}
lexer.advance();
}
return first;
}
public boolean isTokenValid(IElementType tokenType) {
return tokenType != null && WHITE_SPACE_OR_COMMENT_BIT_SET.isInSet(tokenType);
}
}
public static final class CommonParentState {
public TreeElement startLeafBranchStart = null;
public ASTNode nextLeafBranchStart = null;
public CompositeElement strongWhiteSpaceHolder = null;
public boolean isStrongElementOnRisingSlope = true;
}
/*public static void insertMissingTokens(CompositeElement root,
Lexer lexer,
int startOffset,
int endOffset,
final int state, TokenProcessor processor, ParsingContext context) {
insertMissingTokens(root, lexer, startOffset, endOffset, -1, processor, context);
}*/
public static void insertMissingTokens(CompositeElement root,
Lexer lexer,
int startOffset,
int endOffset, int state,
TokenProcessor processor, ParsingContext context) {
if (state < 0) {
lexer.start(lexer.getBuffer(), startOffset, endOffset);
}
else {
lexer.start(lexer.getBuffer(), startOffset, endOffset, state);
}
boolean gt = lexer instanceof JavaLexer || lexer instanceof JavaWithJspTemplateDataLexer;
LeafElement leaf = TreeUtil.findFirstLeaf(root);
if (leaf == null) {
final TreeElement firstMissing = processor.process(lexer, context);
if (firstMissing != null) {
TreeUtil.addChildren(root, firstMissing);
}
return;
}
{
// Missing in the begining
final IElementType tokenType = gt ? GTTokens.getTokenType(lexer) : lexer.getTokenType();
if (tokenType != leaf.getElementType() && processor.isTokenValid(tokenType)) {
final TreeElement firstMissing = processor.process(lexer, context);
if (firstMissing != null) {
TreeUtil.insertBefore((TreeElement)root.getFirstChildNode(), firstMissing);
}
}
passTokenOrChameleon(leaf, lexer, gt);
}
// Missing in tree body
insertMissingTokensInTreeBody(leaf, gt, lexer, processor, context, null);
if(lexer.getTokenType() != null){
// whitespaces at the end of the file
final TreeElement firstMissing = processor.process(lexer, context);
if(firstMissing != null){
ASTNode current = root;
while(current instanceof CompositeElement){
if(current.getUserData(UNCLOSED_ELEMENT_PROPERTY) != null) break;
current = current.getLastChildNode();
}
if(current instanceof CompositeElement){
TreeUtil.addChildren((CompositeElement)current, firstMissing);
}
else{
TreeUtil.insertAfter((TreeElement)root.getLastChildNode(), firstMissing);
}
}
}
bindComments(root);
}
public static void insertMissingTokensInTreeBody(TreeElement leaf,
boolean gt,
Lexer lexer,
TokenProcessor processor,
ParsingContext context,
ASTNode endToken) {
final CommonParentState commonParents = new CommonParentState();
while(leaf != null){
commonParents.strongWhiteSpaceHolder = null;
final IElementType tokenType = gt ? GTTokens.getTokenType(lexer) : lexer.getTokenType();
final TreeElement next;
if (tokenType instanceof IChameleonElementType) {
next = nextLeaf(leaf, commonParents, tokenType);
}
else {
next = nextLeaf(leaf, commonParents, null);
}
if (next == null || tokenType == null || next == endToken) break;
if (tokenType != next.getElementType() && processor.isTokenValid(tokenType)) {
final TreeElement firstMissing = processor.process(lexer, context);
final CompositeElement unclosedElement = commonParents.strongWhiteSpaceHolder;
if (unclosedElement != null) {
if(commonParents.isStrongElementOnRisingSlope || unclosedElement.getFirstChildNode() == null) {
TreeUtil.addChildren(unclosedElement, firstMissing);
}
else {
TreeUtil.insertBefore((TreeElement)unclosedElement.getFirstChildNode(), firstMissing);
}
}
else {
final ASTNode insertBefore = commonParents.nextLeafBranchStart;
TreeElement insertAfter = commonParents.startLeafBranchStart;
TreeElement current = commonParents.startLeafBranchStart;
while (current != insertBefore) {
final TreeElement treeNext = current.getTreeNext();
if (treeNext == insertBefore) {
insertAfter = current;
break;
}
if (treeNext instanceof ModifierListElement) {
insertAfter = current;
break;
}
if (treeNext.getUserData(UNCLOSED_ELEMENT_PROPERTY) != null) {
insertAfter = null;
TreeUtil.addChildren((CompositeElement)treeNext, firstMissing);
break;
}
current = treeNext;
}
if (insertAfter != null) TreeUtil.insertAfter(insertAfter, firstMissing);
}
}
passTokenOrChameleon(next, lexer, gt);
leaf = next;
}
}
private static void passTokenOrChameleon(final ASTNode next, Lexer lexer, boolean gtUse) {
if (next instanceof LeafElement && ((LeafElement)next).isChameleon()) {
final int endOfChameleon = next.getTextLength() + lexer.getTokenStart();
while (lexer.getTokenType() != null && lexer.getTokenEnd() < endOfChameleon) {
lexer.advance();
}
}
if (gtUse) {
GTTokens.advance(next.getElementType(), lexer);
}
else {
lexer.advance();
}
}
public static LeafElement nextLeaf(TreeElement start, CommonParentState commonParent) {
return (LeafElement)nextLeaf(start, commonParent, null);
}
public static TreeElement nextLeaf(TreeElement start, CommonParentState commonParent, IElementType searchedType) {
TreeElement next = null;
if(commonParent != null){
commonParent.startLeafBranchStart = start;
initStrongWhitespaceHolder(commonParent, start, true);
}
TreeElement nextTree = start;
while (next == null && (nextTree = nextTree.getTreeNext()) != null) {
if (nextTree.getElementType() == searchedType) {
return nextTree;
}
next = findFirstLeaf(nextTree, searchedType, commonParent);
}
if(next != null){
if(commonParent != null) commonParent.nextLeafBranchStart = nextTree;
return next;
}
final CompositeElement parent = start.getTreeParent();
if (parent == null) return null;
return nextLeaf(parent, commonParent, searchedType);
}
private static void initStrongWhitespaceHolder(CommonParentState commonParent, ASTNode start, boolean slopeSide) {
if(start instanceof CompositeElement
&& (isStrongWhitespaceHolder(start.getElementType())
|| slopeSide && start.getUserData(UNCLOSED_ELEMENT_PROPERTY) != null)){
commonParent.strongWhiteSpaceHolder = (CompositeElement)start;
commonParent.isStrongElementOnRisingSlope = slopeSide;
}
}
private static TreeElement findFirstLeaf(TreeElement element, IElementType searchedType, CommonParentState commonParent) {
if(commonParent != null){
initStrongWhitespaceHolder(commonParent, element, false);
}
if (element instanceof LeafElement || element.getElementType() == searchedType){
return element;
}
else{
for(TreeElement child = (TreeElement)element.getFirstChildNode(); child != null; child = child.getTreeNext()){
TreeElement leaf = findFirstLeaf(child, searchedType, commonParent);
if (leaf != null) return leaf;
}
return null;
}
}
public static LeafElement prevLeaf(TreeElement start, CommonParentState commonParent) {
LeafElement prev = null;
if(commonParent != null){
if (commonParent.strongWhiteSpaceHolder != null && start.getUserData(UNCLOSED_ELEMENT_PROPERTY) != null) {
commonParent.strongWhiteSpaceHolder = (CompositeElement)start;
}
commonParent.startLeafBranchStart = start;
}
ASTNode prevTree = start;
while (prev == null && (prevTree = prevTree.getTreePrev()) != null) {
prev = TreeUtil.findLastLeaf(prevTree);
}
if(prev != null){
if(commonParent != null) commonParent.nextLeafBranchStart = prevTree;
return prev;
}
final CompositeElement parent = start.getTreeParent();
if (parent == null) return null;
return prevLeaf(parent, commonParent);
}
static void bindComments(ASTNode root) {
TreeElement child = (TreeElement)root.getFirstChildNode();
while (child != null) {
if (child.getElementType() == JavaDocElementType.DOC_COMMENT) {
if (bindDocComment(child)) {
child = child.getTreeParent();
continue;
}
}
// bind "trailing comments" (like "int a; // comment")
if (child.getElementType() == END_OF_LINE_COMMENT || child.getElementType() == C_STYLE_COMMENT) {
if (bindTrailingComment(child)) {
child = child.getTreeParent();
continue;
}
}
// bind "preceding comments" (like "// comment \n void f();")
if (child.getElementType() == END_OF_LINE_COMMENT || child.getElementType() == C_STYLE_COMMENT) {
if (bindPrecedingComment(child)) {
child = child.getTreeParent();
if (child.getTreePrev() != null) {
child = child.getTreePrev();
}
continue;
}
}
if (child instanceof CompositeElement) {
bindComments(child);
}
child = child.getTreeNext();
}
}
private static boolean bindDocComment(TreeElement docComment) {
TreeElement element = docComment.getTreeNext();
if (element == null) return false;
TreeElement startSpaces = null;
ASTNode endSpaces;
// Bypass meaningless tokens and hold'em in hands
while (element.getElementType() == WHITE_SPACE ||
element.getElementType() == C_STYLE_COMMENT ||
element.getElementType() == END_OF_LINE_COMMENT ||
(element.getElementType() == IMPORT_LIST && element.getTextLength() == 0)
) {
if (startSpaces == null) startSpaces = element;
element = element.getTreeNext();
if (element == null) return false;
}
endSpaces = element;
if (element.getElementType() == CLASS || element.getElementType() == FIELD || element.getElementType() == METHOD ||
element.getElementType() == ENUM_CONSTANT) {
TreeElement first = (TreeElement)element.getFirstChildNode();
TreeElement endRange = docComment;
if(startSpaces != null){
element = startSpaces.getTreeNext();
if (startSpaces.getElementType() != IMPORT_LIST) {
endRange = startSpaces;
}
}
TreeUtil.removeRange(docComment, endRange.getTreeNext());
TreeUtil.insertBefore(first, docComment);
if (startSpaces != null) {
TreeElement anchor = startSpaces;
while (element != endSpaces) {
TreeElement next = element.getTreeNext();
if (element.getElementType() != IMPORT_LIST) {
TreeUtil.remove(element);
TreeUtil.insertAfter(anchor, element);
anchor = element;
}
element = next;
}
}
return true;
}
return false;
}
private static final TokenSet BIND_TRAINLING_COMMENT_BIT_SET = TokenSet.orSet(TokenSet.create(new IElementType[]{
FIELD,
METHOD,
CLASS,
CLASS_INITIALIZER,
IMPORT_STATEMENT,
IMPORT_STATIC_STATEMENT,
PACKAGE_STATEMENT
}),
STATEMENT_BIT_SET);
private static boolean bindTrailingComment(TreeElement comment) {
TreeElement element = comment.getTreePrev();
if (element == null) return false;
TreeElement space = null;
if (element.getElementType() == WHITE_SPACE) {
space = element;
element = element.getTreePrev();
}
if (element != null && BIND_TRAINLING_COMMENT_BIT_SET.isInSet(element.getElementType())) {
if (space == null || (!space.textContains('\n') && !space.textContains('\r'))) {
if (!comment.textContains('\n') && !comment.textContains('\r')) {
if (space != null) {
TreeUtil.remove(space);
TreeUtil.addChildren((CompositeElement)element, space);
}
TreeUtil.remove(comment);
TreeUtil.addChildren((CompositeElement)element, comment);
return true;
}
}
}
return false;
}
private static final TokenSet BIND_PRECEDING_COMMENT_BIT_SET = TokenSet.create(new IElementType[]{
FIELD,
METHOD,
CLASS,
CLASS_INITIALIZER,
});
private static final TokenSet PRECEDING_COMMENT_OR_SPACE_BIT_SET = TokenSet.create(new IElementType[]{
C_STYLE_COMMENT, END_OF_LINE_COMMENT, WHITE_SPACE
});
private static boolean bindPrecedingComment(TreeElement comment) {
ASTNode element = TreeUtil.skipElements(comment, PRECEDING_COMMENT_OR_SPACE_BIT_SET);
if (element == null) return false;
if (element.getElementType() == IMPORT_LIST && element.getTextLength() == 0) {
element = element.getTreeNext();
}
if (element != null && BIND_PRECEDING_COMMENT_BIT_SET.isInSet(element.getElementType())) {
for (ASTNode child = comment; child != element; child = child.getTreeNext()) {
if (child.getElementType() == WHITE_SPACE) {
int count = StringUtil.getLineBreakCount(child.getText());
if (count > 1) return false;
}
else {
if (comment.getTreePrev() != null && comment.getTreePrev().getElementType() == ElementType.WHITE_SPACE) {
LeafElement prev = (LeafElement)comment.getTreePrev();
char lastC = prev.charAt(prev.getTextLength() - 1);
if (lastC == '\n' || lastC == '\r') return false;
}
else {
return false;
}
}
}
// check if the comment is on separate line
if (comment.getTreePrev() != null) {
ASTNode prev = comment.getTreePrev();
if (prev.getElementType() != ElementType.WHITE_SPACE) {
return false;
}
else {
if (!prev.textContains('\n')) return false;
}
}
TreeElement first = (TreeElement)element.getFirstChildNode();
TreeElement child = comment;
while (child != element) {
TreeElement next = child.getTreeNext();
if (child.getElementType() != IMPORT_LIST) {
TreeUtil.remove(child);
TreeUtil.insertBefore(first, child);
}
child = next;
}
return true;
}
return false;
}
}
|
package net.fortuna.ical4j.model.property;
import java.text.ParseException;
import net.fortuna.ical4j.model.Date;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Parameter;
import net.fortuna.ical4j.model.ParameterList;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.TimeZone;
import net.fortuna.ical4j.model.TimeZoneRegistryFactory;
import net.fortuna.ical4j.model.ValidationException;
import net.fortuna.ical4j.model.parameter.TzId;
import net.fortuna.ical4j.model.parameter.Value;
import net.fortuna.ical4j.util.Strings;
/**
* Base class for properties with a DATE or DATE-TIME value. Note that some
* sub-classes may only allow either a DATE or a DATE-TIME value, for which
* additional rules/validation should be specified.
* @author Ben Fortuna
*/
public abstract class DateProperty extends Property {
private Date date;
/**
* @param aName
* @param aList
*/
public DateProperty(final String name, final ParameterList parameters) {
super(name, parameters);
}
/**
* @param aName
*/
public DateProperty(final String name) {
super(name);
}
/**
* @return Returns the date.
*/
public final Date getDate() {
return date;
}
/**
* Sets the date value of this property. The timezone of this instance will
* also be updated accordingly.
* @param date The date to set.
*/
public final void setDate(final Date date) {
if (date instanceof DateTime) {
setTimeZone(((DateTime) date).getTimeZone());
}
this.date = date;
}
/**
* Default setValue() implementation. Allows for either DATE or DATE-TIME
* values.
*/
/* (non-Javadoc)
* @see net.fortuna.ical4j.model.Property#setValue(java.lang.String)
*/
public void setValue(final String value) throws ParseException {
// value can be either a date-time or a date..
if (Value.DATE.equals(getParameters().getParameter(Parameter.VALUE))) {
this.date = new Date(value);
}
else {
this.date = new DateTime(value, getTimeZone());
}
}
/* (non-Javadoc)
* @see net.fortuna.ical4j.model.Property#getValue()
*/
public final String getValue() {
return Strings.valueOf(getDate());
}
/**
* Updates the timezone associated with the property's value. If the specified
* timezone is equivalent to UTC any existing TZID parameters will be removed.
* Note that this method is only applicable where the current date is an
* instance of <code>DateTime</code>. For all other cases an
* <code>UnsupportedOperationException</code> will be thrown.
* @param vTimeZone
*/
public final void setTimeZone(final TimeZone timezone) {
if (timezone != null) {
if (getDate() != null && !(getDate() instanceof DateTime)) {
throw new UnsupportedOperationException("TimeZone is not applicable to current value");
}
if (getDate() != null) {
((DateTime) getDate()).setTimeZone(timezone);
}
getParameters().remove(getParameters().getParameter(Parameter.TZID));
TzId tzId = new TzId(timezone.getID());
getParameters().add(tzId);
}
else {
// use setUtc() to reset timezone..
setUtc(false);
}
}
/**
* Returns the timezone referenced by a TzId parameter. This method is for
* internal use only.
* @return a TimeZone instance, or null if no TzId parameter is specified.
*/
protected final TimeZone getTimeZone() {
Parameter tzId = getParameters().getParameter(Parameter.TZID);
if (tzId != null) {
return TimeZoneRegistryFactory.getInstance().getRegistry().getTimeZone(tzId.getValue());
}
return null;
}
/**
* Resets the VTIMEZONE associated with the property. If utc is true,
* any TZID parameters are removed and the Java timezone is updated
* to UTC time. If utc is false, TZID parameters are removed and the
* Java timezone is set to the default timezone (i.e. represents a
* "floating" local time)
* @param utc
*/
public final void setUtc(final boolean utc) {
if (getDate() != null && !(getDate() instanceof DateTime)) {
throw new UnsupportedOperationException("UTC time is not applicable to current value");
}
if (getDate() != null) {
((DateTime) getDate()).setUtc(utc);
}
getParameters().remove(getParameters().getParameter(Parameter.TZID));
}
/**
* Indicates whether the current date value is specified in UTC time.
* @return
*/
public final boolean isUtc() {
if (getDate() instanceof DateTime) {
return ((DateTime) getDate()).isUtc();
}
return false;
}
/* (non-Javadoc)
* @see net.fortuna.ical4j.model.Property#validate()
*/
public void validate() throws ValidationException {
super.validate();
Value value = (Value) getParameters().getParameter(Parameter.VALUE);
if (value != null && !Value.DATE.equals(value) && !Value.DATE_TIME.equals(value)) {
throw new ValidationException("Invalid VALUE parameter [" + value + "]");
}
if ((Value.DATE.equals(value) && getDate() instanceof DateTime)
|| (Value.DATE_TIME.equals(value) && !(getDate() instanceof DateTime))) {
throw new ValidationException("VALUE parameter [" + value + "] is invalid for date instance");
}
if (getDate() instanceof DateTime) {
DateTime dateTime = (DateTime) date;
// ensure tzid matches date-time timezone..
Parameter tzId = getParameters().getParameter(Parameter.TZID);
if (dateTime.getTimeZone() != null
&& (tzId == null || !tzId.getValue().equals(dateTime.getTimeZone().getID()))) {
throw new ValidationException("TZID parameter [" + tzId + "] does not match the timezone [" + dateTime.getTimeZone().getID() + "]");
}
}
}
}
|
package net.sourceforge.texlipse.spelling;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import net.sourceforge.texlipse.PathUtils;
import net.sourceforge.texlipse.SelectedResourceManager;
import net.sourceforge.texlipse.TexlipsePlugin;
import net.sourceforge.texlipse.builder.BuilderRegistry;
import net.sourceforge.texlipse.properties.TexlipseProperties;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IMarkerResolution;
import org.eclipse.ui.texteditor.MarkerUtilities;
/**
* An abstraction to a spell checker program.
*
* @author Kimmo Karlsson
* @author Georg Lippold
*/
public class SpellChecker implements IPropertyChangeListener, IDocumentListener {
// marker type for the spelling errors
public static final String SPELLING_ERROR_MARKER_TYPE = TexlipseProperties.PACKAGE_NAME + ".spellingproblem";
// preference constants
public static final String SPELL_CHECKER_COMMAND = "spellCmd";
public static final String SPELL_CHECKER_ARGUMENTS = "spellArgs";
public static final String SPELL_CHECKER_ENV = "spellEnv";
private static final String SPELL_CHECKER_ENCODING = "spellEnc";
private static final String encoding = ResourcesPlugin.getEncoding();
// These two strings have to have multiple words, because otherwise
// they may come up in aspells proposals.
public static String SPELL_CHECKER_ADD = "spellCheckerAddToUserDict";
// The values are resource bundle entry IDs at startup.
// They are converted to actual strings in the constructor.
public static String SPELL_CHECKER_IGNORE = "spellCheckerIgnoreWord";
/**
* A Spell-checker job.
*/
class SpellCheckJob extends Job {
// the document to check for spelling
private IDocument document;
// the file that contains the document
private IFile file;
/**
* Create a new spell-checker job for the given document.
* @param name document name
* @param doc document
*/
public SpellCheckJob(String name, IDocument doc, IFile file) {
super(name);
document = doc;
this.file = file;
}
/**
* Run the spell checker.
*/
protected IStatus run(IProgressMonitor monitor) {
SpellChecker.checkSpellingDirectly(document, file, monitor);
return new Status(IStatus.OK, TexlipsePlugin.getPluginId(), IStatus.OK, "ok", null);
}
}
// the shared instance
private static SpellChecker instance = new SpellChecker();
// the external spelling program
private Process spellProgram;
// the stream to the program
private PrintWriter output;
// the stream from the program
private BufferedReader input;
// spelling program command with arguments
private String command;
// environment variables for the program
private String[] envp;
// map of proposals so far
private HashMap proposalMap;
// the current language
private String language;
/**
* Private constructor, because we want to keep this singleton.
*/
private SpellChecker() {
proposalMap = new HashMap();
language = "en";
// these two must be initialized in the constructor, otherwise the resource bundle may not be initialized
SPELL_CHECKER_ADD = TexlipsePlugin.getResourceString(SPELL_CHECKER_ADD);
SPELL_CHECKER_IGNORE = TexlipsePlugin.getResourceString(SPELL_CHECKER_IGNORE);
}
/**
* Initialize the spell checker. This method must be called only once.
* Preferably from PreferenceInitializer.
*
* @param prefs the plugin preferences
*/
public static void initializeDefaults(IPreferenceStore prefs) {
String aspell = PathUtils.findEnvFile("aspell", "/usr/bin", "aspell.exe", "C:\\gnu\\aspell");
prefs.setDefault(SPELL_CHECKER_COMMAND, aspell);
// -a == ispell compatibility mode, -t == tex mode
prefs.setDefault(SPELL_CHECKER_ENV, "");
prefs.setDefault(SPELL_CHECKER_ARGUMENTS,
"-a -t --lang=%language --encoding=%encoding");
prefs.setDefault(SPELL_CHECKER_ENCODING, encoding);
prefs.addPropertyChangeListener(instance);
instance.readSettings();
}
/**
* Add the given word to Aspell user dictionary.
* @param word word to add
*/
public static void addWordToAspell(String word) {
String path = TexlipsePlugin.getPreference(SPELL_CHECKER_COMMAND);
if (path == null || path.length() == 0) {
return;
}
File f = new File(path);
if (!f.exists() || f.isDirectory()) {
return;
}
String args = "--encoding=" + encoding
+ " --lang=" + instance.language + " -a";
BuilderRegistry.printToConsole("aspell> adding word: " + word);
String cmd = f.getAbsolutePath() + " " + args;
String[] environp = PathUtils.mergeEnvFromPrefs(PathUtils.getEnv(),
SPELL_CHECKER_ENV);
try {
Process p = Runtime.getRuntime().exec(cmd, environp);
PrintWriter w = new PrintWriter(p.getOutputStream());
w.println("*" + word);
w.println("
w.flush();
w.close();
p.getOutputStream().close();
p.waitFor();
} catch (Exception e) {
BuilderRegistry.printToConsole("Error adding word \""
+ word + "\" to Aspell user dict\n");
TexlipsePlugin.log("Adding word \""
+ word + "\" to Aspell user dict", e);
}
}
/**
* Read settings from the preferences.
*/
private void readSettings() {
command = null;
envp = null;
String path = TexlipsePlugin.getPreference(SPELL_CHECKER_COMMAND);
if (path == null || path.length() == 0) {
return;
}
File f = new File(path);
if (!f.exists() || f.isDirectory()) {
return;
}
String args = TexlipsePlugin.getPreference(SPELL_CHECKER_ARGUMENTS);
args = args.replaceAll("%encoding", TexlipsePlugin.getPreference(SPELL_CHECKER_ENCODING));
args = args.replaceAll("%language", language);
command = f.getAbsolutePath() + " " + args;
envp = PathUtils.mergeEnvFromPrefs(PathUtils.getEnv(), SPELL_CHECKER_ENV);
}
/**
* Check that the current language setting is correct.
*/
private void checkLanguage(IFile file) {
String pLang = null;
IProject prj = file.getProject();
if (prj != null) {
pLang = TexlipseProperties.getProjectProperty(prj, TexlipseProperties.LANGUAGE_PROPERTY);
}
if (pLang != null && pLang.length() > 0) {
if (!pLang.equals(language)) {
// current project is different language than currently running process, so change
language = pLang;
stopProgram();
readSettings();
}
}
}
/**
* Check if the spelling program is still running.
* Restart the program, if necessary.
* @param file
*/
protected void checkProgram(IFile file) {
checkLanguage(file);
if (spellProgram == null) {
startProgram();
} else {
int exitCode = -1;
try {
exitCode = spellProgram.exitValue();
} catch (IllegalThreadStateException e) {
// program is still running, good
}
if (exitCode != -1) {
// an exit code is defined, so program has ended
spellProgram = null;
startProgram();
}
}
}
/**
* Restarts the spelling program.
* Assumes that the program is not currently running.
*/
private void startProgram() {
BuilderRegistry.printToConsole(TexlipsePlugin.getResourceString("viewerRunning") + ' ' + command);
try {
spellProgram = Runtime.getRuntime().exec(command, envp);
} catch (IOException e) {
spellProgram = null;
input = null;
output = null;
BuilderRegistry.printToConsole(TexlipsePlugin.getResourceString("spellProgramStartError"));
return;
}
// get output stream
output = new PrintWriter(spellProgram.getOutputStream());
// get input stream
input = new BufferedReader(new InputStreamReader(spellProgram
.getInputStream()));
// read the version info
try {
String message = input.readLine();
BuilderRegistry.printToConsole("aspell> " + message.trim());
// Now it's up and running :)
// put it in terse mode, then it's faster
output.println("!");
} catch (IOException e) {
TexlipsePlugin.log("Aspell died", e);
BuilderRegistry.printToConsole(TexlipsePlugin.getResourceString("spellProgramStartError"));
}
}
/**
* Stop running the spelling program.
*/
private void stopProgram() {
if (spellProgram != null) {
spellProgram.destroy();
spellProgram = null;
}
}
/**
* Set the spell checker encoding.
* @param enc encoding to use
*/
public static void setEncoding(String enc) {
TexlipsePlugin.getDefault().getPreferenceStore().setValue(SPELL_CHECKER_ENCODING, enc);
// don't stop program yet, because the given encoding might not be different from current setting
}
/**
* The IPropertyChangeListener method.
* Re-reads the settings from preferences.
*/
public void propertyChange(PropertyChangeEvent event) {
String prop = event.getProperty();
if (prop.startsWith("spell")) {
// encoding, program args or program path changed
//BuilderRegistry.printToConsole("spelling property changed: " + prop);
stopProgram();
readSettings();
}
}
/**
* Check spelling of a single line.
*
* @param line the line of text
* @param offset start offset of the line in the document
* @param file file
* @return fix proposals, or empty array if all correct
*/
public static void checkSpelling(String line, int offset, int lineNumber, IFile file) {
instance.checkProgram(file);
instance.checkLineSpelling(line, offset, lineNumber, file);
}
/**
* Check spelling of the entire document.
* This method returns after scheduling a spell-checker job.
* @param document document from the editor
* @param file
*/
public static void checkSpelling(IDocument document, IFile file) {
instance.startSpellCheck(document, file);
}
/**
* Check spelling of the entire document.
* This method returns after scheduling a spell-checker job.
* @param document document from the editor
*/
private void startSpellCheck(IDocument document, IFile file) {
Job job = new SpellCheckJob("Spellchecker", document, file);
job.setUser(true);
job.schedule();
}
/**
* Check spelling of the entire document.
* This method actually checks the spelling.
* @param document document from the editor
*/
private static void checkSpellingDirectly(IDocument document, IFile file, IProgressMonitor monitor) {
instance.checkProgram(file);
instance.checkDocumentSpelling(document, file, monitor);
}
/**
* Check spelling of the entire document.
*
* @param doc the document
* @param file
*/
private void checkDocumentSpelling(IDocument doc, IFile file, IProgressMonitor monitor) {
deleteOldProposals(file);
doc.addDocumentListener(instance);
try {
int num = doc.getNumberOfLines();
monitor.beginTask("Check spelling", num);
for (int i = 0; i < num; i++) {
int offset = doc.getLineOffset(i);
int length = doc.getLineLength(i);
String line = doc.get(offset, length);
checkLineSpelling(line, offset, i+1, file);
monitor.worked(1);
}
} catch (BadLocationException e) {
TexlipsePlugin.log("Checking spelling on a line", e);
}
stopProgram();
}
/**
* Check spelling of a single line.
* This method parses ispell-style spelling error proposals.
*
* @param line the line of text
* @param offset start offset of the line in the document
* @param file
* @return fix proposals, or empty array if all correct
*/
private void checkLineSpelling(String line, int offset, int lineNumber, IFile file) {
// check that there is text for the checker
if (line == null || line.length() == 0) {
return;
}
if (line.trim().length() == 0) {
return;
}
// give the speller something to parse
String lineToPost = line;
if (language.equals("de")) {
// from Boris Brodski:
// This is very usefull for german texts
// It's not a clean solution.
// TODO The problem: if ASpell found a error in the word with \"... command
// a marker will set wrong.
lineToPost = lineToPost.replaceAll("\\\"a", "");
lineToPost = lineToPost.replaceAll("\\\"u", "");
lineToPost = lineToPost.replaceAll("\\\"o", "");
lineToPost = lineToPost.replaceAll("\\\"A", "");
lineToPost = lineToPost.replaceAll("\\\"U", "");
lineToPost = lineToPost.replaceAll("\\\"O", "");
lineToPost = lineToPost.replaceAll("\\ss ", "");
lineToPost = lineToPost.replaceAll("\\ss\\", "\\");
}
output.println("^" + lineToPost);
output.flush();
// wait until there is input
ArrayList lines = new ArrayList();
try {
String result = input.readLine();
while ((!"".equals(result)) && (result != null)) {
lines.add(result);
result = input.readLine();
}
} catch (IOException e) {
BuilderRegistry.printToConsole(TexlipsePlugin.getResourceString("spellProgramStartError"));
TexlipsePlugin.log("aspell error at line " + lineNumber + ": " + lineToPost, e);
}
// loop through the output lines (they contain only errors)
for (int i = 0; i < lines.size(); i++) {
String[] tmp = ((String) lines.get(i)).split(":");
String[] error = tmp[0].split(" ");
String word = error[1].trim();
// column, where the word starts in the line of text
// is always the last entry in error (sometimes 3, if there
// are matches, else 2)
// we have to subtract 1 since the first char is always "^"
int column = Integer.valueOf(error[error.length - 1]).intValue() - 1;
// if we have multi byte chars (e.g. umlauts in utf-8), then aspell
// returns them as multiple columns. computing the difference
// between byte-length and String-length:
byte[] bytes = lineToPost.getBytes();
byte[] before = new byte[column];
for (int j = 0; j < column; j++) {
before[j] = bytes[j];
}
int difference = column - (new String(before)).length();
column -= difference;
// list of proposals starts after the colon
String[] options;
if (tmp.length > 1) {
String[] proposals = (tmp[1].trim()).split(", ");
options = new String[proposals.length + 2];
for (int j = 0; j < proposals.length; j++) {
options[j] = proposals[j].trim();
}
} else {
options = new String[2];
}
options[options.length - 2] = SPELL_CHECKER_IGNORE;
options[options.length - 1] = SPELL_CHECKER_ADD;
createMarker(file, options, offset + column, word.length(),
lineNumber);
}
}
/**
* Adds a spelling error marker to the given file.
*
* @param file the resource to add the marker to
* @param proposals list of proposals for correcting the error
* @param charBegin beginning offset in the file
* @param wordLength length of the misspelled word
*/
private void createMarker(IResource file, String[] proposals, int charBegin, int wordLength, int lineNumber) {
HashMap attributes = new HashMap();
attributes.put(IMarker.CHAR_START, new Integer(charBegin));
attributes.put(IMarker.CHAR_END, new Integer(charBegin+wordLength));
attributes.put(IMarker.LINE_NUMBER, new Integer(lineNumber));
attributes.put(IMarker.SEVERITY, new Integer(IMarker.SEVERITY_WARNING));
attributes.put(IMarker.MESSAGE, TexlipsePlugin.getResourceString("spellMarkerMessage"));
try {
MarkerUtilities.createMarker(file, attributes, SPELLING_ERROR_MARKER_TYPE);
addProposal(file, charBegin, charBegin+wordLength, proposals);
} catch (CoreException e) {
TexlipsePlugin.log("Adding spelling marker", e);
}
}
/**
* Adds a spelling error marker at the given offset in the file.
*
* @param file file the was spell-checked
* @param begin beginning offset of the misspelled word
* @param end ending offset of the misspelled word
* @param proposals correction proposals for the misspelled word
* @throws CoreException
*/
private void addProposal(IResource file, int begin, int end, String[] proposals) throws CoreException {
IMarker[] markers = file.findMarkers(SPELLING_ERROR_MARKER_TYPE, false, IResource.DEPTH_ZERO);
for (int i = 0; i < markers.length; i++) {
int charStart = markers[i].getAttribute(IMarker.CHAR_START, -1);
int charEnd = markers[i].getAttribute(IMarker.CHAR_END, -1);
if (charStart == begin && charEnd == end) {
proposalMap.put(markers[i], proposals);
return;
}
}
}
/**
* Clear all spelling error markers.
*/
public static void clearMarkers(IResource resource) {
instance.deleteOldProposals(resource);
}
/**
* Deletes all the error markers of the previous check.
* This has to be done to avoid duplicates.
* Also, old markers are probably not anymore in the correct positions.
*/
private void deleteOldProposals(IResource res) {
// delete all markers with proposals, because there might be something in the other files
Iterator iter = proposalMap.keySet().iterator();
while (iter.hasNext()) {
IMarker marker = (IMarker) iter.next();
try {
marker.delete();
} catch (CoreException e) {
TexlipsePlugin.log("Deleting marker", e);
}
}
// just in case delete all markers from this file
try {
res.deleteMarkers(SPELLING_ERROR_MARKER_TYPE, false, IResource.DEPTH_ONE);
} catch (CoreException e) {
TexlipsePlugin.log("Deleting markers", e);
}
// clear the old proposals
proposalMap.clear();
}
/**
* Returns the spelling correction proposal words for the given marker.
*
* @param marker a marker
* @return correction proposals
*/
public static String[] getProposals(IMarker marker) {
return (String[]) instance.proposalMap.get(marker);
}
/**
* Finds the spelling correction proposals for the word at the given offset.
*
* @param offset text offset in the current file
* @return completion proposals, or null if there is no marker at the given offset
*/
public static ICompletionProposal[] getSpellingProposal(int offset) {
IResource res = SelectedResourceManager.getDefault().getSelectedResource();
if (res == null) {
return null;
}
IMarker[] markers = null;
try {
markers = res.findMarkers(SPELLING_ERROR_MARKER_TYPE, false, IResource.DEPTH_ZERO);
} catch (CoreException e) {
return null;
}
for (int i = 0; i < markers.length; i++) {
int charBegin = markers[i].getAttribute(IMarker.CHAR_START, -1);
int charEnd = markers[i].getAttribute(IMarker.CHAR_END, -1);
if (charBegin <= offset && offset <= charEnd) {
SpellingResolutionGenerator gen = new SpellingResolutionGenerator();
return convertAll(gen.getResolutions(markers[i]), markers[i]);
}
}
return null;
}
/**
* Converts the given marker resolutions to completion proposals.
*
* @param resolutions marker resolutions
* @param marker marker that holds the given resolutions
* @return completion proposals for the given marker
*/
private static ICompletionProposal[] convertAll(IMarkerResolution[] resolutions, IMarker marker) {
ICompletionProposal[] array = new ICompletionProposal[resolutions.length];
for (int i = 0; i < resolutions.length; i++) {
SpellingMarkerResolution smr = (SpellingMarkerResolution) resolutions[i];
array[i] = new SpellingCompletionProposal(smr.getSolution(), marker);
}
return array;
}
/**
* The manipulation described by the document event will be performed.
* This implementation does nothing.
* @param event the document event describing the document change
*/
public void documentAboutToBeChanged(DocumentEvent event) {
}
/**
* The manipulation described by the document event has been performed.
* This implementation updates spelling error markers to get the positions
* right.
* @param event the document event describing the document change
*/
public void documentChanged(DocumentEvent event) {
int origLength = event.getLength();
String eventText = event.getText();
if (eventText == null) {
eventText = "";
}
int length = eventText.length();
int offset = event.getOffset();
int diff = length - origLength;
Iterator iter = proposalMap.keySet().iterator();
while (iter.hasNext()) {
IMarker marker = (IMarker) iter.next();
int start = marker.getAttribute(IMarker.CHAR_START, -1);
if (start > offset) {
int end = marker.getAttribute(IMarker.CHAR_END, -1);
try {
marker.setAttribute(IMarker.CHAR_START, start + diff);
marker.setAttribute(IMarker.CHAR_END, end + diff);
} catch (CoreException e) {
TexlipsePlugin.log("Setting marker location", e);
}
}
}
}
}
|
package org.voltdb.regressionsuites;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import junit.framework.Test;
import org.voltdb.BackendTarget;
import org.voltdb.VoltTable;
import org.voltdb.client.Client;
import org.voltdb.client.ClientFactory;
import org.voltdb.client.ClientResponse;
import org.voltdb.client.ProcedureCallback;
import org.voltdb.compiler.VoltProjectBuilder;
public class TestStopNode extends RegressionSuite
{
static LocalCluster m_config;
public TestStopNode(String name) {
super(name);
}
static VoltProjectBuilder getBuilderForTest() throws IOException {
VoltProjectBuilder builder = new VoltProjectBuilder();
builder.addLiteralSchema("");
return builder;
}
class StopCallBack implements ProcedureCallback {
final byte m_status;
final int m_hid;
final CountDownLatch m_cdl;
public StopCallBack(CountDownLatch cdl, byte status, int hid) {
m_status = status;
m_hid = hid;
m_cdl = cdl;
}
@Override
public void clientCallback(ClientResponse clientResponse) throws Exception {
m_cdl.countDown();
System.out.println("Host " + m_hid
+ " Result : " + clientResponse.getStatusString() + " Status: " + clientResponse.getStatus());
assertEquals(m_status, clientResponse.getStatus());
}
}
public void waitForHostToBeGone(Client client, int hid) {
while (true) {
VoltTable table = null;
try {
Thread.sleep(1000);
table = client.callProcedure("@SystemInformation", "overview").getResults()[0];
} catch (Exception ex) {
ex.printStackTrace();
continue;
}
boolean done = true;
while (table.advanceRow()) {
long hc = table.getLong("HOST_ID");
if (hc == hid) {
done = false;
break;
}
}
System.out.println("Host " + hid + " Still there");
if (done) {
return;
}
}
}
public void testStopNode() throws Exception {
Client client = ClientFactory.createClient();
client.createConnection("localhost", m_config.port(0));
try {
CountDownLatch cdl = new CountDownLatch(1);
client.callProcedure(new StopCallBack(cdl, ClientResponse.SUCCESS, 4), "@StopNode", 4);
cdl.await();
waitForHostToBeGone(client, 4);
cdl = new CountDownLatch(1);
client.callProcedure(new StopCallBack(cdl, ClientResponse.SUCCESS, 3), "@StopNode", 3);
cdl.await();
waitForHostToBeGone(client, 3);
cdl = new CountDownLatch(1);
client.callProcedure(new StopCallBack(cdl, ClientResponse.SUCCESS, 2), "@StopNode", 2);
cdl.await();
waitForHostToBeGone(client, 2);
client.callProcedure("@SystemInformation", "overview");
} catch (Exception ex) {
//We should not get here
fail();
ex.printStackTrace();
}
boolean lostConnect = false;
try {
CountDownLatch cdl = new CountDownLatch(3);
//Stop a node that should stay up
client.callProcedure(new StopCallBack(cdl, ClientResponse.GRACEFUL_FAILURE, 1), "@StopNode", 1);
//Stop already stopped node.
client.callProcedure(new StopCallBack(cdl, ClientResponse.GRACEFUL_FAILURE, 4), "@StopNode", 4);
//Stop a node that should stay up
client.callProcedure(new StopCallBack(cdl, ClientResponse.GRACEFUL_FAILURE, 0), "@StopNode", 0);
VoltTable tab = client.callProcedure("@SystemInformation", "overview").getResults()[0];
cdl.await();
} catch (Exception pce) {
pce.printStackTrace();
lostConnect = pce.getMessage().contains("was lost before a response was received");
}
//We should never lose contact.
assertFalse(lostConnect);
}
@Override
public void tearDown() throws Exception {
super.tearDown();
}
static public Test suite() throws IOException {
// the suite made here will all be using the tests from this class
MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestStopNode.class);
// build up a project builder for the workload
VoltProjectBuilder project = getBuilderForTest();
boolean success;
//Lets tolerate 3 node failures.
m_config = new LocalCluster("decimal-default.jar", 4, 5, 3, BackendTarget.NATIVE_EE_JNI);
m_config.setHasLocalServer(false);
success = m_config.compile(project);
assertTrue(success);
// add this config to the set of tests to run
builder.addServerConfig(m_config);
return builder;
}
}
|
package morfologik.speller;
import static morfologik.fsa.MatchResult.EXACT_MATCH;
import static morfologik.fsa.MatchResult.SEQUENCE_IS_A_PREFIX;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import morfologik.fsa.FSA;
import morfologik.fsa.FSAFinalStatesIterator;
import morfologik.fsa.FSATraversal;
import morfologik.fsa.MatchResult;
import morfologik.stemming.Dictionary;
import morfologik.stemming.DictionaryMetadata;
import morfologik.util.BufferUtils;
public class Speller {
public static int MAX_WORD_LENGTH = 120;
final static int FREQ_RANGES = 26;
final static int FIRST_RANGE_CODE = 65; // character 'A', less frequent words
private final int editDistance;
private int e_d; // effective edit distance
private final HMatrix hMatrix;
private char[] candidate; /* current replacement */
private int candLen;
private int wordLen; /* length of word being processed */
private char[] word_ff; /* word being processed */
/**
* List of candidate strings, including same additional data such as
* edit distance from the original word.
*/
private final List<CandidateData> candidates = new ArrayList<CandidateData>();
private boolean containsSeparators = true;
/**
* Internal reusable buffer for encoding words into byte arrays using
* {@link #encoder}.
*/
private ByteBuffer byteBuffer = ByteBuffer.allocate(MAX_WORD_LENGTH);
/**
* Internal reusable buffer for encoding words into byte arrays using
* {@link #encoder}.
*/
private CharBuffer charBuffer = CharBuffer.allocate(MAX_WORD_LENGTH);
/**
* Reusable match result.
*/
private final MatchResult matchResult = new MatchResult();
/**
* Features of the compiled dictionary.
*
* @see DictionaryMetadata
*/
private final DictionaryMetadata dictionaryMetadata;
/**
* Charset encoder for the FSA.
*/
private final CharsetEncoder encoder;
/**
* Charset decoder for the FSA.
*/
protected final CharsetDecoder decoder;
/** An FSA used for lookups. */
private final FSATraversal matcher;
/** FSA's root node. */
private final int rootNode;
/**
* The FSA we are using.
*/
protected final FSA fsa;
/** An iterator for walking along the final states of {@link #fsa}. */
private final FSAFinalStatesIterator finalStatesIterator;
public Speller(final Dictionary dictionary) {
this(dictionary, 1);
}
public Speller(final Dictionary dictionary, final int editDistance) {
this(dictionary, editDistance, true);
}
public Speller(final Dictionary dictionary, final int editDistance, final boolean convertCase) {
this.editDistance = editDistance;
hMatrix = new HMatrix(editDistance, MAX_WORD_LENGTH);
this.dictionaryMetadata = dictionary.metadata;
this.rootNode = dictionary.fsa.getRootNode();
this.fsa = dictionary.fsa;
this.matcher = new FSATraversal(fsa);
this.finalStatesIterator = new FSAFinalStatesIterator(fsa, rootNode);
if (rootNode == 0) {
throw new IllegalArgumentException(
"Dictionary must have at least the root node.");
}
if (dictionaryMetadata == null) {
throw new IllegalArgumentException(
"Dictionary metadata must not be null.");
}
encoder = dictionaryMetadata.getEncoder();
decoder = dictionaryMetadata.getDecoder();
// Multibyte separator will result in an exception here.
dictionaryMetadata.getSeparatorAsChar();
}
/**
* Encode a character sequence into a byte buffer, optionally expanding
* buffer.
*/
private ByteBuffer charsToBytes(final CharBuffer chars, ByteBuffer bytes) {
bytes.clear();
final int maxCapacity = (int) (chars.remaining() * encoder.maxBytesPerChar());
if (bytes.capacity() <= maxCapacity) {
bytes = ByteBuffer.allocate(maxCapacity);
}
chars.mark();
encoder.reset();
if (encoder.encode(chars, bytes, true).isError()) {
// in the case of encoding errors, clear the buffer
bytes.clear();
}
bytes.flip();
chars.reset();
return bytes;
}
private ByteBuffer charSequenceToBytes(final CharSequence word) {
// Encode word characters into bytes in the same encoding as the FSA's.
charBuffer.clear();
charBuffer = BufferUtils.ensureCapacity(charBuffer, word.length());
for (int i = 0; i < word.length(); i++) {
final char chr = word.charAt(i);
charBuffer.put(chr);
}
charBuffer.flip();
byteBuffer = charsToBytes(charBuffer, byteBuffer);
return byteBuffer;
}
public boolean isMisspelled(String word) {
// dictionaries usually do not contain punctuation.
boolean isAlphabetic = word.length() != 1 || isAlphabetic(word.charAt(0));
return word.length() > 0
&& (!dictionaryMetadata.isIgnoringPunctuation() || isAlphabetic)
&& (!dictionaryMetadata.isIgnoringNumbers() || !containsDigit(word))
&& !(dictionaryMetadata.isIgnoringCamelCase() && isCamelCase(word))
&& !(dictionaryMetadata.isIgnoringAllUppercase() && isAlphabetic && isAllUppercase(word))
&& !isInDictionary(word)
&& (!dictionaryMetadata.isConvertingCase() ||
!(!isMixedCase(word) && isInDictionary(word.toLowerCase(dictionaryMetadata.getLocale()))));
}
/**
* Test whether the word is found in the dictionary.
* @param word the word to be tested
* @return True if it is found.
*/
public boolean isInDictionary(final CharSequence word) {
byteBuffer = charSequenceToBytes(word);
// Try to find a partial match in the dictionary.
final MatchResult match = matcher.match(matchResult,
byteBuffer.array(), 0, byteBuffer.remaining(), rootNode);
if (match.kind == EXACT_MATCH) {
containsSeparators = false;
return true;
}
return containsSeparators
&& match.kind == SEQUENCE_IS_A_PREFIX
&& fsa.getArc(match.node, dictionaryMetadata.getSeparator()) != 0;
}
/**
* Get the frequency value for a word form.
* It is taken from the first entry with this word form.
* @param word the word to be tested
* @return frequency value in range: 0..FREQ_RANGE-1 (0: less frequent).
*/
public int getFrequency(final CharSequence word) {
if (!dictionaryMetadata.isFrequencyIncluded()) {
return 0;
}
final byte separator = dictionaryMetadata.getSeparator();
byteBuffer = charSequenceToBytes(word);
final MatchResult match = matcher.match(matchResult, byteBuffer.array(), 0,
byteBuffer.remaining(), rootNode);
if (match.kind == SEQUENCE_IS_A_PREFIX) {
final int arc = fsa.getArc(match.node, separator);
if (arc != 0 && !fsa.isArcFinal(arc)) {
finalStatesIterator.restartFrom(fsa.getEndNode(arc));
if (finalStatesIterator.hasNext()) {
final ByteBuffer bb = finalStatesIterator.next();
final byte[] ba = bb.array();
final int bbSize = bb.remaining();
//the last byte contains the frequency after a separator
return ba[bbSize - 1] - FIRST_RANGE_CODE;
}
}
}
return 0;
}
/**
* Propose suggestions for misspelled run-on words. This algorithm is inspired by
* spell.cc in s_fsa package by Jan Daciuk.
*
* @param original The original misspelled word.
* @return The list of suggested pairs, as space-concatenated strings.
*/
public List<String> replaceRunOnWords(final String original) {
final List<String> candidates = new ArrayList<String>();
if (!isInDictionary(original) && dictionaryMetadata.isSupportingRunOnWords()) {
final CharSequence ch = original;
for (int i = 2; i < ch.length(); i++) {
// chop from left to right
final CharSequence firstCh = ch.subSequence(0, i);
if (isInDictionary(firstCh) &&
isInDictionary(ch.subSequence(i, ch.length()))) {
candidates.add(firstCh + " " + ch.subSequence(i, ch.length()));
}
}
}
return candidates;
}
/**
* Find suggestions by using K. Oflazer's algorithm. See Jan Daciuk's s_fsa
* package, spell.cc for further explanation.
*
* @param word
* The original misspelled word.
* @return A list of suggested replacements.
* @throws CharacterCodingException
*/
public List<String> findReplacements(final String word)
throws CharacterCodingException {
candidates.clear();
if (!isInDictionary(word) && word.length() < MAX_WORD_LENGTH) {
List<String> wordsToCheck = new ArrayList<String>();
if (dictionaryMetadata.getReplacementPairs() != null) {
for (final String wordChecked : getAllReplacements(word, 0, 0)) {
if (isInDictionary(wordChecked)
|| dictionaryMetadata.isConvertingCase()
&& isMixedCase(wordChecked)
&& isInDictionary(wordChecked.toLowerCase(dictionaryMetadata.getLocale()))) {
candidates.add(new CandidateData(wordChecked, 0));
} else {
wordsToCheck.add(wordChecked);
}
}
} else {
wordsToCheck.add(word);
}
//If at least one candidate was found with the replacement pairs (which are usual errors),
//probably there is no need for more candidates
if (candidates.isEmpty()) {
for (final String wordChecked : wordsToCheck) {
word_ff = wordChecked.toCharArray();
wordLen = word_ff.length;
candidate = new char[MAX_WORD_LENGTH];
candLen = candidate.length;
e_d = (wordLen <= editDistance ? (wordLen - 1) : editDistance);
charBuffer = BufferUtils.ensureCapacity(charBuffer, MAX_WORD_LENGTH);
byteBuffer = BufferUtils.ensureCapacity(byteBuffer, MAX_WORD_LENGTH);
charBuffer.clear();
byteBuffer.clear();
final byte[] prevBytes = new byte[0];
findRepl(0, fsa.getRootNode(), prevBytes);
}
}
}
Collections.sort(candidates);
//FIXME: I'm an ugly hack
//Use LinkedHashSet to avoid duplicates and keep the order
final Set<String> candStringSet = new LinkedHashSet<String>();
for (final CandidateData cd : candidates) {
candStringSet.add(cd.getWord());
}
final List<String> candStringList = new ArrayList<String>(candStringSet.size());
candStringList.addAll(candStringSet);
return candStringList;
}
private void findRepl(final int depth, final int node, final byte[] prevBytes)
throws CharacterCodingException {
char separatorChar = dictionaryMetadata.getSeparatorAsChar();
int dist = 0;
for (int arc = fsa.getFirstArc(node); arc != 0; arc = fsa.getNextArc(arc)) {
byteBuffer = BufferUtils.ensureCapacity(byteBuffer, prevBytes.length + 1);
byteBuffer.clear();
byteBuffer.put(prevBytes);
byteBuffer.put(fsa.getArcLabel(arc));
final int bufPos = byteBuffer.position();
byteBuffer.flip();
decoder.reset();
final CoderResult c = decoder.decode(byteBuffer, charBuffer, true);
if (c.isMalformed()) { // assume that only valid
// encodings are there
final byte[] prev = new byte[bufPos];
byteBuffer.position(0);
byteBuffer.get(prev);
if (!fsa.isArcTerminal(arc)) {
findRepl(depth, fsa.getEndNode(arc), prev); // note: depth is not incremented
}
byteBuffer.clear();
} else if (!c.isError()) { // unmappable characters are silently discarded
charBuffer.flip();
candidate[depth] = charBuffer.get();
charBuffer.clear();
byteBuffer.clear();
if (cuted(depth) <= e_d) {
if (Math.abs(wordLen - 1 - depth) <= e_d
&& (dist = ed(wordLen - 1, depth)) <= e_d
&& (fsa.isArcFinal(arc) || isBeforeSeparator(arc))) {
addCandidate(depth, dist);
}
if (!fsa.isArcTerminal(arc)
&& !(containsSeparators && candidate[depth] == separatorChar)) {
findRepl(depth + 1, fsa.getEndNode(arc), new byte[0]);
}
}
}
}
return;
}
private boolean isBeforeSeparator(final int arc) {
if (containsSeparators) {
final int arc1 = fsa.getArc(fsa.getEndNode(arc), dictionaryMetadata.getSeparator());
return (arc1 != 0 && !fsa.isArcTerminal(arc1));
}
return false;
}
private void addCandidate(final int depth, final int dist)
throws CharacterCodingException {
final StringBuilder sb = new StringBuilder(depth);
sb.append(candidate, 0, depth + 1);
candidates.add(new CandidateData(sb.toString(), dist));
}
/**
* Calculates edit distance.
*
* @param i length of first word (here: misspelled) - 1;
* @param j length of second word (here: candidate) - 1.
* @return Edit distance between the two words. Remarks: See Oflazer.
*/
public int ed(final int i, final int j) {
int result;
int a, b, c;
if (areEqual(word_ff[i], candidate[j])) {
// last characters are the same
result = hMatrix.get(i, j);
} else if (i > 0 && j > 0 && word_ff[i] == candidate[j - 1]
&& word_ff[i - 1] == candidate[j]) {
// last two characters are transposed
a = hMatrix.get(i - 1, j - 1); // transposition, e.g. ababab, ababba
b = hMatrix.get(i + 1, j); // deletion, e.g. abab, aba
c = hMatrix.get(i, j + 1); // insertion e.g. aba, abab
result = 1 + min(a, b, c);
} else {
// otherwise
a = hMatrix.get(i, j); // replacement, e.g. ababa, ababb
b = hMatrix.get(i + 1, j); // deletion, e.g. ab, a
c = hMatrix.get(i, j + 1); // insertion e.g. a, ab
result = 1 + min(a, b, c);
}
hMatrix.set(i + 1, j + 1, result);
return result;
}
// by Jaume Ortola
private boolean areEqual(char x, char y) {
if (x == y) {
return true;
}
if (dictionaryMetadata.getEquivalentChars() != null) {
if (dictionaryMetadata.getEquivalentChars().containsKey(x)
&& dictionaryMetadata.getEquivalentChars().get(x).contains(y))
return true;
}
if (dictionaryMetadata.isIgnoringDiacritics()) {
String xn = Normalizer.normalize(Character.toString(x), Form.NFD);
String yn = Normalizer.normalize(Character.toString(y), Form.NFD);
if (dictionaryMetadata.isConvertingCase()) {
xn = xn.toLowerCase(dictionaryMetadata.getLocale());
yn = yn.toLowerCase(dictionaryMetadata.getLocale());
}
return xn.charAt(0) == yn.charAt(0);
}
return false;
}
/**
* Calculates cut-off edit distance.
*
* @param depth current length of candidates.
* @return Cut-off edit distance. Remarks: See Oflazer.
*/
public int cuted(final int depth) {
final int l = Math.max(0, depth - e_d); // min chars from word to consider - 1
final int u = Math.min(wordLen - 1, depth + e_d); // max chars from word to
// consider - 1
int min_ed = e_d + 1; // what is to be computed
int d;
for (int i = l; i <= u; i++) {
if ((d = ed(i, depth)) < min_ed) {
min_ed = d;
}
}
return min_ed;
}
private static int min(final int a, final int b, final int c) {
return Math.min(a, Math.min(b, c));
}
/**
* Copy-paste of Character.isAlphabetic() (needed as we require only 1.6)
*
* @param codePoint The input character.
* @return True if the character is a Unicode alphabetic character.
*/
static boolean isAlphabetic(int codePoint) {
return (((((1 << Character.UPPERCASE_LETTER)
| (1 << Character.LOWERCASE_LETTER)
| (1 << Character.TITLECASE_LETTER)
| (1 << Character.MODIFIER_LETTER)
| (1 << Character.OTHER_LETTER)
| (1 << Character.LETTER_NUMBER)) >> Character.getType(codePoint)) & 1) != 0);
}
/**
* Checks whether a string contains a digit. Used for ignoring words with
* numbers
* @param s Word to be checked.
* @return True if there is a digit inside the word.
*/
static boolean containsDigit(final String s) {
for (int k = 0; k < s.length(); k++) {
if (Character.isDigit(s.charAt(k))) {
return true;
}
}
return false;
}
/**
* Returns true if <code>str</code> is made up of all-uppercase characters
* (ignoring characters for which no upper-/lowercase distinction exists).
*/
boolean isAllUppercase(final String str) {
return str.equals(str.toUpperCase(dictionaryMetadata.getLocale()));
}
/**
* @param str input string
*/
boolean isCapitalizedWord(final String str) {
if (!isEmpty(str)) {
if (Character.isUpperCase(str.charAt(0))) {
String substring = str.substring(1);
return substring.equals(substring.toLowerCase(dictionaryMetadata.getLocale()));
}
}
return false;
}
/**
* Helper method to replace calls to "".equals().
*
* @param str
* String to check
* @return true if string is empty OR null
*/
static boolean isEmpty(final String str) {
return str == null || str.length() == 0;
}
/**
* @param str input str
* @return Returns true if str is MixedCase.
*/
boolean isMixedCase(final String str) {
return !isAllUppercase(str)
&& !isCapitalizedWord(str)
&& !str.equals(str.toLowerCase(dictionaryMetadata.getLocale()));
}
/**
* @return Returns true if str is MixedCase.
*/
public boolean isCamelCase(final String str) {
return !isEmpty(str)
&& !isAllUppercase(str)
&& !isCapitalizedWord(str)
&& Character.isUpperCase(str.charAt(0))
&& (!(str.length() > 1) || Character.isLowerCase(str.charAt(1)))
&& !str.equals(str.toLowerCase(dictionaryMetadata.getLocale()));
}
/**
* Returns a list of all possible replacements of a given string
*/
public List<String> getAllReplacements(final String str, final int fromIndex, final int level) {
List<String> replaced = new ArrayList<String>();
if (level > 6) { // Stop searching at some point
replaced.add(str);
return replaced;
}
StringBuilder sb = new StringBuilder();
sb.append(str);
int index = MAX_WORD_LENGTH;
String key = "";
int keyLength = 0;
boolean found = false;
// find first possible replacement after fromIndex position
for (final String auxKey : dictionaryMetadata.getReplacementPairs().keySet()) {
int auxIndex = sb.indexOf(auxKey, fromIndex);
if (auxIndex > -1 && auxIndex <= index) {
if (!(auxIndex == index && auxKey.length()<keyLength)) { //select the longest possible key
index = auxIndex;
key = auxKey;
keyLength = auxKey.length();
}
}
}
if (index < MAX_WORD_LENGTH) {
for (final String rep : dictionaryMetadata.getReplacementPairs().get(key)) {
if (rep.length() <= key.length() || sb.indexOf(rep) != index) {
// start a branch without replacement (only once per key)
if (!found) {
replaced.addAll(getAllReplacements(str, index + key.length(), level + 1));
found = true;
}
// start a branch with replacement
sb.replace(index, index + key.length(), rep);
replaced.addAll(getAllReplacements(sb.toString(), index + rep.length(), level + 1));
sb.setLength(0);
sb.append(str);
}
}
}
if (!found) {
replaced.add(sb.toString());
}
return replaced;
}
/**
* Sets up the word and candidate. Used only to test the edit distance in
* JUnit tests.
*
* @param word the first word
* @param candidate the second word used for edit distance calculation
*/
void setWordAndCandidate(final String word, final String candidate) {
word_ff = word.toCharArray();
wordLen = word_ff.length;
this.candidate = candidate.toCharArray();
candLen = this.candidate.length;
e_d = (wordLen <= editDistance ? (wordLen - 1) : editDistance);
}
public final int getWordLen() {
return wordLen;
}
public final int getCandLen() {
return candLen;
}
public final int getEffectiveED() {
return e_d;
}
/**
* Used to sort candidates according to edit distance, and possibly
* according to their frequency in the future.
*
*/
private class CandidateData implements Comparable<CandidateData> {
private final String word;
private final int distance;
CandidateData(final String word, final int distance) {
this.word = word;
this.distance = distance*FREQ_RANGES + FREQ_RANGES - getFrequency(word) - 1;
}
final String getWord() {
return word;
}
final int getDistance() {
return distance;
}
@Override
public int compareTo(final CandidateData cd) {
// Assume no overflow.
return ((cd.getDistance() > this.distance ? -1 :
(cd.getDistance() == this.distance ? 0 : 1)));
}
}
}
|
package br.odb.fpsdemo;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import br.odb.multiplayer.model.Game;
import br.odb.multiplayer.model.Player;
import br.odb.vintage.dto.FPSGameStatusDTO;
import br.odb.vintage.dto.PlayerStateDTO;
/**
* @author monty
*
*/
public class FPSDemoGame extends Game {
/**
* @param gameId
*/
public FPSDemoGame(int gameId) {
super(gameId, 3);
}
/* (non-Javadoc)
* @see br.odb.multiplayer.model.Game#checkForGameEnd()
*/
@Override
public void checkForGameEnd() {
}
/* (non-Javadoc)
* @see br.odb.multiplayer.model.Game#writeState(java.io.Writer)
*/
@Override
public void writeState(OutputStream os) {
try {
ObjectOutputStream oos = new ObjectOutputStream( os );
List<PlayerStateDTO> playerStates = new ArrayList<>();
PlayerStateDTO[] rawStates;
for ( Player state : players.values() ) {
PlayerState fpsState = (PlayerState) state;
playerStates.add( new PlayerStateDTO( "" + fpsState.playerId, fpsState.position, fpsState.angleXZ, -1.0f ) );
// System.out.println( "player id: " + fpsState.id + " position: " + fpsState.position + " angle: " + fpsState.angleXZ );
}
rawStates = playerStates.toArray( new PlayerStateDTO[0] );
oos.writeObject( new FPSGameStatusDTO( rawStates, new BeamStateDTO[]{} ) );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public Player makeNewPlayer() {
int biggerId = 0;
// for ( Integer i : players.keySet() ) {
// System.out.println( "key: " + i + " -> " + players.get( i ) );
for ( Player p : players.values() ) {
if ( biggerId < p.playerId ) {
biggerId = p.playerId;
}
}
++biggerId;
System.out.println( "Adding player with id " + biggerId );
return new PlayerState(biggerId, id, biggerId, "");
}
/* (non-Javadoc)
* @see br.odb.multiplayer.model.Game#getNumberOfRequiredPlayers()
*/
@Override
public int getNumberOfRequiredPlayers() {
return 20;
}
@Override
public void sendMove(HashMap<String, String> params) {
String parameter = params.get( "playerId" );
// System.out.println( "parameter: " + parameter );
int playerId = Integer.parseInt( parameter );
// System.out.println( "receiving id for player " + playerId );
float x = Float.parseFloat( params.get( "x" ) );
float y = Float.parseFloat( params.get( "y" ) );
float z = Float.parseFloat( params.get( "z" ) );
float a = Float.parseFloat( params.get( "a" ) );
// for ( Integer i : players.keySet() ) {
// System.out.println( "key: " + i + " -> " + players.get( i ) );
PlayerState player = (PlayerState) players.get( playerId );
player.angleXZ = a;
player.position.set( x, y, z );
}
}
|
package org.contikios.cooja.plugins;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.KeyStroke;
import javax.swing.MenuElement;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.plaf.basic.BasicInternalFrameUI;
import org.apache.log4j.Logger;
import org.jdom.Element;
import org.contikios.cooja.ClassDescription;
import org.contikios.cooja.Cooja;
import org.contikios.cooja.Cooja.MoteRelation;
import org.contikios.cooja.HasQuickHelp;
import org.contikios.cooja.Mote;
import org.contikios.cooja.MoteInterface;
import org.contikios.cooja.PluginType;
import org.contikios.cooja.RadioMedium;
import org.contikios.cooja.SimEventCentral.MoteCountListener;
import org.contikios.cooja.Simulation;
import org.contikios.cooja.SupportedArguments;
import org.contikios.cooja.VisPlugin;
import org.contikios.cooja.interfaces.LED;
import org.contikios.cooja.interfaces.Position;
import org.contikios.cooja.interfaces.SerialPort;
import org.contikios.cooja.plugins.skins.AddressVisualizerSkin;
import org.contikios.cooja.plugins.skins.AttributeVisualizerSkin;
import org.contikios.cooja.plugins.skins.GridVisualizerSkin;
import org.contikios.cooja.plugins.skins.IDVisualizerSkin;
import org.contikios.cooja.plugins.skins.LEDVisualizerSkin;
import org.contikios.cooja.plugins.skins.LogVisualizerSkin;
import org.contikios.cooja.plugins.skins.MoteTypeVisualizerSkin;
import org.contikios.cooja.plugins.skins.PositionVisualizerSkin;
import org.contikios.cooja.plugins.skins.TrafficVisualizerSkin;
import org.contikios.cooja.plugins.skins.UDGMVisualizerSkin;
/**
* Simulation visualizer supporting different visualizers
* Motes are painted in the XY-plane, as seen from positive Z axis.
*
* Supports drag-n-drop motes, right-click popup menu, and visualizers
*
* Observes the simulation and all mote positions.
*
* @see #registerMoteMenuAction(Class)
* @see #registerSimulationMenuAction(Class)
* @see #registerVisualizerSkin(Class)
* @see UDGMVisualizerSkin
* @author Fredrik Osterlind
* @author Enrico Jorns
*/
@ClassDescription("Network")
@PluginType(PluginType.SIM_STANDARD_PLUGIN)
public class Visualizer extends VisPlugin implements HasQuickHelp {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(Visualizer.class);
public static final int MOTE_RADIUS = 8;
private static final Color[] DEFAULT_MOTE_COLORS = { Color.WHITE };
private Cooja gui = null;
private Simulation simulation = null;
private final JPanel canvas;
private boolean loadedConfig = false;
private final JMenu viewMenu;
/* Viewport */
private AffineTransform viewportTransform;
public int resetViewport = 0;
private static final int SELECT_MASK = Event.CTRL_MASK;
private static final int MOVE_MASK = Event.SHIFT_MASK;
enum MotesActionState {
UNKNWON,
SELECT_PRESS,
DEFAULT_PRESS,
PAN_PRESS,
PANNING,
MOVING,
// rectangular select
SELECTING
}
/* All selected motes */
public Set<Mote> selectedMotes = new HashSet<>();
/* Mote that was under curser while mouse press */
Mote cursorMote;
MotesActionState mouseActionState = MotesActionState.UNKNWON;
/* Position where mouse button was pressed */
Position pressedPos;
private Set<Mote> movedMotes = null;
private long moveStartTime = -1;
private static final Cursor MOVE_CURSOR = new Cursor(Cursor.MOVE_CURSOR);
private Selection selection;
/* Visualizers */
private static ArrayList<Class<? extends VisualizerSkin>> visualizerSkins =
new ArrayList<Class<? extends VisualizerSkin>>();
static {
/* Register default visualizer skins */
registerVisualizerSkin(IDVisualizerSkin.class);
registerVisualizerSkin(AddressVisualizerSkin.class);
registerVisualizerSkin(LogVisualizerSkin.class);
registerVisualizerSkin(LEDVisualizerSkin.class);
registerVisualizerSkin(TrafficVisualizerSkin.class);
registerVisualizerSkin(PositionVisualizerSkin.class);
registerVisualizerSkin(GridVisualizerSkin.class);
registerVisualizerSkin(MoteTypeVisualizerSkin.class);
registerVisualizerSkin(AttributeVisualizerSkin.class);
}
private ArrayList<VisualizerSkin> currentSkins = new ArrayList<VisualizerSkin>();
/* Generic visualization */
private MoteCountListener newMotesListener;
private Observer posObserver = null;
private Observer moteHighligtObserver = null;
private ArrayList<Mote> highlightedMotes = new ArrayList<Mote>();
private final static Color HIGHLIGHT_COLOR = Color.CYAN;
private final static Color MOVE_COLOR = Color.WHITE;
private Observer moteRelationsObserver = null;
/* Popup menu */
public static interface SimulationMenuAction {
public boolean isEnabled(Visualizer visualizer, Simulation simulation);
public String getDescription(Visualizer visualizer, Simulation simulation);
public void doAction(Visualizer visualizer, Simulation simulation);
}
public static interface MoteMenuAction {
public boolean isEnabled(Visualizer visualizer, Mote mote);
public String getDescription(Visualizer visualizer, Mote mote);
public void doAction(Visualizer visualizer, Mote mote);
}
private ArrayList<Class<? extends SimulationMenuAction>> simulationMenuActions =
new ArrayList<Class<? extends SimulationMenuAction>>();
private ArrayList<Class<? extends MoteMenuAction>> moteMenuActions =
new ArrayList<Class<? extends MoteMenuAction>>();
public Visualizer(Simulation simulation, Cooja gui) {
super("Network", gui);
this.gui = gui;
this.simulation = simulation;
/* Register external visualizers */
String[] skins = gui.getProjectConfig().getStringArrayValue(Visualizer.class, "SKINS");
for (String skinClass: skins) {
Class<? extends VisualizerSkin> skin = gui.tryLoadClass(this, VisualizerSkin.class, skinClass);
if (registerVisualizerSkin(skin)) {
logger.info("Registered external visualizer: " + skinClass);
}
}
/* Menus */
JMenuBar menuBar = new JMenuBar();
viewMenu = new JMenu("View");
viewMenu.addMenuListener(new MenuListener() {
public void menuSelected(MenuEvent e) {
viewMenu.removeAll();
populateSkinMenu(viewMenu);
}
public void menuDeselected(MenuEvent e) {
}
public void menuCanceled(MenuEvent e) {
}
});
JMenu zoomMenu = new JMenu("Zoom");
menuBar.add(viewMenu);
menuBar.add(zoomMenu);
this.setJMenuBar(menuBar);
Action zoomInAction = new AbstractAction("Zoom in") {
public void actionPerformed(ActionEvent e) {
zoomToFactor(zoomFactor() * 1.2);
}
};
zoomInAction.putValue(
Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, ActionEvent.CTRL_MASK)
);
JMenuItem zoomInItem = new JMenuItem(zoomInAction);
zoomMenu.add(zoomInItem);
Action zoomOutAction = new AbstractAction("Zoom out") {
public void actionPerformed(ActionEvent e) {
zoomToFactor(zoomFactor() / 1.2);
}
};
zoomOutAction.putValue(
Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, ActionEvent.CTRL_MASK)
);
JMenuItem zoomOutItem = new JMenuItem(zoomOutAction);
zoomMenu.add(zoomOutItem);
JMenuItem resetViewportItem = new JMenuItem("Reset viewport");
resetViewportItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
resetViewport = 1;
repaint();
}
});
zoomMenu.add(resetViewportItem);
selection = new Selection();
/* Main canvas */
canvas = new JPanel() {
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (resetViewport > 0) {
resetViewport();
resetViewport
}
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (VisualizerSkin skin: currentSkins) {
skin.paintBeforeMotes(g);
}
paintMotes(g);
for (VisualizerSkin skin: currentSkins) {
skin.paintAfterMotes(g);
}
selection.drawSelection(g);
}
};
canvas.setBackground(Color.WHITE);
viewportTransform = new AffineTransform();
this.add(BorderLayout.CENTER, canvas);
/* Observe simulation and mote positions */
posObserver = new Observer() {
public void update(Observable obs, Object obj) {
repaint();
}
};
simulation.getEventCentral().addMoteCountListener(newMotesListener = new MoteCountListener() {
public void moteWasAdded(Mote mote) {
Position pos = mote.getInterfaces().getPosition();
if (pos != null) {
pos.addObserver(posObserver);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
resetViewport = 1;
repaint();
}
});
}
}
public void moteWasRemoved(Mote mote) {
Position pos = mote.getInterfaces().getPosition();
if (pos != null) {
pos.deleteObserver(posObserver);
repaint();
}
}
});
for (Mote mote: simulation.getMotes()) {
Position pos = mote.getInterfaces().getPosition();
if (pos != null) {
pos.addObserver(posObserver);
}
}
/* Observe mote highlights */
gui.addMoteHighlightObserver(moteHighligtObserver = new Observer() {
public void update(Observable obs, Object obj) {
if (!(obj instanceof Mote)) {
return;
}
final Timer timer = new Timer(100, null);
final Mote mote = (Mote) obj;
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/* Count down */
if (timer.getDelay() < 90) {
timer.stop();
highlightedMotes.remove(mote);
repaint();
return;
}
/* Toggle highlight state */
if (highlightedMotes.contains(mote)) {
highlightedMotes.remove(mote);
} else {
highlightedMotes.add(mote);
}
timer.setDelay(timer.getDelay()-1);
repaint();
}
});
timer.start();
}
});
/* Observe mote relations */
gui.addMoteRelationsObserver(moteRelationsObserver = new Observer() {
public void update(Observable obs, Object obj) {
repaint();
}
});
/* Popup menu */
canvas.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
handleMouseDrag(e, false);
}
});
canvas.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
handlePopupRequest(e.getPoint());
return;
}
if (SwingUtilities.isLeftMouseButton(e)){
handleMousePress(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
handlePopupRequest(e.getPoint());
return;
}
if (SwingUtilities.isLeftMouseButton(e)) {
handleMouseRelease(e);
}
}
});
canvas.addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent mwe) {
int x = mwe.getX();
int y = mwe.getY();
int rot = mwe.getWheelRotation();
if (rot > 0) {
zoomToFactor(zoomFactor() / 1.2, new Point(x, y));
} else {
zoomToFactor(zoomFactor() * 1.2, new Point(x, y));
}
}
});
/* Register mote menu actions */
registerMoteMenuAction(MoveMoteMenuAction.class);
registerMoteMenuAction(ButtonClickMoteMenuAction.class);
registerMoteMenuAction(ShowLEDMoteMenuAction.class);
registerMoteMenuAction(ShowSerialMoteMenuAction.class);
registerMoteMenuAction(DeleteMoteMenuAction.class);
/* Register simulation menu actions */
registerSimulationMenuAction(ResetViewportAction.class);
registerSimulationMenuAction(ToggleDecorationsMenuAction.class);
/* Drag and drop files to motes */
DropTargetListener dTargetListener = new DropTargetListener() {
public void dragEnter(DropTargetDragEvent dtde) {
if (acceptOrRejectDrag(dtde)) {
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
} else {
dtde.rejectDrag();
}
}
public void dragExit(DropTargetEvent dte) {
}
public void dropActionChanged(DropTargetDragEvent dtde) {
if (acceptOrRejectDrag(dtde)) {
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
} else {
dtde.rejectDrag();
}
}
public void dragOver(DropTargetDragEvent dtde) {
if (acceptOrRejectDrag(dtde)) {
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
} else {
dtde.rejectDrag();
}
}
public void drop(DropTargetDropEvent dtde) {
Transferable transferable = dtde.getTransferable();
/* Only accept single files */
File file = null;
if (!transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.rejectDrop();
return;
}
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
try {
List<Object> transferList = Arrays.asList(
transferable.getTransferData(DataFlavor.javaFileListFlavor)
);
if (transferList.size() != 1) {
return;
}
List<File> list = (List<File>) transferList.get(0);
if (list.size() != 1) {
return;
}
file = list.get(0);
}
catch (Exception e) {
return;
}
if (file == null || !file.exists()) {
return;
}
handleDropFile(file, dtde.getLocation());
}
private boolean acceptOrRejectDrag(DropTargetDragEvent dtde) {
Transferable transferable = dtde.getTransferable();
/* Make sure one, and only one, mote exists under mouse pointer */
Point point = dtde.getLocation();
Mote[] motes = findMotesAtPosition(point.x, point.y);
if (motes == null || motes.length != 1) {
return false;
}
/* Only accept single files */
File file;
if (!transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}
try {
List<Object> transferList = Arrays.asList(
transferable.getTransferData(DataFlavor.javaFileListFlavor)
);
if (transferList.size() != 1) {
return false;
}
List<File> list = (List<File>) transferList.get(0);
if (list.size() != 1) {
return false;
}
file = list.get(0);
} catch (UnsupportedFlavorException e) {
return false;
} catch (IOException e) {
return false;
}
/* Extract file extension */
return isDropFileAccepted(file);
}
};
canvas.setDropTarget(
new DropTarget(canvas, DnDConstants.ACTION_COPY_OR_MOVE, dTargetListener, true, null)
);
resetViewport = 3; /* XXX Quick-fix */
/* XXX HACK: here we set the position and size of the window when it appears on a blank simulation screen. */
this.setLocation(1, 1);
this.setSize(400, 400);
}
private void generateAndActivateSkin(Class<? extends VisualizerSkin> skinClass) {
for (VisualizerSkin skin: currentSkins) {
if (skinClass == skin.getClass()) {
logger.warn("Selected visualizer already active: " + skinClass);
return;
}
}
if (!isSkinCompatible(skinClass)) {
/*logger.warn("Skin is not compatible with current simulation: " + skinClass);*/
return;
}
/* Create and activate new skin */
try {
VisualizerSkin newSkin = skinClass.newInstance();
newSkin.setActive(Visualizer.this.simulation, Visualizer.this);
currentSkins.add(0, newSkin);
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
repaint();
}
public void startPlugin() {
super.startPlugin();
if (loadedConfig) {
return;
}
/* Activate default skins */
String[] defaultSkins = Cooja.getExternalToolsSetting("VISUALIZER_DEFAULT_SKINS", "").split(";");
for (String skin: defaultSkins) {
if (skin.isEmpty()) {
continue;
}
Class<? extends VisualizerSkin> skinClass =
simulation.getCooja().tryLoadClass(this, VisualizerSkin.class, skin);
generateAndActivateSkin(skinClass);
}
}
public VisualizerSkin[] getCurrentSkins() {
VisualizerSkin[] skins = new VisualizerSkin[currentSkins.size()];
return currentSkins.toArray(skins);
}
/**
* Register simulation menu action.
*
* @see SimulationMenuAction
* @param menuAction Menu action
*/
public void registerSimulationMenuAction(Class<? extends SimulationMenuAction> menuAction) {
if (simulationMenuActions.contains(menuAction)) {
return;
}
simulationMenuActions.add(menuAction);
}
public void unregisterSimulationMenuAction(Class<? extends SimulationMenuAction> menuAction) {
simulationMenuActions.remove(menuAction);
}
/**
* Register mote menu action.
*
* @see MoteMenuAction
* @param menuAction Menu action
*/
public void registerMoteMenuAction(Class<? extends MoteMenuAction> menuAction) {
if (moteMenuActions.contains(menuAction)) {
return;
}
moteMenuActions.add(menuAction);
}
public void unregisterMoteMenuAction(Class<? extends MoteMenuAction> menuAction) {
moteMenuActions.remove(menuAction);
}
public static boolean registerVisualizerSkin(Class<? extends VisualizerSkin> skin) {
if (visualizerSkins.contains(skin)) {
return false;
}
visualizerSkins.add(skin);
return true;
}
public static void unregisterVisualizerSkin(Class<? extends VisualizerSkin> skin) {
visualizerSkins.remove(skin);
}
private void handlePopupRequest(Point point) {
JPopupMenu menu = new JPopupMenu();
/* Mote specific actions */
final Mote[] motes = findMotesAtPosition(point.x, point.y);
if (motes != null && motes.length > 0) {
menu.add(new JSeparator());
/* Add registered mote actions */
for (final Mote mote : motes) {
menu.add(simulation.getCooja().createMotePluginsSubmenu(mote));
for (Class<? extends MoteMenuAction> menuActionClass: moteMenuActions) {
try {
final MoteMenuAction menuAction = menuActionClass.newInstance();
if (menuAction.isEnabled(this, mote)) {
JMenuItem menuItem = new JMenuItem(menuAction.getDescription(this, mote));
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuAction.doAction(Visualizer.this, mote);
}
});
menu.add(menuItem);
}
} catch (InstantiationException e1) {
logger.fatal("Error: " + e1.getMessage(), e1);
} catch (IllegalAccessException e1) {
logger.fatal("Error: " + e1.getMessage(), e1);
}
}
}
}
/* Simulation specific actions */
menu.add(new JSeparator());
for (Class<? extends SimulationMenuAction> menuActionClass : simulationMenuActions) {
try {
final SimulationMenuAction menuAction = menuActionClass.newInstance();
if (menuAction.isEnabled(this, simulation)) {
JMenuItem menuItem = new JMenuItem(menuAction.getDescription(this, simulation));
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuAction.doAction(Visualizer.this, simulation);
}
});
menu.add(menuItem);
}
} catch (InstantiationException e1) {
logger.fatal("Error: " + e1.getMessage(), e1);
} catch (IllegalAccessException e1) {
logger.fatal("Error: " + e1.getMessage(), e1);
}
}
/* Visualizer skin actions */
menu.add(new JSeparator());
/*JMenu skinMenu = new JMenu("Visualizers");
populateSkinMenu(skinMenu);
menu.add(skinMenu);
makeSkinsDefaultAction.putValue(Action.NAME, "Set default visualizers");
JMenuItem skinDefaultItem = new JMenuItem(makeSkinsDefaultAction);
menu.add(skinDefaultItem);*/
/* Show menu */
menu.setLocation(new Point(
canvas.getLocationOnScreen().x + point.x,
canvas.getLocationOnScreen().y + point.y));
menu.setInvoker(canvas);
menu.setVisible(true);
}
private boolean showMoteToMoteRelations = true;
private void populateSkinMenu(MenuElement menu) {
/* Mote-to-mote relations */
JCheckBoxMenuItem moteRelationsItem = new JCheckBoxMenuItem("Mote relations", showMoteToMoteRelations);
moteRelationsItem.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
JCheckBoxMenuItem menuItem = ((JCheckBoxMenuItem)e.getItem());
showMoteToMoteRelations = menuItem.isSelected();
repaint();
}
});
if (menu instanceof JMenu) {
((JMenu)menu).add(moteRelationsItem);
((JMenu)menu).add(new JSeparator());
}
if (menu instanceof JPopupMenu) {
((JPopupMenu)menu).add(moteRelationsItem);
((JPopupMenu)menu).add(new JSeparator());
}
for (Class<? extends VisualizerSkin> skinClass: visualizerSkins) {
/* Should skin be enabled in this simulation? */
if (!isSkinCompatible(skinClass)) {
continue;
}
String description = Cooja.getDescriptionOf(skinClass);
JCheckBoxMenuItem item = new JCheckBoxMenuItem(description, false);
item.putClientProperty("skinclass", skinClass);
/* Select skin if active */
for (VisualizerSkin skin: currentSkins) {
if (skin.getClass() == skinClass) {
item.setSelected(true);
break;
}
}
item.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
JCheckBoxMenuItem menuItem = ((JCheckBoxMenuItem)e.getItem());
if (menuItem == null) {
logger.fatal("No menu item");
return;
}
Class<VisualizerSkin> skinClass =
(Class<VisualizerSkin>) menuItem.getClientProperty("skinclass");
if (skinClass == null) {
logger.fatal("Unknown visualizer skin class: " + skinClass);
return;
}
if (menuItem.isSelected()) {
/* Create and activate new skin */
generateAndActivateSkin(skinClass);
} else {
/* Deactivate skin */
VisualizerSkin skinToDeactivate = null;
for (VisualizerSkin skin: currentSkins) {
if (skin.getClass() == skinClass) {
skinToDeactivate = skin;
break;
}
}
if (skinToDeactivate == null) {
logger.fatal("Unknown visualizer to deactivate: " + skinClass);
return;
}
skinToDeactivate.setInactive();
repaint();
currentSkins.remove(skinToDeactivate);
}
}
});
if (menu instanceof JMenu) {
((JMenu)menu).add(item);
}
if (menu instanceof JPopupMenu) {
((JPopupMenu)menu).add(item);
}
}
}
public boolean isSkinCompatible(Class<? extends VisualizerSkin> skinClass) {
if (skinClass == null) {
return false;
}
/* Check if skin depends on any particular radio medium */
boolean showMenuItem = true;
if (skinClass.getAnnotation(SupportedArguments.class) != null) {
showMenuItem = false;
Class<? extends RadioMedium>[] radioMediums = skinClass.getAnnotation(SupportedArguments.class).radioMediums();
for (Class<? extends Object> o: radioMediums) {
if (o.isAssignableFrom(simulation.getRadioMedium().getClass())) {
showMenuItem = true;
break;
}
}
}
if (!showMenuItem) {
return false;
}
return true;
}
private void handleMousePress(MouseEvent mouseEvent) {
int x = mouseEvent.getX();
int y = mouseEvent.getY();
pressedPos = transformPixelToPosition(mouseEvent.getPoint());
// this is the state we have from pressing button
final Mote[] foundMotes = findMotesAtPosition(x, y);
if (foundMotes == null) {
cursorMote = null;
}
else {
// select top mote
cursorMote = foundMotes[foundMotes.length - 1];
}
int modifiers = mouseEvent.getModifiers();
/* translate input */
if ((modifiers & SELECT_MASK) != 0) {
mouseActionState = MotesActionState.SELECT_PRESS;
}
else if ((modifiers & MOVE_MASK) != 0) {
// only move viewport
mouseActionState = MotesActionState.PAN_PRESS;
}
else {
if (foundMotes == null) {
// move viewport
selectedMotes.clear();
}
else {
// if this mote was not selected before, assume a new selection
if (!selectedMotes.contains(cursorMote)) {
selectedMotes.clear();
selectedMotes.add(cursorMote);
}
}
mouseActionState = MotesActionState.DEFAULT_PRESS;
}
repaint();
}
Map<Mote, double[]> moveStartPositions = new HashMap<>();
private void handleMouseDrag(MouseEvent e, boolean stop) {
Position currPos = transformPixelToPosition(e.getPoint());
switch (mouseActionState) {
case DEFAULT_PRESS:
if (cursorMote == null) {
mouseActionState = MotesActionState.PANNING;
}
else {
mouseActionState = MotesActionState.MOVING;
// save start position
for (Mote m : selectedMotes) {
Position pos = m.getInterfaces().getPosition();
moveStartPositions.put(m, new double[]{
pos.getXCoordinate(),
pos.getYCoordinate(),
pos.getZCoordinate()});
}
}
break;
case MOVING:
canvas.setCursor(MOVE_CURSOR);
for (Mote moveMote : selectedMotes) {
moveMote.getInterfaces().getPosition().setCoordinates(
moveStartPositions.get(moveMote)[0]
+ (currPos.getXCoordinate() - pressedPos.getXCoordinate()),
moveStartPositions.get(moveMote)[1]
+ (currPos.getYCoordinate() - pressedPos.getYCoordinate()),
moveStartPositions.get(moveMote)[2]
);
repaint();
}
break;
case PAN_PRESS:
mouseActionState = MotesActionState.PANNING;
break;
case PANNING:
/* The current mouse position should correspond to where panning started */
viewportTransform.translate(
currPos.getXCoordinate() - pressedPos.getXCoordinate(),
currPos.getYCoordinate() - pressedPos.getYCoordinate()
);
repaint();
break;
case SELECT_PRESS:
mouseActionState = MotesActionState.SELECTING;
selection.setEnabled(true);
break;
case SELECTING:
int pressedX = transformToPixelX(pressedPos.getXCoordinate());
int pressedY = transformToPixelY(pressedPos.getYCoordinate());
int currX = transformToPixelX(currPos.getXCoordinate());
int currY = transformToPixelY(currPos.getYCoordinate());
int startX = pressedX < currX ? pressedX : currX;
int startY = pressedY < currY ? pressedY : currY;
int width = Math.abs(pressedX - currX);
int height = Math.abs(pressedY - currY);
selection.setSelection(startX, startY, width, height);
selectedMotes.clear();
selectedMotes.addAll(Arrays.asList(findMotesInRange(startX, startY, width, height)));
repaint();
break;
}
}
private void handleMouseRelease(MouseEvent mouseEvent) {
switch (mouseActionState) {
case PAN_PRESS:
// ignore
break;
case SELECT_PRESS:
if (cursorMote == null) {
/* Click on free canvas deselects all mote */
selectedMotes.clear();
}
else {
/* toggle selection for mote */
if (selectedMotes.contains(cursorMote)) {
selectedMotes.remove(cursorMote);
}
else {
selectedMotes.add(cursorMote);
}
}
break;
case DEFAULT_PRESS:
if (cursorMote == null) {
/* Click on free canvas deselects all mote */
selectedMotes.clear();
}
else {
/* Click on mote selects single mote */
selectedMotes.clear();
selectedMotes.add(cursorMote);
}
break;
case MOVING:
/* Release stops moving */
canvas.setCursor(Cursor.getDefaultCursor());
break;
case SELECTING:
/* Release stops moving */
selection.setEnabled(false);
repaint();
break;
}
repaint();
}
private void beginMoveRequest(Mote motesToMove, boolean withTiming, boolean confirm) {
if (withTiming) {
moveStartTime = System.currentTimeMillis();
} else {
moveStartTime = -1;
}
mouseActionState = MotesActionState.DEFAULT_PRESS;
selectedMotes.clear();
selectedMotes.add(motesToMove);
repaint();
}
private double zoomFactor() {
return viewportTransform.getScaleX();
}
private void zoomToFactor(double newZoom) {
zoomToFactor(newZoom, new Point(canvas.getWidth()/2, canvas.getHeight()/2));
}
private void zoomToFactor(double newZoom, Point zoomCenter) {
Position center = transformPixelToPosition(zoomCenter);
viewportTransform.setToScale(
newZoom,
newZoom
);
Position newCenter = transformPixelToPosition(zoomCenter);
viewportTransform.translate(
newCenter.getXCoordinate() - center.getXCoordinate(),
newCenter.getYCoordinate() - center.getYCoordinate()
);
repaint();
}
/**
* Returns all motes in rectangular range
*
* @param startX
* @param startY
* @param width
* @param height
* @return All motes in range
*/
public Mote[] findMotesInRange(int startX, int startY, int width, int height) {
List<Mote> motes = new LinkedList<>();
for (Mote m : simulation.getMotes()) {
Position pos = m.getInterfaces().getPosition();
int moteX = transformToPixelX(pos.getXCoordinate());
int moteY = transformToPixelY(pos.getYCoordinate());
if (moteX > startX && moteX < startX + width
&& moteY > startY && moteY < startY + height) {
motes.add(m);
}
}
Mote[] motesArr = new Mote[motes.size()];
return motes.toArray(motesArr);
}
/**
* Returns all motes at given position.
*
* If multiple motes were found on at a position the motes are returned
* in the order they are painted on screen.
* First mote in array is the bottom mote, last mote is the top mote.
*
* @param clickedX
* X coordinate
* @param clickedY
* Y coordinate
* @return All motes at given position
*/
public Mote[] findMotesAtPosition(int clickedX, int clickedY) {
double xCoord = transformToPositionX(clickedX);
double yCoord = transformToPositionY(clickedY);
ArrayList<Mote> motes = new ArrayList<Mote>();
// Calculate painted mote radius in coordinates
double paintedMoteWidth = transformToPositionX(MOTE_RADIUS)
- transformToPositionX(0);
double paintedMoteHeight = transformToPositionY(MOTE_RADIUS)
- transformToPositionY(0);
for (int i = 0; i < simulation.getMotesCount(); i++) {
Position pos = simulation.getMote(i).getInterfaces().getPosition();
// Transform to unit circle before checking if mouse hit this mote
double distanceX = Math.abs(xCoord - pos.getXCoordinate())
/ paintedMoteWidth;
double distanceY = Math.abs(yCoord - pos.getYCoordinate())
/ paintedMoteHeight;
if (distanceX * distanceX + distanceY * distanceY <= 1) {
motes.add(simulation.getMote(i));
}
}
if (motes.size() == 0) {
return null;
}
Mote[] motesArr = new Mote[motes.size()];
return motes.toArray(motesArr);
}
public void paintMotes(Graphics g) {
Mote[] allMotes = simulation.getMotes();
/* Paint mote relations */
if (showMoteToMoteRelations) {
MoteRelation[] relations = simulation.getCooja().getMoteRelations();
for (MoteRelation r: relations) {
Position sourcePos = r.source.getInterfaces().getPosition();
Position destPos = r.dest.getInterfaces().getPosition();
Point sourcePoint = transformPositionToPixel(sourcePos);
Point destPoint = transformPositionToPixel(destPos);
g.setColor(r.color == null ? Color.black : r.color);
drawArrow(g, sourcePoint.x, sourcePoint.y, destPoint.x, destPoint.y, MOTE_RADIUS + 1);
}
}
for (Mote mote: allMotes) {
/* Use the first skin's non-null mote colors */
Color moteColors[] = null;
for (VisualizerSkin skin: currentSkins) {
moteColors = skin.getColorOf(mote);
if (moteColors != null) {
break;
}
}
if (moteColors == null) {
moteColors = DEFAULT_MOTE_COLORS;
}
Position motePos = mote.getInterfaces().getPosition();
Point pixelCoord = transformPositionToPixel(motePos);
int x = pixelCoord.x;
int y = pixelCoord.y;
if (mote == movedMotes) {
g.setColor(MOVE_COLOR);
g.fillOval(x - MOTE_RADIUS, y - MOTE_RADIUS, 2 * MOTE_RADIUS,
2 * MOTE_RADIUS);
} else if (!highlightedMotes.isEmpty() && highlightedMotes.contains(mote)) {
g.setColor(HIGHLIGHT_COLOR);
g.fillOval(x - MOTE_RADIUS, y - MOTE_RADIUS, 2 * MOTE_RADIUS,
2 * MOTE_RADIUS);
} else if (moteColors.length >= 2) {
g.setColor(moteColors[0]);
g.fillOval(x - MOTE_RADIUS, y - MOTE_RADIUS, 2 * MOTE_RADIUS,
2 * MOTE_RADIUS);
g.setColor(moteColors[1]);
g.fillOval(x - MOTE_RADIUS / 2, y - MOTE_RADIUS / 2, MOTE_RADIUS,
MOTE_RADIUS);
} else if (moteColors.length >= 1) {
g.setColor(moteColors[0]);
g.fillOval(x - MOTE_RADIUS, y - MOTE_RADIUS, 2 * MOTE_RADIUS,
2 * MOTE_RADIUS);
}
g.setColor(Color.BLACK);
g.drawOval(x - MOTE_RADIUS, y - MOTE_RADIUS, 2 * MOTE_RADIUS,
2 * MOTE_RADIUS);
}
}
private Polygon arrowPoly = new Polygon();
private void drawArrow(Graphics g, int xSource, int ySource, int xDest, int yDest, int delta) {
double dx = xSource - xDest;
double dy = ySource - yDest;
double dir = Math.atan2(dx, dy);
double len = Math.sqrt(dx * dx + dy * dy);
dx /= len;
dy /= len;
len -= delta;
xDest = xSource - (int) (dx * len);
yDest = ySource - (int) (dy * len);
g.drawLine(xDest, yDest, xSource, ySource);
final int size = 8;
arrowPoly.reset();
arrowPoly.addPoint(xDest, yDest);
arrowPoly.addPoint(xDest + xCor(size, dir + 0.5), yDest + yCor(size, dir + 0.5));
arrowPoly.addPoint(xDest + xCor(size, dir - 0.5), yDest + yCor(size, dir - 0.5));
arrowPoly.addPoint(xDest, yDest);
g.fillPolygon(arrowPoly);
}
private int yCor(int len, double dir) {
return (int)(0.5 + len * Math.cos(dir));
}
private int xCor(int len, double dir) {
return (int)(0.5 + len * Math.sin(dir));
}
/**
* Reset transform to show all motes.
*/
protected void resetViewport() {
Mote[] motes = simulation.getMotes();
if (motes.length == 0) {
/* No motes */
viewportTransform.setToIdentity();
return;
}
final double BORDER_SCALE_FACTOR = 1.1;
double smallX, bigX, smallY, bigY, scaleX, scaleY;
/* Init values */
{
Position pos = motes[0].getInterfaces().getPosition();
smallX = bigX = pos.getXCoordinate();
smallY = bigY = pos.getYCoordinate();
}
/* Extremes */
for (Mote mote: motes) {
Position pos = mote.getInterfaces().getPosition();
smallX = Math.min(smallX, pos.getXCoordinate());
bigX = Math.max(bigX, pos.getXCoordinate());
smallY = Math.min(smallY, pos.getYCoordinate());
bigY = Math.max(bigY, pos.getYCoordinate());
}
/* Scale viewport */
if (smallX == bigX) {
scaleX = 1;
} else {
scaleX = (bigX - smallX) / (canvas.getWidth());
}
if (smallY == bigY) {
scaleY = 1;
} else {
scaleY = (bigY - smallY) / (canvas.getHeight());
}
viewportTransform.setToIdentity();
double newZoom = (1.0/(BORDER_SCALE_FACTOR*Math.max(scaleX, scaleY)));
viewportTransform.setToScale(
newZoom,
newZoom
);
/* Center visible motes */
final double smallXfinal = smallX, bigXfinal = bigX, smallYfinal = smallY, bigYfinal = bigY;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Position viewMid =
transformPixelToPosition(canvas.getWidth()/2, canvas.getHeight()/2);
double motesMidX = (smallXfinal + bigXfinal) / 2.0;
double motesMidY = (smallYfinal + bigYfinal) / 2.0;
viewportTransform.translate(
viewMid.getXCoordinate() - motesMidX,
viewMid.getYCoordinate() - motesMidY);
canvas.repaint();
}
});
}
/**
* Transforms a real-world position to a pixel which can be painted onto the
* current sized canvas.
*
* @param pos
* Real-world position
* @return Pixel coordinates
*/
public Point transformPositionToPixel(Position pos) {
return transformPositionToPixel(
pos.getXCoordinate(),
pos.getYCoordinate(),
pos.getZCoordinate()
);
}
/**
* Transforms real-world coordinates to a pixel which can be painted onto the
* current sized canvas.
*
* @param x Real world X
* @param y Real world Y
* @param z Real world Z (ignored)
* @return Pixel coordinates
*/
public Point transformPositionToPixel(double x, double y, double z) {
return new Point(transformToPixelX(x), transformToPixelY(y));
}
/**
* @return Canvas
*/
public JPanel getCurrentCanvas() {
return canvas;
}
/**
* Transforms a pixel coordinate to a real-world. Z-value will always be 0.
*
* @param pixelPos
* On-screen pixel coordinate
* @return Real world coordinate (z=0).
*/
public Position transformPixelToPosition(Point pixelPos) {
return transformPixelToPosition(pixelPos.x, pixelPos.y);
}
public Position transformPixelToPosition(int x, int y) {
Position position = new Position(null);
position.setCoordinates(
transformToPositionX(x),
transformToPositionY(y),
0.0
);
return position;
}
private int transformToPixelX(double x) {
return (int) (viewportTransform.getScaleX()*x + viewportTransform.getTranslateX());
}
private int transformToPixelY(double y) {
return (int) (viewportTransform.getScaleY()*y + viewportTransform.getTranslateY());
}
private double transformToPositionX(int x) {
return (x - viewportTransform.getTranslateX())/viewportTransform.getScaleX() ;
}
private double transformToPositionY(int y) {
return (y - viewportTransform.getTranslateY())/viewportTransform.getScaleY() ;
}
public void closePlugin() {
for (VisualizerSkin skin: currentSkins) {
skin.setInactive();
}
currentSkins.clear();
if (moteHighligtObserver != null) {
gui.deleteMoteHighlightObserver(moteHighligtObserver);
}
if (moteRelationsObserver != null) {
gui.deleteMoteRelationsObserver(moteRelationsObserver);
}
simulation.getEventCentral().removeMoteCountListener(newMotesListener);
for (Mote mote: simulation.getMotes()) {
Position pos = mote.getInterfaces().getPosition();
if (pos != null) {
pos.deleteObserver(posObserver);
}
}
}
protected boolean isDropFileAccepted(File file) {
return true; /* TODO */
}
protected void handleDropFile(File file, Point point) {
logger.fatal("Drag and drop not implemented: " + file);
}
/**
* @return Selected mote
*/
public Set<Mote> getSelectedMotes() {
return selectedMotes;
}
public Collection<Element> getConfigXML() {
ArrayList<Element> config = new ArrayList<Element>();
Element element;
/* Show mote-to-mote relations */
if (showMoteToMoteRelations) {
element = new Element("moterelations");
element.setText("" + true);
config.add(element);
}
/* Skins */
for (int i=currentSkins.size()-1; i >= 0; i
VisualizerSkin skin = currentSkins.get(i);
element = new Element("skin");
element.setText(skin.getClass().getName());
config.add(element);
}
/* Viewport */
element = new Element("viewport");
double[] matrix = new double[6];
viewportTransform.getMatrix(matrix);
element.setText(
matrix[0] + " " +
matrix[1] + " " +
matrix[2] + " " +
matrix[3] + " " +
matrix[4] + " " +
matrix[5]
);
config.add(element);
/* Hide decorations */
BasicInternalFrameUI ui = (BasicInternalFrameUI) getUI();
if (ui.getNorthPane().getPreferredSize() == null ||
ui.getNorthPane().getPreferredSize().height == 0) {
element = new Element("hidden");
config.add(element);
}
return config;
}
public boolean setConfigXML(Collection<Element> configXML, boolean visAvailable) {
loadedConfig = true;
showMoteToMoteRelations = false;
for (Element element : configXML) {
if (element.getName().equals("skin")) {
String wanted = element.getText();
/* Backwards compatibility: se.sics -> org.contikios */
if (wanted.startsWith("se.sics")) {
wanted = wanted.replaceFirst("se\\.sics", "org.contikios");
}
for (Class<? extends VisualizerSkin> skinClass: visualizerSkins) {
if (wanted.equals(skinClass.getName())
/* Backwards compatibility */
|| wanted.equals(Cooja.getDescriptionOf(skinClass))) {
final Class<? extends VisualizerSkin> skin = skinClass;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
generateAndActivateSkin(skin);
}
});
wanted = null;
break;
}
}
if (wanted != null) {
logger.warn("Could not load visualizer: " + element.getText());
}
} else if (element.getName().equals("moterelations")) {
showMoteToMoteRelations = true;
} else if (element.getName().equals("viewport")) {
try {
String[] matrix = element.getText().split(" ");
viewportTransform.setTransform(
Double.parseDouble(matrix[0]),
Double.parseDouble(matrix[1]),
Double.parseDouble(matrix[2]),
Double.parseDouble(matrix[3]),
Double.parseDouble(matrix[4]),
Double.parseDouble(matrix[5])
);
resetViewport = 0;
} catch (Exception e) {
logger.warn("Bad viewport: " + e.getMessage());
resetViewport();
}
} else if (element.getName().equals("hidden")) {
BasicInternalFrameUI ui = (BasicInternalFrameUI) getUI();
ui.getNorthPane().setPreferredSize(new Dimension(0,0));
}
}
return true;
}
private AbstractAction makeSkinsDefaultAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
StringBuilder sb = new StringBuilder();
for (VisualizerSkin skin: currentSkins) {
if (sb.length() > 0) {
sb.append(';');
}
sb.append(skin.getClass().getName());
}
Cooja.setExternalToolsSetting("VISUALIZER_DEFAULT_SKINS", sb.toString());
}
};
protected static class ButtonClickMoteMenuAction implements MoteMenuAction {
public boolean isEnabled(Visualizer visualizer, Mote mote) {
return mote.getInterfaces().getButton() != null
&& !mote.getInterfaces().getButton().isPressed();
}
public String getDescription(Visualizer visualizer, Mote mote) {
return "Click button on " + mote;
}
public void doAction(Visualizer visualizer, Mote mote) {
mote.getInterfaces().getButton().clickButton();
}
};
protected static class DeleteMoteMenuAction implements MoteMenuAction {
public boolean isEnabled(Visualizer visualizer, Mote mote) {
return true;
}
public String getDescription(Visualizer visualizer, Mote mote) {
return "Delete " + mote;
}
public void doAction(Visualizer visualizer, Mote mote) {
mote.getSimulation().removeMote(mote);
}
};
protected static class ShowLEDMoteMenuAction implements MoteMenuAction {
public boolean isEnabled(Visualizer visualizer, Mote mote) {
return mote.getInterfaces().getLED() != null;
}
public String getDescription(Visualizer visualizer, Mote mote) {
return "Show LEDs on " + mote;
}
public void doAction(Visualizer visualizer, Mote mote) {
Simulation simulation = mote.getSimulation();
LED led = mote.getInterfaces().getLED();
if (led == null) {
return;
}
/* Extract description (input to plugin) */
String desc = Cooja.getDescriptionOf(mote.getInterfaces().getLED());
MoteInterfaceViewer viewer =
(MoteInterfaceViewer) simulation.getCooja().tryStartPlugin(
MoteInterfaceViewer.class,
simulation.getCooja(),
simulation,
mote);
if (viewer == null) {
return;
}
viewer.setSelectedInterface(desc);
viewer.pack();
}
};
protected static class ShowSerialMoteMenuAction implements MoteMenuAction {
public boolean isEnabled(Visualizer visualizer, Mote mote) {
for (MoteInterface intf: mote.getInterfaces().getInterfaces()) {
if (intf instanceof SerialPort) {
return true;
}
}
return false;
}
public String getDescription(Visualizer visualizer, Mote mote) {
return "Show serial port on " + mote;
}
public void doAction(Visualizer visualizer, Mote mote) {
Simulation simulation = mote.getSimulation();
SerialPort serialPort = null;
for (MoteInterface intf: mote.getInterfaces().getInterfaces()) {
if (intf instanceof SerialPort) {
serialPort = (SerialPort) intf;
break;
}
}
if (serialPort == null) {
return;
}
/* Extract description (input to plugin) */
String desc = Cooja.getDescriptionOf(serialPort);
MoteInterfaceViewer viewer =
(MoteInterfaceViewer) simulation.getCooja().tryStartPlugin(
MoteInterfaceViewer.class,
simulation.getCooja(),
simulation,
mote);
if (viewer == null) {
return;
}
viewer.setSelectedInterface(desc);
viewer.pack();
}
};
protected static class MoveMoteMenuAction implements MoteMenuAction {
public boolean isEnabled(Visualizer visualizer, Mote mote) {
return true;
}
public String getDescription(Visualizer visualizer, Mote mote) {
return "Move " + mote;
}
public void doAction(Visualizer visualizer, Mote mote) {
visualizer.beginMoveRequest(mote, false, false);
}
};
protected static class ResetViewportAction implements SimulationMenuAction {
public void doAction(Visualizer visualizer, Simulation simulation) {
visualizer.resetViewport = 1;
visualizer.repaint();
}
public String getDescription(Visualizer visualizer, Simulation simulation) {
return "Reset viewport";
}
public boolean isEnabled(Visualizer visualizer, Simulation simulation) {
return true;
}
};
protected static class ToggleDecorationsMenuAction implements SimulationMenuAction {
public void doAction(final Visualizer visualizer, Simulation simulation) {
if (!(visualizer.getUI() instanceof BasicInternalFrameUI)) {
return;
}
BasicInternalFrameUI ui = (BasicInternalFrameUI) visualizer.getUI();
if (ui.getNorthPane().getPreferredSize() == null ||
ui.getNorthPane().getPreferredSize().height == 0) {
/* Restore window decorations */
ui.getNorthPane().setPreferredSize(null);
} else {
/* Hide window decorations */
ui.getNorthPane().setPreferredSize(new Dimension(0,0));
}
visualizer.revalidate();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
visualizer.repaint();
}
});
}
public String getDescription(Visualizer visualizer, Simulation simulation) {
if (!(visualizer.getUI() instanceof BasicInternalFrameUI)) {
return "Hide window decorations";
}
BasicInternalFrameUI ui = (BasicInternalFrameUI) visualizer.getUI();
if (ui.getNorthPane().getPreferredSize() == null ||
ui.getNorthPane().getPreferredSize().height == 0) {
return "Restore window decorations";
}
return "Hide window decorations";
}
public boolean isEnabled(Visualizer visualizer, Simulation simulation) {
if (!(visualizer.getUI() instanceof BasicInternalFrameUI)) {
return false;
}
return true;
}
}
public String getQuickHelp() {
return "<b>Network</b> "
+ "<p>The network window shows the positions of simulated motes. "
+ "<p>"
+ "It is possible to zoom <em>(Mouse wheel)</em> and pan <em>(Shift+Mouse drag)</em> the current view. "
+ "Motes can be moved by dragging them. "
+ "You can add/remove motes to/from selection <em>(CTRL+Left click)</em> "
+ "or use the rectangular selection tool <em>(CTRL+Mouse drag)</em>. "
+ "Mouse right-click motes for options menu. "
+ "<p>"
+ "The network window supports different views. "
+ "Each view provides some specific information, such as the IP addresses of motes. "
+ "Multiple views can be active at the same time. "
+ "Use the View menu to select views. ";
}
private class Selection {
private int x;
private int y;
private int width;
private int height;
private boolean enable;
public void setSelection(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public void setEnabled(boolean enable) {
this.enable = enable;
}
public void drawSelection(Graphics g) {
/* only draw if enabled */
if (!enable) {
return;
}
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(new Color(64, 64, 64, 10));
g2d.fillRect(x, y, width, height);
BasicStroke dashed
= new BasicStroke(1.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, new float[]{5.0f}, 0.0f);
g2d.setColor(Color.BLACK);
g2d.setStroke(dashed);
g2d.drawRect(x, y, width, height);
}
}
}
|
package twitter4j.util;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.http.Authorization;
import twitter4j.http.BasicAuthorization;
import twitter4j.http.OAuthAuthorization;
import twitter4j.internal.http.HttpClientWrapper;
import twitter4j.internal.http.HttpParameter;
import twitter4j.internal.http.HttpResponse;
import twitter4j.internal.org.json.JSONException;
import twitter4j.internal.org.json.JSONObject;
public abstract class ImageUpload {
public static String DEFAULT_TWITPIC_API_KEY = null;
public abstract String upload(File image) throws TwitterException;
public abstract String upload(File image, String message) throws TwitterException;
public abstract String upload(String imageFileName, InputStream imageBody) throws TwitterException;
public abstract String upload(String imageFileName, InputStream imageBody, String message) throws TwitterException;
/**
* Returns an image uploader to Twitpic. Handles both BasicAuth and OAuth.
* Note: When using OAuth, the Twitpic API Key needs to be specified, either with the field ImageUpload.DEFAULT_TWITPIC_API_KEY,
* or using the getTwitpicUploader (String twitpicAPIKey, OAuthAuthorization auth) method
*/
public static ImageUpload getTwitpicUploader(Twitter twitter) throws TwitterException {
Authorization auth = twitter.getAuthorization();
if (auth instanceof OAuthAuthorization)
return getTwitpicUploader(DEFAULT_TWITPIC_API_KEY, (OAuthAuthorization) auth);
ensureBasicEnabled(auth);
return getTwitpicUploader((BasicAuthorization) auth);
}
/**
* Returns a BasicAuth image uploader to Twitpic
*/
public static ImageUpload getTwitpicUploader(BasicAuthorization auth) {
return new TwitpicBasicAuthUploader(auth);
}
/**
* Returns an OAuth image uploader to Twitpic
*/
public static ImageUpload getTwitpicUploader(String twitpicAPIKey, OAuthAuthorization auth) {
return new TwitpicOAuthUploader(twitpicAPIKey, auth);
}
/**
* Returns an OAuth image uploader to TweetPhoto
*/
public static ImageUpload getTweetPhotoUploader(String tweetPhotoAPIKey, OAuthAuthorization auth) {
return new TweetPhotoOAuthUploader(tweetPhotoAPIKey, auth);
}
/**
* Returns an image uploader to YFrog. Handles both BasicAuth and OAuth
*/
public static ImageUpload getYFrogUploader(Twitter twitter) throws TwitterException {
Authorization auth = twitter.getAuthorization();
if (auth instanceof OAuthAuthorization)
return getYFrogUploader(twitter.getScreenName(), (OAuthAuthorization) auth);
ensureBasicEnabled(auth);
return getYFrogUploader((BasicAuthorization) auth);
}
/**
* Returns a BasicAuth image uploader to YFrog
*/
public static ImageUpload getYFrogUploader(BasicAuthorization auth) {
return new YFrogBasicAuthUploader(auth);
}
/**
* Returns an OAuth image uploader to YFrog
*/
public static ImageUpload getYFrogUploader(String userId, OAuthAuthorization auth) {
return new YFrogOAuthUploader(userId, auth);
}
/**
* Returns an OAuth image uploader to img.ly
*/
public static ImageUpload getImgLyUploader (OAuthAuthorization auth) {
return new ImgLyOAuthUploader (auth);
}
/**
* Returns an OAuth image uploader to Twitgoo
*/
public static ImageUpload getTwitgooUploader(OAuthAuthorization auth) {
return new TwitgooOAuthUploader (auth);
}
private static void ensureBasicEnabled(Authorization auth) {
if (!(auth instanceof BasicAuthorization)) {
throw new IllegalStateException(
"user ID/password combination not supplied");
}
}
private static class YFrogOAuthUploader extends ImageUpload {
private String user;
private OAuthAuthorization auth;
// uses the secure upload URL, not the one specified in the YFrog FAQ
private static final String YFROG_UPLOAD_URL = "https://yfrog.com/api/upload";
private static final String TWITTER_VERIFY_CREDENTIALS = "https://api.twitter.com/1/account/verify_credentials.xml";
public YFrogOAuthUploader(String user, OAuthAuthorization auth) {
this.user = user;
this.auth = auth;
}
@Override
public String upload(File image) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", image)
});
}
@Override
public String upload(File image, String message) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", image),
new HttpParameter("message", message)
});
}
@Override
public String upload(String imageFileName, InputStream imageBody) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", imageFileName, imageBody)
});
}
@Override
public String upload(String imageFileName, InputStream imageBody, String message) throws TwitterException {
try {
message = URLEncoder.encode(message, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
return upload(new HttpParameter[]{
new HttpParameter("media", imageFileName, imageBody),
new HttpParameter("message", message)
});
}
private String upload(HttpParameter[] additionalParams) throws TwitterException {
// step 1 - generate verification URL
String signedVerifyCredentialsURL = generateSignedVerifyCredentialsURL();
// step 2 - generate HTTP parameters
HttpParameter[] params = {
new HttpParameter("auth", "oauth"),
new HttpParameter("username", user),
new HttpParameter("verify_url", signedVerifyCredentialsURL),
};
params = appendHttpParameters(params, additionalParams);
// step 3 - upload the file
HttpClientWrapper client = new HttpClientWrapper();
HttpResponse httpResponse = client.post(YFROG_UPLOAD_URL, params);
// step 4 - check the response
int statusCode = httpResponse.getStatusCode();
if (statusCode != 200) {
throw new TwitterException("YFrog image upload returned invalid status code", httpResponse);
}
String response = httpResponse.asString();
if (-1 != response.indexOf("<rsp stat=\"fail\">")) {
String error = response.substring(response.indexOf("msg") + 5, response.lastIndexOf("\""));
throw new TwitterException("YFrog image upload failed with this error message: " + error, httpResponse);
}
if (-1 != response.indexOf("<rsp stat=\"ok\">")) {
String media = response.substring(response.indexOf("<mediaurl>") + "<mediaurl>".length(), response.indexOf("</mediaurl>"));
return media;
}
throw new TwitterException("Unknown YFrog response", httpResponse);
}
private String generateSignedVerifyCredentialsURL() {
List<HttpParameter> oauthSignatureParams = auth.generateOAuthSignatureHttpParams("GET", TWITTER_VERIFY_CREDENTIALS);
return TWITTER_VERIFY_CREDENTIALS + "?" + OAuthAuthorization.encodeParameters(oauthSignatureParams);
}
}
private static class YFrogBasicAuthUploader extends ImageUpload {
private BasicAuthorization auth;
// uses the secure upload URL, not the one specified in the YFrog FAQ
private static final String YFROG_UPLOAD_URL = "https://yfrog.com/api/upload";
public YFrogBasicAuthUploader(BasicAuthorization auth) {
this.auth = auth;
}
@Override
public String upload(File image) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", image)
});
}
@Override
public String upload(File image, String message) throws TwitterException {
// step 1 - generate HTTP parameters
try {
message = URLEncoder.encode(message, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
return upload(new HttpParameter[]{
new HttpParameter("media", image),
new HttpParameter("message", message)
});
}
@Override
public String upload(String imageFileName, InputStream imageBody) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", imageFileName, imageBody),
});
}
@Override
public String upload(String imageFileName, InputStream imageBody, String message) throws TwitterException {
try {
message = URLEncoder.encode(message, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
return upload(new HttpParameter[]{
new HttpParameter("media", imageFileName, imageBody),
new HttpParameter("message", message),
});
}
private String upload(HttpParameter[] additionalParams) throws TwitterException {
// step 1 - generate HTTP parameters
HttpParameter[] params = {
new HttpParameter("username", auth.getUserId()),
new HttpParameter("password", auth.getPassword()),
};
params = appendHttpParameters(params, additionalParams);
// step 2 - upload the file
HttpClientWrapper client = new HttpClientWrapper();
HttpResponse httpResponse = client.post(YFROG_UPLOAD_URL, params);
// step 3 - check the response
int statusCode = httpResponse.getStatusCode();
if (statusCode != 200)
throw new TwitterException("YFrog image upload returned invalid status code", httpResponse);
String response = httpResponse.asString();
if (-1 != response.indexOf("<rsp stat=\"fail\">")) {
String error = response.substring(response.indexOf("msg") + 5, response.lastIndexOf("\""));
throw new TwitterException("YFrog image upload failed with this error message: " + error, httpResponse);
}
if (-1 != response.indexOf("<rsp stat=\"ok\">")) {
String media = response.substring(response.indexOf("<mediaurl>") + "<mediaurl>".length(), response.indexOf("</mediaurl>"));
return media;
}
throw new TwitterException("Unknown YFrog response", httpResponse);
}
}
private static class TwitpicOAuthUploader extends ImageUpload {
private String twitpicAPIKey;
private OAuthAuthorization auth;
// uses the secure upload URL, not the one specified in the Twitpic FAQ
private static final String TWITPIC_UPLOAD_URL = "https://twitpic.com/api/2/upload.json";
private static final String TWITTER_VERIFY_CREDENTIALS = "https://api.twitter.com/1/account/verify_credentials.json";
public TwitpicOAuthUploader(String twitpicAPIKey, OAuthAuthorization auth) {
if (twitpicAPIKey == null || "".equals(twitpicAPIKey))
throw new IllegalArgumentException("The Twitpic API Key supplied to the OAuth image uploader can't be null or empty");
this.twitpicAPIKey = twitpicAPIKey;
this.auth = auth;
}
@Override
public String upload(File image) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", image)
});
}
@Override
public String upload(File image, String message) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", image),
new HttpParameter("message", message),
});
}
@Override
public String upload(String imageFileName, InputStream imageBody) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", imageFileName, imageBody)
});
}
@Override
public String upload(String imageFileName, InputStream imageBody, String message) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", imageFileName, imageBody),
new HttpParameter("message", message)
});
}
private String upload(HttpParameter[] additionalParams) throws TwitterException {
// step 1 - generate HTTP request headers
String verifyCredentialsAuthorizationHeader = generateVerifyCredentialsAuthorizationHeader();
Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Auth-Service-Provider", TWITTER_VERIFY_CREDENTIALS);
headers.put("X-Verify-Credentials-Authorization", verifyCredentialsAuthorizationHeader);
// step 2 - generate HTTP parameters
HttpParameter[] params = {
new HttpParameter("key", twitpicAPIKey),
};
params = appendHttpParameters(params, additionalParams);
// step 3 - upload the file
HttpClientWrapper client = new HttpClientWrapper();
HttpResponse httpResponse = client.post(TWITPIC_UPLOAD_URL, params, headers);
// step 4 - check the response
int statusCode = httpResponse.getStatusCode();
if (statusCode != 200)
throw new TwitterException("Twitpic image upload returned invalid status code", httpResponse);
String response = httpResponse.asString();
try {
JSONObject json = new JSONObject(response);
if (!json.isNull("url"))
return json.getString("url");
}
catch (JSONException e) {
throw new TwitterException("Invalid Twitpic response: " + response, e);
}
throw new TwitterException("Unknown Twitpic response", httpResponse);
}
private String generateVerifyCredentialsAuthorizationHeader() {
List<HttpParameter> oauthSignatureParams = auth.generateOAuthSignatureHttpParams("GET", TWITTER_VERIFY_CREDENTIALS);
return "OAuth realm=\"http://api.twitter.com/\"," + OAuthAuthorization.encodeParameters(oauthSignatureParams, ",", true);
}
}
private static class TwitpicBasicAuthUploader extends ImageUpload {
private BasicAuthorization auth;
// uses the secure upload URL, not the one specified in the Twitpic FAQ
private static final String TWITPIC_UPLOAD_URL = "https://twitpic.com/api/upload";
public TwitpicBasicAuthUploader(BasicAuthorization auth) {
this.auth = auth;
}
@Override
public String upload(File image) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", image)
});
}
@Override
public String upload(File image, String message) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", image),
new HttpParameter("message", message)
});
}
@Override
public String upload(String imageFileName, InputStream imageBody) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", imageFileName, imageBody)
});
}
@Override
public String upload(String imageFileName, InputStream imageBody, String message) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", imageFileName, imageBody),
new HttpParameter("message", message)
});
}
private String upload(HttpParameter[] additionalParams) throws TwitterException {
// step 1 - generate HTTP parameters
HttpParameter[] params = {
new HttpParameter("username", auth.getUserId()),
new HttpParameter("password", auth.getPassword()),
};
params = appendHttpParameters(params, additionalParams);
// step 2 - upload the file
HttpClientWrapper client = new HttpClientWrapper();
HttpResponse httpResponse = client.post(TWITPIC_UPLOAD_URL, params);
// step 3 - check the response
int statusCode = httpResponse.getStatusCode();
if (statusCode != 200)
throw new TwitterException("Twitpic image upload returned invalid status code", httpResponse);
String response = httpResponse.asString();
if (-1 != response.indexOf("<rsp stat=\"fail\">")) {
String error = response.substring(response.indexOf("msg") + 5, response.lastIndexOf("\""));
throw new TwitterException("Twitpic image upload failed with this error message: " + error, httpResponse);
}
if (-1 != response.indexOf("<rsp stat=\"ok\">")) {
String media = response.substring(response.indexOf("<mediaurl>") + "<mediaurl>".length(), response.indexOf("</mediaurl>"));
return media;
}
throw new TwitterException("Unknown Twitpic response", httpResponse);
}
}
public static class TweetPhotoOAuthUploader extends ImageUpload
{
private String tweetPhotoAPIKey;
private OAuthAuthorization auth;
// uses the secure upload URL, not the one specified in the Twitpic FAQ
private static final String TWEETPHOTO_UPLOAD_URL = "http:
private static final String TWITTER_VERIFY_CREDENTIALS = "https://api.twitter.com/1/account/verify_credentials.xml";
public TweetPhotoOAuthUploader(String tweetPhotoAPIKey, OAuthAuthorization auth) {
if (tweetPhotoAPIKey == null || "".equals(tweetPhotoAPIKey))
throw new IllegalArgumentException("The TweetPhoto API Key supplied to the OAuth image uploader can't be null or empty");
this.tweetPhotoAPIKey = tweetPhotoAPIKey;
this.auth = auth;
}
@Override
public String upload(File image) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", image)
});
}
@Override
public String upload(File image, String message) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", image),
new HttpParameter("message", message)
});
}
@Override
public String upload(String imageFileName, InputStream imageBody) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", imageFileName, imageBody),
});
}
@Override
public String upload(String imageFileName, InputStream imageBody, String message) throws TwitterException {
return upload(new HttpParameter[]{
new HttpParameter("media", imageFileName, imageBody),
new HttpParameter("message", message)
});
}
private String upload(HttpParameter[] additionalParams) throws TwitterException {
// step 1 - generate HTTP request headers
String verifyCredentialsAuthorizationHeader = generateVerifyCredentialsAuthorizationHeader();
Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Auth-Service-Provider", TWITTER_VERIFY_CREDENTIALS);
headers.put("X-Verify-Credentials-Authorization", verifyCredentialsAuthorizationHeader);
// step 2 - generate HTTP parameters
HttpParameter[] params = {
new HttpParameter("api_key", tweetPhotoAPIKey),
};
params = appendHttpParameters(params, additionalParams);
// step 3 - upload the file
HttpClientWrapper client = new HttpClientWrapper();
HttpResponse httpResponse = client.post(TWEETPHOTO_UPLOAD_URL, params, headers);
// step 4 - check the response
int statusCode = httpResponse.getStatusCode();
if (statusCode != 201)
throw new TwitterException("Twitpic image upload returned invalid status code", httpResponse);
String response = httpResponse.asString();
if (-1 != response.indexOf("<Error><ErrorCode>")) {
String error = response.substring(response.indexOf("<ErrorCode>") + "<ErrorCode>".length(), response.lastIndexOf("</ErrorCode>"));
throw new TwitterException("TweetPhoto image upload failed with this error message: " + error, httpResponse);
}
if (-1 != response.indexOf("<Status>OK</Status>")) {
String media = response.substring(response.indexOf("<MediaUrl>") + "<MediaUrl>".length(), response.indexOf("</MediaUrl>"));
return media;
}
throw new TwitterException("Unknown TweetPhoto response", httpResponse);
}
private String generateVerifyCredentialsAuthorizationHeader() {
List<HttpParameter> oauthSignatureParams = auth.generateOAuthSignatureHttpParams("GET", TWITTER_VERIFY_CREDENTIALS);
return "OAuth realm=\"http://api.twitter.com/\"," + OAuthAuthorization.encodeParameters(oauthSignatureParams, ",", true);
}
}
public static class ImgLyOAuthUploader extends ImageUpload
{
private OAuthAuthorization auth;
// uses the secure upload URL, not the one specified in the Twitpic FAQ
private static final String IMGLY_UPLOAD_URL = "http://img.ly/api/2/upload.json";
private static final String TWITTER_VERIFY_CREDENTIALS = "https://api.twitter.com/1/account/verify_credentials.json";
public ImgLyOAuthUploader (OAuthAuthorization auth)
{
this.auth = auth;
}
@Override
public String upload (File image) throws TwitterException
{
return upload(new HttpParameter[]{
new HttpParameter ("media", image)
});
}
@Override
public String upload (File image, String message) throws TwitterException
{
return upload(new HttpParameter[]{
new HttpParameter ("media", image),
new HttpParameter ("message", message)
});
}
@Override
public String upload (String imageFileName, InputStream imageBody) throws TwitterException
{
return upload(new HttpParameter[]{
new HttpParameter ("media", imageFileName, imageBody),
});
}
@Override
public String upload (String imageFileName, InputStream imageBody, String message) throws TwitterException
{
return upload(new HttpParameter[]{
new HttpParameter ("media", imageFileName, imageBody),
new HttpParameter ("message", message)
});
}
private String upload (HttpParameter[] additionalParams) throws TwitterException
{
// step 1 - generate HTTP request headers
String verifyCredentialsAuthorizationHeader = generateVerifyCredentialsAuthorizationHeader ();
Map<String, String> headers = new HashMap<String, String>();
headers.put ("X-Auth-Service-Provider", TWITTER_VERIFY_CREDENTIALS);
headers.put ("X-Verify-Credentials-Authorization", verifyCredentialsAuthorizationHeader);
// step 2 - generate HTTP parameters
HttpParameter[] params = {
};
params = appendHttpParameters(params, additionalParams);
// step 3 - upload the file
HttpClientWrapper client = new HttpClientWrapper ();
HttpResponse httpResponse = client.post (IMGLY_UPLOAD_URL, params, headers);
// step 4 - check the response
int statusCode = httpResponse.getStatusCode ();
if (statusCode != 200)
throw new TwitterException ("ImgLy image upload returned invalid status code", httpResponse);
String response = httpResponse.asString ();
try
{
JSONObject json = new JSONObject (response);
if (! json.isNull ("url"))
return json.getString ("url");
}
catch (JSONException e)
{
throw new TwitterException ("Invalid ImgLy response: " + response, e);
}
throw new TwitterException ("Unknown ImgLy response", httpResponse);
}
private String generateVerifyCredentialsAuthorizationHeader ()
{
List<HttpParameter> oauthSignatureParams = auth.generateOAuthSignatureHttpParams ("GET", TWITTER_VERIFY_CREDENTIALS);
return "OAuth realm=\"http://api.twitter.com/\"," + OAuthAuthorization.encodeParameters (oauthSignatureParams, ",", true);
}
}
public static class TwitgooOAuthUploader extends ImageUpload
{
private OAuthAuthorization auth;
// uses the secure upload URL, not the one specified in the Twitpic FAQ
private static final String TWITGOO_UPLOAD_URL = "http://twitgoo.com/api/uploadAndPost";
private static final String TWITTER_VERIFY_CREDENTIALS = "https://api.twitter.com/1/account/verify_credentials.json";
public TwitgooOAuthUploader(OAuthAuthorization auth)
{
this.auth = auth;
}
@Override
public String upload (File image) throws TwitterException
{
return upload(new HttpParameter[]{
new HttpParameter ("media", image)
});
}
@Override
public String upload (File image, String message) throws TwitterException
{
return upload(new HttpParameter[]{
new HttpParameter ("media", image),
new HttpParameter ("message", message)
});
}
@Override
public String upload (String imageFileName, InputStream imageBody) throws TwitterException
{
return upload(new HttpParameter[]{
new HttpParameter ("media", imageFileName, imageBody),
});
}
@Override
public String upload (String imageFileName, InputStream imageBody, String message) throws TwitterException
{
return upload(new HttpParameter[]{
new HttpParameter ("media", imageFileName, imageBody),
new HttpParameter ("message", message)
});
}
private String upload (HttpParameter[] additionalParams) throws TwitterException
{
// step 1 - generate HTTP request headers
String verifyCredentialsAuthorizationHeader = generateVerifyCredentialsAuthorizationHeader ();
Map<String, String> headers = new HashMap<String, String>();
headers.put ("X-Auth-Service-Provider", TWITTER_VERIFY_CREDENTIALS);
headers.put ("X-Verify-Credentials-Authorization", verifyCredentialsAuthorizationHeader);
// step 2 - generate HTTP parameters
HttpParameter[] params = {
new HttpParameter("no_twitter_post", "1")
};
params = appendHttpParameters(params, additionalParams);
// step 3 - upload the file
HttpClientWrapper client = new HttpClientWrapper ();
HttpResponse httpResponse = client.post (TWITGOO_UPLOAD_URL, params, headers);
// step 4 - check the response
int statusCode = httpResponse.getStatusCode ();
if (statusCode != 200)
throw new TwitterException ("Twitgoo image upload returned invalid status code", httpResponse);
String response = httpResponse.asString ();
if(-1 != response.indexOf("<rsp status=\"ok\">")){
String h = "<mediaurl>";
int i = response.indexOf(h);
if(i != -1){
int j = response.indexOf("</mediaurl>", i + h.length());
if(j != -1){
return response.substring(i + h.length(), j);
}
}
} else if(-1 != response.indexOf("<rsp status=\"fail\">")){
String h = "msg=\"";
int i = response.indexOf(h);
if(i != -1){
int j = response.indexOf("\"", i + h.length());
if(j != -1){
String msg = response.substring(i + h.length(), j);
throw new TwitterException ("Invalid Twitgoo response: " + msg);
}
}
}
throw new TwitterException ("Unknown Twitgoo response", httpResponse);
}
private String generateVerifyCredentialsAuthorizationHeader ()
{
List<HttpParameter> oauthSignatureParams = auth.generateOAuthSignatureHttpParams ("GET", TWITTER_VERIFY_CREDENTIALS);
return "OAuth realm=\"http://api.twitter.com/\"," + OAuthAuthorization.encodeParameters (oauthSignatureParams, ",", true);
}
}
private static HttpParameter[] appendHttpParameters(HttpParameter[] src, HttpParameter[] dst) {
int srcLen = src.length;
int dstLen = dst.length;
HttpParameter[] ret = new HttpParameter[srcLen + dstLen];
for (int i = 0; i < srcLen; i++) {
ret[i] = src[i];
}
for (int i = 0; i < dstLen; i++) {
ret[srcLen + i] = dst[i];
}
return ret;
}
}
|
package soot.jimple.toolkits.callgraph;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import soot.ArrayType;
import soot.Body;
import soot.Context;
import soot.EntryPoints;
import soot.FastHierarchy;
import soot.G;
import soot.Kind;
import soot.Local;
import soot.MethodContext;
import soot.MethodOrMethodContext;
import soot.PackManager;
import soot.PhaseOptions;
import soot.RefType;
import soot.Scene;
import soot.SceneTransformer;
import soot.SootClass;
import soot.SootMethod;
import soot.SootMethodRef;
import soot.Transform;
import soot.Type;
import soot.Unit;
import soot.Value;
import soot.javaToJimple.LocalGenerator;
import soot.jimple.AssignStmt;
import soot.jimple.FieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.Jimple;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.SpecialInvokeExpr;
import soot.jimple.StaticFieldRef;
import soot.jimple.StaticInvokeExpr;
import soot.jimple.Stmt;
import soot.jimple.StringConstant;
import soot.jimple.VirtualInvokeExpr;
import soot.options.CGOptions;
import soot.tagkit.Host;
import soot.tagkit.SourceLnPosTag;
import soot.util.LargeNumberedMap;
import soot.util.NumberedString;
import soot.util.SmallNumberedMap;
import soot.util.queue.ChunkedQueue;
import soot.util.queue.QueueReader;
/** Models the call graph.
* @author Ondrej Lhotak
*/
public final class OnFlyCallGraphBuilder
{
public class DefaultReflectionModel implements ReflectionModel {
protected CGOptions options = new CGOptions( PhaseOptions.v().getPhaseOptions("cg") );
protected HashSet<SootMethod> warnedAlready = new HashSet<SootMethod>();
public void classForName(SootMethod source, Stmt s) {
List<Local> stringConstants = (List<Local>) methodToStringConstants.get(source);
if( stringConstants == null )
methodToStringConstants.put(source, stringConstants = new ArrayList<Local>());
InvokeExpr ie = s.getInvokeExpr();
Value className = ie.getArg(0);
if( className instanceof StringConstant ) {
String cls = ((StringConstant) className ).value;
constantForName( cls, source, s );
} else {
Local constant = (Local) className;
if( options.safe_forname() ) {
for (SootMethod tgt : EntryPoints.v().clinits()) {
addEdge( source, s, tgt, Kind.CLINIT );
}
} else {
for (SootClass cls : Scene.v().dynamicClasses()) {
for (SootMethod clinit : EntryPoints.v().clinitsOf(cls)) {
addEdge( source, s, clinit, Kind.CLINIT);
}
}
VirtualCallSite site = new VirtualCallSite( s, source, null, null, Kind.CLINIT );
List<VirtualCallSite> sites = (List<VirtualCallSite>) stringConstToSites.get(constant);
if (sites == null) {
stringConstToSites.put(constant, sites = new ArrayList<VirtualCallSite>());
stringConstants.add(constant);
}
sites.add(site);
}
}
}
public void classNewInstance(SootMethod source, Stmt s) {
if( options.safe_newinstance() ) {
for (SootMethod tgt : EntryPoints.v().inits()) {
addEdge( source, s, tgt, Kind.NEWINSTANCE );
}
} else {
for (SootClass cls : Scene.v().dynamicClasses()) {
if( cls.declaresMethod(sigInit) ) {
addEdge( source, s, cls.getMethod(sigInit), Kind.NEWINSTANCE );
}
}
if( options.verbose() ) {
G.v().out.println( "Warning: Method "+source+
" is reachable, and calls Class.newInstance;"+
" graph will be incomplete!"+
" Use safe-newinstance option for a conservative result." );
}
}
}
public void contructorNewInstance(SootMethod source, Stmt s) {
if( options.safe_newinstance() ) {
for (SootMethod tgt : EntryPoints.v().allInits()) {
addEdge( source, s, tgt, Kind.NEWINSTANCE );
}
} else {
for (SootClass cls : Scene.v().dynamicClasses()) {
for(SootMethod m: cls.getMethods()) {
if(m.getName().equals("<init>")) {
addEdge( source, s, m, Kind.NEWINSTANCE );
}
}
}
if( options.verbose() ) {
G.v().out.println( "Warning: Method "+source+
" is reachable, and calls Constructor.newInstance;"+
" graph will be incomplete!"+
" Use safe-newinstance option for a conservative result." );
}
}
}
public void methodInvoke(SootMethod container, Stmt invokeStmt) {
if( !warnedAlready(container) ) {
if( options.verbose() ) {
G.v().out.println( "Warning: call to "+
"java.lang.reflect.Method: invoke() from "+container+
"; graph will be incomplete!" );
}
markWarned(container);
}
}
private void markWarned(SootMethod m) {
warnedAlready.add(m);
}
private boolean warnedAlready(SootMethod m) {
return warnedAlready.contains(m);
}
}
public class TraceBasedReflectionModel implements ReflectionModel {
class Guard {
public Guard(SootMethod container, Stmt stmt, String message) {
this.container = container;
this.stmt = stmt;
this.message = message;
}
final SootMethod container;
final Stmt stmt;
final String message;
}
protected Map<SootMethod,Set<String>> classForNameReceivers;
protected Map<SootMethod,Set<String>> classNewInstanceReceivers;
protected Map<SootMethod,Set<String>> constructorNewInstanceReceivers;
protected Map<SootMethod,Set<String>> methodInvokeReceivers;
protected Set<Guard> guards;
private boolean registeredTransformation = false;
private TraceBasedReflectionModel() {
classForNameReceivers = new HashMap<SootMethod, Set<String>>();
classNewInstanceReceivers = new HashMap<SootMethod, Set<String>>();
constructorNewInstanceReceivers = new HashMap<SootMethod, Set<String>>();
methodInvokeReceivers = new HashMap<SootMethod, Set<String>>();
guards = new HashSet<Guard>();
String logFile = options.reflection_log();
if(logFile==null) {
throw new InternalError("Trace based refection model enabled but no trace file given!?");
} else {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(logFile)));
String line;
int lines = 0;
while((line=reader.readLine())!=null) {
if(line.length()==0) continue;
String[] portions = line.split(";");
String kind = portions[0];
String target = portions[1];
String source = portions[2];
Set<SootMethod> possibleSourceMethods = inferSource(source);
for (SootMethod sourceMethod : possibleSourceMethods) {
if(kind.equals("Class.forName")) {
Set<String> receiverNames;
if((receiverNames=classForNameReceivers.get(sourceMethod))==null) {
classForNameReceivers.put(sourceMethod, receiverNames = new HashSet<String>());
}
receiverNames.add(target);
} else if(kind.equals("Class.newInstance")) {
Set<String> receiverNames;
if((receiverNames=classNewInstanceReceivers.get(sourceMethod))==null) {
classNewInstanceReceivers.put(sourceMethod, receiverNames = new HashSet<String>());
}
receiverNames.add(target);
} else if(kind.equals("Method.invoke")) {
if(!Scene.v().containsMethod(target)) {
throw new RuntimeException("Unknown method for signature: "+target);
}
Set<String> receiverNames;
if((receiverNames=methodInvokeReceivers.get(sourceMethod))==null) {
methodInvokeReceivers.put(sourceMethod, receiverNames = new HashSet<String>());
}
receiverNames.add(target);
} else if (kind.equals("Constructor.newInstance")) {
if(!Scene.v().containsMethod(target)) {
throw new RuntimeException("Unknown method for signature: "+target);
}
Set<String> receiverNames;
if((receiverNames=constructorNewInstanceReceivers.get(sourceMethod))==null) {
constructorNewInstanceReceivers.put(sourceMethod, receiverNames = new HashSet<String>());
}
receiverNames.add(target);
} else
throw new RuntimeException("Unknown entry kind: "+kind);
}
lines++;
}
if(options.verbose()) {
G.v().out.println("Successfully read information about "+lines+" reflective call sites from trace file.");
}
} catch (FileNotFoundException e) {
throw new RuntimeException("Trace file not found.",e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private Set<SootMethod> inferSource(String source) {
String classNameDotMethodName = source.substring(0,source.indexOf("("));
String className = classNameDotMethodName.substring(0,classNameDotMethodName.lastIndexOf("."));
String methodName = classNameDotMethodName.substring(classNameDotMethodName.lastIndexOf(".")+1);
if(!Scene.v().containsClass(className)) {
Scene.v().addBasicClass(className, SootClass.BODIES);
Scene.v().loadBasicClasses();
if(!Scene.v().containsClass(className)) {
throw new RuntimeException("Trace file refers to unknown class: "+className);
}
}
SootClass sootClass = Scene.v().getSootClass(className);
Set<SootMethod> methodsWithRightName = new HashSet<SootMethod>();
for (SootMethod m: sootClass.getMethods()) {
if(m.getName().equals(methodName)) {
methodsWithRightName.add(m);
}
}
if(methodsWithRightName.isEmpty()) {
throw new RuntimeException("Trace file refers to unknown method with name "+methodName+" in Class "+className);
} else if(methodsWithRightName.size()==1) {
return Collections.singleton(methodsWithRightName.iterator().next());
} else {
int lineNumber = Integer.parseInt(source.substring(source.indexOf(":")+1, source.lastIndexOf(")")));
//more than one method with that name
for (SootMethod sootMethod : methodsWithRightName) {
if(coversLineNumber(lineNumber, sootMethod)) {
return Collections.singleton(sootMethod);
}
if(sootMethod.hasActiveBody()) {
Body body = sootMethod.getActiveBody();
if(coversLineNumber(lineNumber, body)) {
return Collections.singleton(sootMethod);
}
for (Unit u : body.getUnits()) {
if(coversLineNumber(lineNumber, u)) {
return Collections.singleton(sootMethod);
}
}
}
}
//if we get here then we found no method with the right line number information;
//be conservative and return all method that we found
return methodsWithRightName;
}
}
private boolean coversLineNumber(int lineNumber, Host host) {
SourceLnPosTag tag = (SourceLnPosTag) host.getTag("SourceLnPosTag");
if(tag!=null) {
if(tag.startLn()<=lineNumber && tag.endLn()>=lineNumber) {
return true;
}
}
return false;
}
/**
* Adds an edge to all class initializers of all possible receivers
* of Class.forName() calls within source.
*/
public void classForName(SootMethod container, Stmt forNameInvokeStmt) {
Set<String> classNames = classForNameReceivers.get(container);
if(classNames==null || classNames.isEmpty()) {
registerGuard(container, forNameInvokeStmt, "Class.forName()");
} else {
for (String clsName : classNames) {
constantForName( clsName, container, forNameInvokeStmt );
}
}
}
public void classNewInstance(SootMethod container, Stmt newInstanceInvokeStmt) {
Set<String> classNames = classNewInstanceReceivers.get(container);
if(classNames==null || classNames.isEmpty()) {
registerGuard(container, newInstanceInvokeStmt, "Class.newInstance()");
} else {
for (String clsName : classNames) {
SootClass cls = Scene.v().getSootClass(clsName);
if( cls.declaresMethod(sigInit) ) {
addEdge( container, newInstanceInvokeStmt, cls.getMethod(sigInit), Kind.NEWINSTANCE );
}
}
}
}
public void contructorNewInstance(SootMethod container, Stmt newInstanceInvokeStmt) {
Set<String> constructorSignatures = constructorNewInstanceReceivers.get(container);
if(constructorSignatures==null || constructorSignatures.isEmpty()) {
registerGuard(container, newInstanceInvokeStmt, "Construtor.newInstance(..)");
} else {
for (String constructorSignature : constructorSignatures) {
SootMethod constructor = Scene.v().getMethod(constructorSignature);
addEdge( container, newInstanceInvokeStmt, constructor, Kind.NEWINSTANCE );
}
}
}
public void methodInvoke(SootMethod container, Stmt invokeStmt) {
Set<String> methodSignatures = methodInvokeReceivers.get(container);
if (methodSignatures == null || methodSignatures.isEmpty()) {
registerGuard(container, invokeStmt, "Method.invoke(..)");
} else {
for (String methodSignature : methodSignatures) {
SootMethod method = Scene.v().getMethod(methodSignature);
addEdge( container, invokeStmt, method, Kind.VIRTUAL );
}
}
}
private void registerGuard(SootMethod container, Stmt stmt, String string) {
guards.add(new Guard(container,stmt,string));
if(options.verbose()) {
G.v().out.println("Incomplete trace file: Class.forName() is called in method '" +
container+"' but trace contains no information about the receiver class of this call.");
if(options.guards().equals("ignore")) {
G.v().out.println("Guarding strategy is set to 'ignore'. Will ignore this problem.");
} else if(options.guards().equals("print")) {
G.v().out.println("Guarding strategy is set to 'print'. " +
"Program will print a stack trace if this location is reached during execution.");
} else if(options.guards().equals("throw")) {
G.v().out.println("Guarding strategy is set to 'throw'. Program will throw an " +
"Error if this location is reached during execution.");
} else {
throw new RuntimeException("Invalid value for phase option (guarding): "+options.guards());
}
}
if(!registeredTransformation) {
registeredTransformation=true;
PackManager.v().getPack("wjap").add(new Transform("wjap.guards",new SceneTransformer() {
@Override
protected void internalTransform(String phaseName, Map options) {
for (Guard g : guards) {
insertGuard(g);
}
}
}));
PhaseOptions.v().setPhaseOption("wjap.guards", "enabled");
}
}
private void insertGuard(Guard guard) {
if(options.guards().equals("ignore")) return;
SootMethod container = guard.container;
Stmt insertionPoint = guard.stmt;
if(!container.hasActiveBody()) {
G.v().out.println("WARNING: Tried to insert guard into "+container+" but couldn't because method has no body.");
} else {
Body body = container.getActiveBody();
//exc = new Error
RefType runtimeExceptionType = RefType.v("java.lang.Error");
NewExpr newExpr = Jimple.v().newNewExpr(runtimeExceptionType);
LocalGenerator lg = new LocalGenerator(body);
Local exceptionLocal = lg.generateLocal(runtimeExceptionType);
AssignStmt assignStmt = Jimple.v().newAssignStmt(exceptionLocal, newExpr);
body.getUnits().insertBefore(assignStmt, insertionPoint);
//exc.<init>(message)
SootMethodRef cref = runtimeExceptionType.getSootClass().getMethod("<init>", Collections.singletonList(RefType.v("java.lang.String"))).makeRef();
SpecialInvokeExpr constructorInvokeExpr = Jimple.v().newSpecialInvokeExpr(exceptionLocal, cref, StringConstant.v(guard.message));
InvokeStmt initStmt = Jimple.v().newInvokeStmt(constructorInvokeExpr);
body.getUnits().insertAfter(initStmt, assignStmt);
if(options.guards().equals("print")) {
//exc.printStackTrace();
VirtualInvokeExpr printStackTraceExpr = Jimple.v().newVirtualInvokeExpr(exceptionLocal, Scene.v().getSootClass("java.lang.Throwable").getMethod("printStackTrace", Collections.emptyList()).makeRef());
InvokeStmt printStackTraceStmt = Jimple.v().newInvokeStmt(printStackTraceExpr);
body.getUnits().insertAfter(printStackTraceStmt, initStmt);
} else if(options.guards().equals("throw")) {
body.getUnits().insertAfter(Jimple.v().newThrowStmt(exceptionLocal), initStmt);
} else {
throw new RuntimeException("Invalid value for phase option (guarding): "+options.guards());
}
}
}
}
/** context-insensitive stuff */
private final CallGraph cicg = new CallGraph();
private final HashSet<SootMethod> analyzedMethods = new HashSet<SootMethod>();
private final LargeNumberedMap receiverToSites = new LargeNumberedMap( Scene.v().getLocalNumberer() ); // Local -> List(VirtualCallSite)
private final LargeNumberedMap methodToReceivers = new LargeNumberedMap( Scene.v().getMethodNumberer() ); // SootMethod -> List(Local)
public LargeNumberedMap methodToReceivers() { return methodToReceivers; }
private final SmallNumberedMap stringConstToSites = new SmallNumberedMap( Scene.v().getLocalNumberer() ); // Local -> List(VirtualCallSite)
private final LargeNumberedMap methodToStringConstants = new LargeNumberedMap( Scene.v().getMethodNumberer() ); // SootMethod -> List(Local)
public LargeNumberedMap methodToStringConstants() { return methodToStringConstants; }
private CGOptions options;
private boolean appOnly;
/** context-sensitive stuff */
private ReachableMethods rm;
private QueueReader worklist;
private ContextManager cm;
private final ChunkedQueue targetsQueue = new ChunkedQueue();
private final QueueReader targets = targetsQueue.reader();
public OnFlyCallGraphBuilder( ContextManager cm, ReachableMethods rm ) {
this.cm = cm;
this.rm = rm;
worklist = rm.listener();
options = new CGOptions( PhaseOptions.v().getPhaseOptions("cg") );
if( !options.verbose() ) {
G.v().out.println( "[Call Graph] For information on where the call graph may be incomplete, use the verbose option to the cg phase." );
}
if(options.reflection_log()==null) {
reflectionModel = new DefaultReflectionModel();
} else {
reflectionModel = new TraceBasedReflectionModel();
}
}
public OnFlyCallGraphBuilder( ContextManager cm, ReachableMethods rm, boolean appOnly ) {
this( cm, rm );
this.appOnly = appOnly;
}
public void processReachables() {
while(true) {
if( !worklist.hasNext() ) {
rm.update();
if( !worklist.hasNext() ) break;
}
MethodOrMethodContext momc = (MethodOrMethodContext) worklist.next();
SootMethod m = momc.method();
if( appOnly && !m.getDeclaringClass().isApplicationClass() ) continue;
if( analyzedMethods.add( m ) ) processNewMethod( m );
processNewMethodContext( momc );
}
}
public boolean wantTypes( Local receiver ) {
return receiverToSites.get(receiver) != null;
}
public void addType( Local receiver, Context srcContext, Type type, Context typeContext ) {
FastHierarchy fh = Scene.v().getOrMakeFastHierarchy();
for( Iterator siteIt = ((Collection) receiverToSites.get( receiver )).iterator(); siteIt.hasNext(); ) {
final VirtualCallSite site = (VirtualCallSite) siteIt.next();
InstanceInvokeExpr iie = site.iie();
if( site.kind() == Kind.THREAD
&& !fh.canStoreType( type, clRunnable ) )
continue;
if( site.iie() instanceof SpecialInvokeExpr ) {
targetsQueue.add( VirtualCalls.v().resolveSpecial(
(SpecialInvokeExpr) site.iie(),
site.subSig(),
site.container() ) );
} else {
VirtualCalls.v().resolve( type,
receiver.getType(),
site.subSig(),
site.container(),
targetsQueue );
}
while(targets.hasNext()) {
SootMethod target = (SootMethod) targets.next();
cm.addVirtualEdge(
MethodContext.v( site.container(), srcContext ),
site.stmt(),
target,
site.kind(),
typeContext );
}
}
}
public boolean wantStringConstants( Local stringConst ) {
return stringConstToSites.get(stringConst) != null;
}
public void addStringConstant( Local l, Context srcContext, String constant ) {
for( Iterator siteIt = ((Collection) stringConstToSites.get( l )).iterator(); siteIt.hasNext(); ) {
final VirtualCallSite site = (VirtualCallSite) siteIt.next();
if( constant == null ) {
if( options.verbose() ) {
G.v().out.println( "Warning: Method "+site.container()+
" is reachable, and calls Class.forName on a"+
" non-constant String; graph will be incomplete!"+
" Use safe-forname option for a conservative result." );
}
} else {
if( constant.length() > 0 && constant.charAt(0) == '[' ) {
if( constant.length() > 1 && constant.charAt(1) == 'L'
&& constant.charAt(constant.length()-1) == ';' ) {
constant = constant.substring(2,constant.length()-1);
} else continue;
}
if( !Scene.v().containsClass( constant ) ) {
if( options.verbose() ) {
G.v().out.println( "Warning: Class "+constant+" is"+
" a dynamic class, and you did not specify"+
" it as such; graph will be incomplete!" );
}
} else {
SootClass sootcls = Scene.v().getSootClass( constant );
if( !sootcls.isApplicationClass() ) {
sootcls.setLibraryClass();
}
for (SootMethod clinit : EntryPoints.v().clinitsOf(sootcls)) {
cm.addStaticEdge(
MethodContext.v( site.container(), srcContext ),
site.stmt(),
clinit,
Kind.CLINIT );
}
}
}
}
}
/* End of public methods. */
private void addVirtualCallSite( Stmt s, SootMethod m, Local receiver,
InstanceInvokeExpr iie, NumberedString subSig, Kind kind ) {
List<VirtualCallSite> sites = (List<VirtualCallSite>) receiverToSites.get(receiver);
if (sites == null) {
receiverToSites.put(receiver, sites = new ArrayList<VirtualCallSite>());
List<Local> receivers = (List<Local>) methodToReceivers.get(m);
if( receivers == null )
methodToReceivers.put(m, receivers = new ArrayList<Local>());
receivers.add(receiver);
}
sites.add(new VirtualCallSite(s, m, iie, subSig, kind));
}
private void processNewMethod( SootMethod m ) {
if( m.isNative() || m.isPhantom() ) {
return;
}
Body b = m.retrieveActiveBody();
getImplicitTargets( m );
findReceivers(m, b);
}
private void findReceivers(SootMethod m, Body b) {
for( Iterator sIt = b.getUnits().iterator(); sIt.hasNext(); ) {
final Stmt s = (Stmt) sIt.next();
if (s.containsInvokeExpr()) {
InvokeExpr ie = s.getInvokeExpr();
if (ie instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iie = (InstanceInvokeExpr) ie;
Local receiver = (Local) iie.getBase();
NumberedString subSig =
iie.getMethodRef().getSubSignature();
addVirtualCallSite( s, m, receiver, iie, subSig,
Edge.ieToKind(iie) );
if( subSig == sigStart ) {
addVirtualCallSite( s, m, receiver, iie, sigRun,
Kind.THREAD );
}
} else {
SootMethod tgt = ((StaticInvokeExpr) ie).getMethod();
addEdge(m, s, tgt);
if( tgt.getSignature().equals( "<java.security.AccessController: java.lang.Object doPrivileged(java.security.PrivilegedAction)>" )
|| tgt.getSignature().equals( "<java.security.AccessController: java.lang.Object doPrivileged(java.security.PrivilegedExceptionAction)>" )
|| tgt.getSignature().equals( "<java.security.AccessController: java.lang.Object doPrivileged(java.security.PrivilegedAction,java.security.AccessControlContext)>" )
|| tgt.getSignature().equals( "<java.security.AccessController: java.lang.Object doPrivileged(java.security.PrivilegedExceptionAction,java.security.AccessControlContext)>" ) ) {
Local receiver = (Local) ie.getArg(0);
addVirtualCallSite( s, m, receiver, null, sigObjRun,
Kind.PRIVILEGED );
}
}
}
}
}
ReflectionModel reflectionModel;
private void getImplicitTargets( SootMethod source ) {
final SootClass scl = source.getDeclaringClass();
if( source.isNative() || source.isPhantom() ) return;
if( source.getSubSignature().indexOf( "<init>" ) >= 0 ) {
handleInit(source, scl);
}
Body b = source.retrieveActiveBody();
for( Iterator sIt = b.getUnits().iterator(); sIt.hasNext(); ) {
final Stmt s = (Stmt) sIt.next();
if( s.containsInvokeExpr() ) {
InvokeExpr ie = s.getInvokeExpr();
if( ie.getMethod().getSignature().equals( "<java.lang.reflect.Method: java.lang.Object invoke(java.lang.Object,java.lang.Object[])>" ) ) {
reflectionModel.methodInvoke(source,s);
}
if( ie.getMethod().getSignature().equals( "<java.lang.Class: java.lang.Object newInstance()>" ) ) {
reflectionModel.classNewInstance(source,s);
}
if( ie.getMethod().getSignature().equals( "<java.lang.reflect.Constructor: java.lang.Object newInstance(java.lang.Object[])>" ) ) {
reflectionModel.contructorNewInstance(source, s);
}
if( ie.getMethodRef().getSubSignature() == sigForName ) {
reflectionModel.classForName(source,s);
}
if( ie instanceof StaticInvokeExpr ) {
SootClass cl = ie.getMethodRef().declaringClass();
for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) {
addEdge( source, s, clinit, Kind.CLINIT );
}
}
}
if( s.containsFieldRef() ) {
FieldRef fr = s.getFieldRef();
if( fr instanceof StaticFieldRef ) {
SootClass cl = fr.getFieldRef().declaringClass();
for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) {
addEdge( source, s, clinit, Kind.CLINIT );
}
}
}
if( s instanceof AssignStmt ) {
Value rhs = ((AssignStmt)s).getRightOp();
if( rhs instanceof NewExpr ) {
NewExpr r = (NewExpr) rhs;
SootClass cl = r.getBaseType().getSootClass();
for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) {
addEdge( source, s, clinit, Kind.CLINIT );
}
} else if( rhs instanceof NewArrayExpr || rhs instanceof NewMultiArrayExpr ) {
Type t = rhs.getType();
if( t instanceof ArrayType ) t = ((ArrayType)t).baseType;
if( t instanceof RefType ) {
SootClass cl = ((RefType) t).getSootClass();
for (SootMethod clinit : EntryPoints.v().clinitsOf(cl)) {
addEdge( source, s, clinit, Kind.CLINIT );
}
}
}
}
}
}
private void processNewMethodContext( MethodOrMethodContext momc ) {
SootMethod m = momc.method();
Object ctxt = momc.context();
Iterator it = cicg.edgesOutOf(m);
while( it.hasNext() ) {
Edge e = (Edge) it.next();
cm.addStaticEdge( momc, e.srcUnit(), e.tgt(), e.kind() );
}
}
private void handleInit(SootMethod source, final SootClass scl) {
addEdge( source, null, scl, sigFinalize, Kind.FINALIZE );
FastHierarchy fh = Scene.v().getOrMakeFastHierarchy();
}
private void constantForName( String cls, SootMethod src, Stmt srcUnit ) {
if( cls.length() > 0 && cls.charAt(0) == '[' ) {
if( cls.length() > 1 && cls.charAt(1) == 'L' && cls.charAt(cls.length()-1) == ';' ) {
cls = cls.substring(2,cls.length()-1);
constantForName( cls, src, srcUnit );
}
} else {
if( !Scene.v().containsClass( cls ) ) {
if( options.verbose() ) {
G.v().out.println( "Warning: Class "+cls+" is"+
" a dynamic class, and you did not specify"+
" it as such; graph will be incomplete!" );
}
} else {
SootClass sootcls = Scene.v().getSootClass( cls );
if( !sootcls.isApplicationClass() ) {
sootcls.setLibraryClass();
}
for (SootMethod clinit : EntryPoints.v().clinitsOf(sootcls)) {
addEdge( src, srcUnit, clinit, Kind.CLINIT );
}
}
}
}
private void addEdge( SootMethod src, Stmt stmt, SootMethod tgt,
Kind kind ) {
cicg.addEdge( new Edge( src, stmt, tgt, kind ) );
}
private void addEdge( SootMethod src, Stmt stmt, SootClass cls, NumberedString methodSubSig, Kind kind ) {
if( cls.declaresMethod( methodSubSig ) ) {
addEdge( src, stmt, cls.getMethod( methodSubSig ), kind );
}
}
private void addEdge( SootMethod src, Stmt stmt, SootMethod tgt ) {
InvokeExpr ie = stmt.getInvokeExpr();
addEdge( src, stmt, tgt, Edge.ieToKind(ie) );
}
protected final NumberedString sigFinalize = Scene.v().getSubSigNumberer().
findOrAdd( "void finalize()" );
protected final NumberedString sigInit = Scene.v().getSubSigNumberer().
findOrAdd( "void <init>()" );
protected final NumberedString sigStart = Scene.v().getSubSigNumberer().
findOrAdd( "void start()" );
protected final NumberedString sigRun = Scene.v().getSubSigNumberer().
findOrAdd( "void run()" );
protected final NumberedString sigObjRun = Scene.v().getSubSigNumberer().
findOrAdd( "java.lang.Object run()" );
protected final NumberedString sigForName = Scene.v().getSubSigNumberer().
findOrAdd( "java.lang.Class forName(java.lang.String)" );
protected final RefType clRunnable = RefType.v("java.lang.Runnable");
}
|
package com.iluwatar.monostate;
/**
*
* The Server class. Each Server sits behind a LoadBalancer which delegates the call to the
* servers in a simplistic Round Robin fashion.
*
*/
public class Server {
public final String host;
public final int port;
public final int id;
public Server(String host, int port, int id) {
this.host = host;
this.port = port;
this.id = id;
}
public String getHost() {
return host;
}
public int getPort() {
return port;
}
public final void serve(Request request) {
System.out.println("Server ID " + id + " associated to host : " + getHost() + " and Port " + getPort() +" Processed request with value " + request.value);
}
}
|
package controllers;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Array;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeCreator;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import play.*;
import play.db.DB;
import play.libs.WS;
import play.libs.WS.Response;
import play.mvc.*;
import play.mvc.Http.RequestBody;
import views.html.*;
public class EventManager extends Controller{
public static final String EVENT_GET_SQL_UNRESTRICTED = "select distinct Event.id as id, Event.name as name, Event.location as location, UNIX_TIMESTAMP(Event.time) as time, Event.description as description, Event.visibility as visibility, Event_has_User.rsvp as rsvp from Event inner join Event_has_Tags on Event.id = Event_has_Tags.Event_id inner join Tags on Event_has_Tags.Tags_id = Tags.id inner join Event_has_User on Event.id = Event_has_User.event_id";
public static final String EVENT_GET_SQL = "select distinct Event.id as id, Event.name as name, Event.location as location, UNIX_TIMESTAMP(Event.time) as time, Event.description as description, Event.visibility as visibility, Event_has_User.rsvp as rsvp from Event inner join Event_has_Tags on Event.id = Event_has_Tags.Event_id inner join Tags on Event_has_Tags.Tags_id = Tags.id inner join Event_has_User on Event.id = Event_has_User.event_id WHERE (Event.visibility = 1 OR (Event_has_User.user_id = ? AND Event_has_User.rsvp = 1))";
public static ArrayNode buildEventResults(Connection conn, ResultSet rs) throws SQLException {
ArrayNode arr = JsonNodeFactory.instance.arrayNode();
while(rs.next()) {
ObjectNode eventRes = createEventJson(rs);
try(PreparedStatement stmtTag = conn.prepareStatement("select Tags.tag from Tags INNER JOIN Event_has_Tags ON Tags.id = Event_has_Tags.Tags_id INNER JOIN Event ON Event.id = Event_has_Tags.Event_id WHERE Event.id = ?")) {
stmtTag.setLong(1, rs.getLong("id"));
stmtTag.execute();
ResultSet rsTag = stmtTag.getResultSet();
addCategoriesToEventJson(eventRes, rsTag);
}
arr.add(eventRes);
}
return arr;
}
public static Result create()
{
/* OAuth*/
JsonNode request = request().body().asJson();
try {
Application.checkReqValid(request);
}
catch(AuthorizationException e) {
return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage()));
}
catch(SQLException e) {
e.printStackTrace();
return ok();
}
String title, desc, location;
long timestamp;
int visibility;
ArrayNode categories;
try {
title = request.get("title").textValue();
desc = request.get("desc").textValue();
location = request.get("location").textValue();
timestamp = request.get("date_time").asLong();
visibility = request.get("visibility").intValue();
if(request.has("categories")) {
categories = (ArrayNode) request.get("categories");
}
else {
throw new Exception("categories");
}
}
catch(Exception e) {
return ok(JsonNodeFactory.instance.objectNode()
.put("error", "Parameters: title (string), desc(string), location(string), date_time(long), visibility(int), categories(array)"));
}
// convert time to date
java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(timestamp);
Connection conn = DB.getConnection();
try {
conn.setAutoCommit(false);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO CampusFeed.Event (name,location,time,description,visibility) VALUES (?,?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, title);
stmt.setString(2, location);
stmt.setTimestamp(3, sqlTimestamp);
stmt.setString(4, desc);
stmt.setInt(5, visibility);
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
// get the generated primary key
if(rs.next())
{
long event_id = rs.getLong(1);
long user_id =Application.getUserId(request);
stmt = conn.prepareStatement("INSERT INTO CampusFeed.Event_has_User (event_id,user_id,is_admin) VALUES (?,?,?)");
stmt.setLong(1, event_id);
stmt.setLong(2, user_id);
stmt.setInt(3, 1);
stmt.executeUpdate();
String[] categoriesStr = new String[categories.size()];
for(int i = 0; i < categories.size(); ++i) {
categoriesStr[i] = categories.get(i).textValue();
}
addTags(conn, event_id, categoriesStr);
conn.commit();
conn.close();
return ok(JsonNodeFactory.instance.objectNode().put("event_id", event_id));
}
else {
throw new SQLException();
}
}
catch(SQLException e) {
e.printStackTrace();
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
return ok();
}
}
public static int createFromScrapedPage(JsonNode request)
{
/* OAuth*/
String title, desc, location;
long timestamp;
int visibility;
ArrayNode categories;
try {
title = request.get("title").textValue();
desc = request.get("desc").textValue();
location = request.get("location").textValue();
timestamp = request.get("date_time").asLong();
visibility = request.get("visibility").intValue();
if(request.has("categories")) {
categories = (ArrayNode) request.get("categories");
}
else {
throw new Exception("categories");
}
}
catch(Exception e) {
return -1;
}
// convert time to date
java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(timestamp);
Connection conn = DB.getConnection();
try {
conn.setAutoCommit(false);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO CampusFeed.Event (name,location,time,description,visibility) VALUES (?,?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, title);
stmt.setString(2, location);
stmt.setTimestamp(3, sqlTimestamp);
stmt.setString(4, desc);
stmt.setInt(5, visibility);
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
// get the generated primary key
if(rs.next())
{
long event_id = rs.getLong(1);
long user_id =Application.getUserId(request);
stmt = conn.prepareStatement("INSERT INTO CampusFeed.Event_has_User (event_id,user_id,is_admin) VALUES (?,?,?)");
stmt.setLong(1, event_id);
stmt.setLong(2, ScraperHandler.SCRAPER_ID);
stmt.setInt(3, 1);
stmt.executeUpdate();
String[] categoriesStr = new String[categories.size()];
for(int i = 0; i < categories.size(); ++i) {
categoriesStr[i] = categories.get(i).textValue();
}
addTags(conn, event_id, categoriesStr);
conn.commit();
conn.close();
return 1;
}
else {
throw new SQLException();
}
}
catch(SQLException e) {
e.printStackTrace();
try {
conn.rollback();
return 1;
} catch (SQLException e1) {
e1.printStackTrace();
return -1;
}
}
}
public static Result rsvp_to_event()
{
/* OAuth*/
JsonNode request = request().body().asJson();
if(request==null)
{
return ok();
}
try {
Application.checkReqValid(request);
}
catch(AuthorizationException e) {
return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage()));
}
catch(SQLException e) {
e.printStackTrace();
return ok();
}
// add user to rsvp
// get the user id
long user_id =Application.getUserId(request);
// main thing, only need event_id
int event_id = Integer.parseInt(request.get("event_id").textValue());
// check if user has already rsvp'd
boolean should_add = false;
try(Connection conn = DB.getConnection()) {
PreparedStatement stmt = conn.prepareStatement("SELECT rsvp FROM CampusFeed.Event_has_User WHERE user_id=? AND event_id=?");
stmt.setLong(1, user_id);
stmt.setInt(2, event_id);
stmt.execute();
ResultSet rs = stmt.getResultSet();
int rsvp=-1;
if(rs.next()) {
rsvp= rs.getInt("rsvp");
}
else
{
should_add=true;
}
if(rsvp==1){
return ok("duplicate");
}else
if(rsvp!=1 && should_add!=true)
{
// then only need to update, incase if undo rsvp or something.
try(Connection conn2 = DB.getConnection()) {
PreparedStatement stmt2 = conn2.prepareStatement("UPDATE `CampusFeed`.`Event_has_User` SET `rsvp` = '1' WHERE `event_has_user`.`event_id` = ? AND `event_has_user`.`user_id` = ?");
stmt2.setLong(2, user_id);
stmt2.setInt(1, event_id);
stmt2.executeUpdate();
}
catch(SQLException e) {
e.printStackTrace();
return ok();
}
}
}
catch(SQLException e) {
e.printStackTrace();
return ok();
}
if(should_add){
// main thing, add to rsvp
try(Connection conn = DB.getConnection()) {
PreparedStatement stmt = conn.prepareStatement("INSERT INTO CampusFeed.Event_has_User (user_id,event_id,rsvp,is_admin) VALUES (?,?,1,0)");
stmt.setLong(1, user_id);
stmt.setInt(2, event_id);
stmt.executeUpdate();
}
catch(SQLException e) {
e.printStackTrace();
return ok();
}
}
return ok("success");
}
/**
* Helper function to create event json from results
* @param rs result set from query on a valid event row
* @return the json event
* @throws SQLException
*/
private static ObjectNode createEventJson(ResultSet rs) throws SQLException {
ObjectNode searchResult = JsonNodeFactory.instance.objectNode();
searchResult.put("id", rs.getString("id"));
searchResult.put("name", rs.getString("name"));
searchResult.put("location", rs.getString("location"));
searchResult.put("time", rs.getInt("time"));
searchResult.put("description", rs.getString("description"));
//searchResult.put("category", rs.getString("category"));
searchResult.put("visibility", rs.getInt("visibility"));
searchResult.put("rsvp", rs.getInt("rsvp"));
return searchResult;
}
/**
* Helper function to add categories to event json
* @param event
* @param rs
* @throws SQLException
*/
private static void addCategoriesToEventJson(ObjectNode event, ResultSet rs) throws SQLException {
ArrayNode categories = JsonNodeFactory.instance.arrayNode();
while(rs.next()) {
categories.add(rs.getString("tag"));
}
event.put("categories", categories);
}
public static Result advSearch() {
JsonNode request = request().body().asJson();
try {
Application.checkReqValid(request);
}
catch(AuthorizationException e) {
return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage()));
}
catch(SQLException e) {
e.printStackTrace();
return ok();
}
// get the user id
long user_id =Application.getUserId(request);
//check params
if(!request.has("name") && !(request.has("start_date") && request.has("end_date")) &&
!request.has("desc") && !request.has("tags")){
return ok(JsonNodeFactory.instance.objectNode().put("error", "usage: name (text) or (start_date (date) and end_date (date)) or desc (text) or tags (array)"));
}
try(Connection conn = DB.getConnection()) {
PreparedStatement stmt = null;
List<Object> params = new ArrayList<Object>();
params.add(user_id);
String sql = EVENT_GET_SQL;
if(request.has("name")) {
sql += "name like ?";
params.add("%" + request.get("name").textValue() + "%");
}
if(request.has("start_date") && request.has("end_date")) {
if(params.size() != 0) {
sql += " AND ";
}
sql += "UNIX_TIMESTAMP(time) BETWEEN ? AND ?";
params.add(request.get("start_date").asLong());
params.add(request.get("end_date").asLong());
}
if(request.has("desc")) {
if(params.size() != 0) {
sql += " AND ";
}
sql += "description like ?";
params.add("%" + request.get("desc").textValue() + "%");
}
if(request.has("tags")) {
ArrayNode tags = (ArrayNode) request.get("tags");
if(params.size() != 0) {
sql += " AND (";
}
for(int i = 0; i < tags.size(); ++i) {
sql += "Tags.tag = ?";
params.add(tags.get(i).textValue());
if(i < tags.size() - 1) {
sql += " OR ";
}
}
sql += ")";
}
stmt = conn.prepareStatement(sql);
for(int i = 0; i < params.size(); ++i) {
stmt.setObject(i + 1, params.get(i));
}
stmt.execute();
ResultSet rs = stmt.executeQuery();
return ok(buildEventResults(conn, rs));
}
catch(Exception e) {
e.printStackTrace();
return ok();
}
}
public static Result listEvent() {
JsonNode request = request().body().asJson();
try {
Application.checkReqValid(request);
}
catch(AuthorizationException e) {
return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage()));
}
catch(SQLException e) {
e.printStackTrace();
return ok();
}
// get the user id
long user_id =Application.getUserId(request);
//check params
int page;
try {
page = request.get("page").intValue();
}
catch(Exception e) {
return ok(JsonNodeFactory.instance.objectNode().put("error", "usage: page (int)"));
}
try(Connection conn = DB.getConnection()) {
try(PreparedStatement stmt = conn.prepareStatement(EVENT_GET_SQL + " LIMIT 25 OFFSET ?")) {
stmt.setLong(1, user_id);
stmt.setInt(2, page * 25);
ResultSet rs = stmt.executeQuery();
return ok(buildEventResults(conn, rs));
}
}
catch(SQLException e) {
e.printStackTrace();
return ok();
}
}
private static void addTags(Connection conn, long eventId, String[] tags) throws SQLException{
PreparedStatement lookupTag = conn.prepareStatement("SELECT id FROM Tags WHERE tag = ?");
PreparedStatement addTag = conn.prepareStatement("INSERT INTO Tags (tag) VALUES (?)", Statement.RETURN_GENERATED_KEYS);
PreparedStatement linkTag = conn.prepareStatement("INSERT INTO Event_has_Tags (Event_id, Tags_id) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS);
for(String tag : tags) {
lookupTag.setString(1, tag);
lookupTag.execute();
ResultSet rs;
long tag_id = -1;
if((rs = lookupTag.getResultSet()).next()) {
tag_id = rs.getLong(1);
}
else {
addTag.setString(1, tag);
addTag.execute();
if((rs = addTag.getGeneratedKeys()).next()) {
tag_id = rs.getLong(1);
}
}
linkTag.setLong(1, eventId);
linkTag.setLong(2, tag_id);
linkTag.execute();
}
lookupTag.close();
addTag.close();
linkTag.close();
}
public static Result updateEvent()
{
/* OAuth*/
JsonNode request = request().body().asJson();
try {
Application.checkReqValid(request);
}
catch(AuthorizationException e) {
return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage()));
}
catch(SQLException e) {
e.printStackTrace();
return ok();
}
String title, desc, location;
long timestamp, id;
int visibility;
ArrayNode categories;
try {
title = request.get("title").textValue();
desc = request.get("desc").textValue();
location = request.get("location").textValue();
timestamp = request.get("date_time").asLong();
visibility = request.get("visibility").intValue();
id = request.get("id").longValue();
categories = (ArrayNode) request.get("categories");
if(categories == null) {
throw new Exception("categories");
}
}
catch(Exception e) {
e.printStackTrace();
return ok(JsonNodeFactory.instance.objectNode()
.put("error", "Parameters: title (string), desc(string), location(string), date_time(long), visibility(int), categories(array)"));
}
Connection conn = DB.getConnection();
try {
conn.setAutoCommit(false);
PreparedStatement stmt2 = conn.prepareStatement("UPDATE `CampusFeed`.`Event` SET name=?, location=?,description=?,time=?,visibility=? WHERE `Event`.`id` = ?");
stmt2.setString(1, title);
stmt2.setString(2, location);
stmt2.setString(3, desc);
stmt2.setTimestamp(4, new Timestamp(timestamp));
stmt2.setInt(5, visibility);
stmt2.setLong(6, id);
stmt2.executeUpdate();
stmt2 = conn.prepareStatement("DELETE Event_has_Tags FROM Event_has_Tags INNER JOIN Event ON Event_has_Tags.Event_id = Event.id WHERE (Event.id = ?)");
stmt2.setLong(1, id);
stmt2.executeUpdate();
String[] categoriesStr = new String[categories.size()];
for(int i = 0; i < categories.size(); ++i) {
categoriesStr[i] = categories.get(i).textValue();
}
addTags(conn, id, categoriesStr);
conn.commit();
conn.close();
// send messages to all users
ArrayList<String> user_ids = EventManager.get_user_ids();
for(int a=0;a<user_ids.size();a++)
{
GCMHandler.sendMessage(user_ids.get(a), "Update for: "+title+"\n"+"Description:"+desc+"\nLocation:"+location+"\n");
}
// end messaging.
return ok(JsonNodeFactory.instance.objectNode().put("ok", "ok"));
}
catch(SQLException e) {
e.printStackTrace();
return ok();
}
}
public static ArrayList<String> get_user_ids()
{
try(Connection conn = DB.getConnection()) {
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM `User` WHERE gcm_id IS NOT NULL");
ResultSet s =stmt.executeQuery();
ArrayList<String> user_ids = new ArrayList<String>();
while(s.next())
{
user_ids.add(s.getString("fb_user_id"));
}
s.close();
return user_ids;
}catch(Exception e)
{
return null;
}
}
public static Result allTags()
{
try(Connection conn = DB.getConnection()) {
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM Tags");
ResultSet s =stmt.executeQuery();
ArrayList<String> tags = new ArrayList<String>();
while(s.next())
{
tags.add(s.getString("tag"));
}
s.close();
JsonNode tags_json= JsonNodeFactory.instance.objectNode().put("tags", tags.toString());
return ok(tags_json);
}catch(Exception e)
{
return ok();
}
}
public static Result top5() {
JsonNode request = request().body().asJson();
try {
Application.checkReqValid(request);
}
catch(AuthorizationException e) {
return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage()));
}
catch(SQLException e) {
e.printStackTrace();
return ok();
}
// get the user id
long user_id =Application.getUserId(request);
String category;
try {
category = request.get("category").textValue();
}
catch(Exception e) {
e.printStackTrace();
return ok(JsonNodeFactory.instance.objectNode()
.put("error", "Parameters: category (text)"));
}
try(Connection conn = DB.getConnection()) {
PreparedStatement stmt = conn.prepareStatement(EVENT_GET_SQL + " AND Tags.tag = ? ORDER BY Event.view_count DESC LIMIT 5");
stmt.setLong(1, user_id);
stmt.setString(2, category);
ResultSet rs = stmt.executeQuery();
return ok(buildEventResults(conn, rs));
}
catch(SQLException e) {
return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage()));
}
}
public static Result getEvent() {
JsonNode request = request().body().asJson();
try {
Application.checkReqValid(request);
}
catch(AuthorizationException e) {
return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage()));
}
catch(SQLException e) {
e.printStackTrace();
return ok();
}
// get the user id
long user_id =Application.getUserId(request);
long event_id;
try {
event_id = request.get("event_id").longValue();
}
catch(Exception e) {
return ok(JsonNodeFactory.instance.objectNode().put("error", "usage: auth, event_id (long)"));
}
try(Connection conn = DB.getConnection()) {
PreparedStatement stmt = conn.prepareStatement(EVENT_GET_SQL_UNRESTRICTED + " WHERE Event.id = ?");
stmt.setLong(1, event_id);
ResultSet rs = stmt.executeQuery();
return ok(buildEventResults(conn, rs).get(0));
}
catch(Exception e) {
return ok(JsonNodeFactory.instance.objectNode().put("error", e.getMessage()));
}
}
}
|
package org.opencms.ade.containerpage.client;
import org.opencms.gwt.client.util.CmsMessages;
/**
* Convenience class to access the localized messages of this OpenCms package.<p>
*
* @since 8.0.0
*/
public final class Messages {
/** Message constant for key in the resource bundle. */
public static final String ERR_LOCK_RESOURCE_CHANGED_BY_1 = "ERR_LOCK_RESOURCE_CHANGED_BY_1";
/** Message constant for key in the resource bundle. */
public static final String ERR_LOCK_RESOURCE_LOCKED_BY_1 = "ERR_LOCK_RESOURCE_LOCKED_BY_1";
/** Message constant for key in the resource bundle. */
public static final String ERR_LOCK_TITLE_RESOURCE_CHANGED_0 = "ERR_LOCK_TITLE_RESOURCE_CHANGED_0";
/** Message constant for key in the resource bundle. */
public static final String ERR_LOCK_TITLE_RESOURCE_LOCKED_0 = "ERR_LOCK_TITLE_RESOURCE_LOCKED_0";
/** Message constant for key in the resource bundle. */
public static final String ERR_READING_CONTAINER_PAGE_DATA_0 = "ERR_READING_CONTAINER_PAGE_DATA_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_ASK_DELETE_REMOVED_ELEMENT_0 = "GUI_ASK_DELETE_REMOVED_ELEMENT_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_ASK_DELETE_REMOVED_ELEMENT_TITLE_0 = "GUI_ASK_DELETE_REMOVED_ELEMENT_TITLE_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_BUTTON_BREAK_UP_TEXT_0 = "GUI_BUTTON_BREAK_UP_TEXT_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_BUTTON_CANCEL_TEXT_0 = "GUI_BUTTON_CANCEL_TEXT_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_BUTTON_CHANGE_ORDER_TEXT_0 = "GUI_BUTTON_CHANGE_ORDER_TEXT_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_BUTTON_DISCARD_TEXT_0 = "GUI_BUTTON_DISCARD_TEXT_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_BUTTON_EDITFAVORITES_TEXT_0 = "GUI_BUTTON_EDITFAVORITES_TEXT_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_BUTTON_ELEMENT_EDIT_0 = "GUI_BUTTON_ELEMENT_EDIT_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_BUTTON_REMOVE_TEXT_0 = "GUI_BUTTON_REMOVE_TEXT_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_BUTTON_RESET_DISABLED_0 = "GUI_BUTTON_RESET_DISABLED_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_BUTTON_RESET_TEXT_0 = "GUI_BUTTON_RESET_TEXT_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_BUTTON_RETURN_TEXT_0 = "GUI_BUTTON_RETURN_TEXT_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_BUTTON_SAVE_DISABLED_0 = "GUI_BUTTON_SAVE_DISABLED_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_BUTTON_SAVE_TEXT_0 = "GUI_BUTTON_SAVE_TEXT_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_CLIPBOARD_ITEM_CAN_NOT_BE_EDITED_0 = "GUI_CLIPBOARD_ITEM_CAN_NOT_BE_EDITED_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_DIALOG_LEAVE_NOT_SAVED_0 = "GUI_DIALOG_LEAVE_NOT_SAVED_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_DIALOG_NOT_SAVED_TITLE_0 = "GUI_DIALOG_NOT_SAVED_TITLE_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_DIALOG_PAGE_RESET_0 = "GUI_DIALOG_PAGE_RESET_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_DIALOG_PUBLISH_NOT_SAVED_0 = "GUI_DIALOG_PUBLISH_NOT_SAVED_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_DIALOG_RELOAD_TEXT_0 = "GUI_DIALOG_RELOAD_TEXT_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_DIALOG_RELOAD_TITLE_0 = "GUI_DIALOG_RELOAD_TITLE_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_DIALOG_RESET_TITLE_0 = "GUI_DIALOG_RESET_TITLE_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_DIALOG_SAVE_BEFORE_LEAVING_0 = "GUI_DIALOG_SAVE_BEFORE_LEAVING_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_DIALOG_SAVE_QUESTION_0 = "GUI_DIALOG_SAVE_QUESTION_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_GROUPCONTAINER_CAPTION_0 = "GUI_GROUPCONTAINER_CAPTION_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_GROUPCONTAINER_LABEL_DESCRIPTION_0 = "GUI_GROUPCONTAINER_LABEL_DESCRIPTION_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_GROUPCONTAINER_LABEL_TITLE_0 = "GUI_GROUPCONTAINER_LABEL_TITLE_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_GROUPCONTAINER_LOADING_DATA_0 = "GUI_GROUPCONTAINER_LOADING_DATA_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_INHERITANCECONTAINER_CAPTION_0 = "GUI_INHERITANCECONTAINER_CAPTION_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_INHERITANCECONTAINER_CONFIG_NAME_0 = "GUI_INHERITANCECONTAINER_CONFIG_NAME_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_INHERITANCECONTAINER_HIDE_ELEMENTS_0 = "GUI_INHERITANCECONTAINER_HIDE_ELEMENTS_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_INHERITANCECONTAINER_NO_HIDDEN_ELEMENTS_0 = "GUI_INHERITANCECONTAINER_NO_HIDDEN_ELEMENTS_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_INHERITANCECONTAINER_SHOW_HIDDEN_0 = "GUI_INHERITANCECONTAINER_SHOW_HIDDEN_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_KEEP_ELEMENT_0 = "GUI_KEEP_ELEMENT_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_LOCK_FAIL_0 = "GUI_LOCK_FAIL_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_NO_SETTINGS_0 = "GUI_NO_SETTINGS_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_NO_SETTINGS_TITLE_0 = "GUI_NO_SETTINGS_TITLE_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_NOTIFICATION_ADD_TO_FAVORITES_0 = "GUI_NOTIFICATION_ADD_TO_FAVORITES_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_NOTIFICATION_FAVORITES_SAVED_0 = "GUI_NOTIFICATION_FAVORITES_SAVED_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_NOTIFICATION_GROUP_CONTAINER_SAVED_0 = "GUI_NOTIFICATION_GROUP_CONTAINER_SAVED_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_NOTIFICATION_INHERITANCE_CONTAINER_SAVED_0 = "GUI_NOTIFICATION_INHERITANCE_CONTAINER_SAVED_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_NOTIFICATION_PAGE_SAVED_0 = "GUI_NOTIFICATION_PAGE_SAVED_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_NOTIFICATION_PAGE_UNLOCKED_0 = "GUI_NOTIFICATION_PAGE_UNLOCKED_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_NOTIFICATION_UNABLE_TO_LOCK_0 = "GUI_NOTIFICATION_UNABLE_TO_LOCK_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_PROPERTY_DIALOG_TEXT_0 = "GUI_PROPERTY_DIALOG_TEXT_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_PROPERTY_DIALOG_TITLE_0 = "GUI_PROPERTY_DIALOG_TITLE_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_SETTINGS_LEGEND_0 = "GUI_SETTINGS_LEGEND_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_TAB_FAVORITES_DESCRIPTION_0 = "GUI_TAB_FAVORITES_DESCRIPTION_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_TAB_FAVORITES_NO_ELEMENTS_0 = "GUI_TAB_FAVORITES_NO_ELEMENTS_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_TAB_FAVORITES_TITLE_0 = "GUI_TAB_FAVORITES_TITLE_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_TAB_RECENT_DESCRIPTION_0 = "GUI_TAB_RECENT_DESCRIPTION_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_TAB_RECENT_TITLE_0 = "GUI_TAB_RECENT_TITLE_0";
/** Message constant for key in the resource bundle. */
public static final String GUI_TITLE_INHERITED_FROM_1 = "GUI_TITLE_INHERITED_FROM_1";
/** Name of the used resource bundle. */
private static final String BUNDLE_NAME = "org.opencms.ade.containerpage.clientmessages";
/** Static instance member. */
private static CmsMessages INSTANCE;
/**
* Hides the public constructor for this utility class.<p>
*/
private Messages() {
// hide the constructor
}
/**
* Returns an instance of this localized message accessor.<p>
*
* @return an instance of this localized message accessor
*/
public static CmsMessages get() {
if (INSTANCE == null) {
INSTANCE = new CmsMessages(BUNDLE_NAME);
}
return INSTANCE;
}
/**
* Returns the bundle name for this OpenCms package.<p>
*
* @return the bundle name for this OpenCms package
*/
public String getBundleName() {
return BUNDLE_NAME;
}
}
|
package net.domesdaybook.searcher.sequence;
import net.domesdaybook.reader.ByteReader;
import net.domesdaybook.matcher.sequence.SequenceMatcher;
import net.domesdaybook.matcher.singlebyte.SingleByteMatcher;
import net.domesdaybook.searcher.Searcher;
/**
* BoyerMooreHorspoolSearcher searches for a sequence using the
* Boyer-Moore-Horspool algorithm.
* <p>
* This type of search algorithm does not need to examine every byte in
* the bytes being searched. It is sub-linear, in general needing to
* examine less bytes than actually occur in the bytes being searched.
* <p>
* It proceeds by searching for the search pattern backwards, from the last byte
* in the pattern to the first. It pre-computes a table of minimum safe shifts
* for the search pattern. Given a byte in the bytes being searched,
* the shift table tells us how many bytes we can safely shift ahead without
* missing a possible match. If the shift is zero, then we must validate that
* the pattern actually occurs at this position (the last byte of pattern matches
* the current position in the bytes being searched).
* <p>
* A simple example is looking for the bytes 'XYZ' in the sequence 'ABCDEFGXYZ'.
* The first attempt is to match 'Z', and we find the byte 'C'. Since 'C' does
* not appear anywhere in 'XYZ', we can safely shift 3 bytes ahead and not risk
* missing a possible match. In general, the safe shift is either the length of
* the pattern, if that byte does not appear in the pattern, or the shortest
* distance from the end of the pattern where that byte appears.
* <p>
* One initially counter-intuitive consequence of this type of search is that
* the longer the pattern you are searching for, the better the performance
* usually is, as the possible shifts will be correspondingly bigger.
*
* @author Matt Palmer
*/
public final class BoyerMooreHorspoolSearcher extends SequenceMatcherSearcher {
// volatile arrays are usually a bad idea, as volatile applies to the array
// reference, not to the contents of the array. However, we will never change
// the array contents once it is initialised, so this is safe.
@SuppressWarnings("VolatileArrayField")
private volatile int[] shiftForwardFunction;
@SuppressWarnings("VolatileArrayField")
private volatile int[] shiftBackwardFunction;
private volatile SingleByteMatcher firstSingleMatcher;
private volatile SingleByteMatcher lastSingleMatcher;
/**
* Constructs a BoyerMooreHorspool searcher given a {@link SequenceMatcher}
* to search for.
*
* @param matcher A {@link SequenceMatcher} to search for.
*/
public BoyerMooreHorspoolSearcher(final SequenceMatcher matcher) {
super(matcher);
// Prepopulate the forward and backward shifts, making the class
// effectively immutable once constructed.
// This will increase construction time, and probably build
// shifts which aren't used for one direction, but it makes the
// class thread-safe.
// Another way would be to synchronise access to the shift and
// and last and first matcher objects, which would mean we would
// use less memory and construct faster, at the expense of
// synchronising access.
//getForwardShifts();
//getBackwardShifts();
// Or instead, make fields volatile so we can lazy initialize them.
// we will use a single-check lazy initialization strategy. This can
// result in the field being initialised more than once (if we are
// unlucky), but this doesn't really matter. Most of the time we
// won't, and most field accesses will be slightly faster as a result.
}
/**
* {@inheritDoc}
*/
@Override
public final long searchForwards(final ByteReader reader, final long fromPosition, final long toPosition ) {
final int[] safeShifts = getForwardShifts();
final SingleByteMatcher lastMatcher = getLastSingleMatcher();
final int lastBytePositionInSequence = matcher.length() - 1;
long matchPosition = fromPosition;
boolean matchFound = false;
while (matchPosition <= toPosition) {
// Scan forwards to find a match to the last byte in the sequence:
byte lastByte = reader.readByte(matchPosition);
while (!lastMatcher.matches(lastByte)) {
matchPosition += safeShifts[(int) lastByte & 0xFF];
if ( matchPosition <= toPosition ) {
lastByte = reader.readByte(matchPosition);
} else {
break;
}
}
// If we're still inside the search window, we have a matching last byte.
// Verify whether the rest of the sequence matches at this position:
if (matchPosition <= toPosition ) {
matchFound = matcher.matches(reader, matchPosition - lastBytePositionInSequence);
if (matchFound) {
break;
}
}
// No match was found.
// Shift the match position according to the value of the last byte
// observed at the end of the sequence so far in the file.
// "Sunday" variant of Boyer-Moore-Horspool sometimes gets better average performance
// by shifting based on the next byte of the file, rather than the last byte checked.
// This isn't always faster, as it has less "locality of reference":
//if (matchPosition < toPosition) {
// matchPosition +=1;
// lastByte = reader.readByte(matchPosition);
matchPosition += safeShifts[(int) lastByte & 0xFF];
}
return matchFound ? matchPosition : Searcher.NOT_FOUND;
}
/**
* {@inheritDoc}
*/
@Override
public final long searchBackwards(final ByteReader reader, final long fromPosition, final long toPosition ) {
final int[] safeShifts = getBackwardShifts();
final SingleByteMatcher firstMatcher = getFirstSingleMatcher();
long matchPosition = fromPosition;
boolean matchFound = false;
while (matchPosition >= toPosition) {
// Scan for a match to the first byte in the sequence, scanning backwards from the starting position:
byte firstByte = reader.readByte(matchPosition);
while (!firstMatcher.matches(firstByte)) {
matchPosition += safeShifts[(int) firstByte & 0xFF]; // shifts always add - if the search is backwards, the shift values are already negative.
if ( matchPosition >= toPosition ) {
firstByte = reader.readByte(matchPosition);
} else {
break;
}
}
// As long as we're still inside the search window
// (greater than the last position we can scan backwards to)
// we have a matching first byte - verify that the rest of the sequence matches too.
if (matchPosition >= toPosition) {
matchFound = matcher.matches(reader, matchPosition);
if (matchFound) {
break;
}
}
// No match was found.
// Shift the match position according to the value of the last byte
// observed at the end of the sequence so far in the file.
// Note: always add shifts - if the search is backwards, the shifts are precomputed with negative values.
// "Sunday" variant of Boyer-Moore-Horspool sometimes gets better average performance
// by shifting based on the next byte of the file, rather than the last byte checked.
// This isn't always faster, as it has less "locality of reference":
//if ( matchPosition > toPosition ) {
// matchPosition -=1;
// firstByte = reader.readByte(matchPosition);
matchPosition += safeShifts[(int) firstByte & 0xFF];
}
return matchFound ? matchPosition : Searcher.NOT_FOUND;
}
/**
*
* Uses Single-Check lazy initialisation. This can result in the field
* being initialised more than once, but this doesn't really matter.
*
* @return A 256-element array of integers, giving the safe shift
* for a given byte when searching forwards.
*/
private int[] getForwardShifts() {
int[] result = shiftForwardFunction;
if (result == null) {
shiftForwardFunction = result = createForwardShifts();
}
return result;
}
/**
*
* Uses Single-Check lazy initialisation. This can result in the field
* being initialised more than once, but this doesn't really matter.
*
* @return A 256-element array of integers, giving the safe shift
* for a given byte when searching backwards.
*/
private int[] getBackwardShifts() {
int[] result = shiftBackwardFunction;
if (result == null) {
shiftBackwardFunction = result = createBackwardShifts();
}
return result;
}
/**
* Uses Single-Check lazy initialisation. This can result in the field
* being initialised more than once, but this doesn't really matter.
*
* @return The last single byte matcher in the matcher sequence.
*/
private SingleByteMatcher getLastSingleMatcher() {
SingleByteMatcher result = lastSingleMatcher;
if (result == null) {
lastSingleMatcher = result = matcher.getByteMatcherForPosition(matcher.length()-1);
}
return result;
}
/**
* Uses Single-Check lazy initialisation. This can result in the field
* being initialised more than once, but this doesn't really matter.
*
* @return The first single byte matcher in the matcher sequence.
*/
private SingleByteMatcher getFirstSingleMatcher() {
SingleByteMatcher result = firstSingleMatcher;
if (result == null) {
firstSingleMatcher = result = matcher.getByteMatcherForPosition(0);
}
return result;
}
/**
* Calculates the safe shifts to use if searching backwards.
* A safe shift is either the length of the sequence, if the
* byte does not appear in the {@link SequenceMatcher}, or
* the shortest distance it appears from the beginning of the matcher.
*/
private int[] createBackwardShifts() {
// First set the default shift to the length of the sequence
// (negative if search direction is reversed)
final int[] shifts = new int[256];
final int numBytes = matcher.length();
final int defaultShift = numBytes * -1;
for (int charValueIndex=255; charValueIndex>=0; charValueIndex
shifts[charValueIndex] = defaultShift;
}
// Now set specific byte shifts for the bytes actually in
// the sequence itself. The shift is the distance of each character
// from the end of the sequence, as a zero-indexed offset.
// Each position can match more than one byte (e.g. if a byte class appears).
for ( int sequenceByteIndex = numBytes-1; sequenceByteIndex > 0; sequenceByteIndex
final SingleByteMatcher aMatcher = matcher.getByteMatcherForPosition(sequenceByteIndex);
final byte[] matchingBytes = aMatcher.getMatchingBytes();
for (int byteIndex = 0; byteIndex < matchingBytes.length; byteIndex++) {
final int byteSequenceValue = (matchingBytes[byteIndex] & 0xFF);
shifts[byteSequenceValue] = -sequenceByteIndex; // 1 - numBytes + sequenceByteIndex;
}
}
return shifts;
}
/**
* Calculates the safe shifts to use if searching forwards.
* A safe shift is either the length of the sequence, if the
* byte does not appear in the {@link SequenceMatcher}, or
* the shortest distance it appears from the end of the matcher.
*/
private int[] createForwardShifts() {
// First set the default shift to the length of the sequence
final int[] shifts = new int[256];
final int numBytes = matcher.length();
final int defaultShift = numBytes;
for (int charValueIndex=255; charValueIndex>=0; charValueIndex
shifts[charValueIndex] = defaultShift;
}
// Now set specific byte shifts for the bytes actually in
// the sequence itself. The shift is the distance of each character
// from the end of the sequence, as a zero-indexed offset.
// Each position can match more than one byte (e.g. if a byte class appears).
for ( int sequenceByteIndex = 0; sequenceByteIndex < numBytes -1; sequenceByteIndex++ ) {
final SingleByteMatcher aMatcher = matcher.getByteMatcherForPosition(sequenceByteIndex);
final byte[] matchingBytes = aMatcher.getMatchingBytes();
for (int byteIndex = 0; byteIndex < matchingBytes.length; byteIndex++) {
final int byteSequenceValue = ( matchingBytes[byteIndex] & 0xFF );
shifts[byteSequenceValue]=numBytes-sequenceByteIndex-1;
}
}
return shifts;
}
}
|
package org.opencms.ade.sitemap.client;
import org.opencms.ade.sitemap.client.control.CmsSitemapChangeEvent;
import org.opencms.ade.sitemap.client.control.CmsSitemapController;
import org.opencms.ade.sitemap.client.control.CmsSitemapDNDController;
import org.opencms.ade.sitemap.client.control.CmsSitemapLoadEvent;
import org.opencms.ade.sitemap.client.control.I_CmsSitemapChangeHandler;
import org.opencms.ade.sitemap.client.control.I_CmsSitemapLoadHandler;
import org.opencms.ade.sitemap.client.hoverbar.CmsSitemapHoverbar;
import org.opencms.ade.sitemap.client.toolbar.CmsSitemapToolbar;
import org.opencms.ade.sitemap.client.ui.CmsPage;
import org.opencms.ade.sitemap.client.ui.CmsSitemapHeader;
import org.opencms.ade.sitemap.client.ui.CmsStatusIconUpdateHandler;
import org.opencms.ade.sitemap.client.ui.css.I_CmsImageBundle;
import org.opencms.ade.sitemap.client.ui.css.I_CmsSitemapLayoutBundle;
import org.opencms.ade.sitemap.shared.CmsClientSitemapEntry;
import org.opencms.ade.sitemap.shared.CmsDetailPageTable;
import org.opencms.ade.sitemap.shared.CmsSitemapChange;
import org.opencms.ade.sitemap.shared.CmsSitemapData;
import org.opencms.gwt.client.A_CmsEntryPoint;
import org.opencms.gwt.client.CmsPingTimer;
import org.opencms.gwt.client.dnd.CmsDNDHandler;
import org.opencms.gwt.client.ui.CmsListItemWidget.Background;
import org.opencms.gwt.client.ui.CmsNotification;
import org.opencms.gwt.client.ui.tree.CmsLazyTree;
import org.opencms.gwt.client.ui.tree.CmsLazyTreeItem;
import org.opencms.gwt.client.ui.tree.CmsTreeItem;
import org.opencms.gwt.client.ui.tree.I_CmsLazyOpenHandler;
import org.opencms.gwt.client.util.CmsDomUtil;
import org.opencms.gwt.client.util.CmsStyleVariable;
import org.opencms.gwt.shared.CmsIconUtil;
import org.opencms.util.CmsPair;
import org.opencms.util.CmsStringUtil;
import org.opencms.util.CmsUUID;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
/**
* Sitemap editor.<p>
*
* @since 8.0.0
*/
public final class CmsSitemapView extends A_CmsEntryPoint implements I_CmsSitemapChangeHandler, I_CmsSitemapLoadHandler {
/** The sitemap editor modes. */
public enum EditorMode {
/** The navigation mode. */
navigation,
/** The VFS mode. */
vfs
}
/**
* The sitemap tree open handler.<p>
*/
protected class TreeOpenHandler implements I_CmsLazyOpenHandler<CmsSitemapTreeItem> {
/** Flag indicating the tree is initializing. */
private boolean m_initializing;
/**
* @see org.opencms.gwt.client.ui.tree.I_CmsLazyOpenHandler#load(org.opencms.gwt.client.ui.tree.CmsLazyTreeItem)
*/
public void load(final CmsSitemapTreeItem target) {
// not used
}
/**
* @see org.opencms.gwt.client.ui.tree.I_CmsLazyOpenHandler#onOpen(com.google.gwt.event.logical.shared.OpenEvent)
*/
public void onOpen(OpenEvent<CmsSitemapTreeItem> event) {
CmsSitemapTreeItem target = event.getTarget();
if ((target.getLoadState() == CmsLazyTreeItem.LoadState.UNLOADED)) {
target.onStartLoading();
target.setOpen(false);
getController().getChildren(target.getEntryId(), true, null);
} else if (!m_initializing
&& ((target.getChildren().getWidgetCount() > 0) && (((CmsSitemapTreeItem)target.getChild(0)).getLoadState() == CmsLazyTreeItem.LoadState.UNLOADED))) {
// load grand children in advance
getController().getChildren(target.getEntryId(), false, null);
}
}
/**
* Sets the initializing flag.<p>
*
* @param initializing the initializing flag
*/
protected void setInitializing(boolean initializing) {
m_initializing = initializing;
}
}
/** The singleton instance. */
private static CmsSitemapView m_instance;
/** Text metrics key. */
private static final String TM_SITEMAP = "Sitemap";
/** The displayed sitemap tree. */
protected CmsLazyTree<CmsSitemapTreeItem> m_tree;
/** The controller. */
private CmsSitemapController m_controller;
/** The current sitemap editor mode. */
private EditorMode m_editorMode;
/** Style variable which keeps track of whether we are in VFS mode or navigation mode. */
private CmsStyleVariable m_inNavigationStyle;
/** The sitemap toolbar. */
private CmsSitemapToolbar m_toolbar;
/** The registered tree items. */
private Map<CmsUUID, CmsSitemapTreeItem> m_treeItems;
/** The tree open handler. */
private TreeOpenHandler m_openHandler;
/**
* Returns the instance.<p>
*
* @return the instance
*/
public static CmsSitemapView getInstance() {
return m_instance;
}
/**
* Creates a new tree item from the given sitemap entry.<p>
*
* @param entry the sitemap entry
*
* @return the new created (still orphan) tree item
*/
public CmsSitemapTreeItem create(CmsClientSitemapEntry entry) {
CmsSitemapTreeItem treeItem = new CmsSitemapTreeItem(entry);
CmsSitemapHoverbar.installOn(m_controller, treeItem);
// highlight the open path
if (isLastPage(entry)) {
treeItem.setBackgroundColor(Background.YELLOW);
}
m_treeItems.put(entry.getId(), treeItem);
return treeItem;
}
/**
* Creates a sitemap tree item from a client sitemap entry.<p>
*
* @param entry the entry from which the sitemap tree item should be created
*
* @return the new sitemap tree item
*/
public CmsSitemapTreeItem createSitemapItem(CmsClientSitemapEntry entry) {
CmsSitemapTreeItem result = create(entry);
result.clearChildren();
for (CmsClientSitemapEntry child : entry.getSubEntries()) {
CmsSitemapTreeItem childItem = createSitemapItem(child);
result.addChild(childItem);
}
if (entry.getChildrenLoadedInitially()) {
result.onFinishLoading();
}
return result;
}
/**
* Ensures the given item is visible in the viewport.<p>
*
* @param item the item to see
*/
public void ensureVisible(CmsSitemapTreeItem item) {
// open the tree
CmsTreeItem ti = item.getParentItem();
while (ti != null) {
ti.setOpen(true);
ti = ti.getParentItem();
}
// scroll
CmsDomUtil.ensureVisible(RootPanel.getBodyElement(), item.getElement(), 200);
}
/**
* Returns the controller.<p>
*
* @return the controller
*/
public CmsSitemapController getController() {
return m_controller;
}
/**
* Returns the editor mode.<p>
*
* @return the editor mode
*/
public EditorMode getEditorMode() {
return m_editorMode;
}
/**
* Returns the icon class for the given entry depending on the editor mode.<p>
*
* @param entry the entry to get the icon for
*
* @return the icon CSS class
*/
public String getIconForEntry(CmsClientSitemapEntry entry) {
String iconClass = CmsIconUtil.getResourceIconClasses(entry.getResourceTypeName(), entry.getSitePath(), false);
if (isNavigationMode()) {
if (m_controller.isDetailPage(entry.getId())) {
iconClass = CmsIconUtil.getResourceIconClasses(
m_controller.getDetailPageInfo(entry.getId()).getIconType(),
false);
} else if (!entry.isSubSitemapType()
&& CmsStringUtil.isNotEmptyOrWhitespaceOnly(entry.getDefaultFileType())) {
iconClass = CmsIconUtil.getResourceIconClasses(entry.getDefaultFileType(), false);
}
}
return iconClass;
}
/**
* Gets the list of descendants of a path and splits it into two lists, one containing the sitemap entries whose children have
* already been loaded, and those whose children haven't been loaded.<p>
*
* @param path the path for which the open and closed descendants should be returned
*
* @return a pair whose first and second components are lists of open and closed descendant entries of the path, respectively
*/
public CmsPair<List<CmsClientSitemapEntry>, List<CmsClientSitemapEntry>> getOpenAndClosedDescendants(String path) {
List<CmsClientSitemapEntry> descendants = m_controller.getLoadedDescendants(path);
List<CmsClientSitemapEntry> openDescendants = new ArrayList<CmsClientSitemapEntry>();
List<CmsClientSitemapEntry> closedDescendants = new ArrayList<CmsClientSitemapEntry>();
for (CmsClientSitemapEntry entry : descendants) {
CmsSitemapTreeItem treeItem = getTreeItem(entry.getSitePath());
List<CmsClientSitemapEntry> listToAddTo = treeItem.isLoaded() ? openDescendants : closedDescendants;
listToAddTo.add(entry);
}
return new CmsPair<List<CmsClientSitemapEntry>, List<CmsClientSitemapEntry>>(openDescendants, closedDescendants);
}
/**
* Returns the tree.<p>
*
* @return the tree
*/
public CmsLazyTree<CmsSitemapTreeItem> getTree() {
return m_tree;
}
/**
* Returns the tree entry with the given path.<p>
*
* @param entryId the id of the sitemap entry
*
* @return the tree entry with the given path, or <code>null</code> if not found
*/
public CmsSitemapTreeItem getTreeItem(CmsUUID entryId) {
return m_treeItems.get(entryId);
}
/**
* Returns the tree entry with the given path.<p>
*
* @param path the path to look for
*
* @return the tree entry with the given path, or <code>null</code> if not found
*/
public CmsSitemapTreeItem getTreeItem(String path) {
CmsSitemapData data = m_controller.getData();
CmsClientSitemapEntry root = data.getRoot();
String rootSitePath = root.getSitePath();
String remainingPath = path.substring(rootSitePath.length());
CmsSitemapTreeItem result = getRootItem();
String[] names = CmsStringUtil.splitAsArray(remainingPath, "/");
for (String name : names) {
if (CmsStringUtil.isEmptyOrWhitespaceOnly(name)) {
continue;
}
result = (CmsSitemapTreeItem)result.getChild(name);
if (result == null) {
return null;
}
}
return result;
}
/**
* Highlights the sitemap entry with the given path.<p>
*
* @param sitePath the sitemap path of the entry to highlight
*/
public void highlightPath(String sitePath) {
openItemsOnPath(sitePath);
CmsSitemapTreeItem item = getTreeItem(sitePath);
if (item != null) {
item.highlightTemporarily(1500, isLastPage(item.getSitemapEntry()) ? Background.YELLOW : Background.DEFAULT);
}
}
/**
* Returns if the current sitemap editor mode is navigation.<p>
*
* @return <code>true</code> if the current sitemap editor mode is navigation
*/
public boolean isNavigationMode() {
return EditorMode.navigation == m_editorMode;
}
/**
* @see org.opencms.ade.sitemap.client.control.I_CmsSitemapChangeHandler#onChange(org.opencms.ade.sitemap.client.control.CmsSitemapChangeEvent)
*/
public void onChange(CmsSitemapChangeEvent changeEvent) {
CmsSitemapChange change = changeEvent.getChange();
switch (change.getChangeType()) {
case delete:
CmsSitemapTreeItem item = getTreeItem(change.getEntryId());
item.getParentItem().removeChild(item);
break;
case undelete:
case create:
CmsClientSitemapEntry newEntry = m_controller.getEntryById(change.getEntryId());
CmsSitemapTreeItem newItem = createSitemapItem(newEntry);
getTreeItem(change.getParentId()).insertChild(newItem, newEntry.getPosition());
break;
case bumpDetailPage:
updateDetailPageView(m_controller.getEntryById(change.getEntryId()));
updateAll(m_controller.getEntryById(change.getEntryId()));
break;
case modify:
if (change.hasChangedPosition() || change.hasNewParent()) {
CmsClientSitemapEntry entry = m_controller.getEntryById(change.getEntryId());
CmsSitemapTreeItem moveEntry = getTreeItem(change.getEntryId());
CmsSitemapTreeItem sourceParent = (CmsSitemapTreeItem)moveEntry.getParentItem();
getTree().setAnimationEnabled(false);
sourceParent.removeChild(moveEntry);
CmsSitemapTreeItem destParent = change.hasNewParent()
? getTreeItem(change.getParentId())
: sourceParent;
if (entry.getPosition() < destParent.getChildCount()) {
destParent.insertChild(moveEntry, entry.getPosition());
} else {
destParent.addChild(moveEntry);
}
updateAll(entry);
ensureVisible(moveEntry);
getTree().setAnimationEnabled(true);
break;
}
//$FALL-THROUGH$
case remove:
updateAll(m_controller.getEntryById(change.getEntryId()));
break;
default:
}
}
/**
* @see org.opencms.ade.sitemap.client.control.I_CmsSitemapLoadHandler#onLoad(org.opencms.ade.sitemap.client.control.CmsSitemapLoadEvent)
*/
public void onLoad(CmsSitemapLoadEvent event) {
CmsSitemapTreeItem target = getTreeItem(event.getEntry().getId());
target.getTree().setAnimationEnabled(false);
target.clearChildren();
for (CmsClientSitemapEntry child : event.getEntry().getSubEntries()) {
CmsSitemapTreeItem childItem = createSitemapItem(child);
target.addChild(childItem);
}
target.onFinishLoading();
target.getTree().setAnimationEnabled(true);
if (event.isSetOpen()) {
target.setOpen(true);
}
m_controller.recomputeProperties();
}
/**
* @see com.google.gwt.core.client.EntryPoint#onModuleLoad()
*/
@Override
public void onModuleLoad() {
super.onModuleLoad();
checkBuildId("org.opencms.ade.sitemap");
CmsPingTimer.start();
m_instance = this;
RootPanel rootPanel = RootPanel.get();
m_editorMode = EditorMode.navigation;
// init
I_CmsSitemapLayoutBundle.INSTANCE.sitemapCss().ensureInjected();
I_CmsSitemapLayoutBundle.INSTANCE.clipboardCss().ensureInjected();
I_CmsSitemapLayoutBundle.INSTANCE.sitemapItemCss().ensureInjected();
I_CmsSitemapLayoutBundle.INSTANCE.propertiesCss().ensureInjected();
I_CmsImageBundle.INSTANCE.buttonCss().ensureInjected();
rootPanel.addStyleName(I_CmsSitemapLayoutBundle.INSTANCE.sitemapCss().root());
m_treeItems = new HashMap<CmsUUID, CmsSitemapTreeItem>();
// controller
m_controller = new CmsSitemapController();
m_controller.addChangeHandler(this);
m_controller.addLoadHandler(this);
// toolbar
m_toolbar = new CmsSitemapToolbar(m_controller);
rootPanel.add(m_toolbar);
// header
CmsSitemapHeader title = new CmsSitemapHeader(m_controller.getData().getSitemapInfo());
title.addStyleName(I_CmsSitemapLayoutBundle.INSTANCE.sitemapCss().pageCenter());
rootPanel.add(title);
// content page
final CmsPage page = new CmsPage();
rootPanel.add(page);
// initial content
final Label loadingLabel = new Label(org.opencms.gwt.client.Messages.get().key(
org.opencms.gwt.client.Messages.GUI_LOADING_0));
page.add(loadingLabel);
// initialize the tree
m_openHandler = new TreeOpenHandler();
m_tree = new CmsLazyTree<CmsSitemapTreeItem>(m_openHandler);
m_inNavigationStyle = new CmsStyleVariable(m_tree);
if (m_controller.isEditable()) {
// enable drag'n drop
CmsDNDHandler dndHandler = new CmsDNDHandler(new CmsSitemapDNDController(m_controller, m_toolbar));
dndHandler.addTarget(m_tree);
m_tree.setDNDHandler(dndHandler);
m_tree.setDropEnabled(true);
m_tree.setDNDTakeAll(true);
}
m_tree.truncate(TM_SITEMAP, 920);
m_tree.setAnimationEnabled(true);
page.add(m_tree);
// draw tree items
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
public void execute() {
initiateTreeItems(page, loadingLabel);
}
});
}
/**
* Builds the tree items initially.<p>
*
* @param page the page
* @param loadingLabel the loading label, will be removed when finished
*/
void initiateTreeItems(CmsPage page, Label loadingLabel) {
CmsClientSitemapEntry root = m_controller.getData().getRoot();
CmsSitemapTreeItem rootItem = createSitemapItem(root);
rootItem.onFinishLoading();
rootItem.setOpen(true);
m_tree.addItem(rootItem);
setEditorMode(EditorMode.navigation);
m_controller.addPropertyUpdateHandler(new CmsStatusIconUpdateHandler());
m_controller.recomputeProperties();
rootItem.updateSitePath();
// check if editable
if (!m_controller.isEditable()) {
// notify user
CmsNotification.get().sendSticky(
CmsNotification.Type.WARNING,
Messages.get().key(Messages.GUI_NO_EDIT_NOTIFICATION_1, m_controller.getData().getNoEditReason()));
}
String openPath = m_controller.getData().getOpenPath();
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(openPath)) {
m_openHandler.setInitializing(true);
openItemsOnPath(openPath);
m_openHandler.setInitializing(false);
}
page.remove(loadingLabel);
}
/**
* Removes deleted entry widget reference.<p>
*
* @param entry the entry being deleted
*/
public void removeDeleted(CmsClientSitemapEntry entry) {
for (CmsClientSitemapEntry child : entry.getSubEntries()) {
removeDeleted(child);
}
m_treeItems.remove(entry.getId());
}
/**
* Sets the editor mode.<p>
*
* @param editorMode the editor mode to set
*/
public void setEditorMode(EditorMode editorMode) {
m_editorMode = editorMode;
if (m_editorMode == EditorMode.vfs) {
m_toolbar.setNewEnabled(false, Messages.get().key(Messages.GUI_TOOLBAR_NEW_DISABLE_0));
m_inNavigationStyle.setValue(I_CmsSitemapLayoutBundle.INSTANCE.sitemapItemCss().vfsMode());
} else {
m_toolbar.setNewEnabled(true, null);
m_inNavigationStyle.setValue(I_CmsSitemapLayoutBundle.INSTANCE.sitemapItemCss().navMode());
}
getRootItem().updateEditorMode();
}
/**
* Updates the detail page view for a given changed entry.<p>
*
* @param entry the entry which was changed
*/
public void updateDetailPageView(CmsClientSitemapEntry entry) {
CmsDetailPageTable detailPageTable = m_controller.getDetailPageTable();
List<CmsUUID> idsToUpdate = new ArrayList<CmsUUID>();
if (m_controller.isDetailPage(entry)) {
idsToUpdate.add(entry.getId());
idsToUpdate.addAll(detailPageTable.getAllIds());
}
updateEntriesById(idsToUpdate);
}
/**
* Updates the entries whose id is in the given list of ids.<p>
*
* @param ids a list of sitemap entry ids
*/
public void updateEntriesById(Collection<CmsUUID> ids) {
Map<CmsUUID, CmsClientSitemapEntry> entries = m_controller.getEntriesById(ids);
for (CmsClientSitemapEntry entry : entries.values()) {
CmsSitemapTreeItem item = CmsSitemapTreeItem.getItemById(entry.getId());
item.updateEntry(entry);
}
}
/**
* Gets the sitemap tree item widget which represents the root of the current sitemap.<p>
*
* @return the root sitemap tree item widget
*/
protected CmsSitemapTreeItem getRootItem() {
return (CmsSitemapTreeItem)(m_tree.getWidget(0));
}
/**
* Helper method to get all sitemap tree items from the root to a given path.<p>
*
* For example, if the root item has the site path '/root/', and the value of path is
* '/root/a/b/', the sitemap tree items corresponding to '/root/', '/root/a/' and '/root/a/b'
* will be returned (in that order).<p>
*
* @param path the path for which the sitemap tree items should be returned
*
* @return the sitemap tree items on the path
*/
private List<CmsSitemapTreeItem> getItemsOnPath(String path) {
List<CmsSitemapTreeItem> result = new ArrayList<CmsSitemapTreeItem>();
CmsSitemapData data = m_controller.getData();
CmsClientSitemapEntry root = data.getRoot();
String rootSitePath = root.getSitePath();
String remainingPath = path.substring(rootSitePath.length());
CmsSitemapTreeItem currentItem = getRootItem();
result.add(currentItem);
String[] names = CmsStringUtil.splitAsArray(remainingPath, "/");
for (String name : names) {
if (currentItem == null) {
break;
}
if (CmsStringUtil.isEmptyOrWhitespaceOnly(name)) {
continue;
}
currentItem = (CmsSitemapTreeItem)currentItem.getChild(name);
if (currentItem != null) {
result.add(currentItem);
}
}
return result;
}
/**
* Checks if the given entry represents the last opened page.<p>
*
* @param entry the entry to check
*
* @return <code>true</code> if the given entry is the last opened page
*/
private boolean isLastPage(CmsClientSitemapEntry entry) {
return ((entry.isInNavigation() && (entry.getId().toString().equals(m_controller.getData().getReturnCode()))) || ((entry.getDefaultFileId() != null) && entry.getDefaultFileId().toString().equals(
m_controller.getData().getReturnCode())));
}
/**
* Opens all sitemap tree items on a path, except the last one.<p>
*
* @param path the path for which all intermediate sitemap items should be opened
*/
private void openItemsOnPath(String path) {
List<CmsSitemapTreeItem> itemsOnPath = getItemsOnPath(path);
for (CmsSitemapTreeItem item : itemsOnPath) {
item.setOpen(true);
}
}
/**
* Updates the entry and it's children's view.<p>
*
* @param entry the entry to update
*/
private void updateAll(CmsClientSitemapEntry entry) {
CmsSitemapTreeItem item = getTreeItem(entry.getId());
if (item != null) {
item.updateEntry(entry);
item.updateSitePath(entry.getSitePath());
for (CmsClientSitemapEntry child : entry.getSubEntries()) {
updateAll(child);
}
}
}
}
|
package org.TexasTorque.TexasTorque2013.subsystem.manipulator;
import org.TexasTorque.TexasTorque2013.constants.Constants;
import org.TexasTorque.TexasTorque2013.io.DriverInput;
import org.TexasTorque.TexasTorque2013.io.RobotOutput;
import org.TexasTorque.TexasTorque2013.io.SensorInput;
import org.TexasTorque.TorqueLib.util.Parameters;
import org.TexasTorque.TorqueLib.util.SimPID;
public class Shooter
{
private static Shooter instance;
private RobotOutput robotOutput;
private DriverInput driverInput;
private SensorInput sensorInput;
private Parameters params;
private SimPID frontShooterPID;
private SimPID rearShooterPID;
private SimPID tiltPID;
private double frontMotorSpeed;
private double rearMotorSpeed;
private double tiltMotorSpeed;
private double desiredTiltPosition;
public static Shooter getInstance()
{
return (instance == null) ? instance = new Shooter() : instance;
}
public Shooter()
{
robotOutput = RobotOutput.getInstance();
driverInput = DriverInput.getInstance();
sensorInput = SensorInput.getInstance();
params = Parameters.getInstance();
double p = params.getAsDouble("FrontShooterP", 0.0);
double i = params.getAsDouble("FrontShooterI", 0.0);
double d = params.getAsDouble("FrontShooterD", 0.0);
int e = params.getAsInt("FrontShooterEpsilon", 0);
frontShooterPID = new SimPID(p, i, d, e);
p = params.getAsDouble("RearShooterP", 0.0);
i = params.getAsDouble("RearShooterI", 0.0);
d = params.getAsDouble("RearShooterD", 0.0);
e = params.getAsInt("RearShooterEpsilon", 0);
rearShooterPID = new SimPID(p, i, d, e);
p = params.getAsDouble("TiltP", 0.0);
i = params.getAsDouble("TiltI", 0.0);
d = params.getAsDouble("TiltD", 0.0);
e = params.getAsInt("TiltEpsilon", 0);
tiltPID = new SimPID(p, i, d, e);
frontMotorSpeed = 0.0;
rearMotorSpeed = 0.0;
tiltMotorSpeed = 0.0;
desiredTiltPosition = Constants.TILT_PARALLEL_POSITION;
}
public void run()
{
if(driverInput.shootHigh() && Elevator.getInstance().elevatorAtTop())
{
frontShooterPID.setDesiredValue(params.getAsInt("FrontShooterSpeed", Constants.FRONT_SHOOTER_DEFAULT_RATE));
rearShooterPID.setDesiredValue(params.getAsInt("RearShooterSpeed", Constants.REAR_SHOOTER_DEFAULT_RATE));
// Code to make the tilt do its stuff
}
else
{
desiredTiltPosition = Constants.TILT_PARALLEL_POSITION;
frontShooterPID.setDesiredValue(0);
rearShooterPID.setDesiredValue(0);
}
frontMotorSpeed = limitShooterSpeed(frontShooterPID.calcPID(sensorInput.getFrontShooterRate()));
rearMotorSpeed = limitShooterSpeed(rearShooterPID.calcPID(sensorInput.getRearShooterRate()));
robotOutput.setShooterMotors(frontMotorSpeed, rearMotorSpeed);
robotOutput.setShooterTiltMotor(tiltMotorSpeed);
}
public synchronized void loadFrontShooterPID()
{
double p = params.getAsDouble("FrontShooterP", 0.0);
double i = params.getAsDouble("FrontShooterI", 0.0);
double d = params.getAsDouble("FrontShooterD", 0.0);
frontShooterPID.setConstants(p, i, d);
frontShooterPID.setErrorEpsilon(params.getAsInt("FrontShooterEpsilon", 0));
}
public synchronized void loadRearShooterPID()
{
double p = params.getAsDouble("RearShooterP", 0.0);
double i = params.getAsDouble("RearShooterI", 0.0);
double d = params.getAsDouble("RearShooterD", 0.0);
rearShooterPID.setConstants(p, i, d);
rearShooterPID.setErrorEpsilon(params.getAsInt("RearShooterEpsilon", 0));
}
public synchronized void loadTiltPID()
{
double p = params.getAsDouble("TiltP", 0.0);
double i = params.getAsDouble("TiltI", 0.0);
double d = params.getAsDouble("TiltD", 0.0);
tiltPID.setConstants(p, i, d);
tiltPID.setErrorEpsilon(params.getAsInt("TiltEpsilon", 0));
}
public synchronized boolean isVerticallyLocked()
{
return tiltPID.isDone();
}
public synchronized boolean isParallel()
{
return (isVerticallyLocked() && desiredTiltPosition == Constants.TILT_PARALLEL_POSITION);
}
public synchronized boolean isReadyToFire()
{
return (isVerticallyLocked() && frontShooterPID.isDone() && rearShooterPID.isDone());
}
private double limitShooterSpeed(double shooterSpeed)
{
if(shooterSpeed < 0.0)
{
return 0.0;
}
else
{
return shooterSpeed;
}
}
}
|
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
/**
* Check that there are Interpro descriptions, that each one has an xref, and that the xref has a description.
*/
public class InterproDescriptions extends SingleDatabaseTestCase {
/**
* Create a new InterproDescriptions testcase.
*/
public InterproDescriptions() {
addToGroup("post_genebuild");
addToGroup("release");
setDescription("Check that the repeat_type column of the repeat_consensus table is NOT populated.");
}
/**
* This only really applies to core & vega databases
*/
public void types() {
removeAppliesToType(DatabaseType.EST);
removeAppliesToType(DatabaseType.ESTGENE);
}
/**
* Run the test.
*
* @param dbre The database to use.
* @return true if the test pased.
*
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
// check that the interpro table has some rows
String sql = "SELECT COUNT(*) FROM interpro";
int rows = getRowCount(con, sql);
if (rows == 0) {
ReportManager.problem(this, con, "Interpro table is empty (no xref checks done).");
return false;
} else {
ReportManager.correct(this, con, "Interpro table not empty");
}
// check that there are no Interpro accessions without xrefs
sql = "SELECT count(*) FROM interpro i LEFT JOIN xref x ON i.interpro_ac=x.dbprimary_acc WHERE x.dbprimary_acc IS NULL";
rows = getRowCount(con, sql);
if (rows > 0) {
ReportManager.problem(this, con, "There are " + rows + " rows in the interpro table that have no associated xref");
result = false;
} else {
ReportManager.correct(this, con, "All Interpro accessions have xrefs");
}
// check that the description field is populated for all of them
sql = "SELECT COUNT(*) FROM interpro i, xref x WHERE i.interpro_ac=x.dbprimary_acc AND x.description IS NULL";
rows = getRowCount(con, sql);
if (rows > 0) {
ReportManager.problem(this, con, "There are " + rows + " Interpro xrefs with missing descriptions");
result = false;
} else {
ReportManager.correct(this, con, "All Interpro accessions have xref descriptions");
}
return result;
} // run
} // InterproDescriptions
|
package org.mtransit.android.commons.provider;
import org.mtransit.android.commons.MTLog;
import org.mtransit.android.commons.PreferenceUtils;
import org.mtransit.android.commons.R;
import org.mtransit.android.commons.TimeUtils;
import org.mtransit.android.commons.receiver.DataChange;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class GTFSCurrentNextProvider implements MTLog.Loggable {
private static final String LOG_TAG = GTFSCurrentNextProvider.class.getSimpleName();
@Override
public String getLogTag() {
return LOG_TAG;
}
@Nullable
private static Integer nextFirstDepartureInSec = null;
/**
* Override if multiple {@link GTFSProvider} implementations in same app.
*/
@NonNull
private static Integer getNEXT_FIRST_DEPARTURE_IN_SEC(@NonNull Context context) {
if (nextFirstDepartureInSec == null) {
nextFirstDepartureInSec = context.getResources().getInteger(R.integer.next_gtfs_rts_first_departure_in_sec);
}
return nextFirstDepartureInSec;
}
@Nullable
private static Integer nextLastDepartureInSec = null;
/**
* Override if multiple {@link GTFSProvider} implementations in same app.
*/
@NonNull
private static Integer getNEXT_LAST_DEPARTURE_IN_SEC(@NonNull Context context) {
if (nextLastDepartureInSec == null) {
nextLastDepartureInSec = context.getResources().getInteger(R.integer.next_gtfs_rts_last_departure_in_sec);
}
return nextLastDepartureInSec;
}
@Nullable
private static Integer currentFirstDepartureInSec = null;
/**
* Override if multiple {@link GTFSProvider} implementations in same app.
*/
@NonNull
private static Integer getCURRENT_FIRST_DEPARTURE_IN_SEC(@NonNull Context context) {
if (currentFirstDepartureInSec == null) {
currentFirstDepartureInSec = context.getResources().getInteger(R.integer.current_gtfs_rts_first_departure_in_sec);
}
return currentFirstDepartureInSec;
}
@Nullable
private static Integer currentLastDepartureInSec = null;
/**
* Override if multiple {@link GTFSProvider} implementations in same app.
*/
@NonNull
private static Integer getCURRENT_LAST_DEPARTURE_IN_SEC(@NonNull Context context) {
if (currentLastDepartureInSec == null) {
currentLastDepartureInSec = context.getResources().getInteger(R.integer.current_gtfs_rts_last_departure_in_sec);
}
return currentLastDepartureInSec;
}
public static boolean isCurrentData(@NonNull Context context) {
return hasCurrentData(context)
&& !isNextData(context);
}
@Nullable
private static String currentNextData = null;
private static final String PREF_KEY_CURRENT_NEXT_DATA = "pGTFSCurrentNextData4";
private static final String CURRENT_NEXT_DATA_UNKNOWN = "unknown";
private static final String CURRENT_NEXT_DATA_CURRENT = "current";
private static final String CURRENT_NEXT_DATA_NEXT = "next";
private static final String CURRENT_NEXT_DATA_DEFAULT = CURRENT_NEXT_DATA_UNKNOWN;
@NonNull
public static String getCurrentNextData(@NonNull Context context) {
if (currentNextData == null) {
currentNextData = PreferenceUtils.getPrefLcl(context, PREF_KEY_CURRENT_NEXT_DATA, CURRENT_NEXT_DATA_DEFAULT);
}
return currentNextData;
}
public static void setCurrentNextData(@NonNull Context context, @NonNull String newCurrentNextData) {
if (newCurrentNextData.equals(currentNextData)) {
return; // skip (same value)
}
currentNextData = newCurrentNextData;
PreferenceUtils.savePrefLcl(context, PREF_KEY_CURRENT_NEXT_DATA, newCurrentNextData, false);
}
public static boolean isNextData(@NonNull Context context) {
checkForNextData(context);
return CURRENT_NEXT_DATA_NEXT.equals(getCurrentNextData(context));
}
public static void checkForNextData(@NonNull Context context) {
boolean isNextDataNew = getCURRENT_LAST_DEPARTURE_IN_SEC(context) < TimeUtils.currentTimeSec(); // now AFTER current last departure
String newCurrentNextData = isNextDataNew ? CURRENT_NEXT_DATA_NEXT : CURRENT_NEXT_DATA_CURRENT;
if (CURRENT_NEXT_DATA_UNKNOWN.equals(getCurrentNextData(context))) {
setCurrentNextData(context, newCurrentNextData); // 1st
} else if (!getCurrentNextData(context).equals(newCurrentNextData)) {
setCurrentNextData(context, newCurrentNextData); // 1st
broadcastNextDataChange(context); // 2nd
}
}
private static void broadcastNextDataChange(@NonNull Context context) {
GTFSProvider.onCurrentNextDataChange(context);
GTFSStatusProvider.onCurrentNextDataChange();
DataChange.broadcastDataChange(context, GTFSProvider.getAUTHORITY(context), context.getPackageName(), true);
}
@SuppressWarnings("WeakerAccess")
public static boolean hasNextData(@NonNull Context context) {
return getNEXT_FIRST_DEPARTURE_IN_SEC(context) > 0 && getNEXT_LAST_DEPARTURE_IN_SEC(context) > 0;
}
public static boolean hasCurrentData(@NonNull Context context) {
return getCURRENT_FIRST_DEPARTURE_IN_SEC(context) > 0 && getCURRENT_LAST_DEPARTURE_IN_SEC(context) > 0;
}
}
|
package com.blarg.gdx.tilemap3d;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.utils.Disposable;
import com.blarg.gdx.math.IntersectionTester;
import com.blarg.gdx.tilemap3d.lighting.TileMapLighter;
import com.blarg.gdx.tilemap3d.tilemesh.TileMeshCollection;
public class TileMap extends TileContainer implements Disposable {
final TileChunk[] chunks;
final BoundingBox bounds;
final BoundingBox tmpBounds = new BoundingBox();
final Vector3 tmpPosition = new Vector3();
public final int chunkWidth;
public final int chunkHeight;
public final int chunkDepth;
public final int widthInChunks;
public final int heightInChunks;
public final int depthInChunks;
public final TileMeshCollection tileMeshes;
public final ChunkVertexGenerator vertexGenerator;
public final TileMapLighter lighter;
public byte ambientLightValue;
public byte skyLightValue;
public TileChunk[] getChunks() {
return chunks;
}
@Override
public int getWidth() {
return widthInChunks * chunkWidth;
}
@Override
public int getHeight() {
return heightInChunks * chunkHeight;
}
@Override
public int getDepth() {
return depthInChunks * chunkDepth;
}
@Override
public int getMinX() {
return 0;
}
@Override
public int getMinY() {
return 0;
}
@Override
public int getMinZ() {
return 0;
}
@Override
public int getMaxX() {
return getWidth() - 1;
}
@Override
public int getMaxY() {
return getHeight() - 1;
}
@Override
public int getMaxZ() {
return getDepth() - 1;
}
@Override
public Vector3 getPosition() {
tmpPosition.set(Vector3.Zero);
return tmpPosition;
}
@Override
public BoundingBox getBounds() {
tmpBounds.set(bounds);
return bounds;
}
public TileMap(
int chunkWidth, int chunkHeight, int chunkDepth,
int widthInChunks, int heightInChunks, int depthInChunks,
TileMeshCollection tileMeshes,
ChunkVertexGenerator vertexGenerator,
TileMapLighter lighter
) {
if (tileMeshes == null)
throw new IllegalArgumentException();
if (vertexGenerator == null)
throw new IllegalArgumentException();
this.tileMeshes = tileMeshes;
this.vertexGenerator = vertexGenerator;
this.lighter = lighter;
this.chunkWidth = chunkWidth;
this.chunkHeight = chunkHeight;
this.chunkDepth = chunkDepth;
this.widthInChunks = widthInChunks;
this.heightInChunks = heightInChunks;
this.depthInChunks = depthInChunks;
ambientLightValue = 0;
skyLightValue = Tile.LIGHT_VALUE_SKY;
int numChunks = widthInChunks * heightInChunks * depthInChunks;
chunks = new TileChunk[numChunks];
for (int y = 0; y < heightInChunks; ++y)
{
for (int z = 0; z < depthInChunks; ++z)
{
for (int x = 0; x < widthInChunks; ++x)
{
TileChunk chunk = new TileChunk(
x * chunkWidth, y * chunkHeight, z * chunkDepth,
chunkWidth, chunkHeight, chunkDepth,
this
);
int index = getChunkIndex(x, y, z);
chunks[index] = chunk;
}
}
}
bounds = new BoundingBox();
bounds.min.set(Vector3.Zero);
bounds.max.set(getWidth(), getHeight(), getDepth());
}
public void updateVertices() {
for (int i = 0; i < chunks.length; ++i)
chunks[i].updateVertices(vertexGenerator);
}
public void updateLighting() {
if (lighter != null)
lighter.light(this);
}
public boolean getOverlappedChunks(BoundingBox box, TileCoord min, TileCoord max) {
// make sure the given box actually intersects with the map in the first place
if (!IntersectionTester.test(bounds, box))
return false;
// convert to tile coords. this is in "tilemap space" which is how we want it
// HACK: ceil() calls and "-1"'s keep us from picking up too many/too few
// blocks. these were arrived at through observation
int minX = (int)box.min.x;
int minY = (int)box.min.y;
int minZ = (int)box.min.z;
int maxX = MathUtils.ceil(box.max.x);
int maxY = MathUtils.ceil(box.max.y - 1.0f);
int maxZ = MathUtils.ceil(box.max.z);
// now convert to chunk coords
int minChunkX = minX / chunkWidth;
int minChunkY = minY / chunkHeight;
int minChunkZ = minZ / chunkDepth;
int maxChunkX = maxX / chunkWidth;
int maxChunkY = maxY / chunkHeight;
int maxChunkZ = maxZ / chunkDepth;
// trim off the excess bounds so that we end up with a min-to-max area
// that is completely within the chunk bounds of the map
// HACK: "-1"'s keep us from picking up too many chunks. these were arrived
// at through observation
minChunkX = MathUtils.clamp(minChunkX, 0, widthInChunks);
minChunkY = MathUtils.clamp(minChunkY, 0, (heightInChunks - 1));
minChunkZ = MathUtils.clamp(minChunkZ, 0, depthInChunks);
maxChunkX = MathUtils.clamp(maxChunkX, 0, widthInChunks);
maxChunkY = MathUtils.clamp(maxChunkY, 0, (heightInChunks - 1));
maxChunkZ = MathUtils.clamp(maxChunkZ, 0, depthInChunks);
// return the leftover area
min.x = minChunkX;
min.y = minChunkY;
min.z = minChunkZ;
max.x = maxChunkX;
max.y = maxChunkY;
max.z = maxChunkZ;
return true;
}
@Override
public Tile get(int x, int y, int z) {
TileChunk chunk = getChunkContaining(x, y, z);
int chunkX = x - chunk.x;
int chunkY = y - chunk.y;
int chunkZ = z - chunk.z;
return chunk.get(chunkX, chunkY, chunkZ);
}
@Override
public Tile getSafe(int x, int y, int z) {
if (!isWithinBounds(x, y, z))
return null;
else
return get(x, y, z);
}
public TileChunk getChunk(int chunkX, int chunkY, int chunkZ) {
int index = getChunkIndex(chunkX, chunkY, chunkZ);
return chunks[index];
}
public TileChunk getChunkSafe(int chunkX, int chunkY, int chunkZ) {
if (
(chunkX >= widthInChunks) ||
(chunkY >= heightInChunks) ||
(chunkZ >= depthInChunks)
)
return null;
else
return getChunk(chunkX, chunkY, chunkZ);
}
public TileChunk getChunkNextTo(TileChunk chunk, int chunkOffsetX, int chunkOffsetY, int chunkOffsetZ) {
int checkX = chunk.x + chunkOffsetX;
int checkY = chunk.y + chunkOffsetY;
int checkZ = chunk.z + chunkOffsetZ;
if (
(checkX < 0 || checkX >= widthInChunks) ||
(checkY < 0 || checkY >= heightInChunks) ||
(checkZ < 0 || checkZ >= depthInChunks)
)
return null;
else
return getChunk(checkX, checkY, checkZ);
}
public TileChunk getChunkContaining(int x, int y, int z) {
int index = getChunkIndexAt(x, y, z);
return chunks[index];
}
private int getChunkIndexAt(int x, int y, int z) {
return getChunkIndex(x / chunkWidth, y / chunkHeight, z / chunkDepth);
}
private int getChunkIndex(int chunkX, int chunkY, int chunkZ) {
return (chunkY * widthInChunks * depthInChunks) + (chunkZ * widthInChunks) + chunkX;
}
@Override
public void dispose() {
for (int i = 0; i < chunks.length; ++i)
chunks[i].dispose();
}
}
|
package com.oracle.graal.graph;
import static com.oracle.graal.graph.Edges.Type.*;
import static com.oracle.graal.graph.Graph.*;
import java.lang.annotation.*;
import java.util.*;
import sun.misc.*;
import com.oracle.graal.compiler.common.*;
import com.oracle.graal.graph.Graph.NodeEventListener;
import com.oracle.graal.graph.iterators.*;
import com.oracle.graal.graph.spi.*;
import com.oracle.graal.nodeinfo.*;
/**
* This class is the base class for all nodes, it represent a node which can be inserted in a
* {@link Graph}.
* <p>
* Once a node has been added to a graph, it has a graph-unique {@link #id()}. Edges in the
* subclasses are represented with annotated fields. There are two kind of edges : {@link Input} and
* {@link Successor}. If a field, of a type compatible with {@link Node}, annotated with either
* {@link Input} and {@link Successor} is not null, then there is an edge from this node to the node
* this field points to.
* <p>
* Nodes which are be value numberable should implement the {@link ValueNumberable} interface.
*
* <h1>Assertions and Verification</h1>
*
* The Node class supplies the {@link #assertTrue(boolean, String, Object...)} and
* {@link #assertFalse(boolean, String, Object...)} methods, which will check the supplied boolean
* and throw a VerificationError if it has the wrong value. Both methods will always either throw an
* exception or return true. They can thus be used within an assert statement, so that the check is
* only performed if assertions are enabled.
*/
@NodeInfo
public abstract class Node implements Cloneable, Formattable {
public final static boolean USE_GENERATED_NODES = Boolean.parseBoolean(System.getProperty("graal.useGeneratedNodes", "true"));
public final static boolean USE_UNSAFE_TO_CLONE = Boolean.parseBoolean(System.getProperty("graal.useUnsafeToClone", "false"));
static final int DELETED_ID_START = -1000000000;
static final int INITIAL_ID = -1;
static final int ALIVE_ID_START = 0;
// The use of fully qualified class names here and in the rest
// of this file works around a problem javac has resolving symbols
/**
* Denotes a non-optional (non-null) node input. This should be applied to exactly the fields of
* a node that are of type {@link Node} or {@link NodeInputList}. Nodes that update fields of
* type {@link Node} outside of their constructor should call
* {@link Node#updateUsages(Node, Node)} just prior to doing the update of the input.
*/
@java.lang.annotation.Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.FIELD)
public static @interface Input {
InputType value() default InputType.Value;
}
/**
* Denotes an optional (nullable) node input. This should be applied to exactly the fields of a
* node that are of type {@link Node} or {@link NodeInputList}. Nodes that update fields of type
* {@link Node} outside of their constructor should call {@link Node#updateUsages(Node, Node)}
* just prior to doing the update of the input.
*/
@java.lang.annotation.Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.FIELD)
public static @interface OptionalInput {
InputType value() default InputType.Value;
}
@java.lang.annotation.Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.FIELD)
public static @interface Successor {
}
/**
* Denotes that a parameter of an {@linkplain NodeIntrinsic intrinsic} method must be a compile
* time constant at all call sites to the intrinsic method.
*/
@java.lang.annotation.Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.PARAMETER)
public static @interface ConstantNodeParameter {
}
/**
* Denotes an injected parameter in a {@linkplain NodeIntrinsic node intrinsic} constructor. If
* the constructor is called as part of node intrinsification, the node intrinsifier will inject
* an argument for the annotated parameter. Injected parameters must precede all non-injected
* parameters in a constructor.
*/
@java.lang.annotation.Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.PARAMETER)
public static @interface InjectedNodeParameter {
}
/**
* Annotates a method that can be replaced by a compiler intrinsic. A (resolved) call to the
* annotated method can be replaced with an instance of the node class denoted by
* {@link #value()}. For this reason, the signature of the annotated method must match the
* signature (excluding a prefix of {@linkplain InjectedNodeParameter injected} parameters) of a
* factory method named {@code "create"} in the node class.
*/
@java.lang.annotation.Retention(RetentionPolicy.RUNTIME)
@java.lang.annotation.Target(ElementType.METHOD)
public static @interface NodeIntrinsic {
/**
* Gets the {@link Node} subclass instantiated when intrinsifying a call to the annotated
* method. If not specified, then the class in which the annotated method is declared is
* used (and is assumed to be a {@link Node} subclass).
*/
Class<?> value() default NodeIntrinsic.class;
/**
* Determines if the stamp of the instantiated intrinsic node has its stamp set from the
* return type of the annotated method.
* <p>
* When it is set to true, the stamp that is passed in to the constructor of ValueNode is
* ignored and can therefore safely be {@code null}.
*/
boolean setStampFromReturnType() default false;
}
/**
* Marker for a node that can be replaced by another node via global value numbering. A
* {@linkplain NodeClass#isLeafNode() leaf} node can be replaced by another node of the same
* type that has exactly the same {@linkplain NodeClass#getData() data} values. A non-leaf node
* can be replaced by another node of the same type that has exactly the same data values as
* well as the same {@linkplain Node#inputs() inputs} and {@linkplain Node#successors()
* successors}.
*/
public interface ValueNumberable {
}
private Graph graph;
int id;
// this next pointer is used in Graph to implement fast iteration over NodeClass types, it
// therefore points to the next Node of the same type.
Node typeCacheNext;
static final int INLINE_USAGE_COUNT = 2;
private static final Node[] NO_NODES = {};
/**
* Head of usage list. The elements of the usage list in order are {@link #usage0},
* {@link #usage1} and {@link #extraUsages}. The first null entry terminates the list.
*/
Node usage0;
Node usage1;
Node[] extraUsages;
private Node predecessor;
public static final int NODE_LIST = -2;
public static final int NOT_ITERABLE = -1;
public Node() {
assert USE_GENERATED_NODES == this instanceof GeneratedNode : getClass() + " is not a generated Node class - forgot @" + NodeInfo.class.getSimpleName() + " on class declaration?";
init();
}
final void init() {
id = INITIAL_ID;
extraUsages = NO_NODES;
}
int id() {
return id;
}
/**
* Gets the graph context of this node.
*/
public Graph graph() {
return graph;
}
/**
* Returns an {@link NodeClassIterable iterable} which can be used to traverse all non-null
* input edges of this node.
*
* @return an {@link NodeClassIterable iterable} for all non-null input edges.
*/
public NodeClassIterable inputs() {
return getNodeClass().getEdges(Inputs).getIterable(this);
}
/**
* Returns an {@link NodeClassIterable iterable} which can be used to traverse all non-null
* successor edges of this node.
*
* @return an {@link NodeClassIterable iterable} for all non-null successor edges.
*/
public NodeClassIterable successors() {
return getNodeClass().getEdges(Successors).getIterable(this);
}
/**
* Gets the maximum number of usages this node has had at any point in time.
*/
int getUsageCountUpperBound() {
if (usage0 == null) {
return 0;
}
if (usage1 == null) {
return 1;
}
return 2 + extraUsages.length;
}
/**
* Gets the list of nodes that use this node (i.e., as an input).
*/
public final NodeIterable<Node> usages() {
return new NodeUsageIterable(this);
}
/**
* Finds the index of the last non-null entry in a node array. The search assumes that all
* non-null entries precede the first null entry in the array.
*
* @param nodes the array to search
* @return the index of the last non-null entry in {@code nodes} if it exists, else -1
*/
private static int indexOfLastNonNull(Node[] nodes) {
if (nodes.length == 0 || nodes[0] == null) {
return -1;
}
if (nodes[nodes.length - 1] != null) {
return nodes.length - 1;
}
// binary search
int low = 0;
int high = nodes.length - 1;
while (true) {
int mid = (low + high) >>> 1;
if (nodes[mid] == null) {
if (nodes[mid - 1] != null) {
return mid - 1;
}
high = mid - 1;
} else {
if (mid == nodes.length - 1 || nodes[mid + 1] == null) {
return mid;
}
low = mid + 1;
}
}
}
/**
* Adds a given node to this node's {@linkplain #usages() usages}.
*
* @param node the node to add
*/
private void addUsage(Node node) {
incUsageModCount();
if (usage0 == null) {
usage0 = node;
} else if (usage1 == null) {
usage1 = node;
} else {
int length = extraUsages.length;
if (length == 0) {
extraUsages = new Node[4];
extraUsages[0] = node;
} else {
int lastNonNull = indexOfLastNonNull(extraUsages);
if (lastNonNull == length - 1) {
extraUsages = Arrays.copyOf(extraUsages, length * 2 + 1);
extraUsages[length] = node;
} else if (lastNonNull == -1) {
extraUsages[0] = node;
} else {
extraUsages[lastNonNull + 1] = node;
}
}
}
}
int usageCount() {
if (usage0 == null) {
return 0;
}
if (usage1 == null) {
return 1;
}
return 2 + indexOfLastNonNull(extraUsages) + 1;
}
/**
* Remove all usages between {@code fromIndex} and {@code toIndex} (exclusive), also, if
* {@code toIndex} is a valid usage, it is moved to {@code fromIndex}.
*
* <p>
* Visually,
*
* <pre>
* {@code
* [1, 2, 3, 4, 5, 6, 7].removeUsagesAndShiftFirst(1, 2) == [1, 4, 6, 7, 5, null, null]}
* </pre>
*
*
* @param fromIndex the index of the first element to be removed
* @param toIndex the index after the last element to be removed
*/
private void removeUsagesAndShiftFirst(int fromIndex, int toIndex) {
assert fromIndex < toIndex;
int firstNullIndex = usageCount();
assert toIndex <= firstNullIndex;
int i = fromIndex;
int limit = toIndex;
if (toIndex < firstNullIndex) {
// move usage at toIndex to fromIndex(!)
movUsageTo(toIndex, fromIndex);
limit++;
i++;
}
while (i < limit && firstNullIndex > limit) {
movUsageTo(firstNullIndex - 1, i);
firstNullIndex
i++;
}
while (i < limit) {
if (i == 0) {
usage0 = null;
} else if (i == 1) {
usage1 = null;
} else {
extraUsages[i - INLINE_USAGE_COUNT] = null;
}
i++;
}
}
private void movUsageTo(int usageIndex, int toIndex) {
assert usageIndex > toIndex;
if (toIndex == 0) {
if (usageIndex == 1) {
usage0 = usage1;
usage1 = null;
} else {
usage0 = extraUsages[usageIndex - INLINE_USAGE_COUNT];
extraUsages[usageIndex - INLINE_USAGE_COUNT] = null;
}
} else if (toIndex == 1) {
usage1 = extraUsages[usageIndex - INLINE_USAGE_COUNT];
extraUsages[usageIndex - INLINE_USAGE_COUNT] = null;
} else {
extraUsages[toIndex - INLINE_USAGE_COUNT] = extraUsages[usageIndex - INLINE_USAGE_COUNT];
extraUsages[usageIndex - INLINE_USAGE_COUNT] = null;
}
}
/**
* Removes a given node from this node's {@linkplain #usages() usages}.
*
* @param node the node to remove
* @return whether or not {@code usage} was in the usage list
*/
private boolean removeUsage(Node node) {
assert node != null;
// It is critical that this method maintains the invariant that
// the usage list has no null element preceding a non-null element
incUsageModCount();
if (usage0 == node) {
if (usage1 != null) {
int lastNonNull = indexOfLastNonNull(extraUsages);
if (lastNonNull >= 0) {
usage0 = extraUsages[lastNonNull];
extraUsages[lastNonNull] = null;
} else {
// usage1 is the last element
usage0 = usage1;
usage1 = null;
}
} else {
// usage0 is the last element
usage0 = null;
}
return true;
}
if (usage1 == node) {
int lastNonNull = indexOfLastNonNull(extraUsages);
if (lastNonNull >= 0) {
usage1 = extraUsages[lastNonNull];
extraUsages[lastNonNull] = null;
} else {
// usage1 is the last element
usage1 = null;
}
return true;
}
int matchIndex = -1;
int i = 0;
Node n;
while (i < extraUsages.length && (n = extraUsages[i]) != null) {
if (n == node) {
matchIndex = i;
}
i++;
}
if (matchIndex >= 0) {
extraUsages[matchIndex] = extraUsages[i - 1];
extraUsages[i - 1] = null;
return true;
}
return false;
}
private void clearUsages() {
incUsageModCount();
usage0 = null;
usage1 = null;
extraUsages = NO_NODES;
}
public final Node predecessor() {
return predecessor;
}
public final int modCount() {
if (MODIFICATION_COUNTS_ENABLED && graph != null) {
return graph.modCount(this);
}
return 0;
}
final void incModCount() {
if (MODIFICATION_COUNTS_ENABLED && graph != null) {
graph.incModCount(this);
}
}
final int usageModCount() {
if (MODIFICATION_COUNTS_ENABLED && graph != null) {
return graph.usageModCount(this);
}
return 0;
}
final void incUsageModCount() {
if (MODIFICATION_COUNTS_ENABLED && graph != null) {
graph.incUsageModCount(this);
}
}
public boolean isDeleted() {
return id <= DELETED_ID_START;
}
public boolean isAlive() {
return id >= ALIVE_ID_START;
}
/**
* Updates the usages sets of the given nodes after an input slot is changed from
* {@code oldInput} to {@code newInput} by removing this node from {@code oldInput}'s usages and
* adds this node to {@code newInput}'s usages.
*/
protected void updateUsages(Node oldInput, Node newInput) {
assert isAlive() && (newInput == null || newInput.isAlive()) : "adding " + newInput + " to " + this + " instead of " + oldInput;
if (oldInput != newInput) {
if (oldInput != null) {
boolean result = removeThisFromUsages(oldInput);
assert assertTrue(result, "not found in usages, old input: %s", oldInput);
}
maybeNotifyInputChanged(this);
if (newInput != null) {
newInput.addUsage(this);
}
if (oldInput != null && oldInput.usages().isEmpty()) {
maybeNotifyZeroUsages(oldInput);
}
}
}
protected void updateUsagesInterface(NodeInterface oldInput, NodeInterface newInput) {
updateUsages(oldInput == null ? null : oldInput.asNode(), newInput == null ? null : newInput.asNode());
}
/**
* Updates the predecessor of the given nodes after a successor slot is changed from
* oldSuccessor to newSuccessor: removes this node from oldSuccessor's predecessors and adds
* this node to newSuccessor's predecessors.
*/
protected void updatePredecessor(Node oldSuccessor, Node newSuccessor) {
assert isAlive() && (newSuccessor == null || newSuccessor.isAlive()) : "adding " + newSuccessor + " to " + this + " instead of " + oldSuccessor;
assert graph == null || !graph.isFrozen();
if (oldSuccessor != newSuccessor) {
if (oldSuccessor != null) {
assert assertTrue(oldSuccessor.predecessor == this, "wrong predecessor in old successor (%s): %s, should be %s", oldSuccessor, oldSuccessor.predecessor, this);
oldSuccessor.predecessor = null;
}
if (newSuccessor != null) {
assert assertTrue(newSuccessor.predecessor == null, "unexpected non-null predecessor in new successor (%s): %s, this=%s", newSuccessor, newSuccessor.predecessor, this);
newSuccessor.predecessor = this;
}
}
}
void initialize(Graph newGraph) {
assert assertTrue(id == INITIAL_ID, "unexpected id: %d", id);
this.graph = newGraph;
newGraph.register(this);
for (Node input : inputs()) {
updateUsages(null, input);
}
for (Node successor : successors()) {
updatePredecessor(null, successor);
}
}
public final NodeClass getNodeClass() {
return NodeClass.get(getClass());
}
public boolean isAllowedUsageType(InputType type) {
return getNodeClass().getAllowedUsageTypes().contains(type);
}
private boolean checkReplaceWith(Node other) {
assert assertTrue(graph == null || !graph.isFrozen(), "cannot modify frozen graph");
assert assertFalse(other == this, "cannot replace a node with itself");
assert assertFalse(isDeleted(), "cannot replace deleted node");
assert assertTrue(other == null || !other.isDeleted(), "cannot replace with deleted node %s", other);
return true;
}
public void replaceAtUsages(Node other) {
assert checkReplaceWith(other);
for (Node usage : usages()) {
boolean result = usage.getNodeClass().getEdges(Inputs).replaceFirst(usage, this, other);
assert assertTrue(result, "not found in inputs, usage: %s", usage);
if (other != null) {
maybeNotifyInputChanged(usage);
other.addUsage(usage);
}
}
clearUsages();
}
public void replaceAtMatchingUsages(Node other, NodePredicate usagePredicate) {
assert checkReplaceWith(other);
NodeUsageIterator it = (NodeUsageIterator) usages().iterator();
int removeStart = -1;
while (it.hasNext()) {
Node usage = it.next();
if (usagePredicate.apply(usage)) {
if (removeStart < 0) {
removeStart = it.index - 1;
}
boolean result = usage.getNodeClass().getEdges(Inputs).replaceFirst(usage, this, other);
assert assertTrue(result, "not found in inputs, usage: %s", usage);
if (other != null) {
maybeNotifyInputChanged(usage);
other.addUsage(usage);
}
} else {
if (removeStart >= 0) {
int removeEndIndex = it.index - 1;
removeUsagesAndShiftFirst(removeStart, removeEndIndex);
it.index = removeStart;
it.advance();
removeStart = -1;
}
}
}
if (removeStart >= 0) {
int removeEndIndex = it.index;
removeUsagesAndShiftFirst(removeStart, removeEndIndex);
}
}
public void replaceAtUsages(InputType type, Node other) {
assert checkReplaceWith(other);
for (Node usage : usages().snapshot()) {
NodePosIterator iter = usage.inputs().iterator();
while (iter.hasNext()) {
Position pos = iter.nextPosition();
if (pos.getInputType() == type && pos.get(usage) == this) {
pos.set(usage, other);
}
}
}
}
private void maybeNotifyInputChanged(Node node) {
if (graph != null) {
assert !graph.isFrozen();
NodeEventListener listener = graph.nodeEventListener;
if (listener != null) {
listener.inputChanged(node);
}
}
}
private void maybeNotifyZeroUsages(Node node) {
if (graph != null) {
assert !graph.isFrozen();
NodeEventListener listener = graph.nodeEventListener;
if (listener != null) {
listener.usagesDroppedToZero(node);
}
}
}
public void replaceAtPredecessor(Node other) {
assert checkReplaceWith(other);
if (predecessor != null) {
boolean result = predecessor.getNodeClass().getEdges(Successors).replaceFirst(predecessor, this, other);
assert assertTrue(result, "not found in successors, predecessor: %s", predecessor);
predecessor.updatePredecessor(this, other);
}
}
public void replaceAndDelete(Node other) {
assert checkReplaceWith(other);
if (other != null) {
clearSuccessors();
replaceAtUsages(other);
replaceAtPredecessor(other);
}
safeDelete();
}
public void replaceFirstSuccessor(Node oldSuccessor, Node newSuccessor) {
if (getNodeClass().getEdges(Successors).replaceFirst(this, oldSuccessor, newSuccessor)) {
updatePredecessor(oldSuccessor, newSuccessor);
}
}
public void replaceFirstInput(Node oldInput, Node newInput) {
if (getNodeClass().getEdges(Inputs).replaceFirst(this, oldInput, newInput)) {
updateUsages(oldInput, newInput);
}
}
private void unregisterInputs() {
for (Node input : inputs()) {
removeThisFromUsages(input);
if (input.usages().isEmpty()) {
maybeNotifyZeroUsages(input);
}
}
}
public void clearInputs() {
assert assertFalse(isDeleted(), "cannot clear inputs of deleted node");
unregisterInputs();
getNodeClass().getEdges(Inputs).clear(this);
}
private boolean removeThisFromUsages(Node n) {
return n.removeUsage(this);
}
private void unregisterSuccessors() {
for (Node successor : successors()) {
assert assertTrue(successor.predecessor == this, "wrong predecessor in old successor (%s): %s", successor, successor.predecessor);
successor.predecessor = null;
}
}
public void clearSuccessors() {
assert assertFalse(isDeleted(), "cannot clear successors of deleted node");
unregisterSuccessors();
getNodeClass().getEdges(Successors).clear(this);
}
private boolean checkDeletion() {
assertTrue(usages().isEmpty(), "cannot delete node %s because of usages: %s", this, usages());
assertTrue(predecessor == null, "cannot delete node %s because of predecessor: %s", this, predecessor);
return true;
}
/**
* Removes this node from its graph. This node must have no {@linkplain Node#usages() usages}
* and no {@linkplain #predecessor() predecessor}.
*/
public void safeDelete() {
assert checkDeletion();
unregisterInputs();
unregisterSuccessors();
graph.unregister(this);
id = DELETED_ID_START - id;
assert isDeleted();
}
public final Node copyWithInputs() {
Node newNode = clone(graph, WithOnlyInputEdges);
for (Node input : inputs()) {
input.addUsage(newNode);
}
return newNode;
}
/**
* Must be overridden by subclasses that implement {@link Simplifiable}. The implementation in
* {@link Node} exists to obviate the need to cast a node before invoking
* {@link Simplifiable#simplify(SimplifierTool)}.
*
* @param tool
*/
public void simplify(SimplifierTool tool) {
throw new UnsupportedOperationException();
}
/**
* @param newNode the result of cloning this node or {@link Unsafe#allocateInstance(Class) raw
* allocating} a copy of this node
* @param type the type of edges to process
* @param edgesToCopy if {@code type} is in this set, the edges are copied otherwise they are
* cleared
*/
private void copyOrClearEdgesForClone(NodeClass nodeClass, Node newNode, Edges.Type type, EnumSet<Edges.Type> edgesToCopy) {
if (edgesToCopy.contains(type)) {
nodeClass.getEdges(type).copy(this, newNode);
} else {
if (USE_UNSAFE_TO_CLONE) {
// The direct edges are already null
nodeClass.getEdges(type).initializeLists(newNode, this);
} else {
nodeClass.getEdges(type).clear(newNode);
}
}
}
public static final EnumSet<Edges.Type> WithNoEdges = EnumSet.noneOf(Edges.Type.class);
public static final EnumSet<Edges.Type> WithAllEdges = EnumSet.allOf(Edges.Type.class);
public static final EnumSet<Edges.Type> WithOnlyInputEdges = EnumSet.of(Inputs);
public static final EnumSet<Edges.Type> WithOnlySucessorEdges = EnumSet.of(Successors);
/**
* Makes a copy of this node in(to) a given graph.
*
* @param into the graph in which the copy will be registered (which may be this node's graph)
* @param edgesToCopy specifies the edges to be copied. The edges not specified in this set are
* initialized to their default value (i.e., {@code null} for a direct edge, an empty
* list for an edge list)
* @return the copy of this node
*/
final Node clone(Graph into, EnumSet<Edges.Type> edgesToCopy) {
NodeClass nodeClass = getNodeClass();
if (nodeClass.valueNumberable() && nodeClass.isLeafNode()) {
Node otherNode = into.findNodeInCache(this);
if (otherNode != null) {
return otherNode;
}
}
Node newNode = null;
try {
if (USE_UNSAFE_TO_CLONE) {
newNode = (Node) UnsafeAccess.unsafe.allocateInstance(getClass());
nodeClass.getData().copy(this, newNode);
copyOrClearEdgesForClone(nodeClass, newNode, Inputs, edgesToCopy);
copyOrClearEdgesForClone(nodeClass, newNode, Successors, edgesToCopy);
} else {
newNode = (Node) this.clone();
newNode.typeCacheNext = null;
newNode.usage0 = null;
newNode.usage1 = null;
newNode.predecessor = null;
copyOrClearEdgesForClone(nodeClass, newNode, Inputs, edgesToCopy);
copyOrClearEdgesForClone(nodeClass, newNode, Successors, edgesToCopy);
}
} catch (Exception e) {
throw new GraalGraphInternalError(e).addContext(this);
}
newNode.graph = into;
newNode.id = INITIAL_ID;
into.register(newNode);
newNode.extraUsages = NO_NODES;
if (nodeClass.valueNumberable() && nodeClass.isLeafNode()) {
into.putNodeIntoCache(newNode);
}
newNode.afterClone(this);
return newNode;
}
protected void afterClone(@SuppressWarnings("unused") Node other) {
}
public boolean verify() {
assertTrue(isAlive(), "cannot verify inactive nodes (id=%d)", id);
assertTrue(graph() != null, "null graph");
for (Node input : inputs()) {
assertTrue(input.usages().contains(this), "missing usage in input %s", input);
}
for (Node successor : successors()) {
assertTrue(successor.predecessor() == this, "missing predecessor in %s (actual: %s)", successor, successor.predecessor());
assertTrue(successor.graph() == graph(), "mismatching graph in successor %s", successor);
}
for (Node usage : usages()) {
assertFalse(usage.isDeleted(), "usage %s must never be deleted", usage);
assertTrue(usage.inputs().contains(this), "missing input in usage %s", usage);
NodePosIterator iterator = usage.inputs().iterator();
while (iterator.hasNext()) {
Position pos = iterator.nextPosition();
if (pos.get(usage) == this && pos.getInputType() != InputType.Unchecked) {
assert isAllowedUsageType(pos.getInputType()) : "invalid input of type " + pos.getInputType() + " from " + usage + " to " + this + " (" + pos.getName() + ")";
}
}
}
NodePosIterator iterator = inputs().withNullIterator();
while (iterator.hasNext()) {
Position pos = iterator.nextPosition();
assert pos.isInputOptional() || pos.get(this) != null : "non-optional input " + pos.getName() + " cannot be null in " + this + " (fix nullness or use @OptionalInput)";
}
if (predecessor != null) {
assertFalse(predecessor.isDeleted(), "predecessor %s must never be deleted", predecessor);
assertTrue(predecessor.successors().contains(this), "missing successor in predecessor %s", predecessor);
}
return true;
}
public boolean assertTrue(boolean condition, String message, Object... args) {
if (condition) {
return true;
} else {
throw new VerificationError(message, args).addContext(this);
}
}
public boolean assertFalse(boolean condition, String message, Object... args) {
if (condition) {
throw new VerificationError(message, args).addContext(this);
} else {
return true;
}
}
public Iterable<? extends Node> cfgPredecessors() {
if (predecessor == null) {
return Collections.emptySet();
} else {
return Collections.singleton(predecessor);
}
}
/**
* Returns an iterator that will provide all control-flow successors of this node. Normally this
* will be the contents of all fields marked as NodeSuccessor, but some node classes (like
* EndNode) may return different nodes. Note that the iterator may generate null values if the
* fields contain them.
*/
public Iterable<? extends Node> cfgSuccessors() {
return successors();
}
/**
* Nodes always use an {@linkplain System#identityHashCode(Object) identity} hash code.
*/
@Override
public final int hashCode() {
return System.identityHashCode(this);
}
/**
* Equality tests must rely solely on identity.
*/
@Override
public final boolean equals(Object obj) {
return super.equals(obj);
}
/**
* Provides a {@link Map} of properties of this node for use in debugging (e.g., to view in the
* ideal graph visualizer).
*/
public final Map<Object, Object> getDebugProperties() {
return getDebugProperties(new HashMap<>());
}
/**
* Fills a {@link Map} with properties of this node for use in debugging (e.g., to view in the
* ideal graph visualizer). Subclasses overriding this method should also fill the map using
* their superclass.
*
* @param map
*/
public Map<Object, Object> getDebugProperties(Map<Object, Object> map) {
NodeClass nodeClass = getNodeClass();
Fields properties = nodeClass.getData();
for (int i = 0; i < properties.getCount(); i++) {
map.put(properties.getName(i), properties.get(this, i));
}
return map;
}
/**
* This method is a shortcut for {@link #toString(Verbosity)} with {@link Verbosity#Short}.
*/
@Override
public final String toString() {
return toString(Verbosity.Short);
}
/**
* Creates a String representation for this node with a given {@link Verbosity}.
*/
public String toString(Verbosity verbosity) {
switch (verbosity) {
case Id:
return Integer.toString(id);
case Name:
return getNodeClass().shortName();
case Short:
return toString(Verbosity.Id) + "|" + toString(Verbosity.Name);
case Long:
return toString(Verbosity.Short);
case Debugger:
case All: {
StringBuilder str = new StringBuilder();
str.append(toString(Verbosity.Short)).append(" { ");
for (Map.Entry<Object, Object> entry : getDebugProperties().entrySet()) {
str.append(entry.getKey()).append("=").append(entry.getValue()).append(", ");
}
str.append(" }");
return str.toString();
}
default:
throw new RuntimeException("unknown verbosity: " + verbosity);
}
}
@Deprecated
public int getId() {
return id;
}
@Override
public void formatTo(Formatter formatter, int flags, int width, int precision) {
if ((flags & FormattableFlags.ALTERNATE) == FormattableFlags.ALTERNATE) {
formatter.format("%s", toString(Verbosity.Id));
} else if ((flags & FormattableFlags.UPPERCASE) == FormattableFlags.UPPERCASE) {
// Use All here since Long is only slightly longer than Short.
formatter.format("%s", toString(Verbosity.All));
} else {
formatter.format("%s", toString(Verbosity.Short));
}
boolean neighborsAlternate = ((flags & FormattableFlags.LEFT_JUSTIFY) == FormattableFlags.LEFT_JUSTIFY);
int neighborsFlags = (neighborsAlternate ? FormattableFlags.ALTERNATE | FormattableFlags.LEFT_JUSTIFY : 0);
if (width > 0) {
if (this.predecessor != null) {
formatter.format(" pred={");
this.predecessor.formatTo(formatter, neighborsFlags, width - 1, 0);
formatter.format("}");
}
NodePosIterator inputIter = inputs().iterator();
while (inputIter.hasNext()) {
Position position = inputIter.nextPosition();
Node input = position.get(this);
if (input != null) {
formatter.format(" ");
formatter.format(position.getName());
formatter.format("={");
input.formatTo(formatter, neighborsFlags, width - 1, 0);
formatter.format("}");
}
}
}
if (precision > 0) {
if (!usages().isEmpty()) {
formatter.format(" usages={");
int z = 0;
for (Node usage : usages()) {
if (z != 0) {
formatter.format(", ");
}
usage.formatTo(formatter, neighborsFlags, 0, precision - 1);
++z;
}
formatter.format("}");
}
NodePosIterator succIter = successors().iterator();
while (succIter.hasNext()) {
Position position = succIter.nextPosition();
Node successor = position.get(this);
if (successor != null) {
formatter.format(" ");
formatter.format(position.getName());
formatter.format("={");
successor.formatTo(formatter, neighborsFlags, 0, precision - 1);
formatter.format("}");
}
}
}
}
/**
* If this node is a {@linkplain NodeClass#isLeafNode() leaf} node, returns a hash for this node
* based on its {@linkplain NodeClass#getData() data} fields otherwise return 0.
*
* Overridden by a method generated for leaf nodes.
*/
protected int valueNumberLeaf() {
assert !getNodeClass().isLeafNode();
return 0;
}
/**
* Overridden by a generated method.
*
* @param other
*/
protected boolean dataEquals(Node other) {
return true;
}
/**
* Determines if this node's {@link NodeClass#getData() data} fields are equal to the data
* fields of another node of the same type. Primitive fields are compared by value and
* non-primitive fields are compared by {@link Objects#equals(Object, Object)}.
*
* The result of this method undefined if {@code other.getClass() != this.getClass()}.
*
* @param other a node of exactly the same type as this node
* @return true if the data fields of this object and {@code other} are equal
*/
public boolean valueEquals(Node other) {
return USE_GENERATED_NODES ? dataEquals(other) : getNodeClass().dataEquals(this, other);
}
}
|
package org.objectweb.proactive.core.component.body;
import org.apache.log4j.Logger;
import org.objectweb.proactive.core.body.BodyImpl;
import org.objectweb.proactive.core.body.MetaObjectFactory;
import org.objectweb.proactive.core.body.ProActiveMetaObjectFactory;
import org.objectweb.proactive.core.component.ComponentParameters;
import org.objectweb.proactive.core.component.identity.ProActiveComponent;
/**
* This class is placed in the hierarchy of bodies in order to provide access to the
* component metaobjects (through ProActiveComponentImpl)
*
* @author Matthieu Morel
*/
import java.util.Hashtable;
/** This class has been inserted into the bodies hierarchy in order to instantiate the
* component metaobject (ProActiveComponent).
*/
public class ComponentBodyImpl extends BodyImpl implements ComponentBody {
protected static Logger logger = Logger.getLogger(ComponentBodyImpl.class.getName());
//private static Category cat = Category.getInstance(ComponentBodyImpl.class.getName());
private ProActiveComponent componentIdentity = null;
/**
* Constructor for ComponentBodyImpl.
*/
public ComponentBodyImpl() {
super();
}
/** Constructor for ComponentBodyImpl.
*
* It creates the component metaobject only if the MetaObjectFactory is parameterized
* with ComponentParameters (thus implicitely constructing components)
* @param reifiedObject a reference on the reified object
* @param nodeURL node url
* @param factory factory for the corresponding metaobjects
*/
public ComponentBodyImpl(Object reifiedObject, String nodeURL,
MetaObjectFactory factory, String jobID) {
super(reifiedObject, nodeURL, factory, jobID);
// create the component metaobject if necessary
// --> check the value of the "parameters" field
Hashtable factory_parameters = factory.getParameters();
if ((factory_parameters != null)) {
if (factory_parameters.get(
ProActiveMetaObjectFactory.COMPONENT_PARAMETERS_KEY) != null) {
if (factory_parameters.get(
ProActiveMetaObjectFactory.COMPONENT_PARAMETERS_KEY) instanceof ComponentParameters) {
if (logger.isDebugEnabled()) {
logger.debug("creating metaobject component identity");
}
componentIdentity = factory.newComponentFactory()
.newProActiveComponent(this);
} else {
logger.error(
"component parameters for the components factory are not of type ComponentParameters");
}
}
}
}
/**
* Returns the a reference on the Component meta object
* @return the ProActiveComponent meta-object
*/
public ProActiveComponent getProActiveComponent() {
return componentIdentity;
}
}
|
package com.crossge.necessities;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
public class GetUUID {
private static HashMap<String, UUID> uuids = new HashMap<>();
private File configFileUUIDs = new File("plugins/Necessities/RankManager", "users.yml");
public UUID getID(String name) {
UUID partial = null;
boolean startsWith = false;
for (Player p : Bukkit.getServer().getOnlinePlayers()) {
if (p.getName().equalsIgnoreCase(name))
return p.getUniqueId();
if (!startsWith && p.getName().toLowerCase().startsWith(name.toLowerCase())) {
partial = p.getUniqueId();
startsWith = true;
}
if (partial == null && (p.getName().toLowerCase().contains(name.toLowerCase()) || ChatColor.stripColor(p.getDisplayName()).toLowerCase().contains(name.toLowerCase())))
partial = p.getUniqueId();
}
return partial;
}
public void addUUID(UUID uuid) {
uuids.put(Bukkit.getPlayer(uuid).getName().toLowerCase(), uuid);
}
public UUID getOfflineID(String name) {
if (uuids.containsKey(name.toLowerCase()))
return uuids.get(name.toLowerCase());
return null;
}
public void initiate() {
Bukkit.getConsoleSender().sendMessage(ChatColor.AQUA + "Retrieving all stored UUIDs.");
YamlConfiguration configUUIDs = YamlConfiguration.loadConfiguration(configFileUUIDs);
ArrayList<String> invalidKeys = new ArrayList<>();
for (String key : configUUIDs.getKeys(false))
if (nameFromString(key) != null) {
UUID uuid = null;
try {
uuid = UUID.fromString(key);
} catch (Exception e) {
invalidKeys.add(key);
}
if (uuid != null)
uuids.put(nameFromString(key).toLowerCase(), UUID.fromString(key));
} else
invalidKeys.add(key);
for (String key : invalidKeys)
configUUIDs.set(key, null);
if (!invalidKeys.isEmpty())
try {
configUUIDs.save(configFileUUIDs);
} catch (Exception e) {
}
Bukkit.getConsoleSender().sendMessage(ChatColor.AQUA + "All stored UUIDs retrieved.");
}
public boolean hasJoined(UUID uuid) {
return uuids.containsValue(uuid);
}
public String nameFromString(String message) {
UUID uuid;
try {
uuid = UUID.fromString(message);
} catch (Exception e) {
return null;
}
if (Bukkit.getPlayer(uuid) == null) {
if (Bukkit.getOfflinePlayer(uuid) == null)
return null; //What did you do this time
return Bukkit.getOfflinePlayer(uuid).getName();
}
return Bukkit.getPlayer(uuid).getName();
}
}
|
package mondrian.rolap.agg;
import mondrian.olap.Util;
import mondrian.rolap.*;
import mondrian.spi.SegmentHeader;
import org.apache.log4j.Logger;
import java.io.PrintWriter;
import java.util.*;
/**
* A <code>Segment</code> is a collection of cell values parameterized by a measure, and a set of (column, value) pairs.
* An example of a segment is
* </p>
*
* <blockquote>
* <p>
* (Unit sales, Gender = 'F', State in {'CA','OR'}, Marital Status = <i> anything</i>)
* </p>
* </blockquote>
*
* <p>
* All segments over the same set of columns belong to an Aggregation, in this case:
* </p>
*
* <blockquote>
* <p>
* ('Sales' Star, Gender, State, Marital Status)
* </p>
* </blockquote>
*
* <p>
* Note that different measures (in the same Star) occupy the same Aggregation. Aggregations belong to the
* AggregationManager, a singleton.
* </p>
*
* <p>
* Segments are pinned during the evaluation of a single MDX query. The query evaluates the expressions twice. The first
* pass, it finds which cell values it needs, pins the segments containing the ones which are already present (one
* pin-count for each cell value used), and builds a {@link CellRequest cell request} for those which are not present.
* It executes the cell request to bring the required cell values into the cache, again, pinned. Then it evalutes the
* query a second time, knowing that all cell values are available. Finally, it releases the pins.
* </p>
*
* <p>
* A Segment may have a list of {@link ExcludedRegion} objects. These are caused by cache flushing. Usually a segment is
* a hypercube: it is defined by a set of values on each of its axes. But after a cache flush request, a segment may
* have a rectangular 'hole', and therefore not be a hypercube anymore.
*
* <p>
* For example, the segment defined by {CA, OR, WA} * {F, M} is a 2-dimensional hyper-rectangle with 6 cells. After
* flushing {CA, OR, TX} * {F}, the result is 4 cells:
*
* <pre>
* F M
* CA out in
* OR out in
* WA in in
* </pre>
*
* defined by the original segment minus the region ({CA, OR} * {F}).
*
* @author jhyde
* @since 21 March, 2002
*/
public class Segment {
private static int nextId = 0; // generator for "id"
final int id; // for debug
private String desc;
/**
* This is set in the load method and is used during the processing of a particular aggregate load.
*/
protected final RolapStar.Column[] columns;
public final RolapStar.Measure measure;
/**
* An array of axes, one for each constraining column, containing the values returned for that constraining column.
*/
public final StarColumnPredicate[] predicates;
protected final RolapStar star;
protected final BitKey constrainedColumnsBitKey;
/**
* List of regions to ignore when reading this segment. This list is populated when a region is flushed. The cells for
* these regions may be physically in the segment, because trimming segments can be expensive, but should still be
* ignored.
*/
protected final List<ExcludedRegion> excludedRegions;
private final int aggregationKeyHashCode;
protected final List<StarPredicate> compoundPredicateList;
private final SegmentHeader segmentHeader;
private static final Logger LOGGER = Logger.getLogger( Segment.class );
/**
* Creates a <code>Segment</code>; it's not loaded yet.
*
* @param star
* Star that this Segment belongs to
* @param measure
* Measure whose values this Segment contains
* @param predicates
* List of predicates constraining each axis
* @param excludedRegions
* List of regions which are not in this segment.
*/
public Segment( RolapStar star, BitKey constrainedColumnsBitKey, RolapStar.Column[] columns,
RolapStar.Measure measure, StarColumnPredicate[] predicates, List<ExcludedRegion> excludedRegions,
final List<StarPredicate> compoundPredicateList ) {
this.id = nextId++;
this.star = star;
this.constrainedColumnsBitKey = constrainedColumnsBitKey;
this.columns = columns;
this.measure = measure;
this.predicates = predicates;
this.excludedRegions = excludedRegions;
this.compoundPredicateList = compoundPredicateList;
final List<BitKey> compoundPredicateBitKeys = compoundPredicateList == null ? null : new AbstractList<BitKey>() {
public BitKey get( int index ) {
return compoundPredicateList.get( index ).getConstrainedColumnBitKey();
}
public int size() {
return compoundPredicateList.size();
}
};
this.aggregationKeyHashCode =
AggregationKey.computeHashCode( constrainedColumnsBitKey, star, compoundPredicateBitKeys );
this.segmentHeader = SegmentBuilder.toHeader( this );
}
/**
* Returns the constrained columns.
*/
public RolapStar.Column[] getColumns() {
return columns;
}
/**
* Returns the star.
*/
public RolapStar getStar() {
return star;
}
/**
* Returns the list of compound predicates.
*/
public List<StarPredicate> getCompoundPredicateList() {
return compoundPredicateList;
}
/**
* Returns the BitKey for ALL columns (Measures and Levels) involved in the query.
*/
public BitKey getConstrainedColumnsBitKey() {
return constrainedColumnsBitKey;
}
private void describe( StringBuilder buf, boolean values ) {
final String sep = Util.nl + " ";
buf.append( printSegmentHeaderInfo( sep ) );
for ( int i = 0; i < columns.length; i++ ) {
buf.append( sep );
buf.append( columns[i].getExpression().getGenericExpression() );
describeAxes( buf, i, values );
}
if ( !excludedRegions.isEmpty() ) {
buf.append( sep );
buf.append( "excluded={" );
int k = 0;
for ( ExcludedRegion excludedRegion : excludedRegions ) {
if ( k++ > 0 ) {
buf.append( ", " );
}
excludedRegion.describe( buf );
}
buf.append( '}' );
}
buf.append( '}' );
}
protected void describeAxes( StringBuilder buf, int i, boolean values ) {
predicates[i].describe( buf );
}
private String printSegmentHeaderInfo( String sep ) {
StringBuilder buf = new StringBuilder();
buf.append( "Segment
buf.append( id );
buf.append( " {" );
buf.append( sep );
buf.append( "measure=" );
buf.append( measure.getExpression() == null ? measure.getAggregator().getExpression( "*" ) : measure
.getAggregator().getExpression( measure.getExpression().getGenericExpression() ) );
return buf.toString();
}
public String toString() {
if ( this.desc == null ) {
StringBuilder buf = new StringBuilder( 64 );
describe( buf, false );
this.desc = buf.toString();
}
return this.desc;
}
/**
* Returns whether a cell value is excluded from this segment.
*/
protected final boolean isExcluded( Object[] keys ) {
// Performance critical: cannot use foreach
final int n = excludedRegions.size();
// noinspection ForLoopReplaceableByForEach
for ( int i = 0; i < n; i++ ) {
ExcludedRegion excludedRegion = excludedRegions.get( i );
if ( excludedRegion.wouldContain( keys ) ) {
return true;
}
}
return false;
}
/**
* Prints the state of this <code>Segment</code>, including constraints and values. Blocks the current thread until
* the segment is loaded.
*
* @param pw
* Writer
*/
public void print( PrintWriter pw ) {
final StringBuilder buf = new StringBuilder();
describe( buf, true );
pw.print( buf.toString() );
pw.println();
}
public List<ExcludedRegion> getExcludedRegions() {
return excludedRegions;
}
SegmentDataset createDataset( SegmentAxis[] axes, boolean sparse, SqlStatement.Type type, int size ) {
if ( sparse ) {
return new SparseSegmentDataset();
} else {
switch ( type ) {
case OBJECT:
case LONG:
case STRING:
return new DenseObjectSegmentDataset( axes, size );
case INT:
return new DenseIntSegmentDataset( axes, size );
case DOUBLE:
case DECIMAL:
return new DenseDoubleSegmentDataset( axes, size );
default:
throw Util.unexpected( type );
}
}
}
public boolean matches( AggregationKey aggregationKey, RolapStar.Measure measure ) {
// Perform high-selectivity comparisons first.
return aggregationKeyHashCode == aggregationKey.hashCode() && this.measure == measure && matchesInternal(
aggregationKey );
}
private boolean matchesInternal( AggregationKey aggKey ) {
return constrainedColumnsBitKey.equals( aggKey.getConstrainedColumnsBitKey() ) && star.equals( aggKey.getStar() )
&& AggregationKey.equal( compoundPredicateList, aggKey.compoundPredicateList );
}
/**
* Definition of a region of values which are not in a segment.
*/
public static interface ExcludedRegion {
/**
* Tells whether this exclusion region would contain the cell corresponding to the keys.
*/
public boolean wouldContain( Object[] keys );
/**
* Returns the arity of this region.
*/
public int getArity();
/**
* Describes this exclusion region in a human readable way.
*/
public void describe( StringBuilder buf );
/**
* Returns an approximation of the number of cells exceluded in this region.
*/
public int getCellCount();
}
public SegmentHeader getHeader() {
return this.segmentHeader;
}
}
// End Segment.java
|
package com.dmdirc.config;
import com.dmdirc.interfaces.ConfigChangeListener;
import com.dmdirc.util.MapList;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* The config manager manages the various config sources for each entity.
*
* @author chris
*/
public class ConfigManager extends ConfigSource implements Serializable,
ConfigChangeListener {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 4;
/** Temporary map for lookup stats. */
private static final Map<String, Integer> stats = new TreeMap<String, Integer>();
/** A list of sources for this config manager. */
private List<Identity> sources;
/** The listeners registered for this manager. */
private final MapList<String, ConfigChangeListener> listeners
= new MapList<String, ConfigChangeListener>();
/** The ircd this manager is for. */
private String ircd;
/** The network this manager is for. */
private String network;
/** The server this manager is for. */
private String server;
/** The channel this manager is for. */
private String channel;
/**
* Creates a new instance of ConfigManager.
*
* @param ircd The name of the ircd for this manager
* @param network The name of the network for this manager
* @param server The name of the server for this manager
*/
public ConfigManager(final String ircd, final String network,
final String server) {
this(ircd, network, server, "<Unknown>");
}
/**
* Creates a new instance of ConfigManager.
*
* @param ircd The name of the ircd for this manager
* @param network The name of the network for this manager
* @param server The name of the server for this manager
* @param channel The name of the channel for this manager
*/
public ConfigManager(final String ircd, final String network,
final String server, final String channel) {
final String chanName = channel + "@" + network;
sources = IdentityManager.getSources(ircd, network, server, chanName);
for (Identity identity : sources) {
identity.addListener(this);
}
this.ircd = ircd;
this.network = network;
this.server = server;
this.channel = chanName;
IdentityManager.addConfigManager(this);
}
/** {@inheritDoc} */
@Override
public String getOption(final String domain, final String option) {
doStats(domain, option);
synchronized (sources) {
for (Identity source : sources) {
if (source.hasOption(domain, option)) {
return source.getOption(domain, option);
}
}
}
throw new IllegalArgumentException("Config option not found: " + domain + "." + option);
}
/** {@inheritDoc} */
@Override
public boolean hasOption(final String domain, final String option) {
doStats(domain, option);
synchronized (sources) {
for (Identity source : sources) {
if (source.hasOption(domain, option)) {
return true;
}
}
}
return false;
}
/**
* Returns the name of all known options.
*
* @return A list of options
*/
public Set<String> getOptions() {
final HashSet<String> res = new HashSet<String>();
synchronized (sources) {
for (Identity source : sources) {
for (String key : source.getOptions()) {
res.add(key);
}
}
}
return res;
}
/**
* Returns the name of all the options in the specified domain. If the
* domain doesn't exist, an empty list is returned.
*
* @param domain The domain to search
* @return A list of options in the specified domain
*/
public List<String> getOptions(final String domain) {
final ArrayList<String> res = new ArrayList<String>();
for (String key : getOptions()) {
if (key.startsWith(domain + ".")) {
res.add(key.substring(domain.length() + 1));
}
}
return res;
}
/**
* Removes the specified identity from this manager.
*
* @param identity The identity to be removed
*/
public void removeIdentity(final Identity identity) {
synchronized (sources) {
identity.removeListener(this);
sources.remove(identity);
}
}
/**
* Called whenever there is a new identity available. Checks if the
* identity is relevant for this manager, and adds it if it is.
* @param identity The identity to be checked
*/
public void checkIdentity(final Identity identity) {
String comp;
switch (identity.getTarget().getType()) {
case IRCD:
comp = ircd;
break;
case NETWORK:
comp = network;
break;
case SERVER:
comp = server;
break;
case CHANNEL:
comp = channel;
break;
case PROFILE:
// We don't want profiles
comp = null;
break;
default:
comp = "";
break;
}
if (comp != null && comp.equalsIgnoreCase(identity.getTarget().getData())) {
synchronized (sources) {
sources.add(identity);
identity.addListener(this);
Collections.sort(sources);
}
}
}
/**
* Returns the name of all domains known by this manager.
*
* @return A list of domains known to this manager
*/
public List<String> getDomains() {
final ArrayList<String> res = new ArrayList<String>();
String domain;
for (String key : getOptions()) {
domain = key.substring(0, key.indexOf('.'));
if (!res.contains(domain)) {
res.add(domain);
}
}
return res;
}
/**
* Retrieves a list of sources for this config manager.
* @return This config manager's sources.
*/
public List<Identity> getSources() {
return new ArrayList<Identity>(sources);
}
/**
* Migrates this ConfigManager from its current configuration to the
* appropriate one for the specified new parameters, firing listeners where
* settings have changed.
*
* @param ircd The new name of the ircd for this manager
* @param network The new name of the network for this manager
* @param server The new name of the server for this manager
* @param channel The new name of the channel for this manager
*/
public void migrate(final String ircd, final String network, final String server,
final String channel) {
final ConfigManager old = new ConfigManager(this.ircd, this.network,
this.server, this.channel.substring(0, this.channel.indexOf('@')));
this.ircd = ircd;
this.network = network;
this.server = server;
this.channel = channel + "@" + network;
for (Identity identity : new ArrayList<Identity>(sources)) {
removeIdentity(identity);
}
sources = IdentityManager.getSources(ircd, network, server, this.channel);
for (Identity identity : sources) {
identity.addListener(this);
}
final List<String> myDomains = getDomains();
for (String domain : myDomains) {
final List<String> myKeys = getOptions(domain);
for (String key : myKeys) {
if (!old.hasOption(domain, key) ||
!old.getOption(domain, key).equals(getOption(domain, key))) {
configChanged(domain, key);
}
}
for (String key : old.getOptions(domain)) {
if (!myKeys.contains(key)) {
configChanged(domain, key);
}
}
}
for (String domain : old.getDomains()) {
if (!myDomains.contains(domain)) {
for (String key : old.getOptions(domain)) {
configChanged(domain, key);
}
}
}
}
/**
* Records the lookup request for the specified domain & option.
*
* @param domain The domain that is being looked up
* @param option The option that is being looked up
*/
protected static void doStats(final String domain, final String option) {
final String key = domain + "." + option;
try {
stats.put(key, 1 + (stats.containsKey(key) ? stats.get(key) : 0));
} catch (NullPointerException ex) {
// JVM bugs ftl.
}
}
/**
* Retrieves the statistic map.
*
* @return A map of config options to lookup counts
*/
public static Map<String, Integer> getStats() {
return stats;
}
/**
* Adds a change listener for the specified domain.
*
* @param domain The domain to be monitored
* @param listener The listener to register
*/
public void addChangeListener(final String domain,
final ConfigChangeListener listener) {
addListener(domain, listener);
}
/**
* Adds a change listener for the specified domain and key.
*
* @param domain The domain of the option
* @param key The option to be monitored
* @param listener The listener to register
*/
public void addChangeListener(final String domain, final String key,
final ConfigChangeListener listener) {
addListener(domain + "." + key, listener);
}
/**
* Removes the specified listener for all domains and options.
*
* @param listener The listener to be removed
*/
public void removeListener(final ConfigChangeListener listener) {
listeners.removeFromAll(listener);
}
/**
* Adds the specified listener to the internal map/list.
*
* @param key The key to use (domain or domain.key)
* @param listener The listener to register
*/
private void addListener(final String key,
final ConfigChangeListener listener) {
listeners.add(key, listener);
}
/** {@inheritDoc} */
@Override
public void configChanged(final String domain, final String key) {
final List<ConfigChangeListener> targets
= new ArrayList<ConfigChangeListener>();
if (listeners.containsKey(domain)) {
targets.addAll(listeners.get(domain));
}
if (listeners.containsKey(domain + "." + key)) {
targets.addAll(listeners.get(domain + "." + key));
}
for (ConfigChangeListener listener : targets) {
listener.configChanged(domain, key);
}
}
}
|
package com.github.davidmoten.rx.jdbc;
import static com.github.davidmoten.rx.jdbc.DatabaseCreator.connectionProvider;
import static com.github.davidmoten.rx.jdbc.DatabaseCreator.createDatabase;
import static com.github.davidmoten.rx.jdbc.DatabaseCreator.db;
import static com.github.davidmoten.rx.jdbc.DatabaseCreator.nextUrl;
import static com.github.davidmoten.rx.jdbc.Util.constant;
import static com.github.davidmoten.rx.jdbc.Util.log;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static rx.Observable.from;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2;
import com.github.davidmoten.rx.jdbc.tuple.Tuple2;
import com.github.davidmoten.rx.jdbc.tuple.Tuple3;
import com.github.davidmoten.rx.jdbc.tuple.Tuple4;
import com.github.davidmoten.rx.jdbc.tuple.Tuple5;
import com.github.davidmoten.rx.jdbc.tuple.Tuple6;
import com.github.davidmoten.rx.jdbc.tuple.Tuple7;
import com.github.davidmoten.rx.jdbc.tuple.TupleN;
public class DatabaseTest {
private static final Logger log = LoggerFactory
.getLogger(DatabaseTest.class);
@Test
public void testOldStyle() {
Connection con = connectionProvider().get();
createDatabase(con);
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement("select name from person where name > ?");
ps.setObject(1, "ALEX");
rs = ps.executeQuery();
List<String> list = new ArrayList<String>();
while (rs.next()) {
list.add(rs.getString(1));
}
assertEquals(asList("FRED", "JOSEPH", "MARMADUKE"), list);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (rs != null)
try {
rs.close();
} catch (SQLException e) {
}
if (ps != null)
try {
ps.close();
} catch (SQLException e) {
}
try {
con.close();
} catch (SQLException e) {
}
}
}
@Test
public void testSimpleExample() {
Observable<String> names = db().select(
"select name from person order by name").getAs(String.class);
// convert the names to a list for unit test
List<String> list = names.toList().toBlockingObservable().single();
log.debug("list=" + list);
assertEquals(asList("FRED", "JOSEPH", "MARMADUKE"), list);
}
@Test
public void testCountQuery() {
int count = db().select("select name from person where name >?")
.parameter("ALEX").get().count().first().toBlockingObservable()
.single();
assertEquals(3, count);
}
@Test
public void testTransactionUsingCount() {
Database db = db();
Func1<? super Integer, Boolean> isZero = new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer t1) {
return t1 == 0;
}
};
db.beginTransaction();
Observable<Integer> existingRows = db
.select("select name from person where name=?")
.parameter("FRED").get().count().filter(isZero);
db.update("insert into person(name,score) values(?,0)")
.parameters(existingRows.map(Util.constant("FRED"))).count();
boolean committed = db.commit().toBlockingObservable().single();
assertTrue(committed);
}
@Test
public void testTransactionOnCommit() {
Database db = db().beginTransaction();
Observable<Integer> updateCount = db
.update("update person set score=?").parameter(99).count();
db.commit(updateCount);
long count = db.select("select count(*) from person where score=?")
.parameter(99).dependsOnLastTransaction().getAs(Long.class)
.toBlockingObservable().single();
assertEquals(3, count);
}
@Test
public void testTransactionOnCommitDoesntOccurUnlessSubscribedTo() {
Database db = db();
db.beginTransaction();
Observable<Integer> u = db.update("update person set score=?")
.parameter(99).count();
db.commit(u);
// note that last transaction was not listed as a dependency of the next
// query
long count = db.select("select count(*) from person where score=?")
.parameter(99).getAs(Long.class).toBlockingObservable()
.single();
assertEquals(0, count);
}
@Test
public void testTransactionOnRollback() {
Database db = db();
db.beginTransaction();
Observable<Integer> updateCount = db
.update("update person set score=?").parameter(99).count();
db.rollback(updateCount);
long count = db.select("select count(*) from person where score=?")
.parameter(99).dependsOnLastTransaction().getAs(Long.class)
.toBlockingObservable().single();
assertEquals(0, count);
}
@Test
public void testUseParameterObservable() {
int count = db().select("select name from person where name >?")
.parameters(Observable.from("ALEX")).get().count().first()
.toBlockingObservable().single();
assertEquals(3, count);
}
@Test
public void testTwoParameters() {
List<String> list = db()
.select("select name from person where name > ? and name < ?")
.parameter("ALEX").parameter("LOUIS").getAs(String.class)
.toList().toBlockingObservable().single();
assertEquals(asList("FRED", "JOSEPH"), list);
}
@Test
public void testTakeFewerThanAvailable() {
int count = db().select("select name from person where name >?")
.parameter("ALEX").get().take(2).count().first()
.toBlockingObservable().single();
assertEquals(2, count);
}
@Test
public void testJdbcObservableCountLettersInAllNames() {
Func1<ResultSet, Integer> countLettersInName = new Func1<ResultSet, Integer>() {
@Override
public Integer call(ResultSet rs) {
try {
return rs.getString("name").length();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
};
int count = Observable
.sumInteger(
db().select("select name from person where name >?")
.parameter("ALEX").get(countLettersInName))
.first().toBlockingObservable().single();
assertEquals(19, count);
}
@Test
public void testTransformToTuple2AndTestActionsPrintln() {
Tuple2<String, Integer> tuple = db()
.select("select name,score from person where name >? order by name")
.parameter("ALEX").getAs(String.class, Integer.class).last()
.toBlockingObservable().single();
assertEquals("MARMADUKE", tuple.value1());
assertEquals(25, (int) tuple.value2());
}
@Test
public void testTransformToTupleN() {
TupleN<String> tuple = db()
.select("select name, lower(name) from person order by name")
.getTupleN(String.class).first().toBlockingObservable()
.single();
assertEquals("FRED", tuple.values().get(0));
assertEquals("fred", tuple.values().get(1));
}
@Test
public void testMultipleSetsOfParameters() {
List<Integer> list = db()
.select("select score from person where name=?")
.parameter("FRED").parameter("JOSEPH").getAs(Integer.class)
.toSortedList().toBlockingObservable().single();
assertEquals(asList(21, 34), list);
}
@Test
public void testNoParams() {
List<Tuple2<String, Integer>> tuples = db()
.select("select name, score from person where name=? order by name")
.getAs(String.class, Integer.class).toList()
.toBlockingObservable().single();
assertEquals(0, tuples.size());
}
@Test
public void testComposition2() {
log.debug("running testComposition2");
Func1<Integer, Boolean> isZero = new Func1<Integer, Boolean>() {
@Override
public Boolean call(Integer count) {
return count == 0;
}
};
Database db = db();
Observable<Integer> existingRows = db
.select("select name from person where name=?")
.parameter("FRED").getAs(String.class).count().filter(isZero);
List<Integer> counts = db
.update("insert into person(name,score) values(?,?)")
.parameters(existingRows).count().toList()
.toBlockingObservable().single();
assertEquals(0, counts.size());
}
@Test
public void testEmptyResultSet() {
int count = db().select("select name from person where name >?")
.parameters(Observable.from("ZZTOP")).get().count().first()
.toBlockingObservable().single();
assertEquals(0, count);
}
@Test
public void testMixingExplicitAndObservableParameters() {
String name = db()
.select("select name from person where name > ? and score < ? order by name")
.parameter("BARRY").parameters(Observable.from(100))
.getAs(String.class).first().toBlockingObservable().single();
assertEquals("FRED", name);
}
@Test
public void testInstantiateDatabaseWithUrl() throws SQLException {
Database db = new Database("jdbc:h2:mem:testa1");
Connection con = db.queryContext().connectionProvider().get();
con.close();
}
@Test
public void testComposition() {
// use composition to find the first person alphabetically with
// a score less than the person with the last name alphabetically
// whose name is not XAVIER. Two threads and connections will be used.
Database db = db();
Observable<Integer> score = db
.select("select score from person where name <> ? order by name")
.parameter("XAVIER").getAs(Integer.class).last();
String name = db
.select("select name from person where score < ? order by name")
.parameters(score).getAs(String.class).first()
.toBlockingObservable().single();
assertEquals("FRED", name);
}
@Test
public void testCompositionTwoLevels() {
Database db = db();
Observable<String> names = db.select(
"select name from person order by name").getAs(String.class);
Observable<String> names2 = db
.select("select name from person where name<>? order by name")
.parameters(names).parameters(names).getAs(String.class);
List<String> list = db.select("select name from person where name>?")
.parameters(names2).getAs(String.class).toList()
.toBlockingObservable().single();
System.out.println(list);
assertEquals(12, list.size());
}
@Test(expected = RuntimeException.class)
public void testSqlProblem() {
String name = db().select("select name from pperson where name >?")
.parameter("ALEX").getAs(String.class).first()
.toBlockingObservable().single();
log.debug(name);
}
@Test(expected = ClassCastException.class)
public void testException() {
Integer name = db().select("select name from person where name >?")
.parameter("ALEX").getAs(Integer.class).first()
.toBlockingObservable().single();
log.debug("name=" + name);
}
@Test
public void testDependsUsingAsynchronousQueriesWaitsForFirstByDelayingCalculation() {
Database db = db();
Observable<Integer> insert = db
.update("insert into person(name,score) values(?,?)")
.parameters("JOHN", 45)
.count()
.zip(Observable.interval(100, TimeUnit.MILLISECONDS),
new Func2<Integer, Long, Integer>() {
@Override
public Integer call(Integer t1, Long t2) {
return t1;
}
});
int count = db.select("select name from person").dependsOn(insert)
.get().count().toBlockingObservable().single();
assertEquals(4, count);
}
@Test
public void testAutoMapWillMapStringToStringAndIntToDouble() {
Person person = db()
.select("select name,score,dob,registered from person order by name")
.autoMap(Person.class).first().toBlockingObservable().single();
assertEquals("FRED", person.getName());
assertEquals(21, person.getScore(), 0.001);
assertNull(person.getDateOfBirth());
}
@Test(expected = RuntimeException.class)
public void testAutoMapCannotFindConstructorWithEnoughParameters() {
db().select(
"select name,score,dob,registered,name from person order by name")
.autoMap(Person.class).first().toBlockingObservable().single();
}
@Test
public void testGetTimestamp() {
Database db = db();
java.sql.Timestamp registered = new java.sql.Timestamp(100);
Observable<Integer> u = db
.update("update person set registered=? where name=?")
.parameter(registered).parameter("FRED").count();
Date regTime = db.select("select registered from person order by name")
.dependsOn(u).getAs(Date.class).first().toBlockingObservable()
.single();
assertEquals(100, regTime.getTime());
}
@Test
public void insertClobAndReadAsString() throws SQLException {
Database db = db();
insertClob(db);
// read clob as string
String text = db.select("select document from person_clob")
.getAs(String.class).first().toBlockingObservable().single();
assertTrue(text.contains("about Fred"));
}
private static void insertClob(Database db) {
int count = db
.update("insert into person_clob(name,document) values(?,?)")
.parameter("FRED")
.parameter(
"A description about Fred that is rather long and needs a Clob to store it")
.count().toBlockingObservable().single();
assertEquals(1, count);
}
private static void insertBlob(Database db) {
int count = db
.update("insert into person_blob(name,document) values(?,?)")
.parameter("FRED")
.parameter(
"A description about Fred that is rather long and needs a Clob to store it"
.getBytes()).count().toBlockingObservable()
.single();
assertEquals(1, count);
}
@Test
public void insertClobAndReadAsReader() throws SQLException, IOException {
Database db = db();
insertClob(db);
// read clob as Reader
String text = db.select("select document from person_clob")
.getAs(Reader.class).map(Util.READER_TO_STRING).first()
.toBlockingObservable().single();
assertTrue(text.contains("about Fred"));
}
@Test
public void insertBlobAndReadAsByteArray() throws SQLException {
Database db = db();
insertBlob(db);
// read clob as string
byte[] bytes = db.select("select document from person_blob")
.getAs(byte[].class).first().toBlockingObservable().single();
assertTrue(new String(bytes).contains("about Fred"));
}
@Test
public void testInsertNull() {
int count = db()
.update("insert into person(name,score,dob) values(?,?,?)")
.parameters("JACK", 42, null).count().toBlockingObservable()
.single();
assertEquals(1, count);
}
@Test
public void testAutoMap() {
TimeZone current = TimeZone.getDefault();
try {
TimeZone.setDefault(TimeZone.getTimeZone("AEST"));
Database db = db();
Date dob = new Date(100);
long now = System.currentTimeMillis();
java.sql.Timestamp registered = new java.sql.Timestamp(now);
Observable<Integer> u = db
.update("update person set dob=?, registered=? where name=?")
.parameter(dob).parameter(registered).parameter("FRED")
.count();
Person person = db
.select("select name,score,dob,registered from person order by name")
.dependsOn(u).autoMap(Person.class).first()
.toBlockingObservable().single();
assertEquals("FRED", person.getName());
assertEquals(21, person.getScore(), 0.001);
// Dates are truncated to start of day
assertEquals(0, (long) person.getDateOfBirth());
assertEquals(now, (long) person.getRegistered());
} finally {
TimeZone.setDefault(current);
}
}
@Test
public void testLastTransactionWithoutTransaction() {
Database db = db();
List<Boolean> list = db.lastTransactionResult().toList()
.toBlockingObservable().single();
assertTrue(list.isEmpty());
}
@Test
public void testTuple3() {
Tuple3<String, Integer, String> tuple = db()
.select("select name,1,lower(name) from person order by name")
.getAs(String.class, Integer.class, String.class).first()
.toBlockingObservable().single();
assertEquals("FRED", tuple.value1());
assertEquals(1, (int) tuple.value2());
assertEquals("fred", tuple.value3());
}
@Test
public void testTuple4() {
Tuple4<String, Integer, String, Integer> tuple = db()
.select("select name,1,lower(name),2 from person order by name")
.getAs(String.class, Integer.class, String.class, Integer.class)
.first().toBlockingObservable().single();
assertEquals("FRED", tuple.value1());
assertEquals(1, (int) tuple.value2());
assertEquals("fred", tuple.value3());
assertEquals(2, (int) tuple.value4());
}
@Test
public void testTuple5() {
Tuple5<String, Integer, String, Integer, String> tuple = db()
.select("select name,1,lower(name),2,name from person order by name")
.getAs(String.class, Integer.class, String.class,
Integer.class, String.class).first()
.toBlockingObservable().single();
assertEquals("FRED", tuple.value1());
assertEquals(1, (int) tuple.value2());
assertEquals("fred", tuple.value3());
assertEquals(2, (int) tuple.value4());
assertEquals("FRED", tuple.value5());
}
@Test
public void testTuple6() {
Tuple6<String, Integer, String, Integer, String, Integer> tuple = db()
.select("select name,1,lower(name),2,name,3 from person order by name")
.getAs(String.class, Integer.class, String.class,
Integer.class, String.class, Integer.class).first()
.toBlockingObservable().single();
assertEquals("FRED", tuple.value1());
assertEquals(1, (int) tuple.value2());
assertEquals("fred", tuple.value3());
assertEquals(2, (int) tuple.value4());
assertEquals("FRED", tuple.value5());
assertEquals(3, (int) tuple.value6());
}
@Test
public void testTuple7() {
Tuple7<String, Integer, String, Integer, String, Integer, Integer> tuple = db()
.select("select name,1,lower(name),2,name,3,4 from person order by name")
.getAs(String.class, Integer.class, String.class,
Integer.class, String.class, Integer.class,
Integer.class).first().toBlockingObservable().single();
assertEquals("FRED", tuple.value1());
assertEquals(1, (int) tuple.value2());
assertEquals("fred", tuple.value3());
assertEquals(2, (int) tuple.value4());
assertEquals("FRED", tuple.value5());
assertEquals(3, (int) tuple.value6());
assertEquals(4, (int) tuple.value7());
}
@Test
public void testAutoMapClob() {
Database db = db();
insertClob(db);
List<PersonClob> list = db
.select("select name, document from person_clob")
.autoMap(PersonClob.class).toList().toBlockingObservable()
.single();
assertEquals(1, list.size());
assertEquals("FRED", list.get(0).getName());
assertTrue(list.get(0).getDocument().contains("rather long"));
}
@Test
public void testAutoMapBlob() {
Database db = db();
insertBlob(db);
List<PersonBlob> list = db
.select("select name, document from person_blob")
.autoMap(PersonBlob.class).toList().toBlockingObservable()
.single();
assertEquals(1, list.size());
assertEquals("FRED", list.get(0).getName());
assertTrue(new String(list.get(0).getDocument())
.contains("rather long"));
}
@Test
public void testCalendarParameter() throws SQLException {
Database db = db();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
Observable<Integer> update = db
.update("update person set registered=? where name=?")
.parameters(cal, "FRED").count();
Timestamp t = db.select("select registered from person where name=?")
.parameter("FRED").dependsOn(update).getAs(Timestamp.class)
.first().toBlockingObservable().single();
assertEquals(0, t.getTime());
}
@Test
public void testDatabaseBuilder() {
Database.builder().connectionProvider(connectionProvider())
.transactionalSchedulerOnCurrentThread()
.nonTransactionalSchedulerOnCurrentThread().build();
}
@Test
public void testConnectionPool() {
ConnectionProviderPooled cp = new ConnectionProviderPooled(nextUrl(),
0, 10);
Database db = new Database(cp);
DatabaseCreator.createDatabase(cp.get());
int count = db.select("select name from person order by name").get()
.count().toBlockingObservable().single();
assertEquals(3, count);
}
@Test
public void testConnectionPoolDoesNotRunOutOfConnectionsWhenQueryRunRepeatedly() {
ConnectionProviderPooled cp = new ConnectionProviderPooled(nextUrl(),
0, 1);
Database db = new Database(cp);
DatabaseCreator.createDatabase(cp.get());
assertCountIs(
100,
db.select("select name from person where name=?")
.parameters(
Observable.range(0, 100).map(
Util.constant("FRED"))).get());
}
@Test
public void testDatabaseBuilderWithPool() {
Database.builder().pooled(nextUrl(), 0, 5).build().close();
}
private static void assertCountIs(int count, Observable<?> o) {
assertEquals(count, (int) o.count().toBlockingObservable().single());
}
@Test
public void testOneConnectionOpenAndClosedAfterOneSelect()
throws InterruptedException {
CountDownConnectionProvider cp = new CountDownConnectionProvider(1, 1);
Database db = new Database(cp);
db.select("select name from person").get().count()
.toBlockingObservable().single();
cp.closesLatch().await();
cp.getsLatch().await();
}
@Test
public void testOneConnectionOpenAndClosedAfterOneUpdate()
throws InterruptedException {
CountDownConnectionProvider cp = new CountDownConnectionProvider(1, 1);
Database db = new Database(cp);
db.update("update person set score=? where name=?")
.parameters(23, "FRED").count().toBlockingObservable().single();
cp.closesLatch().await(60, TimeUnit.SECONDS);
cp.getsLatch().await(60, TimeUnit.SECONDS);
}
@Test
public void testLiftWithParameters() {
int score = from("FRED")
.lift(db().select("select score from person where name=?")
.parameterOperator().getAs(Integer.class))
.toBlockingObservable().single();
assertEquals(21, score);
}
@Test
public void testLiftWithManyParameters() {
int score = Observable
.range(1, 3)
.doOnEach(log())
.map(Util.constant("FRED"))
.lift(db().select("select score from person where name=?")
.parameterOperator().getAs(Integer.class))
.sumInteger(rx.functions.Functions.<Integer> identity())
.toBlockingObservable().single();
assertEquals(3 * 21, score);
}
@Test
public void testDetector() throws InterruptedException {
UnsubscribeDetector<Integer> detector = UnsubscribeDetector
.<Integer> detect();
Observable.range(1, 10).lift(detector).take(1).toBlockingObservable()
.single();
detector.latch().await(30, TimeUnit.SECONDS);
}
@Test
public void testUnsubscribeOfBufferAndFlatMap() throws InterruptedException {
UnsubscribeDetector<Long> detector = UnsubscribeDetector
.<Long> detect();
Observable.interval(10, TimeUnit.MILLISECONDS).lift(detector).buffer(2)
.flatMap(constant(Observable.from(1L))).take(6).toList()
.toBlockingObservable().single();
detector.latch().await(3, TimeUnit.SECONDS);
}
// @Test
public void testParametersAreUnsubscribedIfUnsubscribedPostParameterOperatorLift()
throws InterruptedException {
UnsubscribeDetector<Long> detector = UnsubscribeDetector
.<Long> detect();
int score = Observable
.interval(100, TimeUnit.SECONDS)
.lift(detector)
.doOnEach(log())
.map(Util.constant("FRED"))
.lift(db().select("select score from person where name=?")
.parameterOperator().getAs(Integer.class)).take(3)
.sumInteger(rx.functions.Functions.<Integer> identity())
.toBlockingObservable().single();
assertEquals(3 * 21, score);
detector.latch().await(3, TimeUnit.SECONDS);
}
@Test
public void testLiftWithDependencies() {
Database db = db();
int count = db
.update("update person set score=? where name=?")
.parameters(4, "FRED")
.count()
.lift(db.select("select score from person where name=?")
.parameters("FRED").dependencyOperator()
.getAs(Integer.class)).toBlockingObservable().single();
assertEquals(4, count);
}
@Test
public void test() throws InterruptedException {
}
@Test
public void testTwoConnectionsOpenedAndClosedAfterTwoAsyncSelects()
throws InterruptedException {
CountDownConnectionProvider cp = new CountDownConnectionProvider(2, 2);
Database db = new Database(cp);
db.select("select name from person").get().count()
.toBlockingObservable().single();
db.select("select name from person").get().count()
.toBlockingObservable().single();
cp.getsLatch().await(60, TimeUnit.SECONDS);
cp.closesLatch().await(60, TimeUnit.SECONDS);
}
@Test
public void testTwoConnectionsOpenedAndClosedAfterTwoAsyncUpdates()
throws InterruptedException {
CountDownConnectionProvider cp = new CountDownConnectionProvider(2, 2);
Database db = new Database(cp);
db.update("update person set score=? where name=?")
.parameters(23, "FRED").count().toBlockingObservable().single();
db.update("update person set score=? where name=?")
.parameters(25, "JOHN").count().toBlockingObservable().single();
cp.getsLatch().await(60, TimeUnit.SECONDS);
cp.closesLatch().await(60, TimeUnit.SECONDS);
}
@Test
public void testOneConnectionOpenedAndClosedAfterTwoSelectsWithinTransaction()
throws InterruptedException {
CountDownConnectionProvider cp = new CountDownConnectionProvider(1, 1);
Database db = new Database(cp);
db.beginTransaction();
Observable<Integer> count = db.select("select name from person").get()
.count();
Observable<Integer> count2 = db.select("select name from person").get()
.count();
int result = db.commit(count, count2).count().toBlockingObservable()
.single();
log.info("committed " + result);
cp.getsLatch().await();
log.info("gets ok");
cp.closesLatch().await();
log.info("closes ok");
}
@Test
public void testOneConnectionOpenedAndClosedAfterTwoUpdatesWithinTransaction()
throws InterruptedException {
CountDownConnectionProvider cp = new CountDownConnectionProvider(1, 1);
Database db = new Database(cp);
db.beginTransaction();
Observable<Integer> count = db
.update("update person set score=? where name=?")
.parameters(23, "FRED").count();
Observable<Integer> count2 = db
.update("update person set score=? where name=?")
.parameters(25, "JOHN").count();
int result = db.commit(count, count2).count().toBlockingObservable()
.single();
log.info("committed " + result);
cp.getsLatch().await();
log.info("gets ok");
cp.closesLatch().await();
log.info("closes ok");
}
private static class CountDownConnectionProvider implements
ConnectionProvider {
private final ConnectionProvider cp;
private final CountDownLatch closesLatch;
private final CountDownLatch getsLatch;
CountDownConnectionProvider(int expectedGets, int expectedCloses) {
this.cp = connectionProvider();
DatabaseCreator.createDatabase(cp.get());
this.closesLatch = new CountDownLatch(expectedCloses);
this.getsLatch = new CountDownLatch(expectedGets);
}
CountDownLatch closesLatch() {
return closesLatch;
}
CountDownLatch getsLatch() {
return getsLatch;
}
@Override
public Connection get() {
getsLatch.countDown();
Connection inner = cp.get();
return new CountingConnection(inner, closesLatch);
}
@Override
public void close() {
cp.close();
}
}
static class PersonClob {
private final String name;
private final String document;
public PersonClob(String name, String document) {
this.name = name;
this.document = document;
}
public String getName() {
return name;
}
public String getDocument() {
return document;
}
}
static class PersonBlob {
private final String name;
private final byte[] document;
public PersonBlob(String name, byte[] document) {
this.name = name;
this.document = document;
}
public String getName() {
return name;
}
public byte[] getDocument() {
return document;
}
}
static class Person {
private final String name;
private final double score;
private final Long dateOfBirthEpochMs;
private final Long registered;
Person(String name, double score, Long dateOfBirthEpochMs,
Long registered) {
this.name = name;
this.score = score;
this.dateOfBirthEpochMs = dateOfBirthEpochMs;
this.registered = registered;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
public Long getDateOfBirth() {
return dateOfBirthEpochMs;
}
public Long getRegistered() {
return registered;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Pair [name=");
builder.append(name);
builder.append(", score=");
builder.append(score);
builder.append("]");
return builder.toString();
}
}
}
|
package com.ecyrd.jspwiki.util;
import java.util.Date;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.TextUtil;
import com.ecyrd.jspwiki.WikiEngine;
public final class MailUtil
{
private static final String JAVA_COMP_ENV = "java:comp/env";
private static final String FALSE = "false";
private static final String TRUE = "true";
private static boolean c_useJndi = true;
public static final String PROP_MAIL_AUTH = "mail.smtp.auth";
protected static final Logger log = Logger.getLogger(MailUtil.class);
protected static final String DEFAULT_MAIL_JNDI_NAME = "mail/Session";
protected static final String DEFAULT_MAIL_HOST = "localhost";
protected static final String DEFAULT_MAIL_PORT = "25";
protected static final String DEFAULT_MAIL_TIMEOUT = "5000";
protected static final String DEFAULT_SENDER = "jspwiki@localhost";
protected static final String PROP_MAIL_JNDI_NAME = "jspwiki.mail.jndiname";
protected static final String PROP_MAIL_HOST = "mail.smtp.host";
protected static final String PROP_MAIL_PORT = "mail.smtp.port";
protected static final String PROP_MAIL_ACCOUNT = "mail.smtp.account";
protected static final String PROP_MAIL_PASSWORD = "mail.smtp.password";
protected static final String PROP_MAIL_TIMEOUT = "mail.smtp.timeout";
protected static final String PROP_MAIL_CONNECTION_TIMEOUT = "mail.smtp.connectiontimeout";
protected static final String PROP_MAIL_TRANSPORT = "smtp";
protected static final String PROP_MAIL_SENDER = "mail.from";
protected static final String PROP_MAIL_STARTTLS = "mail.smtp.starttls.enable";
/**
* Private constructor prevents instantiation.
*/
private MailUtil()
{
}
public static void sendMessage( WikiEngine engine, String to, String subject, String content )
throws AddressException, MessagingException
{
String from = engine.getWikiProperties().getProperty( PROP_MAIL_SENDER, DEFAULT_SENDER ).trim();
sendMessage( engine, to, from, subject, content );
}
public static void sendMessage(WikiEngine engine, String to, String from, String subject, String content)
throws MessagingException
{
Properties props = engine.getWikiProperties();
String jndiName = props.getProperty( PROP_MAIL_JNDI_NAME, DEFAULT_MAIL_JNDI_NAME ).trim();
Session session = null;
if (c_useJndi)
{
// Try getting the Session from the JNDI factory first
try
{
session = getJNDIMailSession(jndiName);
c_useJndi = false;
}
catch (NamingException e)
{
// Oops! JNDI factory must not be set up
}
}
// JNDI failed; so, get the Session from the standalone factory
if ( session == null )
{
session = getStandaloneMailSession( props );
}
try
{
// Create and address the message
MimeMessage msg = new MimeMessage( session );
msg.setFrom( new InternetAddress( from ) );
msg.setRecipients( Message.RecipientType.TO, InternetAddress.parse( to, false ) );
msg.setSubject( subject );
msg.setText( content, "UTF-8" );
msg.setSentDate( new Date() );
// Send and log it
Transport.send( msg );
if ( log.isInfoEnabled() )
{
log.info( "Sent e-mail to=" + to + ", subject=\"" + subject
+ "\", jndi=" + ( c_useJndi ? TRUE : FALSE ) );
}
}
catch ( MessagingException e )
{
log.error( e );
throw e;
}
}
/**
* Returns a stand-alone JavaMail Session by looking up the correct
* mail account, password and host from a supplied set of properties.
* If the JavaMail property {@value #PROP_MAIL_ACCOUNT} is set to
* a value that is non-<code>null</code> and of non-zero length, the
* Session will be initialized with an instance of
* {@link javax.mail.Authenticator}.
* @param props the properties that contain mail session properties
* @return the initialized JavaMail Session
*/
protected static Session getStandaloneMailSession( Properties props )
{
// Read the JSPWiki settings from the properties
String host = props.getProperty( PROP_MAIL_HOST, DEFAULT_MAIL_HOST );
String port = props.getProperty( PROP_MAIL_PORT, DEFAULT_MAIL_PORT );
String account = props.getProperty( PROP_MAIL_ACCOUNT );
String password = props.getProperty( PROP_MAIL_PASSWORD );
boolean starttls = TextUtil.getBooleanProperty( props, PROP_MAIL_STARTTLS, true);
boolean useAuthentication = account != null && account.length() > 0;
Properties mailProps = new Properties();
// Set JavaMail properties
mailProps.put( PROP_MAIL_HOST, host );
mailProps.put( PROP_MAIL_PORT, port );
mailProps.put( PROP_MAIL_TIMEOUT, DEFAULT_MAIL_TIMEOUT );
mailProps.put( PROP_MAIL_CONNECTION_TIMEOUT, DEFAULT_MAIL_TIMEOUT );
mailProps.put( PROP_MAIL_STARTTLS, starttls ? TRUE : FALSE );
// Add SMTP authentication if required
Session session = null;
if ( useAuthentication )
{
mailProps.put( PROP_MAIL_AUTH, TRUE );
SmtpAuthenticator auth = new SmtpAuthenticator( account, password );
session = Session.getInstance( mailProps, auth );
}
else
{
session = Session.getInstance( mailProps );
}
if ( log.isDebugEnabled() )
{
String mailServer = host + ":" + port + ", auth=" + ( useAuthentication ? TRUE : FALSE );
log.debug( "JavaMail session obtained from standalone mail factory: " + mailServer );
}
return session;
}
/**
* Returns a JavaMail Session instance from a JNDI container-managed factory.
* @param jndiName the JNDI name for the resource. If <code>null</code>, the default value
* of <code>mail/Session</code> will be used
* @return the initialized JavaMail Session
* @throws NamingException if the Session cannot be obtained; for example, if the factory is not configured
*/
protected static Session getJNDIMailSession( String jndiName ) throws NamingException
{
Session session = null;
try
{
Context initCtx = new InitialContext();
Context ctx = (Context) initCtx.lookup( JAVA_COMP_ENV );
session = (Session) ctx.lookup( jndiName );
}
catch( NamingException e )
{
log.warn( "JavaMail initialization error: " + e.getMessage() );
throw e;
}
if ( log.isDebugEnabled() )
{
log.debug( "JavaMail session obtained from JNDI mail factory: " + jndiName );
}
return session;
}
/**
* Simple {@link javax.mail.Authenticator} subclass that authenticates a user to
* an SMTP server.
* @author Christoph Sauer
*/
protected static class SmtpAuthenticator extends Authenticator
{
private static final String BLANK = "";
private final String m_pass;
private final String m_login;
/**
* Constructs a new SmtpAuthenticator with a supplied username and password.
* @param login the user name
* @param pass the password
*/
public SmtpAuthenticator(String login, String pass)
{
super();
m_login = login == null ? BLANK : login;
m_pass = pass == null ? BLANK : pass;
}
/**
* Returns the password used to authenticate to the SMTP server.
*/
public PasswordAuthentication getPasswordAuthentication()
{
if ( BLANK.equals(m_pass) )
{
return null;
}
return new PasswordAuthentication( m_login, m_pass );
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.