answer
stringlengths
17
10.2M
package org.gbif.api.model.occurrence; import org.gbif.api.jackson.DownloadRequestSerde; import java.util.Collection; import java.util.Collections; import java.util.Set; import javax.annotation.Nullable; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.map.annotate.JsonDeserialize; import com.google.common.base.Joiner; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; /** * Represents a request to download occurrence records. * This is the base class for specific type of downloads: predicate based downloads and SQL downloads.. */ @JsonDeserialize(using = DownloadRequestSerde.class) public abstract class DownloadRequest { private static final String DELIMITER = ","; private static final Joiner COMMA_JOINER = Joiner.on(DELIMITER).skipNulls(); private static final Splitter COMMA_SPLITTER = Splitter.on(DELIMITER).omitEmptyStrings().trimResults(); @JsonProperty("creator") private String creator; @JsonProperty("notification_addresses") private Set<String> notificationAddresses; @JsonProperty("send_notification") private boolean sendNotification; @JsonProperty("format") private DownloadFormat format; /** * Default constructor. */ public DownloadRequest() { // Empty constructor required to create instances from the data access layer. } public DownloadRequest(String creator, Collection<String> notificationAddresses, boolean sendNotification, DownloadFormat format) { this.creator = creator; this.notificationAddresses = notificationAddresses == null ? Collections.emptySet() : ImmutableSet.copyOf(notificationAddresses); this.sendNotification = sendNotification; this.format = format; } /** * @return the user account that initiated the download */ @Nullable public String getCreator() { return creator; } /** * @return set of email addresses for notifications */ @Nullable public Set<String> getNotificationAddresses() { return notificationAddresses; } /** * Returns the notification addresses as single string. The emails are separated by ','. */ @Nullable @JsonIgnore public String getNotificationAddressesAsString() { if (notificationAddresses != null) { return COMMA_JOINER.join(notificationAddresses); } return null; } public void setCreator(String creator) { this.creator = creator; } public void setNotificationAddresses(Set<String> notificationAddresses) { this.notificationAddresses = notificationAddresses; } /** * Sets the notificationAddresses using a single String value that is split by ','. */ public void setNotificationAddressesAsString(String notificationAddressesAsString) { if (notificationAddressesAsString != null) { notificationAddresses = Sets.newHashSet(COMMA_SPLITTER.split(notificationAddressesAsString)); } } public boolean getSendNotification() { return sendNotification; } public void setSendNotification(boolean sendNotification) { this.sendNotification = sendNotification; } public DownloadFormat getFormat() { return format; } /** * This parameter determines the output format of the requested download. */ public void setFormat(DownloadFormat format) { this.format = format; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof DownloadRequest)) { return false; } DownloadRequest that = (DownloadRequest) obj; return Objects.equal(this.creator, that.creator) && Objects.equal(this.notificationAddresses, that.notificationAddresses) && Objects.equal(this.sendNotification, that.sendNotification) && Objects.equal(this.format, that.format); } @Override public int hashCode() { return Objects.hashCode(creator, notificationAddresses, sendNotification, format); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("creator", creator) .add("notificationAddresses", notificationAddresses) .add("emailNotification", sendNotification) .add("format", format).toString(); } }
package org.jactiveresource.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface CollectionName { String value(); }
package org.jtrfp.trcl.gui; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import javax.swing.BoxLayout; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import org.jtrfp.trcl.core.ControllerInput; import org.jtrfp.trcl.core.ControllerInputs; import org.jtrfp.trcl.core.ControllerMapper; import org.jtrfp.trcl.core.ControllerMapping; import org.jtrfp.trcl.core.ControllerSource; import org.jtrfp.trcl.core.InputDevice; import org.jtrfp.trcl.core.MappingListener; import org.jtrfp.trcl.gui.ControllerInputDevicePanel.ControllerConfiguration.ConfEntry; public class ControllerInputDevicePanel extends JPanel { private static final long serialVersionUID = 4252247402423635792L; private final InputDevice inputDevice; private static final String NONE = "[none]"; private final ControllerInputs controllerInputs; private JComboBox<String> destBox; private JTable table; private ControllerMapper controllerMapper; private volatile boolean dispatching = false; private ControllerConfiguration controllerConfiguration; private final Collection<String> monitoringCollection = new MonitorCollection(); private final InputStateFeedbackMonitor inputStateFeedbackMonitor = new InputStateFeedbackMonitor(); public ControllerInputDevicePanel(InputDevice id, ControllerInputs ci, ControllerMapper mapper) { if(id == null) throw new NullPointerException("Passed InputDevice intolerably null."); if(ci == null) throw new NullPointerException("Passed ControllerInputs intolerably null."); if(mapper == null) throw new NullPointerException("Passed ControllerMapper intolerably null."); this.inputDevice = id; this.controllerInputs = ci; this.controllerMapper = mapper; this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); table = new JTable(); for(Columns col:Columns.values()) ((DefaultTableModel)table.getModel()).addColumn(col.getTitle()); for(ControllerSource cs: inputDevice.getControllerSources()) cs.addPropertyChangeListener(inputStateFeedbackMonitor); destBox = new JComboBox<String>(); destBox.addItem(NONE); final TableColumnModel cModel = table.getColumnModel(); cModel.getColumn(Columns.DEST .ordinal()).setCellEditor(new DefaultCellEditor(destBox)); cModel.getColumn(Columns.VALUE .ordinal()).setPreferredWidth(20); cModel.getColumn(Columns.SCALAR.ordinal()).setPreferredWidth(20); cModel.getColumn(Columns.OFFSET.ordinal()).setPreferredWidth(20); table.getModel().addTableModelListener(new ControllerTableModelListener()); mapper.addMappingListener(new ControllerMappingListener(), true); JScrollPane tableScrollPane = new JScrollPane(table); table.setFillsViewportHeight(true); this.add(tableScrollPane); ci.getInputNames().addTarget(monitoringCollection, true); }//end ControllerInputDevicePanel private enum Columns{ SOURCE("Source"), VALUE("Value"), DEST("Destination"), SCALAR("Scalar"), OFFSET("Offset"); private String title; Columns(String title){ this.title=title; } public String getTitle(){ return title; } }//end Columns public static class ControllerConfiguration { private String intendedController = "[unnamed]"; private HashMap<String,ConfEntry> entryMap = new HashMap<String,ConfEntry>(); public ConfEntry getEntry(String controllerSourceName){ ConfEntry result = entryMap.get(controllerSourceName); if( result == null ){ result = new ConfEntry(); result.setName(controllerSourceName); entryMap.put(controllerSourceName, result); } return result; }//end getEntry(...) public static class ConfEntry{ private double scale = 1, offset = 0; private String name = "[unnamed]", dest = NONE; public ConfEntry(){super();} public ConfEntry(String dest, String name, double scale, double offset){ setDest(dest); setName(name); setScale(scale); setOffset(offset); }//end constructor(...) public double getScale() { return scale; } public void setScale(double scale) { this.scale = scale; } public double getOffset() { return offset; } public void setOffset(double offset) { this.offset = offset; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDest() { return dest; } public void setDest(String dest) { this.dest = dest; } }//end ConfEntry public HashMap<String, ConfEntry> getEntryMap() { return entryMap; } public void setEntryMap(HashMap<String, ConfEntry> entryMap) { this.entryMap = entryMap; } public String getIntendedController() { return intendedController; } public void setIntendedController(String intendedController) { this.intendedController = intendedController; } }//end ControllerConfiguration private class MonitorCollection implements Collection<String>{ @Override public int size() { // TODO Auto-generated method stub return 0; } @Override public boolean isEmpty() { // TODO Auto-generated method stub return false; } @Override public boolean contains(Object o) { // TODO Auto-generated method stub return false; } @Override public Iterator<String> iterator() { // TODO Auto-generated method stub return null; } @Override public Object[] toArray() { // TODO Auto-generated method stub return null; } @Override public <T> T[] toArray(T[] a) { // TODO Auto-generated method stub return null; } @Override public boolean add(String item) { destBox.addItem(item); return true; }//end add(...) @Override public boolean remove(Object item) { destBox.removeItem(item); return true; } @Override public boolean containsAll(Collection<?> c) { // TODO Auto-generated method stub return false; } @Override public boolean addAll(Collection<? extends String> c) { // TODO Auto-generated method stub return false; } @Override public boolean removeAll(Collection<?> c) { // TODO Auto-generated method stub return false; } @Override public boolean retainAll(Collection<?> c) { // TODO Auto-generated method stub return false; } @Override public void clear() { destBox.removeAllItems(); destBox.addItem(NONE); }//end clear() }//end MonitorCollection private class ControllerTableModelListener implements TableModelListener{ @Override public void tableChanged(TableModelEvent e) { if(isDispatching()) return; final int row = e.getFirstRow(); if((e.getType()==TableModelEvent.UPDATE || e.getType()==TableModelEvent.INSERT) /*&& e.getSource() != ControllerInputDevicePanel.this */&& e.getColumn() != Columns.VALUE.ordinal()){ final TableModel model = table.getModel(); final String inputString = (String)model.getValueAt(row,Columns.DEST.ordinal()); final String srcString = (String)model.getValueAt(row,Columns.SOURCE.ordinal()); final double scale = Double.parseDouble((String)model.getValueAt(row, Columns.SCALAR.ordinal())); final double offset = Double.parseDouble((String)model.getValueAt(row, Columns.OFFSET.ordinal())); //Update config final ControllerConfiguration config = getControllerConfiguration(); final ConfEntry entry = config.getEntry(srcString); final ControllerSource controllerSource = inputDevice.getSourceByName(srcString); setDispatching(true); if(e.getColumn() == Columns.DEST.ordinal() || e.getType() == TableModelEvent.INSERT){ controllerMapper.unmapControllerSource(controllerSource); if(!inputString.contentEquals(NONE)){ entry.setDest (inputString); //Update the actual settings final ControllerInput controllerInput = controllerInputs.getControllerInput(inputString); controllerMapper.mapControllerSourceToInput(controllerSource, controllerInput, scale, offset); }//end if(!NONE) else config.getEntryMap().remove(srcString);//Remove if routed to NONE }//end if(DEST||INSERT) if(e.getColumn() == Columns.SCALAR.ordinal() || e.getType() == TableModelEvent.INSERT){ entry.setScale (scale); } if(e.getColumn() == Columns.OFFSET.ordinal() || e.getType() == TableModelEvent.INSERT){ entry.setOffset(offset); } setDispatching(false); } else if(e.getType()==TableModelEvent.DELETE){ /* final TableModel model = table.getModel(); final String srcString = (String)model.getValueAt(row,Columns.SOURCE.ordinal()); final ControllerSource controllerSource = inputDevice.getSourceByName(srcString); controllerMapper.unmapControllerSource(controllerSource); */ } }//end tableChanged(...) }//end ControllerTableModelListener private class ControllerMappingListener implements MappingListener<ControllerSource,ControllerMapping>{ @Override public void mapped(ControllerSource key, ControllerMapping value) { fireControllerSourceMapped(key,value); } @Override public void unmapped(ControllerSource key) { fireControllerSourceUnmapped(key); } }//end ControllerMappingListener private void fireControllerSourceUnmapped(ControllerSource cSource){ //Check for relevance to this panel final int row = getRowFor(cSource); if(row==-1) return;//Ignore final TableModel model = table.getModel(); //Update config final ControllerConfiguration config = getControllerConfiguration(); final ConfEntry entry = config.getEntry(cSource.getName()); entry.setDest (NONE); entry.setOffset(0); entry.setScale (1.0); //Set actual settings model.setValueAt(NONE, row, Columns.DEST.ordinal()); //Set scalar model.setValueAt("1.0", row, Columns.SCALAR.ordinal()); //Set offset model.setValueAt("0.0", row, Columns.OFFSET.ordinal()); }//end fireControllerSourceUnmapped() private void fireControllerSourceMapped(ControllerSource cSource, ControllerMapping value){ //Check for relevance to this panel final int row = getRowFor(cSource); if(row==-1) return;//Ignore final TableModel model = table.getModel(); //Set destination model.setValueAt(value.getControllerInput().getName(), row, Columns.DEST.ordinal()); //Set scalar model.setValueAt(value.getScale()+"", row, Columns.SCALAR.ordinal()); //Set offset model.setValueAt(value.getOffset()+"", row, Columns.OFFSET.ordinal()); }//end fireControllerSourceMapped(...) private int getRowFor(ControllerSource cSource){ //Check for relevance to this panel if(cSource.getInputDevice() != inputDevice) return -1; final int col = Columns.SOURCE.ordinal(); final String sourceString = cSource.getName(); int row = -1; final TableModel model = table.getModel(); //Find the row containing this sourceString for(int i=0; i<model.getRowCount(); i++){ if(((String)model.getValueAt(i, col)).contentEquals(sourceString)) row=i; }//end for(model rows) if(row==-1) return -1; //Not found in this table. Ignore. return row; }//end getRowFor(...) private class InputStateFeedbackMonitor implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { final TableModel model = table.getModel(); final int row = getRowFor((ControllerSource)evt.getSource()); if(row!=-1) model.setValueAt(evt.getNewValue()+"", row, Columns.VALUE.ordinal()); } }//end InputStateFeedbackMonitor public boolean isDispatching() { return dispatching; } public void setDispatching(boolean dispatching) { this.dispatching = dispatching; } public InputDevice getInputDevice() { return inputDevice; } public ControllerConfiguration getControllerConfiguration() { return controllerConfiguration; } public void setControllerConfiguration( ControllerConfiguration controllerConfiguration) { if(controllerConfiguration==null) throw new NullPointerException("Controller config intolerably null"); this.controllerConfiguration = controllerConfiguration; clearControllerConfiguration(); applyControllerConfiguration(); } private void clearControllerConfiguration(){ final TableModel model = table.getModel(); for(int ri=0; ri<model.getRowCount(); ri++){ final String srcString = (String)model.getValueAt(ri,Columns.SOURCE.ordinal()); final ControllerSource controllerSource = inputDevice.getSourceByName(srcString); controllerMapper.unmapControllerSource(controllerSource); }//end for(rows) ((DefaultTableModel)table.getModel()).setRowCount(0); } private void applyControllerConfiguration(){ for(ControllerSource cs: inputDevice.getControllerSources()){ final String name = cs.getName(); final ConfEntry entry = getControllerConfiguration().getEntry(name); final double scale = entry.getScale(); final double offset = entry.getOffset(); final String dest = entry.getDest(); ((DefaultTableModel)table.getModel()).addRow(new String[]{name,"?",dest+"",scale+"",offset+""}); }//end for(ControllerSources) }//end applyControllerConfiguration() }//end ControllerInputDevicePanel
package liquibase.datatype.core; import liquibase.database.Database; import liquibase.database.core.*; import liquibase.datatype.DataTypeInfo; import liquibase.datatype.DatabaseDataType; import liquibase.datatype.LiquibaseDataType; @DataTypeInfo(name="nvarchar", aliases = {"java.sql.Types.NVARCHAR", "nvarchar2"}, minParameters = 0, maxParameters = 1, priority = LiquibaseDataType.PRIORITY_DEFAULT) public class NVarcharType extends CharType { @Override public DatabaseDataType toDatabaseDataType(Database database) { if (database instanceof HsqlDatabase || database instanceof PostgresDatabase|| database instanceof DerbyDatabase) { return new DatabaseDataType("VARCHAR", getParameters()); } if (database instanceof OracleDatabase) { return new DatabaseDataType("NVARCHAR2", getParameters()); } if (database instanceof MSSQLDatabase) { if (getParameters() != null && getParameters().length > 0) { Object param1 = getParameters()[0]; if (param1.toString().matches("\\d+")) { if (Long.valueOf(param1.toString()) > 8000) { return new DatabaseDataType("NVARCHAR", "MAX"); } } } return new DatabaseDataType("NVARCHAR", getParameters()); } return super.toDatabaseDataType(database); } }
package org.msgpack.rpc.client.netty; import java.net.ConnectException; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.msgpack.rpc.client.TCPSocket; @ChannelPipelineCoverage("all") public class RPCClientHandler extends SimpleChannelHandler { protected TCPSocket sock; public RPCClientHandler(TCPSocket sock) { super(); this.sock = sock; } @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent ev) { try { sock.onConnected(); } catch (Exception e) { e.printStackTrace(); sock.onConnectFailed(); } } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent ev) { try { sock.onMessageReceived(ev.getMessage()); } catch (Exception e) { e.printStackTrace(); sock.onFailed(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent ev) { Throwable e = ev.getCause(); if (e instanceof ConnectException) sock.onConnectFailed(); else sock.onFailed(); ev.getChannel().close(); ctx.sendUpstream(ev); } }
package org.openhab.binding.heos; import java.util.Set; import org.eclipse.smarthome.core.thing.ThingTypeUID; import org.eclipse.smarthome.core.thing.type.ChannelTypeUID; import com.google.common.collect.Sets; /** * The {@link HeosBinding} class defines common constants, which are * used across the whole binding. * * @author Johannes Einig - Initial contribution */ public class HeosBindingConstants { public static final String BINDING_ID = "heos"; // List of all Bridge Type UIDs public final static ThingTypeUID THING_TYPE_BRIDGE = new ThingTypeUID(BINDING_ID, "bridge"); public final static ThingTypeUID THING_TYPE_PLAYER = new ThingTypeUID(BINDING_ID, "player"); public final static ThingTypeUID THING_TYPE_GROUP = new ThingTypeUID(BINDING_ID, "group"); // List off all Channel Types public final static ChannelTypeUID CH_TYPE_PLAYER = new ChannelTypeUID(BINDING_ID, "ch_player"); public final static ChannelTypeUID CH_TYPE_FAVORIT = new ChannelTypeUID(BINDING_ID, "ch_favorit"); public final static ChannelTypeUID CH_TYPE_GROUP = new ChannelTypeUID(BINDING_ID, "ch_group"); // List of all Channel ids public final static String CH_ID_CONTROL = "Control"; public final static String CH_ID_VOLUME = "Volume"; public final static String CH_ID_MUTE = "Mute"; public final static String CH_ID_UNGROUP = "Ungroup"; public final static String CH_ID_SONG = "Titel"; public final static String CH_ID_ARTIST = "Interpret"; public final static String CH_ID_ALBUM = "Album"; public final static String CH_ID_PLAYER = "Player"; public final static String CH_ID_BUILDGROUP = "BuildGroup"; public final static String CH_ID_DYNGROUPSHAND = "DynamicGroupHandling"; public final static String CH_ID_REBOOT = "Reboot"; public final static String HOST = "ipAddress"; public final static String PLAYER_TYPE = "model"; public final static String NAME = "name"; public final static String USER_NAME = "userName"; public final static String PASSWORD = "password"; public final static String PID = "pid"; public final static String GID = "gid"; public final static String LEADER = "leader"; public final static String FAVORIT_SID = "1028"; public final static String MID = "mid"; public final static String STATE = "state"; public final static String PLAY = "play"; public final static String PAUSE = "pause"; public final static String STOP = "stop"; public final static String ON = "on"; public final static String OFF = "off"; public final static String MUTE = "mute"; public final static String VOLUME = "volume"; public final static String SONG = "song"; public final static String ALBUM = "album"; public final static String ARTIST = "artist"; public static Set<ThingTypeUID> supportedThingTypes() { Set<ThingTypeUID> supportedThings = Sets.newHashSet(THING_TYPE_BRIDGE, THING_TYPE_GROUP, THING_TYPE_PLAYER); return supportedThings; } }
package com.alexstyl.specialdates.images; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.net.Uri; import android.view.View; import android.widget.ImageView; import com.alexstyl.specialdates.BuildConfig; import com.alexstyl.specialdates.addevent.ui.AvatarCameraButtonView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.ImageSize; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.nostra13.universalimageloader.core.imageaware.ImageAware; import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; import com.nostra13.universalimageloader.utils.L; public class ImageLoader { private static final boolean DEBUG = BuildConfig.DEBUG; public static void init(Context context) { ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context) .threadPriority(Thread.NORM_PRIORITY - 2) .threadPoolSize(10) .tasksProcessingOrder(QueueProcessingType.LIFO) .imageDecoder(new NutraBaseImageDecoder(BuildConfig.DEBUG)) .imageDownloader(new ImageDownloader(context)); L.writeLogs(DEBUG); // Initialize ImageLoader with configuration. com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config.build()); } private final DisplayImageOptions displayImageOptions; private final com.nostra13.universalimageloader.core.ImageLoader loader; ImageLoader(DisplayImageOptions circleImageOptions) { this.displayImageOptions = circleImageOptions; loader = UniversalImageLoader.newInstance(); } public static ImageLoader createWidgetThumbnailLoader() { DisplayImageOptions options = UniversalImageLoader.buildWidgetImageOptions(); return new ImageLoader(options); } public static ImageLoader createCircleThumbnailLoader(Resources resources) { DisplayImageOptions options = UniversalImageLoader.buildCircleImageOptions(resources); return new ImageLoader(options); } public static ImageLoader createSquareThumbnailLoader(Resources resources) { DisplayImageOptions options = UniversalImageLoader.buildSquareImageOptions(resources); return new ImageLoader(options); } public void displayThumbnail(Uri imagePath, ImageView imageView) { loader.displayImage(imagePath.toString(), imageView, displayImageOptions); } public void displayThumbnail(Uri imagePath, ImageAware imageView) { loader.displayImage(imagePath.toString(), imageView, displayImageOptions); } public void loadImage(Uri imagePath, AvatarCameraButtonView avatarView, final OnImageLoadedCallback callback) { loader.loadImage(imagePath.toString(), new ImageSize(avatarView.getWidth(), avatarView.getHeight()), new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { callback.onImageLoaded(loadedImage); } }); } public Bitmap loadBitmap(Uri imagePath, int width, int height) { ImageSize imageSize = new ImageSize(width, height); return loader.loadImageSync(imagePath.toString(), imageSize); } public void loadBitmapAsync(Uri imagePath, int size, SimpleImageLoadingListener listener) { ImageSize imageSize = new ImageSize(size, size); loader.loadImage(imagePath.toString(), imageSize, displayImageOptions, listener); } public void resume() { loader.resume(); } public void pause() { loader.pause(); } }
package org.simpleframework.xml.filter; import java.util.Map; /** * The <code>PlatformFilter</code> object makes use of all filter * types this resolves user specified properties first, followed * by system properties, and finally environment variables. This * filter will be the default filter used by most applications as * it can make use of all values within the application platform. * * @author Niall Gallagher */ public class PlatformFilter extends StackFilter { /** * Constructor for the <code>PlatformFilter</code> object. This * adds a filter which can be used to resolve environment * variables followed by one that can be used to resolve system * properties and finally one to resolve user specified values. */ public PlatformFilter() { this(null); } /** * Constructor for the <code>PlatformFilter</code> object. This * adds a filter which can be used to resolve environment * variables followed by one that can be used to resolve system * properties and finally one to resolve user specified values. * * @param map this is a map contain the user mappings */ public PlatformFilter(Map map) { this.push(new EnvironmentFilter()); this.push(new SystemFilter()); this.push(new MapFilter(map)); } }
package com.arellomobile.mvp; import android.app.DialogFragment; import android.app.Fragment; import android.os.Build; import android.os.Bundle; @SuppressWarnings("ConstantConditions") public class MvpDialogFragment extends DialogFragment { private boolean mIsStateSaved; private MvpDelegate<? extends MvpDialogFragment> mMvpDelegate; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getMvpDelegate().onCreate(savedInstanceState); } public void onResume() { super.onResume(); mIsStateSaved = false; getMvpDelegate().onAttach(); } public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mIsStateSaved = true; getMvpDelegate().onSaveInstanceState(outState); getMvpDelegate().onDetach(); } @Override public void onStop() { super.onStop(); getMvpDelegate().onDetach(); } @Override public void onDestroyView() { super.onDestroyView(); getMvpDelegate().onDetach(); getMvpDelegate().onDestroyView(); } @Override public void onDestroy() { super.onDestroy(); if (mIsStateSaved) { mIsStateSaved = false; return; } boolean anyParentIsRemoving = false; if (Build.VERSION.SDK_INT >= 17) { Fragment parent = getParentFragment(); while (!anyParentIsRemoving && parent != null) { anyParentIsRemoving = parent.isRemoving(); parent = parent.getParentFragment(); } } if (isRemoving() || anyParentIsRemoving || getActivity().isFinishing()) { getMvpDelegate().onDestroy(); } } /** * @return The {@link MvpDelegate} being used by this Fragment. */ public MvpDelegate getMvpDelegate() { if (mMvpDelegate == null) { mMvpDelegate = new MvpDelegate<>(this); } return mMvpDelegate; } }
package com.myhoard.app.fragments; import android.app.AlertDialog; import android.content.AsyncQueryHandler; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.view.ContextMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import com.myhoard.app.Managers.UserManager; import com.myhoard.app.R; import com.myhoard.app.activities.ElementActivity; import com.myhoard.app.images.ImageAdapterList; import com.myhoard.app.provider.DataStorage; public class ItemsListFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{ public static final String Selected_Collection_ID = "id"; private static final int DELETE_ID = Menu.FIRST + 1; private static final int SHARE_ID = Menu.FIRST + 3; // Facebook private static final int LOAD_COLLECTION_NAME_AND_DESCRIPTION = 2; private static final int LOAD_COLLECTION_ELEMENTS = 0; private static final String NEW_SEARCH_FRAGMENT_NAME = "SearchFragment"; private static final String SEARCH_COLLECTION_ID = "SearchCollection"; private static final String NEW_FACEBOOK_FRAGMENT_NAME = "FacebookFragment"; private Context mContext; private GridView mGridView; private ImageView mEmptyView; private Long mCollectionID; private ImageAdapterList mImageAdapterList; private TextView mItemsDescription; private TextView mItemsTags; private static TextView sortByNameTabText; private static TextView sortByDateTabText; private static final String LABEL_BY_NAME_ASC = "A-Z"; private static final String LABEL_BY_NAME_DESC = "Z-A"; private static final String LABEL_BY_DATE_ASC = "< DATE"; private static final String LABEL_BY_DATE_DESC = "> DATE"; private static final String DEFAULT_SORT = DataStorage.Items.NAME; private static String sortOrder = DEFAULT_SORT; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_items_list, container, false); mContext = getActivity(); // call the method setHasOptionsMenu, to have access to the menu from the fragment setHasOptionsMenu(true); //Create adapter to adapt data to individual list row mImageAdapterList = new ImageAdapterList(mContext, null, 0); assert v != null; mItemsDescription = (TextView) v.findViewById(R.id.tvItemsListDescription); mItemsTags = (TextView)v.findViewById(R.id.tvItemsListTags); mEmptyView = (ImageView)v.findViewById(R.id.imageViewEmptyList); mItemsDescription.setVisibility(View.INVISIBLE); mItemsTags.setVisibility(View.INVISIBLE); mEmptyView.setVisibility(View.INVISIBLE); return v; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); // currently moved to onResume() //setSortTabs(); mGridView = (GridView) view.findViewById(R.id.gvItemsList); getLoaderManager().initLoader(LOAD_COLLECTION_ELEMENTS, null, this); bindData(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // retrieving data from CollectionsListFragment Bundle bundle = this.getArguments(); mCollectionID = bundle.getLong(Selected_Collection_ID); getLoaderManager().initLoader(LOAD_COLLECTION_NAME_AND_DESCRIPTION, null, this); mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent in = new Intent(getActivity(), ElementActivity.class); in.putExtra("elementId",id); startActivity(in); } }); registerForContextMenu(mGridView); } private void setSortTabs() { //getting the action bar from the MainActivity final ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar(); //adding tabs to the action bar actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); //tab sort by name ActionBar.Tab tabSortByName = actionBar.newTab(); tabSortByName.setCustomView(R.layout.sort_tab); sortByNameTabText = (TextView) tabSortByName.getCustomView().findViewById(R.id.tab_text); setSelectedTabByNameText(LABEL_BY_NAME_ASC); ActionBar.TabListener sortByNameTabListener = new ActionBar.TabListener() { @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { sortByName(); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { sortByNameTabUnselected(); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { sortByName(); } }; tabSortByName.setTabListener(sortByNameTabListener); actionBar.addTab(tabSortByName); //tab sort by date ActionBar.Tab tabSortByDate = actionBar.newTab(); tabSortByDate.setCustomView(R.layout.sort_tab); sortByDateTabText = (TextView) tabSortByDate.getCustomView().findViewById(R.id.tab_text); setUnselectedTabByDateText(LABEL_BY_DATE_ASC); ActionBar.TabListener sortByDateTabListener = new ActionBar.TabListener() { @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { sortByDate(); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { sortByDateTabUnselected(); } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { sortByDate(); } }; tabSortByDate.setTabListener(sortByDateTabListener); actionBar.addTab(tabSortByDate); } private void resetActionBarNavigationMode() { //getting the action bar from the MainActivity final ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar(); actionBar.removeAllTabs(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); } @Override public void onResume() { super.onResume(); getLoaderManager().restartLoader(LOAD_COLLECTION_ELEMENTS, null, this); setSortTabs(); } @Override public void onStop() { super.onStop(); resetActionBarNavigationMode(); } @Override public void onDestroyView() { super.onDestroyView(); mImageAdapterList.mImageLoader.clearCache(); } @Override public void onPrepareOptionsMenu(Menu menu) { UserManager userManager = UserManager.getInstance(); MenuItem item; if (userManager.isLoggedIn()) { item = menu.findItem(R.id.action_login); if(item!=null) item.setTitle(R.string.logout); } else { item = menu.findItem(R.id.action_login); if(item!=null) item.setTitle(R.string.Login); } super.onPrepareOptionsMenu(menu); } //create options menu with a MenuInflater to have all needed options visible in this fragment @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { menu.clear(); inflater.inflate(R.menu.item_list, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { Bundle b = new Bundle(); Fragment newFragment; FragmentTransaction transaction; switch(item.getItemId()) { case R.id.action_search: newFragment = new SearchFragment(); transaction = getFragmentManager().beginTransaction(); // Add arguments to opened fragment element b.putLong(SEARCH_COLLECTION_ID,mCollectionID); newFragment.setArguments(b); // Replace whatever is in the fragment_container view with this fragment, // and add the transaction to the back stack transaction.replace(R.id.container, newFragment, NEW_SEARCH_FRAGMENT_NAME); transaction.addToBackStack(NEW_SEARCH_FRAGMENT_NAME); // Commit the transaction transaction.commit(); break; case R.id.action_new_element: Intent in = new Intent(getActivity(),ElementActivity.class); in.putExtra("categoryId",mCollectionID); startActivity(in); break; } return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); int groupId = 0; menu.add(groupId, DELETE_ID, DELETE_ID, R.string.menu_delete); menu.add(groupId, SHARE_ID, SHARE_ID, R.string.menu_share); // Sharing on FB } @Override public boolean onContextItemSelected(MenuItem item) { final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { // Sharing item from list case SHARE_ID: if(info!=null) { newFacebookShareFragment(info.id); } return true; case DELETE_ID: new AlertDialog.Builder(getActivity()) .setTitle(mContext.getString(R.string.edit_colection_dialog_title)) .setMessage(mContext.getString(R.string.edit_colection_dialog_message)) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (info != null) { deleteElement(info.id); } } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Do nothing. } }).show(); return true; } return super.onContextItemSelected(item); } private void deleteElement(long id){ ContentValues values = new ContentValues(); values.put(DataStorage.Items.DELETED,true); AsyncQueryHandler asyncHandler = new AsyncQueryHandler(getActivity().getContentResolver()) { }; asyncHandler.startUpdate(0,null,DataStorage.Items.CONTENT_URI,values,DataStorage.Items._ID + " = ?", new String[]{String.valueOf(id)}); getLoaderManager().restartLoader(LOAD_COLLECTION_ELEMENTS, null, this); bindData(); } private void bindData() { mGridView.setAdapter(mImageAdapterList); } // creates a new loader after initLoader() call @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { CursorLoader cursorLoader = null; String selection; switch(i){ //Get all elements from collection case LOAD_COLLECTION_ELEMENTS: selection = String.format("%s = %s and %s!=%d and (%s=%d or %s is null)",mCollectionID,DataStorage.Items.ID_COLLECTION, DataStorage.Items.TABLE_NAME+"."+DataStorage.Items.DELETED,1, DataStorage.Media.AVATAR,1,DataStorage.Media.AVATAR); cursorLoader = new CursorLoader(mContext, DataStorage.Items.CONTENT_URI, new String[]{DataStorage.Items.NAME, DataStorage.Media.FILE_NAME, DataStorage.Items.TABLE_NAME + "." + DataStorage.Items._ID,DataStorage.Items.DESCRIPTION}, selection, null, sortOrder); break; //Get name and description of elements collection case LOAD_COLLECTION_NAME_AND_DESCRIPTION: selection = String.format("%s = %s",mCollectionID,DataStorage.Collections._ID); cursorLoader = new CursorLoader(mContext, DataStorage.Collections.CONTENT_URI, new String[]{DataStorage.Collections.DESCRIPTION,DataStorage.Collections.TAGS,DataStorage.Collections.NAME}, selection, null, null); break; } return cursorLoader; } @Override public void onLoadFinished(Loader loader, Cursor data) { if(loader.getId()==LOAD_COLLECTION_NAME_AND_DESCRIPTION){ data.moveToFirst(); mItemsDescription.setText(data.getString(0)); mItemsTags.setText(data.getString(1)); getActivity().setTitle(data.getString(2)); } else { if(data.getCount()==0){ mItemsDescription.setVisibility(View.INVISIBLE); mItemsTags.setVisibility(View.INVISIBLE); mEmptyView.setVisibility(View.VISIBLE); } else{ mItemsDescription.setVisibility(View.VISIBLE); mItemsTags.setVisibility(View.VISIBLE); mEmptyView.setVisibility(View.INVISIBLE); } mImageAdapterList.swapCursor(data); } } @Override public void onLoaderReset(Loader loader) { if(loader.getId()!=LOAD_COLLECTION_NAME_AND_DESCRIPTION) { mImageAdapterList.swapCursor(null); } } private void sortByName() { String sortByNameAscending = DataStorage.Items.NAME + " ASC"; if (sortOrder.equals(sortByNameAscending)) { sortOrder = DataStorage.Items.NAME + " DESC"; setSelectedTabByNameText(LABEL_BY_NAME_DESC); } else { sortOrder = sortByNameAscending; setSelectedTabByNameText(LABEL_BY_NAME_ASC); } getLoaderManager().restartLoader(0, null, this); } private void sortByDate() { String sortByDateAscending = DataStorage.Items.TABLE_NAME + "." + DataStorage.Items.CREATED_DATE + " ASC"; if (sortOrder.equals(sortByDateAscending)) { sortOrder = DataStorage.Items.TABLE_NAME + "." + DataStorage.Items.CREATED_DATE + " DESC"; setSelectedTabByDateText(LABEL_BY_DATE_DESC); } else { sortOrder = sortByDateAscending; setSelectedTabByDateText(LABEL_BY_DATE_ASC); } getLoaderManager().restartLoader(0, null, this); } private void sortByNameTabUnselected() { setUnselectedTabByNameText(LABEL_BY_NAME_ASC); sortOrder = DEFAULT_SORT; } private void sortByDateTabUnselected() { setUnselectedTabByDateText(LABEL_BY_DATE_ASC); sortOrder = DEFAULT_SORT; } private void setSelectedTabByNameText(String text) { sortByNameTabText.setTextColor(getResources().getColor(R.color.selected_tab_text_color)); sortByNameTabText.setText(text); } private void setSelectedTabByDateText(String text) { sortByDateTabText.setTextColor(getResources().getColor(R.color.selected_tab_text_color)); sortByDateTabText.setText(text); } private void setUnselectedTabByNameText(String text) { sortByNameTabText.setTextColor(getResources().getColor(R.color.black)); sortByNameTabText.setText(text); } private void setUnselectedTabByDateText(String text) { sortByDateTabText.setTextColor(getResources().getColor(R.color.black)); sortByDateTabText.setText(text); } private void newFacebookShareFragment(long id) { Fragment newFragment = new FacebookItemsToShare(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); Bundle bundle = new Bundle(); bundle.putLong(FacebookItemsToShare.ITEM_ID,id); newFragment.setArguments(bundle); transaction.replace(R.id.container,newFragment,NEW_FACEBOOK_FRAGMENT_NAME); transaction.addToBackStack(NEW_FACEBOOK_FRAGMENT_NAME); transaction.commit(); } }
package se.kits.gakusei.controller; import java.util.*; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.annotation.Cacheable; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import se.kits.gakusei.content.model.Lesson; import se.kits.gakusei.content.model.Nugget; import se.kits.gakusei.content.model.UserLesson; import se.kits.gakusei.content.repository.LessonRepository; import se.kits.gakusei.content.repository.UserLessonRepository; import se.kits.gakusei.util.QuestionHandler; @RestController public class QuestionController { private LessonRepository lessonRepository; private QuestionHandler questionHandler; private UserLessonRepository userLessonRepository; @Value("${gakusei.questions-quantity}") private int quantity; @Autowired public QuestionController( LessonRepository lessonRepository, QuestionHandler questionHandler, UserLessonRepository userLessonRepository ) { this.lessonRepository = lessonRepository; this.questionHandler = questionHandler; this.userLessonRepository = userLessonRepository; } @RequestMapping( value = "/api/questions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE ) ResponseEntity<List<HashMap<String, Object>>> getQuestionsFromLesson( @RequestParam(value = "lessonName") String lessonName, @RequestParam(value = "lessonType", defaultValue = "vocabulary") String lessonType, @RequestParam(name = "questionType", defaultValue = "reading") String questionType, @RequestParam(name = "answerType", defaultValue = "swedish") String answerType, @RequestParam(name = "username") String username, @RequestParam( name = "spacedRepetition", required = false, defaultValue = "false" ) boolean spacedRepetition ) { List<HashMap<String, Object>> questions; if (!lessonName.equals("Favoriter")) { questions = getCachedQuestionsFromLesson( lessonName, lessonType, questionType, answerType, username, spacedRepetition ); //wrongAnswers(username, lessonType, questionType, answerType); } else { questions = getCachedQuestionsFromFavoriteLesson( lessonType, questionType, answerType, username, spacedRepetition ); } return questions.isEmpty() ? new ResponseEntity<>( HttpStatus.INTERNAL_SERVER_ERROR ) : new ResponseEntity<>(questions, HttpStatus.OK); } private List<HashMap<String, Object>> getCachedQuestionsFromFavoriteLesson( String lessonType, String questionType, String answerType, String username, boolean spacedRepetition ) {//get all favorites, for each get unanswered and hard ones List< Lesson > favoriteLessons = userLessonRepository.findUsersStarredLessons( username ).stream().map(UserLesson::getLesson).collect(Collectors.toList()); List<Nugget> favoriteNuggets; if (spacedRepetition) { List<Nugget> retentionNuggets = favoriteLessons.stream().map( lesson -> lessonRepository.findNuggetsByRetentionDate( username, lesson.getName() ) ).flatMap(List::stream).collect(Collectors.toList()); List<Nugget> unansweredRetentionNuggets = favoriteLessons.stream( ).map( lesson -> lessonRepository.findUnansweredRetentionNuggets( username, lesson.getName() ) ).flatMap(List::stream).collect(Collectors.toList()); favoriteNuggets = questionHandler.chooseRetentionNuggets( retentionNuggets, unansweredRetentionNuggets, quantity ); } else { List<Nugget> allLessonNuggets; if (!lessonType.equals("grammar")) { allLessonNuggets = favoriteLessons.stream().map( lesson -> cachedFindNuggets(lesson.getName()) ).flatMap(List::stream).collect(Collectors.toList()); } else { allLessonNuggets = favoriteLessons.stream().map( lesson -> cachedFindVerbNuggets(lesson.getName()) ).flatMap(List::stream).collect(Collectors.toList()); } List<Nugget> unansweredNuggets = favoriteLessons.stream().map( lesson -> lessonRepository.findUnansweredNuggets( username, lesson.getName() ) ).flatMap(List::stream).collect(Collectors.toList()); List<Nugget> nuggetsWithLowSuccessrate = favoriteLessons.stream( ).map( lesson -> lessonRepository.findNuggetsBySuccessrate( username, lesson.getName() ) ).flatMap(List::stream).collect(Collectors.toList()); favoriteNuggets = questionHandler.chooseNuggets( nuggetsWithLowSuccessrate, unansweredNuggets, allLessonNuggets, quantity ); } if (lessonType.equals("grammar")) { return questionHandler.createGrammarQuestions( lessonRepository.findByName(null), favoriteNuggets, questionType, answerType ); //TODO: Fix favorite-mode for grammar questions. } else { return questionHandler.createQuestions( favoriteNuggets, questionType, answerType ); } } private List<HashMap<String, Object>> getCachedQuestionsFromLesson( String lessonName, String lessonType, String questionType, String answerType, String username, boolean spacedRepetition ) { List< Nugget > nuggetsWithLowSuccessrate = lessonRepository.findNuggetsBySuccessrate( username, lessonName ); List<Nugget> unansweredNuggets = lessonRepository.findUnansweredNuggets( username, lessonName ); List< Nugget > retentionNuggets = lessonRepository.findNuggetsByRetentionDate( username, lessonName ); List< Nugget > unansweredRetentionNuggets = lessonRepository.findUnansweredRetentionNuggets( username, lessonName ); List<Nugget> allLessonNuggets; if (lessonType.equals("grammar")) { allLessonNuggets = cachedFindVerbNuggets(lessonName); } else { allLessonNuggets = cachedFindNuggets(lessonName); } List<Nugget> nuggets; if (spacedRepetition) { nuggets = questionHandler.chooseRetentionNuggets( retentionNuggets, unansweredRetentionNuggets, quantity ); } else { nuggets = questionHandler.chooseNuggets( nuggetsWithLowSuccessrate, unansweredNuggets, allLessonNuggets, quantity ); } if (lessonType.equals("grammar")) { return questionHandler.createGrammarQuestions( lessonRepository.findByName(lessonName), nuggets, questionType, answerType ); } else { if (spacedRepetition) { return questionHandler.createSpacedRepetitionQuestions( nuggets, allLessonNuggets, questionType, answerType ); } else { return questionHandler.createQuestions( nuggets, questionType, answerType ); } } } @Cacheable("otherNuggets") public List<Nugget> cachedFindNuggets(String lessonName) { return lessonRepository.findByName(lessonName).getNuggets(); } @Cacheable("verbNuggets") public List<Nugget> cachedFindVerbNuggets(String lessonName) { return lessonRepository.findVerbNuggets( lessonRepository.findByName(lessonName).getId() ); } @RequestMapping( value = "/api/wrongquestions", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE ) ResponseEntity<List<HashMap<String, Object>>> createWrongAnswersQuestions( @RequestParam(value = "lessonType") String lessonType, @RequestParam(value = "questionType") String questionType, @RequestParam(value = "answerType") String answerType, @RequestParam(value = "userName") String userName){ List<HashMap<String, Object>> questions; questions = wrongAnswers(userName, lessonType, questionType, answerType); return questions.isEmpty() ? new ResponseEntity<>( HttpStatus.NO_CONTENT ) : new ResponseEntity<>(questions, HttpStatus.OK); } private List<HashMap<String, Object>> wrongAnswers(String userName, String lessonType, String questionType, String answerType){ return questionHandler.wrongAnswers(userName, lessonType, questionType, answerType); } }
package seedu.todoList.model.task.attributes; import seedu.todoList.commons.exceptions.IllegalValueException; public class Priority { public static final String MESSAGE_PRIORITY_CONSTRAINTS = "Priority should only contain 1, 2 or 3\n" + "1 is HIGH, 2 is MEDIUM , 3 is LOW"; public static final String PRIORITY_VALIDATION_REGEX = "^[1-3|HIGH|MEDIUM|LOW]+$"; public final String priority; public String level = "HIGH"; public final String savePriority; public Priority(String priority) throws IllegalValueException { assert priority != null; priority = priority.trim(); savePriority = priority.trim(); if (!isValidPriority(priority)) { throw new IllegalValueException(MESSAGE_PRIORITY_CONSTRAINTS); } switch(priority){ case "1": level = "HIGH"; break; case "2": level = "MEDIUM"; break; case "3": level = "LOW"; break; case "HIGH": level = "HIGH"; break; case "MEDIUM": level = "MEDIUM"; break; case "LOW": level = "LOW"; break; } this.priority = level; } /** * Returns true if a given string is a valid priority value. */ public static boolean isValidPriority(String test) { return test.matches(PRIORITY_VALIDATION_REGEX); } @Override public String toString() { return priority; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Priority // instanceof handles nulls && this.priority == (((Priority) other).priority)); // state check } @Override public int hashCode() { return priority.hashCode(); } }
package sk.ics.upjs.todo.dao; import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Properties; import org.springframework.jdbc.core.JdbcTemplate; import sk.ics.upjs.todo.entity.Notifikacia; import sk.ics.upjs.todo.rowmappery.NotifikaciaRowMapper; public class DatabazovyNotifikaciaDao implements NotifikaciaDao { private final JdbcTemplate jdbcTemplate; private static final NotifikaciaRowMapper mapovacNotifikacii = new NotifikaciaRowMapper(); private static final String nazovTabulky = "NOTIFIKACIE"; /** * Konstruktor, ktory si sam vyrobi JdbcTemplate - kvoli tomu, aby sme na * serveri nepotrebovali Factory */ public DatabazovyNotifikaciaDao() { jdbcTemplate = new JdbcTemplate(dataSource()); } /** * UlohaDao vyuziva NotifikaciaDao, a tak urobime aj taky konstruktor, ktory * vie pouzit aj jdbcTemplate z Factory * * @param jdbcTemplate */ public DatabazovyNotifikaciaDao(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } /** * Vsetky notifikacie joinuje aj s udajmi o ulohe a pouzivatelovi, aby sme * mali vsetky informacie pre odoslanie emailu * * @return zoznam vsetkych notifikacii */ @Override public List<Notifikacia> dajVsetkyNotifikacie() { return jdbcTemplate.query("SELECT * FROM " + nazovTabulky + " n \n" + " JOIN ULOHY u ON n.id_ulohy = u.uloha_id \n" + " JOIN UZIVATELIA p ON u.vlastnik = p.Meno \n", mapovacNotifikacii); } /** * Prida notifikaciu do databazy * * @param idUlohy id ulohy, na ktoru sa viaze notifikacia */ @Override public void pridajNotifikaciu(long idUlohy) { // pri uprave ulohy tiez vkladame notifikaciu, lebo sa mohlo stat, ze uz // bola odoslana, ale pouzivatel zmenil cas ulohy a bude ju treba poslat znovu, // preto najprv vymazeme tu, ktora uz mozno existuje a nahradime ju novou vymazNotifikaciu(idUlohy); String sqlNotifikacia = "INSERT INTO " + nazovTabulky + " \n" + "(id_ulohy)\n" + "VALUES(?)\n"; jdbcTemplate.update(sqlNotifikacia, idUlohy); } /** * Vymaze notifikaciu z databazy * * @param idUlohy id ulohy, na ktoru sa viaze notifikacia */ @Override public void vymazNotifikaciu(long idUlohy) { String sqlNotifikacia = "DELETE FROM " + nazovTabulky + " \n" + "WHERE id_ulohy = ?"; jdbcTemplate.update(sqlNotifikacia, idUlohy); } /** * Pri behu na serveri by bolo zbytocne pouzivat Factory, tak si vytvorime * novy DataSource * * @return dataSource */ private MysqlDataSource dataSource() { Properties properties = getProperties(); MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setURL((String) properties.get("dataServer")); dataSource.setUser((String) properties.get("dataLogin")); dataSource.setPassword((String) properties.get("dataPass")); return dataSource; } /** * Vrati properties pre pripojenie k databaze a na email * @return */ private Properties getProperties() { try { String propertiesFile; propertiesFile = "/home/todo/todo.properties"; InputStream in; try { // ak sme tu, tak sme u Martina in = new FileInputStream(propertiesFile); } catch (FileNotFoundException e1) { // ak sme tu, tak sme u Alice alebo na serveri // skusime najprv server propertiesFile = "~/todo/todo.properties"; } try { // ak sme tu, tak sme na serveri in = new FileInputStream(propertiesFile); } catch (FileNotFoundException e2) { // ak sme tu, tak sme u Alice propertiesFile = "C:/todo/todo.properties"; } in = new FileInputStream(propertiesFile); Properties properties = new Properties(); properties.load(in); return properties; } catch (IOException e) { throw new IllegalStateException("Nenašiel sa konfiguračný súbor!"); } } }
package sk.mrtn.library.client.storage; import com.google.gwt.logging.client.LogConfiguration; import com.google.gwt.storage.client.Storage; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; public class BrowserStorage implements IStorage { private String reference; private Storage storage; private Map<String ,String> codeStorage; public BrowserStorage(){ this.storage = Storage.getLocalStorageIfSupported(); if (this.storage == null) { if (LogConfiguration.loggingIsEnabled()) { Logger.getLogger("common").warning("local storage not supported"); } this.storage = Storage.getSessionStorageIfSupported(); } if (this.storage == null) { if (LogConfiguration.loggingIsEnabled()) { Logger.getLogger("common").severe("session storage not supported, IStorage disabled"); } this.codeStorage = new HashMap<>(); } } @Override public void clear() { if (this.storage != null) { this.storage.clear(); } else { this.codeStorage = new HashMap<>(); } } @Override public String getItem(String key) { if (this.storage != null) { return this.storage.getItem(this.reference+key); } else { return this.codeStorage.get(this.reference+key); } } @Override public void initialize(String reference) { Logger.getLogger("common").finest("Browser storage initiated, reference: "+reference); this.reference = reference; if (this.reference == null) { this.reference = ""; } } @Override public void removeItem(String key) { if (this.storage != null) { this.storage.removeItem(this.reference+key); } else { this.codeStorage.remove(this.reference+key); } } @Override public void setItem(String key, String data) { if (this.storage != null) { this.storage.setItem(this.reference+key, data); } else { this.codeStorage.put(this.reference+key, data); } } }
package uk.ac.cam.cl.dtg.teaching.api; import java.util.Set; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.QueryParam; import javax.ws.rs.core.UriBuilder; import org.jboss.resteasy.client.ClientRequestFactory; import org.jboss.resteasy.client.ClientResponseFailure; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public interface NotificationApi { // Get @GET @Path("/api/notifications") public GetNotification getNotification(@QueryParam("offset") int offset, @QueryParam("limit") int limit, @QueryParam("section") String section, @QueryParam("foreignId") String foreignId, // Authentication @QueryParam("userId") String userId, @QueryParam("key") String key); public static class GetNotification { private int limit; private int offset; private int total; private boolean read; private User user; private String section; private String foreignId; private Set<Notification> notifications; private String error; private GetData data; private GetFormError formErrors; // Setters and getters public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public boolean isRead() { return read; } public void setRead(boolean read) { this.read = read; } public Object getUser() { return user; } public void setUser(User user) { this.user = user; } public String getSection() { return section; } public void setSection(String section) { this.section = section; } public Set<Notification> getNotifications() { return notifications; } public void setNotifications(Set<Notification> notifications) { this.notifications = notifications; } public String getError() { return error; } public void setError(String error) { this.error = error; } public GetData getData() { return data; } public void setData(GetData data) { this.data = data; } public String getForeignId() { return foreignId; } public void setForeignId(String foreignId) { this.foreignId = foreignId; } public GetFormError getFormErrors() { return formErrors; } public void setFormErrors(GetFormError formErrors) { this.formErrors = formErrors; } } public static class Notification { private int id; private boolean read; private String user; private String notification_id; private String message; private String section; private String link; private String timestamp; // Setters and getters public int getId() { return id; } public void setId(int id) { this.id = id; } public boolean isRead() { return read; } public void setRead(boolean read) { this.read = read; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getNotification_id() { return notification_id; } public void setNotification_id(String notification_id) { this.notification_id = notification_id; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getSection() { return section; } public void setSection(String section) { this.section = section; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } } public static class GetFormError { private String[] limit; private String[] offset; private String[] section; private String[] foreignId; public String[] getLimit() { return limit; } public void setLimit(String[] limit) { this.limit = limit; } public String[] getOffset() { return offset; } public void setOffset(String[] offset) { this.offset = offset; } public String[] getSection() { return section; } public void setSection(String[] section) { this.section = section; } public String[] getForeignId() { return foreignId; } public void setForeignId(String[] foreignId) { this.foreignId = foreignId; } } public static class GetData { private String offset; private String limit; private String section; private String foreignId; public String getOffset() { return offset; } public void setOffset(String offset) { this.offset = offset; } public String getLimit() { return limit; } public void setLimit(String limit) { this.limit = limit; } public String getSection() { return section; } public void setSection(String section) { this.section = section; } public String getForeignId() { return foreignId; } public void setForeignId(String foreignId) { this.foreignId = foreignId; } } public static class User { private String crsid; private String name; // Setters and getters public String getCrsid() { return crsid; } public void setCrsid(String crsid) { this.crsid = crsid; } public String getName() { return name; } public void setName(String name) { this.name = name; } } // Create @POST @Path("/api/notifications") public CreateNotification createNotification( @FormParam("message") String message, @FormParam("section") String section, @FormParam("link") String link, @FormParam("users") String users, @FormParam("foreignId") String foreignId, // Authentication @QueryParam("key") String key); public static class CreateNotification { private String redirectTo; private String error; private CreateData data; private CreateFormError formErrors; // Setters and getters public String getRedirectTo() { return redirectTo; } public void setRedirectTo(String redirectTo) { this.redirectTo = redirectTo; } public String getError() { return error; } public void setError(String error) { this.error = error; } public CreateData getData() { return data; } public void setData(CreateData data) { this.data = data; } public CreateFormError getFormErrors() { return formErrors; } public void setFormErrors(CreateFormError formErrors) { this.formErrors = formErrors; } } public static class CreateFormError { private String[] message; private String[] users; private String[] link; private String[] section; // Setters and getters public String[] getMessage() { return message; } public void setMessage(String[] message) { this.message = message; } public String[] getUsers() { return users; } public void setUsers(String[] users) { this.users = users; } public String[] getLink() { return link; } public void setLink(String[] link) { this.link = link; } public String[] getSection() { return section; } public void setSection(String[] section) { this.section = section; } } public static class CreateData { private String message; private String section; private String link; private String users; private String foreignId; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getSection() { return section; } public void setSection(String section) { this.section = section; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getUsers() { return users; } public void setUsers(String users) { this.users = users; } public String getForeignId() { return foreignId; } public void setForeignId(String foreignId) { this.foreignId = foreignId; } } // Helper methods for API public static class NotificationApiWrapper { // Logger private static Logger log = LoggerFactory .getLogger(NotificationApiWrapper.class); // Variables private String dashboardUrl; private String apiKey; public NotificationApiWrapper(String dashboardUrl, String apiKey) { this.dashboardUrl = dashboardUrl; this.apiKey = apiKey; } /* * Recommended usage as follows: * * NotificationApiWrapper n = new NotificationApiWrapper(dashboardUrl, * apiKey); GetNotification data = n.getNotifications(0, 10, * "dashboard", "userCrsid1"); if (data == null) { * log.error("Internal server error: could not get notifications") } * else { // Manipulate data } */ public GetNotification getNotifications(int offset, int limit, String section, String userId) { return getNotificationsWithForeignId(offset, limit, section, userId, ""); } public GetNotification getNotificationsWithForeignId(int offset, int limit, String section, String userId, String foreignId) { try { try { ClientRequestFactory c = new ClientRequestFactory( UriBuilder.fromUri(dashboardUrl).build()); GetNotification gn = c.createProxy(NotificationApi.class) .getNotification(offset, limit, section, foreignId, userId, apiKey); if (gn == null) { log.error("Internal server error: could not get notifications"); throw new NotificationException( "Internal server error: could not get notifications"); } else if (gn.getError() != null) { log.error(gn.getError()); throw new NotificationException(gn.getError()); } else if (gn.getFormErrors() != null) { // TODO refactor to loop through arrays String errors = gn.getFormErrors().getForeignId() .toString() + gn.getFormErrors().getLimit().toString() + gn.getFormErrors().getOffset().toString() + gn.getFormErrors().getSection().toString(); log.error("Form errors: " + errors); throw new NotificationException("Form errors " + errors); } return gn; } catch (ClientResponseFailure e) { ApiFailureMessage failMessage = APIUtil.getApiFailureMessage(e); throw new NotificationException(failMessage.getMessage()); } } catch (NotificationException e) { log.error(e.getMessage()); return null; } } /* * Recommended usage as follows: * * NotificationApiWrapper n = new NotificationApiWrapper(dashboardUrl, * apiKey); try { n.createNotification("Test message", "dashboard", * "example.com", "userCrsid1,userCrsid2")); * log.info("Successfully created notification"); } catch * (NotificationException e) { log.error(e.getMessage()); } */ public void createNotification(String message, String section, String link, String users) throws NotificationException { createNotificationWithForeignId(message, section, link, users, null); } public void createNotificationWithForeignId(String message, String section, String link, String users, String foreignId) throws NotificationException { try { ClientRequestFactory c = new ClientRequestFactory(UriBuilder .fromUri(dashboardUrl).build()); CreateNotification cn = c.createProxy(NotificationApi.class) .createNotification(message, section, link, users, foreignId, apiKey); if (cn.getRedirectTo() != null) { return; } else if (cn.getError() != null) { log.error(cn.getError()); throw new NotificationException(cn.getError()); } else if (cn.getFormErrors() != null) { // TODO refactor to loop through arrays String errors = cn.getFormErrors().getLink().toString() + cn.getFormErrors().getMessage().toString() + cn.getFormErrors().getSection().toString() + cn.getFormErrors().getUsers().toString(); log.error("Form errors: " + errors); throw new NotificationException("Form errors " + errors); } } catch (ClientResponseFailure e) { @SuppressWarnings("unchecked") ApiFailureMessage failMessage = (ApiFailureMessage) e .getResponse().getEntity(ApiFailureMessage.class); throw new NotificationException(failMessage.getMessage()); } } } }
package net.java.sip.communicator.impl.gui.main.chat; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.customcontrols.*; import net.java.sip.communicator.impl.gui.customcontrols.events.*; import net.java.sip.communicator.impl.gui.main.*; import net.java.sip.communicator.impl.gui.main.MainFrame.*; import net.java.sip.communicator.impl.gui.main.chat.menus.*; import net.java.sip.communicator.impl.gui.main.chat.toolBars.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.gui.event.*; import net.java.sip.communicator.util.*; /** * The chat window is the place, where users can write and send messages, view * received messages. The ChatWindow supports two modes of use: "Group all * messages in one window" and "Open messages in new window". In the first case * a <tt>JTabbedPane</tt> is added in the window, where each tab contains a * <tt>ChatPanel</tt>. In the second case the <tt>ChatPanel</tt> is added * like a "write message area", "send" button, etc. It corresponds to a * <tt>MetaContact</tt> or to a conference. * <p> * Note that the conference case is not yet implemented. * * @author Yana Stamcheva */ public class ChatWindow extends SIPCommFrame implements ExportedWindow, PluginComponentListener { private Logger logger = Logger.getLogger(ChatWindow.class.getName()); private MenusPanel menusPanel; private MainFrame mainFrame; private SIPCommTabbedPane chatTabbedPane = null; /** * Creates an instance of <tt>ChatWindow</tt> by passing to it an instance * of the main application window. * * @param mainFrame the main application window */ public ChatWindow(MainFrame mainFrame) { this.mainFrame = mainFrame; this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); menusPanel = new MenusPanel(this); //If in mode TABBED_CHAT_WINDOW initialize the tabbed pane if(Constants.TABBED_CHAT_WINDOW) { chatTabbedPane = new SIPCommTabbedPane(true, false); chatTabbedPane.addCloseListener(new CloseListener() { public void closeOperation(MouseEvent e) { int tabIndex = chatTabbedPane.getOverTabIndex(); ChatPanel chatPanel = (ChatPanel) chatTabbedPane.getComponentAt(tabIndex); ChatWindow.this.mainFrame .getChatWindowManager().closeChat(chatPanel); } }); } this.setSizeAndLocation(); JPanel northPanel = new JPanel(new BorderLayout()); northPanel.add(new LogoBar(), BorderLayout.NORTH); northPanel.add(menusPanel, BorderLayout.CENTER); this.getContentPane().setLayout(new BorderLayout(5, 5)); this.getContentPane().add(northPanel, BorderLayout.NORTH); this.initPluginComponents(); this.addKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.ALT_DOWN_MASK), new ForwordTabAction()); this.addKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, KeyEvent.ALT_DOWN_MASK), new BackwordTabAction()); this.addKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, KeyEvent.CTRL_DOWN_MASK), new CopyAction()); this.addKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, KeyEvent.SHIFT_DOWN_MASK), new PasteAction()); this.addKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.META_MASK), new CopyAction()); this.addKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.META_MASK), new PasteAction()); this.addKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_M, KeyEvent.CTRL_DOWN_MASK), new OpenSmileyAction()); this.addKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_H, KeyEvent.CTRL_DOWN_MASK), new OpenHistoryAction()); this.addKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_W, KeyEvent.META_MASK), new CloseAction()); this.addKeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_W, KeyEvent.CTRL_DOWN_MASK), new CloseAction()); this.addWindowListener(new ChatWindowAdapter()); } /** * Returns the main application widnow. * * @return The main application widnow. */ public MainFrame getMainFrame() { return mainFrame; } /** * Returns the main toolbar in this chat window. * @return the main toolbar in this chat window */ public MainToolBar getMainToolBar() { return menusPanel.getMainToolBar(); } /** * Adds a given <tt>ChatPanel</tt> to this chat window. * * @param chatPanel The <tt>ChatPanel</tt> to add. */ public void addChat(ChatPanel chatPanel) { if(Constants.TABBED_CHAT_WINDOW) addChatTab(chatPanel); else addSimpleChat(chatPanel); chatPanel.setShown(true); } /** * Adds a given <tt>ChatPanel</tt> to this chat window. * * @param chatPanel The <tt>ChatPanel</tt> to add. */ private void addSimpleChat(ChatPanel chatPanel) { this.getContentPane().add(chatPanel, BorderLayout.CENTER); } /** * Adds a given <tt>ChatPanel</tt> to the <tt>JTabbedPane</tt> of this * chat window. * * @param chatPanel The <tt>ChatPanel</tt> to add. */ private void addChatTab(ChatPanel chatPanel) { String chatName = chatPanel.getChatName(); if (getCurrentChatPanel() == null) { this.getContentPane().add(chatPanel, BorderLayout.CENTER); } else { if (getChatTabCount() == 0) { ChatPanel firstChatPanel = getCurrentChatPanel(); // Add first two tabs to the tabbed pane. chatTabbedPane.addTab( firstChatPanel.getChatName(), chatPanel.getChatStatusIcon(), firstChatPanel); chatTabbedPane.addTab( chatName, chatPanel.getChatStatusIcon(), chatPanel); // When added to the tabbed pane, the first chat panel should // rest the selected component. chatTabbedPane.setSelectedComponent(firstChatPanel); // Workaround for the following problem: // The scrollbar in the conversation area moves up when the // scrollpane is resized. This happens when ChatWindow is in // mode "Group messages in one window" and the first chat panel // is added to the tabbed pane. Then the scrollpane in the // conversation area is slightly resized and is made smaller, // which moves the scrollbar up. firstChatPanel.setCaretToEnd(); //add the chatTabbedPane to the window this.getContentPane().add(chatTabbedPane, BorderLayout.CENTER); this.getContentPane().validate(); } else { // The tabbed pane contains already tabs. chatTabbedPane.addTab( chatName, chatPanel.getChatStatusIcon(), chatPanel); chatTabbedPane.getParent().validate(); } } } /** * Removes a given <tt>ChatPanel</tt> from this chat window. * * @param chatPanel The <tt>ChatPanel</tt> to remove. */ public void removeChat(ChatPanel chatPanel) { logger.debug("Removes chat for contact: " + chatPanel.getChatName()); //if there's no tabs remove the chat panel directly from the content //pane and hide the window. if(getChatTabCount() == 0) { this.getContentPane().remove(chatPanel); this.dispose(); return; } //in the case of a tabbed chat window int index = chatTabbedPane.indexOfComponent(chatPanel); if (index != -1) { if (chatTabbedPane.getTabCount() > 1) chatTabbedPane.removeTabAt(index); if (chatTabbedPane.getTabCount() == 1) { ChatPanel currentChatPanel = (ChatPanel) this.chatTabbedPane .getComponentAt(0); this.chatTabbedPane.removeAll(); this.getContentPane().remove(chatTabbedPane); this.getContentPane().add(currentChatPanel, BorderLayout.CENTER); this.setCurrentChatPanel(currentChatPanel); } } } /** * Removes all tabs in the chat tabbed pane. If not in mode * TABBED_CHAT_WINDOW doesn nothing. */ public void removeAllChats() { logger.debug("Remove all tabs from the chat window."); if(getChatTabCount() > 0) { this.chatTabbedPane.removeAll(); this.getContentPane().remove(chatTabbedPane); } else { this.removeChat(getCurrentChatPanel()); } } /** * Selects the chat tab which corresponds to the given <tt>MetaContact</tt>. * * @param chatPanel The <tt>ChatPanel</tt> to select. */ public void setCurrentChatPanel(ChatPanel chatPanel) { logger.debug("Set current chat panel to: " + chatPanel.getChatName()); if(getChatTabCount() > 0) this.chatTabbedPane.setSelectedComponent(chatPanel); this.setTitle(chatPanel.getChatName()); chatPanel.requestFocusInWriteArea(); } /** * Selects the tab given by the index. If there's no tabbed pane does nothing. * @param index the index to select */ public void setCurrentChatTab(int index) { ChatPanel chatPanel = null; if(getChatTabCount() > 0) { chatPanel = (ChatPanel) this.chatTabbedPane .getComponentAt(index); setCurrentChatPanel(chatPanel); } } /** * Returns the currently selected chat panel. * * @return the currently selected chat panel. */ public ChatPanel getCurrentChatPanel() { if(getChatTabCount() > 0) return (ChatPanel)chatTabbedPane.getSelectedComponent(); else { int componentCount = getContentPane().getComponentCount(); for (int i = 0; i < componentCount; i ++) { Component c = getContentPane().getComponent(i); if(c instanceof ChatPanel) return (ChatPanel)c; } } return null; } /** * Returns the tab count of the chat tabbed pane. Meant to be used when in * "Group chat windows" mode. * * @return int The number of opened tabs. */ public int getChatTabCount() { return (chatTabbedPane == null) ? 0 : chatTabbedPane.getTabCount(); } /** * Highlights the corresponding tab for the given chat panel. * * @param chatPanel the chat panel which corresponds to the tab to highlight */ public void highlightTab(ChatPanel chatPanel) { this.chatTabbedPane.highlightTab( chatTabbedPane.indexOfComponent(chatPanel)); } /** * Sets the given icon to the tab opened for the given chat panel. * * @param chatPanel the chat panel, which corresponds the tab * @param icon the icon to be set */ public void setTabIcon(ChatPanel chatPanel, Icon icon) { int index = this.chatTabbedPane.indexOfComponent(chatPanel); this.chatTabbedPane.setIconAt(index, icon); } /** * Sets the given title to the tab opened for the given chat panel. * @param chatPanel the chat panel * @param title the new title of the tab */ public void setTabTitle(ChatPanel chatPanel, String title) { int index = this.chatTabbedPane.indexOfComponent(chatPanel); if(index > -1) this.chatTabbedPane.setTitleAt(index, title); } /** * The <tt>ForwordTabAction</tt> is an <tt>AbstractAction</tt> that * changes the currently selected tab with the next one. Each time when the * last tab index is reached the first one is selected. */ private class ForwordTabAction extends AbstractAction { public void actionPerformed(ActionEvent e) { if (getChatTabCount() > 0) { int selectedIndex = chatTabbedPane.getSelectedIndex(); if (selectedIndex < chatTabbedPane.getTabCount() - 1) { setCurrentChatTab(selectedIndex + 1); } else { setCurrentChatTab(0); } } } }; /** * The <tt>BackwordTabAction</tt> is an <tt>AbstractAction</tt> that * changes the currently selected tab with the previous one. Each time when * the first tab index is reached the last one is selected. */ private class BackwordTabAction extends AbstractAction { public void actionPerformed(ActionEvent e) { if (getChatTabCount() > 0) { int selectedIndex = chatTabbedPane.getSelectedIndex(); if (selectedIndex != 0) { setCurrentChatTab(selectedIndex - 1); } else { setCurrentChatTab(chatTabbedPane.getTabCount() - 1); } } } }; /** * The <tt>CopyAction</tt> is an <tt>AbstractAction</tt> that copies the * text currently selected. */ private class CopyAction extends AbstractAction { public void actionPerformed(ActionEvent e) { getCurrentChatPanel().copy(); } }; /** * The <tt>PasteAction</tt> is an <tt>AbstractAction</tt> that pastes * the text contained in the clipboard in the current <tt>ChatPanel</tt>. */ private class PasteAction extends AbstractAction { public void actionPerformed(ActionEvent e) { getCurrentChatPanel().paste(); } }; /** * The <tt>SendMessageAction</tt> is an <tt>AbstractAction</tt> that * sends the text that is currently in the write message area. */ private class SendMessageAction extends AbstractAction { public void actionPerformed(ActionEvent e) { ChatPanel chatPanel = getCurrentChatPanel(); // chatPanel.stopTypingNotifications(); chatPanel.sendButtonDoClick(); } } /** * The <tt>OpenSmileyAction</tt> is an <tt>AbstractAction</tt> that * opens the menu, containing all available smilies' icons. */ private class OpenSmileyAction extends AbstractAction { public void actionPerformed(ActionEvent e) { menusPanel.getMainToolBar().getSmiliesSelectorBox().open(); } } /** * The <tt>OpenHistoryAction</tt> is an <tt>AbstractAction</tt> that * opens the history window for the currently selected contact. */ private class OpenHistoryAction extends AbstractAction { public void actionPerformed(ActionEvent e) { menusPanel.getMainToolBar().getHistoryButton().doClick(); } } /** * The <tt>CloseAction</tt> is an <tt>AbstractAction</tt> that * closes a tab in the chat window. */ private class CloseAction extends AbstractAction { public void actionPerformed(ActionEvent e) { close(true); } } /** * Returns the time of the last received message. * * @return The time of the last received message. */ public Date getLastIncomingMsgTimestamp(ChatPanel chatPanel) { return chatPanel.getChatConversationPanel() .getLastIncomingMsgTimestamp(); } /** * Before closing the chat window saves the current size and position * through the <tt>ConfigurationService</tt>. */ public class ChatWindowAdapter extends WindowAdapter { public void windowDeiconified(WindowEvent e) { String title = getTitle(); if (title.startsWith("*")) { setTitle(title.substring(1, title.length())); } } } /** * Implements the <tt>SIPCommFrame</tt> close method. We check for an open * menu and if there's one we close it, otherwise we close the current chat. */ protected void close(boolean isEscaped) { ChatPanel chatPanel = getCurrentChatPanel(); if(isEscaped) { ChatRightButtonMenu chatRightMenu = getCurrentChatPanel() .getChatConversationPanel().getRightButtonMenu(); WritePanelRightButtonMenu writePanelRightMenu = getCurrentChatPanel() .getChatWritePanel().getRightButtonMenu(); SIPCommMenu selectedMenu = menusPanel.getMainMenuBar().getSelectedMenu(); //SIPCommMenu contactMenu = getCurrentChatPanel() // .getProtoContactSelectorBox().getMenu(); MenuSelectionManager menuSelectionManager = MenuSelectionManager.defaultManager(); if (chatRightMenu.isVisible()) { chatRightMenu.setVisible(false); } else if (writePanelRightMenu.isVisible()) { writePanelRightMenu.setVisible(false); } else if (selectedMenu != null //|| contactMenu.isPopupMenuVisible() || menusPanel.getMainToolBar().hasSelectedMenus()) { menuSelectionManager.clearSelectedPath(); } else { mainFrame.getChatWindowManager().closeChat(chatPanel); } } else { mainFrame.getChatWindowManager().closeWindow(); } } /** * Implements the <tt>ExportedWindow.getIdentifier()</tt> method. * Returns the identifier of this window, which will */ public WindowID getIdentifier() { return ExportedWindow.CHAT_WINDOW; } /** * Implements the <tt>ExportedWindow.minimize()</tt> method. Minimizes this * window. */ public void minimize() { this.setExtendedState(JFrame.ICONIFIED); } /** * Implements the <tt>ExportedWindow.maximize()</tt> method. Maximizes this * window. */ public void maximize() { this.setExtendedState(JFrame.MAXIMIZED_BOTH); } /** * Implements the <tt>ExportedWindow.bringToFront()</tt> method. Brings * this window to front. */ public void bringToFront() { if(getExtendedState() == JFrame.ICONIFIED) setExtendedState(JFrame.NORMAL); this.toFront(); } /** * Initialize plugin components already registered for this container. */ private void initPluginComponents() { Iterator pluginComponents = GuiActivator.getUIService() .getComponentsForContainer(UIService.CONTAINER_CHAT_WINDOW_SOUTH); while (pluginComponents.hasNext()) { Component o = (Component) pluginComponents.next(); this.add(o, BorderLayout.SOUTH); } GuiActivator.getUIService().addPluginComponentListener(this); } public void pluginComponentAdded(PluginComponentEvent event) { Component c = (Component) event.getSource(); if (event.getContainerID().equals(UIService.CONTAINER_CHAT_WINDOW_SOUTH)) { this.getContentPane().add(c, BorderLayout.SOUTH); this.pack(); } } public void pluginComponentRemoved(PluginComponentEvent event) { Component c = (Component) event.getSource(); if (event.getContainerID().equals(UIService.CONTAINER_CHAT_WINDOW_SOUTH)) { this.getContentPane().remove(c); } } /** * The source of the window * @return the source of the window */ public Object getSource() { return this; } private class LogoBar extends JPanel { /** * Creates the logo bar and specify the size. */ public LogoBar() { int width = SizeProperties.getSize("logoBarWidth"); int height = SizeProperties.getSize("logoBarHeight"); this.setMinimumSize(new Dimension(width, height)); this.setPreferredSize(new Dimension(width, height)); } /** * Paints the logo bar. * * @param g the <tt>Graphics</tt> object used to paint the background * image of this logo bar. */ public void paintComponent(Graphics g) { super.paintComponent(g); Image backgroundImage = ImageLoader.getImage(ImageLoader.WINDOW_TITLE_BAR); g.setColor(new Color( ColorProperties.getColor("logoBarBackground"))); g.fillRect(0, 0, this.getWidth(), this.getHeight()); g.drawImage(backgroundImage, 0, 0, null); } } }
package net.sf.jaer.graphics; import java.util.Iterator; import com.jogamp.opengl.GL; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GL2ES2; import com.jogamp.opengl.GL3; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.fixedfunc.GLMatrixFunc; import com.jogamp.opengl.glu.GLU; import com.jogamp.opengl.util.PMVMatrix; import eu.seebetter.ini.chips.davis.DavisDisplayConfigInterface; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.ApsDvsEventPacket; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.util.EngineeringFormat; import com.jogamp.opengl.util.gl2.GLUT; import eu.seebetter.ini.chips.DavisChip; import eu.seebetter.ini.chips.davis.imu.IMUSample; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.Scanner; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.aemonitor.AEConstants; import net.sf.jaer.chip.AEChip; import net.sf.jaer.graphics.ChipCanvas.ClipArea; @Description("Displays events in space time using a rolling view where old events are\n" + " * erased and new ones are added to the front.") @DevelopmentStatus(DevelopmentStatus.Status.InDevelopment) public class SpaceTimeRollingEventDisplayMethod extends DisplayMethod implements DisplayMethod3D { EngineeringFormat engFmt = new EngineeringFormat(); private DavisDisplayConfigInterface config; private boolean displayEvents = true; private boolean displayFrames = true; boolean spikeListCreated = false; private GLUT glut = null; private GLU glu = null; private boolean shadersInstalled = false; private int shaderprogram; private int vertexShader; private int fragmentShader; private int vao; private int vbo; final int v_vert = 0; private int BUF_INITIAL_SIZE_EVENTS = 20000; private int BUF_SIZE_INCREMENT_FACTOR = 2; ByteBuffer eventVertexBuffer; int sx, sy, smax; float tfac; private int timeSlice = 0; private FloatBuffer mv = FloatBuffer.allocate(16); private FloatBuffer proj = FloatBuffer.allocate(16); private int idMv, idProj, idt0, idt1; private ArrayList<BasicEvent> eventList = new ArrayList(BUF_INITIAL_SIZE_EVENTS), eventListTmp = new ArrayList(BUF_INITIAL_SIZE_EVENTS); private int timeWindowUs = 100000, t0; private static int EVENT_SIZE_BYTES = (Float.SIZE / 8) * 3;// size of event in shader ByteBuffer private int axesDisplayListId = -1; private boolean regenerateAxesDisplayList = true; private int aspectRatio=4; // depth of 3d cube compared to max of x and y chip dimension /** * Creates a new instance of SpaceTimeEventDisplayMethod */ public SpaceTimeRollingEventDisplayMethod(final ChipCanvas chipCanvas) { super(chipCanvas); this.eventVertexBuffer = ByteBuffer.allocateDirect(BUF_INITIAL_SIZE_EVENTS * EVENT_SIZE_BYTES); eventVertexBuffer.order(ByteOrder.LITTLE_ENDIAN); } private void installShaders(GL2 gl) throws IOException { if (shadersInstalled) { return; } gl.glEnable(GL3.GL_PROGRAM_POINT_SIZE); shadersInstalled = true; IntBuffer b = IntBuffer.allocate(8); // buffer to hold return values shaderprogram = gl.glCreateProgram(); vertexShader = gl.glCreateShader(GL2ES2.GL_VERTEX_SHADER); fragmentShader = gl.glCreateShader(GL2ES2.GL_FRAGMENT_SHADER); checkGLError(gl, "creating shaders and shader program"); String vsrc = readFromStream(SpaceTimeRollingEventDisplayMethod.class .getResourceAsStream("SpaceTimeRollingEventDisplayMethod_Vertex.glsl")); gl.glShaderSource(vertexShader, 1, new String[]{vsrc}, (int[]) null, 0); gl.glCompileShader(vertexShader); b.clear(); gl.glGetShaderiv(vertexShader, GL2ES2.GL_COMPILE_STATUS, b); if (b.get(0) != GL.GL_TRUE) { log.warning("error compiling vertex shader"); printShaderLog(gl); } checkGLError(gl, "compiling vertex shader"); String fsrc = readFromStream(SpaceTimeRollingEventDisplayMethod.class .getResourceAsStream("SpaceTimeRollingEventDisplayMethod_Fragment.glsl")); gl.glShaderSource(fragmentShader, 1, new String[]{fsrc}, (int[]) null, 0); gl.glCompileShader(fragmentShader); b.clear(); gl.glGetShaderiv(fragmentShader, GL2ES2.GL_COMPILE_STATUS, b); if (b.get(0) != GL.GL_TRUE) { log.warning("error compiling fragment shader"); printShaderLog(gl); } checkGLError(gl, "compiling fragment shader"); gl.glAttachShader(shaderprogram, vertexShader); gl.glAttachShader(shaderprogram, fragmentShader); gl.glLinkProgram(shaderprogram); b.clear(); // gl.glGetShaderiv(shaderprogram, GL2ES2.GL_COMPILE_STATUS, b); // if (b.get(0) != GL.GL_TRUE) { // log.warning("error linking shader program"); // printShaderLog(gl); checkGLError(gl, "linking shader program"); b.clear(); gl.glGenVertexArrays(1, b); vao = b.get(0); gl.glBindVertexArray(vao); b.clear(); gl.glGenBuffers(1, b); vbo = b.get(0); checkGLError(gl, "setting up vertex array and vertex buffer"); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo); // gl.glBindAttribLocation(shaderprogram, polarity_vert, "polarity"); // symbolic names in vertex and fragment shaders gl.glBindAttribLocation(shaderprogram, v_vert, "v"); // gl.glBindAttribLocation(shaderprogram, polarity_frag, "frag_polarity"); checkGLError(gl, "binding shader attributes"); gl.glVertexAttribPointer(v_vert, 3, GL.GL_FLOAT, false, EVENT_SIZE_BYTES, 0); // gl.glVertexAttribPointer(polarity_vert, 1, GL.GL_FLOAT, false, EVENT_SIZE_BYTES, 3); checkGLError(gl, "setting vertex attribute pointers"); idMv = gl.glGetUniformLocation(shaderprogram, "mv"); idProj = gl.glGetUniformLocation(shaderprogram, "proj"); idt0 = gl.glGetUniformLocation(shaderprogram, "t0"); idt1 = gl.glGetUniformLocation(shaderprogram, "t1"); if (idMv < 0 || idProj < 0 || idt0 < 0 || idt1 < 0) { throw new RuntimeException("cannot locate uniform variable idMv, idProj, idt0 or idt1 in shader program"); } checkGLError(gl, "getting IDs for uniform modelview and projection matrices in shaders"); } private void checkEventBufferAllocation(int sizeEvents) { if (eventVertexBuffer.capacity() <= sizeEvents * EVENT_SIZE_BYTES) { eventVertexBuffer = ByteBuffer.allocateDirect(eventList.size() * EVENT_SIZE_BYTES); eventVertexBuffer.order(ByteOrder.LITTLE_ENDIAN); } } @Override public void display(final GLAutoDrawable drawable) { if (!(chip instanceof AEChip)) { throw new RuntimeException("Can only render AEChip outputs: chip=" + chip); } final AEChip chip = (AEChip) getChipCanvas().getChip(); if (glut == null) { glut = new GLUT(); } final GL2 gl = drawable.getGL().getGL2(); if (gl == null) { log.warning("null GL context - not displaying"); return; } try { installShaders(gl); } catch (IOException ex) { log.warning("could not load shaders: " + ex.toString()); return; } // render events final EventPacket packet = (EventPacket) chip.getLastData(); if (packet == null) { log.warning("null packet to render"); return; } final int n = packet.getSize(); if (n == 0) { return; } final int t0ThisPacket = packet.getFirstTimestamp(); final int t1 = packet.getLastTimestamp(); // final int dtThisPacket = t1 - t0ThisPacket + 1; // the time that is displayed in rolling window is some multiple of either current frame duration (for live playback) or timeslice (for recorded playback) int colorScale = getRenderer().getColorScale(); // use color scale to determine multiple, up and down arrows set it then int newTimeWindowUs; if (chip.getAeViewer().getPlayMode() == AEViewer.PlayMode.LIVE) { int frameDurationUs = (int) (1e6f / chip.getAeViewer().getFrameRater().getDesiredFPS()); newTimeWindowUs = frameDurationUs * (1 << colorScale); } else if (chip.getAeViewer().getPlayMode() == AEViewer.PlayMode.PLAYBACK) { newTimeWindowUs = chip.getAeViewer().getAePlayer().getTimesliceUs() * (1 << colorScale); } else { newTimeWindowUs = 100000; } if (newTimeWindowUs != timeWindowUs) { regenerateAxesDisplayList = true; } timeWindowUs = newTimeWindowUs; t0 = t1 - timeWindowUs; pruneOldEvents(t0); sx = chip.getSizeX(); sy = chip.getSizeY(); smax = chip.getMaxSize(); tfac=(float)(smax*aspectRatio)/timeWindowUs; addEventsToEventList(packet); checkEventBufferAllocation(eventList.size()); eventVertexBuffer.clear();// TODO should not really clear, rather should erase old events for (BasicEvent ev : eventList) { eventVertexBuffer.putFloat(ev.x); eventVertexBuffer.putFloat(ev.y); eventVertexBuffer.putFloat(tfac*(ev.timestamp - t1)); // negative z } eventVertexBuffer.flip(); checkGLError(gl, "set uniform t0 and t1"); renderEvents(gl, drawable, eventVertexBuffer, eventList.size(), 1e-6f*timeWindowUs, smax*aspectRatio); } private void addEventsToEventList(final EventPacket<BasicEvent> packet) { for (BasicEvent e : packet) { // BasicEvent e = (BasicEvent) o; if (e.isSpecial() || e.isFilteredOut()) { continue; } BasicEvent ne = new BasicEvent(); ne.copyFrom(e); eventList.add(ne); // must do this unfortunately because otherwise the original event object in this list will be reused for a later packet } } private void pruneOldEvents(final int startTimeUs) { eventListTmp.clear(); for (BasicEvent ev : eventList) { if (ev.timestamp >= startTimeUs) { eventListTmp.add(ev); } } eventList.clear(); eventList.addAll(eventListTmp); } void renderEvents(GL2 gl, GLAutoDrawable drawable, ByteBuffer b, int nEvents, float dtS, float zmax) { gl.glClearColor(0, 0, 0, 0); gl.glClear(GL.GL_COLOR_BUFFER_BIT); // axes gl.glColor3f(0, 0, 1); gl.glLineWidth(1f); if (glu == null) { glu = new GLU(); } if (regenerateAxesDisplayList) { regenerateAxesDisplayList = false; if(axesDisplayListId>0){ gl.glDeleteLists(axesDisplayListId, 1); } axesDisplayListId = gl.glGenLists(1); gl.glNewList(axesDisplayListId, GL2.GL_COMPILE); gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); gl.glLoadIdentity(); gl.glTranslatef(0, 0, 0); gl.glScalef(1, 1, 8); // gl.glTranslatef(0, 0, -timeWindowUs); // glu.gluLookAt(0, 0, 0, // 0, 0, -1, // 0, 1, 0); // gl.glTranslatef(-sx,0,0); // gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); // gl.glPushMatrix(); // axes gl.glBegin(GL.GL_LINES); gl.glVertex3f(0, 0, 0); gl.glVertex3f(sx, 0, 0); gl.glVertex3f(0, 0, 0); gl.glVertex3f(0, sy, 0); gl.glVertex3f(sx, 0, 0); gl.glVertex3f(sx, sy, 0); gl.glVertex3f(sx, sy, 0); gl.glVertex3f(0, sy, 0); gl.glVertex3f(0, 0, 0); gl.glVertex3f(0, 0, -zmax); gl.glVertex3f(sx, 0, 0); gl.glVertex3f(sx, 0, -zmax); gl.glVertex3f(0, sy, 0); gl.glVertex3f(0, sy, -zmax); gl.glVertex3f(sx, sy, 0); gl.glVertex3f(sx, sy, -zmax); gl.glVertex3f(0, 0, -zmax); gl.glVertex3f(sx, 0, -zmax); gl.glVertex3f(0, 0, -zmax); gl.glVertex3f(0, sy, -zmax); gl.glVertex3f(sx, 0, -zmax); gl.glVertex3f(sx, sy, -zmax); gl.glVertex3f(sx, sy, -zmax); gl.glVertex3f(0, sy, -zmax); gl.glEnd(); final int font = GLUT.BITMAP_TIMES_ROMAN_24; final int FS = 1; // distance in pixels of text from endZoom of axis gl.glRasterPos3f(sx, 0, 0); glut.glutBitmapString(font, "x=" + sx); gl.glRasterPos3f(0, sy, 0); glut.glutBitmapString(font, "y=" + sy); gl.glRasterPos3f(0, 0, -zmax); glut.glutBitmapString(font, "t=" + engFmt.format(dtS) + "s"); gl.glRasterPos3f(0, 0, 0); glut.glutBitmapString(font, "t=0"); checkGLError(gl, "drawing axes labels"); gl.glEndList(); } gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION); gl.glLoadIdentity(); // gl.glPushMatrix(); ClipArea clip = getChipCanvas().getClipArea(); // gl.glRotatef(-15, 1, 1, 0); // rotate viewpoint by angle deg around the y axis gl.glRotatef(getChipCanvas().getAngley(), 0, 1, 0); // rotate viewpoint by angle deg around the y axis gl.glRotatef(getChipCanvas().getAnglex(), 1, 0, 0); // rotate viewpoint by angle deg around the x axis gl.glOrtho(clip.left, clip.right, clip.bottom, clip.top, -zmax * 4, zmax * 4); gl.glTranslatef(getChipCanvas().getOrigin3dx(), getChipCanvas().getOrigin3dy(), 0); // gl.glTranslatef(sx/2, sy/2, zmax); // glu.gluPerspective(33, (float)drawable.getSurfaceWidth()/drawable.getSurfaceHeight(), .1, zmax*9); // gl.glTranslatef(-sx/2, -sy/2, -zmax); // glu.gluPerspective(30, (float)sx/sy, .1, timeWindowUs*1.1f); // gl.glFrustumf(clip.left, clip.right, clip.bottom, clip.top, .1f, timeWindowUs*20); // gl.glFrustumf(0,sx, 0, sy, .1f, timeWindowUs*20); // gl.glFrustumf(clip.left, clip.right, clip.bottom, clip.top, .1f, timeWindowUs * 10); // gl.glTranslatef(sx, sy, 1); checkGLError(gl, "setting projection"); gl.glCallList(axesDisplayListId); // getChipCanvas().setDefaultProjection(gl, drawable); // draw points using shaders gl.glUseProgram(shaderprogram); gl.glValidateProgram(shaderprogram); // pmvMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION); // pmvMatrix.glLoadIdentity(); // pmvMatrix.glOrthof(-10, sx / zoom + 10, -10, sy / zoom + 10, 10, -10); // clip area has same aspect ratio as screen! // pmvMatrix.glRotatef(getChipCanvas().getAngley(), 0, 1, 0); // rotate viewpoint by angle deg around the y axis // pmvMatrix.glRotatef(getChipCanvas().getAnglex(), 1, 0, 0); // rotate viewpoint by angle deg around the x axis // pmvMatrix.glTranslatef(getChipCanvas().getOrigin3dx(), getChipCanvas().getOrigin3dy(), 0); // pmvMatrix.glGetFloatv(GL2.GL_PROJECTION_MATRIX, proj); // pmvMatrix.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); // pmvMatrix.glLoadIdentity(); // pmvMatrix.glGetFloatv(GL2.GL_MODELVIEW_MATRIX, mv); // checkGLError(gl, "using shader program"); gl.glGetFloatv(GL2.GL_PROJECTION_MATRIX, proj); // gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); // gl.glLoadIdentity(); gl.glGetFloatv(GL2.GL_MODELVIEW_MATRIX, mv); gl.glUniformMatrix4fv(idMv, 1, false, mv); gl.glUniformMatrix4fv(idProj, 1, false, proj); checkGLError(gl, "setting model/view matrix"); gl.glUniform1f(idt0, (float) -zmax); gl.glUniform1f(idt1, (float) 0); checkGLError(gl, "setting t0 or t1 for buffer"); gl.glBindVertexArray(vao); // gl.glEnableVertexAttribArray(polarity_vert); gl.glEnableVertexAttribArray(v_vert); gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo); gl.glBufferData(GL.GL_ARRAY_BUFFER, b.limit(), b, GL2ES2.GL_STREAM_DRAW); checkGLError(gl, "binding vertex buffers"); // gl.glEnable(GL.GL_DEPTH_TEST); // gl.glDepthMask(true); // gl.glEnable(GL.GL_BLEND); // gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE); // gl.glBlendEquation(GL.GL_FUNC_ADD); // checkGLError(gl, "setting blend function"); // draw gl.glDrawArrays(GL.GL_POINTS, 0, nEvents); checkGLError(gl, "drawArrays"); gl.glUseProgram(0); checkGLError(gl, "disable program"); // gl.glPopMatrix(); // pop out so that shader uses matrix without applying it twice // gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION); // gl.glPopMatrix(); // pop out so that shader uses matrix without applying it twice // gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW); // re-enable depth sorting for everything else // gl.glDepthMask(true); } boolean checkGLError(final GL2 gl, String msg) { boolean r = false; int error = gl.glGetError(); int nerrors = 10; while ((error != GL.GL_NO_ERROR) && (nerrors if (glu == null) { glu = new GLU(); } StackTraceElement[] st = Thread.currentThread().getStackTrace(); log.warning("GL error number " + error + " " + glu.gluErrorString(error) + "\n"); new RuntimeException("GL error number " + error + " " + glu.gluErrorString(error)).printStackTrace(); error = gl.glGetError(); r = true; } return r; } private void printShaderLog(GL2 gl) { IntBuffer b = IntBuffer.allocate(8); gl.glGetProgramiv(shaderprogram, GL2ES2.GL_INFO_LOG_LENGTH, b); int logLength = b.get(0); ByteBuffer bb = ByteBuffer.allocate(logLength); b.clear(); gl.glGetProgramInfoLog(shaderprogram, logLength, b, bb); String v = new String(bb.array(), java.nio.charset.StandardCharsets.UTF_8); log.info(v); } private String readFromStream(InputStream ins) throws IOException { if (ins == null) { throw new IOException("Could not read from stream."); } StringBuffer buffer = new StringBuffer(); Scanner scanner = new Scanner(ins); try { while (scanner.hasNextLine()) { buffer.append(scanner.nextLine() + "\n"); } } finally { scanner.close(); } return buffer.toString(); } }
package nl.hanze2017e4.gameclient.model.games.reversi; import nl.hanze2017e4.gameclient.model.master.Board; import nl.hanze2017e4.gameclient.model.master.Player; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import static nl.hanze2017e4.gameclient.model.master.Player.PlayerType.OPPONENT; public class ReversiAI { Board board; Player player1; Player player2; int lookForwardMoves; private Set<Integer> legalMovesSet = new HashSet<>(); private ArrayList<ReversiMove> legalMoves; /** * @param board * @param player1 * @param player2 * @param lookForwardMoves Number of moves to look ahead. Including opponent moves. */ public ReversiAI(Board board, Player player1, Player player2, int lookForwardMoves) { this.board = board; this.player1 = player1; this.player2 = player2; this.lookForwardMoves = lookForwardMoves; legalMoves = new ArrayList<>(); } public int calculateBestMove() { calculateLegalMoves(board); addElementToLegalMoveArray(); ReversiMove move = determineScore(legalMoves); System.out.println("calculateBestMove invoked"); return move.getMove(); } private void addElementToLegalMoveArray(){ for (Integer legalMove: legalMovesSet){ legalMoves.add(new ReversiMove(player1,legalMove,board)); } } private void calculateLegalMoves(Board board) { for (int i = 0; i < 63;i++){ int diagonallTopLeft = i-9; int diagonallTopRight = i-7; int diagonalBotRight = i+9; int diagonalBotLeft = i+7; int horizontalRight = i+1; int horizontalLeft = i-1; int verticalUp = i-8; int verticalDown = i+8; if (board.getPlayerAtPos(i) == null){ try{ // diagonal checker if (board.getPlayerAtPos(diagonallTopLeft) != null || board.getPlayerAtPos(diagonalBotRight) !=null || board.getPlayerAtPos(diagonallTopRight) != null || board.getPlayerAtPos(diagonalBotLeft)!= null ) { legalMovesSet.add(i); } //horizontal checker if (board.getPlayerAtPos(horizontalRight) != null || board.getPlayerAtPos(horizontalLeft) != null) { legalMovesSet.add(i); } //vertical checker if (board.getPlayerAtPos(verticalUp) != null || board.getPlayerAtPos(verticalDown) != null) { legalMovesSet.add(i); } } catch(IndexOutOfBoundsException ex){ } } } } private ReversiMove determineScore(ArrayList<ReversiMove> legalMoves) { //return the move we want to play return null; } }
package org.apache.xml.security.c14n.implementations; import java.io.IOException; import java.io.OutputStream; import java.util.Map; public class UtfHelpper { final static void writeByte(final String str,final OutputStream out,Map cache) throws IOException { byte []result=(byte[]) cache.get(str); if (result==null) { result=getStringInUtf8(str); cache.put(str,result); } out.write(result); } final static void writeCharToUtf8(final char c,final OutputStream out) throws IOException{ if ( (c & 0x80) ==0) { out.write(c); return; } int bias; int write; char ch; if (c > 0x07FF) { ch=(char)(c>>>12); write=0xE0; if (ch>0) { write |= ( ch & 0x0F); } out.write(write); write=0x80; bias=0x3F; } else { write=0xC0; bias=0x1F; } ch=(char)(c>>>6); if (ch>0) { write|= (ch & bias); } out.write(write); out.write(0x80 | ((c) & 0x3F)); } final static void writeStringToUtf8(final String str,final OutputStream out) throws IOException{ final int length=str.length(); int i=0; char c; while (i<length) { c=str.charAt(i++); if ((c & 0x80) == 0) { out.write(c); continue; } char ch; int bias; int write; if (c > 0x07FF) { ch=(char)(c>>>12); write=0xE0; if (ch>0) { write |= ( ch & 0x0F); } out.write(write); write=0x80; bias=0x3F; } else { write=0xC0; bias=0x1F; } ch=(char)(c>>>6); if (ch>0) { write|= (ch & bias); } out.write(write); out.write(0x80 | ((c) & 0x3F)); } } public final static byte[] getStringInUtf8(final String str) { final int length=str.length(); boolean expanded=false; byte []result=new byte[length]; int i=0; int out=0; char c; while (i<length) { c=str.charAt(i++); if ((c & 0x80) == 0) { result[out++]=(byte)c; continue; } if (!expanded) { byte newResult[]=new byte[3*length]; System.arraycopy(result, 0, newResult, 0, out); result=newResult; expanded=true; } char ch; int bias; byte write; if (c > 0x07FF) { ch=(char)(c>>>12); write=(byte)0xE0; if (ch>0) { write |= ( ch & 0x0F); } result[out++]=write; write=(byte)0x80; bias=0x3F; } else { write=(byte)0xC0; bias=0x1F; } ch=(char)(c>>>6); if (ch>0) { write|= (ch & bias); } result[out++]=write; result[out++]=(byte)(0x80 | ((c) & 0x3F)); } if (expanded) { byte newResult[]=new byte[out]; System.arraycopy(result, 0, newResult, 0, out); result=newResult; } return result; } }
package yuku.alkitabconverter.util; import java.io.PrintStream; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import yuku.alkitab.base.model.Ari; public class TextDb { public static final String TAG = TextDb.class.getSimpleName(); public interface TextProcessor { void process(int ari, VerseState verseState); } public static class VerseState { // was: "public int menjorok;" but no longer used public String text; } TreeMap<Integer, VerseState> map = new TreeMap<Integer, VerseState>(); public String append(int bookId, int chapter_1, int verse_1, String s, int currentIndent) { return append(Ari.encode(bookId, chapter_1, verse_1), s, currentIndent); } public String append(int bookId, int chapter_1, int verse_1, String s, int currentIndent, String separatorWhenExisting) { return append(Ari.encode(bookId, chapter_1, verse_1), s, currentIndent, separatorWhenExisting); } /** * @param currentIndent if -1, don't write anything. * @return */ public String append(int ari, String s, int currentIndent) { return append(ari, s, currentIndent, null); } /** * @param separatorWhenExisting if the text is appended to an ari that has already some text, append this first, then the text. * @param currentIndent if -1, don't write anything. * @return */ public String append(int ari, String text, int currentIndent, String separatorWhenExisting) { VerseState as = map.get(ari); boolean isNew = false; if (as == null) { as = new VerseState(); as.text = ""; map.put(ari, as); isNew = true; } boolean writtenParaMarker = false; if (currentIndent != -1) { if (currentIndent == -2) { as.text += "@^"; } else if (currentIndent < 0 || currentIndent > 4) { throw new RuntimeException("menjorok ngaco: " + currentIndent); } else { as.text += "@" + String.valueOf(currentIndent); } writtenParaMarker = true; // was: "update menjoroknya ayatstate" but no longer used // for (int i = 0; i < as.isi.length(); i++) { // if (as.isi.charAt(i) == '@' && as.isi.charAt(i+1) >= '0' && as.isi.charAt(i+1) <= '4') { // as.menjorok = as.isi.charAt(i+1) - '0'; } if (!isNew && separatorWhenExisting != null) { as.text += separatorWhenExisting; } if (writtenParaMarker) { as.text += leftSpaceTrim(text); } else { as.text += text; } // buang spasi di depan kalo ada while (as.text.startsWith(" ")) { as.text = as.text.substring(1); } // kasih @@ kalo depannya blum ada if (as.text.contains("@") && !as.text.startsWith("@@")) { as.text = "@@" + as.text; } return as.text; } private static String leftSpaceTrim(String s) { for (int i = 0; i < s.length(); i++) { if (s.charAt(i) != ' ') { return s.substring(i); } } return s; } public void normalize() { Set<Integer> keys = new TreeSet<Integer>(map.keySet()); int last_bookId = -1; int last_chapter_1 = 0; int last_verse_1 = 0; for (int ari: keys) { int bookId = Ari.toBook(ari); int chapter_1 = Ari.toChapter(ari); int verse_1 = Ari.toVerse(ari); if (bookId != last_bookId) { // must start with chapter_1 1 and verse_1 1 if (chapter_1 != 1 || verse_1 != 1) { throw new RuntimeException("at " + bookId + " " + chapter_1 + " " + verse_1 + ": " + " new book does not start from 1:1"); } // different book, ignore and restart last_bookId = bookId; last_chapter_1 = chapter_1; last_verse_1 = verse_1; continue; } if (chapter_1 == last_chapter_1) { if (verse_1 != last_verse_1 + 1) { System.out.println("at " + bookId + " " + chapter_1 + " " + verse_1 + ": " + " skipped after " + last_bookId + " " + last_chapter_1 + " " + last_verse_1); System.out.println("Adding empty verses:"); for (int a = last_verse_1 + 1; a < verse_1; a++) { System.out.println(" at " + bookId + " " + chapter_1 + " " + a + ": " + " (blank)"); append(bookId, chapter_1, a, "", 0); } } } else if (chapter_1 == last_chapter_1 + 1) { if (verse_1 != 1) { throw new RuntimeException("at " + bookId + " " + chapter_1 + " " + verse_1 + ": " + " verse_1 is not 1"); } } else { throw new RuntimeException("at " + bookId + " " + chapter_1 + " " + verse_1 + ": " + " so wrong! it's after " + last_bookId + " " + last_chapter_1 + " " + last_verse_1); } last_bookId = bookId; last_chapter_1 = chapter_1; last_verse_1 = verse_1; } System.out.println("normalize done"); } public void dump(PrintStream ps) { ps.println("TOTAL text: " + map.size()); for (Entry<Integer, VerseState> e: map.entrySet()) { ps.printf("%d\t%d\t%d\t%s%n", Ari.toBook(e.getKey()) + 1, Ari.toChapter(e.getKey()), Ari.toVerse(e.getKey()), e.getValue().text); } } public void dump() { dump(System.out); } public int size() { return map.size(); } public List<Rec> toRecList() { List<Rec> res = new ArrayList<Rec>(); for (Entry<Integer, VerseState> e: map.entrySet()) { Rec rec = new Rec(); int ari = e.getKey(); rec.book_1 = Ari.toBook(ari) + 1; rec.chapter_1 = Ari.toChapter(ari); rec.verse_1 = Ari.toVerse(ari); rec.text = e.getValue().text; res.add(rec); } return res; } public void processEach(TextProcessor textProcessor) { for (Map.Entry<Integer, VerseState> e: map.entrySet()) { textProcessor.process(e.getKey(), e.getValue()); } } public int getBookCount() { Set<Integer> bookIds = new LinkedHashSet<>(); for (Map.Entry<Integer, VerseState> e: map.entrySet()) { int bookId = Ari.toBook(e.getKey()); bookIds.add(bookId); } return bookIds.size(); } public int[] getBookIds() { Set<Integer> bookIds = new TreeSet<>(); for (Map.Entry<Integer, VerseState> e: map.entrySet()) { int bookId = Ari.toBook(e.getKey()); bookIds.add(bookId); } int[] res = new int[bookIds.size()]; int c = 0; for (Integer bookId: bookIds) { res[c++] = bookId; } return res; } /** * No skipped chapters recognized. So if a book has chapters [1, 5, 6], this returns 6, not 3. */ public int getChapterCountForBook(int bookId) { int maxChapter = 0; for (Map.Entry<Integer, VerseState> e: map.entrySet()) { int ari = e.getKey(); if (Ari.toBook(ari) == bookId) { int chapter_1 = Ari.toChapter(ari); if (chapter_1 > maxChapter) maxChapter = chapter_1; } } return maxChapter; } /** * No skipped verses recognized. So if a chapter has verses [1, 5, 6], this returns 6, not 3. */ public int getVerseCountForBookChapter(int bookId, int chapter_1) { int maxVerse = 0; for (Map.Entry<Integer, VerseState> e: map.entrySet()) { int ari = e.getKey(); if (Ari.toBook(ari) == bookId && Ari.toChapter(ari) == chapter_1) { int verse_1 = Ari.toVerse(ari); if (verse_1 > maxVerse) maxVerse = verse_1; } } return maxVerse; } public String getVerseText(int bookId, int chapter_1, int verse_1) { return map.get(Ari.encode(bookId, chapter_1, verse_1)).text; } }
package net.somethingdreadful.MAL.forum; import android.content.Context; import net.somethingdreadful.MAL.MALDateTools; import net.somethingdreadful.MAL.R; import net.somethingdreadful.MAL.Theme; import net.somethingdreadful.MAL.api.response.Forum; import net.somethingdreadful.MAL.api.response.ForumMain; import net.somethingdreadful.MAL.api.response.User; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; public class HtmlUtil { String structure; String postStructure; String spoilerStructure; public HtmlUtil(Context context) { structure = getString(context, R.raw.forum_post_structure); postStructure = getString(context, R.raw.forum_post_post_structure); spoilerStructure = getString(context, R.raw.forum_post_spoiler_structure); } /** * Convert a forum array into a HTML list. * * @param record The ForumMain object that contains the list which should be converted in a HTML list * @param context The application context to format the dates * @param username The username of the user, this is used for special rights * @return String The HTML source */ public String convertList(ForumMain record, Context context, String username, int page) { ArrayList<Forum> list = record.getList(); String result = ""; for (int i = 0; i < list.size(); i++) { Forum post = list.get(i); String postreal = postStructure; String comment = post.getComment(); comment = comment.replace("data-src=", "width=\"100%\" src="); comment = comment.replace("img src=", "img width=\"100%\" src="); if (post.getUsername().equals(username)) postreal = postreal.replace("<!-- special right methods -->", "<img class=\"edit\" onClick=\"edit('itemID', 'position')\" src=\"http://i.imgur.com/uZ0TbNv.png\"/>"); else postreal = postreal.replace("<!-- special right methods -->", "<img class=\"edit\" onClick=\"quote('itemID', 'position')\" src=\"http://i.imgur.com/yYtLVTV.png\"/>"); if (User.isDeveloperRecord(post.getUsername())) postreal = postreal.replace("=\"title\">", "=\"developer\">"); if (!post.getProfile().getDetails().getAccessRank().equals("Member")) postreal = postreal.replace("=\"title\">", "=\"staff\">"); postreal = postreal.replace("image", post.getProfile().getAvatarUrl() != null ? post.getProfile().getAvatarUrl() : "http://cdn.myanimelist.net/images/na.gif"); postreal = postreal.replace("Title", post.getUsername()); postreal = postreal.replace("itemID", Integer.toString(post.getId())); postreal = postreal.replace("position", Integer.toString(i)); postreal = postreal.replace("Subhead", MALDateTools.formatDateString(post.getTime(), context, true)); postreal = postreal.replace("<!-- place post content here -->", comment); result = result + postreal; } return buildList(result, record, page); } /** * Creates from the given data the list. * * @param result The post list * @param record The ForumMain object that contains the pagenumbers * @param page The current page number * @return String The html source */ private String buildList(String result, ForumMain record, Integer page){ String list = structure.replace("<!-- insert here the posts -->", rebuildSpoiler(result)); if (page == 1) list = list.replace("class=\"item\" value=\"1\"", "class=\"item hidden\" value=\"1\""); if (page == record.getPages()) list = list.replace("class=\"item\" value=\"2\"", "class=\"item hidden\" value=\"2\""); list = list.replace("pages", Integer.toString(record.getPages())); list = list.replace("page", Integer.toString(page)); if (Theme.darkTheme) { list = list.replace("#D2D2D2", "#212121"); // divider list = list.replace("#FAFAFA", "#313131"); // post list = list.replace("#444444", "#E3E3E3"); // title text list = list.replace("class=\"content\"", "class=\"content\" style=\"color:#E3E3E3\""); // post text } return list; } /** * convert a HTML comment into a BBCode comment. * * @param comment The HTML comment * @return String The BBCode comment */ public String convertComment(String comment) { comment = comment.replace("\">", "]"); comment = comment.replace("\n", ""); comment = comment.replace("<br>", "\n"); // Empty line comment = comment.replace("data-src=", "src=").replace(" class=\"userimg\"", ""); // Image comment = comment.replace("<img src=\"", "[img]").replace("\" border=\"0\" />", "[/img]"); comment = comment.replace(".png]", ".png[/img]").replace(".jpg]", ".jpg[/img]").replace(".gif]", ".gif[/img]"); comment = comment.replace("<span style=\"color:", "[color=").replace("<!--color-->", "[/color]"); // Text color comment = comment.replace("<span style=\"font-size: ", "[size=").replace("%;", "").replace("<!--size-->", "[/size]"); // Text size comment = comment.replace("<strong>", "[b]").replace("</strong>", "[/b]"); // Text bold comment = comment.replace("<u>", "[u]").replace("</u>", "[/u]"); // Text underline comment = comment.replace("<div style=\"text-align: center;]", "[center]").replace("<!--center-->", "[/center]"); // Center comment = convertSpoiler(comment); // Spoiler comment = comment.replace("<a href=\"", "[url=").replace("target=\"_blank ", "").replace("</a>", "[/url]"); // Hyperlink comment = comment.replace("<!--quote--><div class=\"quotetext][b]", "[quote=").replace(" said:[/b]<!--quotesaid-->", "]"); // Quote comment = comment.replace("<!--quote-->", "[/quote]"); comment = comment.replace("<ol>", "[list]").replace("</ol>", "[/list]").replace("<li>", "[*]"); // List comment = comment.replace("<span style=\"text-decoration:line-through;]", "[s]").replace("<!--strike-->", "[/s]"); // Text strike comment = comment.replace("<em>", "[i]").replace("</em>", "[/i]"); // Text Italic comment = comment.replace("\n& comment = comment.replace("&amp;", "&"); comment = comment.replace("</div>", ""); comment = comment.replace("</span>", ""); comment = comment.replace("</li>", ""); comment = comment.replace("<!--link return comment; } /** * Converts the spoiler HTML code into the BBCode. * * @param text The text to search for a spoiler * @return String The text with the BBCode spoiler */ private String convertSpoiler(String text) { text = text.replace("<div class=\"spoiler]", ""); text = text.replace("<input type=\"button\" class=\"button\"", ""); text = text.replace(" onclick=\"this.nextSibling.nextSibling.style.display='block';", ""); text = text.replace("this.style.display='none';\"", ""); text = text.replace(" value=\"Show spoiler]", ""); text = text.replace("<span class=\"spoiler_content\" style=\"display:none]", ""); text = text.replace("<input type=\"button\" class=\"button\" ", ""); text = text.replace("onclick=\"this.parentNode.style.display='none';", ""); text = text.replace("this.parentNode.parentNode.childNodes[0].style.display='block';\" ", ""); text = text.replace("value=\"Hide spoiler]", "[spoiler]"); text = text.replace("<!--spoiler--></span>", "[/spoiler]"); return text; } /** * Rebuild the spoiler to work again. * * @param html The html source where this method should fix the spoilers * @return String The source with working spoilers */ private String rebuildSpoiler(String html) { html = html.replace("<div class=\"spoiler\">", ""); html = html.replace("<input type=\"button\" class=\"button\"", ""); html = html.replace(" onclick=\"this.nextSibling.nextSibling.style.display='block';", ""); html = html.replace("this.style.display='none';\"", ""); html = html.replace(" value=\"Show spoiler\">", ""); html = html.replace("<span class=\"spoiler_content\" style=\"display:none\">", ""); html = html.replace("<input type=\"button\" class=\"button\" ", ""); html = html.replace(" onclick=\"this.parentNode.style.display='none';", ""); html = html.replace("this.parentNode.parentNode.childNodes[0].style.display='block';\" ", ""); html = html.replace("value=\"Hide spoiler\"><br>", spoilerStructure); html = html.replace("<!--spoiler--></span>", ""); return html; } /** * Get the string of the given resource file. * * @param context The application context * @param resource The resource of which string we need * @return String the wanted string */ @SuppressWarnings("StatementWithEmptyBody") private String getString(Context context, int resource) { try { InputStream inputStream = context.getResources().openRawResource(resource); byte[] buffer = new byte[inputStream.available()]; while (inputStream.read(buffer) != -1) ; return new String(buffer); } catch (IOException e) { e.printStackTrace(); } return null; } }
package org.osmdroid.views.overlay; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.graphics.Region; import android.view.MotionEvent; import org.osmdroid.api.IGeoPoint; import org.osmdroid.library.R; import org.osmdroid.util.BoundingBox; import org.osmdroid.util.GeoPoint; import org.osmdroid.util.PointL; import org.osmdroid.views.MapView; import org.osmdroid.views.Projection; import org.osmdroid.views.overlay.infowindow.BasicInfoWindow; import org.osmdroid.views.overlay.infowindow.InfoWindow; import org.osmdroid.views.overlay.infowindow.MarkerInfoWindow; import org.osmdroid.views.overlay.milestones.MilestoneManager; import java.util.ArrayList; import java.util.List; public class Polygon extends OverlayWithIW { private final Path mPath = new Path(); //Path drawn is kept for click detection private LinearRing mOutline = new LinearRing(mPath); private ArrayList<LinearRing> mHoles = new ArrayList<>(); protected static InfoWindow mDefaultInfoWindow = null; protected OnClickListener mOnClickListener; /** Paint settings. */ private Paint mFillPaint; private Paint mOutlinePaint; private List<MilestoneManager> mMilestoneManagers = new ArrayList<>(); private GeoPoint mInfoWindowLocation; // Constructors public Polygon(){ this(null); } public Polygon(MapView mapView) { if (mapView != null) { if (mDefaultInfoWindow == null || mDefaultInfoWindow.getMapView() != mapView) { mDefaultInfoWindow = new BasicInfoWindow(R.layout.bonuspack_bubble, mapView); } } setInfoWindow(mDefaultInfoWindow); mFillPaint = new Paint(); mFillPaint.setColor(Color.TRANSPARENT); mFillPaint.setStyle(Paint.Style.FILL); mOutlinePaint = new Paint(); mOutlinePaint.setColor(Color.BLACK); mOutlinePaint.setStrokeWidth(10.0f); mOutlinePaint.setStyle(Paint.Style.STROKE); mOutlinePaint.setAntiAlias(true); } // Getter & Setter public int getFillColor() { return mFillPaint.getColor(); } public int getStrokeColor() { return mOutlinePaint.getColor(); } public float getStrokeWidth() { return mOutlinePaint.getStrokeWidth(); } /** @return the Paint used for the outline. This allows to set advanced Paint settings. */ public Paint getOutlinePaint(){ return mOutlinePaint; } /** * @return the Paint used for the filling. This allows to set advanced Paint settings. * @since 6.0.2 */ public Paint getFillPaint() { return mFillPaint; } public void setGeodesic(boolean geodesic) { mOutline.setGeodesic(geodesic); } public boolean isGeodesic() { return mOutline.isGeodesic(); } /** * @return a copy of the list of polygon's vertices. * Warning: changes on this list may cause strange results on the polygon display. */ public List<GeoPoint> getPoints(){ //TODO This is completely wrong: // - this is not a copy, but a direct handler to the list itself. // - if geodesic, the outline points are not identical to original points. return mOutline.getPoints(); } public boolean isVisible(){ return isEnabled(); } public void setFillColor(final int fillColor) { mFillPaint.setColor(fillColor); } public void setStrokeColor(final int color) { mOutlinePaint.setColor(color); } public void setStrokeWidth(final float width) { mOutlinePaint.setStrokeWidth(width); } public void setVisible(boolean visible){ setEnabled(visible); } /** Set the InfoWindow to be used. * Default is a BasicInfoWindow, with the layout named "bonuspack_bubble". * You can use this method either to use your own layout, or to use your own sub-class of InfoWindow. * If you don't want any InfoWindow to open, you can set it to null. */ public void setInfoWindow(InfoWindow infoWindow){ if (mInfoWindow != null){ if (mInfoWindow.getRelatedObject()==this) mInfoWindow.setRelatedObject(null); if (mInfoWindow != mDefaultInfoWindow) { mInfoWindow.onDetach(); } } mInfoWindow = infoWindow; } /** * Set the points of the polygon outline. * Note that a later change in the original points List will have no effect. * To remove/change points, you must call setPoints again. * If geodesic mode has been set, the long segments will follow the earth "great circle". */ public void setPoints(final List<GeoPoint> points) { mOutline.setPoints(points); setDefaultInfoWindowLocation(); } /** * Add the point at the end of the polygon outline. * If geodesic mode has been set, the long segments will follow the earth "great circle". */ public void addPoint(GeoPoint p){ mOutline.addPoint(p); } public void setHoles(List<? extends List<GeoPoint>> holes){ mHoles = new ArrayList<LinearRing>(holes.size()); for (List<GeoPoint> sourceHole:holes){ LinearRing newHole = new LinearRing(mPath); newHole.setGeodesic(mOutline.isGeodesic()); newHole.setPoints(sourceHole); mHoles.add(newHole); } } /** * returns a copy of the holes this polygon contains * @return never null */ public List<List<GeoPoint>> getHoles(){ List<List<GeoPoint>> result = new ArrayList<List<GeoPoint>>(mHoles.size()); for (LinearRing hole:mHoles){ result.add(hole.getPoints()); //TODO: completely wrong: // hole.getPoints() doesn't return a copy but a direct handler to the internal list. // - if geodesic, this is not the same points as the original list. } return result; } /** Build a list of GeoPoint as a circle. * @param center center of the circle * @param radiusInMeters * @return the list of GeoPoint */ public static ArrayList<GeoPoint> pointsAsCircle(GeoPoint center, double radiusInMeters){ ArrayList<GeoPoint> circlePoints = new ArrayList<GeoPoint>(360/6); for (int f = 0; f < 360; f += 6){ GeoPoint onCircle = center.destinationPoint(radiusInMeters, f); circlePoints.add(onCircle); } return circlePoints; } /** Build a list of GeoPoint as a rectangle. * @param rectangle defined as a BoundingBox * @return the list of 4 GeoPoint */ public static ArrayList<IGeoPoint> pointsAsRect(BoundingBox rectangle){ ArrayList<IGeoPoint> points = new ArrayList<IGeoPoint>(4); points.add(new GeoPoint(rectangle.getLatNorth(), rectangle.getLonWest())); points.add(new GeoPoint(rectangle.getLatNorth(), rectangle.getLonEast())); points.add(new GeoPoint(rectangle.getLatSouth(), rectangle.getLonEast())); points.add(new GeoPoint(rectangle.getLatSouth(), rectangle.getLonWest())); return points; } /** Build a list of GeoPoint as a rectangle. * @param center of the rectangle * @param lengthInMeters on longitude * @param widthInMeters on latitude * @return the list of 4 GeoPoint */ public static ArrayList<IGeoPoint> pointsAsRect(GeoPoint center, double lengthInMeters, double widthInMeters){ ArrayList<IGeoPoint> points = new ArrayList<IGeoPoint>(4); GeoPoint east = center.destinationPoint(lengthInMeters*0.5, 90.0f); GeoPoint south = center.destinationPoint(widthInMeters*0.5, 180.0f); double westLon = center.getLongitude()*2 - east.getLongitude(); double northLat = center.getLatitude()*2 - south.getLatitude(); points.add(new GeoPoint(south.getLatitude(), east.getLongitude())); points.add(new GeoPoint(south.getLatitude(), westLon)); points.add(new GeoPoint(northLat, westLon)); points.add(new GeoPoint(northLat, east.getLongitude())); return points; } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { if (shadow) { return; } final Projection pj = mapView.getProjection(); mPath.rewind(); mOutline.setClipArea(mapView); final PointL offset = mOutline.buildPathPortion(pj, null, mMilestoneManagers.size() > 0); for (final MilestoneManager milestoneManager : mMilestoneManagers) { milestoneManager.init(); milestoneManager.setDistances(mOutline.getDistances()); for (final PointL point : mOutline.getPointsForMilestones()) { milestoneManager.add(point.x, point.y); } milestoneManager.end(); } for (LinearRing hole:mHoles){ hole.setClipArea(mapView); hole.buildPathPortion(pj, offset, mMilestoneManagers.size() > 0); } mPath.setFillType(Path.FillType.EVEN_ODD); //for correct support of holes canvas.drawPath(mPath, mFillPaint); canvas.drawPath(mPath, mOutlinePaint); for (final MilestoneManager milestoneManager : mMilestoneManagers) { milestoneManager.draw(canvas); } if (isInfoWindowOpen() && mInfoWindow!=null && mInfoWindow.getRelatedObject()==this) { mInfoWindow.draw(); } } /** * Show the infowindow, if any. It will be opened either at the latest location, if any, * or to a default location computed by setDefaultInfoWindowLocation method. * Note that you can manually set this location with: setInfoWindowLocation */ public void showInfoWindow(){ if (mInfoWindow != null && mInfoWindowLocation != null) mInfoWindow.open(this, mInfoWindowLocation, 0, 0); } /** Important note: this function returns correct results only if the Polygon has been drawn before, * and if the MapView positioning has not changed. * @param event * @return true if the Polygon contains the event position. */ public boolean contains(MotionEvent event){ if (mPath.isEmpty()) return false; RectF bounds = new RectF(); //bounds of the Path mPath.computeBounds(bounds, true); Region region = new Region(); //Path has been computed in #draw (we assume that if it can be clicked, it has been drawn before). region.setPath(mPath, new Region((int)bounds.left, (int)bounds.top, (int) (bounds.right), (int) (bounds.bottom))); return region.contains((int)event.getX(), (int)event.getY()); } /** * Default listener for a single tap event on a Polygon: * set the infowindow at the tapped position, and open the infowindow (if any). * @param event * @param mapView * @return true if tapped */ @Override public boolean onSingleTapConfirmed(final MotionEvent event, final MapView mapView){ Projection pj = mapView.getProjection(); GeoPoint eventPos = (GeoPoint)pj.fromPixels((int)event.getX(), (int)event.getY()); boolean tapped = contains(event); if (tapped) { if (mOnClickListener == null) { return onClickDefault(this, mapView, eventPos); } else { return mOnClickListener.onClick(this, mapView, eventPos); } } else return tapped; } /** * @return the geopoint location where the infowindow should point at. * Doesn't matter if the infowindow is currently opened or not. * @since 6.0.0 */ public GeoPoint getInfoWindowLocation() { return mInfoWindowLocation; } /** Internal method used to ensure that the infowindow will have a default position in all cases, * so that the user can call showInfoWindow even if no tap occured before. * Currently, set the position on the center of the polygon bounding box. */ protected void setDefaultInfoWindowLocation() { int s = mOutline.getPoints().size(); if (s == 0){ mInfoWindowLocation = new GeoPoint(0.0, 0.0); return; } //TODO: as soon as the polygon bounding box will be a class member, don't compute it again here. mInfoWindowLocation = mOutline.getCenter(null); } /** * Sets the info window anchor point to a geopoint location * @since 6.0.0 * @param location */ public void setInfoWindowLocation(GeoPoint location) { mInfoWindowLocation = location; } @Override public void onDetach(MapView mapView) { mOutline=null; mHoles.clear(); mMilestoneManagers.clear(); onDestroy(); } /** * @since 6.0.0 */ public void setMilestoneManagers(final List<MilestoneManager> pMilestoneManagers) { if (pMilestoneManagers == null) { if (mMilestoneManagers.size() > 0) { mMilestoneManagers.clear(); } } else { mMilestoneManagers = pMilestoneManagers; } } public interface OnClickListener { boolean onClick(Polygon polygon, MapView mapView, GeoPoint eventPos); } /** * default behaviour when no click listener is set */ public boolean onClickDefault(Polygon polygon, MapView mapView, GeoPoint eventPos) { polygon.setInfoWindowLocation(eventPos); polygon.showInfoWindow(); return true; } /** * @since 6.0.2 * @param listener */ public void setOnClickListener(OnClickListener listener) { mOnClickListener = listener; } }
package de.fe1k.game9.components; import de.fe1k.game9.entities.Entity; import de.fe1k.game9.events.Event; import de.fe1k.game9.events.EventCollision; import de.fe1k.game9.events.EventEntityDestroyed; import de.fe1k.game9.events.EventUpdate; import de.fe1k.game9.utils.Direction; import de.nerogar.noise.input.InputHandler; import de.nerogar.noise.util.Logger; import java.util.List; @Depends(components={ComponentMoving.class}) public class ComponentControllable extends Component { private InputHandler inputs; private float jumpPower = 0; private boolean wasKeyDown = false; public ComponentControllable(InputHandler inputHandler) { this.inputs = inputHandler; Event.register(EventUpdate.class, this::update); Event.register(EventCollision.class, this::collision); } private void update(EventUpdate event) { ComponentMoving moving = getOwner().getComponent(ComponentMoving.class); boolean isKeyDown = inputs.isKeyDown(' '); boolean onGround = moving.touching[Direction.DOWN.val]; if (onGround) { jumpPower = 1; } if (isKeyDown && !(onGround && wasKeyDown)) { moving.velocity.add(moving.gravity.multiplied(-0.09f * jumpPower)); jumpPower *= 1 - (10 * event.deltaTime); } moving.velocity.setX(10f); wasKeyDown = isKeyDown; } private void collision(EventCollision event) { if (!event.movingComponent.getOwner().equals(getOwner())) { return; } if (event.collisionDirection.isHorizontal()) { // death Event.trigger(new EventEntityDestroyed(getOwner())); resetPosition(); } } public void resetPosition() { List<ComponentStartMarker> starts = Entity.getComponents(ComponentStartMarker.class); if (starts.isEmpty()) { Logger.getErrorStream().printf("No start marker found, can't teleport to start!"); return; } getOwner().teleport(starts.get(0).getOwner().getPosition()); } @Override public void destroy() { Event.unregister(EventUpdate.class, this::update); Event.unregister(EventCollision.class, this::collision); } }
package de.unipaderborn.visuflow.ui.graph; import static de.unipaderborn.visuflow.model.DataModel.EA_TOPIC_DATA_FILTER_GRAPH; import static de.unipaderborn.visuflow.model.DataModel.EA_TOPIC_DATA_MODEL_CHANGED; import static de.unipaderborn.visuflow.model.DataModel.EA_TOPIC_DATA_SELECTION; import static de.unipaderborn.visuflow.model.DataModel.EA_TOPIC_DATA_UNIT_CHANGED; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.Image; import java.awt.Label; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import org.apache.commons.lang.StringEscapeUtils; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.graphstream.algorithm.Toolkit; import org.graphstream.graph.Edge; import org.graphstream.graph.Graph; import org.graphstream.graph.Node; import org.graphstream.graph.implementations.MultiGraph; import org.graphstream.ui.geom.Point3; import org.graphstream.ui.graphicGraph.GraphicElement; import org.graphstream.ui.layout.Layout; import org.graphstream.ui.layout.springbox.implementations.SpringBox; import org.graphstream.ui.swingViewer.ViewPanel; import org.graphstream.ui.view.Viewer; import org.graphstream.ui.view.ViewerListener; import org.osgi.service.event.Event; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; import com.google.common.base.Optional; import de.unipaderborn.visuflow.ProjectPreferences; import de.unipaderborn.visuflow.builder.GlobalSettings; import de.unipaderborn.visuflow.debug.handlers.NavigationHandler; import de.unipaderborn.visuflow.model.DataModel; import de.unipaderborn.visuflow.model.VFClass; import de.unipaderborn.visuflow.model.VFEdge; import de.unipaderborn.visuflow.model.VFMethod; import de.unipaderborn.visuflow.model.VFMethodEdge; import de.unipaderborn.visuflow.model.VFNode; import de.unipaderborn.visuflow.model.VFUnit; import de.unipaderborn.visuflow.model.graph.ControlFlowGraph; import de.unipaderborn.visuflow.model.graph.ICFGStructure; import de.unipaderborn.visuflow.ui.view.filter.ReturnPathFilter; import de.unipaderborn.visuflow.util.ServiceUtil; import scala.collection.mutable.HashSet; import soot.jimple.InvokeExpr; import soot.jimple.ReturnStmt; import soot.jimple.ReturnVoidStmt; import soot.jimple.Stmt; public class GraphManager implements Runnable, ViewerListener, EventHandler { // private static final transient Logger logger = Visuflow.getDefault().getLogger(); Graph graph; String styleSheet; int maxLength; private Viewer viewer; private ViewPanel view; List<VFClass> analysisData; static Node start = null; static Node end, previous = null; static Map<Node, Node> map = new HashMap<>(); static HashSet<Node> setOfNode = new HashSet<>(); Container panel; JApplet applet; JButton zoomInButton, zoomOutButton, showICFGButton, btColor; JToolBar headerBar, settingsBar; JTextField searchText; JLabel header; JDialog dialog; JPanel panelColor; JColorChooser jcc; List<JButton> stmtTypes; double zoomInDelta, zoomOutDelta, maxZoomPercent, minZoomPercent, panXDelta, panYDelta; boolean autoLayoutEnabled = false; Layout graphLayout = new SpringBox(); private JButton panLeftButton; private JButton panRightButton; private JButton panUpButton; private JButton panDownButton; private JPopupMenu popUp; private BufferedImage imgLeft; private BufferedImage imgRight; private BufferedImage imgUp; private BufferedImage imgDown; private BufferedImage imgPlus; private BufferedImage imgMinus; private int x = 0; private int y = 0; private boolean CFG; // following 3 variables are used for graph dragging with the mouse private boolean draggingGraph = false; private Point mouseDraggedFrom; private Point mouseDraggedTo; private JMenuItem navigateToJimple; private JMenuItem navigateToJava; private JMenuItem showInUnitView; private JMenuItem followCall; private JMenuItem followReturn; private JMenuItem setCosAttr; private JMenu callGraphOption; private JMenuItem cha; private JMenuItem spark; public GraphManager(String graphName, String styleSheet) { // System.setProperty("sun.awt.noerasebackground", "true"); // System.setProperty("org.graphstream.ui.renderer", "org.graphstream.ui.j2dviewer.J2DGraphRenderer"); this.panXDelta = 2; this.panYDelta = 2; this.zoomInDelta = .075; this.zoomOutDelta = .075; this.maxZoomPercent = 0.2; this.minZoomPercent = 1.0; this.maxLength = 45; this.styleSheet = styleSheet; createGraph(graphName); createUI(); renderICFG(ServiceUtil.getService(DataModel.class).getIcfg()); adjustToolbarButtonHeights(); } private void adjustToolbarButtonHeights() { Dimension d = new Dimension(90, 32); showICFGButton.setSize(d); showICFGButton.setPreferredSize(d); showICFGButton.setMinimumSize(d); showICFGButton.setMaximumSize(d); d = new Dimension(100, 32); btColor.setSize(d); btColor.setPreferredSize(d); btColor.setMinimumSize(d); btColor.setMaximumSize(d); } public Container getApplet() { return applet.getRootPane(); } private void registerEventHandler() { String[] topics = new String[] { EA_TOPIC_DATA_FILTER_GRAPH, EA_TOPIC_DATA_SELECTION, EA_TOPIC_DATA_MODEL_CHANGED, EA_TOPIC_DATA_UNIT_CHANGED, "GraphReady" }; Hashtable<String, Object> properties = new Hashtable<>(); properties.put(EventConstants.EVENT_TOPIC, topics); ServiceUtil.registerService(EventHandler.class, this, properties); } void createGraph(String graphName) { graph = new MultiGraph(graphName); graph.addAttribute("ui.stylesheet", styleSheet); graph.setStrict(true); graph.setAutoCreate(true); graph.addAttribute("ui.quality"); graph.addAttribute("ui.antialias"); viewer = new Viewer(graph, Viewer.ThreadingModel.GRAPH_IN_GUI_THREAD); viewer.setCloseFramePolicy(Viewer.CloseFramePolicy.CLOSE_VIEWER); view = viewer.addDefaultView(false); view.getCamera().setAutoFitView(true); } private void reintializeGraph() throws Exception { if (graph != null) { graph.clear(); graph.addAttribute("ui.stylesheet", styleSheet); graph.setStrict(true); graph.setAutoCreate(true); graph.addAttribute("ui.quality"); graph.addAttribute("ui.antialias"); } else { throw new Exception("Graph is null"); } } private void createUI() { createIcons(); createZoomControls(); createShowICFGButton(); createPanningButtons(); createPopUpMenu(); createViewListeners(); createSearchText(); createHeaderBar(); createSettingsBar(); createPanel(); createAppletContainer(); } private void panUp() { Point3 currCenter = view.getCamera().getViewCenter(); view.getCamera().setViewCenter(currCenter.x, currCenter.y + panYDelta, 0); } private void panDown() { Point3 currCenter = view.getCamera().getViewCenter(); view.getCamera().setViewCenter(currCenter.x, currCenter.y - panYDelta, 0); } private void panLeft() { Point3 currCenter = view.getCamera().getViewCenter(); view.getCamera().setViewCenter(currCenter.x - panXDelta, currCenter.y, 0); } private void panRight() { Point3 currCenter = view.getCamera().getViewCenter(); view.getCamera().setViewCenter(currCenter.x + panXDelta, currCenter.y, 0); } private void panToNode(String nodeId) { // view.getCamera().resetView(); Node panToNode = graph.getNode(nodeId); double[] pos = Toolkit.nodePosition(panToNode); double currPosition = view.getCamera().getViewCenter().y; Point3 viewCenter = view.getCamera().getViewCenter(); double diff = pos[1] - viewCenter.y; double sign = Math.signum(diff); double steps = 15; double stepWidth = Math.abs(diff) / steps; for (int i = 0; i < steps; i++) { try { Thread.sleep(40); } catch (InterruptedException e) { e.printStackTrace(); } currPosition += sign * stepWidth; view.getCamera().setViewCenter(pos[0], currPosition, 0.0); } } private void defaultPanZoom() { int count = 0; if (graph.getNodeCount() > 10) count = 10; for (int i = 0; i < count; i++) { try { Thread.sleep(40); zoomOut(); } catch (InterruptedException e) { e.printStackTrace(); } /* * SwingUtilities.invokeLater(new Runnable() { * * @Override public void run() { GraphManager.this.zoomIn(); } }); */ } } private void createPanningButtons() { panLeftButton = new JButton(""); panRightButton = new JButton(""); panUpButton = new JButton(""); panDownButton = new JButton(""); panLeftButton.setToolTipText("shift + arrow key left"); panRightButton.setToolTipText("shift + arrow key right"); panUpButton.setToolTipText("shift + arrow key up"); panDownButton.setToolTipText("shift + arrow key down"); panLeftButton.setIcon(new ImageIcon(getScaledImage(imgLeft, 20, 20))); panRightButton.setIcon(new ImageIcon(getScaledImage(imgRight, 20, 20))); panUpButton.setIcon(new ImageIcon(getScaledImage(imgUp, 20, 20))); panDownButton.setIcon(new ImageIcon(getScaledImage(imgDown, 20, 20))); panLeftButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panLeft(); } }); panRightButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panRight(); } }); panUpButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panUp(); } }); panDownButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { panDown(); } }); } private void createPopUpMenu() { navigateToJimple = new JMenuItem("Navigate to Jimple"); navigateToJava = new JMenuItem("Navigate to Java"); showInUnitView = new JMenuItem("Highlight on Units view"); setCosAttr = new JMenuItem("Set custom attribute"); followCall = new JMenuItem("Follow the Call"); followReturn = new JMenuItem("Follow the Return"); callGraphOption = new JMenu("Call Graph Option"); cha = new JMenuItem("CHA"); spark = new JMenuItem("SPARK"); callGraphOption.add(cha); callGraphOption.add(spark); followCall.setVisible(false); followReturn.setVisible(false); navigateToJimple.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GraphicElement curElement = view.findNodeOrSpriteAt(x, y); if (curElement == null) return; Node curr = graph.getNode(curElement.getId()); Object node = curr.getAttribute("nodeUnit"); NavigationHandler handler = new NavigationHandler(); if (node instanceof VFNode) { ArrayList<VFUnit> units = new ArrayList<>(); units.add(((VFNode) node).getVFUnit()); handler.highlightJimpleSource(units); } } }); setCosAttr.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GraphicElement curElement = view.findNodeOrSpriteAt(x, y); if (curElement == null) { return; } Node curr = graph.getNode(curElement.getId()); Object node = curr.getAttribute("nodeUnit"); if (node instanceof VFNode) { VFUnit selectedVF = ((VFNode) node).getVFUnit(); setCosAttr(selectedVF, curr); // curr.setAttribute("ui.color", jcc.getColor()); } } }); navigateToJava.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GraphicElement curElement = view.findNodeOrSpriteAt(x, y); if (curElement == null) return; Node curr = graph.getNode(curElement.getId()); Object node = curr.getAttribute("nodeUnit"); NavigationHandler handler = new NavigationHandler(); if (node instanceof VFNode) { ArrayList<VFUnit> units = new ArrayList<>(); units.add(((VFNode) node).getVFUnit()); handler.highlightJavaSource(units.get(0)); } } }); showInUnitView.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { DataModel dataModel = ServiceUtil.getService(DataModel.class); GraphicElement curElement = view.findNodeOrSpriteAt(x, y); if (curElement == null) return; Node curr = graph.getNode(curElement.getId()); Object node = curr.getAttribute("nodeUnit"); if (node instanceof VFNode) { ArrayList<VFUnit> units = new ArrayList<>(); units.add(((VFNode) node).getVFUnit()); ArrayList<VFNode> nodes = new ArrayList<>(); nodes.add((VFNode) node); try { dataModel.filterGraph(nodes, true, true, null); } catch (Exception e1) { e1.printStackTrace(); } } } }); followCall.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GraphicElement curElement = view.findNodeOrSpriteAt(x, y); if (curElement == null) return; Node curr = graph.getNode(curElement.getId()); Object node = curr.getAttribute("nodeUnit"); if (node instanceof VFNode) { if (((Stmt) ((VFNode) node).getUnit()).containsInvokeExpr()) { callInvokeExpr(((Stmt) ((VFNode) node).getUnit()).getInvokeExpr()); } } } }); followReturn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GraphicElement curElement = view.findNodeOrSpriteAt(x, y); if (curElement == null) return; Node curr = graph.getNode(curElement.getId()); Object node = curr.getAttribute("nodeUnit"); if (node instanceof VFNode) { if (((VFNode) node).getUnit() instanceof ReturnStmt || ((VFNode) node).getUnit() instanceof ReturnVoidStmt) { System.out.println("Return ahoy"); List<VFUnit> list = new ArrayList<>(); for (VFUnit edge : ((VFNode) node).getVFUnit().getVfMethod().getIncomingEdges()) { list.add(edge); } Display.getDefault().syncExec(new Runnable() { @Override public void run() { Shell shell = new Shell(); ReturnPathFilter returnFilter = new ReturnPathFilter(shell); returnFilter.setPaths(list); returnFilter.setInitialPattern("?"); returnFilter.open(); if (returnFilter.getFirstResult() != null) { returnToCaller((VFUnit) returnFilter.getFirstResult()); } shell.close(); } }); } } } }); cha.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GlobalSettings.put("CallGraphOption", "CHA"); ServiceUtil.getService(DataModel.class).triggerProjectRebuild(); header.setText(header.getText() + " } }); spark.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GlobalSettings.put("CallGraphOption", "SPARK"); ServiceUtil.getService(DataModel.class).triggerProjectRebuild(); header.setText(header.getText() + " } }); } private void createIcons() { try { ClassLoader loader = GraphManager.class.getClassLoader(); imgLeft = ImageIO.read(loader.getResource("/icons/left.png")); imgRight = ImageIO.read(loader.getResource("/icons/right.png")); imgUp = ImageIO.read(loader.getResource("/icons/up.png")); imgDown = ImageIO.read(loader.getResource("/icons/down.png")); imgPlus = ImageIO.read(loader.getResource("/icons/plus.png")); imgMinus = ImageIO.read(loader.getResource("/icons/minus.png")); } catch (IOException e) { e.printStackTrace(); } } private Image getScaledImage(Image srcImg, int w, int h) { BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = resizedImg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(srcImg, 0, 0, w, h, null); g2.dispose(); return resizedImg; } private void createShowICFGButton() { showICFGButton = new JButton("Show ICFG"); showICFGButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { renderICFG(ServiceUtil.getService(DataModel.class).getIcfg()); } }); } private void createSearchText() { this.searchText = new JTextField("Search graph"); searchText.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String searchString = searchText.getText().toLowerCase(); ArrayList<VFNode> vfNodes = new ArrayList<>(); ArrayList<VFUnit> vfUnits = new ArrayList<>(); for (Node node : graph) { if (node.getAttribute("ui.label").toString().toLowerCase().contains((searchString))) { vfNodes.add((VFNode) node.getAttribute("nodeUnit")); vfUnits.add(((VFNode) node.getAttribute("nodeUnit")).getVFUnit()); } } try { DataModel model = ServiceUtil.getService(DataModel.class); model.filterGraph(vfNodes, true, true, "filter"); } catch (Exception e1) { e1.printStackTrace(); } NavigationHandler handler = new NavigationHandler(); handler.highlightJimpleSource(vfUnits); } }); } private void createAppletContainer() { applet = new JApplet(); applet.add(panel); } private void createSettingsBar() { settingsBar = new JToolBar("ControlsBar", JToolBar.HORIZONTAL); settingsBar.add(zoomInButton); settingsBar.add(zoomOutButton); settingsBar.add(showICFGButton); settingsBar.add(btColor); settingsBar.add(panLeftButton); settingsBar.add(panRightButton); settingsBar.add(panUpButton); settingsBar.add(panDownButton); settingsBar.add(searchText); } private void createHeaderBar() { this.headerBar = new JToolBar("Header"); this.headerBar.setFloatable(false); this.header = new JLabel("ICFG"); this.headerBar.add(header); } private void createPanel() { JFrame temp = new JFrame(); temp.setLayout(new BorderLayout()); panel = temp.getContentPane(); panel.add(headerBar,BorderLayout.PAGE_START); panel.add(view); panel.add(settingsBar, BorderLayout.PAGE_END); } private void createViewListeners() { MouseMotionListener defaultListener = view.getMouseMotionListeners()[0]; view.removeMouseMotionListener(defaultListener); view.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { int rotationDirection = e.getWheelRotation(); if (rotationDirection > 0) zoomIn(); else zoomOut(); } }); view.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseMoved(MouseEvent event) { GraphicElement curElement = view.findNodeOrSpriteAt(event.getX(), event.getY()); if (curElement == null) { view.setToolTipText(null); } if (curElement != null) { Node node = graph.getNode(curElement.getId()); String result = "<html><table>"; int maxToolTipLength = 0; for (String key : node.getEachAttributeKey()) { if (key.startsWith("nodeData")) { Object value = node.getAttribute(key); String tempVal = key.substring(key.lastIndexOf(".") + 1) + " : " + value.toString(); if (tempVal.length() > maxToolTipLength) { maxToolTipLength = tempVal.length(); } result += "<tr><td>" + key.substring(key.lastIndexOf(".") + 1) + "</td>" + "<td>" + value.toString() + "</td></tr>"; } } result += "</table></html>"; view.setToolTipText(result); } } @Override public void mouseDragged(MouseEvent e) { if (draggingGraph) { dragGraph(e); } else { defaultListener.mouseDragged(e); } } private void dragGraph(MouseEvent e) { if (mouseDraggedFrom == null) { mouseDraggedFrom = e.getPoint(); } else { if (mouseDraggedTo != null) { mouseDraggedFrom = mouseDraggedTo; } mouseDraggedTo = e.getPoint(); Point3 from = view.getCamera().transformPxToGu(mouseDraggedFrom.x, mouseDraggedFrom.y); Point3 to = view.getCamera().transformPxToGu(mouseDraggedTo.x, mouseDraggedTo.y); double deltaX = from.x - to.x; double deltaY = from.y - to.y; double deltaZ = from.z - to.z; Point3 viewCenter = view.getCamera().getViewCenter(); view.getCamera().setViewCenter(viewCenter.x + deltaX, viewCenter.y + deltaY, viewCenter.z + deltaZ); } } }); view.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { draggingGraph = false; } @Override public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { // reset mouse drag tracking mouseDraggedFrom = null; mouseDraggedTo = null; draggingGraph = true; } } @Override public void mouseExited(MouseEvent e) { // noop } @Override public void mouseEntered(MouseEvent e) { // noop } @Override public void mouseClicked(MouseEvent e) { DataModel dataModel = ServiceUtil.getService(DataModel.class); GraphicElement curElement = view.findNodeOrSpriteAt(e.getX(), e.getY()); if (e.getButton() == MouseEvent.BUTTON3 && !CFG) { x = e.getX(); y = e.getY(); popUp = new JPopupMenu("right click menu"); popUp.add(callGraphOption); popUp.show(e.getComponent(), x, y); } if (e.getButton() == MouseEvent.BUTTON3 && CFG) { x = e.getX(); y = e.getY(); if (curElement != null) { popUp = new JPopupMenu("right click menu"); popUp.add(navigateToJimple); popUp.add(navigateToJava); popUp.add(showInUnitView); popUp.add(setCosAttr); popUp.add(followCall); popUp.add(followReturn); popUp.addPopupMenuListener(new PopupMenuListener() { @Override public void popupMenuWillBecomeVisible(PopupMenuEvent arg0) { GraphicElement curElement = view.findNodeOrSpriteAt(x, y); if (curElement == null) { return; } Node curr = graph.getNode(curElement.getId()); Object node = curr.getAttribute("nodeUnit"); if (node instanceof VFNode) { if (((Stmt) ((VFNode) node).getUnit()).containsInvokeExpr()) { followCall.setVisible(true); followReturn.setVisible(false); } else if (((VFNode) node).getUnit() instanceof ReturnStmt || ((VFNode) node).getUnit() instanceof ReturnVoidStmt) { followCall.setVisible(false); followReturn.setVisible(true); } else { followCall.setVisible(false); followReturn.setVisible(false); } } } @Override public void popupMenuCanceled(PopupMenuEvent arg0) { followCall.setVisible(false); followReturn.setVisible(false); } @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) { followCall.setVisible(false); followReturn.setVisible(false); } }); popUp.show(e.getComponent(), x, y); } } if (curElement == null) return; Node curr = graph.getNode(curElement.getId()); if (e.getButton() == MouseEvent.BUTTON1 && !CFG && !((e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK)) { Object node = curr.getAttribute("nodeMethod"); if (node instanceof VFMethod) { VFMethod selectedMethod = (VFMethod) node; try { if (selectedMethod.getControlFlowGraph() == null) throw new Exception("CFG Null Exception"); else { dataModel.setSelectedMethod(selectedMethod, true); } } catch (Exception e1) { e1.printStackTrace(); } } } else if (e.getButton() == MouseEvent.BUTTON1 && CFG && !((e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK)) { Object node = curr.getAttribute("nodeUnit"); NavigationHandler handler = new NavigationHandler(); if (node instanceof VFNode) { ArrayList<VFUnit> units = new ArrayList<>(); units.add(((VFNode) node).getVFUnit()); handler.highlightJimpleSource(units); handler.highlightJavaSource(units.get(0)); ArrayList<VFNode> nodes = new ArrayList<>(); nodes.add((VFNode) node); try { dataModel.filterGraph(nodes, true, true, null); } catch (Exception e1) { e1.printStackTrace(); } } } else if (e.getButton() == MouseEvent.BUTTON1 && (e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) { String id = curr.getId(); if (id != null) toggleNode(id); } if (e.getButton() == MouseEvent.BUTTON3 && CFG) { x = e.getX(); y = e.getY(); if (curElement != null) popUp.show(e.getComponent(), x, y); } } }); view.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (e.isShiftDown()) { switch (keyCode) { case KeyEvent.VK_UP: // handle up panUp(); break; case KeyEvent.VK_DOWN: // handle down panDown(); break; case KeyEvent.VK_LEFT: // handle left panLeft(); break; case KeyEvent.VK_RIGHT: // handle right panRight(); break; } } } }); } private void returnToCaller(VFUnit unit) { if (unit == null) return; DataModel dataModel = ServiceUtil.getService(DataModel.class); try { if (unit.getVfMethod().getControlFlowGraph() == null) throw new Exception("CFG Null Exception"); else { dataModel.setSelectedMethod(unit.getVfMethod(), true); } } catch (Exception e1) { e1.printStackTrace(); } } private void callInvokeExpr(InvokeExpr expr) { if (expr == null) return; DataModel dataModel = ServiceUtil.getService(DataModel.class); System.out.println(expr); VFMethod selectedMethod = dataModel.getVFMethodByName(expr.getMethod()); try { if (selectedMethod.getControlFlowGraph() == null) throw new Exception("CFG Null Exception"); else { dataModel.setSelectedMethod(selectedMethod, true); } } catch (Exception e1) { e1.printStackTrace(); } } private void zoomOut() { double viewPercent = view.getCamera().getViewPercent(); if (viewPercent > maxZoomPercent) view.getCamera().setViewPercent(viewPercent - zoomInDelta); } private void zoomIn() { double viewPercent = view.getCamera().getViewPercent(); if (viewPercent < minZoomPercent) view.getCamera().setViewPercent(viewPercent + zoomOutDelta); } private void createZoomControls() { zoomInButton = new JButton(); zoomOutButton = new JButton(); zoomInButton.setIcon(new ImageIcon(getScaledImage(imgPlus, 20, 20))); zoomOutButton.setIcon(new ImageIcon(getScaledImage(imgMinus, 20, 20))); zoomInButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { zoomOut(); } }); zoomOutButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { zoomIn(); } }); colorNode(); } private void colorNode() { jcc = new JColorChooser(Color.RED); jcc.getSelectionModel().addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { Color color = jcc.getColor(); System.out.println("color:" + color); } }); dialog = JColorChooser.createDialog(null, "Color Chooser", true, jcc, null, null); panelColor = new JPanel(new GridLayout(0, 2)); btColor = new JButton("Color nodes"); btColor.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { colorTheGraph(); } }); } private void filterGraphNodes(List<VFNode> nodes, boolean selected, boolean panToNode, String uiClassName) { boolean panned = false; if (uiClassName == null) { uiClassName = "filter"; } Iterable<? extends Node> graphNodes = graph.getEachNode(); for (Node node : graphNodes) { if (node.hasAttribute("ui.class")) { node.removeAttribute("ui.class"); } for (VFNode vfNode : nodes) { if (node.getAttribute("unit").toString().contentEquals(vfNode.getUnit().toString())) { if (selected) { node.removeAttribute("ui.color"); node.addAttribute("ui.class", uiClassName); } if (!panned && panToNode) { this.panToNode(node.getId()); panned = true; } } } } } private void renderICFG(ICFGStructure icfg) { if (icfg == null) { return; } Iterator<VFMethodEdge> iterator = icfg.listEdges.iterator(); try { reintializeGraph(); } catch (Exception e) { e.printStackTrace(); } while (iterator.hasNext()) { VFMethodEdge curr = iterator.next(); VFMethod src = curr.getSourceMethod(); VFMethod dest = curr.getDestMethod(); createGraphMethodNode(src); createGraphMethodNode(dest); createGraphMethodEdge(src, dest); } this.CFG = false; this.header.setText("ICFG"); experimentalLayout(); } private void createGraphMethodEdge(VFMethod src, VFMethod dest) { if (graph.getEdge("" + src.getId() + dest.getId()) == null) { graph.addEdge(src.getId() + "" + dest.getId(), src.getId() + "", dest.getId() + "", true); } } private void createGraphMethodNode(VFMethod src) { if (graph.getNode(src.getId() + "") == null) { Node createdNode = graph.addNode(src.getId() + ""); String methodName = src.getSootMethod().getName(); String escapedMethodName = StringEscapeUtils.escapeHtml(methodName); String escapedMethodSignature = StringEscapeUtils.escapeHtml(src.getSootMethod().getSignature()); createdNode.setAttribute("ui.label", methodName); createdNode.setAttribute("nodeData.methodName", escapedMethodName); createdNode.setAttribute("nodeData.methodSignature", escapedMethodSignature); createdNode.setAttribute("nodeData.methodBody", src.getBody().toString().replaceAll(";", ";<br>")); createdNode.setAttribute("nodeData.unescapedMethodName", methodName); createdNode.setAttribute("nodeMethod", src); } } private void renderMethodCFG(ControlFlowGraph interGraph, boolean panToNode) throws Exception { if (interGraph == null) throw new Exception("GraphStructure is null"); this.reintializeGraph(); ListIterator<VFEdge> edgeIterator = interGraph.listEdges.listIterator(); while (edgeIterator.hasNext()) { VFEdge currEdgeIterator = edgeIterator.next(); VFNode src = currEdgeIterator.getSource(); VFNode dest = currEdgeIterator.getDestination(); createGraphNode(src); createGraphNode(dest); createGraphEdge(src, dest); } if (interGraph.listEdges.size() == 1) { VFNode node = interGraph.listNodes.get(0); createGraphNode(node); } this.CFG = true; experimentalLayout(); if (panToNode) { defaultPanZoom(); panToNode(graph.getNodeIterator().next().getId()); } this.header.setText("Method CFG ----> " + ServiceUtil.getService(DataModel.class).getSelectedMethod().toString()); } private void createGraphEdge(VFNode src, VFNode dest) { if (graph.getEdge("" + src.getId() + dest.getId()) == null) { Edge createdEdge = graph.addEdge(src.getId() + "" + dest.getId(), src.getId() + "", dest.getId() + "", true); VFUnit unit = src.getVFUnit(); createdEdge.addAttribute("ui.label", Optional.fromNullable(unit.getOutSet()).or("").toString()); createdEdge.addAttribute("edgeData.outSet", Optional.fromNullable(unit.getInSet()).or("").toString()); } } private void createGraphNode(VFNode node) { if (graph.getNode(node.getId() + "") == null) { Node createdNode = graph.addNode(node.getId() + ""); if (node.getUnit().toString().length() > maxLength) { createdNode.setAttribute("ui.label", node.getUnit().toString().substring(0, maxLength) + "..."); } else { createdNode.setAttribute("ui.label", node.getUnit().toString()); } String str = node.getUnit().toString(); String escapedNodename = StringEscapeUtils.escapeHtml(str); createdNode.setAttribute("unit", str); createdNode.setAttribute("nodeData.unit", escapedNodename); createdNode.setAttribute("nodeData.unitType", node.getUnit().getClass()); String str1 = Optional.fromNullable(node.getVFUnit().getInSet()).or("n/a").toString(); String nodeInSet = StringEscapeUtils.escapeHtml(str1); String str2 = Optional.fromNullable(node.getVFUnit().getInSet()).or("n/a").toString(); String nodeOutSet = StringEscapeUtils.escapeHtml(str2); createdNode.setAttribute("nodeData.inSet", nodeInSet); createdNode.setAttribute("nodeData.outSet", nodeOutSet); Map<String, String> customAttributes = node.getVFUnit().getHmCustAttr(); String attributeData = ""; if(!customAttributes.isEmpty()) { Iterator<Entry<String, String>> customAttributeIterator = customAttributes.entrySet().iterator(); while(customAttributeIterator.hasNext()) { Entry<String, String> curr = customAttributeIterator.next(); // createdNode.setAttribute(arg0, arg1); attributeData += curr.getKey() + " : " + curr.getValue(); attributeData += "<br />"; } createdNode.setAttribute("nodeData.attributes", attributeData); } createdNode.setAttribute("nodeUnit", node); Color nodeColor = new Color(new ProjectPreferences().getColorForNode(node.getUnit().getClass().getName().toString())); createdNode.addAttribute("ui.color", nodeColor); } } @SuppressWarnings("unused") private void getNodesToCollapse(Node n) { boolean present = false; scala.collection.Iterator<Node> setIterator = setOfNode.iterator(); while (setIterator.hasNext()) { if (setIterator.next().equals(n)) { present = true; break; } } if (!present) { Iterator<Edge> edgeIterator = n.getLeavingEdgeIterator(); while (edgeIterator.hasNext()) { Edge edge = edgeIterator.next(); start = edge.getNode1(); Node k = start; while (true) { if (k.getOutDegree() == 1 && k.getInDegree() == 1) { previous = k; k = k.getEachLeavingEdge().iterator().next().getNode1(); } else { break; } } map.put(start, previous); setOfNode.add(n); getNodesToCollapse(k); } } } /* * private void experimentalLayoutOld() if (!CFG) { viewer.enableAutoLayout(new SpringBox()); view.getCamera().resetView(); return; } * viewer.disableAutoLayout(); * * double rowSpacing = 3.0; double columnSpacing = 3.0; Iterator<Node> nodeIterator = graph.getNodeIterator(); int totalNodeCount = graph.getNodeCount(); * int currNodeIndex = 0; while (nodeIterator.hasNext()) { Node curr = nodeIterator.next(); if (curr.hasAttribute("layout.visited")) { continue; } int * currEdgeCount = curr.getOutDegree(); int currEdgeIndex = 0; if (currEdgeCount > 1) { Iterator<Edge> currEdgeIterator = curr.getEdgeIterator(); * curr.setAttribute("xyz", 0.0, ((totalNodeCount * rowSpacing) - currNodeIndex), 0.0); curr.setAttribute("layout.visited"); currNodeIndex++; while * (currEdgeIterator.hasNext()) { Node temp = currEdgeIterator.next().getOpposite(curr); temp.setAttribute("xyz", ((columnSpacing - currEdgeIndex) * * currEdgeCount), ((totalNodeCount * columnSpacing) - currNodeIndex), 0.0); curr.setAttribute("layout.visited"); currEdgeIndex++; } currNodeIndex++; } * curr.setAttribute("xyz", 0.0, ((totalNodeCount * rowSpacing) - currNodeIndex), 0.0); curr.setAttribute("layout.visited"); currNodeIndex++; } * * for (Node node : graph) { double[] pos = Toolkit.nodePosition(graph, node.getId()); int inDegree = node.getInDegree(); int outDegree = * node.getOutDegree(); if (inDegree == 0) continue; if (inDegree > outDegree) { node.setAttribute("xyz", pos[0] - rowSpacing, pos[1], 0.0); } if (outDegree * > inDegree) { node.setAttribute("xyz", pos[0] + rowSpacing, pos[1], 0.0); } if (inDegree > 1 && outDegree > 1 && inDegree == outDegree) { * node.setAttribute("xyz", pos[0] - rowSpacing, pos[1], 0.0); } else continue; } * * view.getCamera().resetView(); } */ private void experimentalLayout() { if (!CFG) { viewer.enableAutoLayout(new SpringBox()); view.getCamera().resetView(); return; } viewer.disableAutoLayout(); Iterator<Node> nodeIterator = graph.getNodeIterator(); Node first = nodeIterator.next(); Iterator<Node> depthFirstIterator = first.getDepthFirstIterator(); //Assign the layer to each node first.setAttribute("layoutLayer", 0); while (depthFirstIterator.hasNext()) { Node curr = depthFirstIterator.next(); int inDegree = curr.getInDegree(); int layer = 1; if (inDegree == 1) { Iterable<Edge> edges = curr.getEachEnteringEdge(); for (Edge edge : edges) { layer = edge.getOpposite(curr).getAttribute("layoutLayer"); layer++; } } if (inDegree > 1) { Iterable<Edge> edges = curr.getEachEnteringEdge(); int parentLayer = layer; for (Edge edge : edges) { Node parent = edge.getOpposite(curr); if (curr.hasAttribute("layoutLayer")) { int currLayer = parent.getAttribute("layoutLayer"); if(currLayer > parentLayer) parentLayer = currLayer; } } layer = parentLayer++; } if(curr.hasAttribute("layoutLayer")) curr.removeAttribute("layoutLayer"); curr.setAttribute("layoutLayer", layer); } HashMap<Integer, Integer> levelCount = new HashMap<>(); for (Node node : graph) { int layer = node.getAttribute("layoutLayer"); if (levelCount.containsKey(layer)) { int currCount = levelCount.get(layer); levelCount.remove(layer); levelCount.put(layer, currCount++); } else { levelCount.put(layer, 1); } } for (Node node : graph) { Collection<Edge> leavingEdgeSet = node.getLeavingEdgeSet(); Edge[] childEdge = new Edge[leavingEdgeSet.size()]; leavingEdgeSet.toArray(childEdge); int directionResolver = childEdge.length/2; int even = childEdge.length % 2; if (even == 0) { for (int i = 0; i < childEdge.length; i++) { Node child = childEdge[i].getOpposite(node); if (i < directionResolver) { child.setAttribute("directionResolver", -1); } else { child.setAttribute("directionResolver", 1); } } } else { for (int i = 0; i < childEdge.length; i++) { Node child = childEdge[i].getOpposite(node); if (i > directionResolver) { child.setAttribute("directionResolver", -1); } else if (i < directionResolver) { child.setAttribute("directionResolver", 1); } } } } //Assign the coordinates to each node double spacingX = 16.0; double spacingY = 3.0; // Iterator<Node> breadthFirstIterator = first.getBreadthFirstIterator(); depthFirstIterator = first.getDepthFirstIterator(); first.setAttribute("xyz", spacingX, spacingY * graph.getNodeCount(), 0.0); while (depthFirstIterator.hasNext()) { Node curr = depthFirstIterator.next(); Node parent = findParentWithHighestLevel(curr); if(parent == null) continue; double[] positionOfParent = Toolkit.nodePosition(parent); int outDegreeOfParent = parent.getOutDegree(); if (outDegreeOfParent == 1) { curr.setAttribute("xyz", positionOfParent[0], positionOfParent[1] - spacingY, 0.0); } else { if(curr.hasAttribute("directionResolver")) curr.setAttribute("xyz", positionOfParent[0] + ((int) curr.getAttribute("directionResolver") * spacingX), positionOfParent[1] - spacingY, 0.0); else curr.setAttribute("xyz", positionOfParent[0], positionOfParent[1] - spacingY, 0.0); } } } Node findParentWithHighestLevel(Node node) { int inDegreeOfNode = node.getInDegree(); Node parent = null; Iterator<Edge> nodeIterator = node.getEachEnteringEdge().iterator(); if(inDegreeOfNode == 1) parent = nodeIterator.next().getOpposite(node); else if (inDegreeOfNode > 1) { parent = nodeIterator.next().getOpposite(node); while (nodeIterator.hasNext()) { Node temp = nodeIterator.next().getOpposite(node); if (temp.hasAttribute("layoutLayer") && (int) temp.getAttribute("layoutLayer") > (int) parent.getAttribute("layoutLayer")) { parent = temp; } } } return parent; } void toggleNode(String id) { Node n = graph.getNode(id); Object[] pos = n.getAttribute("xyz"); Iterator<Node> it = n.getBreadthFirstIterator(true); if (n.hasAttribute("collapsed")) { n.removeAttribute("collapsed"); while (it.hasNext()) { Node m = it.next(); for (Edge e : m.getLeavingEdgeSet()) { e.removeAttribute("ui.hide"); } m.removeAttribute("layout.frozen"); m.setAttribute("x", ((double) pos[0]) + Math.random() * 0.0001); m.setAttribute("y", ((double) pos[1]) + Math.random() * 0.0001); m.removeAttribute("ui.hide"); } n.removeAttribute("ui.class"); } else { n.setAttribute("ui.class", "plus"); n.setAttribute("collapsed"); while (it.hasNext()) { Node m = it.next(); for (Edge e : m.getLeavingEdgeSet()) { e.setAttribute("ui.hide"); } if (n != m) { m.setAttribute("layout.frozen"); // m.setAttribute("x", ((double) pos[0]) + Math.random() * 0.0001); // m.setAttribute("y", ((double) pos[1]) + Math.random() * 0.0001); m.setAttribute("xyz", ((double) pos[0]) + Math.random() * 0.0001, ((double) pos[1]) + Math.random() * 0.0001, 0.0); m.setAttribute("ui.hide"); } } } experimentalLayout(); panToNode(id); } @Override public void run() { this.registerEventHandler(); System.out.println("GraphManager ---> registered for events"); // No need to have the following code. /* * ViewerPipe fromViewer = viewer.newViewerPipe(); fromViewer.addViewerListener(this); fromViewer.addSink(graph); * * // FIXME the Thread.sleep slows down the loop, so that it does not eat up the CPU // but this really should be implemented differently. isn't there * an event listener // or something we can use, so that we call pump() only when necessary while(true) { try { Thread.sleep(1); } catch * (InterruptedException e) { } fromViewer.pump(); } */ } @Override public void buttonPushed(String id) { // noop } @Override public void buttonReleased(String id) { toggleNode(id); experimentalLayout(); } @Override public void viewClosed(String id) { // noop } @SuppressWarnings("unchecked") @Override public void handleEvent(Event event) { if (event.getTopic().contentEquals(DataModel.EA_TOPIC_DATA_MODEL_CHANGED)) { renderICFG((ICFGStructure) event.getProperty("icfg")); } if (event.getTopic().contentEquals(DataModel.EA_TOPIC_DATA_SELECTION)) { VFMethod selectedMethod = (VFMethod) event.getProperty("selectedMethod"); boolean panToNode = (boolean) event.getProperty("panToNode"); try { renderMethodCFG(selectedMethod.getControlFlowGraph(), panToNode); } catch (Exception e) { e.printStackTrace(); } } if (event.getTopic().contentEquals(DataModel.EA_TOPIC_DATA_FILTER_GRAPH)) { filterGraphNodes((List<VFNode>) event.getProperty("nodesToFilter"), (boolean) event.getProperty("selection"), (boolean) event.getProperty("panToNode"), (String) event.getProperty("uiClassName")); } if (event.getTopic().equals(DataModel.EA_TOPIC_DATA_UNIT_CHANGED)) { VFUnit unit = (VFUnit) event.getProperty("unit"); for (Edge edge : graph.getEdgeSet()) { Node src = edge.getSourceNode(); VFNode vfNode = src.getAttribute("nodeUnit"); if (vfNode != null) { VFUnit currentUnit = vfNode.getVFUnit(); if (unit.getFullyQualifiedName().equals(currentUnit.getFullyQualifiedName())) { String outset = Optional.fromNullable(unit.getOutSet()).or("").toString(); edge.setAttribute("ui.label", outset); edge.setAttribute("edgeData.outSet", outset); src.addAttribute("nodeData.inSet", unit.getInSet()); src.addAttribute("nodeData.outSet", unit.getOutSet()); } } } } } public void colorTheGraph() { panelColor.removeAll(); // boolean inICFG = !this.CFG; if (CFG) { for (JButton bt : createStmtTypes(stmtTypes)) { panelColor.add(new Label("Set color preference for this kind of statement")); panelColor.add(bt); bt.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.setVisible(true); // TODO Send vfNode and Color to Kaarthik ProjectPreferences pref = new ProjectPreferences(); pref.updateColorPreferences(bt.getName(),jcc.getColor().getRGB()); DataModel dataModel = ServiceUtil.getService(DataModel.class); dataModel.setSelectedMethod(dataModel.getSelectedMethod(), false); System.out.println("Statement is : " + bt.getName()); System.out.println("Color is : " + jcc.getColor().getRGB()); } }); } int result = JOptionPane.showConfirmDialog(null, panelColor, "Test", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { System.out.println("Color in JOptionPane" + jcc.getColor().getRGB()); } else { System.out.println("Cancelled"); } } else { JOptionPane.showMessageDialog(new JPanel(), "Changing color not possible in the ICFG", "Warning", JOptionPane.WARNING_MESSAGE); } } @SuppressWarnings("rawtypes") public void setCosAttr(VFUnit selectedVF, Node curr) { JPanel panel = new JPanel(new GridLayout(0, 2)); JTextField tfAnalysis = new JTextField(""); JTextField tfAttr = new JTextField(""); panel.add(new JLabel("Attribute: ")); panel.add(tfAnalysis); panel.add(new JLabel("Attribute value: ")); panel.add(tfAttr); int result = JOptionPane.showConfirmDialog(null, panel, "Setting custom attribute", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE); if (result == JOptionPane.OK_OPTION) { Map<String, String> hmCustAttr = new HashMap<>(); // Get actual customized attributes Set set = selectedVF.getHmCustAttr().entrySet(); Iterator i = set.iterator(); // Display elements while (i.hasNext()) { Map.Entry me = (Map.Entry) i.next(); hmCustAttr.put((String) me.getKey(), (String) me.getValue()); } if ((tfAnalysis.getText().length() > 0) && (tfAttr.getText().length() > 0)) { try { hmCustAttr.put(tfAnalysis.getText(), tfAttr.getText()); selectedVF.setHmCustAttr(hmCustAttr); ArrayList<VFUnit> units = new ArrayList<>(); units.add(selectedVF); curr.setAttribute("ui.color", jcc.getColor()); ServiceUtil.getService(DataModel.class).refreshView(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { JOptionPane.showMessageDialog(new JPanel(), "Please make sure all fields are correctly filled out", "Warning", JOptionPane.WARNING_MESSAGE); System.out.println("Please make sure all fields are correctly filled out"); } } else { System.out.println("Cancelled"); } } public void colorCostumizedNode() { for (Node n : graph.getEachNode()) { n.setAttribute("ui.color", jcc.getColor()); } } private List<JButton> createStmtTypes(List<JButton> stmtTypes) { stmtTypes = new ArrayList<>(); // All button JButton btJNopStmt, btJIdentityStmt, btJAssignStmt, btJIfStmt, btJGotoStmt, btJTableSwitchStmt, btJLookupSwitchStmt, btJInvokeStmt, btJReturnStmt, JReturnVoidStmt, btJThrowStmt, btJRetStmt, btJEnterMonitorSmt, btJExitMonitorStmt; btJNopStmt = new JButton("soot.jimple.internal.JNopStmt"); btJNopStmt.setName("soot.jimple.internal.JNopStmt"); btJIdentityStmt = new JButton("soot.jimple.internal.JIdentityStmt"); btJIdentityStmt.setName("soot.jimple.internal.JIdentityStmt"); btJAssignStmt = new JButton("soot.jimple.internal.JAssignStmt"); btJAssignStmt.setName("soot.jimple.internal.JAssignStmt"); btJIfStmt = new JButton("soot.jimple.internal.JIfStmt"); btJIfStmt.setName("soot.jimple.internal.JIfStmt"); btJGotoStmt = new JButton("soot.jimple.internal.JGotoStmt"); btJGotoStmt.setName("soot.jimple.internal.JGotoStmt"); btJTableSwitchStmt = new JButton("soot.jimple.internal.JTableSwitchStmt"); btJTableSwitchStmt.setName("soot.jimple.internal.JTableSwitchStmt"); btJLookupSwitchStmt = new JButton("soot.jimple.internal.JLookupSwitchStmt"); btJLookupSwitchStmt.setName("soot.jimple.internal.JLookupSwitchStmt"); btJInvokeStmt = new JButton("soot.jimple.internal.JInvokeStmt"); btJInvokeStmt.setName("soot.jimple.internal.JInvokeStmt"); btJReturnStmt = new JButton("soot.jimple.internal.JReturnStmt"); btJReturnStmt.setName("soot.jimple.internal.JReturnStmt"); JReturnVoidStmt = new JButton("soot.jimple.internal.JReturnVoidStmt"); JReturnVoidStmt.setName("soot.jimple.internal.JReturnVoidStmt"); btJThrowStmt = new JButton("soot.jimple.internal.JThrowStmt"); btJThrowStmt.setName("soot.jimple.internal.JThrowStmt"); btJRetStmt = new JButton("soot.jimple.internal.JRetStmt"); btJRetStmt.setName("soot.jimple.internal.JRetStmt"); btJEnterMonitorSmt = new JButton("soot.jimple.internal.JEnterMonitorStmt"); btJEnterMonitorSmt.setName("soot.jimple.internal.JEnterMonitorStmt"); btJExitMonitorStmt = new JButton("soot.jimple.internal.JExitMonitorStmt"); btJExitMonitorStmt.setName("soot.jimple.internal.JExitMonitorStmt"); // Add buttons to the list stmtTypes.add(btJNopStmt); stmtTypes.add(btJIdentityStmt); stmtTypes.add(btJAssignStmt); stmtTypes.add(btJIfStmt); stmtTypes.add(btJGotoStmt); stmtTypes.add(btJTableSwitchStmt); stmtTypes.add(btJLookupSwitchStmt); stmtTypes.add(btJInvokeStmt); stmtTypes.add(btJReturnStmt); stmtTypes.add(JReturnVoidStmt); stmtTypes.add(btJThrowStmt); stmtTypes.add(btJRetStmt); stmtTypes.add(btJEnterMonitorSmt); stmtTypes.add(btJExitMonitorStmt); return stmtTypes; } /* * private boolean inICFG(Graph graph) { boolean inICFG = false; * * for (Node n : graph.getEachNode()) { if ((n.getAttribute("nodeData.unitType") == null)) { inICFG = true; break; } } * * return inICFG; * * } */ }
package dr.evomodelxml; import dr.inference.model.Parameter; import dr.util.FileHelpers; import dr.util.TabularData; import dr.xml.*; import dr.evolution.io.NexusImporter; import dr.evolution.io.Importer; import dr.evolution.tree.Tree; import dr.evolution.util.TaxonList; import dr.evomodel.tree.EmpiricalTreeDistributionModel; import java.io.*; import java.util.ArrayList; import java.util.List; /** * @author Andrew Rambaut * <p/> * Reads a list of trees from a NEXUS file. */ public class EmpiricalTreeDistributionParser extends AbstractXMLObjectParser { public String getParserName() { return EmpiricalTreeDistributionModel.EMPIRICAL_TREE_DISTRIBUTION_MODEL; } public String getParserDescription() { return "Read a list of trees from a NEXUS file."; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { final String fileName = xo.getStringAttribute(FILE_NAME); int burnin = 0; if (xo.hasAttribute(BURNIN)) { burnin = xo.getIntegerAttribute(BURNIN); } TaxonList taxa = (TaxonList)xo.getChild(TaxonList.class); final File file = FileHelpers.getFile(fileName); Tree[] trees = null; try { FileReader reader = new FileReader(file); NexusImporter importer = new NexusImporter(reader); trees = importer.importTrees(taxa); } catch (FileNotFoundException e) { throw new XMLParseException(e.getMessage()); } catch (IOException e) { throw new XMLParseException(e.getMessage()); } catch (Importer.ImportException e) { throw new XMLParseException(e.getMessage()); } return new EmpiricalTreeDistributionModel(trees); } public static final String FILE_NAME = "fileName"; public static final String BURNIN = "burnin"; public XMLSyntaxRule[] getSyntaxRules() { return new XMLSyntaxRule[]{ new StringAttributeRule(FILE_NAME, "The name of a NEXUS tree file"), AttributeRule.newIntegerRule(BURNIN, true, "The number of trees to exclude"), new ElementRule(TaxonList.class), }; } public Class getReturnType() { return null; } }
package edu.iu.grid.oim.model.db.record; import java.sql.ResultSet; import java.sql.SQLException; public class WLCGSiteRecord extends RecordBase { @Key public String primary_key; public String short_name; public String official_name; public Double longitude; public Double latitude; public String contact_email; public String country; public String timezone; //load from existing record public WLCGSiteRecord(ResultSet rs) throws SQLException { super(rs); } //for creating new record public WLCGSiteRecord() {} }
package examples.mobile; import jade.util.leap.*; import jade.proto.*; import jade.lang.acl.*; import jade.domain.MobilityOntology; import jade.domain.FIPAException; import jade.lang.Codec; import jade.lang.sl.SL0Codec; import jade.core.*; import jade.onto.OntologyException; import jade.onto.basic.Action; import jade.onto.basic.ResultPredicate; /* * This behaviour extends SimpleAchieveREInitiator in order * to request to the AMS the list of available locations where * the agent can move. * Then, it displays these locations into the GUI * @author Fabio Bellifemine - CSELT S.p.A. * @version $Date$ $Revision$ */ public class GetAvailableLocationsBehaviour extends SimpleAchieveREInitiator { private ACLMessage request; public GetAvailableLocationsBehaviour(MobileAgent a) { // call the constructor of FipaRequestInitiatorBehaviour super(a, new ACLMessage(ACLMessage.REQUEST)); request = (ACLMessage)getDataStore().get(REQUEST_KEY); // fills all parameters of the request ACLMessage request.clearAllReceiver(); request.addReceiver(a.getAMS()); request.setLanguage(SL0Codec.NAME); request.setOntology(MobilityOntology.NAME); request.setProtocol("fipa-request"); // creates the content of the ACLMessage try { Action action = new Action(); action.setActor(a.getAMS()); action.setAction(new MobilityOntology.QueryPlatformLocationsAction()); List tuple = new ArrayList(); tuple.add(action); a.fillMsgContent(request, tuple); } catch(FIPAException fe) { fe.printStackTrace(); } // creates the Message Template // template = MessageTemplate.and(MessageTemplate.MatchOntology(MobilityOntology.NAME),template); // reset the fiparequestinitiatorbheaviour in order to put new values // for the request aclmessage and the template reset(request); } protected void handleNotUnderstood(ACLMessage reply) { System.out.println(myAgent.getLocalName()+ " handleNotUnderstood : "+reply.toString()); } protected void handleRefuse(ACLMessage reply) { System.out.println(myAgent.getLocalName()+ " handleRefuse : "+reply.toString()); } protected void handleFailure(ACLMessage reply) { System.out.println(myAgent.getLocalName()+ " handleFailure : "+reply.toString()); } protected void handleAgree(ACLMessage reply) { } protected void handleInform(ACLMessage inform) { String content = inform.getContent(); //System.out.println(inform.toString()); try { List tuple = myAgent.extractMsgContent(inform); ResultPredicate r = (ResultPredicate)tuple.get(0); //update the GUI ((MobileAgent)myAgent).gui.updateLocations(r.getAll_1()); } catch(Exception e) { e.printStackTrace(); } } }
package experimentalcode.shared.index.xtree; import java.util.ArrayList; import java.util.List; import de.lmu.ifi.dbs.elki.data.NumberVector; import de.lmu.ifi.dbs.elki.database.ids.DBID; import de.lmu.ifi.dbs.elki.database.ids.DBIDIter; import de.lmu.ifi.dbs.elki.database.ids.DBIDUtil; import de.lmu.ifi.dbs.elki.database.ids.DBIDs; import de.lmu.ifi.dbs.elki.database.query.distance.DistanceQuery; import de.lmu.ifi.dbs.elki.database.query.distance.SpatialDistanceQuery; import de.lmu.ifi.dbs.elki.database.query.knn.KNNQuery; import de.lmu.ifi.dbs.elki.database.query.range.RangeQuery; import de.lmu.ifi.dbs.elki.database.relation.Relation; import de.lmu.ifi.dbs.elki.distance.distancevalue.Distance; import de.lmu.ifi.dbs.elki.index.KNNIndex; import de.lmu.ifi.dbs.elki.index.RangeIndex; import de.lmu.ifi.dbs.elki.index.tree.IndexTreePath; import de.lmu.ifi.dbs.elki.index.tree.spatial.SpatialEntry; import de.lmu.ifi.dbs.elki.index.tree.spatial.SpatialPointLeafEntry; import de.lmu.ifi.dbs.elki.index.tree.spatial.rstarvariants.query.RStarTreeUtil; import de.lmu.ifi.dbs.elki.logging.Logging; import de.lmu.ifi.dbs.elki.persistent.PageFile; public class XTreeIndex<O extends NumberVector<?, ?>> extends XTree implements RangeIndex<O>, KNNIndex<O> { private static final Logging logger = Logging.getLogger(XTreeIndex.class); private Relation<O> relation; public XTreeIndex(Relation<O> relation, PageFile<XTreeNode> pagefile, double relativeMinEntries, double relativeMinFanout, float reinsert_fraction, float max_overlap, int overlap_type) { super(pagefile, relativeMinEntries, relativeMinFanout, max_overlap, overlap_type); this.relation = relation; this.initialize(); } protected SpatialEntry createNewLeafEntry(DBID id) { return new SpatialPointLeafEntry(id, relation.get(id)); } /** * Inserts the specified real vector object into this index. * * @param id the object id that was inserted */ @Override public final void insert(DBID id) { insertLeaf(createNewLeafEntry(id)); } /** * Inserts the specified objects into this index. If a bulk load mode is * implemented, the objects are inserted in one bulk. * * @param objects the objects to be inserted */ @Override public final void insertAll(DBIDs ids) { if(ids.isEmpty() || (ids.size() == 1)) { return; } // Make an example leaf if(canBulkLoad()) { List<SpatialEntry> leafs = new ArrayList<SpatialEntry>(ids.size()); for(DBIDIter id = ids.iter(); id.valid(); id.advance()) { leafs.add(createNewLeafEntry(DBIDUtil.deref(id))); } bulkLoad(leafs); } else { for(DBIDIter id = ids.iter(); id.valid(); id.advance()) { insert(DBIDUtil.deref(id)); } } doExtraIntegrityChecks(); } /** * Deletes the specified object from this index. * * @return true if this index did contain the object with the specified id, * false otherwise */ @Override public final boolean delete(DBID id) { // find the leaf node containing o O obj = relation.get(id); IndexTreePath<SpatialEntry> deletionPath = findPathToObject(getRootPath(), obj, id); if(deletionPath == null) { return false; } deletePath(deletionPath); return true; } @Override public void deleteAll(DBIDs ids) { for(DBIDIter id = ids.iter(); id.valid(); id.advance()) { delete(DBIDUtil.deref(id)); } } @Override public <D extends Distance<D>> RangeQuery<O, D> getRangeQuery(DistanceQuery<O, D> distanceQuery, Object... hints) { // Query on the relation we index if(distanceQuery.getRelation() != relation) { return null; } // Can we support this distance function - spatial distances only! if(!(distanceQuery instanceof SpatialDistanceQuery)) { return null; } SpatialDistanceQuery<O, D> dq = (SpatialDistanceQuery<O, D>) distanceQuery; return RStarTreeUtil.getRangeQuery(this, dq, hints); } @Override public <D extends Distance<D>> KNNQuery<O, D> getKNNQuery(DistanceQuery<O, D> distanceQuery, Object... hints) { // Query on the relation we index if(distanceQuery.getRelation() != relation) { return null; } // Can we support this distance function - spatial distances only! if(!(distanceQuery instanceof SpatialDistanceQuery)) { return null; } SpatialDistanceQuery<O, D> dq = (SpatialDistanceQuery<O, D>) distanceQuery; return RStarTreeUtil.getKNNQuery(this, dq, hints); } @Override public String getLongName() { return "X-Tree"; } @Override public String getShortName() { return "xtree"; } @Override protected Logging getLogger() { return logger; } }
package fi.mikuz.boarder.gui; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.ConcurrentModificationException; import java.util.ListIterator; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.media.AudioManager; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.provider.MediaStore; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.webkit.MimeTypeMap; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.thoughtworks.xstream.XStream; import fi.mikuz.boarder.R; import fi.mikuz.boarder.app.BoarderActivity; import fi.mikuz.boarder.component.Slot; import fi.mikuz.boarder.component.soundboard.GraphicalSound; import fi.mikuz.boarder.component.soundboard.GraphicalSoundboard; import fi.mikuz.boarder.component.soundboard.GraphicalSoundboardHistory; import fi.mikuz.boarder.util.AutoArrange; import fi.mikuz.boarder.util.FileProcessor; import fi.mikuz.boarder.util.IconUtils; import fi.mikuz.boarder.util.SoundPlayerControl; import fi.mikuz.boarder.util.XStreamUtil; import fi.mikuz.boarder.util.dbadapter.BoardsDbAdapter; import fi.mikuz.boarder.util.editor.GraphicalSoundboardProvider; import fi.mikuz.boarder.util.editor.ImageDrawing; import fi.mikuz.boarder.util.editor.SoundNameDrawing; /** * * @author Jan Mikael Lindlf */ public class GraphicalSoundboardEditor extends BoarderActivity { //TODO destroy god object private String TAG = "GraphicalSoundboardEditor"; public GraphicalSoundboard mGsb; private GraphicalSoundboardHistory mGsbh; private static final int LISTEN_BOARD = 0; private static final int EDIT_BOARD = 1; private int mMode = LISTEN_BOARD; private static final int DRAG_TEXT = 0; private static final int DRAG_IMAGE = 1; private int mDragTarget = DRAG_TEXT; private static final int EXPLORE_SOUND = 0; private static final int EXPLORE_BACKGROUD = 1; private static final int EXPLORE_SOUND_IMAGE = 2; private static final int CHANGE_NAME_COLOR = 3; private static final int CHANGE_INNER_PAINT_COLOR = 4; private static final int CHANGE_BORDER_PAINT_COLOR = 5; private static final int CHANGE_BACKGROUND_COLOR = 6; private static final int CHANGE_SOUND_PATH = 7; private static final int EXPLORE_SOUND_ACTIVE_IMAGE = 8; private int mCopyColor = 0; private Paint mSoundImagePaint; private GraphicalSound mDragSound = null; private boolean mDrawDragSound = false; private float mInitialNameFrameX = 0; private float mInitialNameFrameY = 0; private float mInitialImageX = 0; private float mInitialImageY = 0; private float mNameFrameDragDistanceX = -1; private float mNameFrameDragDistanceY = -1; private float mImageDragDistanceX = -1; private float mImageDragDistanceY = -1; private long mClickTime = 0; private long mLastTrackballEvent = 0; private DrawingThread mThread; private Menu mMenu; private DrawingPanel mPanel; boolean mCanvasInvalidated = false; boolean mPanelInitialized = false; private boolean mMoveBackground = false; private float mBackgroundLeftDistance = 0; private float mBackgroundTopDistance = 0; final Handler mHandler = new Handler(); ProgressDialog mWaitDialog; boolean mClearBoardDir = false; private File mSbDir = SoundboardMenu.mSbDir; private String mBoardName = null; TextView soundImageWidthText; TextView soundImageHeightText; TextView backgroundWidthText; TextView backgroundHeightText; EditText backgroundWidthInput; EditText backgroundHeightInput; float widthHeightScale; int mNullCanvasCount = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setVolumeControlStream(AudioManager.STREAM_MUSIC); Bundle extras = getIntent().getExtras(); if (extras != null) { mBoardName = extras.getString(BoardsDbAdapter.KEY_TITLE); setTitle(mBoardName); loadBoard(GraphicalSoundboardProvider.getBoard(mBoardName, GraphicalSoundboard.SCREEN_ORIENTATION_PORTAIT)); if (mGsb.getSoundList().isEmpty()) { mMode = EDIT_BOARD; } } else { mMode = EDIT_BOARD; mGsb = new GraphicalSoundboard(); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Set board name"); final EditText input = new EditText(this); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String inputText = input.getText().toString(); if (inputText.contains("\n")) { mBoardName = inputText.substring(0, inputText.indexOf("\n")); } else if (inputText.equals("")) { finish(); }else { mBoardName = inputText; } setTitle(mBoardName); save(); } }); alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { finish(); } }); alert.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }); alert.show(); } mSoundImagePaint = new Paint(); mSoundImagePaint.setColor(Color.WHITE); mSoundImagePaint.setAntiAlias(true); mSoundImagePaint.setTextAlign(Align.LEFT); setRequestedOrientation(mGsb.getScreenOrientation()); mGsbh = new GraphicalSoundboardHistory(GraphicalSoundboardEditor.this); mGsbh.createHistoryCheckpoint(); File icon = new File(mSbDir, mBoardName + "/icon.png"); if (icon.exists()) { Bitmap bitmap = ImageDrawing.decodeFile(this.getApplicationContext(), icon); Drawable drawable = new BitmapDrawable(getResources(), IconUtils.resizeIcon(this, bitmap, (40/6))); this.getActionBar().setLogo(drawable); } mPanel = new DrawingPanel(this); ViewTreeObserver vto = mPanel.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (!mPanelInitialized) { mPanelInitialized = true; issueResolutionConversion(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.clear(); mMenu = menu; MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.graphical_soundboard_editor_bottom, menu); if (mMode == EDIT_BOARD) { menu.setGroupVisible(R.id.edit_mode, false); } else { menu.setGroupVisible(R.id.listen_mode, false); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.menu_listen_mode: mMode = LISTEN_BOARD; this.onCreateOptionsMenu(mMenu); return true; case R.id.menu_edit_mode: mMode = EDIT_BOARD; this.onCreateOptionsMenu(mMenu); return true; case R.id.menu_undo: mGsbh.undo(); return true; case R.id.menu_redo: mGsbh.redo(); return true; case R.id.menu_add_sound: Intent i = new Intent(this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_ADD_GRAPHICAL_SOUND); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, EXPLORE_SOUND); return true; case R.id.menu_save_board: save(); return true; case R.id.menu_convert_board: AlertDialog.Builder convertBuilder = new AlertDialog.Builder(this); convertBuilder.setTitle("Convert"); convertBuilder.setMessage("Clear board directory?"); convertBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mClearBoardDir = true; initializeConvert(); } }); convertBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mClearBoardDir = false; initializeConvert(); } }); convertBuilder.setCancelable(false); convertBuilder.show(); return true; case R.id.menu_play_pause: SoundPlayerControl.togglePlayPause(); return true; case R.id.menu_notification: SoundboardMenu.updateNotification(this, mBoardName, mBoardName); return true; case R.id.menu_take_screenshot: Bitmap bitmap = Bitmap.createBitmap(mPanel.getWidth(), mPanel.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); mPanel.onDraw(canvas); Toast.makeText(getApplicationContext(), FileProcessor.saveScreenshot(bitmap, mBoardName), Toast.LENGTH_LONG).show(); return true; case R.id.menu_board_settings: final CharSequence[] items = {"Sound", "Background", "Icon", "Screen orientation", "Auto-arrange", "Reset position"}; AlertDialog.Builder setAsBuilder = new AlertDialog.Builder(GraphicalSoundboardEditor.this); setAsBuilder.setTitle("Board settings"); setAsBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { LayoutInflater inflater = (LayoutInflater) GraphicalSoundboardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.graphical_soundboard_editor_alert_board_sound_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox checkPlaySimultaneously = (CheckBox) layout.findViewById(R.id.playSimultaneouslyCheckBox); checkPlaySimultaneously.setChecked(mGsb.getPlaySimultaneously()); final EditText boardVolumeInput = (EditText) layout.findViewById(R.id.boardVolumeInput); boardVolumeInput.setText(mGsb.getBoardVolume()*100 + "%"); AlertDialog.Builder builder = new AlertDialog.Builder(GraphicalSoundboardEditor.this); builder.setView(layout); builder.setTitle("Board settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { boolean notifyIncorrectValue = false; mGsb.setPlaySimultaneously(checkPlaySimultaneously.isChecked()); Float boardVolumeValue = null; try { String boardVolumeString = boardVolumeInput.getText().toString(); if (boardVolumeString.contains("%")) { boardVolumeValue = Float.valueOf(boardVolumeString.substring(0, boardVolumeString.indexOf("%"))).floatValue()/100; } else { boardVolumeValue = Float.valueOf(boardVolumeString).floatValue()/100; } if (boardVolumeValue >= 0 && boardVolumeValue <= 1 && boardVolumeValue != null) { mGsb.setBoardVolume(boardVolumeValue); } else { notifyIncorrectValue = true; } } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.show(); } else if (item == 1) { LayoutInflater inflater = (LayoutInflater) GraphicalSoundboardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout. graphical_soundboard_editor_alert_board_background_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox checkUseBackgroundImage = (CheckBox) layout.findViewById(R.id.useBackgroundFileCheckBox); checkUseBackgroundImage.setChecked(mGsb.getUseBackgroundImage()); final Button backgroundColorButton = (Button) layout.findViewById(R.id.backgroundColorButton); backgroundColorButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(GraphicalSoundboardEditor.this, ColorChanger.class); i.putExtra("parentKey", "changeBackgroundColor"); i.putExtras(XStreamUtil.getSoundboardBundle(mGsb)); startActivityForResult(i, CHANGE_BACKGROUND_COLOR); } }); final Button toggleMoveBackgroundFileButton = (Button) layout.findViewById(R.id.toggleMoveBackgroundFileButton); if (mMoveBackground) { toggleMoveBackgroundFileButton.setText("Move Background (file) : Yes"); } else { toggleMoveBackgroundFileButton.setText("Move Background (file) : No"); } toggleMoveBackgroundFileButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mMoveBackground = mMoveBackground ? false : true; if (mMoveBackground) { toggleMoveBackgroundFileButton.setText("Move Background (file) : Yes"); } else { toggleMoveBackgroundFileButton.setText("Move Background (file) : No"); } } }); final Button backgroundFileButton = (Button) layout.findViewById(R.id.backgroundFileButton); backgroundFileButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { selectBackgroundFile(); } }); backgroundWidthText = (TextView) layout.findViewById(R.id.backgroundWidthText); backgroundHeightText = (TextView) layout.findViewById(R.id.backgroundHeightText); if (mGsb.getBackgroundImage() != null) { backgroundWidthText.setText("Width (" + mGsb.getBackgroundImage().getWidth() + ")"); backgroundHeightText.setText("Height (" + mGsb.getBackgroundImage().getHeight() + ")"); } backgroundWidthInput = (EditText) layout.findViewById(R.id.backgroundWidthInput); backgroundWidthInput.setText(Float.toString(mGsb.getBackgroundWidth())); backgroundHeightInput = (EditText) layout.findViewById(R.id.backgroundHeightInput); backgroundHeightInput.setText(Float.toString(mGsb.getBackgroundHeight())); final CheckBox scaleWidthHeight = (CheckBox) layout.findViewById(R.id.scaleWidthHeightCheckBox); scaleWidthHeight.setChecked(true); scaleWidthHeight.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { // Calculate a new scale widthHeightScale = Float.valueOf(backgroundWidthInput.getText().toString()).floatValue() / Float.valueOf(backgroundHeightInput.getText().toString()).floatValue(); } catch(NumberFormatException nfe) {Log.e(TAG, "Unable to calculate width and height scale", nfe);} } }); widthHeightScale = mGsb.getBackgroundWidth() / mGsb.getBackgroundHeight(); backgroundWidthInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (scaleWidthHeight.isChecked()) { try { float value = Float.valueOf( backgroundWidthInput.getText().toString()).floatValue(); backgroundHeightInput.setText( Float.valueOf(value/widthHeightScale).toString()); } catch(NumberFormatException nfe) {} } return false; } }); backgroundHeightInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (scaleWidthHeight.isChecked()) { try { float value = Float.valueOf( backgroundHeightInput.getText().toString()).floatValue(); backgroundWidthInput.setText( Float.valueOf(value*widthHeightScale).toString()); } catch(NumberFormatException nfe) {} } return false; } }); AlertDialog.Builder builder = new AlertDialog.Builder(GraphicalSoundboardEditor.this); builder.setView(layout); builder.setTitle("Board settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { boolean notifyIncorrectValue = false; mGsb.setUseBackgroundImage(checkUseBackgroundImage.isChecked()); try { mGsb.setBackgroundWidth(Float.valueOf(backgroundWidthInput.getText().toString()).floatValue()); mGsb.setBackgroundHeight(Float.valueOf(backgroundHeightInput.getText().toString()).floatValue()); } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } mGsbh.createHistoryCheckpoint(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.show(); } else if (item == 2) { AlertDialog.Builder resetBuilder = new AlertDialog.Builder( GraphicalSoundboardEditor.this); resetBuilder.setTitle("Change board icon"); resetBuilder.setMessage("You can change icon for this board.\n\n" + "You need a png image:\n " + mSbDir + "/" + mBoardName + "/" + "icon.png\n\n" + "Recommended size is about 80x80 pixels."); AlertDialog resetAlert = resetBuilder.create(); resetAlert.show(); } else if (item == 3) { final CharSequence[] items = {"Portait", "Landscape"}; AlertDialog.Builder orientationBuilder = new AlertDialog.Builder( GraphicalSoundboardEditor.this); orientationBuilder.setTitle("Select orientation"); orientationBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0 && mGsb.getScreenOrientation() != GraphicalSoundboard.SCREEN_ORIENTATION_PORTAIT) { screenOrientationWarning(GraphicalSoundboard.SCREEN_ORIENTATION_PORTAIT); } else if (item == 1 && mGsb.getScreenOrientation() != GraphicalSoundboard.SCREEN_ORIENTATION_LANDSCAPE) { screenOrientationWarning(GraphicalSoundboard.SCREEN_ORIENTATION_LANDSCAPE); } } }); AlertDialog orientationAlert = orientationBuilder.create(); orientationAlert.show(); } else if (item == 4) { //Auto-arrange LayoutInflater inflater = (LayoutInflater) GraphicalSoundboardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout. graphical_soundboard_editor_alert_auto_arrange, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox checkEnableAutoArrange = (CheckBox) layout.findViewById(R.id.enableAutoArrange); checkEnableAutoArrange.setChecked(mGsb.getAutoArrange()); final EditText columnsInput = (EditText) layout.findViewById(R.id.columnsInput); columnsInput.setText(Integer.toString(mGsb.getAutoArrangeColumns())); final EditText rowsInput = (EditText) layout.findViewById(R.id.rowsInput); rowsInput.setText(Integer.toString(mGsb.getAutoArrangeRows())); AlertDialog.Builder builder = new AlertDialog.Builder(GraphicalSoundboardEditor.this); builder.setView(layout); builder.setTitle("Board settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { int columns = Integer.valueOf( columnsInput.getText().toString()).intValue(); int rows = Integer.valueOf( rowsInput.getText().toString()).intValue(); if (mGsb.getSoundList().size() <= columns*rows || !checkEnableAutoArrange.isChecked()) { if (mGsb.getAutoArrange() != checkEnableAutoArrange.isChecked() || mGsb.getAutoArrangeColumns() != columns || mGsb.getAutoArrangeRows() != rows) { mGsb.setAutoArrange(checkEnableAutoArrange.isChecked()); mGsb.setAutoArrangeColumns(columns); mGsb.setAutoArrangeRows(rows); } } else { Toast.makeText(getApplicationContext(), "Not enought slots", Toast.LENGTH_SHORT).show(); } mGsbh.createHistoryCheckpoint(); } catch(NumberFormatException nfe) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.show(); } else if (item == 5) { ArrayList<String> itemArray = new ArrayList<String>(); for (GraphicalSound sound : mGsb.getSoundList()) { itemArray.add(sound.getName()); } CharSequence[] items = itemArray.toArray(new CharSequence[itemArray.size()]); AlertDialog.Builder resetBuilder = new AlertDialog.Builder( GraphicalSoundboardEditor.this); resetBuilder.setTitle("Reset sound position"); resetBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { GraphicalSound sound = mGsb.getSoundList().get(item); sound.setNameFrameX(50); sound.setNameFrameY(50); sound.generateImageXYFromNameFrameLocation(); mGsbh.createHistoryCheckpoint(); } }); AlertDialog resetAlert = resetBuilder.create(); resetAlert.show(); } } }); AlertDialog setAsAlert = setAsBuilder.create(); setAsAlert.show(); return true; default: return super.onOptionsItemSelected(item); } } public void loadBoard(GraphicalSoundboard gsb) { GraphicalSoundboard.loadImages(this.getApplicationContext(), gsb); mGsb = gsb; } private void screenOrientationWarning(final int orientation) { AlertDialog.Builder orientationWarningBuilder = new AlertDialog.Builder( GraphicalSoundboardEditor.this); orientationWarningBuilder.setTitle("Select orientation"); orientationWarningBuilder.setMessage( "Changing screen orientation will delete all position data if you don't " + "select deny.\n\n" + "Proceed?"); orientationWarningBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mGsb.setBackgroundX(0); mGsb.setBackgroundY(0); for(GraphicalSound sound : mGsb.getSoundList()) { sound.setNameFrameX(50); sound.setNameFrameY(50); sound.generateImageXYFromNameFrameLocation(); } mGsb.setScreenOrientation(orientation); finishBoard(); } }); orientationWarningBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); orientationWarningBuilder.setNeutralButton("Deny", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mGsb.setScreenOrientation(orientation); finishBoard(); } }); AlertDialog orientationWarningAlert = orientationWarningBuilder.create(); orientationWarningAlert.show(); } private void finishBoard() { try { GraphicalSoundboardEditor.this.finish(); } catch (Throwable e) { Log.e(TAG, "Error closing board", e); } } private void selectBackgroundFile() { Intent i = new Intent(this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_SELECT_BACKGROUND_FILE); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, EXPLORE_BACKGROUD); } private void selectImageFile() { Intent i = new Intent(this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_SELECT_SOUND_IMAGE_FILE); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, EXPLORE_SOUND_IMAGE); } private void selectActiveImageFile() { Intent i = new Intent(this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_SELECT_SOUND_ACTIVE_IMAGE_FILE); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, EXPLORE_SOUND_ACTIVE_IMAGE); } @Override protected void onActivityResult(int requestCode, int resultCode, final Intent intent) { super.onActivityResult(requestCode, resultCode, intent); switch(requestCode) { case EXPLORE_SOUND: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); XStream xstream = XStreamUtil.graphicalBoardXStream(); GraphicalSound sound = (GraphicalSound) xstream.fromXML(extras.getString(FileExplorer.ACTION_ADD_GRAPHICAL_SOUND)); sound.setImage(BitmapFactory.decodeResource(getResources(), R.drawable.sound)); sound.setAutoArrangeColumn(0); sound.setAutoArrangeRow(0); if (mGsb.getAutoArrange()) { if (placeToFreeSlot(sound)) { mGsb.getSoundList().add(sound); } } else { placeToFreeSpace(sound); mGsb.getSoundList().add(sound); } mGsbh.createHistoryCheckpoint(); } break; case EXPLORE_BACKGROUD: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); File background = new File(extras.getString(FileExplorer.ACTION_SELECT_BACKGROUND_FILE)); mGsb.setBackgroundImagePath(background); mGsb.setBackgroundImage(ImageDrawing.decodeFile(this.getApplicationContext(), mGsb.getBackgroundImagePath())); mGsb.setBackgroundWidth(mGsb.getBackgroundImage().getWidth()); mGsb.setBackgroundHeight(mGsb.getBackgroundImage().getHeight()); mGsb.setBackgroundX(0); mGsb.setBackgroundY(0); mGsbh.createHistoryCheckpoint(); } backgroundWidthText.setText("Width (" + mGsb.getBackgroundImage().getWidth() + ")"); backgroundHeightText.setText("Height (" + mGsb.getBackgroundImage().getHeight() + ")"); backgroundWidthInput.setText(Float.toString(mGsb.getBackgroundWidth())); backgroundHeightInput.setText(Float.toString(mGsb.getBackgroundHeight())); break; case EXPLORE_SOUND_IMAGE: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); File image = new File(extras.getString(FileExplorer.ACTION_SELECT_SOUND_IMAGE_FILE)); mDragSound.setImagePath(image); mDragSound.setImage(ImageDrawing.decodeFile(this.getApplicationContext(), mDragSound.getImagePath())); } soundImageWidthText.setText("Width (" + mDragSound.getImage().getWidth() + ")"); soundImageHeightText.setText("Height (" + mDragSound.getImage().getHeight() + ")"); break; case EXPLORE_SOUND_ACTIVE_IMAGE: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); File image = new File(extras.getString(FileExplorer.ACTION_SELECT_SOUND_ACTIVE_IMAGE_FILE)); mDragSound.setActiveImagePath(image); mDragSound.setActiveImage(ImageDrawing.decodeFile(this.getApplicationContext(), mDragSound.getActiveImagePath())); } break; case CHANGE_NAME_COLOR: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); if (extras.getBoolean("copyKey")) { mCopyColor = CHANGE_NAME_COLOR; } else { mDragSound.setNameTextColorInt(extras.getInt("colorKey")); } } break; case CHANGE_INNER_PAINT_COLOR: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); if (extras.getBoolean("copyKey")) { mCopyColor = CHANGE_INNER_PAINT_COLOR; } else { mDragSound.setNameFrameInnerColorInt(extras.getInt("colorKey")); } } break; case CHANGE_BORDER_PAINT_COLOR: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); if (extras.getBoolean("copyKey")) { mCopyColor = CHANGE_BORDER_PAINT_COLOR; } else { mDragSound.setNameFrameBorderColorInt(extras.getInt("colorKey")); } } break; case CHANGE_BACKGROUND_COLOR: if (resultCode == RESULT_OK) { Bundle extras = intent.getExtras(); mGsb.setBackgroundColor(extras.getInt("colorKey")); mGsbh.createHistoryCheckpoint(); } break; case CHANGE_SOUND_PATH: if (resultCode == RESULT_OK) { LayoutInflater removeInflater = (LayoutInflater) GraphicalSoundboardEditor.this.getSystemService(LAYOUT_INFLATER_SERVICE); View removeLayout = removeInflater.inflate( R.layout.graphical_soundboard_editor_alert_remove_sound, (ViewGroup) findViewById(R.id.alert_remove_sound_root)); final CheckBox removeFileCheckBox = (CheckBox) removeLayout.findViewById(R.id.removeFile); removeFileCheckBox.setText(" DELETE " + mDragSound.getPath().getAbsolutePath()); AlertDialog.Builder removeBuilder = new AlertDialog.Builder( GraphicalSoundboardEditor.this); removeBuilder.setView(removeLayout); removeBuilder.setTitle("Changing sound"); removeBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (removeFileCheckBox.isChecked() == true) { mDragSound.getPath().delete(); } Bundle extras = intent.getExtras(); mDragSound.setPath(new File(extras.getString(FileExplorer.ACTION_CHANGE_SOUND_PATH))); } }); removeBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); removeBuilder.setCancelable(false); removeBuilder.show(); } break; default: break; } } private void initializeConvert() { mWaitDialog = ProgressDialog.show(GraphicalSoundboardEditor.this, "", "Please wait", true); Thread t = new Thread() { public void run() { Looper.prepare(); try { if (mClearBoardDir) { cleanDirectory(new File(mSbDir, mBoardName).listFiles()); } FileProcessor.convertGraphicalBoard(GraphicalSoundboardEditor.this, mBoardName, mGsb); save(); } catch (IOException e) { Log.e(TAG, "Error converting board", e); } mHandler.post(mUpdateResults); } }; t.start(); } private void cleanDirectory(File[] files) { for (File file : files) { if (file.isDirectory()) { cleanDirectory(file.listFiles()); if (file.listFiles().length == 0) { Log.d(TAG, "Deleting empty directory " + file.getAbsolutePath()); file.delete(); } } else { boolean boardUsesFile = false; if (file.getName().equals("graphicalBoard") == true || file.getName().equals("icon.png") == true) { boardUsesFile = true; } try { if (file.getName().equals(mGsb.getBackgroundImagePath().getName())) boardUsesFile = true; } catch (NullPointerException e) {} for (GraphicalSound sound : mGsb.getSoundList()) { if (boardUsesFile) break; try { if (sound.getPath().getAbsolutePath().equals(file.getAbsolutePath())) boardUsesFile = true; } catch (NullPointerException e) {} try { if (sound.getImagePath().getAbsolutePath().equals(file.getAbsolutePath())) boardUsesFile = true; } catch (NullPointerException e) {} try { if (sound.getActiveImagePath().getAbsolutePath().equals(file.getAbsolutePath())) boardUsesFile = true; } catch (NullPointerException e) {} } if (boardUsesFile == false) { Log.d(TAG, "Deleting unused file " + file.getAbsolutePath()); file.delete(); } } } } final Runnable mUpdateResults = new Runnable() { public void run() { mWaitDialog.dismiss(); } }; @Override protected void onResume() { super.onResume(); setContentView(mPanel); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override protected void onPause() { save(); super.onPause(); } @Override protected void onDestroy() { GraphicalSoundboard.unloadImages(mGsb); super.onDestroy(); } private void save() { if (mBoardName != null) { try { GraphicalSoundboard gsb = GraphicalSoundboard.copy(mGsb); if (mDragSound != null && mDrawDragSound == true) gsb.getSoundList().add(mDragSound); GraphicalSoundboardProvider.saveBoard(mBoardName, gsb); Log.v(TAG, "Board " + mBoardName + " saved"); } catch (IOException e) { Log.e(TAG, "Unable to save " + mBoardName, e); } } } private void initializeDrag(MotionEvent event, GraphicalSound sound) { if (mMode == LISTEN_BOARD) { if (sound.getPath().getAbsolutePath().equals(SoundboardMenu.mPauseSoundFilePath)) { SoundPlayerControl.togglePlayPause(); } else { if (sound.getSecondClickAction() == GraphicalSound.SECOND_CLICK_PLAY_NEW) { SoundPlayerControl.playSound(mGsb.getPlaySimultaneously(), sound.getPath(), sound.getVolumeLeft(), sound.getVolumeRight(), mGsb.getBoardVolume()); } else if (sound.getSecondClickAction() == GraphicalSound.SECOND_CLICK_PAUSE) { SoundPlayerControl.pauseSound(mGsb.getPlaySimultaneously(), sound.getPath(), sound.getVolumeLeft(), sound.getVolumeRight(), mGsb.getBoardVolume()); } else if (sound.getSecondClickAction() == GraphicalSound.SECOND_CLICK_STOP) { SoundPlayerControl.stopSound(mGsb.getPlaySimultaneously(), sound.getPath(), sound.getVolumeLeft(), sound.getVolumeRight(), mGsb.getBoardVolume()); } mCanvasInvalidated = true; } } else { mDragSound = sound; mDrawDragSound = true; mInitialNameFrameX = sound.getNameFrameX(); mInitialNameFrameY = sound.getNameFrameY(); mInitialImageX = sound.getImageX(); mInitialImageY = sound.getImageY(); mGsb.getSoundList().remove(sound); mNameFrameDragDistanceX = event.getX() - sound.getNameFrameX(); mNameFrameDragDistanceY = event.getY() - sound.getNameFrameY(); mImageDragDistanceX = event.getX() - sound.getImageX(); mImageDragDistanceY = event.getY() - sound.getImageY(); } } private void copyColor(GraphicalSound sound) { switch(mCopyColor) { case CHANGE_NAME_COLOR: mDragSound.setNameTextColorInt(sound.getNameTextColor()); break; case CHANGE_INNER_PAINT_COLOR: mDragSound.setNameFrameInnerColorInt(sound.getNameFrameInnerColor()); break; case CHANGE_BORDER_PAINT_COLOR: mDragSound.setNameFrameBorderColorInt(sound.getNameFrameBorderColor()); break; } mCopyColor = 0; mGsbh.createHistoryCheckpoint(); } void moveSound(float X, float Y) { if (mDragSound.getLinkNameAndImage() || mDragTarget == DRAG_TEXT) { mDragSound.setNameFrameX(X-mNameFrameDragDistanceX); mDragSound.setNameFrameY(Y-mNameFrameDragDistanceY); } if (mDragSound.getLinkNameAndImage() || mDragTarget == DRAG_IMAGE) { mDragSound.setImageX(X-mImageDragDistanceX); mDragSound.setImageY(Y-mImageDragDistanceY); } mGsb.getSoundList().add(mDragSound); mDrawDragSound = false; } public void moveSoundToSlot(GraphicalSound sound, int column, int row, float imageX, float imageY, float nameX, float nameY) { int width = mPanel.getWidth(); int height = mPanel.getHeight(); float middlePointX = width/mGsb.getAutoArrangeColumns()/2; float middlePointY = height/mGsb.getAutoArrangeRows()/2; float lowPointX; float highPointX; float lowPointY; float highPointY; boolean moveName = false; boolean moveImage = false; SoundNameDrawing soundNameDrawing = new SoundNameDrawing(sound); float nameFrameWidth = soundNameDrawing.getNameFrameRect().width(); float nameFrameHeight = soundNameDrawing.getNameFrameRect().height(); if (sound.getHideImageOrText() == GraphicalSound.HIDE_TEXT) { lowPointX = imageX; highPointX = imageX+sound.getImageWidth(); lowPointY = imageY; highPointY = imageY+sound.getImageHeight(); moveImage = true; } else if (sound.getHideImageOrText() == GraphicalSound.HIDE_IMAGE) { lowPointX = nameX; highPointX = nameX+nameFrameWidth; lowPointY = nameY; highPointY = nameY+nameFrameHeight; moveName = true; } else { lowPointX = imageX < nameX ? imageX : nameX; highPointX = imageX+sound.getImageWidth() > nameX+nameFrameWidth ? imageX+sound.getImageWidth() : nameX+nameFrameWidth; lowPointY = imageY < nameY ? imageY : nameY; highPointY = imageY+sound.getImageHeight() > nameY+nameFrameHeight ? imageY+sound.getImageHeight() : nameY+nameFrameHeight; moveImage = true; moveName = true; } float xPoint = (highPointX-lowPointX)/2; float imageDistanceX = imageX-(lowPointX+xPoint); float nameDistanceX = nameX-(lowPointX+xPoint); float yPoint = (highPointY-lowPointY)/2; float imageDistanceY = imageY-(lowPointY+yPoint); float nameDistanceY = nameY-(lowPointY+yPoint); float slotX = column*(width/mGsb.getAutoArrangeColumns()); float slotY = row*(height/mGsb.getAutoArrangeRows()); if (moveImage) { sound.setImageX(slotX+middlePointX+imageDistanceX); sound.setImageY(slotY+middlePointY+imageDistanceY); } if (moveName) { sound.setNameFrameX(slotX+middlePointX+nameDistanceX); sound.setNameFrameY(slotY+middlePointY+nameDistanceY); } sound.setAutoArrangeColumn(column); sound.setAutoArrangeRow(row); mGsbh.createHistoryCheckpoint(); } public boolean placeToFreeSlot(GraphicalSound sound) { try { Slot slot = AutoArrange.getFreeSlot(mGsb.getSoundList(), mGsb.getAutoArrangeColumns(), mGsb.getAutoArrangeRows()); moveSoundToSlot(sound, slot.getColumn(), slot.getRow(), sound.getImageX(), sound.getImageY(), sound.getNameFrameX(), sound.getNameFrameY()); return true; } catch (NullPointerException e) { Toast.makeText(getApplicationContext(), "No slot available", Toast.LENGTH_SHORT).show(); return false; } } public void placeToFreeSpace(GraphicalSound sound) { boolean spaceAvailable = true; float freeSpaceX = 0; float freeSpaceY = 0; int width = mPanel.getWidth(); int height = mPanel.getHeight(); while (freeSpaceY + sound.getImageHeight() < height) { spaceAvailable = true; for (GraphicalSound spaceEater : mGsb.getSoundList()) { if (((freeSpaceX >= spaceEater.getImageX() && freeSpaceX <= spaceEater.getImageX()+spaceEater.getImageWidth()) || freeSpaceX+sound.getImageWidth() >= spaceEater.getImageX() && freeSpaceX+sound.getImageWidth() <= spaceEater.getImageX()+spaceEater.getImageWidth()) && (freeSpaceY >= spaceEater.getImageY() && freeSpaceY <= spaceEater.getImageY()+spaceEater.getImageHeight() || freeSpaceY+sound.getImageHeight() >= spaceEater.getImageY() && freeSpaceY+sound.getImageHeight() <= spaceEater.getImageY()+spaceEater.getImageHeight())) { spaceAvailable = false; break; } } if (spaceAvailable) { sound.setImageX(freeSpaceX); sound.setImageY(freeSpaceY); sound.generateNameFrameXYFromImageLocation(); break; } freeSpaceX = freeSpaceX + 5; if (freeSpaceX + sound.getImageWidth() >= width) { freeSpaceX = 0; freeSpaceY = freeSpaceY + 5; } } if (!spaceAvailable) { sound.setNameFrameX(10); sound.setNameFrameY(sound.getImageHeight()+10); sound.generateImageXYFromNameFrameLocation(); } } public boolean onTrackballEvent (MotionEvent event) { if (mMode == EDIT_BOARD && event.getAction() == MotionEvent.ACTION_MOVE && mDragSound != null && (mLastTrackballEvent == 0 || System.currentTimeMillis() - mLastTrackballEvent > 500)) { mLastTrackballEvent = System.currentTimeMillis(); int movementX = 0; int movementY = 0; if (event.getX() > 0) { movementX = 1; } else if (event.getX() < 0) { movementX = -1; }else if (event.getY() > 0) { movementY = 1; } else if (event.getY() < 0) { movementY = -1; } if (mDragSound.getLinkNameAndImage() || mDragTarget == DRAG_TEXT) { mDragSound.setNameFrameX(mDragSound.getNameFrameX() + movementX); mDragSound.setNameFrameY(mDragSound.getNameFrameY() + movementY); } if (mDragSound.getLinkNameAndImage() || mDragTarget == DRAG_IMAGE) { mDragSound.setImageX(mDragSound.getImageX() + movementX); mDragSound.setImageY(mDragSound.getImageY() + movementY); } mGsbh.setHistoryCheckpoint(); return true; } else { return false; } } public void issueResolutionConversion() { Thread t = new Thread() { public void run() { Looper.prepare(); final int windowWidth = mPanel.getWidth(); final int windowHeight = mPanel.getHeight(); if (mGsb.getScreenHeight() == 0 || mGsb.getScreenWidth() == 0) { mGsb.setScreenWidth(windowWidth); mGsb.setScreenHeight(windowHeight); } else if (mGsb.getScreenWidth() != windowWidth || mGsb.getScreenHeight() != windowHeight) { Log.v(TAG, "Soundoard resolution has been changed"); AlertDialog.Builder builder = new AlertDialog.Builder(GraphicalSoundboardEditor.this); builder.setTitle("Display size"); builder.setMessage("Display size used to make this board differs from your display size.\n\n" + "You can resize this board to fill your display or " + "fit this board to your display. Fit looks accurately like the original one.\n\n" + "(Ps. In 'Edit board' mode you can undo this.)"); builder.setPositiveButton("Resize", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.v(TAG, "Resizing board"); float xScale = (float) windowWidth/(float) (mGsb.getScreenWidth()); float yScale = (float) windowHeight/(float) (mGsb.getScreenHeight()); float avarageScale = xScale+(yScale-xScale)/2; Log.v(TAG, "X scale: \"" + xScale + "\"" + ", old width: \""+mGsb.getScreenWidth() + "\", new width: \"" + windowWidth + "\""); Log.v(TAG, "Y scale: \"" + yScale + "\"" + ", old height: \""+mGsb.getScreenHeight() + "\", new height: \"" + windowHeight + "\""); Log.v(TAG, "Avarage scale: \"" + avarageScale + "\""); mGsb.setBackgroundX(mGsb.getBackgroundX()*xScale); mGsb.setBackgroundY(mGsb.getBackgroundY()*yScale); mGsb.setBackgroundWidth(mGsb.getBackgroundWidth()*xScale); mGsb.setBackgroundHeight(mGsb.getBackgroundHeight()*yScale); for (GraphicalSound sound : mGsb.getSoundList()) { sound = SoundNameDrawing.getScaledTextSize(sound, avarageScale); sound.setNameFrameX(sound.getNameFrameX()*xScale); sound.setNameFrameY(sound.getNameFrameY()*yScale); sound.setImageX(sound.getImageX()*xScale); sound.setImageY(sound.getImageY()*yScale); sound.setImageWidth(sound.getImageWidth()*avarageScale); sound.setImageHeight(sound.getImageHeight()*avarageScale); if (sound.getLinkNameAndImage()) sound.generateNameFrameXYFromImageLocation(); } mGsb.setScreenWidth(windowWidth); mGsb.setScreenHeight(windowHeight); } }); builder.setNeutralButton("Fit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.v(TAG, "Fitting board"); float xScale = (float) (windowWidth)/(float) (mGsb.getScreenWidth()); float yScale = (float) (windowHeight)/(float) (mGsb.getScreenHeight()); boolean xFillsDisplay = xScale < yScale; float applicableScale = (xScale < yScale) ? xScale : yScale; float hiddenAreaSize; if (xFillsDisplay) { hiddenAreaSize = ((float) windowHeight-(float) mGsb.getScreenHeight()*applicableScale)/2; } else { hiddenAreaSize = ((float) windowWidth-(float) mGsb.getScreenWidth()*applicableScale)/2; } Log.v(TAG, "X scale: \"" + xScale + "\"" + ", old width: \""+mGsb.getScreenWidth() + "\", new width: \"" + windowWidth + "\""); Log.v(TAG, "Y scale: \"" + yScale + "\"" + ", old height: \""+mGsb.getScreenHeight() + "\", new height: \"" + windowHeight + "\""); Log.v(TAG, "Applicable scale: \"" + applicableScale + "\""); Log.v(TAG, "Hidden area size: \"" + hiddenAreaSize + "\""); mGsb.setBackgroundWidth(mGsb.getBackgroundWidth()*applicableScale); mGsb.setBackgroundHeight(mGsb.getBackgroundHeight()*applicableScale); if (xFillsDisplay) { mGsb.setBackgroundX(mGsb.getBackgroundX()*applicableScale); mGsb.setBackgroundY(hiddenAreaSize+mGsb.getBackgroundY()*applicableScale); } else { mGsb.setBackgroundX(hiddenAreaSize+mGsb.getBackgroundX()*applicableScale); mGsb.setBackgroundY(mGsb.getBackgroundY()*applicableScale); } for (GraphicalSound sound : mGsb.getSoundList()) { sound = SoundNameDrawing.getScaledTextSize(sound, applicableScale); if (xFillsDisplay) { sound.setNameFrameX(sound.getNameFrameX()*applicableScale); sound.setNameFrameY(hiddenAreaSize+sound.getNameFrameY()*applicableScale); sound.setImageX(sound.getImageX()*applicableScale); sound.setImageY(hiddenAreaSize+sound.getImageY()*applicableScale); } else { Log.w(TAG, "sound: " + sound.getName()); Log.w(TAG, "hiddenAreaSize: " + hiddenAreaSize + " sound.getNameFrameX(): " + sound.getNameFrameX() + " applicableScale: " + applicableScale); Log.w(TAG, "hiddenAreaSize+sound.getNameFrameX()*applicableScale: " + (hiddenAreaSize+sound.getNameFrameX()*applicableScale)); sound.setNameFrameX(hiddenAreaSize+sound.getNameFrameX()*applicableScale); sound.setNameFrameY(sound.getNameFrameY()*applicableScale); sound.setImageX(hiddenAreaSize+sound.getImageX()*applicableScale); sound.setImageY(sound.getImageY()*applicableScale); } sound.setImageWidth(sound.getImageWidth()*applicableScale); sound.setImageHeight(sound.getImageHeight()*applicableScale); if (sound.getLinkNameAndImage()) sound.generateNameFrameXYFromImageLocation(); } GraphicalSound blackBar1 = new GraphicalSound(); blackBar1.setNameFrameInnerColor(255, 0, 0, 0); GraphicalSound blackBar2 = new GraphicalSound(); blackBar2.setNameFrameInnerColor(255, 0, 0, 0); if (xFillsDisplay) { blackBar1.setName("I hide top of the board."); blackBar2.setName("I hide bottom of the board."); blackBar1.setPath(new File(SoundboardMenu.mTopBlackBarSoundFilePath)); blackBar2.setPath(new File(SoundboardMenu.mBottomBlackBarSoundFilePath)); blackBar1.setNameFrameY(hiddenAreaSize); blackBar2.setNameFrameY((float) windowHeight-hiddenAreaSize); } else { blackBar1.setName("I hide left side of the board."); blackBar2.setName("I hide right side of the board."); blackBar1.setPath(new File(SoundboardMenu.mLeftBlackBarSoundFilePath)); blackBar2.setPath(new File(SoundboardMenu.mRightBlackBarSoundFilePath)); blackBar1.setNameFrameX(hiddenAreaSize); blackBar2.setNameFrameX((float) windowWidth-hiddenAreaSize); } mGsb.addSound(blackBar1); mGsb.addSound(blackBar2); mGsb.setScreenWidth(windowWidth); mGsb.setScreenHeight(windowHeight); } }); builder.setNegativeButton("Keep", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mGsb.setScreenWidth(windowWidth); mGsb.setScreenHeight(windowHeight); } }); AlertDialog alert = builder.create(); alert.setOnDismissListener(new OnDismissListener() { public void onDismiss(DialogInterface dialog) { mGsbh.createHistoryCheckpoint(); } }); alert.show(); } Looper.loop(); Looper.myLooper().quit(); } }; t.start(); } class DrawingPanel extends SurfaceView implements SurfaceHolder.Callback { public DrawingPanel(Context context) { super(context); getHolder().addCallback(this); mThread = new DrawingThread(getHolder(), this); } @Override public boolean onTouchEvent(MotionEvent event) { if (mThread == null) return false; synchronized (mThread.getSurfaceHolder()) { if(event.getAction() == MotionEvent.ACTION_DOWN){ if (mMoveBackground) { mBackgroundLeftDistance = event.getX() - mGsb.getBackgroundX(); mBackgroundTopDistance = event.getY() - mGsb.getBackgroundY(); } else { ListIterator<GraphicalSound> iterator = mGsb.getSoundList().listIterator(); while (iterator.hasNext()) {iterator.next();} while (iterator.hasPrevious()) { GraphicalSound sound = iterator.previous(); String soundPath = sound.getPath().getAbsolutePath(); SoundNameDrawing soundNameDrawing = new SoundNameDrawing(sound); float nameFrameX = sound.getNameFrameX(); float nameFrameY = sound.getNameFrameY(); float nameFrameWidth = soundNameDrawing.getNameFrameRect().width(); float nameFrameHeight = soundNameDrawing.getNameFrameRect().height(); if (event.getX() >= sound.getImageX() && event.getX() <= sound.getImageWidth() + sound.getImageX() && event.getY() >= sound.getImageY() && event.getY() <= sound.getImageHeight() + sound.getImageY()) { if (mCopyColor != 0) { copyColor(sound); } else { mDragTarget = DRAG_IMAGE; initializeDrag(event, sound); } break; } else if ((event.getX() >= sound.getNameFrameX() && event.getX() <= nameFrameWidth + sound.getNameFrameX() && event.getY() >= sound.getNameFrameY() && event.getY() <= nameFrameHeight + sound.getNameFrameY()) || soundPath.equals(SoundboardMenu.mTopBlackBarSoundFilePath) && event.getY() <= nameFrameY || soundPath.equals(SoundboardMenu.mBottomBlackBarSoundFilePath) && event.getY() >= nameFrameY || soundPath.equals(SoundboardMenu.mLeftBlackBarSoundFilePath) && event.getX() <= nameFrameX || soundPath.equals(SoundboardMenu.mRightBlackBarSoundFilePath) && event.getX() >= nameFrameX) { if (mCopyColor != 0) { copyColor(sound); } else { mDragTarget = DRAG_TEXT; initializeDrag(event, sound); } break; } } mClickTime = Calendar.getInstance().getTimeInMillis(); } } else if(event.getAction() == MotionEvent.ACTION_MOVE){ if (mMoveBackground) { mGsb.setBackgroundX(event.getX() - mBackgroundLeftDistance); mGsb.setBackgroundY(event.getY() - mBackgroundTopDistance); } else if (mDrawDragSound == true) { if (mDragSound.getLinkNameAndImage() || mDragTarget == DRAG_TEXT) { mDragSound.setNameFrameX(event.getX()-mNameFrameDragDistanceX); mDragSound.setNameFrameY(event.getY()-mNameFrameDragDistanceY); } if (mDragSound.getLinkNameAndImage() || mDragTarget == DRAG_IMAGE) { mDragSound.setImageX(event.getX() - mImageDragDistanceX); mDragSound.setImageY(event.getY() - mImageDragDistanceY); } } } else if(event.getAction() == MotionEvent.ACTION_UP){ if (mMoveBackground) { mGsb.setBackgroundX(event.getX() - mBackgroundLeftDistance); mGsb.setBackgroundY(event.getY() - mBackgroundTopDistance); } else if (mDrawDragSound == true && Calendar.getInstance().getTimeInMillis()-mClickTime < 200) { mClickTime = 0; mDragSound.setNameFrameX(mInitialNameFrameX); mDragSound.setNameFrameY(mInitialNameFrameY); mDragSound.setImageX(mInitialImageX); mDragSound.setImageY(mInitialImageY); mGsb.getSoundList().add(mDragSound); mDrawDragSound = false; invalidate(); final CharSequence[] items = {"Info", "Name settings", "Image settings", "Sound settings", "Duplicate sound", "Remove sound", "Set as..."}; AlertDialog.Builder optionsBuilder = new AlertDialog.Builder(GraphicalSoundboardEditor.this); optionsBuilder.setTitle("Options"); optionsBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { SoundNameDrawing soundNameDrawing = new SoundNameDrawing(mDragSound); AlertDialog.Builder builder = new AlertDialog.Builder(GraphicalSoundboardEditor.this); builder.setTitle("Sound info"); builder.setMessage("Name:\n"+mDragSound.getName()+ "\n\nSound path:\n"+mDragSound.getPath()+ "\n\nImage path:\n"+mDragSound.getImagePath()+ "\n\nActive image path:\n"+mDragSound.getActiveImagePath()+ "\n\nName and image linked:\n"+mDragSound.getLinkNameAndImage()+ "\n\nHide image or text:\n"+mDragSound.getHideImageOrText()+ "\n\nImage X:\n"+mDragSound.getImageX()+ "\n\nImage Y:\n"+mDragSound.getImageY()+ "\n\nImage width:\n"+mDragSound.getImageWidth()+ "\n\nImage height:\n"+mDragSound.getImageHeight()+ "\n\nName frame X:\n"+mDragSound.getNameFrameX()+ "\n\nName frame Y:\n"+mDragSound.getNameFrameY()+ "\n\nName frame width:\n"+soundNameDrawing.getNameFrameRect().width()+ "\n\nName frame height:\n"+soundNameDrawing.getNameFrameRect().height()+ "\n\nAuto arrange column:\n"+mDragSound.getAutoArrangeColumn()+ "\n\nAuto arrange row:\n"+mDragSound.getAutoArrangeRow()+ "\n\nSecond click action:\n"+mDragSound.getSecondClickAction()+ "\n\nLeft volume:\n"+mDragSound.getVolumeLeft()+ "\n\nRight volume:\n"+mDragSound.getVolumeRight()+ "\n\nName frame border color:\n"+mDragSound.getNameFrameBorderColor()+ "\n\nName frame inner color:\n"+mDragSound.getNameFrameInnerColor()+ "\n\nName text color:\n"+mDragSound.getNameTextColor()+ "\n\nName text size:\n"+mDragSound.getNameSize()+ "\n\nShow name frame border paint:\n"+mDragSound.getShowNameFrameBorderPaint()+ "\n\nShow name frame inner paint:\n"+mDragSound.getShowNameFrameBorderPaint()); builder.show(); } else if (item == 1) { LayoutInflater inflater = (LayoutInflater) GraphicalSoundboardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate( R.layout.graphical_soundboard_editor_alert_sound_name_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final EditText soundNameInput = (EditText) layout.findViewById(R.id.soundNameInput); soundNameInput.setText(mDragSound.getName()); final EditText soundNameSizeInput = (EditText) layout.findViewById(R.id.soundNameSizeInput); soundNameSizeInput.setText(Float.toString(mDragSound.getNameSize())); final CheckBox checkShowSoundName = (CheckBox) layout.findViewById(R.id.showSoundNameCheckBox); checkShowSoundName.setChecked(mDragSound.getHideImageOrText() != GraphicalSound.HIDE_TEXT); final CheckBox checkShowInnerPaint = (CheckBox) layout.findViewById(R.id.showInnerPaintCheckBox); checkShowInnerPaint.setChecked(mDragSound.getShowNameFrameInnerPaint()); final CheckBox checkShowBorderPaint = (CheckBox) layout.findViewById(R.id.showBorderPaintCheckBox); checkShowBorderPaint.setChecked(mDragSound.getShowNameFrameBorderPaint()); final Button nameColorButton = (Button) layout.findViewById(R.id.nameColorButton); nameColorButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mDragSound.setName(soundNameInput.getText().toString()); mDragSound.generateImageXYFromNameFrameLocation(); Intent i = new Intent(GraphicalSoundboardEditor.this, ColorChanger.class); i.putExtra("parentKey", "changeNameColor"); i.putExtras(XStreamUtil.getSoundBundle(mDragSound, mGsb)); startActivityForResult(i, CHANGE_NAME_COLOR); } }); final Button innerPaintColorButton = (Button) layout.findViewById(R.id.innerPaintColorButton); innerPaintColorButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mDragSound.setName(soundNameInput.getText().toString()); mDragSound.generateImageXYFromNameFrameLocation(); Intent i = new Intent(GraphicalSoundboardEditor.this, ColorChanger.class); i.putExtra("parentKey", "changeinnerPaintColor"); i.putExtras(XStreamUtil.getSoundBundle(mDragSound, mGsb)); startActivityForResult(i, CHANGE_INNER_PAINT_COLOR); } }); final Button borderPaintColorButton = (Button) layout.findViewById(R.id.borderPaintColorButton); borderPaintColorButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mDragSound.setName(soundNameInput.getText().toString()); mDragSound.generateImageXYFromNameFrameLocation(); Intent i = new Intent(GraphicalSoundboardEditor.this, ColorChanger.class); i.putExtra("parentKey", "changeBorderPaintColor"); i.putExtras(XStreamUtil.getSoundBundle(mDragSound, mGsb)); startActivityForResult(i, CHANGE_BORDER_PAINT_COLOR); } }); AlertDialog.Builder builder = new AlertDialog.Builder(GraphicalSoundboardEditor.this); builder.setView(layout); builder.setTitle("Name settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { boolean notifyIncorrectValue = false; if (checkShowSoundName.isChecked() == false) { mDragSound.setHideImageOrText(GraphicalSound.HIDE_TEXT); } else if (checkShowSoundName.isChecked() && mDragSound.getHideImageOrText() == GraphicalSound.HIDE_TEXT) { mDragSound.setHideImageOrText(GraphicalSound.SHOW_ALL); mDragSound.generateImageXYFromNameFrameLocation(); } mDragSound.setShowNameFrameInnerPaint(checkShowInnerPaint.isChecked()); mDragSound.setShowNameFrameBorderPaint(checkShowBorderPaint.isChecked()); mDragSound.setName(soundNameInput.getText().toString()); try { mDragSound.setNameSize(Float.valueOf( soundNameSizeInput.getText().toString()).floatValue()); } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } if (mDragSound.getLinkNameAndImage()) { mDragSound.generateImageXYFromNameFrameLocation(); } if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } mGsbh.createHistoryCheckpoint(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.show(); } else if (item == 2) { LayoutInflater inflater = (LayoutInflater) GraphicalSoundboardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate( R.layout.graphical_soundboard_editor_alert_sound_image_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox checkShowSoundImage = (CheckBox) layout.findViewById(R.id.showSoundImageCheckBox); checkShowSoundImage.setChecked(mDragSound.getHideImageOrText() != GraphicalSound.HIDE_IMAGE); soundImageWidthText = (TextView) layout.findViewById(R.id.soundImageWidthText); soundImageWidthText.setText("Width (" + mDragSound.getImage().getWidth() + ")"); soundImageHeightText = (TextView) layout.findViewById(R.id.soundImageHeightText); soundImageHeightText.setText("Height (" + mDragSound.getImage().getHeight() + ")"); final EditText soundImageWidthInput = (EditText) layout.findViewById(R.id.soundImageWidthInput); soundImageWidthInput.setText(Float.toString(mDragSound.getImageWidth())); final EditText soundImageHeightInput = (EditText) layout.findViewById(R.id.soundImageHeightInput); soundImageHeightInput.setText(Float.toString(mDragSound.getImageHeight())); final CheckBox scaleWidthHeight = (CheckBox) layout.findViewById(R.id.scaleWidthHeightCheckBox); scaleWidthHeight.setChecked(true); scaleWidthHeight.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { // Calculate a new scale widthHeightScale = Float.valueOf(soundImageWidthInput.getText().toString()).floatValue() / Float.valueOf(soundImageHeightInput.getText().toString()).floatValue(); } catch(NumberFormatException nfe) {Log.e(TAG, "Unable to calculate width and height scale", nfe);} } }); widthHeightScale = mDragSound.getImageWidth() / mDragSound.getImageHeight(); soundImageWidthInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (scaleWidthHeight.isChecked()) { try { float value = Float.valueOf(soundImageWidthInput.getText().toString()).floatValue(); soundImageHeightInput.setText(Float.valueOf(value/widthHeightScale).toString()); } catch(NumberFormatException nfe) {} } return false; } }); soundImageHeightInput.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (scaleWidthHeight.isChecked()) { try { float value = Float.valueOf(soundImageHeightInput.getText().toString()).floatValue(); soundImageWidthInput.setText(Float.valueOf(value*widthHeightScale).toString()); } catch(NumberFormatException nfe) {} } return false; } }); final Button revertSizeButton = (Button) layout.findViewById(R.id.revertImageSizeButton); revertSizeButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { soundImageWidthInput.setText(Float.valueOf(mDragSound.getImageWidth()).toString()); soundImageHeightInput.setText(Float.valueOf(mDragSound.getImageHeight()).toString()); widthHeightScale = mDragSound.getImageWidth() / mDragSound.getImageHeight(); } }); final Button setSoundImageButton = (Button) layout.findViewById(R.id.setSoundImageButton); setSoundImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { selectImageFile(); } }); final Button resetSoundImageButton = (Button) layout.findViewById(R.id.resetSoundImageButton); resetSoundImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mDragSound.setImage(BitmapFactory.decodeResource(getResources(), R.drawable.sound)); mDragSound.setImagePath(null); } }); final Button setSoundActiveImageButton = (Button) layout.findViewById(R.id.setSoundActiveImageButton); setSoundActiveImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { selectActiveImageFile(); } }); final Button resetSoundActiveImageButton = (Button) layout.findViewById(R.id.resetSoundActiveImageButton); resetSoundActiveImageButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { mDragSound.setActiveImage(null); mDragSound.setActiveImagePath(null); } }); AlertDialog.Builder builder = new AlertDialog.Builder(GraphicalSoundboardEditor.this); builder.setView(layout); builder.setTitle("Image settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { boolean notifyIncorrectValue = false; if (checkShowSoundImage.isChecked() == false) { mDragSound.setHideImageOrText(GraphicalSound.HIDE_IMAGE); } else if (checkShowSoundImage.isChecked() && mDragSound.getHideImageOrText() == GraphicalSound.HIDE_IMAGE) { mDragSound.setHideImageOrText(GraphicalSound.SHOW_ALL); } try { mDragSound.setImageWidth(Float.valueOf( soundImageWidthInput.getText().toString()).floatValue()); mDragSound.setImageHeight(Float.valueOf( soundImageHeightInput.getText().toString()).floatValue()); } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } mDragSound.generateImageXYFromNameFrameLocation(); if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } mGsbh.createHistoryCheckpoint(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.show(); } else if (item == 3) { LayoutInflater inflater = (LayoutInflater) GraphicalSoundboardEditor.this. getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate( R.layout.graphical_soundboard_editor_alert_sound_settings, (ViewGroup) findViewById(R.id.alert_settings_root)); final CheckBox linkNameAndImageCheckBox = (CheckBox) layout.findViewById(R.id.linkNameAndImageCheckBox); linkNameAndImageCheckBox.setChecked(mDragSound.getLinkNameAndImage()); final Button changeSoundPathButton = (Button) layout.findViewById(R.id.changeSoundPathButton); changeSoundPathButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent i = new Intent(GraphicalSoundboardEditor.this, FileExplorer.class); i.putExtra(FileExplorer.EXTRA_ACTION_KEY, FileExplorer.ACTION_CHANGE_SOUND_PATH); i.putExtra(FileExplorer.EXTRA_BOARD_NAME_KEY, mBoardName); startActivityForResult(i, CHANGE_SOUND_PATH); } }); final Button secondClickActionButton = (Button) layout.findViewById(R.id.secondClickActionButton); secondClickActionButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { final CharSequence[] items = {"Play new", "Pause", "Stop"}; AlertDialog.Builder secondClickBuilder = new AlertDialog.Builder( GraphicalSoundboardEditor.this); secondClickBuilder.setTitle("Action"); secondClickBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0) { mDragSound.setSecondClickAction(GraphicalSound.SECOND_CLICK_PLAY_NEW); } else if (item == 1) { mDragSound.setSecondClickAction(GraphicalSound.SECOND_CLICK_PAUSE); } else if (item == 2) { mDragSound.setSecondClickAction(GraphicalSound.SECOND_CLICK_STOP); } } }); AlertDialog secondClickAlert = secondClickBuilder.create(); secondClickAlert.show(); } }); final EditText leftVolumeInput = (EditText) layout.findViewById(R.id.leftVolumeInput); leftVolumeInput.setText(Float.toString(mDragSound.getVolumeLeft()*100) + "%"); final EditText rightVolumeInput = (EditText) layout.findViewById(R.id.rightVolumeInput); rightVolumeInput.setText(Float.toString(mDragSound.getVolumeRight()*100) + "%"); AlertDialog.Builder builder = new AlertDialog.Builder(GraphicalSoundboardEditor.this); builder.setView(layout); builder.setTitle("Sound settings"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { mDragSound.setLinkNameAndImage(linkNameAndImageCheckBox.isChecked()); if (mDragSound.getLinkNameAndImage()) { mDragSound.generateImageXYFromNameFrameLocation(); } boolean notifyIncorrectValue = false; Float leftVolumeValue = null; try { String leftVolumeString = leftVolumeInput.getText().toString(); if (leftVolumeString.contains("%")) { leftVolumeValue = Float.valueOf(leftVolumeString.substring(0, leftVolumeString.indexOf("%"))).floatValue()/100; } else { leftVolumeValue = Float.valueOf(leftVolumeString).floatValue()/100; } if (leftVolumeValue >= 0 && leftVolumeValue <= 1 && leftVolumeValue != null) { mDragSound.setVolumeLeft(leftVolumeValue); } else { notifyIncorrectValue = true; } } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } Float rightVolumeValue = null; try { String rightVolumeString = rightVolumeInput.getText().toString(); if (rightVolumeString.contains("%")) { rightVolumeValue = Float.valueOf(rightVolumeString.substring(0, rightVolumeString.indexOf("%"))).floatValue()/100; } else { rightVolumeValue = Float.valueOf(rightVolumeString).floatValue()/100; } if (rightVolumeValue >= 0 && rightVolumeValue <= 1 && rightVolumeValue != null) { mDragSound.setVolumeRight(rightVolumeValue); } else { notifyIncorrectValue = true; } } catch(NumberFormatException nfe) { notifyIncorrectValue = true; } if (notifyIncorrectValue == true) { Toast.makeText(getApplicationContext(), "Incorrect value", Toast.LENGTH_SHORT).show(); } mGsbh.createHistoryCheckpoint(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); builder.show(); } else if (item == 4) { GraphicalSound duplicate = (GraphicalSound) mDragSound.clone(); if (mGsb.getAutoArrange()) { if (placeToFreeSlot(duplicate)) { mGsb.getSoundList().add(duplicate); } } else { placeToFreeSpace(duplicate); mGsb.getSoundList().add(duplicate); } mGsbh.createHistoryCheckpoint(); } else if (item == 5) { LayoutInflater removeInflater = (LayoutInflater) GraphicalSoundboardEditor.this.getSystemService(LAYOUT_INFLATER_SERVICE); View removeLayout = removeInflater.inflate( R.layout.graphical_soundboard_editor_alert_remove_sound, (ViewGroup) findViewById(R.id.alert_remove_sound_root)); final CheckBox removeFileCheckBox = (CheckBox) removeLayout.findViewById(R.id.removeFile); removeFileCheckBox.setText(" DELETE " + mDragSound.getPath().getAbsolutePath()); AlertDialog.Builder removeBuilder = new AlertDialog.Builder( GraphicalSoundboardEditor.this); removeBuilder.setView(removeLayout); removeBuilder.setTitle("Removing " + mDragSound.getName()); removeBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (removeFileCheckBox.isChecked() == true) { mDragSound.getPath().delete(); } mGsb.getSoundList().remove(mDragSound); mGsbh.createHistoryCheckpoint(); } }); removeBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }); removeBuilder.show(); } else if (item == 6) { final CharSequence[] items = {"Ringtone", "Notification", "Alerts"}; AlertDialog.Builder setAsBuilder = new AlertDialog.Builder( GraphicalSoundboardEditor.this); setAsBuilder.setTitle("Set as..."); setAsBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { String filePath = mDragSound.getPath().getAbsolutePath(); ContentValues values = new ContentValues(); values.put(MediaStore.MediaColumns.DATA, filePath); values.put(MediaStore.MediaColumns.TITLE, mDragSound.getName()); values.put(MediaStore.MediaColumns.MIME_TYPE, MimeTypeMap.getSingleton().getMimeTypeFromExtension( filePath.substring(filePath.lastIndexOf('.'+1)))); values.put(MediaStore.Audio.Media.ARTIST, "Artist"); int selectedAction = 0; if (item == 0) { selectedAction = RingtoneManager.TYPE_RINGTONE; values.put(MediaStore.Audio.Media.IS_RINGTONE, true); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false); values.put(MediaStore.Audio.Media.IS_ALARM, false); values.put(MediaStore.Audio.Media.IS_MUSIC, false); } else if (item == 1) { selectedAction = RingtoneManager.TYPE_NOTIFICATION; values.put(MediaStore.Audio.Media.IS_RINGTONE, false); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true); values.put(MediaStore.Audio.Media.IS_ALARM, false); values.put(MediaStore.Audio.Media.IS_MUSIC, false); } else if (item == 2) { selectedAction = RingtoneManager.TYPE_ALARM; values.put(MediaStore.Audio.Media.IS_RINGTONE, false); values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false); values.put(MediaStore.Audio.Media.IS_ALARM, true); values.put(MediaStore.Audio.Media.IS_MUSIC, false); } Uri uri = MediaStore.Audio.Media.getContentUriForPath(filePath); getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + filePath + "\"", null); Uri newUri = GraphicalSoundboardEditor.this.getContentResolver().insert(uri, values); RingtoneManager.setActualDefaultRingtoneUri(GraphicalSoundboardEditor.this, selectedAction, newUri); } }); AlertDialog setAsAlert = setAsBuilder.create(); setAsAlert.show(); } } }); AlertDialog optionsAlert = optionsBuilder.create(); optionsAlert.show(); invalidate(); } else if (mDrawDragSound == true) { if (mGsb.getAutoArrange()) { int width = mPanel.getWidth(); int height = mPanel.getHeight(); int column = -1, i = 0; while (column == -1) { if (event.getX() >= i*(width/mGsb.getAutoArrangeColumns()) && event.getX() <= (i+1)*(width/(mGsb.getAutoArrangeColumns()))) { column = i; } if (i > 1000) { Log.e(TAG, "column fail"); mDragSound.getAutoArrangeColumn(); break; } i++; } i = 0; int row = -1; while (row == -1) { if (event.getY() >= i*(height/mGsb.getAutoArrangeRows()) && event.getY() <= (i+1)*(height/(mGsb.getAutoArrangeRows()))) { row = i; } if (i > 1000) { Log.e(TAG, "row fail"); mDragSound.getAutoArrangeRow(); break; } i++; } GraphicalSound swapSound = null; for (GraphicalSound sound : mGsb.getSoundList()) { if (sound.getAutoArrangeColumn() == column && sound.getAutoArrangeRow() == row) { swapSound = sound; } } if (column == mDragSound.getAutoArrangeColumn() && row == mDragSound.getAutoArrangeRow()) { moveSound(event.getX(), event.getY()); } else { try { moveSoundToSlot(swapSound, mDragSound.getAutoArrangeColumn(), mDragSound.getAutoArrangeRow(), swapSound.getImageX(), swapSound.getImageY(), swapSound.getNameFrameX(), swapSound.getNameFrameY()); } catch (NullPointerException e) {} moveSoundToSlot(mDragSound, column, row, mInitialImageX, mInitialImageY, mInitialNameFrameX, mInitialNameFrameY); mGsb.addSound(mDragSound); mDrawDragSound = false; } } else { moveSound(event.getX(), event.getY()); } mGsbh.createHistoryCheckpoint(); } } return true; } } @Override public void onDraw(Canvas canvas) { if (canvas == null) { Log.w(TAG, "Got null canvas"); mNullCanvasCount++; // Drawing thread is still running while the activity is destroyed (surfaceCreated was probably called after surfaceDestroyed). // Reproduce by killing the editor immediately after it is created. // It's difficult to kill the thread properly while supporting different orientations and closing of screen. if (mNullCanvasCount > 5) { Log.e(TAG, "Drawing thread was not destroyed properly"); mThread.setRunning(false); mThread = null; } } else { mNullCanvasCount = 0; super.dispatchDraw(canvas); canvas.drawColor(mGsb.getBackgroundColor()); if (mGsb.getUseBackgroundImage() == true && mGsb.getBackgroundImagePath().exists()) { RectF bitmapRect = new RectF(); bitmapRect.set(mGsb.getBackgroundX(), mGsb.getBackgroundY(), mGsb.getBackgroundWidth() + mGsb.getBackgroundX(), mGsb.getBackgroundHeight() + mGsb.getBackgroundY()); Paint bgImage = new Paint(); bgImage.setColor(mGsb.getBackgroundColor()); try { canvas.drawBitmap(mGsb.getBackgroundImage(), null, bitmapRect, bgImage); } catch(NullPointerException npe) { Log.e(TAG, "Unable to draw image " + mGsb.getBackgroundImagePath().getAbsolutePath()); mGsb.setBackgroundImage(BitmapFactory.decodeResource(getResources(), R.drawable.sound)); } } try { ArrayList<GraphicalSound> drawList = new ArrayList<GraphicalSound>(); drawList.addAll(mGsb.getSoundList()); if (mDrawDragSound) drawList.add(mDragSound); for (GraphicalSound sound : drawList) { Paint barPaint = new Paint(); barPaint.setColor(sound.getNameFrameInnerColor()); String soundPath = sound.getPath().getAbsolutePath(); if (soundPath.equals(SoundboardMenu.mTopBlackBarSoundFilePath)) { canvas.drawRect(0, 0, canvas.getWidth(), sound.getNameFrameY(), barPaint); } else if (soundPath.equals(SoundboardMenu.mBottomBlackBarSoundFilePath)) { canvas.drawRect(0, sound.getNameFrameY(), canvas.getWidth(), canvas.getHeight(), barPaint); } else if (soundPath.equals(SoundboardMenu.mLeftBlackBarSoundFilePath)) { canvas.drawRect(0, 0, sound.getNameFrameX(), canvas.getHeight(), barPaint); } else if (soundPath.equals(SoundboardMenu.mRightBlackBarSoundFilePath)) { canvas.drawRect(sound.getNameFrameX(), 0, canvas.getWidth(), canvas.getHeight(), barPaint); } else { if (sound.getHideImageOrText() != GraphicalSound.HIDE_TEXT) { float NAME_DRAWING_SCALE = SoundNameDrawing.NAME_DRAWING_SCALE; canvas.scale(1/NAME_DRAWING_SCALE, 1/NAME_DRAWING_SCALE); SoundNameDrawing soundNameDrawing = new SoundNameDrawing(sound); Paint nameTextPaint = soundNameDrawing.getBigCanvasNameTextPaint(); Paint borderPaint = soundNameDrawing.getBorderPaint(); Paint innerPaint = soundNameDrawing.getInnerPaint(); RectF bigCanvasNameFrameRect = soundNameDrawing.getBigCanvasNameFrameRect(); if (sound.getShowNameFrameInnerPaint() == true) { canvas.drawRoundRect(bigCanvasNameFrameRect, 2*NAME_DRAWING_SCALE, 2*NAME_DRAWING_SCALE, innerPaint); } if (sound.getShowNameFrameBorderPaint()) { canvas.drawRoundRect(bigCanvasNameFrameRect, 2*NAME_DRAWING_SCALE, 2*NAME_DRAWING_SCALE, borderPaint); } int i = 0; for (String row : sound.getName().split("\n")) { canvas.drawText(row, (sound.getNameFrameX()+2)*NAME_DRAWING_SCALE, sound.getNameFrameY()*NAME_DRAWING_SCALE+(i+1)*sound.getNameSize()*NAME_DRAWING_SCALE, nameTextPaint); i++; } canvas.scale(NAME_DRAWING_SCALE, NAME_DRAWING_SCALE); } if (sound.getHideImageOrText() != GraphicalSound.HIDE_IMAGE) { RectF imageRect = new RectF(); imageRect.set(sound.getImageX(), sound.getImageY(), sound.getImageWidth() + sound.getImageX(), sound.getImageHeight() + sound.getImageY()); try { if (SoundPlayerControl.isPlaying(sound.getPath()) && sound.getActiveImage() != null) { try { canvas.drawBitmap(sound.getActiveImage(), null, imageRect, mSoundImagePaint); } catch(NullPointerException npe) { Log.e(TAG, "Unable to draw active image " + sound.getActiveImagePath().getAbsolutePath()); sound.setActiveImage(null); canvas.drawBitmap(sound.getImage(), null, imageRect, mSoundImagePaint); } } else { canvas.drawBitmap(sound.getImage(), null, imageRect, mSoundImagePaint); } } catch(NullPointerException npe) { Log.e(TAG, "Unable to draw image " + sound.getImagePath().getAbsolutePath()); sound.setImage(BitmapFactory.decodeResource(getResources(), R.drawable.sound)); } } if (mGsb.getAutoArrange() && sound == mDragSound) { int width = mPanel.getWidth(); int height = mPanel.getHeight(); Paint linePaint = new Paint(); Paint outerLinePaint = new Paint(); { linePaint.setColor(Color.WHITE); outerLinePaint.setColor(Color.YELLOW); outerLinePaint.setStrokeWidth(3); } for (int i = 1; i < mGsb.getAutoArrangeColumns(); i++) { float X = i*(width/mGsb.getAutoArrangeColumns()); canvas.drawLine(X, 0, X, height, outerLinePaint); canvas.drawLine(X, 0, X, height, linePaint); } for (int i = 1; i < mGsb.getAutoArrangeRows(); i++) { float Y = i*(height/mGsb.getAutoArrangeRows()); canvas.drawLine(0, Y, width, Y, outerLinePaint); canvas.drawLine(0, Y, width, Y, linePaint); } } } } } catch(ConcurrentModificationException cme) { Log.w(TAG, "Sound list modification while iteration"); } } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } public void surfaceCreated(SurfaceHolder holder) { try { mThread.setRunning(true); mThread.start(); } catch (NullPointerException e) { mThread = new DrawingThread(getHolder(), this); mThread.setRunning(true); mThread.start(); } Log.d(TAG, "Surface created"); } public void surfaceDestroyed(SurfaceHolder holder) { mThread.setRunning(false); mThread = null; Log.d(TAG, "Surface destroyed"); } } class DrawingThread extends Thread { private SurfaceHolder mSurfaceHolder; private boolean mRun = false; public DrawingThread(SurfaceHolder surfaceHolder, DrawingPanel panel) { mSurfaceHolder = surfaceHolder; mPanel = panel; } public void setRunning(boolean run) { mRun = run; } public SurfaceHolder getSurfaceHolder() { return mSurfaceHolder; } @Override public void run() { while (mRun) { Canvas c; c = null; try { c = mSurfaceHolder.lockCanvas(null); synchronized (mSurfaceHolder) { mPanel.onDraw(c); } } finally { if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } try { if (mMode == EDIT_BOARD && (mDrawDragSound || mMoveBackground )) { Thread.sleep(10); } else if (mMode == EDIT_BOARD && mDrawDragSound == false && mMoveBackground == false) { for (int i = 0; i <= 5; i++) { Thread.sleep(100); if (mDrawDragSound || mMoveBackground) { break; } } } else if (mMode == LISTEN_BOARD) { for (int i = 0; i <= 30; i++) { Thread.sleep(20); if (mMode == EDIT_BOARD || mCanvasInvalidated == true) { mCanvasInvalidated = false; break; } } } else { Log.e(TAG, "Undefined redraw rate state"); Thread.sleep(1000); } } catch (InterruptedException e) {} } } } }
package dyvilx.tools.repl.command; import dyvil.collection.Set; import dyvil.collection.mutable.IdentityHashSet; import dyvil.collection.mutable.TreeSet; import dyvil.reflect.Modifiers; import dyvil.source.LineSource; import dyvil.util.Qualifier; import dyvilx.tools.compiler.ast.classes.ClassBody; import dyvilx.tools.compiler.ast.classes.IClass; import dyvilx.tools.compiler.ast.context.IContext; import dyvilx.tools.compiler.ast.expression.IValue; import dyvilx.tools.compiler.ast.field.IField; import dyvilx.tools.compiler.ast.field.IProperty; import dyvilx.tools.compiler.ast.generic.ITypeContext; import dyvilx.tools.compiler.ast.member.Member; import dyvilx.tools.compiler.ast.method.Candidate; import dyvilx.tools.compiler.ast.method.IMethod; import dyvilx.tools.compiler.ast.method.MatchList; import dyvilx.tools.compiler.ast.parameter.ParameterList; import dyvilx.tools.compiler.ast.type.IType; import dyvilx.tools.compiler.ast.type.builtin.Types; import dyvilx.tools.compiler.parser.DyvilSymbols; import dyvilx.tools.compiler.parser.expression.ExpressionParser; import dyvilx.tools.compiler.util.Markers; import dyvilx.tools.compiler.util.MemberSorter; import dyvilx.tools.compiler.util.Util; import dyvilx.tools.parsing.ParserManager; import dyvilx.tools.parsing.TokenList; import dyvilx.tools.parsing.lexer.DyvilLexer; import dyvilx.tools.parsing.marker.MarkerList; import dyvilx.tools.repl.DyvilREPL; import dyvilx.tools.repl.context.REPLContext; import dyvilx.tools.repl.lang.I18n; import java.io.PrintStream; public class CompleteCommand implements ICommand { @Override public String getName() { return "complete"; } @Override public String[] getAliases() { return new String[] { "c" }; } @Override public String getUsage() { return ":c[omplete] <identifier>[.]"; } @Override public void execute(DyvilREPL repl, String argument) { final IContext context = repl.getContext().getContext(); if (argument == null) { // REPL Variables this.printREPLMembers(repl, ""); return; } final int dotIndex = argument.lastIndexOf('.'); if (dotIndex <= 0) { // REPL Variable Completions this.printREPLMembers(repl, Qualifier.qualify(argument)); return; } final String expression = argument.substring(0, dotIndex); final String memberStart = Qualifier.qualify(argument.substring(dotIndex + 1)); final MarkerList markers = new MarkerList(Markers.INSTANCE); final TokenList tokens = new DyvilLexer(markers, DyvilSymbols.INSTANCE).tokenize(expression); new ParserManager(DyvilSymbols.INSTANCE, tokens.iterator(), markers) .parse(new ExpressionParser((IValue value) -> { value.resolveTypes(markers, context); value = value.resolve(markers, context); value.checkTypes(markers, context); if (!markers.isEmpty()) { // Print Errors, if any final boolean colors = repl.getCompiler().config.useAnsiColors(); final StringBuilder buffer = new StringBuilder(); markers.log(new LineSource(expression), buffer, colors); repl.getOutput().println(buffer); } try { this.printCompletions(repl, memberStart, value); } catch (Throwable throwable) { throwable.printStackTrace(repl.getErrorOutput()); } })); } private void printREPLMembers(DyvilREPL repl, String start) { final REPLContext replContext = repl.getContext(); final Set<IField> variables = new TreeSet<>(MemberSorter.MEMBER_COMPARATOR); final Set<IMethod> methods = new TreeSet<>(MemberSorter.METHOD_COMPARATOR); for (IField variable : replContext.getFields().values()) { checkMember(variables, variable, start); } for (IMethod method : replContext.getMethods()) { checkMember(methods, method, start); } final PrintStream output = repl.getOutput(); boolean hasOutput = false; if (!variables.isEmpty()) { hasOutput = true; output.println(I18n.get("command.complete.variables")); printMembers(output, variables, null); } if (!methods.isEmpty()) { hasOutput = true; output.println(I18n.get("command.complete.methods")); printMethods(output, methods, null); } if (!hasOutput) { output.println(I18n.get("command.complete.none")); } } private void printCompletions(DyvilREPL repl, String memberStart, IValue value) { final IType type = value.getType(); final boolean statics = value.isClassAccess(); final IContext context = repl.getContext().getContext(); final Set<IField> fields = new TreeSet<>(MemberSorter.MEMBER_COMPARATOR); final Set<IProperty> properties = new TreeSet<>(MemberSorter.MEMBER_COMPARATOR); final Set<IMethod> methods = new TreeSet<>(MemberSorter.METHOD_COMPARATOR); final Set<IMethod> extensionMethods = new TreeSet<>(MemberSorter.METHOD_COMPARATOR); final Set<IMethod> conversionMethods = new TreeSet<>(MemberSorter.METHOD_COMPARATOR); final PrintStream output = repl.getOutput(); if (statics) { output.println(I18n.get("command.complete.type", type)); findMembers(type, fields, properties, methods, memberStart, true); findExtensions(context, type, value, extensionMethods, memberStart, true); } else { output.println(I18n.get("command.complete.expression", value, type)); findInstanceMembers(type, fields, properties, methods, memberStart, new IdentityHashSet<>()); findExtensions(context, type, value, extensionMethods, memberStart, false); findConversions(context, type, value, conversionMethods); } boolean hasOutput = false; if (!fields.isEmpty()) { hasOutput = true; output.println(I18n.get("command.complete.fields")); printMembers(output, fields, type); } if (!properties.isEmpty()) { hasOutput = true; output.println(I18n.get("command.complete.properties")); printMembers(output, properties, type); } if (!methods.isEmpty()) { hasOutput = true; output.println(I18n.get("command.complete.methods")); printMethods(output, methods, type); } if (!extensionMethods.isEmpty()) { hasOutput = true; output.println(I18n.get("command.complete.extensions")); printMethods(output, extensionMethods, type); } if (!conversionMethods.isEmpty()) { hasOutput = true; output.println(I18n.get("command.complete.conversions")); printMethods(output, conversionMethods, type); } if (!hasOutput) { output.println(I18n.get("command.complete.none")); } } private static void printMembers(PrintStream out, Set<? extends Member> members, ITypeContext typeContext) { for (Member member : members) { out.print('\t'); out.println(Util.memberSignatureToString(member, typeContext)); } } private static void printMethods(PrintStream out, Set<IMethod> methods, ITypeContext typeContext) { for (IMethod method : methods) { out.print('\t'); out.println(Util.methodSignatureToString(method, typeContext)); } } private static void findMembers(IType type, Set<IField> fields, Set<IProperty> properties, Set<IMethod> methods, String start, boolean statics) { final IClass theClass = type.getTheClass(); if (theClass == null) { return; } final ClassBody body = theClass.getBody(); if (body == null) { return; } for (int i = 0, count = body.fieldCount(); i < count; i++) { checkMember(fields, body.getField(i), start, statics); } for (int i = 0, count = body.propertyCount(); i < count; i++) { checkMember(properties, body.getProperty(i), start, statics); } for (int i = 0, count = body.methodCount(); i < count; i++) { checkMember(methods, body.getMethod(i), start, statics); } } private static void findInstanceMembers(IType type, Set<IField> fields, Set<IProperty> properties, Set<IMethod> methods, String start, Set<IClass> dejaVu) { final IClass iclass = type.getTheClass(); if (iclass == null || dejaVu.contains(iclass)) { return; } dejaVu.add(iclass); // Add members final ParameterList parameterList = iclass.getParameters(); for (int i = 0, count = parameterList.size(); i < count; i++) { checkMember(fields, (IField) parameterList.get(i), start, false); } findMembers(type, fields, properties, methods, start, false); // Recursively scan super types final IType superType = iclass.getSuperType(); if (superType != null) { findInstanceMembers(superType.getConcreteType(type), fields, properties, methods, start, dejaVu); } for (IType interfaceType : iclass.getInterfaces()) { findInstanceMembers(interfaceType.getConcreteType(type), fields, properties, methods, start, dejaVu); } } private static void findExtensions(IContext context, IType type, IValue value, Set<IMethod> methods, String start, boolean statics) { final MatchList<IMethod> matchList = new MatchList<>(context, true); type.getMethodMatches(matchList, value, null, null); context.getMethodMatches(matchList, value, null, null); Types.BASE_CONTEXT.getMethodMatches(matchList, value, null, null); for (Candidate<IMethod> candidate : matchList) { final IMethod member = candidate.getMember(); if (member.hasModifier(Modifiers.INFIX) || member.getEnclosingClass() != type.getTheClass()) { checkMember(methods, member, start, true); } } } private static void findConversions(IContext context, IType type, IValue value, Set<IMethod> methods) { MatchList<IMethod> matchList = new MatchList<>(null, true); type.getImplicitMatches(matchList, value, null); context.getImplicitMatches(matchList, value, null); Types.BASE_CONTEXT.getImplicitMatches(matchList, value, null); for (int i = 0, count = matchList.size(); i < count; i++) { checkMember(methods, matchList.getCandidate(i).getMember(), "", true); } } private static <T extends Member> void checkMember(Set<T> set, T member, String start) { if (member.getName().startsWith(start)) { set.add(member); } } private static <T extends Member> void checkMember(Set<T> set, T member, String start, boolean statics) { if (!member.getName().startsWith(start)) { return; } final long modifiers = member.getAttributes().flags(); if ((modifiers & Modifiers.PUBLIC) != 0 && statics == ((modifiers & Modifiers.STATIC) != 0)) { set.add(member); } } }
package org.voltdb.jdbc; import java.io.Closeable; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.voltdb.client.Client; import org.voltdb.client.ClientConfig; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientImpl; import org.voltdb.client.ClientResponse; import org.voltdb.client.ClientStats; import org.voltdb.client.ClientStatsContext; import org.voltdb.client.NoConnectionsException; import org.voltdb.client.ProcCallException; import org.voltdb.client.ProcedureCallback; /** * Provides a high-level wrapper around the core {@link Client} class to provide performance * tracking, connection pooling and Future-based asynchronous execution support. ClientConnections * should be obtained through the {@link JDBC4ClientConnectionPool} get methods and cannot be * instantiated directly. * * Extending ClientStatusListenerExt allows us to detect dropped connections, etc.. * * @author Seb Coursol (copied and renamed from exampleutils) * @since 2.0 */ public class JDBC4ClientConnection implements Closeable { private final JDBC4PerfCounterMap statistics; private final ArrayList<String> servers; private final ClientConfig config; private AtomicReference<Client> client = new AtomicReference<Client>(); /** * The base hash/key for this connection, that uniquely identifies its parameters, as defined by * the pool. */ protected final String keyBase; /** * The actual hash/key for this connection, that uniquely identifies this specific native * {@link Client} wrapper. */ protected final String key; /** * The number of active users on the connection. Used and managed by the pool to determine when * a specific {@link Client} wrapper has reached capacity (and a new one should be created). */ protected short users = 0; /** * The default asynchronous operation timeout for Future-based executions (while the operation * may so time out on the client side, note that, technically, once submitted to the database * cluster, the call cannot be cancelled!). */ protected long defaultAsyncTimeout = 60000; /** * Creates a new native client wrapper from the given parameters (internal use only). * * @param clientConnectionKeyBase * the base hash/key for this connection, as defined by the pool. * @param clientConnectionKey * the actual hash/key for this connection, as defined by the pool (may contain a * trailing index when the pool decides a new client needs to be created based on the * number of clients). * @param servers * the list of VoltDB servers to connect to in hostname[:port] format. * @param user * the user name to use when connecting to the server(s). * @param password * the password to use when connecting to the server(s). * @param isHeavyWeight * the flag indicating callback processes on this connection will be heavy (long * running callbacks). By default the connection only allocates one background * processing thread to process callbacks. If those callbacks run for a long time, * the network stack can get clogged with pending responses that have yet to be * processed, at which point the server will disconnect the application, thinking it * died and is not reading responses as fast as it is pushing requests. When the flag * is set to 'true', an additional 2 processing thread will deal with processing * callbacks, thus mitigating the issue. * @param maxOutstandingTxns * the number of transactions the client application may push against a specific * connection before getting blocked on back-pressure. By default the connection * allows 3,000 open transactions before preventing the client from posting more * work, thus preventing server fire-hosing. In some cases however, with very fast, * small transactions, this limit can be raised. * @throws IOException * @throws UnknownHostException */ protected JDBC4ClientConnection( String clientConnectionKeyBase, String clientConnectionKey, String[] servers, String user, String password, boolean isHeavyWeight, int maxOutstandingTxns) throws UnknownHostException, IOException { // Save the list of trimmed non-empty server names. this.servers = new ArrayList<String>(servers.length); for (String server : servers) { server = server.trim(); if (!server.isEmpty()) { this.servers.add(server); } } if (this.servers.isEmpty()) { throw new UnknownHostException("JDBC4ClientConnection: no servers provided"); } this.keyBase = clientConnectionKeyBase; this.key = clientConnectionKey; this.statistics = JDBC4ClientConnectionPool.getStatistics(clientConnectionKeyBase); // Create configuration this.config = new ClientConfig(user, password); config.setHeavyweight(isHeavyWeight); if (maxOutstandingTxns > 0) config.setMaxOutstandingTxns(maxOutstandingTxns); // Create client and connect. createClientAndConnect(); } /** * Private method to (re)initialize a client connection. * @return new ClientImpl * @throws UnknownHostException * @throws IOException */ private ClientImpl createClientAndConnect() throws UnknownHostException, IOException { // Make client connections. ClientImpl clientTmp = (ClientImpl) ClientFactory.createClient(this.config); for (String server : this.servers) { clientTmp.createConnection(server); } // If no exception escaped this method it's a good client. this.client.set(clientTmp); this.users++; return clientTmp; } /** * Get current client or reconnect one as needed. * Concurrency strategy: If the connection is lost while providing one the * caller will get a non-null, but ultimately bad connection that will fail. * But it won't cause an NPE. This method is synchronized so that a * reconnection won't happen simultaneously. The client won't get dropped * if a parallel thread comes in later trying to drop the original client * because dropClient() only does it if the request matches the current client. * @return client * @throws UnknownHostException * @throws IOException */ protected synchronized ClientImpl getClient() throws UnknownHostException, IOException { ClientImpl retClient = (ClientImpl) this.client.get() ; if (retClient != null) { return retClient; } return this.createClientAndConnect(); } /** * Used by the pool to indicate a new thread/user is using a specific connection, helping the * pool determine when new connections need to be created. * * @return the reference to this connection to be returned to the calling user. */ protected synchronized JDBC4ClientConnection use() { this.users++; return this; } /** * Used by the pool to indicate a thread/user has stopped using the connection (and optionally * close the underlying client if there are no more users against it). */ protected synchronized void dispose() { this.users if (this.users == 0) { try { Client currentClient = this.client.get(); if (currentClient != null) { currentClient.close(); } } catch (Exception x) { // ignore } } } /** * Drop the client connection, e.g. when a NoConnectionsException is caught. * It will try to reconnect as needed and appropriate. * @param clientToDrop caller-provided client to avoid re-nulling from another thread that comes in later */ protected synchronized void dropClient(ClientImpl clientToDrop) { Client currentClient = this.client.get(); if (currentClient != null && currentClient == clientToDrop) { try { currentClient.close(); this.client.set(null); } catch (Exception x) { // ignore } } this.users = 0; } /** * Closes the connection, releasing it to the pool so another thread/client may pick it up. This * method must be closed by a user when the connection is no longer needed to avoid pool * pressure and leaks where the pool would keep creating new connections all the time, * wrongfully believing all existing connections to be actively used. */ @Override public void close() { JDBC4ClientConnectionPool.dispose(this); } /** * Executes a procedure synchronously and returns the result to the caller. The method * internally tracks execution performance. * * @param procedure * the name of the procedure to call. * @param parameters * the list of parameters to pass to the procedure. * @return the response sent back by the VoltDB cluster for the procedure execution. * @throws IOException * @throws NoConnectionsException * @throws ProcCallException */ public ClientResponse execute(String procedure, long timeout, Object... parameters) throws NoConnectionsException, IOException, ProcCallException { long start = System.currentTimeMillis(); ClientImpl currentClient = this.getClient(); try { // If connections are lost try reconnecting. ClientResponse response = currentClient.callProcedureWithTimeout(procedure, timeout, TimeUnit.SECONDS, parameters); this.statistics.update(procedure, response); return response; } catch (ProcCallException pce) { this.statistics.update(procedure, System.currentTimeMillis() - start, false); throw pce; } catch (NoConnectionsException e) { this.statistics.update(procedure, System.currentTimeMillis() - start, false); this.dropClient(currentClient); throw e; } } /** * Internal asynchronous callback used to track the execution performance of asynchronous calls. */ private static class TrackingCallback implements ProcedureCallback { private final JDBC4ClientConnection Owner; private final String Procedure; private final ProcedureCallback UserCallback; /** * Creates a new callback. * * @param owner * the connection to which the request was sent (and that will be receiving the * response). * @param procedure * the procedure being executed and for which we're awaiting a response. * @param userCallback * the user-specified callback that will be called once we have tracked * statistics, making this internal callback transparent to the calling * application. */ public TrackingCallback(JDBC4ClientConnection owner, String procedure, ProcedureCallback userCallback) { this.Owner = owner; this.Procedure = procedure; this.UserCallback = userCallback; } /** * Processes the server response, tracking performance statistics internally, then calling * the user-specified callback (if any). */ @Override public void clientCallback(ClientResponse response) throws Exception { this.Owner.getStatistics().update(this.Procedure, response); if (this.UserCallback != null) this.UserCallback.clientCallback(response); } } /** * Executes a procedure asynchronously, then calls the provided user callback with the server * response upon completion. * * @param callback * the user-specified callback to call with the server response upon execution * completion. * @param procedure * the name of the procedure to call. * @param parameters * the list of parameters to pass to the procedure. * @return the result of the submission false if the client connection was terminated and unable * to post the request to the server, true otherwise. */ public boolean executeAsync(ProcedureCallback callback, String procedure, Object... parameters) throws NoConnectionsException, IOException { ClientImpl currentClient = this.getClient(); try { return currentClient.callProcedure(new TrackingCallback(this, procedure, callback), procedure, parameters); } catch (NoConnectionsException e) { this.dropClient(currentClient); throw e; } } /** * Executes a procedure asynchronously, returning a Future that can be used by the caller to * wait upon completion before processing the server response. * * @param procedure * the name of the procedure to call. * @param parameters * the list of parameters to pass to the procedure. * @return the Future created to wrap around the asynchronous process. */ public Future<ClientResponse> executeAsync(String procedure, Object... parameters) throws NoConnectionsException, IOException { ClientImpl currentClient = this.getClient(); final JDBC4ExecutionFuture future = new JDBC4ExecutionFuture(this.defaultAsyncTimeout); try { currentClient.callProcedure(new TrackingCallback(this, procedure, new ProcedureCallback() { @SuppressWarnings("unused") final JDBC4ExecutionFuture result; { this.result = future; } @Override public void clientCallback(ClientResponse response) throws Exception { future.set(response); } }), procedure, parameters); } catch (NoConnectionsException e) { this.dropClient(currentClient); throw e; } return future; } /** * Gets the new version of the performance statistics for this connection only. * @return A {@link ClientStatsContext} that correctly represents the client statistics. */ public ClientStatsContext getClientStatsContext() { if (this.client.get() == null) { return null; } return this.client.get().createStatsContext(); } /** * @deprecated * Gets the global performance statistics for this connection (and all connections with the same * parameters). * * @return the counter map aggregated across all the connections in the pool with the same * parameters as this connection. */ @Deprecated public JDBC4PerfCounterMap getStatistics() { return JDBC4ClientConnectionPool.getStatistics(this); } /** * @deprecated * Gets the performance statistics for a specific procedure on this connection (and all * connections with the same parameters). * * @param procedure * the name of the procedure for which to retrieve the statistics. * @return the counter aggregated across all the connections in the pool with the same * parameters as this connection. */ @Deprecated public JDBC4PerfCounter getStatistics(String procedure) { return JDBC4ClientConnectionPool.getStatistics(this).get(procedure); } /** * @deprecated * Gets the aggregated performance statistics for a list of procedures on this connection (and * all connections with the same parameters). * * @param procedures * the list of procedures for which to retrieve the statistics. * @return the counter aggregated across all the connections in the pool with the same * parameters as this connection, and across all procedures. */ @Deprecated public JDBC4PerfCounter getStatistics(String... procedures) { JDBC4PerfCounterMap map = JDBC4ClientConnectionPool.getStatistics(this); JDBC4PerfCounter result = new JDBC4PerfCounter(false); for (String procedure : procedures) result.merge(map.get(procedure)); return result; } /** * Save statistics to a CSV file. * * @param file * File path * @throws IOException */ public void saveStatistics(String file) throws IOException { if (file != null && !file.trim().isEmpty()) { FileWriter fw = new FileWriter(file); fw.write(getStatistics().toRawString(',')); fw.flush(); fw.close(); } } void writeSummaryCSV(ClientStats stats, String path) throws IOException { if (this.client.get() == null) { throw new IOException("Client is unavailable for writing summary CSV."); } this.client.get().writeSummaryCSVWithDoubles(stats, path); } /** * Block the current thread until all queued stored procedure invocations have received * responses or there are no more connections to the cluster * * @throws InterruptedException * @throws IOException * @see Client#drain() */ public void drain() throws InterruptedException, IOException { ClientImpl currentClient = this.getClient(); if (currentClient == null) { throw new IOException("Client is unavailable for drain()."); } currentClient.drain(); } /** * Blocks the current thread until there is no more backpressure or there are no more * connections to the database * * @throws InterruptedException * @throws IOException */ public void backpressureBarrier() throws InterruptedException, IOException { ClientImpl currentClient = this.getClient(); if (currentClient == null) { throw new IOException("Client is unavailable for backpressureBarrier()."); } currentClient.backpressureBarrier(); } /** * Synchronously invokes UpdateApplicationCatalog procedure. Blocks until a result is available. * A {@link ProcCallException} is thrown if the response is anything other then success. * * @param catalogPath * Path to the catalog jar file. * @param deploymentPath * Path to the deployment file * @return array of VoltTable results * @throws IOException * If the files cannot be serialized * @throws NoConnectionException * @throws ProcCallException */ public ClientResponse updateApplicationCatalog(File catalogPath, File deploymentPath) throws IOException, NoConnectionsException, ProcCallException { ClientImpl currentClient = this.getClient(); try { return currentClient.updateApplicationCatalog(catalogPath, deploymentPath); } catch (NoConnectionsException e) { this.dropClient(currentClient); throw e; } } }
package org.folio.okapi; import org.folio.okapi.service.ModuleManager; import org.folio.okapi.web.TenantWebService; import io.vertx.core.AbstractVerticle; import io.vertx.core.Context; import io.vertx.core.Future; import io.vertx.core.Vertx; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServerOptions; import io.vertx.core.json.Json; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.core.spi.cluster.ClusterManager; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.ext.web.handler.CorsHandler; import java.io.InputStream; import java.lang.management.ManagementFactory; import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.folio.okapi.bean.Ports; import org.folio.okapi.bean.TenantDescriptor; import org.folio.okapi.deployment.DeploymentManager; import org.folio.okapi.web.HealthService; import org.folio.okapi.service.ModuleStore; import org.folio.okapi.web.ModuleWebService; import org.folio.okapi.service.ProxyService; import org.folio.okapi.service.TenantManager; import org.folio.okapi.service.TenantStore; import org.folio.okapi.service.TimeStampStore; import org.folio.okapi.util.LogHelper; import org.folio.okapi.common.XOkapiHeaders; import org.folio.okapi.deployment.DeploymentWebService; import org.folio.okapi.discovery.DiscoveryManager; import org.folio.okapi.discovery.DiscoveryService; import org.folio.okapi.env.EnvManager; import org.folio.okapi.env.EnvService; import org.folio.okapi.service.impl.Storage; import static org.folio.okapi.service.impl.Storage.InitMode.*; import org.folio.okapi.util.ProxyContext; public class MainVerticle extends AbstractVerticle { private final Logger logger = LoggerFactory.getLogger("okapi"); private final LogHelper logHelper = new LogHelper(); HealthService healthService; ModuleManager moduleManager; TenantManager tenantManager; EnvService envService; EnvManager envManager; ModuleWebService moduleWebService; ProxyService proxyService; TenantWebService tenantWebService; DeploymentWebService deploymentWebService; DeploymentManager deploymentManager; DiscoveryService discoveryService; DiscoveryManager discoveryManager; ClusterManager clusterManager; private Storage storage; Storage.InitMode initMode = NORMAL; private int port; // Little helper to get a config value: // First from System (-D on command line), // then from config (from the way the verticle gets deployed, e.g. in tests) // finally a default value static String conf(String key, String def, JsonObject c) { return System.getProperty(key, c.getString(key, def)); } public void setClusterManager(ClusterManager mgr) { clusterManager = mgr; } @Override public void init(Vertx vertx, Context context) { InputStream in = getClass().getClassLoader().getResourceAsStream("git.properties"); if (in != null) { try { Properties prop = new Properties(); prop.load(in); in.close(); logger.info("git: " + prop.getProperty("git.remote.origin.url") + " " + prop.getProperty("git.commit.id")); } catch (Exception e) { logger.warn(e); } } boolean enableProxy = false; boolean enableDeployment = false; super.init(vertx, context); JsonObject config = context.config(); port = Integer.parseInt(conf("port", "9130", config)); int port_start = Integer.parseInt(conf("port_start", Integer.toString(port + 1), config)); int port_end = Integer.parseInt(conf("port_end", Integer.toString(port_start + 10), config)); if (clusterManager != null) { logger.info("cluster NodeId " + clusterManager.getNodeID()); } else { logger.info("clusterManager not in use"); } final String host = conf("host", "localhost", config); String okapiUrl = conf("okapiurl", "http://localhost:" + port , config); okapiUrl = okapiUrl.replaceAll("/+$", ""); // Remove trailing slash, if there String storageType = conf("storage", "inmemory", config); String loglevel = conf("loglevel", "", config); if (!loglevel.isEmpty()) { logHelper.setRootLogLevel(loglevel); } String mode = config.getString("mode", "cluster"); switch (mode) { case "cluster": case "dev": enableDeployment = true; enableProxy = true; break; case "deployment": enableDeployment = true; break; case "proxy": enableProxy = true; break; case "purgedatabase": initMode = PURGE; enableProxy = true; // so we get to initialize the database. We exit soon after anyway break; case "initdatabase": initMode = INIT; enableProxy = true; break; default: logger.fatal("Unknown role '" + mode + "'"); System.exit(1); } envManager = new EnvManager(); discoveryManager = new DiscoveryManager(); if (clusterManager != null) { discoveryManager.setClusterManager(clusterManager); } if (enableDeployment) { Ports ports = new Ports(port_start, port_end); deploymentManager = new DeploymentManager(vertx, discoveryManager, envManager, host, ports, port); deploymentWebService = new DeploymentWebService(deploymentManager); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { CountDownLatch latch = new CountDownLatch(1); deploymentManager.shutdown(ar -> { latch.countDown(); }); try { if (!latch.await(2, TimeUnit.MINUTES)) { logger.error("Timed out waiting to undeploy all"); } } catch (InterruptedException e) { throw new IllegalStateException(e); } } }); } if (enableProxy) { discoveryService = new DiscoveryService(discoveryManager); healthService = new HealthService(); moduleManager = new ModuleManager(vertx); tenantManager = new TenantManager(moduleManager); moduleManager.setTenantManager(tenantManager); discoveryManager.setModuleManager(moduleManager); final String okapiUrl_f = okapiUrl; envService = new EnvService(envManager); storage = new Storage(vertx, storageType, config); ModuleStore moduleStore = storage.getModuleStore(); TimeStampStore timeStampStore = storage.getTimeStampStore(); TenantStore tenantStore = storage.getTenantStore(); logger.info("Proxy using " + storageType + " storage"); moduleWebService = new ModuleWebService(vertx, moduleManager, moduleStore, timeStampStore); tenantWebService = new TenantWebService(vertx, tenantManager, tenantStore, discoveryManager); proxyService = new ProxyService(vertx, moduleManager, tenantManager, discoveryManager, okapiUrl_f); } } public void NotFound(RoutingContext ctx) { ProxyContext pc = new ProxyContext(ctx, "okapi.notfound"); String slash = ""; if (ctx.request().path().endsWith("/")) { slash = " Try without a trailing slash"; } pc.responseError(404, "Okapi: unrecognized service " + ctx.request().path() + slash); } @Override public void start(Future<Void> fut) { if (storage != null) { storage.prepareDatabases(initMode, res -> { if (res.failed()) { logger.fatal("start failed", res.cause()); fut.fail(res.cause()); } else { if (initMode != NORMAL) { logger.info("Database operation " + initMode.toString() + " done. Exiting"); System.exit(0); } startModules(fut); } }); } else { startModules(fut); } } private void startModules(Future<Void> fut) { if (moduleWebService == null) { startTenants(fut); } else { moduleWebService.loadModules(res -> { if (res.succeeded()) { startTenants(fut); } else { logger.fatal("load modules: " + res.cause().getMessage()); fut.fail(res.cause()); } }); } } private void startTenants(Future<Void> fut) { if (tenantWebService == null) { checkSuperTenant(fut); } else { tenantWebService.loadTenants(res -> { if (res.succeeded()) { checkSuperTenant(fut); } else { logger.fatal("load tenants failed: " + res.cause().getMessage()); fut.fail(res.cause()); } }); } } /** * Create the super tenant, if not already there. * * @param fut */ private void checkSuperTenant(Future<Void> fut) { if (tenantWebService == null || tenantManager.get(XOkapiHeaders.SUPERTENANT_ID) != null) { startEnv(fut); } else { // need to create it logger.debug("Creating the superTenant " + XOkapiHeaders.SUPERTENANT_ID); final String docTenant = "{" + "\"id\" : \"" + XOkapiHeaders.SUPERTENANT_ID + "\"," + "\"name\" : \"" + XOkapiHeaders.SUPERTENANT_ID + "\"," + "\"description\" : \"Okapi built-in super tenant\"" + "}"; final TenantDescriptor td = Json.decodeValue(docTenant, TenantDescriptor.class); tenantWebService.createInternally(td, res -> { if (res.succeeded()) { startEnv(fut); } else { logger.fatal("Create SuperTenant " + XOkapiHeaders.SUPERTENANT_ID + " failed: " + res.cause().getMessage()); fut.fail(res.cause()); } }); } } /* TODO - Create internal module(s) and enable for the superTenant */ private void startEnv(Future<Void> fut) { if (envManager == null) { startDiscovery(fut); } else { envManager.init(vertx, res -> { if (res.succeeded()) { startDiscovery(fut); } else { fut.fail(res.cause()); } }); } } private void startDiscovery(Future<Void> fut) { if (discoveryManager == null) { startDeployment(fut); } else { discoveryManager.init(vertx, res -> { if (res.succeeded()) { startDeployment(fut); } else { fut.fail(res.cause()); } }); } } public void startDeployment(Future<Void> fut) { if (deploymentManager == null) { startListening(fut); } else { deploymentManager.init(res -> { if (res.succeeded()) { startListening(fut); } else { fut.fail(res.cause()); } }); } } private void startListening(Future<Void> fut) { Router router = Router.router(vertx); //handle CORS router.route().handler(CorsHandler.create("*") .allowedMethod(HttpMethod.PUT) .allowedMethod(HttpMethod.DELETE) .allowedMethod(HttpMethod.GET) .allowedMethod(HttpMethod.POST) //allow request headers .allowedHeader(HttpHeaders.CONTENT_TYPE.toString()) .allowedHeader(XOkapiHeaders.TENANT) .allowedHeader(XOkapiHeaders.TOKEN) .allowedHeader(XOkapiHeaders.AUTHORIZATION) .allowedHeader(XOkapiHeaders.REQUEST_ID) //expose response headers .exposedHeader(HttpHeaders.LOCATION.toString()) .exposedHeader(XOkapiHeaders.TRACE) .exposedHeader(XOkapiHeaders.TOKEN) .exposedHeader(XOkapiHeaders.AUTHORIZATION) .exposedHeader(XOkapiHeaders.REQUEST_ID) ); // Paths that start with /_/ are okapi internal configuration router.route("/_*").handler(BodyHandler.create()); //enable reading body to string if (moduleWebService != null) { router.postWithRegex("/_/proxy/modules").handler(moduleWebService::create); router.delete("/_/proxy/modules/:id").handler(moduleWebService::delete); router.get("/_/proxy/modules/:id").handler(moduleWebService::get); router.getWithRegex("/_/proxy/modules").handler(moduleWebService::list); router.put("/_/proxy/modules/:id").handler(moduleWebService::update); } if (tenantWebService != null) { router.postWithRegex("/_/proxy/tenants").handler(tenantWebService::create); router.getWithRegex("/_/proxy/tenants").handler(tenantWebService::list); router.get("/_/proxy/tenants/:id").handler(tenantWebService::get); router.put("/_/proxy/tenants/:id").handler(tenantWebService::update); router.delete("/_/proxy/tenants/:id").handler(tenantWebService::delete); router.post("/_/proxy/tenants/:id/modules").handler(tenantWebService::enableModule); router.delete("/_/proxy/tenants/:id/modules/:mod").handler(tenantWebService::disableModule); router.post("/_/proxy/tenants/:id/modules/:mod").handler(tenantWebService::updateModule); router.get("/_/proxy/tenants/:id/modules").handler(tenantWebService::listModules); router.get("/_/proxy/tenants/:id/modules/:mod").handler(tenantWebService::getModule); router.getWithRegex("/_/proxy/health").handler(healthService::get); } // Endpoints for internal testing only. // The reload points can be removed as soon as we have a good integration // test that verifies that changes propagate across a cluster... if (moduleWebService != null) { router.getWithRegex("/_/test/reloadmodules").handler(moduleWebService::reloadModules); router.get("/_/test/reloadtenant/:id").handler(tenantWebService::reloadTenant); router.getWithRegex("/_/test/loglevel").handler(logHelper::getRootLogLevel); router.postWithRegex("/_/test/loglevel").handler(logHelper::setRootLogLevel); } if (deploymentWebService != null) { router.postWithRegex("/_/deployment/modules").handler(deploymentWebService::create); router.delete("/_/deployment/modules/:instid").handler(deploymentWebService::delete); router.getWithRegex("/_/deployment/modules").handler(deploymentWebService::list); router.get("/_/deployment/modules/:instid").handler(deploymentWebService::get); } if (discoveryService != null) { router.postWithRegex("/_/discovery/modules").handler(discoveryService::create); router.delete("/_/discovery/modules/:srvcid/:instid").handler(discoveryService::delete); router.get("/_/discovery/modules/:srvcid/:instid").handler(discoveryService::get); router.get("/_/discovery/modules/:srvcid").handler(discoveryService::getSrvcId); router.getWithRegex("/_/discovery/modules").handler(discoveryService::getAll); router.get("/_/discovery/health/:srvcid/:instid").handler(discoveryService::health); router.get("/_/discovery/health/:srvcid").handler(discoveryService::healthSrvcId); router.getWithRegex("/_/discovery/health").handler(discoveryService::healthAll); router.get("/_/discovery/nodes/:id").handler(discoveryService::getNode); router.getWithRegex("/_/discovery/nodes").handler(discoveryService::getNodes); } if (envService != null) { router.postWithRegex("/_/env").handler(envService::create); router.delete("/_/env/:id").handler(envService::delete); router.get("/_/env").handler(envService::getAll); router.get("/_/env/:id").handler(envService::get); } router.route("/_*").handler(this::NotFound); // everything else gets proxified to modules if (proxyService != null) {
package ibis.smartsockets.virtual; import ibis.smartsockets.SmartSocketsProperties; import ibis.smartsockets.direct.DirectSocket; import ibis.smartsockets.direct.DirectSocketAddress; import ibis.smartsockets.direct.DirectSocketFactory; import ibis.smartsockets.discovery.Discovery; import ibis.smartsockets.hub.Hub; import ibis.smartsockets.hub.servicelink.ServiceLink; import ibis.smartsockets.util.TypedProperties; import ibis.smartsockets.virtual.modules.AbstractDirectModule; import ibis.smartsockets.virtual.modules.AcceptHandler; import ibis.smartsockets.virtual.modules.ConnectModule; import ibis.smartsockets.virtual.modules.direct.Direct; import ibis.smartsockets.util.ThreadPool; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.BindException; import java.net.SocketTimeoutException; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class implements a virtual socket factory. * * The VirtualSocketFactory is the public interface to the virtual connection * layer of SmartSockets. It implements several types of connection setup using * the direct connection layer (see {@link DirectSocketFactory}) and a * {@link ServiceLink} to the {@link Hub}. *<p> * The different connection setup schemes are implemented in separate modules * each extending the {@link ConnectModule} class. *<p> * Currently, 4 different connect modules are available:<br> *<p> * {@link Direct}: creates a direct connection to the target.<br> * {@link Reverse}: reverses the connection setup.such that the target creates a * direct connection to the source.<br> * {@link Splice}: uses TCP splicing to create a direct connection to the * target.<br> * {@link Hubrouted}: create a virtual connection that routes all traffic * through the hub overlay.<br> *<p> * To create a new connection, each module is tried in sequence until a * connection is established, or until it is clear that a connection can not be * established at all (e.g., because the destination port does not exist on the * target machine). By default, the order<br> *<p> * Direct, Reverse, Splice, Routed * <p>is used. This order prefers modules that produce a direct connection. This * default order can be changed using the * smartsockets.modules.order property. The order can also be * adjusted on a per connection basis by providing this property to the * createClientSocket method. * * @see ibis.smartsockets.virtual.modules * @see DirectSocketFactory * @see ServiceLink * @see Hub * * @author Jason Maassen * @version 1.0 Jan 30, 2006 * @since 1.0 * */ public final class VirtualSocketFactory { /** * An inner class the prints connection statistics at a regular interval. */ private static class StatisticsPrinter implements Runnable { private int timeout; private VirtualSocketFactory factory; private String prefix; StatisticsPrinter(final VirtualSocketFactory factory, final int timeout, final String prefix) { this.timeout = timeout; this.factory = factory; this.prefix = prefix; } public void run() { int t = getTimeout(); while (t > 0) { try { synchronized (this) { wait(t); } } catch (InterruptedException e) { // ignore } t = getTimeout(); if (t > 0) { try { factory.printStatistics(prefix); } catch (Exception e) { logger.warn("Failed to print statistics", e); } } } } private synchronized int getTimeout() { return timeout; } public synchronized void adjustInterval(final int interval) { timeout = interval; notifyAll(); } } private static final Map<String, VirtualSocketFactory> factories = new HashMap<String, VirtualSocketFactory>(); private static VirtualSocketFactory defaultFactory = null; /** Generic logger for this class. */ protected static final Logger logger = LoggerFactory.getLogger("ibis.smartsockets.virtual.misc"); /** Logger for connection related logging. */ protected static final Logger conlogger = LoggerFactory.getLogger("ibis.smartsockets.virtual.connect"); private static final Logger statslogger = LoggerFactory .getLogger("ibis.smartsockets.statistics"); private final DirectSocketFactory directSocketFactory; private final ArrayList<ConnectModule> modules = new ArrayList<ConnectModule>(); private ConnectModule direct; private final TypedProperties properties; private final int DEFAULT_BACKLOG; private final int DEFAULT_TIMEOUT; private final int DEFAULT_ACCEPT_TIMEOUT; private final boolean DETAILED_EXCEPTIONS; private final Random random; private final HashMap<Integer, VirtualServerSocket> serverSockets = new HashMap<Integer, VirtualServerSocket>(); private int nextPort = 3000; private DirectSocketAddress myAddresses; private DirectSocketAddress hubAddress; private VirtualSocketAddress localVirtualAddress; private String localVirtualAddressAsString; private ServiceLink serviceLink; private Hub hub; private VirtualClusters clusters; private boolean printStatistics = false; private String statisticPrefix = null; private StatisticsPrinter printer = null; /** * An innerclass that accepts incoming connections for a hub. * * Only used when hub delegation is active: a hub and VirtualSocketFactory * are running in the same process and share one contact address. This is * only used in special server processes (such as the Ibis Registry). */ private static class HubAcceptor implements AcceptHandler { private final Hub hub; private HubAcceptor(Hub hub) { this.hub = hub; } public void accept(DirectSocket s, int targetPort, long time) { hub.delegateAccept(s); } } private VirtualSocketFactory(DirectSocketFactory df, TypedProperties p) throws InitializationException { directSocketFactory = df; if (logger.isInfoEnabled()) { logger.info("Creating VirtualSocketFactory"); } random = new Random(); properties = p; DETAILED_EXCEPTIONS = p.booleanProperty( SmartSocketsProperties.DETAILED_EXCEPTIONS, false); DEFAULT_BACKLOG = p.getIntProperty(SmartSocketsProperties.BACKLOG, 50); DEFAULT_ACCEPT_TIMEOUT = p.getIntProperty( SmartSocketsProperties.ACCEPT_TIMEOUT, 60000); // NOTE: order is VERY important here! try { loadModules(); } catch (Exception e) { logger.info("Failed to load modules!", e); throw new InitializationException(e.getMessage(), e); } if (modules.size() == 0) { logger.info("Failed to load any modules!"); throw new InitializationException("Failed to load any modules!"); } // -- this depends on the modules being loaded DEFAULT_TIMEOUT = determineDefaultTimeout(p); startHub(p); // We now create the service link. This may connect to the hub that we // have just started. String localCluster = p.getProperty( SmartSocketsProperties.CLUSTER_MEMBER, null); createServiceLink(localCluster); // Once the servicelink is up and running, we can start the modules. startModules(); if (modules.size() == 0) { logger.info("Failed to start any modules!"); throw new InitializationException("Failed to load any modules!"); } loadClusterDefinitions(); localVirtualAddress = new VirtualSocketAddress(myAddresses, 0, hubAddress, clusters.localCluster()); localVirtualAddressAsString = localVirtualAddress.toString(); printStatistics = p.booleanProperty(SmartSocketsProperties.STATISTICS_PRINT); if (printStatistics) { statisticPrefix = p.getProperty( SmartSocketsProperties.STATISTICS_PREFIX, "SmartSockets"); int tmp = p.getIntProperty( SmartSocketsProperties.STATISTICS_INTERVAL, 0); if (tmp > 0) { printer = new StatisticsPrinter(this, tmp * 1000, statisticPrefix); ThreadPool .createNew(printer, "SmartSockets Statistics Printer"); } } } private void startHub(TypedProperties p) throws InitializationException { if (p.booleanProperty(SmartSocketsProperties.START_HUB, false)) { AbstractDirectModule d = null; // Check if the hub should delegate it's accept call to the direct // module. This way, only a single server port (and address) is // needed to reach both this virtual socket factory and the hub. boolean delegate = p.booleanProperty( SmartSocketsProperties.HUB_DELEGATE, false); if (delegate) { logger.info("Factory delegating hub accepts to direct module!"); // We should now add an AcceptHandler to the direct module that // intercepts incoming connections for the hub. Start by finding // the direct module... for (ConnectModule m : modules) { if (m.module.equals("ConnectModule(Direct)")) { d = (AbstractDirectModule) m; break; } } if (d == null) { throw new InitializationException("Cannot start hub: " + "Failed to find direct module!"); } // And add its address to the property set as the 'delegation' // address. This is needed by the hub (since it needs to know // its own address). p.setProperty(SmartSocketsProperties.HUB_DELEGATE_ADDRESS, d .getAddresses().toString()); } // Now we create the hub logger.info("Factory is starting hub"); try { hub = new Hub(p); logger.info("Hub running on: " + hub.getHubAddress()); } catch (IOException e) { throw new InitializationException("Failed to start hub", e); } // Finally, if delegation is used, we install the accept handler if (delegate) { // Get the 'virtual port' that the hub pretends to be on. int port = p.getIntProperty( SmartSocketsProperties.HUB_VIRTUAL_PORT, 42); d.installAcceptHandler(port, new HubAcceptor(hub)); } } } private void loadClusterDefinitions() { clusters = new VirtualClusters(this, properties, getModules()); } private DirectSocketAddress discoverHub(String localCluster) { DirectSocketAddress address = null; if (logger.isInfoEnabled()) { logger.info("Attempting to discover hub using UDP multicast..."); } int port = properties .getIntProperty(SmartSocketsProperties.DISCOVERY_PORT); int time = properties .getIntProperty(SmartSocketsProperties.DISCOVERY_TIMEOUT); Discovery d = new Discovery(port, 0, time); String message = "Any Proxies? "; message += localCluster; String result = d.broadcastWithReply(message); if (result != null) { try { address = DirectSocketAddress.getByAddress(result); if (logger.isInfoEnabled()) { logger.info("Hub found at: " + address.toString()); } } catch (Exception e) { if (logger.isInfoEnabled()) { logger.info("Got unknown reply to hub discovery!"); } } } else { if (logger.isInfoEnabled()) { logger.info("No hubs found."); } } return address; } private void createServiceLink(String localCluster) { List<DirectSocketAddress> hubs = new LinkedList<DirectSocketAddress>(); if (hub != null) { hubs.add(hub.getHubAddress()); } // Check if the hub address was passed as a property. String[] tmp = properties .getStringList(SmartSocketsProperties.HUB_ADDRESSES); if (tmp != null && tmp.length > 0) { for (String a : tmp) { try { hubs.add(DirectSocketAddress.getByAddress(a)); } catch (Exception e) { logger.warn("Failed to understand hub address: " + Arrays.deepToString(tmp), e); } } } // If we don't have a hub address, we try to find one ourselves if (hubs.size() == 0) { boolean useDiscovery = properties.booleanProperty( SmartSocketsProperties.DISCOVERY_ALLOWED, false); boolean discoveryPreferred = properties.booleanProperty( SmartSocketsProperties.DISCOVERY_PREFERRED, false); DirectSocketAddress address = null; if (useDiscovery && (discoveryPreferred || hub == null)) { address = discoverHub(localCluster); } if (address != null) { hubs.add(address); } } // Still no address ? Give up... if (hubs.size() == 0) { // properties not set, so no central hub is available logger.warn("ServiceLink not created: no hub address available!"); return; } // Sort addresses according to locality ? boolean force = properties .booleanProperty(SmartSocketsProperties.SL_FORCE); try { serviceLink = ServiceLink.getServiceLink(properties, hubs, myAddresses); hubAddress = serviceLink.getAddress(); } catch (Exception e) { logger.warn("Failed to obtain service link to hub!", e); if (force) { // FIXME!! logger.error("Permanent failure of servicelink! -- will exit"); System.exit(1); } return; } if (force) { int retries = Math.max(1, properties .getIntProperty(SmartSocketsProperties.SL_RETRIES)); boolean connected = false; while (!connected && retries > 0) { try { serviceLink.waitConnected(properties .getIntProperty(SmartSocketsProperties.SL_TIMEOUT)); connected = true; } catch (Exception e) { logger.warn("Failed to connect service link to hub " + hubAddress, e); } retries } if (!connected) { // FIXME logger.error("Permanent failure of servicelink! -- will exit"); System.exit(1); } } else { try { serviceLink.waitConnected(properties .getIntProperty(SmartSocketsProperties.SL_TIMEOUT)); } catch (Exception e) { logger.warn("Failed to connect service link to hub " + hubAddress, e); return; } } // Check if the users want us to register any properties with the hub. String[] props = properties.getStringList( "smartsockets.register.property", ",", null); if (props != null && props.length > 0) { try { if (props.length == 1) { serviceLink.registerProperty(props[0], ""); } else { serviceLink.registerProperty(props[0], props[1]); } } catch (Exception e) { if (props.length == 1) { logger .warn("Failed to register user property: " + props[0]); } else { logger.warn("Failed to register user property: " + props[0] + "=" + props[1]); } } } } private ConnectModule instantiateModule(String name) { if (logger.isInfoEnabled()) { logger.info("Loading module: " + name); } String classname = properties.getProperty( SmartSocketsProperties.MODULES_PREFIX + name, null); if (classname == null) { // The class implementing the module is not explicitly defined, so // instead we use an 'educated guess' of the form: // smartsockets.virtual.modules.<name>.<Name> StringBuffer tmp = new StringBuffer(); tmp.append("ibis.smartsockets.virtual.modules."); tmp.append(name.toLowerCase()); tmp.append("."); tmp.append(Character.toUpperCase(name.charAt(0))); tmp.append(name.substring(1)); classname = tmp.toString(); } if (logger.isInfoEnabled()) { logger.info(" class name: " + classname); } try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Class<?> c; // Check if there is a context class loader if (cl != null) { c = cl.loadClass(classname); } else { c = Class.forName(classname); } // Check if the class we loaded is indeed a flavor of ConnectModule if (!ConnectModule.class.isAssignableFrom(c)) { logger.warn("Cannot load module " + classname + " since it is " + " not a subclass of ConnectModule!"); return null; } return (ConnectModule) c.newInstance(); } catch (Exception e) { logger.info("Failed to load module " + classname, e); } return null; } private void loadModule(final String name) throws Exception { ConnectModule m = instantiateModule(name); m.init(this, name, properties, logger); DirectSocketAddress tmp = m.getAddresses(); if (tmp != null) { if (myAddresses == null) { myAddresses = tmp; } else { myAddresses = DirectSocketAddress.merge(myAddresses, tmp); } } modules.add(m); } private void loadModules() throws Exception { // Get the list of modules that we should load. Note that we should // always load the "direct" module, since it is needed to implement the // others. Note that this doesn't neccesarily mean that the user wants // to use it though... String[] mods = properties.getStringList( SmartSocketsProperties.MODULES_DEFINE, ",", new String[0]); if (mods == null || mods.length == 0) { // Should not happen! throw new NoModulesDefinedException( "No smartsockets modules defined!"); } // Get the list of modules to skip. Note that the direct module cannot // be skipped completely (it is needed to implement the others). String[] skip = properties.getStringList( SmartSocketsProperties.MODULES_SKIP, ",", null); int count = mods.length; // Remove all modules that should be skipped. if (skip != null) { for (int s = 0; s < skip.length; s++) { for (int m = 0; m < mods.length; m++) { if (skip[s].equals(mods[m])) { if (logger.isInfoEnabled()) { logger.info("Skipping module " + mods[m]); } mods[m] = null; count } } } } if (logger.isInfoEnabled()) { String t = ""; for (int i = 0; i < mods.length; i++) { if (mods[i] != null) { t += mods[i] + " "; } } logger.info("Loading " + count + " modules: " + t); } if (count == 0) { throw new NoModulesDefinedException("No smartsockets modules " + "left after filtering!"); } // We start by loading the direct module. This one is always needed to // support the other modules, but not necessarily used by the client. try { direct = new Direct(directSocketFactory); direct.init(this, "direct", properties, logger); myAddresses = direct.getAddresses(); } catch (Exception e) { logger.info("Failed to load direct module!", e); throw e; } if (myAddresses == null) { logger.info("Failed to retrieve my own address!"); throw new NoLocalAddressException( "Failed to retrieve local address!"); } for (int i = 0; i < mods.length; i++) { if (mods[i] != null) { if (mods[i].equals("direct")) { modules.add(direct); } else { try { loadModule(mods[i]); } catch (Exception e) { if (logger.isInfoEnabled()) { logger.info("Failed to load module: " + mods[i], e); } mods[i] = null; count } } } } if (logger.isInfoEnabled()) { logger.info(count + " modules loaded."); } if (count == 0) { throw new NoModulesDefinedException("Failed to load any modules"); } } private int determineDefaultTimeout(TypedProperties p) { int[] tmp = new int[modules.size()]; int totalTimeout = 0; for (int i = 0; i < modules.size(); i++) { // Get the module defined timeout tmp[i] = modules.get(i).getDefaultTimeout(); totalTimeout += tmp[i]; } int timeout = p.getIntProperty(SmartSocketsProperties.CONNECT_TIMEOUT, -1); if (timeout <= 0) { // It's up to the modules to determine their own timeout timeout = totalTimeout; } else { // A user-defined timeout should be distributed over the modules for (int i = 0; i < modules.size(); i++) { double t = (((double) tmp[i]) / totalTimeout) * timeout; modules.get(i).setTimeout((int) t); } } if (logger.isInfoEnabled()) { logger.info("Total timeout set to: " + timeout); for (ConnectModule m : modules) { logger.info(" " + m.getName() + ": " + m.getTimeout()); } } return timeout; } /** * Retrieve an array of the available connection modules. * @return array of available connection modules. */ protected ConnectModule[] getModules() { return modules.toArray(new ConnectModule[modules.size()]); } /** * Retrieve an array of the available connection modules whose names are * listed in names. * * @param names set of modules that may be returned. * @return array of available connection modules whose name was included in * names. */ protected ConnectModule[] getModules(String[] names) { ArrayList<ConnectModule> tmp = new ArrayList<ConnectModule>(); for (int i = 0; i < names.length; i++) { boolean found = false; if (names[i] != null && !names[i].equals("none")) { for (int j = 0; j < modules.size(); j++) { ConnectModule m = modules.get(j); if (m.getName().equals(names[i])) { tmp.add(m); found = true; break; } } if (!found) { logger.warn("Module " + names[i] + " not found!"); } } } return tmp.toArray(new ConnectModule[tmp.size()]); } private void startModules() { ArrayList<ConnectModule> failed = new ArrayList<ConnectModule>(); if (serviceLink == null) { // No servicelink, so remove all modules that depend on it.... for (ConnectModule c : modules) { if (c.requiresServiceLink) { failed.add(c); } } for (ConnectModule c : failed) { logger .info("Module " + c.module + " removed (no serviceLink)!"); modules.remove(c); } failed.clear(); } for (ConnectModule c : modules) { try { c.startModule(serviceLink); } catch (Exception e) { // Remove all modules that fail to start... logger.warn("Module " + c.module + " did not accept serviceLink!", e); failed.add(c); } } for (ConnectModule c : failed) { logger.warn("Module " + c.module + " removed (exception during setup)!"); modules.remove(c); } failed.clear(); } /** * Retrieve VirtualServerSocket that is bound to given port. * * @param port port for which to retrieve VirtualServerSocket. * @return VirtualServerSocket bound to port, or null if port is not in use. */ public VirtualServerSocket getServerSocket(int port) { synchronized (serverSockets) { return serverSockets.get(port); } } /** * Retrieve the ConnectModule with a given name. * * @param name name of requested ConnectModule. * @return ConnectModule bound to name, or null is this name is not in use. */ public ConnectModule findModule(String name) { // Direct is special, since it may be loaded without being part of the // modules array. if (name.equals("direct")) { return direct; } for (ConnectModule m : modules) { if (m.module.equals(name)) { return m; } } return null; } /** * Close a VirtualSocket and its related I/O Streams while ignoring * exceptions. * * @param s VirtualSocket to close (may be null). * @param out OutputStream to close (may be null). * @param in InputStream to close (may be null). */ public static void close(VirtualSocket s, OutputStream out, InputStream in) { try { if (out != null) { out.close(); } } catch (Throwable e) { logger.info("Failed to close OutputStream", e); } try { if (in != null) { in.close(); } } catch (Throwable e) { logger.info("Failed to close InputStream", e); } try { if (s != null) { s.close(); } } catch (Throwable e) { logger.info("Failed to close Socket", e); } } /** * Close a VirtualSocket and its related SocketChannel while ignoring * exceptions. * * @param s VirtualSocket to close (may be null). * @param channel SocketChannel to close (may be null). */ public static void close(VirtualSocket s, SocketChannel channel) { if (channel != null) { try { channel.close(); } catch (Exception e) { logger.info("Failed to close SocketChannel", e); } } if (s != null) { try { s.close(); } catch (Exception e) { logger.info("Failed to close Socket", e); } } } /** * This method implements a connect using a specific module. * * This method will return null when: * <p> * - runtime requirements do not match * - the module throws a NonFatalIOException * <p> * When a connection is successfully established, we wait for a accept from * the remote side. There are three possible outcomes: * <p> * - the connection is accepted in time * - the connection is not accepted in time or the connection is lost * - the remote side is overloaded and closes the connection * <p> * In the first case the newly created socket is returned and in the second * case an exception is thrown. In the last case the connection will be * retried using a backoff mechanism until 'timeleft' (the total timeout * specified by the user) is spend. Each new try behaves exactly the same as * the previous attempts. * * @param m ConnectModule to use in connection attempt. * @param target Target VirtualServerSocket. * @param timeout Timeout to use for this specific attempt. * @param timeLeft Total timeout left. * @param fillTimeout Should we retry until the timeout expires ? * @param properties Properties to use in connection setup. * @return a VirtualSocket if the connection setup succeeded, null * otherwise. * @throws IOException a non-transient error occured (i.e., target port does * not exist). * @throws NonFatalIOException a transient error occured (i.e., timeout). */ private VirtualSocket createClientSocket(ConnectModule m, VirtualSocketAddress target, int timeout, int timeLeft, boolean fillTimeout, Map<String, Object> properties) throws IOException, NonFatalIOException { int backoff = 1000; if (!m.matchRuntimeRequirements(properties)) { if (conlogger.isInfoEnabled()) { conlogger.warn("Failed: module " + m.module + " may not be used to set " + "up connection to " + target); } m.connectNotAllowed(); return null; } if (conlogger.isDebugEnabled()) { conlogger.debug("Using module " + m.module + " to set up " + "connection to " + target + " timeout = " + timeout + " timeleft = " + timeLeft); } // We now try to set up a connection. Normally we may not exceed the // timeout, but when we succesfully create a connection we are allowed // to extend this time to timeLeft (either to wait for an accept, or to // retry after a TargetOverLoaded exception). Note that any exception // other than ModuleNotSuitable or TargetOverloaded is passed to the // user. VirtualSocket vs = null; int overloaded = 0; long start = System.currentTimeMillis(); boolean lastAttempt = false; while (true) { long t = System.currentTimeMillis() - start; // Check if we ran out of time. If so, the throw a target overloaded // exception or a timeout exception depending on the value of the // overloaded counter. if (t >= timeLeft) { if (conlogger.isDebugEnabled()) { conlogger.debug("Timeout while using module " + m.module + " to set up " + "connection to " + target + " timeout = " + timeout + " timeleft = " + timeLeft + " t = " + t); } if (overloaded > 0) { m.connectRejected(t); throw new TargetOverloadedException("Failed to create " + "virtual connection to " + target + " within " + timeLeft + " ms. (Target overloaded " + overloaded + " times)"); } else { m.connectFailed(t); throw new SocketTimeoutException("Timeout while creating" + " connection to " + target); } } try { vs = m.connect(target, timeout, properties); } catch (NonFatalIOException e) { long end = System.currentTimeMillis(); // Just print and try the next module... if (conlogger.isInfoEnabled()) { conlogger.info("Module " + m.module + " failed to connect " + "to " + target + " after " + (end - start) + " ms.): " + e.getMessage()); } m.connectFailed(end - start); throw e; // NOTE: The modules may also throw IOExceptions for // non-transient errors (i.e., port not found). These are // forwarded to the user. } t = System.currentTimeMillis() - start; if (vs != null) { // We now have a connection to the correct machine and must wait // for an accept from the serversocket. Since we don't have to // try any other modules, we are allowed to spend all of the // time that is left. Therefore, we start by calculating a new // timeout here, which is based on the left over time for the // entire connect call, minus the time we have spend so far in // this connect. This is the timeout we pass to 'waitForAccept'. int newTimeout = (int) (timeLeft - t); if (newTimeout <= 0) { // Bit of a hack. If we run out of time at the last moment // we allow some extra time to finish the connection setup. // TODO: should we do this ? newTimeout = 1000; } if (conlogger.isInfoEnabled()) { conlogger.info(getVirtualAddressAsString() + ": Success " + m.module + " connected to " + target + " now waiting for accept (for max. " + newTimeout + " ms.)"); } try { vs.waitForAccept(newTimeout); vs.setTcpNoDelay(false); long end = System.currentTimeMillis(); if (conlogger.isInfoEnabled()) { conlogger.info(getVirtualAddressAsString() + ": Success " + m.module + " connected to " + target + " (time = " + (end - start) + " ms.)"); } m.connectSucces(end - start); return vs; } catch (TargetOverloadedException e) { // This is always allowed. if (conlogger.isDebugEnabled()) { conlogger.debug("Connection failed, target " + target + " overloaded (" + overloaded + ") while using " + " module " + m.module); } overloaded++; } catch (IOException e) { if (conlogger.isDebugEnabled()) { conlogger.debug("Connection failed, target " + target + ", got exception (" + e.getMessage() + ") while using " + " module " + m.module); } if (!fillTimeout) { m.connectFailed(System.currentTimeMillis() - start); // We'll only retry if 'fillTimeout' is true throw e; } } // The target has refused our connection. Since we have // obviously found a working module, we will not return. // Instead we will retry using a backoff algorithm until // we run out of time... t = System.currentTimeMillis() - start; m.connectRejected(t); int leftover = (int) (timeLeft - t); if (!lastAttempt && leftover > 0) { int sleeptime = 0; if (backoff < leftover) { // Use a randomized sleep value to ensure the attempts // are distributed. sleeptime = random.nextInt(backoff); } else { sleeptime = leftover; lastAttempt = true; } // System.err.println("Backoff = " + backoff + // " Leftover = " + leftover + " Sleep time = " + // sleeptime); if (sleeptime > 0) { try { Thread.sleep(sleeptime); } catch (Exception x) { // ignored } } if (leftover < 500) { // We're done! timeLeft = 0; } else { backoff *= 2; } } else { // We're done timeLeft = 0; } } } } private String[] getNames(ConnectModule[] modules) { String[] names = new String[modules.length]; for (int n = 0; n < modules.length; n++) { names[n] = modules[n].getName(); } return names; } /** * This method loops over and array of connection modules, trying to setup * a connection with each of them each in turn. * <p> * This method returns when:<br> * - a connection is established<b> * - a non-transient error occurs (i.e. remote port not found)<b> * - all modules have failed<b> * - a timeout occurred<b> * * @param target Target VirtualServerSocket. * @param order ConnectModules in the order in which they should be tried. * @param timeouts Timeouts for each of the modules. * @param totalTimeout Total timeout for the connection setup. * @param timing Array in which to record the time required by each module. * @param fillTimeout Should we retry until the timeout expires ? * @param properties Properties to use in connection setup. * @return a VirtualSocket if the connection setup succeeded, null * otherwise. * @throws IOException a non-transient error occurred (i.e., target port * does not exist on receiver). * @throws NoSuitableModuleException No module could create the connection. */ private VirtualSocket createClientSocket(VirtualSocketAddress target, ConnectModule[] order, int[] timeouts, int totalTimeout, long[] timing, boolean fillTimeout, Map<String, Object> prop) throws IOException, NoSuitableModuleException { Throwable[] exceptions = new Throwable[order.length]; try { int timeLeft = totalTimeout; VirtualSocket vs = null; // Now try the remaining modules (or all of them if we weren't // using the cache in the first place...) for (int i = 0; i < order.length; i++) { ConnectModule m = order[i]; int timeout = (timeouts != null ? timeouts[i] : m.getTimeout()); long start = System.currentTimeMillis(); /* * if (timing != null) { timing[1 + i] = System.nanoTime(); * * if (i > 0) { prop.put("direct.detailed.timing.ignore", null); * } } */ try { vs = createClientSocket(m, target, timeout, timeLeft, fillTimeout, prop); } catch (NonFatalIOException e) { // Store the exeception and continue with the next module exceptions[i] = e; } /* * if (timing != null) { timing[1 + i] = System.nanoTime() - * timing[1 + i]; } */ if (vs != null) { if (i > 0) { // We managed to connect, but not with the first module, // so we remember this to speed up later connections. clusters.succes(target, m); } return vs; } if (order.length > 1 && i < order.length - 1) { timeLeft -= System.currentTimeMillis() - start; if (timeLeft <= 0) { // NOTE: This can only happen when a module breaks // the rules (defensive programming). throw new NoSuitableModuleException("Timeout during " + " connect to " + target, getNames(order), exceptions); } } } if (logger.isInfoEnabled()) { logger.info("No suitable module found to connect to " + target); } // No suitable modules found... throw new NoSuitableModuleException("No suitable module found to" + " connect to " + target + " (timeouts=" + Arrays.toString(timeouts) + ", fillTimeout=" + fillTimeout + ")", getNames(order), exceptions); } finally { if (timing != null && prop != null) { timing[0] = System.nanoTime() - timing[0]; prop.remove("direct.detailed.timing.ignore"); } } } // Distribute a given timeout over a number of modules, taking the relative // sizes of the default module timeouts into account. private int[] distributesTimeout(int timeout, int[] timeouts, ConnectModule[] modules) { if (timeouts == null) { timeouts = new int[modules.length]; } for (int i = 0; i < modules.length; i++) { double t = (((double) modules[i].getTimeout()) / DEFAULT_TIMEOUT); timeouts[i] = (int) (t * timeout); } return timeouts; } /** * Create a connection to the VirtualServerSocket at target. * * This method will attempt to setup a connection to the VirtualServerSocket * at target within the given timeout. Using the prop parameter, properties * can be specified that modify the connection setup behavior. * * @param target Address of target VirtualServerSocket. * @param timeout The maximum timeout for the connection setup in * milliseconds. When the timeout is zero the call may block indefinitely, * while a negative timeout will revert to the default value. * @param prop Properties that modify the connection setup behavior (may be * null). * @return a VirtualSocket when the connection setup was successful. * @throws IOException when the connection setup failed. */ public VirtualSocket createClientSocket(VirtualSocketAddress target, int timeout, Map<String, Object> prop) throws IOException { return createClientSocket(target, timeout, false, prop); } /** * Create a connection to the VirtualServerSocket at target. * * This method will attempt to setup a connection to the VirtualServerSocket * at target within the given timeout. Using the prop parameter, properties * can be specified that modify the connection setup behavior. * * @param target Address of target VirtualServerSocket. * @param timeout The maximum timeout for the connection setup in * milliseconds. When the timeout is zero the call may block indefinitely, * while a negative timeout will revert to the default value. * @param fillTimeout Should we retry until the timeout expires ? * @param prop Properties that modify the connection setup behavior (may be * null). * @return a VirtualSocket when the connection setup was successful. * @throws IOException when the connection setup failed. */ public VirtualSocket createClientSocket(VirtualSocketAddress target, int timeout, boolean fillTimeout, Map<String, Object> prop) throws IOException { // Note: it's up to the user to ensure that this thing is large enough! // i.e., it should be of size 1+modules.length if (conlogger.isDebugEnabled()) { conlogger.debug("createClientSocket(" + target + ", " + timeout + ", " + fillTimeout + ", " + prop + ")"); } /* * long [] timing = null; * * if (prop != null) { // Note: it's up to the user to ensure that this * thing is large // enough! i.e., it should be of size 1+modules.length * timing = (long[]) prop.get("virtual.detailed.timing"); * * if (timing != null) { timing[0] = System.nanoTime(); } } */ // Check the timeout here. If it is not set, we will use the default if (timeout <= 0) { timeout = DEFAULT_TIMEOUT; } ConnectModule[] order = clusters.getOrder(target); int timeLeft = timeout; int[] timeouts = null; boolean lastAttempt = false; int backoff = 250; NoSuitableModuleException exception = null; LinkedList<NoSuitableModuleException> exceptions = null; if (DETAILED_EXCEPTIONS) { exceptions = new LinkedList<NoSuitableModuleException>(); } do { if (timeLeft <= DEFAULT_TIMEOUT) { // determine timeout for each module. We assume that this time // is used completely and therefore only do this once. timeouts = distributesTimeout(timeLeft, timeouts, order); fillTimeout = false; } long start = System.currentTimeMillis(); try { return createClientSocket(target, order, timeouts, timeLeft, /* timing */null, fillTimeout, prop); } catch (NoSuitableModuleException e) { // All modules where tried and failed. It now depends on the // user if he would like to try another round or give up. if (conlogger.isDebugEnabled()) { conlogger.debug("createClientSocket failed. Will " + (fillTimeout ? "" : "NOT ") + "retry"); } if (DETAILED_EXCEPTIONS) { exceptions.add(e); } else { exception = e; } } timeLeft -= System.currentTimeMillis() - start; if (!lastAttempt && fillTimeout && timeLeft > 0) { int sleeptime = 0; if (backoff < timeLeft) { sleeptime = random.nextInt(backoff); } else { sleeptime = timeLeft; lastAttempt = true; } if (sleeptime >= timeLeft) { // In the last attempt we sleep half a second shorter. // This allows us to attempt a connection setup. if (sleeptime > 500) { sleeptime -= 500; } else { // We're done! sleeptime = 0; fillTimeout = false; } } if (sleeptime > 0) { try { Thread.sleep(sleeptime); } catch (Exception x) { // ignored } } backoff *= 2; } else { fillTimeout = false; } } while (fillTimeout); if (DETAILED_EXCEPTIONS) { throw new NoSuitableModuleException("No suitable module found to " + "connect to " + target + "(timeout=" + timeout + ", fillTimeout=" + fillTimeout + ")", exceptions); } else { throw exception; } } private int getPort() { // TODO: should this be random ? synchronized (serverSockets) { while (true) { if (!serverSockets.containsKey(nextPort)) { return nextPort++; } else { nextPort++; } } } } /** * Create a new VirtualServerSocket bound the the given port. * * This method will create a new VirtualServerSocket bound the the given, * and using the specified backlog. If port is zero or negative, a valid * unused port number will be generated. If the backlog is zero or negative, * the default value will be used. * <p> * The properties parameter used to modify the connection setup behavior of * the new VirtualServerSocket. * * @param port The port number to use. * @param backlog The maximum number of pending connections this * VirtualServerSocket will allow. * @param retry Retry if the VirtualServerSocket creation fails. * @param properties Properties that modify the connection setup behavior * (may be null). * @return the new VirtualServerSocket, or null if the creation failed. */ public VirtualServerSocket createServerSocket(int port, int backlog, boolean retry, java.util.Properties properties) { // Fix: extract all string properties, don't use the properties object // as a map! --Ceriel HashMap<String, Object> props = new HashMap<String, Object>(); if (properties != null) { // Fix: stringPropertyNames method isn't available on android, so // added a cast --Roelof // for (String s : properties.stringPropertyNames()) { for (Object string : properties.keySet()) { props.put((String) string, properties .getProperty((String) string)); } } VirtualServerSocket result = null; while (result == null) { try { // Did not pass on properties. Fixed. --Ceriel // result = createServerSocket(port, backlog, null); result = createServerSocket(port, backlog, props); } catch (Exception e) { // retry if (logger.isDebugEnabled()) { logger.debug("Failed to open serversocket on port " + port + " (will retry): ", e); } } } return result; } /** * Create a new unbound VirtualServerSocket. * * This method will create a new VirtualServerSocket that is not yet bound * to a port. * <p> * The properties parameter used to modify the connection setup behavior of * the new VirtualServerSocket. * * @param props Properties that modify the connection setup behavior * (may be null). * @return the new VirtualServerSocket. * @throws IOException the VirtualServerSocket creation has failed. */ public VirtualServerSocket createServerSocket(Map<String, Object> props) throws IOException { return new VirtualServerSocket(this, DEFAULT_ACCEPT_TIMEOUT, props); } /** * Bind an unbound VirtualServerSocket to a port. * * @param vss The VirtualServerSocket to bind to the port. * @param port The port to bind the VirtualServerSocket to. * @throws BindException Failed to bind the port to the VirtualServerSocket. */ protected void bindServerSocket(VirtualServerSocket vss, int port) throws BindException { synchronized (serverSockets) { if (serverSockets.containsKey(port)) { throw new BindException("Port " + port + " already in use!"); } serverSockets.put(port, vss); } } /** * Create a new VirtualServerSocket bound the the given port. * * This method will create a new VirtualServerSocket bound the the given, * and using the specified backlog. If port is zero or negative, a valid * unused port number will be generated. If the backlog is zero or negative, * the default value will be used. * <p> * The properties parameter used to modify the connection setup behavior of * the new VirtualServerSocket. * * @param port The port number to use. * @param backlog The maximum number of pending connections this * VirtualServerSocket will allow. * @param properties Properties that modify the connection setup behavior * (may be null). * @return the new VirtualServerSocket, or null if the creation failed. */ public VirtualServerSocket createServerSocket(int port, int backlog, Map<String, Object> properties) throws IOException { if (backlog <= 0) { backlog = DEFAULT_BACKLOG; } if (port <= 0) { port = getPort(); } if (logger.isInfoEnabled()) { logger.info("Creating VirtualServerSocket(" + port + ", " + backlog + ", " + properties + ")"); } synchronized (serverSockets) { if (serverSockets.containsKey(port)) { throw new BindException("Port " + port + " already in use!"); } VirtualSocketAddress a = new VirtualSocketAddress(myAddresses, port, hubAddress, clusters.localCluster()); VirtualServerSocket vss = new VirtualServerSocket(this, a, port, backlog, DEFAULT_ACCEPT_TIMEOUT, properties); serverSockets.put(port, vss); return vss; } } // TODO: hide this thing ? /** * Retrieve the ServiceLink that is connected to the hub. * @return the ServiceLink that is connected to the Hub */ public ServiceLink getServiceLink() { return serviceLink; } /** * Retrieve the DirectSocketAddress of this machine. * @return the DirectSocketAddress of this machine. */ public DirectSocketAddress getLocalHost() { return myAddresses; } /** * Retrieve the name of the local cluster. * @return the name of the local cluster. */ public String getLocalCluster() { return clusters.localCluster(); } /** * Retrieve the DirectSocketAddress of the hub this VirtualSocketFactory is * connected to. * @return the DirectSocketAddress of the hub this VirtualSocketFactory is * connected to. */ public DirectSocketAddress getLocalHub() { return hubAddress; } /** * Provide a list of hub addresses to the VirtualSocketFactory. * @param hubs The hub addresses. */ public void addHubs(DirectSocketAddress... hubs) { if (hub != null) { hub.addHubs(hubs); } else if (serviceLink != null) { serviceLink.addHubs(hubs); } } /** * Provide a list of hub addresses to the VirtualSocketFactory. * @param hubs The hub addresses. */ public void addHubs(String... hubs) { if (hub != null) { hub.addHubs(hubs); } else if (serviceLink != null) { serviceLink.addHubs(hubs); } } /** * Retrieve the known hub addresses. * @return an array containing the known hub addresses. */ public DirectSocketAddress[] getKnownHubs() { if (hub != null) { return hub.knownHubs(); } else if (serviceLink != null) { try { return serviceLink.hubs(); } catch (IOException e) { logger.info("Failed to retrieve hub list!", e); } } return null; } /** * Shutdown the VirtualSocketFactory. */ public void end() { if (printer != null) { printer.adjustInterval(-1); } if (printStatistics) { printStatistics(statisticPrefix + " [EXIT]"); } if (serviceLink != null) { serviceLink.setDone(); } if (hub != null) { hub.end(); } } /** * Close a port. * @param port the port to close. */ protected void closed(int port) { synchronized (serverSockets) { serverSockets.remove(Integer.valueOf(port)); } } /** * Retrieve a previously created (and configured) VirtualSocketFactory. * * @param name the VirtualSocketFactory to retrieve. * @return the VirtualSocketFactory, or null if it does not exist. */ public static synchronized VirtualSocketFactory getSocketFactory( String name) { return factories.get(name); } /** * Get a VirtualSocketFactory, either by retrieving or by creating it. * * If the VirtualSocketFactory already existed, the provided properties will * be compared to those of the existing VirtualSocketFactory to ensure that * they are the same. If they are not, an InitializationException will be * thrown. * <p> * If the VirtualSocketFactory did not exist, it will be created and stored * under name for later lookup. * * @param name the name of the VirtualSocketFactory to retrieve or create. * @param p A set of properties that configure the VirtualSocketFactory. * @param addDefaults Add the default properties to the configuration. * @return the retrieved or created VirtualSocketFactory. * @throws InitializationException if the VirtualSocketFactory could not be * created or received. */ public static synchronized VirtualSocketFactory getOrCreateSocketFactory( String name, java.util.Properties p, boolean addDefaults) throws InitializationException { VirtualSocketFactory result = factories.get(name); if (result == null) { result = createSocketFactory(p, addDefaults); factories.put(name, result); } else { TypedProperties typedProperties = new TypedProperties(); if (addDefaults) { typedProperties.putAll(SmartSocketsProperties .getDefaultProperties()); } if (p != null) { typedProperties.putAll(p); } if (!typedProperties.equals(result.properties)) { throw new InitializationException("could not retrieve existing" + " factory, properties are not equal"); } } return result; } /** * Register an existing VirtualSocketFactory under a different name. * @param name The name to register the VirtualSocketFactory. * @param factory The VirtualSocketFactory to register. */ public static synchronized void registerSocketFactory(String name, VirtualSocketFactory factory) { factories.put(name, factory); } /** * Retrieve a VirtualSocketFactory using the default configuration. * * @return a VirtualSocketFactory using the default configuration. * @throws InitializationException the VirtualSocketFactory could not be * retrieved. */ public static synchronized VirtualSocketFactory getDefaultSocketFactory() throws InitializationException { if (defaultFactory == null) { defaultFactory = createSocketFactory(); } return defaultFactory; } /** * Create a VirtualSocketFactory using the default configuration. * * @return a VirtualSocketFactory using the default configuration. * @throws InitializationException the VirtualSocketFactory could not be * created. */ public static VirtualSocketFactory createSocketFactory() throws InitializationException { return createSocketFactory((java.util.Properties) null, true); } /** * Create a VirtualSocketFactory using the configuration provided in p. * * @param p the configuration to use (as a key-value map). * @param addDefaults Should the default configuration be added ? * @return a VirtualSocketFactory using the configuration in p. * @throws InitializationException the VirtualSocketFactory could not be * created. */ public static VirtualSocketFactory createSocketFactory(Map<String, ?> p, boolean addDefaults) throws InitializationException { return createSocketFactory(new TypedProperties(p), addDefaults); } /** * Create a VirtualSocketFactory using the configuration provided in * properties. * * @param properties the configuration to use. * @param addDefaults Should the default configuration be added ? * @return a VirtualSocketFactory using the configuration in properties. * @throws InitializationException the VirtualSocketFactory could not be * created. */ public static VirtualSocketFactory createSocketFactory( java.util.Properties properties, boolean addDefaults) throws InitializationException { TypedProperties typedProperties = new TypedProperties(); if (addDefaults) { typedProperties.putAll(SmartSocketsProperties .getDefaultProperties()); } if (properties != null) { typedProperties.putAll(properties); } if (typedProperties.booleanProperty(SmartSocketsProperties.START_HUB, false)) { boolean allowSSHForHub = typedProperties.booleanProperty( SmartSocketsProperties.HUB_SSH_ALLOWED, true); if (allowSSHForHub) { typedProperties.setProperty(SmartSocketsProperties.SSH_IN, "true"); // Do we need this one ? // typedProperties.setProperty(SmartSocketsProperties.SSH_OUT, // "true"); } } VirtualSocketFactory factory = new VirtualSocketFactory( DirectSocketFactory.getSocketFactory(typedProperties), typedProperties); return factory; } /** * Retrieve the contact address of this VirtualSocketFactory. * * @return a VirtualSocketAddress containing the contact address of this * VirtualSocketFactory. */ public VirtualSocketAddress getLocalVirtual() { return localVirtualAddress; } /** * Retrieve the contact address of this VirtualSocketFactory. * * @return a String containing the contact address of this * VirtualSocketFactory. */ public String getVirtualAddressAsString() { return localVirtualAddressAsString; } public void printStatistics(String prefix) { if (statslogger.isInfoEnabled()) { statslogger.info(prefix + " === VirtualSocketFactory (" + modules.size() + " / " + (serviceLink == null ? "No SL" : "SL") + ") ==="); for (ConnectModule c : modules) { c.printStatistics(prefix); } if (serviceLink != null) { serviceLink.printStatistics(prefix); } } } }
package info.tregmine.listeners; import java.sql.Connection; import java.sql.SQLException; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.entity.Item; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerLoginEvent.Result; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Score; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.ScoreboardManager; import info.tregmine.Tregmine; import info.tregmine.api.PlayerReport; import info.tregmine.api.TregminePlayer; import info.tregmine.api.lore.Created; import info.tregmine.api.util.ScoreboardClearTask; import info.tregmine.database.ConnectionPool; import info.tregmine.database.DBInventoryDAO; import info.tregmine.database.DBLogDAO; import info.tregmine.database.DBPlayerDAO; import info.tregmine.database.DBPlayerReportDAO; import info.tregmine.database.DBWalletDAO; import static info.tregmine.database.DBInventoryDAO.InventoryType; public class TregminePlayerListener implements Listener { private static class RankComparator implements Comparator<TregminePlayer> { private int order; public RankComparator() { this.order = 1; } public RankComparator(boolean reverseOrder) { this.order = reverseOrder ? -1 : 1; } @Override public int compare(TregminePlayer a, TregminePlayer b) { return order * (a.getGuardianRank() - b.getGuardianRank()); } } private final static String[] quitMessages = new String[] { ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " deserted from the battlefield with a hearty good bye!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " stole the cookies and ran!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was eaten by a teenage mutant ninja platypus!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " parachuted of the plane and into the unknown!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " stole the cookies and ran!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was eaten by a teenage mutant ninja creeper!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " jumped off the plane with a cobble stone parachute!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " built Rome in one day and now deserves a break!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " will come back soon because Tregmine is awesome!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " leaves the light and enter darkness.", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " disconnects from a better life.", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " already miss the best friends in the world!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " will build something epic next time.", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " is not banned yet!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " has left our world!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " went to browse Tregmine's forums instead!", ChatColor.DARK_GRAY + "Quit - %s" + "'s" + ChatColor.DARK_GRAY + " CPU was killed by the Rendermen!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " logged out on accident!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found the IRL warp!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " left the game due to IRL chunk error issues!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " left the Matrix. Say hi to Morpheus!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " disconnected? What is this!? Impossibru!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " Be sure to visit the rifton general store! Follow the red line at /warp rifton", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " Come to Exon (Near sunspot)", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " his/her mom called.", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " toliet brb", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found a lose cable and ate it.", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found the true END of minecraft.", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " sorry was that the kick button?", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was not accidently banned by " + ChatColor.DARK_RED + "BlackX", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found love elswhere", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " rage quit this server", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " Tregmine will miss you a LOT, I hope your away time is almost as pleasant as being here", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " NOOOOOO What did i do?", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " Voz just got an eargasm (or is it a eyegasm)", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " maybe I won't be back tomorrow." }; private Tregmine plugin; private Map<Item, TregminePlayer> droppedItems; public TregminePlayerListener(Tregmine instance) { this.plugin = instance; droppedItems = new HashMap<Item, TregminePlayer>(); } @EventHandler public void onPlayerItemHeld(InventoryCloseEvent event) { Player player = (Player) event.getPlayer(); if (player.getGameMode() == GameMode.CREATIVE) { for (ItemStack item : player.getInventory().getContents()) { if (item != null) { ItemMeta meta = item.getItemMeta(); List<String> lore = new ArrayList<String>(); lore.add(Created.CREATIVE.toColorString()); TregminePlayer p = this.plugin.getPlayer(player); lore.add(ChatColor.WHITE + "by: " + p.getChatName()); lore.add(ChatColor.WHITE + "Value: " + ChatColor.MAGIC + "0000" + ChatColor.RESET + ChatColor.WHITE + " Treg"); meta.setLore(lore); item.setItemMeta(meta); } } } } @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { Player player = event.getPlayer(); Block block = event.getClickedBlock(); Location loc = block.getLocation(); if (player.getItemInHand().getType() == Material.BOOK) { player.sendMessage(ChatColor.DARK_AQUA + "Type: " + ChatColor.AQUA + block.getType().toString() + " (" + ChatColor.BLUE + block.getType().getId() + ChatColor.DARK_AQUA + ")"); player.sendMessage(ChatColor.DARK_AQUA + "Data: " + ChatColor.AQUA + (int) block.getData()); player.sendMessage(ChatColor.RED + "X" + ChatColor.WHITE + ", " + ChatColor.GREEN + "Y" + ChatColor.WHITE + ", " + ChatColor.BLUE + "Z" + ChatColor.WHITE + ": " + ChatColor.RED + loc.getBlockX() + ChatColor.WHITE + ", " + ChatColor.GREEN + loc.getBlockY() + ChatColor.WHITE + ", " + ChatColor.BLUE + loc.getBlockZ()); try { player.sendMessage(ChatColor.DARK_AQUA + "Biome: " + ChatColor.AQUA + block.getBiome().toString()); } catch (Exception e) { player.sendMessage(ChatColor.DARK_AQUA + "Biome: " + ChatColor.AQUA + "NULL"); } Tregmine.LOGGER.info("POS: " + loc.getBlockX() + ", " + loc.getBlockY() + ", " + loc.getBlockZ()); } } } @EventHandler public void onPreCommand(PlayerCommandPreprocessEvent event) { // Tregmine.LOGGER.info("COMMAND: " + event.getPlayer().getName() + "::" // + event.getMessage()); } @EventHandler public void onPlayerLogin(PlayerLoginEvent event) { TregminePlayer player = null; Connection conn = null; try { conn = ConnectionPool.getConnection(); DBPlayerDAO playerDAO = new DBPlayerDAO(conn); player = playerDAO.getPlayer(event.getPlayer()); if (player == null) { player = playerDAO.createPlayer(event.getPlayer()); } DBPlayerReportDAO reportDAO = new DBPlayerReportDAO(conn); List<PlayerReport> reports = reportDAO.getReportsBySubject(player); for (PlayerReport report : reports) { Date validUntil = report.getValidUntil(); if (validUntil == null) { continue; } if (validUntil.getTime() < System.currentTimeMillis()) { continue; } if (report.getAction() == PlayerReport.Action.SOFTWARN) { player.setTempColor("warned"); } else if (report.getAction() == PlayerReport.Action.HARDWARN) { player.setTempColor("warned"); player.setTrusted(false); } else if (report.getAction() == PlayerReport.Action.BAN) { event.disallow(Result.KICK_BANNED, report.getMessage()); return; } } DBLogDAO logDAO = new DBLogDAO(conn); logDAO.insertLogin(player, false); player.setTemporaryChatName(player.getNameColor() + player.getName()); this.plugin.addPlayer(player); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } if (player.getLocation().getWorld().getName().matches("world_the_end")) { player.teleport(this.plugin.getServer().getWorld("world") .getSpawnLocation()); } if (player.getKeyword() != null) { String keyword = player.getKeyword() + ".mc.tregmine.info:25565".toLowerCase(); Tregmine.LOGGER.warning("host: " + event.getHostname()); Tregmine.LOGGER.warning("keyword:" + keyword); if (keyword.equals(event.getHostname().toLowerCase()) || keyword.matches("mc.tregmine.info")) { Tregmine.LOGGER.warning(player.getName() + " keyword :: success"); } else { Tregmine.LOGGER.warning(player.getName() + " keyword :: faild"); event.disallow(Result.KICK_BANNED, "Wrong keyword!"); } } else { Tregmine.LOGGER.warning(player.getName() + " keyword :: notset"); } if (player.isGuardian()) { player.setGuardianState(TregminePlayer.GuardianState.QUEUED); } } @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { event.setJoinMessage(null); TregminePlayer player = plugin.getPlayer(event.getPlayer()); if (player == null) { event.getPlayer().kickPlayer("error loading profile!"); } // Handle invisibility, if set List<TregminePlayer> players = plugin.getOnlinePlayers(); if (player.isInvisible()) { player.sendMessage(ChatColor.YELLOW + "You are now invisible!"); // Hide the new player from all existing players for (TregminePlayer current : players) { if (!current.isOp()) { current.hidePlayer(player); } else { current.showPlayer(player); } } } else { for (Player current : players) { current.showPlayer(player); } } // Hide currently invisible players from the player that just signed on for (TregminePlayer current : players) { if (current.isInvisible()) { player.hidePlayer(current); } else { player.showPlayer(current); } if (player.isOp()) { player.showPlayer(current); } } // Check if the player is allowed to fly if (player.isDonator() || player.isAdmin() || player.isGuardian() || player.isBuilder()) { player.sendMessage("You are allowed to fly"); player.setAllowFlight(true); } else { player.sendMessage("no-z-cheat"); player.sendMessage("You are NOT allowed to fly"); player.setAllowFlight(false); } // Set applicable game mode if (player.isBuilder()) { player.setGameMode(GameMode.CREATIVE); } else if (!player.isOp()) { player.setGameMode(GameMode.SURVIVAL); } // Load inventory from DB - disabled until we know it's reliable Connection conn = null; /*try { conn = ConnectionPool.getConnection(); PlayerInventory inv = (PlayerInventory) player.getInventory(); DBInventoryDAO invDAO = new DBInventoryDAO(conn); int invId = invDAO.getInventoryId(player.getId(), InventoryType.PLAYER); if (invId != -1) { Tregmine.LOGGER.info("Loaded inventory from DB"); inv.setContents(invDAO.getStacks(invId, inv.getSize())); } int armorId = invDAO.getInventoryId(player.getId(), InventoryType.PLAYER_ARMOR); if (armorId != -1) { Tregmine.LOGGER.info("Loaded armor from DB"); inv.setArmorContents(invDAO.getStacks(armorId, 4)); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { } } }*/ // Show a score board if (player.isOnline()) { ScoreboardManager manager = Bukkit.getScoreboardManager(); Scoreboard board = manager.getNewScoreboard(); Objective objective = board.registerNewObjective("1", "2"); objective.setDisplaySlot(DisplaySlot.SIDEBAR); objective.setDisplayName("" + ChatColor.DARK_RED + "" + ChatColor.BOLD + "Welcome to Tregmine!"); try { conn = ConnectionPool.getConnection(); DBWalletDAO walletDAO = new DBWalletDAO(conn); // Get a fake offline player Score score = objective.getScore(Bukkit .getOfflinePlayer(ChatColor.BLACK + "Your Balance:")); score.setScore((int) walletDAO.balance(player)); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } player.setScoreboard(board); ScoreboardClearTask.start(plugin, player); } // Recalculate guardians activateGuardians(); } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { TregminePlayer player = plugin.getPlayer(event.getPlayer()); event.setQuitMessage(null); Connection conn = null; try { conn = ConnectionPool.getConnection(); DBLogDAO logDAO = new DBLogDAO(conn); logDAO.insertLogin(player, true); PlayerInventory inv = (PlayerInventory) player.getInventory(); // Insert regular inventory DBInventoryDAO invDAO = new DBInventoryDAO(conn); int invId = invDAO.getInventoryId(player.getId(), InventoryType.PLAYER); if (invId == -1) { invId = invDAO.insertInventory(player, null, InventoryType.PLAYER); } invDAO.insertStacks(invId, inv.getContents()); // Insert armor inventory int armorId = invDAO.getInventoryId(player.getId(), InventoryType.PLAYER_ARMOR); if (armorId == -1) { armorId = invDAO.insertInventory(player, null, InventoryType.PLAYER_ARMOR); } invDAO.insertStacks(armorId, inv.getArmorContents()); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } if (!player.isOp()) { String message = null; if (player.getQuitMessage() != null) { message = player.getChatName() + " quit: " + ChatColor.YELLOW + player.getQuitMessage(); } else { Random rand = new Random(); int msgIndex = rand.nextInt(quitMessages.length); message = String.format(quitMessages[msgIndex], player.getChatName()); } plugin.getServer().broadcastMessage(message); } plugin.removePlayer(player); Tregmine.LOGGER.info("Unloaded settings for " + player.getName() + "."); activateGuardians(); } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { TregminePlayer player = this.plugin.getPlayer(event.getPlayer()); if (player == null) { event.getPlayer().kickPlayer("error loading profile!"); } } @EventHandler public void onPlayerPickupItem(PlayerPickupItemEvent event) { TregminePlayer player = this.plugin.getPlayer(event.getPlayer()); if (player.getGameMode() == GameMode.CREATIVE) { event.setCancelled(true); return; } if (player.isAdmin()) { return; } if (!player.isTrusted()) { event.setCancelled(true); return; } Connection conn = null; try { conn = ConnectionPool.getConnection(); Item item = event.getItem(); TregminePlayer droppedBy = droppedItems.get(item); if (droppedBy != null && droppedBy.getId() != player.getId()) { ItemStack stack = item.getItemStack(); DBLogDAO logDAO = new DBLogDAO(conn); logDAO.insertGiveLog(droppedBy, player, stack); player.sendMessage(ChatColor.YELLOW + "You got " + stack.getAmount() + " " + stack.getType() + " from " + droppedBy.getName() + "."); if (droppedBy.isOnline()) { droppedBy.sendMessage(ChatColor.YELLOW + "You gave " + stack.getAmount() + " " + stack.getType() + " to " + player.getName() + "."); } } droppedItems.remove(item); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } } @EventHandler public void onPlayerDropItem(PlayerDropItemEvent event) { TregminePlayer player = this.plugin.getPlayer(event.getPlayer()); if (player.getGameMode() == GameMode.CREATIVE) { event.setCancelled(true); return; } if (player.isAdmin()) { return; } if (!player.isTrusted()) { event.setCancelled(true); return; } Item item = event.getItemDrop(); droppedItems.put(item, player); } @EventHandler public void onPlayerKick(PlayerKickEvent event) { event.setLeaveMessage(null); } private void activateGuardians() { // Identify all guardians and categorize them based on their current // state Player[] players = plugin.getServer().getOnlinePlayers(); Set<TregminePlayer> guardians = new HashSet<TregminePlayer>(); List<TregminePlayer> activeGuardians = new ArrayList<TregminePlayer>(); List<TregminePlayer> inactiveGuardians = new ArrayList<TregminePlayer>(); List<TregminePlayer> queuedGuardians = new ArrayList<TregminePlayer>(); for (Player srvPlayer : players) { TregminePlayer guardian = plugin.getPlayer(srvPlayer.getName()); if (guardian == null || !guardian.isGuardian()) { continue; } TregminePlayer.GuardianState state = guardian.getGuardianState(); if (state == null) { state = TregminePlayer.GuardianState.QUEUED; } switch (state) { case ACTIVE: activeGuardians.add(guardian); break; case INACTIVE: inactiveGuardians.add(guardian); break; case QUEUED: queuedGuardians.add(guardian); break; } guardian.setGuardianState(TregminePlayer.GuardianState.QUEUED); guardians.add(guardian); } Collections.sort(activeGuardians, new RankComparator()); Collections.sort(inactiveGuardians, new RankComparator(true)); Collections.sort(queuedGuardians, new RankComparator()); int idealCount = (int) Math.ceil(Math.sqrt(players.length) / 2); // There are not enough guardians active, we need to activate a few more if (activeGuardians.size() <= idealCount) { // Make a pool of every "willing" guardian currently online List<TregminePlayer> activationList = new ArrayList<TregminePlayer>(); activationList.addAll(activeGuardians); activationList.addAll(queuedGuardians); // If the pool isn't large enough to satisfy demand, we add the // guardians // that have made themselves inactive as well. if (activationList.size() < idealCount) { int diff = idealCount - activationList.size(); // If there aren't enough of these to satisfy demand, we add all // of them if (diff >= inactiveGuardians.size()) { activationList.addAll(inactiveGuardians); } // Otherwise we just add the lowest ranked of the inactive else { activationList.addAll(inactiveGuardians.subList(0, diff)); } } // If there are more than necessarry guardians online, only activate // the most highly ranked. Set<TregminePlayer> activationSet; if (activationList.size() > idealCount) { Collections.sort(activationList, new RankComparator()); activationSet = new HashSet<TregminePlayer>(activationList.subList(0, idealCount)); } else { activationSet = new HashSet<TregminePlayer>(activationList); } // Perform activation StringBuffer globalMessage = new StringBuffer(); String delim = ""; for (TregminePlayer guardian : activationSet) { guardian.setGuardianState(TregminePlayer.GuardianState.ACTIVE); globalMessage.append(delim); globalMessage.append(guardian.getName()); delim = ", "; } Set<TregminePlayer> oldActiveGuardians = new HashSet<TregminePlayer>(activeGuardians); if (!activationSet.containsAll(oldActiveGuardians) || activationSet.size() != oldActiveGuardians.size()) { plugin.getServer() .broadcastMessage( ChatColor.BLUE + "Active guardians are: " + globalMessage + ". Please contact any of them if you need help."); // Notify previously active guardian of their state change for (TregminePlayer guardian : activeGuardians) { if (!activationSet.contains(guardian)) { guardian.sendMessage(ChatColor.BLUE + "You are no longer on active duty, and should not respond to help requests, unless asked by an admin or active guardian."); } } // Notify previously inactive guardians of their state change for (TregminePlayer guardian : inactiveGuardians) { if (activationSet.contains(guardian)) { guardian.sendMessage(ChatColor.BLUE + "You have been restored to active duty and should respond to help requests."); } } // Notify previously queued guardians of their state change for (TregminePlayer guardian : queuedGuardians) { if (activationSet.contains(guardian)) { guardian.sendMessage(ChatColor.BLUE + "You are now on active duty and should respond to help requests."); } } } } } }
package it.unitn.disi.smatch.filters; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.apache.log4j.Level; import org.apache.log4j.Logger; import it.unitn.disi.smatch.data.trees.IContext; import it.unitn.disi.smatch.data.trees.INode; import it.unitn.disi.smatch.data.mappings.HashMapping; import it.unitn.disi.smatch.data.mappings.IContextMapping; import it.unitn.disi.smatch.data.mappings.IMappingElement; import it.unitn.disi.smatch.data.mappings.MappingElement; import it.unitn.disi.smatch.matchers.structure.tree.spsm.SPSMTreeMatcher; import it.unitn.disi.smatch.matchers.structure.tree.spsm.ted.TreeEditDistance; import it.unitn.disi.smatch.matchers.structure.tree.spsm.ted.data.ITreeAccessor; import it.unitn.disi.smatch.matchers.structure.tree.spsm.ted.data.impl.CTXMLTreeAccessor; import it.unitn.disi.smatch.matchers.structure.tree.spsm.ted.utils.impl.InvalidElementException; import it.unitn.disi.smatch.matchers.structure.tree.spsm.ted.utils.impl.MatchedTreeNodeComparator; import it.unitn.disi.smatch.matchers.structure.tree.spsm.ted.utils.impl.WorstCaseDistanceConversion; /** * Class used for reordering the siblings in a tree based on the * relations returned by the matching component. It is also used for * filtering the relations in order to * return 1 to 1 correspondences for the data translation. this is done in the same class for the * purpose of efficiency * * @author Juan Pane pane@disi.unitn.it */ public class SPSMMappingFilter extends BaseFilter implements IMappingFilter { private IContext sourceContext; private IContext targetContext; //used for reordering of siblings private Vector<Integer> sourceIndex; private Vector<Integer> targetIndex; // private Vector<IMappingElement> mappings; /** * the original mappings */ private int numberofOriginalMappings; // private IContextMapping<INode> mappings; //Class used to verify the relations between nodes, and build the QA mechanism // private SPSMMappingFilter spsmFilter; //CNode matrix (matrix of relations between nodes of the ontologies) rebuild from the mappings vector private IMappingElement<INode>[][] cNodeMatrix; //vector with all the source nodes, used for fast searching of the index in the matrix private List<INode> sourceVector; //vector with all the target nodes, used for fast searching of the index in the matrix private List<INode> targetVector; //number of rows private int sourceSize; //number of columns private int targetSize; //Data translation vector // private IMappingElement<INode> filteredMapppings[]; private IContextMapping<INode> spsmMappings; // private Hashtable<String,Integer> orderOfSiblingsInSource; // private Hashtable<String,Integer> orderOfSiblingsInTarget; // IContextMapping<INode> mappings2; private static final Logger log = Logger.getLogger(SPSMMappingFilter.class); /** Contains the original mappings from which it will be computed the * similarity score and then the filtering will take place **/ private IContextMapping<INode> originalMappings; /** * Constructor of the class for * @param source Source Context * @param target Target Context * @param mapp Mapping or semantic relations among the nodes in source and target */ @SuppressWarnings("unchecked") private void init(IContextMapping<INode> mappings){ sourceContext = mappings.getSourceContext(); targetContext = mappings.getTargetContext(); sourceIndex = new Vector<Integer>(); targetIndex = new Vector<Integer>(); // mappings = (Vector<IMappingElement>) mapp.getMapping().clone(); // this.mappings = mapp; // spsmFilter = new SPSMMappingFilter( sourceContext,targetContext,mappings ); sourceVector = mappings.getSourceContext().getNodesList(); targetVector = mappings.getTargetContext().getNodesList(); sourceSize = sourceVector.size(); targetSize = targetVector.size(); cNodeMatrix = new MappingElement[sourceSize][targetSize];//new NodesMatrixMapping(new MatchMatrix(), source, target); // filteredMapppings = new MappingElement[sourceSize]; spsmMappings = new HashMapping<INode>(mappings.getSourceContext(), mappings.getTargetContext()); Iterator<IMappingElement<INode>> mappingIt = mappings.iterator(); while(mappingIt.hasNext()){ IMappingElement<INode> mapping = mappingIt.next(); INode s = mapping.getSource(); INode t = mapping.getTarget(); int sourceIndex = sourceVector.indexOf(s); int targetIndex = targetVector.indexOf(t); cNodeMatrix[sourceIndex][targetIndex] = mapping; } numberofOriginalMappings = mappings.size(); originalMappings = mappings; } /** * Sorts the siblings in the source and target tree defined in the constructor using * the given mapping */ @Override public IContextMapping<INode> filter(IContextMapping<INode> mapping) throws MappingFilterException { //initialize the local variables init(mapping); computeSimilarity(); //add the first mapping element for the root to the mappings result if (numberofOriginalMappings > 0){ if ( isRelated(sourceContext.getRoot(), targetContext.getRoot(), IMappingElement.EQUIVALENCE) || isRelated(sourceContext.getRoot(), targetContext.getRoot(), IMappingElement.LESS_GENERAL) || isRelated(sourceContext.getRoot(), targetContext.getRoot(), IMappingElement.MORE_GENERAL)){ setStrongestMapping(sourceContext.getRoot(), targetContext.getRoot()); filterMappingsOfChildren(sourceContext.getRoot(), targetContext.getRoot(),IMappingElement.EQUIVALENCE); filterMappingsOfChildren(sourceContext.getRoot(), targetContext.getRoot(),IMappingElement.MORE_GENERAL); filterMappingsOfChildren(sourceContext.getRoot(), targetContext.getRoot(),IMappingElement.LESS_GENERAL); } } else{ log.info("No mappings were produced by the Default Tree Matcher"); spsmMappings = originalMappings; } return spsmMappings; } private void computeSimilarity() { TreeEditDistance tde = null; try { ITreeAccessor source = new CTXMLTreeAccessor(sourceContext); ITreeAccessor target = new CTXMLTreeAccessor(targetContext); MatchedTreeNodeComparator mntc = new MatchedTreeNodeComparator(originalMappings); tde = new TreeEditDistance(source, target, mntc, new WorstCaseDistanceConversion()); } catch (InvalidElementException e) { log.info("Problems in the Tree edit distance computation:" +e.getMessage()); if (log.getEffectiveLevel() == Level.TRACE) log.trace(SPSMTreeMatcher.class.getName(), e); } tde.calculate(); double ed = tde.getTreeEditDistance(); double sim=1-(ed/Math.max(sourceSize,targetSize)); spsmMappings.setSimilarity(sim); } /** * Sorts the children of the given nodes. * @param sourceParent Source node * @param targetParent Target node * @param semantic_relation the relation to use for comparison */ private void filterMappingsOfChildren(INode sourceParent, INode targetParent, char semantic_relation){ List<INode> source = convertToModifiableList(sourceParent.getChildrenList()); List<INode> target = convertToModifiableList(targetParent.getChildrenList()); sourceIndex.add(getNodeDepth(sourceParent), 0); targetIndex.add(getNodeDepth(targetParent), 0); if (source.size() >= 1 && target.size() >= 1){ //sorts the siblings first with the strongest relation, and then with the others filterMappingsOfSibligsbyRelation(source,target,semantic_relation); } sourceIndex.remove(getNodeDepth(sourceParent)); targetIndex.remove(getNodeDepth(targetParent)); } /** * converts the unmodifiable list of children to a modifiable list of children * needed when reordering the children * @param unmodifiable * @return */ private List<INode> convertToModifiableList(List<INode> unmodifiable){ List<INode> modifiable = new ArrayList<INode>(); for(int i =0; i<unmodifiable.size(); i++){ modifiable.add(unmodifiable.get(i)); } return modifiable; } /** * Filters the mappings of two siblings node list for which the parents are also supposed to * be related. Checks whether in the two given node list there is a pair of nodes related * by the given relation and if so, if deletes all the other relations for the given 2 * nodes setting the current one as strongest. * * @param source Source vector of siblings * @param target Target vector of siblings * @param semantic_relation Defined relation in edu.unitn.dit.smatch.MatchManager */ private void filterMappingsOfSibligsbyRelation(List<INode> source, List<INode> target, char semantic_relation){ int sourceDepth = (getNodeDepth(source.get(0)) - 1); int targetDepth = (getNodeDepth(target.get(0)) - 1); int sourceSize=source.size(); int targetSize=target.size(); while(sourceIndex.get(sourceDepth) < sourceSize && targetIndex.get(targetDepth) < targetSize) { if( isRelated(source.get(sourceIndex.get(sourceDepth)), target.get(targetIndex.get(targetDepth)), semantic_relation) ){ //sort the children of the matched node setStrongestMapping(source.get(sourceIndex.get(sourceDepth)), target.get(targetIndex.get(targetDepth))); filterMappingsOfChildren(source.get(sourceIndex.get(sourceDepth)), target.get(targetIndex.get(targetDepth)), semantic_relation ); //increment the index inc(sourceIndex,sourceDepth); inc(targetIndex,targetDepth); } else { //look for the next related node in the target int relatedIndex = getRelatedIndex(source, target, semantic_relation); if (relatedIndex > sourceIndex.get(sourceDepth)) { //there is a related node, but further between the siblings //they should be swapped swapINodes(target,targetIndex.get(targetDepth),relatedIndex); //filter the mappings of the children of the matched node filterMappingsOfChildren(source.get(sourceIndex.get(sourceDepth)), target.get(targetIndex.get(targetDepth)),semantic_relation ); //increment the index inc(sourceIndex,sourceDepth); inc(targetIndex,targetDepth); } else { //there is not related item among the remaining siblings //swap this element of source with the last, and decrement the sourceSize swapINodes(source,sourceIndex.get(sourceDepth),(sourceSize-1)); sourceSize } } } } /** * Swaps the INodes in vect in the positions source and target * @param listOfNodes List of INodes of which the elements should be swapped * @param source index of the source element to be swapped * @param target index of the target element to be swapped */ private void swapINodes(List<INode> listOfNodes, int source, int target){ INode aux = null; aux = listOfNodes.get(source); listOfNodes.set(source,listOfNodes.get(target)); listOfNodes.set(target, aux); } /** * Looks for the related index for the source vector at the position sourceIndex * in the target vector beginning at the targetIndex position for the defined relation * @param source source vector of siblings * @param target target vector of siblings * @param semantic_relation Defined relation in edu.unitn.dit.smatch.MatchManager * @return the index of the related element in target, or -1 if there is no relate element */ private int getRelatedIndex(List<INode> source, List<INode> target, char semantic_relation){ int srcIndex = sourceIndex.get(getNodeDepth(source.get(0)) - 1); int tgtIndex = targetIndex.get(getNodeDepth(target.get(0)) - 1); int returnIndex = -1; INode sourceNode = source.get(srcIndex); //find the first one who is related in the same level for (int i = tgtIndex+1; i < target.size(); i++){ INode targetNode = target.get(i); if ( isRelated(sourceNode, targetNode, semantic_relation) ){ setStrongestMapping(sourceNode, targetNode); return i; } } //there was no correspondence between siblings in source and target vectors //try to clean the mapping elements computeStrongestMappingForSource(source.get(srcIndex)); return returnIndex; } /** * Returns the depth of a node in a given tree, the root have a depth of 0 * @param node node from which we want to compute the depth * @return depth of the given node in the tree */ private int getNodeDepth(INode node){ return node.getAncestorsList().size(); } /** * Increments by 1 the Integer of the given vector of integers at the index position * @param vec vector of integers * @param index index of the element to be incremented */ private void inc(Vector<Integer> vec, int index){ vec.set(index,vec.get(index)+1); } /** * Checks if the given source and target elements are related considering the * defined relation and the cNodeMatrix, is the relation is held, then it is set * as the strongest relation for the source and target * @param source Source element * @param target Target element * @param relation Defined relation SEMANTIC_RELATION * @return true if the relation holds between source and target, false otherwise */ private boolean isRelated(INode source, INode target,char semantic_relation){ boolean related = false; IMappingElement<INode> mapping = findMappingElement(source, target, semantic_relation); if ( mapping != null ){ related = true; } return related; } /** * Finds the mapping element in the CNodeMatrix for the given source, target and semantic relation * * @param source source node * @param target target node * @param semantic_relation relation holding between the source and target * @return Mapping between source and target for the given relation, null is there is none */ private IMappingElement<INode> findMappingElement(INode source, INode target, char semantic_relation){ IMappingElement<INode> me = null; int sourceIndex = -1; int targetIndex = -1; sourceIndex = sourceVector.indexOf(source); targetIndex = targetVector.indexOf(target); if ( sourceIndex >= 0 && targetIndex >= 0 ){ if ( cNodeMatrix[sourceIndex][targetIndex] != null && cNodeMatrix[sourceIndex][targetIndex].getRelation() == semantic_relation){ me = cNodeMatrix[sourceIndex][targetIndex]; } } return me; } /** * Set the strongest mapping element for the data translation * for the given source and target * @param source source node * @param target target node */ private void setStrongestMapping(INode source, INode target){ int sourceIndex = sourceVector.indexOf(source); int targetIndex = targetVector.indexOf(target); if (sourceIndex >= 0 && targetIndex >= 0){ setStrongestMapping(sourceIndex,targetIndex); } } /** * Set the given column and row as the strongest mapping element for the given * source and target indexes of the cNodeMatrix, setting all the other realtions * for the same row (source) as IDK if the relations are weaker * @param row * @param col */ private void setStrongestMapping(int row, int col){ //if it's structure preserving if (isSameStructure(sourceVector.get(row),targetVector.get(col))){ // spsmMapppings[row] = cNodeMatrix[row][col]; spsmMappings.add( cNodeMatrix[row][col]); //deletes all the less precedent relations in the row //i.e., for the same source node for(int j = 0; j < targetSize; j++){ //if its not the target of the mapping elements and the relation is weaker if(j != col && cNodeMatrix[row][j] != null && cNodeMatrix[row][j].getRelation() != IMappingElement.IDK && morePrecedent(cNodeMatrix[row][col],cNodeMatrix[row][j])){ cNodeMatrix[row][j] = convertToIDK(cNodeMatrix[row][j]); } } //deletes all the relations in the column for(int i = 0; i < sourceSize; i++){ if(i != row && cNodeMatrix[i][col] != null && cNodeMatrix[i][col].getRelation() != IMappingElement.IDK){ cNodeMatrix[i][col] = convertToIDK(cNodeMatrix[i][col]); } } } else { //the elements are not in the same structure, look for the correct relation computeStrongestMappingForSource(sourceVector.get(row)); } } /** * Takes the existing IMappingElement and copies the source and target into a * new instance of IMappingElement with the IDK relation * @param mapping * @return */ private IMappingElement<INode> convertToIDK(IMappingElement<INode> mapping){ return null; } /** * Looks for the strongest relation for the given source and sets to * IDK all the other mappings existing for the same source if they are less * precedent * * @param source INode to look for the strongest relation */ private void computeStrongestMappingForSource(INode source){ int sourceIndex = sourceVector.indexOf(source); int strongetsRelationInTarget = -1; if (sourceIndex >= 0){ List<IMappingElement<INode>> strongest = new ArrayList<IMappingElement<INode>>(); //look for the strongest relation, and deletes all the non structure //preserving relations for(int j = 0; j < targetSize; j++){ if (isSameStructure(source,targetVector.get(j))){ if (strongest.isEmpty() && cNodeMatrix[sourceIndex][j] != null && findStrongerInColumn(source, targetVector.get(j)) == null){ strongetsRelationInTarget = j; strongest.add(cNodeMatrix[sourceIndex][j]); } else if (cNodeMatrix[sourceIndex][j] != null && !strongest.isEmpty()) { int precedence = comparePrecedence(strongest.get(0).getRelation() ,cNodeMatrix[sourceIndex][j].getRelation()); if ( precedence == -1 && findStrongerInColumn(source, targetVector.get(j)) == null){ //if target is more precedent, and there is no other stronger relation for that particular target strongetsRelationInTarget = j; strongest.set(0,cNodeMatrix[sourceIndex][j]); } } } else { //they are not the same structure, function to function, variable to variable //delete the relation cNodeMatrix[sourceIndex][j] = convertToIDK(cNodeMatrix[sourceIndex][j]); } } //if there is a strongest element, and it is different from IDK if ( !strongest.isEmpty() && strongest.get(0).getRelation() != IMappingElement.IDK){// SEMANTIC_RELATION.NOT_RELATED){ //erase all the weaker relations in the row for(int j = 0; j < targetSize; j++){ if (j != strongetsRelationInTarget && cNodeMatrix[sourceIndex][j] != null){ int precedence = comparePrecedence(strongest.get(0).getRelation(),cNodeMatrix[sourceIndex][j].getRelation()); if( precedence == 1){ cNodeMatrix[sourceIndex][j] = convertToIDK(cNodeMatrix[sourceIndex][j]);//.setSemanticRelation( SEMANTIC_RELATION.NOT_RELATED); } else if ( precedence == 0){ if (isSameStructure(source,targetVector.get(j))){ strongest.add(cNodeMatrix[sourceIndex][j]); } } } } //if there is more than one strongest relation if (strongest.size() > 1){ resolveStrongestMappingConflicts(sourceIndex, strongest); } else { //deletes all the relations in the column for(int i = 0; i < sourceSize; i++){ if(i != sourceIndex ){ cNodeMatrix[i][strongetsRelationInTarget] = convertToIDK(cNodeMatrix[i][strongetsRelationInTarget]); } } if(strongest.get(0).getRelation() != IMappingElement.IDK){ spsmMappings.add(strongest.get(0)); // Remove the relations from the same column and row deleteRemainingRelationsFromMatrix(strongest.get(0)); } } } } } /** * Used to resolve conflicts in case there are more than one element with * the strongest relation for a given source node */ private void resolveStrongestMappingConflicts(int sourceNodeIndex, List<IMappingElement<INode>> strongest){ //copy the relations to a string to log it int strongestIndex = -1; String sourceString = sourceVector.get(sourceNodeIndex).getNodeData().getName().trim(); String strongRelations = ""; for(int i = 0; i < strongest.size() ; i++){ strongRelations += strongest.get(i).getTarget().toString()+"|"; } log.info("more tha one strongest relation for "+ sourceString +": |"+strongRelations); //looks the first related node that is equal to the source node for(int i = 0; i < strongest.size() ; i++){ String strongString = strongest.get(i).getTarget().getNodeData().getName().trim(); if (sourceString.equalsIgnoreCase(strongString)){ strongestIndex = i; break; } } //if there was no equal string, then set it to the first one if(strongestIndex == -1) strongestIndex = 0; // spsmMapppings[sourceNodeIndex] = strongest.get(strongestIndex); if(strongest.get(strongestIndex).getRelation() != IMappingElement.IDK){ spsmMappings.add(strongest.get(strongestIndex)); // Remove the relations from the same column and row deleteRemainingRelationsFromMatrix(strongest.get(strongestIndex)); } } /** * When a given mapping element has been chosen as the strongest, * then delete all the other mappings from the cNodeMatrix by * setting the relation to IDK * @param mapping */ private void deleteRemainingRelationsFromMatrix(IMappingElement<INode> mapping){ int sourceIndex = sourceVector.indexOf(mapping.getSource()); int targetIndex = targetVector.indexOf(mapping.getTarget()); //deletes all the relations in the column for(int i = 0; i < sourceSize; i++){ if(i != sourceIndex ){ cNodeMatrix[i][targetIndex] = convertToIDK(cNodeMatrix[i][targetIndex]); } } //deletes all the relations in the row for(int j = 0; j < targetIndex; j++){ if(j != targetIndex ){ cNodeMatrix[sourceIndex][j] = convertToIDK(cNodeMatrix[sourceIndex][j]); } } } /** * Checks if source and target are structural preserving * this is, function to function and argument to argument match * @param source * @param target * @return true if they are the same structure, false otherwise */ private boolean isSameStructure(INode source, INode target){ boolean result = false; if(source != null && target != null){ if(source.getChildrenList() != null && target.getChildrenList() != null){ int sourceChildren = source.getChildrenList().size(); int targetChildren = target.getChildrenList().size(); if (sourceChildren == 0 && targetChildren == 0){ result = true; } else if (sourceChildren > 0 && targetChildren > 0){ result = true; } } else if (source.getChildrenList() == null && target.getChildrenList() == null){ result = true; } } else if (source == null && target == null){ result = true; } return result; } /** * Checks if there is no other stronger relation in the same column * @param source * @param target * @return */ private IMappingElement<INode> findStrongerInColumn(INode source, INode target){ IMappingElement<INode> newStronger = null; if(source != null && target != null){ int sourceIndex = sourceVector.indexOf(source); int targetIndex = targetVector.indexOf(target); IMappingElement<INode> currentStronger = cNodeMatrix[sourceIndex][targetIndex]; //Compares with the other relations in the column for(int i = 0; i < sourceSize; i++){ if(i != sourceIndex && cNodeMatrix[i][targetIndex] != null && morePrecedent(cNodeMatrix[i][targetIndex],currentStronger) ){ newStronger = cNodeMatrix[i][targetIndex]; break; } } } return newStronger; } /** * Checks if the semantic relation of the source is more important, in the order of precedence * than the one in the target, the order of precedence is, = > < ? * @param source source Mapping element * @param target target Mapping element * @return */ private boolean morePrecedent(IMappingElement<INode> source, IMappingElement<INode> target){ return comparePrecedence(source.getRelation(), target.getRelation()) == 1?true: false; } // /** // * Finds all mappings related to the source node represented by the string // * @param sourceStr String representation of the node // * @return a vector with all the mappings corresponding to specified node // */ // private List<IMappingElement<INode>> findRelatedMappings(INode source ){ // List<IMappingElement<INode>> relatedMappings = new ArrayList<IMappingElement<INode>>(); // int sourceIndex = -1; // sourceIndex = sourceVector.indexOf(source); // //first find all mappings related to the source node // for (int j = 0; j < targetSize ; j++){ // relatedMappings.add(cNodeMatrix[sourceIndex][j]); // return relatedMappings; /** * Compares the semantic relation of the source and target in the order of precedence * = > < ! ?. Returning -1 if source_relation is less precedent than target_relation, * 0 if source_relation is equally precedent than target_relation, * 1 if source_relation is more precedent than target_relation * @param source_relation source relation from IMappingElement * @param target_relation target relation from IMappingElement * @return -1 if source_relation is less precedent than target_relation, * 0 if source_relation is equally precedent than target_relation, * 1 if source_relation is more precedent than target_relation */ private int comparePrecedence(char source_relation, char target_relation){ int result = -1; int sourcePrecedence = getPrecedenceNumber(source_relation); int targetPrecedence = getPrecedenceNumber(target_relation); if (sourcePrecedence < targetPrecedence) { result = 1; } else if (sourcePrecedence == targetPrecedence){ result = 0; } else { result = -1; } return result; } /** * Gives the precedence order for the given SEMANTIC_RELATION. * EQUIVALENT_TO = 1 * MORE_GENERAL = 2 * LESS_GENERAL = 3 * DISJOINT_FROM = 4 * IDK = 5 * * @param source source SEMANTIC_RELATION * @return the order of precedence for the given relation, Integer.MAX_VALUE if the relation * is not recognized */ private int getPrecedenceNumber( char relation){ //initializes the precedence number to the least precedent int precedence = Integer.MAX_VALUE; if (relation == IMappingElement.EQUIVALENCE){ precedence = 1; } else if (relation == IMappingElement.MORE_GENERAL){ precedence = 2; } else if (relation == IMappingElement.LESS_GENERAL){ precedence = 3; } else if (relation == IMappingElement.DISJOINT){ precedence = 4; } else if (relation == IMappingElement.IDK){ precedence = 5; } return precedence; } }
// samskivert library - useful routines for java programs // This library is free software; you can redistribute it and/or modify it // (at your option) any later version. // This library is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // You should have received a copy of the GNU Lesser General Public // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.jdbc.depot; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.HashMap; import com.samskivert.jdbc.JDBCUtil; import static com.samskivert.jdbc.depot.Log.log; /** * These can be registered with the {@link PersistenceContext} to effect hand-coded migrations * between entity versions. The modifier should override {@link #invoke} to perform its * migrations. See {@link PersistenceContext#registerPreMigration} and {@link * PersistenceContext#registerPostMigration}. */ public abstract class EntityMigration extends Modifier { /** * A convenient migration for dropping a column from an entity. */ public static class Drop extends EntityMigration { public Drop (int targetVersion, String columnName) { super(targetVersion); _columnName = columnName; } public int invoke (Connection conn) throws SQLException { if (!JDBCUtil.tableContainsColumn(conn, _tableName, _columnName)) { // we'll accept this inconsistency log.warning(_tableName + "." + _columnName + " already dropped."); return 0; } Statement stmt = conn.createStatement(); try { log.info("Dropping '" + _columnName + "' from " + _tableName); return stmt.executeUpdate( "alter table " + _tableName + " drop column " + _columnName); } finally { stmt.close(); } } protected String _columnName; } /** * A convenient migration for renaming a column in an entity. */ public static class Rename extends EntityMigration { public Rename (int targetVersion, String oldColumnName, String newColumnName) { super(targetVersion); _oldColumnName = oldColumnName; _newColumnName = newColumnName; } public int invoke (Connection conn) throws SQLException { if (!JDBCUtil.tableContainsColumn(conn, _tableName, _oldColumnName)) { if (JDBCUtil.tableContainsColumn(conn, _tableName, _newColumnName)) { // we'll accept this inconsistency log.warning(_tableName + "." + _oldColumnName + " already renamed to " + _newColumnName + "."); return 0; } // but this is not OK throw new IllegalArgumentException( _tableName + " does not contain '" + _oldColumnName + "'"); } // nor is this if (JDBCUtil.tableContainsColumn(conn, _tableName, _newColumnName)) { throw new IllegalArgumentException( _tableName + " already contains '" + _newColumnName + "'"); } Statement stmt = conn.createStatement(); try { log.info("Changing '" + _oldColumnName + "' to '" + _newColumnDef + "' in " + _tableName); return stmt.executeUpdate("alter table " + _tableName + " change column " + _oldColumnName + " " + _newColumnDef); } finally { stmt.close(); } } protected void init (String tableName, HashMap<String,FieldMarshaller> marshallers) { super.init(tableName, marshallers); _newColumnDef = marshallers.get(_newColumnName).getColumnDefinition(); } protected String _oldColumnName, _newColumnName, _newColumnDef; } /** * If this method returns true, this migration will be run <b>before</b> the default * migrations, if false it will be run after. */ public boolean runBeforeDefault () { return true; } /** * When an Entity is being migrated, this method will be called to check whether this migration * should be run. The default implementation runs as long as the currentVersion is less than * the target version supplied to the migration at construct time. */ public boolean shouldRunMigration (int currentVersion, int targetVersion) { return (currentVersion < _targetVersion); } protected EntityMigration (int targetVersion) { super(); _targetVersion = targetVersion; } /** * This is called to provide the migration with the name of the entity table and access to its * field marshallers prior to being invoked. This will <em>only</em> be called after this * migration has been determined to be runnable so one cannot rely on this method having been * called in {@link #shouldRunMigration}. */ protected void init (String tableName, HashMap<String,FieldMarshaller> marshallers) { _tableName = tableName; } protected int _targetVersion; protected String _tableName; }
// $Id: DigesterTask.java,v 1.4 2004/08/10 07:23:12 mdb Exp $ package com.threerings.getdown.tools; import java.io.File; import java.io.IOException; import java.util.ArrayList; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import com.threerings.getdown.data.Application; import com.threerings.getdown.data.Digest; /** * An ant task used to create a <code>digest.txt</code> for a Getdown * application deployment. */ public class DigesterTask extends Task { /** * Sets the application directory. */ public void setAppdir (File appdir) { _appdir = appdir; } /** * Performs the actual work of the task. */ public void execute () throws BuildException { // make sure appdir is set if (_appdir == null) { String errmsg = "Must specify the path to the application " + "directory via the 'appdir' attribute."; throw new BuildException(errmsg); } try { createDigest(_appdir); } catch (IOException ioe) { throw new BuildException("Error creating digest: " + ioe.getMessage(), ioe); } } /** * Creates a digest file in the specified application directory. */ public static void createDigest (File appdir) throws IOException { File target = new File(appdir, Digest.DIGEST_FILE); System.out.println("Generating digest file '" + target + "'..."); // create our application and instruct it to parse its business Application app = new Application(appdir); app.init(false); ArrayList rsrcs = new ArrayList(); rsrcs.add(app.getConfigResource()); rsrcs.addAll(app.getCodeResources()); rsrcs.addAll(app.getResources()); // now generate the digest file Digest.createDigest(rsrcs, target); } /** The application directory in which we're creating a digest file. */ protected File _appdir; }
package org.orbeon.oxf.portlet; import org.apache.log4j.Logger; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.pipeline.InitUtils; import org.orbeon.oxf.pipeline.api.ExternalContext; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.pipeline.api.ProcessorDefinition; import org.orbeon.oxf.processor.Processor; import org.orbeon.oxf.util.AttributesToMap; import org.orbeon.oxf.util.NetUtils; import org.orbeon.oxf.webapp.ProcessorService; import javax.portlet.*; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * OPSPortlet and OPSPortletDelegate are the Portlet (JSR-168) entry point of OPS. OPSPortlet simply delegates to * OPSPortletDelegate and provides an option of using the OPS Class Loader. * * Several OPSServlet and OPSPortlet instances can be used in the same Web or Portlet application. * They all share the same Servlet context initialization parameters, but each Portlet can be * configured with its own main processor and inputs. * * All OPSServlet and OPSPortlet instances in a given Web application share the same resource * manager. * * WARNING: OPSPortlet must only depend on the Servlet API and the OPS Class Loader. */ public class OPSPortletDelegate extends GenericPortlet { private static final String INIT_PROCESSOR_PROPERTY_PREFIX = "oxf.portlet-initialized-processor."; private static final String INIT_PROCESSOR_INPUT_PROPERTY = "oxf.portlet-initialized-processor.input."; private static final String DESTROY_PROCESSOR_PROPERTY_PREFIX = "oxf.portlet-destroyed-processor."; private static final String DESTROY_PROCESSOR_INPUT_PROPERTY = "oxf.portlet-destroyed-processor.input."; private static final String LOG_MESSAGE_PREFIX = "Portlet"; private ProcessorService processorService; private static final String OXF_PORTLET_OUTPUT = "org.orbeon.oxf.buffered-response"; private static final String OXF_PORTLET_OUTPUT_PARAMS = "org.orbeon.oxf.buffered-response-params"; // Servlet context initialization parameters set in web.xml private Map contextInitParameters = null; public void init() throws PortletException { // NOTE: Here we assume that an Orbeon Forms WebAppContext context has already // been initialized. This can be done by another Servlet or Filter. The only reason we // cannot use the WebAppContext appears to be that it has to pass the ServletContext to // the resource manager, which uses in turn to read resources from the Web app classloader. // Create context initialization parameters Map PortletContext portletContext = getPortletContext(); contextInitParameters = createServletInitParametersMap(portletContext); // Get main processor definition ProcessorDefinition mainProcessorDefinition; { // Try to obtain a local processor definition mainProcessorDefinition = InitUtils.getDefinitionFromMap(new PortletInitMap(this), ProcessorService.MAIN_PROCESSOR_PROPERTY_PREFIX, ProcessorService.MAIN_PROCESSOR_INPUT_PROPERTY_PREFIX); // Try to obtain a processor definition from the properties if (mainProcessorDefinition == null) mainProcessorDefinition = InitUtils.getDefinitionFromProperties(ProcessorService.MAIN_PROCESSOR_PROPERTY_PREFIX, ProcessorService.MAIN_PROCESSOR_INPUT_PROPERTY_PREFIX); // Try to obtain a processor definition from the context if (mainProcessorDefinition == null) mainProcessorDefinition = InitUtils.getDefinitionFromMap(new PortletContextInitMap(portletContext), ProcessorService.MAIN_PROCESSOR_PROPERTY_PREFIX, ProcessorService.MAIN_PROCESSOR_INPUT_PROPERTY_PREFIX); } // Get error processor definition ProcessorDefinition errorProcessorDefinition; { // Try to obtain a local processor definition errorProcessorDefinition = InitUtils.getDefinitionFromMap(new PortletInitMap(this), ProcessorService.ERROR_PROCESSOR_PROPERTY_PREFIX, ProcessorService.ERROR_PROCESSOR_INPUT_PROPERTY_PREFIX); // Try to obtain a processor definition from the properties if (errorProcessorDefinition == null) errorProcessorDefinition = InitUtils.getDefinitionFromProperties(ProcessorService.ERROR_PROCESSOR_PROPERTY_PREFIX, ProcessorService.ERROR_PROCESSOR_INPUT_PROPERTY_PREFIX); // Try to obtain a processor definition from the context if (errorProcessorDefinition == null) errorProcessorDefinition = InitUtils.getDefinitionFromMap(new PortletContextInitMap(portletContext), ProcessorService.ERROR_PROCESSOR_PROPERTY_PREFIX, ProcessorService.ERROR_PROCESSOR_INPUT_PROPERTY_PREFIX); } try { // Create and initialize service processorService = new ProcessorService(); processorService.init(mainProcessorDefinition, errorProcessorDefinition); } catch (Exception e) { throw new PortletException(OXFException.getRootThrowable(e)); } // Run listeners try { runListenerProcessor(new PortletInitMap(this), new PortletContextInitMap(portletContext), ProcessorService.logger, LOG_MESSAGE_PREFIX, "Portlet initialized.", INIT_PROCESSOR_PROPERTY_PREFIX, INIT_PROCESSOR_INPUT_PROPERTY); } catch (Exception e) { ProcessorService.logger.error(LOG_MESSAGE_PREFIX + " - Exception when running Portlet initialization processor.", OXFException.getRootThrowable(e)); throw new OXFException(e); } } private void runListenerProcessor(Map localMap, Map contextMap, Logger logger, String logMessagePrefix, String message, String uriNamePropertyPrefix, String processorInputProperty) throws Exception { // Log message if provided if (message != null) logger.info(logMessagePrefix + " - " + message); ProcessorDefinition processorDefinition = null; // Try to obtain a local processor definition if (localMap != null) { processorDefinition = InitUtils.getDefinitionFromMap(localMap, uriNamePropertyPrefix, processorInputProperty); } // Try to obtain a processor definition from the properties if (processorDefinition == null) processorDefinition = InitUtils.getDefinitionFromProperties(uriNamePropertyPrefix, processorInputProperty); // Try to obtain a processor definition from the context if (processorDefinition == null) processorDefinition = InitUtils.getDefinitionFromMap(contextMap, uriNamePropertyPrefix, processorInputProperty); // Create and run processor if (processorDefinition != null) { logger.info(logMessagePrefix + " - About to run processor: " + processorDefinition.toString()); final Processor processor = InitUtils.createProcessor(processorDefinition); final ExternalContext externalContext = new PortletContextExternalContext(getPortletContext()); InitUtils.runProcessor(processor, externalContext, new PipelineContext(), logger); } // Otherwise, just don't do anything } public void processAction(ActionRequest actionRequest, ActionResponse response) throws PortletException, IOException { // If we get a request for an action, we run the service without a // response. The result, if any, is stored into a buffer. Otherwise it // must be a redirect. try { // Make sure the previously cached output is cleared, if there is // any. We potentially keep the result of only one action. actionRequest.getPortletSession().removeAttribute(OXF_PORTLET_OUTPUT); actionRequest.getPortletSession().removeAttribute(OXF_PORTLET_OUTPUT_PARAMS); // Call service final PipelineContext pipelineContext = new PipelineContext(); pipelineContext.setAttribute(PipelineContext.PORTLET_CONFIG, getPortletConfig()); final PortletExternalContext externalContext = new PortletExternalContext(processorService, pipelineContext, getPortletContext(), contextInitParameters, actionRequest); processorService.service(true, externalContext, pipelineContext); // Check whether a redirect was issued, or some output was generated PortletExternalContext.BufferedResponse bufferedResponse = (PortletExternalContext.BufferedResponse) externalContext.getResponse(); if (bufferedResponse.isRedirect()) { // A redirect was issued if (bufferedResponse.isRedirectIsExitPortal()) { // Send a portlet response redirect response.sendRedirect(NetUtils.pathInfoParametersToPathInfoQueryString(bufferedResponse.getRedirectPathInfo(), bufferedResponse.getRedirectParameters())); } else { // NOTE: We take the liberty to modify the Map, as nobody will use it anymore Map redirectParameters = bufferedResponse.getRedirectParameters(); if (redirectParameters == null) redirectParameters = new HashMap(); redirectParameters.put(PortletExternalContext.PATH_PARAMETER_NAME, new String[]{bufferedResponse.getRedirectPathInfo()}); // Set the new parameters for the subsequent render requests response.setRenderParameters(redirectParameters); } } else if (bufferedResponse.isContent()) { // Content was written, keep it in the session for subsequent // render requests with the current action parameters. Map actionParameters = actionRequest.getParameterMap(); response.setRenderParameters(actionParameters); PortletSession session = actionRequest.getPortletSession(); session.setAttribute(OXF_PORTLET_OUTPUT, bufferedResponse); session.setAttribute(OXF_PORTLET_OUTPUT_PARAMS, actionParameters); } else { // Nothing happened, throw an exception (or should we just ignore?) throw new IllegalStateException("Processor execution did not return content or issue a redirect."); } } catch (Exception e) { throw new PortletException(OXFException.getRootThrowable(e)); } } public void render(RenderRequest request, RenderResponse response) throws PortletException, IOException { try { PortletExternalContext.BufferedResponse bufferedResponse = (PortletExternalContext.BufferedResponse) request.getPortletSession().getAttribute(OXF_PORTLET_OUTPUT); Map bufferedResponseParameters = (Map) request.getPortletSession().getAttribute(OXF_PORTLET_OUTPUT_PARAMS); // NOTE: Compare for deep equality as it seems that portlet containers may copy/update the parameter Map if (bufferedResponse != null && deepEquals(request.getParameterMap(), bufferedResponseParameters)) { // The result of an action with the current parameters was a // stream that we cached. Replay that stream and replace URLs. // CHECK: what about mode / state? If they change, we ignore them totally. response.setContentType(bufferedResponse.getContentType()); response.setTitle(bufferedResponse.getTitle() != null ? bufferedResponse.getTitle() : getTitle(request)); bufferedResponse.write(response); } else { // Call service PipelineContext pipelineContext = new PipelineContext(); pipelineContext.setAttribute(PipelineContext.PORTLET_CONFIG, getPortletConfig()); ExternalContext externalContext = new PortletExternalContext(processorService, pipelineContext, getPortletContext(), contextInitParameters, request, response); processorService.service(true, externalContext, pipelineContext); // TEMP: The response is also buffered, because our // rewriting algorithm only operates on Strings for now. PortletExternalContext.DirectResponseTemp directResponse = (PortletExternalContext.DirectResponseTemp) externalContext.getResponse(); response.setContentType(directResponse.getContentType()); response.setTitle(directResponse.getTitle() != null ? directResponse.getTitle() : getTitle(request)); directResponse.write(response); } } catch (Exception e) { throw new PortletException(OXFException.getRootThrowable(e)); } } /** * Checking two maps for deep equality. */ private static boolean deepEquals(Map map1, Map map2) { if ((map1 == null) && (map2 == null)) { return true; } if ((map1 == null) || (map2 == null)) { return false; } final Set keySet1 = map1.keySet(); final Set keySet2 = map2.keySet(); if (keySet1.size() != keySet2.size()) { return false; } final Iterator it1 = keySet1.iterator(); final Iterator it2 = keySet1.iterator(); while (it1.hasNext()) { final Object key1 = it1.next(); final Object value1 = map1.get(key1); final Object key2 = it2.next(); final Object value2 = map2.get(key2); if (!key1.getClass().getName().equals(key2.getClass().getName())) { return false; } if (!value1.getClass().getName().equals(value2.getClass().getName())) { return false; } if (value1 instanceof Object[]) { if (!java.util.Arrays.equals((Object[]) value1, (Object[]) value2)) { return false; } } else { if (!value1.equals(value2)) { return false; } } } return true; } /** * Forward a request. */ public static void forward(ExternalContext.Request request, ExternalContext.Response response) { // Create new external context and call service final PipelineContext pipelineContext = new PipelineContext(); final PortletExternalContext externalContext = new PortletExternalContext(pipelineContext, request, response); externalContext.getProcessorService().service(true, externalContext, externalContext.getPipelineContext()); } /** * Include a request. */ public static void include(ExternalContext.Request request, ExternalContext.Response response) { // Create new external context and call service final PipelineContext pipelineContext = new PipelineContext(); final PortletExternalContext externalContext = new PortletExternalContext(pipelineContext, request, response); externalContext.getProcessorService().service(true, externalContext, externalContext.getPipelineContext()); } public void destroy() { // Run listeners try { runListenerProcessor(new PortletInitMap(this), new PortletContextInitMap(getPortletContext()), ProcessorService.logger, LOG_MESSAGE_PREFIX, "Portlet destroyed.", DESTROY_PROCESSOR_PROPERTY_PREFIX, DESTROY_PROCESSOR_INPUT_PROPERTY); } catch (Exception e) { ProcessorService.logger.error(LOG_MESSAGE_PREFIX + " - Exception when running Portlet destruction processor.", OXFException.getRootThrowable(e)); throw new OXFException(e); } processorService.destroy(); } /** * Return an unmodifiable Map of the Servlet initialization parameters. */ public static Map createServletInitParametersMap(PortletContext portletContext) { Map result = new HashMap(); for (Enumeration e = portletContext.getInitParameterNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); result.put(name, portletContext.getInitParameter(name)); } return Collections.unmodifiableMap(result); } /** * Present a read-only view of the Portlet initialization parameters as a Map. */ public class PortletInitMap extends AttributesToMap { public PortletInitMap(final OPSPortletDelegate portletDelegate) { super(new Attributeable() { public Object getAttribute(String s) { return portletDelegate.getInitParameter(s); } public Enumeration getAttributeNames() { return portletDelegate.getInitParameterNames(); } public void removeAttribute(String s) { throw new UnsupportedOperationException(); } public void setAttribute(String s, Object o) { throw new UnsupportedOperationException(); } }); } } /** * Present a read-only view of the PortletContext initialization parameters as a Map. */ public static class PortletContextInitMap extends AttributesToMap { public PortletContextInitMap(final PortletContext portletContext) { super(new Attributeable() { public Object getAttribute(String s) { return portletContext.getInitParameter(s); } public Enumeration getAttributeNames() { return portletContext.getInitParameterNames(); } public void removeAttribute(String s) { throw new UnsupportedOperationException(); } public void setAttribute(String s, Object o) { throw new UnsupportedOperationException(); } }); } } }
package org.orbeon.oxf.util; import org.apache.commons.pool.ObjectPool; import org.orbeon.oxf.common.OXFException; import org.orbeon.saxon.om.NodeInfo; import org.orbeon.saxon.xpath.StandaloneContext; import org.orbeon.saxon.xpath.Variable; import org.orbeon.saxon.xpath.XPathException; import org.orbeon.saxon.xpath.XPathExpression; import java.util.List; public class PooledXPathExpression { private XPathExpression expression; private ObjectPool pool; private StandaloneContext context; private java.util.Map variables; public PooledXPathExpression ( XPathExpression exp, ObjectPool pool, StandaloneContext context, final java.util.Map vars ) { this.expression = exp; this.pool = pool; this.context = context; variables = vars; } public void returnToPool() { try { pool.returnObject(this); } catch (Exception e) { throw new OXFException(e); } } public List evaluate() throws XPathException { return expression.evaluate(); } public Object evaluateSingle() throws XPathException { return expression.evaluateSingle(); } public void setContextNode(NodeInfo contextNode) { expression.setContextNode(contextNode); } public StandaloneContext getContext() { return context; } public void setVariable(String name, Object value) { try { Variable v = (Variable) variables.get(name); if (v != null) v.setValue(value); } catch (XPathException e) { throw new OXFException(e); } } public void destroy() { context = null; expression = null; pool = null; variables = null; } }
package bisq.network.p2p.network; import bisq.network.p2p.BundleOfEnvelopes; import bisq.network.p2p.CloseConnectionMessage; import bisq.network.p2p.ExtendedDataSizePermission; import bisq.network.p2p.NodeAddress; import bisq.network.p2p.SendersNodeAddressMessage; import bisq.network.p2p.SupportedCapabilitiesMessage; import bisq.network.p2p.peers.keepalive.messages.KeepAliveMessage; import bisq.network.p2p.storage.P2PDataStorage; import bisq.network.p2p.storage.messages.AddDataMessage; import bisq.network.p2p.storage.messages.AddPersistableNetworkPayloadMessage; import bisq.network.p2p.storage.payload.CapabilityRequiringPayload; import bisq.network.p2p.storage.payload.PersistableNetworkPayload; import bisq.network.p2p.storage.payload.ProtectedStoragePayload; import bisq.common.Proto; import bisq.common.UserThread; import bisq.common.app.Capabilities; import bisq.common.app.Capability; import bisq.common.app.HasCapabilities; import bisq.common.app.Version; import bisq.common.config.Config; import bisq.common.proto.ProtobufferException; import bisq.common.proto.network.NetworkEnvelope; import bisq.common.proto.network.NetworkProtoResolver; import bisq.common.util.Utilities; import com.google.protobuf.InvalidProtocolBufferException; import javax.inject.Inject; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.Uninterruptibles; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.InvalidClassException; import java.io.OptionalDataException; import java.io.StreamCorruptedException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.lang.ref.WeakReference; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.Nullable; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; @Slf4j public class Connection implements HasCapabilities, Runnable, MessageListener { // Static @Inject @Nullable private static Config config; // Leaving some constants package-private for tests to know limits. private static final int PERMITTED_MESSAGE_SIZE = 200 * 1024; // 200 kb private static final int MAX_PERMITTED_MESSAGE_SIZE = 10 * 1024 * 1024; // 10 MB (425 offers resulted in about 660 kb, mailbox msg will add more to it) offer has usually 2 kb, mailbox 3kb. //TODO decrease limits again after testing private static final int SOCKET_TIMEOUT = (int) TimeUnit.SECONDS.toMillis(180); public static int getPermittedMessageSize() { return PERMITTED_MESSAGE_SIZE; } // Class fields private final Socket socket; // private final MessageListener messageListener; private final ConnectionListener connectionListener; @Nullable private final NetworkFilter networkFilter; @Getter private final String uid; private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "Connection.java executor-service")); // holder of state shared between InputHandler and Connection @Getter private final Statistic statistic; @Getter private final ConnectionState connectionState; @Getter private final ConnectionStatistics connectionStatistics; // set in init private SynchronizedProtoOutputStream protoOutputStream; // mutable data, set from other threads but not changed internally. @Getter private Optional<NodeAddress> peersNodeAddressOptional = Optional.empty(); @Getter private volatile boolean stopped; @Getter private final ObjectProperty<NodeAddress> peersNodeAddressProperty = new SimpleObjectProperty<>(); private final List<Long> messageTimeStamps = new ArrayList<>(); private final CopyOnWriteArraySet<MessageListener> messageListeners = new CopyOnWriteArraySet<>(); private volatile long lastSendTimeStamp = 0; // We use a weak reference here to ensure that no connection causes a memory leak in case it get closed without // the shutDown being called. private final CopyOnWriteArraySet<WeakReference<SupportedCapabilitiesListener>> capabilitiesListeners = new CopyOnWriteArraySet<>(); @Getter private RuleViolation ruleViolation; private final ConcurrentHashMap<RuleViolation, Integer> ruleViolations = new ConcurrentHashMap<>(); private final Capabilities capabilities = new Capabilities(); // Constructor Connection(Socket socket, MessageListener messageListener, ConnectionListener connectionListener, @Nullable NodeAddress peersNodeAddress, NetworkProtoResolver networkProtoResolver, @Nullable NetworkFilter networkFilter) { this.socket = socket; this.connectionListener = connectionListener; this.networkFilter = networkFilter; uid = UUID.randomUUID().toString(); statistic = new Statistic(); addMessageListener(messageListener); this.networkProtoResolver = networkProtoResolver; connectionState = new ConnectionState(this); connectionStatistics = new ConnectionStatistics(this, connectionState); init(peersNodeAddress); } private void init(@Nullable NodeAddress peersNodeAddress) { try { socket.setSoTimeout(SOCKET_TIMEOUT); // Need to access first the ObjectOutputStream otherwise the ObjectInputStream would block // See: https://stackoverflow.com/questions/5658089/java-creating-a-new-objectinputstream-blocks/5658109#5658109 // When you construct an ObjectInputStream, in the constructor the class attempts to read a header that // the associated ObjectOutputStream on the other end of the connection has written. // It will not return until that header has been read. protoOutputStream = new SynchronizedProtoOutputStream(socket.getOutputStream(), statistic); protoInputStream = socket.getInputStream(); // We create a thread for handling inputStream data singleThreadExecutor.submit(this); if (peersNodeAddress != null) { setPeersNodeAddress(peersNodeAddress); if (networkFilter != null && networkFilter.isPeerBanned(peersNodeAddress)) { reportInvalidRequest(RuleViolation.PEER_BANNED); } } UserThread.execute(() -> connectionListener.onConnection(this)); } catch (Throwable e) { handleException(e); } } // API @Override public Capabilities getCapabilities() { return capabilities; } private final Object lock = new Object(); private final Queue<BundleOfEnvelopes> queueOfBundles = new ConcurrentLinkedQueue<>(); private final ScheduledExecutorService bundleSender = Executors.newSingleThreadScheduledExecutor(); // Called from various threads public void sendMessage(NetworkEnvelope networkEnvelope) { long ts = System.currentTimeMillis(); log.debug(">> Send networkEnvelope of type: {}", networkEnvelope.getClass().getSimpleName()); if (stopped) { log.debug("called sendMessage but was already stopped"); return; } if (networkFilter != null && peersNodeAddressOptional.isPresent() && networkFilter.isPeerBanned(peersNodeAddressOptional.get())) { reportInvalidRequest(RuleViolation.PEER_BANNED); return; } if (!noCapabilityRequiredOrCapabilityIsSupported(networkEnvelope)) { log.debug("Capability for networkEnvelope is required but not supported"); return; } int networkEnvelopeSize = networkEnvelope.toProtoNetworkEnvelope().getSerializedSize(); try { // Throttle outbound network_messages long now = System.currentTimeMillis(); long elapsed = now - lastSendTimeStamp; if (elapsed < getSendMsgThrottleTrigger()) { log.debug("We got 2 sendMessage requests in less than {} ms. We set the thread to sleep " + "for {} ms to avoid flooding our peer. lastSendTimeStamp={}, now={}, elapsed={}, networkEnvelope={}", getSendMsgThrottleTrigger(), getSendMsgThrottleSleep(), lastSendTimeStamp, now, elapsed, networkEnvelope.getClass().getSimpleName()); // check if BundleOfEnvelopes is supported if (getCapabilities().containsAll(new Capabilities(Capability.BUNDLE_OF_ENVELOPES))) { synchronized (lock) { // check if current envelope fits size // - no? create new envelope int size = !queueOfBundles.isEmpty() ? queueOfBundles.element().toProtoNetworkEnvelope().getSerializedSize() + networkEnvelopeSize : 0; if (queueOfBundles.isEmpty() || size > MAX_PERMITTED_MESSAGE_SIZE * 0.9) { // - no? create a bucket queueOfBundles.add(new BundleOfEnvelopes()); // - and schedule it for sending lastSendTimeStamp += getSendMsgThrottleSleep(); bundleSender.schedule(() -> { if (!stopped) { synchronized (lock) { BundleOfEnvelopes bundle = queueOfBundles.poll(); if (bundle != null && !stopped) { NetworkEnvelope envelope; int msgSize; if (bundle.getEnvelopes().size() == 1) { envelope = bundle.getEnvelopes().get(0); msgSize = envelope.toProtoNetworkEnvelope().getSerializedSize(); } else { envelope = bundle; msgSize = networkEnvelopeSize; } try { protoOutputStream.writeEnvelope(envelope); UserThread.execute(() -> messageListeners.forEach(e -> e.onMessageSent(envelope, this))); UserThread.execute(() -> connectionStatistics.addSendMsgMetrics(System.currentTimeMillis() - ts, msgSize)); } catch (Throwable t) { log.error("Sending envelope of class {} to address {} " + "failed due {}", envelope.getClass().getSimpleName(), this.getPeersNodeAddressOptional(), t.toString()); log.error("envelope: {}", envelope); } } } } }, lastSendTimeStamp - now, TimeUnit.MILLISECONDS); } // - yes? add to bucket queueOfBundles.element().add(networkEnvelope); } return; } Thread.sleep(getSendMsgThrottleSleep()); } lastSendTimeStamp = now; if (!stopped) { protoOutputStream.writeEnvelope(networkEnvelope); UserThread.execute(() -> messageListeners.forEach(e -> e.onMessageSent(networkEnvelope, this))); UserThread.execute(() -> connectionStatistics.addSendMsgMetrics(System.currentTimeMillis() - ts, networkEnvelopeSize)); } } catch (Throwable t) { handleException(t); } } // TODO: If msg is BundleOfEnvelopes we should check each individual message for capability and filter out those // which fail. public boolean noCapabilityRequiredOrCapabilityIsSupported(Proto msg) { boolean result; if (msg instanceof AddDataMessage) { final ProtectedStoragePayload protectedStoragePayload = (((AddDataMessage) msg).getProtectedStorageEntry()).getProtectedStoragePayload(); result = !(protectedStoragePayload instanceof CapabilityRequiringPayload); if (!result) result = capabilities.containsAll(((CapabilityRequiringPayload) protectedStoragePayload).getRequiredCapabilities()); } else if (msg instanceof AddPersistableNetworkPayloadMessage) { final PersistableNetworkPayload persistableNetworkPayload = ((AddPersistableNetworkPayloadMessage) msg).getPersistableNetworkPayload(); result = !(persistableNetworkPayload instanceof CapabilityRequiringPayload); if (!result) result = capabilities.containsAll(((CapabilityRequiringPayload) persistableNetworkPayload).getRequiredCapabilities()); } else if (msg instanceof CapabilityRequiringPayload) { result = capabilities.containsAll(((CapabilityRequiringPayload) msg).getRequiredCapabilities()); } else { result = true; } if (!result) { if (capabilities.size() > 1) { Proto data = msg; if (msg instanceof AddDataMessage) { data = ((AddDataMessage) msg).getProtectedStorageEntry().getProtectedStoragePayload(); } // Monitoring nodes have only one capability set, we don't want to log those log.debug("We did not send the message because the peer does not support our required capabilities. " + "messageClass={}, peer={}, peers supportedCapabilities={}", data.getClass().getSimpleName(), peersNodeAddressOptional, capabilities); } } return result; } public void addMessageListener(MessageListener messageListener) { boolean isNewEntry = messageListeners.add(messageListener); if (!isNewEntry) log.warn("Try to add a messageListener which was already added."); } public void removeMessageListener(MessageListener messageListener) { boolean contained = messageListeners.remove(messageListener); if (!contained) log.debug("Try to remove a messageListener which was never added.\n\t" + "That might happen because of async behaviour of CopyOnWriteArraySet"); } public void addWeakCapabilitiesListener(SupportedCapabilitiesListener listener) { capabilitiesListeners.add(new WeakReference<>(listener)); } private boolean violatesThrottleLimit() { long now = System.currentTimeMillis(); messageTimeStamps.add(now); // clean list while (messageTimeStamps.size() > getMsgThrottlePer10Sec()) messageTimeStamps.remove(0); return violatesThrottleLimit(now, 1, getMsgThrottlePerSec()) || violatesThrottleLimit(now, 10, getMsgThrottlePer10Sec()); } private int getMsgThrottlePerSec() { return config != null ? config.msgThrottlePerSec : 200; } private int getMsgThrottlePer10Sec() { return config != null ? config.msgThrottlePer10Sec : 1000; } private int getSendMsgThrottleSleep() { return config != null ? config.sendMsgThrottleSleep : 50; } private int getSendMsgThrottleTrigger() { return config != null ? config.sendMsgThrottleTrigger : 20; } private boolean violatesThrottleLimit(long now, int seconds, int messageCountLimit) { if (messageTimeStamps.size() >= messageCountLimit) { // find the entry in the message timestamp history which determines whether we overshot the limit or not long compareValue = messageTimeStamps.get(messageTimeStamps.size() - messageCountLimit); // if duration < seconds sec we received too much network_messages if (now - compareValue < TimeUnit.SECONDS.toMillis(seconds)) { log.error("violatesThrottleLimit {}/{} second(s)", messageCountLimit, seconds); return true; } } return false; } // MessageListener implementation // Only receive non - CloseConnectionMessage network_messages @Override public void onMessage(NetworkEnvelope networkEnvelope, Connection connection) { checkArgument(connection.equals(this)); if (networkEnvelope instanceof BundleOfEnvelopes) { onBundleOfEnvelopes((BundleOfEnvelopes) networkEnvelope, connection); } else { UserThread.execute(() -> messageListeners.forEach(e -> e.onMessage(networkEnvelope, connection))); } } private void onBundleOfEnvelopes(BundleOfEnvelopes bundleOfEnvelopes, Connection connection) { Map<P2PDataStorage.ByteArray, Set<NetworkEnvelope>> itemsByHash = new HashMap<>(); Set<NetworkEnvelope> envelopesToProcess = new LinkedHashSet<>(); List<NetworkEnvelope> networkEnvelopes = bundleOfEnvelopes.getEnvelopes(); for (NetworkEnvelope networkEnvelope : networkEnvelopes) { // If SendersNodeAddressMessage we do some verifications and apply if successful, otherwise we return false. if (networkEnvelope instanceof SendersNodeAddressMessage && !processSendersNodeAddressMessage((SendersNodeAddressMessage) networkEnvelope)) { continue; } if (networkEnvelope instanceof AddPersistableNetworkPayloadMessage) { PersistableNetworkPayload persistableNetworkPayload = ((AddPersistableNetworkPayloadMessage) networkEnvelope).getPersistableNetworkPayload(); byte[] hash = persistableNetworkPayload.getHash(); String itemName = persistableNetworkPayload.getClass().getSimpleName(); P2PDataStorage.ByteArray byteArray = new P2PDataStorage.ByteArray(hash); itemsByHash.putIfAbsent(byteArray, new HashSet<>()); Set<NetworkEnvelope> envelopesByHash = itemsByHash.get(byteArray); if (!envelopesByHash.contains(networkEnvelope)) { envelopesByHash.add(networkEnvelope); envelopesToProcess.add(networkEnvelope); } else { log.debug("We got duplicated items for {}. We ignore the duplicates. Hash: {}", itemName, Utilities.encodeToHex(hash)); } } else { envelopesToProcess.add(networkEnvelope); } } envelopesToProcess.forEach(envelope -> UserThread.execute(() -> messageListeners.forEach(listener -> listener.onMessage(envelope, connection)))); } // Setters private void setPeersNodeAddress(NodeAddress peerNodeAddress) { checkNotNull(peerNodeAddress, "peerAddress must not be null"); peersNodeAddressOptional = Optional.of(peerNodeAddress); if (this instanceof InboundConnection) { log.debug("\n\n "We got the peers node address set.\n" + "peersNodeAddress= " + peerNodeAddress.getFullAddress() + "\nconnection.uid=" + getUid() + "\n } peersNodeAddressProperty.set(peerNodeAddress); } // Getters public boolean hasPeersNodeAddress() { return peersNodeAddressOptional.isPresent(); } // ShutDown public void shutDown(CloseConnectionReason closeConnectionReason) { shutDown(closeConnectionReason, null); } public void shutDown(CloseConnectionReason closeConnectionReason, @Nullable Runnable shutDownCompleteHandler) { log.debug("shutDown: nodeAddressOpt={}, closeConnectionReason={}", this.peersNodeAddressOptional.orElse(null), closeConnectionReason); connectionState.shutDown(); if (!stopped) { String peersNodeAddress = peersNodeAddressOptional.map(NodeAddress::toString).orElse("null"); log.debug("\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" + "ShutDown connection:" + "\npeersNodeAddress=" + peersNodeAddress + "\ncloseConnectionReason=" + closeConnectionReason + "\nuid=" + uid + "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"); if (closeConnectionReason.sendCloseMessage) { new Thread(() -> { try { String reason = closeConnectionReason == CloseConnectionReason.RULE_VIOLATION ? getRuleViolation().name() : closeConnectionReason.name(); sendMessage(new CloseConnectionMessage(reason)); stopped = true; //noinspection UnstableApiUsage Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS); } catch (Throwable t) { log.error(t.getMessage()); t.printStackTrace(); } finally { stopped = true; UserThread.execute(() -> doShutDown(closeConnectionReason, shutDownCompleteHandler)); } }, "Connection:SendCloseConnectionMessage-" + this.uid).start(); } else { stopped = true; doShutDown(closeConnectionReason, shutDownCompleteHandler); } } else { //TODO find out why we get called that log.debug("stopped was already at shutDown call"); UserThread.execute(() -> doShutDown(closeConnectionReason, shutDownCompleteHandler)); } } private void doShutDown(CloseConnectionReason closeConnectionReason, @Nullable Runnable shutDownCompleteHandler) { // Use UserThread.execute as its not clear if that is called from a non-UserThread UserThread.execute(() -> connectionListener.onDisconnect(closeConnectionReason, this)); try { socket.close(); } catch (SocketException e) { log.trace("SocketException at shutdown might be expected {}", e.getMessage()); } catch (IOException e) { log.error("Exception at shutdown. " + e.getMessage()); e.printStackTrace(); } finally { protoOutputStream.onConnectionShutdown(); capabilitiesListeners.clear(); try { protoInputStream.close(); } catch (IOException e) { log.error(e.getMessage()); e.printStackTrace(); } //noinspection UnstableApiUsage MoreExecutors.shutdownAndAwaitTermination(singleThreadExecutor, 500, TimeUnit.MILLISECONDS); //noinspection UnstableApiUsage MoreExecutors.shutdownAndAwaitTermination(bundleSender, 500, TimeUnit.MILLISECONDS); log.debug("Connection shutdown complete {}", this.toString()); // Use UserThread.execute as its not clear if that is called from a non-UserThread if (shutDownCompleteHandler != null) UserThread.execute(shutDownCompleteHandler); } } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Connection)) return false; Connection that = (Connection) o; return uid.equals(that.uid); } @Override public int hashCode() { return uid.hashCode(); } @Override public String toString() { return "Connection{" + "peerAddress=" + peersNodeAddressOptional + ", connectionState=" + connectionState + ", connectionType=" + (this instanceof InboundConnection ? "InboundConnection" : "OutboundConnection") + ", uid='" + uid + '\'' + '}'; } public String printDetails() { String portInfo; if (socket.getLocalPort() == 0) portInfo = "port=" + socket.getPort(); else portInfo = "localPort=" + socket.getLocalPort() + "/port=" + socket.getPort(); return "Connection{" + "peerAddress=" + peersNodeAddressOptional + ", connectionState=" + connectionState + ", portInfo=" + portInfo + ", uid='" + uid + '\'' + ", ruleViolation=" + ruleViolation + ", ruleViolations=" + ruleViolations + ", supportedCapabilities=" + capabilities + ", stopped=" + stopped + '}'; } // SharedSpace /** * Holds all shared data between Connection and InputHandler * Runs in same thread as Connection */ public boolean reportInvalidRequest(RuleViolation ruleViolation) { log.warn("We got reported the ruleViolation {} at connection {}", ruleViolation, this); int numRuleViolations; numRuleViolations = ruleViolations.getOrDefault(ruleViolation, 0); numRuleViolations++; ruleViolations.put(ruleViolation, numRuleViolations); if (numRuleViolations >= ruleViolation.maxTolerance) { log.warn("We close connection as we received too many corrupt requests.\n" + "numRuleViolations={}\n\t" + "corruptRequest={}\n\t" + "corruptRequests={}\n\t" + "connection={}", numRuleViolations, ruleViolation, ruleViolations.toString(), this); this.ruleViolation = ruleViolation; if (ruleViolation == RuleViolation.PEER_BANNED) { log.warn("We close connection due RuleViolation.PEER_BANNED. peersNodeAddress={}", getPeersNodeAddressOptional()); shutDown(CloseConnectionReason.PEER_BANNED); } else if (ruleViolation == RuleViolation.INVALID_CLASS) { log.warn("We close connection due RuleViolation.INVALID_CLASS"); shutDown(CloseConnectionReason.INVALID_CLASS_RECEIVED); } else { log.warn("We close connection due RuleViolation.RULE_VIOLATION"); shutDown(CloseConnectionReason.RULE_VIOLATION); } return true; } else { return false; } } private void handleException(Throwable e) { CloseConnectionReason closeConnectionReason; // silent fail if we are shutdown if (stopped) return; if (e instanceof SocketException) { if (socket.isClosed()) closeConnectionReason = CloseConnectionReason.SOCKET_CLOSED; else closeConnectionReason = CloseConnectionReason.RESET; log.info("SocketException (expected if connection lost). closeConnectionReason={}; connection={}", closeConnectionReason, this); } else if (e instanceof SocketTimeoutException || e instanceof TimeoutException) { closeConnectionReason = CloseConnectionReason.SOCKET_TIMEOUT; log.info("Shut down caused by exception {} on connection={}", e.toString(), this); } else if (e instanceof EOFException) { closeConnectionReason = CloseConnectionReason.TERMINATED; log.warn("Shut down caused by exception {} on connection={}", e.toString(), this); } else if (e instanceof OptionalDataException || e instanceof StreamCorruptedException) { closeConnectionReason = CloseConnectionReason.CORRUPTED_DATA; log.warn("Shut down caused by exception {} on connection={}", e.toString(), this); } else { closeConnectionReason = CloseConnectionReason.UNKNOWN_EXCEPTION; log.warn("Unknown reason for exception at socket: {}\n\t" + "peer={}\n\t" + "Exception={}", socket.toString(), this.peersNodeAddressOptional, e.toString()); e.printStackTrace(); } shutDown(closeConnectionReason); } private boolean processSendersNodeAddressMessage(SendersNodeAddressMessage sendersNodeAddressMessage) { NodeAddress senderNodeAddress = sendersNodeAddressMessage.getSenderNodeAddress(); checkNotNull(senderNodeAddress, "senderNodeAddress must not be null at SendersNodeAddressMessage " + sendersNodeAddressMessage.getClass().getSimpleName()); Optional<NodeAddress> existingAddressOptional = getPeersNodeAddressOptional(); if (existingAddressOptional.isPresent()) { // If we have already the peers address we check again if it matches our stored one checkArgument(existingAddressOptional.get().equals(senderNodeAddress), "senderNodeAddress not matching connections peer address.\n\t" + "message=" + sendersNodeAddressMessage); } else { setPeersNodeAddress(senderNodeAddress); } if (networkFilter != null && networkFilter.isPeerBanned(senderNodeAddress)) { reportInvalidRequest(RuleViolation.PEER_BANNED); return false; } return true; } // InputHandler // Runs in same thread as Connection, receives a message, performs several checks on it // (including throttling limits, validity and statistics) // and delivers it to the message listener given in the constructor. private InputStream protoInputStream; private final NetworkProtoResolver networkProtoResolver; private long lastReadTimeStamp; private boolean threadNameSet; @Override public void run() { try { Thread.currentThread().setName("InputHandler"); while (!stopped && !Thread.currentThread().isInterrupted()) { if (!threadNameSet && getPeersNodeAddressOptional().isPresent()) { Thread.currentThread().setName("InputHandler-" + getPeersNodeAddressOptional().get().getFullAddress()); threadNameSet = true; } try { if (socket != null && socket.isClosed()) { log.warn("Socket is null or closed socket={}", socket); shutDown(CloseConnectionReason.SOCKET_CLOSED); return; } // Blocking read from the inputStream protobuf.NetworkEnvelope proto = protobuf.NetworkEnvelope.parseDelimitedFrom(protoInputStream); long ts = System.currentTimeMillis(); if (socket != null && socket.isClosed()) { log.warn("Socket is null or closed socket={}", socket); shutDown(CloseConnectionReason.SOCKET_CLOSED); return; } if (proto == null) { if (protoInputStream.read() == -1) { log.warn("proto is null because protoInputStream.read()=-1 (EOF). That is expected if client got stopped without proper shutdown."); } else { log.warn("proto is null. protoInputStream.read()=" + protoInputStream.read()); } shutDown(CloseConnectionReason.NO_PROTO_BUFFER_ENV); return; } if (networkFilter != null && peersNodeAddressOptional.isPresent() && networkFilter.isPeerBanned(peersNodeAddressOptional.get())) { reportInvalidRequest(RuleViolation.PEER_BANNED); return; } // Throttle inbound network_messages long now = System.currentTimeMillis(); long elapsed = now - lastReadTimeStamp; if (elapsed < 10) { log.debug("We got 2 network_messages received in less than 10 ms. We set the thread to sleep " + "for 20 ms to avoid getting flooded by our peer. lastReadTimeStamp={}, now={}, elapsed={}", lastReadTimeStamp, now, elapsed); Thread.sleep(20); } NetworkEnvelope networkEnvelope = networkProtoResolver.fromProto(proto); lastReadTimeStamp = now; log.debug("<< Received networkEnvelope of type: {}", networkEnvelope.getClass().getSimpleName()); int size = proto.getSerializedSize(); // We want to track the size of each object even if it is invalid data statistic.addReceivedBytes(size); // We want to track the network_messages also before the checks, so do it early... statistic.addReceivedMessage(networkEnvelope); // First we check the size boolean exceeds; if (networkEnvelope instanceof ExtendedDataSizePermission) { exceeds = size > MAX_PERMITTED_MESSAGE_SIZE; } else { exceeds = size > PERMITTED_MESSAGE_SIZE; } if (networkEnvelope instanceof AddPersistableNetworkPayloadMessage && !((AddPersistableNetworkPayloadMessage) networkEnvelope).getPersistableNetworkPayload().verifyHashSize()) { log.warn("PersistableNetworkPayload.verifyHashSize failed. hashSize={}; object={}", ((AddPersistableNetworkPayloadMessage) networkEnvelope).getPersistableNetworkPayload().getHash().length, Utilities.toTruncatedString(proto)); if (reportInvalidRequest(RuleViolation.MAX_MSG_SIZE_EXCEEDED)) return; } if (exceeds) { log.warn("size > MAX_MSG_SIZE. size={}; object={}", size, Utilities.toTruncatedString(proto)); if (reportInvalidRequest(RuleViolation.MAX_MSG_SIZE_EXCEEDED)) return; } if (violatesThrottleLimit() && reportInvalidRequest(RuleViolation.THROTTLE_LIMIT_EXCEEDED)) return; // Check P2P network ID if (proto.getMessageVersion() != Version.getP2PMessageVersion() && reportInvalidRequest(RuleViolation.WRONG_NETWORK_ID)) { log.warn("RuleViolation.WRONG_NETWORK_ID. version of message={}, app version={}, " + "proto.toTruncatedString={}", proto.getMessageVersion(), Version.getP2PMessageVersion(), Utilities.toTruncatedString(proto.toString())); return; } boolean causedShutDown = maybeHandleSupportedCapabilitiesMessage(networkEnvelope); if (causedShutDown) { return; } if (networkEnvelope instanceof CloseConnectionMessage) { // If we get a CloseConnectionMessage we shut down log.debug("CloseConnectionMessage received. Reason={}\n\t" + "connection={}", proto.getCloseConnectionMessage().getReason(), this); if (CloseConnectionReason.PEER_BANNED.name().equals(proto.getCloseConnectionMessage().getReason())) { log.warn("We got shut down because we are banned by the other peer. " + "(InputHandler.run CloseConnectionMessage). Peer: {}", getPeersNodeAddressOptional()); } shutDown(CloseConnectionReason.CLOSE_REQUESTED_BY_PEER); return; } else if (!stopped) { // We don't want to get the activity ts updated by ping/pong msg if (!(networkEnvelope instanceof KeepAliveMessage)) statistic.updateLastActivityTimestamp(); // If SendersNodeAddressMessage we do some verifications and apply if successful, // otherwise we return false. if (networkEnvelope instanceof SendersNodeAddressMessage && !processSendersNodeAddressMessage((SendersNodeAddressMessage) networkEnvelope)) { return; } onMessage(networkEnvelope, this); UserThread.execute(() -> connectionStatistics.addReceivedMsgMetrics(System.currentTimeMillis() - ts, size)); } } catch (InvalidClassException e) { log.error(e.getMessage()); e.printStackTrace(); reportInvalidRequest(RuleViolation.INVALID_CLASS); } catch (ProtobufferException | NoClassDefFoundError | InvalidProtocolBufferException e) { log.error(e.getMessage()); e.printStackTrace(); reportInvalidRequest(RuleViolation.INVALID_DATA_TYPE); } catch (Throwable t) { handleException(t); } } } catch (Throwable t) { handleException(t); } } public boolean maybeHandleSupportedCapabilitiesMessage(NetworkEnvelope networkEnvelope) { if (!(networkEnvelope instanceof SupportedCapabilitiesMessage)) { return false; } Capabilities supportedCapabilities = ((SupportedCapabilitiesMessage) networkEnvelope).getSupportedCapabilities(); if (supportedCapabilities == null || supportedCapabilities.isEmpty()) { return false; } if (this.capabilities.equals(supportedCapabilities)) { return false; } if (!Capabilities.hasMandatoryCapability(supportedCapabilities)) { log.info("We close a connection because of " + "CloseConnectionReason.MANDATORY_CAPABILITIES_NOT_SUPPORTED " + "to node {}. Capabilities of old node: {}, " + "networkEnvelope class name={}", getSenderNodeAddressAsString(networkEnvelope), supportedCapabilities.prettyPrint(), networkEnvelope.getClass().getSimpleName()); shutDown(CloseConnectionReason.MANDATORY_CAPABILITIES_NOT_SUPPORTED); return true; } this.capabilities.set(supportedCapabilities); capabilitiesListeners.forEach(weakListener -> { SupportedCapabilitiesListener supportedCapabilitiesListener = weakListener.get(); if (supportedCapabilitiesListener != null) { UserThread.execute(() -> supportedCapabilitiesListener.onChanged(supportedCapabilities)); } }); return false; } @Nullable private NodeAddress getSenderNodeAddress(NetworkEnvelope networkEnvelope) { return getPeersNodeAddressOptional().orElse( networkEnvelope instanceof SendersNodeAddressMessage ? ((SendersNodeAddressMessage) networkEnvelope).getSenderNodeAddress() : null); } private String getSenderNodeAddressAsString(NetworkEnvelope networkEnvelope) { NodeAddress nodeAddress = getSenderNodeAddress(networkEnvelope); return nodeAddress == null ? "null" : nodeAddress.getFullAddress(); } }
package org.ensembl.healthcheck.testcase.generic; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.ensembl.healthcheck.DatabaseRegistryEntry; import org.ensembl.healthcheck.DatabaseType; import org.ensembl.healthcheck.ReportManager; import org.ensembl.healthcheck.Species; import org.ensembl.healthcheck.util.DBUtils; import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase; /** * Check various things about ID mapping-related tables. */ public class MappingSession extends SingleDatabaseTestCase { // historical names to ignore when doing format checking private String[] ignoredNames = { "homo_sapiens_core_120" }; /** * Create a new MappingSession healthcheck. */ public MappingSession() { addToGroup("id_mapping"); addToGroup("release"); setDescription("Checks the mapping session and stable ID tables."); } /** * This only really applies to core databases */ public void types() { removeAppliesToType(DatabaseType.OTHERFEATURES); removeAppliesToType(DatabaseType.ESTGENE); removeAppliesToType(DatabaseType.VEGA); removeAppliesToType(DatabaseType.CDNA); } /** * Run the test - check the ID mapping-related tables. * * @param dbre * The database to check. * @return true if the test passes. */ public boolean run(final DatabaseRegistryEntry dbre) { boolean result = true; // there are several species where ID mapping is not done Species s = dbre.getSpecies(); if (s != Species.CAENORHABDITIS_ELEGANS && s != Species.DROSOPHILA_MELANOGASTER && s != Species.TAKIFUGU_RUBRIPES) { Connection con = dbre.getConnection(); logger.info("Checking tables exist and are populated"); result = checkTablesExistAndPopulated(dbre) && result; logger.info("Checking for null strings"); result = checkNoNullStrings(con) && result; logger.info("Checking DB name format in mapping_session"); result = checkDBNameFormat(con) && result; // logger.info("Checking mapping_session chaining"); // result = checkMappingSessionChaining(con) && result; logger.info("Checking mapping_session/stable_id_event keys"); result = checkMappingSessionStableIDKeys(con) && result; logger.info("Checking mapping_session old_release and new_release values"); result = checkOldAndNewReleases(con) && result; } return result; } // run /** * Check format of old/new DB names in mapping_session. */ private boolean checkDBNameFormat(final Connection con) { boolean result = true; String dbNameRegexp = "[A-Za-z]+_[A-Za-z]+_(core|est|estgene|vega)_\\d+_\\d+[A-Za-z]?.*"; String[] sql = { "SELECT old_db_name from mapping_session WHERE old_db_name <> 'ALL'", "SELECT new_db_name from mapping_session WHERE new_db_name <> 'LATEST'" }; for (int i = 0; i < sql.length; i++) { String[] names = getColumnValues(con, sql[i]); for (int j = 0; j < names.length; j++) { if (!(names[j].matches(dbNameRegexp)) && !ignoreName(names[j])) { ReportManager.problem(this, con, "Database name " + names[j] + " in mapping_session does not appear to be in the correct format"); result = false; } } } if (result) { ReportManager.correct(this, con, "All database names in mapping_session appear to be in the correct format"); } return result; } /** * Checks tables exist and have >0 rows. Doesn't check population for * first-build databases. * * @param con * @return True when all ID mapping-related tables exist and have > 0 rows. * */ private boolean checkTablesExistAndPopulated(final DatabaseRegistryEntry dbre) { String[] tables = new String[] { "stable_id_event", "mapping_session", "gene_archive", "peptide_archive" }; boolean result = true; Connection con = dbre.getConnection(); String dbName = DBUtils.getShortDatabaseName(con); if (!dbName.matches(".*_1[a-zA-Z]?$")) { for (int i = 0; i < tables.length; i++) { String table = tables[i]; boolean exists = checkTableExists(con, table); if (exists) { if (countRowsInTable(con, table) == 0) { ReportManager.problem(this, con, "Empty table:" + table); result = false; } } else { ReportManager.problem(this, con, "Missing table:" + table); result = false; } } } else { logger.info(dbName + " seems to be a new genebuild, skipping table checks"); } return result; } /** * Check no "NULL" or "null" strings in stable_id_event.new_stable_id or * stable_id_event.oldable_id. * * @param con * @return */ private boolean checkNoNullStrings(final Connection con) { boolean result = true; int rows = getRowCount(con, "select count(*) from stable_id_event sie where new_stable_id='NULL'"); if (rows > 0) { ReportManager.problem(this, con, rows + " rows in stable_id_event.new_stable_id contains \"NULL\" string instead of NULL value."); result = false; } rows = getRowCount(con, "select count(*) from stable_id_event sie where new_stable_id='null'"); if (rows > 0) { ReportManager.problem(this, con, rows + " rows in stable_id_event.new_stable_id contains \"null\" string instead of NULL value."); result = false; } rows = getRowCount(con, "select count(*) from stable_id_event sie where old_stable_id='NULL'"); if (rows > 0) { ReportManager.problem(this, con, rows + " rows in stable_id_event.old_stable_id contains \"NULL\" string instead of NULL value."); result = false; } rows = getRowCount(con, "select count(*) from stable_id_event sie where old_stable_id='null'"); if (rows > 0) { ReportManager.problem(this, con, rows + " rows in stable_id_event.old_stable_id contains \"null\" string instead of NULL value."); result = false; } return result; } /** * Check that the old_db_name and new_db_name columns "chain" together. */ private boolean checkMappingSessionChaining(final Connection con) { boolean result = true; String[] oldNames = getColumnValues(con, "SELECT old_db_name FROM mapping_session WHERE old_db_name <> 'ALL' ORDER BY created"); String[] newNames = getColumnValues(con, "SELECT new_db_name FROM mapping_session WHERE new_db_name <> 'LATEST' ORDER BY created"); for (int i = 1; i < oldNames.length; i++) { if (!(oldNames[i].equalsIgnoreCase(newNames[i - 1]))) { ReportManager.problem(this, con, "Old/new names " + oldNames[i] + " " + newNames[i - 1] + " do not chain properly"); result = false; } } if (result) { ReportManager.correct(this, con, "Old/new db name chaining in mapping_session seems OK"); } return result; } /** * Check that all mapping_sessions have entries in stable_id_event and * vice-versa. */ private boolean checkMappingSessionStableIDKeys(final Connection con) { boolean result = true; int orphans = countOrphans(con, "mapping_session", "mapping_session_id", "stable_id_event", "mapping_session_id", false); if (orphans > 0) { ReportManager.problem(this, con, orphans + " dangling references between mapping_session and stable_id_event tables"); result = false; } else { ReportManager.correct(this, con, "All mapping_session/stable_id_event keys are OK"); } return result; } /** * Check that all mapping_sessions have new releases that are greater than the * old releases. */ private boolean checkOldAndNewReleases(final Connection con) { boolean result = true; try { Statement stmt = con.createStatement(); // nasty forced cast by adding 0 required since the columns are VARCHARS and need to be compared lexicographically ResultSet rs = stmt.executeQuery("SELECT mapping_session_id, old_db_name, new_db_name, old_release, new_release FROM mapping_session WHERE old_release+0 > new_release+0"); while (rs.next()) { // ignore homo_sapiens_core_18_34 -> homo_sapiens_core_18_34a since this was when we didn't change numbers between releases if (rs.getString("old_db_name").equals("homo_sapiens_core_18_34")) { continue; } ReportManager.problem(this, con, "Mapping session with ID " + rs.getLong("mapping_session_id") + " (" + rs.getString("old_db_name") + " -> " + rs.getString("new_db_name") + ") has a new_release (" + rs.getInt("new_release") + ") that is not greater than the old release (" + rs.getInt("old_release") + ")"); result = false; } } catch (SQLException se) { se.printStackTrace(); } if (result) { ReportManager.correct(this, con, "All new_release values are greater than old_release."); } return result; } /** * Certain historical names don't match the new format and should be ignored * to prevent constant failures. */ private boolean ignoreName(String name) { for (int i = 0; i < ignoredNames.length; i++) { if (name.equals(ignoredNames[i])) { return true; } } return false; } } // MappingSession
package org.gridsphere.portlets.core.registration; import org.gridsphere.portlet.impl.PortletURLImpl; import org.gridsphere.portlet.service.PortletServiceException; import org.gridsphere.provider.event.jsr.ActionFormEvent; import org.gridsphere.provider.event.jsr.RenderFormEvent; import org.gridsphere.provider.portlet.jsr.ActionPortlet; import org.gridsphere.provider.portletui.beans.MessageBoxBean; import org.gridsphere.provider.portletui.beans.TextFieldBean; import org.gridsphere.services.core.mail.MailMessage; import org.gridsphere.services.core.mail.MailService; import org.gridsphere.services.core.portal.PortalConfigService; import org.gridsphere.services.core.request.Request; import org.gridsphere.services.core.request.RequestService; import org.gridsphere.services.core.security.password.PasswordEditor; import org.gridsphere.services.core.security.password.PasswordManagerService; import org.gridsphere.services.core.security.role.PortletRole; import org.gridsphere.services.core.security.role.RoleManagerService; import org.gridsphere.services.core.user.User; import org.gridsphere.services.core.user.UserManagerService; import javax.portlet.*; import javax.servlet.http.HttpServletRequest; import java.util.*; public class SignupPortlet extends ActionPortlet { private static String ACTIVATE_ACCOUNT_LABEL = "activateaccount"; private static long REQUEST_LIFETIME = 1000 * 60 * 60 * 24 * 3; // 3 days public static final String LOGIN_ERROR_FLAG = "LOGIN_FAILED"; public static final Integer LOGIN_ERROR_UNKNOWN = new Integer(-1); public static final String DO_VIEW_USER_EDIT_LOGIN = "signup/createaccount.jsp"; //edit user private UserManagerService userManagerService = null; private RoleManagerService roleService = null; private PasswordManagerService passwordManagerService = null; private PortalConfigService portalConfigService = null; private RequestService requestService = null; private MailService mailService = null; private String activateAccountURL = null; private String denyAccountURL = null; private String notificationURL = null; public void init(PortletConfig config) throws PortletException { super.init(config); userManagerService = (UserManagerService) createPortletService(UserManagerService.class); roleService = (RoleManagerService) createPortletService(RoleManagerService.class); passwordManagerService = (PasswordManagerService) createPortletService(PasswordManagerService.class); requestService = (RequestService) createPortletService(RequestService.class); mailService = (MailService) createPortletService(MailService.class); portalConfigService = (PortalConfigService) createPortletService(PortalConfigService.class); DEFAULT_VIEW_PAGE = "doNewUser"; } protected String getLocalizedText(HttpServletRequest req, String key) { Locale locale = req.getLocale(); ResourceBundle bundle = ResourceBundle.getBundle("gridsphere.resources.Portlet", locale); return bundle.getString(key); } public void doNewUser(RenderFormEvent evt) throws PortletException { RenderRequest req = evt.getRenderRequest(); RenderResponse res = evt.getRenderResponse(); if (notificationURL == null) { notificationURL = res.createActionURL().toString(); } if (activateAccountURL == null) { PortletURL accountURL = res.createActionURL(); ((PortletURLImpl) accountURL).setRender("approveAccount"); ((PortletURLImpl) accountURL).setLayout("register"); ((PortletURLImpl) accountURL).setEncoding(false); activateAccountURL = accountURL.toString(); } if (denyAccountURL == null) { PortletURL denyURL = res.createActionURL(); ((PortletURLImpl) denyURL).setRender("denyAccount"); ((PortletURLImpl) denyURL).setLayout("register"); ((PortletURLImpl) denyURL).setEncoding(false); denyAccountURL = denyURL.toString(); } boolean canUserCreateAccount = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.CAN_USER_CREATE_ACCOUNT)).booleanValue(); if (!canUserCreateAccount) return; MessageBoxBean msg = evt.getMessageBoxBean("msg"); String savePasswds = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS); if (savePasswds.equals(Boolean.TRUE.toString())) { req.setAttribute("savePass", "true"); } String error = (String) req.getPortletSession(true).getAttribute("error"); if (error != null) { msg.setValue(error); req.getPortletSession(true).removeAttribute("error"); } else { String adminApproval = portalConfigService.getProperty("ADMIN_ACCOUNT_APPROVAL"); if (adminApproval.equals(Boolean.TRUE.toString())) { msg.setKey("LOGIN_ACCOUNT_CREATE_APPROVAL"); } else { msg.setKey("LOGIN_CREATE_ACCT"); } } setNextState(req, DO_VIEW_USER_EDIT_LOGIN); log.debug("in doViewNewUser"); } public void doSaveAccount(ActionFormEvent evt) throws PortletException { ActionRequest req = evt.getActionRequest(); String savePasswds = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS); if (savePasswds.equals(Boolean.TRUE.toString())) { req.setAttribute("savePass", "true"); } boolean canUserCreateAccount = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.CAN_USER_CREATE_ACCOUNT)).booleanValue(); if (!canUserCreateAccount) return; try { //check if the user is new or not validateUser(evt); //new and valid user and will save it notifyNewUser(evt); setNextState(req, "doConfirmSave"); } catch (PortletException e) { //invalid user, an exception was thrown //back to edit log.error("Could not create account: ", e); req.getPortletSession(true).setAttribute("error", e.getMessage()); setNextState(req, DEFAULT_VIEW_PAGE); } } public void doConfirmSave(RenderFormEvent evt) { MessageBoxBean msg = evt.getMessageBoxBean("msg"); msg.setKey("SIGNUP_CONFIRM"); setNextState(evt.getRenderRequest(), "signup/confirmsave.jsp"); } private void validateUser(ActionFormEvent event) throws PortletException { log.debug("Entering validateUser()"); PortletRequest req = event.getActionRequest(); // Validate user name String userName = event.getTextFieldBean("userName").getValue(); if (userName.equals("")) { createErrorMessage(event, this.getLocalizedText(req, "USER_NAME_BLANK") + "<br />"); throw new PortletException("user name is blank!"); } if (this.userManagerService.existsUserName(userName)) { createErrorMessage(event, this.getLocalizedText(req, "USER_EXISTS") + "<br />"); throw new PortletException("user exists already"); } // Validate full name String firstName = event.getTextFieldBean("firstName").getValue(); if (firstName.equals("")) { createErrorMessage(event, this.getLocalizedText(req, "USER_GIVENNAME_BLANK") + "<br />"); throw new PortletException("first name is blank"); } String lastName = event.getTextFieldBean("lastName").getValue(); if (lastName.equals("")) { createErrorMessage(event, this.getLocalizedText(req, "USER_FAMILYNAME_BLANK") + "<br />"); throw new PortletException("last name is blank"); } // Validate e-mail String eMail = event.getTextFieldBean("emailAddress").getValue(); if (eMail.equals("")) { createErrorMessage(event, this.getLocalizedText(req, "USER_NEED_EMAIL") + "<br />"); throw new PortletException("email is blank"); } else if ((eMail.indexOf("@") < 0)) { createErrorMessage(event, this.getLocalizedText(req, "USER_NEED_EMAIL") + "<br />"); throw new PortletException("email address invalid"); } else if ((eMail.indexOf(".") < 0)) { createErrorMessage(event, this.getLocalizedText(req, "USER_NEED_EMAIL") + "<br />"); throw new PortletException("email address invalid"); } //Validate password String savePasswds = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS); if (savePasswds.equals(Boolean.TRUE.toString())) { if (isInvalidPassword(event)) throw new PortletException("password no good!"); } //retrieve the response String response = event.getTextFieldBean("captchaTF").getValue(); String captchaValue = (String) req.getPortletSession(true).getAttribute(nl.captcha.servlet.Constants.SIMPLE_CAPCHA_SESSION_KEY, PortletSession.APPLICATION_SCOPE); if (!response.equals(captchaValue)) { createErrorMessage(event, this.getLocalizedText(req, "USER_CAPTCHA_MISMATCH")); throw new PortletException("captcha challenge mismatch!"); } log.debug("Exiting validateUser()"); } private boolean isInvalidPassword(ActionFormEvent event) { PortletRequest req = event.getActionRequest(); // Validate password String passwordValue = event.getPasswordBean("password").getValue(); String confirmPasswordValue = event.getPasswordBean("confirmPassword").getValue(); if (passwordValue == null) { createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_NOTSET")); return true; } // Otherwise, password must match confirmation if (!passwordValue.equals(confirmPasswordValue)) { createErrorMessage(event, (this.getLocalizedText(req, "USER_PASSWORD_MISMATCH")) + "<br />"); return true; // If they do match, then validate password with our service } else { passwordValue = passwordValue.trim(); if (passwordValue.length() == 0) { createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_BLANK")); return true; } if (passwordValue.length() < 5) { createErrorMessage(event, this.getLocalizedText(req, "USER_PASSWORD_TOOSHORT")); return true; } } return false; } private User saveUser(Request request) { log.debug("Entering saveUser()"); // Account request // Create edit account request User newuser = this.userManagerService.createUser(); // Edit account attributes newuser.setUserName(request.getAttribute("userName")); newuser.setFirstName(request.getAttribute("firstName")); newuser.setLastName(request.getAttribute("lastName")); newuser.setFullName(request.getAttribute("lastName") + ", " + request.getAttribute("firstName")); newuser.setEmailAddress(request.getAttribute("emailAddress")); newuser.setOrganization(request.getAttribute("organization")); long now = Calendar.getInstance().getTime().getTime(); newuser.setAttribute(User.CREATEDATE, String.valueOf(now)); // Submit changes this.userManagerService.saveUser(newuser); String savePasswds = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS); if (savePasswds.equals(Boolean.TRUE.toString())) { PasswordEditor editor = passwordManagerService.editPassword(newuser); String password = request.getAttribute("password"); editor.setValue(password); passwordManagerService.saveHashedPassword(editor); } // Save user role List<PortletRole> defaultRoles = roleService.getDefaultRoles(); for (PortletRole role : defaultRoles) { roleService.addUserToRole(newuser, role); } log.debug("Exiting saveUser()"); return newuser; } public void notifyNewUser(ActionFormEvent evt) throws PortletException { ActionRequest req = evt.getActionRequest(); ActionResponse res = evt.getActionResponse(); TextFieldBean emailTF = evt.getTextFieldBean("emailAddress"); // create a request Request request = requestService.createRequest(ACTIVATE_ACCOUNT_LABEL); long now = Calendar.getInstance().getTime().getTime(); request.setLifetime(new Date(now + REQUEST_LIFETIME)); // request.setUserID(user.getID()); request.setAttribute("userName", evt.getTextFieldBean("userName").getValue()); request.setAttribute("firstName", evt.getTextFieldBean("firstName").getValue()); request.setAttribute("lastName", evt.getTextFieldBean("lastName").getValue()); request.setAttribute("emailAddress", evt.getTextFieldBean("emailAddress").getValue()); request.setAttribute("organization", evt.getTextFieldBean("organization").getValue()); // put hashed pass in request String savePasswds = portalConfigService.getProperty(PortalConfigService.SAVE_PASSWORDS); if (savePasswds.equals(Boolean.TRUE.toString())) { String pass = evt.getPasswordBean("password").getValue(); pass = passwordManagerService.getHashedPassword(pass); request.setAttribute("password", pass); } requestService.saveRequest(request); MailMessage mailToUser = new MailMessage(); mailToUser.setSender(portalConfigService.getProperty(PortalConfigService.MAIL_FROM)); StringBuffer body = new StringBuffer(); String activateURL = activateAccountURL + "&reqid=" + request.getOid(); String denyURL = denyAccountURL + "&reqid=" + request.getOid(); // check if this account request should be approved by an administrator boolean accountApproval = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.ADMIN_ACCOUNT_APPROVAL)).booleanValue(); if (accountApproval) { String admin = portalConfigService.getProperty(PortalConfigService.PORTAL_ADMIN_EMAIL); mailToUser.setEmailAddress(admin); String mailSubject = portalConfigService.getProperty("LOGIN_ACCOUNT_APPROVAL_ADMIN_MAILSUBJECT"); if (mailSubject == null) mailSubject = getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ADMIN_MAILSUBJECT"); mailToUser.setSubject(mailSubject); String adminBody = portalConfigService.getProperty("LOGIN_ACCOUNT_APPROVAL_ADMIN_MAIL"); if (adminBody == null) adminBody = getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ADMIN_MAIL"); body.append(adminBody).append("\n\n"); body.append(getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ALLOW")).append("\n\n"); body.append(activateURL).append("\n\n"); body.append(getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_DENY")).append("\n\n"); body.append(denyURL).append("\n\n"); } else { mailToUser.setEmailAddress(emailTF.getValue()); String mailSubjectHeader = portalConfigService.getProperty("LOGIN_ACTIVATE_SUBJECT"); String loginActivateMail = portalConfigService.getProperty("LOGIN_ACTIVATE_BODY"); if (mailSubjectHeader == null) mailSubjectHeader = getLocalizedText(req, "LOGIN_ACTIVATE_SUBJECT"); mailToUser.setSubject(mailSubjectHeader); if (loginActivateMail == null) loginActivateMail = getLocalizedText(req, "LOGIN_ACTIVATE_MAIL"); body.append(loginActivateMail).append("\n\n"); body.append(activateURL).append("\n\n"); } body.append(getLocalizedText(req, "USERNAME")).append("\t"); body.append(evt.getTextFieldBean("userName").getValue()).append("\n"); body.append(getLocalizedText(req, "GIVENNAME")).append("\t"); body.append(evt.getTextFieldBean("firstName").getValue()).append("\n"); body.append(getLocalizedText(req, "FAMILYNAME")).append("\t"); body.append(evt.getTextFieldBean("lastName").getValue()).append("\n"); body.append(getLocalizedText(req, "ORGANIZATION")).append("\t"); body.append(evt.getTextFieldBean("organization").getValue()).append("\n"); body.append(getLocalizedText(req, "EMAILADDRESS")).append("\t"); body.append(evt.getTextFieldBean("emailAddress").getValue()).append("\n"); mailToUser.setBody(body.toString()); try { mailService.sendMail(mailToUser); } catch (PortletServiceException e) { createErrorMessage(evt, this.getLocalizedText(req, "LOGIN_FAILURE_MAIL")); throw new PortletException("Unable to send mail message!", e); } boolean adminRequired = Boolean.valueOf(portalConfigService.getProperty(PortalConfigService.ADMIN_ACCOUNT_APPROVAL)); if (adminRequired) { createSuccessMessage(evt, this.getLocalizedText(req, "LOGIN_ACCT_ADMIN_MAIL")); } else { createSuccessMessage(evt, this.getLocalizedText(req, "LOGIN_ACCT_MAIL")); } } private void doEmailAction(ActionFormEvent event, String msg, boolean createAccount) { ActionRequest req = event.getActionRequest(); ActionResponse res = event.getActionResponse(); String id = req.getParameter("reqid"); User user = null; Request request = requestService.getRequest(id, ACTIVATE_ACCOUNT_LABEL); if (request != null) { requestService.deleteRequest(request); String subject = ""; String body = ""; if (createAccount) { user = saveUser(request); createSuccessMessage(event, msg + " " + user.getUserName()); // send the user an email subject = portalConfigService.getProperty("LOGIN_ACCOUNT_APPROVAL_ACCOUNT_CREATED"); if (subject == null) subject = getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ACCOUNT_CREATED"); body = portalConfigService.getProperty("LOGIN_ACCOUNT_APPROVAL_ACCOUNT_CREATED_BODY"); if (body == null) body = getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ACCOUNT_CREATED"); } else { createSuccessMessage(event, msg); // send the user an email subject = portalConfigService.getProperty("LOGIN_ACCOUNT_APPROVAL_ACCOUNT_DENY"); if (subject == null) subject = getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ACCOUNT_DENY"); body = portalConfigService.getProperty("LOGIN_ACCOUNT_APPROVAL_ACCOUNT_DENY_BODY"); if (body == null) body = getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ACCOUNT_DENY"); } MailMessage mailToUser = new MailMessage(); mailToUser.setEmailAddress(user.getEmailAddress()); mailToUser.setSender(portalConfigService.getProperty(PortalConfigService.MAIL_FROM)); mailToUser.setSubject(subject); StringBuffer msgbody = new StringBuffer(); msgbody.append(body).append("\n\n"); msgbody.append(notificationURL); mailToUser.setBody(body.toString()); try { mailService.sendMail(mailToUser); } catch (PortletServiceException e) { log.error("Error: ", e); createErrorMessage(event, this.getLocalizedText(req, "LOGIN_FAILURE_MAIL")); } } setNextState(req, DEFAULT_VIEW_PAGE); } public void activate(ActionFormEvent event) { PortletRequest req = event.getActionRequest(); String msg = this.getLocalizedText(req, "USER_NEW_ACCOUNT") + "<br>" + this.getLocalizedText(req, "USER_PLEASE_LOGIN"); doEmailAction(event, msg, true); setNextState(req, "signup/activate.jsp"); } public void approveAccount(ActionFormEvent event) { PortletRequest req = event.getActionRequest(); String msg = this.getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ACCOUNT_CREATED"); doEmailAction(event, msg, true); setNextState(req, "signup/approveAccount.jsp"); } public void denyAccount(ActionFormEvent event) { PortletRequest req = event.getActionRequest(); String msg = this.getLocalizedText(req, "LOGIN_ACCOUNT_APPROVAL_ACCOUNT_DENY"); doEmailAction(event, msg, false); setNextState(req, "signup/denyAccount.jsp"); } }
package org.objectweb.proactive.p2p.core.service; import org.apache.log4j.Logger; import org.objectweb.proactive.ActiveObjectCreationException; import org.objectweb.proactive.Body; import org.objectweb.proactive.InitActive; import org.objectweb.proactive.ProActive; import org.objectweb.proactive.core.ProActiveException; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.node.NodeException; import org.objectweb.proactive.core.node.NodeFactory; import org.objectweb.proactive.core.runtime.ProActiveRuntime; import org.objectweb.proactive.core.runtime.RuntimeFactory; import org.objectweb.proactive.core.runtime.VMInformation; import org.objectweb.proactive.core.util.UrlBuilder; import org.objectweb.proactive.p2p.core.info.Info; import org.objectweb.proactive.p2p.core.service.KnownTable.KnownTableElement; import java.io.IOException; import java.io.Serializable; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collection; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.Vector; /** * Implemantation of P2P Service. * * @author Alexandre di Costanzo * */ public class P2PServiceImpl implements P2PService, InitActive, Serializable { protected static Logger logger = Logger.getLogger(P2PServiceImpl.class.getName()); private ProActiveRuntime runtime = null; private String acquisitionMethod = "rmi:"; private String portNumber = System.getProperty("proactive.rmi.port"); private KnownTable knownProActiveJVM = null; private String runtimeName = null; private int load = 0; private String peerHostname; private String peerUrl = null; private Info serviceInfo; private FakeProActiveRuntime fakeProActiveRuntime; /** * <p> * Create a ProActiveRuntime with defaults params. * </p> * <p> * Use RMI with default port number. * </p> */ public P2PServiceImpl() { // Empty Cronstructor } /** * <p> * Create a ProActiveRuntime * </p> * * @param acquisitionMethod * like "rmi:" * @param portNumber * like 2410 * @param createNode */ public P2PServiceImpl(String acquisitionMethod, String portNumber) { try { this.acquisitionMethod = acquisitionMethod; this.portNumber = portNumber; // URL String url = InetAddress.getLocalHost().getCanonicalHostName(); this.peerHostname = url; if (url.endsWith("/")) { url.replace('/', ' '); url.trim(); } url += (":" + this.portNumber); this.peerUrl = "//" + url; this.runtime = RuntimeFactory.getProtocolSpecificRuntime(this.acquisitionMethod); this.runtimeName = this.runtime.getURL(); this.serviceInfo = new Info(0, 0, this.getServiceName()); this.fakeProActiveRuntime = new FakeProActiveRuntime(); } catch (UnknownHostException e) { logger.error("Could't return the URL of this P2P Service "); } catch (ProActiveException e) { logger.error(e); } } // Privates and Protected Methods /** * Add the default name of the P2P Node to a specified <code>url</code>. * @param url the url. * @return the <code>url</code> with the name of the P2P Node. */ private static String urlAdderP2PNodeName(String url) { if (url.endsWith("/")) { url += P2PServiceImpl.P2P_NODE_NAME; } else { url += ("/" + P2PServiceImpl.P2P_NODE_NAME); } return url; } /** * Get the specified remote P2P Service. * * @param url * the url of the remote P2P Service. * @return the specified P2P Service. * @throws NodeException * @throws ActiveObjectCreationException */ protected static P2PService getRemoteP2PService(String url) throws NodeException, ActiveObjectCreationException { url = urlAdderP2PNodeName(url); Node node = NodeFactory.getNode(url); try { String runtimeUrl = node.getProActiveRuntime().getURL(); } catch (ProActiveException e) { logger.error("Can't get remote ProActiveRuntime URL of " + url); } P2PService p2p = (P2PService) node.getActiveObjects(P2PServiceImpl.class.getName())[0]; return p2p; } /** * * @param remoteUrl URL of a remote node. * @return The node pointed by the remoteUrl. * @throws NodeException * @throws ActiveObjectCreationException */ protected static Node getRemoteNode(String remoteUrl) throws NodeException, ActiveObjectCreationException { return NodeFactory.getNode(urlAdderP2PNodeName(remoteUrl)); } /** * * @param distNode Node upon we can find a remote p2pService * @return The runtime url where the node is located. * @throws NodeException * @throws ActiveObjectCreationException */ protected static String getRemoteProActiveRuntimeURL(Node distNode) throws NodeException, ActiveObjectCreationException { String runtimeUrl = ""; try { runtimeUrl = distNode.getProActiveRuntime().getURL(); } catch (ProActiveException e) { logger.error("Can't get remote ProActiveRuntime URL"); } return runtimeUrl; } /** * * @param distNode Node upon we can find a remote p2pService * @return The remote P2PService. * @throws NodeException If node is unavailable * @throws ActiveObjectCreationException */ protected static P2PService getRemoteP2PService(Node distNode) throws NodeException, ActiveObjectCreationException { return (P2PService) distNode.getActiveObjects(P2PServiceImpl.class.getName())[0]; } private ProActiveRuntime getRemoteProActiveRuntime() throws ProActiveException { return RuntimeFactory.getDefaultRuntime(); } /** * @see org.objectweb.proactive.p2p.core.service.P2PService#registerP2PServices(java.util.Collection) */ public void registerP2PServices(Collection servers) { Iterator it = servers.iterator(); while (it.hasNext()) { String currentServer = (String) it.next(); // Record the current server in this PAR this.registerP2PService(currentServer); } } /** * * @param myHostname Current hostname. * @param remoteUrl A remote url. */ public void registerP2PService(String remoteUrl) { // we should find an hostname matching this kind of pattern : hostname.inria.fr:PORT try { if (this.peerHostname.compareTo(UrlBuilder.removePortFromHost( UrlBuilder.getHostNameFromUrl(remoteUrl))) != 0) { P2PService dist; Node remoteP2PNode = P2PServiceImpl.getRemoteNode(remoteUrl); if ((dist = P2PServiceImpl.getRemoteP2PService(remoteP2PNode)) != null) { this.registerP2PService(P2PServiceImpl.getRemoteProActiveRuntimeURL( remoteP2PNode), dist.getInfo(), true); if (logger.isInfoEnabled()) { logger.info(this.getServiceName() + " has register " + remoteUrl); } } } } catch (NodeException e) { logger.error("Could't register the P2P Service in: " + remoteUrl + e.getMessage()); } catch (ActiveObjectCreationException e) { logger.error("No P2P Service was found in: " + remoteUrl); } catch (UnknownHostException e) { logger.error("Host unknown: " + remoteUrl); } } public void registerP2PService(String remoteProActiveRuntimeURL, Info distInfo, boolean remoteRecord) { KnownTableElement exist = (KnownTableElement) knownProActiveJVM.get(remoteProActiveRuntimeURL); if (exist != null) { exist.setLastUpdate(System.currentTimeMillis()); if (logger.isInfoEnabled()) { logger.info("Update ProActive JVM: " + remoteProActiveRuntimeURL); } } else { KnownTableElement element = this.knownProActiveJVM.new KnownTableElement(remoteProActiveRuntimeURL, distInfo); knownProActiveJVM.put(remoteProActiveRuntimeURL, element); if (logger.isInfoEnabled()) { logger.info("Add ProActive JVM: " + remoteProActiveRuntimeURL); } } if (remoteRecord) { P2PService distService; try { // we get remote service directly to avoid deadlock instead of // get it from the distInfo if ((distService = P2PServiceImpl.getRemoteP2PService(this.acquisitionMethod + " UrlBuilder.getHostNameAndPortFromUrl( remoteProActiveRuntimeURL))) != null) { distService.registerP2PService(this.getServiceName(), this.serviceInfo, false); if (logger.isInfoEnabled()) { logger.info(this.getServiceName() + " remote record" + remoteProActiveRuntimeURL); } } } catch (NodeException e) { logger.error("Could't register the P2P Service in: " + peerUrl + e.getMessage()); } catch (ActiveObjectCreationException e) { logger.error("No P2P Service was found in: " + peerUrl); } catch (UnknownHostException e) { logger.error("Cannot get the host from: " + remoteProActiveRuntimeURL); } } } /** * returninformation available for this peer such as name, load, stub */ public Info getInfo() { return this.serviceInfo; } /** * @see org.objectweb.proactive.p2p.core.service.P2PService#unregisterP2PService(java.lang.String) */ public void unregisterP2PService(String service) { this.knownProActiveJVM.remove(service); if (logger.isInfoEnabled()) { logger.info("Remove ProActive JVM: " + service); } } /** * @see org.objectweb.proactive.p2p.core.service.P2PService#unregisterP2PService(org.objectweb.proactive.p2p.core.service.P2PService) */ public void unregisterP2PService(P2PService service) { this.unregisterP2PService(service.getServiceName()); } /** * @see org.objectweb.proactive.p2p.core.service.P2PService#getProActiveJVMs(int) */ public ProActiveRuntime[] getProActiveJVMs(int n) throws ProActiveException { return this.getProActiveJVMs(n, P2PService.TTL); } /** * @see org.objectweb.proactive.p2p.core.service.P2PService#getProActiveJVMs(int, * int) */ public ProActiveRuntime[] getProActiveJVMs(int n, int TTL) throws ProActiveException { return this.getProActiveJVMs(n, TTL, new LinkedList()); } /** * @see org.objectweb.proactive.p2p.core.service.P2PService#getProActiveJVMs(int, * int, java.lang.String) */ public ProActiveRuntime[] getProActiveJVMs(int n, int TTL, LinkedList parentList) throws ProActiveException { return this.getProActiveJVMs(n, TTL, parentList, false); } public ProActiveRuntime[] getProActiveJVMs(int n, int TTL, LinkedList parentList, boolean internalUSe) throws ProActiveException { Hashtable res = new Hashtable(); KnownTableElement[] tmp = this.knownProActiveJVM.toArray(); LinkedList peerToContact = new LinkedList(); // adding "this" reference in the parent search path parentList.add(this.getServiceName()); int i = 0; while (i < tmp.length) { if (!parentList.contains(tmp[i].getKey())) { peerToContact.add(tmp[i]); } i++; } if (logger.isInfoEnabled()) { logger.info(this.getServiceName() + " knows " + tmp.length + " P2PNode, where " + peerToContact.size() + " are not parents, TTL is " + TTL); } KnownTableElement peerElement; Iterator it = peerToContact.iterator(); while (it.hasNext()) { peerElement = (KnownTableElement) it.next(); if (peerElement.getLoad() > 0) { if (logger.isInfoEnabled()) { logger.info(this.getServiceName() + " has selected " + peerElement.getKey() + " has a possible giveable JVM "); } Object tmpPar = peerElement.getP2PService().getProActiveRuntime(); Object par = ProActive.getFutureValue(tmpPar); if (par instanceof ProActiveRuntime) { VMInformation vmi = ((ProActiveRuntime) par).getVMInformation(); res.put(vmi.getName(), par); if (logger.isInfoEnabled()) { logger.info(this.getServiceName() + " has added " + peerElement.getKey() + " JVM to result list"); } } } } if ((res.size() >= n) || (TTL == 0)) { Vector resFinal = new Vector(res.values()); if (resFinal.size() >= n) { if (logger.isInfoEnabled()) { logger.info(this.getServiceName() + " has send back " + n + " JVM"); } return (ProActiveRuntime[]) resFinal.subList(0, n).toArray(new ProActiveRuntime[n]); } else if (TTL == 0) { if (logger.isInfoEnabled()) { logger.info(this.getServiceName() + " has send back " + resFinal.size() + " JVM"); } return (ProActiveRuntime[]) resFinal.toArray(new ProActiveRuntime[resFinal.size()]); } } it = peerToContact.iterator(); // asking to contact list peers for new JVM .... while ((res.size() < n) && (it.hasNext())) { P2PService current = ((KnownTableElement) it.next()).getP2PService(); ProActiveRuntime[] currentRes; try { String peerName = null; if (logger.isInfoEnabled()) { peerName = current.getServiceName(); logger.info(this.getServiceName() + " asking " + peerName + " for " + (n - res.size()) + " new source .... "); } currentRes = current.getProActiveJVMs(n - res.size(), TTL - 1, parentList); if (logger.isInfoEnabled()) { if (currentRes != null) { logger.info("Finnally " + peerName + " has return " + currentRes.length + " JVM"); } else { logger.info("Finnally " + peerName + " has return 0 JVM"); } } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Could't get JVMS", e); } continue; } if (currentRes != null) { for (int j = 0; j < currentRes.length; j++) { res.put(currentRes[j].getVMInformation().getName(), currentRes[j]); } } } // res.remove(this.runtimeName); Vector resFinal = new Vector(res.values()); if (resFinal.size() > n) { return (ProActiveRuntime[]) resFinal.subList(0, n).toArray(new ProActiveRuntime[n]); } else { return (ProActiveRuntime[]) resFinal.toArray(new ProActiveRuntime[resFinal.size()]); } } /** * @see org.objectweb.proactive.p2p.core.service.P2PService#getProActiveJVMs() */ public ProActiveRuntime[] getProActiveJVMs() throws ProActiveException { Vector res = new Vector(this.knownProActiveJVM.size()); Object[] table = this.knownProActiveJVM.toArray(); for (int i = 0; i < table.length; i++) { KnownTableElement elem = (KnownTableElement) table[i]; try { Object par = elem.getP2PService().getProActiveRuntime(); if (par instanceof ProActiveRuntime) { res.add(par); } } catch (Exception e) { // The remote is dead => remove from known table this.unregisterP2PService((String) elem.getKey()); } } return (ProActiveRuntime[]) res.toArray(new ProActiveRuntime[res.size()]); } /** * @see org.objectweb.proactive.p2p.core.service.P2PService#getProActiveRuntime() */ public Object getProActiveRuntime() { if (this.serviceInfo.getFreeLoad() > 0) { this.setLoad(this.serviceInfo.getFreeLoad() - 1); if (logger.isInfoEnabled()) { logger.info(this.getServiceName() + " give is ProActiveRuntime"); } return this.runtime; } else { // As it's not possible to return null when using Future we return a // FakeProActiveRuntime object if (logger.isInfoEnabled()) { logger.info(this.getServiceName() + " doesn't give is ProActiveRuntime because load is full"); } return this.fakeProActiveRuntime; } } /** * @return Returns the name of theis P2P Service. */ public String getServiceName() { return this.runtimeName; } /** * @see org.objectweb.proactive.p2p.core.service.P2PService#getProtocol() */ public String getProtocol() { return this.acquisitionMethod; } /** * @see org.objectweb.proactive.p2p.core.service.P2PService#getURL() */ public String getURL() { return this.peerUrl; } // Implements Load /** * @see org.objectweb.proactive.p2p.core.load.Load#setLoad(int) */ public void setLoad(int load) { this.serviceInfo.setFreeLoad(load); Object[] values = this.knownProActiveJVM.toArray(); for (int i = 0; i < values.length; i++) { P2PService service = ((KnownTableElement) values[i]).getP2PService(); service.registerP2PService(this.getServiceName(), this.serviceInfo, false); } } /** * @see org.objectweb.proactive.p2p.core.load.Load#getLoad() */ public int getLoad() { // !!! return MAXLOAD - currentLoad !!! return this.serviceInfo.getFreeLoad(); } public void printKnownPeer() { this.knownProActiveJVM.printKnownPeer(); } // Init Activity /** * @see org.objectweb.proactive.InitActive#initActivity(org.objectweb.proactive.Body) */ public void initActivity(Body body) { try { this.serviceInfo.setService((P2PService) ProActive.getStubOnThis()); // Create the known table this.knownProActiveJVM = (KnownTable) ProActive.newActive(KnownTable.class.getName(), null, P2PServiceImpl.urlAdderP2PNodeName(this.peerUrl)); ProActive.enableAC(this.knownProActiveJVM); // Launch a thread to update the known table. Object[] params = { this.knownProActiveJVM, ProActive.getStubOnThis(), this.getServiceName() }; ProActive.newActive(Updater.class.getName(), params, P2PServiceImpl.urlAdderP2PNodeName(this.peerUrl)); } catch (ActiveObjectCreationException e) { logger.error("Could't create the Updater"); } catch (NodeException e) { logger.error(e); } catch (IOException e) { logger.error(e); } } // Overrides Methods /** * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return (this.getServiceName().compareTo(((P2PService) obj).getServiceName()) == 0) ? true : false; } /** * This class is use as a possible return value for the method * getProActiveRuntime() We need it because the call to the method lead to * the creation of a future, so we can't return null if the p2pservice * doesn't want to give is runtime. We can use this class to store some * information about future availability of the peer ... * * @author vcave * * TODO To change the template for this generated type comment go to Window - * Preferences - Java - Code Style - Code Templates */ public class FakeProActiveRuntime implements Serializable { public FakeProActiveRuntime() { } } }
package com.coco.flowimageview; import android.content.Context; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.util.Log; import android.view.animation.LinearInterpolator; import android.widget.ImageView; import android.widget.Scroller; /** * Zaker style flow image view, it's image horizontal scrolling slowly, using as Zaker's main screen background. */ public class FlowImageView extends ImageView { private static final String TAG = "FlowImageView"; private static final boolean DEBUG = true; private static void DEBUG_LOG(String msg) { if (DEBUG) { Log.v(TAG, msg); } } private static final float MIN_FLOW_VELOCITY = 0.3333f; // dips per second private static final float DEFAULT_FLOW_VELOCITY = 0.6667f; // dips per second private static final int DEFAULT_EDGE_DELAY = 2000; private float mMinFlowVelocity; private float mFlowVelocity; private int mEdgeDelay = DEFAULT_EDGE_DELAY; private Scroller mScroller; private boolean mIsLayouted; private boolean mIsFlowInited; private boolean mIsFlowPositive = true; private boolean mFlowStarted; private Matrix mImageMatrix = new Matrix(); private float mScale; private float mTranslateX; private float mTranslateXEnd; private final Runnable mReverseFlowRunnable = new Runnable() { public void run() { mIsFlowPositive = !mIsFlowPositive; DEBUG_LOG("mReverseFlowRunnable mIsFlowPositive=" + mIsFlowPositive); startFlow(); } }; public FlowImageView(Context context) { super(context); initFlowImageView(); } public FlowImageView(Context context, AttributeSet attrs) { super(context, attrs); initFlowImageView(); } public FlowImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initFlowImageView(); } private void initFlowImageView() { setScaleType(ImageView.ScaleType.MATRIX); final Context context = getContext(); final float density = context.getResources().getDisplayMetrics().density; mMinFlowVelocity = MIN_FLOW_VELOCITY * density; mFlowVelocity = DEFAULT_FLOW_VELOCITY * density; mScroller = new Scroller(context, new LinearInterpolator()); } public float getFlowVelocity() { return mFlowVelocity; } /** * Setting flow velocity. * * @param flowVelocity * pixels per second */ public void setFlowVelocity(float flowVelocity) { if (flowVelocity < mMinFlowVelocity) { flowVelocity = mMinFlowVelocity; } mFlowVelocity = flowVelocity; restartFlow(); } public int getEdgeDelay() { return mEdgeDelay; } public void setEdgeDelay(int edgeDelay) { if (edgeDelay < 0) { edgeDelay = 0; } mEdgeDelay = edgeDelay; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); mIsLayouted = false; startFlow(); } @Override protected void onDetachedFromWindow() { mIsLayouted = false; stopFlow(); super.onDetachedFromWindow(); } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(hasWindowFocus); DEBUG_LOG("onWindowFocusChanged hasWindowFocus=" + hasWindowFocus); if (hasWindowFocus) { startFlow(); } else { stopFlow(); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); DEBUG_LOG("onLayout changed=" + changed + ", left=" + left + ", top=" + top + ", right=" + right + ", bottom=" + bottom); mIsLayouted = true; initFlow(); startFlow(); } private void initFlow() { if (!mIsLayouted) { return; } Drawable drawable = getDrawable(); if (drawable != null) { final float viewWidth = getWidth(); final float viewHeight = getHeight(); final float imgWidth = drawable.getIntrinsicWidth(); final float imgHeight = drawable.getIntrinsicHeight(); mScale = viewHeight / imgHeight; mTranslateXEnd = viewWidth - imgWidth * mScale; mIsFlowInited = true; } } private void restartFlow() { if (mFlowStarted) { startFlow(); } } private void startFlow() { if (!mIsLayouted || !mIsFlowInited) { return; } final int sx = (int) mTranslateX; final int dx = (int) ((mIsFlowPositive ? mTranslateXEnd : 0) - mTranslateX); if (dx == 0) { getHandler().removeCallbacks(mReverseFlowRunnable); getHandler().post(mReverseFlowRunnable); return; } final int duration = (int) Math.abs(dx / mFlowVelocity * 1000); DEBUG_LOG("startFlow mIsFlowPositive=" + mIsFlowPositive + ", mTranslateX=" + mTranslateX + ", mTranslateXEnd=" + mTranslateXEnd + ", sx=" + sx + ", dx=" + dx + ", duration=" + duration); mScroller.abortAnimation(); mScroller.startScroll(sx * 100, 0, dx * 100, 0, duration); ViewCompat.postInvalidateOnAnimation(this); mFlowStarted = true; } private void stopFlow() { mScroller.abortAnimation(); if (getHandler() != null) { getHandler().removeCallbacks(mReverseFlowRunnable); } mFlowStarted = false; } @Override public void computeScroll() { if (!mIsLayouted || !mIsFlowInited || !mFlowStarted) { return; } if (!mScroller.isFinished() && mScroller.computeScrollOffset()) { mTranslateX = mScroller.getCurrX() / 100f; DEBUG_LOG("computeScroll mTranslateX=" + mTranslateX); setImageMatrix(); // Keep on drawing until the animation has finished. ViewCompat.postInvalidateOnAnimation(this); return; } // Done with scroll, clean up state. getHandler().removeCallbacks(mReverseFlowRunnable); getHandler().postDelayed(mReverseFlowRunnable, mEdgeDelay); } private void setImageMatrix() { mImageMatrix.reset(); mImageMatrix.postScale(mScale, mScale); mImageMatrix.postTranslate(mTranslateX, 0); setImageMatrix(mImageMatrix); } }
package imj3.draft.machinelearning; import imj3.draft.machinelearning.NearestNeighborClassifier.Prototype; import java.util.List; /** * Clusters data by reading each element only once. * * @author codistmonk (creation 2015-02-04) */ public final class StreamingClustering extends NearestNeighborClustering { public StreamingClustering(final Measure measure, final int clusterCount) { super(measure, clusterCount); } @Override public final void cluster(final DataSource<?, ?> inputs, final NearestNeighborClassifier classifier) { final int k = this.getClusterCount(); final List<Prototype> prototypes = classifier.getPrototypes(); final Classification<Prototype> tmp = new Classification<>(); for (final Classification<?> classification : inputs) { final int n = prototypes.size(); // XXX should the weights be considered instead of performing a normal classification? final Classification<Prototype> c = classifier.classify(tmp, classification.getInput()); if (c == null) { throw new NullPointerException(); } if (0.0 != c.getScore() && n < k) { prototypes.add(new Prototype(c.getInput().clone()).setClassIndex(n)); } else if (0.0 == c.getScore()) { c.getClassifierClass().updateWeight(1.0); } else { final Prototype prototype = c.getClassifierClass(); mergeInto(prototype.toArray(), prototype.getWeight(), c.getInput(), 1.0); prototype.updateWeight(1.0); } } } private static final long serialVersionUID = 1208345425946241729L; public static final void mergeInto(final double[] v1, final double w1, final double[] v2, final double w2) { final int n = v1.length; final double w = w1 + w2; for (int i = 0; i < n; ++i) { v1[i] = (v1[i] * w1 + v2[i] * w2) / w; } } }
package circlebinder.common.event; import android.os.Parcel; import android.os.Parcelable; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import circlebinder.common.checklist.ChecklistColor; public final class Circle implements Parcelable { public static class Builder { private int id; private Space space; private Genre genre; private ChecklistColor checklistColor; private String name; private String penName; private List<CircleLink> links; private boolean checked; private String freeMemo; public Builder() { links = new CopyOnWriteArrayList<CircleLink>(); } public Builder(Builder builder) { id = builder.id; space = builder.space; genre = builder.genre; checklistColor = builder.checklistColor; name = builder.name; penName = builder.penName; links = builder.links; freeMemo = builder.freeMemo; } public Circle build() { return new Circle(this); } public Builder addLink(CircleLink link) { this.links.add(link); return this; } public Builder setLink(CircleLink link) { this.links.clear(); this.links.add(link); return this; } public Builder setPenName(String penName) { this.penName = penName; return this; } public Builder setName(String name) { this.name = name; return this; } public Builder setChecklistColor(ChecklistColor checklistColor) { this.checklistColor = checklistColor; return this; } public Builder setGenre(Genre genre) { this.genre = genre; return this; } public Builder setSpace(Space space) { this.space = space; return this; } public Builder setId(int id) { this.id = id; return this; } public Builder setChecked(boolean checked) { this.checked = checked; return this; } public Builder setFreeMemo(String freeMemo) { this.freeMemo = freeMemo; return this; } public Builder clear() { id = 0; space = null; genre = null; checklistColor = null; name = null; penName = null; links.clear(); checked = false; freeMemo = null; return this; } } private final int id; private final Space space; private final Genre genre; private final ChecklistColor checklistColor; private final String name; private final String penName; private final CircleLinks links; private final boolean checked; private final String freeMemo; private Circle(Builder builder) { id = builder.id; space = builder.space; genre = builder.genre; checklistColor = builder.checklistColor; name = builder.name; penName = builder.penName; links = new CircleLinks(builder.links); checked = builder.checked; freeMemo = builder.freeMemo; } public int getId() { return id; } public Space getSpace() { return space; } public Genre getGenre() { return genre; } public ChecklistColor getChecklistColor() { return checklistColor; } public String getName() { return name; } public String getPenName() { return penName; } public CircleLinks getLinks() { return links; } public boolean isChecked() { return checked; } public String getFreeMemo() { return freeMemo; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.id); dest.writeParcelable(this.space, 0); dest.writeParcelable(this.genre, 0); dest.writeInt(this.checklistColor == null ? -1 : this.checklistColor.ordinal()); dest.writeString(this.name); dest.writeString(this.penName); dest.writeParcelable(this.links, 0); dest.writeByte(checked ? (byte) 1 : (byte) 0); dest.writeString(this.freeMemo); } private Circle(Parcel in) { this.id = in.readInt(); this.space = in.readParcelable(Space.class.getClassLoader()); this.genre = in.readParcelable(Genre.class.getClassLoader()); int tmpChecklistColor = in.readInt(); this.checklistColor = tmpChecklistColor == -1 ? null : ChecklistColor.values()[tmpChecklistColor]; this.name = in.readString(); this.penName = in.readString(); this.links = in.readParcelable(CircleLinks.class.getClassLoader()); this.checked = in.readByte() != 0; this.freeMemo = in.readString(); } public static Creator<Circle> CREATOR = new Creator<Circle>() { public Circle createFromParcel(Parcel source) { return new Circle(source); } public Circle[] newArray(int size) { return new Circle[size]; } }; }
package com.namelessdev.mpdroid; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.widget.ArrayAdapter; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.ActionBar.OnNavigationListener; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuItem; import com.namelessdev.mpdroid.fragments.AlbumsFragment; import com.namelessdev.mpdroid.fragments.ArtistsFragment; import com.namelessdev.mpdroid.fragments.FSFragment; import com.namelessdev.mpdroid.fragments.PlaylistsFragment; import com.namelessdev.mpdroid.fragments.StreamsFragment; public class LibraryTabActivity extends SherlockFragmentActivity implements OnNavigationListener { /** * The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the * sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will * keep every loaded fragment in memory. If this becomes too memory intensive, it may be best * to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}. */ SectionsPagerAdapter mSectionsPagerAdapter; /** * The {@link ViewPager} that will host the section contents. */ ViewPager mViewPager; @TargetApi(11) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.library_tabs); // Create the adapter that will return a fragment for each of the three primary sections // of the app. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the action bar. final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setDisplayShowTitleEnabled(false); actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); ArrayAdapter<CharSequence> actionBarAdapter = new ArrayAdapter<CharSequence>(this, R.layout.sherlock_spinner_item); actionBarAdapter.add(getString(R.string.artists)); actionBarAdapter.add(getString(R.string.albums)); actionBarAdapter.add(getString(R.string.playlists)); actionBarAdapter.add(getString(R.string.streams)); actionBarAdapter.add(getString(R.string.files)); if(Build.VERSION.SDK_INT >= 14) { //Bug on ICS with sherlock's layout actionBarAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } else { actionBarAdapter.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item); } actionBar.setListNavigationCallbacks(actionBarAdapter, this); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); // When swiping between different sections, select the corresponding tab. // We can also use ActionBar.Tab#select() to do this if we have a reference to the // Tab. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); } @Override public void onStart() { super.onStart(); MPDApplication app = (MPDApplication) getApplicationContext(); app.setActivity(this); } @Override public void onStop() { super.onStop(); MPDApplication app = (MPDApplication) getApplicationContext(); app.unsetActivity(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getSupportMenuInflater().inflate(R.menu.mpd_browsermenu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: this.onSearchRequested(); return true; case android.R.id.home: finish(); return true; } return false; } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { mViewPager.setCurrentItem(itemPosition); return true; } /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary * sections of the app. */ public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int i) { Fragment fragment = null; switch (i) { case 0: fragment = new ArtistsFragment(); break; case 1: fragment = new AlbumsFragment(); break; case 2: fragment = new PlaylistsFragment(); break; case 3: fragment = new StreamsFragment(); break; case 4: fragment = new FSFragment(); break; } return fragment; } @Override public int getCount() { return 5; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return getString(R.string.artists); case 1: return getString(R.string.albums); case 2: return getString(R.string.playlists); case 3: return getString(R.string.streams); case 4: return getString(R.string.files); } return null; } } }
package asa.controller; import asa.bean.Appointment; import asa.service.AppointmentService; import org.springframework.web.bind.annotation.*; import org.springframework.http.MediaType; import org.springframework.beans.factory.annotation.Autowired; import java.util.*; @RestController @RequestMapping("/appointment") public class AppointmentController { @Autowired private AppointmentService appointmentService; @RequestMapping(method = RequestMethod.GET) public @ResponseBody Map<String,Object> view(){ Map<String,Object> map=new HashMap<>(); System.out.println("Inside AppointmentController"); List<Appointment> list= appointmentService.get(); System.out.println("Length :"+list.size()); if(list.size()!=0){ map.put("result",new String("success")); map.put("list",list); } else{ map.put("result",new String("failed")); } return map; } @RequestMapping(method = RequestMethod.GET) public @ResponseBody Map<String,Object> viewByDate(@RequestParam("date") String date){ Map<String,Object> map=new HashMap<>(); System.out.println("Inside AppointmentController"); List<Appointment> list= appointmentService.getByDate(date); System.out.println("Length :"+list.size()); if(list.size()!=0){ map.put("result",new String("success")); map.put("list",list); } else{ map.put("result",new String("failed")); } return map; } @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody Map<String,String> add(@RequestBody Appointment appointment){ Map<String,String> map=new HashMap<>(); if(appointmentService.add(appointment)){ map.put("result","success"); } else{ map.put("result","failed"); } return map; } /* @RequestMapping(value="/test",method = RequestMethod.GET) public @ResponseBody Map<String,String> addTest(){ System.out.println("Inside AppointmentController POST TEST"); Map<String,String> map=new HashMap<>(); if(appointmentService.add(appointment)){ map.put("result","success"); } else{ map.put("result","failed"); } return map; } */ }
package br.ufmg.dcc.labsoft.apidiff; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.List; import java.util.Map; public class UtilFile { /** * Imprime a lista em uma arquivo. Cada item em uma linha. * @param nameFile * @param listMsg */ public static void writeFile(final String nameFile, final List<String> listMsg){ try { Writer writer = new BufferedWriter(new OutputStreamWriter (new FileOutputStream(nameFile, true), "utf-8")); for(String msg: listMsg){ writer.write(msg + "\n"); } writer.close(); } catch (IOException e) { System.err.println("Erro ao escrever resultado no arquivo de saida. " + e); } } public static Map<String, String> readCSV(final String nameFile) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(nameFile)); String SEPARATOR = ";"; String line = ""; Map<String, String> result = new HashMap<String, String>(); try { while ((line = br.readLine()) != null){ String [] data = line.split(SEPARATOR); if(data.length == 2){ result.put(data[0], data[1]); } else{ System.err.println("File format invalid! " + line); } } } finally { br.close(); } return result; } }
package org.kaazing.robot.driver; import static org.jboss.netty.channel.Channels.pipeline; import static org.jboss.netty.channel.Channels.pipelineFactory; import static org.jboss.netty.util.CharsetUtil.UTF_8; import static org.kaazing.robot.driver.netty.bootstrap.BootstrapFactory.newBootstrapFactory; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.ChildChannelStateEvent; import org.jboss.netty.channel.DefaultChannelFuture; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.jboss.netty.channel.group.ChannelGroupFuture; import org.jboss.netty.channel.group.ChannelGroupFutureListener; import org.jboss.netty.channel.group.DefaultChannelGroup; import org.jboss.netty.channel.local.DefaultLocalClientChannelFactory; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.kaazing.robot.driver.behavior.Configuration; import org.kaazing.robot.driver.behavior.PlayBackScript; import org.kaazing.robot.driver.behavior.RobotCompletionFuture; import org.kaazing.robot.driver.behavior.RobotCompletionFutureImpl; import org.kaazing.robot.driver.behavior.handler.CompletionHandler; import org.kaazing.robot.driver.behavior.parser.Parser; import org.kaazing.robot.driver.behavior.visitor.GatherStreamsLocationVisitor; import org.kaazing.robot.driver.behavior.visitor.GenerateConfigurationVisitor; import org.kaazing.robot.driver.netty.bootstrap.BootstrapFactory; import org.kaazing.robot.driver.netty.bootstrap.ClientBootstrap; import org.kaazing.robot.driver.netty.bootstrap.ServerBootstrap; import org.kaazing.robot.driver.netty.channel.CompositeChannelFuture; import org.kaazing.robot.lang.LocationInfo; import org.kaazing.robot.lang.ast.AstScriptNode; import org.kaazing.robot.lang.parser.ScriptParser; public class Robot { private static final InternalLogger LOGGER = InternalLoggerFactory.getInstance(Robot.class); /* * A list of completion futures that will indicate that the script is completed. Each stream except for a AcceptNode has * a completion handler. The completion handler's handlerFuture is the complete future */ private final List<ChannelFuture> completionFutures = new ArrayList<>(); private final List<LocationInfo> progressInfos = new ArrayList<>(); private final Map<LocationInfo, Object> serverLocations = new HashMap<>(); private final List<ChannelFuture> bindFutures = new ArrayList<>(); private final List<ChannelFuture> connectFutures = new ArrayList<>(); private final Channel channel = new DefaultLocalClientChannelFactory().newChannel(pipeline(new SimpleChannelHandler())); private final ChannelFuture startedFuture = Channels.future(channel); private final RobotCompletionFutureImpl finishedFuture = new RobotCompletionFutureImpl(channel, true); private final DefaultChannelGroup serverChannels = new DefaultChannelGroup(); private final DefaultChannelGroup clientChannels = new DefaultChannelGroup(); private final Map<LocationInfo, Throwable> failedCauses = new HashMap<>(); private String expectedScript; private Configuration configuration; private AstScriptNode scriptAST; private ChannelFuture preparedFuture; private volatile boolean destroyed; private final BootstrapFactory bootstrapFactory; private final boolean releaseBootstrapFactory; // tests public Robot() { this(newBootstrapFactory(), true); } public Robot(BootstrapFactory bootstrapFactory) { this(bootstrapFactory, false); } private Robot(BootstrapFactory bootstrapFactory, boolean releaseBootstrapFactory) { this.bootstrapFactory = bootstrapFactory; this.releaseBootstrapFactory = releaseBootstrapFactory; listenForFinishedFuture(); } public RobotCompletionFuture getScriptCompleteFuture() { return finishedFuture; } public ChannelFuture getPreparedFuture() { return preparedFuture; } public ChannelFuture getStartedFuture() { return startedFuture; } public ChannelFuture prepare(String script) throws Exception { if (preparedFuture != null) { throw new IllegalStateException("Script already prepared"); } this.expectedScript = script; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Expected script:\n" + expectedScript); } final ScriptParser parser = new Parser(); scriptAST = parser.parse(new ByteArrayInputStream(expectedScript.getBytes(UTF_8))); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Parsed script:\n" + scriptAST); } final GenerateConfigurationVisitor visitor = new GenerateConfigurationVisitor(bootstrapFactory); configuration = scriptAST.accept(visitor, new GenerateConfigurationVisitor.State()); preparedFuture = bindServers(); /* Iterate over the set of completion handlers. */ for (final CompletionHandler h : configuration.getCompletionHandlers()) { /* Add the completion future */ final ChannelFuture f = h.getHandlerFuture(); completionFutures.add(f); /* * Listen for each completion future and grab its location info. * This is the last command or event (not implicit) that * succeeds */ f.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { LocationInfo location = h.getProgressInfo(); /* * An accept or connect that never connected will have a * null location. Don't include these. */ if (location != null) { progressInfos.add(location); } Throwable cause = future.getCause(); if (cause != null) { failedCauses.put(h.getStreamStartLocation(), cause); } } }); } // We start listening before start because one can abort before start. listenForScriptCompletion(); return preparedFuture; } public ChannelFuture prepareAndStart(String script) throws Exception { ChannelFuture prepareFuture = prepare(script); prepareFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { start(); } }); return startedFuture; } public ChannelFuture start() throws Exception { if (preparedFuture == null || !preparedFuture.isSuccess()) { throw new IllegalStateException("Script has not been prepared or is still preparing"); } else if (startedFuture.isDone()) { throw new IllegalStateException("Script has already been started"); } /* Connect to any clients */ for (final ClientBootstrap client : configuration.getClientBootstraps()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("[id: ] connect " + client.getOption("remoteAddress")); } ChannelFuture connectFuture = client.connect(); connectFutures.add(connectFuture); clientChannels.add(connectFuture.getChannel()); } /* * If we have no completion futures it means that there was an error or * otherwise we have the null script */ if (completionFutures.isEmpty() && !scriptAST.toString().equals("")) { throw new RobotException("No Completion Futures exists"); } startedFuture.setSuccess(); return startedFuture; } public RobotCompletionFuture abort() { if (!finishedFuture.isDone()) { finishedFuture.cancel(); } return finishedFuture; } public boolean isDestroyed() { return destroyed; } public boolean destroy() { if (destroyed) { return true; } abort(); if (releaseBootstrapFactory) { try { bootstrapFactory.releaseExternalResources(); } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Caught exception releasing resources", e); } return false; } } return destroyed = true; } private void listenForScriptCompletion() { /* * OK. Now listen for the set of all completion futures so that we can * tell the client when we are done */ ChannelFuture executionFuture = new CompositeChannelFuture<>(channel, completionFutures); executionFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { /* * We need to map our progressInfos to streams so that we can create the observed script. After running the * GatherStreamsLocationVisitor our results are in state.results. */ final GatherStreamsLocationVisitor.State state = new GatherStreamsLocationVisitor.State(progressInfos, serverLocations); scriptAST.accept(new GatherStreamsLocationVisitor(), state); // Create observed Script PlayBackScript o = new PlayBackScript(expectedScript, state.results, failedCauses); String observedScript = o.createPlayBackScript(); detachAllPipelines(); // Cancel any pending binds and connects for (ChannelFuture f : bindFutures) { f.cancel(); } for (ChannelFuture f : connectFutures) { f.cancel(); } // Close server and client channels closeChannels(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Observed script:\n" + observedScript); } if (finishedFuture.isDone()) { finishedFuture.setExpectedScript(expectedScript); finishedFuture.setObservedScript(observedScript); } else { finishedFuture.setSuccess(observedScript, expectedScript); } } }); } // If we are canceling we have to cancel the script execution. // And then ... in all cases we need to release external resources. private void listenForFinishedFuture() { finishedFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isCancelled()) { if (configuration != null) { for (final CompletionHandler h : configuration.getCompletionHandlers()) { // Cancel the completion handler ChannelFuture cancelFuture = h.cancel(); boolean isDefaultChannelFuture = cancelFuture instanceof DefaultChannelFuture; // Edge case. Normally the cancel occurs immediately. Only when the pipeline is not // prepared (preperation event) does it not. // Since we are aborting we don't care that we are blocking in the io thread. if (isDefaultChannelFuture) { DefaultChannelFuture.setUseDeadLockChecker(false); } boolean isCancelled = cancelFuture.awaitUninterruptibly(500); if (isDefaultChannelFuture) { DefaultChannelFuture.setUseDeadLockChecker(true); } if (!isCancelled) { // Force the completion handler future to success if it does not cancel in half a second h.getHandlerFuture().setSuccess(); } } } else { // Then we just get the empty script LOGGER.debug("Abort received but script not prepared"); finishedFuture.setObservedScript(""); } } } }); } private void detachAllPipelines() { // We need some kind of handler to avoid warnings. ChannelHandler finalHandler = new SimpleChannelHandler() { @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { Channel channel = ctx.getChannel(); channel.close(); } }; /* * Set the pipelines to empty just in case some one trys to connect before we close the server channel Or just in * case one of the client bootstraps havent connected yet ... dont think that is poosible */ for (ServerBootstrap bootstrap : configuration.getServerBootstraps()) { bootstrap.setPipelineFactory(pipelineFactory(pipeline(finalHandler))); } for (ClientBootstrap bootstrap : configuration.getClientBootstraps()) { bootstrap.setPipelineFactory(pipelineFactory(pipeline(finalHandler))); } /* * Remove all the handlers from any existing channels. The problem we are solving here is that when a script is * aborted we set the pipeline future of the completion handler to success. However, this does not cause earlier * pipeline futures to succeed. As such if there are any barriers. A subsequent close will end up getting queued and * will never end. Another option would be when be to cancel the pipeline future. And make that cancel on a composite * cancel all its containing futures. However, it does not seem right to do that for cancel, but not setSuccess and * setFailure. But maybe we can do that too. But ... removing all the handlers seems cleaner anyway. Why have events * flowing through the system do to us closing the channels when the script is already considered complete. */ for (Channel c : clientChannels) { ChannelPipeline pipeline = c.getPipeline(); for (ChannelHandler handler : pipeline.toMap().values()) { pipeline.remove(handler); } pipeline.addLast("SCRIPTDONEHANDLER", finalHandler); } } private void closeChannels() { final ChannelGroupFuture closeFuture = serverChannels.close(); closeFuture.addListener(new ChannelGroupFutureListener() { @Override public void operationComplete(final ChannelGroupFuture future) { clientChannels.close(); } }); } private ChannelFuture bindServers() { /* Accept's ... Robot acting as a server */ for (final ServerBootstrap server : configuration.getServerBootstraps()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Binding to address " + server.getOption("localAddress")); } final LocationInfo location = (LocationInfo) server.getOption("locationInfo"); assert !serverLocations.containsKey(location) : "There is already a location " + location + " for this server " + server.getOption("localAddress"); /* Keep track of the client channels */ server.setParentHandler(new SimpleChannelHandler() { @Override public void childChannelOpen(ChannelHandlerContext ctx, ChildChannelStateEvent e) throws Exception { clientChannels.add(e.getChildChannel()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { Channel channel = ctx.getChannel(); channel.close(); } }); // Bind Asynchronously ChannelFuture bindFuture = server.bindAsync(); // Add to out serverChannel Group serverChannels.add(bindFuture.getChannel()); // Add to our list of bindFutures so we can cancel them later on a possible abort bindFutures.add(bindFuture); // Listen for the bindFuture. bindFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { final boolean isDebugEnabled = LOGGER.isDebugEnabled(); if (future.isSuccess()) { if (isDebugEnabled) { LOGGER.debug("Successfully bound to " + server.getOption("localAddress")); } // Add to our list of serverLocations ... which contain the locationInfo's of successfully bound // server channels serverLocations.put((LocationInfo) server.getOption("locationInfo"), null); } else { Throwable cause = future.getCause(); /* * Grab the set of completion handlers for the server. This is the set of completion futures for the * Accept stream. */ @SuppressWarnings("unchecked") final Collection<ChannelFuture> serverCompletionFutures = (Collection<ChannelFuture>) server.getOption("completionFutures"); /* Set all the futures to fail. If we couldn't bind */ for (ChannelFuture f : serverCompletionFutures) { f.setFailure(cause); } } } }); } // What should prepared mean ... server channels have all completed binding or just that they started. // Initially I was thinking that it should be when they are done. But I'm not so sure. // In that case what should happen if a subset of the binds fail and a subset succeed? What should happen if they all // fail? I think in either case the robot should generate an observed script with the exception events in place of // the accept lines. This is why I choose to return a successful future rather than some composite of the bind // futures. return Channels.succeededFuture(channel); } }
package ch.bind.philib.validation; import java.util.Collection; /** * @author Philipp Meinen */ public abstract class Validation { protected Validation() { } public static void notNegative(int value) { if (value < 0) { throw new IllegalArgumentException("value must not be negative"); } } public static void notNegative(int value, String message) { if (value < 0) { throw new IllegalArgumentException(message); } } public static void notNegative(long value) { if (value < 0) { throw new IllegalArgumentException("value must not be negative"); } } public static void notNegative(long value, String message) { if (value < 0) { throw new IllegalArgumentException(message); } } public static void notNull(Object obj) { if (obj == null) { throw new IllegalArgumentException("object must not be null"); } } public static void notNull(Object obj, String message) { if (obj == null) { throw new IllegalArgumentException(message); } } public static void isTrue(boolean value) { if (!value) { throw new IllegalArgumentException("value must be true"); } } public static void isTrue(boolean value, String message) { if (!value) { throw new IllegalArgumentException(message); } } public static void isFalse(boolean value) { if (value) { throw new IllegalArgumentException("value must be false"); } } public static void isFalse(boolean value, String message) { if (value) { throw new IllegalArgumentException(message); } } public static void notNullOrEmpty(CharSequence value) { notNullOrEmpty(value, "null or empty string provided"); } public static void notNullOrEmpty(CharSequence value, String message) { if (value == null || value.length() == 0) { throw new IllegalArgumentException(message); } } public static void notNullOrEmpty(Collection<?> value) { notNullOrEmpty(value, "null or empty collection provided"); } public static void notNullOrEmpty(Collection<?> value, String message) { if (value == null || value.isEmpty()) { throw new IllegalArgumentException(message); } } public static <T> void notNullOrEmpty(T[] value) { notNullOrEmpty(value, "null or empty array provided"); } public static <T> void notNullOrEmpty(T[] value, String message) { if (value == null || value.length == 0) { throw new IllegalArgumentException(message); } } public static <T> void noNullValues(T[] values) { noNullValues(values, "array must only contain non-null values"); } public static <T> void noNullValues(T[] values, String message) { for (T v : values) { notNull(v, message); } } }
package com.axiastudio.zoefx.core.db; import java.util.List; import java.util.Map; public interface Manager<E> { Object getId(E entity); E save(E entity); void save(List<E> entities); void delete(E entity); void deleteRow(Object row); void truncate(); E get(Long id); List<E> getAll(); List<E> query(); List<E> query(Integer size); List<E> query(Integer size, Integer startindex); List<E> query(String orderby); List<E> query(String orderby, Boolean reverse); List<E> query(List<String> orderby); List<E> query(List<String> orderby, List<Boolean> reverse); List<E> query(String orderby, Integer size); List<E> query(List<String> orderby, Integer size); List<E> query(String orderby, Boolean reverse, Integer size); List<E> query(List<String> orderby, List<Boolean> reverse, Integer size); List<E> query(String orderby, Integer size, Integer startindex); List<E> query(List<String> orderby, Integer size, Integer startindex); List<E> query(String orderby, Boolean reverse, Integer size, Integer startindex); List<E> query(List<String> orderby, List<Boolean> reverse, Integer size, Integer startindex); List<E> query(Map<String, Object> map); List<E> query(Map<String, Object> map, Integer size); List<E> query(Map<String, Object> map, Integer size, Integer startindex); List<E> query(Map<String, Object> map, String orderby); List<E> query(Map<String, Object> map, String orderby, Boolean reverse); List<E> query(Map<String, Object> map, List<String> orderby); List<E> query(Map<String, Object> map, List<String> orderby, List<Boolean> reverse); List<E> query(Map<String, Object> map, String orderby, Integer size); List<E> query(Map<String, Object> map, List<String> orderby, Integer size); List<E> query(Map<String, Object> map, String orderby, Boolean reverse, Integer size); List<E> query(Map<String, Object> map, List<String> orderby, List<Boolean> reverse, Integer size); List<E> query(Map<String, Object> map, String orderby, Integer size, Integer startindex); List<E> query(Map<String, Object> map, List<String> orderby, Integer size, Integer startindex); List<E> query(Map<String, Object> map, String orderby, Boolean reverse, Integer size, Integer startindex); List<E> query(Map<String, Object> map, List<String> orderby, List<Boolean> reverse, Integer size, Integer startindex); E create(); Object createRow(String collectionName); }
package com.bio4j.model.uniprot; import com.bio4j.model.uniprot.vertices.*; import com.bio4j.model.uniprot.edges.*; import com.bio4j.model.uniprot_enzymedb.UniProtEnzymeDBGraph; import com.bio4j.model.uniprot_go.UniProtGoGraph; import com.bio4j.model.uniprot_ncbiTaxonomy.UniProtNCBITaxonomyGraph; import com.bio4j.model.uniprot_uniref.UniProtUniRefGraph; import com.bio4j.angulillos.*; import java.util.Date; public abstract class UniProtGraph< // untyped graph I extends UntypedGraph<RV, RVT, RE, RET>, // vertices RV, RVT, // edges RE, RET > implements TypedGraph< UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > { protected I raw = null; public UniProtGraph(I graph){ raw = graph; } public I raw(){ return raw; } public abstract UniProtUniRefGraph<I,RV,RVT,RE,RET> uniProtUniRefGraph(); public abstract UniProtGoGraph<I,RV,RVT,RE,RET> uniProtGoGraph(); public abstract UniProtEnzymeDBGraph<I,RV,RVT,RE,RET> uniProtEnzymeDBGraph(); public abstract UniProtNCBITaxonomyGraph<I,RV,RVT,RE,RET> uniProtNCBITaxonomyGraph(); // indices public abstract TypedVertexIndex.Unique < // vertex AlternativeProduct<I,RV,RVT,RE,RET>, AlternativeProductType, // property AlternativeProductType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > alternativeProductNameIndex(); public abstract TypedVertexIndex.Unique < // vertex GeneLocation<I,RV,RVT,RE,RET>, GeneLocationType, // property GeneLocationType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > geneLocationNameIndex(); public abstract TypedVertexIndex.Unique < // vertex GeneName<I,RV,RVT,RE,RET>, GeneNameType, // property GeneNameType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > geneNameNameIndex(); public abstract TypedVertexIndex.Unique < // vertex Disease<I,RV,RVT,RE,RET>, DiseaseType, // property DiseaseType.id, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > diseaseIdIndex(); public abstract TypedVertexIndex.Unique < // vertex Journal<I,RV,RVT,RE,RET>, JournalType, // property JournalType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > journalNameIndex(); public abstract TypedVertexIndex.Unique < // vertex Article<I,RV,RVT,RE,RET>, ArticleType, // property ArticleType.title, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > articleTitleIndex(); public abstract TypedVertexIndex.Unique < // vertex OnlineJournal<I,RV,RVT,RE,RET>, OnlineJournalType, // property OnlineJournalType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > onlineJournalNameIndex(); public abstract TypedVertexIndex.Unique < // vertex OnlineArticle<I,RV,RVT,RE,RET>, OnlineArticleType, // property OnlineArticleType.title, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > onlineArticleTitleIndex(); public abstract TypedVertexIndex.Unique < // vertex City<I,RV,RVT,RE,RET>, CityType, // property CityType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > cityNameIndex(); public abstract TypedVertexIndex.Unique < // vertex Publisher<I,RV,RVT,RE,RET>, PublisherType, // property PublisherType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > publisherNameIndex(); public abstract TypedVertexIndex.Unique < // vertex Book<I,RV,RVT,RE,RET>, BookType, // property BookType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > bookNameIndex(); public abstract TypedVertexIndex.Unique < // vertex DB<I,RV,RVT,RE,RET>, DBType, // property DBType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > dbNameIndex(); public abstract TypedVertexIndex.Unique < // vertex Country<I,RV,RVT,RE,RET>, CountryType, // property CountryType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > countryNameIndex(); public abstract TypedVertexIndex.Unique < // vertex Patent<I,RV,RVT,RE,RET>, PatentType, // property PatentType.number, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > patentNumberIndex(); public abstract TypedVertexIndex.Unique < // vertex SequenceCaution<I,RV,RVT,RE,RET>, SequenceCautionType, // property SequenceCautionType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > sequenceCautionNameIndex(); public abstract TypedVertexIndex.Unique < // vertex Submission<I,RV,RVT,RE,RET>, SubmissionType, // property SubmissionType.title, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > submissionTitleIndex(); public abstract TypedVertexIndex.Unique < // vertex SubcellularLocation<I,RV,RVT,RE,RET>, SubcellularLocationType, // property SubcellularLocationType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > subcellularLocationNameIndex(); public abstract TypedVertexIndex.Unique < // vertex Institute<I,RV,RVT,RE,RET>, InstituteType, // property InstituteType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > instituteNameIndex(); public abstract TypedVertexIndex.Unique < // vertex Isoform<I,RV,RVT,RE,RET>, IsoformType, // property IsoformType.id, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > isoformIdIndex(); public abstract TypedVertexIndex.Unique < // vertex Consortium<I,RV,RVT,RE,RET>, ConsortiumType, // property ConsortiumType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > consortiumNameIndex(); public abstract TypedVertexIndex.Unique < // vertex Thesis<I,RV,RVT,RE,RET>, ThesisType, // property ThesisType.title, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > thesisTitleIndex(); public abstract TypedVertexIndex.Unique < // vertex Person<I,RV,RVT,RE,RET>, PersonType, // property PersonType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > personNameIndex(); public abstract TypedVertexIndex.Unique < // vertex Protein<I,RV,RVT,RE,RET>, ProteinType, // property ProteinType.accession, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > proteinAccessionIndex(); public abstract TypedVertexIndex.Unique < // vertex Ensembl<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.EnsemblType, // property UniProtGraph<I,RV,RVT,RE,RET>.EnsemblType.id, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > ensemblIdIndex(); public abstract TypedVertexIndex.Unique < // vertex PIR<I,RV,RVT,RE,RET>, PIRType, // property PIRType.id, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > pIRIdIndex(); public abstract TypedVertexIndex.Unique < // vertex Pubmed<I,RV,RVT,RE,RET>, PubmedType, // property PubmedType.id, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > pubmedIdIndex(); public abstract TypedVertexIndex.Unique < // vertex UniGene<I,RV,RVT,RE,RET>, UniGeneType, // property UniGeneType.id, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > uniGeneIdIndex(); public abstract TypedVertexIndex.Unique < // vertex Kegg<I,RV,RVT,RE,RET>, KeggType, // property KeggType.id, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > keggIdIndex(); public abstract TypedVertexIndex.Unique < // vertex EMBL<I,RV,RVT,RE,RET>, EMBLType, // property EMBLType.id, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > eMBLIdIndex(); public abstract TypedVertexIndex.Unique < // vertex RefSeq<I,RV,RVT,RE,RET>, RefSeqType, // property RefSeqType.id, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > refSeqIdIndex(); public abstract TypedVertexIndex.Unique < // vertex ReactomeTerm<I,RV,RVT,RE,RET>, ReactomeTermType, // property ReactomeTermType.id, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > reactomeTermIdIndex(); public abstract TypedVertexIndex.Unique < // vertex Dataset<I,RV,RVT,RE,RET>, DatasetType, // property DatasetType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > datasetNameIndex(); public abstract TypedVertexIndex.Unique < // vertex Keyword<I,RV,RVT,RE,RET>, KeywordType, // property KeywordType.id, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > keywordIdIndex(); public abstract TypedVertexIndex.Unique < // vertex InterPro<I,RV,RVT,RE,RET>, InterProType, // property InterProType.id, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > interproIdIndex(); public abstract TypedVertexIndex.Unique < // vertex Pfam<I,RV,RVT,RE,RET>, PfamType, // property PfamType.id, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > pfamIdIndex(); public abstract TypedVertexIndex.Unique < // vertex Organism<I,RV,RVT,RE,RET>, OrganismType, // property OrganismType.scientificName, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > organismScientificNameIndex(); public abstract TypedVertexIndex.Unique < // vertex Taxon<I,RV,RVT,RE,RET>, TaxonType, // property TaxonType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > taxonNameIndex(); public abstract TypedVertexIndex.Unique < // vertex FeatureType<I,RV,RVT,RE,RET>, FeatureTypeType, // property FeatureTypeType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > featureTypeNameIndex(); public abstract TypedVertexIndex.Unique < // vertex CommentType<I,RV,RVT,RE,RET>, CommentTypeType, // property CommentTypeType.name, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > commentTypeNameIndex(); public abstract TypedVertexIndex.Unique < // vertex Reference<I,RV,RVT,RE,RET>, ReferenceType, // property ReferenceType.id, String, // graph UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET > referenceIdIndex(); // types // vertices public abstract AlternativeProductType AlternativeProduct(); public abstract ArticleType Article(); public abstract BookType Book(); public abstract CityType City(); public abstract DiseaseType Disease(); public abstract CommentTypeType CommentType(); public abstract ConsortiumType Consortium(); public abstract DatasetType Dataset(); public abstract CountryType Country(); public abstract DBType DB(); public abstract EMBLType EMBL(); public abstract EnsemblType Ensembl(); public abstract FeatureTypeType FeatureType(); public abstract GeneLocationType GeneLocation(); public abstract GeneNameType GeneName(); public abstract InstituteType Institute(); public abstract InterProType InterPro(); public abstract IsoformType Isoform(); public abstract JournalType Journal(); public abstract KeggType Kegg(); public abstract KeywordType Keyword(); public abstract OnlineArticleType OnlineArticle(); public abstract OrganismType Organism(); public abstract OnlineJournalType OnlineJournal(); public abstract PatentType Patent(); public abstract PersonType Person(); public abstract SequenceCautionType SequenceCaution(); public abstract PfamType Pfam(); public abstract PIRType PIR(); public abstract ProteinType Protein(); public abstract PublisherType Publisher(); public abstract PubmedType Pubmed(); public abstract ReactomeTermType ReactomeTerm(); public abstract ReferenceType Reference(); public abstract RefSeqType RefSeq(); public abstract SubcellularLocationType SubcellularLocation(); public abstract SubmissionType Submission(); public abstract TaxonType Taxon(); public abstract ThesisType Thesis(); public abstract UniGeneType UniGene(); public abstract UnpublishedObservationType UnpublishedObservation(); // edges public abstract IsoformEventGeneratorType IsoformEventGenerator(); public abstract ArticleJournalType ArticleJournal(); public abstract ArticlePubmedType ArticlePubmed(); public abstract BookCityType BookCity(); public abstract BookPublisherType BookPublisher(); public abstract BookEditorType BookEditor(); public abstract InstituteCountryType InstituteCountry(); public abstract OnlineArticleOnlineJournalType OnlineArticleOnlineJournal(); public abstract OrganismTaxonType OrganismTaxon(); public abstract ProteinCommentType ProteinComment(); public abstract ProteinDatasetType ProteinDataset(); public abstract ProteinDiseaseType ProteinDisease(); public abstract ProteinEMBLType ProteinEMBL(); public abstract ProteinEnsemblType ProteinEnsembl(); public abstract ProteinFeatureType ProteinFeature(); public abstract ProteinGeneLocationType ProteinGeneLocation(); public abstract ProteinGeneNameType ProteinGeneName(); public abstract ProteinInterProType ProteinInterPro(); public abstract ProteinKeggType ProteinKegg(); public abstract ProteinKeywordType ProteinKeyword(); public abstract ProteinOrganismType ProteinOrganism(); public abstract ProteinPfamType ProteinPfam(); public abstract ProteinPIRType ProteinPIR(); public abstract ProteinProteinInteractionType ProteinProteinInteraction(); public abstract ProteinIsoformInteractionType ProteinIsoformInteraction(); public abstract ProteinIsoformType ProteinIsoform(); public abstract ProteinReactomeTermType ProteinReactomeTerm(); public abstract ProteinSubcellularLocationType ProteinSubcellularLocation(); public abstract ProteinUniGeneType ProteinUniGene(); public abstract ProteinRefSeqType ProteinRefSeq(); public abstract ProteinReferenceType ProteinReference(); public abstract ProteinSequenceCautionType ProteinSequenceCaution(); public abstract ReferenceAuthorPersonType ReferenceAuthorPerson(); public abstract ReferenceAuthorConsortiumType ReferenceAuthorConsortium(); public abstract ReferenceArticleType ReferenceArticle(); public abstract ReferenceBookType ReferenceBook(); public abstract ReferenceOnlineArticleType ReferenceOnlineArticle(); public abstract ReferencePatentType ReferencePatent(); public abstract ReferenceThesisType ReferenceThesis(); public abstract ReferenceSubmissionType ReferenceSubmission(); public abstract ReferenceUnpublishedObservationType ReferenceUnpublishedObservation(); public abstract SubmissionDBType SubmissionDB(); public abstract SubcellularLocationParentType SubcellularLocationParent(); public abstract TaxonParentType TaxonParent(); public abstract ThesisInstituteType ThesisInstitute(); // Vertex types public final class AlternativeProductType extends UniProtVertexType< AlternativeProduct<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.AlternativeProductType > { public final name name = new name(); public AlternativeProductType(RVT raw) { super(raw); } @Override public AlternativeProductType value() { return graph().AlternativeProduct(); } @Override public AlternativeProduct<I,RV,RVT,RE,RET> from(RV vertex) { return new AlternativeProduct<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<AlternativeProduct<I,RV,RVT,RE,RET>, AlternativeProductType, name, String> { public name() { super(AlternativeProductType.this); } public final Class<String> valueClass() { return String.class; } } } public final class ArticleType extends UniProtVertexType< Article<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ArticleType > { public final doId doId = new doId(); public final title title = new title(); public ArticleType(RVT raw) { super(raw); } @Override public ArticleType value() { return graph().Article(); } @Override public Article<I,RV,RVT,RE,RET> from(RV vertex) { return new Article<I,RV,RVT,RE,RET>(vertex, this); } public final class doId extends UniProtVertexProperty<Article<I,RV,RVT,RE,RET>, ArticleType, doId, String> { public doId() { super(ArticleType.this); } public Class<String> valueClass() { return String.class; } } public final class title extends UniProtVertexProperty<Article<I,RV,RVT,RE,RET>, ArticleType, title, String> { public title() { super(ArticleType.this); } public Class<String> valueClass() { return String.class; } } } public final class BookType extends UniProtVertexType< Book<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.BookType > { public final name name = new name(); public BookType(RVT raw) { super(raw); } @Override public BookType value() { return graph().Book(); } @Override public Book<I,RV,RVT,RE,RET> from(RV vertex) { return new Book<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<Book<I,RV,RVT,RE,RET>, BookType, name, String> { public name() { super(BookType.this); } public Class<String> valueClass() { return String.class; } } } public final class CityType extends UniProtVertexType< City<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.CityType > { public final name name = new name(); public CityType(RVT raw) { super(raw); } @Override public CityType value() { return graph().City(); } @Override public City<I,RV,RVT,RE,RET> from(RV vertex) { return new City<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<City<I,RV,RVT,RE,RET>, CityType, name, String> { public name() { super(CityType.this); } public Class<String> valueClass() { return String.class; } } } public final class ConsortiumType extends UniProtVertexType< Consortium<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ConsortiumType > { public final name name = new name(); public ConsortiumType(RVT raw) { super(raw); } @Override public ConsortiumType value() { return graph().Consortium(); } @Override public Consortium<I,RV,RVT,RE,RET> from(RV vertex) { return new Consortium<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<Consortium<I,RV,RVT,RE,RET>, ConsortiumType, name, String> { public name() { super(ConsortiumType.this); } public Class<String> valueClass() { return String.class; } } } public final class CommentTypeType extends UniProtVertexType< CommentType<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.CommentTypeType > { public final name name = new name(); public CommentTypeType(RVT raw) { super(raw); } @Override public CommentTypeType value() { return graph().CommentType(); } @Override public CommentType<I,RV,RVT,RE,RET> from(RV vertex) { return new CommentType<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<CommentType<I,RV,RVT,RE,RET>, CommentTypeType, name, String> { public name() { super(CommentTypeType.this); } public Class<String> valueClass() { return String.class; } } } public final class CountryType extends UniProtVertexType< Country<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.CountryType > { public final name name = new name(); public CountryType(RVT raw) { super(raw); } @Override public CountryType value() { return graph().Country(); } @Override public Country<I,RV,RVT,RE,RET> from(RV vertex) { return new Country<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<Country<I,RV,RVT,RE,RET>, CountryType, name, String> { public name() { super(CountryType.this); } public Class<String> valueClass() { return String.class; } } } public final class DatasetType extends UniProtVertexType< Dataset<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.DatasetType > { public final name name = new name(); public DatasetType(RVT raw) { super(raw); } @Override public DatasetType value() { return graph().Dataset(); } @Override public Dataset<I,RV,RVT,RE,RET> from(RV vertex) { return new Dataset<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<Dataset<I,RV,RVT,RE,RET>, DatasetType, name, String> { public name() { super(DatasetType.this); } public Class<String> valueClass() { return String.class; } } } public final class DBType extends UniProtVertexType< DB<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.DBType > { public final name name = new name(); public DBType(RVT raw) { super(raw); } @Override public DBType value() { return graph().DB(); } @Override public DB<I,RV,RVT,RE,RET> from(RV vertex) { return new DB<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<DB<I,RV,RVT,RE,RET>, DBType, name, String> { public name() { super(DBType.this); } public Class<String> valueClass() { return String.class; } } } public final class DiseaseType extends UniProtVertexType< Disease<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.DiseaseType > { public final name name = new name(); public final id id = new id(); public final acronym acronym = new acronym(); public final description description = new description(); public DiseaseType(RVT raw) { super(raw); } @Override public DiseaseType value() { return graph().Disease(); } @Override public Disease<I,RV,RVT,RE,RET> from(RV vertex) { return new Disease<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<Disease<I,RV,RVT,RE,RET>, DiseaseType, name, String> { public name() { super(DiseaseType.this); } public Class<String> valueClass() { return String.class; } } public final class id extends UniProtVertexProperty<Disease<I,RV,RVT,RE,RET>, DiseaseType, id, String> { public id() { super(DiseaseType.this); } public Class<String> valueClass() { return String.class; } } public final class acronym extends UniProtVertexProperty<Disease<I,RV,RVT,RE,RET>, DiseaseType, acronym, String> { public acronym() { super(DiseaseType.this); } public Class<String> valueClass() { return String.class; } } public final class description extends UniProtVertexProperty<Disease<I,RV,RVT,RE,RET>, DiseaseType, description, String> { public description() { super(DiseaseType.this); } public Class<String> valueClass() { return String.class; } } } public final class EMBLType extends UniProtVertexType< EMBL<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.EMBLType > { public final id id = new id(); public final proteinSequenceId proteinSequenceId = new proteinSequenceId(); public final moleculeType moleculeType = new moleculeType(); public EMBLType(RVT raw) { super(raw); } @Override public EMBLType value() { return graph().EMBL(); } @Override public EMBL<I,RV,RVT,RE,RET> from(RV vertex) { return new EMBL<I,RV,RVT,RE,RET>(vertex, this); } public final class id extends UniProtVertexProperty<EMBL<I,RV,RVT,RE,RET>, EMBLType, id, String> { public id() { super(EMBLType.this); } public Class<String> valueClass() { return String.class; } } public final class proteinSequenceId extends UniProtVertexProperty<EMBL<I,RV,RVT,RE,RET>, EMBLType, proteinSequenceId, String> { public proteinSequenceId() { super(EMBLType.this); } public Class<String> valueClass() { return String.class; } } public final class moleculeType extends UniProtVertexProperty<EMBL<I,RV,RVT,RE,RET>, EMBLType, moleculeType, String> { public moleculeType() { super(EMBLType.this); } public Class<String> valueClass() { return String.class; } } } public final class EnsemblType extends UniProtVertexType< Ensembl<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.EnsemblType > { public final id id = new id(); public final proteinSequenceId proteinSequenceId = new proteinSequenceId(); public final moleculeId moleculeId = new moleculeId(); public final geneId geneId = new geneId(); public EnsemblType(RVT raw) { super(raw); } @Override public EnsemblType value() { return graph().Ensembl(); } @Override public Ensembl<I,RV,RVT,RE,RET> from(RV vertex) { return new Ensembl<I,RV,RVT,RE,RET>(vertex, this); } public final class id extends UniProtVertexProperty<Ensembl<I,RV,RVT,RE,RET>, EnsemblType, id, String> { public id() { super(EnsemblType.this); } public Class<String> valueClass() { return String.class; } } public final class proteinSequenceId extends UniProtVertexProperty<Ensembl<I,RV,RVT,RE,RET>, EnsemblType, proteinSequenceId, String> { public proteinSequenceId() { super(EnsemblType.this); } public Class<String> valueClass() { return String.class; } } public final class moleculeId extends UniProtVertexProperty<Ensembl<I,RV,RVT,RE,RET>, EnsemblType, moleculeId, String> { public moleculeId() { super(EnsemblType.this); } public Class<String> valueClass() { return String.class; } } public final class geneId extends UniProtVertexProperty<Ensembl<I,RV,RVT,RE,RET>, EnsemblType, geneId, String> { public geneId() { super(EnsemblType.this); } public Class<String> valueClass() { return String.class; } } } public final class FeatureTypeType extends UniProtVertexType< FeatureType<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.FeatureTypeType > { public final name name = new name(); public FeatureTypeType(RVT raw) { super(raw); } @Override public FeatureTypeType value() { return graph().FeatureType(); } @Override public FeatureType<I,RV,RVT,RE,RET> from(RV vertex) { return new FeatureType<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<FeatureType<I,RV,RVT,RE,RET>, FeatureTypeType, name, String> { public name() { super(FeatureTypeType.this); } public Class<String> valueClass() { return String.class; } } } public final class GeneLocationType extends UniProtVertexType< GeneLocation<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.GeneLocationType > { public final name name = new name(); public GeneLocationType(RVT raw) { super(raw); } @Override public GeneLocationType value() { return graph().GeneLocation(); } @Override public GeneLocation<I,RV,RVT,RE,RET> from(RV vertex) { return new GeneLocation<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<GeneLocation<I,RV,RVT,RE,RET>, GeneLocationType, name, String> { public name() { super(GeneLocationType.this); } public Class<String> valueClass() { return String.class; } } } public final class GeneNameType extends UniProtVertexType< GeneName<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.GeneNameType > { public final name name = new name(); public GeneNameType(RVT raw) { super(raw); } @Override public GeneNameType value() { return graph().GeneName(); } @Override public GeneName<I,RV,RVT,RE,RET> from(RV vertex) { return new GeneName<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<GeneName<I,RV,RVT,RE,RET>, GeneNameType, name, String> { public name() { super(GeneNameType.this); } public Class<String> valueClass() { return String.class; } } } public final class InterProType extends UniProtVertexType< InterPro<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.InterProType > { public final name name = new name(); public final id id = new id(); public InterProType(RVT raw) { super(raw); } @Override public InterProType value() { return graph().InterPro(); } @Override public InterPro<I,RV,RVT,RE,RET> from(RV vertex) { return new InterPro<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<InterPro<I,RV,RVT,RE,RET>, InterProType, name, String> { public name() { super(InterProType.this); } public Class<String> valueClass() { return String.class; } } public final class id extends UniProtVertexProperty<InterPro<I,RV,RVT,RE,RET>, InterProType, id, String> { public id() { super(InterProType.this); } public Class<String> valueClass() { return String.class; } } } public final class InstituteType extends UniProtVertexType< Institute<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.InstituteType > { public final name name = new name(); public InstituteType(RVT raw) { super(raw); } @Override public InstituteType value() { return graph().Institute(); } @Override public Institute<I,RV,RVT,RE,RET> from(RV vertex) { return new Institute<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<Institute<I,RV,RVT,RE,RET>, InstituteType, name, String> { public name() { super(InstituteType.this); } public Class<String> valueClass() { return String.class; } } } public final class IsoformType extends UniProtVertexType< Isoform<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.IsoformType > { public final name name = new name(); public final id id = new id(); public final note note = new note(); public final sequence sequence = new sequence(); public IsoformType(RVT raw) { super(raw); } @Override public IsoformType value() { return graph().Isoform(); } @Override public Isoform<I,RV,RVT,RE,RET> from(RV vertex) { return new Isoform<I,RV,RVT,RE,RET>(vertex, this); } public final class sequence extends UniProtVertexProperty<Isoform<I,RV,RVT,RE,RET>, IsoformType, sequence, String> { public sequence() { super(IsoformType.this); } public Class<String> valueClass() { return String.class; } } public final class note extends UniProtVertexProperty<Isoform<I,RV,RVT,RE,RET>, IsoformType, note, String> { public note() { super(IsoformType.this); } public Class<String> valueClass() { return String.class; } } public final class id extends UniProtVertexProperty<Isoform<I,RV,RVT,RE,RET>, IsoformType, id, String> { public id() { super(IsoformType.this); } public Class<String> valueClass() { return String.class; } } public final class name extends UniProtVertexProperty<Isoform<I,RV,RVT,RE,RET>, IsoformType, name, String> { public name() { super(IsoformType.this); } public Class<String> valueClass() { return String.class; } } } public final class JournalType extends UniProtVertexType< Journal<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.JournalType > { public final name name = new name(); public JournalType(RVT raw) { super(raw); } @Override public JournalType value() { return graph().Journal(); } @Override public Journal<I,RV,RVT,RE,RET> from(RV vertex) { return new Journal<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<Journal<I,RV,RVT,RE,RET>, JournalType, name, String> { public name() { super(JournalType.this); } public Class<String> valueClass() { return String.class; } } } public final class KeggType extends UniProtVertexType< Kegg<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.KeggType > { public final id id = new id(); public KeggType(RVT raw) { super(raw); } @Override public KeggType value() { return graph().Kegg(); } @Override public Kegg<I,RV,RVT,RE,RET> from(RV vertex) { return new Kegg<I,RV,RVT,RE,RET>(vertex, this); } public final class id extends UniProtVertexProperty<Kegg<I,RV,RVT,RE,RET>, KeggType, id, String> { public id() { super(KeggType.this); } public Class<String> valueClass() { return String.class; } } } public final class KeywordType extends UniProtVertexType< Keyword<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.KeywordType > { public final name name = new name(); public final id id = new id(); public KeywordType(RVT raw) { super(raw); } @Override public KeywordType value() { return graph().Keyword(); } @Override public Keyword<I,RV,RVT,RE,RET> from(RV vertex) { return new Keyword<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<Keyword<I,RV,RVT,RE,RET>, KeywordType, name, String> { public name() { super(KeywordType.this); } public Class<String> valueClass() { return String.class; } } public final class id extends UniProtVertexProperty<Keyword<I,RV,RVT,RE,RET>, KeywordType, id, String> { public id() { super(KeywordType.this); } public Class<String> valueClass() { return String.class; } } } public final class OnlineArticleType extends UniProtVertexType< OnlineArticle<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.OnlineArticleType > { public final title title = new title(); public OnlineArticleType(RVT raw) { super(raw); } @Override public OnlineArticleType value() { return graph().OnlineArticle(); } @Override public OnlineArticle<I,RV,RVT,RE,RET> from(RV vertex) { return new OnlineArticle<I,RV,RVT,RE,RET>(vertex, this); } public final class title extends UniProtVertexProperty<OnlineArticle<I,RV,RVT,RE,RET>, OnlineArticleType, title, String> { public title() { super(OnlineArticleType.this); } public Class<String> valueClass() { return String.class; } } } public final class OnlineJournalType extends UniProtVertexType< OnlineJournal<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.OnlineJournalType > { public final name name = new name(); public OnlineJournalType(RVT raw) { super(raw); } @Override public OnlineJournalType value() { return graph().OnlineJournal(); } @Override public OnlineJournal<I,RV,RVT,RE,RET> from(RV vertex) { return new OnlineJournal<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<OnlineJournal<I,RV,RVT,RE,RET>, OnlineJournalType, name, String> { public name() { super(OnlineJournalType.this); } public Class<String> valueClass() { return String.class; } } } public final class OrganismType extends UniProtVertexType< Organism<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.OrganismType > { public final scientificName scientificName = new scientificName(); public final commonName commonName = new commonName(); public final synonymName synonymName = new synonymName(); public OrganismType(RVT raw) { super(raw); } @Override public OrganismType value() { return graph().Organism(); } @Override public Organism<I,RV,RVT,RE,RET> from(RV vertex) { return new Organism<I,RV,RVT,RE,RET>(vertex, this); } public final class scientificName extends UniProtVertexProperty<Organism<I,RV,RVT,RE,RET>, OrganismType, scientificName, String> { public scientificName() { super(OrganismType.this); } public Class<String> valueClass() { return String.class; } } public final class commonName extends UniProtVertexProperty<Organism<I,RV,RVT,RE,RET>, OrganismType, commonName, String> { public commonName() { super(OrganismType.this); } public Class<String> valueClass() { return String.class; } } public final class synonymName extends UniProtVertexProperty<Organism<I,RV,RVT,RE,RET>, OrganismType, synonymName, String> { public synonymName() { super(OrganismType.this); } public Class<String> valueClass() { return String.class; } } } public final class PatentType extends UniProtVertexType< Patent<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.PatentType > { public final title title = new title(); public final number number = new number(); public PatentType(RVT raw) { super(raw); } @Override public PatentType value() { return graph().Patent(); } @Override public Patent<I,RV,RVT,RE,RET> from(RV vertex) { return new Patent<I,RV,RVT,RE,RET>(vertex, this); } public final class title extends UniProtVertexProperty<Patent<I,RV,RVT,RE,RET>, PatentType, title, String> { public title() { super(PatentType.this); } public Class<String> valueClass() { return String.class; } } public final class number extends UniProtVertexProperty<Patent<I,RV,RVT,RE,RET>, PatentType, number, String> { public number() { super(PatentType.this); } public Class<String> valueClass() { return String.class; } } } public final class PersonType extends UniProtVertexType< Person<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.PersonType > { public final name name = new name(); public PersonType(RVT raw) { super(raw); } @Override public PersonType value() { return graph().Person(); } @Override public Person<I,RV,RVT,RE,RET> from(RV vertex) { return new Person<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<Person<I,RV,RVT,RE,RET>, PersonType, name, String> { public name() { super(PersonType.this); } public Class<String> valueClass() { return String.class; } } } public final class PfamType extends UniProtVertexType< Pfam<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.PfamType > { public final name name = new name(); public final id id = new id(); public PfamType(RVT raw) { super(raw); } @Override public PfamType value() { return graph().Pfam(); } @Override public Pfam<I,RV,RVT,RE,RET> from(RV vertex) { return new Pfam<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<Pfam<I,RV,RVT,RE,RET>, PfamType, name, String> { public name() { super(PfamType.this); } public Class<String> valueClass() { return String.class; } } public final class id extends UniProtVertexProperty<Pfam<I,RV,RVT,RE,RET>, PfamType, id, String> { public id() { super(PfamType.this); } public Class<String> valueClass() { return String.class; } } } public final class PubmedType extends UniProtVertexType< Pubmed<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.PubmedType > { public final id id = new id(); public PubmedType(RVT raw) { super(raw); } @Override public PubmedType value() { return graph().Pubmed(); } @Override public Pubmed<I,RV,RVT,RE,RET> from(RV vertex) { return new Pubmed<I,RV,RVT,RE,RET>(vertex, this); } public final class id extends UniProtVertexProperty<Pubmed<I,RV,RVT,RE,RET>, PubmedType, id, String> { public id() { super(PubmedType.this); } public Class<String> valueClass() { return String.class; } } } public final class PIRType extends UniProtVertexType< PIR<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.PIRType > { public final id id = new id(); public final entryName entryName = new entryName(); public PIRType(RVT raw) { super(raw); } @Override public PIRType value() { return graph().PIR(); } @Override public PIR<I,RV,RVT,RE,RET> from(RV vertex) { return new PIR<I,RV,RVT,RE,RET>(vertex, this); } public final class id extends UniProtVertexProperty<PIR<I,RV,RVT,RE,RET>, PIRType, id, String> { public id() { super(PIRType.this); } public Class<String> valueClass() { return String.class; } } public final class entryName extends UniProtVertexProperty<PIR<I,RV,RVT,RE,RET>, PIRType, entryName, String> { public entryName() { super(PIRType.this); } public Class<String> valueClass() { return String.class; } } } public final class ProteinType extends UniProtVertexType < Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType > { public final accession accession = new accession(); public final entryName entryName = new entryName(); public final fullName fullName = new fullName(); public final sequence sequence = new sequence(); public final length length = new length(); public final mass mass = new mass(); public final uniRef100ClusterId uniRef100ClusterId = new uniRef100ClusterId(); public final uniRef90ClusterId uniRef90ClusterId = new uniRef90ClusterId(); public final uniRef50ClusterId uniRef50ClusterId = new uniRef50ClusterId(); public ProteinType(RVT raw) { super(raw); } @Override public final ProteinType value() { return graph().Protein(); } @Override public final Protein<I,RV,RVT,RE,RET> from(RV vertex) { return new Protein<I,RV,RVT,RE,RET>(vertex, this); } /* This property is always present, and identifies the protein. */ public final class accession extends UniProtVertexProperty<Protein<I,RV,RVT,RE,RET>, ProteinType, accession, String> { public accession() { super(ProteinType.this); } public Class<String> valueClass() { return String.class; } } /* This property is **optional**. */ public final class shortName extends UniProtVertexProperty<Protein<I,RV,RVT,RE,RET>, ProteinType, shortName, String> { public shortName() { super(ProteinType.this); } public Class<String> valueClass() { return String.class; } } /* The protein sequence. This property is **always present**. */ public final class sequence extends UniProtVertexProperty<Protein<I,RV,RVT,RE,RET>, ProteinType, sequence, String> { public sequence() { super(ProteinType.this); } public Class<String> valueClass() { return String.class; } } /* This property is **always present**. It is normally larger and more descriptive than `name`. */ public final class fullName extends UniProtVertexProperty<Protein<I,RV,RVT,RE,RET>, ProteinType, fullName, String> { public fullName() { super(ProteinType.this); } public Class<String> valueClass() { return String.class; } } /* The entry name, as displayed on the UniProt website */ public final class entryName extends UniProtVertexProperty<Protein<I,RV,RVT,RE,RET>, ProteinType, entryName, String> { public entryName() { super(ProteinType.this); } public Class<String> valueClass() { return String.class; } } public final class mass extends UniProtVertexProperty<Protein<I,RV,RVT,RE,RET>, ProteinType, mass, Integer> { public mass() { super(ProteinType.this); } public Class<Integer> valueClass() { return Integer.class; } } public final class length extends UniProtVertexProperty<Protein<I,RV,RVT,RE,RET>, ProteinType, length, Integer> { public length() { super(ProteinType.this); } public Class<Integer> valueClass() { return Integer.class; } } public final class uniRef100ClusterId extends UniProtVertexProperty<Protein<I,RV,RVT,RE,RET>, ProteinType, uniRef100ClusterId, String> { public uniRef100ClusterId() { super(ProteinType.this); } public Class<String> valueClass() { return String.class; } } public final class uniRef90ClusterId extends UniProtVertexProperty<Protein<I,RV,RVT,RE,RET>, ProteinType, uniRef90ClusterId, String> { public uniRef90ClusterId() { super(ProteinType.this); } public Class<String> valueClass() { return String.class; } } public final class uniRef50ClusterId extends UniProtVertexProperty<Protein<I,RV,RVT,RE,RET>, ProteinType, uniRef50ClusterId, String> { public uniRef50ClusterId() { super(ProteinType.this); } public Class<String> valueClass() { return String.class; } } } public final class PublisherType extends UniProtVertexType< Publisher<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.PublisherType > { public final name name = new name(); public PublisherType(RVT raw) { super(raw); } @Override public PublisherType value() { return graph().Publisher(); } @Override public Publisher<I,RV,RVT,RE,RET> from(RV vertex) { return new Publisher<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<Publisher<I,RV,RVT,RE,RET>, PublisherType, name, String> { public name() { super(PublisherType.this); } public Class<String> valueClass() { return String.class; } } } public final class ReactomeTermType extends UniProtVertexType< ReactomeTerm<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReactomeTermType > { public final id id = new id(); public final pathwayName pathwayName = new pathwayName(); public ReactomeTermType(RVT raw) { super(raw); } @Override public ReactomeTermType value() { return graph().ReactomeTerm(); } @Override public ReactomeTerm<I,RV,RVT,RE,RET> from(RV vertex) { return new ReactomeTerm<I,RV,RVT,RE,RET>(vertex, this); } public final class id extends UniProtVertexProperty<ReactomeTerm<I,RV,RVT,RE,RET>, ReactomeTermType, id, String> { public id() { super(ReactomeTermType.this); } public Class<String> valueClass() { return String.class; } } public final class pathwayName extends UniProtVertexProperty<ReactomeTerm<I,RV,RVT,RE,RET>, ReactomeTermType, pathwayName, String> { public pathwayName() { super(ReactomeTermType.this); } public Class<String> valueClass() { return String.class; } } } public final class ReferenceType extends UniProtVertexType< Reference<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceType > { public final id id = new id(); public final date date = new date(); public ReferenceType(RVT raw) { super(raw); } @Override public ReferenceType value() { return graph().Reference(); } @Override public Reference<I,RV,RVT,RE,RET> from(RV vertex) { return new Reference<I,RV,RVT,RE,RET>(vertex, this); } public final class id extends UniProtVertexProperty<Reference<I,RV,RVT,RE,RET>, ReferenceType, id, String> { public id() { super(ReferenceType.this); } public Class<String> valueClass() { return String.class; } } public final class date extends UniProtVertexProperty<Reference<I,RV,RVT,RE,RET>, ReferenceType, date, String> { public date() { super(ReferenceType.this); } public Class<String> valueClass() { return String.class; } } } public final class RefSeqType extends UniProtVertexType< RefSeq<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.RefSeqType > { public final id id = new id(); public final nucleotideSequenceId nucleotideSequenceId = new nucleotideSequenceId(); public RefSeqType(RVT raw) { super(raw); } @Override public RefSeqType value() { return graph().RefSeq(); } @Override public RefSeq<I,RV,RVT,RE,RET> from(RV vertex) { return new RefSeq<I,RV,RVT,RE,RET>(vertex, this); } public final class id extends UniProtVertexProperty<RefSeq<I,RV,RVT,RE,RET>, RefSeqType, id, String> { public id() { super(RefSeqType.this); } public Class<String> valueClass() { return String.class; } } public final class nucleotideSequenceId extends UniProtVertexProperty<RefSeq<I,RV,RVT,RE,RET>, RefSeqType, nucleotideSequenceId, String> { public nucleotideSequenceId() { super(RefSeqType.this); } public Class<String> valueClass() { return String.class; } } } public final class SequenceCautionType extends UniProtVertexType< SequenceCaution<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.SequenceCautionType > { public final name name = new name(); public SequenceCautionType(RVT raw) { super(raw); } @Override public SequenceCautionType value() { return graph().SequenceCaution(); } @Override public SequenceCaution<I,RV,RVT,RE,RET> from(RV vertex) { return new SequenceCaution<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<SequenceCaution<I,RV,RVT,RE,RET>, SequenceCautionType, name, String> { public name() { super(SequenceCautionType.this); } public Class<String> valueClass() { return String.class; } } } public final class SubcellularLocationType extends UniProtVertexType< SubcellularLocation<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.SubcellularLocationType > { public final name name = new name(); public SubcellularLocationType(RVT raw) { super(raw); } @Override public SubcellularLocationType value() { return graph().SubcellularLocation(); } @Override public SubcellularLocation<I,RV,RVT,RE,RET> from(RV vertex) { return new SubcellularLocation<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<SubcellularLocation<I,RV,RVT,RE,RET>, SubcellularLocationType, name, String> { public name() { super(SubcellularLocationType.this); } public Class<String> valueClass() { return String.class; } } } public final class SubmissionType extends UniProtVertexType< Submission<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.SubmissionType > { public final title title = new title(); public SubmissionType(RVT raw) { super(raw); } @Override public SubmissionType value() { return graph().Submission(); } @Override public Submission<I,RV,RVT,RE,RET> from(RV vertex) { return new Submission<I,RV,RVT,RE,RET>(vertex, this); } public final class title extends UniProtVertexProperty<Submission<I,RV,RVT,RE,RET>, SubmissionType, title, String> { public title() { super(SubmissionType.this); } public Class<String> valueClass() { return String.class; } } } public final class TaxonType extends UniProtVertexType< Taxon<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.TaxonType > { public final name name = new name(); public TaxonType(RVT raw) { super(raw); } @Override public TaxonType value() { return graph().Taxon(); } @Override public Taxon<I,RV,RVT,RE,RET> from(RV vertex) { return new Taxon<I,RV,RVT,RE,RET>(vertex, this); } public final class name extends UniProtVertexProperty<Taxon<I,RV,RVT,RE,RET>, TaxonType, name, String> { public name() { super(TaxonType.this); } public Class<String> valueClass() { return String.class; } } } public final class ThesisType extends UniProtVertexType< Thesis<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ThesisType > { public final title title = new title(); public ThesisType(RVT raw) { super(raw); } @Override public ThesisType value() { return graph().Thesis(); } @Override public Thesis<I,RV,RVT,RE,RET> from(RV vertex) { return new Thesis<I,RV,RVT,RE,RET>(vertex, this); } public final class title extends UniProtVertexProperty<Thesis<I,RV,RVT,RE,RET>, ThesisType, title, String> { public title() { super(ThesisType.this); } public Class<String> valueClass() { return String.class; } } } public final class UniGeneType extends UniProtVertexType< UniGene<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.UniGeneType > { public final id id = new id(); public UniGeneType(RVT raw) { super(raw); } @Override public UniGeneType value() { return graph().UniGene(); } @Override public UniGene<I,RV,RVT,RE,RET> from(RV vertex) { return new UniGene<I,RV,RVT,RE,RET>(vertex, this); } public final class id extends UniProtVertexProperty<UniGene<I,RV,RVT,RE,RET>, UniGeneType, id, String> { public id() { super(UniGeneType.this); } public Class<String> valueClass() { return String.class; } } } public final class UnpublishedObservationType extends UniProtVertexType< UnpublishedObservation<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.UnpublishedObservationType > { public final scope scope = new scope(); public UnpublishedObservationType(RVT raw) { super(raw); } @Override public UnpublishedObservationType value() { return graph().UnpublishedObservation(); } @Override public UnpublishedObservation<I,RV,RVT,RE,RET> from(RV vertex) { return new UnpublishedObservation<I,RV,RVT,RE,RET>(vertex, this); } public final class scope extends UniProtVertexProperty<UnpublishedObservation<I,RV,RVT,RE,RET>, UnpublishedObservationType, scope, String> { public scope() { super(UnpublishedObservationType.this); } public Class<String> valueClass() { return String.class; } } } // Edge types public final class ArticleJournalType extends UniProtEdgeType< Article<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ArticleType, ArticleJournal<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ArticleJournalType, Journal<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.JournalType > implements TypedEdge.Type.ManyToOne { public ArticleJournalType(RET raw) { super(UniProtGraph.this.Article(), raw, UniProtGraph.this.Journal()); } @Override public ArticleJournalType value() { return graph().ArticleJournal(); } @Override public ArticleJournal<I,RV,RVT,RE,RET> from(RE edge) { return new ArticleJournal<I,RV,RVT,RE,RET>(edge, this); } public final volume volume = new volume(); public final first first = new first(); public final last last = new last(); public final class volume extends UniProtEdgeProperty< Article<I,RV,RVT,RE,RET>, ArticleType, ArticleJournal<I,RV,RVT,RE,RET>, ArticleJournalType, Journal<I,RV,RVT,RE,RET>, JournalType, volume, String > { public volume() { super(ArticleJournalType.this); } public Class<String> valueClass() { return String.class; } } public final class first extends UniProtEdgeProperty< Article<I,RV,RVT,RE,RET>, ArticleType, ArticleJournal<I,RV,RVT,RE,RET>, ArticleJournalType, Journal<I,RV,RVT,RE,RET>, JournalType, first, String > { public first() { super(ArticleJournalType.this); } public Class<String> valueClass() { return String.class; } } public final class last extends UniProtEdgeProperty< Article<I,RV,RVT,RE,RET>, ArticleType, ArticleJournal<I,RV,RVT,RE,RET>, ArticleJournalType, Journal<I,RV,RVT,RE,RET>, JournalType, last, String > { public last() { super(ArticleJournalType.this); } public Class<String> valueClass() { return String.class; } } } public final class ArticlePubmedType extends UniProtEdgeType< Article<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ArticleType, ArticlePubmed<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ArticlePubmedType, Pubmed<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.PubmedType > implements TypedEdge.Type.OneToOne { public ArticlePubmedType(RET raw) { super(UniProtGraph.this.Article(), raw, UniProtGraph.this.Pubmed()); } @Override public ArticlePubmedType value() { return graph().ArticlePubmed(); } @Override public ArticlePubmed<I,RV,RVT,RE,RET> from(RE edge) { return new ArticlePubmed<I,RV,RVT,RE,RET>(edge, this); } } public final class BookCityType extends UniProtEdgeType< Book<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.BookType, BookCity<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.BookCityType, City<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.CityType > implements TypedEdge.Type.ManyToOne { public BookCityType(RET raw) { super(UniProtGraph.this.Book(), raw, UniProtGraph.this.City()); } @Override public BookCityType value() { return graph().BookCity(); } @Override public BookCity<I,RV,RVT,RE,RET> from(RE edge) { return new BookCity<I,RV,RVT,RE,RET>(edge, this); } } public final class BookEditorType extends UniProtEdgeType< Book<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.BookType, BookEditor<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.BookEditorType, Person<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.PersonType > implements TypedEdge.Type.ManyToOne { public BookEditorType(RET raw) { super(UniProtGraph.this.Book(), raw, UniProtGraph.this.Person()); } @Override public BookEditorType value() { return graph().BookEditor(); } @Override public BookEditor<I,RV,RVT,RE,RET> from(RE edge) { return new BookEditor<I,RV,RVT,RE,RET>(edge, this); } } public final class BookPublisherType extends UniProtEdgeType< Book<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.BookType, BookPublisher<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.BookPublisherType, Publisher<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.PublisherType > implements TypedEdge.Type.ManyToOne { public BookPublisherType(RET raw) { super(UniProtGraph.this.Book(), raw, UniProtGraph.this.Publisher()); } @Override public BookPublisherType value() { return graph().BookPublisher(); } @Override public BookPublisher<I,RV,RVT,RE,RET> from(RE edge) { return new BookPublisher<I,RV,RVT,RE,RET>(edge, this); } } public final class InstituteCountryType extends UniProtEdgeType< Institute<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.InstituteType, InstituteCountry<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.InstituteCountryType, Country<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.CountryType > implements TypedEdge.Type.ManyToOne { public InstituteCountryType(RET raw) { super(UniProtGraph.this.Institute(), raw, UniProtGraph.this.Country()); } @Override public InstituteCountryType value() { return graph().InstituteCountry(); } @Override public InstituteCountry<I,RV,RVT,RE,RET> from(RE edge) { return new InstituteCountry<I,RV,RVT,RE,RET>(edge, this); } } public final class OnlineArticleOnlineJournalType extends UniProtEdgeType< OnlineArticle<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.OnlineArticleType, OnlineArticleOnlineJournal<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.OnlineArticleOnlineJournalType, OnlineJournal<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.OnlineJournalType > implements TypedEdge.Type.ManyToOne { public OnlineArticleOnlineJournalType(RET raw) { super(UniProtGraph.this.OnlineArticle(), raw, UniProtGraph.this.OnlineJournal()); } @Override public OnlineArticleOnlineJournalType value() { return graph().OnlineArticleOnlineJournal(); } @Override public OnlineArticleOnlineJournal<I,RV,RVT,RE,RET> from(RE edge) { return new OnlineArticleOnlineJournal<I,RV,RVT,RE,RET>(edge, this); } public final locator locator = new locator(); public final class locator extends UniProtEdgeProperty< OnlineArticle<I,RV,RVT,RE,RET>, OnlineArticleType, OnlineArticleOnlineJournal<I,RV,RVT,RE,RET>, OnlineArticleOnlineJournalType, OnlineJournal<I,RV,RVT,RE,RET>, OnlineJournalType, locator, String > { public locator() { super(OnlineArticleOnlineJournalType.this); } public Class<String> valueClass() { return String.class; } } } public final class OrganismTaxonType extends UniProtEdgeType< Organism<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.OrganismType, OrganismTaxon<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.OrganismTaxonType, Taxon<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.TaxonType > implements TypedEdge.Type.ManyToOne { public OrganismTaxonType(RET raw) { super(UniProtGraph.this.Organism(), raw, UniProtGraph.this.Taxon()); } @Override public OrganismTaxonType value() { return graph().OrganismTaxon(); } @Override public OrganismTaxon<I,RV,RVT,RE,RET> from(RE edge) { return new OrganismTaxon<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinCommentType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinComment<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.CommentTypeType > implements TypedEdge.Type.ManyToMany { public ProteinCommentType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.CommentType()); } @Override public ProteinCommentType value() { return graph().ProteinComment(); } @Override public ProteinComment<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinComment<I,RV,RVT,RE,RET>(edge, this); } public final redoxPotentialEvidence redoxPotentialEvidence = new redoxPotentialEvidence(); public final redoxPotential redoxPotential = new redoxPotential(); public final absorptionText absorptionText = new absorptionText(); public final absorptionMax absorptionMax = new absorptionMax(); public final kineticsXML kineticsXML = new kineticsXML(); public final phDependence phDependence = new phDependence(); public final temperatureDependence temperatureDependence = new temperatureDependence(); public final text text = new text(); public final status status = new status(); public final evidence evidence = new evidence(); public final begin begin = new begin(); public final end end = new end(); public final method method = new method(); public final mass mass = new mass(); public final position position = new position(); public final class redoxPotentialEvidence extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, redoxPotentialEvidence, String > { public redoxPotentialEvidence() { super(ProteinCommentType.this); } public Class<String> valueClass() { return String.class; } } public final class redoxPotential extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, redoxPotential, String > { public redoxPotential() { super(ProteinCommentType.this); } public Class<String> valueClass() { return String.class; } } public final class absorptionText extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, absorptionText, String > { public absorptionText() { super(ProteinCommentType.this); } public Class<String> valueClass() { return String.class; } } public final class absorptionMax extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, absorptionMax, String > { public absorptionMax() { super(ProteinCommentType.this); } public Class<String> valueClass() { return String.class; } } public final class kineticsXML extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, kineticsXML, String > { public kineticsXML() { super(ProteinCommentType.this); } public Class<String> valueClass() { return String.class; } } public final class phDependence extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, phDependence, String > { public phDependence() { super(ProteinCommentType.this); } public Class<String> valueClass() { return String.class; } } public final class temperatureDependence extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, temperatureDependence, String > { public temperatureDependence() { super(ProteinCommentType.this); } public Class<String> valueClass() { return String.class; } } public final class position extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, position, String > { public position() { super(ProteinCommentType.this); } public Class<String> valueClass() { return String.class; } } public final class mass extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, mass, String > { public mass() { super(ProteinCommentType.this); } public Class<String> valueClass() { return String.class; } } public final class method extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, method, String > { public method() { super(ProteinCommentType.this); } public Class<String> valueClass() { return String.class; } } public final class end extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, end, Integer > { public end() { super(ProteinCommentType.this); } public Class<Integer> valueClass() { return Integer.class; } } public final class begin extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, begin, Integer > { public begin() { super(ProteinCommentType.this); } public Class<Integer> valueClass() { return Integer.class; } } public final class text extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, text, String > { public text() { super(ProteinCommentType.this); } public Class<String> valueClass() { return String.class; } } public final class status extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, status, String > { public status() { super(ProteinCommentType.this); } public Class<String> valueClass() { return String.class; } } public final class evidence extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinComment<I,RV,RVT,RE,RET>, ProteinCommentType, CommentType<I,RV,RVT,RE,RET>, CommentTypeType, evidence, String > { public evidence() { super(ProteinCommentType.this); } public Class<String> valueClass() { return String.class; } } } public final class ProteinDatasetType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinDataset<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinDatasetType, Dataset<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.DatasetType > implements TypedEdge.Type.ManyToOne { public ProteinDatasetType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.Dataset()); } @Override public ProteinDatasetType value() { return graph().ProteinDataset(); } @Override public ProteinDataset<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinDataset<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinDiseaseType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinDisease<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinDiseaseType, Disease<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.DiseaseType > implements TypedEdge.Type.ManyToMany { public final text text = new text(); public final status status = new status(); public final evidence evidence = new evidence(); public ProteinDiseaseType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.Disease()); } @Override public ProteinDiseaseType value() { return graph().ProteinDisease(); } @Override public ProteinDisease<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinDisease<I,RV,RVT,RE,RET>(edge, this); } public final class text extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinDisease<I,RV,RVT,RE,RET>, ProteinDiseaseType, Disease<I,RV,RVT,RE,RET>, DiseaseType, text, String > { public text() { super(ProteinDiseaseType.this); } public Class<String> valueClass() { return String.class; } } public final class status extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinDisease<I,RV,RVT,RE,RET>, ProteinDiseaseType, Disease<I,RV,RVT,RE,RET>, DiseaseType, status, String > { public status() { super(ProteinDiseaseType.this); } public Class<String> valueClass() { return String.class; } } public final class evidence extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinDisease<I,RV,RVT,RE,RET>, ProteinDiseaseType, Disease<I,RV,RVT,RE,RET>, DiseaseType, evidence, String > { public evidence() { super(ProteinDiseaseType.this); } public Class<String> valueClass() { return String.class; } } } public final class ProteinEMBLType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinEMBL<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinEMBLType, EMBL<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.EMBLType > implements TypedEdge.Type.ManyToMany { public ProteinEMBLType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.EMBL()); } @Override public ProteinEMBLType value() { return graph().ProteinEMBL(); } @Override public ProteinEMBL<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinEMBL<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinEnsemblType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinEnsembl<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinEnsemblType, Ensembl<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.EnsemblType > implements TypedEdge.Type.ManyToMany { public ProteinEnsemblType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.Ensembl()); } @Override public ProteinEnsemblType value() { return graph().ProteinEnsembl(); } @Override public ProteinEnsembl<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinEnsembl<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinFeatureType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinFeature<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinFeatureType, FeatureType<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.FeatureTypeType > implements TypedEdge.Type.ManyToMany { public final description description = new description(); public final id id = new id(); public final evidence evidence = new evidence(); public final status status = new status(); public final begin begin = new begin(); public final end end = new end(); public final original original = new original(); public final variation variation = new variation(); public final ref ref = new ref(); public ProteinFeatureType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.FeatureType()); } @Override public ProteinFeatureType value() { return graph().ProteinFeature(); } @Override public ProteinFeature<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinFeature<I,RV,RVT,RE,RET>(edge, this); } public final class description extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinFeature<I,RV,RVT,RE,RET>, ProteinFeatureType, FeatureType<I,RV,RVT,RE,RET>, FeatureTypeType, description, String > { public description() { super(ProteinFeatureType.this); } public Class<String> valueClass() { return String.class; } } public final class id extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinFeature<I,RV,RVT,RE,RET>, ProteinFeatureType, FeatureType<I,RV,RVT,RE,RET>, FeatureTypeType, id, String > { public id() { super(ProteinFeatureType.this); } public Class<String> valueClass() { return String.class; } } public final class evidence extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinFeature<I,RV,RVT,RE,RET>, ProteinFeatureType, FeatureType<I,RV,RVT,RE,RET>, FeatureTypeType, evidence, String > { public evidence() { super(ProteinFeatureType.this); } public Class<String> valueClass() { return String.class; } } public final class status extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinFeature<I,RV,RVT,RE,RET>, ProteinFeatureType, FeatureType<I,RV,RVT,RE,RET>, FeatureTypeType, status, String > { public status() { super(ProteinFeatureType.this); } public Class<String> valueClass() { return String.class; } } public final class begin extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinFeature<I,RV,RVT,RE,RET>, ProteinFeatureType, FeatureType<I,RV,RVT,RE,RET>, FeatureTypeType, begin, Integer > { public begin() { super(ProteinFeatureType.this); } public Class<Integer> valueClass() { return Integer.class; } } public final class end extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinFeature<I,RV,RVT,RE,RET>, ProteinFeatureType, FeatureType<I,RV,RVT,RE,RET>, FeatureTypeType, end, Integer > { public end() { super(ProteinFeatureType.this); } public Class<Integer> valueClass() { return Integer.class; } } public final class original extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinFeature<I,RV,RVT,RE,RET>, ProteinFeatureType, FeatureType<I,RV,RVT,RE,RET>, FeatureTypeType, original, String > { public original() { super(ProteinFeatureType.this); } public Class<String> valueClass() { return String.class; } } public final class variation extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinFeature<I,RV,RVT,RE,RET>, ProteinFeatureType, FeatureType<I,RV,RVT,RE,RET>, FeatureTypeType, variation, String > { public variation() { super(ProteinFeatureType.this); } public Class<String> valueClass() { return String.class; } } public final class ref extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinFeature<I,RV,RVT,RE,RET>, ProteinFeatureType, FeatureType<I,RV,RVT,RE,RET>, FeatureTypeType, ref, String > { public ref() { super(ProteinFeatureType.this); } public Class<String> valueClass() { return String.class; } } } public final class ProteinGeneLocationType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinGeneLocation<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinGeneLocationType, GeneLocation<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.GeneLocationType > implements TypedEdge.Type.ManyToMany { public final name name = new name(); public ProteinGeneLocationType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.GeneLocation()); } @Override public ProteinGeneLocationType value() { return graph().ProteinGeneLocation(); } @Override public ProteinGeneLocation<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinGeneLocation<I,RV,RVT,RE,RET>(edge, this); } public final class name extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinGeneLocation<I,RV,RVT,RE,RET>, ProteinGeneLocationType, GeneLocation<I,RV,RVT,RE,RET>, GeneLocationType, name, String > { public name() { super(ProteinGeneLocationType.this); } public Class<String> valueClass() { return String.class; } } } public final class ProteinGeneNameType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinGeneName<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinGeneNameType, GeneName<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.GeneNameType > implements TypedEdge.Type.ManyToMany { public final geneNameType geneNameType = new geneNameType(); public ProteinGeneNameType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.GeneName()); } @Override public ProteinGeneNameType value() { return graph().ProteinGeneName(); } @Override public ProteinGeneName<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinGeneName<I,RV,RVT,RE,RET>(edge, this); } public final class geneNameType extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinGeneName<I,RV,RVT,RE,RET>, ProteinGeneNameType, GeneName<I,RV,RVT,RE,RET>, GeneNameType, geneNameType, String > { public geneNameType() { super(ProteinGeneNameType.this); } public Class<String> valueClass() { return String.class; } } } public final class IsoformEventGeneratorType extends UniProtEdgeType< Isoform<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.IsoformType, IsoformEventGenerator<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.IsoformEventGeneratorType, AlternativeProduct<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.AlternativeProductType > implements TypedEdge.Type.ManyToMany { public IsoformEventGeneratorType(RET raw) { super(UniProtGraph.this.Isoform(), raw, UniProtGraph.this.AlternativeProduct()); } @Override public IsoformEventGeneratorType value() { return graph().IsoformEventGenerator(); } @Override public IsoformEventGenerator<I,RV,RVT,RE,RET> from(RE edge) { return new IsoformEventGenerator<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinInterProType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinInterPro<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinInterProType, InterPro<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.InterProType > implements TypedEdge.Type.ManyToMany { public ProteinInterProType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.InterPro()); } @Override public ProteinInterProType value() { return graph().ProteinInterPro(); } @Override public ProteinInterPro<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinInterPro<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinKeggType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinKegg<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinKeggType, Kegg<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.KeggType > implements TypedEdge.Type.ManyToMany { public ProteinKeggType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.Kegg()); } @Override public ProteinKeggType value() { return graph().ProteinKegg(); } @Override public ProteinKegg<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinKegg<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinKeywordType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinKeyword<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinKeywordType, Keyword<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.KeywordType > implements TypedEdge.Type.ManyToMany { public ProteinKeywordType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.Keyword()); } @Override public ProteinKeywordType value() { return graph().ProteinKeyword(); } @Override public ProteinKeyword<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinKeyword<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinOrganismType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinOrganism<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinOrganismType, Organism<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.OrganismType > implements TypedEdge.Type.ManyToOne { public ProteinOrganismType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.Organism()); } @Override public ProteinOrganismType value() { return graph().ProteinOrganism(); } @Override public ProteinOrganism<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinOrganism<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinPfamType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinPfam<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinPfamType, Pfam<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.PfamType > implements TypedEdge.Type.ManyToMany { public ProteinPfamType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.Pfam()); } @Override public ProteinPfamType value() { return graph().ProteinPfam(); } @Override public ProteinPfam<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinPfam<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinPIRType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinPIR<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinPIRType, PIR<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.PIRType > implements TypedEdge.Type.ManyToMany { public ProteinPIRType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.PIR()); } @Override public ProteinPIRType value() { return graph().ProteinPIR(); } @Override public ProteinPIR<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinPIR<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinProteinInteractionType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinProteinInteraction<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinProteinInteractionType, Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType > implements TypedEdge.Type.ManyToMany { public ProteinProteinInteractionType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.Protein()); } @Override public ProteinProteinInteractionType value() { return graph().ProteinProteinInteraction(); } @Override public ProteinProteinInteraction<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinProteinInteraction<I,RV,RVT,RE,RET>(edge, this); } public final experiments experiments = new experiments(); public final organismsDiffer organismsDiffer = new organismsDiffer(); public final intActId1 intActId1 = new intActId1(); public final intActId2 intActId2 = new intActId2(); public final class experiments extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinProteinInteraction<I,RV,RVT,RE,RET>, ProteinProteinInteractionType, Protein<I,RV,RVT,RE,RET>, ProteinType, experiments, Integer > { public experiments() { super(ProteinProteinInteractionType.this); } public Class<Integer> valueClass() { return Integer.class; } } public final class organismsDiffer extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinProteinInteraction<I,RV,RVT,RE,RET>, ProteinProteinInteractionType, Protein<I,RV,RVT,RE,RET>, ProteinType, organismsDiffer, Boolean > { public organismsDiffer() { super(ProteinProteinInteractionType.this); } public Class<Boolean> valueClass() { return Boolean.class; } } public final class intActId1 extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinProteinInteraction<I,RV,RVT,RE,RET>, ProteinProteinInteractionType, Protein<I,RV,RVT,RE,RET>, ProteinType, intActId1, String > { public intActId1() { super(ProteinProteinInteractionType.this); } public Class<String> valueClass() { return String.class; } } public final class intActId2 extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinProteinInteraction<I,RV,RVT,RE,RET>, ProteinProteinInteractionType, Protein<I,RV,RVT,RE,RET>, ProteinType, intActId2, String > { public intActId2() { super(ProteinProteinInteractionType.this); } public Class<String> valueClass() { return String.class; } } } public final class ProteinIsoformType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinIsoform<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinIsoformType, Isoform<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.IsoformType > implements TypedEdge.Type.ManyToMany { public ProteinIsoformType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.Isoform()); } @Override public ProteinIsoformType value() { return graph().ProteinIsoform(); } @Override public ProteinIsoform<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinIsoform<I,RV,RVT,RE,RET>(edge, this); } } /* This edge corresponds to a protein-isoform interaction, as found in the comments section of the UniProt XML. By direct inspection of UniProt XML file we have concluded that: 1. the source id is always a protein, I don't know why 2. target can be either an isoform or a protein, and the id is in `interactant/id`. Isoform ids *look* to be `${protein.id}-{number}` We don't know if there are interactions between isoforms. */ public final class ProteinIsoformInteractionType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinIsoformInteraction<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinIsoformInteractionType, Isoform<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.IsoformType > implements TypedEdge.Type.ManyToMany { public ProteinIsoformInteractionType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.Isoform()); } @Override public ProteinIsoformInteractionType value() { return graph().ProteinIsoformInteraction(); } @Override public ProteinIsoformInteraction<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinIsoformInteraction<I,RV,RVT,RE,RET>(edge, this); } public final experiments experiments = new experiments(); public final organismsDiffer organismsDiffer = new organismsDiffer(); public final intActId1 intActId1 = new intActId1(); public final intActId2 intActId2 = new intActId2(); public final class experiments extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinIsoformInteraction<I,RV,RVT,RE,RET>, ProteinIsoformInteractionType, Isoform<I,RV,RVT,RE,RET>, IsoformType, experiments, Integer > { public experiments() { super(ProteinIsoformInteractionType.this); } public Class<Integer> valueClass() { return Integer.class; } } public final class organismsDiffer extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinIsoformInteraction<I,RV,RVT,RE,RET>, ProteinIsoformInteractionType, Isoform<I,RV,RVT,RE,RET>, IsoformType, organismsDiffer, Boolean > { public organismsDiffer() { super(ProteinIsoformInteractionType.this); } public Class<Boolean> valueClass() { return Boolean.class; } } public final class intActId1 extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinIsoformInteraction<I,RV,RVT,RE,RET>, ProteinIsoformInteractionType, Isoform<I,RV,RVT,RE,RET>, IsoformType, intActId1, String > { public intActId1() { super(ProteinIsoformInteractionType.this); } public Class<String> valueClass() { return String.class; } } public final class intActId2 extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinIsoformInteraction<I,RV,RVT,RE,RET>, ProteinIsoformInteractionType, Isoform<I,RV,RVT,RE,RET>, IsoformType, intActId2, String > { public intActId2() { super(ProteinIsoformInteractionType.this); } public Class<String> valueClass() { return String.class; } } } public final class ProteinReactomeTermType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinReactomeTerm<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinReactomeTermType, ReactomeTerm<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReactomeTermType > implements TypedEdge.Type.ManyToMany { public ProteinReactomeTermType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.ReactomeTerm()); } @Override public ProteinReactomeTermType value() { return graph().ProteinReactomeTerm(); } @Override public ProteinReactomeTerm<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinReactomeTerm<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinReferenceType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinReference<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinReferenceType, Reference<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceType > implements TypedEdge.Type.ManyToMany { public ProteinReferenceType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.Reference()); } @Override public ProteinReferenceType value() { return graph().ProteinReference(); } @Override public ProteinReference<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinReference<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinRefSeqType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinRefSeq<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinRefSeqType, RefSeq<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.RefSeqType > implements TypedEdge.Type.ManyToMany { public ProteinRefSeqType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.RefSeq()); } @Override public ProteinRefSeqType value() { return graph().ProteinRefSeq(); } @Override public ProteinRefSeq<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinRefSeq<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinSequenceCautionType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinSequenceCaution<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinSequenceCautionType, SequenceCaution<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.SequenceCautionType > implements TypedEdge.Type.ManyToMany { public final evidence evidence = new evidence(); public final status status = new status(); public final text text = new text(); public final id id = new id(); public final resource resource = new resource(); public final version version = new version(); public final position position = new position(); public ProteinSequenceCautionType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.SequenceCaution()); } @Override public ProteinSequenceCautionType value() { return graph().ProteinSequenceCaution(); } @Override public ProteinSequenceCaution<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinSequenceCaution<I,RV,RVT,RE,RET>(edge, this); } public final class position extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinSequenceCaution<I,RV,RVT,RE,RET>, ProteinSequenceCautionType, SequenceCaution<I,RV,RVT,RE,RET>, SequenceCautionType, position, String > { public position() { super(ProteinSequenceCautionType.this); } public Class<String> valueClass() { return String.class; } } public final class version extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinSequenceCaution<I,RV,RVT,RE,RET>, ProteinSequenceCautionType, SequenceCaution<I,RV,RVT,RE,RET>, SequenceCautionType, version, String > { public version() { super(ProteinSequenceCautionType.this); } public Class<String> valueClass() { return String.class; } } public final class resource extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinSequenceCaution<I,RV,RVT,RE,RET>, ProteinSequenceCautionType, SequenceCaution<I,RV,RVT,RE,RET>, SequenceCautionType, resource, String > { public resource() { super(ProteinSequenceCautionType.this); } public Class<String> valueClass() { return String.class; } } public final class id extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinSequenceCaution<I,RV,RVT,RE,RET>, ProteinSequenceCautionType, SequenceCaution<I,RV,RVT,RE,RET>, SequenceCautionType, id, String > { public id() { super(ProteinSequenceCautionType.this); } public Class<String> valueClass() { return String.class; } } public final class evidence extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinSequenceCaution<I,RV,RVT,RE,RET>, ProteinSequenceCautionType, SequenceCaution<I,RV,RVT,RE,RET>, SequenceCautionType, evidence, String > { public evidence() { super(ProteinSequenceCautionType.this); } public Class<String> valueClass() { return String.class; } } public final class status extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinSequenceCaution<I,RV,RVT,RE,RET>, ProteinSequenceCautionType, SequenceCaution<I,RV,RVT,RE,RET>, SequenceCautionType, status, String > { public status() { super(ProteinSequenceCautionType.this); } public Class<String> valueClass() { return String.class; } } public final class text extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinSequenceCaution<I,RV,RVT,RE,RET>, ProteinSequenceCautionType, SequenceCaution<I,RV,RVT,RE,RET>, SequenceCautionType, text, String > { public text() { super(ProteinSequenceCautionType.this); } public Class<String> valueClass() { return String.class; } } } public final class ProteinSubcellularLocationType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinSubcellularLocation<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinSubcellularLocationType, SubcellularLocation<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.SubcellularLocationType > implements TypedEdge.Type.ManyToMany { public final evidence evidence = new evidence(); public final status status = new status(); public final topology topology = new topology(); public final topologyStatus topologyStatus = new topologyStatus(); public final class topologyStatus extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinSubcellularLocation<I,RV,RVT,RE,RET>, ProteinSubcellularLocationType, SubcellularLocation<I,RV,RVT,RE,RET>, SubcellularLocationType, topologyStatus, String > { public topologyStatus() { super(ProteinSubcellularLocationType.this); } public Class<String> valueClass() { return String.class; } } public final class topology extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinSubcellularLocation<I,RV,RVT,RE,RET>, ProteinSubcellularLocationType, SubcellularLocation<I,RV,RVT,RE,RET>, SubcellularLocationType, topology, String > { public topology() { super(ProteinSubcellularLocationType.this); } public Class<String> valueClass() { return String.class; } } public final class evidence extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinSubcellularLocation<I,RV,RVT,RE,RET>, ProteinSubcellularLocationType, SubcellularLocation<I,RV,RVT,RE,RET>, SubcellularLocationType, evidence, String > { public evidence() { super(ProteinSubcellularLocationType.this); } public Class<String> valueClass() { return String.class; } } public final class status extends UniProtEdgeProperty< Protein<I,RV,RVT,RE,RET>, ProteinType, ProteinSubcellularLocation<I,RV,RVT,RE,RET>, ProteinSubcellularLocationType, SubcellularLocation<I,RV,RVT,RE,RET>, SubcellularLocationType, status, String > { public status() { super(ProteinSubcellularLocationType.this); } public Class<String> valueClass() { return String.class; } } public ProteinSubcellularLocationType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.SubcellularLocation()); } @Override public ProteinSubcellularLocationType value() { return graph().ProteinSubcellularLocation(); } @Override public ProteinSubcellularLocation<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinSubcellularLocation<I,RV,RVT,RE,RET>(edge, this); } } public final class ProteinUniGeneType extends UniProtEdgeType< Protein<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinType, ProteinUniGene<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ProteinUniGeneType, UniGene<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.UniGeneType > implements TypedEdge.Type.ManyToMany { public ProteinUniGeneType(RET raw) { super(UniProtGraph.this.Protein(), raw, UniProtGraph.this.UniGene()); } @Override public ProteinUniGeneType value() { return graph().ProteinUniGene(); } @Override public ProteinUniGene<I,RV,RVT,RE,RET> from(RE edge) { return new ProteinUniGene<I,RV,RVT,RE,RET>(edge, this); } } public final class ReferenceAuthorConsortiumType extends UniProtEdgeType< Reference<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceType, ReferenceAuthorConsortium<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceAuthorConsortiumType, Consortium<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ConsortiumType > implements TypedEdge.Type.ManyToMany { public ReferenceAuthorConsortiumType(RET raw) { super(UniProtGraph.this.Reference(), raw, UniProtGraph.this.Consortium()); } @Override public ReferenceAuthorConsortiumType value() { return graph().ReferenceAuthorConsortium(); } @Override public ReferenceAuthorConsortium<I,RV,RVT,RE,RET> from(RE edge) { return new ReferenceAuthorConsortium<I,RV,RVT,RE,RET>(edge, this); } } public final class ReferenceAuthorPersonType extends UniProtEdgeType< Reference<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceType, ReferenceAuthorPerson<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceAuthorPersonType, Person<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.PersonType > implements TypedEdge.Type.ManyToMany { public ReferenceAuthorPersonType(RET raw) { super(UniProtGraph.this.Reference(), raw, UniProtGraph.this.Person()); } @Override public ReferenceAuthorPersonType value() { return graph().ReferenceAuthorPerson(); } @Override public ReferenceAuthorPerson<I,RV,RVT,RE,RET> from(RE edge) { return new ReferenceAuthorPerson<I,RV,RVT,RE,RET>(edge, this); } } public final class ReferenceArticleType extends UniProtEdgeType< Reference<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceType, ReferenceArticle<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceArticleType, Article<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ArticleType > implements TypedEdge.Type.OneToOne { public ReferenceArticleType(RET raw) { super(UniProtGraph.this.Reference(), raw, UniProtGraph.this.Article()); } @Override public ReferenceArticleType value() { return graph().ReferenceArticle(); } @Override public ReferenceArticle<I,RV,RVT,RE,RET> from(RE edge) { return new ReferenceArticle<I,RV,RVT,RE,RET>(edge, this); } } public final class ReferenceBookType extends UniProtEdgeType< Reference<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceType, ReferenceBook<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceBookType, Book<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.BookType > implements TypedEdge.Type.OneToOne { public final title title = new title(); public final first first = new first(); public final last last = new last(); public final volume volume = new volume(); public ReferenceBookType(RET raw) { super(UniProtGraph.this.Reference(), raw, UniProtGraph.this.Book()); } @Override public ReferenceBookType value() { return graph().ReferenceBook(); } @Override public ReferenceBook<I,RV,RVT,RE,RET> from(RE edge) { return new ReferenceBook<I,RV,RVT,RE,RET>(edge, this); } public final class title extends UniProtEdgeProperty< Reference<I,RV,RVT,RE,RET>, ReferenceType, ReferenceBook<I,RV,RVT,RE,RET>, ReferenceBookType, Book<I,RV,RVT,RE,RET>, BookType, title, String > { public title() { super(ReferenceBookType.this); } public Class<String> valueClass() { return String.class; } } public final class volume extends UniProtEdgeProperty< Reference<I,RV,RVT,RE,RET>, ReferenceType, ReferenceBook<I,RV,RVT,RE,RET>, ReferenceBookType, Book<I,RV,RVT,RE,RET>, BookType, volume, String > { public volume() { super(ReferenceBookType.this); } public Class<String> valueClass() { return String.class; } } public final class first extends UniProtEdgeProperty< Reference<I,RV,RVT,RE,RET>, ReferenceType, ReferenceBook<I,RV,RVT,RE,RET>, ReferenceBookType, Book<I,RV,RVT,RE,RET>, BookType, first, Integer > { public first() { super(ReferenceBookType.this); } public Class<Integer> valueClass() { return Integer.class; } } public final class last extends UniProtEdgeProperty< Reference<I,RV,RVT,RE,RET>, ReferenceType, ReferenceBook<I,RV,RVT,RE,RET>, ReferenceBookType, Book<I,RV,RVT,RE,RET>, BookType, last, Integer > { public last() { super(ReferenceBookType.this); } public Class<Integer> valueClass() { return Integer.class; } } } public final class ReferencePatentType extends UniProtEdgeType< Reference<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceType, ReferencePatent<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferencePatentType, Patent<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.PatentType > implements TypedEdge.Type.OneToOne { public ReferencePatentType(RET raw) { super(UniProtGraph.this.Reference(), raw, UniProtGraph.this.Patent()); } @Override public ReferencePatentType value() { return graph().ReferencePatent(); } @Override public ReferencePatent<I,RV,RVT,RE,RET> from(RE edge) { return new ReferencePatent<I,RV,RVT,RE,RET>(edge, this); } } public final class ReferenceThesisType extends UniProtEdgeType< Reference<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceType, ReferenceThesis<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceThesisType, Thesis<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ThesisType > implements TypedEdge.Type.OneToOne { public ReferenceThesisType(RET raw) { super(UniProtGraph.this.Reference(), raw, UniProtGraph.this.Thesis()); } @Override public ReferenceThesisType value() { return graph().ReferenceThesis(); } @Override public ReferenceThesis<I,RV,RVT,RE,RET> from(RE edge) { return new ReferenceThesis<I,RV,RVT,RE,RET>(edge, this); } } public final class ReferenceSubmissionType extends UniProtEdgeType< Reference<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceType, ReferenceSubmission<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceSubmissionType, Submission<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.SubmissionType > implements TypedEdge.Type.OneToOne { public ReferenceSubmissionType(RET raw) { super(UniProtGraph.this.Reference(), raw, UniProtGraph.this.Submission()); } @Override public ReferenceSubmissionType value() { return graph().ReferenceSubmission(); } @Override public ReferenceSubmission<I,RV,RVT,RE,RET> from(RE edge) { return new ReferenceSubmission<I,RV,RVT,RE,RET>(edge, this); } } public final class ReferenceUnpublishedObservationType extends UniProtEdgeType< Reference<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceType, ReferenceUnpublishedObservation<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceUnpublishedObservationType, UnpublishedObservation<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.UnpublishedObservationType > implements TypedEdge.Type.OneToOne { public ReferenceUnpublishedObservationType(RET raw) { super(UniProtGraph.this.Reference(), raw, UniProtGraph.this.UnpublishedObservation()); } @Override public ReferenceUnpublishedObservationType value() { return graph().ReferenceUnpublishedObservation(); } @Override public ReferenceUnpublishedObservation<I,RV,RVT,RE,RET> from(RE edge) { return new ReferenceUnpublishedObservation<I,RV,RVT,RE,RET>(edge, this); } } public final class ReferenceOnlineArticleType extends UniProtEdgeType< Reference<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceType, ReferenceOnlineArticle<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ReferenceOnlineArticleType, OnlineArticle<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.OnlineArticleType > implements TypedEdge.Type.OneToOne { public ReferenceOnlineArticleType(RET raw) { super(UniProtGraph.this.Reference(), raw, UniProtGraph.this.OnlineArticle()); } @Override public ReferenceOnlineArticleType value() { return graph().ReferenceOnlineArticle(); } @Override public ReferenceOnlineArticle<I,RV,RVT,RE,RET> from(RE edge) { return new ReferenceOnlineArticle<I,RV,RVT,RE,RET>(edge, this); } } public final class SubcellularLocationParentType extends UniProtEdgeType< SubcellularLocation<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.SubcellularLocationType, SubcellularLocationParent<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.SubcellularLocationParentType, SubcellularLocation<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.SubcellularLocationType > implements TypedEdge.Type.ManyToOne { public SubcellularLocationParentType(RET raw) { super(UniProtGraph.this.SubcellularLocation(), raw, UniProtGraph.this.SubcellularLocation()); } @Override public SubcellularLocationParentType value() { return graph().SubcellularLocationParent(); } @Override public SubcellularLocationParent<I,RV,RVT,RE,RET> from(RE edge) { return new SubcellularLocationParent<I,RV,RVT,RE,RET>(edge, this); } } public final class SubmissionDBType extends UniProtEdgeType< Submission<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.SubmissionType, SubmissionDB<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.SubmissionDBType, DB<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.DBType > implements TypedEdge.Type.ManyToOne { public SubmissionDBType(RET raw) { super(UniProtGraph.this.Submission(), raw, UniProtGraph.this.DB()); } @Override public SubmissionDBType value() { return graph().SubmissionDB(); } @Override public SubmissionDB<I,RV,RVT,RE,RET> from(RE edge) { return new SubmissionDB<I,RV,RVT,RE,RET>(edge, this); } } public final class TaxonParentType extends UniProtEdgeType< Taxon<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.TaxonType, TaxonParent<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.TaxonParentType, Taxon<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.TaxonType > implements TypedEdge.Type.ManyToOne { public TaxonParentType(RET raw) { super(UniProtGraph.this.Taxon(), raw, UniProtGraph.this.Taxon()); } @Override public TaxonParentType value() { return graph().TaxonParent(); } @Override public TaxonParent<I,RV,RVT,RE,RET> from(RE edge) { return new TaxonParent<I,RV,RVT,RE,RET>(edge, this); } } public final class ThesisInstituteType extends UniProtEdgeType< Thesis<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ThesisType, ThesisInstitute<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.ThesisInstituteType, Institute<I,RV,RVT,RE,RET>, UniProtGraph<I,RV,RVT,RE,RET>.InstituteType > implements TypedEdge.Type.ManyToOne { public ThesisInstituteType(RET raw) { super(UniProtGraph.this.Thesis(), raw, UniProtGraph.this.Institute()); } @Override public ThesisInstituteType value() { return graph().ThesisInstitute(); } @Override public ThesisInstitute<I,RV,RVT,RE,RET> from(RE edge) { return new ThesisInstitute<I,RV,RVT,RE,RET>(edge, this); } } // helper classes public abstract class UniProtVertexProperty< V extends UniProtVertex<V, VT, I, RV, RVT, RE, RET>, VT extends UniProtGraph<I,RV,RVT,RE,RET>.UniProtVertexType<V, VT>, P extends UniProtVertexProperty<V, VT, P, PV>, PV > implements Property<V, VT, P, PV, UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET> { protected UniProtVertexProperty(VT type) { this.type = type; } private VT type; @Override public final VT elementType() { return type; } } public abstract class UniProtEdgeProperty< S extends UniProtVertex<S, ST, I, RV, RVT, RE, RET>, ST extends UniProtGraph<I,RV,RVT,RE,RET>.UniProtVertexType<S, ST>, E extends UniProtEdge<S, ST, E, ET, T, TT, I, RV, RVT, RE, RET>, ET extends UniProtGraph<I,RV,RVT,RE,RET>.UniProtEdgeType<S, ST, E, ET, T, TT>, T extends UniProtVertex<T, TT, I, RV, RVT, RE, RET>, TT extends UniProtGraph<I,RV,RVT,RE,RET>.UniProtVertexType<T, TT>, P extends UniProtEdgeProperty < S, ST, E, ET, T, TT, P, PV >, PV > implements Property<E, ET, P, PV, UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET> { protected UniProtEdgeProperty(ET type) { this.type = type; } private ET type; @Override public final ET elementType() { return type; } } public abstract static class UniProtVertex< V extends UniProtVertex<V, VT, I, RV, RVT, RE, RET>, VT extends UniProtGraph<I,RV,RVT,RE,RET>.UniProtVertexType<V, VT>, I extends UntypedGraph<RV, RVT, RE, RET>, RV, RVT, RE, RET > implements TypedVertex<V, VT, UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET> { private RV vertex; private VT type; protected UniProtVertex(RV vertex, VT type) { this.vertex = vertex; this.type = type; } @Override public UniProtGraph<I,RV,RVT,RE,RET> graph() { return type().graph(); } @Override public RV raw() { return this.vertex; } @Override public VT type() { return type; } } abstract class UniProtVertexType< V extends UniProtVertex<V, VT, I, RV, RVT, RE, RET>, VT extends UniProtGraph<I,RV,RVT,RE,RET>.UniProtVertexType<V, VT> > implements TypedVertex.Type<V, VT, UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET> { private RVT raw; protected UniProtVertexType(RVT raw) { this.raw = raw; } @Override public final RVT raw() { return raw; } @Override public final UniProtGraph<I,RV,RVT,RE,RET> graph() { return UniProtGraph.this; } } public abstract static class UniProtEdge< S extends UniProtVertex<S, ST, I, RV, RVT, RE, RET>, ST extends UniProtGraph<I,RV,RVT,RE,RET>.UniProtVertexType<S, ST>, E extends UniProtEdge<S, ST, E, ET, T, TT, I, RV, RVT, RE, RET>, ET extends UniProtGraph<I,RV,RVT,RE,RET>.UniProtEdgeType<S, ST, E, ET, T, TT>, T extends UniProtVertex<T, TT, I, RV, RVT, RE, RET>, TT extends UniProtGraph<I,RV,RVT,RE,RET>.UniProtVertexType<T, TT>, I extends UntypedGraph<RV, RVT, RE, RET>, RV, RVT, RE, RET > implements TypedEdge< S, ST, UniProtGraph<I,RV,RVT,RE,RET>, E, ET, UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET, T, TT, UniProtGraph<I,RV,RVT,RE,RET> > { private RE edge; private ET type; protected UniProtEdge(RE edge, ET type) { this.edge = edge; this.type = type; } @Override public UniProtGraph<I,RV,RVT,RE,RET> graph() { return type().graph(); } @Override public RE raw() { return this.edge; } @Override public ET type() { return type; } } abstract class UniProtEdgeType< S extends UniProtVertex<S, ST, I, RV, RVT, RE, RET>, ST extends UniProtGraph<I,RV,RVT,RE,RET>.UniProtVertexType<S, ST>, E extends UniProtEdge<S, ST, E, ET, T, TT, I, RV, RVT, RE, RET>, ET extends UniProtGraph<I,RV,RVT,RE,RET>.UniProtEdgeType<S, ST, E, ET, T, TT>, T extends UniProtVertex<T, TT, I, RV, RVT, RE, RET>, TT extends UniProtGraph<I,RV,RVT,RE,RET>.UniProtVertexType<T, TT> > implements TypedEdge.Type< S, ST, UniProtGraph<I,RV,RVT,RE,RET>, E, ET, UniProtGraph<I,RV,RVT,RE,RET>, I, RV, RVT, RE, RET, T, TT, UniProtGraph<I,RV,RVT,RE,RET> > { private RET raw; private ST srcT; private TT tgtT; protected UniProtEdgeType(ST srcT, RET raw, TT tgtT) { this.raw = raw; this.srcT = srcT; this.tgtT = tgtT; } @Override public final ST sourceType() { return srcT; } @Override public final TT targetType() { return tgtT; } @Override public final RET raw() { return raw; } @Override public final UniProtGraph<I,RV,RVT,RE,RET> graph() { return UniProtGraph.this; } } }
package com.jme3.system; import com.jme3.app.SettingsDialog; import com.jme3.app.SettingsDialog.SelectionListener; import com.jme3.asset.AssetManager; import com.jme3.asset.AssetNotFoundException; import com.jme3.asset.DesktopAssetManager; import com.jme3.audio.AudioRenderer; import com.jme3.system.JmeContext.Type; import com.jme3.texture.Image; import com.jme3.texture.image.DefaultImageRaster; import com.jme3.texture.image.ImageRaster; import com.jme3.util.Screenshots; import java.awt.EventQueue; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.net.URL; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import javax.imageio.ImageIO; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; /** * * @author Kirill Vainer, normenhansen */ public class JmeDesktopSystem extends JmeSystemDelegate { @Override public AssetManager newAssetManager(URL configFile) { return new DesktopAssetManager(configFile); } @Override public void writeImageFile(OutputStream outStream, String format, ByteBuffer imageData, int width, int height) throws IOException { BufferedImage awtImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); Screenshots.convertScreenShot(imageData, awtImage); ImageIO.write(awtImage, format, outStream); } @Override public ImageRaster createImageRaster(Image image, int slice) { assert image.getEfficentData() == null; return new DefaultImageRaster(image, slice); } @Override public AssetManager newAssetManager() { return new DesktopAssetManager(null); } @Override public void showErrorDialog(String message) { final String msg = message; final String title = "Error in application"; EventQueue.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(null, msg, title, JOptionPane.ERROR_MESSAGE); } }); } @Override public boolean showSettingsDialog(AppSettings sourceSettings, final boolean loadFromRegistry) { if (SwingUtilities.isEventDispatchThread()) { throw new IllegalStateException("Cannot run from EDT"); } final AppSettings settings = new AppSettings(false); settings.copyFrom(sourceSettings); String iconPath = sourceSettings.getSettingsDialogImage(); if(iconPath == null){ iconPath = ""; } final URL iconUrl = JmeSystem.class.getResource(iconPath.startsWith("/") ? iconPath : "/" + iconPath); if (iconUrl == null) { throw new AssetNotFoundException(sourceSettings.getSettingsDialogImage()); } final AtomicBoolean done = new AtomicBoolean(); final AtomicInteger result = new AtomicInteger(); final Object lock = new Object(); final SelectionListener selectionListener = new SelectionListener() { public void onSelection(int selection) { synchronized (lock) { done.set(true); result.set(selection); lock.notifyAll(); } } }; SwingUtilities.invokeLater(new Runnable() { public void run() { synchronized (lock) { SettingsDialog dialog = new SettingsDialog(settings, iconUrl, loadFromRegistry); dialog.setSelectionListener(selectionListener); dialog.showDialog(); } } }); synchronized (lock) { while (!done.get()) { try { lock.wait(); } catch (InterruptedException ex) { } } } sourceSettings.copyFrom(settings); return result.get() == SettingsDialog.APPROVE_SELECTION; } private JmeContext newContextLwjgl(AppSettings settings, JmeContext.Type type) { try { Class<? extends JmeContext> ctxClazz = null; switch (type) { case Canvas: ctxClazz = (Class<? extends JmeContext>) Class.forName("com.jme3.system.lwjgl.LwjglCanvas"); break; case Display: ctxClazz = (Class<? extends JmeContext>) Class.forName("com.jme3.system.lwjgl.LwjglDisplay"); break; case OffscreenSurface: ctxClazz = (Class<? extends JmeContext>) Class.forName("com.jme3.system.lwjgl.LwjglOffscreenBuffer"); break; default: throw new IllegalArgumentException("Unsupported context type " + type); } return ctxClazz.newInstance(); } catch (InstantiationException ex) { logger.log(Level.SEVERE, "Failed to create context", ex); } catch (IllegalAccessException ex) { logger.log(Level.SEVERE, "Failed to create context", ex); } catch (ClassNotFoundException ex) { logger.log(Level.SEVERE, "CRITICAL ERROR: Context class is missing!\n" + "Make sure jme3_lwjgl-ogl is on the classpath.", ex); } return null; } private JmeContext newContextJogl(AppSettings settings, JmeContext.Type type) { try { Class<? extends JmeContext> ctxClazz = null; switch (type) { case Display: ctxClazz = (Class<? extends JmeContext>) Class.forName("com.jme3.system.jogl.JoglNewtDisplay"); break; case Canvas: ctxClazz = (Class<? extends JmeContext>) Class.forName("com.jme3.system.jogl.JoglNewtCanvas"); break; default: throw new IllegalArgumentException("Unsupported context type " + type); } return ctxClazz.newInstance(); } catch (InstantiationException ex) { logger.log(Level.SEVERE, "Failed to create context", ex); } catch (IllegalAccessException ex) { logger.log(Level.SEVERE, "Failed to create context", ex); } catch (ClassNotFoundException ex) { logger.log(Level.SEVERE, "CRITICAL ERROR: Context class is missing!\n" + "Make sure jme3_jogl is on the classpath.", ex); } return null; } private JmeContext newContextCustom(AppSettings settings, JmeContext.Type type) { try { String className = settings.getRenderer().substring("CUSTOM".length()); Class<? extends JmeContext> ctxClazz = null; ctxClazz = (Class<? extends JmeContext>) Class.forName(className); return ctxClazz.newInstance(); } catch (InstantiationException ex) { logger.log(Level.SEVERE, "Failed to create context", ex); } catch (IllegalAccessException ex) { logger.log(Level.SEVERE, "Failed to create context", ex); } catch (ClassNotFoundException ex) { logger.log(Level.SEVERE, "CRITICAL ERROR: Context class is missing!", ex); } return null; } @Override public JmeContext newContext(AppSettings settings, Type contextType) { initialize(settings); JmeContext ctx; if (settings.getRenderer() == null || settings.getRenderer().equals("NULL") || contextType == JmeContext.Type.Headless) { ctx = new NullContext(); ctx.setSettings(settings); } else if (settings.getRenderer().startsWith("LWJGL")) { ctx = newContextLwjgl(settings, contextType); ctx.setSettings(settings); } else if (settings.getRenderer().startsWith("JOGL")) { ctx = newContextJogl(settings, contextType); ctx.setSettings(settings); } else if (settings.getRenderer().startsWith("CUSTOM")) { ctx = newContextCustom(settings, contextType); ctx.setSettings(settings); } else { throw new UnsupportedOperationException( "Unrecognizable renderer specified: " + settings.getRenderer()); } return ctx; } @Override public AudioRenderer newAudioRenderer(AppSettings settings) { initialize(settings); Class<? extends AudioRenderer> clazz = null; try { if (settings.getAudioRenderer().startsWith("LWJGL")) { clazz = (Class<? extends AudioRenderer>) Class.forName("com.jme3.audio.lwjgl.LwjglAudioRenderer"); } else if (settings.getAudioRenderer().startsWith("JOAL")) { clazz = (Class<? extends AudioRenderer>) Class.forName("com.jme3.audio.joal.JoalAudioRenderer"); } else { throw new UnsupportedOperationException( "Unrecognizable audio renderer specified: " + settings.getAudioRenderer()); } AudioRenderer ar = clazz.newInstance(); return ar; } catch (InstantiationException ex) { logger.log(Level.SEVERE, "Failed to create context", ex); } catch (IllegalAccessException ex) { logger.log(Level.SEVERE, "Failed to create context", ex); } catch (ClassNotFoundException ex) { logger.log(Level.SEVERE, "CRITICAL ERROR: Audio implementation class is missing!\n" + "Make sure jme3_lwjgl-oal or jm3_joal is on the classpath.", ex); } return null; } @Override public void initialize(AppSettings settings) { if (initialized) { return; } initialized = true; try { if (!lowPermissions) { // can only modify logging settings // JmeFormatter formatter = new JmeFormatter(); // Handler fileHandler = new FileHandler("jme.log"); // fileHandler.setFormatter(formatter); // Logger.getLogger("").addHandler(fileHandler); // Handler consoleHandler = new ConsoleHandler(); // consoleHandler.setFormatter(formatter); // Logger.getLogger("").removeHandler(Logger.getLogger("").getHandlers()[0]); // Logger.getLogger("").addHandler(consoleHandler); } // } catch (IOException ex){ // logger.log(Level.SEVERE, "I/O Error while creating log file", ex); } catch (SecurityException ex) { logger.log(Level.SEVERE, "Security error in creating log file", ex); } logger.log(Level.INFO, "Running on {0}", getFullName()); if (!lowPermissions) { try { Natives.extractNativeLibs(getPlatform(), settings); } catch (IOException ex) { logger.log(Level.SEVERE, "Error while copying native libraries", ex); } } } }
package com.crawljax.browser; import java.util.List; import org.apache.log4j.Logger; import org.openqa.selenium.chrome.ChromeDriver; /** * @author amesbah * @version $Id$ */ public class WebDriverChrome extends AbstractWebDriver { private static final Logger LOGGER = Logger.getLogger(WebDriverChrome.class.getName()); /** * Creates a new WebDriverChrome object. * * @param driver * the WebDriver ChromeDriver. * @param filterAttributes * the attributes to be filtered from DOM. * @param crawlWaitReload * the period to wait after a reload. * @param crawlWaitEvent * the period to wait after an event is fired. */ public WebDriverChrome(ChromeDriver driver, List<String> filterAttributes, long crawlWaitReload, long crawlWaitEvent) { super(driver, LOGGER, filterAttributes, crawlWaitReload, crawlWaitEvent); } /** * the empty constructor. * * @param filterAttributes * the attributes to be filtered from DOM. * @param crawlWaitReload * the period to wait after a reload. * @param crawlWaitEvent * the period to wait after an event is fired. */ public WebDriverChrome(List<String> filterAttributes, long crawlWaitReload, long crawlWaitEvent) { this(new ChromeDriver(), filterAttributes, crawlWaitReload, crawlWaitEvent); } @Override public EmbeddedBrowser clone() { return new WebDriverChrome(new ChromeDriver(), getFilterAttributes(), getCrawlWaitReload(), getCrawlWaitEvent()); } }
package com.curlip.unleashed.blocks; import java.util.ArrayList; import java.util.List; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.state.BlockState; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.model.ModelBakery; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import com.curlip.unleashed.UnleashedInfo; import com.curlip.unleashed.UnleashedMod; import com.curlip.unleashed.framework.SimpleBlock; import com.curlip.unleashed.framework.interfaces.UnleashedBlock; import com.curlip.unleashed.framework.interfaces.UnleashedMetaBlock; import com.curlip.unleashed.framework.interfaces.UnleashedMetaItem; public class Gradient extends Block implements UnleashedMetaBlock { public static final PropertyEnum COLOR = PropertyEnum.create("color", EnumDyeColor.class); private String id; public Gradient(String id, Class<? extends ItemBlock> iblock) { super(Material.rock); this.id = id; GameRegistry.registerBlock(this, iblock, id); setUnlocalizedName(id); setCreativeTab(UnleashedMod.tabUnleashed); setDefaultState(this.blockState.getBaseState().withProperty(COLOR, EnumDyeColor.WHITE)); } public List<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) { List<ItemStack> ret = new java.util.ArrayList<ItemStack>(); ret.add(new ItemStack(this, 1, state.getBlock().getMetaFromState(state))); return ret; } @Override protected BlockState createBlockState() { return new BlockState(this, new IProperty[] { COLOR }); } @Override public IBlockState getStateFromMeta(int meta) { return getDefaultState().withProperty(COLOR, EnumDyeColor.byMetadata(meta)); } @Override public int getMetaFromState(IBlockState state) { EnumDyeColor type = (EnumDyeColor) state.getValue(COLOR); return type.getMetadata(); } @Override public void getSubBlocks(Item itemIn, CreativeTabs tab, List list) { for(EnumDyeColor color : EnumDyeColor.values()){ list.add(new ItemStack(itemIn, 1, color.getMetadata())); } } @Override @SideOnly(Side.CLIENT) public int colorMultiplier(IBlockAccess worldIn, BlockPos pos, int renderPass){ EnumDyeColor color = (EnumDyeColor) Minecraft.getMinecraft().theWorld.getBlockState(pos).getProperties().get(COLOR); if(color != null){ return color.getMapColor().colorValue; } return 0xFFFFFF; } @Override public String getID() { return id; } @Override public Block getMinecraftBlock() { return this; } @Override public String getUnlocalizedNameForIndex(int index) { return getUnlocalizedName().substring(5) + "_" + index; } @Override public String getModelNameForIndex(int index) { return getUnlocalizedName().substring(5); } @Override public ItemStack getPickBlock(MovingObjectPosition target, World world, BlockPos pos){ return new ItemStack(Item.getItemFromBlock(this), 1, ((EnumDyeColor) world.getBlockState(pos).getProperties().get(COLOR)).getMetadata()); } @Override public void registerRender() { for(int i = 0; i <= 16; i++){ Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(this), i, new ModelResourceLocation(UnleashedInfo.MODID + ":" + getModelNameForIndex(i), "inventory")); } } }
package com.duck8823.web.line; import com.linecorp.bot.client.LineBotClient; import com.linecorp.bot.client.exception.LineBotAPIException; import com.linecorp.bot.model.callback.Event; import com.linecorp.bot.model.content.Content; import com.linecorp.bot.model.content.TextContent; import com.linecorp.bot.spring.boot.annotation.LineBotMessages; import lombok.extern.log4j.Log4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; @Log4j @RequestMapping("line") @RestController public class LineController { @Autowired private LineBotClient lineBotClient; @RequestMapping(path = "callback", method = RequestMethod.POST) public void callback(@LineBotMessages List<Event> events) throws LineBotAPIException { for (Event event : events) { Content content = event.getContent(); if (content instanceof TextContent) { TextContent text = (TextContent) content; log.debug(text.getText()); lineBotClient.sendText(text.getText(), text.getFrom()); } } } }
package com.ford.openxc.rain; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.openxc.measurements.Latitude; import com.openxc.measurements.Longitude; import com.openxc.measurements.UnrecognizedMeasurementTypeException; import com.openxc.remote.NoValueException; import com.openxc.VehicleService; import android.os.Handler; import android.util.Log; import android.widget.TextView; public class FetchAlertsTask implements Runnable { private final String TAG = "FetchAlertsTask"; private final String API_URL = "http://api.wunderground.com/api/dcffc57e05a81ad8/alerts/q/"; private VehicleService mVehicleService; private Handler mHandler; private TextView mAlertStatusView; public FetchAlertsTask(VehicleService vehicleService, Handler handler, TextView alertStatusView) { mVehicleService = vehicleService; mHandler = handler; mAlertStatusView = alertStatusView; } public void run() { double latitudeValue; double longitudeValue; try { Latitude latitude = (Latitude) mVehicleService.get(Latitude.class); Longitude longitude = (Longitude) mVehicleService.get(Longitude.class); latitudeValue = latitude.getValue().doubleValue(); longitudeValue = longitude.getValue().doubleValue(); } catch(UnrecognizedMeasurementTypeException e) { return; } catch (NoValueException e) { latitudeValue = 28; longitudeValue = 131; } Log.d(TAG, "Querying for weather alerts near " + latitudeValue + ", " + longitudeValue); StringBuilder urlBuilder = new StringBuilder(API_URL); urlBuilder.append(latitudeValue + ","); urlBuilder.append(longitudeValue + ".json"); final URL wunderground; try { wunderground = new URL(urlBuilder.toString()); } catch (MalformedURLException e) { Log.w(TAG, "URL we created isn't valid", e); return; } new Thread(new Runnable() { public void run() { fetchAlerts(wunderground); } }).start(); mHandler.postDelayed(this, 60000); } private void fetchAlerts(URL url) { StringBuilder builder = new StringBuilder(); try { HttpURLConnection wundergroundConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream( wundergroundConnection.getInputStream()); InputStreamReader is = new InputStreamReader(in); BufferedReader br = new BufferedReader(is); String line; while((line = br.readLine()) != null) { builder.append(line); } } catch (IOException e) { Log.w(TAG, "Unable to fetch alert information", e); return; } final boolean hasAlerts; try { JSONObject result = new JSONObject(builder.toString()); if(!result.has("alerts")) { hasAlerts = false; Log.d(TAG, "Wunderground didn't recognize the lat/long"); } else { JSONArray alerts = result.getJSONArray("alerts"); hasAlerts = alerts.length() > 0; Log.d(TAG, "Wunderground reports an alert: " + hasAlerts); } } catch(JSONException e) { Log.w(TAG, "Received invalid JSON", e); return; } mHandler.post(new Runnable() { public void run() { mAlertStatusView.setText("" + hasAlerts); } }); } }
package com.github.buzztaiki.jmpstat; import java.io.IOException; import java.io.PrintStream; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryUsage; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; public class JmpStat { private void usage(PrintStream out) { out.println("Usage: jmpstat <host>:<port> [<pool_names> <interval>]"); } private int run(Args args) throws Exception { String conn = args.get(0); if (conn == null) { usage(System.err); return 1; } try (JMXConnector jmxConn = JMXConnectorFactory.connect(getUrl(conn))) { MBeanServerConnection server = jmxConn.getMBeanServerConnection(); Set<String> poolNames = poolNames(args.get(1, "")); System.out.println(poolNames.size()); if (poolNames.isEmpty()) { printAllPools(server); } else { long interval = Long.parseLong(args.get(2, "1000")); pollLoop(server, poolNames, interval); } return 0; } } private Set<String> poolNames(String arg) { Set<String> xs = new HashSet<>(Arrays.asList(arg.split(" *, *", 0))); xs.remove(""); return xs; } private void printAllPools(MBeanServerConnection server) throws IOException { for (MemoryPoolMXBean memoryPool : ManagementFactory.getPlatformMXBeans(server, MemoryPoolMXBean.class)) { System.out.format("%s\t%s%n", memoryPool.getName(), memoryPool.getUsage()); } } private void pollLoop(MBeanServerConnection server, Set<String> poolNames, long interval) throws IOException { System.out.println("pool_name\tinit\tused\tcommitted\tmax"); for (;;) { for (MemoryPoolMXBean memoryPool : ManagementFactory.getPlatformMXBeans(server, MemoryPoolMXBean.class)) { if (!poolNames.contains(memoryPool.getName())) { continue; } MemoryUsage usage = memoryPool.getUsage(); System.out.format("%s\t%d\t%d\t%d\t%d%n", memoryPool.getName(), usage.getInit()/1024, usage.getUsed()/1024, usage.getCommitted()/1024, usage.getMax()/1024); } try { Thread.sleep(interval); } catch (InterruptedException e) { return; } } } private JMXServiceURL getUrl(String conn) throws IOException { try { return getPidUrl(Integer.parseInt(conn)); } catch (NumberFormatException e) { return new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + conn + "/jmxrmi"); } } private JMXServiceURL getPidUrl(int pid) throws IOException { /* LocalVirtualMachine vm = LocalVirtualMachine.getLocalVirtualMachine(pid); if (vm.isManageable()) { return new JMXServiceURL(vm.toUrl()); } vm.startManagementAgent(); if (vm.isManageable()) { return new JMXServiceURL(vm.toUrl()); } throw new IOException("Could not start agent for " + pid); */ throw new UnsupportedOperationException("getPidUrl"); } public static void main(String[] args) throws Exception { System.exit(new JmpStat().run(Args.of(args))); } }
package com.google.javascript.clutz; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.io.Files; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.regex.Pattern; /** * Representation of the data contained in a depgraph file. * * This JSON file is produced by Bazel javascript rules, and describes the shape of the dependency * graph for a given rule. We use it to determine which inputs to the compiler are srcs and which * come from deps. */ class Depgraph { private final Set<String> roots = new LinkedHashSet<>(); private final Set<String> nonroots = new LinkedHashSet<>(); private final Set<String> externs = new LinkedHashSet<>(); private Depgraph() {} boolean isRoot(String fileName) { // roots can only be empty if no Depgraphs were passed in, in which case we accept all files. return roots.isEmpty() || roots.contains(fileName); } Depgraph withNonrootsAsRoots() { Depgraph res = new Depgraph(); res.roots.addAll(roots); res.roots.addAll(nonroots); res.externs.addAll(externs); return res; } Set<String> getRoots() { return Collections.unmodifiableSet(roots); } Set<String> getNonroots() { return Collections.unmodifiableSet(nonroots); } Set<String> getExterns() { return Collections.unmodifiableSet(externs); } static Depgraph forRoots(Set<String> roots, Set<String> nonroots) { Depgraph result = new Depgraph(); result.roots.addAll(roots); result.nonroots.addAll(nonroots); return result; } // TODO(alexeagle): consider parsing into an object graph rather than nested loops over List<?>. static Depgraph parseFrom(List<String> fileNames) { Depgraph result = new Depgraph(); if (fileNames.isEmpty()) { return result; } for (String depgraphName : fileNames) { try { String depgraph = Files.toString(new File(depgraphName), UTF_8); List<List<?>> list = new Gson().fromJson(depgraph, new TypeToken<List<List<?>>>() { /* empty */ }.getType()); for (List<?> outer : list) { String key = (String) outer.get(0); @SuppressWarnings("unchecked") List<List<?>> value = (List<List<?>>) outer.get(1); result.collectFiles("roots".equals(key) , value); } } catch (FileNotFoundException e) { throw new IllegalArgumentException("depgraph file not found: " + depgraphName, e); } catch (IOException e) { throw new RuntimeException("error reading depgraph file " + depgraphName, e); } catch (Exception e) { throw new RuntimeException("malformed depgraph: " + depgraphName, e); } } if (result.roots.isEmpty() && result.externs.isEmpty()) { throw new IllegalStateException("No roots were found in the provided depgraphs files"); } return result; } // Strip brackets from bazel's "[blaze-out/.../]foo/bar" path prefixes. private static final Pattern GENERATED_FILE = Pattern.compile("^\\[([^]]+)\\]"); private void collectFiles(boolean isRoots, List<List<?>> fileList) { for (List<?> rootDescriptor : fileList) { String fileName = (String) rootDescriptor.get(0); // *-bootstrap.js are automatically added to every rule by Bazel if (fileName.endsWith("-bootstrap.js")) { continue; } @SuppressWarnings("unchecked") List<List<?>> fileProperties = (List<List<?>>) rootDescriptor.get(1); boolean isExterns = false; for (List<?> tuple: fileProperties) { String key = (String) tuple.get(0); if ("is_externs".equals(key) && Boolean.TRUE.equals(tuple.get(1))) { isExterns = true; break; } } fileName = GENERATED_FILE.matcher(fileName).replaceAll("$1"); if (isExterns) { externs.add(fileName); } else if (isRoots) { roots.add(fileName); } else { nonroots.add(fileName); } } } }
package com.google.sps.servlets; import com.google.gson.Gson; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeTokenRequest; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.store.FileDataStoreFactory; // import com.google.api.services.admin.directory.Directory; // import com.google.api.services.admin.directory.DirectoryScopes; // import com.google.api.services.admin.directory.model.User; // import com.google.api.services.admin.directory.model.Users; import java.io.IOException; import java.util.List; import java.util.ArrayList; @WebServlet("/token") public class TokenServlet extends HttpServlet { private final Gson GSON_OBJECT = new Gson(); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { final String authCode = (String) request.getParameter("code"); String CLIENT_SECRET_FILE = "/path/to/client_secret.json"; System.out.println("fin"); // GoogleClientSecrets clientSecrets = // GoogleClientSecrets.load( // JacksonFactory.getDefaultInstance(), new FileReader(CLIENT_SECRET_FILE)); GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest( new NetHttpTransport(), JacksonFactory.getDefaultInstance(), "https://oauth2.googleapis.com/token", "934172118901-btsopome05u5a6ma1rfkde5p12015th1.apps.googleusercontent.com", //clientSecrets.getDetails().getClientId(), "L0RvHrl9GHbl5cU6tbIPtOjt", //clientSecrets.getDetails().getClientSecret(), authCode, "/index.html") .execute(); String accessToken = tokenResponse.getAccessToken(); System.out.println(accessToken); } }
package com.googlecode.mp4parser; import com.coremedia.iso.BoxParser; import com.coremedia.iso.ChannelHelper; import com.coremedia.iso.Hex; import com.coremedia.iso.IsoFile; import com.coremedia.iso.IsoTypeWriter; import com.coremedia.iso.boxes.Box; import com.coremedia.iso.boxes.ContainerBox; import com.coremedia.iso.boxes.UserBox; import com.googlecode.mp4parser.annotations.DoNotParseDetail; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.logging.Logger; import static com.googlecode.mp4parser.util.CastUtils.l2i; /** * A basic on-demand parsing box. Requires the implementation of three methods to become a fully working box: * <ol> * <li>{@link #_parseDetails(java.nio.ByteBuffer)}</li> * <li>{@link #getContent(java.nio.ByteBuffer)}</li> * <li>{@link #getContentSize()}</li> * </ol> * additionally this new box has to be put into the <code>isoparser-default.properties</code> file so that * it is accessible by the <code>PropertyBoxParserImpl</code> */ public abstract class AbstractBox implements Box { private static Logger LOG = Logger.getLogger(AbstractBox.class.getName()); protected String type; private byte[] userType; private ContainerBox parent; private ByteBuffer content; private ByteBuffer deadBytes = null; protected AbstractBox(String type) { this.type = type; } protected AbstractBox(String type, byte[] userType) { this.type = type; this.userType = userType; } /** * Get the box's content size without its header. This must be the exact number of bytes * that <code>getContent(ByteBuffer)</code> writes. * * @return Gets the box's content size in bytes * @see #getContent(java.nio.ByteBuffer) */ protected abstract long getContentSize(); /** * Write the box's content into the given <code>ByteBuffer</code>. This must include flags * and version in case of a full box. <code>byteBuffer</code> has been initialized with * <code>getSize()</code> bytes. * * @param byteBuffer the sink for the box's content */ protected abstract void getContent(ByteBuffer byteBuffer); /** * Parse the box's fields and child boxes if any. * * @param content the box's raw content beginning after the 4-cc field. */ protected abstract void _parseDetails(ByteBuffer content); /** * Read the box's content from a byte channel without parsing it. Parsing is done on-demand. * * @param readableByteChannel the (part of the) iso file to parse * @param contentSize expected contentSize of the box * @param boxParser creates inner boxes * @throws IOException in case of an I/O error. */ @DoNotParseDetail public void parse(ReadableByteChannel readableByteChannel, ByteBuffer header, long contentSize, BoxParser boxParser) throws IOException { if (readableByteChannel instanceof FileChannel && contentSize > 1024 * 1024) { // It's quite expensive to map a file into the memory. Just do it when the box is larger than a MB. content = ((FileChannel) readableByteChannel).map(FileChannel.MapMode.READ_ONLY, ((FileChannel) readableByteChannel).position(), contentSize); ((FileChannel) readableByteChannel).position(((FileChannel) readableByteChannel).position() + contentSize); } else { assert contentSize < Integer.MAX_VALUE; content = ChannelHelper.readFully(readableByteChannel, contentSize); } } public void getBox(WritableByteChannel os) throws IOException { ByteBuffer bb = ByteBuffer.allocate(l2i(getSize())); getHeader(bb); if (content == null) { getContent(bb); if (deadBytes != null) { deadBytes.rewind(); while (deadBytes.remaining() > 0) { bb.put(deadBytes); } } } else { content.rewind(); bb.put(content); } bb.rewind(); os.write(bb); } /** * Parses the raw content of the box. It surrounds the actual parsing * which is done */ synchronized final void parseDetails() { if (content != null) { ByteBuffer content = this.content; this.content = null; content.rewind(); _parseDetails(content); if (content.remaining() > 0) { deadBytes = content.slice(); } assert verify(content); } } /** * Sets the 'dead' bytes. These bytes are left if the content of the box * has been parsed but not all bytes have been used up. * * @param newDeadBytes the unused bytes with no meaning but required for bytewise reconstruction */ protected void setDeadBytes(ByteBuffer newDeadBytes) { deadBytes = newDeadBytes; } /** * Gets the full size of the box including header and content. * * @return the box's size */ public long getSize() { long size = (content == null ? getContentSize() : content.limit()); size += (8 + // size|type (size >= ((1L << 32) - 8) ? 8 : 0) + // 32bit - 8 byte size and type (UserBox.TYPE.equals(getType()) ? 16 : 0)); size += (deadBytes == null ? 0 : deadBytes.limit()); return size; } @DoNotParseDetail public String getType() { return type; } @DoNotParseDetail public byte[] getUserType() { return userType; } @DoNotParseDetail public ContainerBox getParent() { return parent; } @DoNotParseDetail public void setParent(ContainerBox parent) { this.parent = parent; } @DoNotParseDetail public IsoFile getIsoFile() { return parent.getIsoFile(); } /** * Check if details are parsed. * * @return <code>true</code> whenever the content <code>ByteBuffer</code> is not <code>null</code> */ public boolean isParsed() { return content == null; } /** * Verifies that a box can be reconstructed byte-exact after parsing. * * @param content the raw content of the box * @return <code>true</code> if raw content exactly matches the reconstructed content */ private boolean verify(ByteBuffer content) { ByteBuffer bb = ByteBuffer.allocate(l2i(getContentSize() + (deadBytes != null ? deadBytes.limit() : 0))); getContent(bb); if (deadBytes != null) { deadBytes.rewind(); while (deadBytes.remaining() > 0) { bb.put(deadBytes); } } content.rewind(); bb.rewind(); if (content.remaining() != bb.remaining()) { LOG.severe(this.getType() + ": remaining differs " + content.remaining() + " vs. " + bb.remaining()); return false; } int p = content.position(); for (int i = content.limit() - 1, j = bb.limit() - 1; i >= p; i byte v1 = content.get(i); byte v2 = bb.get(j); if (v1 != v2) { LOG.severe("buffers differ at " + i + ": " + v1 + "/" + v2); byte[] b1 = new byte[content.remaining()]; byte[] b2 = new byte[bb.remaining()]; content.get(b1); bb.get(b2); System.err.println(Hex.encodeHex(b1)); System.err.println(Hex.encodeHex(b2)); return false; } } return true; } private boolean isSmallBox() { return (content == null ? (getContentSize() + (deadBytes != null ? deadBytes.limit() : 0) + 8) : content.limit()) < 1L << 32; } private void getHeader(ByteBuffer byteBuffer) { if (isSmallBox()) { IsoTypeWriter.writeUInt32(byteBuffer, this.getSize()); byteBuffer.put(IsoFile.fourCCtoBytes(getType())); } else { IsoTypeWriter.writeUInt32(byteBuffer, 1); byteBuffer.put(IsoFile.fourCCtoBytes(getType())); IsoTypeWriter.writeUInt64(byteBuffer, getSize()); } if (UserBox.TYPE.equals(getType())) { byteBuffer.put(getUserType()); } } }
package com.imsweb.naaccrxml.sas; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; /** * Use this class to convert a given CSV file into a NAACCR XML file. */ public class SasCsvToXml { private File _csvFile, _xmlFile; private String _naaccrVersion, _recordType; public SasCsvToXml(String xmlPath, String naaccrVersion, String recordType) { this(xmlPath.replace(".xml", ".csv"), xmlPath, naaccrVersion, recordType); } public SasCsvToXml(String csvPath, String xmlPath, String naaccrVersion, String recordType) { _xmlFile = new File(xmlPath); System.out.println(" > target XML: " + _xmlFile.getAbsolutePath()); if (csvPath.endsWith(".gz")) csvPath = csvPath.replace(".gz", ""); _csvFile = new File(csvPath); System.out.println(" > temp CSV: " + _csvFile.getAbsolutePath()); _naaccrVersion = naaccrVersion; _recordType = recordType; } public String getCsvPath() { return _csvFile.getPath(); } public String getXmlPath() { return _xmlFile.getPath(); } public String getNaaccrVersion() { return _naaccrVersion; } public String getRecordType() { return _recordType; } public List<SasFieldInfo> getFields() { return SasUtils.getFields(_recordType, _naaccrVersion); } public void convert() throws IOException { convert(null); } public void convert(String fields) throws IOException { Set<String> requestedFields = null; if (fields != null) { requestedFields = new HashSet<>(); for (String s : fields.split(",")) requestedFields.add(s.trim()); } List<String> rootFields = new ArrayList<>(), patientFields = new ArrayList<>(), tumorFields = new ArrayList<>(); for (SasFieldInfo field : getFields()) { if (requestedFields == null || requestedFields.contains(field.getNaaccrId())) { if ("NaaccrData".equals(field.getParentTag())) rootFields.add(field.getNaaccrId()); else if ("Patient".equals(field.getParentTag())) patientFields.add(field.getNaaccrId()); else if ("Tumor".equals(field.getParentTag())) tumorFields.add(field.getNaaccrId()); } } LineNumberReader reader = null; BufferedWriter writer = null; try { reader = new LineNumberReader(new InputStreamReader(new FileInputStream(_csvFile), StandardCharsets.UTF_8)); writer = SasUtils.createWriter(_xmlFile); Pattern p = Pattern.compile(","); List<String> headers = new ArrayList<>(); headers.addAll(Arrays.asList(p.split(reader.readLine()))); int patNumIdx = headers.indexOf("patientIdNumber"); if (patNumIdx == -1) throw new IOException("Unable to find 'patientIdNumber' in the headers"); String currentPatNum = null; String line = reader.readLine(); while (line != null) { String[] valArray = p.split(line); Map<String, String> values = new HashMap<>(); for (int i = 0; i < valArray.length; i++) values.put(headers.get(i), valArray[i]); String patNum = values.get("patientIdNumber"); if (patNum == null) throw new IOException("Line " + reader.getLineNumber() + ": patient ID Number is required to write XML files"); // do we have to write the root? if (currentPatNum == null) { writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.write("\n"); writer.write("<NaaccrData"); writer.write(" baseDictionaryUri=\"http://naaccr.org/naaccrxml/naaccr-dictionary-" + _naaccrVersion + ".xml\""); writer.write(" recordType=\"" + _recordType + "\""); writer.write(" specificationVersion=\"1.3\""); writer.write(" xmlns=\"http://naaccr.org/naaccrxml\""); writer.write(">\n"); for (String id : rootFields) { String val = values.get(id); if (val != null && !val.trim().isEmpty()) writer.write(" <Item naaccrId=\"" + id + "\">" + val + "</Item>\n"); } } // do we have to write the patient? if (currentPatNum == null || !currentPatNum.equals(patNum)) { if (currentPatNum != null) writer.write(" </Patient>\n"); writer.write(" <Patient>\n"); for (String id : patientFields) { String val = values.get(id); if (val != null && !val.trim().isEmpty()) writer.write(" <Item naaccrId=\"" + id + "\">" + val + "</Item>\n"); } } // we always have to write the tumor! writer.write(" <Tumor>\n"); for (String id : tumorFields) { String val = values.get(id); if (val != null && !val.trim().isEmpty()) writer.write(" <Item naaccrId=\"" + id + "\">" + val + "</Item>\n"); } writer.write(" </Tumor>\n"); currentPatNum = patNum; line = reader.readLine(); } writer.write(" </Patient>\n"); writer.write("</NaaccrData>"); } finally { if (writer != null) writer.close(); if (reader != null) reader.close(); } } public void cleanup() { if (!_csvFile.delete()) System.err.println("!!! Unable to cleanup tmp CSV file."); } }
package com.javatao.jkami.support; import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.javatao.jkami.JkException; import com.javatao.jkami.Page; import com.javatao.jkami.RunConfing; import com.javatao.jkami.jdbc.BeanListHandle; import com.javatao.jkami.jdbc.JdbcTypesUtils; import com.javatao.jkami.jdbc.MapListHandle; import com.javatao.jkami.jdbc.NumberHandle; import com.javatao.jkami.jdbc.ResultHandle; import com.javatao.jkami.utils.FKParse; import com.javatao.jkami.utils.JkBeanUtils; import com.javatao.jkami.utils.SqlUtils; /** * jdbc * * @author tao */ public class DataMapper { private static DataMapper mapper; private static final Log logger = LogFactory.getLog(DataMapper.class); private static final String DEFAULT_BEAN = "defaultBean"; private static final String EMPTY = ""; private static final String SEMICOLON = ";"; public static final String DATABSE_TYPE_MYSQL = "mysql"; public static final String DATABSE_TYPE_POSTGRE = "postgresql"; public static final String DATABSE_TYPE_ORACLE = "oracle"; public static final String DATABSE_TYPE_SQLSERVER = "sqlserver"; /** * SQL */ // mysql select * from ( {0} ) page_tab limit {1},{2} private static final String MYSQL_SQL = "select * from ( {0} ) page_kami_tab limit ?,?"; // postgresql {2} offset {1} private static final String POSTGRE_SQL = "select * from ( {0} ) page_kami_tab limit ? offset ?"; // oracle where rownum <= {1}) where rownum_>{2} private static final String ORACLE_SQL = "select * from (select row_.*,rownum rownum_ from ({0}) row_ where rownum <= ?) where rownum_> ? "; private static final String SQLSERVER_SQL = "select * from ( select row_number() over(order by tempColumn) tempRowNumber, * from (select top ? tempColumn = 0, {0} ) t ) tt where tempRowNumber > ? "; // sqlserver private static final String COUNT_SQL = "select count(1) from ( {0} ) conut_kami_tab"; // count_sql // oracle private static final String SEQUENCE_SQL = "select {0}.nextval from dual"; // sequence_sql private static final Pattern pat = Pattern.compile(":[ tnx0Bfr]*[a-z.A-Z]+"); private static final String numberRegex = "^:\\d+$"; /** * Connection * * @return Connection */ private Connection getCon() { return RunConfing.getConfig().getConnection(); } /** * * * @param con * Connection */ private void doReleaseConnection(Connection con) { RunConfing.getConfig().doReleaseConnection(con); } /** * DataMapper * * @return DataMapper */ public static DataMapper getMapper() { if (mapper == null) { mapper = new DataMapper(); } return mapper; } /** * * * @param ps * PreparedStatement * @param args * * @throws SQLException * SQLException */ private void setPSValue(PreparedStatement ps, Object... args) throws SQLException { if (args != null && args.length > 0) { if (args[0] instanceof Collection) { args = ((Collection<?>) args[0]).toArray(); } for (int i = 0; i < args.length; i++) { Object v = args[i]; int index = i + 1; if (v instanceof Date) { ps.setTimestamp(index, new java.sql.Timestamp(((Date) v).getTime())); } else { ps.setObject(index, v); } if (logger.isDebugEnabled()) { logger.debug("params[" + i + ":" + v + "]"); } } } } /** * * * @param ps * PreparedStatement * @param entity * * @return */ private int setPSEntityValue(PreparedStatement ps, Object entity) { try { Class<?> classType = entity.getClass(); List<String> fileds = SqlUtils.getEntityAttrMp(classType); for (int i = 0; i < fileds.size(); i++) { String fd = fileds.get(i); Object value = JkBeanUtils.getPropertyValue(entity, fd); int index = i + 1; if (value == null) { ps.setNull(index, JdbcTypesUtils.getJdbcType(value)); } else { if (value instanceof Date) { ps.setTimestamp(index, new java.sql.Timestamp(((Date) value).getTime())); } else { ps.setObject(index, value); } } } return fileds.size(); } catch (Exception e) { throw new JkException(e); } } /** * * * @param o * * @return */ public int save(Object o) { RunConfing config = RunConfing.getConfig(); Connection con = config.getConnection(); Class<?> classType = o.getClass(); String sql = SqlUtils.getSqls(classType, SqlUtils.TYPE.INSERT); try { Object[] key = SqlUtils.getTableKey(classType); if (key == null) { throw new JkException(classType.getPackage() + classType.getName() + " no @key annotation "); } Object idValue = JkBeanUtils.getPropertyValue(o, (String) key[0]); String dbType = config.getDbType(); if (idValue == null) { if (dbType.contains(DATABSE_TYPE_ORACLE)) { String s = SqlUtils.getSequenceGeneratorVal(classType); if (s != null) { String sequenceSql = MessageFormat.format(SEQUENCE_SQL, s); idValue = query(sequenceSql, new NumberHandle<Long>()); if (idValue != null) { JkBeanUtils.setProperty(o, (String) key[1], idValue); } } } } PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); setPSEntityValue(ps, o); int n = ps.executeUpdate(); if (idValue == null) { ResultSet rs = ps.getGeneratedKeys(); ResultHandle<Long> handle = new NumberHandle<Long>(); idValue = handle.handle(rs); JkBeanUtils.setProperty(o, (String) key[1], idValue); } ps.close(); return n; } catch (Exception e) { throw new RuntimeException(e); } finally { doReleaseConnection(con); } } /** * * * @param <T> * * @param sql * sql * @param result * * @param currentDepth * * @param maxDepth * * @param params * * @return */ public <T> T queryForObject(String sql, Class<T> result, int currentDepth, int maxDepth, Object... params) { List<T> list = query(sql, new BeanListHandle<>(result, currentDepth, maxDepth), params); if (list != null) { if (list.size() > 1) { throw new JkException("queryForObject size = " + list.size() + " not one"); } if (list.size() == 1) { return list.get(0); } } return null; } /** * * * @param <E> * * @param sql * sql * @param handle * * @param params * * @return */ public <E> E query(String sql, ResultHandle<E> handle, Object... params) { Connection con = getCon(); try { if (logger.isDebugEnabled()) { logger.debug(sql); } PreparedStatement ps = con.prepareStatement(sql); setPSValue(ps, params); ResultSet rs = ps.executeQuery(); E rows = handle.handle(rs); ps.close(); return rows; } catch (Exception e) { throw new JkException(e); } finally { doReleaseConnection(con); } } /** * * * @param <T> * * @param result * * @param sqlParameter * sql parameter * @return */ public <T> T findOne(Class<T> result, Map<String, Object> sqlParameter) { Connection con = getCon(); StringBuilder sb = new StringBuilder(SqlUtils.getSqls(result, SqlUtils.TYPE.SELECT)); try { sb.append(" where 1=1 "); Map<String, String> filedMap = SqlUtils.getEntityFiledColumnMap(result); List<Object> values = new ArrayList<>(); for (String ky : sqlParameter.keySet()) { String col = filedMap.get(ky); if (col == null) { col = ky; } sb.append(" and " + col + " = ? "); values.add(sqlParameter.get(ky)); } String sql = sb.toString(); int maxDepth = JkBeanUtils.getMaxDepth(result); return queryForObject(sql, result, 1, maxDepth, values); } catch (Exception e) { throw new JkException(e); } finally { doReleaseConnection(con); } } /** * * * @param sql * sql * @param params * * @return */ public List<Map<String, Object>> queryForMap(String sql, Object... params) { return query(sql, new MapListHandle(), params); } /** * id * * @param <T> * * @param id * ID * @param classType * * @return */ public <T> T findById(Serializable id, Class<T> classType) { Connection con = getCon(); String sql = SqlUtils.getSqls(classType, SqlUtils.TYPE.SELECT); try { Object[] key = SqlUtils.getTableKey(classType); if (key == null) { throw new RuntimeException(classType.getPackage() + classType.getName() + "no @key annotation "); } sql += " where " + key[1] + " = ? "; int maxDepth = JkBeanUtils.getMaxDepth(classType); return queryForObject(sql, classType, 1, maxDepth, id); } catch (Exception e) { throw new RuntimeException(e); } finally { doReleaseConnection(con); } } /** * * * @param <T> * * @param o * * @return */ public <T> int updateById(T o) { Class<?> classType = o.getClass(); String sql = SqlUtils.getSqls(classType, SqlUtils.TYPE.UPDATE); Object[] key = SqlUtils.getTableKey(classType); if (key == null) { throw new RuntimeException(classType.getPackage() + classType.getName() + "no @key annotation "); } sql += " where " + key[1] + " = ? "; Object kv = JkBeanUtils.getPropertyValue(o, (String) key[0]); return executeUpdate(sql, kv); } /** * * * @param sql * sql * @param params * * @return */ public int executeUpdate(String sql, Object... params) { Connection con = getCon(); try { if (logger.isDebugEnabled()) { logger.debug(sql); } PreparedStatement ps = con.prepareStatement(sql); ps.addBatch(sql); setPSValue(ps, params); int n = ps.executeUpdate(); ps.close(); return n; } catch (Exception e) { throw new JkException(e); } finally { doReleaseConnection(con); } } /** * * * @param sqls * sql * @param params * * @return */ public Object executeBatchUpdate(String sqls, Object... params) { Connection con = getCon(); try { if (sqls.indexOf(SEMICOLON) == -1) { return executeUpdate(sqls, params); } String[] sqlss = sqls.replaceAll("\r|\n", EMPTY).split(SEMICOLON); int length = sqlss.length; Statement st = con.createStatement(); for (int i = 0; i < length; i++) { String sql = sqlss[i]; if (logger.isDebugEnabled()) { logger.debug("addBatch: " + sql); } st.addBatch(sql); } if (logger.isDebugEnabled()) { logger.debug("executeBatchUpdate size: " + length); } int[] batch = st.executeBatch(); st.close(); return batch; } catch (Exception e) { throw new JkException(e); } finally { doReleaseConnection(con); } } /** * id <br> * delete from tabel where id=? * * @param <T> * * @param id * id * @param classType * * @return */ public <T> int deleteById(Serializable id, Class<T> classType) { Object[] key = SqlUtils.getTableKey(classType); StringBuilder sb = new StringBuilder("delete from "); sb.append(SqlUtils.getTableName(classType)); sb.append(" where " + key[1] + " = ? "); String sql = sb.toString(); return executeUpdate(sql, id); } /** * * * @param <T> * * @param o * * @return */ public <T> int updateNotNullById(T o) { Class<?> classType = o.getClass(); StringBuilder sb = new StringBuilder("update "); sb.append(SqlUtils.getTableName(classType)); sb.append(" set "); List<String> attrs = SqlUtils.getEntityAttrMp(classType); Map<String, String> filedMap = SqlUtils.getEntityFiledColumnMap(classType); List<Object> values = new ArrayList<>(); boolean isFirst = true; for (int i = 0; i < attrs.size(); i++) { String attr = attrs.get(i); Object value = JkBeanUtils.getPropertyValue(o, attr); if (value != null) { if (!isFirst) { sb.append(","); } sb.append(filedMap.get(attr) + " = ? "); values.add(value); isFirst = false; } } String sql = sb.toString(); return executeUpdate(sql, values); } /** * * * @param <T> * * @param sql * sql * @param classType * * @param page * * @return */ public <T> Page<T> findPage(String sql, Class<T> classType, Page<T> page) { if (page == null) { page = new Page<>(); } if (sql == null) { sql = SqlUtils.getSelectSqls(classType); } RunConfing config = RunConfing.getConfig(); String dbType = config.getDbType(); ArrayList<Object> params = new ArrayList<>(); String sqlParam = SqlUtils.getSearchParames(classType, page, params); sql += sqlParam; String pageSql = createPageSql(dbType, sql, page.getPage(), page.getSize(), params); String countSql = MessageFormat.format(COUNT_SQL, sql); int maxDepth = JkBeanUtils.getMaxDepth(classType); List<T> result = query(pageSql, new BeanListHandle<>(classType, 1, maxDepth), params); params.remove(params.size() - 1); params.remove(params.size() - 1); Long total = query(countSql, new NumberHandle<>(), params); page.setRows(result); page.setTotal(total); return page; } /** * SQL * * @param dbType * * @param sql * sql * @param page * * @param rows * * @param params * * @return sql */ public static String createPageSql(String dbType, String sql, int page, int rows, ArrayList<Object> params) { int beginNum = (page - 1) * rows; if (JkBeanUtils.isBlank(dbType)) { throw new RuntimeException("(:dbType) ,"); } if (dbType.indexOf(DATABSE_TYPE_MYSQL) > -1) { sql = MessageFormat.format(MYSQL_SQL, sql); params.add(beginNum); params.add(rows); } else if (dbType.indexOf(DATABSE_TYPE_POSTGRE) > -1) { sql = MessageFormat.format(POSTGRE_SQL, sql); params.add(rows); params.add(beginNum); } else { int endIndex = beginNum + rows; params.add(endIndex); params.add(beginNum); if (dbType.indexOf(DATABSE_TYPE_ORACLE) > -1) { sql = MessageFormat.format(ORACLE_SQL, sql); } else if (dbType.indexOf(DATABSE_TYPE_SQLSERVER) > -1) { sql = MessageFormat.format(SQLSERVER_SQL, sql); } } return sql; } /** * - Map * * @param executeSql * sql * @param sqlParamsMap * * @param result * * @param k * * @return sql */ public String placeholderSqlParam(String executeSql, Map<String, Object> sqlParamsMap, List<Object> result, String... k) { String key = EMPTY; if (k != null && k.length > 0) { key = k[0]; } Matcher m = pat.matcher(executeSql); while (m.find()) { String match = m.group(); if (match.matches(numberRegex)) { continue; } executeSql = executeSql.replace(match, "?"); Object v = FKParse.parseTemplateContent("${" + match.replace(":", key).trim() + "}", sqlParamsMap); result.add(v); if (logger.isDebugEnabled()) { logger.debug(" Match [" + match + "] at positions " + m.start() + "-" + (m.end() - 1) + " value:" + v); } } // sql ${...} if (sqlParamsMap != null && !sqlParamsMap.isEmpty()) { executeSql = FKParse.parseTemplateContent(executeSql, sqlParamsMap); } return executeSql; } /** * - Map * * @param executeSql * sql * @param result * * @param value * * @return sql */ public String placeholderSqlParam(String executeSql, List<Object> result, Object value) { Map<String, Object> sqlParamsMap = new HashMap<>(); sqlParamsMap.put(DEFAULT_BEAN, value); return placeholderSqlParam(executeSql, sqlParamsMap, result, DEFAULT_BEAN + "."); } }
package com.joelhockey.jairusunit; import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.regex.Pattern; import junit.framework.Assert; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestResult; import junit.framework.TestSuite; import org.mozilla.javascript.Context; import org.mozilla.javascript.ContextFactory; import org.mozilla.javascript.Function; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.NativeJavaObject; import org.mozilla.javascript.RhinoException; import org.mozilla.javascript.tools.debugger.Main; /** * Main class to execute JairusUnit. Takes names of js files as args. * @author Joel Hockey */ public class JairusUnit { public static final int SUCCESS_EXIT = 0; public static final int FAILURE_EXIT = 1; public static final int EXCEPTION_EXIT = 2; public static final Pattern STACK_TRACE_FILTER = Pattern.compile( "^\tat (" + "junit|java.lang.reflect" + "|org.mozilla.javascript.(Context|JavaAdapter|MemberBox|NativeJava|[Oo]ptimizer|ScriptRuntime|.*jairusunit.js)" + "|sun.reflect" + "|org.apache.tools.ant" + "|com.joelhockey.jairusunit" + ")" ); /** * Return JUnit {@link TestSuite} containing all * tests from given js file. * @param file javascript file containing tests * @return test suite */ public static TestSuite jairusunitTestSuite(String file) { TestSuite result = new TestSuite("jairusunit"); Context cx = Context.enter(); try { JairusUnitScope scope = new JairusUnitScope(); // ClassCache.get(scope).setCachingEnabled(false); // need this try { scope.load("jairusunit.js"); Function jairusunitTestSuite = (Function) scope.get("jairusunitTestSuite", scope); NativeJavaObject obj = (NativeJavaObject) jairusunitTestSuite.call( cx, scope, jairusunitTestSuite, new Object[] {file}); TestSuite suite = (TestSuite) obj.unwrap(); result.addTest(suite); } catch (Exception e) { String msg = JairusUnit.dumpError("Error loading jairusunit.js", e); result.addTest(JairusUnit.warning(msg)); } } finally { Context.exit(); } return result; } /** Returns a test which will fail and log a warning message. */ public static Test warning(final String msg) { return new TestCase("warning") { protected void runTest() { Assert.fail(msg); } }; } /** * Dump error. * @param notRhinoExceptionMsg msg if throwable is not {@link RhinoException} * @param file javascript filename with error * @param throwable should be {@link Throwable}, with special handling for * {@link RhinoException} * @return formatted message with stack dump */ public static String dumpError(String notRhinoExceptionMsg, Object throwable) { StringWriter sw = new StringWriter(); if (throwable instanceof RhinoException) { RhinoException re = (RhinoException) throwable; String filename = ""; if (re.sourceName() != null) { filename = "\"" + re.sourceName() + "\", "; } sw.write("\n" + filename + "line " + re.lineNumber() + ": " + re.details()); String ls = re.lineSource(); if (ls != null) { sw.write("\n" + ls + "\n"); for (int i = 0; i < re.columnNumber() - 1; i++) { sw.write("."); } sw.write("^\n"); } if (throwable instanceof JavaScriptException) { sw.write("\n" + ((JavaScriptException) throwable).getValue().toString()); } } else if (notRhinoExceptionMsg != null) { sw.write(notRhinoExceptionMsg); } if (throwable != null && throwable instanceof Throwable) { sw.write('\n'); ((Throwable) throwable).printStackTrace(new PrintWriter(sw)); } return sw.toString(); } /** * Dump stacktrace to string. * @param t throwable to dump * @return dump of stacktrace */ public static String dumpStackTrace(Throwable t) { if (t == null) { return null; } StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); return sw.toString(); } /** * Return stacktrace string with uninteresting lines removed. * @param t throwable * @return stacktrace string with uninteresting lines removed */ public static String filterStackTrace(Throwable t) { return filterStackTrace(dumpStackTrace(t)); } /** * Return stacktrace string with uninteresting lines removed. * @param stack stacktrace dump * @return stacktrace string with uninteresting lines removed */ public static String filterStackTrace(String stack) { if (stack == null) { return null; } StringBuilder result = new StringBuilder(); for (String line : stack.split("\n")) { if (!STACK_TRACE_FILTER.matcher(line).find()) { result.append(line).append("\n"); } } return result.toString(); } /** * Main. Args include filenames with optional '-todir &;t'dir>' or '-basedir &lt;dir> included * at any position within files. todir option gives directory to write * junit-style 'plain' and 'xml' reports, default todir is 'target/surefire-reports'. * basedir gives base directory for given filenames, default basedir is '/'. * @param args js files */ public static void main(String[] args) { // start debugger if -Ddebugjs if (System.getProperty("debugjs") != null) { Main main = new Main("JairusUnit Debug"); main.attachTo(ContextFactory.getGlobal()); main.pack(); main.setSize(960, 720); main.setVisible(true); } // enter context here to ensure only single context used for whole test // this helps debugger and tests, and means that any change to the // ContextFactory will not take effect Context.enter(); boolean failure = false; String todir = "target/surefire-reports"; String basedir = ""; int i = 0; try { while (i < args.length) { String arg = args[i++]; if ("-todir".equals(arg)) { todir = args[i++]; File f = new File(todir); if (!f.exists()) { f.mkdir(); } continue; } else if ("-basedir".equals(arg)) { basedir = args[i++]; continue; } // get suite using full filepath TestSuite suite = jairusunitTestSuite(basedir + "/" + arg); // we need to mimic java-style pkgname.classname style to make reports look nice // strip '.js' suffix, exclude basedir, prefix with 'jairusunit.' and change slashes to dots String testName = "jairusunit." + arg.replaceAll("\\.js$", "").replaceAll("/|\\\\", "."); // always write plain and xml reports - don't bother making people choose PrintStream plain = new PrintStream(new FileOutputStream(todir + "/TEST-" + testName + ".txt"), true, "UTF-8"); PrintStream xml = new PrintStream(new FileOutputStream(todir + "/TEST-" + testName + ".xml"), true, "UTF-8");; JairusUnitResultWriter printer = new JairusUnitResultWriter(System.out, plain, xml); TestResult result = new TestResult(); result.addListener(printer); printer.startTestSuite(testName); suite.run(result); printer.endTestSuite(testName); plain.close(); xml.close(); if (!result.wasSuccessful()) { failure = true; } } System.exit(failure ? FAILURE_EXIT : SUCCESS_EXIT); } catch (Exception e) { e.printStackTrace(); System.exit(EXCEPTION_EXIT); } } }
package com.kekstudio.musictheorytest; import com.kekstudio.musictheory.Chord; import com.kekstudio.musictheory.Key; import com.kekstudio.musictheory.Note; import com.kekstudio.musictheory.Scale; /** * * @author Andy671 */ public class Sample { public static void main(String[] args) { Note dSharpNote = new Note("D System.out.println(dSharpNote); // D#4[63] dSharpNote = new Note("D System.out.println(dSharpNote); // D#5[75] Chord dSharpm7Chord = dSharpNote.chord("m7"); System.out.println(dSharpm7Chord); // D#m7 inversion[0] {D#5[75], F#5[78], A#5[82], C#6[85]} Scale dSharpScale = dSharpNote.scale("minor"); System.out.println(dSharpScale); // D# minor scale {D#5[75], E#5[77], F#5[78], G#5[80], A#5[82], B5[83], C#6[85]} Key cFlatMajorKey = new Key("Cb", "major"); System.out.println(cFlatMajorKey); // Cb major key Chord thirdFlatDegreeAugChord = cFlatMajorKey.chord("bIII", "aug"); System.out.println(thirdFlatDegreeAugChord); // Ebbaug inversion[0] {Ebb4[62], Gb4[66], Bb4[70]} thirdFlatDegreeAugChord.setPosition(1); System.out.println(thirdFlatDegreeAugChord); // Ebbaug inversion[1] {Bb5[82], Ebb4[62], Gb4[66]} thirdFlatDegreeAugChord.sort(); System.out.println(thirdFlatDegreeAugChord); // Ebbaug inversion[1] {Ebb4[62], Gb4[66], Bb5[82]} } }
package com.kurento.kmf.media; import java.io.IOException; public class PlayerEndPoint extends UriEndPoint { private static final long serialVersionUID = 1L; PlayerEndPoint(com.kurento.kms.api.MediaObject playerEndPoint) { super(playerEndPoint); } /* SYNC */ public void play() throws IOException { start(); } /* ASYNC */ public void play(Continuation<Void> cont) throws IOException { start(cont); } }
package com.lothrazar.cyclic.util; import org.lwjgl.opengl.GL11; import com.lothrazar.cyclic.ModCyclic; import com.lothrazar.cyclic.data.OffsetEnum; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.platform.GlStateManager.DestFactor; import com.mojang.blaze3d.platform.GlStateManager.SourceFactor; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ActiveRenderInfo; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; public class RenderUtil { public static class LaserConfig { public static final int MAX_TIMER = 100; public LaserConfig(BlockPos first, BlockPos second, double rotationTime, float alpha, double beamWidth, float[] color) { this.first = first; this.second = second; this.rotationTime = rotationTime; this.alpha = alpha; this.beamWidth = beamWidth; this.color = color; } BlockPos first; BlockPos second; double rotationTime; float alpha; double beamWidth; float[] color; public int timer = LaserConfig.MAX_TIMER; public OffsetEnum xOffset = OffsetEnum.CENTER; public OffsetEnum yOffset = OffsetEnum.CENTER; public OffsetEnum zOffset = OffsetEnum.CENTER; @Override public String toString() { return second + " : " + first; } } public static final int MAX_LIGHT_X = 0xF000F0; public static final int MAX_LIGHT_Y = MAX_LIGHT_X; @OnlyIn(Dist.CLIENT) public static void renderLaser(LaserConfig conf, MatrixStack matrixStack) { if (conf.first == null || conf.second == null) { return; } double offsetX = conf.xOffset.getOffset(); double offsetY = conf.yOffset.getOffset(); double offsetZ = conf.zOffset.getOffset(); RenderUtil.renderLaser( conf.first.getX() + offsetX, conf.first.getY() + offsetY, conf.first.getZ() + offsetZ, conf.second.getX() + offsetX, conf.second.getY() + offsetY, conf.second.getZ() + offsetZ, conf.rotationTime, conf.alpha, conf.beamWidth, conf.color, conf.timer, matrixStack); } //I got this function from ActuallyAdditions by Ellpeck // source https://github.com/Ellpeck/ActuallyAdditions/blob/08d0e8b7fb463054e3f392ddbb2a2ca2e2877000/src/main/java/de/ellpeck/actuallyadditions/mod/util/AssetUtil.java#L257 // who in turn left their source where they got it, copied verabitm: //Thanks to feldim2425 for this. //I can't do rendering code. Ever. @OnlyIn(Dist.CLIENT) public static void renderLaser(double firstX, double firstY, double firstZ, double secondX, double secondY, double secondZ, double rotationTime, float alpha, double beamWidth, float[] color, double timer, MatrixStack matrixStack) { Tessellator tessy = Tessellator.getInstance(); BufferBuilder buffer = tessy.getBuffer(); World world = Minecraft.getInstance().world; float r = color[0]; float g = color[1]; float b = color[2]; Vec3d vecFirst = new Vec3d(firstX, firstY, firstZ); Vec3d vecSecond = new Vec3d(secondX, secondY, secondZ); Vec3d combinedVec = vecSecond.subtract(vecFirst); // world.getGameTime()getTotalWorldTime double rot = rotationTime > 0 ? (360D * ((world.getGameTime() % rotationTime) / rotationTime)) : 0; double pitch = Math.atan2(combinedVec.y, Math.sqrt(combinedVec.x * combinedVec.x + combinedVec.z * combinedVec.z)); double yaw = Math.atan2(-combinedVec.z, combinedVec.x); float length = (float) combinedVec.length(); length = (float) (length * (timer / (LaserConfig.MAX_TIMER * 1.0F))); RenderSystem.pushMatrix(); RenderSystem.rotatef((float) (180 * yaw / Math.PI), 0, 1, 0); RenderSystem.rotatef((float) (180 * pitch / Math.PI), 0, 0, 1); RenderSystem.rotatef((float) rot, 1, 0, 0); PlayerEntity player = ModCyclic.proxy.getClientPlayer(); ActiveRenderInfo renderInfo = Minecraft.getInstance().gameRenderer.getActiveRenderInfo(); double staticPlayerX = player.lastTickPosX; double staticPlayerY = player.lastTickPosY; double staticPlayerZ = player.lastTickPosZ; staticPlayerX = renderInfo.getProjectedView().getX(); staticPlayerY = renderInfo.getProjectedView().getY(); staticPlayerZ = renderInfo.getProjectedView().getZ(); // matrixStack.func_227860_a_(); // push // matrixStack.func_227861_a_(firstX - staticPlayerX, firstY - staticPlayerY, firstZ - staticPlayerZ); // RenderSystem.translated(firstX, firstY, firstZ); RenderSystem.translated(firstX - staticPlayerX, firstY - staticPlayerY, firstZ - staticPlayerZ); // RenderSystem.translated(secondX - staticPlayerX, secondY - staticPlayerY, secondZ - staticPlayerZ); // GL11.glTranslated(staticPlayerX, staticPlayerY, staticPlayerZ); // RenderSystem.translated(firstX - TileEntityRendererDispatcher.staticPlayerX, firstY - TileEntityRendererDispatcher.staticPlayerY, firstZ - TileEntityRendererDispatcher.staticPlayerZ); RenderSystem.disableTexture(); // RenderSystem.disableTexture2D(); RenderSystem.disableLighting(); RenderSystem.enableBlend(); RenderSystem.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE); buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR); // buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_LMAP_COLOR); for (double i = 0; i < 4; i++) {//four corners of the quad float width = (float) (beamWidth * (i / 4.0F)); // func_225582_a_ == .pos // func_225583_a_ == .tex// for UR //func_227885_a_ == color // .lightmap(MAX_LIGHT_X, MAX_LIGHT_Y) == I DONT KNOW buffer.func_225582_a_(length, width, width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(0, width, width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(0, -width, width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(length, -width, width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(length, -width, -width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(0, -width, -width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(0, width, -width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(length, width, -width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(length, width, -width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(0, width, -width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(0, width, width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(length, width, width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(length, -width, width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(0, -width, width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(0, -width, -width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); buffer.func_225582_a_(length, -width, -width).func_225587_b_(0, 0).func_227885_a_(r, g, b, alpha).endVertex(); } tessy.draw(); // matrixStack.func_227865_b_(); // pop RenderSystem.blendFunc(SourceFactor.SRC_ALPHA, DestFactor.ONE_MINUS_SRC_ALPHA); RenderSystem.disableBlend(); RenderSystem.enableLighting(); RenderSystem.disableTexture(); // RenderSystem.enableTexture2D(); RenderSystem.popMatrix(); } }
package com.ociweb.iot.hardware; import java.util.concurrent.locks.ReentrantLock; import com.ociweb.iot.impl.*; import com.ociweb.iot.maker.*; import com.ociweb.iot.transducer.*; import com.ociweb.pronghorn.iot.schema.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ociweb.gl.api.Behavior; import com.ociweb.gl.api.MsgCommandChannel; import com.ociweb.gl.impl.BuilderImpl; import com.ociweb.gl.impl.ChildClassScanner; import com.ociweb.gl.impl.schema.IngressMessages; import com.ociweb.gl.impl.schema.MessagePubSub; import com.ociweb.gl.impl.schema.MessageSubscription; import com.ociweb.gl.impl.schema.TrafficAckSchema; import com.ociweb.gl.impl.schema.TrafficOrderSchema; import com.ociweb.gl.impl.schema.TrafficReleaseSchema; import com.ociweb.gl.impl.stage.TrafficCopStage; import com.ociweb.iot.hardware.impl.DirectHardwareAnalogDigitalOutputStage; import com.ociweb.iot.hardware.impl.SerialDataReaderStage; import com.ociweb.iot.hardware.impl.SerialDataWriterStage; import com.ociweb.iot.hardware.impl.SerialInputSchema; import com.ociweb.iot.hardware.impl.SerialOutputSchema; import com.ociweb.iot.hardware.impl.edison.EdisonConstants; import com.ociweb.iot.impl.AnalogListenerBase; import com.ociweb.iot.impl.DigitalListenerBase; import com.ociweb.iot.impl.I2CListenerBase; import com.ociweb.iot.impl.RotaryListenerBase; import com.ociweb.iot.impl.SerialListenerBase; import com.ociweb.iot.maker.Baud; import com.ociweb.iot.maker.FogRuntime; import com.ociweb.iot.maker.Hardware; import com.ociweb.iot.maker.Port; import com.ociweb.iot.transducer.AnalogListenerTransducer; import com.ociweb.iot.transducer.DigitalListenerTransducer; import com.ociweb.iot.transducer.I2CListenerTransducer; import com.ociweb.iot.transducer.RotaryListenerTransducer; import com.ociweb.iot.transducer.SerialListenerTransducer; import com.ociweb.pronghorn.iot.ReactiveIoTListenerStage; import com.ociweb.pronghorn.iot.ReadDeviceInputStage; import com.ociweb.pronghorn.iot.i2c.I2CBacking; import com.ociweb.pronghorn.iot.i2c.I2CJFFIStage; import com.ociweb.pronghorn.iot.i2c.impl.I2CNativeLinuxBacking; import com.ociweb.pronghorn.iot.rs232.RS232Client; import com.ociweb.pronghorn.iot.rs232.RS232Clientable; import com.ociweb.pronghorn.network.schema.ClientHTTPRequestSchema; import com.ociweb.pronghorn.network.schema.HTTPRequestSchema; import com.ociweb.pronghorn.network.schema.NetPayloadSchema; import com.ociweb.pronghorn.network.schema.NetResponseSchema; import com.ociweb.pronghorn.pipe.Pipe; import com.ociweb.pronghorn.pipe.PipeConfig; import com.ociweb.pronghorn.pipe.util.hash.IntHashTable; import com.ociweb.pronghorn.stage.PronghornStage; import com.ociweb.pronghorn.stage.route.ReplicatorStage; import com.ociweb.pronghorn.stage.scheduling.GraphManager; import com.ociweb.pronghorn.stage.test.PipeCleanerStage; import com.ociweb.pronghorn.util.math.PMath; import com.ociweb.pronghorn.util.math.ScriptedSchedule; public abstract class HardwareImpl extends BuilderImpl implements Hardware { private static final int MAX_MOVING_AVERAGE_SUPPORTED = 101; //TOOD: is this still needed, remove??? private static final HardwareConnection[] EMPTY = new HardwareConnection[0]; protected boolean configCamera = false; protected boolean configI2C; //Humidity, LCD need I2C address so.. protected long debugI2CRateLastTime; protected HardwareConnection[] digitalInputs; //Button, Motion protected HardwareConnection[] digitalOutputs;//Relay Buzzer protected HardwareConnection[] analogInputs; //Light, UV, Moisture protected HardwareConnection[] pwmOutputs; //Servo //(only 3, 5, 6, 9, 10, 11 when on edison) protected I2CConnection[] i2cInputs; protected I2CConnection[] i2cOutputs; private static final int DEFAULT_LENGTH = 16; private static final int DEFAULT_PAYLOAD_SIZE = 128; private static final int DEFAULT_CUSTOM_RATE_MS = -1; private static final int DEFAULT_CUSTOM_AVG_WINDOW_MS = -1; private static final boolean DEFAULT_EVERY_VALUE = false; private int i2cBus; protected I2CBacking i2cBackingInternal; protected static final long MS_TO_NS = 1_000_000; private static final Logger logger = LoggerFactory.getLogger(HardwareImpl.class); protected final IODevice[] deviceOnPort= new IODevice[Port.values().length]; ///Pipes for initial startup declared subscriptions. (Not part of graph) private final int maxStartupSubs = 64; private final int maxTopicLengh = 128; private Pipe<MessagePubSub> tempPipeOfStartupSubscriptions; protected ReentrantLock devicePinConfigurationLock = new ReentrantLock(); protected RS232Client rs232Client; protected String rs232ClientDevice = "/dev/ttyMFD1";//custom hardware should override this edison value protected Baud rs232ClientBaud = Baud.B_____9600; protected String bluetoothDevice = null; private static final boolean debug = false; private int IDX_PIN = -1; private int IDX_I2C = -1; private int IDX_SER = -1; private int imageTriggerRateMillis = 1250; public void setImageTriggerRate(int triggerRateMillis) { if (triggerRateMillis < 1250) { throw new RuntimeException("Image listeners cannot be used with trigger rates of less than 1250 MS."); } this.imageTriggerRateMillis = triggerRateMillis; } public IODevice getConnectedDevice(Port p) { return deviceOnPort[p.ordinal()]; } public HardwareImpl(GraphManager gm, String[] args, int i2cBus) { this(gm, args, i2cBus, false,false,EMPTY,EMPTY,EMPTY,EMPTY,EMPTY); } protected HardwareImpl(GraphManager gm, String[] args, int i2cBus, boolean publishTime, boolean configI2C, HardwareConnection[] multiDigitalInput, HardwareConnection[] digitalInputs, HardwareConnection[] digitalOutputs, HardwareConnection[] pwmOutputs, HardwareConnection[] analogInputs) { super(gm, args); ReactiveIoTListenerStage.initOperators(operators); this.pcm.addConfig(new PipeConfig<HTTPRequestSchema>(HTTPRequestSchema.instance, 2, //only a few requests when FogLight MAXIMUM_INCOMMING_REST_SIZE)); this.pcm.addConfig(new PipeConfig<NetPayloadSchema>(NetPayloadSchema.instance, 2, //only a few requests when FogLight MINIMUM_TLS_BLOB_SIZE)); this.pcm.addConfig(new PipeConfig<SerialInputSchema>(SerialInputSchema.instance, DEFAULT_LENGTH, DEFAULT_PAYLOAD_SIZE)); this.i2cBus = i2cBus; this.configI2C = configI2C; //may be removed. this.digitalInputs = digitalInputs; this.digitalOutputs = digitalOutputs; this.pwmOutputs = pwmOutputs; this.analogInputs = analogInputs; this.getTempPipeOfStartupSubscriptions().initBuffers(); } public I2CBacking getI2CBacking() { if (null == i2cBackingInternal) { i2cBackingInternal = getI2CBacking((byte)i2cBus, false); } return i2cBackingInternal; } private static I2CBacking getI2CBacking(byte deviceNum, boolean reportError) { long start = System.currentTimeMillis(); try { return new I2CNativeLinuxBacking().configure(deviceNum); } catch (Throwable t) { if (reportError) { logger.info("warning could not find the i2c bus", t); } //avoid non error case that is used to detect which hardware is running. return null; } finally { logger.info("duration of getI2CBacking {} ", System.currentTimeMillis()-start); } } protected HardwareConnection[] growHardwareConnections(HardwareConnection[] original, HardwareConnection toAdd) { final int len = original.length; //Validate that what we are adding is safe int i = len; while (--i>=0) { if (original[i].register == toAdd.register) { throw new UnsupportedOperationException("This connection "+toAdd.register+" already has attachment "+original[i].twig+" so the attachment "+toAdd.twig+" can not be added."); } } //Grow the array HardwareConnection[] result = new HardwareConnection[len+1]; System.arraycopy(original, 0, result, 0, len); result[len] = toAdd; return result; } protected I2CConnection[] growI2CConnections(I2CConnection[] original, I2CConnection toAdd){ if (null==original) { return new I2CConnection[] {toAdd}; } else { int l = original.length; I2CConnection[] result = new I2CConnection[l+1]; System.arraycopy(original, 0, result, 0, l); result[l] = toAdd; return result; } } protected Hardware internalConnectAnalog(IODevice t, int connection, int customRate, int customAverageMS, boolean everyValue) { if (t.isInput()) { assert(!t.isOutput()); analogInputs = growHardwareConnections(analogInputs, new HardwareConnection(t,connection, customRate, customAverageMS, everyValue)); } else { assert(t.isOutput()); pwmOutputs = growHardwareConnections(pwmOutputs, new HardwareConnection(t,connection, customRate, customAverageMS, everyValue)); } return this; } protected Hardware internalConnectDigital(IODevice t, int connection, int customRate, int customAverageMS, boolean everyValue) { if (t.isInput()) { assert(!t.isOutput()); digitalInputs = growHardwareConnections(digitalInputs, new HardwareConnection(t,connection, customRate, customAverageMS, everyValue)); } else { assert(t.isOutput()); digitalOutputs = growHardwareConnections(digitalOutputs, new HardwareConnection(t,connection, customRate, customAverageMS, everyValue)); } return this; } @Override public Hardware connect(I2CIODevice t){ logger.debug("Connecting I2C Device "+t.getClass()); if(t.isInput()){ i2cInputs = growI2CConnections(i2cInputs, t.getI2CConnection()); } if(t.isOutput()){ i2cOutputs = growI2CConnections(i2cOutputs, t.getI2CConnection()); } this.useI2C(); return this; } @Override public Hardware connect(I2CIODevice t, int customRateMS){ logger.debug("Connecting I2C Device "+t.getClass()); if(t.isInput()){ i2cInputs = growI2CConnections(i2cInputs, new I2CConnection(t.getI2CConnection(),customRateMS)); } if(t.isOutput()){ i2cOutputs = growI2CConnections(i2cOutputs, t.getI2CConnection()); } this.useI2C(); return this; } public Hardware useSerial(Baud baud) { this.rs232ClientBaud = baud; return this; } /** * * @param baud * @param device Name of the port. On UNIX systems this will typically * be of the form /dev/ttyX, where X is a port number. On * Windows systems this will typically of the form COMX, * where X is again a port number. */ public Hardware useSerial(Baud baud, String device) { this.rs232ClientBaud = baud; this.rs232ClientDevice = device; return this; } public Hardware useI2C() { this.configI2C = true; return this; } public Hardware useCamera() { this.configCamera = true; return this; } @Deprecated //would be nice if we did not have to do this. public Hardware useI2C(int bus) { this.configI2C = true; this.i2cBus = bus; return this; } public boolean isUseI2C() { return this.configI2C; } public abstract HardwarePlatformType getPlatformType(); public abstract int read(Port port); //Platform specific public abstract void write(Port port, int value); //Platform specific public int maxAnalogMovingAverage() { return MAX_MOVING_AVERAGE_SUPPORTED; } public void coldSetup(){ System.out.println(""); } protected HardwareConnection[] buildUsedLines() { HardwareConnection[] result = new HardwareConnection[digitalInputs.length+ digitalOutputs.length+ pwmOutputs.length+ analogInputs.length+ (configI2C?2:0)]; int pos = 0; System.arraycopy(digitalInputs, 0, result, pos, digitalInputs.length); pos+=digitalInputs.length; findDup(result,pos,digitalOutputs, false); System.arraycopy(digitalOutputs, 0, result, pos, digitalOutputs.length); pos+=digitalOutputs.length; findDup(result,pos,pwmOutputs, false); System.arraycopy(pwmOutputs, 0, result, pos, pwmOutputs.length); pos+=pwmOutputs.length; findDup(result,pos,analogInputs, true); int j = analogInputs.length; while (--j>=0) { result[pos++] = new HardwareConnection(analogInputs[j].twig,(int) EdisonConstants.ANALOG_CONNECTOR_TO_PIN[analogInputs[j].register]); } if (configI2C) { findDup(result,pos,EdisonConstants.i2cPins, false); System.arraycopy(EdisonConstants.i2cPins, 0, result, pos, EdisonConstants.i2cPins.length); pos+=EdisonConstants.i2cPins.length; } return result; } private static void findDup(HardwareConnection[] base, int baseLimit, HardwareConnection[] items, boolean mapAnalogs) { int i = items.length; while (--i>=0) { int j = baseLimit; while (--j>=0) { if (mapAnalogs ? base[j].register == EdisonConstants.ANALOG_CONNECTOR_TO_PIN[items[i].register] : base[j]==items[i]) { throw new UnsupportedOperationException("Connector "+items[i]+" is assigned more than once."); } } } } public void shutdown() { super.shutdown(); //can be overridden by specific hardware impl if shutdown is supported. } private void createUARTInputStage(Pipe<SerialInputSchema> masterUARTPipe) { RS232Clientable client = buildSerialClient(); new SerialDataReaderStage(this.gm, masterUARTPipe, client); } protected RS232Clientable buildSerialClient() { if (null==rs232Client) { //custom hardware can override this rs232Client = new RS232Client(rs232ClientDevice, rs232ClientBaud); } return rs232Client; } protected void createADInputStage(Pipe<GroveResponseSchema> masterResponsePipe) { //NOTE: rate is NOT set since stage sets and configs its own rate based on polling need. ReadDeviceInputStage adInputStage = new ReadDeviceInputStage(this.gm, masterResponsePipe, this); } protected void createI2COutputInputStage(Pipe<I2CCommandSchema>[] i2cPipes, Pipe<TrafficReleaseSchema>[] masterI2CgoOut, Pipe<TrafficAckSchema>[] masterI2CackIn, Pipe<I2CResponseSchema> masterI2CResponsePipe) { if (hasI2CInputs()) { I2CJFFIStage i2cJFFIStage = new I2CJFFIStage(gm, masterI2CgoOut, i2cPipes, masterI2CackIn, masterI2CResponsePipe, this); } else { //TODO: build an output only version of this stage because there is nothing to read I2CJFFIStage i2cJFFIStage = new I2CJFFIStage(gm, masterI2CgoOut, i2cPipes, masterI2CackIn, masterI2CResponsePipe, this); } } protected void createADOutputStage(Pipe<GroveRequestSchema>[] requestPipes, Pipe<TrafficReleaseSchema>[] masterPINgoOut, Pipe<TrafficAckSchema>[] masterPINackIn) { DirectHardwareAnalogDigitalOutputStage adOutputStage = new DirectHardwareAnalogDigitalOutputStage(gm, requestPipes, masterPINgoOut, masterPINackIn, this); } public boolean isListeningToSerial(Object listener) { return listener instanceof SerialListenerBase || !ChildClassScanner.visitUsedByClass(listener, deepListener, SerialListenerTransducer.class); } public boolean isListeningToCamera(Object listener) { return listener instanceof ImageListenerBase || !ChildClassScanner.visitUsedByClass(listener, deepListener, ImageListenerTransducer.class); } public boolean isListeningToI2C(Object listener) { return listener instanceof I2CListenerBase || !ChildClassScanner.visitUsedByClass(listener, deepListener, I2CListenerTransducer.class); } public boolean isListeningToPins(Object listener) { return listener instanceof DigitalListenerBase || listener instanceof AnalogListenerBase || listener instanceof RotaryListenerBase || !ChildClassScanner.visitUsedByClass(listener, deepListener, DigitalListenerTransducer.class) || !ChildClassScanner.visitUsedByClass(listener, deepListener, AnalogListenerTransducer.class) || !ChildClassScanner.visitUsedByClass(listener, deepListener, RotaryListenerTransducer.class); } private Pipe<MessagePubSub> getTempPipeOfStartupSubscriptions() { if (null==tempPipeOfStartupSubscriptions) { final PipeConfig<MessagePubSub> messagePubSubConfig = new PipeConfig<MessagePubSub>(MessagePubSub.instance, maxStartupSubs,maxTopicLengh); tempPipeOfStartupSubscriptions = new Pipe<MessagePubSub>(messagePubSubConfig); } return tempPipeOfStartupSubscriptions; } public boolean hasI2CInputs() { return this.i2cInputs!=null && this.i2cInputs.length>0; } public I2CConnection[] getI2CInputs() { return null==i2cInputs?new I2CConnection[0]:i2cInputs; } public HardwareConnection[] getAnalogInputs() { return analogInputs; } public HardwareConnection[] getDigitalInputs() { return digitalInputs; } public ScriptedSchedule buildI2CPollSchedule() { I2CConnection[] localInputs = getI2CInputs(); long[] schedulePeriods = new long[localInputs.length]; for (int i = 0; i < localInputs.length; i++) { schedulePeriods[i] = localInputs[i].responseMS*MS_TO_NS; } //logger.debug("known I2C rates: {}",Arrays.toString(schedulePeriods)); return PMath.buildScriptedSchedule(schedulePeriods); } public boolean hasDigitalOrAnalogInputs() { return (analogInputs.length+digitalInputs.length)>0; } public boolean hasDigitalOrAnalogOutputs() { return (pwmOutputs.length+digitalOutputs.length)>0; } public HardwareConnection[] combinedADConnections() { HardwareConnection[] localAInputs = getAnalogInputs(); HardwareConnection[] localDInputs = getDigitalInputs(); int totalCount = localAInputs.length + localDInputs.length; HardwareConnection[] results = new HardwareConnection[totalCount]; System.arraycopy(localAInputs, 0, results, 0, localAInputs.length); System.arraycopy(localDInputs, 0, results, localAInputs.length, localDInputs.length); return results; } public ScriptedSchedule buildADPollSchedule() { HardwareConnection[] localAInputs = getAnalogInputs(); HardwareConnection[] localDInputs = getDigitalInputs(); int totalCount = localAInputs.length + localDInputs.length; if (0==totalCount) { return null; } long[] schedulePeriods = new long[totalCount]; int j = 0; for (int i = 0; i < localAInputs.length; i++) { schedulePeriods[j++] = localAInputs[i].responseMS*MS_TO_NS; } for (int i = 0; i < localDInputs.length; i++) { schedulePeriods[j++] = localDInputs[i].responseMS*MS_TO_NS; } //analogs then the digitals return PMath.buildScriptedSchedule(schedulePeriods); } public byte convertToPort(byte connection) { return connection; } @Override public Hardware connect(ADIODevice t, Port port, int customRateMS, int customAvgWindowMS, boolean everyValue) { int portsLeft = t.pinsUsed(); while (--portsLeft >= 0){ deviceOnPort[port.ordinal()] = t; if (0 != (port.mask&Port.IS_ANALOG)) { internalConnectAnalog(t, port.port, customRateMS, customAvgWindowMS, everyValue); } else if (0 != (port.mask&Port.IS_DIGITAL)) { internalConnectDigital(t, port.port, customRateMS, customAvgWindowMS, everyValue); } port = Port.nextPort(port); } return this; } @Override public Hardware connect(ADIODevice t, Port port, int customRateMS, int customAvgWindowMS) { return connect(t,port,customRateMS, customAvgWindowMS ,DEFAULT_EVERY_VALUE); } @Override public Hardware connect(ADIODevice t, Port port, int customRateMS) { return connect(t,port,customRateMS, DEFAULT_CUSTOM_AVG_WINDOW_MS ,false); } @Override public Hardware connect(ADIODevice t, Port port, int customRateMS, boolean everyValue) { return connect(t,port,customRateMS, DEFAULT_CUSTOM_AVG_WINDOW_MS ,everyValue); } @Override public Hardware connect(ADIODevice t, Port port) { return connect (t, port, DEFAULT_CUSTOM_RATE_MS,DEFAULT_CUSTOM_AVG_WINDOW_MS,false); } public void releasePinOutTraffic(int count, MsgCommandChannel<?> gcc) { MsgCommandChannel.publishGo(count, IDX_PIN, gcc); } public void releaseI2CTraffic(int count, MsgCommandChannel<?> gcc) { MsgCommandChannel.publishGo(count, IDX_I2C, gcc); } @Override public void releasePubSubTraffic(int count, MsgCommandChannel<?> gcc) { MsgCommandChannel.publishGo(count, IDX_MSG, gcc); } public void buildStages(IntHashTable subscriptionPipeLookup2, GraphManager gm2) { Pipe<I2CResponseSchema>[] i2cResponsePipes = GraphManager.allPipesOfTypeWithNoProducer(gm2, I2CResponseSchema.instance); Pipe<GroveResponseSchema>[] responsePipes = GraphManager.allPipesOfTypeWithNoProducer(gm2, GroveResponseSchema.instance); Pipe<SerialOutputSchema>[] serialOutputPipes = GraphManager.allPipesOfTypeWithNoConsumer(gm2, SerialOutputSchema.instance); Pipe<I2CCommandSchema>[] i2cPipes = GraphManager.allPipesOfTypeWithNoConsumer(gm2, I2CCommandSchema.instance); Pipe<GroveRequestSchema>[] pinRequestPipes = GraphManager.allPipesOfTypeWithNoConsumer(gm2, GroveRequestSchema.instance); Pipe<SerialInputSchema>[] serialInputPipes = GraphManager.allPipesOfTypeWithNoProducer(gm2, SerialInputSchema.instance); Pipe<ImageSchema>[] imageInputPipes = GraphManager.allPipesOfTypeWithNoProducer(gm2, ImageSchema.instance); Pipe<NetResponseSchema>[] httpClientResponsePipes = GraphManager.allPipesOfTypeWithNoProducer(gm2, NetResponseSchema.instance); Pipe<MessageSubscription>[] subscriptionPipes = GraphManager.allPipesOfTypeWithNoProducer(gm2, MessageSubscription.instance); Pipe<TrafficOrderSchema>[] orderPipes = GraphManager.allPipesOfTypeWithNoConsumer(gm2, TrafficOrderSchema.instance); Pipe<ClientHTTPRequestSchema>[] httpClientRequestPipes = GraphManager.allPipesOfTypeWithNoConsumer(gm2, ClientHTTPRequestSchema.instance); Pipe<MessagePubSub>[] messagePubSub = GraphManager.allPipesOfTypeWithNoConsumer(gm2, MessagePubSub.instance); Pipe<IngressMessages>[] ingressMessagePipes = GraphManager.allPipesOfTypeWithNoConsumer(gm2, IngressMessages.instance); //TODO: must pull out those pubSub Pipes for direct connections //TODO: new MessageSchema for direct messages from point to point // create the pipe instead of pub sub and attach? //TODO: declare up front once in connections, direct connect topics // upon seeing these we build a new pipe int commandChannelCount = orderPipes.length; int eventSchemas = 0; IDX_PIN = pinRequestPipes.length>0 ? eventSchemas++ : -1; IDX_I2C = i2cPipes.length>0 || i2cResponsePipes.length > 0 ? eventSchemas++ : -1; //the 'or' check is to ensure that reading without a cmd channel works IDX_MSG = (IntHashTable.isEmpty(subscriptionPipeLookup2) && subscriptionPipes.length==0 && messagePubSub.length==0) ? -1 : eventSchemas++; IDX_NET = useNetClient(httpClientRequestPipes) ? eventSchemas++ : -1; IDX_SER = serialOutputPipes.length>0 ? eventSchemas++ : -1; long timeout = 20_000; //20 seconds //TODO: can we share this while with the parent BuilderImpl, I think so.. int maxGoPipeId = 0; int t = commandChannelCount; Pipe<TrafficReleaseSchema>[][] masterGoOut = new Pipe[eventSchemas][0]; Pipe<TrafficAckSchema>[][] masterAckIn = new Pipe[eventSchemas][0]; if (IDX_PIN >= 0) { masterGoOut[IDX_PIN] = new Pipe[pinRequestPipes.length]; masterAckIn[IDX_PIN] = new Pipe[pinRequestPipes.length]; } if (IDX_I2C >= 0) { masterGoOut[IDX_I2C] = new Pipe[i2cPipes.length]; masterAckIn[IDX_I2C] = new Pipe[i2cPipes.length]; } if (IDX_MSG >= 0) { masterGoOut[IDX_MSG] = new Pipe[messagePubSub.length]; masterAckIn[IDX_MSG] = new Pipe[messagePubSub.length]; } if (IDX_NET >= 0) { masterGoOut[IDX_NET] = new Pipe[httpClientRequestPipes.length]; masterAckIn[IDX_NET] = new Pipe[httpClientRequestPipes.length]; } if (IDX_SER >=0) { masterGoOut[IDX_SER] = new Pipe[serialOutputPipes.length]; masterAckIn[IDX_SER] = new Pipe[serialOutputPipes.length]; } while (--t>=0) { int features = getFeatures(gm2, orderPipes[t]); Pipe<TrafficReleaseSchema>[] goOut = new Pipe[eventSchemas]; Pipe<TrafficAckSchema>[] ackIn = new Pipe[eventSchemas]; boolean isDynamicMessaging = (features&Behavior.DYNAMIC_MESSAGING) != 0; boolean isNetRequester = (features&Behavior.NET_REQUESTER) != 0; boolean isPinWriter = (features&FogRuntime.PIN_WRITER) != 0; boolean isI2CWriter = (features&FogRuntime.I2C_WRITER) != 0; boolean isSerialWriter = (features&FogRuntime.SERIAL_WRITER) != 0; boolean hasConnections = false; if (isDynamicMessaging && IDX_MSG>=0) { hasConnections = true; maxGoPipeId = populateGoAckPipes(maxGoPipeId, masterGoOut, masterAckIn, goOut, ackIn, IDX_MSG); } if (isNetRequester && IDX_NET>=0) { hasConnections = true; maxGoPipeId = populateGoAckPipes(maxGoPipeId, masterGoOut, masterAckIn, goOut, ackIn, IDX_NET); } if (isPinWriter && IDX_PIN>=0) { hasConnections = true; maxGoPipeId = populateGoAckPipes(maxGoPipeId, masterGoOut, masterAckIn, goOut, ackIn, IDX_PIN); } if (isI2CWriter && IDX_I2C>=0) { hasConnections = true; maxGoPipeId = populateGoAckPipes(maxGoPipeId, masterGoOut, masterAckIn, goOut, ackIn, IDX_I2C); } if (isSerialWriter && IDX_SER>=0) { hasConnections = true; maxGoPipeId = populateGoAckPipes(maxGoPipeId, masterGoOut, masterAckIn, goOut, ackIn, IDX_SER); } if (hasConnections) { TrafficCopStage trafficCopStage = new TrafficCopStage(gm, timeout, orderPipes[t], ackIn, goOut, this); } else { PipeCleanerStage.newInstance(gm, orderPipes[t]); } } initChannelBlocker(maxGoPipeId); buildHTTPClientGraph(httpClientResponsePipes, httpClientRequestPipes, masterGoOut, masterAckIn); if (IDX_MSG <0) { logger.trace("saved some resources by not starting up the unused pub sub service."); } else { createMessagePubSubStage(subscriptionPipeLookup2, ingressMessagePipes, messagePubSub, masterGoOut[IDX_MSG], masterAckIn[IDX_MSG], subscriptionPipes); } // int c = masterGoOut.length; // while (--c>=0) { // if (!PronghornStage.noNulls(masterGoOut[c])) { // if (!PronghornStage.noNulls(masterAckIn[c])) { //only build and connect I2C if it is used for either in or out Pipe<I2CResponseSchema> masterI2CResponsePipe = null; if (i2cResponsePipes.length>0) { masterI2CResponsePipe = I2CResponseSchema.instance.newPipe(DEFAULT_LENGTH, DEFAULT_PAYLOAD_SIZE); ReplicatorStage.newInstance(gm, masterI2CResponsePipe, i2cResponsePipes); } if (i2cPipes.length>0 || (null!=masterI2CResponsePipe)) { createI2COutputInputStage(i2cPipes, masterGoOut[IDX_I2C], masterAckIn[IDX_I2C], masterI2CResponsePipe); } //only build and connect gpio input responses if it is used if (responsePipes.length>1) { Pipe<GroveResponseSchema> masterResponsePipe = GroveResponseSchema.instance.newPipe(DEFAULT_LENGTH, DEFAULT_PAYLOAD_SIZE); ReplicatorStage.newInstance(gm, masterResponsePipe, responsePipes); createADInputStage(masterResponsePipe); } else { if (responsePipes.length==1) { createADInputStage(responsePipes[0]); } } //only build serial output if data is sent if (serialOutputPipes.length>0) { assert(null!=masterGoOut[IDX_SER]); assert(serialOutputPipes.length == masterGoOut[IDX_SER].length) : serialOutputPipes.length+" == "+masterGoOut[IDX_SER].length; createSerialOutputStage(serialOutputPipes, masterGoOut[IDX_SER], masterAckIn[IDX_SER]); } //only build serial input if the data is consumed if (serialInputPipes.length>1) { Pipe<SerialInputSchema> masterUARTPipe = new Pipe<SerialInputSchema>(pcm.getConfig(SerialInputSchema.class)); new ReplicatorStage<SerialInputSchema>(gm, masterUARTPipe, serialInputPipes); createUARTInputStage(masterUARTPipe); } else { if (serialInputPipes.length==1) { createUARTInputStage(serialInputPipes[0]); } else { } } //only build image input if the data is consumed // TODO: Is this where we determine what kind of platform to listen on (e.g., Edison, Pi)? if (imageInputPipes.length > 1) { Pipe<ImageSchema> masterImagePipe = ImageSchema.instance.newPipe(DEFAULT_LENGTH, DEFAULT_PAYLOAD_SIZE); new ReplicatorStage<ImageSchema>(gm, masterImagePipe, imageInputPipes); new PiImageListenerStage(gm, masterImagePipe, imageTriggerRateMillis); } else if (imageInputPipes.length == 1){ new PiImageListenerStage(gm, imageInputPipes[0], imageTriggerRateMillis); } //only build direct pin output when we detected its use if (IDX_PIN>=0) { assert(PronghornStage.noNulls(masterGoOut[IDX_PIN])) : "Go Pipe must not contain nulls"; assert(PronghornStage.noNulls(masterAckIn[IDX_PIN])) : "Ack Pipe must not contain nulls"; createADOutputStage(pinRequestPipes, masterGoOut[IDX_PIN], masterAckIn[IDX_PIN]); } } private String featureName(final int c) { if (c == IDX_I2C) { //FogRuntime.I2C_WRITER; return "I2C_WRITER"; } if (c == IDX_MSG) { //Behavior.DYNAMIC_MESSAGING; return "DYNAMIC_MESSAGING"; } if (c == IDX_NET) { //TODO: where is the responder?? //Behavior.NET_REQUESTER; return "NET_REQUESTER"; } if (c == IDX_PIN) { //FogRuntime.PIN_WRITER; return "PIN_WRITER"; } if (c == IDX_SER) { //FogRuntime.SERIAL_WRITER; return "SERIAL_WRITER"; } return null; } protected void createSerialOutputStage(Pipe<SerialOutputSchema>[] serialOutputPipes, Pipe<TrafficReleaseSchema>[] masterGoOut, Pipe<TrafficAckSchema>[] masterAckIn) { new SerialDataWriterStage(gm, serialOutputPipes, masterGoOut, masterAckIn, this, this.buildSerialClient()); } public static int serialIndex(HardwareImpl hardware) { return hardware.IDX_SER; } public static int i2cIndex(HardwareImpl hardware) { return hardware.IDX_I2C; } @Override public int pubSubIndex() { return IDX_MSG; } @Override public int netIndex() { return IDX_NET; } public boolean isTestHardware() { return false; } }
package com.puntodeventa.mvc.Views; import com.puntodeventa.global.Entity.*; import com.puntodeventa.global.Util.Constants.Command; import com.puntodeventa.global.Util.Constants.ShortCuts; import com.puntodeventa.global.Util.Constants.TableColumns; import com.puntodeventa.global.Util.Extended.DefaultTableModelExtended; import com.puntodeventa.global.Util.LogHelper; import com.puntodeventa.global.Util.ParamHelper; import com.puntodeventa.global.Util.TagHelper; import com.puntodeventa.global.Util.Util; import com.puntodeventa.global.Util.ValidacionForms; import com.puntodeventa.global.printservice.POSPrintService; import com.puntodeventa.mvc.Controller.VentaLogic; import com.puntodeventa.mvc.Controller.VentadDetalleLogic; import com.puntodeventa.services.DAO.ProductDAO; import com.tyket.model.Article; import com.tyket.model.Ticket; import com.tyket.model.TyketRestClient; import com.tyket.model.User; import java.awt.Color; import java.awt.Event; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JComponent; import javax.swing.KeyStroke; import javax.swing.table.DefaultTableModel; import org.springframework.http.HttpMethod; /** * * @author USER */ public class jfrmVenta extends javax.swing.JFrame { private final Usuario user = Util.getCurrentUser(); private final LogHelper objLog = new LogHelper("jfrmVenta"); private final ProductDAO prodDao = new ProductDAO(); private final DefaultTableModelExtended tblModel = new DefaultTableModelExtended(); private final ValidacionForms valid = new ValidacionForms(); private final int r = Integer.parseInt(ParamHelper.getParam("system.background.colorR").toString()); private final int g = Integer.parseInt(ParamHelper.getParam("system.background.colorG").toString()); private final int b = Integer.parseInt(ParamHelper.getParam("system.background.colorB").toString()); public jfrmVenta() { initComponents(); configureControls(); setClock(); } @Override public Image getIconImage() { Image retValue = Toolkit.getDefaultToolkit(). getImage(ClassLoader.getSystemResource("images/ico.png")); return retValue; } private void setClock() { javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Calendar now = Calendar.getInstance(); int h = now.get(Calendar.HOUR_OF_DAY); int m = now.get(Calendar.MINUTE); int s = now.get(Calendar.SECOND); String hr = h < 10 ? "0" + h : "" + h; String mn = m < 10 ? "0" + m : "" + m; String se = s < 10 ? "0" + s : "" + s; jlblTimeField.setText("" + hr + ":" + mn + ":" + se); int d = now.get(Calendar.DAY_OF_MONTH); int mo = now.get(Calendar.MONTH) + 1; int y = now.get(Calendar.YEAR); String day = d < 10 ? "0" + d : "" + d; String month = mo < 10 ? "0" + mo : "" + mo; jlblDateField.setText("" + day + "/" + month + "/" + y); } }); t.start(); } private void configureControls() { //Set the table design (columns) setTableModel(); //Set background color this.getContentPane().setBackground(new Color(r, g, b)); jpnlTotales.setBackground(new java.awt.Color(r, g, b)); jpnlProducts.setBackground(new java.awt.Color(r, g, b)); jpnlAttendedBy.setBackground(new java.awt.Color(r, g, b)); setTags(); //Maximize window this.setExtendedState(MAXIMIZED_BOTH); this.txt.requestFocus(); //Adding Menu shortcut Ctrl + M KeyStroke keyMenu = KeyStroke.getKeyStroke(ShortCuts.SC_M, Event.CTRL_MASK); Action showMenu = new AbstractAction("Menu") { @Override public void actionPerformed(ActionEvent e) { showVentaMenu(); } }; txt.getActionMap().put("showMenu", showMenu); txt.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyMenu, "showMenu"); //Adding Menu shortcut Ctrl + B KeyStroke keySearch = KeyStroke.getKeyStroke(ShortCuts.SC_B, Event.CTRL_MASK); Action searchProduct = new AbstractAction("Search") { @Override public void actionPerformed(ActionEvent e) { showSearchProductWindow(); } }; txt.getActionMap().put("searchProduct", searchProduct); txt.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keySearch, "searchProduct"); //Adding Menu shortcut Ctrl + P KeyStroke keyDoPayment = KeyStroke.getKeyStroke(KeyEvent.VK_P, Event.CTRL_MASK); Action doPayment = new AbstractAction("Pay") { @Override public void actionPerformed(ActionEvent e) { doPayment(); } }; txt.getActionMap().put("doPayment", doPayment); txt.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyDoPayment, "doPayment"); } private void setTags() { this.setTitle(TagHelper.getTag("generaltag.applicationTitle")); this.jlblAttendedBy.setText(TagHelper.getTag("jfrmVenta.jlblAttendedBy")); this.jlblUserName.setText(user.getNombre()); this.jlblDateField.setText(TagHelper.getTag("jfrmVenta.jlblDateField")); this.jlblTimeField.setText(TagHelper.getTag("jfrmVenta.jlblTimeField")); this.jlblTotalTitle.setText(TagHelper.getTag("jfrmVenta.jlblTotalTitle")); this.jlblTotal.setText(TagHelper.getTag("jfrmVenta.jlblTotal")); this.jlblEfectivoTitle.setText(TagHelper.getTag("jfrmVenta.jlblEfectivoTitle")); this.jlblEfectivo.setText(TagHelper.getTag("jfrmVenta.jlblEfectivo")); this.jlblCambioTitle.setText(TagHelper.getTag("jfrmVenta.jlblCambioTitle")); this.jlblCambio.setText(TagHelper.getTag("jfrmVenta.jlblCambio")); } private void setTableModel() { tblModel.addColumn(TableColumns.PRODUCT_CODE); tblModel.addColumn(TableColumns.PRODUCT_DESCR); tblModel.addColumn(TableColumns.QUANTITY); tblModel.addColumn(TableColumns.UNIT_PRICE); tblModel.addColumn(TableColumns.SUBTOTAL); this.jtblVenta.setModel(tblModel); valid.anchoColumTable(jtblVenta); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jpnlTotales = new javax.swing.JPanel(); jlblTotalTitle = new javax.swing.JLabel(); jlblEfectivoTitle = new javax.swing.JLabel(); jlblEfectivo = new javax.swing.JLabel(); jlblCambioTitle = new javax.swing.JLabel(); jlblCambio = new javax.swing.JLabel(); jlblDateField = new javax.swing.JLabel(); jlblTimeField = new javax.swing.JLabel(); jlblTotal = new javax.swing.JLabel(); jpnlProducts = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jtblVenta = new javax.swing.JTable(); txt = new javax.swing.JTextField(); jpnlAttendedBy = new javax.swing.JPanel(); jlblUserName = new javax.swing.JLabel(); jlblAttendedBy = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); setBackground(new java.awt.Color(235, 122, 122)); setIconImage(getIconImage()); setUndecorated(Boolean.valueOf(ParamHelper.getParam("system.main.window.undecorated").toString()) ); setResizable(Boolean.valueOf(ParamHelper.getParam("system.main.window.resizable").toString()) ); jpnlTotales.setBackground(new java.awt.Color(255, 102, 102)); jpnlTotales.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jlblTotalTitle.setFont(new java.awt.Font("Tahoma", 0, 50)); // NOI18N jlblTotalTitle.setText("Total:"); jlblEfectivoTitle.setFont(new java.awt.Font("Tahoma", 0, 50)); // NOI18N jlblEfectivoTitle.setText("Efectivo:"); jlblEfectivo.setFont(new java.awt.Font("Tahoma", 0, 90)); // NOI18N jlblEfectivo.setText("1,000,000"); jlblCambioTitle.setFont(new java.awt.Font("Tahoma", 0, 50)); // NOI18N jlblCambioTitle.setText("Cambio:"); jlblCambio.setFont(new java.awt.Font("Tahoma", 0, 90)); // NOI18N jlblCambio.setText("1,000,000"); jlblDateField.setFont(new java.awt.Font("Tahoma", 0, 50)); // NOI18N jlblDateField.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jlblDateField.setText("21/01/2012"); jlblTimeField.setFont(new java.awt.Font("Tahoma", 0, 50)); // NOI18N jlblTimeField.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jlblTimeField.setText("59:59:59"); jlblTimeField.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); jlblTotal.setFont(new java.awt.Font("Tahoma", 0, 90)); // NOI18N jlblTotal.setText("1,000,000"); javax.swing.GroupLayout jpnlTotalesLayout = new javax.swing.GroupLayout(jpnlTotales); jpnlTotales.setLayout(jpnlTotalesLayout); jpnlTotalesLayout.setHorizontalGroup( jpnlTotalesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpnlTotalesLayout.createSequentialGroup() .addContainerGap() .addGroup(jpnlTotalesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jlblTotalTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jlblCambioTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jlblEfectivoTitle, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jpnlTotalesLayout.createSequentialGroup() .addComponent(jlblDateField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jlblTimeField, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addComponent(jlblTotal, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jlblEfectivo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jlblCambio, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) ); jpnlTotalesLayout.setVerticalGroup( jpnlTotalesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpnlTotalesLayout.createSequentialGroup() .addContainerGap() .addGroup(jpnlTotalesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlblTimeField) .addComponent(jlblDateField)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE) .addComponent(jlblTotalTitle) .addGap(18, 18, 18) .addComponent(jlblTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(15, 15, 15) .addComponent(jlblEfectivoTitle) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jlblEfectivo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jlblCambioTitle) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jlblCambio) .addContainerGap()) ); jpnlProducts.setBackground(new java.awt.Color(255, 102, 102)); jtblVenta.setFont(new java.awt.Font("Tahoma", 0, 15)); // NOI18N jtblVenta.setModel(this.tblModel); jtblVenta.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); jtblVenta.setGridColor(new java.awt.Color(0, 0, 0)); jtblVenta.setRowHeight(20); jtblVenta.setRowMargin(5); jtblVenta.setSelectionBackground(new Color(r, g, b)); jtblVenta.setShowVerticalLines(false); jtblVenta.getTableHeader().setResizingAllowed(false); jtblVenta.getTableHeader().setReorderingAllowed(false); jtblVenta.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jtblVentaKeyPressed(evt); } }); jScrollPane1.setViewportView(jtblVenta); txt.setFont(new java.awt.Font("Tahoma", 0, 17)); // NOI18N txt.setHorizontalAlignment(javax.swing.JTextField.LEFT); txt.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { txtFocusGained(evt); } }); txt.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtKeyTyped(evt); } }); javax.swing.GroupLayout jpnlProductsLayout = new javax.swing.GroupLayout(jpnlProducts); jpnlProducts.setLayout(jpnlProductsLayout); jpnlProductsLayout.setHorizontalGroup( jpnlProductsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpnlProductsLayout.createSequentialGroup() .addContainerGap() .addGroup(jpnlProductsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addComponent(txt)) .addContainerGap()) ); jpnlProductsLayout.setVerticalGroup( jpnlProductsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jpnlProductsLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jpnlAttendedBy.setBackground(new java.awt.Color(255, 102, 102)); jpnlAttendedBy.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jlblUserName.setFont(new java.awt.Font("Tahoma", 0, 28)); // NOI18N jlblUserName.setText("Usuario Usuario Usuario "); jlblAttendedBy.setFont(new java.awt.Font("Tahoma", 0, 28)); // NOI18N jlblAttendedBy.setText("Le atendió:"); javax.swing.GroupLayout jpnlAttendedByLayout = new javax.swing.GroupLayout(jpnlAttendedBy); jpnlAttendedBy.setLayout(jpnlAttendedByLayout); jpnlAttendedByLayout.setHorizontalGroup( jpnlAttendedByLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnlAttendedByLayout.createSequentialGroup() .addContainerGap() .addComponent(jlblAttendedBy) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jlblUserName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jpnlAttendedByLayout.setVerticalGroup( jpnlAttendedByLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnlAttendedByLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jpnlAttendedByLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jlblUserName) .addComponent(jlblAttendedBy)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jpnlProducts, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jpnlAttendedBy, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jpnlTotales, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jpnlProducts, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jpnlAttendedBy, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jpnlTotales, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtFocusGained this.txt.selectAll(); }//GEN-LAST:event_txtFocusGained private void txtKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtKeyTyped try { // if (evt.isControlDown()) { // return; if (evt.isControlDown()) { switch (evt.getKeyChar()) { case ShortCuts.SC_END_SALE: if (this.jtblVenta.getRowCount() > 0) { if (Util.isValidCashValue(txt.getText())) { if (Util.isCashExceeded(txt.getText())) { if (isCorrectAmount()) { this.finishOrder(); } else { valid.msjInfo(this, TagHelper.getTag("jfrmVenta.insufficientAmount")); } } else { valid.msjInfo(this, TagHelper.getTag("jfrmVenta.cashExceeded")); } } else { valid.msjInfo(this, TagHelper.getTag("jfrmVenta.emptyOrInvalidCash")); } } break; case ShortCuts.SC_QUERY_PRODUCT: txt.setText(Command.QUERY_PRODUCT); break; } } else { switch (evt.getKeyChar()) { case ShortCuts.SC_ENTER: String txtValue = this.txt.getText().trim(); if (!txtValue.isEmpty()) { String productCode = ""; String command = ""; int quantity = 1; //Identify command and codes if (txtValue.startsWith(Command.QUERY_PRODUCT)) { command = Command.QUERY_PRODUCT; productCode = txtValue.substring(2, txtValue.length()); } else if (Util.isMultiplicationCommand(txtValue)) { if (Util.isValidQty(txtValue.substring(0, txtValue.indexOf(Command.MULTIPLICATION)))) { command = Command.MULTIPLICATION; productCode = txtValue.substring(txtValue.indexOf(Command.MULTIPLICATION) + 1, txtValue.length()); quantity = Integer.parseInt(txtValue.substring(0, txtValue.indexOf(Command.MULTIPLICATION))); } else { valid.msjInfo(this, TagHelper.getTag("jfrmVenta.notValidQty").replace("#", ParamHelper.getParam("system.maxProducts").toString())); txt.setText(""); return; } } //Process command switch (command) { case Command.MULTIPLICATION: this.addProduct(quantity, productCode); break; case Command.QUERY_PRODUCT: queryProduct(productCode); break; default: this.addProduct(quantity, txtValue); break; } } break; } } } catch (NumberFormatException ex) { objLog.Log(ex.getMessage()); } }//GEN-LAST:event_txtKeyTyped private void jtblVentaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtblVentaKeyPressed if (evt.getKeyCode() == KeyEvent.VK_DELETE) { String productDescr = this.jtblVenta.getValueAt(jtblVenta.getSelectedRow(), 1).toString(); int op = valid.msjOption(TagHelper.getTag("jfrmVenta.cancelProductMsg").replace("#", productDescr), TagHelper.getTag("jfrmVenta.cancelProductTitle")); if (op == 0) { ((DefaultTableModel) jtblVenta.getModel()).removeRow(jtblVenta.getSelectedRow()); this.jlblTotal.setText(Util.formatDoubleValueToMoney(this.getTotalFromTable())); txt.requestFocus(); } } }//GEN-LAST:event_jtblVentaKeyPressed public void addProduct(int quantity, String productCode) { Product product = prodDao.selectProduct(productCode); if (product != null) { if (product.getActivo() == 0) { valid.msjInfo(this, TagHelper.getTag("jfrmVenta.tnaProduct")); } else { DefaultTableModelExtended model = (DefaultTableModelExtended) this.jtblVenta.getModel(); String[] rowData = new String[5]; rowData[0] = String.valueOf(product.getId_product()); rowData[1] = product.getDescripcion(); rowData[2] = String.valueOf(quantity); rowData[3] = String.valueOf(product.getP_venta()); rowData[4] = String.valueOf(quantity * product.getP_venta()); model.addRow(rowData); this.jlblTotal.setText(Util.formatDoubleValueToMoney(this.getTotalFromTable())); cleanLabelAndFieldValues(); } } else { valid.msjInfo(this, TagHelper.getTag("jfrmVenta.unknownProduct")); } } private void queryProduct(String productCode) { Product product = prodDao.selectProduct(productCode); if (product != null) { this.txt.setText(""); jfrmVentaConsultProductPrice queryProd = new jfrmVentaConsultProductPrice(this, true, product); queryProd.setVisible(true); } } private boolean isCorrectAmount() { boolean returnValue = false; try { double total = Util.formatMoneyToDouble(this.jlblTotal.getText().replace("$", "")); double cash = Util.formatMoneyToDouble(this.txt.getText().replace("$", "")); if (cash >= total) { returnValue = true; } } catch (NumberFormatException nfe) { objLog.Log(nfe.getMessage()); } return returnValue; } private void showVentaMenu() { jfrmVentaMenu menu = new jfrmVentaMenu(this, true); menu.setVisible(true); } private void showSearchProductWindow() { jfrmVentaMenuSearchProducts searchProducts = new jfrmVentaMenuSearchProducts(this, true); searchProducts.setVisible(true); } private void doPayment() { if (this.jtblVenta.getRowCount() > 0) { if (Util.isValidCashValue(txt.getText())) { if (Util.isCashExceeded(txt.getText())) { if (isCorrectAmount()) { this.finishOrder(); } else { valid.msjInfo(this, TagHelper.getTag("jfrmVenta.insufficientAmount")); } } else { valid.msjInfo(this, TagHelper.getTag("jfrmVenta.cashExceeded")); } } else { valid.msjInfo(this, TagHelper.getTag("jfrmVenta.emptyOrInvalidCash")); } } } private double getTotalFromTable() { int rows = this.jtblVenta.getRowCount(); Double orderTotal = 0.0; Double[] subtotalValues = new Double[rows]; try { for (int i = 0; i < rows; i++) { String columnValue = this.jtblVenta.getValueAt(i, this.jtblVenta.getColumnCount() - 1).toString(); subtotalValues[i] = Double.valueOf(columnValue); } } catch (NumberFormatException nfe) { objLog.Log("Error while getting values from jTable. " + nfe.getMessage()); } try { for (int i = 0; i < subtotalValues.length; i++) { orderTotal += subtotalValues[i]; } } catch (Exception e) { objLog.Log("Error while make the sum of the order. " + e.getMessage()); } return orderTotal; } private void finishOrder() { VentaLogic vtaLogic = new VentaLogic(); List<VentaDetalle> vdList = new ArrayList<>(); Venta venta = new Venta();; int cantidad = 0; int ticketNumber = 0; double total = 0; double efectivo = 0; double cambio = 0; try { cantidad = this.jtblVenta.getRowCount(); total = Util.formatMoneyToDouble(jlblTotal.getText().replace("$", "")); efectivo = Double.valueOf(txt.getText()); cambio = efectivo - total; jlblEfectivo.setText(Util.formatDoubleValueToMoney(efectivo)); jlblCambio.setText(Util.formatDoubleValueToMoney(cambio)); } catch (NumberFormatException nfe) { objLog.Log(nfe.getMessage()); } venta.setFecha(Util.getDate()); venta.setIdUsuario(Util.getCurrentUser()); venta.setTotal(total); //TODO: Se agrega el cliente fijo para guardar la venta venta.setCveCliente(1); venta.setEfectivo(efectivo); venta.setCambio(cambio); venta.setCantidad(cantidad); try { ticketNumber = vtaLogic.saveVenta(venta); vdList = saveOrderDetail(venta); } catch (Exception e) { objLog.Log(e.getMessage()); } if (!vdList.isEmpty()) { try { restartControls(); // Question before print ticket if (Boolean.valueOf(ParamHelper.getParam("jfrmVenta.printTicketQuestionnEnabled").toString())) { int option = valid.msjOption(TagHelper.getTag("jfrmVenta.printTicketMsg"), TagHelper.getTag("jfrmVenta.printTicketTitle")); if (option == 0) { POSPrintService.printTicket(venta); } else { POSPrintService.printTicket(null); } sendTyketPostRequest(vdList); } else { POSPrintService.printTicket(venta); } } catch (Exception e) { objLog.Log("Possible cause: Error while printing. " + e.getMessage()); } } else { objLog.Log("Order number " + ticketNumber + " not saved correctly"); } } private List<VentaDetalle> saveOrderDetail(Venta venta) { List<VentaDetalle> vdList = new ArrayList<>(); int items = this.jtblVenta.getRowCount(); try { for (int i = 0; i < items; i++) { String productCode = String.valueOf(this.jtblVenta.getValueAt(i, 0)); int cantidad = Integer.parseInt(this.jtblVenta.getValueAt(i, 2).toString()); double subTotal = Double.valueOf(this.jtblVenta.getValueAt(i, 4).toString()); VentaDetalle vd = new VentaDetalle(); vd.setVenta(venta); vd.setProductCode(productCode); vd.setCantidad(cantidad); vd.setSubtotal(subTotal); try { VentadDetalleLogic vdLogic = new VentadDetalleLogic(); vdLogic.saveVentaDetalle(vd); vdList.add(vd); } catch (Exception e) { objLog.Log("Error while saving OrderDetail. " + e.getMessage()); return null; } } } catch (NumberFormatException nfe) { objLog.Log(nfe.getMessage()); return null; } catch (UnsupportedOperationException | ClassCastException | NullPointerException | IllegalArgumentException nfe) { objLog.Log(nfe.getMessage()); return null; } return vdList; } public void restartControls() { valid.cleanTable(jtblVenta); this.txt.setText(""); } private void cleanLabelAndFieldValues() { this.txt.setText(""); double cash = Util.formatMoneyToDouble(this.jlblEfectivo.getText().replace("$", "")); if (cash > 0) { this.jlblEfectivo.setText(TagHelper.getTag("jfrmVenta.jlblEfectivo")); this.jlblCambio.setText(TagHelper.getTag("jfrmVenta.jlblCambio")); } } private void sendTyketPostRequest(List<VentaDetalle> detail){ if(!detail.isEmpty()){ TyketRestClient restClient = new TyketRestClient(); // Create USER Venta v = detail.get(0).getVenta(); User u = new User(); u.setUsername(v.getIdUsuario().getNombre()); restClient.sendRequest(HttpMethod.POST, u, u.getClass()); // Crete Ticket Ticket ticket = new Ticket(); ticket.setDate(Util.getDate()); ticket.setUser(u); restClient.sendRequest(HttpMethod.POST, ticket, ticket.getClass()); for (VentaDetalle vd : detail) { Product product = prodDao.selectProduct(vd.getProductCode()); Article article = new Article(); article.setName(product.getDescripcion()); article.setPrice(product.getP_venta()); article.setAmount(vd.getCantidad()); article.setTicket(ticket); restClient.sendRequest(HttpMethod.POST, article, article.getClass()); } } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel jlblAttendedBy; private javax.swing.JLabel jlblCambio; private javax.swing.JLabel jlblCambioTitle; private javax.swing.JLabel jlblDateField; private javax.swing.JLabel jlblEfectivo; private javax.swing.JLabel jlblEfectivoTitle; private javax.swing.JLabel jlblTimeField; private javax.swing.JLabel jlblTotal; private javax.swing.JLabel jlblTotalTitle; private javax.swing.JLabel jlblUserName; private javax.swing.JPanel jpnlAttendedBy; private javax.swing.JPanel jpnlProducts; private javax.swing.JPanel jpnlTotales; protected javax.swing.JTable jtblVenta; private javax.swing.JTextField txt; // End of variables declaration//GEN-END:variables }
package storm2014.commands; import edu.wpi.first.wpilibj.command.Command; import storm2014.Robot; public class TomahawkRev extends Command { private double _speed; private boolean _hasBeenForward = false; public TomahawkRev(double speed){ _speed = speed; } protected void initialize() { Robot.tomahawk.setMotorRaw(_speed); } protected void execute() { if (!_hasBeenForward ){ _hasBeenForward = Robot.tomahawk.isForward(); } } protected boolean isFinished() { return _hasBeenForward && Robot.tomahawk.isForward(); } protected void end() { Robot.tomahawk.setMotorRaw(0); } protected void interrupted() { end(); } }
package com.realexpayments.hpp.sdk; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.realexpayments.hpp.sdk.domain.HppRequest; import com.realexpayments.hpp.sdk.domain.HppResponse; import com.realexpayments.hpp.sdk.utils.JsonUtils; import com.realexpayments.hpp.sdk.utils.ValidationUtils; /** * <p> * RealexHpp class for converting HPP requests and responses to and from JSON. * This class is also responsible for validating inputs, generating defaults and encoding parameter values. * </p> * <p> * Creating Request JSON for Realex JS SDK * <code><pre> * HppRequest hppRequest = new HppRequest().addMerchantId("merchantId").addAmount(100)...addAutoSettleFlag(true); * RealexHpp realexHpp = new RealexHpp("mySecret"); * String json = realexHpp.requestToJson(hppRequest); * </pre></code> * </p> * <p> * Consuming Response JSON from Realex JS SDK * <code><pre> * RealexHpp realexHpp = new RealexHpp("mySecret"); * HppResponse hppResponse = realexHpp.responseFromJson(responseJson); * </pre></code> * </p> * @author markstanford * */ public class RealexHpp { /** * Logger */ private static final Logger LOGGER = LoggerFactory.getLogger(RealexHpp.class); /** * The shared secret issued by Realex. Used to create the SHA-1 hash in the request and * to verify the validity of the XML response. */ private String secret; /** * RealexHpp constructor. * * @param secret */ public RealexHpp(String secret) { this.secret = secret; } /** * <p> * Method produces JSON from <code>HppRequest</code> object. * Carries out the following actions: * <ul> * <li>Validates inputs</li> * <li>Generates defaults for security hash, order ID and time stamp (if required)</li> * <li>Base64 encodes inputs</li> * <li>Serialises request object to JSON</li> * </ul> * </p> * * @param hppRequest * @return String */ public String requestToJson(HppRequest hppRequest) { LOGGER.info("Converting HppRequest to JSON."); String json = null; //generate defaults LOGGER.debug("Generating defaults."); hppRequest.generateDefaults(secret); //validate request LOGGER.debug("Validating request."); ValidationUtils.validate(hppRequest); //encode LOGGER.debug("Encoding object."); hppRequest = hppRequest.encode(); //convert to JSON LOGGER.debug("Converting to JSON."); json = JsonUtils.toJson(hppRequest); return json; } /** * <p> * Method produces <code>HppRequest</code> object from JSON. * Carries out the following actions: * <ul> * <li>Deserialises JSON to request object</li> * <li>Decodes Base64 inputs</li> * <li>Validates inputs</li> * </ul> * </p> * * @param json * @param encoded <code>true</code> if the JSON values have been encoded. * @return HppRequest */ public HppRequest requestFromJson(String json, boolean encoded) { LOGGER.info("Converting JSON to HppRequest."); //convert to HppRequest from JSON HppRequest hppRequest = JsonUtils.fromJsonHppRequest(json); //decode if necessary if (encoded) { LOGGER.debug("Decoding object."); hppRequest = hppRequest.decode(); } //validate HPP request LOGGER.debug("Validating request."); ValidationUtils.validate(hppRequest); return hppRequest; } /** * <p> * Method produces <code>HppRequest</code> object from JSON. * Carries out the following actions: * <ul> * <li>Deserialises JSON to request object</li> * <li>Decodes Base64 inputs</li> * <li>Validates inputs</li> * </ul> * </p> * * @param json * @return HppRequest */ public HppRequest requestFromJson(String json) { return requestFromJson(json, true); } /** * <p> * Method produces JSON from <code>HppResponse</code> object. * Carries out the following actions: * <ul> * <li>Generates security hash</li> * <li>Base64 encodes inputs</li> * <li>Serialises response object to JSON</li> * </ul> * </p> * * @param hppResponse * @return String */ public String responseToJson(HppResponse hppResponse) { LOGGER.info("Converting HppResponse to JSON."); String json = null; //generate hash LOGGER.debug("Generating hash."); hppResponse.hash(secret); //encode LOGGER.debug("Encoding object."); hppResponse = hppResponse.encode(); //convert to JSON LOGGER.debug("Converting to JSON."); json = JsonUtils.toJson(hppResponse); return json; } /** * <p> * Method produces <code>HppResponse</code> object from JSON. * Carries out the following actions: * <ul> * <li>Deserialises JSON to response object</li> * <li>Decodes Base64 inputs</li> * <li>Validates hash</li> * </ul> * </p> * * @param json * @return HppRequest */ public HppResponse responseFromJson(String json) { return responseFromJson(json, true); } /** * <p> * Method produces <code>HppResponse</code> object from JSON. * Carries out the following actions: * <ul> * <li>Deserialises JSON to response object</li> * <li>Decodes Base64 inputs</li> * <li>Validates hash</li> * </ul> * </p> * * @param json * @param encoded <code>true</code> if the JSON values have been encoded. * @return HppRequest */ public HppResponse responseFromJson(String json, boolean encoded) { LOGGER.info("Converting JSON to HppResponse."); //convert to HppResponse from JSON HppResponse hppResponse = JsonUtils.fromJsonHppResponse(json); //decode if necessary if (encoded) { LOGGER.debug("Decoding object."); hppResponse = hppResponse.decode(); } //validate HPP response hash LOGGER.debug("Validating response hash."); ValidationUtils.validate(hppResponse, secret); return hppResponse; } }
package com.roamsys.gwtjqvmap; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArrayString; /** * jQuery Vector Map properties * @author mbartel (ROAMSYS S.A.) */ public final class VMapProperties extends JavaScriptObject { protected VMapProperties() {}; /** * Map you want to load. Must include the javascript file with the name of the map you want. * Available maps with this library are world_en, usa_en, europe_en and germany_en * @param map name of the map to use */ public native void setMap(final String map) /*-{ this.map = map; }-*/; /** * Background color of map container in any CSS compatible format. * @param backgroundColor the RGG color code */ public native void setBackgroundColor(final String backgroundColor) /*-{ this.backgroundColor = backgroundColor; }-*/; /** * Border Color to use to outline map objects * @param borderColor the RGB color code */ public native void setBorderColor(final String borderColor) /*-{ this.borderColor = borderColor; }-*/; /** * Border Opacity to use to outline map objects * @param borderOpacity use anything from 0-1, e.g. 0.5, defaults to 0.25 */ public native void setBorderOpacity(final double borderOpacity) /*-{ this.borderOpacity = borderOpacity; }-*/; /** * Border Width to use to outline map objects * @param borderWidth the border with (default is 1) */ public native void setBorderWidth(final int borderWidth) /*-{ this.borderWidth = borderWidth; }-*/; /** * Color of map regions * @param color the RGB color code */ public native void setColor(final String color) /*-{ this.color = color; }-*/; /** * Returns the color of unselected map regions * @return the RGB color code */ public native String getColor() /*-{ return this.color; }-*/; /** * Colors of individual map regions. Keys of the colors objects are country codes according to ISO 3166-1 alpha-2 standard. Keys of colors must be in lower case. * @param colors map of ISO code to RGB color code */ private native void setColors(final JavaScriptObject colors) /*-{ this.colors = colors; }-*/; /** * Whether to Enable Map Zoom * @param enableZoom true or false, defaults to true */ public native void setEnableZoom(final boolean enableZoom) /*-{ this.enableZoom = enableZoom; }-*/; /** * Color of the region when mouse pointer is over it * @param hoverColor the RGB color code */ public native void setHoverColor(final String hoverColor) /*-{ this.hoverColor = hoverColor; }-*/; /** * Opacity of the region when mouse pointer is over it * @param hoverOpacity use anything from 0-1, defaults to 0.5 */ public native void setHoverOpacity(final double hoverOpacity) /*-{ this.hoverOpacity = hoverOpacity; }-*/; /** * This option defines colors, with which regions will be painted when you set option values. * Array scaleColors can have more then two elements. Elements should be strings representing colors in RGB hex format. * @param scaleColors list of RGB colors */ public void setScaleColors(final Iterable<String> scaleColors) { final JavaScriptObject array = JsArrayString.createArray(); for (final String color : scaleColors) { ((JsArrayString) array).push(color); } setScaleColors(array); } private native void setScaleColors(final JavaScriptObject scaleColors) /*-{ this.scaleColors = scaleColors; }-*/; /** * The color to use to highlight the selected region * @param selectedColor the RGB color code */ public native void setSelectedColor(final String selectedColor) /*-{ this.selectedColor = selectedColor; }-*/; /** * This is the Region that you are looking to have preselected * @param selectedRegion two letter ISO code, defaults to null */ public native void setSelectedRegion(final String selectedRegion) /*-{ this.selectedRegion = selectedRegion; }-*/; /** * Whether to show Tooltips on Mouseover * @param showTooltip true or false, defaults to true */ public native void showTooltip(final boolean showTooltip) /*-{ this.showTooltip = showTooltip; }-*/; /** * Creates a new instance with standard properties * @return a new world map properties instance */ public static VMapProperties create() { return create(VMap.ON_REGION_OVER_PREFIX, VMap.ON_REGION_OUT_PREFIX, VMap.ON_REGION_CLICK_PREFIX); } /** * Creates a new instance with standard properties * @param over prefix for onRegionOver event handlers * @param out prefix for onRegionOut event handlers * @param click prefix for onRegionClick event handlers * @return a new world map properties instance */ private static native VMapProperties create(final String over, final String out, final String click) /*-{ var uuid = Math.floor((1 + Math.random()) * 0x100000000).toString(16); var handleVMapEvents = $entry(@com.roamsys.gwtjqvmap.VMap::handleVMapRegionEvents(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)); return { uuid: uuid, map: 'world_en', showTooltip: false, color: '#f4f3f0', enableZoom: true, onRegionOver: function(event, code, region) { handleVMapEvents(uuid, over, code, region); }, onRegionOut: function(event, code, region) { handleVMapEvents(uuid, out, code, region); }, onRegionClick: function(event, code, region) { handleVMapEvents(uuid, click, code, region); } }; }-*/; /** * Returns the unique ID, that will be provided by each callback execution * @return the unique ID */ public native String getUUID() /*-{ return this.uuid; }-*/; }
package com.rultor.agents.daemons; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.jcabi.aspects.Immutable; import com.jcabi.aspects.Tv; import com.jcabi.log.Logger; import com.jcabi.ssh.SSH; import com.jcabi.ssh.Shell; import com.jcabi.xml.XML; import com.rultor.Time; import com.rultor.agents.AbstractAgent; import com.rultor.agents.shells.TalkShells; import java.io.IOException; import java.util.Collection; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import org.xembly.Directive; import org.xembly.Directives; import org.xembly.Xembler; /** * Marks the daemon as done. * * @author Yegor Bugayenko (yegor@teamed.io) * @version $Id$ * @since 1.0 * @checkstyle ClassDataAbstractionCoupling (500 lines) * @todo @567 Refactor this class to use less objects and remove checkstyle * exception above. */ @Immutable @ToString @EqualsAndHashCode(callSuper = false) public final class EndsDaemon extends AbstractAgent { /** * Prefix for log highlights. */ public static final String HIGHLIGHTS_PREFIX = "RULTOR: "; /** * Join shell commands with this string. */ private static final String SHELL_JOINER = " && "; /** * Ctor. */ public EndsDaemon() { super("/talk/daemon[started and not(code) and not(ended)]"); } @Override public Iterable<Directive> process(final XML xml) throws IOException { final Shell shell = new TalkShells(xml).get(); final String dir = xml.xpath("/talk/daemon/dir/text()").get(0); final int exit = new Shell.Empty(shell).exec( Joiner.on(EndsDaemon.SHELL_JOINER).join( String.format("cd %s ", SSH.escape(dir)), "if [ ! -e pid ]; then exit 1; fi", "pid=$(cat pid)", "ps -p \"${pid}\" >/dev/null" ) ); final Directives dirs = new Directives(); if (exit == 0) { Logger.info( this, "the daemon is still running in %s (%s)", dir, xml.xpath("/talk/@name").get(0) ); } else { dirs.append(this.end(shell, dir)); } return dirs; } /** * End this daemon. * @param shell Shell * @param dir The dir * @return Directives * @throws IOException If fails */ private Iterable<Directive> end(final Shell shell, final String dir) throws IOException { final int exit = EndsDaemon.exit(shell, dir); final String stdout = new Shell.Plain(new Shell.Safe(shell)).exec( Joiner.on(EndsDaemon.SHELL_JOINER).join( String.format("cd %s", SSH.escape(dir)), "cat stdout" ) ); final Collection<String> lines = Lists.newArrayList( Splitter.on(System.lineSeparator()).split(stdout) ); final String highlights = Joiner.on("\n").join( Iterables.transform( Iterables.filter( lines, new Predicate<String>() { @Override public boolean apply(final String input) { return input.startsWith( EndsDaemon.HIGHLIGHTS_PREFIX ); } } ), new Function<String, String>() { @Override public String apply(final String str) { return StringUtils.removeStart( str, EndsDaemon.HIGHLIGHTS_PREFIX ); } } ) ); Logger.info(this, "daemon finished at %s, exit: %d", dir, exit); return new Directives() .xpath("/talk/daemon") .strict(1) .add("ended").set(new Time().iso()).up() .add("code").set(Integer.toString(exit)).up() .add("highlights").set(Xembler.escape(highlights)).up() .add("tail") .set( Xembler.escape( StringUtils.substring( Joiner.on(System.lineSeparator()).join( Iterables.skip( lines, Math.max(lines.size() - Tv.SIXTY, 0) ) ), -Tv.HUNDRED * Tv.THOUSAND ) ) ); } /** * Get exit code. * @param shell Shell * @param dir The dir * @return Exit code * @throws IOException If fails */ private static int exit(final Shell shell, final String dir) throws IOException { final String status = new Shell.Plain(new Shell.Safe(shell)).exec( Joiner.on(EndsDaemon.SHELL_JOINER).join( String.format("cd %s", SSH.escape(dir)), "if [ ! -e status ]; then echo 127; exit; fi", "cat status" ) ).trim().replaceAll("[^0-9]", ""); final int exit; if (status.isEmpty()) { exit = 1; } else { exit = Integer.parseInt(status); } return exit; } }
package com.skelril.aurora.util; import com.sk89q.worldedit.BlockVector; import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.blocks.BlockType; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import java.util.ArrayList; import java.util.List; public class LocationUtil { private static final BlockFace[] surroundingBlockFaces = new BlockFace[]{ BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.NORTH_EAST, BlockFace.NORTH_WEST, BlockFace.SOUTH_EAST, BlockFace.SOUTH_WEST }; @Deprecated private static Location matchLocationFromId(int id) { int trueId = id - 1; Location[] TeleportLocations = new Location[5]; TeleportLocations[0] = new Location(Bukkit.getWorld("Destrio"), -594, 10, 1180); TeleportLocations[1] = Bukkit.getWorld("Destrio").getSpawnLocation(); TeleportLocations[2] = new Location(Bukkit.getWorld("Destrio"), 36, 79, 1125); TeleportLocations[3] = new Location(Bukkit.getWorld("Destrio"), -285, 140, -664); TeleportLocations[4] = new Location(Bukkit.getWorld("Destrio"), -59, 98, -1698); for (int i = 0; i < TeleportLocations.length; i++) { if (i == trueId) return TeleportLocations[i]; } return null; } @Deprecated private static int getLocationId(String name) { String[] LocationNames = new String[5]; LocationNames[0] = "THE BANK"; LocationNames[1] = "FLINT"; LocationNames[2] = "FORT"; LocationNames[3] = "SKY CITY"; LocationNames[4] = "MUSHROOM ISLE"; for (int i = 0; i < LocationNames.length; i++) { if (LocationNames[i].equalsIgnoreCase(name)) { return i + 1; } } return 0; } @Deprecated public static Location matchLocationFromText(String name) { return matchLocationFromId(getLocationId(name)); } public static double distanceSquared2D(Location a, Location b) { return Math.pow(a.getX() - b.getX(), 2) + Math.pow(a.getZ() - b.getZ(), 2); } public static Location grandBank(World world) { if (!world.getName().equals("City")) return null; return new Location(world, 592, 83, 1176.5); } public static boolean toGround(Player player) { return player.teleport(findFreePosition(player.getLocation())); } public static Location findFreePosition(final Location pos) { // Find the raw safe position Location mPos = findRawFreePosition(pos); // Null safety check if (mPos == null) { return mPos; } // Add the offset to the location mPos.add(pos.getX() - pos.getBlockX(), 0, pos.getZ() - pos.getBlockZ()); // Move to the center of the block if undefined if (mPos.getX() == mPos.getBlockX()) mPos.add(.5, 0, 0); if (mPos.getZ() == mPos.getBlockZ()) mPos.add(0, 0, .5); return mPos; } public static Location findRawFreePosition(final Location pos) { World world = pos.getWorld(); // Let's try going down Block block = pos.getBlock().getRelative(0, 1, 0); if (!block.getChunk().isLoaded()) { block.getChunk().load(); } int free = 0; // Look for ground while (block.getY() > 1 && (BlockType.canPassThrough(block.getTypeId()) || block.getTypeId() == BlockID.BED)) { free++; block = block.getRelative(0, -1, 0); } if (block.getY() == 0) return null; // No ground below! if (free >= 2) { if (block.getTypeId() == BlockID.LAVA || block.getTypeId() == BlockID.STATIONARY_LAVA) { return null; // Not safe } Block tb = block.getRelative(0, 1, 0); Location l = tb.getLocation(); l.add(new Vector(0, BlockType.centralTopLimit(tb.getTypeId(), tb.getData()), 0)); l.setPitch(pos.getPitch()); l.setYaw(pos.getYaw()); return l; } // Let's try going up block = pos.getBlock().getRelative(0, -1, 0); free = 0; boolean foundGround = false; while (block.getY() + 1 < world.getMaxHeight()) { if (BlockType.canPassThrough(block.getTypeId()) || block.getTypeId() == BlockID.BED) { free++; } else { free = 0; foundGround = block.getTypeId() != BlockID.LAVA && block.getTypeId() != BlockID.STATIONARY_LAVA; } if (foundGround && free == 2) { Block tb = block.getRelative(0, -1, 0); Location l = tb.getLocation(); l.add(new Vector(0, BlockType.centralTopLimit(tb.getTypeId(), tb.getData()), 0)); l.setPitch(pos.getPitch()); l.setYaw(pos.getYaw()); return l; } block = block.getRelative(0, 1, 0); } return null; } public static Location findRandomLoc(Location searchFromLocation, final int radius) { return findRandomLoc(searchFromLocation.getBlock(), radius); } public static Location findRandomLoc(Block searchFromLocation, final int radius) { return findRandomLoc(searchFromLocation, radius, false); } public static Location findRandomLoc(Location searchFromLocation, final int radius, boolean trueRandom) { return findRandomLoc(searchFromLocation.getBlock(), radius, trueRandom); } public static Location findRandomLoc(Location searchFromLocation, final int radius, boolean trueRandom, boolean airOnly) { return findRandomLoc(searchFromLocation.getBlock(), radius, trueRandom, airOnly); } public static Location findRandomLoc(Block searchFromLocation, final int radius, boolean trueRandom) { return findRandomLoc(searchFromLocation, radius, trueRandom, true); } public static Location findRandomLoc(Block searchFromLocation, final int radius, boolean trueRandom, boolean airOnly) { int trueRadius = trueRandom ? ChanceUtil.getRandom(radius) : radius; BlockFace dir; do { dir = BlockFace.values()[(ChanceUtil.getRandom(BlockFace.values().length) - 1)]; } while (dir == null); if (airOnly) { return findFreePosition(searchFromLocation.getRelative(dir, trueRadius).getLocation()); } else { return searchFromLocation.getRelative(dir, trueRadius).getLocation(); } } public static boolean containsPlayer(World world, ProtectedRegion region) { for (Player player : world.getPlayers()) { Location loc = player.getLocation(); if (region.contains(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())) { return true; } } return false; } public static boolean isInRegion(ProtectedRegion region, Entity entity) { return isInRegion(region, entity.getLocation()); } public static boolean isInRegion(ProtectedRegion region, Location loc) { return region.contains(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); } public static boolean isInRegion(World world, ProtectedRegion region, Entity entity) { return isInRegion(world, region, entity.getLocation()); } public static boolean isInRegion(World world, ProtectedRegion region, Location loc) { return world.equals(loc.getWorld()) && region.contains(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); } public static List<Player> getPlayersStandingOnRegion(World world, ProtectedRegion region) { List<Player> playerList = new ArrayList<>(); for (Player player : world.getPlayers()) { Block block = player.getLocation().getBlock(); if (region.contains(block.getX(), block.getY() - 1, block.getZ()) || region.contains(block.getX(), block.getY() - 2, block.getZ())) { playerList.add(player); } } return playerList; } public static boolean isBelowPlayer(World world, ProtectedRegion region) { for (Player player : world.getPlayers()) { Block block = player.getLocation().getBlock(); if (region.contains(block.getX(), block.getY() - 1, block.getZ()) || region.contains(block.getX(), block.getY() - 2, block.getZ())) { return true; } } return false; } public static boolean isBelowPlayer(World world, ProtectedRegion region, Player player) { Block block = player.getLocation().getBlock(); return (region.contains(block.getX(), block.getY() - 1, block.getZ()) || region.contains(block.getX(), block.getY() - 2, block.getZ())) && world.equals(player.getWorld()); } public static boolean isCloseToPlayer(Block block, int distance) { return isCloseToPlayer(block.getLocation(), distance); } public static boolean isCloseToPlayer(Location location, int distance) { int DISTANCE_SQ = distance * distance; for (Player player : location.getWorld().getPlayers()) { if (player.getLocation().distanceSquared(location) <= DISTANCE_SQ) { return true; } } return false; } public static Location[] getNearbyLocations(Location startLocation, int searchRadius) { return getNearbyLocations(startLocation, searchRadius, 0); } public static Location[] getNearbyLocations(Location startLocation, int searchRadius, int vert) { if (searchRadius < 1) { return new Location[]{startLocation}; } Location[] locations; if (vert > 0) { locations = new Location[(searchRadius * BlockFace.values().length) + (searchRadius * BlockFace.values() .length * (vert * 2))]; } else { locations = new Location[searchRadius * BlockFace.values().length]; } int locationNumber = 0; for (int r = 0; r < searchRadius; r++) { for (BlockFace blockFace : BlockFace.values()) { locations[locationNumber] = startLocation.getBlock().getRelative(blockFace, r).getLocation(); locationNumber++; } } if (vert > 0) { for (int v = 0; v < vert; v++) { for (int r = 0; r < searchRadius; r++) { for (BlockFace blockFace : BlockFace.values()) { locations[locationNumber] = startLocation.getBlock().getRelative(blockFace, r).getRelative(BlockFace.UP, v + 1).getLocation(); locationNumber++; } for (BlockFace blockFace : BlockFace.values()) { locations[locationNumber] = startLocation.getBlock().getRelative(blockFace, r).getRelative(BlockFace.DOWN, v + 1).getLocation(); locationNumber++; } } } } return locations; } public static com.sk89q.worldedit.Vector pickLocation(BlockVector min, BlockVector max) { return pickLocation(min.getX(), max.getX(), min.getZ(), max.getZ()); } public static com.sk89q.worldedit.Vector pickLocation(double minX, double maxX, double minZ, double maxZ) { double x; double z; if (minX > maxX) { x = ChanceUtil.getRangedRandom(maxX, minX); } else { x = ChanceUtil.getRangedRandom(minX, maxX); } if (minZ > maxZ) { z = ChanceUtil.getRangedRandom(maxZ, minZ); } else { z = ChanceUtil.getRangedRandom(minZ, maxZ); } return new com.sk89q.worldedit.Vector(x, 0, z); } public static com.sk89q.worldedit.Vector pickLocation(double minX, double maxX, double minY, double maxY, double minZ, double maxZ) { double y; if (minY > maxY) { y = ChanceUtil.getRangedRandom(maxY, minY); } else { y = ChanceUtil.getRangedRandom(minY, maxY); } return pickLocation(minX, maxX, minZ, maxZ).add(0, y, 0); } public static boolean isLocNearby(Location startLocation, Location location, int searchRadius) { for (Location checkLocation : getNearbyLocations(startLocation, searchRadius)) { if (location.equals(checkLocation)) { return true; } } return false; } public static Location parseLocation(String string) { try { String[] locationString = string.split(","); return new Location(Bukkit.getWorld(locationString[3]), Integer.parseInt(locationString[0]), Integer.parseInt(locationString[1]), Integer.parseInt(locationString[2])); } catch (Exception e) { return null; } } public static boolean getBelowID(Location loc, int id) { Block searchBlock = loc.add(0, -1, 0).getBlock(); if (searchBlock.getTypeId() == id) return true; if (searchBlock.getTypeId() != BlockID.AIR) return false; for (BlockFace blockFace : surroundingBlockFaces) { if (searchBlock.getRelative(blockFace).getTypeId() == id) return true; } return false; } }
package com.squareup.spoon; import com.android.ddmlib.testrunner.ITestRunListener; import com.android.ddmlib.testrunner.TestIdentifier; import com.squareup.spoon.adapters.TestIdentifierAdapter; import java.util.HashMap; import java.util.Map; import static com.google.common.base.Preconditions.checkNotNull; import static com.squareup.spoon.SpoonLogger.logDebug; import static com.squareup.spoon.SpoonLogger.logError; import static com.squareup.spoon.SpoonLogger.logInfo; /** Marshals an {@link ITestRunListener}'s output to a {@link DeviceResult.Builder}. */ final class SpoonTestListener implements ITestRunListener { private final DeviceResult.Builder result; private final Map<TestIdentifier, DeviceTestResult.Builder> methodResults = new HashMap<TestIdentifier, DeviceTestResult.Builder>(); private final boolean debug; private final TestIdentifierAdapter testIdentifierAdapter; SpoonTestListener(DeviceResult.Builder result, boolean debug, TestIdentifierAdapter testIdentifierAdapter) { checkNotNull(result); this.result = result; this.debug = debug; this.testIdentifierAdapter = testIdentifierAdapter; } @Override public void testRunStarted(String runName, int testCount) { logDebug(debug, "testCount=%d runName=%s", testCount, runName); } @Override public void testStarted(TestIdentifier test) { logDebug(debug, "test=%s", test); DeviceTestResult.Builder methodResult = new DeviceTestResult.Builder().startTest(); methodResults.put(testIdentifierAdapter.adapt(test), methodResult); } @Override public void testFailed(TestFailure status, TestIdentifier test, String trace) { logDebug(debug, "test=%s", test); test = testIdentifierAdapter.adapt(test); DeviceTestResult.Builder methodResult = methodResults.get(test); if (methodResult == null) { logError("unknown test=%s", test); methodResult = new DeviceTestResult.Builder(); methodResults.put(test, methodResult); } switch (status) { case FAILURE: logDebug(debug, "failed %s", trace); methodResult.markTestAsFailed(trace); break; case ERROR: logDebug(debug, "error %s", trace); methodResult.markTestAsError(trace); logInfo("Failed " + test); break; default: throw new IllegalArgumentException("Unknown test failure status: " + status); } } @Override public void testEnded(TestIdentifier test, Map<String, String> testMetrics) { logDebug(debug, "test=%s", test); test = testIdentifierAdapter.adapt(test); DeviceTestResult.Builder methodResult = methodResults.get(test); if (methodResult == null) { logError("unknown test=%s", test); methodResult = new DeviceTestResult.Builder().startTest(); methodResults.put(test, methodResult); } DeviceTestResult.Builder methodResultBuilder = methodResult.endTest(); result.addTestResultBuilder(DeviceTest.from(test), methodResultBuilder); logInfo("Passed " + test); } @Override public void testRunFailed(String errorMessage) { logDebug(debug, "errorMessage=%s", errorMessage); result.addException(errorMessage); } @Override public void testRunStopped(long elapsedTime) { logDebug(debug, "elapsedTime=%d", elapsedTime); } @Override public void testRunEnded(long elapsedTime, Map<String, String> runMetrics) { logDebug(debug, "elapsedTime=%d", elapsedTime); } }
package de.evosec.pomversionupdater; import static java.util.Objects.requireNonNull; public class Artifact { private final String groupId; private final String artifactId; private String type = "jar"; private String classifier; private String version; public Artifact(String groupId, String artifactId) { this.groupId = requireNonNull(groupId); this.artifactId = requireNonNull(artifactId); } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getClassifier() { return classifier; } public void setClassifier(String classifier) { this.classifier = classifier; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getGroupId() { return groupId; } public String getArtifactId() { return artifactId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (artifactId == null ? 0 : artifactId.hashCode()); result = prime * result + (classifier == null ? 0 : classifier.hashCode()); result = prime * result + (groupId == null ? 0 : groupId.hashCode()); result = prime * result + (type == null ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Artifact other = (Artifact) obj; if (artifactId == null) { if (other.artifactId != null) { return false; } } else if (!artifactId.equals(other.artifactId)) { return false; } if (classifier == null) { if (other.classifier != null) { return false; } } else if (!classifier.equals(other.classifier)) { return false; } if (groupId == null) { if (other.groupId != null) { return false; } } else if (!groupId.equals(other.groupId)) { return false; } if (type == null) { if (other.type != null) { return false; } } else if (!type.equals(other.type)) { return false; } return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(groupId).append(":").append(artifactId); if (type != null) { builder.append(":").append(type); } if (classifier != null) { builder.append(":").append(classifier); } if (version != null) { builder.append(":").append(version); } return builder.toString(); } }
package de.is24.deadcode4j; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.annotation.Nonnull; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.util.Collection; import static com.google.common.collect.Lists.newArrayList; /** * Analyzes Spring XML files: lists the classes being referenced. * * @since 1.0.2 */ public class SpringXmlAnalyzer implements Analyzer { private final SAXParser parser; private final XmlHandler handler; private final Collection<String> referencedClasses = newArrayList(); public SpringXmlAnalyzer() { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); this.parser = factory.newSAXParser(); } catch (Exception e) { throw new RuntimeException("Failed to set up XML parser!", e); } this.handler = new XmlHandler(); } @Override public void doAnalysis(@Nonnull CodeContext codeContext, @Nonnull String fileName) { if (fileName.endsWith(".xml")) { analyzeXmlFile(codeContext, fileName); } } private void analyzeXmlFile(@Nonnull CodeContext codeContext, @Nonnull String file) { this.referencedClasses.clear(); this.handler.reset(); try { parser.parse(codeContext.getClassLoader().getResourceAsStream(file), handler); } catch (StopParsing command) { return; } catch (Exception e) { throw new RuntimeException("Failed to parse [" + file + "]!", e); } codeContext.addDependencies("_Spring_", this.referencedClasses); } /** * Used to indicate that XML parsing can be stopped. * * @since 1.0.2 */ private static class StopParsing extends SAXException { } private class XmlHandler extends DefaultHandler { private boolean firstElement = true; @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws StopParsing { if (firstElement && !"beans".equals(qName)) { throw new StopParsing(); } else { firstElement = false; } if (!"bean".equals(qName)) { return; } String className = attributes.getValue("class"); if (className != null) { referencedClasses.add(className); } } public void reset() { this.firstElement = true; } } }
package de.teiesti.postie.recipients; import de.teiesti.postie.Postman; import de.teiesti.postie.Recipient; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; /** * A {@link Mailbox} is a {@link Recipient} that stores accepted {@link Letter}s until they where received. To use a * {@link Mailbox} register it to one or more {@link Postman} with {@link Postman#register(Recipient)}. A {@link * Postman} will put any received {@link Letter} into this {@link Mailbox} using {@link #accept(Object, * Postman)}. You can receive accepted letters with {@link #receive()}. * @param <Letter> type of the letters */ public class Mailbox<Letter> implements Recipient<Letter> { private final BlockingQueue<Letter> inbox = new LinkedBlockingQueue<>(); /** * Accepts {@link Letter}s and stores it in this {@link Mailbox} until they where received with {@link #receive()}. * * @param letter the {@link Letter} * @param postman the {@link Postman} that delivered the {@link Letter} - not used */ @Override public void accept(Letter letter, Postman postman) { inbox.add(letter); } /** * Returns a {@link Letter} that was put into this {@link Mailbox} with {@link #accept(Object, * Postman)}. A {@link Mailbox} works according to the FIFO principle: {@link #receive()} will return the {@link * Letter} that was accepted the longest time ago. Receiving a {@link Letter} from a {@link Mailbox} will remove * it. A {@link Letter} can only received once. If this {@link Mailbox} does not store a {@link Letter} when this * method is called, it will block until a {@link Letter} was accepted or the blocking {@link Thread} was * interrupted. * * @return the {@link Letter} * * @throws InterruptedException if a waiting {@link Thread} was interrupted */ public Letter receive() throws InterruptedException { return inbox.take(); } /** * Returns if this {@link Mailbox} has a {@link Letter} at the moment. This method returns {@code true} if and * only if {@link #receive()} does not block. But please do not rely on this guarantee in a multi-threaded * environment. Another thread may steal "your" {@link Letter}. * * @return if this {@link Mailbox} stores a {@link Letter} */ public boolean hasLetter() { return !inbox.isEmpty(); } }
package de.themoep.inventorygui; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.Nameable; import org.bukkit.Sound; import org.bukkit.block.BlockState; import org.bukkit.entity.Entity; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockDispenseEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.inventory.InventoryAction; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryDragEvent; import org.bukkit.event.inventory.InventoryMoveItemEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerSwapHandItemsEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.material.MaterialData; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * The main library class that lets you create and manage your GUIs */ public class InventoryGui implements Listener { private final static int[] ROW_WIDTHS = {3, 5, 9}; private final static InventoryType[] INVENTORY_TYPES = { InventoryType.DISPENSER, InventoryType.HOPPER, InventoryType.CHEST }; private final static Sound CLICK_SOUND; private final static Map<String, InventoryGui> GUI_MAP = new HashMap<>(); private final static Map<UUID, ArrayDeque<InventoryGui>> GUI_HISTORY = new HashMap<>(); private final static Map<String, Pattern> PATTERN_CACHE = new HashMap<>(); private final JavaPlugin plugin; private final List<UnregisterableListener> listeners = new ArrayList<>(); private final UnregisterableListener[] optionalListeners = new UnregisterableListener[]{ new ItemSwapGuiListener(this) }; private String title; private final char[] slots; private final Map<Character, GuiElement> elements = new HashMap<>(); private InventoryType inventoryType; private Map<UUID, Inventory> inventories = new LinkedHashMap<>(); private InventoryHolder owner = null; private boolean listenersRegistered = false; private Map<UUID, Integer> pageNumbers = new LinkedHashMap<>(); private Map<UUID, Integer> pageAmounts = new LinkedHashMap<>(); private GuiElement.Action outsideAction = click -> false; private CloseAction closeAction = close -> true; private boolean silent = false; static { // Sound names changed, make it compatible with both versions Sound clickSound = null; String[] clickSounds = {"UI_BUTTON_CLICK", "CLICK"}; for (String s : clickSounds) { try { clickSound = Sound.valueOf(s.toUpperCase()); break; } catch (IllegalArgumentException ignored) {} } if (clickSound == null) { for (Sound sound : Sound.values()) { if (sound.name().contains("CLICK")) { clickSound = sound; break; } } } CLICK_SOUND = clickSound; } public InventoryGui(JavaPlugin plugin, InventoryHolder owner, String title, String[] rows, GuiElement... elements) { this.plugin = plugin; this.owner = owner; this.title = title; listeners.add(new GuiListener(this)); for (UnregisterableListener listener : optionalListeners) { if (listener.isCompatible()) { listeners.add(listener); } } int width = ROW_WIDTHS[0]; for (String row : rows) { if (row.length() > width) { width = row.length(); } } for (int i = 0; i < ROW_WIDTHS.length && i < INVENTORY_TYPES.length; i++) { if (width < ROW_WIDTHS[i]) { width = ROW_WIDTHS[i]; } if (width == ROW_WIDTHS[i]) { inventoryType = INVENTORY_TYPES[i]; break; } } if (inventoryType == null) { throw new IllegalArgumentException("Could not match row setup to an inventory type!"); } StringBuilder slotsBuilder = new StringBuilder(); for (String row : rows) { if (row.length() < width) { double side = (width - row.length()) / 2; for (int i = 0; i < Math.floor(side); i++) { slotsBuilder.append(" "); } slotsBuilder.append(row); for (int i = 0; i < Math.ceil(side); i++) { slotsBuilder.append(" "); } } else if (row.length() == width) { slotsBuilder.append(row); } else { slotsBuilder.append(row.substring(0, width)); } } slots = slotsBuilder.toString().toCharArray(); addElements(elements); } public InventoryGui(JavaPlugin plugin, String title, String[] rows, GuiElement... elements) { this(plugin, null, title, rows, elements); } public InventoryGui(JavaPlugin plugin, InventoryHolder owner, String title, String[] rows, Collection<GuiElement> elements) { this(plugin, owner, title, rows); addElements(elements); } /** * Add an element to the gui * @param element The {@link GuiElement} to add */ public void addElement(GuiElement element) { elements.put(element.getSlotChar(), element); element.setGui(this); element.setSlots(getSlots(element.getSlotChar())); } private int[] getSlots(char slotChar) { ArrayList<Integer> slotList = new ArrayList<>(); for (int i = 0; i < slots.length; i++) { if (slots[i] == slotChar) { slotList.add(i); } } return slotList.stream().mapToInt(Integer::intValue).toArray(); } /** * Create and add a {@link StaticGuiElement} in one quick method. * @param slotChar The character to replace in the gui setup string * @param item The item that should be displayed * @param action The {@link de.themoep.inventorygui.GuiElement.Action} to run when the player clicks on this element * @param text The text to display on this element, placeholders are automatically * replaced, see {@link InventoryGui#replaceVars} for a list of the * placeholder variables. Empty text strings are also filter out, use * a single space if you want to add an empty line!<br> * If it's not set/empty the item's default name will be used */ public void addElement(char slotChar, ItemStack item, GuiElement.Action action, String... text) { addElement(new StaticGuiElement(slotChar, item, action, text)); } /** * Create and add a {@link StaticGuiElement} that has no action. * @param slotChar The character to replace in the gui setup string * @param item The item that should be displayed * @param text The text to display on this element, placeholders are automatically * replaced, see {@link InventoryGui#replaceVars} for a list of the * placeholder variables. Empty text strings are also filter out, use * a single space if you want to add an empty line!<br> * If it's not set/empty the item's default name will be used */ public void addElement(char slotChar, ItemStack item, String... text) { addElement(new StaticGuiElement(slotChar, item, null, text)); } /** * Create and add a {@link StaticGuiElement} in one quick method. * @param slotChar The character to replace in the gui setup string * @param materialData The {@link MaterialData} of the item of tihs element * @param action The {@link de.themoep.inventorygui.GuiElement.Action} to run when the player clicks on this element * @param text The text to display on this element, placeholders are automatically * replaced, see {@link InventoryGui#replaceVars} for a list of the * placeholder variables. Empty text strings are also filter out, use * a single space if you want to add an empty line!<br> * If it's not set/empty the item's default name will be used */ public void addElement(char slotChar, MaterialData materialData, GuiElement.Action action, String... text) { addElement(slotChar, materialData.toItemStack(1), action, text); } /** * Create and add a {@link StaticGuiElement} * @param slotChar The character to replace in the gui setup string * @param material The {@link Material} that the item should have * @param data The <code>byte</code> representation of the material data of this element * @param action The {@link GuiElement.Action} to run when the player clicks on this element * @param text The text to display on this element, placeholders are automatically * replaced, see {@link InventoryGui#replaceVars} for a list of the * placeholder variables. Empty text strings are also filter out, use * a single space if you want to add an empty line!<br> * If it's not set/empty the item's default name will be used */ public void addElement(char slotChar, Material material, byte data, GuiElement.Action action, String... text) { addElement(slotChar, new MaterialData(material, data), action, text); } /** * Create and add a {@link StaticGuiElement} * @param slotChar The character to replace in the gui setup string * @param material The {@link Material} that the item should have * @param action The {@link GuiElement.Action} to run when the player clicks on this element * @param text The text to display on this element, placeholders are automatically * replaced, see {@link InventoryGui#replaceVars} for a list of the * placeholder variables. Empty text strings are also filter out, use * a single space if you want to add an empty line!<br> * If it's not set/empty the item's default name will be used */ public void addElement(char slotChar, Material material, GuiElement.Action action, String... text) { addElement(slotChar, material, (byte) 0, action, text); } /** * Add multiple elements to the gui * @param elements The {@link GuiElement}s to add */ public void addElements(GuiElement... elements) { for (GuiElement element : elements) { addElement(element); } } /** * Add multiple elements to the gui * @param elements The {@link GuiElement}s to add */ public void addElements(Collection<GuiElement> elements) { for (GuiElement element : elements) { addElement(element); } } /** * Remove a specific element from this gui. * @param element The element to remove * @return Whether or not the gui contained this element and if it was removed */ public boolean removeElement(GuiElement element) { return elements.remove(element.getSlotChar(), element); } /** * Remove the element that is currently assigned to a specific slot char * @param slotChar The char of the slot * @return The element which was in that slot or <code>null</code> if there was none */ public GuiElement removeElement(char slotChar) { return elements.remove(slotChar); } /** * Set the filler element for empty slots * @param item The item for the filler element */ public void setFiller(ItemStack item) { addElement(new StaticGuiElement(' ', item, " ")); } /** * Get the filler element * @return The filler element for empty slots */ public GuiElement getFiller() { return elements.get(' '); } /** * Get the number of the page that this gui is on. zero indexed. Only affects group elements. * @return The page number * @deprecated Use {@link #getPageNumber(HumanEntity)} */ @Deprecated public int getPageNumber() { return getPageNumber(null); } /** * Get the number of the page that this gui is on. zero indexed. Only affects group elements. * @param player The Player to query the page number for * @return The page number */ public int getPageNumber(HumanEntity player) { return player != null ? pageNumbers.getOrDefault(player.getUniqueId(), 0) : pageNumbers.isEmpty() ? 0 : pageNumbers.values().iterator().next(); } /** * Set the number of the page that this gui is on for all players. zero indexed. Only affects group elements. * @param pageNumber The page number to set */ public void setPageNumber(int pageNumber) { for (UUID playerId : inventories.keySet()) { Player player = plugin.getServer().getPlayer(playerId); if (player != null) { setPageNumber(player, pageNumber); } } } /** * Set the number of the page that this gui is on for a player. zero indexed. Only affects group elements. * @param player The player to set the page number for * @param pageNumber The page number to set */ public void setPageNumber(HumanEntity player, int pageNumber) { pageNumbers.put(player.getUniqueId(), pageNumber); draw(player); } /** * Get the amount of pages that this GUI has * @return The amount of pages * @deprecated Use {@link #getPageAmount(HumanEntity)} */ @Deprecated public int getPageAmount() { return getPageAmount(null); } /** * Get the amount of pages that this GUI has for a certain player * @param player The Player to query the page amount for * @return The amount of pages */ public int getPageAmount(HumanEntity player) { return player != null ? pageAmounts.getOrDefault(player.getUniqueId(), 1) : pageAmounts.isEmpty() ? 1 : pageAmounts.values().iterator().next(); } /** * Set the amount of pages that this GUI has for a certain player * @param player The Player to query the page amount for * @param pageAmount The page amount */ private void setPageAmount(HumanEntity player, int pageAmount) { pageAmounts.put(player.getUniqueId(), pageAmount); } private void calculatePageAmount(HumanEntity player) { for (GuiElement element : elements.values()) { int pageAmount = getPageAmount(player); int amount = calculatePageAmount(player, element); if (amount > 0 && (pageAmount - 1) * element.getSlots().length < amount) { setPageAmount(player, (int) Math.ceil((double) amount / element.getSlots().length)); } } } private int calculatePageAmount(HumanEntity player, GuiElement element) { if (element instanceof GuiElementGroup) { return ((GuiElementGroup) element).size(); } else if (element instanceof GuiStorageElement) { return ((GuiStorageElement) element).getStorage().getSize(); } else if (element instanceof DynamicGuiElement) { return calculatePageAmount(player, ((DynamicGuiElement) element).queryElement(player)); } return 0; } private void registerListeners() { if (listenersRegistered) { return; } for (UnregisterableListener listener : listeners) { plugin.getServer().getPluginManager().registerEvents(listener, plugin); } listenersRegistered = true; } private void unregisterListeners() { for (UnregisterableListener listener : listeners) { listener.unregister(); } listenersRegistered = false; } /** * Show this GUI to a player * @param player The Player to show the GUI to */ public void show(HumanEntity player) { show(player, true); } /** * Show this GUI to a player * @param player The Player to show the GUI to * @param checkOpen Whether or not it should check if this gui is already open */ public void show(HumanEntity player, boolean checkOpen) { draw(player); if (!checkOpen || !this.equals(getOpen(player))) { if (player.getOpenInventory().getType() != InventoryType.CRAFTING) { // If the player already has a gui open then we assume that the call was from that gui. // In order to not close it in a InventoryClickEvent listener (which will lead to errors) // we delay the opening for one tick to run after it finished processing the event plugin.getServer().getScheduler().runTask(plugin, () -> { Inventory inventory = getInventory(player); if (inventory != null) { addHistory(player, this); player.openInventory(inventory); } }); } else { Inventory inventory = getInventory(player); if (inventory != null) { clearHistory(player); addHistory(player, this); player.openInventory(inventory); } } } } /** * Build the gui */ public void build() { build(owner); } /** * Set the gui's owner and build it * @param owner The {@link InventoryHolder} that owns the gui */ public void build(InventoryHolder owner) { setOwner(owner); registerListeners(); } /** * Draw the elements in the inventory. This can be used to manually refresh the gui. */ public void draw() { for (UUID playerId : inventories.keySet()) { Player player = plugin.getServer().getPlayer(playerId); if (player != null) { draw(player); } } } /** * Draw the elements in the inventory. This can be used to manually refresh the gui. * @param who For who to draw the GUI */ public void draw(HumanEntity who) { Inventory inventory = getInventory(who); calculatePageAmount(who); if (inventory == null) { build(); if (slots.length != inventoryType.getDefaultSize()) { inventory = plugin.getServer().createInventory(new Holder(this), slots.length, replaceVars(who, title)); } else { inventory = plugin.getServer().createInventory(new Holder(this), inventoryType, replaceVars(who, title)); } inventories.put(who != null ? who.getUniqueId() : null, inventory); } else { inventory.clear(); } for (int i = 0; i < inventory.getSize(); i++) { GuiElement element = getElement(i); if (element == null) { element = getFiller(); } if (element != null) { inventory.setItem(i, element.getItem(who, i)); } } } /** * Closes the GUI for everyone viewing it */ public void close() { close(true); } /** * Close the GUI for everyone viewing it * @param clearHistory Whether or not to close the GUI completely (by clearing the history) */ public void close(boolean clearHistory) { for (Inventory inventory : inventories.values()) { for (HumanEntity viewer : new ArrayList<>(inventory.getViewers())) { if (clearHistory) { clearHistory(viewer); } viewer.closeInventory(); } } } /** * Destroy this GUI. This unregisters all listeners and removes it from the GUI_MAP */ public void destroy() { destroy(true); } private void destroy(boolean closeInventories) { if (closeInventories) { close(); } for (Inventory inventory : inventories.values()) { inventory.clear(); } inventories.clear(); pageNumbers.clear(); pageAmounts.clear(); unregisterListeners(); removeFromMap(); } /** * Add a new history entry to the end of the history * @param player The player to add the history entry for * @param gui The GUI to add to the history */ public static void addHistory(HumanEntity player, InventoryGui gui) { GUI_HISTORY.putIfAbsent(player.getUniqueId(), new ArrayDeque<>()); Deque<InventoryGui> history = getHistory(player); if (history.peekLast() != gui) { history.add(gui); } } /** * Get the history of a player * @param player The player to get the history for * @return The history as a deque of InventoryGuis; * returns an empty one and not <code>null</code>! */ public static Deque<InventoryGui> getHistory(HumanEntity player) { return GUI_HISTORY.getOrDefault(player.getUniqueId(), new ArrayDeque<>()); } /** * Go back one entry in the history * @param player The player to show the previous gui to * @return <code>true</code> if there was a gui to show; <code>false</code> if not */ public static boolean goBack(HumanEntity player) { Deque<InventoryGui> history = getHistory(player); history.pollLast(); if (history.isEmpty()) { return false; } InventoryGui previous = history.peekLast(); if (previous != null) { previous.show(player, false); } return true; } /** * Clear the history of a player * @param player The player to clear the history for * @return The history */ public static Deque<InventoryGui> clearHistory(HumanEntity player) { if (GUI_HISTORY.containsKey(player.getUniqueId())) { return GUI_HISTORY.remove(player.getUniqueId()); } return new ArrayDeque<>(); } /** * Get element in a certain slot * @param slot The slot to get the element from * @return The GuiElement or <code>null</code> if the slot is empty/there wasn't one */ public GuiElement getElement(int slot) { return slot < 0 || slot >= slots.length ? null : elements.get(slots[slot]); } /** * Get an element by its character * @param c The character to get the element by * @return The GuiElement or <code>null</code> if there is no element for that character */ public GuiElement getElement(char c) { return elements.get(c); } /** * Get all elements of this gui. This collection is immutable, use the addElement and removeElement methods * to modify the elements in this gui. * @return An immutable collection of all elements in this group */ public Collection<GuiElement> getElements() { return Collections.unmodifiableCollection(elements.values()); } /** * Set the owner of this GUI. Will remove the previous assignment. * @param owner The owner of the GUI */ public void setOwner(InventoryHolder owner) { removeFromMap(); this.owner = owner; if (owner instanceof Entity) { GUI_MAP.put(((Entity) owner).getUniqueId().toString(), this); } else if (owner instanceof BlockState) { GUI_MAP.put(((BlockState) owner).getLocation().toString(), this); } } /** * Get the owner of this GUI. Will be null if th GUI doesn't have one * @return The InventoryHolder of this GUI */ public InventoryHolder getOwner() { return owner; } /** * Check whether or not the Owner of this GUI is real or fake * @return <code>true</code> if the owner is a real world InventoryHolder; <code>false</code> if it is null */ public boolean hasRealOwner() { return owner != null; } /** * Get the Action that is run when clicked outside of the inventory * @return The Action for when the player clicks outside the inventory; can be null */ public GuiElement.Action getOutsideAction() { return outsideAction; } /** * Set the Action that is run when clicked outside of the inventory * @param outsideAction The Action for when the player clicks outside the inventory; can be null */ public void setOutsideAction(GuiElement.Action outsideAction) { this.outsideAction = outsideAction; } /** * Get the action that is run when this GUI is closed * @return The action for when the player closes this inventory; can be null */ public CloseAction getCloseAction() { return closeAction; } /** * Set the action that is run when this GUI is closed; it should return true if the GUI should go back * @param closeAction The action for when the player closes this inventory; can be null */ public void setCloseAction(CloseAction closeAction) { this.closeAction = closeAction; } /** * Get whether or not this GUI should make a sound when interacting with elements that make sound * @return Whether or not to make a sound when interacted with */ public boolean isSilent() { return silent; } /** * Set whether or not this GUI should make a sound when interacting with elements that make sound * @param silent Whether or not to make a sound when interacted with */ public void setSilent(boolean silent) { this.silent = silent; } private void removeFromMap() { if (owner instanceof Entity) { GUI_MAP.remove(((Entity) owner).getUniqueId().toString(), this); } else if (owner instanceof BlockState) { GUI_MAP.remove(((BlockState) owner).getLocation().toString(), this); } } /** * Get the GUI registered to an InventoryHolder * @param holder The InventoryHolder to get the GUI for * @return The InventoryGui registered to it or <code>null</code> if none was registered to it */ public static InventoryGui get(InventoryHolder holder) { if (holder instanceof Entity) { return GUI_MAP.get(((Entity) holder).getUniqueId().toString()); } else if (holder instanceof BlockState) { return GUI_MAP.get(((BlockState) holder).getLocation().toString()); } return null; } /** * Get the GUI that a player has currently open * @param player The Player to get the GUI for * @return The InventoryGui that the player has open */ public static InventoryGui getOpen(HumanEntity player) { return getHistory(player).peekLast(); } /** * Get the title of the gui * @return The title of the gui */ public String getTitle() { return title; } /** * Set the title of the gui * @param title The {@link String} that should be the title of the gui */ public void setTitle(String title) { this.title = title; } /** * Play a click sound e.g. when an element acts as a button */ public void playClickSound() { if (isSilent()) return; for (Inventory inventory : inventories.values()) { for (HumanEntity humanEntity : inventory.getViewers()) { if (humanEntity instanceof Player) { ((Player) humanEntity).playSound(humanEntity.getEyeLocation(), CLICK_SOUND, 1, 1); } } } } /** * Get the inventory. Package scope as it should only be used by InventoryGui.Holder * @return The GUI's generated inventory */ Inventory getInventory() { return getInventory(null); } /** * Get the inventory of a certain player * @param who The player, if null it will try to return the inventory created first or null if none was created * @return The GUI's generated inventory, null if none was found */ private Inventory getInventory(HumanEntity who) { return who != null ? inventories.get(who.getUniqueId()) : (inventories.isEmpty() ? null : inventories.values().iterator().next()); } private interface UnregisterableListener extends Listener { void unregister(); default boolean isCompatible() { try { getClass().getMethods(); getClass().getDeclaredMethods(); return true; } catch (NoClassDefFoundError e) { return false; } } } /** * All the listeners that InventoryGui needs to work */ public class GuiListener implements UnregisterableListener { private final InventoryGui gui; private GuiListener(InventoryGui gui) { this.gui = gui; } @EventHandler private void onInventoryClick(InventoryClickEvent event) { if (event.getInventory().equals(getInventory(event.getWhoClicked()))) { int slot = -1; if (event.getRawSlot() < event.getView().getTopInventory().getSize()) { slot = event.getRawSlot(); } else if (event.getAction() == InventoryAction.MOVE_TO_OTHER_INVENTORY) { slot = event.getInventory().firstEmpty(); } GuiElement.Action action = null; GuiElement element = null; if (slot >= 0) { element = getElement(slot); if (element != null) { action = element.getAction(event.getWhoClicked()); } } else if (slot == -999) { action = outsideAction; } else { // Click was neither for the top inventory or outside // E.g. click is in the bottom inventory if (event.getAction() == InventoryAction.COLLECT_TO_CURSOR) { simulateCollectToCursor(new GuiElement.Click(gui, slot, null, event)); } return; } try { if (action == null || action.onClick(new GuiElement.Click(gui, slot, element, event))) { event.setCancelled(true); if (event.getWhoClicked() instanceof Player) { ((Player) event.getWhoClicked()).updateInventory(); } } if (action != null) { // Let's assume something changed and re-draw all currently shown inventories for (UUID playerId : inventories.keySet()) { if (!event.getWhoClicked().getUniqueId().equals(playerId)) { Player player = plugin.getServer().getPlayer(playerId); if (player != null) { draw(player); } } } } } catch (Throwable t) { event.setCancelled(true); if (event.getWhoClicked() instanceof Player) { ((Player) event.getWhoClicked()).updateInventory(); } plugin.getLogger().log(Level.SEVERE, "Exception while trying to run action for click on " + (element != null ? element.getClass().getSimpleName() : "empty element") + " in slot " + event.getRawSlot() + " of " + gui.getTitle() + " GUI!"); t.printStackTrace(); } } else if (hasRealOwner() && owner.equals(event.getInventory().getHolder())) { // Click into inventory by same owner but not the inventory of the GUI // Assume that the underlying inventory changed and redraw the GUI plugin.getServer().getScheduler().runTask(plugin, (Runnable) gui::draw); } } @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onInventoryDrag(InventoryDragEvent event) { Inventory inventory = getInventory(event.getWhoClicked()); if (event.getInventory().equals(inventory)) { int rest = 0; Map<Integer, ItemStack> resetSlots = new HashMap<>(); for (Map.Entry<Integer, ItemStack> items : event.getNewItems().entrySet()) { if (items.getKey() < inventory.getSize()) { GuiElement element = getElement(items.getKey()); if (!(element instanceof GuiStorageElement) || !((GuiStorageElement) element).setStorageItem(items.getKey(), items.getValue())) { ItemStack slotItem = event.getInventory().getItem(items.getKey()); if (!items.getValue().isSimilar(slotItem)) { rest += items.getValue().getAmount(); } else if (slotItem != null) { rest += items.getValue().getAmount() - slotItem.getAmount(); } //items.getValue().setAmount(0); // can't change resulting items :/ resetSlots.put(items.getKey(), event.getInventory().getItem(items.getKey())); // reset them manually } } } plugin.getServer().getScheduler().runTask(plugin, () -> { for (Map.Entry<Integer, ItemStack> items : resetSlots.entrySet()) { event.getView().getTopInventory().setItem(items.getKey(), items.getValue()); } }); if (rest > 0) { int cursorAmount = event.getCursor() != null ? event.getCursor().getAmount() : 0; if (!event.getOldCursor().isSimilar(event.getCursor())) { event.setCursor(event.getOldCursor()); cursorAmount = 0; } int newCursorAmount = cursorAmount + rest; if (newCursorAmount <= event.getCursor().getMaxStackSize()) { event.getCursor().setAmount(newCursorAmount); } else { event.getCursor().setAmount(event.getCursor().getMaxStackSize()); ItemStack add = event.getCursor().clone(); int addAmount = newCursorAmount - event.getCursor().getMaxStackSize(); if (addAmount > 0) { add.setAmount(addAmount); for (ItemStack drop : event.getWhoClicked().getInventory().addItem(add).values()) { event.getWhoClicked().getLocation().getWorld().dropItem(event.getWhoClicked().getLocation(), drop); } } } } } } @EventHandler(priority = EventPriority.MONITOR) public void onInventoryClose(InventoryCloseEvent event) { Inventory inventory = getInventory(event.getPlayer()); if (event.getInventory().equals(inventory)) { // go back. that checks if the player is in gui and has history if (gui.equals(getOpen(event.getPlayer()))) { if (closeAction == null || closeAction.onClose(new Close(event.getPlayer(), gui, event))) { goBack(event.getPlayer()); } else { clearHistory(event.getPlayer()); } } if (inventories.size() <= 1) { destroy(false); } else { inventory.clear(); for (HumanEntity viewer : inventory.getViewers()) { if (viewer != event.getPlayer()) { viewer.closeInventory(); } } inventories.remove(event.getPlayer().getUniqueId()); pageAmounts.remove(event.getPlayer().getUniqueId()); pageNumbers.remove(event.getPlayer().getUniqueId()); } } } @EventHandler(priority = EventPriority.MONITOR) public void onInventoryMoveItem(InventoryMoveItemEvent event) { if (hasRealOwner() && (owner.equals(event.getDestination().getHolder()) || owner.equals(event.getSource().getHolder()))) { plugin.getServer().getScheduler().runTask(plugin, (Runnable) gui::draw); } } @EventHandler(priority = EventPriority.MONITOR) public void onDispense(BlockDispenseEvent event) { if (hasRealOwner() && owner.equals(event.getBlock().getState())) { plugin.getServer().getScheduler().runTask(plugin, (Runnable) gui::draw); } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockBreak(BlockBreakEvent event) { if (hasRealOwner() && owner.equals(event.getBlock().getState())) { destroy(); } } @EventHandler(priority = EventPriority.MONITOR) public void onEntityDeath(EntityDeathEvent event) { if (hasRealOwner() && owner.equals(event.getEntity())) { destroy(); } } public void unregister() { InventoryClickEvent.getHandlerList().unregister(this); InventoryDragEvent.getHandlerList().unregister(this); InventoryCloseEvent.getHandlerList().unregister(this); InventoryMoveItemEvent.getHandlerList().unregister(this); BlockDispenseEvent.getHandlerList().unregister(this); BlockBreakEvent.getHandlerList().unregister(this); EntityDeathEvent.getHandlerList().unregister(this); } } /** * Event isn't available on older version so just use a separate listener... */ public class ItemSwapGuiListener implements UnregisterableListener { private final InventoryGui gui; private ItemSwapGuiListener(InventoryGui gui) { this.gui = gui; } @EventHandler(priority = EventPriority.HIGHEST) public void onInventoryMoveItem(PlayerSwapHandItemsEvent event) { Inventory inventory = getInventory(event.getPlayer()); if (event.getPlayer().getOpenInventory().getTopInventory().equals(inventory)) { event.setCancelled(true); } } public void unregister() { PlayerSwapHandItemsEvent.getHandlerList().unregister(this); } } /** * Fake InventoryHolder for the GUIs */ public static class Holder implements InventoryHolder { private InventoryGui gui; public Holder(InventoryGui gui) { this.gui = gui; } @Override public Inventory getInventory() { return gui.getInventory(); } public InventoryGui getGui() { return gui; } } public static interface CloseAction { /** * Executed when a player closes a GUI inventory * @param close The close object holding information about this close * @return Whether or not the close should go back or not */ boolean onClose(Close close); } public static class Close { private final HumanEntity player; private final InventoryGui gui; private final InventoryCloseEvent event; public Close(HumanEntity player, InventoryGui gui, InventoryCloseEvent event) { this.player = player; this.gui = gui; this.event = event; } public HumanEntity getPlayer() { return player; } public InventoryGui getGui() { return gui; } public InventoryCloseEvent getEvent() { return event; } } /** * Set the text of an item using the display name and the lore. * Also replaces any placeholders in the text and filters out empty lines. * Use a single space to create an emtpy line. * @param item The {@link ItemStack} to set the text for * @param text The text lines to set * @deprecated Use {@link #setItemText(HumanEntity, ItemStack, String...)} */ @Deprecated public void setItemText(ItemStack item, String... text) { setItemText(null, item, text); } /** * Set the text of an item using the display name and the lore. * Also replaces any placeholders in the text and filters out empty lines. * Use a single space to create an emtpy line. * @param player The player viewing the GUI * @param item The {@link ItemStack} to set the text for * @param text The text lines to set */ public void setItemText(HumanEntity player, ItemStack item, String... text) { if (item != null && text != null && text.length > 0) { ItemMeta meta = item.getItemMeta(); if (meta != null) { String combined = replaceVars(player, Arrays.stream(text) .filter(Objects::nonNull) .filter(s -> !s.isEmpty()) .collect(Collectors.joining("\n"))); String[] lines = combined.split("\n"); meta.setDisplayName(lines[0]); if (lines.length > 1) { meta.setLore(Arrays.asList(Arrays.copyOfRange(lines, 1, lines.length))); } else { meta.setLore(null); } item.setItemMeta(meta); } } } /** * Replace some placeholders in the with values regarding the gui's state. Replaced color codes.<br> * The placeholders are:<br> * <code>%plugin%</code> - The name of the plugin that this gui is from.<br> * <code>%owner%</code> - The name of the owner of this gui. Will be an empty string when the owner is null.<br> * <code>%title%</code> - The title of this GUI.<br> * <code>%page%</code> - The current page that this gui is on.<br> * <code>%nextpage%</code> - The next page. "none" if there is no next page.<br> * <code>%prevpage%</code> - The previous page. "none" if there is no previous page.<br> * <code>%pages%</code> - The amount of pages that this gui has. * @param text The text to replace the placeholders in * @param replacements Additional repplacements. i = placeholder, i+1 = replacements * @return The text with all placeholders replaced * @deprecated Use {@link #replaceVars(HumanEntity, String, String...)} */ @Deprecated public String replaceVars(String text, String... replacements) { return replaceVars(null, text, replacements); } /** * Replace some placeholders in the with values regarding the gui's state. Replaced color codes.<br> * The placeholders are:<br> * <code>%plugin%</code> - The name of the plugin that this gui is from.<br> * <code>%owner%</code> - The name of the owner of this gui. Will be an empty string when the owner is null.<br> * <code>%title%</code> - The title of this GUI.<br> * <code>%page%</code> - The current page that this gui is on.<br> * <code>%nextpage%</code> - The next page. "none" if there is no next page.<br> * <code>%prevpage%</code> - The previous page. "none" if there is no previous page.<br> * <code>%pages%</code> - The amount of pages that this gui has. * @param player The player viewing the GUI * @param text The text to replace the placeholders in * @param replacements Additional repplacements. i = placeholder, i+1 = replacements * @return The text with all placeholders replaced */ public String replaceVars(HumanEntity player, String text, String... replacements) { text = replace(replace(text, replacements), "plugin", plugin.getName(), "owner", owner instanceof Nameable ? ((Nameable) owner).getCustomName() : "", "title", title, "page", String.valueOf(getPageNumber(player) + 1), "nextpage", getPageNumber(player) + 1 < getPageAmount(player) ? String.valueOf(getPageNumber(player) + 2) : "none", "prevpage", getPageNumber(player) > 0 ? String.valueOf(getPageNumber(player)) : "none", "pages", String.valueOf(getPageAmount(player)) ); return ChatColor.translateAlternateColorCodes('&', text); } /** * Replace placeholders in a string * @param string The string to replace in * @param replacements What to replace the placeholders with. The n-th index is the placeholder, the n+1-th the value. * @return The string with all placeholders replaced (using the configured placeholder prefix and suffix) */ private String replace(String string, String... replacements) { for (int i = 0; i + 1 < replacements.length; i+=2) { if (replacements[i] == null) { continue; } String placeholder = "%" + replacements[i] + "%"; Pattern pattern = PATTERN_CACHE.get(placeholder); if (pattern == null) { PATTERN_CACHE.put(placeholder, pattern = Pattern.compile(placeholder, Pattern.LITERAL)); } string = pattern.matcher(string).replaceAll(Matcher.quoteReplacement(replacements[i+1] != null ? replacements[i+1] : "null")); } return string; } /** * Simulate the collecting to the cursor while respecting elements that can't be modified * @param click The click that startet it all */ void simulateCollectToCursor(GuiElement.Click click) { ItemStack newCursor = click.getEvent().getCursor().clone(); boolean itemInGui = false; for (int i = 0; i < click.getEvent().getView().getTopInventory().getSize(); i++) { if (i != click.getEvent().getRawSlot()) { ItemStack viewItem = click.getEvent().getView().getTopInventory().getItem(i); if (newCursor.isSimilar(viewItem)) { itemInGui = true; } GuiElement element = getElement(i); if (element instanceof GuiStorageElement) { GuiStorageElement storageElement = (GuiStorageElement) element; ItemStack otherStorageItem = storageElement.getStorageItem(i); if (addToStack(newCursor, otherStorageItem)) { if (otherStorageItem.getAmount() == 0) { otherStorageItem = null; } storageElement.setStorageItem(i, otherStorageItem); if (newCursor.getAmount() == newCursor.getMaxStackSize()) { break; } } } } } if (itemInGui) { click.getEvent().setCurrentItem(null); click.getEvent().setCancelled(true); if (click.getEvent().getWhoClicked() instanceof Player) { ((Player) click.getEvent().getWhoClicked()).updateInventory(); } if (click.getElement() instanceof GuiStorageElement) { ((GuiStorageElement) click.getElement()).setStorageItem(click.getSlot(), null); } if (newCursor.getAmount() < newCursor.getMaxStackSize()) { Inventory bottomInventory = click.getEvent().getView().getBottomInventory(); for (ItemStack bottomIem : bottomInventory) { if (addToStack(newCursor, bottomIem)) { if (newCursor.getAmount() == newCursor.getMaxStackSize()) { break; } } } } click.getEvent().setCursor(newCursor); draw(); } } /** * Add items to a stack up to the max stack size * @param item The base item * @param add The item stack to add * @return <code>true</code> if the stack is finished; <code>false</code> if these stacks can't be merged */ private static boolean addToStack(ItemStack item, ItemStack add) { if (item.isSimilar(add)) { int newAmount = item.getAmount() + add.getAmount(); if (newAmount >= item.getMaxStackSize()) { item.setAmount(item.getMaxStackSize()); add.setAmount(newAmount - item.getAmount()); } else { item.setAmount(newAmount); add.setAmount(0); } return true; } return false; } }
package edu.cmu.lti.oaqa.gerp.core; import java.util.Map; import org.apache.uima.UimaContext; import org.apache.uima.analysis_engine.AnalysisEngine; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.analysis_engine.JCasIterator; import org.apache.uima.cas.AbstractCas; import org.apache.uima.cas.CAS; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.cas.TOP; import org.apache.uima.jcas.tcas.Annotation; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.util.CasCopier; import org.oaqa.model.gerp.GerpMeta; import org.uimafit.component.JCasMultiplier_ImplBase; import org.uimafit.descriptor.OperationalProperties; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; import edu.cmu.lti.oaqa.core.data.TopWrapper; import edu.cmu.lti.oaqa.core.data.WrapperHelper; import edu.cmu.lti.oaqa.core.data.WrapperIndexer; import edu.cmu.lti.oaqa.ecd.BaseExperimentBuilder; import edu.cmu.lti.oaqa.gerp.data.EvidenceWrapper; import edu.cmu.lti.oaqa.gerp.data.GerpMetaWrapper; import edu.cmu.lti.oaqa.gerp.data.Gerpable; import edu.cmu.lti.oaqa.gerp.data.GerpableList; import edu.cmu.lti.oaqa.gerp.data.PruningDecisionWrapper; import edu.cmu.lti.oaqa.gerp.data.RankWrapper; /** * Extended from {@link edu.cmu.lti.oaqa.ecd.phase.BasePhase}, which instead of using * <code>options</code> for integrating components, generators, evidencers, rankers and pruners * inherited from {@link AbstractGenerator}, {@link AbstractEvidencer}, {@link AbstractRanker}, or * {@link AbstractPruner} should be listed in separated fields in the descriptor. Moreover, the type * of the {@link TOP} or {@link Annotation} should be specified for the parameter <code>type</code>. * Other options, e.g. <code>name</code>, <code>option-timeout</code>, * <code>lazy-load-options</code> are preserved. * <p> * Each combination of TOPs generated by previous {@link GerpPhase}s ( * {@link JCasMultiplier_ImplBase} implementations), claimed by * {@link AbstractGenerator#getRequiredInputTypes()} as input arguments, will be stored in different * {@link CAS}es and processed by the {@link #process(JCas)} separately, and further passed along * the pipeline within the analysis engine for evidencing, ranking and pruning. The number of * {@link CAS}es output from the {@link #next()} method of each GerpPhase instance is equal to the * number of <code>generator</code>s defined in the descriptor. * * @author Zi Yang <ziy@cs.cmu.edu> * */ @OperationalProperties(outputsNewCases = true) public class GerpPhase<T extends TOP, W extends Gerpable & TopWrapper<T>> extends JCasMultiplier_ImplBase { /* * Field name constants copied from BasePhase */ public static final String QA_INTERNAL_PHASEID = "__.qa.internal.phaseid.__"; public static final String TIMEOUT_KEY = "option-timeout"; public static final String LAZY_LOAD_KEY = "lazy-load-options"; private Map<String, Object> confs; private String gerpableClassName; private int gerpableType; private GerpMetaWrapper gerpMeta; private AnalysisEngine generatorSubPhase, evidencerSubPhase, rankerSubPhase, prunerSubPhase; private JCas mergedJcas; private WrapperIndexer mergedCasIndexer; private GerpableList<T, W> gerpables; private int gerpableIdx; @Override public void initialize(UimaContext context) throws ResourceInitializationException { super.initialize(context); confs = GerpPhaseUtils.getConfigurationTuples(context, "persistence-provider", "name", QA_INTERNAL_PHASEID, TIMEOUT_KEY, LAZY_LOAD_KEY, BaseExperimentBuilder.EXPERIMENT_UUID_PROPERTY, BaseExperimentBuilder.STAGE_ID_PROPERTY, "generators", "evidencers", "rankers", "pruners"); try { gerpableClassName = (String) context.getConfigParameterValue("type"); Class<? extends TOP> topClass = Class.forName(gerpableClassName).asSubclass(TOP.class); gerpableType = (Integer) topClass.getDeclaredField("type").get(null); } catch (Exception e) { throw new ResourceInitializationException(e); } gerpMeta = new GerpMetaWrapper(gerpableClassName, GerpPhaseUtils.toClassNames((String) confs .get("generators")), GerpPhaseUtils.toClassNames((String) confs.get("evidencers")), GerpPhaseUtils.toClassNames((String) confs.get("rankers")), GerpPhaseUtils.toClassNames((String) confs.get("pruners"))); } @Override public void process(JCas aJCas) throws AnalysisEngineProcessException { // initialize mergedCasIndexer = new WrapperIndexer(); gerpables = new GerpableList<T, W>(); gerpableIdx = 0; Map<String, Object> subPhaseConfs = GerpPhaseUtils .copyTuples(confs, "persistence-provider", QA_INTERNAL_PHASEID, TIMEOUT_KEY, LAZY_LOAD_KEY, BaseExperimentBuilder.EXPERIMENT_UUID_PROPERTY, BaseExperimentBuilder.STAGE_ID_PROPERTY); mergedJcas = aJCas; WrapperHelper.unwrap(new WrapperIndexer(), gerpMeta, mergedJcas).addToIndexes(mergedJcas); JCasIterator jcasIter; // create generation subphase subPhaseConfs.put("name", confs.get("name") + "|GENERATION"); subPhaseConfs.put("options", confs.get("generators")); generatorSubPhase = GerpPhaseUtils.createBasePhase(subPhaseConfs); // execute generation subphase jcasIter = generatorSubPhase.processAndOutputNewCASes(mergedJcas); // merge generated gerpables mergeGerpables(jcasIter); // create evidencing subphase subPhaseConfs.put("name", confs.get("name") + "|EVIDENCING"); subPhaseConfs.put("options", confs.get("evidencers")); evidencerSubPhase = GerpPhaseUtils.createBasePhase(subPhaseConfs); // execute evidencing subphase jcasIter = evidencerSubPhase.processAndOutputNewCASes(mergedJcas); // merge evidences mergeEvidences(jcasIter); // create ranking subphase subPhaseConfs.put("name", confs.get("name") + "|RANKING"); subPhaseConfs.put("options", confs.get("rankers")); rankerSubPhase = GerpPhaseUtils.createBasePhase(subPhaseConfs); // execute ranking subphase jcasIter = rankerSubPhase.processAndOutputNewCASes(mergedJcas); // merge ranks mergeRanks(jcasIter); // create pruning subphase subPhaseConfs.put("name", confs.get("name") + "|PRUNING"); subPhaseConfs.put("options", confs.get("pruners")); prunerSubPhase = GerpPhaseUtils.createBasePhase(subPhaseConfs); // execute pruning subphase jcasIter = prunerSubPhase.processAndOutputNewCASes(mergedJcas); // merge pruning decisions mergePruningDecisions(jcasIter); // post processing ultimatePrune(); GerpPhaseUtils.removeAllTopsFromIndexesAndIndexer(mergedJcas, mergedCasIndexer, GerpMeta.type); } private void mergeGerpables(JCasIterator jcasIter) throws AnalysisEngineProcessException { while (jcasIter.hasNext()) { JCas jcas = jcasIter.next(); TOP top = Iterables.getOnlyElement(GerpPhaseUtils.getAllTops(jcas, gerpableType)); @SuppressWarnings("unchecked") W gerpable = (W) WrapperHelper.wrap(new WrapperIndexer(), top); gerpable.setGerpMeta(gerpMeta); gerpables.add(gerpable); jcas.release(); } for (W gerpable : gerpables.getGerpables()) { T top = WrapperHelper.unwrap(mergedCasIndexer, gerpable, mergedJcas); top.addToIndexes(mergedJcas); } } private void mergeEvidences(JCasIterator jcasIter) throws AnalysisEngineProcessException { Map<W, EvidenceWrapper<?, ?>> gerpable2evidences = Maps.newHashMap(); while (jcasIter.hasNext()) { JCas jcas = jcasIter.next(); for (TOP top : GerpPhaseUtils.getAllTops(jcas, gerpableType)) { @SuppressWarnings("unchecked") W gerpable = (W) WrapperHelper.wrap(new WrapperIndexer(), top); gerpable2evidences.put(gerpable, gerpable.getEvidences().get(0)); } gerpables.addAllEvidences(gerpable2evidences); jcas.release(); } GerpPhaseUtils.removeAllTopsFromIndexesAndIndexer(mergedJcas, mergedCasIndexer, gerpableType); for (W gerpable : gerpables.getGerpables()) { T top = WrapperHelper.unwrap(mergedCasIndexer, gerpable, mergedJcas); top.addToIndexes(mergedJcas); } } private void mergeRanks(JCasIterator jcasIter) throws AnalysisEngineProcessException { Map<W, RankWrapper> gerpable2ranks = Maps.newHashMap(); while (jcasIter.hasNext()) { JCas jcas = jcasIter.next(); for (TOP top : GerpPhaseUtils.getAllTops(jcas, gerpableType)) { @SuppressWarnings("unchecked") W gerpable = (W) WrapperHelper.wrap(new WrapperIndexer(), top); gerpable2ranks.put(gerpable, gerpable.getRanks().get(0)); } gerpables.addAllRanks(gerpable2ranks); jcas.release(); } GerpPhaseUtils.removeAllTopsFromIndexesAndIndexer(mergedJcas, mergedCasIndexer, gerpableType); for (W gerpable : gerpables.getGerpables()) { T top = WrapperHelper.unwrap(mergedCasIndexer, gerpable, mergedJcas); top.addToIndexes(mergedJcas); } } private void mergePruningDecisions(JCasIterator jcasIter) throws AnalysisEngineProcessException { Map<W, PruningDecisionWrapper> gerpable2pruningDecisions = Maps.newHashMap(); while (jcasIter.hasNext()) { JCas jcas = jcasIter.next(); for (TOP top : GerpPhaseUtils.getAllTops(jcas, gerpableType)) { @SuppressWarnings("unchecked") W gerpable = (W) WrapperHelper.wrap(new WrapperIndexer(), top); gerpable2pruningDecisions.put(gerpable, gerpable.getPruningDecisions().get(0)); } gerpables.addAllPruningDecisions(gerpable2pruningDecisions); jcas.release(); } GerpPhaseUtils.removeAllTopsFromIndexesAndIndexer(mergedJcas, mergedCasIndexer, gerpableType); } private void ultimatePrune() { // TODO Auto-generated method stub } @Override public boolean hasNext() throws AnalysisEngineProcessException { if (gerpableIdx < gerpables.size()) { return true; } else { mergedJcas.release(); return false; } } @Override public AbstractCas next() throws AnalysisEngineProcessException { JCas output = getEmptyJCas(); CasCopier.copyCas(mergedJcas.getCas(), output.getCas(), true); T top = WrapperHelper.unwrap(new WrapperIndexer(), gerpables.get(gerpableIdx++), output); top.addToIndexes(output); return output; } @Override public void collectionProcessComplete() throws AnalysisEngineProcessException { super.collectionProcessComplete(); generatorSubPhase.collectionProcessComplete(); evidencerSubPhase.collectionProcessComplete(); rankerSubPhase.collectionProcessComplete(); prunerSubPhase.collectionProcessComplete(); } }
package edu.neu.ccs.pyramid.application; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ConcurrentHashMultiset; import com.google.common.collect.Multiset; import edu.neu.ccs.pyramid.configuration.Config; import edu.neu.ccs.pyramid.dataset.*; import edu.neu.ccs.pyramid.elasticsearch.ESIndex; import edu.neu.ccs.pyramid.elasticsearch.FeatureLoader; import edu.neu.ccs.pyramid.elasticsearch.MultiLabelIndex; import edu.neu.ccs.pyramid.feature.*; import edu.neu.ccs.pyramid.feature_extraction.NgramEnumerator; import edu.neu.ccs.pyramid.feature_extraction.NgramTemplate; import edu.neu.ccs.pyramid.util.Serialization; import org.apache.commons.io.FileUtils; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import java.util.logging.*; import java.util.regex.Pattern; import java.util.stream.Collectors; public class App1 { public static void main(String[] args) throws Exception{ if (args.length !=1){ throw new IllegalArgumentException("Please specify a properties file."); } Config config = new Config(args[0]); main(config); } public static void main(Config config) throws Exception{ Logger logger = Logger.getAnonymousLogger(); String logFile = config.getString("output.log"); FileHandler fileHandler = null; if (!logFile.isEmpty()){ new File(logFile).getParentFile().mkdirs(); //todo should append? fileHandler = new FileHandler(logFile, true); java.util.logging.Formatter formatter = new SimpleFormatter(); fileHandler.setFormatter(formatter); logger.addHandler(fileHandler); logger.setUseParentHandlers(false); } logger.info(config.toString()); File output = new File(config.getString("output.folder")); output.mkdirs(); if (config.getBoolean("createTrainSet")){ try (MultiLabelIndex index = loadIndex(config, logger)){ createTrainSet(config, index, logger); } } if (config.getBoolean("createTestSet")){ try (MultiLabelIndex index = loadIndex(config, logger)){ createTestSet(config, index, logger); } } if (fileHandler!=null){ fileHandler.close(); } } static MultiLabelIndex loadIndex(Config config, Logger logger) throws Exception{ MultiLabelIndex.Builder builder = new MultiLabelIndex.Builder() .setIndexName(config.getString("index.indexName")) .setClusterName(config.getString("index.clusterName")) .setClientType(config.getString("index.clientType")) .setExtMultiLabelField(config.getString("index.labelField")) .setDocumentType(config.getString("index.documentType")); if (config.getString("index.clientType").equals("transport")){ String[] hosts = config.getString("index.hosts").split(Pattern.quote(",")); String[] ports = config.getString("index.ports").split(Pattern.quote(",")); builder.addHostsAndPorts(hosts,ports); } MultiLabelIndex index = builder.build(); logger.info("index loaded"); logger.info("there are "+index.getNumDocs()+" documents in the index."); return index; } static String[] getDocsForSplitFromQuery(ESIndex index, String query){ List<String> docs = index.matchStringQuery(query); return docs.toArray(new String[docs.size()]); } static IdTranslator loadIdTranslator(String[] indexIds) throws Exception{ IdTranslator idTranslator = new IdTranslator(); for (int i=0;i<indexIds.length;i++){ idTranslator.addData(i,""+indexIds[i]); } return idTranslator; } private static boolean matchPrefixes(String name, Set<String> prefixes){ for (String prefix: prefixes){ if (name.startsWith(prefix)){ return true; } } return false; } static void addInitialFeatures(Config config, ESIndex index, FeatureList featureList, String[] ids, Logger logger) throws Exception{ String featureFieldPrefix = config.getString("index.featureFieldPrefix"); Set<String> prefixes = Arrays.stream(featureFieldPrefix.split(",")).map(String::trim).collect(Collectors.toSet()); Set<String> allFields = index.listAllFields(); List<String> featureFields = allFields.stream(). filter(field -> matchPrefixes(field,prefixes)). collect(Collectors.toList()); logger.info("all possible initial features:"+featureFields); for (String field: featureFields){ String featureType = index.getFieldType(field); if (featureType.equalsIgnoreCase("string")){ CategoricalFeatureExpander expander = new CategoricalFeatureExpander(); expander.setStart(featureList.size()); expander.setVariableName(field); expander.putSetting("source","field"); Collection<org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket> buckets= index.termAggregation(field,ids); Set<String> categories = buckets.stream().map(Terms.Bucket::getKey).collect(Collectors.toSet()); for (String category: categories){ expander.addCategory(category); } // for (String id: ids){ // String category = index.getStringField(id, field); // expander.addCategory(category); List<CategoricalFeature> group = expander.expand(); boolean toAdd = true; if (config.getBoolean("feature.categFeature.filter")){ double threshold = config.getDouble("feature.categFeature.percentThreshold"); int numCategories = group.size(); if (numCategories> ids.length*threshold){ toAdd=false; logger.info("field "+field+" has too many categories " +"("+numCategories+"), omitted."); } } if(toAdd){ for (Feature feature: group){ featureList.add(feature); } } } else { Feature feature = new Feature(); feature.setName(field); feature.setIndex(featureList.size()); feature.getSettings().put("source", "field"); featureList.add(feature); } } } static boolean interesting(Multiset<Ngram> allNgrams, Ngram candidate, int count){ for (int slop = 0;slop<candidate.getSlop();slop++){ Ngram toCheck = new Ngram(); toCheck.setInOrder(candidate.isInOrder()); toCheck.setField(candidate.getField()); toCheck.setNgram(candidate.getNgram()); toCheck.setSlop(slop); toCheck.setName(candidate.getName()); if (allNgrams.count(toCheck)==count){ return false; } } return true; } static Set<Ngram> gather(Config config, ESIndex index, String[] ids, Logger logger) throws Exception{ File metaDataFolder = new File(config.getString("output.folder"),"meta_data"); metaDataFolder.mkdirs(); Multiset<Ngram> allNgrams = ConcurrentHashMultiset.create(); List<Integer> ns = config.getIntegers("feature.ngram.n"); int minDf = config.getInt("feature.ngram.minDf"); List<String> fields = config.getStrings("index.ngramExtractionFields"); List<Integer> slops = config.getIntegers("feature.ngram.slop"); for (String field: fields){ for (int n: ns){ for (int slop:slops){ logger.info("gathering "+n+ "-grams from field "+field+" with slop "+slop+" and minDf "+minDf); NgramTemplate template = new NgramTemplate(field,n,slop); Multiset<Ngram> ngrams = NgramEnumerator.gatherNgram(index, ids, template, minDf); logger.info("gathered "+ngrams.elementSet().size()+ " ngrams"); int newCounter = 0; for (Multiset.Entry<Ngram> entry: ngrams.entrySet()){ Ngram ngram = entry.getElement(); int count = entry.getCount(); if (interesting(allNgrams,ngram,count)){ allNgrams.add(ngram,count); newCounter += 1; } } logger.info(newCounter+" are really new"); } } } logger.info("there are "+allNgrams.elementSet().size()+" ngrams in total"); // BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File(metaDataFolder,"all_ngrams.txt"))); // for (Multiset.Entry<Ngram> ngramEntry: allNgrams.entrySet()){ // bufferedWriter.write(ngramEntry.getElement().toString()); // bufferedWriter.write("\t"); // bufferedWriter.write(""+ngramEntry.getCount()); // bufferedWriter.newLine(); // bufferedWriter.close(); // //for serialization // Set<Ngram> uniques = new HashSet<>(); // uniques.addAll(allNgrams.elementSet()); // Serialization.serialize(uniques, new File(metaDataFolder, "all_ngrams.ser")); return allNgrams.elementSet(); } private static List<Ngram> addNgramFromFile(Config config, ESIndex index, Logger logger) throws IOException { List<Ngram> ngrams = new ArrayList<>(); String externalNgramFile = config.getString("feature.externalNgramFile"); List<String> lines = FileUtils.readLines(new File(externalNgramFile)); List<String> fields = config.getStrings("index.ngramExtractionFields"); String analyzer = config.getString("feature.analyzer"); for (String field: fields){ for (String line: lines){ Ngram ngram = index.analyze(line,analyzer); ngram.setField(field); ngrams.add(ngram); } } logger.info("ngrams collected from file "+externalNgramFile); logger.info(ngrams.toString()); return ngrams; } private static void addCodeDescription(Config config, ESIndex index, FeatureList featureList) throws Exception{ String file = config.getString("feature.codeDesc.File"); List<String> lines = FileUtils.readLines(new File(file)); String analyzer = config.getString("feature.codeDesc.analyzer"); String field = config.getString("feature.codeDesc.matchField"); int percentage = config.getInt("feature.codeDesc.minMatchPercentage"); for (String line: lines){ List<String> terms = index.analyzeString(line, analyzer); CodeDescription codeDescription = new CodeDescription(terms, percentage, field); featureList.add(codeDescription); } } static void addNgramFeatures(FeatureList featureList, Set<Ngram> ngrams){ ngrams.stream().forEach(ngram -> { ngram.getSettings().put("source","matching_score"); featureList.add(ngram); }); } //todo keep track of feature types(numerical /binary) static MultiLabelClfDataSet loadData(Config config, MultiLabelIndex index, FeatureList featureList, IdTranslator idTranslator, int totalDim, LabelTranslator labelTranslator, String docFilter) throws Exception{ File metaDataFolder = new File(config.getString("output.folder"),"meta_data"); Config savedConfig = new Config(new File(metaDataFolder, "saved_config")); int numDataPoints = idTranslator.numData(); int numClasses = labelTranslator.getNumClasses(); MultiLabelClfDataSet dataSet = MLClfDataSetBuilder.getBuilder() .numDataPoints(numDataPoints).numFeatures(totalDim) .numClasses(numClasses).dense(false) .missingValue(savedConfig.getBoolean("feature.missingValue")).build(); for(int i=0;i<numDataPoints;i++){ String dataIndexId = idTranslator.toExtId(i); List<String> extMultiLabel = index.getExtMultiLabel(dataIndexId); if (savedConfig.getBoolean("index.labelFilter")){ String prefix = savedConfig.getString("index.labelFilter.prefix"); extMultiLabel = extMultiLabel.stream().filter(extLabel -> extLabel.startsWith(prefix)).collect(Collectors.toList()); } for (String extLabel: extMultiLabel){ int intLabel = labelTranslator.toIntLabel(extLabel); dataSet.addLabel(i,intLabel); } } String matchScoreTypeString = savedConfig.getString("index.ngramMatchScoreType"); FeatureLoader.MatchScoreType matchScoreType; switch (matchScoreTypeString){ case "es_original": matchScoreType= FeatureLoader.MatchScoreType.ES_ORIGINAL; break; case "binary": matchScoreType= FeatureLoader.MatchScoreType.BINARY; break; case "frequency": matchScoreType= FeatureLoader.MatchScoreType.FREQUENCY; break; case "tfifl": matchScoreType= FeatureLoader.MatchScoreType.TFIFL; break; default: throw new IllegalArgumentException("unknown ngramMatchScoreType"); } FeatureLoader.loadFeatures(index, dataSet, featureList, idTranslator, matchScoreType, docFilter); dataSet.setIdTranslator(idTranslator); dataSet.setLabelTranslator(labelTranslator); return dataSet; } static LabelTranslator loadTrainLabelTranslator(Config config, MultiLabelIndex index, String[] trainIndexIds, Logger logger) throws Exception{ Collection<Terms.Bucket> buckets = index.termAggregation(config.getString("index.labelField"), trainIndexIds); if (config.getBoolean("index.labelFilter")){ String prefix = config.getString("index.labelFilter.prefix"); buckets = buckets.stream().filter(bucket -> bucket.getKey().startsWith(prefix)).collect(Collectors.toList()); } logger.info("there are "+buckets.size()+" classes in the training set."); List<String> labels = new ArrayList<>(); logger.info("label distribution in training set:"); StringBuilder stringBuilder = new StringBuilder(); for (Terms.Bucket bucket: buckets){ stringBuilder.append(bucket.getKey()); stringBuilder.append(":"); stringBuilder.append(bucket.getDocCount()); stringBuilder.append(", "); labels.add(bucket.getKey()); } logger.info(stringBuilder.toString()); LabelTranslator labelTranslator = new LabelTranslator(labels); // logger.info(labelTranslator); return labelTranslator; } static LabelTranslator loadAugmentedLabelTranslator(Config config, MultiLabelIndex index, String[] testIndexIds, LabelTranslator trainLabelTranslator, Logger logger){ List<String> extLabels = new ArrayList<>(); for (int i=0;i<trainLabelTranslator.getNumClasses();i++){ extLabels.add(trainLabelTranslator.toExtLabel(i)); } Collection<Terms.Bucket> buckets = index.termAggregation(config.getString("index.labelField"), testIndexIds); if (config.getBoolean("index.labelFilter")){ String prefix = config.getString("index.labelFilter.prefix"); buckets = buckets.stream().filter(bucket -> bucket.getKey().startsWith(prefix)).collect(Collectors.toList()); } List<String> newLabels = new ArrayList<>(); logger.info("label distribution in data set:"); StringBuilder stringBuilder = new StringBuilder(); for (Terms.Bucket bucket: buckets){ stringBuilder.append(bucket.getKey()); stringBuilder.append(":"); stringBuilder.append(bucket.getDocCount()); stringBuilder.append(", "); if (!extLabels.contains(bucket.getKey())){ extLabels.add(bucket.getKey()); newLabels.add(bucket.getKey()); } } logger.info(stringBuilder.toString()); if (!newLabels.isEmpty()){ logger.warning("found new labels in data set: "+newLabels); } return new LabelTranslator(extLabels); } // static void getNgramDistributions(Config config, ESIndex index, String[] ids,LabelTranslator labelTranslator ) throws Exception{ // File metaDataFolder = new File(config.getString("output.folder"),"meta_data"); // metaDataFolder.mkdirs(); // logger.info("generating ngram distributions"); // StopWatch stopWatch = new StopWatch(); // stopWatch.start(); // File file = new File(metaDataFolder,"all_ngrams.ser"); // Set<Ngram> ngrams= (Set) Serialization.deserialize(file); // String labelField = config.getString("index.labelField"); // long[] labelDistribution = LabelDistribution.getLabelDistribution(index,labelField,ids,labelTranslator); // .collect(Collectors.toList()); // Serialization.serialize(distributions,new File(metaDataFolder,"distributions.ser")); // BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File(metaDataFolder,"distributions.txt"))); // bufferedWriter.write(distribution.toString()); // bufferedWriter.newLine(); // bufferedWriter.close(); // logger.info("done"); // logger.info("time spent on generating distributions = "+stopWatch); static void generateMetaData(Config config, MultiLabelIndex index, Logger logger) throws Exception{ logger.info("generating meta data"); File metaDataFolder = new File(config.getString("output.folder"),"meta_data"); metaDataFolder.mkdirs(); String[] trainIndexIds; trainIndexIds = getDocsForSplitFromQuery(index, config.getString("index.splitQuery.train")); LabelTranslator trainLabelTranslator = loadTrainLabelTranslator(config, index, trainIndexIds, logger); Serialization.serialize(trainLabelTranslator,new File(metaDataFolder,"label_translator.ser")); FileUtils.writeStringToFile(new File(metaDataFolder,"label_translator.txt"),trainLabelTranslator.toString()); FeatureList featureList = new FeatureList(); if (config.getBoolean("feature.useInitialFeatures")){ addInitialFeatures(config,index,featureList,trainIndexIds, logger); } if (config.getBoolean("feature.useCodeDescription")){ addCodeDescription(config, index, featureList); } Set<Ngram> ngrams = new HashSet<>(); ngrams.addAll(gather(config,index,trainIndexIds, logger)); if (config.getBoolean("feature.filterNgramsByKeyWords")){ ngrams = keywordsFilter(config,index,ngrams); } if (config.getBoolean("feature.filterNgramsByRegex")){ ngrams = regexFilter(config,ngrams); } if (config.getBoolean("feature.addExternalNgrams")){ ngrams.addAll(addNgramFromFile(config, index, logger)); } // if (config.getBoolean("feature.generateDistribution")){ // getNgramDistributions(config,index,trainIndexIds,trainLabelTranslator); addNgramFeatures(featureList,ngrams); Serialization.serialize(featureList,new File(metaDataFolder,"feature_list.ser")); try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new File(metaDataFolder,"feature_list.txt"))) ){ for (Feature feature: featureList.getAll()){ bufferedWriter.write(feature.toString()); bufferedWriter.newLine(); } } Config metaConfig = new Config(); String[] keys = {"index.labelFilter", "index.labelFilter.prefix", "index.ngramMatchScoreType", "feature.missingValue"}; Config.copy(config, metaConfig, keys); metaConfig.store(new File(metaDataFolder, "saved_config")); logger.info("meta data generated"); } static void createDataSet(Config config, MultiLabelIndex index, String[] indexIds, String datasetName, String docFilter, Logger logger) throws Exception{ // String splitValueAll = splitListToString(splitValues); logger.info("creating data set "+datasetName); File metaDataFolder = new File(config.getString("output.folder"),"meta_data"); IdTranslator idTranslator = loadIdTranslator(indexIds); String archive = config.getString("output.folder"); LabelTranslator trainLabelTranslator = (LabelTranslator)Serialization.deserialize(new File(metaDataFolder,"label_translator.ser")); LabelTranslator labelTranslator = loadAugmentedLabelTranslator(config, index, indexIds, trainLabelTranslator, logger); FeatureList featureList = (FeatureList)Serialization.deserialize(new File(metaDataFolder,"feature_list.ser")); MultiLabelClfDataSet dataSet = loadData(config, index, featureList, idTranslator, featureList.size(), labelTranslator, docFilter); dataSet.setFeatureList(featureList); File dataFile = new File(new File(archive,"data_sets"),datasetName); TRECFormat.save(dataSet,dataFile); logger.info("data set "+datasetName+" created"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.writeValue(new File(dataFile,"data_config.json"),config); } static void createTrainSet(Config config, MultiLabelIndex index, Logger logger) throws Exception{ generateMetaData(config, index, logger); String[] indexIds = getDocsForSplitFromQuery(index, config.getString("index.splitQuery.train")); createDataSet(config, index, indexIds,config.getString("output.trainFolder"), config.getString("index.splitQuery.train"), logger); } static void createTestSet(Config config, MultiLabelIndex index, Logger logger) throws Exception{ String[] indexIds = getDocsForSplitFromQuery(index, config.getString("index.splitQuery.test")); createDataSet(config, index, indexIds,config.getString("output.testFolder"), config.getString("index.splitQuery.test"), logger); } // public static String splitListToString(List<String> splitValues){ // String splitValueAll = ""; // for (int i=0;i<splitValues.size();i++){ // splitValueAll = splitValueAll+splitValues.get(i); // if (i<splitValues.size()-1){ // splitValueAll = splitValueAll+"_"; // return splitValueAll; /** * filter ngrams by given unigrams in the file * do not filter unigram candidates */ private static Set<Ngram> keywordsFilter(Config config, ESIndex index, Set<Ngram> ngrams) throws IOException { String externalKeywordsFile = config.getString("feature.filterNgrams.keyWordsFile"); List<String> lines = FileUtils.readLines(new File(externalKeywordsFile)); String analyzer = config.getString("feature.analyzer"); Set<String> keywords = new HashSet<>(); for (String line: lines){ keywords.add(index.analyze(line, analyzer).getNgram()); } return ngrams.stream().parallel().filter(ngram-> ngram.getN()==1||containsKeyWords(ngram,keywords)) .collect(Collectors.toSet()); } private static boolean containsKeyWords(Ngram ngram, Set<String> keywords){ String[] terms = ngram.getTerms(); for (String term: terms){ if (keywords.contains(term)){ return true; } } return false; } /** * * @param config * @param ngrams * @return ngrams that do not match the regular expression */ private static Set<Ngram> regexFilter(Config config, Set<Ngram> ngrams){ String regex = config.getString("feature.filterNgrams.regex"); return ngrams.parallelStream().filter(ngram->!ngram.getNgram().matches(regex)).collect(Collectors.toSet()); } }
package fi.solita.utils.functional; import static fi.solita.utils.functional.Collections.newList; import static fi.solita.utils.functional.Functional.forall; import static fi.solita.utils.functional.Functional.head; import static fi.solita.utils.functional.Functional.isEmpty; import static fi.solita.utils.functional.Functional.map; import static fi.solita.utils.functional.Functional.span; import static fi.solita.utils.functional.Functional.take; import static fi.solita.utils.functional.FunctionalA.max; import static fi.solita.utils.functional.FunctionalA.min; import static fi.solita.utils.functional.Option.None; import static fi.solita.utils.functional.Option.Some; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.PriorityQueue; public abstract class Iterables { public static final Transformer<Iterable<?>,Option<Long>> resolveSize = new Transformer<Iterable<?>,Option<Long>>() { private final Option<Long> SOME_ZERO = Some(0l); private final Option<Long> SOME_ONE = Some(1l); public Option<Long> transform(Iterable<?> source) { if (source instanceof Collection) { return Some((long)((Collection<?>)source).size()); } if (source instanceof PossiblySizeAwareIterable) { return ((PossiblySizeAwareIterable<?>)source).sizeEstimate(); } if (source instanceof Option) { return ((Option<?>)source).isDefined() ? SOME_ONE : SOME_ZERO; } return None(); } }; private static final Transformer<Iterator<?>,Boolean> hasNext = new Transformer<Iterator<?>,Boolean>() { public Boolean transform(Iterator<?> source) { return source.hasNext(); } }; private static final Transformer<Iterator<Object>, Object> next = new Transformer<Iterator<Object>,Object>() { public Object transform(Iterator<Object> source) { return source.next(); } }; private static final Transformer<Iterable<Object>,Iterator<Object>> toIterator = new Transformer<Iterable<Object>,Iterator<Object>>() { public Iterator<Object> transform(Iterable<Object> source) { return source.iterator(); } }; static abstract class PossiblySizeAwareIterable<T> implements Iterable<T> { public abstract Option<Long> sizeEstimate(); public String toString() { return getClass().getSimpleName() + Collections.newList(this).toString(); } } static final class RangeIterable<T> extends PossiblySizeAwareIterable<T> { private final Enumerable<T> enumeration; private final Option<T> from; private final Option<T> toInclusive; private final Option<Long> knownSize; public RangeIterable(Enumerable<T> enumeration, T from, Option<T> toInclusive) { this(enumeration, from, toInclusive, Option.<Long>None()); } public RangeIterable(Enumerable<T> enumeration, T from, T toInclusive, long knownSize) { this(enumeration, from, Some(toInclusive), Some(knownSize)); } private RangeIterable(Enumerable<T> enumeration, T from, Option<T> toInclusive, Option<Long> knownSize) { this.enumeration = enumeration; this.from = Some(from); this.toInclusive = toInclusive; this.knownSize = knownSize; } public Iterator<T> iterator() { return new Iterator<T>() { private Option<T> nextToReturn = from; public boolean hasNext() { return nextToReturn.isDefined(); } public T next() { T ret; try { ret = nextToReturn.get(); } catch (RuntimeException e) { throw new NoSuchElementException(); } if (toInclusive.isDefined() && ret.equals(toInclusive.get())) { nextToReturn = None(); } else { nextToReturn = enumeration.succ(ret); } return ret; } public void remove() { throw new UnsupportedOperationException(); } }; } public Option<Long> sizeEstimate() { return knownSize.isDefined() ? Some(knownSize.get()) : Option.<Long>None(); } } static final class RepeatingIterable<T> extends PossiblySizeAwareIterable<T> { private final T value; private final Long amount; public RepeatingIterable(T value) { this.value = value; this.amount = null; } public RepeatingIterable(T value, long amount) { this.value = value; this.amount = amount; } public Option<Long> sizeEstimate() { return amount != null ? Some(amount) : Option.<Long>None(); } public Iterator<T> iterator() { return new Iterator<T>() { private int current = 0; public boolean hasNext() { return amount == null || current < amount; } public T next() { if (amount != null && current == amount) { throw new NoSuchElementException(); } current++; return value; } public void remove() { throw new UnsupportedOperationException(); } }; } } static final class TransposingIterable<T> extends PossiblySizeAwareIterable<Iterable<T>> { private final Iterable<? extends Iterable<T>> elements; public TransposingIterable(Iterable<? extends Iterable<T>> elements) { this.elements = elements; } public Iterator<Iterable<T>> iterator() { return new Iterator<Iterable<T>>() { @SuppressWarnings("unchecked") private final List<Iterator<T>> iterators = newList(map((Transformer<Iterable<T>,Iterator<T>>)(Object)toIterator, elements)); public boolean hasNext() { return !iterators.isEmpty() && forall(hasNext, iterators); } @SuppressWarnings("unchecked") public Iterable<T> next() { if (!hasNext()) { throw new NoSuchElementException(); } return newList(map((Transformer<Iterator<T>, T>)(Object)next, iterators)); } public void remove() { throw new UnsupportedOperationException(); } }; } public Option<Long> sizeEstimate() { return None(); } } static final class ZippingIterable<A,B> extends PossiblySizeAwareIterable<Tuple2<A, B>> { private final Iterable<A> elements1; private final Iterable<B> elements2; public ZippingIterable(Iterable<A> elements1, Iterable<B> elements2) { this.elements1 = elements1; this.elements2 = elements2; } public Iterator<Tuple2<A, B>> iterator() { return new Iterator<Tuple2<A, B>>() { private final Iterator<A> it1 = elements1.iterator(); private final Iterator<B> it2 = elements2.iterator(); public boolean hasNext() { return it1.hasNext() && it2.hasNext(); } public Tuple2<A, B> next() { return Tuple.of(it1.next(), it2.next()); } public void remove() { throw new UnsupportedOperationException(); } }; } public Option<Long> sizeEstimate() { for (long a: resolveSize.apply(elements1)) { for (long b: resolveSize.apply(elements2)) { return Some(Functional.min(a,b)); } } return None(); } } static class ConcatenatingIterable<T> extends PossiblySizeAwareIterable<T> { private final Iterable<? extends Iterable<? extends T>> elements; public ConcatenatingIterable(Iterable<? extends Iterable<? extends T>> elements) { this.elements = elements; } public Option<Long> sizeEstimate() { long s = 0; for (Option<Long> size: map(resolveSize, elements)) { if (size.isDefined()) { s += size.get(); } else { return Option.None(); } } return Some(s); } public Iterator<T> iterator() { return new Iterator<T>() { @SuppressWarnings("unchecked") private final Iterator<Iterator<? extends T>> it = Functional.map((Transformer<Iterable<? extends T>,Iterator<? extends T>>)(Object)toIterator, elements).iterator(); private Iterator<? extends T> lastUsed = it.hasNext() ? it.next() : java.util.Collections.<T>emptyList().iterator(); public boolean hasNext() { while (!lastUsed.hasNext() && it.hasNext()) { lastUsed = it.next(); } return lastUsed.hasNext(); } public T next() { hasNext(); return lastUsed.next(); } public void remove() { throw new UnsupportedOperationException(); } }; } } static final class FlatteningIterable<T> extends ConcatenatingIterable<T> { public FlatteningIterable(Iterable<? extends Iterable<? extends T>> elements) { super(elements); } public Option<Long> sizeEstimate() { return None(); } } static final class FilteringIterable<T> extends PossiblySizeAwareIterable<T> { private final Iterable<T> iterable; private final Apply<? super T, Boolean> filter; public FilteringIterable(Iterable<T> iterable, Apply<? super T, Boolean> filter) { this.iterable = iterable; this.filter = filter; } public Option<Long> sizeEstimate() { return None(); } public Iterator<T> iterator() { return new Iterator<T>() { private boolean hasNext; private T next; private final Iterator<T> source = iterable.iterator(); { readNext(); } public boolean hasNext() { return hasNext; } private void readNext() { hasNext = false; while (!hasNext && source.hasNext()) { T n = source.next(); if (filter.apply(n)) { next = n; hasNext = true; } } } public T next() { if (!hasNext) { throw new NoSuchElementException(); } T ret = (T) next; readNext(); return ret; } public void remove() { throw new UnsupportedOperationException(); } }; } } static final class TransformingIterable<S,T> extends PossiblySizeAwareIterable<T> { private final Iterable<S> iterable; private final Apply<? super S, ? extends T> transformer; public TransformingIterable(Iterable<S> iterable, Apply<? super S, ? extends T> transformer) { this.iterable = iterable; this.transformer = transformer; } public Option<Long> sizeEstimate() { return resolveSize.apply(iterable); } public Iterator<T> iterator() { return new Iterator<T>() { private final Iterator<S> source = iterable.iterator(); public boolean hasNext() { return source.hasNext(); } public T next() { return transformer.apply(source.next()); } public void remove() { throw new UnsupportedOperationException(); } }; } } static final class ReversingIterable<T> extends PossiblySizeAwareIterable<T> { private final Iterable<T> iterable; public ReversingIterable(Iterable<T> iterable) { this.iterable = iterable; } public Option<Long> sizeEstimate() { return resolveSize.apply(iterable); } public Iterator<T> iterator() { return new Iterator<T>() { private final List<T> list = iterable instanceof List ? (List<T>)iterable : newList(iterable); private final ListIterator<T> underlying = list.listIterator(list.size()); public boolean hasNext() { return underlying.hasPrevious(); } public T next() { return underlying.previous(); } public void remove() { throw new UnsupportedOperationException(); } }; } } static final class CharSequenceIterable extends PossiblySizeAwareIterable<Character> implements CharSequence { private final CharSequence chars; public CharSequenceIterable(CharSequence chars) { this.chars = chars; } public char charAt(int index) { return chars.charAt(index); } public int length() { return chars.length(); } public CharSequence subSequence(int start, int end) { return chars.subSequence(start, end); } public Iterator<Character> iterator() { return new Iterator<Character>() { private int read = 0; public boolean hasNext() { try { chars.charAt(read); return true; } catch (IndexOutOfBoundsException e) { return false; } } public Character next() { char ret = chars.charAt(read); read++; return ret; } public void remove() { throw new UnsupportedOperationException(); } }; } public Option<Long> sizeEstimate() { if (chars instanceof String || chars instanceof StringBuilder || chars instanceof StringBuffer) { return Some((long)chars.length()); } else { return None(); } } public String toString() { return chars.toString(); } } static class MemoizingCharSequenceIterable extends PossiblySizeAwareIterable<Character> implements CharSequence, Iterable<Character> { private final StringBuilder memo = new StringBuilder(); private final Iterator<Character> it; public MemoizingCharSequenceIterable(Iterable<Character> chars) { it = chars.iterator(); } private int resolveLength() { while (it.hasNext()) { memo.append(it.next()); } return memo.length(); } /** * Does not neccessarily check if <i>end</i> is bigger than <i>length()<i> */ public CharSequence subSequence(int start, int end) { if (start < 0 || end < 0 || start > end || !it.hasNext() && end > length()) { throw new IndexOutOfBoundsException(); } return new MemoizingCharSequenceIterable(take(end - start, FunctionalImpl.drop(start, this))); } public int length() { return resolveLength(); } public char charAt(int index) { if (index < 0) throw new IndexOutOfBoundsException(); Iterator<Character> it = iterator(); try { for (int i = 0; i < index; ++i) { it.next(); } return it.next(); } catch (NoSuchElementException e) { throw new IndexOutOfBoundsException(index + " was greater than " + length()); } } public Iterator<Character> iterator() { return new Iterator<Character>() { private int read = 0; public boolean hasNext() { if (read == memo.length() && it.hasNext()) { memo.append(it.next()); } return read < memo.length(); } public Character next() { if (read == memo.length()) { memo.append(it.next()); } char ret = memo.charAt(read); read++; return ret; } public void remove() { throw new UnsupportedOperationException(); } }; } public Option<Long> sizeEstimate() { if (!it.hasNext()) { return Some((long)memo.length()); } else { return None(); } } public String toString() { resolveLength(); return memo.toString(); } } static final class SortingIterable<T> extends PossiblySizeAwareIterable<T> { private final Iterable<T> iterable; private final Comparator<? super T> comparator; public SortingIterable(Iterable<T> iterable, Comparator<? super T> comparator) { this.iterable = iterable; this.comparator = comparator; } public Iterator<T> iterator() { long initialSize = resolveSize.apply(iterable).getOrElse(11l); if (initialSize == 0) { return java.util.Collections.<T>emptyList().iterator(); } final PriorityQueue<T> queue = new PriorityQueue<T>((int)initialSize, comparator); if (iterable instanceof Collection) { queue.addAll((Collection<T>)iterable); } else { for (T t: iterable) { queue.add(t); } } return new Iterator<T>() { public boolean hasNext() { return !queue.isEmpty(); } public T next() { return queue.remove(); } public void remove() { throw new UnsupportedOperationException(); } }; } public Option<Long> sizeEstimate() { return resolveSize.apply(iterable); } } static final class TakingIterable<T> extends PossiblySizeAwareIterable<T> { private final Iterable<T> elements; private final long amount; public TakingIterable(Iterable<T> elements, long amount) { if (amount < 0) { amount = 0; } this.elements = elements; this.amount = amount; } public Iterator<T> iterator() { return new Iterator<T>() { private long left = amount; private final Iterator<T> it = elements.iterator(); public boolean hasNext() { return left > 0 && it.hasNext(); } public T next() { if (left == 0) { throw new NoSuchElementException(); } left return it.next(); } public void remove() { throw new UnsupportedOperationException(); } }; } public Option<Long> sizeEstimate() { Option<Long> s = resolveSize.apply(elements); if (s.isDefined()) { return Some(min(s.get(), amount)); } else { // a good guess, since it's probably rare that 'take' is // called with an amount of significantly larger than the size // of the iterable. Right? return Some(amount); } } } static final class DroppingIterable<T> extends PossiblySizeAwareIterable<T> { private final Iterable<T> elements; private final long amount; public DroppingIterable(Iterable<T> elements, long amount) { if (amount < 0) { amount = 0; } this.elements = elements; this.amount = amount; } public Iterator<T> iterator() { Iterator<T> it = elements.iterator(); long left = amount; while (left > 0 && it.hasNext()) { it.next(); left } return it; } public Option<Long> sizeEstimate() { Option<Long> s = resolveSize.apply(elements); if (s.isDefined()) { return Some(max(s.get() - amount, 0l)); } else { return None(); } } } static final class GroupingIterable<T> extends PossiblySizeAwareIterable<Iterable<T>> { private final Iterable<T> elements; private final Apply<Tuple2<T,T>, Boolean> comparator; public GroupingIterable(Iterable<T> elements, Apply<Tuple2<T,T>, Boolean> comparator) { this.elements = elements; this.comparator = comparator; } public Option<Long> sizeEstimate() { return None(); } public Iterator<Iterable<T>> iterator() { return new Iterator<Iterable<T>>() { private Iterable<T> remaining = elements; public boolean hasNext() { return !isEmpty(remaining); } public Iterable<T> next() { if (!hasNext()) { throw new NoSuchElementException(); } final T first = head(remaining); Pair<Iterable<T>, Iterable<T>> s = span(new Predicate<T>() { public boolean accept(T candidate) { return comparator.apply(Tuple.of(candidate, first)); } }, remaining); remaining = s.right; return s.left; } public void remove() { throw new UnsupportedOperationException(); } }; } } }
package info.u_team.u_team_core.block; import info.u_team.u_team_core.creativetab.UCreativeTab; import info.u_team.u_team_core.item.UItemBlock; import info.u_team.u_team_core.sub.USub; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraftforge.fml.common.registry.GameRegistry; /** * Block API<br> * -> Basic Block * * @date 17.08.2017 * @author MrTroble, HyCraftHD */ public class UBlock extends Block { private UItemBlock uitemblock = null; public UBlock(Material material, String name) { this(material, name, null, UItemBlock.class); } public UBlock(Material material, String name, Class<? extends UItemBlock> itemblock) { this(material, name, null, itemblock); } public UBlock(Material material, String name, UCreativeTab tab) { this(material, name, tab, UItemBlock.class); } public UBlock(Material material, String name, UCreativeTab tab, Class<? extends UItemBlock> itemblock) { super(material); setRegistryName(USub.getID(), name); setUnlocalizedName(name); if (tab != null) { setCreativeTab(tab); } try { uitemblock = itemblock.getConstructor(UBlock.class).newInstance(this); } catch (Exception ex) { ex.printStackTrace(); } register(); } private final void register() { GameRegistry.register(this); GameRegistry.register(uitemblock); } }
package io.burt.jmespath.ast; public class FlattenListNode extends JmesPathNode { public FlattenListNode(JmesPathNode source) { super(source); } @Override protected boolean internalEquals(Object o) { return true; } @Override protected int internalHashCode() { return 19; } }
package io.openshift.booster; import io.vertx.core.AbstractVerticle; import io.vertx.core.Future; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.Router; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.StaticHandler; import static io.vertx.core.http.HttpHeaders.CONTENT_TYPE; public class HttpApplication extends AbstractVerticle { protected static final String template = "Bonjour, %s!"; @Override public void start(Future<Void> future) { // Create a router object. Router router = Router.router(vertx); router.get("/api/greeting").handler(this::greeting);
package io.tus.java.client; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; public class TusRetryingClient extends TusClient { private int[] delays = new int[]{500, 1000, 2000, 3000}; public void setDelays(int[] delays) { this.delays = delays; } public int[] getDelays() { return delays; } @Override @Nullable public TusUploader createUpload(@NotNull TusUpload upload) throws ProtocolException, IOException { int attempt = 0; while(true) { attempt++; try { return super.createUpload(upload); } catch(ProtocolException e) { // Do not attempt a retry, if the Exception suggests so. if(!e.shouldRetry()) throw e; if(attempt >= delays.length) { // We exceeds the number of maximum retries. In this case the latest exception // is thrown. throw e; } } catch(IOException e) { if(attempt >= delays.length) { // We exceeds the number of maximum retries. In this case the latest exception // is thrown. throw e; } } try { // Sleep for the specified delay before attempting the next retry. Thread.sleep(delays[attempt]); } catch(InterruptedException e) { // If we get interrupted while waiting for the next retry, the user has cancelled // the upload willingly and we return null as a signal. return null; } } } @Override @Nullable public TusUploader resumeUpload(@NotNull TusUpload upload) throws FingerprintNotFoundException, ResumingNotEnabledException, ProtocolException, IOException { int attempt = 0; while(true) { attempt++; try { return super.resumeUpload(upload); } catch(ProtocolException e) { // Do not attempt a retry, if the Exception suggests so. if(!e.shouldRetry()) throw e; if(attempt >= delays.length) { // We exceeds the number of maximum retries. In this case the latest exception // is thrown. throw e; } } catch(IOException e) { if(attempt >= delays.length) { // We exceeds the number of maximum retries. In this case the latest exception // is thrown. throw e; } } try { // Sleep for the specified delay before attempting the next retry. Thread.sleep(delays[attempt]); } catch(InterruptedException e) { // If we get interrupted while waiting for the next retry, the user has cancelled // the upload willingly and we return null as a signal. return null; } } } // TODO resumeOrCreateUpload will return null if resumeUpload does so without trying to create one. }
package it.unipi.di.acube.smaph; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import org.apache.commons.lang.NotImplementedException; import it.unipi.di.acube.batframework.systemPlugins.CachedWATAnnotator; import it.unipi.di.acube.batframework.systemPlugins.WATAnnotator; import it.unipi.di.acube.batframework.utils.WikipediaInterface; import it.unipi.di.acube.searchapi.CachedWebsearchApi; import it.unipi.di.acube.searchapi.WebsearchApi; import it.unipi.di.acube.searchapi.callers.BingSearchApiCaller; import it.unipi.di.acube.searchapi.callers.GoogleSearchApiCaller; import it.unipi.di.acube.smaph.datasets.wikiAnchors.EntityToAnchors; import it.unipi.di.acube.smaph.datasets.wikitofreebase.WikipediaToFreebase; import it.unipi.di.acube.smaph.learn.featurePacks.AnnotationFeaturePack; import it.unipi.di.acube.smaph.learn.featurePacks.EntityFeaturePack; import it.unipi.di.acube.smaph.learn.featurePacks.FeaturePack; import it.unipi.di.acube.smaph.learn.featurePacks.GreedyFeaturePack; import it.unipi.di.acube.smaph.learn.models.entityfilters.EntityFilter; import it.unipi.di.acube.smaph.learn.models.entityfilters.LibSvmEntityFilter; import it.unipi.di.acube.smaph.learn.models.entityfilters.NoEntityFilter; import it.unipi.di.acube.smaph.learn.models.linkback.annotationRegressor.AnnotationRegressor; import it.unipi.di.acube.smaph.learn.models.linkback.annotationRegressor.LibSvmAnnotationRegressor; import it.unipi.di.acube.smaph.learn.models.linkback.bindingRegressor.BindingRegressor; import it.unipi.di.acube.smaph.learn.models.linkback.bindingRegressor.RankLibBindingRegressor; import it.unipi.di.acube.smaph.learn.normalizer.FeatureNormalizer; import it.unipi.di.acube.smaph.learn.normalizer.NoFeatureNormalizer; import it.unipi.di.acube.smaph.learn.normalizer.ZScoreFeatureNormalizer; import it.unipi.di.acube.smaph.linkback.AdvancedIndividualLinkback; import it.unipi.di.acube.smaph.linkback.CollectiveLinkBack; import it.unipi.di.acube.smaph.linkback.DummyLinkBack; import it.unipi.di.acube.smaph.linkback.GreedyLinkback; import it.unipi.di.acube.smaph.linkback.LinkBack; import it.unipi.di.acube.smaph.linkback.bindingGenerator.BindingGenerator; import it.unipi.di.acube.smaph.linkback.bindingGenerator.DefaultBindingGenerator; import it.unipi.di.acube.smaph.snippetannotationfilters.FrequencyAnnotationFilter; public class SmaphBuilder { public static final BindingGenerator DEFAULT_BINDING_GENERATOR = new DefaultBindingGenerator(); public static final CachedWATAnnotator DEFAULT_CACHED_AUX_ANNOTATOR = new CachedWATAnnotator("wikisense.mkapp.it", 80, "base", "COMMONNESS", "mw", "0.2", "0.0"); public static final WATAnnotator DEFAULT_AUX_ANNOTATOR = new WATAnnotator("wikisense.mkapp.it", 80, "base", "COMMONNESS", "mw", "0.2", "0.0"); public static WebsearchApi BING_WEBSEARCH_API = null; public static WebsearchApi GOOGLE_WEBSEARCH_API = null; private static Map<URL, FeatureNormalizer> urlToNormalizer = new HashMap<>(); private static Map<URL, EntityFilter> urlToEntityFilter = new HashMap<>(); private static Map<URL, AnnotationRegressor> urlToAnnotationRegressor = new HashMap<>(); private static Map<URL, BindingRegressor> urlToBindingRegressor = new HashMap<>(); public static final int DEFAULT_NORMALSEARCH_RESULTS = 5; public static final int DEFAULT_WIKISEARCH_RESULTS = 10; public static final int DEFAULT_ANNOTATED_SNIPPETS = 15; public static final double DEFAULT_ANNOTATIONFILTER_RATIO = 0.03; public static final double DEFAULT_ANCHOR_MENTION_ED = 0.7; public static final Websearch DEFAULT_WEBSEARCH = Websearch.GOOGLE_CSE; public enum SmaphVersion { ENTITY_FILTER("ef"), ANNOTATION_REGRESSOR("ar"), COLLECTIVE("coll"), GREEDY("greedy"); private String label; private SmaphVersion(String label) { this.label = label; } @Override public String toString() { return label; } } public enum Websearch { BING, GOOGLE_CSE } public static Websearch websearchFromString(String wsStr) { switch (wsStr) { case "bing": return SmaphBuilder.Websearch.BING; case "google": return SmaphBuilder.Websearch.GOOGLE_CSE; } return null; } public static WebsearchApi getWebsearch(Websearch ws, SmaphConfig c) throws FileNotFoundException, ClassNotFoundException, IOException { if (c.getDefaultWebsearchCache() == null) switch (ws) { case GOOGLE_CSE: return new WebsearchApi(new GoogleSearchApiCaller(c.getDefaultGoogleCseId(), c.getDefaultGoogleApiKey())); case BING: return new WebsearchApi(new BingSearchApiCaller(c.getDefaultBingKey())); } else switch (ws) { case GOOGLE_CSE: if (GOOGLE_WEBSEARCH_API == null) GOOGLE_WEBSEARCH_API = CachedWebsearchApi.builder() .api(new GoogleSearchApiCaller(c.getDefaultGoogleCseId(), c.getDefaultGoogleApiKey())) .dbFrom((CachedWebsearchApi) BING_WEBSEARCH_API).path(c.getDefaultWebsearchCache()).create(); return GOOGLE_WEBSEARCH_API; case BING: if (BING_WEBSEARCH_API == null) BING_WEBSEARCH_API = CachedWebsearchApi.builder().api(new BingSearchApiCaller(c.getDefaultBingKey())) .dbFrom((CachedWebsearchApi) GOOGLE_WEBSEARCH_API).path(c.getDefaultWebsearchCache()).create(); return BING_WEBSEARCH_API; } return null; } public static SmaphAnnotator getDefaultSmaphParamTopk(WikipediaInterface wikiApi, WikipediaToFreebase wikiToFreeb, WATAnnotator auxAnnotator, EntityToAnchors e2a, EntityFilter entityFilter, FeatureNormalizer efNorm, LinkBack lb, boolean s1, int topkS1, boolean s2, int topkS2, boolean s3, int topkS3, Websearch ws, SmaphConfig c) throws FileNotFoundException, ClassNotFoundException, IOException { return new SmaphAnnotator(s1, topkS1, s2, topkS2, s3, topkS3, DEFAULT_ANCHOR_MENTION_ED, false, lb, entityFilter, efNorm, DEFAULT_BINDING_GENERATOR, auxAnnotator, new FrequencyAnnotationFilter(DEFAULT_ANNOTATIONFILTER_RATIO), wikiApi, wikiToFreeb, getWebsearch(ws, c), e2a); } private static SmaphAnnotator getDefaultSmaphParam(WikipediaInterface wikiApi, WikipediaToFreebase wikiToFreeb, WATAnnotator auxAnnotator, EntityToAnchors e2a, EntityFilter entityFilter, FeatureNormalizer efNorm, LinkBack lb, boolean s1, boolean s2, boolean s3, Websearch ws, SmaphConfig c) throws FileNotFoundException, ClassNotFoundException, IOException { return getDefaultSmaphParamTopk(wikiApi, wikiToFreeb, auxAnnotator, e2a, entityFilter, efNorm, lb, s1, DEFAULT_NORMALSEARCH_RESULTS, s2, DEFAULT_WIKISEARCH_RESULTS, s3, DEFAULT_ANNOTATED_SNIPPETS, ws, c); } public static SmaphAnnotator getSmaphGatherer(WikipediaInterface wikiApi, WikipediaToFreebase wikiToFreeb, EntityToAnchors e2a, boolean s1, boolean s2, boolean s3, Websearch ws, SmaphConfig c) throws FileNotFoundException, ClassNotFoundException, IOException { return getDefaultSmaphParam(wikiApi, wikiToFreeb, DEFAULT_CACHED_AUX_ANNOTATOR, e2a, new NoEntityFilter(), null, new DummyLinkBack(), s1, s2, s3, ws, c); } public static SmaphAnnotator getSmaphGatherer(WikipediaInterface wikiApi, WikipediaToFreebase wikiToFreeb, EntityToAnchors e2a, boolean s1, int topkS1, boolean s2, int topkS2, boolean s3, int topkS3, Websearch ws, SmaphConfig c) throws FileNotFoundException, ClassNotFoundException, IOException { return getDefaultSmaphParamTopk(wikiApi, wikiToFreeb, DEFAULT_CACHED_AUX_ANNOTATOR, e2a, new NoEntityFilter(), null, new DummyLinkBack(), s1, topkS1, s2, topkS2, s3, topkS3, ws, c); } public static SmaphAnnotator getSmaph(SmaphVersion v, WikipediaInterface wikiApi, WikipediaToFreebase wikiToFreeb, WATAnnotator auxAnnotator, EntityToAnchors e2a, boolean includeS2, Websearch ws, SmaphConfig c) throws FileNotFoundException, ClassNotFoundException, IOException { URL model = getDefaultModel(v, ws, true, includeS2, true, -1); URL zscore = getDefaultZscoreNormalizer(v, ws, true, includeS2, true, -1); SmaphAnnotator a = null; switch (v) { case ANNOTATION_REGRESSOR: { AnnotationRegressor ar = getCachedAnnotationRegressor(model); FeatureNormalizer fn = getCachedFeatureNormalizer(zscore, new GreedyFeaturePack()); a = getDefaultSmaphParam(wikiApi, wikiToFreeb, auxAnnotator, e2a, new NoEntityFilter(), null, new AdvancedIndividualLinkback(ar, fn, wikiApi, wikiToFreeb, e2a, DEFAULT_ANCHOR_MENTION_ED), true, includeS2, true, ws, c); } break; case ENTITY_FILTER: { EntityFilter ef = getCachedSvmEntityFilter(model); FeatureNormalizer norm = getCachedFeatureNormalizer(zscore, new EntityFeaturePack()); a = getDefaultSmaphParam(wikiApi, wikiToFreeb, auxAnnotator, e2a, ef, norm, new DummyLinkBack(), true, includeS2, true, ws, c); } break; case COLLECTIVE: { BindingRegressor bindingRegressor = getCachedBindingRegressor(model); CollectiveLinkBack lb = new CollectiveLinkBack(wikiApi, wikiToFreeb, e2a, new DefaultBindingGenerator(), bindingRegressor, new NoFeatureNormalizer()); a = getDefaultSmaphParam(wikiApi, wikiToFreeb, auxAnnotator, e2a, new NoEntityFilter(), null, lb, true, includeS2, true, ws, c); } break; case GREEDY: { List<AnnotationRegressor> regressors = new Vector<>(); List<FeatureNormalizer> fns = new Vector<>(); int nGreedySteps = 0; while (getDefaultModel(v, ws, true, includeS2, true, nGreedySteps) != null) nGreedySteps++; if (nGreedySteps == 0) throw new IllegalArgumentException("Could not find models."); for (int i = 0; i < nGreedySteps; i++) { URL modelI = getDefaultModel(v, ws, true, includeS2, true, i); URL zscoreI = getDefaultZscoreNormalizer(v, ws, true, includeS2, true, i); AnnotationRegressor arI = getCachedAnnotationRegressor(modelI); FeatureNormalizer fnI = getCachedFeatureNormalizer(zscoreI, new GreedyFeaturePack()); regressors.add(arI); fns.add(fnI); } GreedyLinkback lbGreedy = new GreedyLinkback(regressors, fns, wikiApi, wikiToFreeb, e2a, DEFAULT_ANCHOR_MENTION_ED); a = getDefaultSmaphParam(wikiApi, wikiToFreeb, auxAnnotator, e2a, new NoEntityFilter(), null, lbGreedy, true, includeS2, true, ws, c); } break; default: throw new NotImplementedException(); } a.appendName(String.format(" - %s, %s%s", v, ws, includeS2 ? "" : ", excl. S2")); return a; } private static AnnotationRegressor getCachedAnnotationRegressor(URL model) { if (!urlToAnnotationRegressor.containsKey(model)) urlToAnnotationRegressor.put(model, LibSvmAnnotationRegressor.fromUrl(model)); return urlToAnnotationRegressor.get(model); } private static EntityFilter getCachedSvmEntityFilter(URL model) throws IOException { if (!urlToEntityFilter.containsKey(model)) urlToEntityFilter.put(model, LibSvmEntityFilter.fromUrl(model)); return urlToEntityFilter.get(model); } private static <T> FeatureNormalizer getCachedFeatureNormalizer(URL zscore, FeaturePack<T> fp) { if (!urlToNormalizer.containsKey(zscore)) urlToNormalizer.put(zscore, ZScoreFeatureNormalizer.fromUrl(zscore, fp)); return urlToNormalizer.get(zscore); } private static BindingRegressor getCachedBindingRegressor(URL model) throws IOException { if (!urlToBindingRegressor.containsKey(model)) urlToBindingRegressor.put(model, RankLibBindingRegressor.fromUrl(model)); return urlToBindingRegressor.get(model); } public static SmaphAnnotator getSmaph(SmaphVersion v, WikipediaInterface wikiApi, WikipediaToFreebase wikiToFreeb, WATAnnotator auxAnnotator, EntityToAnchors e2a, SmaphConfig c) throws FileNotFoundException, ClassNotFoundException, IOException { return getSmaph(v, wikiApi, wikiToFreeb, auxAnnotator, e2a, false, DEFAULT_WEBSEARCH, c); } public static String getDefaultLabel(SmaphVersion v, Websearch ws, boolean s1, boolean s2, boolean s3) { return getSourceLabel(v, ws, s1 ? DEFAULT_NORMALSEARCH_RESULTS : 0, s2 ? DEFAULT_WIKISEARCH_RESULTS : 0, s3 ? DEFAULT_ANNOTATED_SNIPPETS : 0); } private static URL getBestModelFileBase(String label, String extension, int greedyStep) { String stepStr = greedyStep < 0 ? "" : String.format("_%d", greedyStep); return SmaphBuilder.class.getClassLoader().getResource(String.format("models/best_%s%s.%s", label, stepStr, extension)); } private static URL getDefaultModel(SmaphVersion v, Websearch ws, boolean s1, boolean s2, boolean s3, int greedyStep) { return getBestModelFileBase(getDefaultLabel(v, ws, s1, s2, s3), "model", greedyStep); } public static URL getDefaultZscoreNormalizer(SmaphVersion v, Websearch ws, boolean s1, boolean s2, boolean s3, int greedyStep) { return getBestModelFileBase(getDefaultLabel(v, ws, s1, s2, s3), "zscore", greedyStep); } public static URL getModel(SmaphVersion v, Websearch ws, int topKS1, int topKS2, int topKS3, int greedyStep) { return getBestModelFileBase(getSourceLabel(v, ws, topKS1, topKS2, topKS3), "model", greedyStep); } public static URL getZscoreNormalizer(SmaphVersion v, Websearch ws, int topKS1, int topKS2, int topKS3, int greedyStep) { return getBestModelFileBase(getSourceLabel(v, ws, topKS1, topKS2, topKS3), "zscore", greedyStep); } public static String getSourceLabel(SmaphVersion v, Websearch ws, int topKS1, int topKS2, int topKS3) { return String.format("%s_%s-S1=%d_S2=%d_S3=%d", v, ws, topKS1, topKS2, topKS3); } public static File getModelFile(SmaphVersion v, Websearch ws, int topKS1, int topKS2, int topKS3, int step) { String label = getSourceLabel(v, ws, topKS1, topKS2, topKS3); String stepStr = step < 0 ? "" : String.format("_%d", step); return Paths.get("src", "main", "resources", "models", String.format("best_%s%s.model", label, stepStr)).toFile(); } public static File getModelFile(SmaphVersion v, Websearch ws, int topKS1, int topKS2, int topKS3) { return getModelFile(v, ws, topKS1, topKS2, topKS3, -1); } public static File getZscoreNormalizerFile(SmaphVersion v, Websearch ws, int topKS1, int topKS2, int topKS3, int step) { String label = getSourceLabel(v, ws, topKS1, topKS2, topKS3); String stepStr = step == -1 ? "" : String.format("_%d", step); return Paths.get("src", "main", "resources", "models", String.format("best_%s%s.zscore", label, stepStr)).toFile(); } public static File getZscoreNormalizerFile(SmaphVersion v, Websearch ws, int topKS1, int topKS2, int topKS3) { return getZscoreNormalizerFile(v, ws, topKS1, topKS2, topKS3, -1); } }
package jenkins.plugins.git; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardCredentials; import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials; import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.EnvVars; import hudson.Extension; import hudson.model.Item; import hudson.model.TaskListener; import hudson.plugins.git.BranchSpec; import hudson.plugins.git.GitException; import hudson.plugins.git.GitSCM; import hudson.plugins.git.GitTool; import hudson.plugins.git.UserRemoteConfig; import hudson.remoting.VirtualChannel; import hudson.scm.SCM; import hudson.security.ACL; import hudson.util.LogTaskListener; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.URISyntaxException; import java.util.Arrays; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.logging.Level; import java.util.logging.Logger; import jenkins.scm.api.SCMFile; import jenkins.scm.api.SCMFileSystem; import jenkins.scm.api.SCMHead; import jenkins.scm.api.SCMRevision; import jenkins.scm.api.SCMSource; import org.apache.commons.lang.StringUtils; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.URIish; import org.jenkinsci.plugins.gitclient.ChangelogCommand; import org.jenkinsci.plugins.gitclient.Git; import org.jenkinsci.plugins.gitclient.GitClient; import org.jenkinsci.plugins.gitclient.RepositoryCallback; /** * Base implementation of {@link SCMFileSystem}. * * @since FIXME */ public class GitSCMFileSystem extends SCMFileSystem { /** * Our logger. */ private static final Logger LOGGER = Logger.getLogger(GitSCMFileSystem.class.getName()); private final String cacheEntry; private final TaskListener listener; private final String remote; private final String head; private final GitClient client; private final ObjectId commitId; /** * Constructor. * * @param client the client * @param remote the remote GIT URL * @param head identifier for the head commit to be referenced * @param rev the revision. * @throws IOException on I/O error * @throws InterruptedException on thread interruption */ protected GitSCMFileSystem(GitClient client, String remote, final String head, @CheckForNull AbstractGitSCMSource.SCMRevisionImpl rev) throws IOException, InterruptedException { super(rev); this.remote = remote; this.head = head; cacheEntry = AbstractGitSCMSource.getCacheEntry(remote); listener = new LogTaskListener(LOGGER, Level.FINER); this.client = client; commitId = rev == null ? invoke(new FSFunction<ObjectId>() { @Override public ObjectId invoke(Repository repository) throws IOException, InterruptedException { return repository.getRef(head).getObjectId(); } }) : ObjectId.fromString(rev.getHash()); } @Override public AbstractGitSCMSource.SCMRevisionImpl getRevision() { return (AbstractGitSCMSource.SCMRevisionImpl) super.getRevision(); } @Override public long lastModified() throws IOException, InterruptedException { return invoke(new FSFunction<Long>() { @Override public Long invoke(Repository repository) throws IOException { try (RevWalk walk = new RevWalk(repository)) { RevCommit commit = walk.parseCommit(commitId); return TimeUnit.SECONDS.toMillis(commit.getCommitTime()); } } }); } @NonNull @Override public SCMFile getRoot() { return new GitSCMFile(this); } /*package*/ ObjectId getCommitId() { return commitId; } /** * Called with an {@link FSFunction} callback with a singleton repository * cache lock. * * An example usage might be: * * <blockquote><pre>{@code * return fs.invoke(new GitSCMFileSystem.FSFunction<byte[]>() { * public byte[] invoke(Repository repository) throws IOException, InterruptedException { * Git activeRepo = getClonedRepository(repository); * File repoDir = activeRepo.getRepository().getDirectory().getParentFile(); * System.out.println("Repo cloned to: " + repoDir.getCanonicalPath()); * try { * File f = new File(repoDir, filePath); * if (f.canRead()) { * return IOUtils.toByteArray(new FileInputStream(f)); * } * return null; * } finally { * FileUtils.deleteDirectory(repoDir); * } * } * }); * }</pre></blockquote> * * @param <V> return type * @param function callback executed with a locked repository * @return whatever you return from the provided function * @throws IOException if there is an I/O error * @throws InterruptedException if interrupted */ public <V> V invoke(final FSFunction<V> function) throws IOException, InterruptedException { Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry); cacheLock.lock(); try { File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry); if (cacheDir == null || !cacheDir.isDirectory()) { throw new IOException("Closed"); } return client.withRepository(new RepositoryCallback<V>() { @Override public V invoke(Repository repository, VirtualChannel virtualChannel) throws IOException, InterruptedException { return function.invoke(repository); } }); } finally { cacheLock.unlock(); } } @Override public boolean changesSince(@CheckForNull SCMRevision revision, @NonNull OutputStream changeLogStream) throws UnsupportedOperationException, IOException, InterruptedException { AbstractGitSCMSource.SCMRevisionImpl rev = getRevision(); if (rev == null ? revision == null : rev.equals(revision)) { // special case where somebody is asking one of two stupid questions: // 1. what has changed between the latest and the latest // 2. what has changed between the current revision and the current revision return false; } Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry); cacheLock.lock(); try { File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry); if (cacheDir == null || !cacheDir.isDirectory()) { throw new IOException("Closed"); } boolean executed = false; ChangelogCommand changelog = client.changelog(); try (Writer out = new OutputStreamWriter(changeLogStream, "UTF-8")) { changelog.includes(commitId); ObjectId fromCommitId; if (revision instanceof AbstractGitSCMSource.SCMRevisionImpl) { fromCommitId = ObjectId.fromString(((AbstractGitSCMSource.SCMRevisionImpl) revision).getHash()); changelog.excludes(fromCommitId); } else { fromCommitId = null; } changelog.to(out).max(GitSCM.MAX_CHANGELOG).execute(); executed = true; return !commitId.equals(fromCommitId); } catch (GitException ge) { throw new IOException("Unable to retrieve changes", ge); } finally { if (!executed) { changelog.abort(); } changeLogStream.close(); } } finally { cacheLock.unlock(); } } /** * Simple callback that is used with * {@link #invoke(jenkins.plugins.git.GitSCMFileSystem.FSFunction)} * in order to provide a locked view of the Git repository * @param <V> the return type */ public interface FSFunction<V> { /** * Called with a lock on the repository in order to perform some * operations that might result in changes and necessary re-indexing * @param repository the bare git repository * @return value to return from {@link #invoke(jenkins.plugins.git.GitSCMFileSystem.FSFunction)} * @throws IOException if there is an I/O error * @throws InterruptedException if interrupted */ V invoke(Repository repository) throws IOException, InterruptedException; } @Extension(ordinal = Short.MIN_VALUE) public static class BuilderImpl extends SCMFileSystem.Builder { @Override public boolean supports(SCM source) { return source instanceof GitSCM && ((GitSCM) source).getUserRemoteConfigs().size() == 1 && ((GitSCM) source).getBranches().size() == 1 && ((GitSCM) source).getBranches().get(0).getName().matches( "^((\\Q" + Constants.R_HEADS + "\\E.*)|([^/]+)|(\\*/[^/*]+))$" ); // we only support where the branch spec is obvious } @Override public boolean supports(SCMSource source) { return source instanceof AbstractGitSCMSource; } @Override public SCMFileSystem build(@NonNull Item owner, @NonNull SCM scm, @CheckForNull SCMRevision rev) throws IOException, InterruptedException { if (rev != null && !(rev instanceof AbstractGitSCMSource.SCMRevisionImpl)) { return null; } TaskListener listener = new LogTaskListener(LOGGER, Level.FINE); GitSCM gitSCM = (GitSCM) scm; UserRemoteConfig config = gitSCM.getUserRemoteConfigs().get(0); BranchSpec branchSpec = gitSCM.getBranches().get(0); String remote = config.getUrl(); String cacheEntry = AbstractGitSCMSource.getCacheEntry(remote); Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry); cacheLock.lock(); try { File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry); Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir); GitTool tool = gitSCM.resolveGitTool(listener); if (tool != null) { git.using(tool.getGitExe()); } GitClient client = git.getClient(); String credentialsId = config.getCredentialsId(); if (credentialsId != null) { StandardCredentials credential = CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentials( StandardUsernameCredentials.class, owner, ACL.SYSTEM, URIRequirementBuilder.fromUri(remote).build() ), CredentialsMatchers.allOf( CredentialsMatchers.withId(credentialsId), GitClient.CREDENTIALS_MATCHER ) ); client.addDefaultCredentials(credential); CredentialsProvider.track(owner, credential); } if (!client.hasGitRepo()) { listener.getLogger().println("Creating git repository in " + cacheDir); client.init(); } String remoteName = StringUtils.defaultIfBlank(config.getName(), Constants.DEFAULT_REMOTE_NAME); listener.getLogger().println("Setting " + remoteName + " to " + remote); client.setRemoteUrl(remoteName, remote); listener.getLogger().println("Fetching & pruning " + remoteName + "..."); URIish remoteURI = null; try { remoteURI = new URIish(remoteName); } catch (URISyntaxException ex) { listener.getLogger().println("URI syntax exception for '" + remoteName + "' " + ex); } String headName; if (rev != null) { headName = rev.getHead().getName(); } else { if (branchSpec.getName().startsWith(Constants.R_HEADS)) { headName = branchSpec.getName().substring(Constants.R_HEADS.length()); } else if (branchSpec.getName().startsWith("*/")) { headName = branchSpec.getName().substring(2); } else { headName = branchSpec.getName(); } } client.fetch_().prune().from(remoteURI, Arrays .asList(new RefSpec( "+" + Constants.R_HEADS + headName + ":" + Constants.R_REMOTES + remoteName + "/" + headName))).execute(); listener.getLogger().println("Done."); return new GitSCMFileSystem(client, remote, Constants.R_REMOTES + remoteName + "/" +headName, (AbstractGitSCMSource.SCMRevisionImpl) rev); } finally { cacheLock.unlock(); } } @Override public SCMFileSystem build(@NonNull SCMSource source, @NonNull SCMHead head, @CheckForNull SCMRevision rev) throws IOException, InterruptedException { if (rev != null && !(rev instanceof AbstractGitSCMSource.SCMRevisionImpl)) { return null; } TaskListener listener = new LogTaskListener(LOGGER, Level.FINE); AbstractGitSCMSource gitSCMSource = (AbstractGitSCMSource) source; GitSCMBuilder<?> builder = gitSCMSource.newBuilder(head, rev); String cacheEntry = gitSCMSource.getCacheEntry(); Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry); cacheLock.lock(); try { File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry); Git git = Git.with(listener, new EnvVars(EnvVars.masterEnvVars)).in(cacheDir); GitTool tool = gitSCMSource.resolveGitTool(builder.gitTool()); if (tool != null) { git.using(tool.getGitExe()); } GitClient client = git.getClient(); client.addDefaultCredentials(gitSCMSource.getCredentials()); if (!client.hasGitRepo()) { listener.getLogger().println("Creating git repository in " + cacheDir); client.init(); } String remoteName = builder.remoteName(); listener.getLogger().println("Setting " + remoteName + " to " + gitSCMSource.getRemote()); client.setRemoteUrl(remoteName, gitSCMSource.getRemote()); listener.getLogger().println("Fetching & pruning " + remoteName + "..."); URIish remoteURI = null; try { remoteURI = new URIish(remoteName); } catch (URISyntaxException ex) { listener.getLogger().println("URI syntax exception for '" + remoteName + "' " + ex); } client.fetch_().prune().from(remoteURI, builder.asRefSpecs()).execute(); listener.getLogger().println("Done."); return new GitSCMFileSystem(client, gitSCMSource.getRemote(), Constants.R_REMOTES+remoteName+"/"+head.getName(), (AbstractGitSCMSource.SCMRevisionImpl) rev); } finally { cacheLock.unlock(); } } } }
package me.rkfg.xmpp.bot.plugins.game; import static me.rkfg.xmpp.bot.plugins.game.misc.Attrs.*; import static me.rkfg.xmpp.bot.plugins.game.misc.Utils.*; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Optional; import me.rkfg.xmpp.bot.Main; import me.rkfg.xmpp.bot.plugins.game.effect.AbstractEffectReceiver; import me.rkfg.xmpp.bot.plugins.game.effect.AmbushFatigueEffect; import me.rkfg.xmpp.bot.plugins.game.effect.BattleFatigueEffect; import me.rkfg.xmpp.bot.plugins.game.effect.DeadEffect; import me.rkfg.xmpp.bot.plugins.game.effect.EquipRedirectorEffect; import me.rkfg.xmpp.bot.plugins.game.effect.ExpiringBonusPointsEffect; import me.rkfg.xmpp.bot.plugins.game.effect.HideFatigueEffect; import me.rkfg.xmpp.bot.plugins.game.effect.IEffect; import me.rkfg.xmpp.bot.plugins.game.effect.LootEffect; import me.rkfg.xmpp.bot.plugins.game.effect.SearchFatigueEffect; import me.rkfg.xmpp.bot.plugins.game.effect.SpeechFatigueEffect; import me.rkfg.xmpp.bot.plugins.game.effect.StaminaRegenEffect; import me.rkfg.xmpp.bot.plugins.game.effect.trait.BattleAuraEffect; import me.rkfg.xmpp.bot.plugins.game.event.EquipEvent; import me.rkfg.xmpp.bot.plugins.game.event.UnequipEvent; import me.rkfg.xmpp.bot.plugins.game.exception.NotEquippableException; import me.rkfg.xmpp.bot.plugins.game.item.IArmor; import me.rkfg.xmpp.bot.plugins.game.item.IItem; import me.rkfg.xmpp.bot.plugins.game.item.IMutableSlot; import me.rkfg.xmpp.bot.plugins.game.item.ISlot; import me.rkfg.xmpp.bot.plugins.game.item.IWeapon; import me.rkfg.xmpp.bot.plugins.game.item.Slot; import me.rkfg.xmpp.bot.plugins.game.misc.Attrs.GamePlayerState; import me.rkfg.xmpp.bot.plugins.game.misc.IMutableStats; import me.rkfg.xmpp.bot.plugins.game.misc.TypedAttribute; import me.rkfg.xmpp.bot.plugins.game.misc.TypedAttributeMap; public class Player extends AbstractEffectReceiver implements IMutablePlayer, IMutableStats { public static final int BASE_BONUS_POINTS = 5; public static final int BASE_LCK = 10; public static final int BASE_PRT = 5; public static final int BASE_STR = 5; public static final int BASE_DEF = 10; public static final int BASE_ATK = 10; public static final int BASE_HP = 30; public static final int BONUS_EXPIRATON_TICKS = 8; public static final int BASE_STM = 15; private static final String UNNAMED = "<безымянный>"; public static final int BATTLE_FATIGUE_COST = 5; public static final int AMBUSH_FATIGUE_COST = 5; public static final int HIDE_FATIGUE_COST = 2; public static final int SEARCH_FATIGUE_COST = 4; public static final int YELL_FATIGUE_COST = 2; public static final int WHISPER_FATIGUE_COST = 1; private class LogEntry { String message; public LogEntry(String message) { this.message = message; } @Override public String toString() { return message; } } private List<LogEntry> log = new LinkedList<>(); private TypedAttributeMap stats = new TypedAttributeMap(); private TypedAttributeMap equipment = new TypedAttributeMap(); private String id; private String roomId = ""; private String name = UNNAMED; private List<IItem> backpack = new ArrayList<>(); public Player(String id) { this.id = id; setState(GamePlayerState.NONE); } @Override public boolean isAlive() { return !hasEffect(DeadEffect.TYPE); } @Override public String getId() { return id; } @Override public void setId(String id) { this.id = id; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public void dumpStats() { StringBuilder sb = new StringBuilder("Статы: "); final String statsStr = STATS.stream().map(attr -> stats.get(attr).map(stat -> { Integer modStat = applyWeaponArmorStats(stat, attr); return attr.getName() + ": " + (modStat.equals(stat) ? stat : modStat + " (" + stat + ")"); })).filter(Optional::isPresent).map(Optional::get).reduce(pipeReducer).orElse("нет стат"); sb.append(statsStr); stats.get(BONUS_POINTS).filter(p -> p > 0).ifPresent(p -> sb.append(" | Бонусные очки: ").append(p)); final String effectsStr = listEffects().stream().filter(IEffect::isVisible) .map(effect -> effect.getDescription().orElse(effect.getType())).reduce(pipeReducer).orElse("нет эффектов"); sb.append("\nЭффекты: ").append(effectsStr); final String slotsStr = SLOTS.stream() .map(slotAttr -> equipment.get(slotAttr) .map(s -> String.format("%s: %s", s.getDescription().orElse(""), s.getItem().flatMap(i -> i.getDescription(Verbosity.WITH_PARAMS)).orElse("пусто"))) .orElse("")) .reduce(pipeReducer).orElse("нет слотов"); sb.append("\nСлоты: ").append(slotsStr); log(sb.toString()); } private Integer applyWeaponArmorStats(Integer stat, TypedAttribute<Integer> attr) { if (attr == ATK) { stat += getWeapon().map(IWeapon::getAttack).orElse(0); } if (attr == DEF) { stat += getWeapon().map(IWeapon::getDefence).orElse(0) + getArmor().map(IArmor::getDefence).orElse(0); } if (attr == STR) { stat += getWeapon().map(IWeapon::getStrength).orElse(0); } if (attr == PRT) { stat += getArmor().map(IArmor::getProtection).orElse(0); } return stat; } @Override public String getLog() { StringBuilder sb = new StringBuilder(); for (LogEntry logEntry : log) { sb.append(logEntry.toString()).append("\n"); } log.clear(); return sb.toString(); } @Override public void flushLogs() { final String logStr = getLog(); if (!logStr.isEmpty()) { Main.INSTANCE.sendMessage(logStr, roomId); } } @Override public void log(String message) { log.add(new LogEntry(message)); } @Override public void setDead(boolean dead) { final boolean alreadyDead = hasEffect(DeadEffect.TYPE); if (alreadyDead != dead) { if (dead) { enqueueAttachEffect(new DeadEffect()); } else { enqueueDetachEffect(DeadEffect.TYPE); } } } @SuppressWarnings("unchecked") @Override public <T extends IGameObject> Optional<T> as(TypedAttribute<T> type) { if (type == PLAYER_OBJ || type == MUTABLEPLAYER_OBJ || type == STATS_OBJ || type == MUTABLESTATS_OBJ) { return Optional.of((T) this); } return Optional.empty(); } @Override public Optional<ISlot> getSlot(TypedAttribute<ISlot> slot) { return equipment.get(slot); } @Override public void equipItem(IItem item) { TypedAttribute<ISlot> slotAttr = item.getFittingSlot().orElseThrow(NotEquippableException::new); Optional<IMutableSlot> slot = equipment.get(slotAttr).map(s -> (s instanceof IMutableSlot) ? (IMutableSlot) s : null); if (!slot.isPresent()) { throw new NotEquippableException(String.format("слот [%s] не найден", slotAttr.getName())); } slot.ifPresent(s -> { Optional<IItem> itemInSlot = s.getItem(); itemInSlot.ifPresent(i -> { throw new NotEquippableException(String.format("слот [%s] уже занят предметом [%s]", s.getDescription().orElse("неизвестный"), i.getDescription().orElse("неизвестно"))); }); s.setItem(item); item.setOwner(this); }); } @Override public void unequipItem(TypedAttribute<ISlot> slotAttr) { equipment.get(slotAttr).map(s -> (s instanceof IMutableSlot) ? (IMutableSlot) s : null).ifPresent(s -> s.setItem(null)); } @Override public List<IItem> getBackpack() { return Collections.unmodifiableList(backpack); } @Override public void putItemToBackpack(IItem item) { backpack.add(item); item.setOwner(this); } @Override public void removeFromBackpack(IItem item) { backpack.remove(item); } @Override public boolean enqueueEquipItem(IItem item) { if (!item.getFittingSlot().map(this::enqueueUnequipItem).orElse(true)) { return false; } final EquipEvent equipEvent = new EquipEvent(item); if (enqueueEvent(equipEvent)) { equipEvent.equip(); if (!equipEvent.isCancelled()) { removeFromBackpack(item); return true; } } return false; } @Override public boolean enqueueUnequipItem(TypedAttribute<ISlot> slot) { return getSlot(slot).flatMap(ISlot::getItem).map(i -> { final UnequipEvent event = new UnequipEvent(slot); if (enqueueEvent(event)) { event.unequip(); if (!event.isCancelled()) { putItemToBackpack(i); return true; } } return false; }).orElse(true); } @Override public TypedAttributeMap getAttrs() { return stats; } @Override public void reset() { resetEffects(); stats = new TypedAttributeMap(); equipment = new TypedAttributeMap(); backpack = new ArrayList<>(); name = UNNAMED; stats.put(HP, BASE_HP); stats.put(ATK, BASE_ATK); stats.put(DEF, BASE_DEF); stats.put(STR, BASE_STR); stats.put(PRT, BASE_PRT); stats.put(LCK, BASE_LCK); stats.put(STM, BASE_STM); stats.put(BONUS_POINTS, BASE_BONUS_POINTS); equipment.put(WEAPON_SLOT, new Slot("держит в руках")); equipment.put(ARMOR_SLOT, new Slot("одет в")); enqueueAttachEffect(new BattleFatigueEffect(BATTLE_FATIGUE_COST)); enqueueAttachEffect(new HideFatigueEffect(HIDE_FATIGUE_COST)); enqueueAttachEffect(new SearchFatigueEffect(SEARCH_FATIGUE_COST)); enqueueAttachEffect(new AmbushFatigueEffect(AMBUSH_FATIGUE_COST)); enqueueAttachEffect(new StaminaRegenEffect()); enqueueAttachEffect(new EquipRedirectorEffect()); enqueueAttachEffect(new LootEffect()); enqueueAttachEffect(new BattleAuraEffect()); enqueueAttachEffect(new SpeechFatigueEffect(YELL_FATIGUE_COST, WHISPER_FATIGUE_COST)); enqueueAttachEffect(new ExpiringBonusPointsEffect(5, BONUS_EXPIRATON_TICKS)); setState(GamePlayerState.PLAYING); } @Override public void setState(GamePlayerState state) { setAttribute(READY, state); } @Override public GamePlayerState getState() { return getAttribute(READY).orElse(GamePlayerState.NONE); } @Override public void setRoomId(String roomId) { this.roomId = roomId; } @Override public String getRoomId() { return roomId; } @Override public Optional<String> getDescription() { Optional<String> description = listEffects().stream().map(e -> capitalize(e.getDescription(Verbosity.VERBOSE).orElse(""))) .filter(s -> !s.isEmpty()).reduce((a, s) -> { if (a.endsWith(".")) { return a + " " + s; } return a + ". " + s; }); if (!description.isPresent()) { return Optional.of("Об этом персонаже нельзя сказать ничего особенного."); } return description; } }
import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.net.InetAddress; import java.util.Observable; import java.util.Observer; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; //TODO : change the System.out.println with appropriate log event /** * This class holds the GUI part of the applet. It creates the GUI objects : * button, fields, label and the ping globe and is responsible for their drawing * * @author RaphaelBonaque */ public class PingsGUI implements ActionListener { private PingsApplet applet; //GUI related variables, they holds the GUI components private JButton pause_button, rename_button ; private JLabel pings_counter_display, client_info_display; private JTextField nickname_field; private PingsGlobe ping_globe; private Container button_container; private Color text_color = new Color(70,70,70); private Color background_color = new Color(0,0,0); //GUI component for the retry private JTextArea retry_message; private JButton retry_button; //State variables private int pings_counter = 0; private GeoipInfo client_geoip_info = null; //The observers of the subclients that add pings effect on the globe // see ClientThreadObserver for more details private clientThreadObserver[][] clients_observers; //Some strings private String pause_tooltip = "Pause the application once the current pings are done."; private String resume_tooltip = "Resume the application."; /** * Create and initialize the components of the GUI. * <p> * That is :the globe , one pause/resume button and a field to change the * client's nickname. * The globe is turnable, zoomable and show an effect for pings * The buttons comes with tooltips and shortcuts. */ PingsGUI (PingsApplet parent) { applet = parent; applet.setBackground(background_color); //Recover the content and background of the applet to add components button_container = applet.getContentPane(); button_container.setBackground (background_color); button_container.setLayout(null); //Add the pause/resume button to the applet pause_button = new JButton ("Pause"); pause_button.setMnemonic(KeyEvent.VK_P); pause_button.setToolTipText(pause_tooltip); pause_button.setActionCommand("pause"); pause_button.addActionListener(this); button_container.add (pause_button); //Add the button to change the nickname rename_button = new JButton ("Change"); rename_button.setMnemonic(KeyEvent.VK_U); rename_button.setToolTipText("Update your name for the leaderboard"); rename_button.setActionCommand("rename"); rename_button.addActionListener(this); rename_button.setEnabled(false); button_container.add (rename_button); //Add the field to change the nickname nickname_field = new JTextField(15); nickname_field.setText(applet.pings_clients[0].getNickname()); //Add a listener to able/disable the rename_button if the nickname is //different from the one stored nickname_field.getDocument().addDocumentListener( new DocumentListener() { public void changedUpdate(DocumentEvent e) { check_enable_button(); } public void insertUpdate(DocumentEvent e) { check_enable_button(); } public void removeUpdate(DocumentEvent e) { check_enable_button(); } }); //Add a listener to update the name when 'ENTER' key is hit nickname_field.addKeyListener( new KeyListener() { public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { rename_button.doClick(); } } }); button_container.add (nickname_field); //Add the display for the number of pings done pings_counter_display = new JLabel("No ping sent yet"); pings_counter_display.setForeground(text_color); button_container.add (pings_counter_display); //Add the display for the client info client_info_display = new JLabel(""); client_info_display.setForeground(text_color); button_container.add (client_info_display); //Add the globe ping_globe = new PingsGlobe(); ping_globe.resizeGlobe(Math.min(applet.getWidth(),applet.getHeight())); applet.getContentPane().add(ping_globe); //Create the component for the "retry view" but don't hook them to the applet retry_message = new JTextArea(""); retry_button = new JButton(); //Set the layout setLayout(); //Add an observer to refresh globe on resize applet.addComponentListener(new onResize()); //Add an observer to the client to update the GUI. clients_observers = new clientThreadObserver[applet.nb_clients][]; for (int i = 0; i < applet.nb_clients; i++) { PingsClient.subClient[] subClientsPool = applet.pings_clients[i].getSubClientsPoolCopy(); clients_observers[i] = new clientThreadObserver[subClientsPool.length]; for (int j = 0; j < subClientsPool.length; j++) { clients_observers[i][j] = new clientThreadObserver(); subClientsPool[j].addObserver(clients_observers[i][j]); } } } /** * Position the component of the GUI. * * Currently use absolute positioning to gather most of the component in the * top-left corner. */ private void setLayout() { //Set the globe to use the full space available ping_globe.setBounds(0, 0, applet.getWidth(), applet.getHeight()); //First raw of display Dimension name_size = nickname_field.getPreferredSize(); Dimension update_name_size = rename_button.getPreferredSize(); Dimension client_info_size = client_info_display.getPreferredSize(); int row_height = name_size.height; nickname_field.setBounds(5,5, name_size.width,row_height); rename_button.setBounds(8 + name_size.width, 5, update_name_size.width, row_height); client_info_display.setBounds(11 + name_size.width + update_name_size.width, 5, client_info_size.width,row_height ); //Second raw of display Dimension counter_size = pings_counter_display.getPreferredSize(); Dimension pause_size = pause_button.getMinimumSize(); pings_counter_display.setBounds(5, 8 + row_height, counter_size.width, row_height); pause_button.setBounds(8 + counter_size.width,8 + row_height, pause_size.width, row_height); retry_message.setBounds((applet.getWidth()/2)-200, (applet.getHeight()/2)-50, 400, 100); retry_button.setBounds((applet.getWidth()/2)-100, (applet.getHeight()/2)+50, 200, 50); } /** * Update the counter displaying the number of ping sent */ private void updatePingsCounterDisplay() { if (pings_counter == 0) { pings_counter_display.setText("No ping sent yet"); } else { pings_counter_display.setText(pings_counter + " ip tested"); } setLayout(); } private void updateClientInfoDisplay(String ip_address, GeoipInfo client_info) { String info_str = ": " + ip_address + " "; if (client_info.city != null && !client_info.city.equals("")) info_str += client_info.city + ", "; info_str += client_info.country; client_info_display.setText(info_str); ping_globe.setOrigin(client_info); setLayout(); applet.repaint(); } public void check_enable_button() { if (nickname_field.getText().equals(applet.pings_clients[0].getNickname())) { rename_button.setEnabled(false); } else { rename_button.setEnabled(true); } } class clientThreadObserver implements Observer { private PingsGlobe.PingGUI gui_effect = null; private InetAddress last_address = null ; public void update(Observable o, Object arg) { PingsClient.subClient client = (PingsClient.subClient)o; if (client.getSourceGeoip() != null) { if (!client.getSourceGeoip().equals(client_geoip_info)) { client_geoip_info = client.getSourceGeoip(); //FIXME: get ip from server SwingUtilities.invokeLater( new Runnable() { public void run() { updateClientInfoDisplay("", client_geoip_info); } }); } } GeoipInfo current_ping_geoip = client.getCurrentDestGeoip(); InetAddress current_ping_address = client.getCurrentPingDest(); //If there are several subClient threads then this might still be // reachable as they try to set the same geoip several times if (current_ping_address == null) return; //If there is a new ping add it to the counter and register an //effect for the globe if (gui_effect == null && last_address != current_ping_address) { last_address = current_ping_address; pings_counter++; SwingUtilities.invokeLater( new Runnable() { public void run() { updatePingsCounterDisplay(); } }); gui_effect = ping_globe.addPing(current_ping_geoip); } //Else if it's the last ping update it else if (gui_effect != null && last_address == current_ping_address) { gui_effect.updatePingGUIValue(client.getCurrentPingResult()); gui_effect = null; } //Else there are two case : //_ either the destination address is the same (and with the //current implementation there is no way to know it). This case has a //very low probability. //_ or we somehow missed the result of the previous ping, hence //we need to do some workaround for the old ping and declare a //new one. else { if (gui_effect != null) gui_effect.unknownError(); String value = client.getCurrentPingResult(); gui_effect = ping_globe.addPing(current_ping_geoip); if (value!= null && !value.equals("")) { gui_effect.updatePingGUIValue(client.getCurrentPingResult()); gui_effect = null; } } } } /** * This method is used to refresh the Pause/Resume button to make it show * 'Pause' or 'Resume' and act accordingly depending on the client state * expressed by the 'm_is_running' variable. * <p> * If the client is running this makes the button show "Pause" otherwise it * shows "Resume". */ private void refreshPauseButton() { if (!applet.pings_clients[0].isRunning()) { pause_button.setText("Resume"); pause_button.setToolTipText(resume_tooltip); pause_button.setActionCommand("resume"); } else { pause_button.setText("Pause"); pause_button.setToolTipText(pause_tooltip); pause_button.setActionCommand("pause"); } setLayout(); } /** * The listener for events in the applet : the interactions with the * components (other than the globe) are handled here. */ public void actionPerformed (ActionEvent event) { //Find the issued command and store it in the 'command' variable String command = event.getActionCommand(); //Handle the pause/resume button if (command.equals("pause")) { //Pause the client if it was running, do nothing otherwise boolean was_running = applet.pings_clients[0].isRunning(); //Issue a warning if the client was not running if (!was_running) { //System.out.println ("Was already paused."); } else { applet.stop(); } //Then refresh the button SwingUtilities.invokeLater( new Runnable() { public void run() { refreshPauseButton(); } }); } else if (command.equals("resume")) { //resume the client if it was paused, do nothing otherwise boolean was_running = applet.pings_clients[0].isRunning(); //Issue a warning if the client was running if (was_running) { //System.out.println ("Was already running."); } else { applet.start(); } //Then refresh the button SwingUtilities.invokeLater( new Runnable() { public void run() { refreshPauseButton(); } }); } //Handle the rename button else if (command.equals("rename")) { String new_name = nickname_field.getText(); for (int i = 0; i < applet.nb_clients; i++) { applet.pings_clients[i].setNickname(new_name); } SwingUtilities.invokeLater( new Runnable() { public void run() { rename_button.setEnabled(false); } }); System.out.println("Nick updated to " + new_name); } //Handle any other unknown component else { //FIXME System.out.println ("Error in button interface."); } } class onResize implements ComponentListener{ public void componentResized(ComponentEvent e) { ping_globe.forceRefresh(); SwingUtilities.invokeLater( new Runnable() { public void run() { setLayout(); } }); } public void componentShown(ComponentEvent e) {} public void componentHidden(ComponentEvent e) {} public void componentMoved(ComponentEvent e) {} } /** * Destroy as much of the GUI as possible. * <p> * It remove the components and unregister the observers of the clients, * for this reason it can fail is the client was destroyed before (hence the * 'try'). */ public void destroy() { try { ping_globe.removeAll(); button_container.removeAll(); for (int i = 0; i < applet.nb_clients; i++) { PingsClient.subClient[] subClientsPool = applet.pings_clients[i].getSubClientsPoolCopy(); for (int j = 0; j < subClientsPool.length; j++) { subClientsPool[j].deleteObserver(clients_observers[i][j]); } } } catch (Exception _) {} } private class CreateRetryInterface implements Runnable, ActionListener{ private String message; public CreateRetryInterface(String msg) { this.message = msg; } //Handle the retry button public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater( new Runnable() { public void run() { button_container.removeAll(); applet.restartApplet(); } }); } public void run() { button_container = applet.getContentPane(); button_container.setBackground (background_color); button_container.setLayout(null); retry_message.setText(message); retry_message.setForeground(text_color); retry_message.setBackground(background_color); retry_message.setLineWrap(true); retry_message.setEditable(false); button_container.add (retry_message); retry_button.setText("Retry"); retry_button.setMnemonic(KeyEvent.VK_R); retry_button.setToolTipText("Try to relaunch the application"); retry_button.setActionCommand("retry_connect"); retry_button.addActionListener(this); button_container.add (retry_button); setLayout(); applet.repaint(); } } public void createRetryInterface(String message) { SwingUtilities.invokeLater( new CreateRetryInterface(message)); } }
package mil.nga.geopackage.geom; import org.locationtech.proj4j.units.Units; import mil.nga.proj.Projection; import mil.nga.proj.ProjectionConstants; import mil.nga.proj.ProjectionFactory; import mil.nga.sf.Geometry; import mil.nga.sf.GeometryEnvelope; import mil.nga.sf.proj.GeometryTransform; import mil.nga.sf.util.GeometryUtils; /** * Geometry Crop utilities * * @author osbornb * @since 6.5.0 */ public class GeometryCrop { /** * Crop the geometry data with a world map envelope, defined in the provided * projection * * @param projection * geometry data and envelope projection * @param geometryData * geometry data */ public static void crop(Projection projection, GeoPackageGeometryData geometryData) { GeometryEnvelope envelope = envelope(projection); crop(projection, geometryData, envelope); } /** * Crop the geometry data with the envelope, both in the provided projection * * @param projection * geometry data and envelope projection * @param geometryData * geometry data * @param envelope * geometry envelope */ public static void crop(Projection projection, GeoPackageGeometryData geometryData, GeometryEnvelope envelope) { if (geometryData != null && !geometryData.isEmpty()) { Geometry geometry = geometryData.getGeometry(); Geometry bounded = crop(projection, geometry, envelope); geometryData.setGeometry(bounded); } } /** * Crop the geometry with a world map envelope, defined in the provided * projection * * @param projection * geometry and envelope projection * @param geometry * geometry * @return cropped geometry */ public static Geometry crop(Projection projection, Geometry geometry) { GeometryEnvelope envelope = envelope(projection); return crop(projection, geometry, envelope); } /** * Crop the geometry with the envelope, both in the provided projection * * @param projection * geometry and envelope projection * @param geometry * geometry * @param envelope * geometry envelope * @return cropped geometry */ public static Geometry crop(Projection projection, Geometry geometry, GeometryEnvelope envelope) { GeometryTransform transform = null; if (!projection.isUnit(Units.METRES)) { transform = new GeometryTransform(projection, ProjectionFactory .getProjection(ProjectionConstants.EPSG_WEB_MERCATOR)); GeometryUtils.boundWGS84Transformable(geometry); geometry = transform.transform(geometry); envelope = transform.transform(envelope); } Geometry cropped = GeometryUtils.crop(geometry, envelope); if (transform != null) { transform = transform.getInverseTransformation(); cropped = transform.transform(cropped); GeometryUtils.minimizeWGS84(cropped); } return cropped; } /** * Get a geometry envelope for the projection * * @param projection * projection * @return envelope */ public static GeometryEnvelope envelope(Projection projection) { GeometryEnvelope envelope = null; if (projection.isUnit(Units.METRES)) { envelope = GeometryUtils.webMercatorEnvelope(); } else { envelope = GeometryUtils.wgs84EnvelopeWithWebMercator(); } return envelope; } }
package net.dean.jraw.models; import com.fasterxml.jackson.databind.JsonNode; import net.dean.jraw.models.meta.JsonProperty; import net.dean.jraw.models.meta.Model; import java.text.NumberFormat; /** * Represents an account with additional information visible only to the logged-in user. */ @Model(kind = Model.Kind.ACCOUNT) public final class LoggedInAccount extends Account { /** Instantiates a new LoggedInAccount */ public LoggedInAccount(JsonNode data) { super(data); } /** Checks if the user has unread mail. */ @JsonProperty public Boolean hasMail() { return data("has_mail", Boolean.class); } /** Checks if the user has moderator mail */ @JsonProperty(nullable = true) public Boolean hasModMail() { return data("has_mod_mail", Boolean.class); } /** Checks if the user has a verified email */ @JsonProperty public Boolean hasVerifiedEmail() { return data("has_verified_email", Boolean.class); } /** Gets the amount of non-moderator mail the user has. */ @JsonProperty public Integer getInboxCount() { return data("inbox_count", Integer.class); } /** Gets the localized amount of non-moderator mail the user has. */ public String getLocalizedInboxCount() { try { return NumberFormat.getInstance().format(getInboxCount()); } catch (final IllegalArgumentException ex) { return null; } } /** Gets the amount of gold creddits (one month worth of reddit gold) the user has. */ @JsonProperty public Integer getCreddits() { return data("gold_creddits", Integer.class); } }
package net.moznion.micro.escape; /** * String escaper for HTML. */ public class HTMLEscaper { /** * Escape string for HTML. * * @param rawString raw string. If you give null, this method returns empty string. * @return escaped string. */ public static String escape(final String rawString) { if (rawString == null) { return ""; } // 6 (== "&quot;".length()) is a magic coefficient for performance! final StringBuilder sb = new StringBuilder(rawString.length() * 6); for (char c : rawString.toCharArray()) { switch (c) { case '&': sb.append("&amp;"); break; case '>': sb.append("&gt;"); break; case '<': sb.append("&lt;"); break; case '"': sb.append("&quot;"); break; case '\'': sb.append("& break; case '`': sb.append("& break; case '{': sb.append("&#123;"); break; case '}': sb.append("&#125;"); break; default: sb.append(c); } } return sb.toString(); } }
package net.osten.watermap.convert; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.Charset; import java.text.ParseException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.logging.Logger; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import net.osten.watermap.model.WaterReport; import net.osten.watermap.pct.xml.GpxType; import net.osten.watermap.pct.xml.WptType; import net.osten.watermap.util.RegexUtils; import org.apache.commons.lang3.time.FastDateFormat; import com.google.common.io.Files; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * Parser for PCT water report based on the PCT Google Sheets downloaded using the API. */ @Singleton @Startup public class PCTReport { private static final FastDateFormat dateFormatter = FastDateFormat.getInstance("M/dd/yy"); private static final String SOURCE_TITLE = "PCT Water Report"; private static final String SOURCE_URL = "http://pctwater.com/"; private String dataDir = null; private String[] stateChars = new String[] { "CA", "OR", "WA" }; private char[] sectionChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G' , 'M', 'N', 'O', 'P', 'Q', 'R'}; private List<WptType> waypoints = new ArrayList<WptType>(); private static Logger log = Logger.getLogger(PCTReport.class.getName()); /** * Default constructor. */ public PCTReport() { initialize(); } /** * Parse the PCT water report Google docs files. * * @return set of water reports */ public synchronized Set<WaterReport> convert() throws IOException { Set<WaterReport> results = new HashSet<WaterReport>(); log.info("dataDir=" + dataDir); // parse json files if (dataDir != null) { for (String stateChar : stateChars) { for (char sectionChar : sectionChars) { try { String fileName = "pct-" +stateChar + "-" + sectionChar + ".json"; File jsonFile = new File(dataDir + File.separator + fileName); if (jsonFile.exists() && jsonFile.canRead()) { log.info("reading json file " + jsonFile); String htmlSource = Files.toString(jsonFile, Charset.forName("UTF-8")); JsonParser parser = new JsonParser(); JsonElement root = parser.parse(htmlSource); log.info("json root is obj=" + root.isJsonObject()); results.addAll(parseDocument(root.getAsJsonObject())); } } catch (IOException e) { log.severe(e.getLocalizedMessage()); } } } } return results; } public void initialize() { log.info("initializing PCT report..."); setDataDir(System.getenv("OPENSHIFT_DATA_DIR")); // parse waypoints XML files if (dataDir != null) { for (String stateChar : stateChars) { for (char sectionChar : sectionChars) { try { JAXBContext jc = JAXBContext.newInstance("net.osten.watermap.pct.xml"); Unmarshaller u = jc.createUnmarshaller(); @SuppressWarnings("unchecked") GpxType waypointList = ((JAXBElement<GpxType>) u.unmarshal(new FileInputStream(dataDir + File.separator + stateChar + "_Sec_" + sectionChar + "_waypoints.gpx"))).getValue(); log.info("found " + waypointList.getWpt().size() + " waypoints for section " + sectionChar); waypoints.addAll(waypointList.getWpt()); } catch (JAXBException | IOException e) { log.severe(e.getLocalizedMessage()); } } } } log.info("imported " + waypoints.size() + " waypoints"); log.info("done initializing PCT report"); } /** * Sets the directory where the data files are. * * @param dataDir data directory */ public void setDataDir(String dataDir) { this.dataDir = dataDir; } /** * There are discrepencies between some of the water report names and the waypoint names. * * @param waterReportName name from the water report * @return mapped name in waypoint file */ private String fixNames(String waterReportName) { String result = null; if (waterReportName.equalsIgnoreCase("LkMorenaCG")) { result = "LakeMorenaCG"; } else if (waterReportName.equalsIgnoreCase("BoulderOaksCG")) { result = "BoulderOakCG"; } else if (waterReportName.equalsIgnoreCase("WRCS091")) { result = "WR091"; } else if (waterReportName.equalsIgnoreCase("WR016B")) { result = "WR106B"; } else if (waterReportName.equalsIgnoreCase("CS183B")) { result = "CS0183"; } else if (waterReportName.equalsIgnoreCase("Fuller Ridge")) { result = "FullerRidgeTH"; } else if (waterReportName.equalsIgnoreCase("WRCS219")) { result = "WhitewaterTr"; } else if (waterReportName.equalsIgnoreCase("WR233")) { result = "WR234"; } else if (waterReportName.equalsIgnoreCase("WR239")) { result = "WRCS0239"; } else if (waterReportName.equalsIgnoreCase("WR256")) { result = "WRCS056"; } return result; } private Set<WaterReport> parseDocument(JsonObject reportJson) { Set<WaterReport> results = new HashSet<WaterReport>(); log.info("json children=" + reportJson.getAsJsonArray("values").size()); JsonArray currentRow = null; for (JsonElement row : reportJson.getAsJsonArray("values")) { if (row.isJsonArray()) { currentRow = row.getAsJsonArray(); log.info("row has " + currentRow.size() + "elements"); if (currentRow.size() >= 6) { try { String waypoint = currentRow.get(2).getAsJsonPrimitive().getAsString(); String desc = currentRow.get(3).getAsJsonPrimitive().getAsString(); String rpt = currentRow.get(4).getAsJsonPrimitive().getAsString(); String date = currentRow.get(5).getAsJsonPrimitive().getAsString(); log.info("waypoint=" + waypoint); String[] names = waypoint.split(","); for (String name : names) { name = name.trim(); WaterReport report = processWaypoint(name, desc, date, rpt); if (report.getLat() == null) { // DEO try prefixing the name (this is for split names: "WR127,B") name = names[0] + name; report = processWaypoint(name, desc, date, rpt); if (report.getLat() == null) { log.info("cannot find coords for " + waypoint); } else { log.info("Adding " + report.toString()); results.add(report); } } else { log.info("Adding " + report.toString()); results.add(report); } } } catch (Exception e) { e.printStackTrace(); } } else { log.info("skipping row " + row.toString()); } } else { log.warning("row is not json array but " + row.getClass().getName()); } } log.info("returning " + results.size() + " pct reports"); return results; } private WaterReport processWaypoint(String waypoint, String desc, String date, String rpt) { log.finer("waypoint=" + waypoint); WaterReport report = new WaterReport(); report.setDescription(rpt); report.setLocation(desc); report.setName(waypoint); if (date != null && !date.isEmpty()) { try { report.setLastReport(dateFormatter.parse(date)); } catch (ParseException e) { log.severe(e.getLocalizedMessage()); } } report.setSource(SOURCE_TITLE); report.setUrl(SOURCE_URL); report.setState(WaterStateParser.parseState(rpt)); // TODO replace with something more elegant than this brute force search for (WptType wpt : waypoints) { if (wpt.getName().equalsIgnoreCase(waypoint)) { // System.out.println("found matching lat/lon"); report.setLat(wpt.getLat()); report.setLon(wpt.getLon()); break; } } // if coords not found, try adding leading 0 (e.g. WRCS292 -> WRCS0292) if (report.getLat() == null) { String modifiedWaypoint = RegexUtils.addLeadingZerosToWaypoint(waypoint); for (WptType wpt : waypoints) { if (wpt.getName().equalsIgnoreCase(modifiedWaypoint)) { // System.out.println("found matching lat/lon"); report.setLat(wpt.getLat()); report.setLon(wpt.getLon()); break; } } } // if coords not found, try with leading 0 in waypoint (i.e. WR0213); this happens in Section B waypoint file if (report.getLat() == null && waypoint.length() > 2) { String modifiedWaypoint = "WR0" + waypoint.substring(2); for (WptType wpt : waypoints) { if (wpt.getName().equalsIgnoreCase(modifiedWaypoint)) { // System.out.println("found matching lat/lon"); report.setLat(wpt.getLat()); report.setLon(wpt.getLon()); break; } } } // if coords still not found, try with mapped name if (report.getLat() == null) { String modifiedName = fixNames(report.getName()); for (WptType wpt : waypoints) { if (wpt.getName().equalsIgnoreCase(modifiedName)) { // System.out.println("found matching lat/lon"); report.setLat(wpt.getLat()); report.setLon(wpt.getLon()); break; } } } return report; } }
package openmods.utils; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraftforge.common.util.ForgeDirection; import openmods.utils.bitmap.IReadableBitMap; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class SidedInventoryAdapter implements ISidedInventory { private final IInventory inventory; private class SlotInfo { private final IReadableBitMap<ForgeDirection> sideFlags; private final boolean canInsert; private final boolean canExtract; private SlotInfo(IReadableBitMap<ForgeDirection> sideFlags, boolean canInsert, boolean canExtract) { this.sideFlags = sideFlags; this.canInsert = canInsert; this.canExtract = canExtract; } private boolean canAccessFromSide(ForgeDirection side) { return sideFlags.get(side); } } private final Map<Integer, SlotInfo> slots = Maps.newHashMap(); public SidedInventoryAdapter(IInventory inventory) { this.inventory = inventory; } public void registerSlot(Enum<?> slot, IReadableBitMap<ForgeDirection> sideFlags, boolean canInsert, boolean canExtract) { registerSlot(slot.ordinal(), sideFlags, canInsert, canExtract); } public void registerSlot(int slot, IReadableBitMap<ForgeDirection> sideFlags, boolean canInsert, boolean canExtract) { final int sizeInventory = inventory.getSizeInventory(); Preconditions.checkArgument(slot >= 0 && slot < sizeInventory, "Tried to register invalid slot: %s (inventory size: %s)", slot, sizeInventory); slots.put(slot, new SlotInfo(sideFlags, canInsert, canExtract)); } public void registerSlots(int start, int count, IReadableBitMap<ForgeDirection> sideFlags, boolean canInsert, boolean canExtract) { for (int i = start; i < start + count; i++) registerSlot(i, sideFlags, canInsert, canExtract); } public void registerAllSlots(IReadableBitMap<ForgeDirection> sideFlags, boolean canInsert, boolean canExtract) { for (int i = 0; i < inventory.getSizeInventory(); i++) registerSlot(i, sideFlags, canInsert, canExtract); } @Override public int getSizeInventory() { return inventory.getSizeInventory(); } @Override public ItemStack getStackInSlot(int i) { return inventory.getStackInSlot(i); } @Override public ItemStack decrStackSize(int i, int j) { return inventory.decrStackSize(i, j); } @Override public ItemStack getStackInSlotOnClosing(int i) { return inventory.getStackInSlotOnClosing(i); } @Override public void setInventorySlotContents(int i, ItemStack itemstack) { inventory.setInventorySlotContents(i, itemstack); } @Override public int getInventoryStackLimit() { return inventory.getInventoryStackLimit(); } @Override public boolean isUseableByPlayer(EntityPlayer entityplayer) { return inventory.isUseableByPlayer(entityplayer); } @Override public boolean isItemValidForSlot(int i, ItemStack itemstack) { return inventory.isItemValidForSlot(i, itemstack); } @Override public int[] getAccessibleSlotsFromSide(int side) { ForgeDirection dir = ForgeDirection.getOrientation(side); Set<Integer> result = Sets.newHashSet(); for (Entry<Integer, SlotInfo> entry : slots.entrySet()) { if (entry.getValue().canAccessFromSide(dir)) result.add(entry.getKey()); } int tmp[] = new int[result.size()]; int i = 0; for (Integer value : result) tmp[i++] = value; return tmp; } @Override public boolean canInsertItem(int slotIndex, ItemStack itemstack, int side) { ForgeDirection dir = ForgeDirection.getOrientation(side); SlotInfo slot = slots.get(slotIndex); if (slot == null) return false; return slot.canInsert && slot.canAccessFromSide(dir) && inventory.isItemValidForSlot(slotIndex, itemstack); } @Override public boolean canExtractItem(int slotIndex, ItemStack itemstack, int side) { ForgeDirection dir = ForgeDirection.getOrientation(side); SlotInfo slot = slots.get(slotIndex); if (slot == null) return false; return slot.canExtract && slot.canAccessFromSide(dir); } @Override public String getInventoryName() { return inventory.getInventoryName(); } @Override public boolean hasCustomInventoryName() { return inventory.hasCustomInventoryName(); } @Override public void markDirty() { inventory.markDirty(); } @Override public void openInventory() {} @Override public void closeInventory() {} }
package org.adridadou.ethereum; import static org.adridadou.ethereum.values.EthValue.wei; import java.math.BigInteger; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import org.adridadou.ethereum.converters.input.InputTypeHandler; import org.adridadou.ethereum.converters.output.OutputTypeHandler; import org.adridadou.ethereum.event.*; import org.adridadou.ethereum.values.*; import org.adridadou.exception.EthereumApiException; import org.ethereum.core.CallTransaction; import org.ethereum.util.ByteUtil; import rx.Observable; public class EthereumProxy { private static final long BLOCK_WAIT_LIMIT = 16; private final EthereumBackend ethereum; private final EthereumEventHandler eventHandler; private final Map<EthAddress, Set<EthHash>> pendingTransactions = new ConcurrentHashMap<>(); private final Map<EthAddress, BigInteger> nonces = new ConcurrentHashMap<>(); private final InputTypeHandler inputTypeHandler; private final OutputTypeHandler outputTypeHandler; public EthereumProxy(EthereumBackend ethereum, EthereumEventHandler eventHandler, InputTypeHandler inputTypeHandler, OutputTypeHandler outputTypeHandler) { this.ethereum = ethereum; this.eventHandler = eventHandler; this.inputTypeHandler = inputTypeHandler; this.outputTypeHandler = outputTypeHandler; updateNonce(); ethereum.register(eventHandler); } public SmartContract mapFromAbi(ContractAbi abi, EthAddress address, EthAccount account) { return new SmartContract(new CallTransaction.Contract(abi.getAbi()), account, address, this, ethereum); } public CompletableFuture<EthAddress> publish(CompiledContract contract, EthAccount account, Object... constructorArgs) { return createContract(contract, account, constructorArgs); } private CompletableFuture<EthAddress> createContract(CompiledContract contract, EthAccount account, Object... constructorArgs) { CallTransaction.Contract contractAbi = new CallTransaction.Contract(contract.getAbi().getAbi()); CallTransaction.Function constructor = contractAbi.getConstructor(); if (constructor == null && constructorArgs.length > 0) { throw new EthereumApiException("No constructor with params found"); } byte[] argsEncoded = constructor == null ? new byte[0] : constructor.encodeArguments(prepareArguments(constructorArgs)); return publishContract(wei(0), EthData.of(ByteUtil.merge(contract.getBinary().data, argsEncoded)), account); } public Object[] prepareArguments(Object[] args) { return Arrays.stream(args) .map(inputTypeHandler::convert) .toArray(); } public BigInteger getNonce(final EthAddress address) { nonces.computeIfAbsent(address, ethereum::getNonce); BigInteger nonce = nonces.get(address); return nonce.add(BigInteger.valueOf(pendingTransactions.getOrDefault(address, new HashSet<>()).size())); } public SmartContractByteCode getCode(EthAddress address) { return ethereum.getCode(address); } public <T> Observable<T> observeEvents(ContractAbi abi, EthAddress contractAddress, String eventName, Class<T> cls) { CallTransaction.Contract contract = new CallTransaction.Contract(abi.getAbi()); return eventHandler.observeTransactions() .filter(params -> contractAddress.equals(params.receipt.receiveAddress)) .flatMap(params -> Observable.from(params.logs)) .map(contract::parseEvent) .filter(invocation -> invocation != null && eventName.equals(invocation.function.name)) .map(invocation -> outputTypeHandler.convertSpecificType(invocation.args, cls)); } public CompletableFuture<EthAddress> publishContract(EthValue ethValue, EthData data, EthAccount account) { return this.sendTxInternal(ethValue, data, account, EthAddress.empty()) .thenApply(receipt -> receipt.contractAddress); } public CompletableFuture<EthExecutionResult> sendTx(EthValue value, EthData data, EthAccount account, EthAddress address) { return this.sendTxInternal(value, data, account, address) .thenApply(receipt -> new EthExecutionResult(receipt.executionResult)); } private CompletableFuture<TransactionReceipt> sendTxInternal(EthValue value, EthData data, EthAccount account, EthAddress toAddress) { return eventHandler.ready().thenCompose((v) -> { BigInteger gasLimit = estimateGas(value, data, account, toAddress); EthHash txHash = ethereum.submit(account, toAddress, value, data, getNonce(account.getAddress()), gasLimit); long currentBlock = eventHandler.getCurrentBlockNumber(); CompletableFuture<TransactionReceipt> result = CompletableFuture.supplyAsync(() -> { Observable<OnTransactionParameters> droppedTxs = eventHandler.observeTransactions() .filter(params -> params.receipt != null && Objects.equals(params.receipt.hash, txHash) && params.status == TransactionStatus.Dropped); Observable<OnTransactionParameters> timeoutBlock = eventHandler.observeBlocks() .filter(blockParams -> blockParams.blockNumber > currentBlock + BLOCK_WAIT_LIMIT) .map(params -> null); Observable<OnTransactionParameters> blockTxs = eventHandler.observeBlocks() .flatMap(params -> Observable.from(params.receipts)) .filter(receipt -> Objects.equals(receipt.hash, txHash)) .map(this::createTransactionParameters); return Observable.merge(droppedTxs, blockTxs, timeoutBlock) .map(params -> { if (params == null) { throw new EthereumApiException("the transaction has not been included in the last " + BLOCK_WAIT_LIMIT + " blocks"); } TransactionReceipt receipt = params.receipt; if (params.status == TransactionStatus.Dropped) { throw new EthereumApiException("the transaction has been dropped! - " + params.receipt.error); } return checkForErrors(receipt); }).toBlocking().first(); }); increasePendingTransactionCounter(account.getAddress(), txHash); return result; }); } private BigInteger estimateGas(EthValue value, EthData data, EthAccount account, EthAddress toAddress) { BigInteger gasLimit = ethereum.estimateGas(account, toAddress, value, data); //if it is a contract creation if (toAddress.isEmpty()) { gasLimit = gasLimit.add(BigInteger.valueOf(15_000)); } return gasLimit.add(BigInteger.valueOf(200_000)); } private OnTransactionParameters createTransactionParameters(TransactionReceipt receipt) { return new OnTransactionParameters(receipt, TransactionStatus.Executed, new ArrayList<>()); } private TransactionReceipt checkForErrors(final TransactionReceipt receipt) { if (receipt.isSuccessful) { return receipt; } else { throw new EthereumApiException("error with the transaction " + receipt.hash + ". error:" + receipt.error); } } private void updateNonce() { eventHandler.observeTransactions() .filter(tx -> tx.status == TransactionStatus.Dropped) .forEach(params -> { EthAddress currentAddress = params.receipt.sender; EthHash hash = params.receipt.hash; Optional.ofNullable(pendingTransactions.get(currentAddress)).ifPresent(hashes -> { hashes.remove(hash); nonces.put(currentAddress, ethereum.getNonce(currentAddress)); }); }); eventHandler.observeBlocks() .forEach(params -> params.receipts.stream() .forEach(receipt -> Optional.ofNullable(pendingTransactions.get(receipt.sender)) .ifPresent(hashes -> { hashes.remove(receipt.hash); nonces.put(receipt.sender, ethereum.getNonce(receipt.sender)); }))); } public EthereumEventHandler events() { return eventHandler; } public boolean addressExists(EthAddress address) { return ethereum.addressExists(address); } public EthValue getBalance(EthAddress address) { return ethereum.getBalance(address); } private void increasePendingTransactionCounter(EthAddress address, EthHash hash) { Set<EthHash> hashes = pendingTransactions.getOrDefault(address, new HashSet<EthHash>()); hashes.add(hash); pendingTransactions.put(address, hashes); } }
package org.cojen.tupl.rows; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.cojen.maker.ClassMaker; import org.cojen.maker.Label; import org.cojen.maker.MethodMaker; import org.cojen.maker.Variable; /** * * * @author Brian S O'Neill * @see RowSorter * @see SortTranscoderMaker */ class SortDecoderMaker { /** * Find or instantiate an info object which describes the encoding of the keys and values. * * @param orderBySpec ordering specification * @param projection columns to decode; can pass null to decode all available columns * @param allowDuplicates pass false for "select distinct" behavior */ static SecondaryInfo findSortedInfo(Class<?> rowType, String orderBySpec, Set<String> projection, boolean allowDuplicates) { var key = new InfoKey(rowType, orderBySpec, projection, allowDuplicates); return mSortedInfos.obtain(key, null); } /** * Find or generate a decoder instance. * * @param sortedInfo describes the encoding of the keys and values * @param projection columns to decode; can pass null to decode all available columns */ @SuppressWarnings("unchecked") static <R> RowDecoder<R> findDecoder(Class<?> rowType, SecondaryInfo sortedInfo, Set<String> projection) { var key = new DecoderKey(rowType, sortedInfo.indexSpec(), projection); return mDecoders.obtain(key, sortedInfo); } private record DecoderKey(Class<?> rowType, String sortedInfoSpec, Set<String> projection) { DecoderKey withNullProjection() { return new DecoderKey(rowType, sortedInfoSpec, null); } } private static final WeakCache<DecoderKey, RowDecoder, SecondaryInfo> mDecoders; static { mDecoders = new WeakCache<>() { @Override protected RowDecoder newValue(DecoderKey key, SecondaryInfo sortedInfo) { Set<String> projection = key.projection(); if (projection != null && projection.equals(sortedInfo.allColumns.keySet())) { // Null is the canonical form when projecting all columns. return obtain(key.withNullProjection(), sortedInfo); } else { return makeDecoder(key.rowType, sortedInfo, key.projection()); } } }; } private record InfoKey(Class<?> rowType, String orderBySpec, Set<String> projection, boolean allowDuplicates) { InfoKey withNullProjection() { return new InfoKey(rowType, orderBySpec, null, allowDuplicates); } } private static final WeakCache<InfoKey, SecondaryInfo, RowInfo> mSortedInfos; static { mSortedInfos = new WeakCache<>() { @Override protected SecondaryInfo newValue(InfoKey key, RowInfo rowInfo) { Set<String> projection = key.projection(); if (projection != null) { if (rowInfo == null) { rowInfo = RowInfo.find(key.rowType); } if (projection.equals(rowInfo.allColumns.keySet())) { // Null is the canonical form when projecting all columns. return obtain(key.withNullProjection(), rowInfo); } } return newSortedInfo(key.rowType, key.orderBySpec, projection, key.allowDuplicates); } }; } static SecondaryInfo newSortedInfo(Class<?> rowType, String orderBySpec, Set<String> projection, boolean allowDuplicates) { RowInfo rowInfo = RowInfo.find(rowType); if (projection == null) { projection = rowInfo.allColumns.keySet(); } Set<String> available = allowDuplicates ? rowInfo.allColumns.keySet() : projection; var sortedInfo = new SecondaryInfo(rowInfo, false); sortedInfo.keyColumns = new LinkedHashMap<>(); OrderBy orderBy = OrderBy.forSpec(rowInfo, orderBySpec); for (Map.Entry<String, OrderBy.Rule> e : orderBy.entrySet()) { ColumnInfo orderColumn = e.getValue().asColumn(); if (!available.contains(orderColumn.name)) { throw new IllegalArgumentException(); } sortedInfo.keyColumns.put(orderColumn.name, orderColumn); } boolean hasDuplicates = false; for (ColumnInfo keyColumn : rowInfo.keyColumns.values()) { if (!available.contains(keyColumn.name)) { hasDuplicates = true; } else if (!sortedInfo.keyColumns.containsKey(keyColumn.name)) { sortedInfo.keyColumns.put(keyColumn.name, keyColumn); } } if (!hasDuplicates) { // All of the primary key columns are part of the target key, and so no duplicates // can exist. Define the remaining projected columns in the target value. for (String colName : projection) { if (!available.contains(colName)) { throw new IllegalArgumentException(); } if (!sortedInfo.keyColumns.containsKey(colName)) { if (sortedInfo.valueColumns == null) { sortedInfo.valueColumns = new TreeMap<>(); } sortedInfo.valueColumns.put(colName, rowInfo.allColumns.get(colName)); } } } else { // Because duplicate keys can exist, define all available columns in the target // key. This doesn't fully prevent duplicates, and so any extra rows will be // eliminated by the sorter. Proper "select distinct" behavior happens when the // available set is the same as the projected set. for (String colName : available) { if (!sortedInfo.keyColumns.containsKey(colName)) { sortedInfo.keyColumns.put(colName, rowInfo.allColumns.get(colName)); } } } if (sortedInfo.valueColumns == null) { sortedInfo.valueColumns = Collections.emptyNavigableMap(); } sortedInfo.allColumns = new TreeMap<>(); sortedInfo.allColumns.putAll(sortedInfo.keyColumns); sortedInfo.allColumns.putAll(sortedInfo.valueColumns); return sortedInfo; } /** * @param sortedInfo describes the encoding of the keys and values * @param projection columns to decode; can pass null to decode all available columns */ private static RowDecoder makeDecoder(Class<?> rowType, SecondaryInfo sortedInfo, Set<String> projection) { if (projection == null) { projection = sortedInfo.allColumns.keySet(); } RowInfo rowInfo = RowInfo.find(rowType); RowGen rowGen = rowInfo.rowGen(); Class rowClass = RowMaker.find(rowType); ClassMaker cm = rowGen.anotherClassMaker (SortDecoderMaker.class, rowClass, null).implement(RowDecoder.class).final_(); // Keep a singleton instance, in order for a weakly cached reference to the RowDecoder // to stick around until the class is unloaded. cm.addField(RowDecoder.class, "THE").private_().static_(); { MethodMaker mm = cm.addConstructor().private_(); mm.invokeSuperConstructor(); mm.field("THE").set(mm.this_()); } MethodMaker mm = cm.addMethod (Object.class, "decodeRow", Object.class, byte[].class, byte[].class).public_(); var rowVar = mm.param(0); var keyVar = mm.param(1); var valueVar = mm.param(2); Label notRow = mm.label(); var typedRowVar = CodeUtils.castOrNew(rowVar, rowClass, notRow); Label hasTypedRow = mm.label(); typedRowVar.ifNe(null, hasTypedRow); typedRowVar.set(mm.new_(rowClass)); hasTypedRow.here(); RowGen sortedRowGen = sortedInfo.rowGen(); decodeColumns(projection, mm, typedRowVar, keyVar, sortedRowGen.keyCodecs()); decodeColumns(projection, mm, typedRowVar, valueVar, sortedRowGen.valueCodecs()); // Mark projected columns as clean; all others are unset. ColumnCodec[] keyCodecs = rowGen.keyCodecs(); ColumnCodec[] valueCodecs = rowGen.valueCodecs(); int maxNum = rowInfo.allColumns.size(); int mask = 0; for (int num = 0; num < maxNum; ) { ColumnCodec codec; if (num < keyCodecs.length) { codec = keyCodecs[num]; } else { codec = valueCodecs[num - keyCodecs.length]; } if (projection.contains(codec.mInfo.name)) { mask |= RowGen.stateFieldMask(num, 0b01); // clean state } if ((++num & 0b1111) == 0 || num >= maxNum) { typedRowVar.field(sortedRowGen.stateField(num - 1)).set(mask); mask = 0; } } mm.return_(typedRowVar); // Assume the passed in row is actually a RowConsumer. notRow.here(); CodeUtils.acceptAsRowConsumerAndReturn(rowVar, rowClass, keyVar, valueVar); try { MethodHandles.Lookup lookup = cm.finishHidden(); MethodHandle mh = lookup.findConstructor (lookup.lookupClass(), MethodType.methodType(void.class)); return (RowDecoder) mh.invoke(); } catch (Throwable e) { throw RowUtils.rethrow(e); } } private static void decodeColumns(Set<String> projection, MethodMaker mm, Variable rowVar, Variable srcVar, ColumnCodec[] codecs) { if (codecs.length != 0) { codecs = ColumnCodec.bind(codecs, mm); var offsetVar = mm.var(int.class).set(0); for (int i=0; i<codecs.length; i++) { ColumnCodec codec = codecs[i]; String name = codec.mInfo.name; if (projection.contains(name)) { codec.decode(rowVar.field(name), srcVar, offsetVar, null); } else if (i < codecs.length - 1) { codec.decodeSkip(srcVar, offsetVar, null); } } } } }
package org.fiteagle.north.sfa.am.dm; import java.util.UUID; //import javax.annotation.Resource; import javax.inject.Inject; import javax.jms.JMSContext; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Topic; import javax.ws.rs.GET; import javax.ws.rs.Path; import org.fiteagle.api.core.IMessageBus; import com.hp.hpl.jena.rdf.model.Model; import com.hp.hpl.jena.rdf.model.ModelFactory; import com.hp.hpl.jena.vocabulary.RDF; import org.codehaus.jackson.map.ObjectMapper; import com.hp.hpl.jena.rdf.model.Resource; import org.fiteagle.api.core.MessageBusMsgFactory; import org.fiteagle.api.core.MessageBusOntologyModel; @Path("/sfarest") public class SFArest { @Inject private JMSContext context; //@Resource(mappedName = IMessageBus.TOPIC_CORE_NAME) @javax.annotation.Resource(mappedName = IMessageBus.TOPIC_CORE_NAME) private Topic topic; public SFArest(){ // TODO Auto-generated constructor stub } @GET @Path("getVersion") public void getTestbedDescription(){ String testbedDescription = ""; Model requestModel = ModelFactory.createDefaultModel(); Resource resource = requestModel.createResource(); resource.addProperty(RDF.type, MessageBusOntologyModel.classTestbed); requestModel = MessageBusMsgFactory.createMsgRequest(requestModel); try { Message request = createRequest(MessageBusMsgFactory.serializeModel(requestModel), IMessageBus.TYPE_REQUEST); //Message request = createRequest(null, IMessageBus.TYPE_REQUEST); //sendRequest(request); System.out.println("sending testbed description query..."); this.context.createProducer().send(this.topic, request); Message rcvMessage = waitForResult(request.getJMSCorrelationID()); testbedDescription = getResult(rcvMessage); System.out.println("testbed description is " + testbedDescription); } catch (JMSException e) { e.printStackTrace(); } } private Message createRequest(final String rdfInput, final String methodType) throws JMSException { System.out.println("creating request..."); final Message message = this.context.createMessage(); System.out.println("message created..."); message.setStringProperty(IMessageBus.METHOD_TYPE, methodType); message.setStringProperty(IMessageBus.SERIALIZATION, IMessageBus.SERIALIZATION_DEFAULT); message.setStringProperty(IMessageBus.RDF, rdfInput); //message.setStringProperty(IMessageBus.QUERY, "SELECT * {?s ?p ?o} LIMIT 100"); message.setJMSCorrelationID(UUID.randomUUID().toString()); System.out.println("JMSCorrelationID " + message.getJMSCorrelationID()); return message; } private void sendRequest(final Message message) { System.out.println("sending testbed description query..."); this.context.createProducer().send(this.topic, message); } private Message waitForResult(final String correlationID) throws JMSException { final String filter = "JMSCorrelationID='" + correlationID + "'"; final Message rcvMessage = this.context.createConsumer(this.topic, filter).receive(IMessageBus.TIMEOUT); // IMessageBus.TIMEOUT System.out.println("message received"); return rcvMessage; } private String getResult(final Message rcvMessage) throws JMSException { String resources = IMessageBus.STATUS_408; System.out.println("Received a message..."); if (null != rcvMessage) { resources = rcvMessage.getStringProperty(IMessageBus.RDF); System.out.println(" the RDF description is " + resources); } return resources; } //@Produces("text/turtle") @GET @Path("listResources") public void listResources() { final int TIMEOUT = 5000; final Message message = this.context.createMessage(); try { message.setStringProperty(IMessageBus.TYPE_REQUEST, SFAsender.LIST_RESOURCES); message.setStringProperty(IMessageBus.SERIALIZATION, "TURTLE"); message.setStringProperty(IMessageBus.QUERY, "SELECT * {?s ?p ?o} LIMIT 100"); message.setJMSCorrelationID(UUID.randomUUID().toString()); System.out.println("sending a request from SFA to resource repository"); this.context.createProducer().send(this.topic, message); final String filter = "JMSCorrelationID='"+ message.getJMSCorrelationID() + "'"; Message rcvMessage = this.context.createConsumer(this.topic, filter).receive(TIMEOUT); String result = ""; if (null != rcvMessage){ result = rcvMessage.getStringProperty(IMessageBus.RESULT); System.out.println("the received result for listResources method is " + result); } else System.out.println("the received result for listResources method is empty !"); } catch (JMSException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package org.javaee7.websocket.bingo; /** * * @author sree */ import org.json.simple.JSONObject; public class PeerInfo { JSONObject peerInfo; PeerInfo(String id) { System.out.println(id); peerInfo = new JSONObject(); peerInfo.put("Type", "Id Description"); peerInfo.put("id", id); } public JSONObject getJSONObject() { return peerInfo; } }