answer
stringlengths
17
10.2M
package net.java.sip.communicator.plugin.otr; import java.security.*; import java.util.*; import org.osgi.framework.*; import net.java.otr4j.*; import net.java.otr4j.session.*; import net.java.sip.communicator.service.browserlauncher.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.protocol.*; /** * @author George Politis */ public class ScOtrEngineImpl implements ScOtrEngine { private final OtrConfigurator configurator = new OtrConfigurator(); private static final Map<SessionID, Contact> contactsMap = new Hashtable<SessionID, Contact>(); private final List<String> injectedMessageUIDs = new Vector<String>(); private final List<ScOtrEngineListener> listeners = new Vector<ScOtrEngineListener>(); private final OtrEngine otrEngine = new OtrEngineImpl(new ScOtrEngineHost()); public void addListener(ScOtrEngineListener l) { synchronized (listeners) { if (!listeners.contains(l)) listeners.add(l); } } public void removeListener(ScOtrEngineListener l) { synchronized (listeners) { listeners.remove(l); } } public boolean isMessageUIDInjected(String mUID) { return injectedMessageUIDs.contains(mUID); } class ScOtrEngineHost implements OtrEngineHost { public KeyPair getKeyPair(SessionID sessionID) { AccountID accountID = OtrActivator.getAccountIDByUID(sessionID.getAccountID()); KeyPair keyPair = OtrActivator.scOtrKeyManager.loadKeyPair(accountID); if (keyPair == null) OtrActivator.scOtrKeyManager.generateKeyPair(accountID); return OtrActivator.scOtrKeyManager.loadKeyPair(accountID); } public void showWarning(SessionID sessionID, String warn) { Contact contact = getContact(sessionID); if (contact == null) return; OtrActivator.uiService.getChat(contact).addMessage( contact.getDisplayName(), System.currentTimeMillis(), Chat.SYSTEM_MESSAGE, warn, OperationSetBasicInstantMessaging.DEFAULT_MIME_TYPE); } public void showError(SessionID sessionID, String err) { ScOtrEngineImpl.this.showError(sessionID, err); } public void injectMessage(SessionID sessionID, String messageText) { Contact contact = getContact(sessionID); OperationSetBasicInstantMessaging imOpSet = contact .getProtocolProvider() .getOperationSet(OperationSetBasicInstantMessaging.class); Message message = imOpSet.createMessage(messageText); injectedMessageUIDs.add(message.getMessageUID()); imOpSet.sendInstantMessage(contact, message); } public OtrPolicy getSessionPolicy(SessionID sessionID) { return getContactPolicy(getContact(sessionID)); } } public void showError(SessionID sessionID, String err) { Contact contact = getContact(sessionID); if (contact == null) return; OtrActivator.uiService.getChat(contact).addMessage( contact.getDisplayName(), System.currentTimeMillis(), Chat.ERROR_MESSAGE, err, OperationSetBasicInstantMessaging.DEFAULT_MIME_TYPE); } public ScOtrEngineImpl() { this.otrEngine.addOtrEngineListener(new OtrEngineListener() { public void sessionStatusChanged(SessionID sessionID) { Contact contact = getContact(sessionID); if (contact == null) return; String message = ""; switch (otrEngine.getSessionStatus(sessionID)) { case ENCRYPTED: PublicKey remotePubKey = otrEngine.getRemotePublicKey(sessionID); PublicKey storedPubKey = OtrActivator.scOtrKeyManager.loadPublicKey(contact); if (!remotePubKey.equals(storedPubKey)) OtrActivator.scOtrKeyManager.savePublicKey(contact, remotePubKey); if (!OtrActivator.scOtrKeyManager.isVerified(contact)) { String unverifiedSessionWarning = OtrActivator.resourceService .getI18NString( "plugin.otr.activator.unverifiedsessionwarning", new String[] { contact.getDisplayName() }); OtrActivator.uiService.getChat(contact).addMessage( contact.getDisplayName(), System.currentTimeMillis(), Chat.SYSTEM_MESSAGE, unverifiedSessionWarning, OperationSetBasicInstantMessaging.HTML_MIME_TYPE); } message = OtrActivator.resourceService .getI18NString( (OtrActivator.scOtrKeyManager .isVerified(contact)) ? "plugin.otr.activator.sessionstared" : "plugin.otr.activator.unverifiedsessionstared", new String[] { contact.getDisplayName() }); break; case FINISHED: message = OtrActivator.resourceService.getI18NString( "plugin.otr.activator.sessionfinished", new String[] { contact.getDisplayName() }); break; case PLAINTEXT: message = OtrActivator.resourceService.getI18NString( "plugin.otr.activator.sessionlost", new String[] { contact.getDisplayName() }); break; } OtrActivator.uiService.getChat(contact).addMessage( contact.getDisplayName(), System.currentTimeMillis(), Chat.SYSTEM_MESSAGE, message, OperationSetBasicInstantMessaging.HTML_MIME_TYPE); for (ScOtrEngineListener l : listeners) { l.sessionStatusChanged(contact); } } }); } public static SessionID getSessionID(Contact contact) { SessionID sessionID = new SessionID(contact.getProtocolProvider().getAccountID() .getAccountUniqueID(), contact.getAddress(), contact .getProtocolProvider().getProtocolName()); synchronized (contactsMap) { contactsMap.put(sessionID, contact); } return sessionID; } public static Contact getContact(SessionID sessionID) { return contactsMap.get(sessionID); } public void endSession(Contact contact) { SessionID sessionID = getSessionID(contact); try { otrEngine.endSession(sessionID); } catch (OtrException e) { showError(sessionID, e.getMessage()); } } public SessionStatus getSessionStatus(Contact contact) { return otrEngine.getSessionStatus(getSessionID(contact)); } public String transformReceiving(Contact contact, String msgText) { SessionID sessionID = getSessionID(contact); try { return otrEngine.transformReceiving(sessionID, msgText); } catch (OtrException e) { showError(sessionID, e.getMessage()); return null; } } public String transformSending(Contact contact, String msgText) { SessionID sessionID = getSessionID(contact); try { return otrEngine.transformSending(sessionID, msgText); } catch (OtrException e) { showError(sessionID, e.getMessage()); return null; } } public void refreshSession(Contact contact) { SessionID sessionID = getSessionID(contact); try { otrEngine.refreshSession(sessionID); } catch (OtrException e) { showError(sessionID, e.getMessage()); } } public void startSession(Contact contact) { SessionID sessionID = getSessionID(contact); try { otrEngine.startSession(sessionID); } catch (OtrException e) { showError(sessionID, e.getMessage()); } } public OtrPolicy getGlobalPolicy() { return new OtrPolicyImpl(this.configurator.getPropertyInt("POLICY", OtrPolicy.OTRL_POLICY_DEFAULT)); } public void setGlobalPolicy(OtrPolicy policy) { if (policy == null) this.configurator.removeProperty("POLICY"); else this.configurator.setProperty("POLICY", policy.getPolicy()); for (ScOtrEngineListener l : listeners) l.globalPolicyChanged(); } public void launchHelp() { ServiceReference ref = OtrActivator.bundleContext .getServiceReference(BrowserLauncherService.class.getName()); if (ref == null) return; BrowserLauncherService service = (BrowserLauncherService) OtrActivator.bundleContext.getService(ref); service.openURL(OtrActivator.resourceService .getI18NString("plugin.otr.authbuddydialog.HELP_URI")); } public OtrPolicy getContactPolicy(Contact contact) { int policy = this.configurator.getPropertyInt(getSessionID(contact) + "policy", -1); if (policy < 0) return getGlobalPolicy(); else return new OtrPolicyImpl(policy); } public void setContactPolicy(Contact contact, OtrPolicy policy) { String propertyID = getSessionID(contact) + "policy"; if (policy == null) this.configurator.removeProperty(propertyID); else this.configurator.setProperty(propertyID, policy.getPolicy()); for (ScOtrEngineListener l : listeners) l.contactPolicyChanged(contact); } }
package com.amee.service.profile; import com.amee.domain.AMEEStatus; import com.amee.domain.Pager; import com.amee.domain.auth.User; import com.amee.domain.data.DataCategory; import com.amee.domain.profile.LegacyProfileItem; import com.amee.domain.profile.Profile; import com.amee.domain.profile.ProfileItem; import com.amee.platform.science.StartEndDate; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.*; import org.hibernate.criterion.Restrictions; import org.joda.time.DateTime; import org.joda.time.Period; import org.springframework.stereotype.Service; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import java.io.Serializable; import java.util.*; /** * Encapsulates all persistence operations for Profiles and Profile Items. */ @Service public class ProfileServiceDAO implements Serializable { private final Log log = LogFactory.getLog(getClass()); private static final String CACHE_REGION = "query.profileService"; @PersistenceContext private EntityManager entityManager; @SuppressWarnings(value = "unchecked") protected Profile getProfileByUid(String uid) { Profile profile = null; if (!StringUtils.isBlank(uid)) { Session session = (Session) entityManager.getDelegate(); Criteria criteria = session.createCriteria(Profile.class); criteria.add(Restrictions.naturalId().set("uid", uid)); criteria.add(Restrictions.ne("status", AMEEStatus.TRASH)); criteria.setCacheable(true); criteria.setCacheRegion(CACHE_REGION); List<Profile> profiles = criteria.list(); if (profiles.size() == 1) { log.debug("getProfileByUid() found: " + uid); profile = profiles.get(0); } else { log.debug("getProfileByUid() NOT found: " + uid); } } return profile; } @SuppressWarnings(value = "unchecked") protected Profile getProfileByPath(String path) { Profile profile = null; List<Profile> profiles = entityManager.createQuery( "FROM Profile p " + "WHERE p.path = :path " + "AND p.status != :trash") .setParameter("path", path) .setParameter("trash", AMEEStatus.TRASH) .setHint("org.hibernate.cacheable", true) .setHint("org.hibernate.cacheRegion", CACHE_REGION) .getResultList(); if (profiles.size() == 1) { log.debug("getProfileByPath() found: " + path); profile = profiles.get(0); } else { log.debug("getProfileByPath() NOT found: " + path); } return profile; } @SuppressWarnings(value = "unchecked") protected List<Profile> getProfiles(User user, Pager pager) { // first count all profiles long count = (Long) entityManager.createQuery( "SELECT count(p) " + "FROM Profile p " + "WHERE p.user.id = :userId " + "AND p.status != :trash") .setParameter("userId", user.getId()) .setParameter("trash", AMEEStatus.TRASH) .setHint("org.hibernate.cacheable", true) .setHint("org.hibernate.cacheRegion", CACHE_REGION) .getSingleResult(); // tell pager how many profiles there are and give it a chance to select the requested page again pager.setItems(count); pager.goRequestedPage(); // now get the profiles for the current page List<Profile> profiles = entityManager.createQuery( "SELECT p " + "FROM Profile p " + "WHERE p.user.id = :userId " + "AND p.status != :trash " + "ORDER BY p.created DESC") .setParameter("userId", user.getId()) .setParameter("trash", AMEEStatus.TRASH) .setHint("org.hibernate.cacheable", true) .setHint("org.hibernate.cacheRegion", CACHE_REGION) .setMaxResults(pager.getItemsPerPage()) .setFirstResult((int) pager.getStart()) .getResultList(); // update the pager pager.setItemsFound(profiles.size()); // all done, return results return profiles; } protected void persist(Profile profile) { entityManager.persist(profile); } /** * Removes (trashes) a Profile. * * @param profile to remove */ protected void remove(Profile profile) { profile.setStatus(AMEEStatus.TRASH); } // ProfileItems @SuppressWarnings(value = "unchecked") protected ProfileItem getProfileItem(String uid) { LegacyProfileItem profileItem = null; if (!StringUtils.isBlank(uid)) { // See http://www.hibernate.org/117.html#A12 for notes on DISTINCT_ROOT_ENTITY. Session session = (Session) entityManager.getDelegate(); Criteria criteria = session.createCriteria(LegacyProfileItem.class); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.add(Restrictions.naturalId().set("uid", uid.toUpperCase())); criteria.add(Restrictions.ne("status", AMEEStatus.TRASH)); criteria.setFetchMode("itemValues", FetchMode.JOIN); criteria.setCacheable(true); criteria.setCacheRegion(CACHE_REGION); List<LegacyProfileItem> profileItems = criteria.list(); if (profileItems.size() == 1) { log.debug("getProfileItem() found: " + uid); profileItem = profileItems.get(0); } else { log.debug("getProfileItem() NOT found: " + uid); } } return ProfileItem.getProfileItem(profileItem); } @SuppressWarnings(value = "unchecked") protected int getProfileItemCount(Profile profile, DataCategory dataCategory) { if ((dataCategory == null) || (dataCategory.getItemDefinition() == null)) { return -1; } log.debug("getProfileItemCount() start"); int count = entityManager.createQuery( "SELECT COUNT(pi.id) " + "FROM LegacyProfileItem pi " + "WHERE pi.dataCategory.id = :dataCategoryId " + "AND pi.profile.id = :profileId") .setParameter("dataCategoryId", dataCategory.getId()) .setParameter("profileId", profile.getId()) .setHint("org.hibernate.cacheable", true) .setHint("org.hibernate.cacheRegion", CACHE_REGION) .getResultList().size(); log.debug("getProfileItemCount() count: " + count); return count; } @SuppressWarnings(value = "unchecked") protected List<ProfileItem> getProfileItems(Profile profile, DataCategory dataCategory, Date profileDate) { if ((dataCategory == null) || (dataCategory.getItemDefinition() == null)) { return null; } if (log.isDebugEnabled()) { log.debug("getProfileItems() start"); } // need to roll the date forward DateTime nextMonth = new DateTime(profileDate).plus(Period.months(1)); profileDate = nextMonth.toDate(); // now get all the Profile Items List<LegacyProfileItem> legacyProfileItems = entityManager.createQuery( "SELECT DISTINCT pi " + "FROM LegacyProfileItem pi " + "LEFT JOIN FETCH pi.itemValues " + "WHERE pi.dataCategory.id = :dataCategoryId " + "AND pi.profile.id = :profileId " + "AND pi.startDate < :profileDate " + "AND pi.status != :trash ") .setParameter("dataCategoryId", dataCategory.getId()) .setParameter("profileId", profile.getId()) .setParameter("profileDate", profileDate) .setParameter("trash", AMEEStatus.TRASH) .setHint("org.hibernate.cacheable", true) .setHint("org.hibernate.cacheRegion", CACHE_REGION) .getResultList(); // Order the returned collection by pi.name, di.name and pi.startDate DESC Collections.sort(legacyProfileItems, new Comparator<LegacyProfileItem>() { public int compare(LegacyProfileItem p1, LegacyProfileItem p2) { int nd = p1.getName().compareTo(p2.getName()); int dnd = p1.getDataItem().getName().compareTo(p2.getDataItem().getName()); int sdd = p2.getStartDate().compareTo(p1.getStartDate()); if (nd != 0) return nd; if (dnd != 0) return dnd; if (sdd != 0) return sdd; return 0; } }); if (log.isDebugEnabled()) { log.debug("getProfileItems() done (" + legacyProfileItems.size() + ")"); } // Convert from legacy to adapter. List<ProfileItem> profileItems = new ArrayList<ProfileItem>(); for (LegacyProfileItem legacyProfileItem : legacyProfileItems) { profileItems.add(ProfileItem.getProfileItem(legacyProfileItem)); } return profileItems; } @SuppressWarnings(value = "unchecked") protected List<ProfileItem> getProfileItems( Profile profile, DataCategory dataCategory, StartEndDate startDate, StartEndDate endDate) { if ((dataCategory == null) || (dataCategory.getItemDefinition() == null)) { return null; } if (log.isDebugEnabled()) { log.debug("getProfileItems() start"); } // Create HQL. StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("SELECT DISTINCT pi "); queryBuilder.append("FROM LegacyProfileItem pi "); queryBuilder.append("LEFT JOIN FETCH pi.itemValues "); queryBuilder.append("WHERE pi.dataCategory.id = :dataCategoryId "); queryBuilder.append("AND pi.profile.id = :profileId AND "); if (endDate == null) { queryBuilder.append("(pi.endDate IS NULL OR pi.endDate > :startDate) "); } else { queryBuilder.append("(pi.startDate < :endDate) AND (pi.endDate IS NULL OR pi.endDate > :startDate) "); } queryBuilder.append("AND pi.status != :trash "); queryBuilder.append("ORDER BY pi.startDate DESC"); // Create Query. Query query = entityManager.createQuery(queryBuilder.toString()); query.setParameter("dataCategoryId", dataCategory.getId()); query.setParameter("profileId", profile.getId()); query.setParameter("startDate", startDate.toDate()); if (endDate != null) { query.setParameter("endDate", endDate.toDate()); } query.setParameter("trash", AMEEStatus.TRASH); query.setHint("org.hibernate.cacheable", true); query.setHint("org.hibernate.cacheRegion", CACHE_REGION); // Execute query. List<LegacyProfileItem> legacyProfileItems = query.getResultList(); if (log.isDebugEnabled()) { log.debug("getProfileItems() done (" + legacyProfileItems.size() + ")"); } // Convert from legacy to adapter. List<ProfileItem> profileItems = new ArrayList<ProfileItem>(); for (LegacyProfileItem legacyProfileItem : legacyProfileItems) { profileItems.add(ProfileItem.getProfileItem(legacyProfileItem)); } return profileItems; } @SuppressWarnings(value = "unchecked") protected boolean equivalentProfileItemExists(ProfileItem profileItem) { List<LegacyProfileItem> profileItems = entityManager.createQuery( "SELECT DISTINCT pi " + "FROM LegacyProfileItem pi " + "LEFT JOIN FETCH pi.itemValues " + "WHERE pi.profile.id = :profileId " + "AND pi.uid != :uid " + "AND pi.dataCategory.id = :dataCategoryId " + "AND pi.dataItem.id = :dataItemId " + "AND pi.startDate = :startDate " + "AND pi.name = :name " + "AND pi.status != :trash") .setParameter("profileId", profileItem.getProfile().getId()) .setParameter("uid", profileItem.getUid()) .setParameter("dataCategoryId", profileItem.getDataCategory().getId()) .setParameter("dataItemId", profileItem.getDataItem().getId()) .setParameter("startDate", profileItem.getStartDate()) .setParameter("name", profileItem.getName()) .setParameter("trash", AMEEStatus.TRASH) .getResultList(); if (profileItems.size() > 0) { log.debug("equivalentProfileItemExists() - found ProfileItem(s)"); return true; } else { log.debug("equivalentProfileItemExists() - no ProfileItem(s) found"); return false; } } protected void persist(ProfileItem profileItem) { entityManager.persist(profileItem.getAdaptedEntity()); } protected void remove(ProfileItem profileItem) { profileItem.getAdaptedEntity().setStatus(AMEEStatus.TRASH); } // Profile DataCategories @SuppressWarnings(value = "unchecked") protected Collection<Long> getProfileDataCategoryIds(Profile profile) { StringBuilder sql; SQLQuery query; // check arguments if (profile == null) { throw new IllegalArgumentException("A required argument is missing."); } // create SQL sql = new StringBuilder(); sql.append("SELECT DISTINCT DATA_CATEGORY_ID ID "); sql.append("FROM ITEM "); sql.append("WHERE TYPE = 'PI' "); sql.append("AND PROFILE_ID = :profileId "); sql.append("AND STATUS != :trash"); // create query Session session = (Session) entityManager.getDelegate(); query = session.createSQLQuery(sql.toString()); query.addScalar("ID", Hibernate.LONG); // set parameters query.setLong("profileId", profile.getId()); query.setInteger("trash", AMEEStatus.TRASH.ordinal()); // execute SQL return (List<Long>) query.list(); } }
// Revision 1.1 1999-01-31 13:33:08+00 sm11td // Initial revision package Debrief.Wrappers; import java.awt.Color; import java.awt.Font; import java.awt.Point; import java.beans.IntrospectionException; import java.beans.MethodDescriptor; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyDescriptor; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; import java.util.Vector; import Debrief.ReaderWriter.Replay.FormatTracks; import Debrief.Wrappers.Track.AbsoluteTMASegment; import Debrief.Wrappers.Track.CoreTMASegment; import Debrief.Wrappers.Track.PlanningSegment; import Debrief.Wrappers.Track.RelativeTMASegment; import Debrief.Wrappers.Track.SplittableLayer; import Debrief.Wrappers.Track.TrackSegment; import Debrief.Wrappers.Track.TrackWrapper_Support; import Debrief.Wrappers.Track.TrackWrapper_Support.FixSetter; import Debrief.Wrappers.Track.TrackWrapper_Support.SegmentList; import Debrief.Wrappers.Track.WormInHoleOffset; import MWC.GUI.BaseLayer; import MWC.GUI.CanvasType; import MWC.GUI.DynamicPlottable; import MWC.GUI.Editable; import MWC.GUI.FireExtended; import MWC.GUI.FireReformatted; import MWC.GUI.Layer; import MWC.GUI.Plottable; import MWC.GUI.Canvas.CanvasTypeUtilities; import MWC.GUI.Layer.ProvidesContiguousElements; import MWC.GUI.Layers; import MWC.GUI.MessageProvider; import MWC.GUI.PlainWrapper; import MWC.GUI.Properties.LineStylePropertyEditor; import MWC.GUI.Properties.TimeFrequencyPropertyEditor; import MWC.GUI.Shapes.DraggableItem; import MWC.GUI.Shapes.HasDraggableComponents; import MWC.GUI.Shapes.TextLabel; import MWC.GUI.Shapes.Symbols.Vessels.WorldScaledSym; import MWC.GenericData.HiResDate; import MWC.GenericData.TimePeriod; import MWC.GenericData.Watchable; import MWC.GenericData.WatchableList; import MWC.GenericData.WorldArea; import MWC.GenericData.WorldDistance; import MWC.GenericData.WorldDistance.ArrayLength; import MWC.GenericData.WorldLocation; import MWC.GenericData.WorldSpeed; import MWC.GenericData.WorldVector; import MWC.TacticalData.Fix; import MWC.Utilities.TextFormatting.FormatRNDateTime; /** * the TrackWrapper maintains the GUI and data attributes of the whole track * iteself, but the responsibility for the fixes within the track are demoted to * the FixWrapper */ public class TrackWrapper extends MWC.GUI.PlainWrapper implements WatchableList, DynamicPlottable, MWC.GUI.Layer, DraggableItem, HasDraggableComponents, ProvidesContiguousElements, ISecondaryTrack { // member variables /** * class containing editable details of a track */ public final class trackInfo extends Editable.EditorType implements Editable.DynamicDescriptors { /** * constructor for this editor, takes the actual track as a parameter * * @param data * track being edited */ public trackInfo(final TrackWrapper data) { super(data, data.getName(), ""); } @Override public final MethodDescriptor[] getMethodDescriptors() { // just add the reset color field first final Class<TrackWrapper> c = TrackWrapper.class; final MethodDescriptor[] mds = { method(c, "exportThis", null, "Export Shape"), method(c, "resetLabels", null, "Reset DTG Labels"), method(c, "calcCourseSpeed", null/* no params */, "Generate calculated Course and Speed") }; return mds; } @Override public final String getName() { return super.getName(); } @Override public final PropertyDescriptor[] getPropertyDescriptors() { try { PropertyDescriptor[] res = { expertProp("SymbolType", "the type of symbol plotted for this label", FORMAT), expertProp("LineThickness", "the width to draw this track", FORMAT), expertProp("Name", "the track name"), expertProp("InterpolatePoints", "whether to interpolate points between known data points", SPATIAL), expertProp("Color", "the track color", FORMAT), expertProp("SymbolColor", "the color of the symbol (when used)", FORMAT), expertProp( "PlotArrayCentre", "highlight the sensor array centre when non-zero array length provided", FORMAT), expertProp("TrackFont", "the track label font", FORMAT), expertProp("NameVisible", "show the track label", VISIBILITY), expertProp("PositionsVisible", "show individual Positions", VISIBILITY), expertProp("NameAtStart", "whether to show the track name at the start (or end)", VISIBILITY), expertProp("LinkPositions", "whether to join the track points", FORMAT), expertProp("Visible", "whether the track is visible", VISIBILITY), expertLongProp("NameLocation", "relative location of track label", MWC.GUI.Properties.LocationPropertyEditor.class), expertLongProp("LabelFrequency", "the label frequency", MWC.GUI.Properties.TimeFrequencyPropertyEditor.class), expertLongProp("SymbolFrequency", "the symbol frequency", MWC.GUI.Properties.TimeFrequencyPropertyEditor.class), expertLongProp("ResampleDataAt", "the data sample rate", MWC.GUI.Properties.TimeFrequencyPropertyEditor.class), expertLongProp("ArrowFrequency", "the direction marker frequency", MWC.GUI.Properties.TimeFrequencyPropertyEditor.class), expertLongProp("LineStyle", "the line style used to join track points", MWC.GUI.Properties.LineStylePropertyEditor.class), }; res[0] .setPropertyEditorClass(MWC.GUI.Shapes.Symbols.SymbolFactoryPropertyEditor.class); res[1] .setPropertyEditorClass(MWC.GUI.Properties.LineWidthPropertyEditor.class); // SPECIAL CASE: if we have a world scaled symbol, provide // editors for // the symbol size final TrackWrapper item = (TrackWrapper) this.getData(); if (item._theSnailShape instanceof WorldScaledSym) { // yes = better create height/width editors final PropertyDescriptor[] res2 = new PropertyDescriptor[res.length + 2]; System.arraycopy(res, 0, res2, 2, res.length); res2[0] = expertProp("SymbolLength", "Length of symbol", FORMAT); res2[1] = expertProp("SymbolWidth", "Width of symbol", FORMAT); // and now use the new value res = res2; } return res; } catch (final IntrospectionException e) { return super.getPropertyDescriptors(); } } } private static final String SOLUTIONS_LAYER_NAME = "Solutions"; public static final String SENSORS_LAYER_NAME = "Sensors"; /** * keep track of versions - version id */ static final long serialVersionUID = 1; /** * put the other objects into this one as children * * @param wrapper * whose going to receive it * @param theLayers * the top level layers object * @param parents * the track wrapppers containing the children * @param subjects * the items to insert. */ public static void groupTracks(final TrackWrapper target, final Layers theLayers, final Layer[] parents, final Editable[] subjects) { // ok, loop through the subjects, adding them onto the target for (int i = 0; i < subjects.length; i++) { final Layer thisL = (Layer) subjects[i]; final TrackWrapper thisP = (TrackWrapper) parents[i]; if (thisL != target) { // is it a plain segment? if (thisL instanceof TrackWrapper) { // pass down through the positions/segments final Enumeration<Editable> pts = thisL.elements(); while (pts.hasMoreElements()) { final Editable obj = pts.nextElement(); if (obj instanceof SegmentList) { final SegmentList sl = (SegmentList) obj; final Enumeration<Editable> segs = sl.elements(); while (segs.hasMoreElements()) { final TrackSegment ts = (TrackSegment) segs.nextElement(); // reset the name if we need to if (ts.getName().startsWith("Posi")) { ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate() .getTime())); } target.add(ts); } } else { if (obj instanceof TrackSegment) { final TrackSegment ts = (TrackSegment) obj; // reset the name if we need to if (ts.getName().startsWith("Posi")) { ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate() .getTime())); } // and remember it target.add(ts); } } } } else { // get it's data, and add it to the target target.add(thisL); } // and remove the layer from it's parent if (thisL instanceof TrackSegment) { thisP.removeElement(thisL); // does this just leave an empty husk? if (thisP.numFixes() == 0) { // may as well ditch it anyway theLayers.removeThisLayer(thisP); } } else { // we'll just remove it from the top level layer theLayers.removeThisLayer(thisL); } } } } /** * perform a merge of the supplied tracks. * * @param target * the final recipient of the other items * @param theLayers * @param parents * the parent tracks for the supplied items * @param subjects * the actual selected items * @return sufficient information to undo the merge */ public static int mergeTracksInPlace(final Editable target, final Layers theLayers, final Layer[] parents, final Editable[] subjects) { // where we dump the new data points Layer receiver = (Layer) target; // check that the legs don't overlap String failedMsg = checkTheyAreNotOverlapping(subjects); // how did we get on? if (failedMsg != null) { MessageProvider.Base.Provider.show("Merge tracks", "Sorry, " + failedMsg + " overlap in time. Please correct this and retry", MessageProvider.ERROR); return MessageProvider.ERROR; } // right, if the target is a TMA track, we have to change it into a // proper // track, since // the merged tracks probably contain manoeuvres if (target instanceof CoreTMASegment) { final CoreTMASegment tma = (CoreTMASegment) target; final TrackSegment newSegment = new TrackSegment(tma); // now do some fancy footwork to remove the target from the wrapper, // and // replace it with our new segment newSegment.getWrapper().removeElement(target); newSegment.getWrapper().add(newSegment); // store the new segment into the receiver receiver = newSegment; } // ok, loop through the subjects, adding them onto the target for (int i = 0; i < subjects.length; i++) { final Layer thisL = (Layer) subjects[i]; final TrackWrapper thisP = (TrackWrapper) parents[i]; // is this the target item (note we're comparing against the item // passed // in, not our // temporary receiver, since the receiver may now be a tracksegment, // not a // TMA segment if (thisL != target) { // is it a plain segment? if (thisL instanceof TrackWrapper) { // pass down through the positions/segments final Enumeration<Editable> pts = thisL.elements(); while (pts.hasMoreElements()) { final Editable obj = pts.nextElement(); if (obj instanceof SegmentList) { final SegmentList sl = (SegmentList) obj; final Enumeration<Editable> segs = sl.elements(); while (segs.hasMoreElements()) { final TrackSegment ts = (TrackSegment) segs.nextElement(); receiver.add(ts); } } else { final Layer ts = (Layer) obj; receiver.append(ts); } } } else { // get it's data, and add it to the target receiver.append(thisL); } // and remove the layer from it's parent if (thisL instanceof TrackSegment) { thisP.removeElement(thisL); // does this just leave an empty husk? if (thisP.numFixes() == 0) { // may as well ditch it anyway theLayers.removeThisLayer(thisP); } } else { // we'll just remove it from the top level layer theLayers.removeThisLayer(thisL); } } } return MessageProvider.OK; } /** * perform a merge of the supplied tracks. * * @param target * the final recipient of the other items * @param theLayers * @param parents * the parent tracks for the supplied items * @param subjects * the actual selected items * @param _newName * name to give to the merged object * @return sufficient information to undo the merge */ public static int mergeTracks(final TrackWrapper recipient, final Layers theLayers, final Editable[] subjects) { // where we dump the new data points TrackWrapper newTrack = (TrackWrapper) recipient; // check that the legs don't overlap String failedMsg = checkTheyAreNotOverlapping(subjects); // how did we get on? if (failedMsg != null) { MessageProvider.Base.Provider.show("Merge tracks", "Sorry, " + failedMsg + " overlap in time. Please correct this and retry", MessageProvider.ERROR); return MessageProvider.ERROR; } // ok, loop through the subjects, adding them onto the target for (int i = 0; i < subjects.length; i++) { final Layer thisL = (Layer) subjects[i]; // is it a plain segment? if (thisL instanceof TrackWrapper) { // pass down through the positions/segments final Enumeration<Editable> pts = thisL.elements(); while (pts.hasMoreElements()) { final Editable obj = pts.nextElement(); if (obj instanceof SegmentList) { final SegmentList sl = (SegmentList) obj; TrackSegment newT = new TrackSegment(); duplicateFixes(sl, newT); newTrack.add(newT); } else if (obj instanceof TrackSegment) { TrackSegment ts = (TrackSegment) obj; // ok, duplicate the fixes in this segment TrackSegment newT = new TrackSegment(); duplicateFixes(ts, newT); // and add it to the new track newTrack.append(newT); } } } else if (thisL instanceof TrackSegment) { TrackSegment ts = (TrackSegment) thisL; // ok, duplicate the fixes in this segment TrackSegment newT = new TrackSegment(); duplicateFixes(ts, newT); // and add it to the new track newTrack.append(newT); } else if (thisL instanceof SegmentList) { SegmentList sl = (SegmentList) thisL; TrackSegment newT = new TrackSegment(); // ok, duplicate the fixes in this segment duplicateFixes(sl, newT); // and add it to the new track newTrack.append(newT); } } // and store the new track theLayers.addThisLayer(newTrack); return MessageProvider.OK; } private static void duplicateFixes(SegmentList sl, TrackSegment target) { final Enumeration<Editable> segs = sl.elements(); while (segs.hasMoreElements()) { final TrackSegment segment = (TrackSegment) segs.nextElement(); if (segment instanceof CoreTMASegment) { CoreTMASegment ct = (CoreTMASegment) segment; TrackSegment newSeg = new TrackSegment(ct); duplicateFixes(newSeg, target); } else { duplicateFixes(segment, target); } } } private static void duplicateFixes(TrackSegment source, TrackSegment target) { // ok, retrieve the points in the track segment Enumeration<Editable> tsPts = source.elements(); while (tsPts.hasMoreElements()) { FixWrapper existingFix = (FixWrapper) tsPts.nextElement(); FixWrapper newF = new FixWrapper(existingFix.getFix()); target.addFix(newF); } } private static String checkTheyAreNotOverlapping(final Editable[] subjects) { // first, check they don't overlap. // start off by collecting the periods final TimePeriod[] _periods = new TimePeriod.BaseTimePeriod[subjects.length]; for (int i = 0; i < subjects.length; i++) { final Editable editable = subjects[i]; TimePeriod thisPeriod = null; if (editable instanceof TrackWrapper) { final TrackWrapper tw = (TrackWrapper) editable; thisPeriod = new TimePeriod.BaseTimePeriod(tw.getStartDTG(), tw.getEndDTG()); } else if (editable instanceof TrackSegment) { final TrackSegment ts = (TrackSegment) editable; thisPeriod = new TimePeriod.BaseTimePeriod(ts.startDTG(), ts.endDTG()); } _periods[i] = thisPeriod; } // now test them. String failedMsg = null; for (int i = 0; i < _periods.length; i++) { final TimePeriod timePeriod = _periods[i]; for (int j = 0; j < _periods.length; j++) { final TimePeriod timePeriod2 = _periods[j]; // check it's not us if (timePeriod2 != timePeriod) { if (timePeriod.overlaps(timePeriod2)) { failedMsg = "'" + subjects[i].getName() + "' and '" + subjects[j].getName() + "'"; break; } } } } return failedMsg; } /** * whether to interpolate points in this track */ private boolean _interpolatePoints = false; /** * the end of the track to plot the label */ private boolean _LabelAtStart = true; private HiResDate _lastLabelFrequency = null; private HiResDate _lastSymbolFrequency = null; private HiResDate _lastArrowFrequency = null; private HiResDate _lastDataFrequency = new HiResDate(0, TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY); /** * the width of this track */ private int _lineWidth = 2; /** * the style of this line * */ private int _lineStyle = CanvasType.SOLID; /** * whether or not to link the Positions */ private boolean _linkPositions; /** * whether to show a highlight for the array centre * */ private boolean _plotArrayCentre; /** * our editable details */ protected transient Editable.EditorType _myEditor = null; /** * keep a list of points waiting to be plotted * */ transient int[] _myPts; /** * the sensor tracks for this vessel */ final private BaseLayer _mySensors; /** * the TMA solutions for this vessel */ final private BaseLayer _mySolutions; /** * keep track of how far we are through our array of points * */ transient int _ptCtr = 0; /** * whether or not to show the Positions */ private boolean _showPositions; /** * the label describing this track */ private final MWC.GUI.Shapes.TextLabel _theLabel; /** * the list of wrappers we hold */ protected SegmentList _thePositions; /** * the symbol to pass on to a snail plotter */ private MWC.GUI.Shapes.Symbols.PlainSymbol _theSnailShape; /** * working ZERO location value, to reduce number of working values */ final private WorldLocation _zeroLocation = new WorldLocation(0, 0, 0); // member functions transient private FixWrapper finisher; transient private HiResDate lastDTG; transient private FixWrapper lastFix; // for getNearestTo transient private FixWrapper nearestFix; /** * working parameters */ // for getFixesBetween transient private FixWrapper starter; transient private TimePeriod _myTimePeriod; transient private WorldArea _myWorldArea; transient private final PropertyChangeListener _locationListener; // constructors /** * Wrapper for a Track (a series of position fixes). It combines the data with * the formatting details */ public TrackWrapper() { _mySensors = new SplittableLayer(true); _mySensors.setName(SENSORS_LAYER_NAME); _mySolutions = new BaseLayer(true); _mySolutions.setName(SOLUTIONS_LAYER_NAME); // create a property listener for when fixes are moved _locationListener = new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent arg0) { fixMoved(); } }; // declare our arrays _thePositions = new TrackWrapper_Support.SegmentList(); _thePositions.setWrapper(this); _linkPositions = true; // start off with positions showing (although the default setting for a // fix // is to not show a symbol anyway). We need to make this "true" so that // when a fix position is set to visible it is not over-ridden by this // setting _showPositions = true; _theLabel = new MWC.GUI.Shapes.TextLabel(new WorldLocation(0, 0, 0), null); // set an initial location for the label _theLabel.setRelativeLocation(new Integer( MWC.GUI.Properties.LocationPropertyEditor.RIGHT)); // initialise the symbol to use for plotting this track in snail mode _theSnailShape = MWC.GUI.Shapes.Symbols.SymbolFactory .createSymbol("Submarine"); } /** * add the indicated point to the track * * @param point * the point to add */ @Override public void add(final MWC.GUI.Editable point) { boolean done = false; // see what type of object this is if (point instanceof FixWrapper) { final FixWrapper fw = (FixWrapper) point; fw.setTrackWrapper(this); addFix(fw); done = true; } // is this a sensor? else if (point instanceof SensorWrapper) { final SensorWrapper swr = (SensorWrapper) point; // add to our list _mySensors.add(swr); // tell the sensor about us swr.setHost(this); // and the track name (if we're loading from REP it will already // know // the name, but if this data is being pasted in, it may start with // a different // parent track name - so override it here) swr.setTrackName(this.getName()); // indicate success done = true; } // is this a TMA solution track? else if (point instanceof TMAWrapper) { final TMAWrapper twr = (TMAWrapper) point; // add to our list _mySolutions.add(twr); // tell the sensor about us twr.setHost(this); // and the track name (if we're loading from REP it will already // know // the name, but if this data is being pasted in, it may start with // a different // parent track name - so override it here) twr.setTrackName(this.getName()); // indicate success done = true; } else if (point instanceof TrackSegment) { final TrackSegment seg = (TrackSegment) point; seg.setWrapper(this); _thePositions.addSegment((TrackSegment) point); done = true; // hey, sort out the positions sortOutRelativePositions(); } if (!done) { MWC.GUI.Dialogs.DialogFactory.showMessage( "Add point", "Sorry it is not possible to add:" + point.getName() + " to " + this.getName()); } } /** * add the fix wrapper to the track * * @param theFix * the Fix to be added */ public void addFix(final FixWrapper theFix) { // do we have any track segments if (_thePositions.size() == 0) { // nope, add one final TrackSegment firstSegment = new TrackSegment(); firstSegment.setName("Positions"); _thePositions.addSegment(firstSegment); } // add fix to last track segment final TrackSegment last = (TrackSegment) _thePositions.last(); last.addFix(theFix); // tell the fix about it's daddy theFix.setTrackWrapper(this); // and extend the start/end DTGs if (_myTimePeriod == null) { _myTimePeriod = new TimePeriod.BaseTimePeriod(theFix.getDateTimeGroup(), theFix.getDateTimeGroup()); } else { _myTimePeriod.extend(theFix.getDateTimeGroup()); } if (_myWorldArea == null) { _myWorldArea = new WorldArea(theFix.getLocation(), theFix.getLocation()); } else { _myWorldArea.extend(theFix.getLocation()); } // we want to listen out for the fix being moved. better listen in to it // theFix.addPropertyChangeListener(PlainWrapper.LOCATION_CHANGED, // _locationListener); } /** * append this other layer to ourselves (although we don't really bother with * it) * * @param other * the layer to add to ourselves */ @Override public void append(final Layer other) { // is it a track? if ((other instanceof TrackWrapper) || (other instanceof TrackSegment)) { // yes, break it down. final java.util.Enumeration<Editable> iter = other.elements(); while (iter.hasMoreElements()) { final Editable nextItem = iter.nextElement(); if (nextItem instanceof Layer) { append((Layer) nextItem); } else { add(nextItem); } } } else { // nope, just add it to us. add(other); } } /** * instruct this object to clear itself out, ready for ditching */ @Override public final void closeMe() { // and my objects // first ask them to close themselves final Enumeration<Editable> it = getPositions(); while (it.hasMoreElements()) { final Object val = it.nextElement(); if (val instanceof PlainWrapper) { final PlainWrapper pw = (PlainWrapper) val; pw.closeMe(); } } // now ditch them _thePositions.removeAllElements(); _thePositions = null; // and my objects // first ask the sensors to close themselves if (_mySensors != null) { final Enumeration<Editable> it2 = _mySensors.elements(); while (it2.hasMoreElements()) { final Object val = it2.nextElement(); if (val instanceof PlainWrapper) { final PlainWrapper pw = (PlainWrapper) val; pw.closeMe(); } } // now ditch them _mySensors.removeAllElements(); } // now ask the solutions to close themselves if (_mySolutions != null) { final Enumeration<Editable> it2 = _mySolutions.elements(); while (it2.hasMoreElements()) { final Object val = it2.nextElement(); if (val instanceof PlainWrapper) { final PlainWrapper pw = (PlainWrapper) val; pw.closeMe(); } } // now ditch them _mySolutions.removeAllElements(); } // and our utility objects finisher = null; lastFix = null; nearestFix = null; starter = null; // and our editor _myEditor = null; // now get the parent to close itself super.closeMe(); } /** * switch the two track sections into one track section * * @param res * the previously split track sections */ public void combineSections(final Vector<TrackSegment> res) { // ok, remember the first final TrackSegment keeper = res.firstElement(); // now remove them all, adding them to the first final Iterator<TrackSegment> iter = res.iterator(); while (iter.hasNext()) { final TrackSegment pl = iter.next(); if (pl != keeper) { keeper.append((Layer) pl); } _thePositions.removeElement(pl); } // and put the keepers back in _thePositions.addSegment(keeper); } /** * return our tiered data as a single series of elements * * @return */ @Override public Enumeration<Editable> contiguousElements() { final Vector<Editable> res = new Vector<Editable>(0, 1); if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper sw = (SensorWrapper) iter.nextElement(); // is it visible? if (sw.getVisible()) { res.addAll(sw._myContacts); } } } if (_mySolutions != null) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final TMAWrapper sw = (TMAWrapper) iter.nextElement(); if (sw.getVisible()) { res.addAll(sw._myContacts); } } } if (_thePositions != null) { res.addAll(getRawPositions()); } return res.elements(); } /** * get an enumeration of the points in this track * * @return the points in this track */ @Override public Enumeration<Editable> elements() { final TreeSet<Editable> res = new TreeSet<Editable>(); if (_mySensors.size() > 0) { res.add(_mySensors); } if (_mySolutions.size() > 0) { res.add(_mySolutions); } // ok, we want to wrap our fast-data as a set of plottables // see how many track segments we have if (_thePositions.size() == 1) { // just the one, insert it res.add(_thePositions.first()); } else { // more than one, insert them as a tree res.add(_thePositions); } return new TrackWrapper_Support.IteratorWrapper(res.iterator()); } /** * export this track to REPLAY file */ @Override public final void exportShape() { // call the method in PlainWrapper this.exportThis(); } /** * filter the list to the specified time period, then inform any listeners * (such as the time stepper) * * @param start * the start dtg of the period * @param end * the end dtg of the period */ @Override public final void filterListTo(final HiResDate start, final HiResDate end) { final Enumeration<Editable> fixWrappers = getPositions(); while (fixWrappers.hasMoreElements()) { final FixWrapper fw = (FixWrapper) fixWrappers.nextElement(); final HiResDate dtg = fw.getTime(); if ((dtg.greaterThanOrEqualTo(start)) && (dtg.lessThanOrEqualTo(end))) { fw.setVisible(true); } else { fw.setVisible(false); } } // now do the same for our sensor data if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final WatchableList sw = (WatchableList) iter.nextElement(); sw.filterListTo(start, end); } // through the sensors } // whether we have any sensors // and our solution data if (_mySolutions != null) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final WatchableList sw = (WatchableList) iter.nextElement(); sw.filterListTo(start, end); } // through the sensors } // whether we have any sensors // do we have any property listeners? if (getSupport() != null) { final Debrief.GUI.Tote.StepControl.somePeriod newPeriod = new Debrief.GUI.Tote.StepControl.somePeriod( start, end); getSupport().firePropertyChange(WatchableList.FILTERED_PROPERTY, null, newPeriod); } } @Override public void findNearestHotSpotIn(final Point cursorPos, final WorldLocation cursorLoc, final ComponentConstruct currentNearest, final Layer parentLayer) { // initialise thisDist, since we're going to be over-writing it WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS); // cycle through the fixes final Enumeration<Editable> fixes = getPositions(); while (fixes.hasMoreElements()) { final FixWrapper thisF = (FixWrapper) fixes.nextElement(); // only check it if it's visible if (thisF.getVisible()) { // how far away is it? thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist); final WorldLocation fixLocation = new WorldLocation(thisF.getLocation()) { private static final long serialVersionUID = 1L; @Override public void addToMe(final WorldVector delta) { super.addToMe(delta); thisF.setFixLocation(this); } }; // try range currentNearest.checkMe(this, thisDist, null, parentLayer, fixLocation); } } } @Override public void findNearestHotSpotIn(final Point cursorPos, final WorldLocation cursorLoc, final LocationConstruct currentNearest, final Layer parentLayer, final Layers theData) { // initialise thisDist, since we're going to be over-writing it WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS); // cycle through the fixes final Enumeration<Editable> fixes = getPositions(); while (fixes.hasMoreElements()) { final FixWrapper thisF = (FixWrapper) fixes.nextElement(); if (thisF.getVisible()) { // how far away is it? thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist); // is it closer? currentNearest.checkMe(this, thisDist, null, parentLayer); } } } public void findNearestSegmentHotspotFor(final WorldLocation cursorLoc, final Point cursorPt, final LocationConstruct currentNearest) { // initialise thisDist, since we're going to be over-writing it WorldDistance thisDist; // cycle through the track segments final Collection<Editable> segments = _thePositions.getData(); for (final Iterator<Editable> iterator = segments.iterator(); iterator .hasNext();) { final TrackSegment thisSeg = (TrackSegment) iterator.next(); if (thisSeg.getVisible()) { // how far away is it? thisDist = new WorldDistance(thisSeg.rangeFrom(cursorLoc), WorldDistance.DEGS); // is it closer? currentNearest.checkMe(thisSeg, thisDist, null, this); } } } /** * one of our fixes has moved. better tell any bits that rely on the locations * of our bits * * @param theFix * the fix that moved */ public void fixMoved() { if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper nextS = (SensorWrapper) iter.nextElement(); nextS.setHost(this); } } } /** * return the arrow frequencies for the track * * @return frequency in seconds */ public final HiResDate getArrowFrequency() { return _lastArrowFrequency; } /** * calculate a position the specified distance back along the ownship track * (note, we always interpolate the parent track position) * * @param searchTime * the time we're looking at * @param sensorOffset * how far back the sensor should be * @param wormInHole * whether to plot a straight line back, or make sensor follow * ownship * @return the location */ public FixWrapper getBacktraceTo(final HiResDate searchTime, final ArrayLength sensorOffset, final boolean wormInHole) { FixWrapper res = null; if (wormInHole && sensorOffset != null) { res = WormInHoleOffset.getWormOffsetFor(this, searchTime, sensorOffset); } else { final boolean parentInterpolated = getInterpolatePoints(); setInterpolatePoints(true); final MWC.GenericData.Watchable[] list = getNearestTo(searchTime); // and restore the interpolated value setInterpolatePoints(parentInterpolated); FixWrapper wa = null; if (list.length > 0) { wa = (FixWrapper) list[0]; } // did we find it? if (wa != null) { // yes, store it res = new FixWrapper(wa.getFix().makeCopy()); // ok, are we dealing with an offset? if (sensorOffset != null) { // get the current heading final double hdg = wa.getCourse(); // and calculate where it leaves us final WorldVector vector = new WorldVector(hdg, sensorOffset, null); // now apply this vector to the origin res.setLocation(new WorldLocation(res.getLocation().add(vector))); } } } return res; } // editing parameters /** * what geographic area is covered by this track? * * @return get the outer bounds of the area */ @Override public final WorldArea getBounds() { // we no longer just return the bounds of the track, because a portion // of the track may have been made invisible. // instead, we will pass through the full dataset and find the outer // bounds // of the visible area WorldArea res = null; if (!getVisible()) { // hey, we're invisible, return null } else { final Enumeration<Editable> it = getPositions(); while (it.hasMoreElements()) { final FixWrapper fw = (FixWrapper) it.nextElement(); // is this point visible? if (fw.getVisible()) { // has our data been initialised? if (res == null) { // no, initialise it res = new WorldArea(fw.getLocation(), fw.getLocation()); } else { // yes, extend to include the new area res.extend(fw.getLocation()); } } } // also extend to include our sensor data if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final PlainWrapper sw = (PlainWrapper) iter.nextElement(); final WorldArea theseBounds = sw.getBounds(); if (theseBounds != null) { if (res == null) { res = new WorldArea(theseBounds); } else { res.extend(sw.getBounds()); } } } // step through the sensors } // whether we have any sensors // and our solution data if (_mySolutions != null) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final PlainWrapper sw = (PlainWrapper) iter.nextElement(); final WorldArea theseBounds = sw.getBounds(); if (theseBounds != null) { if (res == null) { res = new WorldArea(theseBounds); } else { res.extend(sw.getBounds()); } } } // step through the sensors } // whether we have any sensors } // whether we're visible // SPECIAL CASE: if we're a DR track, the positions all // have the same value if (res != null) { // have we ended up with an empty area? if (res.getHeight() == 0) { // ok - force a bounds update sortOutRelativePositions(); // and retrieve the bounds of hte first segment res = this.getSegments().first().getBounds(); } } return res; } /** * the time of the last fix * * @return the DTG */ @Override public final HiResDate getEndDTG() { HiResDate dtg = null; final TimePeriod res = getTimePeriod(); if (res != null) { dtg = res.getEndDTG(); } return dtg; } /** * the editable details for this track * * @return the details */ @Override public Editable.EditorType getInfo() { if (_myEditor == null) { _myEditor = new trackInfo(this); } return _myEditor; } /** * create a new, interpolated point between the two supplied * * @param previous * the previous point * @param next * the next point * @return and interpolated point */ private final FixWrapper getInterpolatedFix(final FixWrapper previous, final FixWrapper next, final HiResDate requestedDTG) { FixWrapper res = null; // do we have a start point if (previous == null) { res = next; } // hmm, or do we have an end point? if (next == null) { res = previous; } // did we find it? if (res == null) { res = FixWrapper.interpolateFix(previous, next, requestedDTG); } return res; } @Override public final boolean getInterpolatePoints() { return _interpolatePoints; } /** * get the set of fixes contained within this time period (inclusive of both * end values) * * @param start * start DTG * @param end * end DTG * @return series of fixes */ @Override public final Collection<Editable> getItemsBetween(final HiResDate start, final HiResDate end) { SortedSet<Editable> set = null; // does our track contain any data at all if (_thePositions.size() > 0) { // see if we have _any_ points in range if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start))) { // don't bother with it. } else { // SPECIAL CASE! If we've been asked to show interpolated data // points, // then // we should produce a series of items between the indicated // times. How // about 1 minute resolution? if (getInterpolatePoints()) { final long ourInterval = 1000 * 60; // one minute set = new TreeSet<Editable>(); for (long newTime = start.getDate().getTime(); newTime < end .getDate().getTime(); newTime += ourInterval) { final HiResDate newD = new HiResDate(newTime); final Watchable[] nearestOnes = getNearestTo(newD); if (nearestOnes.length > 0) { final FixWrapper nearest = (FixWrapper) nearestOnes[0]; set.add(nearest); } } } else { // bugger that - get the real data // have a go.. if (starter == null) { starter = new FixWrapper(new Fix((start), _zeroLocation, 0.0, 0.0)); } else { starter.getFix().setTime(new HiResDate(0, start.getMicros() - 1)); } if (finisher == null) { finisher = new FixWrapper(new Fix(new HiResDate(0, end.getMicros() + 1), _zeroLocation, 0.0, 0.0)); } else { finisher.getFix().setTime(new HiResDate(0, end.getMicros() + 1)); } // ok, ready, go for it. set = getPositionsBetween(starter, finisher); } } } return set; } /** * method to allow the setting of label frequencies for the track * * @return frequency to use */ public final HiResDate getLabelFrequency() { return this._lastLabelFrequency; } /** * what is the style used for plotting this track? * * @return */ public int getLineStyle() { return _lineStyle; } /** * the line thickness (convenience wrapper around width) * * @return */ @Override public int getLineThickness() { return _lineWidth; } /** * whether to link points * * @return */ public boolean getLinkPositions() { return _linkPositions; } /** * just have the one property listener - rather than an anonymous class * * @return */ public PropertyChangeListener getLocationListener() { return _locationListener; } /** * name of this Track (normally the vessel name) * * @return the name */ @Override public final String getName() { return _theLabel.getString(); } /** * get our child segments * * @return */ public SegmentList getSegments() { return _thePositions; } /** * whether to show the track label at the start or end of the track * * @return yes/no to indicate <I>At Start</I> */ public final boolean getNameAtStart() { return _LabelAtStart; } /** * the relative location of the label * * @return the relative location */ public final Integer getNameLocation() { return _theLabel.getRelativeLocation(); } /** * whether the track label is visible or not * * @return yes/no */ public final boolean getNameVisible() { return _theLabel.getVisible(); } /** * find the fix nearest to this time (or the first fix for an invalid time) * * @param DTG * the time of interest * @return the nearest fix */ @Override public final Watchable[] getNearestTo(final HiResDate srchDTG) { /** * we need to end up with a watchable, not a fix, so we need to work our way * through the fixes */ FixWrapper res = null; // check that we do actually contain some data if (_thePositions.size() == 0) { return new MWC.GenericData.Watchable[] {}; } // special case - if we've been asked for an invalid time value if (srchDTG == TimePeriod.INVALID_DATE) { final TrackSegment seg = (TrackSegment) _thePositions.first(); final FixWrapper fix = (FixWrapper) seg.first(); // just return our first location return new MWC.GenericData.Watchable[] { fix }; } // see if this is the DTG we have just requestsed if ((srchDTG.equals(lastDTG)) && (lastFix != null)) { res = lastFix; } else { final TrackSegment firstSeg = (TrackSegment) _thePositions.first(); final TrackSegment lastSeg = (TrackSegment) _thePositions.last(); if ((firstSeg != null) && (firstSeg.size() > 0)) { // see if this DTG is inside our data range // in which case we will just return null final FixWrapper theFirst = (FixWrapper) firstSeg.first(); final FixWrapper theLast = (FixWrapper) lastSeg.last(); if ((srchDTG.greaterThan(theFirst.getTime())) && (srchDTG.lessThanOrEqualTo(theLast.getTime()))) { // yes it's inside our data range, find the first fix // after the indicated point // right, increment the time, since we want to allow matching // points // HiResDate DTG = new HiResDate(0, srchDTG.getMicros() + 1); // see if we have to create our local temporary fix if (nearestFix == null) { nearestFix = new FixWrapper(new Fix(srchDTG, _zeroLocation, 0.0, 0.0)); } else { nearestFix.getFix().setTime(srchDTG); } // right, we really should be filtering the list according to if // the // points are visible. // how do we do filters? // get the data. use tailSet, since it's inclusive... SortedSet<Editable> set = getRawPositions().tailSet(nearestFix); // see if the requested DTG was inside the range of the data if (!set.isEmpty() && (set.size() > 0)) { res = (FixWrapper) set.first(); // is this one visible? if (!res.getVisible()) { // right, the one we found isn't visible. duplicate the // set, so that // we can remove items // without affecting the parent TreeSet<Editable> tmpSet = new TreeSet<Editable>(set); // ok, start looping back until we find one while ((!res.getVisible()) && (tmpSet.size() > 0)) { // the first one wasn't, remove it tmpSet.remove(res); if (tmpSet.size() > 0) { res = (FixWrapper) tmpSet.first(); } } // SPECIAL CASE: when the time period is after // the end of the filtered period, the above logic will // result in the very last point on the list being // selected. In truth, the first point on the // list is closer to the requested time. // when this happens, return the first item in the // original list. if(tmpSet.size() == 0) { res = (FixWrapper) set.first(); } } } // right, that's the first points on or before the indicated // DTG. Are we // meant // to be interpolating? if (res != null) { if (getInterpolatePoints()) { // right - just check that we aren't actually on the // correct time // point. // HEY, USE THE ORIGINAL SEARCH TIME, NOT THE // INCREMENTED ONE, // SINCE WE DON'T WANT TO COMPARE AGAINST A MODIFIED // TIME if (!res.getTime().equals(srchDTG)) { // right, we haven't found an actual data point. // Better calculate // one // hmm, better also find the point before our one. // the // headSet operation is exclusive - so we need to // find the one // after the first final SortedSet<Editable> otherSet = getRawPositions().headSet( nearestFix); FixWrapper previous = null; if (!otherSet.isEmpty()) { previous = (FixWrapper) otherSet.last(); } // did it work? if (previous != null) { // cool, sort out the interpolated point USING // THE ORIGINAL // SEARCH TIME res = getInterpolatedFix(previous, res, srchDTG); } } } } } else if (srchDTG.equals(theFirst.getDTG())) { // aaah, special case. just see if we're after a data point // that's the // same // as our start time res = theFirst; } } // and remember this fix lastFix = res; lastDTG = srchDTG; } if (res != null) { return new MWC.GenericData.Watchable[] { res }; } else { return new MWC.GenericData.Watchable[] {}; } } public boolean getPlotArrayCentre() { return _plotArrayCentre; } /** * get the position data, not all the sensor/contact/position data mixed * together * * @return */ public final Enumeration<Editable> getPositions() { final SortedSet<Editable> res = getRawPositions(); return new TrackWrapper_Support.IteratorWrapper(res.iterator()); } private SortedSet<Editable> getPositionsBetween(final FixWrapper starter2, final FixWrapper finisher2) { // first get them all as one list final SortedSet<Editable> pts = getRawPositions(); // now do the sort return pts.subSet(starter2, finisher2); } /** * whether positions are being shown * * @return */ public final boolean getPositionsVisible() { return _showPositions; } private SortedSet<Editable> getRawPositions() { SortedSet<Editable> res = null; // do we just have the one list? if (_thePositions.size() == 1) { final TrackSegment p = (TrackSegment) _thePositions.first(); res = (SortedSet<Editable>) p.getData(); } else { // loop through them res = new TreeSet<Editable>(); final Enumeration<Editable> segs = _thePositions.elements(); while (segs.hasMoreElements()) { // get this segment final TrackSegment seg = (TrackSegment) segs.nextElement(); // add all the points res.addAll(seg.getData()); } } return res; } /** * method to allow the setting of data sampling frequencies for the track & * sensor data * * @return frequency to use */ public final HiResDate getResampleDataAt() { return this._lastDataFrequency; } /** * get the list of sensors for this track */ public final BaseLayer getSensors() { return _mySensors; } /** * return the symbol to be used for plotting this track in snail mode */ @Override public final MWC.GUI.Shapes.Symbols.PlainSymbol getSnailShape() { return _theSnailShape; } /** * get the list of sensors for this track */ public final BaseLayer getSolutions() { return _mySolutions; } // watchable (tote related) parameters /** * the earliest fix in the track * * @return the DTG */ @Override public final HiResDate getStartDTG() { HiResDate res = null; final TimePeriod period = getTimePeriod(); if (period != null) { res = period.getStartDTG(); } return res; } /** * get the color used to plot the symbol * * @return the color */ public final Color getSymbolColor() { return _theSnailShape.getColor(); } /** * return the symbol frequencies for the track * * @return frequency in seconds */ public final HiResDate getSymbolFrequency() { return _lastSymbolFrequency; } public WorldDistance getSymbolLength() { WorldDistance res = null; if (_theSnailShape instanceof WorldScaledSym) { final WorldScaledSym sym = (WorldScaledSym) _theSnailShape; res = sym.getLength(); } return res; } /** * get the type of this symbol */ public final String getSymbolType() { return _theSnailShape.getType(); } public WorldDistance getSymbolWidth() { WorldDistance res = null; if (_theSnailShape instanceof WorldScaledSym) { final WorldScaledSym sym = (WorldScaledSym) _theSnailShape; res = sym.getWidth(); } return res; } private TimePeriod getTimePeriod() { TimePeriod res = null; final Enumeration<Editable> segs = _thePositions.elements(); while (segs.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segs.nextElement(); // do we have a dtg? if ((seg.startDTG() != null) && (seg.endDTG() != null)) { // yes, get calculating if (res == null) { res = new TimePeriod.BaseTimePeriod(seg.startDTG(), seg.endDTG()); } else { res.extend(seg.startDTG()); res.extend(seg.endDTG()); } } } return res; } /** * the colour of the points on the track * * @return the colour */ public final Color getTrackColor() { return getColor(); } /** * font handler * * @return the font to use for the label */ public final java.awt.Font getTrackFont() { return _theLabel.getFont(); } /** * get the set of fixes contained within this time period which haven't been * filtered, and which have valid depths. The isVisible flag indicates whether * a track has been filtered or not. We also have the getVisibleFixesBetween * method (below) which decides if a fix is visible if it is set to Visible, * and it's label or symbol are visible. * <p/> * We don't have to worry about a valid depth, since 3d doesn't show points * with invalid depth values * * @param start * start DTG * @param end * end DTG * @return series of fixes */ public final Collection<Editable> getUnfilteredItems(final HiResDate start, final HiResDate end) { // see if we have _any_ points in range if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start))) { return null; } if (this.getVisible() == false) { return null; } // get ready for the output final Vector<Editable> res = new Vector<Editable>(0, 1); // put the data into a period final TimePeriod thePeriod = new TimePeriod.BaseTimePeriod(start, end); // step through our fixes final Enumeration<Editable> iter = getPositions(); while (iter.hasMoreElements()) { final FixWrapper fw = (FixWrapper) iter.nextElement(); if (fw.getVisible()) { // is it visible? if (thePeriod.contains(fw.getTime())) { // hey, it's valid - continue res.add(fw); } } } return res; } /** * whether this object has editor details * * @return yes/no */ @Override public final boolean hasEditor() { return true; } @Override public boolean hasOrderedChildren() { return false; } /** * quick accessor for how many fixes we have * * @return */ public int numFixes() { return getRawPositions().size(); } private void checkPointsArray() { // is our points store long enough? if ((_myPts == null) || (_myPts.length < numFixes() * 2)) { _myPts = new int[numFixes() * 2]; } // reset the points counter _ptCtr = 0; } private boolean paintFixes(final CanvasType dest) { // we need an array to store the polyline of points in. Check it's big // enough checkPointsArray(); // keep track of if we have plotted any points (since // we won't be plotting the name if none of the points are visible). // this typically occurs when filtering is applied and a short // track is completely outside the time period boolean plotted_anything = false; // java.awt.Point lastP = null; Color lastCol = null; final int defaultlineStyle = getLineStyle(); boolean locatedTrack = false; WorldLocation lastLocation = null; FixWrapper lastFix = null; final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); // how shall we plot this segment? final int thisLineStyle; // is the parent using the default style? if (defaultlineStyle == CanvasType.SOLID) { // yes, let's override it, if the segment wants to thisLineStyle = seg.getLineStyle(); } else { // no, we're using a custom style - don't override it. thisLineStyle = defaultlineStyle; } // SPECIAL HANDLING, SEE IF IT'S A TMA SEGMENT TO BE PLOTTED IN // RELATIVE MODE final boolean isRelative = seg.getPlotRelative(); WorldLocation tmaLastLoc = null; long tmaLastDTG = 0; // if it's not a relative track, and it's not visible, we don't // need to work with ut if (!getVisible() && !isRelative) { continue; } // is this segment visible? if (!seg.getVisible()) { continue; } final Enumeration<Editable> fixWrappers = seg.elements(); while (fixWrappers.hasMoreElements()) { final FixWrapper fw = (FixWrapper) fixWrappers.nextElement(); // now there's a chance that our fix has forgotten it's // parent, // particularly if it's the victim of a // copy/paste operation. Tell it about it's children fw.setTrackWrapper(this); // is this fix visible? if (!fw.getVisible()) { // nope. Don't join it to the last position. // ok, if we've built up a polygon, we need to write it // now paintSetOfPositions(dest, lastCol, thisLineStyle); } // Note: we're carrying on working with this position even // if it isn't visible, // since we need to use non-visible positions to build up a // DR track. // ok, so we have plotted something plotted_anything = true; // ok, are we in relative? if (isRelative) { final long thisTime = fw.getDateTimeGroup().getDate().getTime(); // ok, is this our first location? if (tmaLastLoc == null) { tmaLastLoc = new WorldLocation(seg.getTrackStart()); lastLocation = tmaLastLoc; } else { // calculate a new vector final long timeDelta = thisTime - tmaLastDTG; if (lastFix != null) { final double speedKts = lastFix.getSpeed(); final double courseRads = lastFix.getCourse(); final double depthM = lastFix.getDepth(); // use the value of depth as read in from the // file tmaLastLoc.setDepth(depthM); final WorldVector thisVec = seg.vectorFor(timeDelta, speedKts, courseRads); tmaLastLoc.addToMe(thisVec); lastLocation = tmaLastLoc; } } lastFix = fw; tmaLastDTG = thisTime; // dump the location into the fix fw.setFixLocationSilent(new WorldLocation(tmaLastLoc)); } else { // this is an absolute position lastLocation = fw.getLocation(); } // ok, we only do this writing to screen if the actual // position is visible if (!fw.getVisible()) continue; final java.awt.Point thisP = dest.toScreen(lastLocation); // just check that there's enough GUI to create the plot // (i.e. has a point been returned) if (thisP == null) { return false; } // so, we're looking at the first data point. Do // we want to use this to locate the track name? // or have we already sorted out the location if (_LabelAtStart && !locatedTrack) { locatedTrack = true; _theLabel.setLocation(new WorldLocation(lastLocation)); } // are we if (getLinkPositions() && (getLineStyle() != LineStylePropertyEditor.UNCONNECTED)) { // right, just check if we're a different colour to // the previous one final Color thisCol = fw.getColor(); // do we know the previous colour if (lastCol == null) { lastCol = thisCol; } // is this to be joined to the previous one? if (fw.getLineShowing()) { // so, grow the the polyline, unless we've got a // colour change... if (thisCol != lastCol) { // add our position to the list - so it // finishes on us _myPts[_ptCtr++] = thisP.x; _myPts[_ptCtr++] = thisP.y; // yup, better get rid of the previous // polygon paintSetOfPositions(dest, lastCol, thisLineStyle); } // add our position to the list - we'll output // the polyline at the end _myPts[_ptCtr++] = thisP.x; _myPts[_ptCtr++] = thisP.y; } else { // nope, output however much line we've got so // far - since this // line won't be joined to future points paintSetOfPositions(dest, thisCol, thisLineStyle); // start off the next line _myPts[_ptCtr++] = thisP.x; _myPts[_ptCtr++] = thisP.y; } /* * set the colour of the track from now on to this colour, so that the * "link" to the next fix is set to this colour if left unchanged */ dest.setColor(fw.getColor()); // and remember the last colour lastCol = thisCol; } if (_showPositions && fw.getVisible()) { // this next method just paints the fix. we've put the // call into paintThisFix so we can override the painting // in the CompositeTrackWrapper class paintThisFix(dest, lastLocation, fw); } }// while fixWrappers has more elements // SPECIAL HANDLING, IF IT'S A TMA SEGMENT PLOT THE VECTOR LABEL if (seg instanceof CoreTMASegment) { CoreTMASegment tma = (CoreTMASegment) seg; WorldLocation firstLoc = seg.first().getBounds().getCentre(); WorldLocation lastLoc = seg.last().getBounds().getCentre(); Font f = new Font("Sans Serif", Font.PLAIN, 11); Color c = _theLabel.getColor(); // tell the segment it's being stretched final String spdTxt = MWC.Utilities.TextFormatting.GeneralFormat .formatOneDecimalPlace(tma.getSpeed().getValueIn(WorldSpeed.Kts)); // copied this text from RelativeTMASegment double courseVal = tma.getCourse(); if (courseVal < 0) courseVal += 360; String textLabel = "[" + spdTxt + " kts " + (int) courseVal + "\u00B0]"; // ok, now plot it CanvasTypeUtilities.drawLabelOnLine(dest, textLabel, f, c, firstLoc, lastLoc, 1.2, true); textLabel = tma.getName().replace(TextLabel.NEWLINE_MARKER, " "); CanvasTypeUtilities.drawLabelOnLine(dest, textLabel, f, c, firstLoc, lastLoc, 1.2, false); } // ok, just see if we have any pending polylines to paint paintSetOfPositions(dest, lastCol, thisLineStyle); } // are we trying to put the label at the end of the track? // have we found at least one location to plot? if (!_LabelAtStart && lastLocation != null) { _theLabel.setLocation(new WorldLocation(lastLocation)); } return plotted_anything; } private void paintSingleTrackLabel(final CanvasType dest) { // check that we have found a location for the label if (_theLabel.getLocation() == null) return; // is the first track a DR track? final TrackSegment t1 = (TrackSegment) _thePositions.first(); if (t1.getPlotRelative()) { _theLabel.setFont(_theLabel.getFont().deriveFont(Font.ITALIC)); } else if (_theLabel.getFont().isItalic()) { _theLabel.setFont(_theLabel.getFont().deriveFont(Font.PLAIN)); } // check that we have set the name for the label if (_theLabel.getString() == null) { _theLabel.setString(getName()); } // does the first label have a colour? if (_theLabel.getColor() == null) { // check we have a colour Color labelColor = getColor(); // did we ourselves have a colour? if (labelColor == null) { // nope - do we have any legs? final Enumeration<Editable> numer = this.getPositions(); if (numer.hasMoreElements()) { // ok, use the colour of the first point final FixWrapper pos = (FixWrapper) numer.nextElement(); labelColor = pos.getColor(); } } _theLabel.setColor(labelColor); } // and paint it _theLabel.paint(dest); } private void paintMultipleSegmentLabel(final CanvasType dest) { final Enumeration<Editable> posis = _thePositions.elements(); while (posis.hasMoreElements()) { final TrackSegment thisE = (TrackSegment) posis.nextElement(); // is this segment visible? if (!thisE.getVisible()) { continue; } // does it have visible data points? if(thisE.size() == 0) { continue; } // is the first track a DR track? if (thisE.getPlotRelative()) { _theLabel.setFont(_theLabel.getFont().deriveFont(Font.ITALIC)); } else if (_theLabel.getFont().isItalic()) { _theLabel.setFont(_theLabel.getFont().deriveFont(Font.PLAIN)); } final WorldLocation theLoc = thisE.getTrackStart(); final String oldTxt = _theLabel.getString(); _theLabel.setString(thisE.getName()); // just see if this is a planning segment, with its own colors if (thisE instanceof PlanningSegment) { final PlanningSegment ps = (PlanningSegment) thisE; _theLabel.setColor(ps.getColor()); } else { _theLabel.setColor(getColor()); } _theLabel.setLocation(theLoc); _theLabel.paint(dest); _theLabel.setString(oldTxt); } } /** * draw this track (we can leave the Positions to draw themselves) * * @param dest * the destination */ @Override public final void paint(final CanvasType dest) { // check we are visible and have some track data, else we won't work if (!getVisible() || this.getStartDTG() == null) { return; } // set the thickness for this track dest.setLineWidth(_lineWidth); // and set the initial colour for this track if (getColor() != null) dest.setColor(getColor()); // firstly plot the solutions if (_mySolutions.getVisible()) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final TMAWrapper sw = (TMAWrapper) iter.nextElement(); // just check that the sensor knows we're it's parent if (sw.getHost() == null) { sw.setHost(this); } // and do the paint sw.paint(dest); } // through the solutions } // whether the solutions are visible // now plot the sensors if (_mySensors.getVisible()) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper sw = (SensorWrapper) iter.nextElement(); // just check that the sensor knows we're it's parent if (sw.getHost() == null) { sw.setHost(this); } // and do the paint sw.paint(dest); } // through the sensors } // whether the sensor layer is visible // and now the track itself // just check if we are drawing anything at all if ((!getLinkPositions() || getLineStyle() == LineStylePropertyEditor.UNCONNECTED) && (!_showPositions)) { return; } // let the fixes draw themselves in final boolean plotted_anything = paintFixes(dest); // and draw the track label // still, we only plot the track label if we have plotted any // points if (_theLabel.getVisible() && plotted_anything) { // just see if we have multiple segments. if we do, // name them individually if (this._thePositions.size() <= 1) { paintSingleTrackLabel(dest); } else { // we've got multiple segments, name them paintMultipleSegmentLabel(dest); } } // if the label is visible // paint vector label if (plotted_anything) { paintVectorLabel(dest); } } private void paintVectorLabel(final CanvasType dest) { if (getVisible()) { final Enumeration<Editable> posis = _thePositions.elements(); while (posis.hasMoreElements()) { final TrackSegment thisE = (TrackSegment) posis.nextElement(); // paint only visible planning segments if ((thisE instanceof PlanningSegment) && thisE.getVisible()) { PlanningSegment ps = (PlanningSegment) thisE; ps.paintLabel(dest); } } } } /** * get the fix to paint itself * * @param dest * @param lastLocation * @param fw */ protected void paintThisFix(final CanvasType dest, final WorldLocation lastLocation, final FixWrapper fw) { fw.paintMe(dest, lastLocation, fw.getColor()); } /** * this accessor is present for debug/testing purposes only. Do not use * outside testing! * * @return the list of screen locations about to be plotted */ public int[] debug_GetPoints() { return _myPts; } /** * this accessor is present for debug/testing purposes only. Do not use * outside testing! * * @return the length of the list of screen points waiting to be plotted */ public int debug_GetPointCtr() { return _ptCtr; } /** * paint any polyline that we've built up * * @param dest * - where we're painting to * @param thisCol * @param lineStyle */ private void paintSetOfPositions(final CanvasType dest, final Color thisCol, final int lineStyle) { if (_ptCtr > 0) { dest.setColor(thisCol); dest.setLineStyle(lineStyle); final int[] poly = new int[_ptCtr]; System.arraycopy(_myPts, 0, poly, 0, _ptCtr); dest.drawPolyline(poly); dest.setLineStyle(CanvasType.SOLID); // and reset the counter _ptCtr = 0; } } /** * return the range from the nearest corner of the track * * @param other * the other location * @return the range */ @Override public final double rangeFrom(final WorldLocation other) { double nearest = -1; // do we have a track? if (_myWorldArea != null) { // find the nearest point on the track nearest = _myWorldArea.rangeFrom(other); } return nearest; } /** * remove the requested item from the track * * @param point * the point to remove */ @Override public final void removeElement(final Editable point) { // just see if it's a sensor which is trying to be removed if (point instanceof SensorWrapper) { _mySensors.removeElement(point); // tell the sensor wrapper to forget about us final TacticalDataWrapper sw = (TacticalDataWrapper) point; sw.setHost(null); } else if (point instanceof TMAWrapper) { _mySolutions.removeElement(point); // tell the sensor wrapper to forget about us final TacticalDataWrapper sw = (TacticalDataWrapper) point; sw.setHost(null); } else if (point instanceof SensorContactWrapper) { // ok, cycle through our sensors, try to remove this contact... final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper sw = (SensorWrapper) iter.nextElement(); // try to remove it from this one... sw.removeElement(point); } } else if (point instanceof TrackSegment) { _thePositions.removeElement(point); // and clear the parent item final TrackSegment ts = (TrackSegment) point; ts.setWrapper(null); } else if (point == _mySensors) { // ahh, the user is trying to delete all the solution, cycle through // them final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final Editable editable = iter.nextElement(); // tell the sensor wrapper to forget about us final TacticalDataWrapper sw = (TacticalDataWrapper) editable; sw.setHost(null); } // and empty them out _mySensors.removeAllElements(); } else if (point == _mySolutions) { // ahh, the user is trying to delete all the solution, cycle through // them final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final Editable editable = iter.nextElement(); // tell the sensor wrapper to forget about us final TacticalDataWrapper sw = (TacticalDataWrapper) editable; sw.setHost(null); } // and empty them out _mySolutions.removeAllElements(); } else { // loop through the segments final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); seg.removeElement(point); // and stop listening to it (if it's a fix) if (point instanceof FixWrapper) { final FixWrapper fw = (FixWrapper) point; fw.removePropertyChangeListener(PlainWrapper.LOCATION_CHANGED, _locationListener); } } } } // LAYER support methods /** * pass through the track, resetting the labels back to their original DTG */ @FireReformatted public void resetLabels() { FormatTracks.formatTrack(this); } /** * how frequently symbols are placed on the track * * @param theVal * frequency in seconds */ public final void setArrowFrequency(final HiResDate theVal) { this._lastArrowFrequency = theVal; // set the "showPositions" parameter, as long as we are // not setting the symbols off if (theVal.getMicros() != 0.0) { this.setPositionsVisible(true); } final FixSetter setSymbols = new FixSetter() { @Override public void execute(final FixWrapper fix, final boolean val) { fix.setArrowShowing(val); } }; setFixes(setSymbols, theVal); } /** * set the colour of this track label * * @param theCol * the colour */ @Override @FireReformatted public final void setColor(final Color theCol) { // do the parent super.setColor(theCol); // now do our processing _theLabel.setColor(theCol); } /** * the setter function which passes through the track */ private void setFixes(final FixSetter setter, final HiResDate theVal) { if (theVal == null) { return; } final long freq = theVal.getMicros(); // briefly check if we are revealing/hiding all times (ie if freq is 1 // or 0) if (freq == TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY) { // show all of the labels final Enumeration<Editable> iter = getPositions(); while (iter.hasMoreElements()) { final FixWrapper fw = (FixWrapper) iter.nextElement(); setter.execute(fw, true); } } else { // no, we're not just blindly doing all of them. do them at the // correct // frequency // hide all of the labels/symbols first final Enumeration<Editable> enumA = getPositions(); while (enumA.hasMoreElements()) { final FixWrapper fw = (FixWrapper) enumA.nextElement(); setter.execute(fw, false); } if (freq == 0) { // we can ignore this, since we have just hidden all of the // points } else { if (getStartDTG() != null) { // pass through the track setting the values // sort out the start and finish times long start_time = getStartDTG().getMicros(); final long end_time = getEndDTG().getMicros(); // first check that there is a valid time period between start // time // and end time if (start_time + freq < end_time) { long num = start_time / freq; // we need to add one to the quotient if it has rounded down if (start_time % freq == 0) { // start is at our freq, so we don't need to increment } else { num++; } // calculate new start time start_time = num * freq; } else { // there is not one of our 'intervals' between the start and // the end, // so use the start time } while (start_time <= end_time) { // right, increment the start time by one, because we were // getting the // fix immediately before the requested time final HiResDate thisDTG = new HiResDate(0, start_time); final MWC.GenericData.Watchable[] list = this.getNearestTo(thisDTG); // check we found some if (list.length > 0) { final FixWrapper fw = (FixWrapper) list[0]; setter.execute(fw, true); } // produce the next time step start_time += freq; } } } } } @Override public final void setInterpolatePoints(final boolean val) { _interpolatePoints = val; } /** * set the label frequency (in seconds) * * @param theVal * frequency to use */ public final void setLabelFrequency(final HiResDate theVal) { this._lastLabelFrequency = theVal; final FixSetter setLabel = new FixSetter() { @Override public void execute(final FixWrapper fix, final boolean val) { fix.setLabelShowing(val); } }; setFixes(setLabel, theVal); } // track-shifting operation // support for dragging the track around /** * set the style used for plotting the lines for this track * * @param val */ public void setLineStyle(final int val) { _lineStyle = val; } /** * the line thickness (convenience wrapper around width) */ public void setLineThickness(final int val) { _lineWidth = val; } /** * whether to link points * * @param linkPositions */ public void setLinkPositions(final boolean linkPositions) { _linkPositions = linkPositions; } /** * set the name of this track (normally the name of the vessel * * @param theName * the name as a String */ @Override @FireReformatted public final void setName(final String theName) { _theLabel.setString(theName); } /** * whether to show the track name at the start or end of the track * * @param val * yes no for <I>show label at start</I> */ public final void setNameAtStart(final boolean val) { _LabelAtStart = val; } /** * the relative location of the label * * @param val * the relative location */ public final void setNameLocation(final Integer val) { _theLabel.setRelativeLocation(val); } /** * whether to show the track name * * @param val * yes/no */ public final void setNameVisible(final boolean val) { _theLabel.setVisible(val); } public void setPlotArrayCentre(final boolean plotArrayCentre) { _plotArrayCentre = plotArrayCentre; } /** * whether to show the position fixes * * @param val * yes/no */ public final void setPositionsVisible(final boolean val) { _showPositions = val; } /** * set the data frequency (in seconds) for the track & sensor data * * @param theVal * frequency to use */ @FireExtended public final void setResampleDataAt(final HiResDate theVal) { this._lastDataFrequency = theVal; // have a go at trimming the start time to a whole number of intervals final long interval = theVal.getMicros(); // do we have a start time (we may just be being tested...) if (this.getStartDTG() == null) { return; } final long currentStart = this.getStartDTG().getMicros(); long startTime = (currentStart / interval) * interval; // just check we're in the range if (startTime < currentStart) { startTime += interval; } // just check it's not a barking frequency if (theVal.getDate().getTime() <= 0) { // ignore, we don't need to do anything for a zero or a -1 } else { final SegmentList segments = _thePositions; final Enumeration<Editable> theEnum = segments.elements(); while (theEnum.hasMoreElements()) { final TrackSegment seg = (TrackSegment) theEnum.nextElement(); seg.decimate(theVal, this, startTime); } // start off with the sensor data if (_mySensors != null) { for (final Enumeration<Editable> iterator = _mySensors.elements(); iterator .hasMoreElements();) { final SensorWrapper thisS = (SensorWrapper) iterator.nextElement(); thisS.decimate(theVal, startTime); } } // now the solutions if (_mySolutions != null) { for (final Enumeration<Editable> iterator = _mySolutions.elements(); iterator .hasMoreElements();) { final TMAWrapper thisT = (TMAWrapper) iterator.nextElement(); thisT.decimate(theVal, startTime); } } } } public final void setSymbolColor(final Color col) { _theSnailShape.setColor(col); } /** * how frequently symbols are placed on the track * * @param theVal * frequency in seconds */ public final void setSymbolFrequency(final HiResDate theVal) { this._lastSymbolFrequency = theVal; // set the "showPositions" parameter, as long as we are // not setting the symbols off if (theVal == null) { return; } if (theVal.getMicros() != 0.0) { this.setPositionsVisible(true); } final FixSetter setSymbols = new FixSetter() { @Override public void execute(final FixWrapper fix, final boolean val) { fix.setSymbolShowing(val); } }; setFixes(setSymbols, theVal); } public void setSymbolLength(final WorldDistance symbolLength) { if (_theSnailShape instanceof WorldScaledSym) { final WorldScaledSym sym = (WorldScaledSym) _theSnailShape; sym.setLength(symbolLength); } } public final void setSymbolType(final String val) { // is this the type of our symbol? if (val.equals(_theSnailShape.getType())) { // don't bother we're using it already } else { // remember the size of the symbol final double scale = _theSnailShape.getScaleVal(); // remember the color of the symbol final Color oldCol = _theSnailShape.getColor(); // replace our symbol with this new one _theSnailShape = MWC.GUI.Shapes.Symbols.SymbolFactory.createSymbol(val); _theSnailShape.setColor(oldCol); _theSnailShape.setScaleVal(scale); } } public void setSymbolWidth(final WorldDistance symbolWidth) { if (_theSnailShape instanceof WorldScaledSym) { final WorldScaledSym sym = (WorldScaledSym) _theSnailShape; sym.setHeight(symbolWidth); } } // note we are putting a track-labelled wrapper around the colour // parameter, to make the properties window less confusing /** * the colour of the points on the track * * @param theCol * the colour to use */ @FireReformatted public final void setTrackColor(final Color theCol) { setColor(theCol); } /** * font handler * * @param font * the font to use for the label */ public final void setTrackFont(final java.awt.Font font) { _theLabel.setFont(font); } @Override public void shift(final WorldLocation feature, final WorldVector vector) { feature.addToMe(vector); // right, one of our fixes has moved. get the sensors to update // themselves fixMoved(); } @Override public void shift(final WorldVector vector) { this.shiftTrack(elements(), vector); } /** * move the whole of the track be the provided offset */ public final void shiftTrack(final Enumeration<Editable> theEnum, final WorldVector offset) { Enumeration<Editable> enumA = theEnum; // keep track of if the track contains something that doesn't get // dragged boolean handledData = false; if (enumA == null) { enumA = elements(); } while (enumA.hasMoreElements()) { final Object thisO = enumA.nextElement(); if (thisO instanceof TrackSegment) { final TrackSegment seg = (TrackSegment) thisO; seg.shift(offset); // ok - job well done handledData = true; } else if (thisO instanceof SegmentList) { final SegmentList list = (SegmentList) thisO; final Collection<Editable> items = list.getData(); for (final Iterator<Editable> iterator = items.iterator(); iterator .hasNext();) { final TrackSegment segment = (TrackSegment) iterator.next(); segment.shift(offset); } handledData = true; } else if (thisO instanceof SensorWrapper) { final SensorWrapper sw = (SensorWrapper) thisO; final Enumeration<Editable> enumS = sw.elements(); while (enumS.hasMoreElements()) { final SensorContactWrapper scw = (SensorContactWrapper) enumS .nextElement(); // does this fix have it's own origin? final WorldLocation sensorOrigin = scw.getOrigin(); if (sensorOrigin != null) { // create new object to contain the updated location final WorldLocation newSensorLocation = new WorldLocation( sensorOrigin); newSensorLocation.addToMe(offset); // so the contact did have an origin, change it scw.setOrigin(newSensorLocation); } } // looping through the contacts // ok - job well done handledData = true; } // whether this is a sensor wrapper else if (thisO instanceof TrackSegment) { final TrackSegment tw = (TrackSegment) thisO; final Enumeration<Editable> enumS = tw.elements(); // fire recursively, smart-arse. shiftTrack(enumS, offset); // ok - job well done handledData = true; } // whether this is a sensor wrapper } // looping through this track // ok, did we handle the data? if (!handledData) { System.err.println("TrackWrapper problem; not able to shift:" + enumA); } } /** * if we've got a relative track segment, it only learns where its individual * fixes are once they've been initialised. This is where we do it. */ public void sortOutRelativePositions() { final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); // SPECIAL HANDLING, SEE IF IT'S A TMA SEGMENT TO BE PLOTTED IN // RELATIVE MODE final boolean isRelative = seg.getPlotRelative(); WorldLocation tmaLastLoc = null; long tmaLastDTG = 0; // if it's not a relative track, and it's not visible, we don't // need to // work with ut if (!isRelative) { continue; } final Enumeration<Editable> fixWrappers = seg.elements(); while (fixWrappers.hasMoreElements()) { final FixWrapper fw = (FixWrapper) fixWrappers.nextElement(); // now there's a chance that our fix has forgotten it's parent, // particularly if it's the victim of a // copy/paste operation. Tell it about it's children fw.setTrackWrapper(this); // ok, are we in relative? if (isRelative) { final long thisTime = fw.getDateTimeGroup().getDate().getTime(); // ok, is this our first location? if (tmaLastLoc == null) { tmaLastLoc = new WorldLocation(seg.getTrackStart()); } else { // calculate a new vector final long timeDelta = thisTime - tmaLastDTG; if (lastFix != null) { final double speedKts = lastFix.getSpeed(); final double courseRads = lastFix.getCourse(); final double depthM = lastFix.getDepth(); // use the value of depth as read in from the file tmaLastLoc.setDepth(depthM); final WorldVector thisVec = seg.vectorFor(timeDelta, speedKts, courseRads); tmaLastLoc.addToMe(thisVec); } } lastFix = fw; tmaLastDTG = thisTime; // dump the location into the fix fw.setFixLocationSilent(new WorldLocation(tmaLastLoc)); } } } } /** * split this whole track into two sub-tracks * * @param splitPoint * the point at which we perform the split * @param splitBeforePoint * whether to put split before or after specified point * @return a list of the new track segments (used for subsequent undo * operations) */ public Vector<TrackSegment> splitTrack(final FixWrapper splitPoint, final boolean splitBeforePoint) { FixWrapper splitPnt = splitPoint; Vector<TrackSegment> res = null; TrackSegment relevantSegment = null; // are we still in one section? if (_thePositions.size() == 1) { relevantSegment = (TrackSegment) _thePositions.first(); // yup, looks like we're going to be splitting it. // better give it a proper name relevantSegment.setName(relevantSegment.startDTG().getDate().toString()); } else { // ok, find which segment contains our data final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); if (seg.getData().contains(splitPnt)) { relevantSegment = seg; break; } } } if (relevantSegment == null) { throw new RuntimeException( "failed to provide relevant segment, alg will break"); } // hmm, if we're splitting after the point, we need to move along the // bus by // one if (!splitBeforePoint) { final Collection<Editable> items = relevantSegment.getData(); final Iterator<Editable> theI = items.iterator(); Editable previous = null; while (theI.hasNext()) { final Editable thisE = theI.next(); // have we chosen to remember the previous item? if (previous != null) { // yes, this must be the one we're after splitPnt = (FixWrapper) thisE; break; } // is this the one we're looking for? if (thisE == splitPnt) { // yup, remember it - we want to use the next value previous = thisE; } } } // yup, do our first split final SortedSet<Editable> p1 = relevantSegment.headSet(splitPnt); final SortedSet<Editable> p2 = relevantSegment.tailSet(splitPnt); // get our results ready final TrackSegment ts1, ts2; // aaah, just sort out if we are splitting a TMA segment, in which case // want to create two // tma segments, not track segments if (relevantSegment instanceof RelativeTMASegment) { final RelativeTMASegment theTMA = (RelativeTMASegment) relevantSegment; // aah, sort out if we are splitting before or after. // find out the offset at the split point, so we can initiate it for // the // second part of the track final WorldLocation refTrackLoc = theTMA.getReferenceTrack() .getNearestTo(splitPnt.getDateTimeGroup())[0].getLocation(); final WorldVector secondOffset = splitPnt.getLocation().subtract( refTrackLoc); // put the lists back into plottable layers final RelativeTMASegment tr1 = new RelativeTMASegment(theTMA, p1, theTMA.getOffset()); final RelativeTMASegment tr2 = new RelativeTMASegment(theTMA, p2, secondOffset); // update the freq's tr1.setBaseFrequency(((CoreTMASegment) relevantSegment) .getBaseFrequency()); tr2.setBaseFrequency(((CoreTMASegment) relevantSegment) .getBaseFrequency()); // and store them ts1 = tr1; ts2 = tr2; } else if (relevantSegment instanceof AbsoluteTMASegment) { final AbsoluteTMASegment theTMA = (AbsoluteTMASegment) relevantSegment; // aah, sort out if we are splitting before or after. // find out the offset at the split point, so we can initiate it for // the // second part of the track final Watchable[] matches = this .getNearestTo(splitPnt.getDateTimeGroup()); final WorldLocation origin = matches[0].getLocation(); final FixWrapper t1Start = (FixWrapper) p1.first(); // put the lists back into plottable layers final AbsoluteTMASegment tr1 = new AbsoluteTMASegment(theTMA, p1, t1Start.getLocation(), null, null); final AbsoluteTMASegment tr2 = new AbsoluteTMASegment(theTMA, p2, origin, null, null); // update the freq's tr1.setBaseFrequency(((CoreTMASegment) relevantSegment) .getBaseFrequency()); tr2.setBaseFrequency(((CoreTMASegment) relevantSegment) .getBaseFrequency()); // and store them ts1 = tr1; ts2 = tr2; } else { // put the lists back into plottable layers ts1 = new TrackSegment(p1); ts2 = new TrackSegment(p2); } // now clear the positions _thePositions.removeElement(relevantSegment); // and put back our new layers _thePositions.addSegment(ts1); _thePositions.addSegment(ts2); // remember them res = new Vector<TrackSegment>(); res.add(ts1); res.add(ts2); return res; } /** * extra parameter, so that jvm can produce a sensible name for this * * @return the track name, as a string */ @Override public final String toString() { return "Track:" + getName(); } /** * is this track visible between these time periods? * * @param start * start DTG * @param end * end DTG * @return yes/no */ @Override public final boolean visibleBetween(final HiResDate start, final HiResDate end) { boolean visible = false; if (getStartDTG().lessThan(end) && (getEndDTG().greaterThan(start))) { visible = true; } return visible; } /** * Calculates Course & Speed for the track. */ public void calcCourseSpeed() { // step through our fixes final Enumeration<Editable> iter = getPositions(); FixWrapper prevFw = null; while (iter.hasMoreElements()) { final FixWrapper currFw = (FixWrapper) iter.nextElement(); if (prevFw == null) prevFw = currFw; else { // calculate the course final WorldVector wv = currFw.getLocation().subtract( prevFw.getLocation()); prevFw.getFix().setCourse(wv.getBearing()); // calculate the speed // get distance in meters final WorldDistance wd = new WorldDistance(wv); final double distance = wd.getValueIn(WorldDistance.METRES); // get time difference in seconds final long timeDifference = (currFw.getTime().getMicros() - prevFw .getTime().getMicros()) / 1000000; // get speed in meters per second and convert it to knots final WorldSpeed speed = new WorldSpeed(distance / timeDifference, WorldSpeed.M_sec); final double knots = WorldSpeed.convert(WorldSpeed.M_sec, WorldSpeed.Kts, speed.getValue()); prevFw.setSpeed(knots); prevFw = currFw; } } } public void trimTo(TimePeriod period) { if (_mySensors != null) { final Enumeration<Editable> iter = _mySensors.elements(); while (iter.hasMoreElements()) { final SensorWrapper sw = (SensorWrapper) iter.nextElement(); sw.trimTo(period); } } if (_mySolutions != null) { final Enumeration<Editable> iter = _mySolutions.elements(); while (iter.hasMoreElements()) { final TMAWrapper sw = (TMAWrapper) iter.nextElement(); sw.trimTo(period); } } if (_thePositions != null) { final Enumeration<Editable> segments = _thePositions.elements(); while (segments.hasMoreElements()) { final TrackSegment seg = (TrackSegment) segments.nextElement(); seg.trimTo(period); } } } @Override public Enumeration<Editable> segments() { return elements(); } /** accessor to determine if this is a relative track * * @return */ public boolean isTMATrack() { boolean res = false; if(_thePositions != null) if(_thePositions.size() > 0) if(_thePositions.first() instanceof CoreTMASegment) { res = true; } return res; } @Override public int compareTo(Plottable arg0) { Integer answer = null; // SPECIAL PROCESSING: we wish to push TMA tracks to the top of any // tracks shown in the outline view. // is he a track? if(arg0 instanceof TrackWrapper) { TrackWrapper other = (TrackWrapper) arg0; // yes, he's a track. See if we're a relative track boolean iAmTMA = isTMATrack(); // is he relative? boolean heIsTMA = other.isTMATrack(); if(heIsTMA) { // ok, he's a TMA segment. now we need to sort out if we are. if(iAmTMA) { // we're both relative, compare names answer = getName().compareTo(other.getName()); } else { // only he is relative, he comes first answer = 1; } } else { // he's not relative. am I? if(iAmTMA) { // I am , so go first answer = -1; } } } else { // we're a track, they're not - put us at the end! answer = 1; } // if we haven't worked anything out yet, just use the parent implementation if(answer == null) answer = super.compareTo(arg0); return answer; } }
package com.bakerbeach.market.core.api.model; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public interface Order { public final static String STATUS_TMP = "tmp"; public final static String STATUS_SUBMITTED = "submitted"; @Deprecated public final static String STATUS_SUBMIT = "submit"; public final static String STATUS_ACCEPTED = "accepted"; public final static String STATUS_CANCELED = "canceled"; String getId(); void setId(String id); String getShopCode(); void setShopCode(String shopCode); @Deprecated String getCurrency(); String getCurrencyCode(); void setCurrencyCode(String currencyCode); BigDecimal getTotal(); void setTotal(BigDecimal total); String getCustomerId(); void setCustomerId(String customerId); Address getShippingAddress(); void setShippingAddress(Address shippingAddress); Address getBillingAddress(); void setBillingAddress(Address billingAddress); Address newAddress(Address source); @Deprecated List<OrderItem> getItems(); Map<String, OrderItem> getAllItems(); OrderItem getItem(String key); @Deprecated void addItem(Object newOrderItem); void addItem(OrderItem item); Map<String, Object> getAllAttributes(); void addAttributes(Map<String, Object> map); @Deprecated HashMap<String, Object> getAttributes(); @Deprecated HashMap<String, Object> getAdditionalInformations(); @Deprecated String getOrderStatus(); String getStatus(); void setStatus(String status); String getCustomerEmail(); void setCustomerEmail(String customerEmail); Date getUpdatedAt(); void setUpdatedAt(Date date); Date getCreatedAt(); void setCreatedAt(Date createdAt); String getPaymentCode(); void setPaymentCode(String paymentCode); String getPaymentTransactionId(); OrderItem newItem(); }
package net.sf.jaer.eventprocessing.filter; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import com.jogamp.opengl.util.gl2.GLUT; import java.beans.PropertyChangeEvent; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.Random; import java.util.SortedSet; import java.util.TreeSet; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.ApsDvsEvent; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.OutputEventIterator; import net.sf.jaer.event.PolarityEvent; import net.sf.jaer.eventio.AEInputStream; import static net.sf.jaer.eventprocessing.EventFilter.log; import net.sf.jaer.eventprocessing.EventFilter2D; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.graphics.AEViewer; import net.sf.jaer.graphics.FrameAnnotater; import net.sf.jaer.util.RemoteControlCommand; import net.sf.jaer.util.RemoteControlled; /** * Filter for testing noise filters * * @author tobid/shasah */ @Description("Tests noise filters by injecting known noise and measuring how much signal and noise is filtered") @DevelopmentStatus(DevelopmentStatus.Status.Stable) public class NoiseTesterFilter extends AbstractNoiseFilter implements FrameAnnotater, RemoteControlled { FilterChain chain; private float shotNoiseRateHz = getFloat("shotNoiseRateHz", .1f); private float leakNoiseRateHz = getFloat("leakNoiseRateHz", .1f); private static String DEFAULT_CSV_FILENAME_BASE = "NoiseTesterFilter"; private String csvFileName = getString("csvFileName", DEFAULT_CSV_FILENAME_BASE); private File csvFile = null; private BufferedWriter csvWriter = null; // chip size values, set in initFilter() private int sx = 0; private int sy = 0; private int npix = 0; private Integer lastTimestampPreviousPacket = null; // use Integer Object so it can be null to signify no value yet private float TPR = 0; private float TPO = 0; private float TNR = 0; private float accuracy = 0; private float BR = 0; private EventPacket<ApsDvsEvent> signalAndNoisePacket = null; private EventSet<BasicEvent> noiseList = new EventSet(); private Random random = new Random(); private int poissonDtUs = 1; private AbstractNoiseFilter[] noiseFilters = null; private AbstractNoiseFilter selectedFilter = null; protected boolean resetCalled = true; // flag to reset on next event public static final float RATE_LIMIT_HZ = 10; public enum NoiseFilter { BackgroundActivityFilter, SpatioTemporalCorrelationFilter, SequenceBasedFilter, OrderNBackgroundActivityFilter } private NoiseFilter selectedNoiseFilterEnum = NoiseFilter.valueOf(getString("selectedNoiseFilter", NoiseFilter.BackgroundActivityFilter.toString())); //default is BAF private float correlationTimeS = getFloat("correlationTimeS", 20e-3f); // float BR = 2 * TPR * TPO / (TPR + TPO); // wish to norm to 1. if both TPR and TPO is 1. the value is 1 public NoiseTesterFilter(AEChip chip) { super(chip); setPropertyTooltip("shotNoiseRateHz", "rate per pixel of shot noise events"); setPropertyTooltip("leakNoiseRateHz", "rate per pixel of leak noise events"); setPropertyTooltip("csvFileName", "Enter a filename base here to open CSV output file (appending to it if it already exists)"); setPropertyTooltip("selectedNoiseFilter", "Choose a noise filter to test"); if (chip.getRemoteControl() != null) { log.info("adding RemoteControlCommand listener to AEChip\n"); chip.getRemoteControl().addCommandListener(this, "setNoiseFilterParameters", "set correlation time or distance."); } } @Override public synchronized void setFilterEnabled(boolean yes) { filterEnabled = yes; if (yes) { for (EventFilter2D f : chain) { if (selectedFilter != null && selectedFilter == f) { f.setFilterEnabled(yes); } } } else { for (EventFilter2D f : chain) { f.setFilterEnabled(false); } } } public void doCloseCsvFile() { if (csvFile != null) { try { log.info("closing statistics output file" + csvFile); csvWriter.close(); } catch (IOException e) { log.warning("could not close " + csvFile + ": caught " + e.toString()); } finally { csvFile = null; csvWriter = null; } } } private void openCvsFiile() { String fn = csvFileName + ".csv"; csvFile = new File(fn); log.info(String.format("opening %s for output", fn)); try { csvWriter = new BufferedWriter(new FileWriter(csvFile, true)); if (!csvFile.exists()) { // write header log.info("file did not exist, so writing header"); csvWriter.write(String.format("TP,TN,FP,FN,TPR,TNR,BR,firstE.timestamp," + "inSignalRateHz,inNoiseRateHz,outSignalRateHz,outNoiseRateHz\n")); } } catch (IOException ex) { log.warning(String.format("could not open %s for output; caught %s", fn, ex.toString())); } } @Override public void annotate(GLAutoDrawable drawable) { if (!showFilteringStatistics) { return; } findUnusedDawingY(); GL2 gl = drawable.getGL().getGL2(); gl.glPushMatrix(); final GLUT glut = new GLUT(); gl.glColor3f(.2f, .2f, .8f); // must set color before raster position (raster position is like glVertex) gl.glRasterPos3f(0, statisticsDrawingPosition, 0); String s = String.format("TPR=%%%6.1f, TNR=%%%6.1f, BR=%%%6.1f, poissonDt=%d us", 100 * TPR, 100 * TNR, 100 * BR, poissonDtUs); glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, s); gl.glPopMatrix(); } final private class TimeStampComparator<E extends BasicEvent> implements Comparator<E> { @Override public int compare(final E e1, final E e2) { return e1.timestamp - e2.timestamp; } } private TimeStampComparator timestampComparator=new TimeStampComparator<BasicEvent>(); private final class EventSet<BasicEvent> extends TreeSet{ public EventSet() { super(timestampComparator); } public EventSet(Collection c){ this(); addAll(c); } } @Override synchronized public EventPacket<?> filterPacket(EventPacket<?> in) { totalEventCount = 0; // from super, to measure filtering filteredOutEventCount = 0; int TP = 0; // filter take real events as real events. the number of events int TN = 0; // filter take noise events as noise events int FP = 0; // filter take noise events as real events int FN = 0; // filter take real events as noise events if (in == null || in.isEmpty()) { log.warning("empty packet, cannot inject noise"); return in; } BasicEvent firstE = in.getFirstEvent(); if (resetCalled) { resetCalled = false; int ts = in.getLastTimestamp(); // we use getLastTimestamp because getFirstTimestamp contains event from BEFORE the rewind :-( // initialize filters with lastTimesMap to Poisson waiting times log.info("initializing timestamp maps with Poisson process waiting times"); for (AbstractNoiseFilter f : noiseFilters) { int[][] map = f.getLastTimesMap(); if (map != null) { initializeLastTimesMapForNoiseRate(map, shotNoiseRateHz + leakNoiseRateHz, ts); } } } // copy input events to inList EventSet signalList=new EventSet(); // HashSet signalList = new HashSet(in.getSize()); for (BasicEvent e : in) { totalEventCount += 1; signalList.add(e); } // add noise into signalList to get the outputPacketWithNoiseAdded, track noise in noiseList addNoise(in, signalAndNoisePacket, noiseList, shotNoiseRateHz, leakNoiseRateHz); // we need to copy the augmented event packet to a HashSet for use with Collections // HashSet signalAndNoiseList = new HashSet(signalAndNoisePacket.getSize()); EventSet signalAndNoiseList = new EventSet(); for (BasicEvent e : signalAndNoisePacket) { signalAndNoiseList.add(e); } // filter the augmented packet EventPacket<BasicEvent> passedSignalAndNoisePacket = getEnclosedFilterChain().filterPacket(signalAndNoisePacket); // make a copy of the output packet, which has noise filtered out by selected filter // HashSet passedSignalAndNoiseList = new HashSet(passedSignalAndNoisePacket.getSize()); EventSet passedSignalAndNoiseList = new EventSet(); for (BasicEvent e : passedSignalAndNoisePacket) { passedSignalAndNoiseList.add(e); } // now we sort out the mess // make a list of everything that was removed // Collection removedList = new HashSet(signalAndNoiseList); // start with S+N Collection removedList = new EventSet(signalAndNoiseList); // start with S+N removedList.removeAll(passedSignalAndNoiseList); // remove the filtered S+N, leaves everything that was filtered out // False negatives: Signal that was incorrectly removed by filter. // Collection fnList = new HashSet(signalList); // start with signal Collection fnList = new EventSet(signalList); // start with signal fnList.removeAll(passedSignalAndNoiseList); // Signal - (passed Signal (TP)) = FN // remove from signal the filtered output which removes all signal left //over plus removes all noise (which is not there to start with). // What is left is signal that was removed by filtering, which are the false negatives FN = fnList.size(); // True positives: Signal that was correctly retained by filtering // Collection tpList = new HashSet(signalList); // start with signal Collection tpList = new EventSet(signalList); // start with signal tpList.retainAll(passedSignalAndNoiseList); // signal intersect (passed S+N) = TP TP = tpList.size(); // False positives: Noise that is incorrectly passed by filter // Collection fpList = new HashSet(noiseList); // start with added noise Collection fpList = new EventSet(noiseList); // start with added noise fpList.retainAll(passedSignalAndNoiseList); // noise intersect with (passed S+N) which means noise are regarded as signal FP = fpList.size(); // True negatives: Noise that was correctly removed by filter // Collection tnList = new HashSet(removedList); // start with all N Collection tnList = new EventSet(noiseList); // start with noiseList tnList.removeAll(passedSignalAndNoiseList); // N - (passed S + N) is N filtered out TN = tnList.size(); // System.out.printf("every packet is: %d %d %d %d %d, %d %d %d: %d %d %d %d\n", inList.size(), newInList.size(), outList.size(), outRealList.size(), outNoiseList.size(), outInitList.size(), outInitRealList.size(), outInitNoiseList.size(), TP, TN, FP, FN); TPR = TP + FN == 0 ? 0f : (float) (TP * 1.0 / (TP + FN)); // percentage of true positive events. that's output real events out of all real events TPO = TP + FP == 0 ? 0f : (float) (TP * 1.0 / (TP + FP)); // percentage of real events in the filter's output TNR = TN + FP == 0 ? 0f : (float) (TN * 1.0 / (TN + FP)); accuracy = (float) ((TP + TN) * 1.0 / (TP + TN + FP + FN)); BR = TPR + TPO == 0 ? 0f : (float) (2 * TPR * TPO / (TPR + TPO)); // wish to norm to 1. if both TPR and TPO is 1. the value is 1 // System.out.printf("shotNoiseRateHz and leakNoiseRateHz is %.2f and %.2f\n", shotNoiseRateHz, leakNoiseRateHz); float inSignalRateHz = 0, inNoiseRateHz = 0, outSignalRateHz = 0, outNoiseRateHz = 0; if (lastTimestampPreviousPacket != null) { int deltaTime = in.getLastTimestamp() - lastTimestampPreviousPacket; lastTimestampPreviousPacket = in.getLastTimestamp(); inSignalRateHz = (1e-6f * in.getSize()) / deltaTime; inNoiseRateHz = (1e-6f * noiseList.size()) / deltaTime; outSignalRateHz = (1e-6f * tpList.size()) / deltaTime; outNoiseRateHz = (1e-6f * fpList.size()) / deltaTime; } if (csvWriter != null) { try { csvWriter.write(String.format("%d,%d,%d,%d,%f,%f,%f,%d,%f,%f,%f,%f\n", TP, TN, FP, FN, TPR, TNR, BR, firstE.timestamp, inSignalRateHz, inNoiseRateHz, outSignalRateHz, outNoiseRateHz)); } catch (IOException e) { doCloseCsvFile(); } } int outputEventCount = passedSignalAndNoiseList.size(); filteredOutEventCount = totalEventCount - outputEventCount; return passedSignalAndNoisePacket; } @Override synchronized public void resetFilter() { lastTimestampPreviousPacket = null; resetCalled = true; getEnclosedFilterChain().reset(); } @Override public void initFilter() { chain = new FilterChain(chip); noiseFilters = new AbstractNoiseFilter[]{new BackgroundActivityFilter(chip), new SpatioTemporalCorrelationFilter(chip), new SequenceBasedFilter(chip), new OrderNBackgroundActivityFilter((chip))}; for (AbstractNoiseFilter n : noiseFilters) { n.initFilter(); chain.add(n); } setEnclosedFilterChain(chain); sx = chip.getSizeX() - 1; sy = chip.getSizeY() - 1; npix = (chip.getSizeX() * chip.getSizeY()); signalAndNoisePacket = new EventPacket<>(ApsDvsEvent.class); if (chip.getAeViewer() != null) { chip.getAeViewer().getSupport().addPropertyChangeListener(AEInputStream.EVENT_REWOUND, this); chip.getAeViewer().getSupport().addPropertyChangeListener(AEViewer.EVENT_CHIP, this); } setSelectedNoiseFilter(selectedNoiseFilterEnum); } /** * @return the shotNoiseRateHz */ public float getShotNoiseRateHz() { return shotNoiseRateHz; } @Override public int[][] getLastTimesMap() { return null; } /** * @param shotNoiseRateHz the shotNoiseRateHz to set */ public void setShotNoiseRateHz(float shotNoiseRateHz) { if (shotNoiseRateHz < 0) { shotNoiseRateHz = 0; } if (shotNoiseRateHz > RATE_LIMIT_HZ) { log.warning("high leak rates will hang the filter and consume all memory"); shotNoiseRateHz = RATE_LIMIT_HZ; } putFloat("shotNoiseRateHz", shotNoiseRateHz); getSupport().firePropertyChange("shotNoiseRateHz", this.shotNoiseRateHz, shotNoiseRateHz); this.shotNoiseRateHz = shotNoiseRateHz; } /** * @return the leakNoiseRateHz */ public float getLeakNoiseRateHz() { return leakNoiseRateHz; } /** * @param leakNoiseRateHz the leakNoiseRateHz to set */ public void setLeakNoiseRateHz(float leakNoiseRateHz) { if (leakNoiseRateHz < 0) { leakNoiseRateHz = 0; } if (leakNoiseRateHz > RATE_LIMIT_HZ) { log.warning("high leak rates will hang the filter and consume all memory"); leakNoiseRateHz = RATE_LIMIT_HZ; } putFloat("leakNoiseRateHz", leakNoiseRateHz); getSupport().firePropertyChange("leakNoiseRateHz", this.leakNoiseRateHz, leakNoiseRateHz); this.leakNoiseRateHz = leakNoiseRateHz; } /** * @return the csvFileName */ public String getCsvFilename() { return csvFileName; } /** * @param csvFileName the csvFileName to set */ public void setCsvFilename(String csvFileName) { if (csvFileName.toLowerCase().endsWith(".csv")) { csvFileName = csvFileName.substring(0, csvFileName.length() - 4); } this.csvFileName = csvFileName; putString("csvFileName", csvFileName); openCvsFiile(); } private void addNoise(EventPacket<? extends BasicEvent> in, EventPacket<? extends ApsDvsEvent> augmentedPacket, EventSet<BasicEvent> generatedNoise, float shotNoiseRateHz, float leakNoiseRateHz) { // we need at least 1 event to be able to inject noise before it if ((in.isEmpty())) { log.warning("no input events in this packet, cannot inject noise because there is no end event"); return; } // save input packet augmentedPacket.clear(); generatedNoise.clear(); // make the itertor to save events with added noise events OutputEventIterator<ApsDvsEvent> outItr = (OutputEventIterator<ApsDvsEvent>) augmentedPacket.outputIterator(); if (leakNoiseRateHz == 0 && shotNoiseRateHz == 0) { for (BasicEvent ie : in) { outItr.nextOutput().copyFrom(ie); } return; // no noise, just return which returns the copy from filterPacket } // the rate per pixel results in overall noise rate for entire sensor that is product of pixel rate and number of pixels. // we compute this overall noise rate to determine the Poisson sample interval that is much smaller than this to enable simple Poisson noise sampling. // Compute time step that is 10X less than the overall mean interval for noise // dt is the time interval such that if we sample a random value 0-1 every dt us, the the overall noise rate will be correct. float tmp = (float) (1.0 / ((leakNoiseRateHz + shotNoiseRateHz) * npix)); // this value is very small poissonDtUs = (int) ((tmp / 10) * 1000000); // 1s = 1000000 us if (poissonDtUs < 1) { poissonDtUs = 1; } float shotOffThresholdProb = 0.5f * (poissonDtUs * 1e-6f * npix) * shotNoiseRateHz; // bounds for samppling Poisson noise, factor 0.5 so total rate is shotNoiseRateHz float shotOnThresholdProb = 1 - shotOffThresholdProb; // for shot noise sample both sides, for leak events just generate ON events float leakOnThresholdProb = (poissonDtUs * 1e-6f * npix) * leakNoiseRateHz; // bounds for samppling Poisson noise int firstTsThisPacket = in.getFirstTimestamp(); // insert noise between last event of last packet and first event of current packet // but only if there waa a previous packet and we are monotonic if (lastTimestampPreviousPacket != null) { if (firstTsThisPacket < lastTimestampPreviousPacket) { log.warning(String.format("non-monotonic timestamp: Resetting filter. (first event %d is smaller than previous event %d by %d)", firstTsThisPacket, lastTimestampPreviousPacket, firstTsThisPacket - lastTimestampPreviousPacket)); resetFilter(); return; } // we had some previous event int lastPacketTs = lastTimestampPreviousPacket; // timestamp of the last event in the last packet for (int ts = lastPacketTs; ts < firstTsThisPacket; ts += poissonDtUs) { sampleNoiseEvent(ts, outItr, noiseList, shotOffThresholdProb, shotOnThresholdProb, leakOnThresholdProb); } } // insert noise between events of this packet after the first event, record their timestamp int preEts = 0; int lastEventTs = in.getFirstTimestamp(); for (BasicEvent ie : in) { // if it is the first event or any with first event timestamp then just copy them if (ie.timestamp == firstTsThisPacket) { outItr.nextOutput().copyFrom(ie); continue; } // save the previous timestamp and get the next one, and then inject noise between them preEts = lastEventTs; lastEventTs = ie.timestamp; for (int ts = preEts; ts <= lastEventTs; ts += poissonDtUs) { // TODO might be truncation error here with leftover time sampleNoiseEvent(ts, outItr, noiseList, shotOffThresholdProb, shotOnThresholdProb, leakOnThresholdProb); } outItr.nextOutput().copyFrom(ie); } } private void sampleNoiseEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, EventSet<BasicEvent> noiseList, float shotOffThresholdProb, float shotOnThresholdProb, float leakOnThresholdProb) { float randomnum = random.nextFloat(); if (randomnum < shotOffThresholdProb) { injectOffEvent(ts, outItr, noiseList); } else if (randomnum > shotOnThresholdProb) { injectOnEvent(ts, outItr, noiseList); } if (random.nextFloat() < leakOnThresholdProb) { injectOnEvent(ts, outItr, noiseList); } } private void injectOnEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, EventSet<BasicEvent> noiseList) { ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput(); e.setSpecial(false); e.polarity = PolarityEvent.Polarity.On; int x = (short) random.nextInt(sx); int y = (short) random.nextInt(sy); e.x = (short) (x); e.y = (short) (y); e.timestamp = ts; noiseList.add(e); } private void injectOffEvent(int ts, OutputEventIterator<ApsDvsEvent> outItr, EventSet<BasicEvent> noiseList) { ApsDvsEvent e = (ApsDvsEvent) outItr.nextOutput(); e.setSpecial(false); e.polarity = PolarityEvent.Polarity.Off; int x = (short) random.nextInt(sx); int y = (short) random.nextInt(sy); e.x = (short) (x); e.y = (short) (y); e.timestamp = ts; noiseList.add(e); } @Override public void propertyChange(PropertyChangeEvent evt) { super.propertyChange(evt); //To change body of generated methods, choose Tools | Templates. if (evt.getPropertyName() == AEInputStream.EVENT_REWOUND) { log.info(String.format("got rewound event %s, setting reset on next packet flat", evt)); resetCalled = true; } } /** * @return the selectedNoiseFilter */ public NoiseFilter getSelectedNoiseFilter() { return selectedNoiseFilterEnum; } /** * @param selectedNoiseFilter the selectedNoiseFilter to set */ synchronized public void setSelectedNoiseFilter(NoiseFilter selectedNoiseFilter) { this.selectedNoiseFilterEnum = selectedNoiseFilter; putString("selectedNoiseFilter", selectedNoiseFilter.toString()); for (AbstractNoiseFilter n : noiseFilters) { if (n.getClass().getSimpleName().equals(selectedNoiseFilter.toString())) { n.initFilter(); n.setFilterEnabled(true); selectedFilter = n; } else { n.setFilterEnabled(false); } } resetCalled = true; // make sure we iniitialize the timestamp maps on next packet for new filter } private String USAGE = "Need at least 2 arguments: noisefilter <command> <args>\nCommands are: setNoiseFilterParameters <csvFilename> xx <shotNoiseRateHz> xx <leakNoiseRateHz> xx and specific to the filter\n"; @Override public String processRemoteControlCommand(RemoteControlCommand command, String input) { // parse command and set parameters of NoiseTesterFilter, and pass command to specific filter for further processing // setNoiseFilterParameters csvFilename 10msBAFdot_500m_0m_300num0 shotNoiseRateHz 0.5 leakNoiseRateHz 0 dt 300 num 0 String[] tok = input.split("\\s"); if (tok.length < 2) { return USAGE; } else { for (int i = 1; i < tok.length; i++) { if (tok[i].equals("csvFilename")) { setCsvFilename(tok[i + 1]); } else if (tok[i].equals("shotNoiseRateHz")) { setShotNoiseRateHz(Float.parseFloat(tok[i + 1])); log.info(String.format("setShotNoiseRateHz %f", shotNoiseRateHz)); } else if (tok[i].equals("leakNoiseRateHz")) { setLeakNoiseRateHz(Float.parseFloat(tok[i + 1])); log.info(String.format("setLeakNoiseRateHz %f", leakNoiseRateHz)); } } log.info("Received Command:" + input); String out = selectedFilter.setParameters(command, input); log.info("Execute Command:" + input); return out; } } /** * Fills lastTimesMap with waiting times drawn from Poisson process with * rate noiseRateHz * * @param lastTimesMap map * @param noiseRateHz rate in Hz * @param lastTimestampUs the last timestamp; waiting times are created * before this time */ protected void initializeLastTimesMapForNoiseRate(int[][] lastTimesMap, float noiseRateHz, int lastTimestampUs) { for (final int[] arrayRow : lastTimesMap) { for (int i = 0; i < arrayRow.length; i++) { final float p = random.nextFloat(); final double t = -noiseRateHz * Math.log(1 - p); final int tUs = (int) (1000000 * t); arrayRow[i] = lastTimestampUs - tUs; } } } @Override public float getCorrelationTimeS() { return this.correlationTimeS; } @Override public void setCorrelationTimeS(float dtS) { this.correlationTimeS = dtS; for (AbstractNoiseFilter f : noiseFilters) { f.setCorrelationTimeS(dtS); } putFloat("correlationTimeS", this.correlationTimeS); } }
package com.bynder.sdk.service.upload; import java.io.File; import java.io.FileInputStream; import java.util.Arrays; import java.util.Map; import com.bynder.sdk.api.BynderApi; import com.bynder.sdk.model.FinaliseResponse; import com.bynder.sdk.model.PollStatus; import com.bynder.sdk.model.UploadRequest; import com.bynder.sdk.query.FinaliseUploadQuery; import com.bynder.sdk.query.PollStatusQuery; import com.bynder.sdk.query.RegisterChunkQuery; import com.bynder.sdk.query.RequestUploadQuery; import com.bynder.sdk.query.SaveMediaQuery; import com.bynder.sdk.query.UploadQuery; import com.bynder.sdk.service.AmazonService; import com.bynder.sdk.service.exception.BynderUploadException; import com.bynder.sdk.service.impl.AmazonServiceImpl; import com.bynder.sdk.util.Utils; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import retrofit2.Response; /** * Class used to upload files to Bynder. */ public class FileUploader { /** * Max chunk size. */ private static final int MAX_CHUNK_SIZE = 1024 * 1024 * 5; /** * Max polling iterations to wait for the file to be converted. */ private static final int MAX_POLLING_ITERATIONS = 60; /** * Idle time between polling iterations. */ private static final int POLLING_IDLE_TIME = 2000; /** * Instance of {@link BynderApi} which handles the HTTP communication. */ private final BynderApi bynderApi; /** * Amazon service used to upload parts (chunks). */ private AmazonService amazonService; /** * Creates a new instance of the class. * * @param bynderApi Instance to handle the HTTP communication with the Bynder API. */ public FileUploader(final BynderApi bynderApi) { this.bynderApi = bynderApi; } /** * Uploads a file with the information specified in the query parameter. * * @param uploadQuery Upload query with the information to upload the file. * @return {@link Observable} with Boolean indicating if upload was successful or not. */ public Observable<Boolean> uploadFile(final UploadQuery uploadQuery) { return Observable.create(observableEmitter -> { try { Observable<Response<String>> s3EndpointObs = getClosestS3Endpoint(); s3EndpointObs.subscribe(awsBucketResponse -> { this.amazonService = new AmazonServiceImpl(awsBucketResponse.body()); Observable<Response<UploadRequest>> uploadInformationObs = getUploadInformation(new RequestUploadQuery(uploadQuery.getFilepath())); uploadInformationObs.subscribe(uploadRequestResponse -> { UploadRequest uploadRequest = uploadRequestResponse.body(); File file = new File(uploadQuery.getFilepath()); if (!file.exists()) { observableEmitter.onError(new BynderUploadException(String.format("File: %s not found. Upload not completed.", file.getName()))); return; } startUploadProcess(uploadQuery, observableEmitter, uploadRequest, file); }, throwable -> observableEmitter.onError(throwable)); }, throwable -> observableEmitter.onError(throwable)); } catch (Exception e) { observableEmitter.onError(e); } }); } /** * Starts the process to upload a file to Bynder, after the {@link AmazonService} was * successfully instantiated with the closest s3 endpoint and the upload was successfully * initialise in Bynder. * * @param uploadQuery Upload query with the information to upload the file. * @param observableEmitter Observable returned by {@link FileUploader#uploadFile(UploadQuery)}. * @param uploadRequest Upload authorisation information. * @param file File to be uploaded. */ private void startUploadProcess(final UploadQuery uploadQuery, final ObservableEmitter<Boolean> observableEmitter, final UploadRequest uploadRequest, final File file) { Observable<Integer> uploadPartsObs = uploadParts(file, uploadRequest); uploadPartsObs.subscribe(chunksResponse -> { Observable<Response<FinaliseResponse>> finaliseUploadedFileObs = finaliseUpload(new FinaliseUploadQuery(uploadRequest.getS3File().getUploadId(), uploadRequest.getS3File().getTargetId(), uploadRequest.getS3Filename(), chunksResponse)); finaliseUploadedFileObs.subscribe(finaliseResponse -> processFinaliseResponse(uploadQuery, observableEmitter, file, finaliseResponse), throwable -> observableEmitter.onError(throwable)); }, throwable -> observableEmitter.onError(throwable)); } /** * Uploads the parts (chunks) to Amazon and registers them in Bynder. * * @param file File to be uploaded. * @param uploadRequest Upload authorisation information. */ private Observable<Integer> uploadParts(final File file, final UploadRequest uploadRequest) { return Observable.create(observableEmitter -> { try { FileInputStream fileInputStream = new FileInputStream(file); UploadProcessData uploadProcessData = new UploadProcessData(file, fileInputStream, uploadRequest, MAX_CHUNK_SIZE); uploadProcessData.incrementChunk(); processChunk(uploadProcessData).repeatUntil(() -> { boolean isProcessed = uploadProcessData.isCompleted(); if (isProcessed) { observableEmitter.onNext(uploadProcessData.getNumberOfChunks()); observableEmitter.onComplete(); } else { uploadProcessData.incrementChunk(); } return isProcessed; } ).subscribe(booleanResponse -> { }, throwable -> observableEmitter.onError(throwable)); } catch (Exception e) { observableEmitter.onError(e); } }); } /** * Calls the {@link AmazonService} to upload the chunk to Amazon and after registers the * uploaded chunk in Bynder. * * @param uploadProcessData Upload process data of the file being uploaded. * @return {@link Observable} with Boolean indicating if upload was successful or not. */ private Observable<Boolean> processChunk(final UploadProcessData uploadProcessData) { return Observable.create(observableEmitter -> { try { Observable<Response<Void>> uploadPartToAmazonObs = amazonService.uploadPartToAmazon(uploadProcessData.getFile().getName(), uploadProcessData.getUploadRequest(), uploadProcessData.getChunkNumber(), uploadProcessData.getBuffer(), uploadProcessData.getNumberOfChunks()); uploadPartToAmazonObs.subscribe(voidResponse -> registerUploadedChunk(uploadProcessData, observableEmitter), throwable -> observableEmitter.onError(throwable)); } catch (Exception e) { observableEmitter.onError(e); } }); } private void registerUploadedChunk(final UploadProcessData uploadProcessData, final ObservableEmitter<Boolean> observableEmitter) throws IllegalAccessException { String filename = String.format("%s/p%s", uploadProcessData.getUploadRequest().getS3Filename(), Integer.toString(uploadProcessData.getChunkNumber())); Observable<Response<Void>> registerChunkObs = registerChunk(new RegisterChunkQuery(uploadProcessData.getUploadRequest().getS3File().getUploadId(), uploadProcessData.getChunkNumber(), uploadProcessData.getUploadRequest().getS3File().getTargetId(), filename)); registerChunkObs.subscribe(voidResponse -> { observableEmitter.onNext(true); observableEmitter.onComplete(); }, throwable -> observableEmitter.onError(throwable)); } /** * Calls the {@link FileUploader#hasFinishedSuccessfully(String)} using the information from the * {@link FinaliseResponse} to check if the upload was completed successfully. * * @param uploadQuery Upload query with the information to upload the file. * @param observableEmitter Observable returned by {@link FileUploader#uploadFile(UploadQuery)}. * @param file File uploaded. * @param finaliseResponse Finalise response returned by * {@link FileUploader#finaliseUpload(FinaliseUploadQuery)}. * @throws InterruptedException */ private void processFinaliseResponse(final UploadQuery uploadQuery, final ObservableEmitter<Boolean> observableEmitter, final File file, final Response<FinaliseResponse> finaliseResponse) { String importId = finaliseResponse.body().getImportId(); hasFinishedSuccessfully(importId).subscribe(hasFinishedSuccessfully -> { if (hasFinishedSuccessfully) { saveUploadedMedia(uploadQuery, observableEmitter, file, importId); } else { observableEmitter.onError(new BynderUploadException("Converter did not finished. Upload not completed.")); } }, throwable -> observableEmitter.onError(throwable)); } /** * Method to check if file has finished converting within expected timeout. * * @param importId Import id of the upload. * @return True if file has finished converting successfully. False otherwise. */ private Observable<Boolean> hasFinishedSuccessfully(final String importId) { return Observable.create(observableEmitter -> { try { FileConverterStatus fileConverterStatus = new FileConverterStatus(MAX_POLLING_ITERATIONS); getPollStatus(new PollStatusQuery(Arrays.asList(importId))).repeatUntil(() -> { if (fileConverterStatus.isDone()) { observableEmitter.onNext(fileConverterStatus.isSuccessful()); observableEmitter.onComplete(); return true; } if (!fileConverterStatus.nextAttempt()) { observableEmitter.onNext(false); observableEmitter.onComplete(); return true; } else { Thread.sleep(POLLING_IDLE_TIME); return false; } }).subscribe(pollStatusResponse -> { PollStatus pollStatus = pollStatusResponse.body(); if (pollStatus != null) { if (pollStatus.getItemsDone().contains(importId)) { fileConverterStatus.setDone(true); } if (pollStatus.getItemsFailed().contains(importId)) { fileConverterStatus.setDone(false); } } }, throwable -> observableEmitter.onError(throwable)); } catch (Exception e) { observableEmitter.onError(e); } }); } private void saveUploadedMedia(final UploadQuery uploadQuery, final ObservableEmitter<Boolean> observableEmitter, final File file, final String importId) throws IllegalAccessException { Observable<Response<Void>> saveMediaObs; if (uploadQuery.getMediaId() == null) { saveMediaObs = saveMedia(new SaveMediaQuery(importId).setBrandId(uploadQuery.getBrandId()).setName(file.getName()).setAudit(uploadQuery.isAudit())); } else { saveMediaObs = saveMedia(new SaveMediaQuery(importId).setMediaId(uploadQuery.getMediaId()).setAudit(uploadQuery.isAudit())); } saveMediaObs.subscribe(voidResponse -> observableEmitter.onNext(true), throwable -> observableEmitter.onError(throwable), () -> observableEmitter.onComplete()); } /** * Check {@link BynderApi#getClosestS3Endpoint()} for more information. */ private Observable<Response<String>> getClosestS3Endpoint() { return bynderApi.getClosestS3Endpoint(); } private Observable<Response<UploadRequest>> getUploadInformation(final RequestUploadQuery requestUploadQuery) throws IllegalAccessException { Map<String, String> params = Utils.getApiParameters(requestUploadQuery); return bynderApi.getUploadInformation(params); } private Observable<Response<Void>> registerChunk(final RegisterChunkQuery registerChunkQuery) throws IllegalAccessException { Map<String, String> params = Utils.getApiParameters(registerChunkQuery); return bynderApi.registerChunk(params); } private Observable<Response<FinaliseResponse>> finaliseUpload(final FinaliseUploadQuery finaliseUploadQuery) throws IllegalAccessException { Map<String, String> params = Utils.getApiParameters(finaliseUploadQuery); return bynderApi.finaliseUpload(params); } private Observable<Response<PollStatus>> getPollStatus(final PollStatusQuery pollStatusQuery) throws IllegalAccessException { Map<String, String> params = Utils.getApiParameters(pollStatusQuery); return bynderApi.getPollStatus(params); } private Observable<Response<Void>> saveMedia(final SaveMediaQuery saveMediaQuery) throws IllegalAccessException { Map<String, String> params = Utils.getApiParameters(saveMediaQuery); return bynderApi.saveMedia(params); } }
package com.hololo.library.otpview; import android.content.Context; import android.content.res.TypedArray; import android.os.Build; import android.support.annotation.RequiresApi; import android.text.InputType; import android.util.AttributeSet; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.LinearLayout; public class OTPView extends LinearLayout { private OTPListener listener; private int count, inputType, textColor, hintColor, viewsPadding, textSize; private String hint; public OTPView(Context context) { super(context); init(null); } public OTPView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs); } public OTPView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(attrs); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public OTPView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(attrs); } public OTPView setHint(String hint) { this.hint = hint; return this; } public OTPView setCount(int count) { this.count = count; return this; } public OTPView setInputType(int inputType) { this.inputType = inputType; return this; } public OTPView setTextColor(int textColor) { this.textColor = textColor; return this; } public OTPView setHintColor(int hintColor) { this.hintColor = hintColor; return this; } public OTPView setViewsPadding(int viewsPadding) { this.viewsPadding = viewsPadding; return this; } public OTPView setTextSize(int textSize) { this.textSize = textSize; return this; } private void init(AttributeSet attrs) { int padding = (int) dp2px(8); setPadding(padding, padding, padding, padding); setFocusableInTouchMode(true); TypedArray styles = getContext().obtainStyledAttributes(attrs, R.styleable.OTPView); count = styles.getInt(R.styleable.OTPView_count, 5); inputType = styles.getInt(R.styleable.OTPView_inputType, InputType.TYPE_CLASS_TEXT); textColor = styles.getInt(R.styleable.OTPView_textColor, -1); hintColor = styles.getInt(R.styleable.OTPView_hintColor, -1); viewsPadding = styles.getInt(R.styleable.OTPView_viewsPadding, -1); hint = styles.getString(R.styleable.OTPView_otpHint); textSize = styles.getInt(R.styleable.OTPView_textSize, -1); String text = styles.getString(R.styleable.OTPView_otpText); fillLayout(); setOtp(text); } public void fillLayout() { clearLayout(); for (int i = 0; i < count; i++) { OTPEditText editText = new OTPEditText(getContext(), i); editText.setMargin((int) dp2px(22)); editText.setInputType(inputType); if (textColor != -1) { editText.setTextColor(textColor); } if (hintColor != -1) { editText.setHintTextColor(hintColor); } if (viewsPadding != -1) { editText.setMargin(viewsPadding); } if (textSize != -1) { editText.setTextSize(dp2px(textSize)); } if (hint != null && hint.length() > 0) { editText.setHint(hint.substring(0, 1)); } addView(editText); } getChildAt(0).requestFocus(); } private void clearLayout() { removeAllViewsInLayout(); } public void onBackPressed(OTPEditText view) { OTPEditText child = (OTPEditText) getChildAt(view.getOrder() - 1); if (child != null) { child.setText(""); child.requestFocus(); } } public void onKeyPressed(OTPEditText view) { OTPEditText child = (OTPEditText) getChildAt(view.getOrder() + 1); if (child != null) { child.requestFocus(); } else { InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(getWindowToken(), 0); } requestFocus(); if (listener != null) { listener.otpFinished(getOtp()); } } } public OTPView setListener(OTPListener listener) { this.listener = listener; return this; } public OTPView setOtp(String otp) { if (otp != null) for (int i = 0; i < otp.length(); i++) { OTPEditText child = (OTPEditText) getChildAt(i); String a = String.valueOf(otp.toCharArray()[i]); child.setText(a); } return this; } public String getOtp() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < getChildCount(); i++) { OTPEditText child = (OTPEditText) getChildAt(i); builder.append(child.getText().toString()); } return builder.toString(); } private float dp2px(int dip) { float scale = getContext().getResources().getDisplayMetrics().density; return dip * scale + 0.5f; } public void focusChange(View view) { OTPEditText editText = (OTPEditText) view; if (editText.getOrder() < getOtp().length() - 1) { setFocus(); InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.toggleSoftInputFromWindow(getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0); } } } public OTPView setFocus() { View view = getChildAt(getOtp().length()); if (view != null) { view.requestFocus(); } else { view = getChildAt(getChildCount() - 1); view.requestFocus(); } return this; } }
package com.egf.db.services.impl; import com.egf.db.core.define.column.Comment; import com.egf.db.core.define.column.PrimaryKey; import com.egf.db.core.define.column.Limit; import com.egf.db.core.define.column.NotNull; import com.egf.db.core.define.column.Unique; import com.egf.db.core.define.column.types.Blob; import com.egf.db.core.define.column.types.Clob; import com.egf.db.core.define.column.types.Date; import com.egf.db.core.define.column.types.Varchar2; import com.egf.db.core.define.name.ColumnName; import com.egf.db.core.define.name.IndexName; import com.egf.db.core.define.name.TableName; import com.egf.db.services.DatabaseService; import com.egf.db.services.Migration; /** * * * @author fangj * @version $Revision: 2.0 $ * @since 1.0 */ public abstract class AbstractMigration extends DatabaseServiceImpl implements Migration,DatabaseService{ protected final static Unique UNIQUE=new UniqueImpl(); protected final static NotNull NOTNULL=new NotNullImpl(); /**number**/ protected final static com.egf.db.core.define.column.types.Number NUMBER=new NumberImpl(); protected final static Date DATE=new DateImpl(); /**blob**/ protected final static Blob BLOB=new BlobImpl(); /**clob**/ protected final static Clob CLOB=new ClobImpl(); protected final static PrimaryKey IS_PRIMARYKEY=new PrimaryKeyImpl(); protected static TableName TableName(String name) { return new TableNameImpl(name); } protected static IndexName IndexName(String name) { return new IndexNameImpl(name); } protected static ColumnName ColumnName(String name) { return new ColumnNameImpl(name); } protected static Limit Limit(int length) { return new LimitImpl(length); } protected static Comment Comment(String comment) { return new CommentImpl(comment); } protected static Varchar2 Varchar2(int length) { return new Varchar2Impl(length); } protected static com.egf.db.core.define.column.Default Default(String value) { return new DefaultImpl(value); } }
package com.elgassia.bridge.Model; import java.util.List; import java.util.Observable; import java.util.Observer; public class UserBiddingModel extends Observable implements Observer { private int userID; private BiddingModel biddingModel; private List<Card> userDeck; UserBiddingModel(int userID,BiddingModel biddingModel) { this.userID = userID; this.biddingModel=biddingModel; this.userDeck=biddingModel.getPlayerCards(userID); biddingModel.addObserver(this); } List<Card> getMyDeck() { return userDeck; } boolean bid(Bid bid) { if(biddingModel.bid(bid,userID)) { setChanged(); notifyObservers(); return true; } return false; } List<Bid> getBiddingHistory() { return biddingModel.getBiddingHistory(); } String getCurrentPlayer() { return biddingModel.getCurrentPlayer(); } @Override public void update(Observable o, Object arg) { setChanged(); notifyObservers(); } }
package org.objectweb.proactive.core.group.spmd; import java.io.Serializable; /** * This class describes the state of a barrier. * * @author Laurent Baduel */ public class BarrierState implements Serializable { /** The number of calls awaited to finish the barrier */ private int awaitedCalls = 0; /** The number of calls already received */ private int receivedCalls = 0; /** * Returns the number of awaited calls to finish the barrier * @return the number of awaited calls to finish the barrier */ public int getAwaitedCalls() { return this.awaitedCalls; } /** * Returns the number of received calls to finish the barrier * @return the number of received calls to finish the barrier */ public int getReceivedCalls() { return this.receivedCalls; } /** * Sets the number of calls need to finish the barrier * @param nbCalls the number of calls need to finish the barrier */ public void setAwaitedCalls(int nbCalls) { this.awaitedCalls = nbCalls; } /** * Increments the number of received calls to finish the barrier */ public void incrementReceivedCalls() { this.receivedCalls++; } }
package org.openstreetmap.josm.plugins.notes; import static org.openstreetmap.josm.tools.I18n.tr; import java.util.Collection; import java.util.Iterator; import javax.swing.JOptionPane; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.actions.upload.UploadHook; import org.openstreetmap.josm.data.APIDataSet; import org.openstreetmap.josm.data.osm.OsmPrimitive; public class NotesUploadHook implements UploadHook { public boolean checkUpload(APIDataSet apiData) { boolean containsOsbData = checkOpenStreetBugs(apiData.getPrimitivesToAdd()); containsOsbData |= checkOpenStreetBugs(apiData.getPrimitivesToUpdate()); containsOsbData |= checkOpenStreetBugs(apiData.getPrimitivesToDelete()); if(containsOsbData) { JOptionPane.showMessageDialog(Main.parent, tr("<html>The selected data contains Notes.<br>" + "You cannot upload this data. Maybe you have selected the wrong layer?"), tr("Warning"), JOptionPane.WARNING_MESSAGE); return false; } else { return true; } } private boolean checkOpenStreetBugs(Collection<OsmPrimitive> osmPrimitives) { for (Iterator<OsmPrimitive> iterator = osmPrimitives.iterator(); iterator.hasNext();) { OsmPrimitive osmPrimitive = iterator.next(); if(osmPrimitive.get("openstreetbug") != null) { return true; } } return false; } }
package com.fasterxml.jackson.core.util; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import com.fasterxml.jackson.core.io.NumberInput; /** * TextBuffer is a class similar to {@link StringBuffer}, with * following differences: *<ul> * <li>TextBuffer uses segments character arrays, to avoid having * to do additional array copies when array is not big enough. * This means that only reallocating that is necessary is done only once: * if and when caller * wants to access contents in a linear array (char[], String). * </li> * <li>TextBuffer can also be initialized in "shared mode", in which * it will just act as a wrapper to a single char array managed * by another object (like parser that owns it) * </li> * <li>TextBuffer is not synchronized. * </li> * </ul> */ public final class TextBuffer { final static char[] NO_CHARS = new char[0]; /** * Let's start with sizable but not huge buffer, will grow as necessary */ final static int MIN_SEGMENT_LEN = 1000; /** * Let's limit maximum segment length to something sensible * like 256k */ final static int MAX_SEGMENT_LEN = 0x40000; private final BufferRecycler _allocator; /** * Shared input buffer; stored here in case some input can be returned * as is, without being copied to collector's own buffers. Note that * this is read-only for this Object. */ private char[] _inputBuffer; /** * Character offset of first char in input buffer; -1 to indicate * that input buffer currently does not contain any useful char data */ private int _inputStart; private int _inputLen; /** * List of segments prior to currently active segment. */ private ArrayList<char[]> _segments; /** * Flag that indicates whether _seqments is non-empty */ private boolean _hasSegments = false; // // // Currently used segment; not (yet) contained in _seqments /** * Amount of characters in segments in {@link _segments} */ private int _segmentSize; private char[] _currentSegment; /** * Number of characters in currently active (last) segment */ private int _currentSize; /** * String that will be constructed when the whole contents are * needed; will be temporarily stored in case asked for again. */ private String _resultString; private char[] _resultArray; public TextBuffer(BufferRecycler allocator) { _allocator = allocator; } /** * Method called to indicate that the underlying buffers should now * be recycled if they haven't yet been recycled. Although caller * can still use this text buffer, it is not advisable to call this * method if that is likely, since next time a buffer is needed, * buffers need to reallocated. * Note: calling this method automatically also clears contents * of the buffer. */ public void releaseBuffers() { if (_allocator == null) { resetWithEmpty(); } else { if (_currentSegment != null) { // First, let's get rid of all but the largest char array resetWithEmpty(); // And then return that array char[] buf = _currentSegment; _currentSegment = null; _allocator.releaseCharBuffer(BufferRecycler.CHAR_TEXT_BUFFER, buf); } } } /** * Method called to clear out any content text buffer may have, and * initializes buffer to use non-shared data. */ public void resetWithEmpty() { _inputStart = -1; // indicates shared buffer not used _currentSize = 0; _inputLen = 0; _inputBuffer = null; _resultString = null; _resultArray = null; // And then reset internal input buffers, if necessary: if (_hasSegments) { clearSegments(); } } /** * Method called to initialize the buffer with a shared copy of data; * this means that buffer will just have pointers to actual data. It * also means that if anything is to be appended to the buffer, it * will first have to unshare it (make a local copy). */ public void resetWithShared(char[] buf, int start, int len) { // First, let's clear intermediate values, if any: _resultString = null; _resultArray = null; // Then let's mark things we need about input buffer _inputBuffer = buf; _inputStart = start; _inputLen = len; // And then reset internal input buffers, if necessary: if (_hasSegments) { clearSegments(); } } public void resetWithCopy(char[] buf, int start, int len) { _inputBuffer = null; _inputStart = -1; // indicates shared buffer not used _inputLen = 0; _resultString = null; _resultArray = null; // And then reset internal input buffers, if necessary: if (_hasSegments) { clearSegments(); } else if (_currentSegment == null) { _currentSegment = buf(len); } _currentSize = _segmentSize = 0; append(buf, start, len); } public void resetWithString(String value) { _inputBuffer = null; _inputStart = -1; _inputLen = 0; _resultString = value; _resultArray = null; if (_hasSegments) { clearSegments(); } _currentSize = 0; } /** * Helper method used to find a buffer to use, ideally one * recycled earlier. */ private char[] buf(int needed) { if (_allocator != null) { return _allocator.allocCharBuffer(BufferRecycler.CHAR_TEXT_BUFFER, needed); } return new char[Math.max(needed, MIN_SEGMENT_LEN)]; } private void clearSegments() { _hasSegments = false; /* Let's start using _last_ segment from list; for one, it's * the biggest one, and it's also most likely to be cached */ /* 28-Aug-2009, tatu: Actually, the current segment should * be the biggest one, already */ //_currentSegment = _segments.get(_segments.size() - 1); _segments.clear(); _currentSize = _segmentSize = 0; } /** * @return Number of characters currently stored by this collector */ public int size() { if (_inputStart >= 0) { // shared copy from input buf return _inputLen; } if (_resultArray != null) { return _resultArray.length; } if (_resultString != null) { return _resultString.length(); } // local segmented buffers return _segmentSize + _currentSize; } public int getTextOffset() { /* Only shared input buffer can have non-zero offset; buffer * segments start at 0, and if we have to create a combo buffer, * that too will start from beginning of the buffer */ return (_inputStart >= 0) ? _inputStart : 0; } /** * Method that can be used to check whether textual contents can * be efficiently accessed using {@link #getTextBuffer}. */ public boolean hasTextAsCharacters() { // if we have array in some form, sure if (_inputStart >= 0 || _resultArray != null) return true; // not if we have String as value if (_resultString != null) return false; return true; } public char[] getTextBuffer() { // Are we just using shared input buffer? if (_inputStart >= 0) return _inputBuffer; if (_resultArray != null) return _resultArray; if (_resultString != null) { return (_resultArray = _resultString.toCharArray()); } // Nope; but does it fit in just one segment? if (!_hasSegments) return _currentSegment; // Nope, need to have/create a non-segmented array and return it return contentsAsArray(); } public String contentsAsString() { if (_resultString == null) { // Has array been requested? Can make a shortcut, if so: if (_resultArray != null) { _resultString = new String(_resultArray); } else { // Do we use shared array? if (_inputStart >= 0) { if (_inputLen < 1) { return (_resultString = ""); } _resultString = new String(_inputBuffer, _inputStart, _inputLen); } else { // nope... need to copy // But first, let's see if we have just one buffer int segLen = _segmentSize; int currLen = _currentSize; if (segLen == 0) { // yup _resultString = (currLen == 0) ? "" : new String(_currentSegment, 0, currLen); } else { // no, need to combine StringBuilder sb = new StringBuilder(segLen + currLen); // First stored segments if (_segments != null) { for (int i = 0, len = _segments.size(); i < len; ++i) { char[] curr = _segments.get(i); sb.append(curr, 0, curr.length); } } // And finally, current segment: sb.append(_currentSegment, 0, _currentSize); _resultString = sb.toString(); } } } } return _resultString; } public char[] contentsAsArray() { char[] result = _resultArray; if (result == null) { _resultArray = result = resultArray(); } return result; } /** * Convenience method for converting contents of the buffer * into a {@link BigDecimal}. */ public BigDecimal contentsAsDecimal() throws NumberFormatException { // Already got a pre-cut array? if (_resultArray != null) { return NumberInput.parseBigDecimal(_resultArray); } // Or a shared buffer? if ((_inputStart >= 0) && (_inputBuffer != null)) { return NumberInput.parseBigDecimal(_inputBuffer, _inputStart, _inputLen); } // Or if not, just a single buffer (the usual case) if ((_segmentSize == 0) && (_currentSegment != null)) { return NumberInput.parseBigDecimal(_currentSegment, 0, _currentSize); } // If not, let's just get it aggregated... return NumberInput.parseBigDecimal(contentsAsArray()); } /** * Convenience method for converting contents of the buffer * into a Double value. */ public double contentsAsDouble() throws NumberFormatException { return NumberInput.parseDouble(contentsAsString()); } /** * Method called to make sure that buffer is not using shared input * buffer; if it is, it will copy such contents to private buffer. */ public void ensureNotShared() { if (_inputStart >= 0) { unshare(16); } } public void append(char c) { // Using shared buffer so far? if (_inputStart >= 0) { unshare(16); } _resultString = null; _resultArray = null; // Room in current segment? char[] curr = _currentSegment; if (_currentSize >= curr.length) { expand(1); curr = _currentSegment; } curr[_currentSize++] = c; } public void append(char[] c, int start, int len) { // Can't append to shared buf (sanity check) if (_inputStart >= 0) { unshare(len); } _resultString = null; _resultArray = null; // Room in current segment? char[] curr = _currentSegment; int max = curr.length - _currentSize; if (max >= len) { System.arraycopy(c, start, curr, _currentSize, len); _currentSize += len; return; } // No room for all, need to copy part(s): if (max > 0) { System.arraycopy(c, start, curr, _currentSize, max); start += max; len -= max; } /* And then allocate new segment; we are guaranteed to now * have enough room in segment. */ // Except, as per [Issue-24], not for HUGE appends... so: do { expand(len); int amount = Math.min(_currentSegment.length, len); System.arraycopy(c, start, _currentSegment, 0, amount); _currentSize += amount; start += amount; len -= amount; } while (len > 0); } public void append(String str, int offset, int len) { // Can't append to shared buf (sanity check) if (_inputStart >= 0) { unshare(len); } _resultString = null; _resultArray = null; // Room in current segment? char[] curr = _currentSegment; int max = curr.length - _currentSize; if (max >= len) { str.getChars(offset, offset+len, curr, _currentSize); _currentSize += len; return; } // No room for all, need to copy part(s): if (max > 0) { str.getChars(offset, offset+max, curr, _currentSize); len -= max; offset += max; } /* And then allocate new segment; we are guaranteed to now * have enough room in segment. */ // Except, as per [Issue-24], not for HUGE appends... so: do { expand(len); int amount = Math.min(_currentSegment.length, len); str.getChars(offset, offset+amount, _currentSegment, 0); _currentSize += amount; offset += amount; len -= amount; } while (len > 0); } public char[] getCurrentSegment() { /* Since the intention of the caller is to directly add stuff into * buffers, we should NOT have anything in shared buffer... ie. may * need to unshare contents. */ if (_inputStart >= 0) { unshare(1); } else { char[] curr = _currentSegment; if (curr == null) { _currentSegment = buf(0); } else if (_currentSize >= curr.length) { // Plus, we better have room for at least one more char expand(1); } } return _currentSegment; } public char[] emptyAndGetCurrentSegment() { // inlined 'resetWithEmpty()' _inputStart = -1; // indicates shared buffer not used _currentSize = 0; _inputLen = 0; _inputBuffer = null; _resultString = null; _resultArray = null; // And then reset internal input buffers, if necessary: if (_hasSegments) { clearSegments(); } char[] curr = _currentSegment; if (curr == null) { _currentSegment = curr = buf(0); } return curr; } public int getCurrentSegmentSize() { return _currentSize; } public void setCurrentLength(int len) { _currentSize = len; } public char[] finishCurrentSegment() { if (_segments == null) { _segments = new ArrayList<char[]>(); } _hasSegments = true; _segments.add(_currentSegment); int oldLen = _currentSegment.length; _segmentSize += oldLen; // Let's grow segments by 50% int newLen = Math.min(oldLen + (oldLen >> 1), MAX_SEGMENT_LEN); char[] curr = carr(newLen); _currentSize = 0; _currentSegment = curr; return curr; } /** * Method called to expand size of the current segment, to * accommodate for more contiguous content. Usually only * used when parsing tokens like names if even then. */ public char[] expandCurrentSegment() { final char[] curr = _currentSegment; // Let's grow by 50% final int len = curr.length; // Must grow by at least 1 char, no matter what int newLen = (len == MAX_SEGMENT_LEN) ? (MAX_SEGMENT_LEN+1) : Math.min(MAX_SEGMENT_LEN, len + (len >> 1)); return (_currentSegment = Arrays.copyOf(curr, newLen)); } /** * Method called to expand size of the current segment, to * accommodate for more contiguous content. Usually only * used when parsing tokens like names if even then. * * @param minSize Required minimum strength of the current segment * * @since 2.4.0 */ public char[] expandCurrentSegment(int minSize) { char[] curr = _currentSegment; if (curr.length >= minSize) return curr; _currentSegment = curr = Arrays.copyOf(curr, minSize); return curr; } /** * Note: calling this method may not be as efficient as calling * {@link #contentsAsString}, since it's not guaranteed that resulting * String is cached. */ @Override public String toString() { return contentsAsString(); } /** * Method called if/when we need to append content when we have been * initialized to use shared buffer. */ private void unshare(int needExtra) { int sharedLen = _inputLen; _inputLen = 0; char[] inputBuf = _inputBuffer; _inputBuffer = null; int start = _inputStart; _inputStart = -1; // Is buffer big enough, or do we need to reallocate? int needed = sharedLen+needExtra; if (_currentSegment == null || needed > _currentSegment.length) { _currentSegment = buf(needed); } if (sharedLen > 0) { System.arraycopy(inputBuf, start, _currentSegment, 0, sharedLen); } _segmentSize = 0; _currentSize = sharedLen; } /** * Method called when current segment is full, to allocate new * segment. */ private void expand(int minNewSegmentSize) { // First, let's move current segment to segment list: if (_segments == null) { _segments = new ArrayList<char[]>(); } char[] curr = _currentSegment; _hasSegments = true; _segments.add(curr); _segmentSize += curr.length; int oldLen = curr.length; // Let's grow segments by 50% minimum int sizeAddition = oldLen >> 1; if (sizeAddition < minNewSegmentSize) { sizeAddition = minNewSegmentSize; } _currentSize = 0; _currentSegment = carr(Math.min(MAX_SEGMENT_LEN, oldLen + sizeAddition)); } private char[] resultArray() { if (_resultString != null) { // Can take a shortcut... return _resultString.toCharArray(); } // Do we use shared array? if (_inputStart >= 0) { final int len = _inputLen; if (len < 1) { return NO_CHARS; } final int start = _inputStart; if (start == 0) { return Arrays.copyOf(_inputBuffer, len); } return Arrays.copyOfRange(_inputBuffer, start, start+len); } // nope, not shared int size = size(); if (size < 1) { return NO_CHARS; } int offset = 0; final char[] result = carr(size); if (_segments != null) { for (int i = 0, len = _segments.size(); i < len; ++i) { char[] curr = (char[]) _segments.get(i); int currLen = curr.length; System.arraycopy(curr, 0, result, offset, currLen); offset += currLen; } } System.arraycopy(_currentSegment, 0, result, offset, _currentSize); return result; } private char[] carr(int len) { return new char[len]; } }
package org.pentaho.di.trans.steps.mappinginput; import java.util.List; import org.pentaho.di.core.Const; import org.pentaho.di.core.RowSet; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.di.trans.steps.mapping.MappingValueRename; /** * Do nothing. Pass all input data to the next steps. * * @author Matt * @since 2-jun-2003 */ public class MappingInput extends BaseStep implements StepInterface { private MappingInputMeta meta; private MappingInputData data; public MappingInput(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } // ProcessRow is not doing anything // It's a place holder for accepting rows from the parent transformation... // So, basically, this is a glorified Dummy with a little bit of meta-data public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(MappingInputMeta)smi; data=(MappingInputData)sdi; if (!data.linked) { // Wait until we know were to read from the parent transformation... // However, don't wait forever, if we don't have a connection after 60 seconds: bail out! int totalsleep = 0; while (!isStopped() && data.sourceSteps==null) { try { totalsleep+=10; Thread.sleep(10); } catch(InterruptedException e) { stopAll(); } if (totalsleep>60000) { throw new KettleException(Messages.getString("MappingInput.Exception.UnableToConnectWithParentMapping", ""+(totalsleep/1000))); } } // OK, now we're ready to read from the parent source steps. data.linked=true; } Object[] row = getRow(); if (row==null) { setOutputDone(); return false; } if (first) { first=false; // The Input RowMetadata is not the same as the output row meta-data. // The difference is described in the data interface // String[] data.sourceFieldname // String[] data.targetFieldname // --> getInputRowMeta() is not corresponding to what we're outputting. // In essence, we need to rename a couple of fields... data.outputRowMeta = getInputRowMeta().clone(); meta.setInputRowMeta(getInputRowMeta()); // Now change the field names according to the mapping specification... // That means that all fields go through unchanged, unless specified. if (meta.isSelectingAndSortingUnspecifiedFields()) { // Create a list of the indexes to select to get the right order or fields on the output. data.fieldNrs = new int[data.outputRowMeta.size()]; for (int i=0;i<data.outputRowMeta.size();i++) { data.fieldNrs[i] = getInputRowMeta().indexOfValue(data.outputRowMeta.getValueMeta(i).getName()); } } else { for (MappingValueRename valueRename : data.valueRenames) { ValueMetaInterface valueMeta = data.outputRowMeta.searchValueMeta(valueRename.getSourceValueName()); if (valueMeta==null) { throw new KettleStepException(Messages.getString("MappingInput.Exception.UnableToFindMappedValue", valueRename.getSourceValueName())); } valueMeta.setName(valueRename.getTargetValueName()); } } meta.getFields(data.outputRowMeta, getStepname(), null, null, this); } if (meta.isSelectingAndSortingUnspecifiedFields()) { Object[] outputRowData = RowDataUtil.allocateRowData(data.outputRowMeta.size()); for (int i=0;i<data.fieldNrs.length;i++) { outputRowData[i] = row[data.fieldNrs[i]]; } putRow(data.outputRowMeta, outputRowData); } else { putRow(data.outputRowMeta, row); } return true; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(MappingInputMeta)smi; data=(MappingInputData)sdi; if (super.init(smi, sdi)) { // Add init code here. return true; } return false; } public void setConnectorSteps(StepInterface[] sourceSteps, List<MappingValueRename> valueRenames) { for (int i=0;i<sourceSteps.length;i++) { // OK, before we leave, make sure there is a rowset that covers the path to this target step. // We need to create a new RowSet and add it to the Input RowSets of the target step RowSet rowSet = new RowSet(getTransMeta().getSizeRowset()); // This is always a single copy, both for source and target... rowSet.setThreadNameFromToCopy(sourceSteps[i].getStepname(), 0, getStepname(), 0); // Make sure to connect it to both sides... sourceSteps[i].getOutputRowSets().add(rowSet); getInputRowSets().add(rowSet); } data.valueRenames = valueRenames; data.sourceSteps = sourceSteps; } // Run is were the action happens! public void run() { try { logBasic(Messages.getString("System.Log.StartingToRun")); //$NON-NLS-1$ while (processRow(meta, data) && !isStopped()); } catch(Throwable t) { logError(Messages.getString("System.Log.UnexpectedError")+" : "); //$NON-NLS-1$ //$NON-NLS-2$ logError(Const.getStackTracker(t)); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }
package com.fatboyindustrial.raygun; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.classic.spi.IThrowableProxy; import ch.qos.logback.classic.spi.StackTraceElementProxy; import ch.qos.logback.core.AppenderBase; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableMap; import com.mindscapehq.raygun4java.core.RaygunClient; import com.mindscapehq.raygun4java.core.RaygunMessageBuilder; import com.mindscapehq.raygun4java.core.messages.RaygunErrorMessage; import com.mindscapehq.raygun4java.core.messages.RaygunErrorStackTraceLineMessage; import com.mindscapehq.raygun4java.core.messages.RaygunMessage; import java.net.InetAddress; import java.net.UnknownHostException; import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneId; /** * A logback appender that emits details to {@code raygun.io}. */ public class RaygunAppender extends AppenderBase<ILoggingEvent> { /** The name of our Raygun submission software. */ private static final String NAME = "logback-raygun"; /** The version of our Raygun submission software. */ private static final String VERSION = "1.0.0-SNAPSHOT"; /** The URL of our Raygun submission software. */ private static final String URL = "https://github.com/gkopff/logback-raygun"; /** * The RayGun API key. * The optional value is used to detect missing items in the configuration file - an absent value will * result in an error when the appender is started. */ private Optional<String> apiKey = Optional.absent(); /** * No-arg constructor required by Logback. */ public RaygunAppender() { ; } /** * Appends the logging event. * @param logEvent The logging event. */ @Override protected void append(ILoggingEvent logEvent) { final RaygunClient ray = new RaygunClient(this.apiKey.get()); // we check its present when the appender starts // We use the Raygun supplied classes a bit ... but we customise. final RaygunMessage msg = RaygunMessageBuilder.New() .SetEnvironmentDetails() .SetMachineName(getMachineName()) .SetClientDetails() .Build(); msg.getDetails().getClient().setName(NAME); msg.getDetails().getClient().setVersion(VERSION); msg.getDetails().getClient().setClientUrlString(URL); msg.getDetails().setError(buildRaygunMessage(logEvent)); msg.getDetails().setUserCustomData(ImmutableMap.of( "thread", logEvent.getThreadName(), "logger", logEvent.getLoggerName(), "datetime", OffsetDateTime.ofInstant(Instant.ofEpochMilli(logEvent.getTimeStamp()), ZoneId.systemDefault()))); ray.Post(msg); } /** * Starts the appender. */ @Override public void start() { if (! this.apiKey.isPresent()) { addError("API key missing for appender [" + this.name + "]."); } super.start(); } /** * Sets the API key. * @param apiKey The API key. */ @SuppressWarnings("UnusedDeclaration") // called by slf4j public void setApiKey(String apiKey) { Preconditions.checkNotNull(apiKey, "apiKey cannot be null"); this.apiKey = Optional.of(apiKey); } /** * Builds a {@code RaygunErrorMessage} for the given logging event. * @param loggingEvent The logging event. * @return The raygun message. */ private static RaygunErrorMessage buildRaygunMessage(ILoggingEvent loggingEvent) { final Optional<IThrowableProxy> exception = Optional.fromNullable(loggingEvent.getThrowableProxy()); return buildRaygunMessage(loggingEvent.getFormattedMessage(), exception); } /** * Builds a raygun message based on the given log message and optional exception details. * @param message The log message (fully formatted). * @param exception The optional exception details. * @return The raygun message. */ private static RaygunErrorMessage buildRaygunMessage(String message, Optional<IThrowableProxy> exception) { // The Raygun error message constructor wants a real exception, which we don't have - we only have // a logback throwable proxy. Therefore, we construct the error message with any old exception, // then make a second pass to fill in the real values. final RaygunErrorMessage error = new RaygunErrorMessage(new Exception()); final String className; final RaygunErrorStackTraceLineMessage[] trace; final Optional<RaygunErrorMessage> inner; final StringBuilder buff = new StringBuilder(); buff.append(message); if (exception.isPresent()) { buff.append("; "); buff.append(buildCausalString(exception.get())); className = exception.get().getClassName(); trace = buildRaygunStack(exception.get()); if (exception.get().getCause() != null) { inner = Optional.of(buildRaygunMessage("Caused by", Optional.of(exception.get().getCause()))); } else { inner = Optional.absent(); } } else { trace = new RaygunErrorStackTraceLineMessage[] { new RaygunErrorStackTraceLineMessage(locateCallSite()) }; className = trace[0].getClassName(); inner = Optional.absent(); } error.setMessage(buff.toString()); error.setClassName(className); error.setStackTrace(trace); if (inner.isPresent()) { error.setInnerError(inner.get()); } return error; } /** * Builds an exception causation string by following the exception caused-by chain. * @param exception The exception to process. * @return A string describing all exceptions in the chain. */ private static String buildCausalString(IThrowableProxy exception) { final StringBuilder buff = new StringBuilder(); buff.append(exception.getClassName()); if (exception.getMessage() != null) { buff.append(": ").append(exception.getMessage()); } if (exception.getCause() != null) { buff.append("; caused by: ").append(buildCausalString(exception.getCause())); } return buff.toString(); } /** * Builds a raygun stack trace from the given logback throwable proxy object. * @param throwableProxy The logback throwable proxy. * @return The raygun stack trace information. */ private static RaygunErrorStackTraceLineMessage[] buildRaygunStack(IThrowableProxy throwableProxy) { final StackTraceElementProxy[] proxies = throwableProxy.getStackTraceElementProxyArray(); final RaygunErrorStackTraceLineMessage[] lines = new RaygunErrorStackTraceLineMessage[proxies.length]; for (int i = 0; i < proxies.length; i++) { final StackTraceElementProxy step = proxies[i]; lines[i] = new RaygunErrorStackTraceLineMessage(step.getStackTraceElement()); } return lines; } /** * Gets the machine's hostname. * @return The hostname, or "UnknownHost" if it cannot be determined. */ private static String getMachineName() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { return "UnknownHost"; } } /** * Finds the stack trace elements that corresponds to the actual log call-site. * @return The applicable stack trace element. */ private static StackTraceElement locateCallSite() { // The stack will contain Fat Boy Industrial entries, followed by logback entries, // and then the actual call-site ... final String FBI = "com.fatboyindustrial.raygun.RaygunAppender"; final String LOGBACK = "ch.qos.logback."; for (StackTraceElement ste : new Exception().getStackTrace()) { if (ste.getClassName().startsWith(FBI) || ste.getClassName().startsWith(LOGBACK)) { continue; } return ste; } throw new IllegalStateException("Unable to determine call-site"); } }
package org.sosy_lab.java_smt.solvers.yices2; @SuppressWarnings({"unused", "checkstyle:methodname", "checkstyle:parametername"}) public class Yices2NativeApi { private Yices2NativeApi() {} // Yices2 status codes public static final int YICES_STATUS_IDLE = 0; public static final int YICES_STATUS_SEARCHING = 1; public static final int YICES_STATUS_UNKNOWN = 2; public static final int YICES_STATUS_SAT = 3; public static final int YICES_STATUS_UNSAT = 4; public static final int YICES_STATUS_INTERRUPTED = 5; public static final int YICES_STATUS_ERROR = 6; // Yices2 term constructors public static final int YICES_CONSTRUCTOR_ERROR = -1; public static final int YICES_BOOL_CONST = 0; public static final int YICES_ARITH_CONST = 1; public static final int YICES_BV_CONST = 2; public static final int YICES_SCALAR_CONST = 3; // NOT used in JavaSMT public static final int YICES_VARIABLE = 4; public static final int YICES_UNINTERPRETED_TERM = 5; public static final int YICES_ITE_TERM = 6; // if-then-else public static final int YICES_APP_TERM = 7; // application of an uninterpreted function public static final int YICES_UPDATE_TERM = 8; // function update public static final int YICES_TUPLE_TERM = 9; // tuple constructor public static final int YICES_EQ_TERM = 10; // equality public static final int YICES_DISTINCT_TERM = 11; // distinct t_1 ... t_n public static final int YICES_FORALL_TERM = 12; // quantifier public static final int YICES_LAMBDA_TERM = 13; // lambda public static final int YICES_NOT_TERM = 14; // (not t) public static final int YICES_OR_TERM = 15; // n-ary OR public static final int YICES_XOR_TERM = 16; // n-ary XOR public static final int YICES_BV_ARRAY = 17; // array of boolean terms public static final int YICES_BV_DIV = 18; // unsigned division public static final int YICES_BV_REM = 19; // unsigned remainder public static final int YICES_BV_SDIV = 20; // signed division public static final int YICES_BV_SREM = 21; // remainder in signed division (rounding to 0) public static final int YICES_BV_SMOD = 22; // remainder in signed division (rounding to // -infinity) public static final int YICES_BV_SHL = 23; // shift left (padding with 0) public static final int YICES_BV_LSHR = 24; // logical shift right (padding with 0) public static final int YICES_BV_ASHR = 25; // arithmetic shift right (padding with sign bit) public static final int YICES_BV_GE_ATOM = 26; // unsigned comparison: (t1 >= t2) public static final int YICES_BV_SGE_ATOM = 27; // signed comparison (t1 >= t2) public static final int YICES_ARITH_GE_ATOM = 28; // atom (t1 >= t2) for arithmetic terms: t2 is // always 0 public static final int YICES_ARITH_ROOT_ATOM = 29; // atom (0 <= k <= root_count(p)) && (x r // root(p,k)) for r in <, <=, ==, !=, >, >= public static final int YICES_ABS = 30; // absolute value public static final int YICES_CEIL = 31; // ceil public static final int YICES_FLOOR = 32; // floor public static final int YICES_RDIV = 33; // real division (as in x/y) public static final int YICES_IDIV = 34; // integer division public static final int YICES_IMOD = 35; // modulo public static final int YICES_IS_INT_ATOM = 36; // integrality test: (is-int t) public static final int YICES_DIVIDES_ATOM = 37; // divisibility test: (divides t1 t2) // projections public static final int YICES_SELECT_TERM = 38; // tuple projection public static final int YICES_BIT_TERM = 39; // bit-select: extract the i-th bit of a bitvector // sums public static final int YICES_BV_SUM = 40; // sum of pairs a * t where a is a bitvector constant // (and t is a bitvector term) public static final int YICES_ARITH_SUM = 41; // sum of pairs a * t where a is a rational (and t // is an arithmetic term) // products public static final int YICES_POWER_PRODUCT = 42; // power products: (t1^d1 * ... * t_n^d_n) // Workaround as Yices misses some useful operators, // MAX_INT avoids collisions with existing constants public static final int YICES_AND = Integer.MAX_VALUE - 1; public static final int YICES_BV_MUL = Integer.MAX_VALUE - 2; /* * Yices model tags */ public static final int YVAL_UNKNOWN = 0; public static final int YVAL_BOOL = 1; public static final int YVAL_RATIONAL = 2; public static final int YVAL_ALGEBRAIC = 3; public static final int YVAL_BV = 4; public static final int YVAL_SCALAR = 5; public static final int YVAL_TUPLE = 6; public static final int YVAL_FUNCTION = 7; public static final int YVAL_MAPPING = 8; /* * Yices initialization and exit */ /** Initializes Yices data structures. Needs to be called before doing anything else. */ public static native void yices_init(); /** Call at the end to free memory allocated by Yices. */ public static native void yices_exit(); /** * Perform a full reset of Yices * * <p>This function deletes all the terms and types defined in Yices and resets the symbol tables. * It also deletes all contexts, models, configuration descriptors, and other records allocated in * Yices. */ public static native void yices_reset(); /** * Frees the specified String. Several API functions build and return a character string that is * allocated by Yices. To avoid memory leaks, this string must be freed when it is no longer used * by calling this function. * * @param stringPtr The pointer to the String */ public static native void free_string(long stringPtr); /* * Yices Version checking for test purposes */ public static native int yices_get_version(); public static native int yices_get_major_version(); public static native int yices_get_patch_level(); /* * Context/ Environment creation */ public static native long yices_new_config(); public static native void yices_free_config(long cfg); /** * Set option to specified value. * * @param cfg The configuration to set the option in. * @param option The option to set. * @param value The value that the option will be set to. */ public static native void yices_set_config(long cfg, String option, String value); /** * Prepares a context configuration for the specified logic. * * @param cfg The configuration to be prepared * @param logic Name of the logic to prepare for or "NULL" * @return 0 if successful, -1 if an error occurred */ public static native int yices_default_config_for_logic(long cfg, String logic); public static native long yices_new_context(long cfg); public static native void yices_free_context(long ctx); public static native void yices_context_enable_option(long ctx, String option); public static native void yices_context_disable_option(long ctx, String option); /* * Yices search params */ public static native long yices_new_param_record(); public static native int yices_set_param(long record, String name, String value); public static native void yices_default_params_for_context(long ctx, long record); public static native void yices_free_param_record(long record); /* * Yices type construction */ public static native int yices_bool_type(); public static native int yices_int_type(); public static native int yices_real_type(); /** * Constructs a bitvector type. * * @param size is the number of bits. It must be positive and no more than YICES_MAX_BVSIZE * @return bitvector type */ public static native int yices_bv_type(int size); public static native int yices_function_type(int n, int[] dom, int range); /* * Yices type tests */ public static native boolean yices_type_is_bool(int t); public static native boolean yices_type_is_int(int t); public static native boolean yices_type_is_real(int t); /** * Checks if type is arithmetic (i.e., either integer or real). * * @param t Type to check * @return true if arithmetic, false otherwise */ public static native boolean yices_type_is_arithmetic(int t); public static native boolean yices_type_is_bitvector(int t); public static native boolean yices_type_is_function(int t); /** * Tests if the first type is a subtype of the second. * * @param t1 The first type * @param t2 The second type * @return true if t1 is a subtype of t2, otherwise false */ public static native boolean yices_test_subtype(int t1, int t2); /** * Tests if Type1 and Type2 are compatible. * * @param t1 The first type * @param t2 The second type * @return true if t1 and t2 are compatible, otherwise false */ public static native boolean yices_compatible_types(int t1, int t2); /** * Size of bitvector. * * @param t Bitvector to get the size of * @return Number of bits in bitvector or 0 if an error occurred */ public static native int yices_bvtype_size(int t); public static native int yices_type_num_children(int t); public static native int yices_type_child(int t, int index); public static native int[] yices_type_children(int t); /* * TERM CONSTRUCTION */ public static native int yices_new_uninterpreted_term(int type); public static native int yices_new_variable(int type); public static native int yices_constant(int type, int index); public static native int yices_ite(int t_if, int t_then, int t_else); public static native int yices_eq(int t_1, int t_2); public static native int yices_neq(int t_1, int t_2); public static native int yices_distinct(int size, int[] terms); public static native int yices_application(int t, int size, int[] terms); public static native int yices_update(int t1, int size, int[] terms, int t2); public static native int yices_forall(int size, int[] terms, int t); public static native int yices_exists(int size, int[] terms, int t); public static native int yices_lambda(int size, int[] terms, int t); /* * Bool Terms */ public static native int yices_true(); public static native int yices_false(); public static native int yices_not(int t); public static native int yices_and(int n, int[] arg); public static native int yices_and2(int t1, int t2); public static native int yices_and3(int t1, int t2, int t3); public static native int yices_or(int n, int[] arg); public static native int yices_or2(int t1, int t2); public static native int yices_or3(int t1, int t2, int t3); public static native int yices_xor(int n, int[] arg); public static native int yices_xor2(int t1, int t2); public static native int yices_xor3(int t1, int t2, int t3); public static native int yices_iff(int t1, int t2); public static native int yices_implies(int t1, int t2); /* * Arithmetic Terms */ public static native int yices_zero(); public static native int yices_int32(int value); public static native int yices_int64(long val); public static native int yices_rational32(int num, int den); public static native int yices_rational64(long num, long den); public static native int yices_parse_rational(String val); public static native int yices_parse_float(String val); public static native int yices_add(int t1, int t2); public static native int yices_sub(int t1, int t2); public static native int yices_neg(int t); public static native int yices_mul(int t1, int t2); public static native int yices_square(int t); public static native int yices_power(int t, int power); public static native int yices_division(int t1, int t2); public static native int yices_sum(int size, int[] terms); public static native int yices_product(int size, int[] terms); public static native int yices_poly_int32(int size, int[] coeff, int[] terms); public static native int yices_poly_int64(int size, long[] coeff, int[] terms); public static native int yices_abs(int t); public static native int yices_floor(int t); public static native int yices_ceil(int t); public static native int yices_idiv(int t1, int t2); public static native int yices_imod(int t1, int t2); public static native int yices_arith_eq_atom(int t1, int t2); public static native int yices_arith_neq_atom(int t1, int t2); public static native int yices_arith_geq_atom(int t1, int t2); public static native int yices_arith_leq_atom(int t1, int t2); public static native int yices_arith_gt_atom(int t1, int t2); public static native int yices_arith_lt_atom(int t1, int t2); public static native int yices_arith_eq0_atom(int t); public static native int yices_arith_neq0_atom(int t); public static native int yices_arith_geq0_atom(int t); public static native int yices_arith_leq0_atom(int t); public static native int yices_arith_gt0_atom(int t); public static native int yices_arith_lt0_atom(int t); public static native int yices_divides_atom(int t1, int t2); public static native int yices_is_int_atom(int t); /* * Bitvector Terms */ public static native int yices_bvconst_uint32(int size, int value); public static native int yices_bvcinst_uint64(int size, long value); public static native int yices_bvconst_int32(int size, int value); public static native int yices_bvconst_int64(int size, long value); public static native int yices_bvconst_zero(int size); public static native int yices_bvconst_one(int size); public static native int yices_bvconst_minus_one(int size); /** * Parses the given Array in little endian order values[0] becomes the least significant bit. * values[size-1] becomes the most significant bit. */ public static native int yices_bvconst_from_array(int size, int[] values); public static native int yices_parse_bvbin(String value); public static native int yices_parse_bvhex(String value); public static native int yices_bvadd(int t1, int t2); public static native int yices_bvsub(int t1, int t2); public static native int yices_bvneg(int t); public static native int yices_bvmul(int t1, int t2); public static native int yices_bvsquare(int t); public static native int yices_bvpower(int t, int power); public static native int yices_bvsum(int size, int[] terms); public static native int yices_bvproduct(int size, int[] terms); public static native int yices_bvdiv(int t1, int t2); public static native int yices_bvrem(int t1, int t2); public static native int yices_bvsdiv(int t1, int t2); public static native int yices_bvsrem(int t1, int t2); public static native int yices_bvsmod(int t1, int t2); public static native int yices_bvnot(int t); public static native int yices_bvand(int size, int[] terms); public static native int yices_bvand2(int t1, int t2); public static native int yices_bvand3(int t1, int t2, int t3); public static native int yices_bvor(int size, int[] terms); public static native int yices_bvor2(int t1, int t2); public static native int yices_bvor3(int t1, int t2, int t3); public static native int yices_bvxor(int size, int[] terms); public static native int yices_bvxor2(int t1, int t2); public static native int yices_bvxor3(int t1, int t2, int t3); public static native int yices_bvnand(int t1, int t2); public static native int yices_bvnor(int t1, int t2); public static native int yices_bvxnor(int t1, int t2); public static native int yices_shift_left0(int t, int shift); public static native int yices_shift_left1(int t, int shift); public static native int yices_shift_right0(int t, int shift); public static native int yices_shift_right1(int t, int shift); public static native int yices_ashift_right(int t, int shift); public static native int yices_rotate_left(int t, int shift); public static native int yices_rotate_right(int t, int shift); public static native int yices_bvshl(int t1, int t2); public static native int yices_bvlshr(int t1, int t2); public static native int yices_bvashr(int t1, int t2); public static native int yices_bvextract(int t, int limit1, int limit2); public static native int yices_bitextract(int t, int pos); public static native int yices_bvconcat(int size, int[] terms); public static native int yices_bvconcat2(int t1, int t2); public static native int yices_bvrepeat(int t, int times); public static native int yices_sign_extend(int t, int times); public static native int yices_zero_extend(int t, int times); public static native int yices_redand(int t); public static native int yices_redor(int t); public static native int yices_redcomp(int t1, int t2); public static native int yices_bvarray(int size, int[] terms); public static native int yices_bveq_atom(int t1, int t2); public static native int yices_bvneq_atom(int t1, int t2); public static native int yices_bvge_atom(int t1, int t2); public static native int yices_bvgt_atom(int t1, int t2); public static native int yices_bvle_atom(int t1, int t2); public static native int yices_bvlt_atom(int t1, int t2); public static native int yices_bvsge_atom(int t1, int t2); public static native int yices_bvsgt_atom(int t1, int t2); public static native int yices_bvsle_atom(int t1, int t2); public static native int yices_bvslt_atom(int t1, int t2); /* * Term properties */ public static native int yices_type_of_term(int t); public static native boolean yices_term_is_bool(int t); public static native boolean yices_term_is_int(int t); public static native boolean yices_term_is_real(int t); public static native boolean yices_term_is_arithmetic(int t); public static native boolean yices_term_is_bitvector(int t); public static native boolean yices_term_is_function(int t); public static native int yices_term_bitsize(int t); public static native boolean yices_term_is_ground(int t); public static native boolean yices_term_is_atomic(int t); public static native boolean yices_term_is_composite(int t); public static native boolean yices_term_is_projection(int t); public static native boolean yices_term_is_sum(int t); public static native boolean yices_term_is_bvsum(int t); public static native boolean yices_term_is_product(int t); public static native int yices_term_constructor(int t); public static native int yices_term_num_children(int t); public static native int yices_term_child(int t, int index); public static native int yices_proj_index(int t); public static native int yices_proj_arg(int t); public static native boolean yices_bool_const_value(int t); // TODO Return bool[] instead of int[]? /** Returns in little endian order. */ public static native int[] yices_bv_const_value(int t, int bitsize); public static native String yices_rational_const_value(int t); /** * Returns i-th sum component of term t as String-Array [coefficient, term]. If t is in a form * like 3+x, for i = 0 the returned term will be -1/NULL_TERM. */ public static native String[] yices_sum_component(int t, int i); /** * Returns the i-th component of a bvsum. Returned array has length bitsize+1. array[0] to * array[array.length-2] contain the coefficient, array[array.length-1] the term. If the t is in a * form like [101]+x, for i = 0, the returned term will be -1/NULL_TERM. */ public static native int[] yices_bvsum_component(int t, int i, int bitsize); // TODO can return up to UINT32_MAX ? /** Returns an array in the form [term,power]. */ public static native int[] yices_product_component(int t, int i); /* * SAT Checking */ public static native int yices_context_status(long ctx); public static native void yices_assert_formula(long ctx, int f); public static native void yices_assert_formulas(long ctx, int size, int[] formulas); /** @param params Set to 0 for default search parameters. */ public static native int yices_check_context(long ctx, long params); public static native void yices_stop_search(long ctx); public static native void yices_reset_context(long ctx); public static native int yices_assert_blocking_clause(long ctx); public static native void yices_push(long ctx); public static native void yices_pop(long ctx); /** @param params Set to 0 for default search parameters. */ public static native int yices_check_context_with_assumptions( long ctx, long params, int size, int[] terms); public static native int[] yices_get_unsat_core(long ctx); /** @param params Set to 0 for default search parameters. */ public static boolean yices_check_sat(long ctx, long params) throws IllegalStateException { return check_result(yices_check_context(ctx, params)); } /** @param params Set to 0 for default search parameters. */ public static boolean yices_check_sat_with_assumptions( long ctx, long params, int size, int[] assumptions) throws IllegalStateException { return check_result(yices_check_context_with_assumptions(ctx, params, size, assumptions)); } private static boolean check_result(int result) throws IllegalStateException { switch (result) { case YICES_STATUS_SAT: return true; case YICES_STATUS_UNSAT: return false; default: // TODO Further ERROR CLARIFICATION String code = (result == YICES_STATUS_UNKNOWN) ? "\"unknown\"" : result + ""; throw new IllegalStateException("Yices check returned:" + code); } } /* * Model generation and exploration */ public static native long yices_get_model(long ctx, int keepSubst); public static native long yices_model_from_map(int size, int[] var, int[] constant); /* * renamed collect_defined_terms to def_terms as it caused an UnsatisfiedLinkError for some reason */ public static native int[] yices_def_terms(long model); // collect_defined_terms(long model); public static native void yices_free_model(long model); /** get the value of a term as pair [node_id, node_tag]. */ public static native int[] yices_get_value(long m, int t); public static native int yices_val_bitsize(long m, int id, int tag); public static native int yices_val_function_arity(long m, int id, int tag); public static native boolean yices_val_get_bool(long m, int id, int tag); public static native String yices_val_get_mpq(long m, int id, int tag); /* * node_id / node_tag separated to preserve C call order * Returns in little endian order */ public static native int[] yices_val_get_bv(long m, int id, int size, int tag); /** * Returns array of yval_t values built like this: [yval_t.node_id, yval_t.node_tag, * yval_t.node_id, yval_t.node_tag, ...]. The first pair of values represent the default value, * the following values should represent mappings, which can be expanded using expand_mapping(). */ public static native int[] yices_val_expand_function(long m, int id, int tag); /** * Returns array of yval_t values built like this: [yval_t.node_id, yval_t.node_tag, * yval_t.node_id, yval_t.node_tag, ...]. The last pair of values represent the function's value, * the other pairs are values for the function's arguments. node_id / node_tag separated to * preserve C call order */ public static native int[] yices_val_expand_mapping(long m, int id, int arity, int tag); /** get the value of a term as (constant) term. */ public static native int yices_get_value_as_term(long m, int t); public static native void yices_set_term_name(int t, String name); public static native String yices_get_term_name(int t); public static native int yices_get_term_by_name(String name); /** * Use to print a term in a readable format. Result will be truncated if height/width of the * String are too small. * * @param t The term to print * @param width The width of the resulting String * @param height The height/lines of resulting String */ private static native String yices_term_to_string(int t, int width, int height, int offset); private static native String yices_type_to_string(int t, int width, int height, int offset); private static native String yices_model_to_string(long m, int width, int height, int offset); public static String yices_term_to_string(int t) { return yices_term_to_string(t, Integer.MAX_VALUE, 1, 0); } public static String yices_type_to_string(int t) { return yices_type_to_string(t, Integer.MAX_VALUE, 1, 0); } public static String yices_model_to_string(long m) { return yices_model_to_string(m, Integer.MAX_VALUE, 1, 0); } /** Parse Term in SMT-Lib2 / Yices input language. */ public static native int yices_parse_term(String t); public static native int yices_subst_term(int size, int[] from, int[] to, int t); public static int yices_named_variable(int type, String name) { int termFromName = yices_get_term_by_name(name); if (termFromName != -1) { int termFromNameType = yices_type_of_term(termFromName); if (type == termFromNameType) { return termFromName; } else { throw new IllegalArgumentException( String.format( "Can't create variable with name '%s' and type '%s' " + "as it would omit a variable with type '%s'", name, yices_type_to_string(type), yices_type_to_string(termFromNameType))); } } int var = yices_new_uninterpreted_term(type); yices_set_term_name(var, name); return var; } }
package com.gamingmesh.jobs.container; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import com.gamingmesh.jobs.Jobs; import com.gamingmesh.jobs.stuff.Debug; public class ExploreChunk { int x; int z; Set<String> playerNames = new HashSet<>(); private Integer dbId = null; private boolean updated = false; public ExploreChunk(String playerName, int x, int z) { this.x = x; this.z = z; this.playerNames.add(playerName); } public ExploreChunk(int x, int z) { this.x = x; this.z = z; } public ExploreRespond addPlayer(String playerName) { boolean newChunkForPlayer = false; if (!playerNames.contains(playerName)) { if (playerNames.size() < Jobs.getExplore().getPlayerAmount()) { playerNames.add(playerName); updated = true; } newChunkForPlayer = true; } return new ExploreRespond(newChunkForPlayer ? playerNames.size() : playerNames.size() + 1, newChunkForPlayer); } public boolean isAlreadyVisited(String playerName) { return playerNames.contains(playerName); } public int getCount() { return this.playerNames.size(); } public int getX() { return this.x; } public int getZ() { return this.z; } public Set<String> getPlayers() { return this.playerNames; } public String serializeNames() { String s = ""; for (String one : this.playerNames) { if (!s.isEmpty()) s += ";"; s += one; } return s; } public void deserializeNames(String names) { if (names.contains(";")) playerNames.addAll(Arrays.asList(names.split(";"))); else playerNames.add(names); } public Integer getDbId() { return dbId; } public void setDbId(Integer dbId) { this.dbId = dbId; } public boolean isUpdated() { return updated; } public void setUpdated(boolean updated) { this.updated = updated; } }
package com.github.brotherlogic.pictureframe; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import javax.swing.JFrame; import javax.swing.SwingUtilities; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import io.grpc.BindableService; public class Frame extends FrameBase { private DropboxConnector connector; private Config config; private File configFile; public Frame(String token, File configFile) { connector = new DropboxConnector(token); try { if (configFile != null) { this.configFile = configFile; FileInputStream fis = new FileInputStream(configFile); config = new Config(proto.ConfigOuterClass.Config.parseFrom(fis).toByteArray()); } else { config = new Config(); } } catch (IOException e) { config = new Config(); } } public void runWebServer() throws IOException { new HttpServer(config, this); } public static void main(String[] args) throws Exception { Option optionServer = OptionBuilder.withLongOpt("server").hasArg().withDescription("Hostname of server") .create("s"); Option optionToken = OptionBuilder.withLongOpt("token").hasArg().withDescription("Token to use for dropbox") .create("t"); Option optionConfig = OptionBuilder.withLongOpt("config").hasArg().withDescription("Config file to user") .create("c"); Options options = new Options(); options.addOption(optionServer); options.addOption(optionToken); CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); String server = "10.0.1.17"; System.out.println("ARGS = " + Arrays.toString(args)); if (line.hasOption("server")) server = line.getOptionValue("s"); String token = "unknown"; if (line.hasOption("token")) token = line.getOptionValue("t"); String configLocation = ".config"; if (line.hasOption("config")) configLocation = line.getOptionValue("c"); Frame f = new Frame(token, new File(configLocation)); f.runWebServer(); f.Serve(server); } @Override public String getServerName() { return "PictureFrame"; } public void saveConfig() { try { System.out.println("SAVING TO " + configFile); FileOutputStream fos = new FileOutputStream(configFile); config.getConfig().writeTo(fos); fos.close(); } catch (IOException e) { e.printStackTrace(); } } @Override public List<BindableService> getServices() { return new LinkedList<BindableService>(); } public void syncAndDisplay() { if (connector != null) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { d.getContentPane().removeAll(); File out = new File("pics/"); out.mkdirs(); try { connector.syncFolder("/", out); Photo p = getTimedLatestPhoto(out.getAbsolutePath()); if (p != null) { System.out.println("Got picture: " + p.getName()); final ImagePanel imgPanel = new ImagePanel(p.getImage()); d.add(imgPanel); System.out.println("Added picture"); d.revalidate(); } } catch (Exception e) { e.printStackTrace(); } } }); } } @Override public Config getConfig() { return config; } public void backgroundSync() { while (true) { syncAndDisplay(); // Wait before updating the picture try { Thread.sleep(2 * 60 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } } FrameDisplay d; @Override public void localServe() { d = new FrameDisplay(); d.setSize(800, 480); d.setLocationRelativeTo(null); d.setVisible(true); d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); backgroundSync(); } }
package com.github.davidmoten.rtree; import java.util.List; import com.google.common.base.Optional; /** * Used for tracking deletions through recursive calls. * * @param <T> * entry type */ public class NodeAndEntries<T> { private final Optional<? extends Node<T>> node; private final List<Entry<T>> entries; private final int count; /** * Constructor. * * @param node * absent = whole node was deleted present = either an unchanged * node because of no removal or the newly created node without * the deleted entry * @param entries * from nodes that dropped below minChildren in size and thus * their entries are to be redistributed (readded to the tree) * @param countDeleted * count of the number of entries removed */ public NodeAndEntries(Optional<? extends Node<T>> node, List<Entry<T>> entries, int countDeleted) { this.node = node; this.entries = entries; this.count = countDeleted; } public Optional<? extends Node<T>> node() { return node; } public List<Entry<T>> entriesToAdd() { return entries; } public int countDeleted() { return count; } }
package com.github.skare69.boo; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.codec.digest.DigestUtils; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class DuplicateFileFinder { private static Logger logger = Logger.getLogger(DuplicateFileFinder.class); /** * Max file size default value: 5 MB */ private static final Integer DEFAULT_MAX_FILE_SIZE = 5242880; private static Options options; /** * Set the CLI options. */ static { options = new Options(); for (CliOption option : CliOption.values()) { Option newOption = new Option(option.getOpt(), option.getHasArg(), option.getDescription()); if (option.getLongOpt() != null) { newOption.setLongOpt(option.getLongOpt()); } newOption.setRequired(option.isRequired()); options.addOption(newOption); } } private HashMap<String, List<String>> fileHashesMap = new HashMap<>(); private Integer fileCount = 0; private CommandLine commandLine; public static void main(String[] args) { DuplicateFileFinder duplicateFileFinder = new DuplicateFileFinder(); CommandLineParser parser = new BasicParser(); try { duplicateFileFinder.setCommandLine(parser.parse(options, args)); if (duplicateFileFinder.getCommandLine().hasOption(CliOption.HELP.getOpt())) { HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("boo", options); return; } } catch (ParseException e) { logger.info(e.getMessage()); HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("boo", options); return; } if (duplicateFileFinder.getCommandLine().hasOption(CliOption.VERBOSE_OUTPUT.getOpt())) { LogManager.getRootLogger().setLevel(Level.DEBUG); } if (duplicateFileFinder.getCommandLine().hasOption(CliOption.FLAT_SCAN.getOpt())) { logger.info("Doing a flat scan; i.e. not recursively scanning directories. "); } if (duplicateFileFinder.getCommandLine().hasOption(CliOption.HIDDEN_FILES.getOpt())) { logger.info("Including hidden files in scan."); } duplicateFileFinder.scanDirectory(duplicateFileFinder.getCommandLine().getOptionValue(CliOption.DIRECTORY_TO_SCAN.getOpt())); displayResults(duplicateFileFinder); } /** * Display the results of the scanned files. Lists all found duplicates if any were found. * * @param duplicateFileFinder The {@link com.github.skare69.boo.DuplicateFileFinder} instance which was used to scan the files. */ private static void displayResults(DuplicateFileFinder duplicateFileFinder) { logger.info(String.format("Scanned %d files", duplicateFileFinder.getFileCount())); Iterator<Map.Entry<String, List<String>>> iterator = duplicateFileFinder.getFileHashesMap().entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, List<String>> entry = iterator.next(); if (entry.getValue().size() < 2) iterator.remove(); else { logger.info("Found duplicates"); for (String file : entry.getValue()) { logger.info("* " + file); } logger.info(""); // pseudo new line as the logger automatically inserts a line separator after each log message } } if (duplicateFileFinder.getFileHashesMap().isEmpty()) { logger.info("No duplicates found."); } } public CommandLine getCommandLine() { return commandLine; } public void setCommandLine(CommandLine commandLine) { this.commandLine = commandLine; } public Integer getFileCount() { return fileCount; } /** * Increment the {@code fileCount} by 1. */ private void incrementFileCount() { this.fileCount++; } public HashMap<String, List<String>> getFileHashesMap() { return fileHashesMap; } /** * Add a new entry to the {@code fileHashesMap} if the file's MD5 hash is not yet contained in the list. Add it to the appropriate * entry's list otherwise. * * @param file The new file to add. * @throws IOException if the file can't be hashed */ private void addToFileHashesMap(File file) throws IOException { String md5Hex = DigestUtils.md5Hex(new FileInputStream(file)); if (fileHashesMap.containsKey(md5Hex)) { fileHashesMap.get(md5Hex).add(file.getAbsolutePath()); } else { List<String> newFilePathList = new ArrayList<>(1); newFilePathList.add(file.getAbsolutePath()); fileHashesMap.put(md5Hex, newFilePathList); } } /** * Recursively scan the provided files. If an entry is a file it is added to the {@code fileHashesMap}. If it is a directory it is * also scanned by this method. * * @param filesInDirectory a list of files to scan */ private void scanFilesInDirectory(File[] filesInDirectory) { if (filesInDirectory.length > 0) { for (File file : filesInDirectory) { if (file.isHidden()) { if (!commandLine.hasOption(CliOption.HIDDEN_FILES.getOpt())) continue; } Integer maxFileSize = DEFAULT_MAX_FILE_SIZE; String maxFileSizeOptionValue = getCommandLine().getOptionValue(CliOption.MAX_FILE_SIZE.getOpt()); if (maxFileSizeOptionValue != null) { maxFileSize = Integer.valueOf(maxFileSizeOptionValue); } if (file.length() > maxFileSize) { logger.debug(String.format("Skipping file %s due to file size (file: %d, max: %d)", file.getAbsolutePath(), file.length(), maxFileSize)); continue; } if (file.isFile()) { logger.debug(String.format("Scanning file %s", file.getAbsolutePath())); incrementFileCount(); try { addToFileHashesMap(file); } catch (IOException e) { e.printStackTrace(); } } else if (file.isDirectory()) { logger.debug(String.format("Scanning directory %s", file.getAbsolutePath())); scanDirectory(file); } } } } /** * Scan the specified directory for file duplicates. * * @param directory the directory to scan */ private void scanDirectory(File directory) { File[] filesInDirectory = getFilesInDirectory(directory); scanFilesInDirectory(filesInDirectory); } /** * Scan the specified directory for file duplicates. * * @param directoryPath the directory to scan */ private void scanDirectory(String directoryPath) { File[] filesInDirectory = getFilesInDirectory(directoryPath); logger.debug(String.format("Scanning files in directory: %s", directoryPath)); scanFilesInDirectory(filesInDirectory); } /** * Alternative version of the {@link com.github.skare69.boo.DuplicateFileFinder#getFilesInDirectory(java.io.File)} method; taking a * {@link java.lang.String} as the input argument instead of a {@link java.io.File}. * * @param directoryPath The path of the directory to scan. * @return a list of files contained in this directory (including files and other directories) if there were any; an empty array * otherwise */ private File[] getFilesInDirectory(String directoryPath) { File directory = new File(directoryPath); return getFilesInDirectory(directory); } /** * Get all files in the specified directory. * * @param directory the directory to scan. * @return a list of files contained in this directory (including files and other directories) if there were any; an empty array * otherwise */ private File[] getFilesInDirectory(File directory) { if (directory.isDirectory()) return directory.listFiles(); else return new File[]{}; } /** * This enum contains all commandline interface options for easier access. */ private enum CliOption { HELP("h", "help", false, "display this help message"), HIDDEN_FILES("f", false, "include hidden files (default: false)"), DIRECTORY_TO_SCAN("t", "target", true, "target directory to scan", true), FLAT_SCAN("f", "flat", false, "do a flat scan of the provided directory only; i.e. no recursion (default: false)"), VERBOSE_OUTPUT("v", "verbose", false, "print a verbose output of what's happening (default: false)"), MAX_FILE_SIZE("m", "max", true, "the maximum size of a file to scan in bytes (default: 5 MB)"); private String opt; private String longOpt; private boolean hasArg; private String description; private boolean required; CliOption(String opt, boolean hasArg, String description) { this.opt = opt; this.hasArg = hasArg; this.description = description; } CliOption(String opt, String longOpt, boolean hasArg, String description) { this.opt = opt; this.longOpt = longOpt; this.hasArg = hasArg; this.description = description; } CliOption(String opt, String longOpt, boolean hasArg, String description, boolean required) { this.opt = opt; this.longOpt = longOpt; this.hasArg = hasArg; this.description = description; this.required = required; } public String getOpt() { return opt; } public String getLongOpt() { return longOpt; } public boolean getHasArg() { return hasArg; } public String getDescription() { return description; } public boolean isRequired() { return required; } } }
package com.gmail.nossr50.listeners; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.AnimalTamer; import org.bukkit.entity.Entity; import org.bukkit.entity.FallingBlock; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.entity.TNTPrimed; import org.bukkit.entity.Tameable; import org.bukkit.entity.Wolf; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; import org.bukkit.event.entity.EntityChangeBlockEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDamageEvent.DamageCause; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.entity.EntityTameEvent; import org.bukkit.event.entity.EntityTargetEvent; import org.bukkit.event.entity.ExplosionPrimeEvent; import org.bukkit.event.entity.FoodLevelChangeEvent; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.config.Config; import com.gmail.nossr50.datatypes.McMMOPlayer; import com.gmail.nossr50.datatypes.PlayerProfile; import com.gmail.nossr50.events.fake.FakeEntityDamageByEntityEvent; import com.gmail.nossr50.events.fake.FakeEntityDamageEvent; import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.skills.acrobatics.Acrobatics; import com.gmail.nossr50.skills.acrobatics.AcrobaticsManager; import com.gmail.nossr50.skills.archery.Archery; import com.gmail.nossr50.skills.fishing.Fishing; import com.gmail.nossr50.skills.herbalism.Herbalism; import com.gmail.nossr50.skills.mining.MiningManager; import com.gmail.nossr50.skills.runnables.BleedTimer; import com.gmail.nossr50.skills.taming.TamingManager; import com.gmail.nossr50.skills.utilities.CombatTools; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.Users; public class EntityListener implements Listener { private final mcMMO plugin; public EntityListener(final mcMMO plugin) { this.plugin = plugin; } /** * Monitor EntityChangeBlock events. * * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityChangeBlockEvent(EntityChangeBlockEvent event) { Entity entity = event.getEntity(); if (entity instanceof FallingBlock) { Block block = event.getBlock(); if (mcMMO.placeStore.isTrue(block) && !mcMMO.placeStore.isSpawnedMob(entity)) { mcMMO.placeStore.setFalse(block); mcMMO.placeStore.addSpawnedMob(entity); } else if (mcMMO.placeStore.isSpawnedMob(entity)) { mcMMO.placeStore.setTrue(block); mcMMO.placeStore.removeSpawnedMob(entity); } } } /** * Handle EntityDamageByEntity events that involve modifying the event. * * @param event The event to watch */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { if (event instanceof FakeEntityDamageByEntityEvent || event.getDamage() <= 0) return; Entity defender = event.getEntity(); if (Misc.isNPCEntity(defender) || defender.isDead()) { return; } Entity attacker = event.getDamager(); if (attacker instanceof Projectile) { attacker = ((Projectile) attacker).getShooter(); } else if (attacker instanceof Tameable) { AnimalTamer animalTamer = ((Tameable) attacker).getOwner(); if (animalTamer != null) { attacker = (Entity) animalTamer; } } if (defender instanceof Player) { Player defendingPlayer = (Player) defender; if (!defendingPlayer.isOnline()) { return; } if (attacker instanceof Player && PartyManager.inSameParty(defendingPlayer, (Player) attacker)) { if (!(Permissions.friendlyFire((Player) attacker) && Permissions.friendlyFire(defendingPlayer))) { event.setCancelled(true); return; } } } /* Check for invincibility */ if (defender instanceof LivingEntity) { LivingEntity livingDefender = (LivingEntity) defender; if (!Misc.isInvincible(livingDefender, event)) { CombatTools.combatChecks(event, attacker, livingDefender); } } } /** * Handle EntityDamage events that involve modifying the event. * * @param event The event to modify */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityDamage(EntityDamageEvent event) { if (event instanceof FakeEntityDamageEvent || event.getDamage() <= 0) { return; } Entity entity = event.getEntity(); if (!(entity instanceof LivingEntity)) { return; } DamageCause cause = event.getCause(); LivingEntity livingEntity = (LivingEntity) entity; if (livingEntity instanceof Player) { Player player = (Player) entity; if (!player.isOnline() || Misc.isNPCPlayer(player)) { return; } McMMOPlayer mcMMOPlayer = Users.getPlayer(player); PlayerProfile profile = mcMMOPlayer.getProfile(); /* Check for invincibility */ if (profile.getGodMode()) { event.setCancelled(true); return; } if (!Misc.isInvincible(player, event)) { if (cause == DamageCause.FALL && player.getItemInHand().getType() != Material.ENDER_PEARL && !(Acrobatics.afkLevelingDisabled && player.isInsideVehicle()) && Permissions.roll(player)) { AcrobaticsManager acrobaticsManager = new AcrobaticsManager(mcMMOPlayer); acrobaticsManager.rollCheck(event); } else if (cause == DamageCause.BLOCK_EXPLOSION && Permissions.demolitionsExpertise(player)) { MiningManager miningManager = new MiningManager(mcMMOPlayer); miningManager.demolitionsExpertise(event); } if (event.getDamage() >= 1) { profile.actualizeRecentlyHurt(); } } } else if (livingEntity instanceof Tameable) { Tameable pet = (Tameable) livingEntity; AnimalTamer owner = pet.getOwner(); if ((!Misc.isInvincible(livingEntity, event)) && pet.isTamed() && owner instanceof Player && pet instanceof Wolf) { TamingManager tamingManager = new TamingManager(Users.getPlayer((Player) owner)); tamingManager.preventDamage(event); } } } /** * Monitor EntityDeath events. * * @param event The event to watch */ @EventHandler (priority = EventPriority.MONITOR) public void onEntityDeath(EntityDeathEvent event) { LivingEntity entity = event.getEntity(); if (Misc.isNPCEntity(entity)) { return; } entity.setFireTicks(0); BleedTimer.remove(entity); Archery.arrowRetrievalCheck(entity); mcMMO.placeStore.removeSpawnedMob(entity); } /** * Monitor CreatureSpawn events. * * @param event The event to watch */ @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCreatureSpawn(CreatureSpawnEvent event) { if (Misc.isSpawnerXPEnabled) { return; } SpawnReason reason = event.getSpawnReason(); if (reason == SpawnReason.SPAWNER || reason == SpawnReason.SPAWNER_EGG) { mcMMO.placeStore.addSpawnedMob(event.getEntity()); } } /** * Handle ExplosionPrime events that involve modifying the event. * * @param event The event to modify */ @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onExplosionPrime(ExplosionPrimeEvent event) { Entity entity = event.getEntity(); if (entity instanceof TNTPrimed) { int id = entity.getEntityId(); if (plugin.tntIsTracked(id)) { Player player = plugin.getTNTPlayer(id); if (Permissions.biggerBombs(player)) { MiningManager miningManager = new MiningManager(Users.getPlayer(player)); miningManager.biggerBombs(event); } } } } /** * Handle EntityExplode events that involve modifying the event. * * @param event The event to modify */ @EventHandler (priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEnitityExplode(EntityExplodeEvent event) { Entity entity = event.getEntity(); if (entity instanceof TNTPrimed) { int id = entity.getEntityId(); if (plugin.tntIsTracked(id)) { Player player = plugin.getTNTPlayer(id); MiningManager miningManager = new MiningManager(Users.getPlayer(player)); miningManager.blastMiningDropProcessing(event); plugin.removeFromTNTTracker(id); } } } /** * Handle FoodLevelChange events that involve modifying the event. * * @param event The event to modify */ @EventHandler (priority = EventPriority.LOW, ignoreCancelled = true) public void onFoodLevelChange(FoodLevelChangeEvent event) { Entity entity = event.getEntity(); if (entity instanceof Player) { Player player = (Player) entity; if (Misc.isNPCPlayer(player)) { return; } int currentFoodLevel = player.getFoodLevel(); int newFoodLevel = event.getFoodLevel(); int foodChange = newFoodLevel - currentFoodLevel; /* * Some foods have 3 ranks * Some foods have 5 ranks * The number of ranks is based on how 'common' the item is * We can adjust this quite easily if we find something is giving too much of a bonus */ if (foodChange > 0) { switch (player.getItemInHand().getType()) { case BAKED_POTATO: /* RESTORES 3 HUNGER - RESTORES 5 1/2 HUNGER @ 1000 */ case BREAD: /* RESTORES 2 1/2 HUNGER - RESTORES 5 HUNGER @ 1000 */ case CARROT_ITEM: /* RESTORES 2 HUNGER - RESTORES 4 1/2 HUNGER @ 1000 */ case GOLDEN_CARROT: /* RESTORES 3 HUNGER - RESTORES 5 1/2 HUNGER @ 1000 */ case MUSHROOM_SOUP: /* RESTORES 4 HUNGER - RESTORES 6 1/2 HUNGER @ 1000 */ case PUMPKIN_PIE: /* RESTORES 4 HUNGER - RESTORES 6 1/2 HUNGER @ 1000 */ Herbalism.farmersDiet(player, Herbalism.farmersDietRankLevel1, event); break; case COOKIE: /* RESTORES 1/2 HUNGER - RESTORES 2 HUNGER @ 1000 */ case MELON: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */ case POISONOUS_POTATO: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */ case POTATO_ITEM: /* RESTORES 1/2 HUNGER - RESTORES 2 HUNGER @ 1000 */ Herbalism.farmersDiet(player, Herbalism.farmersDietRankLevel2, event); break; case COOKED_FISH: /* RESTORES 2 1/2 HUNGER - RESTORES 5 HUNGER @ 1000 */ Fishing.beginFishermansDiet(player, Fishing.fishermansDietRankLevel1, event); break; case RAW_FISH: /* RESTORES 1 HUNGER - RESTORES 2 1/2 HUNGER @ 1000 */ Fishing.beginFishermansDiet(player, Fishing.fishermansDietRankLevel2, event); break; default: return; } } } } /** * Monitor EntityTame events. * * @param event The event to watch */ @EventHandler (priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityTame(EntityTameEvent event) { Player player = (Player) event.getOwner(); if (Misc.isNPCPlayer(player)) { return; } TamingManager tamingManager = new TamingManager(Users.getPlayer(player)); tamingManager.awardTamingXP(event); } @EventHandler (ignoreCancelled = true) public void onEntityTarget(EntityTargetEvent event) { if (event.getEntity() instanceof Tameable && event.getTarget() instanceof Player) { Player player = (Player) event.getTarget(); Tameable tameable = (Tameable) event.getEntity(); if (Misc.isFriendlyPet(player, tameable)) { // isFriendlyPet ensures that the Tameable is: Tamed, owned by a player, and the owner is in the same party // So we can make some assumptions here, about our casting and our check Player owner = (Player) tameable.getOwner(); if (!(Permissions.friendlyFire(player) && Permissions.friendlyFire(owner))) { event.setCancelled(true); return; } } } } }
package com.hp.hpl.jena.shared.impl; public class JenaParameters { // Parameters affected handling of typed literals public static boolean enableEagerLiteralValidation = false; /** * Set this flag to true to allow language-free, plain literals and xsd:strings * containing the same character sequence to test as sameAs. * <p> * RDF plain literals and typed literals of type xsd:string are distinct, not * least because plain literals may have a language tag which typed literals * may not. However, in the absence of a languge tag it can be convenient * for applications if the java objects representing identical character * strings in these two ways test as semantically "sameAs" each other. * At the time of writing is unclear if such identification would be sanctioned * by the RDF working group. </p> */ public static boolean enablePlainLiteralSameAsString = true; /** * Set this flag to true to allow unknown literal datatypes to be * accepted, if false then such literals will throw an exception when * first detected. Note that any datatypes unknown datatypes encountered * whilst this flag is 'true' will be automatically registered (as a type * whose value and lexical spaces are identical). Subsequently turning off * this flag will not unregister those unknown types already encountered. * <p> * RDF allows any URI to be used to indicate a datatype. Jena2 allows * user defined datatypes to be registered but it is sometimes convenient * to be able to process models containing unknown datatypes (e.g. when the * application does not need to touch the value form of the literal). However, * this behaviour means that common errors, such as using the wrong URI for * xsd datatypes, may go unnoticed and throw obscure errors late in processing. * Hence, the default is the require unknown datatypes to be registered. */ public static boolean enableSilentAcceptanceOfUnknownDatatypes = true; /** * Set this flag to true to switch on checking of surrounding whitespace * in non-string XSD numeric types. In the false (default) setting then * leading and trailing white space is silently trimmed when parsing an * XSD numberic typed literal. */ public static boolean enableWhitespaceCheckingOfTypedLiterals = false; /** * Set this flag to true (default) to hide certain internal nodes from the output * of inference graphs. Some rule sets (notably owl-fb) create blank nodes as * part of their reasoning process. If these match some query they can appear * in the results. Such nodes are recorded as "hidden" and if this flag is set * all triples involving such hidden nodes will be removed from the output - any * indirect consequences will, however, still be visible. */ public static boolean enableFilteringOfHiddenInfNodes = true; /** * If this flag is true (default) then attmempts to build an OWL inference * graph over another OWL inference graph will log a warning message. */ public static boolean enableOWLRuleOverOWLRuleWarnings = true; /** * If this flag is true (default is false) then bNodes are assigned a * simple count local to this JVM. This is ONLY for use in debugging * systems exhibiting non-deterministic behaviour due to the * time-dependence of UIDs, not for normal production use. In particular, it * breaks the contract that anonIDs should be unique on the same machine: they * will only be unique for this single JVM run. */ public static boolean disableBNodeUIDGeneration = false; }
package com.hubspot.jinjava.el.ext; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import javax.el.ELContext; import javax.el.ELException; import javax.el.PropertyNotFoundException; import com.google.common.collect.Iterables; import com.hubspot.jinjava.objects.collections.PyList; import de.odysseus.el.misc.LocalMessages; import de.odysseus.el.tree.Bindings; import de.odysseus.el.tree.impl.ast.AstBracket; import de.odysseus.el.tree.impl.ast.AstNode; public class AstRangeBracket extends AstBracket { protected final AstNode rangeMax; public AstRangeBracket(AstNode base, AstNode rangeStart, AstNode rangeMax, boolean lvalue, boolean strict, boolean ignoreReturnType) { super(base, rangeStart, lvalue, strict, ignoreReturnType); this.rangeMax = rangeMax; } @Override public Object eval(Bindings bindings, ELContext context) { Object base = prefix.eval(bindings, context); if (base == null) { throw new PropertyNotFoundException(LocalMessages.get("error.property.base.null", prefix)); } boolean baseIsString = base.getClass().equals(String.class); if (!Iterable.class.isAssignableFrom(base.getClass()) && !base.getClass().isArray() && !baseIsString) { throw new ELException("Property " + prefix + " is not a sequence."); } if (baseIsString) { return evalString((String) base, bindings, context); } Iterable<?> baseItr = base.getClass().isArray() ? Arrays.asList((Object[]) base) : (Iterable<?>) base; Object start = property == null ? 0 : property.eval(bindings, context); if (start == null && strict) { return Collections.emptyList(); } if (!(start instanceof Number)) { throw new ELException("Range start is not a number"); } Object end = rangeMax == null ? (Iterables.size(baseItr)) : rangeMax.eval(bindings, context); if (end == null && strict) { return Collections.emptyList(); } if (!(end instanceof Number)) { throw new ELException("Range end is not a number"); } int startNum = ((Number) start).intValue(); int endNum = ((Number) end).intValue(); PyList result = new PyList(new ArrayList<>()); int index = 0; // Handle negative indices. if ((startNum < 0) || (endNum < 0)) { // size may have been calculated already int size = rangeMax == null ? endNum : Iterables.size(baseItr); if (startNum < 0) { startNum += size; } if (endNum < 0) { endNum += size; } } Iterator<?> baseIterator = baseItr.iterator(); while (baseIterator.hasNext()) { Object next = baseIterator.next(); if (index >= startNum) { if (index >= endNum) { break; } result.add(next); } index++; } return result; } private String evalString(String base, Bindings bindings, ELContext context) { int startNum = intVal(property, 0, base.length(), bindings, context); int endNum = intVal(rangeMax, base.length(), base.length(), bindings, context); endNum = Math.min(endNum, base.length()); if (startNum > endNum) { return ""; } return base.substring(startNum, endNum); } private int intVal(AstNode node, int defVal, int baseLength, Bindings bindings, ELContext context) { if (node == null) { return defVal; } Object val = node.eval(bindings, context); if (val == null) { return defVal; } if (!(val instanceof Number)) { throw new ELException("Range start/end is not a number"); } int result = ((Number) val).intValue(); return result >= 0 ? result : baseLength + result; } @Override public String toString() { return "[:]"; } }
package com.infinityraider.agricraft.config; import com.agricraft.agricore.config.AgriConfigAdapter; import com.infinityraider.agricraft.api.v1.config.IAgriConfig; import com.infinityraider.agricraft.impl.v1.genetics.GeneStat; import com.infinityraider.agricraft.impl.v1.requirement.SeasonPlugin; import com.infinityraider.agricraft.reference.Names; import com.infinityraider.infinitylib.config.ConfigurationHandler; import net.minecraft.util.text.TextFormatting; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.common.ForgeConfigSpec; import net.minecraftforge.fml.config.ModConfig; public abstract class Config implements IAgriConfig, ConfigurationHandler.SidedModConfig, AgriConfigAdapter { private Config() {} public static abstract class Common extends Config { // debug private final ForgeConfigSpec.ConfigValue<Boolean> debug; private final ForgeConfigSpec.ConfigValue<Boolean> enableLogging; // core private final ForgeConfigSpec.ConfigValue<Boolean> generateMissingDefaults; private final ForgeConfigSpec.ConfigValue<Boolean> enableJsonWriteBack; private final ForgeConfigSpec.ConfigValue<Boolean> plantOffCropSticks; private final ForgeConfigSpec.ConfigValue<Boolean> onlyFertileCropsSpread; private final ForgeConfigSpec.ConfigValue<Boolean> fertilizerMutations; private final ForgeConfigSpec.ConfigValue<Boolean> disableVanillaFarming; private final ForgeConfigSpec.ConfigValue<Double> growthMultiplier; private final ForgeConfigSpec.ConfigValue<Boolean> onlyMatureSeedDrops; private final ForgeConfigSpec.ConfigValue<Boolean> overwriteGrassDrops; private final ForgeConfigSpec.ConfigValue<Boolean> disableWeeds; private final ForgeConfigSpec.ConfigValue<Boolean> matureWeedsKillPlants; private final ForgeConfigSpec.ConfigValue<Boolean> weedSpreading; private final ForgeConfigSpec.ConfigValue<Boolean> weedsDestroyCropSticks; private final ForgeConfigSpec.ConfigValue<Boolean> rakingDropsItems; private final ForgeConfigSpec.ConfigValue<Double> seedCompostValue; private final ForgeConfigSpec.ConfigValue<Boolean> animalAttraction; private final ForgeConfigSpec.ConfigValue<Integer> seedBagEnchantCost; // stats private final ForgeConfigSpec.ConfigValue<String> statTraitLogic; private final ForgeConfigSpec.ConfigValue<Integer> minGain; private final ForgeConfigSpec.ConfigValue<Integer> maxGain; private final ForgeConfigSpec.ConfigValue<Boolean> hiddenGain; private final ForgeConfigSpec.ConfigValue<Integer> minGrowth; private final ForgeConfigSpec.ConfigValue<Integer> maxGrowth; private final ForgeConfigSpec.ConfigValue<Boolean> hiddenGrowth; private final ForgeConfigSpec.ConfigValue<Integer> minStrength; private final ForgeConfigSpec.ConfigValue<Integer> maxStrength; private final ForgeConfigSpec.ConfigValue<Boolean> hiddenStrength; private final ForgeConfigSpec.ConfigValue<Integer> minResistance; private final ForgeConfigSpec.ConfigValue<Integer> maxResistance; private final ForgeConfigSpec.ConfigValue<Boolean> hiddenResistance; private final ForgeConfigSpec.ConfigValue<Integer> minFertility; private final ForgeConfigSpec.ConfigValue<Integer> maxFertility; private final ForgeConfigSpec.ConfigValue<Boolean> hiddenFertility; private final ForgeConfigSpec.ConfigValue<Integer> minMutativity; private final ForgeConfigSpec.ConfigValue<Integer> maxMutativity; private final ForgeConfigSpec.ConfigValue<Boolean> hiddenMutativity; // irrigation private final ForgeConfigSpec.ConfigValue<Integer> tankCapacity; private final ForgeConfigSpec.ConfigValue<Integer> channelCapacity; private final ForgeConfigSpec.ConfigValue<Integer> rainFillRate; private final ForgeConfigSpec.ConfigValue<Integer> sprinkleInterval; private final ForgeConfigSpec.ConfigValue<Double> sprinkleGrowthChance; private final ForgeConfigSpec.ConfigValue<Integer> sprinklerWaterConsumption; // decoration private final ForgeConfigSpec.ConfigValue<Boolean> climbableGrate; // compat private final ForgeConfigSpec.ConfigValue<Boolean> progressiveJEI; private final ForgeConfigSpec.ConfigValue<String> seasonLogic; private final ForgeConfigSpec.ConfigValue<Boolean> topControlledByMagnifyingGlass; public Common(ForgeConfigSpec.Builder builder) { super(); builder.push("debug"); this.debug = builder.comment("\nSet to true to enable debug mode") .define("debug", false); this.enableLogging = builder.comment("\nSet to true to enable logging on the ${log} channel.") .define("Enable Logging", true); builder.pop(); builder.push("core"); this.generateMissingDefaults = builder.comment("\nSet to false to disable the generation of missing default jsons") .define("Generate missing default JSONs", true); this.enableJsonWriteBack = builder.comment("\nSet to false to disable automatic JSON writeback.") .define("Enable JSON write back", true); this.plantOffCropSticks = builder.comment("\nSet to false to disable planting of (agricraft) seeds outside crop sticks") .define("Plant outside crop sticks", true); this.onlyFertileCropsSpread = builder.comment("\nSet to true to allow only fertile plants to be able to cause, participate in, or contribute to a spreading / mutation action\n" + "(note that this may cause issues with obtaining some specific plants)") .define("Only fertile crops mutate", false); this.fertilizerMutations = builder.comment("\nSet to false if to disable triggering of mutations by using fertilizers on a cross crop.") .define("Fertilizer mutations", true); this.disableVanillaFarming = builder.comment("\nSet to true to disable vanilla farming, meaning you can only grow plants on crops.") .define("Disable vanilla farming", true); this.growthMultiplier = builder.comment("\nThis is a global growth rate multiplier for crops planted on crop sticks.") .defineInRange("Growth rate multiplier", 1.0, 0.0, 3.0); this.onlyMatureSeedDrops = builder.comment("\nSet this to true to make only mature crops drop seeds (to encourage trowel usage).") .define("Only mature crops drop seeds", false); this.overwriteGrassDrops = builder.comment("\nDetermines if AgriCraft should completely override grass drops with those configured in the JSON files.") .define("Overwrite Grass Drops", true); this.disableWeeds = builder.comment("\nSet to true to completely disable the spawning of weeds") .define("Disable weeds", false); this.matureWeedsKillPlants = builder.comment("\nSet to false to disable mature weeds killing plants") .define("Mature weeds kill plants", true); this.weedSpreading = builder.comment("\nSet to false to disable the spreading of weeds") .define("Weeds can spread", true); this.weedsDestroyCropSticks = builder.comment("\nSet this to true to have weeds destroy the crop sticks when they are broken with weeds (to encourage rake usage).") .define("Weeds destroy crop sticks", false); this.rakingDropsItems = builder.comment("\nSet to false if you wish to disable drops from raking weeds.") .define("Raking weeds drops items", true); this.seedCompostValue = builder.comment("\nDefines the seed compost value, if set to zero, seeds will not be compostable") .defineInRange("Seed compost value", 0.3, 0, 1.0); this.animalAttraction = builder.comment("\nSet to false to disable certain animals eating certain crops (prevents auto-breeding)") .define("animal attracting crops", true); this.seedBagEnchantCost = builder.comment("\nEnchantment cost in player levels to enchant the seed bag") .defineInRange("seed bag enchant cost", 10, 0, 30); builder.pop(); builder.push("stats"); this.statTraitLogic = builder.comment("\nLogic to calculate stats from gene pairs, accepted values are: \"min\", \"min\", and \"mean\"") .defineInList("Stat calculation logic", "max", GeneStat.getLogicOptions()); this.minGain = builder.comment("\nMinimum allowed value of the Gain stat (setting min and max equal will freeze the stat to that value in crop breeding)") .defineInRange("Gain stat min", 1, 1, 10); this.maxGain = builder.comment("\nMaximum allowed value of the Gain stat (setting min and max equal will freeze the stat to that value in crop breeding)") .defineInRange("Gain stat max", 10, 1, 10); this.hiddenGain = builder.comment("\nSet to true to hide the Gain stat (hidden stats will not show up in tooltips or seed analysis)\n" + "setting min and max equal and hiding a stat effectively disables it, with its behaviour at the defined value for min and max.") .define("hide Gain stat", false); this.minGrowth = builder.comment("\nMinimum allowed value of the Growth stat (setting min and max equal will freeze the stat to that value in crop breeding)") .defineInRange("Growth stat min", 1, 1, 10); this.maxGrowth = builder.comment("\nMaximum allowed value of the Growth stat (setting min and max equal will freeze the stat to that value in crop breeding)") .defineInRange("Growth stat max", 10, 1, 10); this.hiddenGrowth = builder.comment("\nSet to true to hide the Growth stat (hidden stats will not show up in tooltips or seed analysis)\n" + "setting min and max equal and hiding a stat effectively disables it, with its behaviour at the defined value for min and max.") .define("hide Growth stat", false); this.minStrength = builder.comment("\nMinimum allowed value of the Strength stat (setting min and max equal will freeze the stat to that value in crop breeding)") .defineInRange("Strength stat min", 1, 1, 10); this.maxStrength = builder.comment("\nMaximum allowed value of the Strength stat (setting min and max equal will freeze the stat to that value in crop breeding)") .defineInRange("Strength stat max", 10, 1, 10); this.hiddenStrength = builder.comment("\nSet to true to hide the Strength stat (hidden stats will not show up in tooltips or seed analysis)\n" + "setting min and max equal and hiding a stat effectively disables it, with its behaviour at the defined value for min and max.") .define("hide Strength stat", false); this.minResistance = builder.comment("\nMinimum allowed value of the Resistance stat (setting min and max equal will freeze the stat to that value in crop breeding)") .defineInRange("Resistance stat min", 1, 1, 10); this.maxResistance = builder.comment("\nMaximum allowed value of the Resistance stat (setting min and max equal will freeze the stat to that value in crop breeding)") .defineInRange("Resistance stat max", 10, 1, 10); this.hiddenResistance = builder.comment("\nSet to true to hide the Resistance stat (hidden stats will not show up in tooltips or seed analysis)\n" + "setting min and max equal and hiding a stat effectively disables it, with its behaviour at the defined value for min and max.") .define("hide Resistance stat", false); this.minFertility = builder.comment("\nMinimum allowed value of the Fertility stat (setting min and max equal will freeze the stat to that value in crop breeding)") .defineInRange("Fertility stat min", 1, 1, 10); this.maxFertility = builder.comment("\nMaximum allowed value of the Fertility stat (setting min and max equal will freeze the stat to that value in crop breeding)") .defineInRange("Fertility stat max", 10, 1, 10); this.hiddenFertility = builder.comment("\nSet to true to hide the Fertility stat (hidden stats will not show up in tooltips or seed analysis)\n" + "setting min and max equal and hiding a stat effectively disables it, with its behaviour at the defined value for min and max.") .define("hide Fertility stat", false); this.minMutativity = builder.comment("\nMinimum allowed value of the Mutativity stat (setting min and max equal will freeze the stat to that value in crop breeding)") .defineInRange("Mutativity stat min", 1, 1, 10); this.maxMutativity = builder.comment("\nMaximum allowed value of the Mutativity stat (setting min and max equal will freeze the stat to that value in crop breeding)") .defineInRange("Mutativity stat max", 10, 1, 10); this.hiddenMutativity = builder.comment("\nSet to true to hide the Mutativity stat (hidden stats will not show up in tooltips or seed analysis)\n" + "setting min and max equal and hiding a stat effectively disables it, with its behaviour at the defined value for min and max.") .define("hide Mutativity stat", false); builder.pop(); builder.push("irrigation"); this.tankCapacity = builder.comment("\nConfigures the capacity (in mB) of one tank block") .defineInRange("Tank capacity", 8000, 1000, 40000); this.channelCapacity = builder.comment("\nConfigures the capacity (in mB) of one channel block") .defineInRange("Tank capacity", 50, 500, 2000); this.rainFillRate = builder.comment("\nConfigures the rate (in mB/t) at which tanks accrue water while raining (0 disables filling from rainfall)") .defineInRange("Rain fill rate", 5, 0, 50); this.sprinkleInterval = builder.comment("\nThe minimum number of ticks between successive starts of irrigation.") .defineInRange("Sprinkler growth interval", 40, 1, 1200); this.sprinkleGrowthChance = builder.comment("\nEvery loop, each unobscured plant in sprinkler range has this chance to get a growth tick from the sprinkler.") .defineInRange("Sprinkler growth chance", 0.2, 0, 1.0); this.sprinklerWaterConsumption = builder.comment("\nDefined in terms of mB per second. The irrigation loop progress will pause when there is insufficient water.") .defineInRange("Sprinkler water usage", 10, 0, 1000); builder.pop(); builder.push("decoration"); this.climbableGrate = builder.comment("\nWhen true, entities will be able to climb on grates") .define("Grates always climbable", true); builder.pop(); builder.push("compat"); this.progressiveJEI = builder.comment("\nSet to false if you want all mutations to be shown in JEI all the time instead of having to research them") .define("Progressive JEI", true); this.seasonLogic = builder.comment("\nDefines the mod controlling season logic in case multiple are installed\naccepted values are: " + SeasonPlugin.getConfigComment()) .defineInList("season logic", Names.Mods.SERENE_SEASONS, SeasonPlugin.SEASON_MODS); this.topControlledByMagnifyingGlass = builder.comment("\nDefines wether or not additional The One Probe data is rendered only when the magnifying glass is being used") .define("TOP only with magnifying glass", true); builder.pop(); } @Override public boolean debugMode() { return this.debug.get(); } @Override public boolean allowPlantingOutsideCropSticks() { return this.plantOffCropSticks.get(); } @Override public boolean onlyFertileCropsCanSpread() { return this.onlyFertileCropsSpread.get(); } @Override public boolean allowFertilizerMutations() { return this.fertilizerMutations.get(); } @Override public boolean disableVanillaFarming() { return this.disableVanillaFarming.get(); } @Override public double growthMultiplier() { return this.growthMultiplier.get(); } @Override public boolean onlyMatureSeedDrops() { return this.onlyMatureSeedDrops.get(); } @Override public boolean overwriteGrassDrops() { return this.overwriteGrassDrops.get(); } @Override public boolean disableWeeds() { return this.disableWeeds.get(); } @Override public boolean allowLethalWeeds() { return this.matureWeedsKillPlants.get(); } @Override public boolean allowAggressiveWeeds() { return this.weedSpreading.get(); } @Override public boolean weedsDestroyCropSticks() { return this.weedsDestroyCropSticks.get(); } @Override public boolean rakingDropsItems() { return this.rakingDropsItems.get(); } @Override public float seedCompostValue() { return this.seedCompostValue.get().floatValue(); } @Override public boolean enableAnimalAttractingCrops() { return this.animalAttraction.get(); } @Override public int seedBagEnchantCost() { return this.seedBagEnchantCost.get(); } @Override public String getStatTraitLogic() { return this.statTraitLogic.get(); } @Override public int getGainStatMinValue() { return this.minGain.get(); } @Override public int getGainStatMaxValue() { return this.maxGain.get(); } @Override public boolean isGainStatHidden() { return this.hiddenGain.get(); } @Override public int getGrowthStatMinValue() { return this.minGrowth.get(); } @Override public int getGrowthStatMaxValue() { return this.maxGrowth.get(); } @Override public boolean isGrowthStatHidden() { return this.hiddenGrowth.get(); } @Override public int getStrengthStatMinValue() { return this.minStrength.get(); } @Override public int getStrengthStatMaxValue() { return this.maxStrength.get(); } @Override public boolean isStrengthStatHidden() { return this.hiddenStrength.get(); } @Override public int getResistanceStatMinValue() { return this.minResistance.get(); } @Override public int getResistanceStatMaxValue() { return this.maxResistance.get(); } @Override public boolean isResistanceStatHidden() { return this.hiddenResistance.get(); } @Override public int getFertilityStatMinValue() { return this.minFertility.get(); } @Override public int getFertilityStatMaxValue() { return this.maxFertility.get(); } @Override public boolean isFertilityStatHidden() { return this.hiddenFertility.get(); } @Override public int getMutativityStatMinValue() { return this.minMutativity.get(); } @Override public int getMutativityStatMaxValue() { return this.maxMutativity.get(); } @Override public boolean isMutativityStatHidden() { return this.hiddenMutativity.get(); } @Override public int tankCapacity() { return this.tankCapacity.get(); } @Override public int channelCapacity() { return this.channelCapacity.get(); } @Override public int rainFillRate() { return this.rainFillRate.get(); } @Override public int sprinkleInterval() { return this.sprinkleInterval.get(); } @Override public double sprinkleGrowthChance() { return this.sprinkleGrowthChance.get(); } @Override public int sprinklerWaterConsumption() { return this.sprinklerWaterConsumption.get(); } @Override public boolean areGratesClimbable() { return this.climbableGrate.get(); } @Override public ModConfig.Type getSide() { return ModConfig.Type.COMMON; } @Override public boolean generateMissingDefaultJsons() { return this.generateMissingDefaults.get(); } @Override public boolean enableJsonWriteback() { return this.enableJsonWriteBack.get(); } @Override public boolean enableLogging() { return this.enableLogging.get(); } @Override public boolean progressiveJEI() { return this.progressiveJEI.get(); } @Override public String getSeasonLogicMod() { return this.seasonLogic.get(); } @Override public boolean doesMagnifyingGlassControlTOP() { return this.topControlledByMagnifyingGlass.get(); } } @OnlyIn(Dist.CLIENT) public static final class Client extends Common { //debug private final ForgeConfigSpec.ConfigValue<Boolean> registryTooltips; private final ForgeConfigSpec.ConfigValue<Boolean> tagTooltips; private final ForgeConfigSpec.ConfigValue<Boolean> nbtTooltips; //core private final ForgeConfigSpec.ConfigValue<Boolean> vanillaFarmingWarning; private final ForgeConfigSpec.ConfigValue<String> statFormat; private final ForgeConfigSpec.ConfigValue<Boolean> disableParticles; public Client(ForgeConfigSpec.Builder builder) { super(builder); builder.push("debug"); this.registryTooltips = builder.comment("\nSet to true to add Registry information to itemstack tooltips (Client only)") .define("Registry tooltips", false); this.tagTooltips = builder.comment("\nSet to true to add Tag information to itemstack tooltips (Client only)") .define("Tag tooltips", false); this.nbtTooltips = builder.comment("\nSet to true to add NBT information to itemstack tooltips (Client only)") .define("NBT tooltips", false); builder.pop(); builder.push("core"); this.vanillaFarmingWarning = builder.comment("\nSet to false to warn that vanilla farming is disabled when trying to plant vanilla plant (Client only)") .define("Show Disabled Vanilla Farming Warning", true); this.statFormat = builder.comment("\nThis defines how to display the stats of plants (Client only)") .define("Stat Format", TextFormatting.GREEN + "- {0}: [{1}/{2}]"); builder.pop(); builder.push("irrigation"); this.disableParticles = builder.comment("\nSet to true to disable particles (Client only)") .define("Disable particles", false); builder.pop(); } @Override public boolean registryTooltips() { return this.registryTooltips.get(); } @Override public boolean tagTooltips() { return this.tagTooltips.get(); } @Override public boolean nbtTooltips() { return this.nbtTooltips.get(); } @Override public boolean vanillaFarmingWarning() { return this.vanillaFarmingWarning.get(); } @Override public String statDisplayFormat() { return this.statFormat.get(); } @Override public boolean disableParticles() { return this.disableParticles.get(); } @Override public ModConfig.Type getSide() { return ModConfig.Type.CLIENT; } } public static final class Server extends Common { public Server(ForgeConfigSpec.Builder builder) { super(builder); } @Override @OnlyIn(Dist.CLIENT) public boolean registryTooltips() { return false; } @Override @OnlyIn(Dist.CLIENT) public boolean tagTooltips() { return false; } @Override @OnlyIn(Dist.CLIENT) public boolean nbtTooltips() { return false; } @Override @OnlyIn(Dist.CLIENT) public boolean vanillaFarmingWarning() { return false; } @Override @OnlyIn(Dist.CLIENT) public String statDisplayFormat() { return null; } @Override @OnlyIn(Dist.CLIENT) public boolean disableParticles() { return false; } @Override public ModConfig.Type getSide() { return ModConfig.Type.COMMON; } } }
package com.jomofisher.cmakeify; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Collection; public class LinuxScriptBuilder extends ScriptBuilder { final private static String TOOLS_FOLDER = ".cmakeify/tools"; final private static String DOWNLOADS_FOLDER = ".cmakeify/downloads"; final private StringBuilder script = new StringBuilder(); private LinuxScriptBuilder append(String format, Object... args) { script.append(String.format(format + "\n", args)); return this; } @Override ScriptBuilder createToolsFolder() { return append("mkdir --parents %s/", TOOLS_FOLDER); } @Override ScriptBuilder createDownloadsFolder() { return append("mkdir --parents %s/", DOWNLOADS_FOLDER); } @Override ScriptBuilder downloadCMake(CMakeVersion version) { ArchiveInfo archive = new ArchiveInfo(version.linux); return append(archive.downloadToFolder(DOWNLOADS_FOLDER)) .append(archive.uncompressToFolder(DOWNLOADS_FOLDER, TOOLS_FOLDER)); //.append("CMAKEIFY_CMAKE_FOLDER=%s/%s", TOOLS_FOLDER, archive.baseName); //.append("$CMAKEIFY_CMAKE_FOLDER/bin/cmake --version"); } @Override File writeToShellScript() { BufferedWriter writer = null; File file = new File(".cmakeify/build.sh"); file.getAbsoluteFile().mkdirs(); file.delete(); try { writer = new BufferedWriter(new FileWriter(file)); writer.write(script.toString()); } catch (Exception e) { e.printStackTrace(); } finally { try { // Close the writer regardless of what happens... writer.close(); } catch (Exception e) { } } return file; } @Override ScriptBuilder checkForCompilers(Collection<String> compilers) { for (String compiler : compilers) { append("if [[ -z \"$(which %s)\" ]]; then", compiler); append(" echo Missing %s. Please install.", compiler); append(" exit 100"); append("fi"); } return this; } @Override ScriptBuilder cmake(File workingDirectory, CMakeVersion version) { ArchiveInfo archive = new ArchiveInfo(version.linux); String cmakeExe = String.format("%s/%s/bin/cmake", TOOLS_FOLDER, archive.baseName); String outputFolder = String.format("%s/%s", workingDirectory, version.tag); File buildFolder = new File(outputFolder, "build-files"); append("mkdir --parents %s", buildFolder); append(String.format( "%s \\\n" + " -H%s \\\n" + " -B%s \\\n" + " -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=%s/bin \\\n" + " -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=%s/bin \\\n" + " -DCMAKE_RUNTIME_OUTPUT_DIRECTORY=%s/bin \\\n" + " -DCMAKE_SYSTEM_NAME=linux \\\n" + " -DCMAKE_C_COMPILER=gcc \\\n" + " -DCMAKE_CXX_COMPILER=g++", cmakeExe, workingDirectory, buildFolder, outputFolder, outputFolder, outputFolder, outputFolder)); return this; } @Override public String toString() { return script.toString(); } }
package com.kodcu.controller; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.install4j.api.launcher.ApplicationLauncher; import com.kodcu.bean.RecentFiles; import com.kodcu.component.*; import com.kodcu.config.*; import com.kodcu.logging.MyLog; import com.kodcu.logging.TableViewLogAppender; import com.kodcu.other.*; import com.kodcu.outline.Section; import com.kodcu.service.*; import com.kodcu.service.config.YamlService; import com.kodcu.service.convert.GitbookToAsciibookService; import com.kodcu.service.convert.docbook.DocBookConverter; import com.kodcu.service.convert.ebook.EpubConverter; import com.kodcu.service.convert.ebook.MobiConverter; import com.kodcu.service.convert.html.HtmlBookConverter; import com.kodcu.service.convert.markdown.MarkdownService; import com.kodcu.service.convert.odf.ODFConverter; import com.kodcu.service.convert.pdf.AbstractPdfConverter; import com.kodcu.service.convert.slide.SlideConverter; import com.kodcu.service.extension.MathJaxService; import com.kodcu.service.extension.PlantUmlService; import com.kodcu.service.extension.TreeService; import com.kodcu.service.extension.chart.ChartProvider; import com.kodcu.service.shortcut.ShortcutProvider; import com.kodcu.service.table.AsciidocTableController; import com.kodcu.service.ui.*; import com.sun.javafx.application.HostServicesDelegate; import com.sun.webkit.dom.DocumentFragmentImpl; import de.jensd.fx.fontawesome.AwesomeDude; import de.jensd.fx.fontawesome.AwesomeIcon; import javafx.animation.KeyFrame; import javafx.animation.KeyValue; import javafx.animation.Timeline; import javafx.application.Platform; import javafx.beans.property.*; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.event.EventHandler; import javafx.event.EventType; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Insets; import javafx.geometry.Side; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.control.cell.TextFieldTreeCell; import javafx.scene.input.*; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.text.Text; import javafx.scene.web.WebEngine; import javafx.scene.web.WebHistory; import javafx.scene.web.WebView; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.util.Duration; import netscape.javascript.JSObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.embedded.EmbeddedWebApplicationContext; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import org.yaml.snakeyaml.Yaml; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.CodeSource; import java.time.Instant; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiPredicate; import java.util.function.Consumer; import java.util.regex.Pattern; import java.util.stream.Collectors; import static java.nio.file.StandardOpenOption.*; @Component public class ApplicationController extends TextWebSocketHandler implements Initializable { public TabPane previewTabPane; @Autowired public HtmlPane htmlPane; public Label odfPro; public VBox logVBox; public Label statusText; public SplitPane editorSplitPane; public Label statusMessage; public Label showHideLogs; public Tab outlineTab; public MenuItem newFolder; public MenuItem newSlide; public Menu newMenu; public ProgressBar progressBar; public Menu favoriteDirMenu; public MenuItem addToFavoriteDir; public MenuItem afxVersionItem; private Logger logger = LoggerFactory.getLogger(ApplicationController.class); private Path userHome = Paths.get(System.getProperty("user.home")); private TreeSet<Section> outlineList = new TreeSet<>(); private ObservableList<DocumentMode> modeList = FXCollections.observableArrayList(); private final Pattern bookArticleHeaderRegex = Pattern.compile("^:doctype:.*(book|article)", Pattern.MULTILINE); private final Pattern forceIncludeRegex = Pattern.compile("^:forceinclude:", Pattern.MULTILINE); public CheckMenuItem hidePreviewPanel; public MenuItem hideFileBrowser; public MenuButton panelShowHideMenuButton; public MenuItem renameFile; public MenuItem newFile; public TabPane tabPane; public SplitPane splitPane; public SplitPane splitPaneVertical; public TreeView<Item> treeView; public Label workingDirButton; public Label goHomeLabel; public Label refreshLabel; public AnchorPane rootAnchor; public ProgressIndicator indikator; public ListView<String> recentListView; public MenuItem openFileTreeItem; public MenuItem deletePathItem; public MenuItem openFolderTreeItem; public MenuItem openFileListItem; public MenuItem openFolderListItem; public MenuItem copyPathTreeItem; public MenuItem copyPathListItem; public MenuItem copyTreeItem; public MenuItem copyListItem; public MenuButton leftButton; private WebView mathjaxView; public Label htmlPro; public Label pdfPro; public Label ebookPro; public Label docbookPro; public Label browserPro; public SeparatorMenuItem renameSeparator; public SeparatorMenuItem addToFavSeparator; private AnchorPane markdownTableAnchor; private Stage markdownTableStage; private TreeView<Section> sectionTreeView; private BooleanProperty stopRendering = new SimpleBooleanProperty(false); private AtomicBoolean includeAsciidocResource = new AtomicBoolean(false); private static ObservableList<MyLog> logList = FXCollections.synchronizedObservableList(FXCollections.observableArrayList()); @Autowired private EditorConfigBean editorConfigBean; @Autowired private PreviewConfigBean previewConfigBean; @Autowired private HtmlConfigBean htmlConfigBean; @Autowired private OdfConfigBean odfConfigBean; @Autowired private DocbookConfigBean docbookConfigBean; @Autowired private ApplicationContext applicationContext; @Autowired private ConfigurationService configurationService; @Autowired private AsciidocTableController asciidocTableController; @Autowired private GitbookToAsciibookService gitbookToAsciibook; @Autowired private PathOrderService pathOrder; @Autowired private TreeService treeService; @Autowired private TooltipTimeFixService tooltipTimeFixService; @Autowired private TabService tabService; @Autowired private ODFConverter odfConverter; @Autowired private PathResolverService pathResolver; @Autowired private PlantUmlService plantUmlService; @Autowired private EditorService editorService; @Autowired private MathJaxService mathJaxService; @Autowired private YamlService yamlService; @Autowired private WebviewService webviewService; @Autowired private DocBookConverter docBookConverter; @Autowired private HtmlBookConverter htmlBookService; @Autowired @Qualifier("pdfBookConverter") private AbstractPdfConverter pdfBookConverter; @Autowired private EpubConverter epubConverter; @Autowired private Current current; @Autowired private FileBrowseService fileBrowser; @Autowired private IndikatorService indikatorService; @Autowired private MobiConverter mobiConverter; @Autowired private SampleBookService sampleBookService; @Autowired private EmbeddedWebApplicationContext server; @Autowired private ParserService parserService; @Autowired private AwesomeService awesomeService; @Autowired private DirectoryService directoryService; @Autowired private ThreadService threadService; @Autowired private DocumentService documentService; @Autowired private EpubController epubController; @Autowired private ShortcutProvider shortcutProvider; @Autowired private RestTemplate restTemplate; @Autowired private Base64.Encoder base64Encoder; @Autowired private ChartProvider chartProvider; @Autowired private MarkdownService markdownService; private Stage stage; private StringProperty lastRendered = new SimpleStringProperty(); private List<WebSocketSession> sessionList = new ArrayList<>(); private ObjectProperty<Scene> scene = new SimpleObjectProperty<>(); private AnchorPane asciidocTableAnchor; private Stage asciidocTableStage; private final Clipboard clipboard = Clipboard.getSystemClipboard(); private final ObservableList<String> recentFilesList = FXCollections.synchronizedObservableList(FXCollections.observableArrayList()); private int port = 8080; private HostServicesDelegate hostServices; private Path configPath; private BooleanProperty fileBrowserVisibility = new SimpleBooleanProperty(false); private BooleanProperty previewPanelVisibility = new SimpleBooleanProperty(false); private final List<String> bookNames = Arrays.asList("book.asc", "book.txt", "book.asciidoc", "book.adoc", "book.ad"); private Map<String, String> shortCuts; private RecentFiles recentFiles; private final ChangeListener<String> lastRenderedChangeListener = (observableValue, old, nev) -> { if (Objects.isNull(nev)) return; threadService.runActionLater(() -> { htmlPane.refreshUI(nev); }); sessionList.stream().filter(e -> e.isOpen()).forEach(e -> { try { e.sendMessage(new TextMessage(nev)); } catch (Exception ex) { logger.error("Problem occured while sending content over WebSocket", ex); } }); }; @Value("${application.version}") private String version; @Autowired private SlideConverter slideConverter; @Autowired private SlidePane slidePane; private Path installationPath; private Path logPath; @Autowired private LiveReloadPane liveReloadPane; private List<String> supportedModes; @Autowired private FileWatchService fileWatchService; private PreviewTab previewTab; private Timeline progressBarTimeline = null; private ObservableList<String> favoriteDirectories = FXCollections.observableArrayList(); @Autowired private FileWatchService watchService; public void createAsciidocTable() { asciidocTableStage.showAndWait(); } public void createMarkdownTable() { markdownTableStage.showAndWait(); } @FXML private void fullScreen(ActionEvent event) { getStage().setFullScreen(!getStage().isFullScreen()); } @FXML private void directoryView(ActionEvent event) { splitPane.setDividerPositions(0.1610294117647059, 0.5823529411764706); } private void generatePdf() { this.generatePdf(false); } private void generatePdf(boolean askPath) { if (!current.currentPath().isPresent()) saveDoc(); threadService.runTaskLater(() -> { pdfBookConverter.convert(askPath); }); } @FXML private void generateSampleBook(ActionEvent event) { DirectoryChooser directoryChooser = directoryService.newDirectoryChooser("Select a New Directory for sample book"); File file = directoryChooser.showDialog(null); threadService.runTaskLater(() -> { sampleBookService.produceSampleBook(configPath, file.toPath()); directoryService.setWorkingDirectory(Optional.of(file.toPath())); fileBrowser.browse(file.toPath()); fileWatchService.registerWatcher(file.toPath()); threadService.runActionLater(() -> { directoryView(null); tabService.addTab(file.toPath().resolve("book.adoc")); }); }); } public void convertDocbook() { convertDocbook(false); } public void convertDocbook(boolean askPath) { threadService.runTaskLater(() -> { if (!current.currentPath().isPresent()) saveDoc(); threadService.runActionLater(() -> { Path currentTabPath = current.currentPath().get(); Path currentTabPathDir = currentTabPath.getParent(); String tabText = current.getCurrentTabText().replace("*", "").trim(); Path docbookPath; if (askPath) { FileChooser fileChooser = directoryService.newFileChooser("Save Docbook file"); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Docbook", "*.xml")); docbookPath = fileChooser.showSaveDialog(null).toPath(); } else docbookPath = currentTabPathDir.resolve(tabText + ".xml"); Consumer<String> step = docbook -> { final String finalDocbook = docbook; threadService.runTaskLater(() -> { IOHelper.writeToFile(docbookPath, finalDocbook, CREATE, TRUNCATE_EXISTING, WRITE); }); threadService.runActionLater(() -> { getRecentFilesList().remove(docbookPath.toString()); getRecentFilesList().add(0, docbookPath.toString()); }); }; docBookConverter.convert(false, step); }); }); } private void convertEpub() { convertEpub(false); } private void convertEpub(boolean askPath) { epubConverter.produceEpub3(askPath); } public void appendFormula(String fileName, String formula) { mathJaxService.appendFormula(fileName, formula); } public void svgToPng(String fileName, String svg, String formula, float width, float height) { threadService.runTaskLater(() -> { mathJaxService.svgToPng(fileName, svg, formula, width, height); }); } private void convertMobi() { convertMobi(false); } private void convertMobi(boolean askPath) { if (Objects.nonNull(editorConfigBean.getKindlegen())) { if (!Files.exists(editorConfigBean.getKindlegen())) { editorConfigBean.setKindlegen(null); } } if (Objects.isNull(editorConfigBean.getKindlegen())) { FileChooser fileChooser = directoryService.newFileChooser("Select 'kindlegen' executable"); File kindlegenFile = fileChooser.showOpenDialog(null); if (Objects.isNull(kindlegenFile)) return; editorConfigBean.setKindlegen(kindlegenFile.toPath().getParent()); } threadService.runTaskLater(() -> { mobiConverter.convert(askPath); }); } private void generateHtml() { this.generateHtml(false); } private void generateHtml(boolean askPath) { if (!current.currentPath().isPresent()) this.saveDoc(); threadService.runTaskLater(() -> { htmlBookService.convert(askPath); }); } public void createFileTree(String tree, String type, String fileName, String width, String height) { threadService.runTaskLater(() -> { treeService.createFileTree(tree, type, fileName, width, height); }); } public void createHighlightFileTree(String tree, String type, String fileName, String width, String height) { threadService.runTaskLater(() -> { treeService.createHighlightFileTree(tree, type, fileName, width, height); }); } @FXML public void refreshWorkingDir() { current.currentPath().map(Path::getParent).ifPresent(directoryService::changeWorkigDir); } @FXML public void goHome() { directoryService.changeWorkigDir(userHome); } @WebkitCall public void imageToBase64Url(final String url, final int index) { threadService.runTaskLater(() -> { try { byte[] imageBuffer = restTemplate.getForObject(url, byte[].class); String imageBase64 = base64Encoder.encodeToString(imageBuffer); threadService.runActionLater(() -> { htmlPane.updateBase64Url(index, imageBase64); }); } catch (Exception e) { logger.error("Problem occured while converting image to base64 for {}", url); } }); } @Override public void initialize(URL url, ResourceBundle rb) { threadService.runActionLater(() -> { configurationService.loadConfigurations(); this.bindConfigurations(); }, true); port = server.getEmbeddedServletContainer().getPort(); progressBar.prefWidthProperty().bind(previewTabPane.widthProperty()); progressBarTimeline = new Timeline( new KeyFrame( Duration.ZERO, new KeyValue(progressBar.progressProperty(), 0) ), new KeyFrame( Duration.seconds(15), new KeyValue(progressBar.progressProperty(), 1) )); this.previewTab = new PreviewTab("Preview", htmlPane); this.previewTab.setClosable(false); threadService.runActionLater(() -> { previewTabPane.getTabs().add(previewTab); }, true); // Hide tab if one in tabpane previewTabPane.getTabs().addListener((ListChangeListener) change -> { final StackPane header = (StackPane) previewTabPane.lookup(".tab-header-area"); if (header != null) { if (previewTabPane.getTabs().size() == 1) header.setPrefHeight(0); else header.setPrefHeight(-1); } }); previewTabPane.setRotateGraphic(true); outlineTab.getTabPane() .getSelectionModel() .selectedItemProperty() .addListener((observable, oldValue, newValue) -> { if (newValue == outlineTab) { current.currentEditor().rerender(); } }); initializePaths(); initializeLogViewer(); initializeDoctypes(); previewTabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS); previewTabPane.setSide(Side.RIGHT); tooltipTimeFixService.fix(); // Convert menu label icons AwesomeDude.setIcon(htmlPro, AwesomeIcon.HTML5); AwesomeDude.setIcon(pdfPro, AwesomeIcon.FILE_PDF_ALT); AwesomeDude.setIcon(ebookPro, AwesomeIcon.BOOK); AwesomeDude.setIcon(docbookPro, AwesomeIcon.CODE); AwesomeDude.setIcon(odfPro, AwesomeIcon.FILE_WORD_ALT); AwesomeDude.setIcon(browserPro, AwesomeIcon.FLASH); // Left menu label icons AwesomeDude.setIcon(workingDirButton, AwesomeIcon.FOLDER_ALT, "14.0"); AwesomeDude.setIcon(panelShowHideMenuButton, AwesomeIcon.COLUMNS, "14.0"); AwesomeDude.setIcon(refreshLabel, AwesomeIcon.REFRESH, "14.0"); AwesomeDude.setIcon(goHomeLabel, AwesomeIcon.HOME, "14.0"); leftButton.setGraphic(AwesomeDude.createIconLabel(AwesomeIcon.ELLIPSIS_H, "14.0")); afxVersionItem.setText(String.join(" ", "Version", version)); ContextMenu htmlProMenu = new ContextMenu(); htmlProMenu.getStyleClass().add("build-menu"); htmlPro.setContextMenu(htmlProMenu); htmlPro.setOnMouseClicked(event -> { htmlProMenu.show(htmlPro, event.getScreenX(), 50); }); htmlProMenu.getItems().add(MenuItemBuilt.item("Save").click(event -> { this.generateHtml(); })); htmlProMenu.getItems().add(MenuItemBuilt.item("Save as").click(event -> { this.generateHtml(true); })); htmlProMenu.getItems().add(MenuItemBuilt.item("Copy source").tip("Copy HTML source").click(event -> { this.cutCopy(lastRendered.getValue()); })); htmlProMenu.getItems().add(MenuItemBuilt.item("Clone source").tip("Copy HTML source (Embedded images)").click(event -> { htmlPane.call("imageToBase64Url", new Object[]{}); })); ContextMenu pdfProMenu = new ContextMenu(); pdfProMenu.getStyleClass().add("build-menu"); pdfProMenu.getItems().add(MenuItemBuilt.item("Save").click(event -> { this.generatePdf(); })); pdfProMenu.getItems().add(MenuItemBuilt.item("Save as").click(event -> { this.generatePdf(true); })); pdfPro.setContextMenu(pdfProMenu); pdfPro.setOnMouseClicked(event -> { pdfProMenu.show(pdfPro, event.getScreenX(), 50); }); ContextMenu docbookProMenu = new ContextMenu(); docbookProMenu.getStyleClass().add("build-menu"); docbookProMenu.getItems().add(MenuItemBuilt.item("Save").click(event -> { this.convertDocbook(); })); docbookProMenu.getItems().add(MenuItemBuilt.item("Save as").click(event -> { this.convertDocbook(true); })); docbookPro.setContextMenu(docbookProMenu); docbookPro.setOnMouseClicked(event -> { docbookProMenu.show(docbookPro, event.getScreenX(), 50); }); ContextMenu ebookProMenu = new ContextMenu(); ebookProMenu.getStyleClass().add("build-menu"); ebookProMenu.getItems().add(MenuBuilt.name("Mobi") .add(MenuItemBuilt.item("Save").click(event -> { this.convertMobi(); })) .add(MenuItemBuilt.item("Save as").click(event -> { this.convertMobi(true); })).build()); ebookProMenu.getItems().add(MenuBuilt.name("Epub") .add(MenuItemBuilt.item("Save").click(event -> { this.convertEpub(); })) .add(MenuItemBuilt.item("Save as").click(event -> { this.convertEpub(true); })).build()); ebookPro.setOnMouseClicked(event -> { ebookProMenu.show(ebookPro, event.getScreenX(), 50); }); ebookPro.setContextMenu(ebookProMenu); ContextMenu odfProMenu = new ContextMenu(); odfProMenu.getStyleClass().add("build-menu"); odfProMenu.setAutoHide(true); odfProMenu.getItems().add(MenuItemBuilt.item("Save").click(event -> { odfProMenu.hide(); this.generateODFDocument(); })); odfProMenu.getItems().add(MenuItemBuilt.item("Save as").click(event -> { odfProMenu.hide(); this.generateODFDocument(true); })); odfPro.setContextMenu(odfProMenu); odfPro.setOnMouseClicked(event -> { odfProMenu.show(odfPro, event.getScreenX(), 50); }); browserPro.setOnMouseClicked(event -> { if (event.getButton() == MouseButton.PRIMARY) this.externalBrowse(); }); loadConfigurations(); loadRecentFileList(); loadShortCuts(); recentListView.setItems(recentFilesList); recentFilesList.addListener((ListChangeListener<String>) c -> { recentListView.visibleProperty().setValue(c.getList().size() > 0); recentListView.getSelectionModel().selectFirst(); }); recentListView.setOnMouseClicked(event -> { if (event.getClickCount() > 1) { openRecentListFile(event); } }); if (favoriteDirectories.size() == 0) { favoriteDirMenu.setVisible(false); } else { int size = 0; for (String favoriteDirectory : favoriteDirectories) { this.addItemToFavoriteDir(size++, favoriteDirectory); } this.includeClearAllToFavoriteDir(); } favoriteDirectories.addListener((ListChangeListener<String>) c -> { c.next(); favoriteDirMenu.setVisible(true); int size = favoriteDirMenu.getItems().size(); boolean empty = size == 0; List<? extends String> addedSubList = c.getAddedSubList(); for (String path : addedSubList) { if (size > 0) this.addItemToFavoriteDir(size++ - 2, path); else this.addItemToFavoriteDir(size++, path); } if (empty) this.includeClearAllToFavoriteDir(); }); treeView.setCellFactory(param -> { TreeCell<Item> cell = new TextFieldTreeCell<Item>(); cell.setOnDragDetected(event -> { Dragboard db = cell.startDragAndDrop(TransferMode.ANY); ClipboardContent content = new ClipboardContent(); content.putFiles(Arrays.asList(cell.getTreeItem().getValue().getPath().toFile())); db.setContent(content); }); return cell; }); lastRendered.addListener(lastRenderedChangeListener); // MathJax mathjaxView = new WebView(); mathjaxView.setVisible(false); rootAnchor.getChildren().add(mathjaxView); WebEngine mathjaxEngine = mathjaxView.getEngine(); mathjaxEngine.getLoadWorker().stateProperty().addListener((observableValue1, state, state2) -> { JSObject window = (JSObject) mathjaxEngine.executeScript("window"); if (window.getMember("afx").equals("undefined")) window.setMember("afx", this); }); threadService.runActionLater(() -> { mathjaxEngine.load(String.format("http://localhost:%d/mathjax.html", port)); }); htmlPane.load(String.format("http://localhost:%d/preview.html", port)); /// Treeview if (Objects.nonNull(recentFiles.getWorkingDirectory())) { Path path = Paths.get(recentFiles.getWorkingDirectory()); Optional<Path> optional = Files.notExists(path) ? Optional.empty() : Optional.of(path); directoryService.setWorkingDirectory(optional); } Path workDir = directoryService.getWorkingDirectory().orElse(userHome); fileBrowser.browse(workDir); watchService.registerWatcher(workDir); openFileTreeItem.setOnAction(event -> { ObservableList<TreeItem<Item>> selectedItems = treeView.getSelectionModel().getSelectedItems(); selectedItems.stream() .map(e -> e.getValue()) .map(e -> e.getPath()) .filter(path -> { if (selectedItems.size() == 1) return true; return !Files.isDirectory(path); }) .forEach(directoryService.getOpenFileConsumer()::accept); }); deletePathItem.setOnAction(event -> { ObservableList<TreeItem<Item>> selectedItems = treeView.getSelectionModel().getSelectedItems(); AlertHelper.deleteAlert().ifPresent(btn -> { if (btn == ButtonType.YES) selectedItems.stream() .map(e -> e.getValue()) .map(e -> e.getPath()) .forEach(path -> threadService.runTaskLater(() -> { if (Files.isDirectory(path)) { IOHelper.deleteDirectory(path); } else { IOHelper.deleteIfExists(path); } })); }); }); openFolderTreeItem.setOnAction(event -> { Path path = tabService.getSelectedTabPath(); path = Files.isDirectory(path) ? path : path.getParent(); if (Objects.nonNull(path)) getHostServices().showDocument(path.toString()); }); openFolderListItem.setOnAction(event -> { Path path = Paths.get(recentListView.getSelectionModel().getSelectedItem()); path = Files.isDirectory(path) ? path : path.getParent(); if (Objects.nonNull(path)) getHostServices().showDocument(path.toString()); }); openFileListItem.setOnAction(this::openRecentListFile); copyPathTreeItem.setOnAction(event -> { Path path = tabService.getSelectedTabPath(); this.cutCopy(path.toString()); }); copyPathListItem.setOnAction(event -> { this.cutCopy(recentListView.getSelectionModel().getSelectedItem()); }); copyTreeItem.setOnAction(event -> { Path path = tabService.getSelectedTabPath(); this.copyFile(path); }); copyListItem.setOnAction(event -> { Path path = Paths.get(recentListView.getSelectionModel().getSelectedItem()); this.copyFile(path); }); treeView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); treeView.setOnMouseClicked(event -> { TreeItem<Item> selectedItem = treeView.getSelectionModel().getSelectedItem(); if (Objects.isNull(selectedItem)) return; Path selectedPath = selectedItem.getValue().getPath(); if (event.getButton() == MouseButton.PRIMARY) if (event.getClickCount() == 2) directoryService.getOpenFileConsumer().accept(selectedPath); }); treeView.getSelectionModel().getSelectedIndices().addListener((ListChangeListener<? super Integer>) p -> { ObservableList<TreeItem<Item>> selectedItems = treeView.getSelectionModel().getSelectedItems(); if (selectedItems.size() > 1) { renameFile.setVisible(false); newMenu.setVisible(false); addToFavoriteDir.setVisible(false); renameSeparator.setVisible(false); if (favoriteDirMenu.getItems().size() > 0) { addToFavSeparator.setVisible(true); } else { addToFavSeparator.setVisible(false); } } else if (selectedItems.size() == 1) { Path path = selectedItems.get(0).getValue().getPath(); boolean isDirectory = Files.isDirectory(path); newMenu.setVisible(isDirectory); renameFile.setVisible(!isDirectory); renameSeparator.setVisible(true); addToFavoriteDir.setVisible(isDirectory); if (favoriteDirMenu.getItems().size() == 0 && !isDirectory) { addToFavSeparator.setVisible(false); } else { addToFavSeparator.setVisible(true); } if (favoriteDirectories.size() > 0) { boolean has = favoriteDirectories.contains(path.toString()); if (has) addToFavoriteDir.setDisable(true); else addToFavoriteDir.setDisable(false); } } }); htmlPane.webEngine().setOnAlert(event -> { if ("PREVIEW_LOADED".equals(event.getData())) { if (htmlPane.getMember("afx").equals("undefined")) { htmlPane.setMember("afx", this); } if (Objects.nonNull(lastRendered.getValue())) lastRenderedChangeListener.changed(null, null, lastRendered.getValue()); } }); CheckMenuItem renderingCheckbox = new CheckMenuItem(); renderingCheckbox.setGraphic(new Label("Stop rendering")); stopRendering.bind(renderingCheckbox.selectedProperty()); ContextMenu previewContextMenu = new ContextMenu( MenuItemBuilt.item("Go back").click(event -> { WebHistory history = htmlPane.webEngine().getHistory(); if (history.getCurrentIndex() != 0) history.go(-1); }), MenuItemBuilt.item("Go forward").click(event -> { WebHistory history = htmlPane.webEngine().getHistory(); if (history.getCurrentIndex() + 1 != history.getEntries().size()) history.go(+1); }), new SeparatorMenuItem(), renderingCheckbox, new SeparatorMenuItem(), MenuItemBuilt.item("Copy Html").click(event -> { DocumentFragmentImpl selectionDom = (DocumentFragmentImpl) htmlPane.webEngine().executeScript("window.getSelection().getRangeAt(0).cloneContents()"); ClipboardContent content = new ClipboardContent(); content.putHtml(XMLHelper.nodeToString(selectionDom, true)); clipboard.setContent(content); }), MenuItemBuilt.item("Copy Text").click(event -> { String selection = (String) htmlPane.webEngine().executeScript("window.getSelection().toString()"); ClipboardContent content = new ClipboardContent(); content.putString(selection); clipboard.setContent(content); }), MenuItemBuilt.item("Copy Source").click(event -> { DocumentFragmentImpl selectionDom = (DocumentFragmentImpl) htmlPane.webEngine().executeScript("window.getSelection().getRangeAt(0).cloneContents()"); ClipboardContent content = new ClipboardContent(); content.putString(XMLHelper.nodeToString(selectionDom, true)); clipboard.setContent(content); }), new SeparatorMenuItem(), MenuItemBuilt.item("Refresh").click(event -> { htmlPane.webEngine().executeScript("clearImageCache()"); }), MenuItemBuilt.item("Reload").click(event -> { htmlPane.webEngine().reload(); }) ); previewContextMenu.setAutoHide(true); htmlPane.getWebView().setOnMouseClicked(event -> { if (event.getButton() == MouseButton.SECONDARY) { previewContextMenu.show(htmlPane.getWebView(), event.getScreenX(), event.getScreenY()); } else { previewContextMenu.hide(); } }); tabService.initializeTabChangeListener(tabPane); newDoc(null); Platform.runLater(() -> { // editorSplitPane.setDividerPositions(1); // splitPane.setDividerPositions(); }); threadService.runTaskLater(this::checkNewVersion); // threadService.runTaskLater(this::initializeAutoSaver); } /* private void initializeAutoSaver() { final AtomicReference<Instant> currentTime = new AtomicReference<>(Instant.now()); stage.addEventFilter(EventType.ROOT, event -> { currentTime.set(Instant.now()); }); Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (currentTime.get().plusSeconds(3).isBefore(Instant.now())) { currentTime.set(Instant.now()); ObservableList<Tab> tabs = tabPane.getTabs(); for (Tab tab : tabs) { MyTab myTab = (MyTab) tab; if(!myTab.isNew()){ } } } } }, 0, 500); }*/ private void bindConfigurations() { /*ObjectProperty<Color> colorProperty = editorConfigBean.backgroundColorProperty(); ObjectProperty<Color> innerColorProperty = editorConfigBean.innerBackgroundColorProperty(); colorProperty.addListener((observable, oldValue, newValue) -> { if (Objects.nonNull(newValue)) { String backgroundColor = Integer.toHexString(newValue.hashCode()); if (Objects.isNull(innerColorProperty.get())) { rootAnchor.setStyle(String.format("-fx-base: #%s;", backgroundColor)); } else { String innerBackgroundColor = Integer.toHexString(innerColorProperty.get().hashCode()); rootAnchor.setStyle(String.format("-fx-base: #%s;-fx-control-inner-background: #%s", backgroundColor, innerBackgroundColor)); } } }); innerColorProperty.addListener((observable, oldValue, newValue) -> { if (Objects.nonNull(newValue)) { String innerBackgroundColor = Integer.toHexString(newValue.hashCode()); if (Objects.isNull(colorProperty.get())) { rootAnchor.setStyle(String.format("-fx-control-inner-background: #%s;", innerBackgroundColor)); } else { String backgroundColor = Integer.toHexString(colorProperty.get().hashCode()); rootAnchor.setStyle(String.format("-fx-base: #%s;-fx-control-inner-background: #%s", backgroundColor, innerBackgroundColor)); } } });*/ editorConfigBean.showGutterProperty().addListener((observable, oldValue, newValue) -> { if (Objects.nonNull(newValue)) { applyForAllEditorPanes(editorPane -> editorPane.setShowGutter(newValue)); } }); editorConfigBean.useWrapModeProperty().addListener((observable, oldValue, newValue) -> { if (Objects.nonNull(newValue)) { applyForAllEditorPanes(editorPane -> editorPane.setUseWrapMode(newValue)); } }); editorConfigBean.wrapLimitProperty().addListener((observable, oldValue, newValue) -> { if (Objects.nonNull(newValue)) { applyForAllEditorPanes(editorPane -> editorPane.setWrapLimitRange(newValue)); } }); editorConfigBean.directoryPanelProperty().addListener((observable, oldValue, newValue) -> { if (newValue) { showFileBrowser(); } else { hideFileBrowser(null); } }); ListChangeListener<String> themeChangeListener = c -> { c.next(); if (c.wasAdded()) { String theme = c.getList().get(0); applyForAllEditorPanes(editorPane -> editorPane.setTheme(theme)); } }; editorConfigBean.editorThemeProperty().addListener((observable, oldValue, newValue) -> { if (Objects.nonNull(newValue)) { newValue.addListener(themeChangeListener); } if (Objects.nonNull(oldValue)) { oldValue.removeListener(themeChangeListener); } }); editorConfigBean.fontSizeProperty().addListener((observable, oldValue, newValue) -> { applyForAllEditorPanes(editorPane -> editorPane.setFontSize(newValue.intValue())); }); } private void applyForAllEditorPanes(Consumer<EditorPane> editorPaneConsumer){ ObservableList<Tab> tabs = tabPane.getTabs(); for (Tab tab : tabs) { MyTab myTab = (MyTab) tab; editorPaneConsumer.accept(myTab.getEditorPane()); } } private void includeClearAllToFavoriteDir() { favoriteDirMenu.getItems().addAll(new SeparatorMenuItem(), MenuItemBuilt .item("Clear List") .click(event -> { ObservableList<TreeItem<Item>> selectedItems = treeView.getSelectionModel().getSelectedItems(); if (selectedItems.size() == 1) { Path path = selectedItems.get(0).getValue().getPath(); boolean isDirectory = Files.isDirectory(path); addToFavSeparator.setVisible(isDirectory); } else addToFavSeparator.setVisible(false); favoriteDirectories.clear(); favoriteDirMenu.getItems().clear(); recentFiles.getFavoriteDirectories().clear(); favoriteDirMenu.setVisible(false); addToFavoriteDir.setDisable(false); })); } private void addItemToFavoriteDir(int index, String path) { favoriteDirMenu.getItems().add(index, MenuItemBuilt .item(path) .tip("Go to favorite dir") .click(event -> { directoryService.changeWorkigDir(Paths.get(path)); })); } private void checkNewVersion() { try { ApplicationLauncher.launchApplication("504", null, false, new ApplicationLauncher.Callback() { public void exited(int exitValue) { //TODO add your code here (not invoked on event dispatch thread) } public void prepareShutdown() { //TODO add your code here (not invoked on event dispatch thread) } } ); } catch (IOException e) { // logger.error("Problem occured while checking new version", e); } } private void generateODFDocument(boolean askPath) { if (!current.currentPath().isPresent()) this.saveDoc(); odfConverter.generateODFDocument(askPath); } private void generateODFDocument() { this.generateODFDocument(false); } private void initializeDoctypes() { try { ObjectMapper mapper = new ObjectMapper(); Object readValue = mapper.readValue(configPath.resolve("ace_doctypes.json").toFile(), new TypeReference<List<DocumentMode>>() { }); modeList.addAll((Collection) readValue); supportedModes = modeList.stream() .map(d -> d.getExtensions()) .filter(Objects::nonNull) .flatMap(d -> Arrays.asList(d.split("\\|")).stream()) .collect(Collectors.toList()); } catch (Exception e) { e.printStackTrace(); logger.error("Problem occured while loading document types", e); } } private void initializePaths() { try { CodeSource codeSource = ApplicationController.class.getProtectionDomain().getCodeSource(); File jarFile = new File(codeSource.getLocation().toURI().getPath()); installationPath = jarFile.toPath().getParent().getParent(); configPath = installationPath.resolve("conf"); logPath = installationPath.resolve("log"); } catch (URISyntaxException e) { logger.error("Problem occured while resolving conf and log paths", e); } } @WebkitCall public void updateStatusBox(long row, long column, long linecount, long wordcount) { threadService.runTaskLater(() -> { threadService.runActionLater(() -> { statusText.setText(String.format("(Characters: %d) (Lines: %d) (%d:%d)", wordcount, linecount, row, column)); }); }); } private void initializeLogViewer() { TableView<MyLog> logViewer = new TableView<>(); logViewer.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); ContextMenu logViewerContextMenu = new ContextMenu(); logViewerContextMenu.getItems().add(MenuItemBuilt.item("Copy").click(e -> { ObservableList<MyLog> rowList = (ObservableList) logViewer.getSelectionModel().getSelectedItems(); StringBuilder clipboardString = new StringBuilder(); for (MyLog rowLog : rowList) { clipboardString.append(String.format("%s => %s", rowLog.getLevel(), rowLog.getMessage())); clipboardString.append("\n\n"); } ClipboardContent clipboardContent = new ClipboardContent(); clipboardContent.putString(clipboardString.toString()); clipboard.setContent(clipboardContent); })); logViewer.setContextMenu(logViewerContextMenu); logViewer.getStyleClass().add("log-viewer"); FilteredList<MyLog> logFilteredList = new FilteredList<MyLog>(logList, log -> true); logViewer.setItems(logFilteredList); // logViewer.setColumnResizePolicy((param) -> true); logViewer.getItems().addListener((ListChangeListener<MyLog>) c -> { c.next(); final int size = logViewer.getItems().size(); if (size > 0) { logViewer.scrollTo(size - 1); } }); TableColumn<MyLog, String> levelColumn = new TableColumn<>("Level"); levelColumn.getStyleClass().add("level-column"); TableColumn<MyLog, String> messageColumn = new TableColumn<>("Message"); levelColumn.setCellValueFactory(new PropertyValueFactory<MyLog, String>("level")); messageColumn.setCellValueFactory(new PropertyValueFactory<MyLog, String>("message")); messageColumn.prefWidthProperty().bind(logViewer.widthProperty().subtract(levelColumn.widthProperty()).subtract(5)); logViewer.setRowFactory(param -> new TableRow<MyLog>() { @Override protected void updateItem(MyLog item, boolean empty) { super.updateItem(item, empty); if (!empty) { getStyleClass().removeAll("DEBUG", "INFO", "WARN", "ERROR"); getStyleClass().add(item.getLevel()); } } }); messageColumn.setCellFactory(param -> new TableCell<MyLog, String>() { @Override protected void updateItem(String item, boolean empty) { if (item == getItem()) return; super.updateItem(item, empty); if (item == null) { super.setText(null); super.setGraphic(null); } else { Text text = new Text(item); super.setGraphic(text); text.wrappingWidthProperty().bind(messageColumn.widthProperty().subtract(0)); } } }); logViewer.getColumns().addAll(levelColumn, messageColumn); logViewer.setEditable(true); TableViewLogAppender.setLogList(logList); TableViewLogAppender.setLogShortMessage(statusMessage); TableViewLogAppender.setLogViewer(logViewer); final EventHandler<ActionEvent> filterByLogLevel = event -> { ToggleButton logLevelItem = (ToggleButton) event.getTarget(); if (Objects.nonNull(logLevelItem)) { logFilteredList.setPredicate(myLog -> { String text = logLevelItem.getText(); return text.equals("All") || text.equalsIgnoreCase(myLog.getLevel()); }); } }; ToggleGroup toggleGroup = new ToggleGroup(); ToggleButton allToggle = ToggleButtonBuilt.item("All").tip("Show all").click(filterByLogLevel); ToggleButton errorToggle = ToggleButtonBuilt.item("Error").tip("Filter by Error").click(filterByLogLevel); ToggleButton warnToggle = ToggleButtonBuilt.item("Warn").tip("Filter by Warn").click(filterByLogLevel); ToggleButton infoToggle = ToggleButtonBuilt.item("Info").tip("Filter by Info").click(filterByLogLevel); ToggleButton debugToggle = ToggleButtonBuilt.item("Debug").tip("Filter by Debug").click(filterByLogLevel); toggleGroup.getToggles().addAll( allToggle, errorToggle, warnToggle, infoToggle, debugToggle ); toggleGroup.selectToggle(allToggle); Button clearLogsButton = new Button("Clear"); clearLogsButton.setOnAction(e -> { statusMessage.setText(""); logList.clear(); }); Button browseLogsButton = new Button("Browse"); browseLogsButton.setOnAction(e -> { getHostServices().showDocument(logPath.toUri().toString()); }); TextField searchLogField = new TextField(); searchLogField.setPromptText("Search in logs.."); searchLogField.textProperty().addListener((observable, oldValue, newValue) -> { if (Objects.isNull(newValue)) { return; } if (newValue.isEmpty()) { logFilteredList.setPredicate(myLog -> true); } logFilteredList.setPredicate(myLog -> { final AtomicBoolean result = new AtomicBoolean(false); String message = myLog.getMessage(); if (Objects.nonNull(message)) { if (!result.get()) result.set(message.toLowerCase().contains(newValue.toLowerCase())); } String level = myLog.getLevel(); String toggleText = ((ToggleButton) toggleGroup.getSelectedToggle()).getText(); boolean inputContains = level.toLowerCase().contains(newValue.toLowerCase()); if (Objects.nonNull(level)) { if (!result.get()) { result.set(inputContains); } } boolean levelContains = toggleText.toLowerCase().equalsIgnoreCase(level); if (!toggleText.equals("All") && !levelContains) { result.set(false); } return result.get(); }); }); List<Control> controls = Arrays.asList(allToggle, errorToggle, warnToggle, infoToggle, debugToggle, searchLogField, clearLogsButton, browseLogsButton); HBox logHBox = new HBox(); for (Control control : controls) { logHBox.getChildren().add(control); HBox.setMargin(control, new Insets(3)); control.prefHeightProperty().bind(searchLogField.heightProperty()); } AwesomeDude.setIcon(showHideLogs, AwesomeIcon.CHEVRON_CIRCLE_UP, "14.0"); HBox.setMargin(showHideLogs, new Insets(0, 0, 0, 3)); HBox.setMargin(statusText, new Insets(0, 3, 0, 0)); showHideLogs.setOnMouseClicked(event -> { showHideLogs.setRotate(showHideLogs.getRotate() + 180); if (showHideLogs.getRotate() % 360 == 0) editorSplitPane.setDividerPositions(1); else editorSplitPane.setDividerPositions(0.5); }); scene.addListener((observableScene, oldScene, newScene) -> { if (Objects.nonNull(newScene)) { newScene.heightProperty().addListener((observable, oldValue, newValue) -> { if (showHideLogs.getRotate() % 360 == 0) { threadService.runActionLater(() -> { editorSplitPane.setDividerPositions(1); }, true); } }); } }); logVBox.getChildren().addAll(logHBox, logViewer); VBox.setVgrow(logViewer, Priority.ALWAYS); } private void loadShortCuts() { try { String yamlC = IOHelper.readFile(configPath.resolve("shortcuts.yml")); Yaml yaml = new Yaml(); this.shortCuts = yaml.loadAs(yamlC, Map.class); } catch (Exception e) { logger.error("Problem occured while loading shortcuts.yml file", e); } } private void openRecentListFile(Event event) { Path path = Paths.get(recentListView.getSelectionModel().getSelectedItem()); directoryService.getOpenFileConsumer().accept(path); } private void loadConfigurations() { // try { // String yamlContent = IOHelper.readFile(configPath.resolve("config.yml")); // Yaml yaml = new Yaml(); // config = yaml.loadAs(yamlContent, Config.class); // } catch (Exception e) { // logger.error("Problem occured while loading config.yml file", e); } private void loadRecentFileList() { try { String yamlContent = IOHelper.readFile(configPath.resolve("recentFiles.yml")); Yaml yaml = new Yaml(); recentFiles = yaml.loadAs(yamlContent, RecentFiles.class); recentFilesList.addAll(recentFiles.getFiles()); favoriteDirectories.addAll(recentFiles.getFavoriteDirectories()); } catch (Exception e) { logger.error("Problem occured while loading recent file list", e); } } public void externalBrowse() { ObservableList<Tab> tabs = previewTabPane.getTabs(); for (Tab tab : tabs) { if (tab.isSelected()) { Node content = tab.getContent(); if (Objects.nonNull(content)) ((ViewPanel) content).browse(); } } } @WebkitCall(from = "index") public void fillOutlines(JSObject doc) { if (outlineTab.isSelected()) threadService.runActionLater(() -> { htmlPane.fillOutlines(doc); }); } @WebkitCall(from = "index") public void clearOutline() { outlineList = new TreeSet<>(); } @WebkitCall(from = "index") public void finishOutline() { threadService.runTaskLater(() -> { if (Objects.isNull(sectionTreeView)) { sectionTreeView = new TreeView<Section>(); TreeItem<Section> rootItem = new TreeItem<>(); rootItem.setExpanded(true); Section rootSection = new Section(); rootSection.setLevel(-1); String outlineTitle = "Outline"; rootSection.setTitle(outlineTitle); rootItem.setValue(rootSection); sectionTreeView.setRoot(rootItem); sectionTreeView.setOnMouseClicked(event -> { try { TreeItem<Section> item = sectionTreeView.getSelectionModel().getSelectedItem(); EditorPane editorPane = current.currentEditor(); editorPane.moveCursorTo(item.getValue().getLineno()); } catch (Exception e) { logger.error("Problem occured while jumping from outline"); } }); } sectionTreeView.getRoot().getChildren().clear(); for (Section section : outlineList) { TreeItem<Section> sectionItem = new TreeItem<>(section); sectionItem.setExpanded(true); sectionTreeView.getRoot().getChildren().add(sectionItem); TreeSet<Section> subsections = section.getSubsections(); for (Section subsection : subsections) { TreeItem<Section> subItem = new TreeItem<>(subsection); subItem.setExpanded(true); sectionItem.getChildren().add(subItem); this.addSubSections(subItem, subsection.getSubsections()); } } threadService.runActionLater(() -> { if (outlineList.size() == 0) { outlineTab.setContent(new Label(" There is no Asciidoc header to generate outline.")); } else { outlineTab.setContent(sectionTreeView); } }); }); } private void addSubSections(TreeItem<Section> subItem, TreeSet<Section> outlineList) { for (Section section : outlineList) { TreeItem<Section> sectionItem = new TreeItem<>(section); subItem.getChildren().add(sectionItem); TreeSet<Section> subsections = section.getSubsections(); for (Section subsection : subsections) { TreeItem<Section> item = new TreeItem<>(subsection); sectionItem.getChildren().add(item); this.addSubSections(item, subsection.getSubsections()); } } } @WebkitCall(from = "index") public void fillOutline(String parentLineNo, String level, String title, String lineno, String id) { Section section = new Section(); section.setLevel(Integer.valueOf(level)); section.setTitle(title); section.setLineno(Integer.valueOf(lineno)); section.setId(id); if (Objects.isNull(parentLineNo)) outlineList.add(section); else { Integer parentLine = Integer.valueOf(parentLineNo); Optional<Section> parentSection = outlineList.stream() .filter(e -> e.getLineno().equals(parentLine)) .findFirst(); if (parentSection.isPresent()) parentSection.get().getSubsections().add(section); else { this.traverseEachSubSection(outlineList, parentLine, section); } } } private void traverseEachSubSection(TreeSet<Section> sections, Integer parentLine, Section section) { sections.stream().forEach(s -> { Optional<Section> subs = s.getSubsections().stream() .filter(e -> e.getLineno().equals(parentLine)) .findFirst(); if (subs.isPresent()) subs.get().getSubsections().add(section); else this.traverseEachSubSection(s.getSubsections(), parentLine, section); }); } @FXML public void changeWorkingDir(Event actionEvent) { directoryService.changeWorkigDir(); } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessionList.add(session); String value = lastRendered.getValue(); if (Objects.nonNull(value)) session.sendMessage(new TextMessage(value)); } @FXML public void closeApp(ActionEvent event) { try { Map<String, ConfigurationBase> configurationBeansAsMap = applicationContext.getBeansOfType(ConfigurationBase.class); for (ConfigurationBase configurationBean : configurationBeansAsMap.values()) { configurationBean.save(event); } yamlService.persist(); } catch (Exception e) { logger.error("Error while closing app", e); } } @FXML public void openDoc(Event event) { documentService.openDoc(); } @FXML public void newDoc(Event event) { threadService.runActionLater(() -> { documentService.newDoc(); }, true); } @WebkitCall(from = "editor") public boolean isLiveReloadPane() { return previewTab.getContent() == liveReloadPane; } @WebkitCall(from = "editor") public void onscroll(Object pos, Object max) { Node content = previewTab.getContent(); if (Objects.nonNull(content)) { ((ViewPanel) content).onscroll(pos, max); } } @WebkitCall(from = "editor") public void scrollToCurrentLine(String text) { if (previewTab.getContent() == slidePane) { slidePane.flipThePage(htmlPane.findRenderedSelection(text)); // slide } if (previewTab.getContent() == htmlPane) { threadService.runActionLater(() -> { try { htmlPane.call("runScroller", text); } catch (Exception e) { logger.debug(e.getMessage(), e); } }); } } public void plantUml(String uml, String type, String fileName) throws IOException { threadService.runTaskLater(() -> { plantUmlService.plantUml(uml, type, fileName); }); } public void chartBuildFromCsv(String csvFile, String fileName, String chartType, String options) { if (Objects.isNull(fileName) || Objects.isNull(chartType)) return; getCurrent().currentPath().map(Path::getParent).ifPresent(root -> { threadService.runTaskLater(() -> { String csvContent = IOHelper.readFile(root.resolve(csvFile)); threadService.runActionLater(() -> { try { Map<String, String> optMap = parseChartOptions(options); optMap.put("csv-file", csvFile); chartProvider.getProvider(chartType).chartBuild(csvContent, fileName, optMap); } catch (Exception e) { logger.info(e.getMessage(), e); } }); }); }); } public void chartBuild(String chartContent, String fileName, String chartType, String options) { if (Objects.isNull(fileName) || Objects.isNull(chartType)) return; threadService.runActionLater(() -> { try { Map<String, String> optMap = parseChartOptions(options); chartProvider.getProvider(chartType).chartBuild(chartContent, fileName, optMap); } catch (Exception e) { logger.info(e.getMessage(), e); } }); } private Map<String, String> parseChartOptions(String options) { Map<String, String> optMap = new HashMap<>(); if (Objects.nonNull(options)) { String[] optPart = options.split(","); for (String opt : optPart) { String[] keyVal = opt.split("="); if (keyVal.length != 2) continue; optMap.put(keyVal[0], keyVal[1]); } } return optMap; } @WebkitCall(from = "editor") public void appendWildcard() { String currentTabText = current.getCurrentTabText(); if (!currentTabText.contains(" *")) current.setCurrentTabText(currentTabText + " *"); } @WebkitCall(from = "editor") public void textListener(String text, String mode) { if (stopRendering.get()) { return; } threadService.runTaskLater(() -> { boolean bookArticleHeader = this.bookArticleHeaderRegex.matcher(text).find(); boolean forceInclude = this.forceIncludeRegex.matcher(text).find(); threadService.runActionLater(() -> { try { if ("asciidoc".equalsIgnoreCase(mode)) { if (bookArticleHeader && !forceInclude) setIncludeAsciidocResource(true); ConverterResult result = htmlPane.convertAsciidoc(text); setIncludeAsciidocResource(false); if (result.isBackend("html5")) { lastRendered.setValue(result.getRendered()); previewTab.setContent(htmlPane); } if (result.isBackend("revealjs") || result.isBackend("deckjs")) { slidePane.setBackend(result.getBackend()); slideConverter.convert(result.getRendered()); } } else if ("html".equalsIgnoreCase(mode)) { if (previewTab.getContent() != liveReloadPane) { liveReloadPane.setOnSuccess(() -> { liveReloadPane.setMember("afx", this); liveReloadPane.initializeDiffReplacer(); }); liveReloadPane.load(String.format("http://localhost:%d/livereload/index.reload", port)); } else { liveReloadPane.updateDomdom(); } previewTab.setContent(liveReloadPane); } else if ("markdown".equalsIgnoreCase(mode)) { markdownService.convertToAsciidoc(text, asciidoc -> { threadService.runActionLater(() -> { ConverterResult result = htmlPane.convertAsciidoc(asciidoc); result.afterRender(lastRendered::setValue); }); }); previewTab.setContent(htmlPane); } } catch (Exception e) { setIncludeAsciidocResource(false); logger.error("Problem occured while rendering content", e); } }); }); } @WebkitCall(from = "asciidoctor-odf.js") public void convertToOdf(String name, Object obj) throws Exception { JSObject jObj = (JSObject) obj; odfConverter.buildDocument(name, jObj); } @WebkitCall public String getTemplate(String templateName, String templateDir) throws IOException { return htmlPane.getTemplate(templateName, templateDir); } public void cutCopy(String data) { ClipboardContent clipboardContent = new ClipboardContent(); clipboardContent.putString(data); clipboard.setContent(clipboardContent); } public void copyFile(Path path) { ClipboardContent clipboardContent = new ClipboardContent(); clipboardContent.putFiles(Arrays.asList(path.toFile())); clipboard.setContent(clipboardContent); } @WebkitCall(from = "asciidoctor") public String readDefaultStylesheet() { final CompletableFuture<String> completableFuture = new CompletableFuture(); completableFuture.runAsync(() -> { threadService.runTaskLater(() -> { Path defaultCssPath = configPath.resolve("data/stylesheets/asciidoctor-default.css"); String defaultCss = IOHelper.readFile(defaultCssPath); completableFuture.complete(defaultCss); }); }); return completableFuture.join(); } @WebkitCall(from = "asciidoctor") public String readAsciidoctorResource(String uri, Integer parent) { if (uri.matches(".*?\\.(asc|adoc|ad|asciidoc|md|markdown)") && getIncludeAsciidocResource()) return String.format("link:%s[]", uri); final CompletableFuture<String> completableFuture = new CompletableFuture(); completableFuture.runAsync(() -> { threadService.runTaskLater(() -> { PathFinderService fileReader = applicationContext.getBean("pathFinder", PathFinderService.class); Path path = fileReader.findPath(uri, parent); if (!Files.exists(path)) { completableFuture.complete("404"); } else { completableFuture.complete(IOHelper.readFile(path)); } }); }); return completableFuture.join(); } @WebkitCall public String clipboardValue() { return clipboard.getString(); } @WebkitCall public void pasteRaw() { JSObject editor = (JSObject) current.currentEngine().executeScript("editor"); if (clipboard.hasFiles()) { Optional<String> block = parserService.toImageBlock(clipboard.getFiles()); if (block.isPresent()) { editor.call("insert", block.get()); return; } } editor.call("execCommand", "paste-raw-1"); } @WebkitCall public void paste() { JSObject window = (JSObject) htmlPane.webEngine().executeScript("window"); JSObject editor = (JSObject) current.currentEngine().executeScript("editor"); if (clipboard.hasFiles()) { Optional<String> block = parserService.toImageBlock(clipboard.getFiles()); if (block.isPresent()) { editor.call("insert", block.get()); return; } } try { if (clipboard.hasHtml() || (Boolean) window.call("isHtml", clipboard.getString())) { String content = Optional.ofNullable(clipboard.getHtml()).orElse(clipboard.getString()); if (current.currentTab().isAsciidoc() || current.currentTab().isMarkdown()) content = (String) window.call(current.currentTab().htmlToMarkupFunction(), content); editor.call("insert", content); return; } } catch (Exception e) { logger.error(e.getMessage(), e); } editor.call("execCommand", "paste-raw-1"); } public void adjustSplitPane() { if (splitPane.getDividerPositions()[0] > 0.1) { hideFileAndPreviewPanels(null); } else { showFileBrowser(); showPreviewPanel(); } } @WebkitCall public void debug(String message) { logger.debug(message); } @WebkitCall public void error(String message) { logger.error(message); } @WebkitCall public void info(String message) { logger.info(message); } @WebkitCall public void warn(String message) { logger.warn(message); } public void saveDoc() { documentService.saveDoc(); } @FXML public void saveDoc(Event actionEvent) { documentService.saveDoc(); } public void fitToParent(Node node) { AnchorPane.setTopAnchor(node, 0.0); AnchorPane.setBottomAnchor(node, 0.0); AnchorPane.setLeftAnchor(node, 0.0); AnchorPane.setRightAnchor(node, 0.0); } public void saveAndCloseCurrentTab() { this.saveDoc(); threadService.runActionLater(current.currentTab()::close); } public ProgressIndicator getIndikator() { return indikator; } public void setStage(Stage stage) { this.stage = stage; } public Stage getStage() { return stage; } public Scene getScene() { return scene.get(); } public ObjectProperty<Scene> sceneProperty() { return scene; } public void setScene(Scene scene) { this.scene.set(scene); } public void setAsciidocTableAnchor(AnchorPane asciidocTableAnchor) { this.asciidocTableAnchor = asciidocTableAnchor; } public AnchorPane getAsciidocTableAnchor() { return asciidocTableAnchor; } public void setAsciidocTableStage(Stage asciidocTableStage) { this.asciidocTableStage = asciidocTableStage; } public Stage getAsciidocTableStage() { return asciidocTableStage; } public SplitPane getSplitPane() { return splitPane; } public TreeView<Item> getTreeView() { return treeView; } public void setHostServices(HostServicesDelegate hostServices) { this.hostServices = hostServices; } public HostServicesDelegate getHostServices() { return hostServices; } public AsciidocTableController getAsciidocTableController() { return asciidocTableController; } public StringProperty getLastRendered() { return lastRendered; } public ObservableList<String> getRecentFilesList() { return recentFilesList; } public TabPane getTabPane() { return tabPane; } public WebView getMathjaxView() { return mathjaxView; } public ChangeListener<String> getLastRenderedChangeListener() { return lastRenderedChangeListener; } public AnchorPane getRootAnchor() { return rootAnchor; } public int getPort() { return port; } public Path getConfigPath() { return configPath; } public Current getCurrent() { return current; } public Map<String, String> getShortCuts() { if (Objects.isNull(shortCuts)) shortCuts = new HashMap<>(); return shortCuts; } @FXML private void bugReport(ActionEvent actionEvent) { getHostServices().showDocument("https://github.com/asciidocfx/AsciidocFX/issues"); } @FXML private void openCommunityForum(ActionEvent actionEvent) { getHostServices().showDocument("https://groups.google.com/d/forum/asciidocfx-discuss"); } @FXML private void openGitterChat(ActionEvent actionEvent) { getHostServices().showDocument("https://gitter.im/asciidocfx/AsciidocFX"); } @FXML private void openGithubPage(ActionEvent actionEvent) { getHostServices().showDocument("https://github.com/asciidocfx/AsciidocFX"); } @FXML public void generateCheatSheet(ActionEvent actionEvent) { Path cheatsheetPath = configPath.resolve("cheatsheet/cheatsheet.adoc"); tabService.addTab(cheatsheetPath); } public void setMarkdownTableAnchor(AnchorPane markdownTableAnchor) { this.markdownTableAnchor = markdownTableAnchor; } public AnchorPane getMarkdownTableAnchor() { return markdownTableAnchor; } public void setMarkdownTableStage(Stage markdownTableStage) { this.markdownTableStage = markdownTableStage; } public Stage getMarkdownTableStage() { return markdownTableStage; } public ShortcutProvider getShortcutProvider() { return shortcutProvider; } @FXML public void createFolder(ActionEvent actionEvent) { DialogBuilder dialog = DialogBuilder.newFolderDialog(); Consumer<String> consumer = result -> { if (dialog.isShowing()) dialog.hide(); if (result.matches(DialogBuilder.FOLDER_NAME_REGEX)) { Path path = treeView.getSelectionModel().getSelectedItem() .getValue().getPath(); Path folderPath = path.resolve(result); threadService.runTaskLater(() -> { IOHelper.createDirectory(folderPath); directoryService.changeWorkigDir(folderPath); }); } }; dialog.getEditor().setOnAction(event -> { consumer.accept(dialog.getEditor().getText()); }); dialog.showAndWait().ifPresent(consumer); } @FXML public void createFile(ActionEvent actionEvent) { DialogBuilder dialog = DialogBuilder.newFileDialog(); Consumer<String> consumer = result -> { if (dialog.isShowing()) dialog.hide(); if (result.matches(DialogBuilder.FILE_NAME_REGEX)) { Path path = treeView.getSelectionModel().getSelectedItem() .getValue().getPath(); IOHelper.writeToFile(path.resolve(result), ""); tabService.addTab(path.resolve(result)); // dikkat // threadService.runActionLater(() -> { // directoryService.changeWorkigDir(path); } }; dialog.getEditor().setOnAction(event -> { consumer.accept(dialog.getEditor().getText()); }); dialog.showAndWait().ifPresent(consumer); } @FXML public void renameFile(ActionEvent actionEvent) { RenameDialog dialog = RenameDialog.create(); Path path = treeView.getSelectionModel().getSelectedItem() .getValue().getPath(); dialog.getEditor().setText(path.getFileName().toString()); Consumer<String> consumer = result -> { if (dialog.isShowing()) dialog.hide(); if (result.trim().matches("^[^\\\\/:?*\"<>|]+$")) IOHelper.move(path, path.getParent().resolve(result.trim())); }; dialog.getEditor().setOnAction(event -> { consumer.accept(dialog.getEditor().getText()); }); dialog.showAndWait().ifPresent(consumer); } @FXML public void gitbookToAsciibook(ActionEvent actionEvent) { File gitbookRoot = null; File asciibookRoot = null; BiPredicate<File, File> nullPathPredicate = (p1, p2) -> Objects.isNull(p1) || Objects.isNull(p2); DirectoryChooser gitbookChooser = new DirectoryChooser(); gitbookChooser.setTitle("Select Gitbook Root Directory"); gitbookRoot = gitbookChooser.showDialog(null); DirectoryChooser asciibookChooser = new DirectoryChooser(); asciibookChooser.setTitle("Select Blank Asciibook Root Directory"); asciibookRoot = asciibookChooser.showDialog(null); if (nullPathPredicate.test(gitbookRoot, asciibookRoot)) { AlertHelper.nullDirectoryAlert(); return; } final File finalGitbookRoot = gitbookRoot; final File finalAsciibookRoot = asciibookRoot; threadService.runTaskLater(() -> { logger.debug("Gitbook to Asciibook conversion started"); indikatorService.startProgressBar(); gitbookToAsciibook.gitbookToAsciibook(finalGitbookRoot.toPath(), finalAsciibookRoot.toPath()); indikatorService.stopProgressBar(); logger.debug("Gitbook to Asciibook conversion ended"); }); } public boolean getFileBrowserVisibility() { return fileBrowserVisibility.get(); } public BooleanProperty fileBrowserVisibilityProperty() { return fileBrowserVisibility; } public boolean getPreviewPanelVisibility() { return previewPanelVisibility.get(); } public BooleanProperty previewPanelVisibilityProperty() { return previewPanelVisibility; } @FXML public void hideFileBrowser(ActionEvent actionEvent) { splitPane.setDividerPosition(0, 0); fileBrowserVisibility.setValue(true); } public void showFileBrowser() { splitPane.setDividerPositions(0.195, splitPane.getDividerPositions()[1]); fileBrowserVisibility.setValue(false); } public void hidePreviewPanel() { splitPane.setDividerPosition(1, 1); previewPanelVisibility.setValue(true); } @FXML public void togglePreviewPanel(ActionEvent actionEvent) { if (hidePreviewPanel.isSelected()) { hidePreviewPanel(); } else { showPreviewPanel(); } } public void showPreviewPanel() { splitPane.setDividerPosition(1, 0.6); previewPanelVisibility.setValue(false); hidePreviewPanel.setSelected(false); } @FXML public void hideFileAndPreviewPanels(ActionEvent actionEvent) { hidePreviewPanel.setSelected(true); togglePreviewPanel(actionEvent); hideFileBrowser(actionEvent); } /* @WebkitCall public void fillModeList(String mode) { threadService.runActionLater(() -> { modeList.add(mode); }); }*/ public RecentFiles getRecentFiles() { return recentFiles; } public void clearImageCache() { htmlPane.webEngine().executeScript("clearImageCache()"); } public ObservableList<DocumentMode> getModeList() { return modeList; } public List<String> getSupportedModes() { return supportedModes; } public boolean getIncludeAsciidocResource() { return includeAsciidocResource.get(); } public void setIncludeAsciidocResource(boolean includeAsciidocResource) { this.includeAsciidocResource.set(includeAsciidocResource); } public void removeChildElement(Node node) { getRootAnchor().getChildren().remove(node); } @FXML public void switchSlideView(ActionEvent actionEvent) { splitPane.setDividerPositions(0, 0.45); fileBrowserVisibility.setValue(true); } public TabPane getPreviewTabPane() { return previewTabPane; } public PreviewTab getPreviewTab() { return previewTab; } public ProgressBar getProgressBar() { return progressBar; } public Timeline getProgressBarTimeline() { return progressBarTimeline; } @FXML public void newSlide(ActionEvent actionEvent) { DialogBuilder dialog = DialogBuilder.newFolderDialog(); dialog.showAndWait().ifPresent(folderName -> { if (dialog.isShowing()) dialog.hide(); if (folderName.matches(DialogBuilder.FOLDER_NAME_REGEX)) { Path path = treeView.getSelectionModel().getSelectedItem() .getValue().getPath(); Path folderPath = path.resolve(folderName); threadService.runTaskLater(() -> { IOHelper.createDirectory(folderPath); indikatorService.startProgressBar(); IOHelper.copyDirectory(configPath.resolve("slide/frameworks"), folderPath); indikatorService.stopProgressBar(); directoryService.changeWorkigDir(folderPath); threadService.runActionLater(() -> { tabService.addTab(folderPath.resolve("slide.adoc")); this.switchSlideView(actionEvent); }); }); } }); } @FXML public void addToFavoriteDir(ActionEvent actionEvent) { Path selectedTabPath = tabService.getSelectedTabPath(); if (Files.isDirectory(selectedTabPath)) { boolean has = favoriteDirectories.contains(selectedTabPath.toString()); if (!has) { favoriteDirectories.add(selectedTabPath.toString()); recentFiles.getFavoriteDirectories().add(selectedTabPath.toString()); } } } public EditorConfigBean getEditorConfigBean() { return editorConfigBean; } public void showSettings(ActionEvent actionEvent) { configurationService.showConfig(); } }
package entity.language; import entity.Player; public class Dansk implements Language{ @Override public String notifyLangChange(){ return "Sproget er nu sat til dansk!"; } @Override public String askForNumberOfPlayers() { return "Hvor mange spillere skal være med? Der kan vælges fra 2 til 6"; } @Override public String askForPlayerName(int playerNumber){ return "Indtast spiller " + playerNumber + "'s navn, alle spillere skal have forskellige navne."; } @Override public String fieldDescription(int fieldNumber) { String fieldDescription = null; switch (fieldNumber) { case 0: fieldDescription = "Modtag 4000"; break; case 2: case 7: case 17: case 22: case 33: case 36: fieldDescription = "Prøv lykken"; break; case 4: fieldDescription = "Betal 10% eller kr. 4000"; break; case 10: fieldDescription = "På besøg i fængselet"; break; case 20: fieldDescription = "Parkering"; break; case 30: fieldDescription = "De fængsles"; break; case 38: fieldDescription = "Betal kr. 2000 i skat"; break; } return fieldDescription; } @Override public String fieldNames(int fieldNumber) { String fieldName = null; switch (fieldNumber) { case 0: fieldName = "START"; break; case 1: fieldName = "Rødovrevej"; break; case 2: fieldName = "Prøv lykken"; break; case 3: fieldName = "Hvidovrevej"; break; case 4: fieldName = "Skat"; break; case 5: fieldName = "SFL"; break; case 6: fieldName = "Roskildevej"; break; case 7: fieldName = "Prøv lykken"; break; case 8: fieldName = "Valby Langgade"; break; case 9: fieldName = "Allégade"; break; case 10: fieldName = "På Besøg"; break; case 11: fieldName = "Frederiksberg Alle"; break; case 12: fieldName = "TUBORG"; break; case 13: fieldName = "Bølowsvej"; break; case 14: fieldName = "Gl. Kongevej"; break; case 15: fieldName = "Kalundb./Århus"; break; case 16: fieldName = "Bernstorffsvej"; break; case 17: fieldName = "Prøv lykken"; break; case 18: fieldName = "Hellerupvej"; break; case 19: fieldName = "Strandvej"; break; case 20: fieldName = "Parkering"; break; case 21: fieldName = "Trianglen"; break; case 22: fieldName = "Prøv lykken"; break; case 23: fieldName = "Østerbrogade"; break; case 24: fieldName = "Grønningen"; break; case 25: fieldName = "DFDS"; break; case 26: fieldName = "Bredgade"; break; case 27: fieldName = "Kgs.Nytorv"; break; case 28: fieldName = "Coca Cola"; break; case 29: fieldName = "Østergade"; break; case 30: fieldName = "De Fængsles"; break; case 31: fieldName = "Amagertorv"; break; case 32: fieldName = "Vimmelskaftet"; break; case 33: fieldName = "Prøv lykken"; break; case 34: fieldName = "Nygade"; break; case 35: fieldName = "Halssk./Knudsh."; break; case 36: fieldName = "Prøv lykken"; break; case 37: fieldName = "Frederiksberg gade"; break; case 38: fieldName = "Skat"; break; case 39: fieldName = "Rådhuspladsen"; break; } return fieldName; } @Override public String fieldPrices(int fieldPrice) { return "kr. " + fieldPrice; } @Override public String readyToBegin(){ return "Spillet vil nu begynde. Spillet er vundet af den spiller der står tilbage når de andre er bankerot!"; } @Override public String winnerMsg(Player player){ return player.getName() + " har vundet spillet med " + player.getBankAccount().getBalance() + " kr.!"; } @Override public String preMsg(Player player){ return "Det er " + player.getName() + "'s tur, tryk på en knap!"; } @Override public String throwDices(){ return "Slå Terning"; } @Override public String build() { return "Bygge"; } @Override public String trade(){ return "Handle"; } @Override public String youGetJailedForThreeTimesEqual() { return "De fængles for at have slået to ens 3 gange i træk!"; } @Override public String getChanceCardMsg(int topCardNumber) { String chanceCardMsg = null; switch(topCardNumber) { case 1: chanceCardMsg = "Modtag udbytte af Deres aktier kr. 1000."; break; case 2: chanceCardMsg = "Deres præmieobligation er kommet ud. De modtager kr. 1000 af banken."; break; case 3: chanceCardMsg = "Grundet dyrtiden har De fået gageforhøjelse. Modtag kr. 1000."; break; case 4: chanceCardMsg = "Værdien af egen avl fra nytthaven udgør kr. 200, som De modtager af banken."; break; case 5: chanceCardMsg = "De modtager \"Matador-legatet for værdig trængende\", stort kr. 40000. Ved værdig trængende forstås, at Deres formue, d.v.s. Deres kontante penge + skøder + bygninger ikke overstiger kr. 15000."; break; case 6: chanceCardMsg = "Kommunen har eftergivet et kvartals skat. Hæv i banken kr. 3000."; break; case 7: chanceCardMsg = "Det er Deres fødselsdag. Modtag af hver medspiller kr. 200."; break; case 8: chanceCardMsg = "De havde en række med elleve rigtige i tipning. Modtag kr. 1000."; break; case 9: chanceCardMsg = "De har vundet i Klasselotteriet. Modtag kr. 500."; break; case 10: chanceCardMsg = "De har måttet vedtage en parkeringsbøde. Betal kr. 200 i bøde."; break; case 11: chanceCardMsg = "De har kør frem for \"Fuld Stop\". Betal kr. 1000 i bøde"; break; case 12: chanceCardMsg = "Betal kr. 3000 for reparation af Deres vogn"; break; case 13: chanceCardMsg = "Betal Deres bilforsikring kr. 1000."; break; case 14: chanceCardMsg = "Betal kr. 3000 for reparation af Deres vogn"; break; case 15: chanceCardMsg = "De har modtaget Deres tandlægeregning. Betal kr. 2000"; break; case 16: chanceCardMsg = "De har været en tur i udlandet og haft for mange cigaretter med hjem. Betal told kr. 200."; break; case 17: chanceCardMsg = "Ejendomsskatterne er steget, ekstraudgifterne er:\nkr. 800 pr. hus,\nkr. 2300 pr. hotel."; break; case 18: chanceCardMsg = "Oliepriserne er steget, og De skal betale:\nkr. 500 pr. hus,\nkr. 2000 pr. hotel."; break; case 19: chanceCardMsg = "I anledning af dronningens fødselsdag benådes De herved for fængsel. Dette kort kan opbevares, indtil De får brug for det, eller De kan sælge det"; break; case 20: chanceCardMsg = "Gå i fængsel. Ryk direkte til fængslet. Selv om De passerer \"Start\", indkasserer de ikke kr. 4000"; break; case 21: chanceCardMsg = "Ryk brikken frem til det nærmeste rederi og betal ejeren to gange den leje, han ellers er berettiget til. Hvis selskabet ikke ejes af nogen kan De købe det af banken."; break; case 22: chanceCardMsg = "Tag med den nærmeste færge - Flyt brikken frem, og hvis De passerer \"Start\", indkassér da kr. 4000."; break; case 23: chanceCardMsg = "Ryk frem til Grønningen. Hvis De passerer \"Start\", indkassér da kr. 4000."; break; case 24: chanceCardMsg = "Ryk frem til \"Start\"."; break; case 25: chanceCardMsg = "Ryk frem til Frederiksberg Allé. Hvis De passerer \"Start\", indkassér kr. 4000."; break; case 26: chanceCardMsg = "Tag ind på Rådhuspladsen."; break; case 27: chanceCardMsg = "Ryk tre felter tilbage."; break; default: chanceCardMsg = "Prøv lykken"; break; } return chanceCardMsg; } @Override public String fieldMsg(int fieldNumber){ String fieldString = null; switch (fieldNumber) { case 2: case 7: case 17: case 22: case 33: case 36: fieldString = "Du er landet på \"Prøv lykken\". Tryk på \"Prøv lykken\" bunken i midten for trække et kort!"; break; case 4: case 38: fieldString = "Du er landet på et skatte-felt. Du bedes betale skat."; break; case 10: fieldString = "Du tager et smut på besøg i fængslet"; break; case 20: fieldString = "Du er landet på \"Parkering\". Du modtager kr. 5000."; break; case 30: fieldString = "Du ryger i fængsel."; break; default: fieldString = "Du er landet på " + fieldNames(fieldNumber) + "."; break; } return fieldString; } @Override public String landedOnOwnedField(Player owner) { return "Dette felt ejes af " + owner.getName() + ", det kommer til at koste!"; } @Override public String youPaidThisMuchToThisPerson(int amountPayed, Player owner) { return "Du betalte " + amountPayed + " kr. til " + owner.getName() + "."; } @Override public String youOwnThisField() { return "Slap af! Du ejer selv dette felt ;)"; } @Override public String getTaxChoice() { return "Du kan vælge enten at betale 4000 kr eller 10% af din pengebeholdning," + "\nvil du betale 10%?"; } @Override public String youAreBroke() { return "Du er desværre gået bankerot, tak for spillet!"; } @Override public String notBuildable(){ return "Du har ingen grunde du kan bygge på."; } @Override public String choosePlotToBuildOn(){ return "Vælg en grund at bygge på."; } @Override public String noDemolitionableProperties(){ return "Du har ingen grunde hvor du kan nedrive bygninger."; } @Override public String choosePropertyToDemolishOn(){ return "Vælg den grund hvor du vil nedrive en bygning."; } @Override public String noTradeableProperties(){ return "Du har ingen felter at handle med."; } @Override public String choosePlotTrade(){ return "Vælg det felt du vil handle."; } @Override public String choosePropertyBuyer(){ return "Hvem køber feltet?"; } @Override public String enterTradePrice(){ return "Hvilken pris skal feltet sælges til?"; } @Override public String confirmTrade(){ return "Vil du bekræfte handlen?"; } @Override public String yes() { return "Ja!"; } @Override public String no() { return "Nej!"; } @Override public String noPawnableFields(){ return "Du har ingen felter at pantsætte."; } @Override public String choosePropertyToPawn(){ return "Vælg et felt at pantsætte."; } @Override public String pawnSuccessful(){ return "Din grund er blevet pantsat."; } @Override public String pawnUnsuccessful(){ return "Din grund kunne ikke pantsættes."; } @Override public String noPawnedProperties(){ return "Du har ingen felter at hæve pantsætningen på."; } @Override public String choosePropertyToUndoPawn(){ return "Vælg en grund at hæve pantsætningen på."; } @Override public String undoPawnSuccessful(){ return "Din pantsætning er blevet indfriet"; } @Override public String undoPawnUnsuccessful(){ return "Din pantsætning kunne ikke indfries"; } @Override public String buyingOfferMsg(int price) { return "Dette felt er ikke ejet af nogen, vil du købe det for " + price + " kr.?"; } @Override public String purchaseConfirmation() { return "Du har nu købt feltet!"; } @Override public String notEnoughMoney() { return "Du havde desværre ikke nok penge.."; } @Override public String enterAuctionPrice(){ return "Hvad blev auktionsprisen?"; } @Override public String confirmPurchase() { return "Vil du bekræfte købet?"; } @Override public String pawn(){ return "Pantsæt"; } @Override public String demolish(){ return "Nedriv bygninger"; } @Override public String bankrupt(){ return "Erklær konkurs"; } @Override public String toPay(int targetAmount){ return "Du skal betale " + targetAmount + "kr., men du har ikke penge nok. Hvad vil du gøre?"; } @Override public String canGetMoney(){ return "Du kan godt få nok penge, ved at nedrive bygninger og pantsætte ejendomme!"; } // ALL METHODS UNDER THIS LINE AREN'T USED IN THIS CURRENT VERSION OF THE GAME. @Override public String nonOwnableFieldEffectMsg(int fieldNumber) { String message = null; switch (fieldNumber) { case 0: message = "Du er passeret START og fÃ¥r 4.000 kr."; break; case 2: message = "Du landede på Prøv lykken og du skal tage et af chancekortene"; break; case 4: message = "Du landede på Skat feltet og skal betale 10% eller kr.4000"; break; case 7: message = "Du landede på Prøv lykken og du skal tage et af chancekortene"; break; case 10: message = "Du er på besøg i fængslet"; break; case 17: message = "Du landede på Prøv lykken og du skal tage et af chancekortene"; break; case 22: message = "Du landede på Prøv lykken og du skal tage et af chancekortene"; break; case 30: message = "Du landede på fængsel og skal går i fængsel"; break; case 33: message = "Du landede på Prøv lykken og du skal tage et af chancekortene"; break; case 36: message = "Du landede på Prøv lykken og du skal tage et af chancekortene"; break; case 38: message = "Du landede på Skat feltet og skal betale 10% eller kr.4000"; break; } return message; } @Override public String menu(){ return "Tast 1 for at skifte antal sider på terningerne.\n" + "Tast 2 for at ændre sprog.\n" + "Tast 3 for at vise scoren.\n"+ "Tast 4 for at afslutte spillet.\n" + "Tast 5 for at fortsætte spillet."; } @Override public String printRules(){ return "Dette spil er et terningespil mellem 2 personer. Du slår med terninger og lander på et felt fra 1-39. \n Her er vist listen over felterne: \n" + "1. Rødovrevej: 1200 kr. \n" + "2. Prøv lykken: \n" + "3. Hvidovrevej: 1200 kr. \n" + "4. Skat: 10% eller 4.000 kr. \n" + "5. SFL: 4000 kr. \n" + "6. Roskildevej: 2000 kr. \n" + "7. Prøv lykken: \n" + "8. Valby Langgade: 2000 kr. \n" + "9. Alløgade: 2400 kr. \n" + "10. Fængsel \n" + "11. Frederiksberg Alle: 2800 kr. \n" + "12. TUBORG: 3000 kr. \n" + "13. Bølowsvej: 4700 kr. \n" + "14. Gl. Kongevej: 3200 kr. \n" + "15. Kalundborg/ Århus: 4000 k. \n" + "16. Bernstorffsvej: 3600 kr. \n" + "17. Prøv lykken: \n" + "18. Hellerupvej: 3600 kr. \n" + "19. Strandvej: 4000 kr. \n" + "20. Parkering: Bank \n" + "21. Trianglen: 4400 kr. \n" + "22. Prøv lykken: \n" + "23. Østerbrogade: 4400 kr. \n" + "24. Grønningen: 4800 kr. \n" + "25. DFDS SEAWAYS: 4000 kr. \n" + "26. Bredgade: 5200 kr. \n" + "27. Kgs.Nytorv: 5200 kr. \n" + "28. CocaCola: 3000 kr. \n" + "29. Østergade: 5600 kr. \n" + "30. Fængsle: Fængsel \n" + "31. Amagertorv: 6000 kr. \n" + "32. Vimmelskaftet: 6000 kr. \n" + "33. Prøv lykken: \n" + "34. Nygade: 6400 kr. \n" + "35. Helsskov/ Knudshoved: 4000 kr. \n" + "36. Prøv lykken: \n" + "37. Frederiksberggade: 7000 kr. \n" + "38. Skat: 2000 kr. \n" + "39. Rådhuspladsen: 8000 kr. \n"; } @Override public String printScore(Player[] players){ StringBuilder str = new StringBuilder(); str.append("Stillingen er:"); for (int i = 0; i < players.length; i++) str.append("\n").append(players[i].getName()).append(" har ").append(players[i].getBankAccount().getBalance()); return str.toString(); } @Override public String changeDices(){ return "Indtast hvor mange øjne de to terninger skal have, på formatet \"x,y\" - summen skal være 12"; } @Override public String printDiceChangeSucces(){ return "Terningerne er nu ændret!"; } @Override public String printDiceChangeNotExecuted(){ return "Terningerne kunne ikke ændres"; } }
package info.ata4.io; import java.io.IOException; /** * Interface for IO classes that provide random access. * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public interface Seekable { /** * Seek to the specified position relative to an origin. * * @param where The position to seek to. * @param whence Origin point of the new position. * @throws IOException */ public void seek(long where, SeekOrigin whence) throws IOException; /** * Sets a new absolute position. * * @param where The position to seek to. * @throws IOException */ public void position(long where) throws IOException; /** * Obtain the current position. * * @return * @throws IOException */ public long position() throws IOException; /** * Returns the total capacity in bytes. * * @return * @throws IOException */ public long capacity() throws IOException; /** * Returns amount of remaining bytes that are available for reading or * writing. * * @return * @throws IOException */ public long remaining() throws IOException; /** * Return true if there are remaining bytes to read or write. * * @return * @throws IOException */ public boolean hasRemaining() throws IOException; }
package examples; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import kodkod.ast.Expression; import kodkod.ast.Formula; import kodkod.ast.IntConstant; import kodkod.ast.IntExpression; import kodkod.ast.Relation; import kodkod.ast.Variable; import kodkod.engine.Evaluator; import kodkod.engine.Solution; import kodkod.engine.Solver; import kodkod.engine.config.Options; import kodkod.engine.satlab.SATFactory; import kodkod.instance.Bounds; import kodkod.instance.Instance; import kodkod.instance.Tuple; import kodkod.instance.TupleFactory; import kodkod.instance.TupleSet; import kodkod.instance.Universe; import kodkod.util.ints.IntSet; import kodkod.util.ints.IntTreeSet; import kodkod.util.nodes.Nodes; import kodkod.util.nodes.PrettyPrinter; /** * Pure Kodkod encoding of the new test case for ConfigAssure. * @author Emina Torlak */ public final class ConfigAssure { /** * port is a unary relation that contains all the port atoms, represented * by concatenating the device name and the interface of each port. **/ private final Relation port; /** The addr relation maps port atoms to all the power-of-2 atoms (1, 2, 4, ..., 2^31). */ private final Relation addr; /** * The subnet relation maps one representative port atom in each subnet to all the other * port atoms in the same subnet. For example, the Prolog predicate subnet(['IOS_00037'-'Vlan790', 'IOS_00038'-'Vlan790']) * is represented by the tuples <'IOS_00037'-'Vlan790', 'IOS_00037'-'Vlan790'> and <'IOS_00037'-'Vlan790', 'IOS_00038'-'Vlan790'> * in the subnet relation. We arbitrarily chose the first atom in each Prolog predicate to be representative of * that subnet. This encoding assumes that each port can participate in at most one subnet. */ private final Relation subnet; /** * The group relation maps all atoms in each subnet that have the same interface * to one representative port atom. For example, the Prolog predicate subnet(['IOS_00091'-'Vlan820', 'IOS_00092'-'Vlan820', 'IOS_00096'-'FastEthernet0/0']) * is represented by the tuples <'IOS_00091'-'Vlan820', 'IOS_00091'-'Vlan820'>, <'IOS_00092'-'Vlan820', 'IOS_00091'-'Vlan820>, * and <'IOS_00096'-'FastEthernet0/0','IOS_00096'-'FastEthernet0/0'> * in the group relation. Ports that are not part of any subnet form their own group (of which they are a representative). */ private final Relation group; /** * The groupMask relation maps port atoms that are group representatives to the integer atoms 1, 2, 4, 8 and 16, implicitly * representing each group's mask by the number of zeros it contains [0..31]. **/ private final Relation groupMask; /** * Join of the group relation with the groupMask relation: provides an implicit mask for each port. */ private final Expression mask; private final IntConstant ones = IntConstant.constant(-1); private final static int minAddr = (121<<24) | (96<<16); private final static int maxAddr = minAddr | (255<<8) | 255; /** * Constructs a new instance of ConfigAssure. */ public ConfigAssure() { this.port = Relation.unary("port"); this.addr = Relation.binary("addr"); this.groupMask = Relation.binary("groupMask"); this.subnet = Relation.binary("subnet"); this.group = Relation.binary("group"); this.mask = group.join(groupMask); } /** * Returns the netID of the given port. * @return netID of the given port */ IntExpression netid(Expression p) { return addr(p).and(explicitMask(p)); } /** * Returns the ip address of the given port. * @return ip address of the given port */ IntExpression addr(Expression p) { return p.join(addr).sum(); } /** * Returns the number of zeros in the mask of the given port. * @return the number of zeros in the mask of the given port */ IntExpression implicitMask(Expression p) { return p.join(mask).sum(); } /** * Returns the explicit mask of the given port. * @return explicit mask of the given port */ IntExpression explicitMask(Expression p) { return ones.shl(implicitMask(p)); } /** * Returns the subnet of the given port. * @return subnet of the given port */ Expression subnet(Expression p) { return p.join(subnet); } /** * Returns a Formula that evaluates to true if the netid represented of the port p0 * contains the netid of the port p1. * @return zeros(p0) >= zeros(p1) and (addr(p0) & mask(p0)) = (addr(p1) & mask(p0)) */ Formula contains(Expression p0, Expression p1) { final Formula f0 = implicitMask(p0).gte(implicitMask(p1)); final Formula f1 = addr(p0).and(explicitMask(p0)).eq(addr(p1).and(explicitMask(p0))); return f0.and(f1); } /** * Returns the requirements. * @return requirements */ public Formula requirements () { final List<Formula> reqs = new ArrayList<Formula>(); final Variable p0 = Variable.unary("p0"), p1 = Variable.unary("p1"), p2 = Variable.unary("p2"); // the domain of the subnet expression contains all the representative atoms for each subnet final Expression subreps = subnet.join(port); // no two ports on the same subnet have the same address: // all p0: subreps, disj p1, p2: p0.subnet | addr(p1) != addr(p2) final Expression submembers = p0.join(subnet); reqs.add( p1.eq(p2).not().implies(addr(p1).eq(addr(p2)).not()). forAll(p0.oneOf(subreps).and(p1.oneOf(submembers)).and(p2.oneOf(submembers))) ); // all ports on the same subnet have the same netid: // all p0: subreps, p1: p0.subnet | netid(p0) = netid(p1) reqs.add( netid(p0).eq(netid(p1)). forAll(p0.oneOf(subreps).and(p1.oneOf(submembers))) ); // netids don't overlap: // all disj p0, p1: subreps | not contains(p0, p1) and not contains(p1, p0) reqs.add( p0.eq(p1).not().implies(contains(p0,p1).not().and(contains(p1, p0).not())). forAll(p0.oneOf(subreps).and(p1.oneOf(subreps)) )); return Nodes.and(reqs); } /** * Returns a new universe that contains the given ports atoms, followed by Integer objects * containing powers of 2 (1, 2, 4, ..., 2^31). */ private final Universe universe(Set<String> ports) { final List<Object> atoms = new ArrayList<Object>(ports.size() + 32); atoms.addAll(ports); for(int i = 0; i < 32; i++) { atoms.add(Integer.valueOf(1<<i)); } return new Universe(atoms); } public Bounds bounds(String ipAddrsFile, String subnetsFile) throws IOException { final Map<String, IPAddress> addresses = parseAddresses(ipAddrsFile); final Collection<Subnet> subnets = parseSubnets(subnetsFile, addresses); final Universe universe = universe(addresses.keySet()); final Bounds bounds = new Bounds(universe); final TupleFactory factory = universe.factory(); // bind the integers for(int i = 0; i < 32; i++) { bounds.boundExactly(1<<i, factory.setOf(Integer.valueOf(1<<i))); } // bind the port relation exactly to the port names bounds.boundExactly(port, factory.range(factory.tuple(1, 0), factory.tuple(1, addresses.keySet().size()-1))); // bind the subnet relation exactly, choosing the first element of each subnet as the representative final TupleSet subnetBound = factory.noneOf(2); for(Subnet sub : subnets) { final Iterator<IPAddress> itr = sub.members.iterator(); final String first = itr.next().port; subnetBound.add(factory.tuple(first, first)); while(itr.hasNext()) { subnetBound.add(factory.tuple(first, itr.next().port)); } } bounds.boundExactly(subnet, subnetBound); // bind the addr relation so that each address is guaranteed to be between minAddr (121.96.0.0) and maxAddr (121.96.255.255), inclusive final TupleSet lAddr = factory.noneOf(2), uAddr = factory.noneOf(2); for(IPAddress ad : addresses.values()) { if (ad.varAddress) { // unknown address for(int i = 0 ; i < 32; i++) { if ((minAddr & (1<<i))!=0) lAddr.add(factory.tuple(ad.port, Integer.valueOf(1<<i))); if ((maxAddr & (1<<i))!=0) uAddr.add(factory.tuple(ad.port, Integer.valueOf(1<<i))); } } else { // known address for(int i = 0 ; i < 32; i++) { if ((ad.address & (1<<i)) != 0) { final Tuple tuple = factory.tuple(ad.port, Integer.valueOf(1<<i)); lAddr.add(tuple); uAddr.add(tuple); } } } } bounds.bound(addr, lAddr, uAddr); // bind the group and groupMask relations so that all ports with the same interface on the same subnet are guaranteed to have the same mask final TupleSet lMask = factory.noneOf(2), uMask = factory.noneOf(2), groupBound = factory.noneOf(2); for(Subnet sub : subnets) { for(Set<IPAddress> subgroup : sub.groups.values()) { final Iterator<IPAddress> itr = subgroup.iterator(); final IPAddress first = itr.next(); addresses.remove(first.port); int maskVal = first.varMask ? -1 : first.mask; groupBound.add(factory.tuple(first.port, first.port)); while(itr.hasNext()) { final IPAddress next = itr.next(); addresses.remove(next.port); if (maskVal < 0 && !next.varMask) maskVal = next.mask; groupBound.add(factory.tuple(next.port, first.port)); } if (maskVal < 0) { // unknown (same) mask for this group for(int i = 0 ; i < 5; i++) { // need only 5 bits for the mask uMask.add(factory.tuple(first.port, Integer.valueOf(1<<i))); } } else { // known (same) mask for this group for(int i = 0 ; i < 5; i++) { // need to look at only low-order 5 bits for the mask if ((maskVal & (1<<i)) != 0) { final Tuple tuple = factory.tuple(first.port, Integer.valueOf(1<<i)); lMask.add(tuple); uMask.add(tuple); } } } } } // bind the group and groupMask relations for ports that are not a part of any subnet for(IPAddress ad : addresses.values()) { groupBound.add(factory.tuple(ad.port, ad.port)); if (ad.varMask) { // unknown (same) mask for this group for(int i = 0 ; i < 5; i++) { // need only 5 bits for the mask uMask.add(factory.tuple(ad.port, Integer.valueOf(1<<i))); } } else { // known (same) mask for this group for(int i = 0 ; i < 5; i++) { // need to look at only low-order 5 bits for the mask if ((ad.mask & (1<<i)) != 0) { final Tuple tuple = factory.tuple(ad.port, Integer.valueOf(1<<i)); lMask.add(tuple); uMask.add(tuple); } } } } bounds.bound(groupMask, lMask, uMask); bounds.boundExactly(group, groupBound); System.out.println("groupMask.size: " + uMask.size() + ", group.size: " + groupBound.size()); return bounds; } /** * Displays an instance obtained with the given options. * @requires inst != null and opt != null */ private final void display(Instance inst, Options opt) { final Universe univ = inst.universe(); final Evaluator eval = new Evaluator(inst, opt); final TupleFactory factory = univ.factory(); final List<TupleSet> subnets = new ArrayList<TupleSet>(); System.out.println(" for(int i = 0, ports = univ.size()-32; i < ports; i++) { final Object atom = univ.atom(i); final Relation p = Relation.unary(atom.toString()); inst.add(p, factory.setOf(atom)); System.out.print(p); System.out.print(": addr=" + eval.evaluate(addr(p))); System.out.print(", mask=" + eval.evaluate(implicitMask(p))); System.out.println(", netid=" + eval.evaluate(netid(p)) + "."); final TupleSet members = eval.evaluate(subnet(p)); if (!members.isEmpty()) subnets.add(members); } System.out.println(" for(TupleSet sub : subnets) { System.out.println(sub); } } private static void usage() { System.out.println("java examples.ConfigAssure <ipAddresses file> <subnets file>"); System.exit(1); } /** * Usage: java examples.ConfigAssure <ipAddresses file> <subnets file> */ public static void main(String[] args) { if (args.length < 2) usage(); try { final ConfigAssure ca = new ConfigAssure(); final Solver solver = new Solver(); solver.options().setBitwidth(32); solver.options().setSolver(SATFactory.MiniSat); final Formula formula = ca.requirements(); final Bounds bounds = ca.bounds(args[0], args[1]); System.out.println("requirements: "); System.out.println(PrettyPrinter.print(formula, 2)); System.out.println("solving with config files " + args[0] + " and " + args[1]); final Solution sol = solver.solve(formula, bounds); System.out.println(" System.out.println(sol.outcome()); System.out.println("\n System.out.println(sol.stats()); if (sol.instance() != null) { System.out.println("\n---INSTANCE--"); ca.display(sol.instance(), solver.options()); } } catch (IOException ioe) { ioe.printStackTrace(); usage(); } } /** * Parses the given ipAddresses file and returns a map that * binds each port name in the file to its corresponding IPAddress record. * @return a map that binds each port name in the given file to its corresponding IPAddress record. * @throws IOException */ private static Map<String, IPAddress> parseAddresses(String ipAddrsFile) throws IOException { final Map<String, IPAddress> addresses = new LinkedHashMap<String, IPAddress>(); final BufferedReader reader = new BufferedReader(new FileReader(new File(ipAddrsFile))); for(String line = reader.readLine(); line != null; line = reader.readLine()) { final IPAddress addr = new IPAddress(line); if (addresses.put(addr.port, addr) != null) throw new IllegalArgumentException("Duplicate ip address specification: " + line); } return addresses; } /** * Returns a grouping of the given IPAddresses into subnets according to the subnet information * in the given file. * @return a grouping of the given IPAddresses into subnets according to the subnet information * in the given file. * @throws IOException */ private static Collection<Subnet> parseSubnets(String subnetsFile, Map<String, IPAddress> addresses) throws IOException { final Collection<Subnet> subnets = new ArrayList<Subnet>(); final BufferedReader reader = new BufferedReader(new FileReader(new File(subnetsFile))); for(String line = reader.readLine(); line != null; line = reader.readLine()) { subnets.add(new Subnet(line, addresses)); } return subnets; } /** * A record containing the information parsed out of a * Prolog ipAddress predicate, e.g. ipAddress('IOS_00008', 'Vlan608', int(0), mask(1)). * @specfield device, interfaceName, port: String * @specfield varAddress, varMask: boolean // true if the address (resp. mask) are variables * @specfield address, mask: int // variable or constant identifier of the address or mask * @invariant port = device + "-" + port * @invariant !varAddress => (minAddr <= address <= maxAddr) * @invariant !varMask => (0 <= mask <= 31) * @author Emina Torlak */ private static class IPAddress { final String device, interfaceName, port; final boolean varAddress, varMask; final int address, mask; private static final Pattern pAddress = Pattern.compile("ipAddress\\((.+), (.+), (\\S+), (\\S+)\\)\\."); private static final Pattern pAddrVar = Pattern.compile("int\\((\\d+)\\)"); private static final Pattern pMaskVar = Pattern.compile("mask\\((\\d+)\\)"); private static final Matcher mAddress = pAddress.matcher(""); private static final Matcher mAddrVar = pAddrVar.matcher(""), mMaskVar = pMaskVar.matcher(""); /** * Constructs an IP address object using the provided ipAddress string. */ IPAddress(String addrString) { if (mAddress.reset(addrString).matches()) { this.device = mAddress.group(1); this.interfaceName = mAddress.group(2); this.port = device + "-" + interfaceName; if (mAddrVar.reset(mAddress.group(3)).matches()) { this.varAddress = true; this.address = Integer.parseInt(mAddrVar.group(1)); } else { this.varAddress = false; this.address = parseConstant(mAddress.group(3), minAddr, maxAddr, "Expected the address to be a variable spec, int(<number>), or a number between " + minAddr + " and " + maxAddr + ", inclusive: " + addrString); } if (mMaskVar.reset(mAddress.group(4)).matches()) { this.varMask = true; this.mask = Integer.parseInt(mMaskVar.group(1)); } else { this.varMask = false; this.mask = parseConstant(mAddress.group(4), 0, 31, "Expected the mask to be a variable spec, mask(<number>), or a number between 0 and 31, inclusive: " + addrString); } } else { throw new IllegalArgumentException("Unrecognized IP Address format: " + addrString); } } private static int parseConstant(String value, int min, int max, String msg) { try { final int val = Integer.parseInt(value); if (min <= val && val <= max) { return val; } } catch (NumberFormatException nfe) { } throw new IllegalArgumentException(msg); } } /** * A record containing the information parsed out of a * Prolog subnet predicate, e.g. subnet(['IOS_00091'-'Vlan820', 'IOS_00092'-'Vlan820', 'IOS_00096'-'FastEthernet0/0']). * @specfield member: some IPAddress // members of this subnet * @specfield groups: String -> member * @invariant groups = { s: String, a: IPAddress | a.interfaceName = s } * @invariant all i: member.interfaceName, m1, m2: groups[i] | (!m1.varMask and !m2.varMask) => m1.mask = m2.mask * @author Emina Torlak */ private static class Subnet { final Set<IPAddress> members; final Map<String, Set<IPAddress>> groups; private static final Pattern pSubnet = Pattern.compile("subnet\\(\\[(.+)\\]\\)\\."); private static final Pattern pSubMember = Pattern.compile(",*\\s*([^,]+)"); private static final Matcher mSubnet = pSubnet.matcher(""), mSubMember = pSubMember.matcher(""); /** * Constructs a subnet object out of the given subnet string and addresses. */ Subnet(String subnetString, Map<String, IPAddress> addresses) { this.members = members(subnetString, addresses); this.groups = groups(subnetString, members); } /** * Returns the subnet members specified by the given subnet string. * @return subnet members specified by the given subnet string. */ private static Set<IPAddress> members(String subnetString, Map<String, IPAddress> addresses) { if (mSubnet.reset(subnetString).matches()) { final Set<IPAddress> members = new LinkedHashSet<IPAddress>(); mSubMember.reset(mSubnet.group(1)); while(mSubMember.find()) { final String port = mSubMember.group(1); if (addresses.containsKey(port)) { members.add(addresses.get(port)); } else { throw new IllegalArgumentException("Unrecognized port " + port + " in " + subnetString); } } if (members.isEmpty()) { throw new IllegalArgumentException("Subnet spec is empty: " + subnetString); } return Collections.unmodifiableSet(members); } else { throw new IllegalArgumentException("Unrecognized subnet format: " + subnetString); } } /** * Returns a grouping of the given subnet members according to their interface names. * @return a grouping of the given subnet members according to their interface names. */ private static Map<String, Set<IPAddress>> groups(String subnetString, Set<IPAddress> members) { final Map<String, Set<IPAddress>> groups = new LinkedHashMap<String, Set<IPAddress>>(); for(IPAddress addr : members) { Set<IPAddress> group = groups.get(addr.interfaceName); if (group == null) { group = new LinkedHashSet<IPAddress>(); groups.put(addr.interfaceName, group); } group.add(addr); } for(Map.Entry<String, Set<IPAddress>> entry : groups.entrySet()) { final Set<IPAddress> group = entry.getValue(); final IntSet masks = new IntTreeSet(); for(IPAddress addr : group) { if (!addr.varMask) { masks.add(addr.mask); } } if (masks.size()>1) throw new IllegalArgumentException("All members of a subnet with the same interface must have the same mask: " + subnetString); entry.setValue(Collections.unmodifiableSet(group)); } return Collections.unmodifiableMap(groups); } } }
package org.usfirst.frc2811.RecycleRush.subsystems; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.networktables.NetworkTable; import edu.wpi.first.wpilibj.tables.TableKeyNotDefinedException; public class NetTables extends Subsystem { static double x; static double y; public NetTables(){ } public static void update(){ //put code here NetworkTable server = NetworkTable.getTable("SmartDashboard"); try{ x = server.getNumber("COG_X", 000); y = server.getNumber("COG_Y", 000); }catch(TableKeyNotDefinedException ex) { y=-1; x=-1; } //set x //set y } @Override protected void initDefaultCommand() { // TODO Auto-generated method stub } public static double getX(){ update(); return x; } public static double getY(){ update(); return y; } }
package com.matt.forgehax.util.draw; import com.matt.forgehax.util.Utils; import net.minecraft.client.renderer.GlStateManager; import uk.co.hexeption.thx.ttf.MinecraftFontRenderer; import static com.matt.forgehax.Globals.MC; import static org.lwjgl.opengl.GL11.*; public class SurfaceBuilder { private static final double[] EMPTY_VECTOR3D = new double[] {0.D, 0.D, 0.D}; private static final double[] EMPTY_VECTOR4D = new double[] {0.D, 0.D, 0.D, 0.D}; private static final SurfaceBuilder INSTANCE = new SurfaceBuilder(); public static SurfaceBuilder getBuilder() { return INSTANCE; } private double[] color4d = EMPTY_VECTOR4D; // 0-3 = rgba private double[] scale3d = EMPTY_VECTOR3D; // 0-2 = xyz private double[] translate3d = EMPTY_VECTOR3D; // 0-2 = xyz private double[] rotated4d = EMPTY_VECTOR4D; // 0 = angle, 1-3 = xyz private MinecraftFontRenderer fontRenderer = null; public SurfaceBuilder begin(int mode) { glBegin(mode); return this; } public SurfaceBuilder beginLines() { return begin(GL_LINES); } public SurfaceBuilder beginLineLoop() { return begin(GL_LINE_LOOP); } public SurfaceBuilder beginQuads() { return begin(GL_QUADS); } public SurfaceBuilder beginPolygon() { return begin(GL_POLYGON); } public SurfaceBuilder end() { glEnd(); return this; } public SurfaceBuilder apply() { if(color4d != EMPTY_VECTOR4D) glColor4d(color4d[0], color4d[1], color4d[2], color4d[3]); if(scale3d != EMPTY_VECTOR3D) glScaled(scale3d[0], scale3d[1], scale3d[2]); if(translate3d != EMPTY_VECTOR3D) glTranslated(translate3d[0], translate3d[1], translate3d[2]); if(rotated4d != EMPTY_VECTOR4D) glRotated(rotated4d[0], rotated4d[1], rotated4d[2], rotated4d[3]); return this; } public SurfaceBuilder unapply() { color4d = EMPTY_VECTOR4D; scale3d = EMPTY_VECTOR3D; translate3d = EMPTY_VECTOR3D; rotated4d = EMPTY_VECTOR4D; fontRenderer = null; return this; } public SurfaceBuilder push() { GlStateManager.pushMatrix(); apply(); return this; } public SurfaceBuilder pop() { GlStateManager.popMatrix(); unapply(); return this; } public SurfaceBuilder color(double r, double g, double b, double a) { color4d = new double[] {r, g, b, a}; return this; } public SurfaceBuilder color(int buffer) { return color( (buffer >> 16 & 255) / 255.D, (buffer >> 8 & 255) / 255.D, (buffer & 255) / 255.D, (buffer >> 24 & 255) / 255.D ); } public SurfaceBuilder color(int r, int g, int b, int a) { return color(r / 255.D, g / 255.D, b / 255.D, a / 255.D); } public SurfaceBuilder scale(double x, double y, double z) { scale3d = new double[] {Math.max(x, 0), Math.max(y, 0), Math.max(z, 0)}; return this; } public SurfaceBuilder scale(double s) { return scale(s, s, s); } public SurfaceBuilder scale() { return scale(0.D); } public SurfaceBuilder translate(double x, double y, double z) { translate3d = new double[] {x, y, z}; return this; } public SurfaceBuilder rotate(double angle, double x, double y, double z) { rotated4d = new double[] {angle, x, y, z}; return this; } public SurfaceBuilder width(double width) { GlStateManager.glLineWidth((float) width); return this; } public SurfaceBuilder vertex(double x, double y, double z) { glVertex3d(x, y, z); return this; } public SurfaceBuilder vertex(double x, double y) { return vertex(x, y, 0.D); } public SurfaceBuilder line(double startX, double startY, double endX, double endY) { return vertex(startX, startY) .vertex(endX, endY); } public SurfaceBuilder rectangle(double x, double y, double w, double h) { return vertex(x, y) .vertex(x, y + h) .vertex(x + w, y + h) .vertex(x + w, y); } public SurfaceBuilder fontRenderer(MinecraftFontRenderer fontRenderer) { this.fontRenderer = fontRenderer; return this; } private SurfaceBuilder text(String text, double x, double y, boolean shadow) { if(this.fontRenderer != null) // use custom font renderer this.fontRenderer.drawString(text, x, y, Utils.toRGBA(color4d), shadow); else // use default minecraft font MC.fontRenderer.drawString(text, Math.round(x), Math.round(y), Utils.toRGBA(color4d), shadow); return this; } public SurfaceBuilder text(String text, double x, double y) { return text(text, x, y, false); } public SurfaceBuilder textWithShadow(String text, double x, double y) { return text(text, x, y, true); } public SurfaceBuilder task(Runnable task) { task.run(); return this; } public int getFontWidth(String text) { return fontRenderer != null ? fontRenderer.getStringWidth(text) : MC.fontRenderer.getStringWidth(text); } public int getFontHeight() { return fontRenderer != null ? fontRenderer.getHeight() : MC.fontRenderer.FONT_HEIGHT; } public int getFontHeight(String text) { return getFontHeight(); } public static void preRenderSetup() { GlStateManager.enableBlend(); GlStateManager.disableTexture2D(); GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); } public static void postRenderSetup() { GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); } }
package com.miviclin.collections; import java.util.AbstractQueue; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /** * This queue is implemented as a linked list with a pool of nodes. The main difference is that this queue has a pool of * nodes, so it does not need to create new nodes if there are nodes available in the pool.<br> * This queue does not allow null objects. * * @author Miguel Vicente Linares * * @param <E> */ public class PooledLinkedQueue<E> extends AbstractQueue<E> { private Node<E> head; private Node<E> tail; private int size; private ArrayList<Node<E>> nodePool; /** * Creates a new PooledLinkedQueue with 10 pooled nodes. */ public PooledLinkedQueue() { this(10); } /** * Creates a new PooledLinkedQueue with the specified initial number of pooled nodes. * * @param initialNumPooledNodes Initial number of pooled nodes. */ public PooledLinkedQueue(int initialNumPooledNodes) { super(); this.head = null; this.tail = null; this.size = 0; this.nodePool = new ArrayList<>(initialNumPooledNodes); for (int i = 0; i < initialNumPooledNodes; i++) { this.nodePool.add(new Node<E>()); } } /** * Creates a new PooledLinkedQueue filled with the specified collection and 0 pooled nodes. * * @param collection Collection. */ public PooledLinkedQueue(Collection<E> collection) { this(0, collection); } /** * Creates a new PooledLinkedQueue filled with the specified collection and the specified initial number of pooled * nodes. * * @param initialNumPooledNodes Initial number of pooled nodes. After the collection is added to the queue, the * specified amount of pooled nodes will be available for later insertions. * @param collection Collection. */ public PooledLinkedQueue(int initialNumPooledNodes, Collection<E> collection) { this(initialNumPooledNodes + collection.size()); addAll(collection); } @Override public boolean offer(E e) { if (e == null) { throw new NullPointerException(); } Node<E> node = obtainNode(); node.setItem(e); if (size == 0) { head = node; } if (tail != null) { tail.setNextNode(node); } node.setPreviousNode(tail); tail = node; size++; return true; } @Override public E poll() { if (head == null) { return null; } if (head == tail) { tail = null; } E removedItem = removeHead(); if (removedItem != null) { size } return removedItem; } @Override public E peek() { if (head == null) { return null; } return head.getItem(); } @Override public Iterator<E> iterator() { return new PooledLinkedQueueIterator(); } @Override public int size() { return size; } /** * Returns a node from the pool if possible. If the pool is empty, creates a new node and returns it. * * @return Node */ private Node<E> obtainNode() { if (nodePool.size() == 0) { return new Node<E>(); } int index = nodePool.size() - 1; return nodePool.remove(index); } /** * Resets the specified node and stores it in the pool for later use. * * @param node Node. */ private void recycleNode(Node<E> node) { node.reset(); nodePool.add(node); } /** * Removes the head node and recycles it. * * @return Item of the removed head. */ private E removeHead() { Node<E> previousHead = head; head = head.getNextNode(); if (head != null) { head.setPreviousNode(null); } E item = previousHead.getItem(); recycleNode(previousHead); return item; } /** * Node. * * @author Miguel Vicente Linares * * @param <E> */ private static class Node<E> { private E item; private Node<E> nextNode; private Node<E> previousNode; /** * Creates a new Node. */ public Node() { reset(); } /** * Resets the item, nextNode and previousNode to null. */ void reset() { this.item = null; this.nextNode = null; this.previousNode = null; } /** * Returns the item of this Node. * * @return The item of this Node. */ public E getItem() { return item; } /** * Sets the item of this Node. * * @param item New value. */ public void setItem(E item) { this.item = item; } /** * Returns the next Node. * * @return Next Node */ public Node<E> getNextNode() { return nextNode; } /** * Sets the next Node. * * @param nextNode New value. */ public void setNextNode(Node<E> nextNode) { this.nextNode = nextNode; } /** * Returns the previous Node. * * @return Previous Node */ public Node<E> getPreviousNode() { return previousNode; } /** * Sets the previous Node. * * @param previousNode New value. */ public void setPreviousNode(Node<E> previousNode) { this.previousNode = previousNode; } } /** * Iterator for PooledLinkedQueue. * * @author Miguel Vicente Linares */ private class PooledLinkedQueueIterator implements Iterator<E> { private Node<E> lastReturnedNode; private Node<E> nextNode; private boolean allowRemove; /** * Creates a new PooledLinkedQueueIterator. */ public PooledLinkedQueueIterator() { this.lastReturnedNode = null; this.nextNode = head; this.allowRemove = false; } @Override public boolean hasNext() { return nextNode != null; } @Override public E next() { E currentItem = nextNode.getItem(); lastReturnedNode = nextNode; nextNode = nextNode.getNextNode(); allowRemove = true; return currentItem; } @Override public void remove() { if (lastReturnedNode == null) { return; } if (!allowRemove) { throw new IllegalStateException("The next method has not yet been called, or the remove method has " + "already been called after the last call to the next method"); } Node<E> previousLastReturnedNode = lastReturnedNode; lastReturnedNode = lastReturnedNode.getPreviousNode(); if (nextNode != null) { nextNode.setPreviousNode(lastReturnedNode); } recycleNode(previousLastReturnedNode); size allowRemove = false; } } }
package com.primetoxinz.stacksonstacks; import mcmultipart.block.TileMultipartContainer; import mcmultipart.multipart.IMultipart; import mcmultipart.multipart.IMultipartContainer; import mcmultipart.multipart.MultipartHelper; import mcmultipart.multipart.MultipartRegistry; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.VertexBuffer; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.util.text.TextComponentString; import net.minecraft.world.World; import net.minecraftforge.client.event.DrawBlockHighlightEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import net.minecraftforge.oredict.OreDictionary; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.UUID; import static mcmultipart.multipart.MultipartHelper.getPartContainer; import static net.minecraft.util.EnumActionResult.*; public class IngotPlacer { @SubscribeEvent(priority = EventPriority.HIGH) @SideOnly(Side.CLIENT) public final void onDrawBlockHighlight(DrawBlockHighlightEvent event) { EntityPlayer player = event.getPlayer(); ItemStack main = player.getHeldItemMainhand(); ItemStack off = player.getHeldItemOffhand(); BlockPos pos = event.getTarget().getBlockPos(); float partialTicks = event.getPartialTicks(); if (canBeIngot(main) || canBeIngot(off)) { drawSelectionBox(player, event.getTarget(), 0, partialTicks); } } private double round(double num, double r) { return ((int) (num * (int) (r))) / r; } private double relativePos(double x) { double pos = ((x > 0) ? Math.floor(x): Math.ceil(x)); return Math.abs(x - pos); } private IngotLocation getPositionFromHit(Vec3d hit, BlockPos pos,EntityPlayer player) { double x = round(hit.xCoord, 2); System.out.println(hit.xCoord+","+x); double y = round(hit.yCoord, 8); double z = round(hit.zCoord, 4); IngotLocation loc = new IngotLocation(relativePos(x), relativePos(y), relativePos(z), player.getHorizontalFacing().getAxis()); return loc; } private boolean canBeIngot(ItemStack stack) { if (stack == null) return false; int[] ids = OreDictionary.getOreIDs(stack); for(int id: ids) { String name = OreDictionary.getOreName(id); if(name.startsWith("ingot")) { return true; } } return stack.getUnlocalizedName().contains("ingot"); } @SubscribeEvent(priority = EventPriority.HIGH) public void placeIngot(PlayerInteractEvent.RightClickBlock e) { if (e.getSide().isClient()) return; onItemUse(e.getItemStack(), e.getEntityPlayer(), e.getWorld(), e.getPos(), e.getHand(), e.getFace(), e.getHitVec()); } public boolean canAddPart(World world, BlockPos pos, PartIngot ingot) { IMultipartContainer container = getPartContainer(world, pos); if (container == null) { List<AxisAlignedBB> list = new ArrayList<AxisAlignedBB>(); for (AxisAlignedBB bb : list) if (!world.checkNoEntityCollision(bb.offset(pos.getX(), pos.getY(), pos.getZ()))) return false; Collection<? extends IMultipart> parts = MultipartRegistry.convert(world, pos, true); if (parts != null && !parts.isEmpty()) { TileMultipartContainer tmp = new TileMultipartContainer(); for (IMultipart p : parts) tmp.getPartContainer().addPart(p, false, false, false, false, UUID.randomUUID()); return tmp.canAddPart(ingot); } return true; } else { for (IMultipart part : container.getParts()) { if (part instanceof PartIngot) { PartIngot i = (PartIngot) part; if (i.getLocation().equals(ingot)) { System.out.println("equals"); return false; } } } return container.canAddPart(ingot); } } private EnumActionResult onItemUse(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing side, Vec3d hit) { if (canBeIngot(stack) && player.canPlayerEdit(pos, side, stack)) { if (player.isSneaking()) { int i = 0; while (stack.stackSize > 0) { if (i > 64) break; System.out.println(stack.stackSize); Vec3d newHit = new Vec3d(0, 0, 0); if (place(world, pos, side, newHit, stack, player)) if (!player.isCreative()) consumeItem(stack); i++; } return SUCCESS; } else { if (place(world, pos, side, hit, stack, player)) { if (!player.isCreative()) consumeItem(stack); return SUCCESS; } } return PASS; } return FAIL; } private boolean place(World world, BlockPos pos, EnumFacing side, Vec3d hit, ItemStack stack, EntityPlayer player) { if (side != EnumFacing.UP) return false; if (MultipartHelper.getPartContainer(world, pos) == null) { pos = pos.offset(side); } else { IngotLocation location = getPositionFromHit(hit, pos,player); player.addChatComponentMessage(new TextComponentString(location.toString())); if (location.getRelativeLocation().getY() == 0) { pos = pos.offset(side); } } IngotLocation location = getPositionFromHit(hit, pos,player); PartIngot part = new PartIngot(location, new IngotType(stack)); if (canAddPart(world, pos, part)) { if (!world.isRemote) { try {MultipartHelper.addPart(world, pos, part);}catch(NullPointerException e){} } SoundType sound = SoundType.METAL; if (sound != null) world.playSound(player, pos, sound.getPlaceSound(), SoundCategory.BLOCKS, sound.getVolume(), sound.getPitch()); return true; } return false; } private void consumeItem(ItemStack stack) { stack.stackSize } public static void drawSelectionBox(EntityPlayer player, RayTraceResult movingObjectPositionIn, int execute, float partialTicks) { World world = player.getEntityWorld(); if (execute == 0 && movingObjectPositionIn.typeOfHit == RayTraceResult.Type.BLOCK) { GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO); GlStateManager.color(0.0F, 0.0F, 0.0F, 0.4F); GlStateManager.glLineWidth(2.0F); GlStateManager.disableTexture2D(); GlStateManager.depthMask(false); BlockPos pos = movingObjectPositionIn.getBlockPos(); IBlockState state = world.getBlockState(pos); EnumFacing.Axis facing = player.getHorizontalFacing().getAxis(); if (state.getMaterial() != Material.AIR && world.getWorldBorder().contains(pos)) { double d0 = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) partialTicks; double d1 = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) partialTicks; double d2 = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) partialTicks; AxisAlignedBB block = state.getSelectedBoundingBox(world, pos); double x = pos.getX(), y = (block.maxY), z = pos.getZ(); AxisAlignedBB box; for (int i = 1; i <= 4; i++) { for(int j=1;j<=2;j++) { if (facing == EnumFacing.Axis.Z) { box = new AxisAlignedBB(x + (i / 4d) - .25, y, z + (.5 * (j - 1)), x + (i / 4d), y,z + j * .5 ).expandXyz(.002d).offset(-d0, -d1, -d2); } else { box = new AxisAlignedBB(x + (.5 * (j - 1)), y, z + (i / 4d) - .25, x + j * .5, y, z + (i / 4d)).expandXyz(.002d).offset(-d0, -d1, -d2); } drawLine(box); } } } GlStateManager.depthMask(true); GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); } } public static void drawLine(AxisAlignedBB boundingBox) { Tessellator tessellator = Tessellator.getInstance(); VertexBuffer vertexbuffer = tessellator.getBuffer(); vertexbuffer.begin(3, DefaultVertexFormats.POSITION); vertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex(); vertexbuffer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).endVertex(); vertexbuffer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).endVertex(); vertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).endVertex(); vertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex(); tessellator.draw(); } }
package sulfur; import sulfur.configs.SEnvConfig; import sulfur.configs.SPageConfig; import sulfur.factories.SEnvConfigFactory; import sulfur.factories.SPageConfigFactory; import sulfur.utils.SDataProviderUtils; import org.testng.annotations.AfterMethod; import org.testng.annotations.DataProvider; import java.util.*; /** * @author Ivan De Marino */ abstract public class SBaseTest { private List<SPage> mPagesToDisposeAfterTest = new ArrayList<SPage>(); /** * Utility method to ensure, even on test failure, the SPage object is correctly closed (i.e. "driver.quit()" is invoked). * * @see SBaseTest#disposePagesAfterTestMethod() * @param page SPage to dispose after the test. */ protected SPage disposeAfterTestMethod(SPage page) { mPagesToDisposeAfterTest.add(page); return page; } @AfterMethod protected void disposePagesAfterTestMethod() { for (SPage p : mPagesToDisposeAfterTest) { p.dispose(); } } /** * Factory method to create an SPage that is already .open() AND registered via {@link SBaseTest#disposeAfterTestMethod(SPage)}. * Use this method when you know you don't need to set anything extra on the page before "opening" it. * * @param envConfig Sulfur Environment Configuration * @param driverName Name of the WebDriver you want to use (see {@link sulfur.factories.SWebDriverFactory}) * @param pageConfig Page Configuration * @param pathParams Map of Path Parameters to use * @param queryParams Map of Query Parameters to use * @return Newly created SPage, already open and registered for self disposal */ protected SPage createOpenAndSelfDisposingPage(SEnvConfig envConfig, String driverName, SPageConfig pageConfig, Map<String, String> pathParams, Map<String, String> queryParams) { return disposeAfterTestMethod( new SPage(envConfig, driverName, pageConfig, pathParams, queryParams)).open(); } /** * See {@link SBaseTest#createOpenAndSelfDisposingPage(sulfur.configs.SEnvConfig, String, sulfur.configs.SPageConfig, java.util.Map, java.util.Map)}. * * @param envName * @param driverName * @param pageName * @param pathParams * @param queryParams * @return Newly created SPage, already open and registered for self disposal */ protected SPage createOpenAndSelfDisposingPage(String envName, String driverName, String pageName, Map<String, String> pathParams, Map<String, String> queryParams) { SEnvConfig envConfig = SEnvConfigFactory.getInstance().getEnvConfig(envName); SPageConfig pageConfig = SPageConfigFactory.getInstance().getPageConfig(pageName); return createOpenAndSelfDisposingPage(envConfig, driverName, pageConfig, pathParams, queryParams); } /** * DataProvider of all the Page Configs found by the SPageConfigFactory. * Name of the DataProvider is "provideConfiguredPageConfigs" * * @return DataProvider bi-dimensional array with list of all Page Configs (SPageConfig) that were found */ @DataProvider(name = "provideConfiguredPageConfigs") protected Object[][] provideConfiguredPageConfigs() { List<Object[]> pageConfigs = new ArrayList<Object[]>(); for (SPageConfig pageConfig : SPageConfigFactory.getInstance().getPageConfigs().values()) { pageConfigs.add(new Object[]{ pageConfig }); } return pageConfigs.toArray(new Object[pageConfigs.size()][]); } /** * DataProvider of all the Env Configs found by the SEnvConfigFactory. * Name of the DataProvider is "provideConfiguredEnvConfigs" * * @return DataProvider bi-dimensional array with list of all Env Configs (SEnvConfigs) that were found */ @DataProvider(name = "provideConfiguredEnvConfigs") public Object[][] provideConfiguredEnvConfigs() { List<Object[]> envConfigs = new ArrayList<Object[]>(); for (SEnvConfig envConfig : SEnvConfigFactory.getInstance().getEnvConfigs().values()) { envConfigs.add(new Object[] { envConfig }); } return envConfigs.toArray(new Object[envConfigs.size()][]); } /** * Returns DataProvider-friendly dataset of Driver Names (based on Sulfur Configuration). * It's ideal to be used to implement a DataProvider for a specific SEnvConfig. * * @return DataProvider bi-dimensional array with list of Drivers to use for the test */ protected Object[][] provideDriverNamesByEnvConfig(SEnvConfig envConfig) { List<Object[]> driverNames = new ArrayList<Object[]>(); for (String configuredDriverName : envConfig.getDrivers()) { driverNames.add(new Object[]{configuredDriverName}); } return driverNames.toArray(new Object[driverNames.size()][]); } /** * Comodity method that delegates SDataProviderUtils to create Cartesian Products of @DataProvider * * @see sulfur.utils.SDataProviderUtils#cartesianProvider(Object[][]...) * @param providersData vararg of @DataProvider results * @return A @DataProvider iterator, ready to use */ protected Iterator<Object[]> makeCartesianProvider(Object[][]...providersData) { return SDataProviderUtils.cartesianProvider(providersData); } /** * Comodity method that delegates SDataProviderUtils to create Cartesian Products of @DataProvider * * @see sulfur.utils.SDataProviderUtils#cartesianProvider(java.util.List) * @param providersData List of @DataProvider results * @return A @DataProvider iterator, ready to use */ protected Iterator<Object[]> makeCartesianProvider(List<Object[][]> providersData) { return SDataProviderUtils.cartesianProvider(providersData); } }
package com.raoulvdberge.refinedstorage.api; import com.raoulvdberge.refinedstorage.api.autocrafting.craftingmonitor.ICraftingMonitorElementList; import com.raoulvdberge.refinedstorage.api.autocrafting.craftingmonitor.ICraftingMonitorElementRegistry; import com.raoulvdberge.refinedstorage.api.autocrafting.preview.ICraftingPreviewElementRegistry; import com.raoulvdberge.refinedstorage.api.autocrafting.registry.ICraftingTaskRegistry; import com.raoulvdberge.refinedstorage.api.network.INetworkMaster; import com.raoulvdberge.refinedstorage.api.network.readerwriter.IReaderWriterChannel; import com.raoulvdberge.refinedstorage.api.network.readerwriter.IReaderWriterHandlerRegistry; import com.raoulvdberge.refinedstorage.api.solderer.ISoldererRegistry; import com.raoulvdberge.refinedstorage.api.util.IComparer; import com.raoulvdberge.refinedstorage.api.util.IStackList; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fluids.FluidStack; import javax.annotation.Nonnull; /** * Represents a Refined Storage API implementation. * Delivered by the {@link RSAPIInject} annotation. */ public interface IRSAPI { /** * @return the comparer */ @Nonnull IComparer getComparer(); /** * @return the solderer registry */ @Nonnull ISoldererRegistry getSoldererRegistry(); /** * @return the crafting task registry */ @Nonnull ICraftingTaskRegistry getCraftingTaskRegistry(); /** * @return the crafting monitor element registry */ @Nonnull ICraftingMonitorElementRegistry getCraftingMonitorElementRegistry(); /** * @return the crafting preview element registry */ @Nonnull ICraftingPreviewElementRegistry getCraftingPreviewElementRegistry(); /** * @return the reader writer handler registry */ @Nonnull IReaderWriterHandlerRegistry getReaderWriterHandlerRegistry(); /** * @return a new reader writer channel */ @Nonnull IReaderWriterChannel createReaderWriterChannel(String name, INetworkMaster network); /** * @return an empty item stack list */ @Nonnull IStackList<ItemStack> createItemStackList(); /** * @return an empty fluid stack list */ @Nonnull IStackList<FluidStack> createFluidStackList(); /** * @return an empty crafting monitor element list */ @Nonnull ICraftingMonitorElementList createCraftingMonitorElementList(); /** * Notifies the neighbors of a node that there is a node placed at the given position. * * @param world the world * @param pos the position of the node */ void discoverNode(World world, BlockPos pos); /** * @param stack the stack * @return a hashcode for the given stack */ int getItemStackHashCode(ItemStack stack); /** * @param stack the stack * @return a hashcode for the given stack */ int getFluidStackHashCode(FluidStack stack); }
package org.postgresql.test.jdbc4; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.postgresql.core.ServerVersion; import org.postgresql.geometric.PGbox; import org.postgresql.jdbc.PgConnection; import org.postgresql.jdbc.PreferQueryMode; import org.postgresql.test.TestUtil; import org.postgresql.test.jdbc2.BaseTest4; import org.postgresql.test.util.RegexMatcher; import org.postgresql.util.PGobject; import org.postgresql.util.PGtokenizer; import org.junit.Assert; import org.junit.Assume; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.sql.Array; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.UUID; @RunWith(Parameterized.class) public class ArrayTest extends BaseTest4 { private Connection conn; public ArrayTest(BinaryMode binaryMode) { setBinaryMode(binaryMode); } @Parameterized.Parameters(name = "binary = {0}") public static Iterable<Object[]> data() { Collection<Object[]> ids = new ArrayList<Object[]>(); for (BinaryMode binaryMode : BinaryMode.values()) { ids.add(new Object[]{binaryMode}); } return ids; } @Override public void setUp() throws Exception { super.setUp(); conn = con; TestUtil.createTable(conn, "arrtest", "intarr int[], decarr decimal(2,1)[], strarr text[]" + (TestUtil.haveMinimumServerVersion(conn, ServerVersion.v8_3) ? ", uuidarr uuid[]" : "") + ", floatarr float8[]" + ", intarr2 int4[][]"); TestUtil.createTable(conn, "arrcompprnttest", "id serial, name character(10)"); TestUtil.createTable(conn, "arrcompchldttest", "id serial, name character(10), description character varying, parent integer"); TestUtil.createTable(conn, "\"CorrectCasing\"", "id serial"); TestUtil.createTable(conn, "\"Evil.Table\"", "id serial"); } @Override public void tearDown() throws SQLException { TestUtil.dropTable(conn, "arrtest"); TestUtil.dropTable(conn, "arrcompprnttest"); TestUtil.dropTable(conn, "arrcompchldttest"); TestUtil.dropTable(conn, "\"CorrectCasing\""); super.tearDown(); } @Test public void testCreateArrayOfBool() throws SQLException { PreparedStatement pstmt = conn.prepareStatement("SELECT ?::bool[]"); pstmt.setArray(1, conn.unwrap(PgConnection.class).createArrayOf("boolean", new boolean[] { true, true, false })); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); Boolean[] out = (Boolean[]) arr.getArray(); Assert.assertEquals(3, out.length); Assert.assertEquals(Boolean.TRUE, out[0]); Assert.assertEquals(Boolean.TRUE, out[1]); Assert.assertEquals(Boolean.FALSE, out[2]); } @Test public void testCreateArrayOfInt() throws SQLException { PreparedStatement pstmt = conn.prepareStatement("SELECT ?::int[]"); Integer[] in = new Integer[3]; in[0] = 0; in[1] = -1; in[2] = 2; pstmt.setArray(1, conn.createArrayOf("int4", in)); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); Integer[] out = (Integer[]) arr.getArray(); Assert.assertEquals(3, out.length); Assert.assertEquals(0, out[0].intValue()); Assert.assertEquals(-1, out[1].intValue()); Assert.assertEquals(2, out[2].intValue()); } @Test public void testCreateArrayOfBytes() throws SQLException { PreparedStatement pstmt = conn.prepareStatement("SELECT ?::bytea[]"); final byte[][] in = new byte[][] { { 0x01, (byte) 0xFF, (byte) 0x12 }, {}, { (byte) 0xAC, (byte) 0xE4 }, null }; final Array createdArray = conn.createArrayOf("bytea", in); byte[][] inCopy = (byte[][]) createdArray.getArray(); Assert.assertEquals(4, inCopy.length); Assert.assertArrayEquals(in[0], inCopy[0]); Assert.assertArrayEquals(in[1], inCopy[1]); Assert.assertArrayEquals(in[2], inCopy[2]); Assert.assertArrayEquals(in[3], inCopy[3]); Assert.assertNull(inCopy[3]); pstmt.setArray(1, createdArray); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); byte[][] out = (byte[][]) arr.getArray(); Assert.assertEquals(4, out.length); Assert.assertArrayEquals(in[0], out[0]); Assert.assertArrayEquals(in[1], out[1]); Assert.assertArrayEquals(in[2], out[2]); Assert.assertArrayEquals(in[3], out[3]); Assert.assertNull(out[3]); } @Test public void testCreateArrayOfBytesFromString() throws SQLException { assumeMinimumServerVersion("support for bytea[] as string requires hex string support from 9.0", ServerVersion.v9_0); PreparedStatement pstmt = conn.prepareStatement("SELECT ?::bytea[]"); final byte[][] in = new byte[][] { { 0x01, (byte) 0xFF, (byte) 0x12 }, {}, { (byte) 0xAC, (byte) 0xE4 }, null }; pstmt.setString(1, "{\"\\\\x01ff12\",\"\\\\x\",\"\\\\xace4\",NULL}"); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); byte[][] out = (byte[][]) arr.getArray(); Assert.assertEquals(4, out.length); Assert.assertArrayEquals(in[0], out[0]); Assert.assertArrayEquals(in[1], out[1]); Assert.assertArrayEquals(in[2], out[2]); Assert.assertArrayEquals(in[3], out[3]); Assert.assertNull(out[3]); } @Test public void testCreateArrayOfSmallInt() throws SQLException { PreparedStatement pstmt = conn.prepareStatement("SELECT ?::smallint[]"); Short[] in = new Short[3]; in[0] = 0; in[1] = -1; in[2] = 2; pstmt.setArray(1, conn.createArrayOf("int2", in)); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); Short[] out = (Short[]) arr.getArray(); Assert.assertEquals(3, out.length); Assert.assertEquals(0, out[0].shortValue()); Assert.assertEquals(-1, out[1].shortValue()); Assert.assertEquals(2, out[2].shortValue()); } @Test public void testCreateArrayOfMultiString() throws SQLException { PreparedStatement pstmt = conn.prepareStatement("SELECT ?::text[]"); String[][] in = new String[2][2]; in[0][0] = "a"; in[0][1] = ""; in[1][0] = "\\"; in[1][1] = "\"\\'z"; pstmt.setArray(1, conn.createArrayOf("text", in)); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); String[][] out = (String[][]) arr.getArray(); Assert.assertEquals(2, out.length); Assert.assertEquals(2, out[0].length); Assert.assertEquals("a", out[0][0]); Assert.assertEquals("", out[0][1]); Assert.assertEquals("\\", out[1][0]); Assert.assertEquals("\"\\'z", out[1][1]); } @Test public void testCreateArrayOfMultiJson() throws SQLException { if (!TestUtil.haveMinimumServerVersion(conn, ServerVersion.v9_2)) { return; } PreparedStatement pstmt = conn.prepareStatement("SELECT ?::json[]"); PGobject p1 = new PGobject(); p1.setType("json"); p1.setValue("{\"x\": 10}"); PGobject p2 = new PGobject(); p2.setType("json"); p2.setValue("{\"x\": 20}"); PGobject[] in = new PGobject[] { p1, p2 }; pstmt.setArray(1, conn.createArrayOf("json", in)); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); ResultSet arrRs = arr.getResultSet(); Assert.assertTrue(arrRs.next()); Assert.assertEquals(in[0], arrRs.getObject(2)); Assert.assertTrue(arrRs.next()); Assert.assertEquals(in[1], arrRs.getObject(2)); } @Test public void testCreateArrayWithNonStandardDelimiter() throws SQLException { PGbox[] in = new PGbox[2]; in[0] = new PGbox(1, 2, 3, 4); in[1] = new PGbox(5, 6, 7, 8); PreparedStatement pstmt = conn.prepareStatement("SELECT ?::box[]"); pstmt.setArray(1, conn.createArrayOf("box", in)); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); ResultSet arrRs = arr.getResultSet(); Assert.assertTrue(arrRs.next()); Assert.assertEquals(in[0], arrRs.getObject(2)); Assert.assertTrue(arrRs.next()); Assert.assertEquals(in[1], arrRs.getObject(2)); Assert.assertFalse(arrRs.next()); } @Test public void testCreateArrayOfNull() throws SQLException { String sql = "SELECT ?"; // We must provide the type information for V2 protocol if (preferQueryMode == PreferQueryMode.SIMPLE) { sql = "SELECT ?::int8[]"; } PreparedStatement pstmt = conn.prepareStatement(sql); String[] in = new String[2]; in[0] = null; in[1] = null; pstmt.setArray(1, conn.createArrayOf("int8", in)); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); Long[] out = (Long[]) arr.getArray(); Assert.assertEquals(2, out.length); Assert.assertNull(out[0]); Assert.assertNull(out[1]); } @Test public void testCreateEmptyArrayOfIntViaAlias() throws SQLException { PreparedStatement pstmt = conn.prepareStatement("SELECT ?::int[]"); Integer[] in = new Integer[0]; pstmt.setArray(1, conn.createArrayOf("integer", in)); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); Integer[] out = (Integer[]) arr.getArray(); Assert.assertEquals(0, out.length); ResultSet arrRs = arr.getResultSet(); Assert.assertFalse(arrRs.next()); } @Test public void testCreateArrayWithoutServer() throws SQLException { String[][] in = new String[2][2]; in[0][0] = "a"; in[0][1] = ""; in[1][0] = "\\"; in[1][1] = "\"\\'z"; Array arr = conn.createArrayOf("varchar", in); String[][] out = (String[][]) arr.getArray(); Assert.assertEquals(2, out.length); Assert.assertEquals(2, out[0].length); Assert.assertEquals("a", out[0][0]); Assert.assertEquals("", out[0][1]); Assert.assertEquals("\\", out[1][0]); Assert.assertEquals("\"\\'z", out[1][1]); } @Test public void testCreatePrimitiveArray() throws SQLException { double[][] in = new double[2][2]; in[0][0] = 3.5; in[0][1] = -4.5; in[1][0] = 10.0 / 3; in[1][1] = 77; Array arr = conn.createArrayOf("float8", in); Double[][] out = (Double[][]) arr.getArray(); Assert.assertEquals(2, out.length); Assert.assertEquals(2, out[0].length); Assert.assertEquals(3.5, out[0][0], 0.00001); Assert.assertEquals(-4.5, out[0][1], 0.00001); Assert.assertEquals(10.0 / 3, out[1][0], 0.00001); Assert.assertEquals(77, out[1][1], 0.00001); } @Test public void testUUIDArray() throws SQLException { Assume.assumeTrue("UUID is not supported in PreferQueryMode.SIMPLE", preferQueryMode != PreferQueryMode.SIMPLE); Assume.assumeTrue("UUID requires PostgreSQL 8.3+", TestUtil.haveMinimumServerVersion(conn, ServerVersion.v8_3)); UUID uuid1 = UUID.randomUUID(); UUID uuid2 = UUID.randomUUID(); UUID uuid3 = UUID.randomUUID(); // insert a uuid array, and check PreparedStatement pstmt1 = conn.prepareStatement("INSERT INTO arrtest(uuidarr) VALUES (?)"); pstmt1.setArray(1, conn.createArrayOf("uuid", new UUID[]{uuid1, uuid2, uuid3})); pstmt1.executeUpdate(); PreparedStatement pstmt2 = conn.prepareStatement("SELECT uuidarr FROM arrtest WHERE uuidarr @> ?"); pstmt2.setObject(1, conn.createArrayOf("uuid", new UUID[]{uuid1}), Types.OTHER); ResultSet rs = pstmt2.executeQuery(); Assert.assertTrue(rs.next()); Array arr = rs.getArray(1); UUID[] out = (UUID[]) arr.getArray(); Assert.assertEquals(3, out.length); Assert.assertEquals(uuid1, out[0]); Assert.assertEquals(uuid2, out[1]); Assert.assertEquals(uuid3, out[2]); // concatenate a uuid, and check UUID uuid4 = UUID.randomUUID(); PreparedStatement pstmt3 = conn.prepareStatement("UPDATE arrtest SET uuidarr = uuidarr || ? WHERE uuidarr @> ?"); pstmt3.setObject(1, uuid4, Types.OTHER); pstmt3.setArray(2, conn.createArrayOf("uuid", new UUID[]{uuid1})); pstmt3.executeUpdate(); pstmt2.setObject(1, conn.createArrayOf("uuid", new UUID[]{uuid4}), Types.OTHER); rs = pstmt2.executeQuery(); Assert.assertTrue(rs.next()); arr = rs.getArray(1); out = (UUID[]) arr.getArray(); Assert.assertEquals(4, out.length); Assert.assertEquals(uuid1, out[0]); Assert.assertEquals(uuid2, out[1]); Assert.assertEquals(uuid3, out[2]); Assert.assertEquals(uuid4, out[3]); } @Test public void testSetObjectFromJavaArray() throws SQLException { String[] strArray = new String[] { "a", "b", "c" }; Object[] objCopy = Arrays.copyOf(strArray, strArray.length, Object[].class); PreparedStatement pstmt = conn.prepareStatement("INSERT INTO arrtest(strarr) VALUES (?)"); // cannot handle generic Object[] try { pstmt.setObject(1, objCopy, Types.ARRAY); pstmt.executeUpdate(); Assert.fail("setObject() with a Java array parameter and Types.ARRAY shouldn't succeed"); } catch (org.postgresql.util.PSQLException ex) { // Expected failure. } try { pstmt.setObject(1, objCopy); pstmt.executeUpdate(); Assert.fail("setObject() with a Java array parameter and no Types argument shouldn't succeed"); } catch (org.postgresql.util.PSQLException ex) { // Expected failure. } pstmt.setObject(1, strArray); pstmt.executeUpdate(); pstmt.setObject(1, strArray, Types.ARRAY); pstmt.executeUpdate(); // Correct way, though the use of "text" as a type is non-portable. // Only supported for JDK 1.6 and JDBC4 Array sqlArray = conn.createArrayOf("text", strArray); pstmt.setArray(1, sqlArray); pstmt.executeUpdate(); pstmt.close(); } @Test public void testGetArrayOfComposites() throws SQLException { Assume.assumeTrue("array_agg(expression) requires PostgreSQL 8.4+", TestUtil.haveMinimumServerVersion(conn, ServerVersion.v8_4)); PreparedStatement insertParentPstmt = conn.prepareStatement("INSERT INTO arrcompprnttest (name) " + "VALUES ('aParent');"); insertParentPstmt.execute(); String[] children = { "November 5, 2013", "\"A Book Title\"", "4\" by 6\"", "5\",3\""}; PreparedStatement insertChildrenPstmt = conn.prepareStatement("INSERT INTO arrcompchldttest (name,description,parent) " + "VALUES ('child1',?,1)," + "('child2',?,1)," + "('child3',?,1)," + "('child4',?,1);"); insertChildrenPstmt.setString(1, children[0]); insertChildrenPstmt.setString(2, children[1]); insertChildrenPstmt.setString(3, children[2]); insertChildrenPstmt.setString(4, children[3]); insertChildrenPstmt.execute(); PreparedStatement pstmt = conn.prepareStatement( "SELECT arrcompprnttest.name, " + "array_agg(" + "DISTINCT(arrcompchldttest.id, " + "arrcompchldttest.name, " + "arrcompchldttest.description)) " + "AS children " + "FROM arrcompprnttest " + "LEFT JOIN arrcompchldttest " + "ON (arrcompchldttest.parent = arrcompprnttest.id) " + "WHERE arrcompprnttest.id=? " + "GROUP BY arrcompprnttest.name;"); pstmt.setInt(1, 1); ResultSet rs = pstmt.executeQuery(); assertNotNull(rs); Assert.assertTrue(rs.next()); Array childrenArray = rs.getArray("children"); assertNotNull(childrenArray); ResultSet rsChildren = childrenArray.getResultSet(); assertNotNull(rsChildren); while (rsChildren.next()) { String comp = rsChildren.getString(2); PGtokenizer token = new PGtokenizer(PGtokenizer.removePara(comp), ','); token.remove("\"", "\""); // remove surrounding double quotes if (2 < token.getSize()) { int childID = Integer.parseInt(token.getToken(0)); // remove double quotes escaping with double quotes String value = token.getToken(2).replace("\"\"", "\""); Assert.assertEquals(children[childID - 1], value); } else { Assert.fail("Needs to have 3 tokens"); } } } @Test public void testCasingComposite() throws SQLException { Assume.assumeTrue("Arrays of composite types requires PostgreSQL 8.3+", TestUtil.haveMinimumServerVersion(conn, ServerVersion.v8_3)); PGobject cc = new PGobject(); cc.setType("\"CorrectCasing\""); cc.setValue("(1)"); Object[] in = new Object[1]; in[0] = cc; Array arr = conn.createArrayOf("\"CorrectCasing\"", in); PreparedStatement pstmt = conn.prepareStatement("SELECT ?::\"CorrectCasing\"[]"); pstmt.setArray(1, arr); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Object[] resArr = (Object[]) rs.getArray(1).getArray(); Assert.assertTrue(resArr[0] instanceof PGobject); PGobject resObj = (PGobject) resArr[0]; Assert.assertEquals("(1)", resObj.getValue()); } @Test public void testCasingBuiltinAlias() throws SQLException { Array arr = conn.createArrayOf("INT", new Integer[]{1, 2, 3}); PreparedStatement pstmt = conn.prepareStatement("SELECT ?::INT[]"); pstmt.setArray(1, arr); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Integer[] resArr = (Integer[]) rs.getArray(1).getArray(); Assert.assertArrayEquals(new Integer[]{1, 2, 3}, resArr); } @Test public void testCasingBuiltinNonAlias() throws SQLException { Array arr = conn.createArrayOf("INT4", new Integer[]{1, 2, 3}); PreparedStatement pstmt = conn.prepareStatement("SELECT ?::INT4[]"); pstmt.setArray(1, arr); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Integer[] resArr = (Integer[]) rs.getArray(1).getArray(); Assert.assertArrayEquals(new Integer[]{1, 2, 3}, resArr); } @Test public void testEvilCasing() throws SQLException { Assume.assumeTrue("Arrays of composite types requires PostgreSQL 8.3+", TestUtil.haveMinimumServerVersion(conn, ServerVersion.v8_3)); PGobject cc = new PGobject(); cc.setType("\"Evil.Table\""); cc.setValue("(1)"); Object[] in = new Object[1]; in[0] = cc; Array arr = conn.createArrayOf("\"Evil.Table\"", in); PreparedStatement pstmt = conn.prepareStatement("SELECT ?::\"Evil.Table\"[]"); pstmt.setArray(1, arr); ResultSet rs = pstmt.executeQuery(); Assert.assertTrue(rs.next()); Object[] resArr = (Object[]) rs.getArray(1).getArray(); Assert.assertTrue(resArr[0] instanceof PGobject); PGobject resObj = (PGobject) resArr[0]; Assert.assertEquals("(1)", resObj.getValue()); } @Test public void testToString() throws SQLException { Double[] d = new Double[4]; d[0] = 3.5; d[1] = -4.5; d[2] = null; d[3] = 77.0; Array arr = con.createArrayOf("float8", d); PreparedStatement pstmt = con.prepareStatement("INSERT INTO arrtest(floatarr) VALUES (?)"); ResultSet rs = null; try { pstmt.setArray(1, arr); pstmt.execute(); } finally { TestUtil.closeQuietly(pstmt); } Statement stmt = null; try { stmt = con.createStatement(); rs = stmt.executeQuery("select floatarr from arrtest"); while (rs.next()) { Array doubles = rs.getArray(1); String actual = doubles.toString(); if (actual != null) { // if a binary array is provided, the string representation looks like [0:1][0:1]={{1,2},{3,4}} int idx = actual.indexOf('='); if (idx > 0) { actual = actual.substring(idx + 1); } // Remove all double quotes. They do not make a difference here. actual = actual.replaceAll("\"", ""); } //the string format may vary based on how data stored Assert.assertThat(actual, RegexMatcher.matchesPattern("\\{3\\.5,-4\\.5,NULL,77(.0)?\\}")); } } finally { TestUtil.closeQuietly(rs); TestUtil.closeQuietly(stmt); } } @Test public void nullArray() throws SQLException { PreparedStatement ps = con.prepareStatement("INSERT INTO arrtest(floatarr) VALUES (?)"); ps.setNull(1, Types.ARRAY, "float8[]"); ps.execute(); ps.close(); ps = con.prepareStatement("select floatarr from arrtest"); ResultSet rs = ps.executeQuery(); Assert.assertTrue("arrtest should contain a row", rs.next()); Array getArray = rs.getArray(1); Assert.assertNull("null array should return null value on getArray", getArray); Object getObject = rs.getObject(1); Assert.assertNull("null array should return null on getObject", getObject); } @Test public void createNullArray() throws SQLException { Array arr = con.createArrayOf("float8", null); assertNotNull(arr); Assert.assertNull(arr.getArray()); } @Test public void multiDimIntArray() throws SQLException { Array arr = con.createArrayOf("int4", new int[][]{{1,2}, {3,4}}); PreparedStatement ps = con.prepareStatement("select ?::int4[][]"); ps.setArray(1, arr); ResultSet rs = ps.executeQuery(); rs.next(); Array resArray = rs.getArray(1); String stringValue = resArray.toString(); // if a binary array is provided, the string representation looks like [0:1][0:1]={{1,2},{3,4}} int idx = stringValue.indexOf('='); if (idx > 0) { stringValue = stringValue.substring(idx + 1); } // Both {{"1","2"},{"3","4"}} and {{1,2},{3,4}} are the same array representation stringValue = stringValue.replaceAll("\"", ""); Assert.assertEquals("{{1,2},{3,4}}", stringValue); TestUtil.closeQuietly(rs); TestUtil.closeQuietly(ps); } @Test public void insertAndQueryMultiDimArray() throws SQLException { Array arr = con.createArrayOf("int4", new int[][] { { 1, 2 }, { 3, 4 } }); PreparedStatement insertPs = con.prepareStatement("INSERT INTO arrtest(intarr2) VALUES (?)"); insertPs.setArray(1, arr); insertPs.execute(); insertPs.close(); PreparedStatement selectPs = con.prepareStatement("SELECT intarr2 FROM arrtest"); ResultSet rs = selectPs.executeQuery(); rs.next(); Array array = rs.getArray(1); Integer[][] secondRowValues = (Integer[][]) array.getArray(2, 1); Assert.assertEquals(3, secondRowValues[0][0].intValue()); Assert.assertEquals(4, secondRowValues[0][1].intValue()); } @Test public void testJsonbArray() throws SQLException { Assume.assumeTrue("jsonb requires PostgreSQL 9.4+", TestUtil.haveMinimumServerVersion(con, ServerVersion.v9_4)); TestUtil.createTempTable(con, "jsonbarray", "jbarray jsonb[]" ); try (Statement stmt = con.createStatement()) { stmt.executeUpdate("insert into jsonbarray values( ARRAY['{\"a\":\"a\"}'::jsonb, '{\"b\":\"b\"}'::jsonb] )"); try (ResultSet rs = stmt.executeQuery("select jbarray from jsonbarray")) { assertTrue(rs.next()); Array jsonArray = rs.getArray(1); assertNotNull(jsonArray); assertEquals("jsonb", jsonArray.getBaseTypeName()); } } } }
package com.rigiresearch.examgen.model; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Random; import java.util.stream.Collectors; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.experimental.Accessors; /** * A written examination. * @author Miguel Jimenez (miguel@uvic.ca) * @date 2017-08-20 * @version $Id$ * @since 0.0.1 */ @Accessors(fluent = true) @AllArgsConstructor @Getter public final class Examination { /** * Parameters regarding this exam. * @author Miguel Jimenez (miguel@uvic.ca) * @date 2017-08-21 * @version $Id$ * @since 0.0.1 */ public enum Parameter { /** * The class to which this exam belongs. */ CLASS, /** * The expected date in which this exam takes place. */ DATE, /** * The specific class section, if any. */ SECTION, /** * The corresponding term. */ TERM, /** * The time allocated to this exam. */ TIME_LIMIT, /** * This exam's title. */ TITLE, } /** * Optional fields regarding the student's information. * @author Miguel Jimenez (miguel@uvic.ca) * @date 2017-08-21 * @version $Id$ * @since 0.0.1 */ public enum Field { /** * The assigned grade. */ GRADE, /** * The student identification number. */ STUDENT_ID, /** * The student name. */ STUDENT_NAME, } /** * Parameters composing the document header. Values are expected. */ private final Map<Parameter, String> parameters; /** * Fields printed below the document header. Values are optional. */ private final Map<Field, String> fields; /** * This examination's set of questions. */ private final List<Question> questions; /** * Scramble this exam. * @param seed the seed for the random number generator * @return a scrambled version of this exam */ public Examination scrambled(final long seed) { final List<Question> scrambledQuestions = this.questions.stream() .map(question -> question.scrambled(seed)) .collect(Collectors.toList()); Collections.shuffle( scrambledQuestions, new Random(seed) ); return new Examination( this.parameters, this.fields, scrambledQuestions ); } }
package com.siemens.ct.exi.types; import java.util.HashMap; import java.util.Map; import javax.xml.namespace.QName; import com.siemens.ct.exi.Constants; import com.siemens.ct.exi.context.QNameContext; import com.siemens.ct.exi.datatype.BinaryBase64Datatype; import com.siemens.ct.exi.datatype.BinaryHexDatatype; import com.siemens.ct.exi.datatype.BooleanDatatype; import com.siemens.ct.exi.datatype.Datatype; import com.siemens.ct.exi.datatype.DatetimeDatatype; import com.siemens.ct.exi.datatype.DecimalDatatype; import com.siemens.ct.exi.datatype.EnumerationDatatype; import com.siemens.ct.exi.datatype.FloatDatatype; import com.siemens.ct.exi.datatype.IntegerDatatype; import com.siemens.ct.exi.datatype.ListDatatype; import com.siemens.ct.exi.datatype.StringDatatype; import com.siemens.ct.exi.exceptions.EXIException; import com.siemens.ct.exi.util.xml.QNameUtilities; /** * * @author Daniel.Peintner.EXT@siemens.com * @author Joerg.Heuer@siemens.com * * @version 0.9.7-SNAPSHOT */ public abstract class AbstractTypeCoder implements TypeCoder { // DTR maps protected final QName[] dtrMapTypes; protected final QName[] dtrMapRepresentations; protected final Map<QName, Datatype> dtrMapRepresentationsDatatype; protected Map<QName, Datatype> dtrMap; protected final boolean dtrMapInUse; public AbstractTypeCoder() throws EXIException { this(null, null, null); } public AbstractTypeCoder(QName[] dtrMapTypes, QName[] dtrMapRepresentations, Map<QName, Datatype> dtrMapRepresentationsDatatype) throws EXIException { this.dtrMapTypes = dtrMapTypes; this.dtrMapRepresentations = dtrMapRepresentations; this.dtrMapRepresentationsDatatype = dtrMapRepresentationsDatatype; if (dtrMapTypes == null) { dtrMapInUse = false; } else { dtrMapInUse = true; dtrMap = new HashMap<QName, Datatype>(); assert (dtrMapTypes.length == dtrMapRepresentations.length); this.initDtrMaps(); } } private void initDtrMaps() throws EXIException { assert (dtrMapInUse); // binary dtrMap.put( BuiltIn.XSD_BASE64BINARY, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_BASE64BINARY)); dtrMap.put( BuiltIn.XSD_HEXBINARY, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_HEXBINARY)); // boolean dtrMap.put( BuiltIn.XSD_BOOLEAN, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_BOOLEAN)); // date-times dtrMap.put( BuiltIn.XSD_DATETIME, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_DATETIME)); dtrMap.put( BuiltIn.XSD_TIME, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_TIME)); dtrMap.put( BuiltIn.XSD_DATE, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_DATE)); dtrMap.put( BuiltIn.XSD_GYEARMONTH, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_GYEARMONTH)); dtrMap.put( BuiltIn.XSD_GYEAR, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_GYEAR)); dtrMap.put( BuiltIn.XSD_GMONTHDAY, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_GMONTHDAY)); dtrMap.put( BuiltIn.XSD_GDAY, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_GDAY)); dtrMap.put( BuiltIn.XSD_GMONTH, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_GMONTH)); // decimal dtrMap.put( BuiltIn.XSD_DECIMAL, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_DECIMAL)); // float dtrMap.put( BuiltIn.XSD_FLOAT, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_DOUBLE)); dtrMap.put( BuiltIn.XSD_DOUBLE, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_DOUBLE)); // integer dtrMap.put( BuiltIn.XSD_INTEGER, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_INTEGER)); // string dtrMap.put( BuiltIn.XSD_STRING, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_STRING)); dtrMap.put( BuiltIn.XSD_ANY_SIMPLE_TYPE, getDatatypeRepresentation(Constants.W3C_EXI_NS_URI, Constants.W3C_EXI_LN_STRING)); // all types derived by union are done differently for (int i = 0; i < dtrMapTypes.length; i++) { QName dtrMapRepr = dtrMapRepresentations[i]; Datatype representation = getDatatypeRepresentation( dtrMapRepr.getNamespaceURI(), dtrMapRepr.getLocalPart()); QName type = dtrMapTypes[i]; dtrMap.put(type, representation); } } protected Datatype getDtrDatatype(final Datatype datatype) { assert (dtrMapInUse); Datatype dtrDatatype = null; if (datatype == BuiltIn.DEFAULT_DATATYPE) { // e.g., untyped values are encoded always as String dtrDatatype = datatype; } else { // check mappings QName schemaType = datatype.getSchemaType().getQName(); // unions if ( dtrDatatype == null && datatype.getBuiltInType() == BuiltInType.STRING && ((StringDatatype) datatype).isDerivedByUnion()) { dtrDatatype = datatype; // union ancestors of interest // Datatype dtBase = qncSchemaType.getSimpleBaseDatatype(); Datatype dtBase = datatype.getBaseDatatype(); if (dtBase != null && dtBase.getBuiltInType() == BuiltInType.STRING && ((StringDatatype) dtBase).isDerivedByUnion()) { // check again dtrDatatype = null; } } // lists if ( dtrDatatype == null && datatype.getBuiltInType() == BuiltInType.LIST) { if (dtrMap.containsKey(schemaType)) { // direct DTR mapping dtrDatatype = dtrMap.get(schemaType); } else { ListDatatype ldt = (ListDatatype) datatype; Datatype datatypeList = ldt.getListDatatype(); Datatype dtrDatatypeList = getDtrDatatype(datatypeList); if(datatypeList.getBuiltInType() == dtrDatatypeList.getBuiltInType()) { dtrDatatype = datatype; } else { // update DTR for list datatype dtrDatatype = new ListDatatype(dtrDatatypeList, ldt.getSchemaType()); } } // dtrDatatype = datatype; // // list ancestors of interest // // Datatype dtBase = qncSchemaType.getSimpleBaseDatatype(); // Datatype dtBase = datatype.getBaseDatatype(); // if (dtBase != null // && dtBase.getBuiltInType() == BuiltInType.LIST) { // // check again // dtrDatatype = null; } // enums if ( dtrDatatype == null && datatype.getBuiltInType() == BuiltInType.ENUMERATION) { if (dtrMap.containsKey(schemaType)) { // direct DTR mapping dtrDatatype = dtrMap.get(schemaType); } else { EnumerationDatatype edt = (EnumerationDatatype) datatype; Datatype datatypeEnum = edt.getEnumValueDatatype(); Datatype dtrDatatypeEnum = getDtrDatatype(datatypeEnum); if(datatypeEnum.getBuiltInType() == dtrDatatypeEnum.getBuiltInType()) { dtrDatatype = datatype; } else { // update DTR for list datatype dtrDatatype = dtrDatatypeEnum; } } // dtrDatatype = datatype; // // only ancestor types that have enums are of interest // // Datatype dtBase = qncSchemaType.getSimpleBaseDatatype(); // Datatype dtBase = datatype.getBaseDatatype(); // if (dtBase != null // && dtBase.getBuiltInType() == BuiltInType.ENUMERATION) { // // check again // dtrDatatype = null; } if (dtrDatatype == null) { // QNameContext qncSchemaType = datatype.getSchemaType(); dtrDatatype = dtrMap.get(schemaType); if (dtrDatatype == null) { // no mapping yet // dtrDatatype = updateDtrDatatype(qncSchemaType); dtrDatatype = updateDtrDatatype(datatype); // // special integer handling // if (dtrDatatype.getBuiltInType() == BuiltInType.INTEGER // && (datatype.getBuiltInType() == BuiltInType.NBIT_UNSIGNED_INTEGER || datatype // .getBuiltInType() == BuiltInType.UNSIGNED_INTEGER)) { // dtrDatatype = datatype; // dtrMap.put(qncSchemaType.getQName(), dtrDatatype); } } } // // list item types // assert (dtrDatatype != null); // if (dtrDatatype.getBuiltInType() == BuiltInType.LIST) { // Datatype prev = dtrDatatype; // ListDatatype ldt = (ListDatatype) dtrDatatype; // Datatype dtList = ldt.getListDatatype(); // dtrDatatype = this.getDtrDatatype(dtList); // if (dtrDatatype != dtList) { // // update item codec // dtrDatatype = new ListDatatype(dtrDatatype, ldt.getSchemaType()); // } else { // dtrDatatype = prev; return dtrDatatype; } // protected Datatype updateDtrDatatype(QNameContext qncSchemaType) { protected Datatype updateDtrDatatype(Datatype datatype) { // protected Datatype updateDtrDatatype(QNameContext qncSchemaType) { assert (dtrMapInUse); // // QNameContext qncSchemaType = datatype.getSchemaType(); // QNameContext qncBase = qncSchemaType.getSimpleBaseType(); // assert(qncSchemaType != null); //// // special integer handling //// if (dtrDatatype.getBuiltInType() == BuiltInType.INTEGER //// && (datatype.getBuiltInType() == BuiltInType.NBIT_UNSIGNED_INTEGER || datatype //// .getBuiltInType() == BuiltInType.UNSIGNED_INTEGER)) { //// dtrDatatype = datatype; // Datatype dt = dtrMap.get(qncBase.getQName()); // if (dt == null) { // // dt = updateDtrDatatype(simpleBaseType); // // dt = updateDtrDatatype(qncSchemaType.getSimpleBaseDatatype()); // dt = updateDtrDatatype(qncBase); //baseDatatype); //// dtrMap.put(qncBase.getQName(), dt); // } else { // // save new mapping in map //// dtrMap.put(qncSchemaType.getQName(), dt); // return dt; Datatype baseDatatype = datatype.getBaseDatatype(); // QNameContext qncSchemaType = datatype.getSchemaType(); // QNameContext simpleBaseType = qncSchemaType.getSimpleBaseDatatype().getSchemaType(); QNameContext simpleBaseType = baseDatatype.getSchemaType(); Datatype dtrDatatype = dtrMap.get(simpleBaseType.getQName()); if (dtrDatatype == null) { // dt = updateDtrDatatype(simpleBaseType); // dt = updateDtrDatatype(qncSchemaType.getSimpleBaseDatatype()); dtrDatatype = updateDtrDatatype(baseDatatype); } // special integer handling if ((dtrDatatype.getBuiltInType() == BuiltInType.INTEGER || dtrDatatype.getBuiltInType() == BuiltInType.UNSIGNED_INTEGER) && (datatype.getBuiltInType() == BuiltInType.NBIT_UNSIGNED_INTEGER || datatype .getBuiltInType() == BuiltInType.UNSIGNED_INTEGER)) { dtrDatatype = datatype; } // save new mapping in map dtrMap.put(datatype.getSchemaType().getQName(), dtrDatatype); return dtrDatatype; } protected Datatype getDatatypeRepresentation(String reprUri, String reprLocalPart) throws EXIException { assert (dtrMapInUse); try { // find datatype for given representation Datatype datatype = null; if (Constants.W3C_EXI_NS_URI.equals(reprUri)) { // EXI built-in datatypes // see http://www.w3.org/TR/exi/#builtInEXITypes if ("base64Binary".equals(reprLocalPart)) { datatype = new BinaryBase64Datatype(null); } else if ("hexBinary".equals(reprLocalPart)) { datatype = new BinaryHexDatatype(null); } else if ("boolean".equals(reprLocalPart)) { datatype = new BooleanDatatype(null); } else if ("dateTime".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.dateTime, null); } else if ("time".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.time, null); } else if ("date".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.date, null); } else if ("gYearMonth".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.gYearMonth, null); } else if ("gYear".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.gYear, null); } else if ("gMonthDay".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.gMonthDay, null); } else if ("gDay".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.gDay, null); } else if ("gMonth".equals(reprLocalPart)) { datatype = new DatetimeDatatype(DateTimeType.gMonth, null); } else if ("decimal".equals(reprLocalPart)) { datatype = new DecimalDatatype(null); } else if ("double".equals(reprLocalPart)) { datatype = new FloatDatatype(null); } else if ("integer".equals(reprLocalPart)) { datatype = new IntegerDatatype(null); } else if ("string".equals(reprLocalPart)) { datatype = new StringDatatype(null); } else { throw new EXIException( "[EXI] Unsupported datatype representation: {" + reprUri + "}" + reprLocalPart); } } else { // try to load datatype QName qn = new QName(reprUri, reprLocalPart); if(this.dtrMapRepresentationsDatatype != null) { datatype = this.dtrMapRepresentationsDatatype.get(qn); } if(datatype == null) { // final try: load class with this qname String className = QNameUtilities.getClassName(qn); @SuppressWarnings("rawtypes") Class c = Class.forName(className); Object o = c.newInstance(); if (o instanceof Datatype) { datatype = (Datatype) o; } else { throw new Exception("[EXI] no Datatype instance"); } } } return datatype; } catch (Exception e) { throw new EXIException(e); } } }
package org.lwjgl.generator.util; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; public class TemplateFormatter { final JRadioButton radioConst; final JRadioButton radioFunc; final JTextField prefix; private final JTextArea input; private final JTextArea output; private TemplateFormatter() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } JFrame frame = new JFrame("Template Formatter"); frame.getContentPane().setLayout(new BorderLayout(4, 4)); // Settings radioConst = new JRadioButton("Constants", true); radioFunc = new JRadioButton("Functions"); prefix = new JTextField("GL", 4); ButtonGroup radioGroup = new ButtonGroup(); radioGroup.add(radioConst); radioGroup.add(radioFunc); JPanel radioPane = new JPanel(new FlowLayout()); radioPane.add(radioConst); radioPane.add(radioFunc); radioPane.add(new JLabel("Prefix:")); radioPane.add(prefix); frame.getContentPane().add(radioPane, BorderLayout.NORTH); // Text areas Font font = new Font(Font.MONOSPACED, Font.PLAIN, 14); input = new JTextArea(32, 64); input.setFont(font); input.setLineWrap(false); input.setTabSize(4); output = new JTextArea(32, 64); output.setFont(font); output.setLineWrap(false); output.setTabSize(4); output.setBackground(Color.LIGHT_GRAY); output.setEditable(false); setup(); frame.getContentPane().add(new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, true, new JScrollPane(input), new JScrollPane(output) ), BorderLayout.CENTER); // Config and show try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); frame.setIconImages(Arrays.asList(new Image[] { ImageIO.read(cl.getResource("lwjgl16.png")), ImageIO.read(cl.getResource("lwjgl32.png")), })); } catch (IOException e) { e.printStackTrace(); } frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { new TemplateFormatter(); } private void setup() { input.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { format(); } public void removeUpdate(DocumentEvent e) { format(); } public void changedUpdate(DocumentEvent e) { format(); } }); ActionListener settingsAction = new ActionListener() { public void actionPerformed(ActionEvent e) { format(); } }; radioConst.addActionListener(settingsAction); radioFunc.addActionListener(settingsAction); prefix.addActionListener(settingsAction); } private void format() { String inputText = input.getText().trim(); if ( inputText.isEmpty() ) { output.setBackground(Color.LIGHT_GRAY); output.setText(""); return; } try { String outputText = radioConst.isSelected() ? formatConstants(inputText, prefix.getText()) : formatFunctions(inputText, prefix.getText()); // Try to automatically detect the input type if ( outputText.isEmpty() ) { outputText = radioConst.isSelected() ? formatFunctions(inputText, prefix.getText()) : formatConstants(inputText, prefix.getText()); // Got it, flip the selection if ( !outputText.isEmpty() ) (radioConst.isSelected() ? radioFunc : radioConst).setSelected(true); } if ( outputText.isEmpty() ) { output.setBackground(Color.ORANGE); output.setText("** PARSE ERROR **"); } else { output.setBackground(Color.WHITE); output.setText(outputText); // Copy output to clipboard //final StringSelection copyData = new StringSelection(outputText); //Toolkit.getDefaultToolkit().getSystemClipboard().setContents(copyData, copyData); } } catch (Exception e) { e.printStackTrace(); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); output.setBackground(Color.ORANGE); output.setText("** ERROR **\n\n" + writer.toString()); } } private static final String BLOCK_COMMENT = "(?:/[*]+.+?[*]+/)?"; private static final String DESCRIPTION = "(?:(?:/[*]+\\s*(.+?)\\s*[*]+/)|(?:([^:]+:)))"; private static final String DEFINE = "(?:#define\\s+)?"; private static final String CONSTANT_VALUE = "(?:[-x\\p{XDigit}]+)|(?:\\([^)]+\\))"; private static final Pattern BLOCK_PATTERN = Pattern.compile( DESCRIPTION + "\\s+((?:\\s*" + DEFINE + "[0-9A-Za-z_]+\\s+(?:" + CONSTANT_VALUE + ")[ \t]*" + BLOCK_COMMENT + "\\s*$)+)\\s*", Pattern.MULTILINE | Pattern.DOTALL ); private static final Pattern COMMENT_CLEANUP = Pattern.compile("[\n\n]*(?:\\s*[*])?\\s+", Pattern.MULTILINE); private static final Pattern CODE_CLEANUP = Pattern.compile("<([^>]+)>"); private static final Pattern TOKEN_SPLIT = Pattern.compile("(?<!@code)\\s+"); // Don't split code fragments private static final Pattern CONSTANT_PATTERN = Pattern.compile( DEFINE + "([0-9A-Za-z_]+)\\s+(" + CONSTANT_VALUE + ")[ \t]*" + BLOCK_COMMENT, Pattern.DOTALL ); private static String formatConstants(String input, String prefix) { StringBuilder builder = new StringBuilder(input.length()); Matcher blockMatcher = BLOCK_PATTERN.matcher(input); int blockCount = 0; while ( blockMatcher.find() ) { if ( 0 < blockCount++ ) builder.append('\n'); String description = CODE_CLEANUP.matcher( COMMENT_CLEANUP.matcher(blockMatcher.group(1)).replaceAll(" ").trim() ).replaceAll("{@code $1}"); builder.append("\tIntConstant.block(\n"); if ( description.length() <= 160 - (4 + 4 + 2 + 1) ) { builder.append("\t\t\""); builder.append(description); builder.append('\"'); } else { builder.append("\t\t\"\"\"\n"); builder.append("\t\t"); String[] tokens = TOKEN_SPLIT.split(description); int MAX_LINE_LENGTH = 160 - (4 + 4); int lineLength = 0; for ( String token : tokens ) { lineLength += token.length(); if ( token.length() < lineLength ) { if ( MAX_LINE_LENGTH < 1 + lineLength ) { builder.append("\n\t\t"); lineLength = token.length(); } else { builder.append(' '); lineLength++; } } builder.append(token); } builder.append("\n\t\t\"\"\""); } builder.append(",\n\n"); Matcher constantMatcher = CONSTANT_PATTERN.matcher(blockMatcher.group(3)); int constCount = 0; while ( constantMatcher.find() ) { if ( 0 < constCount++ ) builder.append(",\n"); String token = constantMatcher.group(1); if ( token.startsWith(prefix + '_') ) token = token.substring(prefix.length() + 1); builder.append("\t\t\""); builder.append(token); String value = constantMatcher.group(2); try { Integer.decode(value); builder.append("\" _ "); builder.append(value); } catch (NumberFormatException e) { builder.append("\".expr<Int>(\""); builder.append(value.substring(1, value.length() - 1)); builder.append("\")"); } } builder.append("\n\t)\n"); } return builder.toString(); } private static final Pattern TYPE_PATTERN = Pattern.compile( // This is a little funny because we can have whitespace on either side of * "(?:const\\s+)?(?:unsigned\\s+)?[0-9a-zA-Z_]+(?:(?:\\s*[*]+\\s*)|\\s+)(?:/[*]\\s*)?[0-9a-zA-Z_]+(?:\\s*[*]/)?" ); private static final Pattern FUNCTION_PATTERN = Pattern.compile( TYPE_PATTERN + "\\s*[(](?:,?\\s*" + TYPE_PATTERN + ")*\\s*(?:void\\s*)?[)]", Pattern.MULTILINE ); // Same as TYPE_PATTERN, with capturing groups and without the whitespace stuff (we've already verified correct syntax) private static final Pattern PARAM_PATTERN = Pattern.compile( "(const\\s+)?((?:unsigned\\s+)?[0-9a-zA-Z_]+)\\s*([*]+)?\\s*(?:/[*]\\s*)?([0-9a-zA-Z_]+)(?:\\s*[*]/)?", Pattern.MULTILINE ); private static String formatFunctions(String input, String prefix) { StringBuilder builder = new StringBuilder(input.length()); Matcher funcMatcher = FUNCTION_PATTERN.matcher(input); int funcCount = 0; while ( funcMatcher.find() ) { if ( 0 < funcCount++ ) builder.append("\n\n"); String function = funcMatcher.group(); Matcher paramMatcher = PARAM_PATTERN.matcher(function); int paramCount = -1; while ( paramMatcher.find() ) { if ( paramCount == -1 ) { // Return type + function name builder.append('\t'); if ( paramMatcher.group(1) != null ) builder.append("(const _ "); if ( !paramMatcher.group(2).startsWith(prefix) ) builder.append(prefix); builder.append(paramMatcher.group(2)); if ( paramMatcher.group(3) != null ) // pointer writerPointer(builder, paramMatcher); if ( paramMatcher.group(1) != null ) builder.append(')'); builder.append(".func(\n"); builder.append("\t\t\""); builder.append(paramMatcher.group(4)); builder.append("\",\n"); builder.append("\t\t\"\""); paramCount = 0; } else { // Normal parameter builder.append(",\n"); if ( paramCount++ == 0 ) builder.append('\n'); builder.append("\t\t"); if ( paramMatcher.group(1) != null ) // const builder.append("const _ "); if ( !paramMatcher.group(2).startsWith(prefix) ) builder.append(prefix); builder.append(paramMatcher.group(2)); if ( paramMatcher.group(3) != null ) // pointer writerPointer(builder, paramMatcher); builder.append(".IN(\""); builder.append(paramMatcher.group(4)); builder.append("\", \"\")"); } } builder.append("\n\t)"); } return builder.toString(); } private static void writerPointer(StringBuilder builder, Matcher paramMatcher) { builder.append('_'); for ( int i = 0; i < paramMatcher.group(3).length(); i++ ) builder.append('p'); } }
package com.skelril.skree.system.world; import com.google.common.base.Optional; import com.google.inject.Inject; import com.skelril.skree.SkreePlugin; import com.skelril.skree.content.world.wilderness.WildernessWorldWrapper; import com.skelril.skree.service.WorldService; import com.skelril.skree.service.internal.world.WorldCommand; import com.skelril.skree.service.internal.world.WorldServiceImpl; import org.spongepowered.api.Game; import org.spongepowered.api.world.DimensionTypes; import org.spongepowered.api.world.GeneratorTypes; import org.spongepowered.api.world.World; import org.spongepowered.api.world.WorldBuilder; import java.util.Random; public class WorldSystem { private static final String BUILD = "Sion"; private static final String INSTANCE = "Instance"; private static final String WILDERNESS = "Wilderness"; private static final String WILDERNESS_NETHER = "Wilderness_nether"; private Random randy = new Random(); private WorldService service; @Inject public WorldSystem(SkreePlugin plugin, Game game) { service = new WorldServiceImpl(); // Create worlds initBuild(plugin, game); initInstance(plugin, game); initWilderness(plugin, game); // Command reg game.getCommandDispatcher().register(plugin, WorldCommand.aquireSpec(game), "world"); } private void initBuild(SkreePlugin plugin, Game game) { Optional<World> curWorld = game.getServer().getWorld(BUILD); if (!curWorld.isPresent()) { curWorld = obtainOverworld(game).name(BUILD).seed(randy.nextLong()).usesMapFeatures(false).build(); } if (curWorld.isPresent()) { // TODO build world wrapper } } private void initInstance(SkreePlugin plugin, Game game) { // Instance World Optional<World> curWorld = game.getServer().getWorld(INSTANCE); if (!curWorld.isPresent()) { curWorld = obtainFlatworld(game).name(INSTANCE).seed(randy.nextLong()).usesMapFeatures(false).build(); } if (curWorld.isPresent()) { // TODO Instance world wrapper } } private void initWilderness(SkreePlugin plugin, Game game) { // Wilderness World WildernessWorldWrapper wrapper = new WildernessWorldWrapper(plugin, game); Optional<World> curWorld = game.getServer().getWorld(WILDERNESS); if (!curWorld.isPresent()) { curWorld = obtainOverworld(game).name(WILDERNESS).seed(randy.nextLong()).usesMapFeatures(true).build(); } if (curWorld.isPresent()) { wrapper.addWorld(curWorld.get()); } // Wilderness Nether World curWorld = game.getServer().getWorld(WILDERNESS_NETHER); if (!curWorld.isPresent()) { curWorld = obtainNetherworld(game).name(WILDERNESS_NETHER).seed(randy.nextLong()).usesMapFeatures(true).build(); } if (curWorld.isPresent()) { wrapper.addWorld(curWorld.get()); } // Wilderness wrapper reg game.getEventManager().register(plugin, wrapper); service.registerEffectWrapper(wrapper); } private WorldBuilder obtainOverworld(Game game) { return obtainAutoloadingWorld(game).dimensionType(DimensionTypes.OVERWORLD).generator(GeneratorTypes.OVERWORLD); } private WorldBuilder obtainFlatworld(Game game) { return obtainAutoloadingWorld(game).dimensionType(DimensionTypes.OVERWORLD).generator(GeneratorTypes.FLAT); } public WorldBuilder obtainNetherworld(Game game) { return obtainAutoloadingWorld(game).dimensionType(DimensionTypes.NETHER).generator(GeneratorTypes.NETHER); } private WorldBuilder obtainAutoloadingWorld(Game game) { WorldBuilder builder = game.getRegistry().getWorldBuilder().reset(); return builder.enabled(true).loadsOnStartup(true); } }
package at.jku.pervasive.ecg; import java.io.File; import java.net.URISyntaxException; import java.net.URL; import java.util.List; import java.util.concurrent.Semaphore; import javax.bluetooth.ServiceRecord; import junit.framework.TestCase; public class HeartManDiscoveryTest extends TestCase { private HeartManDiscovery heartManDiscovery; private HeartManSimulator heartManSimulator; public void testDiscoverHeartManDevices() throws Exception { heartManSimulator.createDevice(); List<HeartManDevice> devices = heartManDiscovery.discoverHeartManDevices(); assertNotNull(devices); assertEquals(1, devices.size()); HeartManDevice device = devices.get(0); assertNotNull(device); } public void testGetService() throws Exception { String address = heartManSimulator.createDevice(); heartManDiscovery.discoverHeartManDevices(); List<ServiceRecord> services = heartManDiscovery.searchServices(address); assertNotNull(services); assertEquals(1, services.size()); } public void testListeningOnMoreDevices() throws Exception { final String first = heartManSimulator .createFileDevice(getFile("/recording20s_sleep5ms_1.dat")); final String second = heartManSimulator .createFileDevice(getFile("/recording20s_sleep5ms_2.dat")); heartManDiscovery.discoverHeartManDevices(); final Semaphore s1 = new Semaphore(0); final Semaphore s2 = new Semaphore(0); TestHeartManListener l = new TestHeartManListener() { @Override public void dataReceived(String address, long timestamp, double value) { System.out.printf("%1$s received %2$f\n", address, value); if (address.equals(first)) { s1.release(); } else if (address.equals(second)) { s2.release(); } } }; heartManDiscovery.startListening(first, l); heartManDiscovery.startListening(second, l); s1.acquire(); s2.acquire(); } public void testRecording() throws Exception { String address = heartManSimulator.createDevice(); heartManDiscovery.discoverHeartManDevices(); heartManDiscovery.startRecording(address); final Semaphore s = new Semaphore(0); TestHeartManListener listener = new TestHeartManListener() { @Override public void dataReceived(String address, long timestamp, double value) { s.release(); } }; heartManDiscovery.startListening(address, listener); heartManSimulator.sendValue(address, 1.0); heartManSimulator.sendValue(address, 2.0); heartManSimulator.sendValue(address, 3.0); heartManSimulator.sendValue(address, 4.0); s.acquire(4); List<Double> recordings = heartManDiscovery.stopRecording(address); assertNotNull(recordings); assertEquals(4, recordings.size()); assertEquals(1.0, recordings.get(0), 0.1D); assertEquals(2.0, recordings.get(1), 0.1D); assertEquals(3.0, recordings.get(2), 0.1D); assertEquals(4.0, recordings.get(3), 0.1D); } public void testStartListening() throws Exception { String address = heartManSimulator.createDevice(); heartManDiscovery.discoverHeartManDevices(); final Semaphore s = new Semaphore(0); TestHeartManListener listener = new TestHeartManListener() { @Override public void dataReceived(String address, long timestamp, double value) { super.dataReceived(address, timestamp, value); s.release(); } }; heartManDiscovery.startListening(address, listener); heartManSimulator.sendValue(address, 6.0D); s.acquireUninterruptibly(); assertEquals(6.0D, listener.receivedValue, 0.01D); System.out.println("finished"); } public void testStartListeningForInvalidAdress() throws Exception { try { heartManDiscovery.startListening((String) null, new TestHeartManListener()); fail("should throw an exception when trying to start listening for a device which is not available"); } catch (Exception e) { } } public void testStartListeningForMoreDevices() throws Exception { String first = heartManSimulator.createDevice(); String second = heartManSimulator.createDevice(); final Semaphore s = new Semaphore(0); TestHeartManListener listener = new TestHeartManListener() { @Override public void dataReceived(String address, long timestamp, double value) { super.dataReceived(address, timestamp, value); s.release(1); } }; List<HeartManDevice> devices = heartManDiscovery.discoverHeartManDevices(); assertNotNull(devices); assertEquals(2, devices.size()); heartManDiscovery.startListening(first, listener); heartManDiscovery.startListening(second, listener); heartManSimulator.sendValue(first, 1.0D); s.acquire(); assertTrue(listener.invoked); assertEquals(first, listener.address); assertEquals(1.0D, listener.receivedValue, 0.1D); assertEquals(0, s.availablePermits()); listener.reset(); heartManSimulator.sendValue(second, 2.0D); s.acquire(); assertTrue(listener.invoked); assertEquals(second, listener.address); assertEquals(2.0D, listener.receivedValue, 0.1D); assertEquals(0, s.availablePermits()); } public void testStartListeningWithMoreListeners() throws Exception { String address = heartManSimulator.createDevice(); final Semaphore s = new Semaphore(0); TestHeartManListener l1 = new TestHeartManListener() { @Override public void dataReceived(String address, long timestamp, double value) { super.dataReceived(address, timestamp, value); s.release(1); } }; TestHeartManListener l2 = new TestHeartManListener() { @Override public void dataReceived(String address, long timestamp, double value) { super.dataReceived(address, timestamp, value); s.release(1); } }; heartManDiscovery.discoverHeartManDevices(); heartManDiscovery.startListening(address, l1); heartManSimulator.sendValue(address, 1.0D); // wait until listener got invoked s.acquire(1); // l1 invoked - l2 not assertTrue(l1.invoked); assertEquals(1.0D, l1.receivedValue, 0.1D); assertFalse(l2.invoked); // reset l1.reset(); l2.reset(); // add second listener heartManDiscovery.startListening(address, l2); heartManSimulator.sendValue(address, 5.0D); // wait until both are invoked s.acquire(2); // both listeners invoked assertTrue(l1.invoked); assertEquals(5.0D, l1.receivedValue, 0.1D); assertTrue(l2.invoked); assertEquals(5.0D, l2.receivedValue, 0.1D); } public void testStartListeringWithInvalidListener() throws Exception { String address = heartManSimulator.createDevice(); List<HeartManDevice> devices = heartManDiscovery.discoverHeartManDevices(); assertNotNull(devices); assertEquals(1, devices.size()); try { heartManDiscovery.startListening(address, null); } catch (Exception e) { fail("should not throw an exception"); } } public void testStopListening() throws Exception { String address = heartManSimulator.createDevice(); heartManDiscovery.discoverHeartManDevices(); final Semaphore s = new Semaphore(0); TestHeartManListener listener = new TestHeartManListener() { @Override public void dataReceived(String address, long timestamp, double value) { super.dataReceived(address, timestamp, value); s.release(); } }; heartManDiscovery.startListening(address, listener); heartManSimulator.sendValue(address, 42); s.acquire(); assertTrue(listener.invoked); listener.reset(); heartManDiscovery.stopListening(address); heartManSimulator.sendValue(address, 69); assertFalse(listener.invoked); } public void testStopListeningForNullAddress() throws Exception { try { heartManDiscovery.stopListening(null); } catch (Exception e) { fail("should not thrown an exception"); } } public void testStopListeningWhenNotListening() throws Exception { String address = heartManSimulator.createDevice(); try { heartManDiscovery.stopListening(address); } catch (Exception e) { fail("should not thrown an exception"); } } public void testTwoHeartManDiscoveryInstances() throws Exception { heartManSimulator.createDevice(); List<HeartManDevice> firstList = heartManDiscovery .discoverHeartManDevices(); assertNotNull(firstList); assertEquals(1, firstList.size()); HeartManDiscovery secondDiscovery = new HeartManDiscovery(); List<HeartManDevice> secondList = secondDiscovery.discoverHeartManDevices(); assertNotNull(secondList); assertEquals(1, secondList.size()); } protected File getFile(String path) throws URISyntaxException { URL url = ECGMonitorMain.class.getResource(path); return new File(url.toURI()); } @Override protected void setUp() throws Exception { super.setUp(); heartManSimulator = new HeartManSimulator(); heartManDiscovery = new HeartManDiscovery(); assertTrue(heartManDiscovery.isBluetoothEnabled()); } @Override protected void tearDown() throws Exception { super.tearDown(); heartManDiscovery = null; heartManSimulator.stopServer(); heartManSimulator = null; } }
package com.treasure_data.jdbc.command; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.msgpack.unpacker.Unpacker; import com.treasure_data.client.ClientException; import com.treasure_data.client.TreasureDataClient; import com.treasure_data.jdbc.TDConnection; import com.treasure_data.jdbc.TDResultSet; import com.treasure_data.jdbc.TDResultSetBase; import com.treasure_data.logger.Config; import com.treasure_data.logger.TreasureDataLogger; import com.treasure_data.model.AuthenticateRequest; import com.treasure_data.model.Database; import com.treasure_data.model.GetJobResultRequest; import com.treasure_data.model.GetJobResultResult; import com.treasure_data.model.Job; import com.treasure_data.model.JobResult; import com.treasure_data.model.JobSummary; import com.treasure_data.model.ShowJobRequest; import com.treasure_data.model.ShowJobResult; import com.treasure_data.model.SubmitJobRequest; import com.treasure_data.model.SubmitJobResult; import com.treasure_data.model.TableSummary; public class TDClientAPI implements ClientAPI { private static final Logger LOG = Logger.getLogger(TDClientAPI.class.getName()); private TreasureDataClient client; private Properties props; private Database database; private int maxRows = 5000; public TDClientAPI(TDConnection conn) { this(new TreasureDataClient(conn.getProperties()), conn.getProperties(), conn.getDatabase(), conn.getMaxRows()); } public TDClientAPI(TreasureDataClient client, Properties props, Database database) { this(client, props, database, 5000); } public TDClientAPI(TreasureDataClient client, Properties props, Database database, int maxRows) { this.client = client; this.props = props; this.database = database; this.maxRows = maxRows; checkCredentials(); { Properties sysprops = System.getProperties(); if (sysprops.getProperty(Config.TD_LOGGER_AGENTMODE) == null) { sysprops.setProperty(Config.TD_LOGGER_AGENTMODE, "false"); } if (sysprops.getProperty(Config.TD_LOGGER_API_KEY) == null) { String apiKey = client.getTreasureDataCredentials().getAPIKey(); sysprops.setProperty(Config.TD_LOGGER_API_KEY, apiKey); } } } private void checkCredentials() { String apiKey = client.getTreasureDataCredentials().getAPIKey(); if (apiKey != null) { return; } if (props == null) { return; } String user = props.getProperty("user"); String password = props.getProperty("password"); try { client.authenticate(new AuthenticateRequest(user, password)); } catch (ClientException e) { LOG.throwing(this.getClass().getName(), "checkCredentials", e); return; } } public List<TableSummary> showTables() throws ClientException { return client.listTables(database); } public boolean drop(String table) throws ClientException { client.deleteTable(database.getName(), table); return true; } public boolean create(String table) throws ClientException { client.createTable(database, table); return true; } public boolean insert(String tableName, Map<String, Object> record) throws ClientException { TreasureDataLogger logger = TreasureDataLogger.getLogger(database.getName()); return logger.log(tableName, record); } public TDResultSetBase select(String sql) throws ClientException { TDResultSetBase rs = null; Job job = new Job(database, sql); SubmitJobRequest request = new SubmitJobRequest(job); SubmitJobResult result = client.submitJob(request); job = result.getJob(); if (job != null) { rs = new TDResultSet(this, maxRows, job); } return rs; } public JobSummary waitJobResult(Job job) throws ClientException { ShowJobResult result; while (true) { ShowJobRequest request = new ShowJobRequest(job); result = client.showJob(request); if (LOG.isLoggable(Level.FINE)) { LOG.fine("Job status: " + result.getJob().getStatus()); } JobSummary.Status stat = result.getJob().getStatus(); if (stat == JobSummary.Status.SUCCESS) { break; } else if (stat == JobSummary.Status.ERROR) { throw new ClientException("job status: error"); } else if (stat == JobSummary.Status.KILLED) { throw new ClientException("job status: killed"); } try { Thread.sleep(2 * 1000); } catch (InterruptedException e) { // ignore } } return result.getJob(); } public Unpacker getJobResult(Job job) throws ClientException { GetJobResultRequest request = new GetJobResultRequest(new JobResult(job)); GetJobResultResult result = client.getJobResult(request); return result.getJobResult().getResult(); } public boolean flush() { TreasureDataLogger logger = TreasureDataLogger.getLogger(database.getName()); logger.flush(); return true; } }
package com.vaguehope.morrigan.server; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.vaguehope.morrigan.Args; import com.vaguehope.morrigan.config.Config; import com.vaguehope.morrigan.util.NetHelper; import com.vaguehope.morrigan.util.NetHelper.IfaceAndAddr; import com.vaguehope.morrigan.util.PropertiesFile; public class ServerConfig implements AuthChecker { private static final String SERVER_PROPS = "server.properties"; // TODO move to Config class. private static final String KEY_PASS = "pass"; private static final String DEFAULT_PASS = "Morrigan"; private static final Logger LOG = LoggerFactory.getLogger(ServerConfig.class); private final PropertiesFile propFile; private final Args args; public ServerConfig(final Config config, final Args args) { this.propFile = new PropertiesFile(new File(config.getConfigDir(), SERVER_PROPS)); this.args = args; } public boolean verifyUsername(String username) { return true; // Accept all usernames. } public boolean verifyPassword (final String passToTest) throws IOException { // TODO use bcrypt. final String pass = this.propFile.getString(KEY_PASS, DEFAULT_PASS); return pass.equals(passToTest); } public InetAddress getBindAddress(final String whatFor) throws IOException { final String strIface = this.args.getInterface(); final InetAddress ret; if (strIface != null) { ret = InetAddress.getByName(strIface); LOG.info("{} using address: {}", whatFor, ret); } else { final List<IfaceAndAddr> addresses = NetHelper.getIpAddresses(); ret = addresses.iterator().next().getAddr(); LOG.info("addresses: {}, {} using address: {}", addresses, whatFor, ret); } return ret; } // AuthChecker @Override public boolean verifyAuth(String user, String pass) { try { return verifyUsername(user) && verifyPassword(pass); } catch (final IOException e) { LOG.warn("Failed to verify password.", e); return false; } } }
package com.frameworkium.listeners; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.events.WebDriverEventListener; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestResult; import com.frameworkium.capture.ElementHighlighter; import com.frameworkium.capture.ScreenshotCapture; import com.frameworkium.capture.model.Command; import com.frameworkium.config.DriverType; import com.frameworkium.config.WebDriverWrapper; import com.frameworkium.tests.internal.BaseTest; public class CaptureListener implements WebDriverEventListener, ITestListener { private static final Logger logger = LogManager.getLogger(CaptureListener.class); private void takeScreenshotAndSendToCapture(Command command, WebDriver driver) { logger.debug("takeScreenshotAndSendToCapture"); BaseTest.getCapture().takeAndSendScreenshot(command, driver, null); } private void takeScreenshotAndSendToCapture(String action, WebDriver driver) { Command command = new Command(action, "n/a", "n/a"); takeScreenshotAndSendToCapture(command, driver); } private void takeScreenshotAndSendToCaptureWithException(String action, WebDriver driver, Throwable thrw) { Command command = new Command(action, "n/a", "n/a"); BaseTest.getCapture().takeAndSendScreenshot(command, driver, thrw.getMessage() + "\n" + ExceptionUtils.getStackTrace(thrw)); } private void sendFinalScreenshot(ITestResult result, String action) { WebDriverWrapper webDriver = BaseTest.getDriver(); Throwable thrw = result.getThrowable(); if (null != thrw) { takeScreenshotAndSendToCaptureWithException(action, webDriver, thrw); } else { Command command = new Command(action, "n/a", "n/a"); takeScreenshotAndSendToCapture(command, webDriver); } } private void highlightElementTakeScreenshotAndSendToCapture(String action, WebDriver driver, WebElement element) { logger.debug(String.format("highlightElementTakeScreenshotAndSendToCapture: action=%s", action)); ElementHighlighter highlighter = null; try { if (!DriverType.isNative()) { logger.debug("Trying to highlight the element"); highlighter = new ElementHighlighter(driver); highlighter.highlightElement(element); } Command command = new Command(action, element); takeScreenshotAndSendToCapture(command, driver); if (null != highlighter) { highlighter.unhighlightLast(); } } catch (StaleElementReferenceException serex) { logger.debug("Caught StaleElementReferenceException when trying to (un)highlight an element."); } } /* WebDriver events */ @Override public void beforeClickOn(WebElement element, WebDriver driver) { highlightElementTakeScreenshotAndSendToCapture("click", driver, element); } @Override public void afterChangeValueOf(WebElement element, WebDriver driver) { highlightElementTakeScreenshotAndSendToCapture("change", driver, element); } @Override public void beforeNavigateBack(WebDriver driver) { takeScreenshotAndSendToCapture("nav back", driver); } @Override public void beforeNavigateForward(WebDriver driver) { takeScreenshotAndSendToCapture("nav forward", driver); } @Override public void beforeNavigateTo(String url, WebDriver driver) { Command command = new Command("nav", "url", url); takeScreenshotAndSendToCapture(command, driver); } @Override public void beforeScript(String script, WebDriver driver) { takeScreenshotAndSendToCapture("script", driver); } /* Test end methods */ @Override public void onTestSuccess(ITestResult result) { if (ScreenshotCapture.isRequired()) { sendFinalScreenshot(result, "pass"); } } @Override public void onTestFailure(ITestResult result) { if (ScreenshotCapture.isRequired()) { sendFinalScreenshot(result, "fail"); } } @Override public void onTestSkipped(ITestResult result) { if (ScreenshotCapture.isRequired()) { sendFinalScreenshot(result, "skip"); } } /* * Methods we don't really want screenshots for. */ @Override public void onException(Throwable thrw, WebDriver driver) {} @Override public void afterClickOn(WebElement element, WebDriver driver) {} @Override public void beforeChangeValueOf(WebElement element, WebDriver driver) {} @Override public void afterFindBy(By by, WebElement arg1, WebDriver arg2) {} @Override public void afterNavigateBack(WebDriver driver) {} @Override public void afterNavigateForward(WebDriver driver) {} @Override public void afterNavigateTo(String url, WebDriver driver) {} @Override public void afterScript(String script, WebDriver driver) {} @Override public void beforeFindBy(By by, WebElement element, WebDriver arg2) {} @Override public void onTestStart(ITestResult result) {} @Override public void onTestFailedButWithinSuccessPercentage(ITestResult result) {} @Override public void onStart(ITestContext context) {} @Override public void onFinish(ITestContext context) {} }
package crazypants.enderzoo.item; import java.util.HashMap; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionHelper; import net.minecraftforge.fml.common.FMLCommonHandler; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.relauncher.ReflectionHelper; import net.minecraftforge.fml.relauncher.Side; import crazypants.enderzoo.EnderZoo; import crazypants.enderzoo.EnderZooTab; import crazypants.enderzoo.Log; public class ItemWitheringDust extends Item { public static final String NAME = "witheringDust"; public static ItemWitheringDust create() { ItemWitheringDust res = new ItemWitheringDust(); res.init(); return res; } private ItemWitheringDust() { setUnlocalizedName(NAME); setCreativeTab(EnderZooTab.tabEnderZoo); setHasSubtypes(false); } private void init() { GameRegistry.registerItem(this, NAME); try { HashMap myPotionRequirements = (HashMap)ReflectionHelper.getPrivateValue(PotionHelper.class, null, "potionRequirements", "field_179539_o"); myPotionRequirements.put(Integer.valueOf(Potion.wither.getId()), "0 & 1 & 2 & 3 & 0+6"); } catch (Exception e) { Log.error("ItemWitheringDust: Could not register wither potion recipe " + e); } } @Override public String getPotionEffect(ItemStack p_150896_1_) { return "+0+1+2+3&4-4+13"; } }
package com.github.davidmoten.rx.jdbc; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.Reader; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import rx.Observable; import rx.util.functions.Func1; import rx.util.functions.Func2; import com.github.davidmoten.rx.jdbc.tuple.Tuple2; import com.github.davidmoten.rx.jdbc.tuple.TupleN; public class DatabaseTest { private static final Logger log = Logger.getLogger(DatabaseTest.class); private static AtomicInteger dbNumber = new AtomicInteger(); @Test public void testOldStyle() { Connection con = connectionProvider().get(); createDatabase(con); PreparedStatement ps = null; ResultSet rs = null; try { ps = con.prepareStatement("select name from person where name > ?"); ps.setObject(1, "ALEX"); rs = ps.executeQuery(); List<String> list = new ArrayList<String>(); while (rs.next()) { list.add(rs.getString(1)); } assertEquals(asList("FRED", "JOSEPH", "MARMADUKE"), list); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) try { rs.close(); } catch (SQLException e) { } if (ps != null) try { ps.close(); } catch (SQLException e) { } try { con.close(); } catch (SQLException e) { } } } @Test public void testSimpleExample() { Observable<String> names = db().select( "select name from person order by name").getAs(String.class); // convert the names to a list for unit test List<String> list = names.toList().toBlockingObservable().single(); log.debug(list); assertEquals(asList("FRED", "JOSEPH", "MARMADUKE"), list); } @Test public void testCountQuery() { int count = db().select("select name from person where name >?") .parameter("ALEX").get().count().first().toBlockingObservable() .single(); assertEquals(3, count); } @Test public void testTransactionUsingCount() { Database db = db(); Func1<? super Integer, Boolean> isZero = new Func1<Integer, Boolean>() { @Override public Boolean call(Integer t1) { return t1 == 0; } }; db.beginTransaction(); Observable<Integer> existingRows = db .select("select name from person where name=?") .parameter("FRED").get().count().filter(isZero); db.update("insert into person(name,score) values(?,0)") .parameters(existingRows.map(Util.constant("FRED"))).getCount(); boolean committed = db.commit().toBlockingObservable().single(); assertTrue(committed); } @Test public void testTransactionOnCommit() { Database db = db().beginTransaction(); Observable<Integer> updateCount = db .update("update person set score=?").parameter(99).getCount(); db.commit(updateCount); long count = db.select("select count(*) from person where score=?") .parameter(99).dependsOnLastTransaction().getAs(Long.class) .toBlockingObservable().single(); assertEquals(3, count); } @Test public void testTransactionOnCommitDoesntOccurUnlessSubscribedTo() { Database db = db(); db.beginTransaction(); Observable<Integer> u = db.update("update person set score=?") .parameter(99).getCount(); db.commit(u); // note that last transaction was not listed as a dependency of the next // query long count = db.select("select count(*) from person where score=?") .parameter(99).getAs(Long.class).toBlockingObservable() .single(); assertEquals(0, count); } @Test public void testTransactionOnRollback() { Database db = db(); db.beginTransaction(); Observable<Integer> updateCount = db .update("update person set score=?").parameter(99).getCount(); db.rollback(updateCount); long count = db.select("select count(*) from person where score=?") .parameter(99).dependsOnLastTransaction().getAs(Long.class) .toBlockingObservable().single(); assertEquals(0, count); } @Test public void testUseParameterObservable() { int count = db().select("select name from person where name >?") .parameters(Observable.from("ALEX")).get().count().first() .toBlockingObservable().single(); assertEquals(3, count); } @Test public void testTwoParameters() { List<String> list = db() .select("select name from person where name > ? and name < ?") .parameter("ALEX").parameter("LOUIS").getAs(String.class) .toList().toBlockingObservable().single(); assertEquals(asList("FRED", "JOSEPH"), list); } @Test public void testTakeFewerThanAvailable() { int count = db().select("select name from person where name >?") .parameter("ALEX").get().take(2).count().first() .toBlockingObservable().single(); assertEquals(2, count); } @Test public void testJdbcObservableCountLettersInAllNames() { Func1<ResultSet, Integer> countLettersInName = new Func1<ResultSet, Integer>() { @Override public Integer call(ResultSet rs) { try { return rs.getString("name").length(); } catch (SQLException e) { throw new RuntimeException(e); } } }; int count = Observable .sumInteger( db().select("select name from person where name >?") .parameter("ALEX").get(countLettersInName)) .first().toBlockingObservable().single(); assertEquals(19, count); } @Test public void testTransformToTuple2AndTestActionsPrintln() { Tuple2<String, Integer> tuple = db() .select("select name,score from person where name >? order by name") .parameter("ALEX").getAs(String.class, Integer.class).last() .toBlockingObservable().single(); assertEquals("MARMADUKE", tuple.value1()); assertEquals(25, (int) tuple.value2()); } @Test public void testTransformToTupleN() { TupleN<String> tuple = db() .select("select name, lower(name) from person order by name") .getTupleN(String.class).first().toBlockingObservable() .single(); assertEquals("FRED", tuple.values().get(0)); assertEquals("fred", tuple.values().get(1)); } @Test public void testMultipleSetsOfParameters() { List<Integer> list = db() .select("select score from person where name=?") .parameter("FRED").parameter("JOSEPH").getAs(Integer.class) .toSortedList().toBlockingObservable().single(); assertEquals(asList(21, 34), list); } @Test public void testNoParams() { List<Tuple2<String, Integer>> tuples = db() .select("select name, score from person where name=? order by name") .getAs(String.class, Integer.class).toList() .toBlockingObservable().single(); assertEquals(0, tuples.size()); } @Test public void testComposition2() { log.debug("running testComposition2"); Func1<Integer, Boolean> isZero = new Func1<Integer, Boolean>() { @Override public Boolean call(Integer count) { return count == 0; } }; Database db = db(); Observable<Integer> existingRows = db .select("select name from person where name=?") .parameter("FRED").getAs(String.class).count().filter(isZero); List<Integer> counts = db .update("insert into person(name,score) values(?,?)") .parameters(existingRows).getCount().toList() .toBlockingObservable().single(); assertEquals(0, counts.size()); } @Test public void testEmptyResultSet() { int count = db().select("select name from person where name >?") .parameters(Observable.from("ZZTOP")).get().count().first() .toBlockingObservable().single(); assertEquals(0, count); } @Test public void testMixingExplicitAndObservableParameters() { String name = db() .select("select name from person where name > ? and score < ? order by name") .parameter("BARRY").parameters(Observable.from(100)) .getAs(String.class).first().toBlockingObservable().single(); assertEquals("FRED", name); } @Test public void testInstantiateDatabaseWithUrl() throws SQLException { Database db = new Database("jdbc:h2:mem:test" + dbNumber.incrementAndGet()); Connection con = db.getQueryContext().connectionProvider().get(); con.close(); } @Test public void testComposition() { // use composition to find the first person alphabetically with // a score less than the person with the last name alphabetically // whose name is not XAVIER. Two threads and connections will be used. Database db = db(); Observable<Integer> score = db .select("select score from person where name <> ? order by name") .parameter("XAVIER").getAs(Integer.class).last(); String name = db .select("select name from person where score < ? order by name") .parameters(score).getAs(String.class).first() .toBlockingObservable().single(); assertEquals("FRED", name); } @Test public void testCompositionTwoLevels() { Database db = db(); Observable<String> names = db.select( "select name from person order by name").getAs(String.class); Observable<String> names2 = db .select("select name from person where name<>? order by name") .parameters(names).parameters(names).getAs(String.class); List<String> list = db.select("select name from person where name>?") .parameters(names2).getAs(String.class).toList() .toBlockingObservable().single(); System.out.println(list); assertEquals(12, list.size()); } @Test(expected = RuntimeException.class) public void testSqlProblem() { String name = db().select("select name from pperson where name >?") .parameter("ALEX").getAs(String.class).first() .toBlockingObservable().single(); log.debug(name); } @Test(expected = ClassCastException.class) public void testException() { Integer name = db().select("select name from person where name >?") .parameter("ALEX").getAs(Integer.class).first() .toBlockingObservable().single(); log.debug(name); } @Test public void testDependsUsingAsynchronousQueriesWaitsForFirstByDelayingCalculation() { Database db = db(); Observable<Integer> insert = db .update("insert into person(name,score) values(?,?)") .parameters("JOHN", 45) .getCount() .zip(Observable.interval(100, TimeUnit.MILLISECONDS), new Func2<Integer, Long, Integer>() { @Override public Integer call(Integer t1, Long t2) { return t1; } }); int count = db.select("select name from person").dependsOn(insert) .get().count().toBlockingObservable().single(); assertEquals(4, count); } @Test public void testAutoMapWillMapStringToStringAndIntToDouble() { Person person = db() .select("select name,score,dob,registered from person order by name") .autoMap(Person.class).first().toBlockingObservable().single(); assertEquals("FRED", person.getName()); assertEquals(21, person.getScore(), 0.001); assertNull(person.getDateOfBirth()); } @Test public void testGetTimestamp() { Database db = db(); java.sql.Timestamp registered = new java.sql.Timestamp(100); Observable<Integer> u = db .update("update person set registered=? where name=?") .parameter(registered).parameter("FRED").getCount(); Date regTime = db.select("select registered from person order by name") .dependsOn(u).getAs(Date.class).first().toBlockingObservable() .single(); assertEquals(100, regTime.getTime()); } @Test public void insertClobAndReadAsString() throws SQLException { Database db = db(); insertClob(db); // read clob as string String text = db.select("select document from person_clob") .getAs(String.class).first().toBlockingObservable().single(); assertTrue(text.contains("about Fred")); } private static void insertClob(Database db) { int count = db .update("insert into person_clob(name,document) values(?,?)") .parameter("FRED") .parameter( "A description about Fred that is rather long and needs a Clob to store it") .getCount().toBlockingObservable().single(); assertEquals(1, count); } private static void insertBlob(Database db) { int count = db .update("insert into person_blob(name,document) values(?,?)") .parameter("FRED") .parameter( "A description about Fred that is rather long and needs a Clob to store it" .getBytes()).getCount().toBlockingObservable() .single(); assertEquals(1, count); } @Test public void insertClobAndReadAsReader() throws SQLException, IOException { Database db = db(); insertClob(db); // read clob as Reader String text = db.select("select document from person_clob") .getAs(Reader.class).map(Util.READER_TO_STRING).first() .toBlockingObservable().single(); assertTrue(text.contains("about Fred")); } @Test public void insertBlobAndReadAsByteArray() throws SQLException { Database db = db(); insertBlob(db); // read clob as string byte[] bytes = db.select("select document from person_blob") .getAs(byte[].class).first().toBlockingObservable().single(); assertTrue(new String(bytes).contains("about Fred")); } @Test public void testInsertNull() { int count = db() .update("insert into person(name,score,dob) values(?,?,?)") .parameters("JACK", 42, null).getCount().toBlockingObservable() .single(); assertEquals(1, count); } @Test public void testAutoMap() { TimeZone current = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("AEST")); Database db = db(); Date dob = new Date(100); long now = System.currentTimeMillis(); java.sql.Timestamp registered = new java.sql.Timestamp(now); Observable<Integer> u = db .update("update person set dob=?, registered=? where name=?") .parameter(dob).parameter(registered).parameter("FRED") .getCount(); Person person = db .select("select name,score,dob,registered from person order by name") .dependsOn(u).autoMap(Person.class).first() .toBlockingObservable().single(); assertEquals("FRED", person.getName()); assertEquals(21, person.getScore(), 0.001); // Dates are truncated to start of day assertEquals(0, (long) person.getDateOfBirth()); assertEquals(now, (long) person.getRegistered()); } finally { TimeZone.setDefault(current); } } @Test public void testLastTransactionWithoutTransaction() { Database db = db(); List<Boolean> list = db.getLastTransactionResult().toList() .toBlockingObservable().single(); assertTrue(list.isEmpty()); } @Test public void testAutoMapClob() { Database db = db(); insertClob(db); List<PersonClob> list = db .select("select name, document from person_clob") .autoMap(PersonClob.class).toList().toBlockingObservable() .single(); assertEquals(1, list.size()); assertEquals("FRED", list.get(0).getName()); assertTrue(list.get(0).getDocument().contains("rather long")); } @Test public void testAutoMapBlob() { Database db = db(); insertBlob(db); List<PersonBlob> list = db .select("select name, document from person_blob") .autoMap(PersonBlob.class).toList().toBlockingObservable() .single(); assertEquals(1, list.size()); assertEquals("FRED", list.get(0).getName()); assertTrue(new String(list.get(0).getDocument()) .contains("rather long")); } static class PersonClob { private final String name; private final String document; public PersonClob(String name, String document) { this.name = name; this.document = document; } public String getName() { return name; } public String getDocument() { return document; } } static class PersonBlob { private final String name; private final byte[] document; public PersonBlob(String name, byte[] document) { this.name = name; this.document = document; } public String getName() { return name; } public byte[] getDocument() { return document; } } static class Person { private final String name; private final double score; private final Long dateOfBirthEpochMs; private final Long registered; Person(String name, double score, Long dateOfBirthEpochMs, Long registered) { this.name = name; this.score = score; this.dateOfBirthEpochMs = dateOfBirthEpochMs; this.registered = registered; } public String getName() { return name; } public double getScore() { return score; } public Long getDateOfBirth() { return dateOfBirthEpochMs; } public Long getRegistered() { return registered; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Pair [name="); builder.append(name); builder.append(", score="); builder.append(score); builder.append("]"); return builder.toString(); } } private ConnectionProvider connectionProvider() { return new ConnectionProviderFromUrl("jdbc:h2:mem:test" + dbNumber.incrementAndGet() + ";DB_CLOSE_DELAY=-1"); } private Database db() { ConnectionProvider cp = connectionProvider(); createDatabase(cp.get()); return new Database(cp); } private static void createDatabase(Connection c) { try { c.setAutoCommit(true); c.prepareStatement( "create table person (name varchar(50) primary key, score int not null,dob date, registered timestamp)") .execute(); c.prepareStatement( "insert into person(name,score) values('FRED',21)") .execute(); c.prepareStatement( "insert into person(name,score) values('JOSEPH',34)") .execute(); c.prepareStatement( "insert into person(name,score) values('MARMADUKE',25)") .execute(); c.prepareStatement( "create table person_clob (name varchar(50) not null, document clob not null)") .execute(); c.prepareStatement( "create table person_blob (name varchar(50) not null, document blob not null)") .execute(); } catch (SQLException e) { throw new RuntimeException(e); } } }
package cz.meza.spring.boot.camel.route; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; /** * Dummy route */ @Component public class DummyRoute extends RouteBuilder { @Override public void configure() throws Exception { from("direct:getInfo").process(exchange -> { exchange.getIn().setBody("Basic information"); }); } }
package com.github.veqryn.collect; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.SortedSet; import java.util.TreeSet; import org.junit.Test; import com.github.veqryn.util.TestingUtil; /** * Tests for the PatriciaTrie class * * @author Mark Christopher Duncan */ public class TestPatriciaTrie { final String[] testWords = new String[] { "and", "ant", "antacid", "ante", "antecede", "anteceded", "antecededs", "antecededsic", "antecedent", "antewest", "awe"}; @Test public void testWords() { final Trie<String, String> trie1 = new PatriciaTrie<String>(); final Trie<String, String> trie2 = new PatriciaTrie<String>().prefixedByMap("a", true); final Map<String, String> wordMap = new HashMap<>(); for (final String word : testWords) { trie1.put(word, word); trie2.put(word, word); wordMap.put(word, word); } final Trie<String, String> trie3 = new PatriciaTrie<String>(trie1); final Trie<String, String> trie4 = new PatriciaTrie<String>(trie2); final Trie<String, String> trie5 = new PatriciaTrie<String>(wordMap); tryThisTrie(trie1); tryThisTrie(trie2); tryThisTrie(trie3); tryThisTrie(trie4); tryThisTrie(trie5); assertEquals("antecededs", wordMap.remove("antecededs")); assertEquals(wordMap, trie1); assertEquals(trie1, trie2); assertEquals(trie2, trie3); assertEquals(trie3, trie4); assertEquals(trie4, trie5); } public void tryThisTrie(final Trie<String, String> trie) { assertEquals(testWords.length, trie.size()); assertEquals("ant", trie.shortestPrefixOfValue("antecede", true)); assertEquals("ant", trie.shortestPrefixOfValue("antecede", false)); assertEquals("antecede", trie.longestPrefixOfValue("antecede", true)); assertEquals("ante", trie.longestPrefixOfValue("antecede", false)); assertArrayEquals(new Object[] {"ant", "ante", "antecede"}, trie.prefixOfValues("antecede", true).toArray()); assertArrayEquals(new Object[] {"ant", "ante"}, trie.prefixOfValues("antecede", false).toArray()); assertArrayEquals(new Object[] {"ant", "ante", "antecede"}, trie.prefixOfMap("antecede", true).keySet().toArray()); assertArrayEquals(new Object[] {"ant", "ante"}, trie.prefixOfMap("antecede", false).keySet().toArray()); assertArrayEquals( new Object[] {"antecede", "anteceded", "antecededs", "antecededsic", "antecedent"}, trie.prefixedByValues("antecede", true).toArray()); assertArrayEquals(new Object[] {"anteceded", "antecededs", "antecededsic", "antecedent"}, trie.prefixedByValues("antecede", false).toArray()); assertArrayEquals( new Object[] {"antecede", "anteceded", "antecededs", "antecededsic", "antecedent"}, trie.prefixedByMap("antecede", true).keySet().toArray()); assertArrayEquals(new Object[] {"anteceded", "antecededs", "antecededsic", "antecedent"}, trie.prefixedByMap("antecede", false).keySet().toArray()); // Try removing from a View: final Collection<String> prefixedByValues = trie.prefixedByValues("antecede", false); assertArrayEquals(new Object[] {"anteceded", "antecededs", "antecededsic", "antecedent"}, prefixedByValues.toArray()); assertTrue(prefixedByValues.remove("antecededs")); assertFalse(prefixedByValues.remove("antecedents")); assertArrayEquals(new Object[] {"anteceded", "antecededsic", "antecedent"}, prefixedByValues.toArray()); } @Test public void testIndividualUnicodeCharacters() { final PatriciaTrie<String> trie = new PatriciaTrie<>(); for (final String unicodeCharacter : new TestingUtil.UnicodeGenerator()) { assertEquals(0, trie.size()); trie.put(unicodeCharacter, unicodeCharacter); assertEquals(1, trie.size()); final Iterator<Entry<String, String>> iter = trie.entrySet().iterator(); final Entry<String, String> entry = iter.next(); assertEquals(unicodeCharacter, entry.getValue()); assertEquals(unicodeCharacter, entry.getKey()); assertEquals(entry.getValue(), entry.getKey()); iter.remove(); } } @Test public void testMultipleUnicodeCharacters() { final PatriciaTrie<String> trie = new PatriciaTrie<>(); for (final String unicodeCharacter1 : new TestingUtil.UnicodeGenerator(0, 0x10FFFF, 512)) { for (final String unicodeCharacter2 : new TestingUtil.UnicodeGenerator(0, 0x10FFFF, 512)) { assertEquals(0, trie.size()); final String unicodeCharacters = unicodeCharacter1 + unicodeCharacter2; trie.put(unicodeCharacters, unicodeCharacters); final String firstKey = trie.keySet().iterator().next(); assertEquals(firstKey, trie.remove(firstKey)); assertEquals(unicodeCharacters, firstKey); } } } @Test public void testComparator() { final Comparator<? super String> comparator = new PatriciaTrie<>().getCodec().comparator(); assertNotNull(comparator); final SortedSet<String> expected = new TreeSet<>(); final SortedSet<String> actual = new TreeSet<>(comparator); for (final String word : testWords) { expected.add(word); actual.add(word); } assertEquals(expected.size(), actual.size()); final Iterator<String> expIter = expected.iterator(); final Iterator<String> actIter = actual.iterator(); while (expIter.hasNext()) { assertEquals(expIter.next(), actIter.next()); } } }
package de.minestar.core.database; import com.j256.ormlite.dao.Dao; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; /** * Consumes objects and store them into to the database. <br> * <p> * The objects are buffered into a queue and only persisted, when the flush size is reached (default * {@value DatabaseConsumer#DEFAULT_FLUSH_SIZE}) or the methods {@link DatabaseConsumer#flush()} or * {@link DatabaseConsumer#stop()} are invoked. The objects are stored in a {@link java.util.concurrent.BlockingQueue} * and drained into a temporary buffer. This reduces the blocking time while flushing. * <p> * The consumer will check the size of its queue in a interval(default {@value DatabaseConsumer#DEFAULT_SLEEP_TIME_MILLIS} ms). * If the queue contains much more than the flush size is, the time interval will be halved and will be reset when the * consumer had enough idle cycles without a flush. This mechanism will prevent heavy load spikes. * <p> * The method {@link DatabaseConsumer#kickOf(DatabaseConsumer)} provide a standard method to start a consumer. The consumer * are handled by a Thread Pool. Using an own thread for the consumer needs to invoke {@link DatabaseConsumer#start()} * before starting the thread. * * @param <T> The type of objects to consume */ public class DatabaseConsumer<T> implements Runnable { private static final double TOO_MANY_ELEMENTS = 1.1; private static final long DEFAULT_SLEEP_TIME_MILLIS = 50L; private static final int DEFAULT_FLUSH_SIZE = 32; private static final int IDLE_CYCLES_BEFORE_RESET = 10; private static final int MAX_BUFFER_SIZE = 256; private final DatabaseAccess access; private final int flushSize; private final Class<T> entityClass; private final List<T> flushBuffer; private final long initialSleepTime; private long sleepTime; private BlockingQueue<T> queue; private boolean isRunning; private AtomicInteger idleCycles; /** * Creates an default database consumer with default sleep time of {@value DatabaseConsumer#DEFAULT_SLEEP_TIME_MILLIS} ms * and a default flush size of {@value DatabaseConsumer#DEFAULT_FLUSH_SIZE}. * * @param access The access to the database. Cannot be null * @param entityClass The class of the entity to consume. Cannot be null */ public DatabaseConsumer(final DatabaseAccess access, final Class<T> entityClass) { this(access, entityClass, DEFAULT_FLUSH_SIZE, DEFAULT_SLEEP_TIME_MILLIS); } /** * Creates a database consumer with fine adjustment of running parameter. * * @param access The access to the database. Cannot be null * @param entityClass The class of the entity to consume. Cannot be null * @param flushSize If the added object count is equals or higher than this parameter, the queue will be flushed. * @param sleepTimeMillis The interval the consumer will check queues size */ public DatabaseConsumer(final DatabaseAccess access, final Class<T> entityClass, final int flushSize, final long sleepTimeMillis) { this.access = access; this.flushSize = flushSize; this.entityClass = entityClass; this.initialSleepTime = sleepTimeMillis; this.sleepTime = sleepTimeMillis; this.idleCycles = new AtomicInteger(); this.queue = new LinkedBlockingQueue<>(); this.flushBuffer = new ArrayList<>(flushSize); } /** * Add an object to the consumer. The consumer will persist it later. * * @param ele The object to add */ public void consume(T ele) { this.queue.add(ele); } /** * Starts the consumer. This does not mean, that the consumer will persist the objects immediately! This method should * be invoked by a Thread before the Thread is started! */ public void start() { this.isRunning = true; } /** * Stops the consumer. If the consumer is running by a Thread, it will flush the queue. Otherwise, a manual flush * is necessary! */ public void stop() { this.isRunning = false; } /** * Persists all objects in the queue ignoring the flush size. */ public void flush() { this.flush(queue.size()); } @Override public void run() { while (isRunning) { int queueSize = queue.size(); // Flush the queue if (queueSize >= flushSize) { flush(queueSize); // Decrease the sleep time if the queue was overloaded this.sleepTime = wasQueueOverloaded(queueSize) ? sleepTime / 2L : sleepTime; } // Idle cycle // If they are high enough reset sleep time to initial sleep time to prevent idle cycles due sleep time // reduction else if (idleCycles.incrementAndGet() > IDLE_CYCLES_BEFORE_RESET) { idleCycles.set(0); this.sleepTime = initialSleepTime; } try { Thread.sleep(sleepTime); } catch (InterruptedException e) { System.out.println("Thread " + Thread.currentThread().getName() + " was interrupted. Flush queue!"); stop(); } } if (!queue.isEmpty()) flush(); } private boolean wasQueueOverloaded(int queueSize) { return ((double) queueSize / (double) flushSize) > TOO_MANY_ELEMENTS; } private void flush(int queueSize) { int elements = queue.drainTo(flushBuffer, Math.min(MAX_BUFFER_SIZE, queueSize)); try { Dao<T, ?> dao = access.getDao(entityClass); dao.callBatchTasks(() -> { for (int i = 0; i < elements; ++i) { dao.create(flushBuffer.get(i)); } return null; }); flushBuffer.clear(); } catch (Exception ignore) { } } private static ExecutorService threadPool = Executors.newCachedThreadPool(); /** * Starts the consumer using a Thread provided by Thread Pool. Using this method is suggested, but not necessary. * * @param consumer The consumer to start. The consumer will be handled by a Thread. * @param <T> The type of objects to consume */ public static <T> void kickOf(DatabaseConsumer<T> consumer) { consumer.start(); threadPool.submit(consumer); } }
package com.yahoo.omid.notifications; import static com.yahoo.omid.examples.Constants.COLUMN_1; import static com.yahoo.omid.examples.Constants.COLUMN_FAMILY_1; import static com.yahoo.omid.examples.Constants.TABLE_1; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.hadoop.hbase.client.Result; import org.apache.zookeeper.data.Stat; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.curator.framework.CuratorFramework; import com.netflix.curator.framework.CuratorFrameworkFactory; import com.netflix.curator.retry.ExponentialBackoffRetry; import com.netflix.curator.test.TestingServer; import com.netflix.curator.utils.ZKPaths; import com.yahoo.omid.examples.Constants; import com.yahoo.omid.notifications.client.DeltaOmid; import com.yahoo.omid.notifications.client.IncrementalApplication; import com.yahoo.omid.notifications.client.Observer; import com.yahoo.omid.notifications.comm.ZNRecord; import com.yahoo.omid.notifications.comm.ZNRecordSerializer; import com.yahoo.omid.notifications.conf.ClientConfiguration; import com.yahoo.omid.transaction.Transaction; public class TestDeltaOmid extends TestInfrastructure { private static Logger logger = LoggerFactory.getLogger(TestDeltaOmid.class); private TestingServer server; private static final ExecutorService tsoExecutor = Executors.newSingleThreadExecutor(); @Before public void setup() throws Exception { server = new TestingServer(); } @After public void teardown() throws Exception { server.stop(); server.close(); } @Test public void testBuilderBuildsAppWithTheRigthName() throws Exception { Interest interest = new Interest(TABLE_1, COLUMN_FAMILY_1, COLUMN_1); Observer obs = mock(Observer.class); when(obs.getName()).thenReturn("TestObserver"); when(obs.getInterest()).thenReturn(interest); ClientConfiguration appConfig = new ClientConfiguration(); appConfig.setZkServers(server.getConnectString()); final IncrementalApplication app = new DeltaOmid.AppBuilder("TestApp", 6666).setConfiguration(appConfig) .addObserver(obs).build(); assertEquals("This test app should be called TestApp", "TestApp", app.getName()); app.close(); } @Test public void testBuilderWritesTheRighNodePathForAppInZk() throws Exception { Interest interest = new Interest(TABLE_1, COLUMN_FAMILY_1, COLUMN_1); Observer obs = mock(Observer.class); when(obs.getName()).thenReturn("TestObserver"); when(obs.getInterest()).thenReturn(interest); ClientConfiguration appConfig = new ClientConfiguration(); appConfig.setZkServers(server.getConnectString()); final IncrementalApplication app = new DeltaOmid.AppBuilder("TestApp", 6666).setConfiguration(appConfig) .addObserver(obs).build(); CuratorFramework zkClient = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); zkClient.start(); String expectedPath = ZKPaths.makePath(ZkTreeUtils.getAppsNodePath(), "TestApp"); Stat s = zkClient.checkExists().forPath(expectedPath); assertTrue("The expected path for App is not found in ZK", s != null); app.close(); } @Test public void testBuilderWritesTheRighNodePathForAppInstanceInZk() throws Exception { Interest interest = new Interest(TABLE_1, COLUMN_FAMILY_1, COLUMN_1); Observer obs = mock(Observer.class); when(obs.getName()).thenReturn("TestObserver"); when(obs.getInterest()).thenReturn(interest); ClientConfiguration appConfig = new ClientConfiguration(); appConfig.setZkServers(server.getConnectString()); final IncrementalApplication app = new DeltaOmid.AppBuilder("TestApp", 6666).setConfiguration(appConfig) .addObserver(obs).build(); CuratorFramework zkClient = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); zkClient.start(); String expectedPath = ZKPaths.makePath(ZkTreeUtils.getAppsNodePath(), "TestApp"); List<String> children = zkClient.getChildren().forPath(expectedPath); assertNotNull("Returned children list is null", children); assertFalse("No app instance registered for TestApp", children.isEmpty()); assertEquals("More than one instances registered for TestApp", 1, children.size()); app.close(); } @Test public void testBuilderWritesTheRighDataInZkAppNode() throws Exception { final Interest interest = new Interest(TABLE_1, COLUMN_FAMILY_1, COLUMN_1); Observer obs = new Observer() { public void onInterestChanged(Result rowData, Transaction tx) { logger.info("I'm observer " + getName()); } @Override public String getName() { return "TestObserver"; } @Override public Interest getInterest() { return interest; } }; ClientConfiguration appConfig = new ClientConfiguration(); appConfig.setZkServers(server.getConnectString()); final IncrementalApplication app = new DeltaOmid.AppBuilder("TestApp", 6666).setConfiguration(appConfig) .addObserver(obs).build(); CuratorFramework zkClient = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); zkClient.start(); String expectedPath = ZKPaths.makePath(ZkTreeUtils.getAppsNodePath(), "TestApp"); byte[] data = zkClient.getData().forPath(expectedPath); ZNRecord zkRecord = (ZNRecord) new ZNRecordSerializer().deserialize(data); ZNRecord expectedRecord = new ZNRecord("TestApp"); expectedRecord.putListField("observer-interest-list", Collections.singletonList("TestObserver" + "/" + interest.toZkNodeRepresentation())); assertEquals("The content stored in the ZK record is not the same", expectedRecord, zkRecord); app.close(); } @Test public void testBuilderWritesTheRighComplexDataInZkAppNodeForTwoObservers() throws Exception { final Interest o1i1 = new Interest(Constants.TABLE_1, Constants.COLUMN_FAMILY_1, Constants.COLUMN_1); final Interest o2i1 = new Interest(Constants.TABLE_1, Constants.COLUMN_FAMILY_1, Constants.COLUMN_2); Observer obs1 = mock(Observer.class); when(obs1.getName()).thenReturn("TestObserver3"); when(obs1.getInterest()).thenReturn(o1i1); Observer obs2 = mock(Observer.class); when(obs2.getName()).thenReturn("TestObserver2"); when(obs2.getInterest()).thenReturn(o2i1); ClientConfiguration appConfig = new ClientConfiguration(); appConfig.setZkServers(server.getConnectString()); final IncrementalApplication app = new DeltaOmid.AppBuilder("TestApp", 6666).setConfiguration(appConfig) .addObserver(obs1).addObserver(obs2).build(); CuratorFramework zkClient = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); zkClient.start(); String expectedPath = ZKPaths.makePath(ZkTreeUtils.getAppsNodePath(), "TestApp"); byte[] data = zkClient.getData().forPath(expectedPath); ZNRecord zkRecord = (ZNRecord) new ZNRecordSerializer().deserialize(data); ZNRecord expectedRecord = new ZNRecord("TestApp"); List<String> expectedObsIntList = new ArrayList<String>(); expectedObsIntList.add(obs1.getName() + "/" + o1i1.toZkNodeRepresentation()); expectedObsIntList.add(obs2.getName() + "/" + o2i1.toZkNodeRepresentation()); expectedRecord.putListField("observer-interest-list", expectedObsIntList); assertEquals("The content stored in the ZK record is not the same", expectedRecord, zkRecord); app.close(); } @Test public void testAppInstanceNodeDissapearsInZkAfterClosingApp() throws Exception { Interest interest = new Interest(TABLE_1, COLUMN_FAMILY_1, COLUMN_1); Observer obs = mock(Observer.class); when(obs.getName()).thenReturn("TestObserver"); when(obs.getInterest()).thenReturn(interest); ClientConfiguration appConfig = new ClientConfiguration(); appConfig.setZkServers(server.getConnectString()); final IncrementalApplication app = new DeltaOmid.AppBuilder("TestApp", 6666).setConfiguration(appConfig) .addObserver(obs).build(); app.close(); CuratorFramework zkClient = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); zkClient.start(); String localhost = InetAddress.getLocalHost().getHostAddress(); String expectedPath = ZKPaths.makePath(ZKPaths.makePath(ZkTreeUtils.getAppsNodePath(), "TestApp"), localhost); Stat s = zkClient.checkExists().forPath(expectedPath); assertTrue("The expected path for App Instance should not be found in ZK", s == null); } }
package edu.drexel.cs451_rbbtd.apologies.gui; import com.sun.jmx.remote.security.JMXPluggableAuthenticator; import java.util.*; import javax.swing.*; import java.awt.*; import java.awt.event.InputEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.List; import java.awt.event.*; public class Board extends JPanel implements MouseListener { private List<Pawn> pawns; private Image img; private Deck deck; private Card currentCard; private JPanel[] Panels; private int selectionX = 0; private int selectionY = 0; private Positions positions = new Positions(); private JRadioButton TWO_A; private JRadioButton TWO_B; private JRadioButton SKIP; private JTextArea PLAYER; private int optSelected = 1; private Boolean isDeckClickable = true; private Boolean isPawnMovable = false; private ArrayList<PlayerColor> players = new ArrayList<PlayerColor>(); private int specialSequence = 0; // For pawn swapping logic private Pawn pawnOne; private Pawn pawnTwo; private int indexOne; private int indexTwo; String yellowPawn = Apologies.getResourcePath("YellowPawn.png"); String greenPawn = Apologies.getResourcePath("GreenPawn.png"); String redPawn = Apologies.getResourcePath("RedPawn.png"); String bluePawn = Apologies.getResourcePath("BluePawn.png"); Image selectionBoxImage; // String yellowPawn = "resources/YellowPawn.png"; // String greenPawn = "resources/GreenPawn.png"; // String redPawn = "resources/RedPawn.png"; // String bluePawn = "resources/BluePawn.png"; public Board(Image img, ArrayList<PlayerColor> playerColors, PlayerColor first) { // Initialize positions int yellowPositions[][] = positions.yellowPositions; int greenPositions[][] = positions.greenPositions; int redPositions[][] = positions.redPositions; int bluePositions[][] = positions.bluePositions; // init selectionBox image String selectionBox = Apologies.getResourcePath("selectionBox.png"); ImageIcon ii = new ImageIcon(selectionBox); selectionBoxImage = ii.getImage(); // Add Board base components this.img = img; addMouseListener(this); setFocusable(true); setBackground(Color.BLACK); setDoubleBuffered(true); // Create panels JPanel TWO_PANEL = new JPanel(); TWO_A = new JRadioButton("Start a Pawn"); TWO_B = new JRadioButton("Move a pawn forward 2 spaces"); SKIP = new JRadioButton("Skip Turn"); PLAYER = new JTextArea(""); PLAYER.setEditable(false); PLAYER.setBackground(TWO_PANEL.getBackground()); TWO_A.addActionListener(new buttonOneClicked()); TWO_B.addActionListener(new buttonTwoClicked()); SKIP.addActionListener(new skipButtonClicked()); ButtonGroup TWO_OPTIONS = new ButtonGroup(); TWO_OPTIONS.add(TWO_A); TWO_OPTIONS.add(TWO_B); TWO_OPTIONS.add(SKIP); TWO_PANEL.add(TWO_A); TWO_PANEL.add(TWO_B); TWO_PANEL.add(SKIP); TWO_PANEL.add(PLAYER); // Set current panel this.setLayout(new BorderLayout()); this.add(TWO_PANEL, BorderLayout.SOUTH); // Initialize pawns pawns = new ArrayList<Pawn>(); if (playerColors.contains(PlayerColor.YELLOW)) { int x1 = 130; int x2 = 170; int y1 = 50; int y2 = 90; pawns.add(new Pawn(x1, y2, yellowPositions, yellowPawn, PlayerColor.YELLOW)); pawns.add(new Pawn(x2, y2, yellowPositions, yellowPawn, PlayerColor.YELLOW)); pawns.add(new Pawn(x1, y1, yellowPositions, yellowPawn, PlayerColor.YELLOW)); pawns.add(new Pawn(x2, y1, yellowPositions, yellowPawn, PlayerColor.YELLOW)); } if (playerColors.contains(PlayerColor.GREEN)) { int x1 = 445; int x2 = 485; int y1 = 130; int y2 = 170; pawns.add(new Pawn(x1, y2, greenPositions, greenPawn, PlayerColor.GREEN)); pawns.add(new Pawn(x2, y2, greenPositions, greenPawn, PlayerColor.GREEN)); pawns.add(new Pawn(x1, y1, greenPositions, greenPawn, PlayerColor.GREEN)); pawns.add(new Pawn(x2, y1, greenPositions, greenPawn, PlayerColor.GREEN)); } if (playerColors.contains(PlayerColor.RED)) { int x1 = 365; int x2 = 405; int y1 = 440; int y2 = 480; pawns.add(new Pawn(x1, y2, redPositions, redPawn, PlayerColor.RED)); pawns.add(new Pawn(x2, y2, redPositions, redPawn, PlayerColor.RED)); pawns.add(new Pawn(x1, y1, redPositions, redPawn, PlayerColor.RED)); pawns.add(new Pawn(x2, y1, redPositions, redPawn, PlayerColor.RED)); } if (playerColors.contains(PlayerColor.BLUE)) { int x1 = 45; int x2 = 85; int y1 = 365; int y2 = 405; pawns.add(new Pawn(x1, y2, bluePositions, bluePawn, PlayerColor.BLUE)); pawns.add(new Pawn(x2, y2, bluePositions, bluePawn, PlayerColor.BLUE)); pawns.add(new Pawn(x1, y1, bluePositions, bluePawn, PlayerColor.BLUE)); pawns.add(new Pawn(x2, y1, bluePositions, bluePawn, PlayerColor.BLUE)); } setupPlayers(first, playerColors); deck = new Deck(165, 210); } // Draw Background Image public void paintComponent(Graphics g) { g.drawImage(img, 0, 0, null); } // Paint Game Objects public void paint(Graphics g) { super.paint(g); Graphics2D g2d = (Graphics2D)g; // Paint Pawns for (Pawn pawn : pawns) { g2d.drawImage(pawn.getImage(), pawn.getX(), pawn.getY(), this); } // Paint Deck g2d.drawImage(deck.getImage(), deck.getX(), deck.getY(), this); // Paint current card if not null if (currentCard != null){ g2d.drawImage(currentCard.getImage(), currentCard.getX(), currentCard.getY(), this); } // paint selected region if (selectionX != 0 && selectionY != 0){ g2d.drawImage(selectionBoxImage, selectionX, selectionY, this); } Toolkit.getDefaultToolkit().sync(); g.dispose(); } // Handle mouse clicks public void mouseClicked(MouseEvent e) { final int pawnClickAreaWidth = 50; final int pawnClickAreaHeight = 50; final int cardClickAreaWidth = 120; final int cardClickAreaHeight = 160; // Left Click if ((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK){ // Left Click pawn - Iterate through pawns int count = 0; for (Pawn pawn: pawns) { count++; if (e.getX() > pawn.getX() && e.getX() < pawn.getX()+pawnClickAreaWidth && e.getY() > pawn.getY() && e.getY() < pawn.getY()+pawnClickAreaHeight && isPawnMovable){ // If card is an eleven or sorry then special sequence if (currentCard.getNumber() == 8 && optSelected == 2 || currentCard.getNumber() == 10){ if (specialSequence == 0){ selectionX = pawn.getX() + 15; selectionY = pawn.getY() + 10; pawnOne = pawns.get(count-1); indexOne = count-1; pawn.errorMessage = "Select a Pawn to swap with."; repaint(); } if (specialSequence == 1){ selectionX = pawn.getX() + 15; selectionY = pawn.getY() + 10; pawnTwo = pawns.get(count-1); indexTwo = count-1; // swap pawns logic int space1 = pawns.get(indexOne).getSpace(); // the space of your pawn int space2 = pawns.get(indexTwo).getSpace(); // the space of opponents paws int temp = pawns.get(indexOne).getIndex(pawns.get(indexTwo).getX(), pawns.get(indexTwo).getY()); int temp2 = pawns.get(indexTwo).getIndex(pawns.get(indexOne).getX(), pawns.get(indexOne).getY()); pawns.get(indexOne).moveTo(temp); pawns.get(indexTwo).moveTo(temp2); repaint(); } specialSequence++; } // Move Pawn if (isPawnMovable == true){ pawn.Move(currentCard.getNumber(), optSelected); } // Print error message if applicable if (pawn.getErrorMessage() != null){ JOptionPane.showMessageDialog(this, pawn.getErrorMessage(), "Error", JOptionPane.ERROR_MESSAGE); pawn.resetErrorMessage(); // remove error message so it won't carry over to to next card break; } //rotate the first player to the end of the list PlayerColor first = players.get(0); players.remove(first); players.add(first); PLAYER.setText(Apologies.getNames(0) + "'s Turn"); Apologies.swapFirstLast(); //reset the clickable flag for deck and pawn and sequence isDeckClickable = true; isPawnMovable = false; specialSequence = 0; repaint(); } } if (e.getX() > deck.getX() && e.getX() < deck.getX()+cardClickAreaWidth && e.getY() > deck.getY() && e.getY() < deck.getY()+cardClickAreaHeight && isDeckClickable){ // Draw a card and paint it on the board currentCard = new Card(deck.drawCard()); //make deck unclickable and make pawns clickable isDeckClickable = false; isPawnMovable = true; updateMoveOptions(currentCard.getNumber() + 1); repaint(); } } // Right Click - just for debugging purposes if ((e.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK){ // Iterate through pawns for (Pawn pawn : pawns) { if (e.getX() > pawn.getX() && e.getX() < pawn.getX()+pawnClickAreaWidth && e.getY() > pawn.getY() && e.getY() < pawn.getY()+pawnClickAreaHeight){ // Move pawn back a space pawn.moveForward(1); repaint(); } } } } public void setupPlayers(PlayerColor first, ArrayList<PlayerColor> playerColors) { players.add(first); int index = players.indexOf(first); //if the the first color was selected just add list in order if (index == 0) { playerColors.remove(first); for (PlayerColor p : playerColors) players.add(p); int swaps; if (first == PlayerColor.RED) swaps = 0; else if (first == PlayerColor.BLUE) swaps = 1; else if (first == PlayerColor.YELLOW) swaps = 2; else swaps = 3; for (int i = swaps; i > 0; i--) { Apologies.swapFirstLast(); } } else { //if first color was not selected, add colors after it, then the //ones before it to get the correct order for (int i = index + 1; i < playerColors.size(); i++) { players.add(playerColors.get(i)); } for (int i = 0; i < index; i++) { players.add(playerColors.get(i)); } } PLAYER.setText(Apologies.getNames(0) + "'s Turn"); } public void updateMoveOptions(int cardNo) { String text1 = ""; String text2 = ""; String buttonText1 = ""; String buttonText2 = ""; String blank = ""; String baseStr = "Move a pawn @"; switch (cardNo) { case 1: text1 = "from start"; text2 = "forward 1 space"; break; case 2: text1 = "from start"; text2 = "back 2 spaces"; break; case 3: text1 = "forward 3 spaces"; text2 = blank; break; case 4: text1 = "back 4 spaces"; text2 = blank; break; case 5: text1 = "forward 5 spaces"; text2 = blank; break; case 6: text1 = "forward 7 spaces"; text2 = "Split between 2 pawns"; break; case 7: text1 = "forward 8 spaces"; text2 = blank; break; case 8: text1 = "forward 10 spaces"; text2 = "back 1 space"; break; case 9: text1 = "forward 11 spaces"; text2 = "Switch places with opposing pawn"; break; case 10: text1 = "forward 12 spaces"; text2 = blank; break; case 11: text1 = "Move pawn from start to an opponent's square"; text2 = blank; break; } if (text1.startsWith("forward") || text1.startsWith("back") || text1.startsWith("from")) buttonText1 = baseStr.replace("@", text1); else buttonText1 = text1; if (text2.startsWith("forward") || text2.startsWith("back") || text2.startsWith("from")) buttonText2 = baseStr.replace("@", text2); else buttonText2 = text2; TWO_A.setText(buttonText1); TWO_B.setText(buttonText2); } public class buttonOneClicked implements ActionListener{ public void actionPerformed(ActionEvent e){ optSelected = 1; } } public class buttonTwoClicked implements ActionListener{ public void actionPerformed(ActionEvent e){ optSelected = 2; } } public class skipButtonClicked implements ActionListener{ public void actionPerformed(ActionEvent e){ optSelected = 3; } } // Unused MouseListener functions public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} } // end class
package net.openhft.chronicle; import org.junit.Test; import java.io.IOException; import static org.junit.Assert.assertEquals; /** * @author peter.lawrey */ public class IndexedChronicleTest { @Test public void singleThreaded() throws IOException { final String basePath = System.getProperty("java.io.tmpdir") + "/singleThreaded"; ChronicleTools.deleteOnExit(basePath); IndexedChronicle chronicle = new IndexedChronicle(basePath); ExcerptAppender w = chronicle.createAppender(); ExcerptTailer r = chronicle.createTailer(); OUTER: for (int i = 0; i < 50000; i++) { // System.out.println(i); w.startExcerpt(8); w.writeLong(1); /* w.writeDouble(2); w.write(3); */ w.finish(); int count = 100; do { if (count break OUTER; } while (!r.nextIndex()); long l = r.readLong(); r.finish(); assertEquals(1, l); /* double d = r.readDouble(); assertEquals(2, d, 0.0); byte b = r.readByte(); assertEquals(3, b); */ } w.close(); r.close(); } @Test public void multiThreaded() throws IOException { final String basePath = System.getProperty("java.io.tmpdir") + "/multiThreaded"; ChronicleTools.deleteOnExit(basePath); IndexedChronicle chronicle = new IndexedChronicle(basePath); final ExcerptTailer r = chronicle.createTailer(); final int runs = 1000 * 1000 * 1000; final int size = 2; long start = System.nanoTime(); Thread t = new Thread(new Runnable() { @Override public void run() { try { IndexedChronicle chronicle = new IndexedChronicle(basePath); final ExcerptAppender w = chronicle.createAppender(); for (int i = 0; i < runs; i += size) { w.startExcerpt(8 * size); for (int s = 0; s < size; s += 2) { w.writeLong(1 + i); w.writeLong(1 + i); } // w.writeDouble(2); // w.writeShort(3); // w.writeByte(4); w.finish(); } w.close(); chronicle.close(); } catch (IOException e) { e.printStackTrace(); } } }); t.start(); for (int i = 0; i < runs; i += size) { do { } while (!r.nextIndex()); try { for (int s = 0; s < size; s += 2) { long l = r.readLong(); // if (l != i + 1) // throw new AssertionError(); long l2 = r.readLong(); // if (l2 != i + 1) // throw new AssertionError(); } // double d = r.readDouble(); // short s = r.readShort(); // byte b = r.readByte(); // if (b != 4) // throw new AssertionError(); r.finish(); } catch (Exception e) { System.err.println("i= " + i); e.printStackTrace(); break; } } r.close(); long rate = runs / size * 10000L / (System.nanoTime() - start); System.out.println("Rate = " + rate / 10.0 + " Mmsg/sec"); } }
package edu.ucsf.mousedatabase.filters; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; import java.text.ParseException; import java.util.*; import java.util.concurrent.*; import javax.naming.ServiceUnavailableException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.microsoft.aad.adal4j.AuthenticationContext; import com.microsoft.aad.adal4j.AuthenticationException; import com.microsoft.aad.adal4j.AuthenticationResult; import com.microsoft.aad.adal4j.ClientCredential; import com.microsoft.aad.adal4j.UserInfo; import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.JWTParser; import com.nimbusds.oauth2.sdk.AuthorizationCode; import com.nimbusds.oauth2.sdk.http.HTTPResponse; import com.nimbusds.oauth2.sdk.token.Token; import com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse; import com.nimbusds.openid.connect.sdk.AuthenticationResponse; import com.nimbusds.openid.connect.sdk.AuthenticationResponseParser; import com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse; import edu.ucsf.mousedatabase.HTMLGeneration; import edu.ucsf.mousedatabase.Log; import org.apache.commons.lang3.StringUtils; import javax.servlet.http.Cookie; public class BasicFilter implements Filter { public static final String STATES = "states"; public static final String STATE = "state"; public static final Integer STATE_TTL = 3600; public static final String FAILED_TO_VALIDATE_MESSAGE = "Failed to validate data received from Authorization service - "; private String clientId = ""; private String clientSecret = ""; private String tenant = ""; private String authority; private List<String> adminList; public void destroy() { } private boolean isAdmin(String userId) { if (adminList.contains(userId)) { return true; } return false; } private boolean isAdminLogin(AuthenticationSuccessResponse oidcResponse) { /* * HashMap<String, String> params = new HashMap<>(); * * Map<String,String[]> parameters = httpRequest.getParameterMap(); Set<String> * keys = parameters.keySet(); for (String key : keys) { params.put(key, * parameters.get(key)[0]); } AuthenticationResponse authResponse = * AuthenticationResponseParser.parse(new URI(fullUrl), params); * AuthenticationSuccessResponse oidcResponse = (AuthenticationSuccessResponse) * authResponse; */ try { JWT idToken = oidcResponse.getIDToken(); JWTClaimsSet claims = idToken.getJWTClaimsSet(); String user = (String) claims.getClaim("objectidentifier"); return isAdmin(user); } catch (Exception e) { return false; } } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; Log.Info("is a httpservlet request"); try { String currentUri = httpRequest.getRequestURL().toString(); String queryStr = httpRequest.getQueryString(); String fullUrl = currentUri + (queryStr != null ? "?" + queryStr : ""); Log.Info("full url: " + fullUrl); // check if user has a AuthData in the session if (!AuthHelper.isAuthenticated(httpRequest)) { Log.Info("request is not authenticated"); if (AuthHelper.containsAuthenticationData(httpRequest)) { Log.Info("about to process authentication data"); processAuthenticationData(httpRequest, httpResponse, currentUri, fullUrl); chain.doFilter(request, response); return; } else { // not authenticated Log.Info("about to send auth redirect"); sendAuthRedirect(httpRequest, httpResponse); return; } } Log.Info("past try loop"); if (isAuthDataExpired(httpRequest)) { updateAuthDataUsingRefreshToken(httpRequest); } } catch (Throwable exc) { httpResponse.setStatus(500); request.setAttribute("error", exc.getMessage()); request.getRequestDispatcher("/error.jsp").forward(request, response); } } chain.doFilter(request, response); } private boolean isAuthDataExpired(HttpServletRequest httpRequest) { AuthenticationResult authData = AuthHelper.getAuthSessionObject(httpRequest); return authData.getExpiresOnDate().before(new Date()) ? true : false; } private void updateAuthDataUsingRefreshToken(HttpServletRequest httpRequest) throws Throwable { AuthenticationResult authData = getAccessTokenFromRefreshToken( AuthHelper.getAuthSessionObject(httpRequest).getRefreshToken()); setSessionPrincipal(httpRequest, authData); } private void processAuthenticationData(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String currentUri, String fullUrl) throws Throwable { HashMap<String, String> params = new HashMap<>(); Map<String, String[]> parameters = httpRequest.getParameterMap(); Set<String> keys = parameters.keySet(); for (String key : keys) { params.put(key, parameters.get(key)[0]); } // validate that state in response equals to state in request StateData stateData = validateState(httpRequest.getSession(), params.get(STATE)); AuthenticationResponse authResponse = AuthenticationResponseParser.parse(new URI(fullUrl), params); if (AuthHelper.isAuthenticationSuccessful(authResponse)) { AuthenticationSuccessResponse oidcResponse = (AuthenticationSuccessResponse) authResponse; // validate that OIDC Auth Response matches Code Flow (contains only requested // artifacts) validateAuthRespMatchesCodeFlow(oidcResponse); AuthenticationResult authData = getAccessToken(oidcResponse.getAuthorizationCode(), currentUri); // validate nonce to prevent reply attacks (code maybe substituted to one with // broader access) validateNonce(stateData, getClaimValueFromIdToken(authData.getIdToken(), "nonce")); UserInfo uInfo = authData.getUserInfo(); String uniqueId = uInfo.getUniqueId(); if (isAdmin(uniqueId)) { Log.Info("is an admin"); setSessionPrincipal(httpRequest, authData); } else { Log.Info("is not an admin"); httpRequest.getRequestDispatcher("/accessDenied.jsp").forward(httpRequest, httpResponse); return; } } else { AuthenticationErrorResponse oidcResponse = (AuthenticationErrorResponse) authResponse; throw new Exception(String.format("Request for auth code failed: %s - %s", oidcResponse.getErrorObject().getCode(), oidcResponse.getErrorObject().getDescription())); } } private void validateNonce(StateData stateData, String nonce) throws Exception { if (StringUtils.isEmpty(nonce) || !nonce.equals(stateData.getNonce())) { throw new Exception(FAILED_TO_VALIDATE_MESSAGE + "could not validate nonce"); } } private String getClaimValueFromIdToken(String idToken, String claimKey) throws ParseException { return (String) JWTParser.parse(idToken).getJWTClaimsSet().getClaim(claimKey); } private void sendAuthRedirect(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException { // use state parameter to validate response from Authorization server String state = UUID.randomUUID().toString(); // use nonce parameter to validate idToken String nonce = UUID.randomUUID().toString(); storeStateInSession(httpRequest.getSession(), state, nonce); String currentUri = httpRequest.getRequestURL().toString(); Log.Info("about to send redirect"); String redirectUrl = getRedirectUrl(currentUri, state, nonce); Log.Info("redirect url is " + redirectUrl); httpResponse.sendRedirect(redirectUrl); } /** * make sure that state is stored in the session, delete it from session - * should be used only once * * @param session * @param state * @throws Exception */ private StateData validateState(HttpSession session, String state) throws Exception { if (StringUtils.isNotEmpty(state)) { StateData stateDataInSession = removeStateFromSession(session, state); if (stateDataInSession != null) { return stateDataInSession; } } throw new Exception(FAILED_TO_VALIDATE_MESSAGE + "could not validate state"); } private void validateAuthRespMatchesCodeFlow(AuthenticationSuccessResponse oidcResponse) throws Exception { if (oidcResponse.getIDToken() != null || oidcResponse.getAccessToken() != null || oidcResponse.getAuthorizationCode() == null) { throw new Exception(FAILED_TO_VALIDATE_MESSAGE + "unexpected set of artifacts received"); } } @SuppressWarnings("unchecked") private StateData removeStateFromSession(HttpSession session, String state) { Map<String, StateData> states = (Map<String, StateData>) session.getAttribute(STATES); if (states != null) { eliminateExpiredStates(states); StateData stateData = states.get(state); if (stateData != null) { states.remove(state); return stateData; } } return null; } @SuppressWarnings("unchecked") private void storeStateInSession(HttpSession session, String state, String nonce) { if (session.getAttribute(STATES) == null) { session.setAttribute(STATES, new HashMap<String, StateData>()); } ((Map<String, StateData>) session.getAttribute(STATES)).put(state, new StateData(nonce, new Date())); } private void eliminateExpiredStates(Map<String, StateData> map) { Iterator<Map.Entry<String, StateData>> it = map.entrySet().iterator(); Date currTime = new Date(); while (it.hasNext()) { Map.Entry<String, StateData> entry = it.next(); long diffInSeconds = TimeUnit.MILLISECONDS .toSeconds(currTime.getTime() - entry.getValue().getExpirationDate().getTime()); if (diffInSeconds > STATE_TTL) { it.remove(); } } } private AuthenticationResult getAccessTokenFromRefreshToken(String refreshToken) throws Throwable { AuthenticationContext context; AuthenticationResult result = null; ExecutorService service = null; try { service = Executors.newFixedThreadPool(1); context = new AuthenticationContext(authority + tenant + "/", true, service); Future<AuthenticationResult> future = context.acquireTokenByRefreshToken(refreshToken, new ClientCredential(clientId, clientSecret), null, null); result = future.get(); } catch (ExecutionException e) { throw e.getCause(); } finally { service.shutdown(); } if (result == null) { throw new ServiceUnavailableException("authentication result was null"); } return result; } private AuthenticationResult getAccessToken(AuthorizationCode authorizationCode, String currentUri) throws Throwable { String authCode = authorizationCode.getValue(); ClientCredential credential = new ClientCredential(clientId, clientSecret); AuthenticationContext context; AuthenticationResult result = null; ExecutorService service = null; try { service = Executors.newFixedThreadPool(1); context = new AuthenticationContext(authority + tenant + "/", true, service); Future<AuthenticationResult> future = context.acquireTokenByAuthorizationCode(authCode, new URI(currentUri), credential, null); result = future.get(); } catch (ExecutionException e) { throw e.getCause(); } finally { service.shutdown(); } if (result == null) { throw new ServiceUnavailableException("authentication result was null"); } return result; } private void setSessionPrincipal(HttpServletRequest httpRequest, AuthenticationResult result) { httpRequest.getSession().setAttribute(AuthHelper.PRINCIPAL_SESSION_NAME, result); } private void removePrincipalFromSession(HttpServletRequest httpRequest) { httpRequest.getSession().removeAttribute(AuthHelper.PRINCIPAL_SESSION_NAME); } private String getRedirectUrl(String currentUri, String state, String nonce) throws UnsupportedEncodingException { String patchedUri = currentUri; if (!currentUri.contains("localhost")) { patchedUri = currentUri.replace("http:", "https:"); } String redirectUrl = authority + this.tenant + "/oauth2/authorize?response_type=code&scope=directory.read.all&response_mode=form_post&redirect_uri=" + URLEncoder.encode(patchedUri, "UTF-8") + "&client_id=" + clientId + "&resource=https%3a%2f%2fgraph.microsoft.com" + "&state=" + state + "&nonce=" + nonce; Log.Info("Redirect url is :: " + redirectUrl); return redirectUrl; } public void init(FilterConfig config) throws ServletException { adminList = Arrays.asList(System.getenv("ADMINISTRATOR_IDS").split(",")); clientId = System.getenv("AUTH_CLIENTID"); authority = System.getenv("AUTH_AUTHORITY"); tenant = System.getenv("AUTH_TENANT"); clientSecret = System.getenv("AUTH_SECRETKEY"); } private class StateData { private String nonce; private Date expirationDate; public StateData(String nonce, Date expirationDate) { this.nonce = nonce; this.expirationDate = expirationDate; } public String getNonce() { return nonce; } public Date getExpirationDate() { return expirationDate; } } }
package net.openhft.chronicle.queue; import net.openhft.chronicle.core.OS; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; public class DirectoryUtils { private static final Logger LOGGER = LoggerFactory.getLogger(DirectoryUtils.class); private static final AtomicLong TIMESTAMPER = new AtomicLong(System.currentTimeMillis()); /** * Beware, this can give different results depending on whether you are * a) running inside maven * b) are running in a clean directory (without a "target" dir) * See OS.TARGET */ @NotNull public static File tempDir(String name) { final File tmpDir = new File(OS.TARGET, name + "-" + Long.toString(TIMESTAMPER.getAndIncrement(), 36)); DeleteStatic.INSTANCE.add(tmpDir); // Log the temporary directory in OSX as it is quite obscure if (OS.isMacOSX()) { LOGGER.info("Tmp dir: {}", tmpDir); } return tmpDir; } public static void deleteDir(@NotNull File dir) { if (dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { deleteDir(file); } else if (!file.delete()) { LOGGER.warn("... unable to delete {}", file); } } } } dir.delete(); } // TODO: why not deleteOnExit? enum DeleteStatic { INSTANCE; final Set<File> toDeleteList = Collections.synchronizedSet(new LinkedHashSet<>()); { Runtime.getRuntime().addShutdownHook(new Thread( () -> toDeleteList.forEach(DirectoryUtils::deleteDir) )); } synchronized void add(File path) { toDeleteList.add(path); } } }
package org.accidia.jrz.resources; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import com.google.common.base.Strings; import org.accidia.jrz.IJrzApplication; import org.accidia.jrz.JrzApplicationTestGuid; import org.accidia.jrz.misc.MediaType; import org.accidia.jrz.protos.JrzProtos; import org.accidia.jrz.providers.ProtobufMessageReader; import org.accidia.jrz.providers.ProtobufMessageWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; public class GuidResourceTest { private final Logger logger = LoggerFactory.getLogger(getClass()); private final IJrzApplication application; private final WebTarget webTarget; public GuidResourceTest() { this.application = new JrzApplicationTestGuid(); this.webTarget = ClientBuilder.newClient() .register(ProtobufMessageReader.class) .register(ProtobufMessageWriter.class) .target(JrzApplicationTestGuid.BASE_URI); } @BeforeClass public void setUp() throws Exception { logger.debug("setUp"); this.application.startServer(); } @AfterClass public void tearDown() throws Exception { logger.debug("tearDown"); this.application.stopServer(); } @Test public void testGetGuid() { logger.debug("testGetGuid"); final JrzProtos.Guid guid = this.webTarget.path(".guid") .request(MediaType.APPLICATION_PROTOBUF).get(JrzProtos.Guid.class); assertNotNull(guid); assertFalse(Strings.isNullOrEmpty(guid.getGuid())); assertTrue(guid.getTimestampUtc() <= System.currentTimeMillis()); } @Test public void testGetStatus() { logger.debug("testGetStatus"); final JrzProtos.Status status = this.webTarget.path(".status") .request(MediaType.APPLICATION_PROTOBUF).get(JrzProtos.Status.class); assertNotNull(status); } }
package org.jscep.client; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.math.BigInteger; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.PublicKey; import java.security.SecureRandom; import java.security.cert.CertStore; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Calendar; import java.util.Collection; import java.util.Date; import javax.security.auth.x500.X500Principal; import org.bouncycastle.asn1.DERPrintableString; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; import org.bouncycastle.operator.ContentSigner; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder; import org.jscep.client.verification.OptimisticCertificateVerifier; import org.jscep.transport.response.Capabilities; import org.jscep.transport.response.Capability; import org.junit.Test; /** * This isn't really a test, but it shows how to use the API. */ public class KeyStoreExampleClientTest extends ScepServerSupport { @Test public void testExample() throws Exception { // For the sake of simplicity, we use an optimistic verifier. This has // place in production code. DefaultCallbackHandler handler = new DefaultCallbackHandler( new OptimisticCertificateVerifier()); Client client = new Client(getUrl(), handler); // Get the capabilities of the SCEP server Capabilities caps = client.getCaCapabilities(); // We construct a Bouncy Castle digital signature provider early on, // so it can be reused later. JcaContentSignerBuilder signerBuilder; if (caps.contains(Capability.SHA_1)) { signerBuilder = new JcaContentSignerBuilder("SHA1withRSA"); } else { signerBuilder = new JcaContentSignerBuilder("MD5withRSA"); } // The following variables are used to represent the SCEP client KeyPair idPair = KeyPairGenerator.getInstance("RSA").genKeyPair(); X500Name issuer = new X500Name("CN=client"); BigInteger serial = new BigInteger(16, new SecureRandom()); Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); Date notBefore = cal.getTime(); cal.add(Calendar.DATE, 2); Date notAfter = cal.getTime(); X500Name subject = issuer; PublicKey publicKey = idPair.getPublic(); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( issuer, serial, notBefore, notAfter, subject, publicKey); X509CertificateHolder idHolder = certBuilder.build(signerBuilder .build(idPair.getPrivate())); // Convert Bouncy Castle representation of X509Certificate into // something usable X509Certificate id = (X509Certificate) CertificateFactory.getInstance( "X509").generateCertificate( new ByteArrayInputStream(idHolder.getEncoded())); // The following variables are used to represent the entity being // enrolled X500Name entityName = new X500Name("CN=entity"); KeyPair entityPair = KeyPairGenerator.getInstance("RSA").genKeyPair(); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo .getInstance(entityPair.getPublic().getEncoded()); // Generate the certificate signing request PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder( entityName, publicKeyInfo); // SCEP servers usually require a challenge password csrBuilder.addAttribute( PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERPrintableString(new String("password".toCharArray()))); ContentSigner signer = signerBuilder.build(entityPair.getPrivate()); PKCS10CertificationRequest csr = csrBuilder.build(signer); // Send the enrollment request EnrollmentResponse response = client .enrol(id, idPair.getPrivate(), csr); if (response.isFailure()) { // Our request was rejected! System.out.println("Failed!"); } else if (response.isPending()) { // The server hasn't enrolled us, but we should try again. System.out.println("Pending!"); X500Principal entityPrincipal = new X500Principal( entityName.getEncoded()); // We should deal with the response to the poll too. Since this a // short-lived // test, we conveniently stop processing here. Usually you'd // schedule the poll // to run at some point in the future. // It isn't a requirement to use the same ID and private key. response = client.poll(id, idPair.getPrivate(), entityPrincipal, response.getTransactionId()); } else if (response.isSuccess()) { // The entity has been enrolled System.out.println("Success!"); // Convert the store to a certificate chain CertStore store = response.getCertStore(); Collection<? extends Certificate> certs = store .getCertificates(null); Certificate[] chain = new Certificate[certs.size()]; int i = 0; for (Certificate certificate : certs) { chain[i++] = certificate; } // Store the entity key and certificate in a key store KeyStore entityStore = KeyStore.getInstance("JKS"); entityStore.load(null, null); entityStore.setKeyEntry("entity", entityPair.getPrivate(), "secret".toCharArray(), chain); entityStore.store(new ByteArrayOutputStream(), "secret".toCharArray()); } } }
package kademlia; import java.text.DecimalFormat; /** * Class that keeps statistics for this Kademlia instance. * * These statistics are temporary and will be lost when Kad is shut down. * * @author Joshua Kissoon * @since 20140505 */ public class Statistician implements SocialKadStatistician { /* How much data was sent and received by the server over the network */ private long totalDataSent, totalDataReceived; private long numDataSent, numDataReceived; /* Bootstrap timings */ private long bootstrapTime; /* Content lookup operation timing & route length */ private int numContentLookups, numFailedContentLookups; private int numContentLookupsFUC; private int numFUCUpdatesFound; private long totalContentLookupTime; private long totalRouteLength; { this.totalDataSent = 0; this.totalDataReceived = 0; this.bootstrapTime = 0; this.numContentLookups = 0; this.totalContentLookupTime = 0; this.totalRouteLength = 0; this.numFUCUpdatesFound = 0; } @Override public void sentData(long size) { this.totalDataSent += size; this.numDataSent++; } @Override public long getTotalDataSent() { if (this.totalDataSent == 0) { return 0L; } return this.totalDataSent / 1000L; } @Override public void receivedData(long size) { this.totalDataReceived += size; this.numDataReceived++; } @Override public long getTotalDataReceived() { if (this.totalDataReceived == 0) { return 0L; } return this.totalDataReceived / 1000L; } @Override public void setBootstrapTime(long time) { this.bootstrapTime = time; } @Override public long getBootstrapTime() { return this.bootstrapTime / 1000000L; } @Override public void addContentLookup(long time, int routeLength, boolean isSuccessful) { if (isSuccessful) { this.numContentLookups++; this.totalContentLookupTime += time; this.totalRouteLength += routeLength; } else { this.numFailedContentLookups++; } } @Override public void addContentLookupFUC(long time, int routeLength, boolean updateAvailable, boolean isContentFound) { this.addContentLookup(time, routeLength, isContentFound); this.numContentLookupsFUC++; if (updateAvailable) { this.numFUCUpdatesFound++; } } @Override public int numContentLookups() { return this.numContentLookups; } @Override public int numFailedContentLookups() { return this.numFailedContentLookups; } @Override public int numContentLookupsFUC() { return this.numContentLookupsFUC; } @Override public int numFUCUpdatesFound() { return this.numFUCUpdatesFound; } @Override public long totalContentLookupTime() { return this.totalContentLookupTime; } @Override public double averageContentLookupTime() { if (this.totalContentLookupTime == 0 || this.numContentLookups == 0) { return 0D; } double avg = (double) ((double) this.totalContentLookupTime / (double) this.numContentLookups) / 1000000D; DecimalFormat df = new DecimalFormat(" return new Double(df.format(avg)); } @Override public double averageContentLookupRouteLength() { if (this.numContentLookups == 0) { return 0D; } double avg = (double) ((double) this.totalRouteLength / (double) this.numContentLookups); DecimalFormat df = new DecimalFormat(" return new Double(df.format(avg)); } @Override public String toString() { StringBuilder sb = new StringBuilder("Statistician: ["); sb.append("Bootstrap Time: "); sb.append(this.getBootstrapTime()); sb.append("; "); sb.append("Data Sent: "); sb.append("("); sb.append(this.numDataSent); sb.append(") "); sb.append(this.getTotalDataSent()); sb.append(" bytes; "); sb.append("Data Received: "); sb.append("("); sb.append(this.numDataReceived); sb.append(") "); sb.append(this.getTotalDataReceived()); sb.append(" bytes; "); sb.append("Num Content Lookups: "); sb.append(this.numContentLookups()); sb.append("(FUC: "); sb.append(this.numContentLookupsFUC()); sb.append(") "); sb.append("; "); sb.append("Avg Content Lookup Time: "); sb.append(this.averageContentLookupTime()); sb.append("; "); sb.append("Avg Content Lookup Route Lth: "); sb.append(this.averageContentLookupRouteLength()); sb.append("; "); sb.append("]"); return sb.toString(); } }
package innovimax.mixthem.operation; import innovimax.mixthem.MixException; import java.util.List; interface ILineOperation extends IOperation { /** * Processes operation and set new result in the LineResult parameter. * @param lineRange The range of lines to mix * @param result The previous operation result * @return The result of the operation (maybe null) * @throws MixException - If an mixing error occurs * @see innovimax.mixthem.operation.LineResult */ void process(List<String> lineRange, LineResult result) throws MixException; /** * Is mixing oparation is possible on line range? * @param lineRange The range of lines to mix * @return True if mixing operation is possible */ default boolean mixable(List<String> lineRange) { return true; } }
package io.github.mzmine.util.scans; import com.google.common.collect.BoundType; import com.google.common.collect.Range; import com.google.common.collect.RangeMap; import com.google.common.collect.TreeRangeMap; import com.google.common.util.concurrent.AtomicDouble; import gnu.trove.list.array.TDoubleArrayList; import io.github.mzmine.datamodel.Frame; import io.github.mzmine.datamodel.IMSRawDataFile; import io.github.mzmine.datamodel.ImsMsMsInfo; import io.github.mzmine.datamodel.MassList; import io.github.mzmine.datamodel.MassSpectrum; import io.github.mzmine.datamodel.MassSpectrumType; import io.github.mzmine.datamodel.MergedMassSpectrum; import io.github.mzmine.datamodel.MergedMsMsSpectrum; import io.github.mzmine.datamodel.MobilityScan; import io.github.mzmine.datamodel.PolarityType; import io.github.mzmine.datamodel.Scan; import io.github.mzmine.datamodel.featuredata.IonMobilogramTimeSeries; import io.github.mzmine.datamodel.features.ModularFeature; import io.github.mzmine.datamodel.impl.BuildingMobilityScan; import io.github.mzmine.datamodel.impl.SimpleFrame; import io.github.mzmine.datamodel.impl.SimpleMergedMassSpectrum; import io.github.mzmine.datamodel.impl.SimpleMergedMsMsSpectrum; import io.github.mzmine.parameters.parametertypes.tolerances.MZTolerance; import io.github.mzmine.util.DataPointSorter; import io.github.mzmine.util.MemoryMapStorage; import io.github.mzmine.util.SortingDirection; import io.github.mzmine.util.SortingProperty; import io.github.mzmine.util.maths.CenterFunction; import io.github.mzmine.util.maths.CenterMeasure; import io.github.mzmine.util.maths.Weighting; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Logger; import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class SpectraMerging { public static final double EPSILON = 1E-15; public static final CenterMeasure DEFAULT_CENTER_MEASURE = CenterMeasure.AVG; public static final Weighting DEFAULT_WEIGHTING = Weighting.LINEAR; public static final CenterFunction DEFAULT_CENTER_FUNCTION = new CenterFunction( DEFAULT_CENTER_MEASURE, DEFAULT_WEIGHTING); // for merging IMS-TOF MS1 scans ~Steffen public static final MZTolerance defaultMs1MergeTol = new MZTolerance(0.005, 15); private static final DataPointSorter sorter = new DataPointSorter(SortingProperty.Intensity, SortingDirection.Descending); private static Logger logger = Logger.getLogger(SpectraMerging.class.getName()); /** * Calculates merged intensities and mz values of all data points in the given spectrum. Ideally, * {@link MassList}s should be used so noise is filtered out by the user. * * @param source The {@link MassSpectrum} source * @param tolerance m/z tolerance to merge peaks. * @param mergingType The way to calculate intensities (avg, sum, max) * @param mzCenterFunction A function to center m/z values after merging. * @param <T> Any type of {@link MassSpectrum} * @param inputNoiseLevel A noise level to use. May be null or 0 if no noise level shall be * used. * @param outputNoiseLevel Minimum intensity to be achieved in the merged intensity. May be null * or 0. * @return double[2][] array, [0][] being the mzs, [1] being the intensities. Empty double[2][0] * if the source collection is empty. */ public static <T extends MassSpectrum> double[][] calculatedMergedMzsAndIntensities( @NotNull final Collection<T> source, @NotNull final MZTolerance tolerance, @NotNull final MergingType mergingType, @NotNull final CenterFunction mzCenterFunction, @Nullable final Double inputNoiseLevel, @Nullable final Double outputNoiseLevel) { if (source.isEmpty()) { return new double[][]{new double[0], new double[0]}; } final List<IndexedDataPoint> dataPoints = new ArrayList<>(); // extract all data points in the mass spectrum final int numDp = source.stream().mapToInt(MassSpectrum::getNumberOfDataPoints).max() .getAsInt(); final double[] rawMzs = new double[numDp]; final double[] rawIntensities = new double[numDp]; int index = 0; for (T spectrum : source) { spectrum.getMzValues(rawMzs); spectrum.getIntensityValues(rawIntensities); for (int i = 0; i < spectrum.getNumberOfDataPoints(); i++) { if (inputNoiseLevel == null || rawIntensities[i] > inputNoiseLevel) { final IndexedDataPoint dp = new IndexedDataPoint(rawMzs[i], rawIntensities[i], index); dataPoints.add(dp); } } index++; } dataPoints.sort(sorter); // set is sorted by the index of the datapoint, so we can quickly check the presence of the same index RangeMap<Double, SortedSet<IndexedDataPoint>> dataPointRanges = TreeRangeMap.create(); for (IndexedDataPoint dp : dataPoints) { // todo hash map should be smarter, just put by index SortedSet<IndexedDataPoint> dplist = dataPointRanges.get(dp.getMZ()); boolean containsIndex = false; // no entry -> make a new one if (dplist == null) { dplist = new TreeSet<>(Comparator.comparingInt(IndexedDataPoint::getIndex)); Range<Double> range = createNewNonOverlappingRange(dataPointRanges, tolerance.getToleranceRange(dp.getMZ())); dataPointRanges.put(range, dplist); } else { // we have an entry, check if if we have the same index in there already if (dp.getIndex() > dplist.first().getIndex() && dp.getIndex() < dplist.last().getIndex()) { for (IndexedDataPoint indexedDataPoint : dplist) { if (dp.getIndex() == indexedDataPoint.getIndex()) { containsIndex = true; break; } if (dp.getIndex() > indexedDataPoint.getIndex()) { break; } } } // if an entry contains that index, make a new entry (this way multiple data points from a // single scan will not be merged together) if (containsIndex) { dplist = new TreeSet<>(Comparator.comparingInt(IndexedDataPoint::getIndex)); Range<Double> range = createNewNonOverlappingRange(dataPointRanges, tolerance.getToleranceRange(dp.getMZ())); dataPointRanges.put(range, dplist); } } // now add the datapoint to the set dplist.add(dp); } final int numDps = dataPointRanges.asMapOfRanges().size(); final TDoubleArrayList newIntensities = new TDoubleArrayList(numDps); final TDoubleArrayList newMzs = new TDoubleArrayList(numDps); // now we got everything in place and have to calculate the new intensities and mzs for (Entry<Range<Double>, SortedSet<IndexedDataPoint>> entry : dataPointRanges.asMapOfRanges() .entrySet()) { double[] mzs = entry.getValue().stream().mapToDouble(IndexedDataPoint::getMZ).toArray(); double[] intensities = entry.getValue().stream().mapToDouble(IndexedDataPoint::getIntensity) .toArray(); double newMz = mzCenterFunction.calcCenter(mzs, intensities); double newIntensity = switch (mergingType) { case SUMMED -> Arrays.stream(intensities).sum(); case MAXIMUM -> Arrays.stream(intensities).max().orElse(0d); case AVERAGE -> Arrays.stream(intensities).average().orElse(0d); }; if (outputNoiseLevel == null || newIntensity > outputNoiseLevel) { newMzs.add(newMz); newIntensities.add(newIntensity); } } return new double[][]{newMzs.toArray(), newIntensities.toArray()}; } /** * Creates a new non overlapping range for this range map. Ranges are created seamless, therefore * no gaps are introduced during this process. * * @param rangeMap * @param proposedRange The proposed range must not enclose a range in this map without * overlapping, otherwise the enclosed range will be deleted. * @return */ public static Range<Double> createNewNonOverlappingRange(RangeMap<Double, ?> rangeMap, final Range<Double> proposedRange) { Entry<Range<Double>, ?> lowerEntry = rangeMap.getEntry( proposedRange.lowerBoundType() == BoundType.CLOSED ? proposedRange.lowerEndpoint() : proposedRange.lowerEndpoint() + EPSILON); Entry<Range<Double>, ?> upperEntry = rangeMap.getEntry( proposedRange.upperBoundType() == BoundType.CLOSED ? proposedRange.upperEndpoint() : proposedRange.upperEndpoint() - EPSILON); if (lowerEntry == null && upperEntry == null) { return proposedRange; } if (lowerEntry != null && proposedRange.intersection(lowerEntry.getKey()).isEmpty() && upperEntry == null) { return proposedRange; } if (upperEntry != null && proposedRange.intersection(upperEntry.getKey()).isEmpty() && lowerEntry == null) { return proposedRange; } if (upperEntry != null && lowerEntry != null && proposedRange.intersection(lowerEntry.getKey()) .isEmpty() && proposedRange.intersection(upperEntry.getKey()).isEmpty()) { return proposedRange; } BoundType lowerBoundType = proposedRange.lowerBoundType(); BoundType upperBoundType = proposedRange.upperBoundType(); double lowerBound = proposedRange.lowerEndpoint(); double upperBound = proposedRange.upperEndpoint(); // check if the ranges actually overlap or if they are closed and open if (lowerEntry != null && !proposedRange.intersection(lowerEntry.getKey()).isEmpty()) { lowerBound = lowerEntry.getKey().upperEndpoint(); lowerBoundType = BoundType.OPEN; } if (upperEntry != null && !proposedRange.intersection(upperEntry.getKey()).isEmpty()) { upperBound = upperEntry.getKey().lowerEndpoint(); upperBoundType = BoundType.OPEN; } return createNewNonOverlappingRange(rangeMap, Range.range(lowerBound, lowerBoundType, upperBound, upperBoundType)); } /** * Creates a merged MS/MS spectrum for a PASEF {@link ImsMsMsInfo}. * * @param info The MS/MS info to create a merged spectrum for * @param tolerance The m/z tolerence to merge peaks from separate mobility scans with. * @param mergingType The merging type. Usually {@link MergingType#SUMMED}. * @param storage The storage to use or null. * @param mobilityRange If the MS/MS shall only be created for a specific mobility range, e.g., * in the case of isomeric features that have been resolved. * @param outputNoiseLevel Minimum intensity to be achieved in the merged intensity. May be null * * or 0. * @return A {@link MergedMsMsSpectrum} or null the spectrum would not have any data points. */ @Nullable public static MergedMsMsSpectrum getMergedMsMsSpectrumForPASEF(@NotNull final ImsMsMsInfo info, @NotNull final MZTolerance tolerance, @NotNull final MergingType mergingType, @Nullable final MemoryMapStorage storage, @Nullable Range<Float> mobilityRange, @Nullable final Double outputNoiseLevel) { final Range<Integer> spectraNumbers = info.getSpectrumNumberRange(); final Frame frame = info.getFrameNumber(); final float collisionEnergy = info.getCollisionEnergy(); final double precursorMz = info.getLargestPeakMz(); List<MobilityScan> mobilityScans = frame.getMobilityScans().stream().filter( ms -> spectraNumbers.contains(ms.getMobilityScanNumber()) && (mobilityRange == null || mobilityRange.contains((float) ms.getMobility()))).collect(Collectors.toList()); if (mobilityScans.isEmpty()) { return null; } final CenterFunction cf = DEFAULT_CENTER_FUNCTION; final List<MassList> massLists = mobilityScans.stream().map(MobilityScan::getMassList).filter( Objects::nonNull).collect(Collectors.toList()); if (massLists.isEmpty()) { logger.info( "Cannot calculate a merged MS/MS spectrum, because MS2 Scans do not contain a MassList."); return null; } final double[][] merged = calculatedMergedMzsAndIntensities(massLists, tolerance, mergingType, cf, null, outputNoiseLevel); if (merged[0].length == 0) { return null; } return new SimpleMergedMsMsSpectrum(storage, merged[0], merged[1], precursorMz, info.getPrecursorCharge(), collisionEnergy, frame.getMSLevel(), mobilityScans, mergingType, cf); } /** * Merges Multiple MS/MS spectra with the same collision energy into a single MS/MS spectrum. * * @param spectra The source spectra, may be of multiple collision energies. * @param tolerance The mz tolerance to merch peaks in a spectrum * @param mergingType Specifies the way to treat intensities (sum, avg, max) * @param storage The storage to use. * @return A list of all merged spectra (Spectra with the same collision energy have been merged). */ public static List<MergedMsMsSpectrum> mergeMsMsSpectra( @NotNull final Collection<MergedMsMsSpectrum> spectra, @NotNull final MZTolerance tolerance, @NotNull final MergingType mergingType, @Nullable final MemoryMapStorage storage) { final CenterFunction cf = new CenterFunction(CenterMeasure.AVG, Weighting.LINEAR); final List<MergedMsMsSpectrum> mergedSpectra = new ArrayList<>(); // group spectra with the same CE into the same list final Map<Float, List<MergedMsMsSpectrum>> grouped = spectra.stream() .collect(Collectors.groupingBy(spectrum -> spectrum.getCollisionEnergy())); for (final Entry<Float, List<MergedMsMsSpectrum>> entry : grouped.entrySet()) { final MergedMsMsSpectrum spectrum = entry.getValue().get(0); final double[][] mzIntensities = calculatedMergedMzsAndIntensities(entry.getValue(), tolerance, mergingType, cf, null, null); if (mzIntensities[0].length == 0) { continue; } final List<MassSpectrum> sourceSpectra = entry.getValue().stream() .flatMap(s -> s.getSourceSpectra().stream()).collect(Collectors.toList()); final MergedMsMsSpectrum mergedMsMsSpectrum = new SimpleMergedMsMsSpectrum(storage, mzIntensities[0], mzIntensities[1], spectrum.getPrecursorMZ(), spectrum.getPrecursorCharge(), spectrum.getCollisionEnergy(), spectrum.getMSLevel(), sourceSpectra, mergingType, cf); mergedSpectra.add(mergedMsMsSpectrum); } return mergedSpectra; } @Nullable public static MergedMassSpectrum extractSummedMobilityScan(@NotNull final ModularFeature f, @NotNull final MZTolerance tolerance, @NotNull final Range<Float> mobilityRange, @Nullable final MemoryMapStorage storage) { return extractSummedMobilityScan(f, tolerance, mobilityRange, Range.all(), storage); } @Nullable public static MergedMassSpectrum extractSummedMobilityScan(@NotNull final ModularFeature f, @NotNull final MZTolerance tolerance, @NotNull final Range<Float> mobilityRange, @NotNull final Range<Float> rtRange, @Nullable final MemoryMapStorage storage) { if (!(f.getFeatureData() instanceof IonMobilogramTimeSeries series)) { return null; } final List<MobilityScan> scans = series.getMobilograms().stream() .<MobilityScan>mapMulti((s, c) -> { for (var spectrum : s.getSpectra()) { if (mobilityRange.contains((float) spectrum.getMobility()) && rtRange .contains(spectrum.getRetentionTime())) { c.accept(spectrum); } } }).toList(); // todo use mass lists over raw scans to merge (separate PR) final double merged[][] = calculatedMergedMzsAndIntensities(scans, tolerance, MergingType.SUMMED, DEFAULT_CENTER_FUNCTION, null, null); return new SimpleMergedMassSpectrum(storage, merged[0], merged[1], 1, scans, MergingType.SUMMED, DEFAULT_CENTER_FUNCTION); } /** * @return A summed spectrum with the given tolerances. */ public static <T extends MassSpectrum> MergedMassSpectrum mergeSpectra( final @NotNull List<T> source, @NotNull final MZTolerance tolerance, @Nullable final MemoryMapStorage storage) { // if we have mass lists, use them to merge. final List<? extends MassSpectrum> spectra; if (source.stream().allMatch(s -> s instanceof Scan)) { spectra = source.stream().map(s -> ((Scan) s).getMassList()).toList(); } else { spectra = source; } final double[][] mzIntensities = calculatedMergedMzsAndIntensities(spectra, tolerance, MergingType.SUMMED, DEFAULT_CENTER_FUNCTION, null, null); final int msLevel = source.stream().filter(s -> s instanceof Scan) .mapToInt(s -> ((Scan) s).getScanNumber()).min().orElse(1); return new SimpleMergedMassSpectrum(storage, mzIntensities[0], mzIntensities[1], msLevel, source, MergingType.SUMMED, DEFAULT_CENTER_FUNCTION); } public static Frame getMergedFrame(@NotNull final Collection<Frame> frames, @NotNull final MZTolerance tolerance, @Nullable final MemoryMapStorage storage, final int mobilityScanBin, @NotNull final AtomicDouble progress) { if (frames.isEmpty()) { throw new IllegalStateException("No frames in collection to be merged."); } final Frame aFrame = frames.stream().findAny().get(); final int msLevel = aFrame.getMSLevel(); final PolarityType polarityType = aFrame.getPolarity(); float lowestRt = Float.MAX_VALUE; float highestRt = Float.MIN_VALUE; Range<Double> scanMzRange = aFrame.getScanningMZRange(); // map all mobility scans that shall be merged together into the same list final Map<Integer, List<MobilityScan>> scanMap = new HashMap<>(); for (final Frame frame : frames) { for (final MobilityScan mobilityScan : frame.getMobilityScans()) { final List<MobilityScan> mobilityScans = scanMap .computeIfAbsent(mobilityScan.getMobilityScanNumber() / mobilityScanBin, i -> new ArrayList<>()); mobilityScans.add(mobilityScan); } if (frame.getRetentionTime() < lowestRt) { lowestRt = frame.getRetentionTime(); } if (frame.getRetentionTime() > highestRt) { highestRt = frame.getRetentionTime(); } if (!scanMzRange.equals(frame.getScanningMZRange()) && !scanMzRange .encloses(frame.getScanningMZRange())) { scanMzRange = scanMzRange.span(frame.getScanningMZRange()); } if (msLevel != frame.getMSLevel()) { throw new AssertionError("Cannot merge frames of different MS levels"); } if (polarityType != frame.getPolarity()) { throw new AssertionError("Cannot merge frames of different polarities"); } } final CenterFunction cf = new CenterFunction(CenterMeasure.AVG, CenterFunction.DEFAULT_MZ_WEIGHTING); final IMSRawDataFile file = (IMSRawDataFile) frames.stream().findAny().get().getDataFile(); final SimpleFrame frame = new SimpleFrame(file, -1, msLevel, (highestRt + lowestRt) / 2, 0d, 0, null, null, MassSpectrumType.CENTROIDED, polarityType, "Merged frame (" + frames.stream() + ")", scanMzRange, aFrame.getMobilityType(), null); final AtomicInteger processed = new AtomicInteger(0); final double totalFrames = scanMap.size(); // create a merged spectrum for each mobility scan bin final List<BuildingMobilityScan> buildingMobilityScans = scanMap.entrySet().parallelStream() .map(entry -> { final List<MassList> massLists = entry.getValue().stream().map(MobilityScan::getMassList) .collect(Collectors.toList()); if (massLists.size() != entry.getValue().size()) { throw new IllegalArgumentException( "Not all mobility scans contain a mass list. Cannot merge Frames."); } double[][] mzIntensities = calculatedMergedMzsAndIntensities(massLists, tolerance, MergingType.SUMMED, cf, null, null); processed.getAndIncrement(); progress.set(processed.get() / totalFrames); return new BuildingMobilityScan(entry.getKey(), mzIntensities[0], mzIntensities[1]); }).sorted(Comparator.comparingInt(BuildingMobilityScan::getMobilityScanNumber)) .collect(Collectors.toList()); final double[] mobilities = new double[scanMap.size()]; int i = 0; for (Integer num : scanMap.keySet()) { mobilities[i] = aFrame.getMobilityScan(Math.min(num * mobilityScanBin + (mobilityScanBin / 2), aFrame.getNumberOfMobilityScans() - 1)).getMobility(); i++; } frame.setMobilityScans(buildingMobilityScans); frame.setMobilities(mobilities); double[][] mergedSpectrum = calculatedMergedMzsAndIntensities(buildingMobilityScans, tolerance, MergingType.SUMMED, cf, null, null); frame.setDataPoints(mergedSpectrum[0], mergedSpectrum[1]); return frame; } public enum MergingType { SUMMED, MAXIMUM, AVERAGE } }
package io.joshworks.restclient.http; import org.apache.http.HttpHost; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponseInterceptor; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.client.CookieStore; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.config.RequestConfig; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.impl.client.BasicCookieStore; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.function.Function; public class ClientBuilder { private CredentialsProvider credentialsProvider; private int maxTotal = 20; private int maxRoute = 2; private String baseUrl = ""; private Function<String, String> urlTransformer = (url) -> url; private Map<String, Object> defaultHeaders = new HashMap<>(); private RequestConfig.Builder configBuilder = RequestConfig.custom(); private List<HttpRequestInterceptor> requestInterceptors = new LinkedList<>(); private List<HttpResponseInterceptor> responseInterceptor = new LinkedList<>(); private final CookieStore cookieStore = new BasicCookieStore(); ClientBuilder() { } public RestClient build() { try { RequestConfig clientConfig = configBuilder.build(); PoolingHttpClientConnectionManager syncConnectionManager = new PoolingHttpClientConnectionManager(); syncConnectionManager.setMaxTotal(maxTotal); syncConnectionManager.setDefaultMaxPerRoute(maxRoute); CloseableHttpClient syncClient = createSyncClient(clientConfig, syncConnectionManager); DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(); PoolingNHttpClientConnectionManager asyncConnectionManager = new PoolingNHttpClientConnectionManager(ioReactor); asyncConnectionManager.setMaxTotal(maxTotal); asyncConnectionManager.setDefaultMaxPerRoute(maxRoute); CloseableHttpAsyncClient asyncClient = createAsyncClient(clientConfig, asyncConnectionManager); RestClient restClient = new RestClient(baseUrl, defaultHeaders, urlTransformer, asyncConnectionManager, syncConnectionManager, asyncClient, syncClient, cookieStore); ClientContainer.addClient(restClient); return restClient; } catch (Exception e) { throw new RuntimeException(e); } } private CloseableHttpAsyncClient createAsyncClient(RequestConfig clientConfig, PoolingNHttpClientConnectionManager manager) { HttpAsyncClientBuilder asyncBuilder = HttpAsyncClientBuilder.create() .setDefaultRequestConfig(clientConfig) .setDefaultCookieStore(cookieStore) .setConnectionManager(manager); return addInterceptors(asyncBuilder).build(); } private CloseableHttpClient createSyncClient(RequestConfig clientConfig, HttpClientConnectionManager manager) { HttpClientBuilder syncBuilder = HttpClientBuilder.create() .setDefaultRequestConfig(clientConfig) .setDefaultCookieStore(cookieStore) .setDefaultCredentialsProvider(credentialsProvider) .setConnectionManager(manager); return addInterceptors(syncBuilder).build(); } private HttpClientBuilder addInterceptors(HttpClientBuilder builder) { for (HttpRequestInterceptor interceptor : requestInterceptors) { builder.addInterceptorLast(interceptor); } for (HttpResponseInterceptor interceptor : responseInterceptor) { builder.addInterceptorLast(interceptor); } return builder; } private HttpAsyncClientBuilder addInterceptors(HttpAsyncClientBuilder builder) { for (HttpRequestInterceptor interceptor : requestInterceptors) { builder.addInterceptorLast(interceptor); } for (HttpResponseInterceptor interceptor : responseInterceptor) { builder.addInterceptorLast(interceptor); } return builder; } public ClientBuilder baseUrl(String baseUrl) { this.baseUrl = baseUrl; return this; } public ClientBuilder defaultHeader(String key, String value) { this.defaultHeaders.put(key, value); return this; } public ClientBuilder followRedirect(boolean followRedirect) { configBuilder.setRedirectsEnabled(followRedirect); return this; } public ClientBuilder interceptor(HttpRequestInterceptor interceptor) { this.requestInterceptors.add(interceptor); return this; } public ClientBuilder interceptor(HttpResponseInterceptor interceptor) { this.responseInterceptor.add(interceptor); return this; } public ClientBuilder defaultHeader(String key, long value) { this.defaultHeaders.put(key, value); return this; } public ClientBuilder credentialProvider(CredentialsProvider provider) { this.credentialsProvider = provider; return this; } public ClientBuilder urlTransformer(Function<String, String> transformer) { this.urlTransformer = transformer; return this; } public ClientBuilder cookieSpec(String cookieSpec) { configBuilder.setCookieSpec(cookieSpec); return this; } public ClientBuilder proxy(HttpHost proxy) { configBuilder.setProxy(proxy); return this; } public ClientBuilder proxy(HttpHost proxy, Credentials credentials) { this.credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()), credentials); return this.proxy(proxy); } /** * Set the connection timeout and socket timeout * * @param connectionTimeout The timeout until a connection with the server is established (in milliseconds). Default is 10000. Set to zero to disable the timeout. * @param readTimeout The timeout to receive data (in milliseconds). Default is 60000. Set to zero to disable the timeout. */ public ClientBuilder timeout(int connectionTimeout, int readTimeout) { configBuilder.setSocketTimeout(readTimeout).setConnectTimeout(connectionTimeout); return this; } /** * Set the concurrency levels * * @param maxTotal Defines the overall connection limit for a connection pool. Default is 20. */ public ClientBuilder concurrency(int maxTotal) { this.maxTotal = maxTotal; return this; } /** * Set the concurrency levels per host * * @param maxRoute Defines the connection limit for a connection pool per host. Default is 2. */ public ClientBuilder routeConcurrency(int maxRoute){ this.maxRoute = maxRoute; return this; } }
package io.sinistral.proteus.server; import java.net.URI; import java.nio.ByteBuffer; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.google.inject.Inject; import io.sinistral.proteus.server.predicates.ServerPredicates; import io.undertow.io.IoCallback; import io.undertow.server.DefaultResponseListener; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.Cookie; import io.undertow.util.HeaderMap; import io.undertow.util.HeaderValues; import io.undertow.util.Headers; import io.undertow.util.HttpString; import io.undertow.util.StatusCodes; /** * @author jbauer * Base server response. Friendlier interface to underlying exchange. * @TODO extend javax.ws.rs.core.Response */ public class ServerResponse<T> { private static Logger log = LoggerFactory.getLogger(ServerResponse.class.getCanonicalName()); @Inject protected static XmlMapper XML_MAPPER; @Inject protected static ObjectMapper OBJECT_MAPPER; protected ByteBuffer body; protected int status = StatusCodes.OK; protected final HeaderMap headers = new HeaderMap(); protected final Map<String, Cookie> cookies = new HashMap<>(); protected String contentType = null; protected T entity; protected Throwable throwable; // protected Class<? extends JsonContext> jsonContext; protected IoCallback ioCallback; protected boolean hasCookies = false; protected boolean hasHeaders = false; protected boolean hasIoCallback = false; protected boolean processXml = false; protected boolean processJson = false; protected boolean preprocessed = false; protected String location = null; public ServerResponse() { } public ByteBuffer getBody() { return body; } public int getStatus() { return this.status; } public Map<String, Cookie> getCookies() { return this.cookies; } public HeaderMap getHeaders() { return this.headers; } public ServerResponse<T> addHeader(HttpString headerName, String headerValue) { this.headers.add(headerName, headerValue); this.hasHeaders = true; return this; } public ServerResponse<T> addHeader(String headerString, String headerValue) { HttpString headerName = HttpString.tryFromString(headerString); this.headers.add(headerName, headerValue); this.hasHeaders = true; return this; } public ServerResponse<T> setHeader(HttpString headerName, String headerValue) { this.headers.put(headerName, headerValue); this.hasHeaders = true; return this; } public ServerResponse<T> setHeader(String headerString, String headerValue) { HttpString headerName = HttpString.tryFromString(headerString); this.headers.put(headerName, headerValue); this.hasHeaders = true; return this; } /** * @return the contentType */ public String getContentType() { return contentType; } /** * @return the callback */ public IoCallback getIoCallback() { return ioCallback; } /** * @param ioCallback * the ioCallback to set */ public void setIoCallback(IoCallback ioCallback) { this.ioCallback = ioCallback; } /** * @param body * the body to set */ public void setBody(ByteBuffer body) { this.body = body; } /** * @param status * the status to set */ public void setStatus(int status) { this.status = status; } /** * @param status * the status to set */ public void setStatus(Response.Status status) { this.status = status.getStatusCode(); } /** * @param contentType * the contentType to set */ protected void setContentType(String contentType) { this.contentType = contentType; if (this.contentType.equals(javax.ws.rs.core.MediaType.APPLICATION_JSON)) { if (!this.preprocessed) { this.processJson = true; } } else if (this.contentType.equals(javax.ws.rs.core.MediaType.APPLICATION_XML)) { if (!this.preprocessed) { this.processXml = true; } } } public ServerResponse<T> body(ByteBuffer body) { this.body = body; this.preprocessed = true; return this; } public ServerResponse<T> body(String body) { return this.body(ByteBuffer.wrap(body.getBytes())); } public ServerResponse<T> entity(T entity) { this.entity = entity; this.preprocessed = false; return this; } public ServerResponse<T> lastModified(Date date) { this.headers.put(Headers.LAST_MODIFIED, date.getTime()); return this; } public ServerResponse<T> contentLanguage(Locale locale) { this.headers.put(Headers.CONTENT_LANGUAGE, locale.toLanguageTag()); return this; } public ServerResponse<T> contentLanguage(String language) { this.headers.put(Headers.CONTENT_LANGUAGE, language); return this; } public ServerResponse<T> throwable(Throwable throwable) { this.throwable = throwable; if (this.status == StatusCodes.ACCEPTED) { return badRequest(throwable); } return this; } public ServerResponse<T> status(int status) { this.status = status; return this; } public ServerResponse<T> header(HttpString headerName, String value) { this.headers.put(headerName, value); this.hasHeaders = true; return this; } public ServerResponse<T> cookie(String cookieName, Cookie cookie) { this.cookies.put(cookieName, cookie); this.hasCookies = true; return this; } public ServerResponse<T> contentType(String contentType) { this.setContentType(contentType); return this; } public ServerResponse<T> contentType(javax.ws.rs.core.MediaType mediaType) { this.setContentType(mediaType.toString()); return this; } public ServerResponse<T> contentType(MediaType mediaType) { this.setContentType(mediaType.contentType()); return this; } public ServerResponse<T> applicationJson() { if (!this.preprocessed) { this.processJson = true; } this.contentType = javax.ws.rs.core.MediaType.APPLICATION_JSON; return this; } public ServerResponse<T> textHtml() { this.contentType = javax.ws.rs.core.MediaType.TEXT_HTML; return this; } public ServerResponse<T> applicationOctetStream() { this.contentType = javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM; return this; } public ServerResponse<T> applicationXml() { if (!this.preprocessed) { this.processXml = true; } this.contentType = javax.ws.rs.core.MediaType.APPLICATION_XML; return this; } public ServerResponse<T> textPlain() { this.contentType = javax.ws.rs.core.MediaType.TEXT_PLAIN; return this; } // public ServerResponse<T> jsonContext(Class<? extends JsonContext> context) // this.jsonContext = context; // return this; public ServerResponse<T> ok() { this.status = StatusCodes.OK; return this; } public ServerResponse<T> redirect(String location) { this.location = location; this.status = StatusCodes.FOUND; return this; } public ServerResponse<T> redirectPermanently(String location) { this.location = location; this.status = StatusCodes.MOVED_PERMANENTLY;; return this; } public ServerResponse<T> found() { this.status = StatusCodes.FOUND; return this; } public ServerResponse<T> accepted() { this.status = StatusCodes.ACCEPTED; return this; } public ServerResponse<T> badRequest() { this.status = StatusCodes.BAD_REQUEST; return this; } public ServerResponse<T> badRequest(Throwable t) { this.throwable = t; return this.badRequest(); } public ServerResponse<T> badRequest(String message) { return this.errorMessage(message).badRequest(); } public ServerResponse<T> internalServerError() { this.status = StatusCodes.INTERNAL_SERVER_ERROR; return this; } public ServerResponse<T> internalServerError(Throwable t) { this.throwable = t; return this.internalServerError(); } public ServerResponse<T> internalServerError(String message) { return this.errorMessage(message).internalServerError(); } public ServerResponse<T> created() { this.status = StatusCodes.CREATED; return this; } public ServerResponse<T> created(String location) { this.status = StatusCodes.CREATED; this.location = location; return this; } public ServerResponse<T> created(URI uri) { this.status = StatusCodes.CREATED; this.location = uri.toString(); return this; } public ServerResponse<T> notModified() { this.status = StatusCodes.NOT_MODIFIED; return this; } public ServerResponse<T> notFound() { this.status = StatusCodes.NOT_FOUND; return this; } public ServerResponse<T> notFound(Throwable t) { this.throwable = t; return this.notFound(); } public ServerResponse<T> notFound(String message) { return this.errorMessage(message).notFound(); } public ServerResponse<T> forbidden() { this.status = StatusCodes.FORBIDDEN; return this; } public ServerResponse<T> forbidden(Throwable t) { this.throwable = t; return this.forbidden(); } public ServerResponse<T> forbidden(String message) { return this.errorMessage(message).forbidden(); } public ServerResponse<T> noContent() { this.status = StatusCodes.NO_CONTENT; return this; } public ServerResponse<T> noContent(Throwable t) { this.throwable = t; return this.noContent(); } public ServerResponse<T> noContent(String message) { return this.errorMessage(message).noContent(); } public ServerResponse<T> serviceUnavailable() { this.status = StatusCodes.SERVICE_UNAVAILABLE; return this; } public ServerResponse<T> serviceUnavailable(Throwable t) { this.throwable = t; return this.serviceUnavailable(); } public ServerResponse<T> serviceUnavailable(String message) { return this.errorMessage(message).serviceUnavailable(); } public ServerResponse<T> unauthorized() { this.status = StatusCodes.UNAUTHORIZED; return this; } public ServerResponse<T> unauthorized(Throwable t) { this.throwable = t; return this.unauthorized(); } public ServerResponse<T> unauthorized(String message) { return this.errorMessage(message).unauthorized(); } public ServerResponse<T> errorMessage(String message) { this.throwable = new Throwable(message); return this; } public ServerResponse<T> withIoCallback(IoCallback ioCallback) { this.ioCallback = ioCallback; this.hasIoCallback = ioCallback == null; return this; } public void send(final HttpServerExchange exchange) throws RuntimeException { send(null, exchange); } public void send(final HttpHandler handler, final HttpServerExchange exchange) throws RuntimeException { exchange.setStatusCode(this.status); if(this.location != null) { exchange.getResponseHeaders().put(Headers.LOCATION, this.location); } if(this.status == StatusCodes.TEMPORARY_REDIRECT || this.status == StatusCodes.PERMANENT_REDIRECT) { exchange.endExchange(); return; } final boolean hasBody = this.body != null; final boolean hasEntity = this.entity != null; final boolean hasError = this.throwable != null; if (this.hasHeaders) { long itr = this.headers.fastIterateNonEmpty(); while (itr != -1L) { final HeaderValues values = this.headers.fiCurrent(itr); exchange.getResponseHeaders().putAll(values.getHeaderName(), values); itr = this.headers.fiNextNonEmpty(itr); } } if (this.hasCookies) { exchange.getResponseCookies().putAll(this.cookies); } if (this.contentType != null) { exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, this.contentType); } else if (!this.processJson && !this.processXml) { if (ServerPredicates.ACCEPT_JSON_PREDICATE.resolve(exchange)) { this.applicationJson(); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, this.contentType); } else if (ServerPredicates.ACCEPT_XML_PREDICATE.resolve(exchange)) { this.applicationXml(); exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, this.contentType); } } if (hasError) { exchange.putAttachment(DefaultResponseListener.EXCEPTION, throwable); return; } if (hasBody) { if (!this.hasIoCallback) { exchange.getResponseSender().send(this.body); } else { exchange.getResponseSender().send(this.body, this.ioCallback); } } else if (hasEntity) { try { if (this.processXml) { exchange.getResponseSender().send(ByteBuffer.wrap(XML_MAPPER.writeValueAsBytes(this.entity))); } else { exchange.getResponseSender().send(ByteBuffer.wrap(OBJECT_MAPPER.writeValueAsBytes(this.entity))); } } catch (Exception e) { log.error(e.getMessage() + " for entity " + this.entity, e); throw new IllegalArgumentException(e); } } else { exchange.endExchange(); } } /** * Creates builder to build {@link ServerResponse}. * * @return created builder */ public static <T> ServerResponse<T> response(Class<T> clazz) { return new ServerResponse<T>(); } public static ServerResponse<ByteBuffer> response(ByteBuffer body) { return new ServerResponse<ByteBuffer>().body(body); } public static ServerResponse<ByteBuffer> response(String body) { return new ServerResponse<ByteBuffer>().body(body); } public static <T> ServerResponse<T> response(T entity) { return new ServerResponse<T>().entity(entity); } @SuppressWarnings("rawtypes") public static ServerResponse response() { return new ServerResponse(); } }
package me.deftware.client.framework.utils; import net.minecraft.client.renderer.texture.DynamicTexture; import net.minecraft.client.renderer.texture.NativeImage; import org.lwjgl.opengl.GL11; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.io.ByteArrayInputStream; import java.io.IOException; import static org.lwjgl.opengl.GL11.*; public class Texture { /* int width; int height; DynamicTexture dynamicTexture; NativeImage nativeImage; public Texture(int width, int height, boolean clear) { this.width = width; this.height = height; this.nativeImage = new NativeImage(NativeImage.PixelFormat.RGBA, width, height, clear); this.dynamicTexture = new DynamicTexture(nativeImage); } public int getHeight() { return height; } public int getWidth() { return width; } public void refreshParameters(){ this.width = nativeImage.getWidth(); this.height = nativeImage.getHeight(); } public int fillFromBufferedImage(BufferedImage img){ try { this.nativeImage = new NativeImage(img.getWidth(), img.getHeight(), true); for(int width = 0; width<img.getWidth(); width++){ for(int height = 0; height<img.getHeight(); height++){ this.setPixel(width, height, img.getRGB(width, height)); } } this.refreshParameters(); } catch (Exception e) { e.printStackTrace(); return 2; } return 0; } public int fillFromBufferedRGBImage(BufferedImage img){ byte[] imageBytes = ((DataBufferByte) img.getData().getDataBuffer()).getData(); try { this.nativeImage = NativeImage.read(NativeImage.PixelFormat.RGB, new ByteArrayInputStream(imageBytes)); this.dynamicTexture.setTextureData(nativeImage); this.refreshParameters(); } catch (IOException ioe){ return 1; } catch (Exception e) { e.printStackTrace(); return 2; } return 0; } public int clearPixels(){ try { for(int x = 0; x<nativeImage.getWidth(); x++) { for(int y = 0; y<nativeImage.getHeight(); y++) { int rgb = ((0xFF) << 24) | ((0xFF) << 16) | ((0xFF) << 8) | ((0xFF) << 0); this.setPixel(x,y, rgb); } } this.dynamicTexture.setTextureData(this.nativeImage); } catch (Exception e) { e.printStackTrace(); return 1; } return 0; } public void setPixel(int x, int y, int red, int green, int blue){ int rgb = ((red & 0xFF) << 16) | ((green & 0xFF) << 8) | ((blue & 0xFF)); this.nativeImage.setPixelRGBA(x, y, rgb); } public void setPixel(int x, int y, int red, int green, int blue, int alpha){ int rgba = ((alpha & 0xFF) << 24) | ((red & 0xFF) << 16) | ((green & 0xFF) << 8) | ((blue & 0xFF)); this.nativeImage.setPixelRGBA(x, y, rgba); } public void setPixel(int x, int y, int rgba){ this.nativeImage.setPixelRGBA(x, y, rgba); } public int getPixel(int x, int y){ return this.nativeImage.getPixelRGBA(x, y); } public byte getAlpha(int x, int y){ return this.nativeImage.getPixelAlpha(x, y); } public int updatePixels(){ try { this.dynamicTexture.setTextureData(nativeImage); } catch (Exception e) { e.printStackTrace(); return 1; } return 0; } public void updateTexture(){ this.dynamicTexture.updateDynamicTexture(); } public int update(){ int errorCode = 0; errorCode += this.updateTexture(); this.refreshParameters(); errorCode += this.updatePixels(); return errorCode; } public void bind(){ this.bind(GL_ONE); } public void bind(int blendfunc){ GL11.glEnable(GL_BLEND); GL11.glBlendFunc(GL_SRC_ALPHA, blendfunc); this.blindBind(); } public void blindBind(){ this.dynamicTexture.bindTexture(); } public void unbind(){ if(GL11.glIsEnabled(GL_BLEND)) GL11.glDisable(GL_BLEND); } public void destroy() { nativeImage.close(); nativeImage = null; dynamicTexture.close(); dynamicTexture = null; } */ }
package net.shadowfacts.enfusion.recipes; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import net.shadowfacts.enfusion.block.EFBlocks; import net.shadowfacts.enfusion.item.EFItems; public class EFRecipes { public static void registerRecipes() { registerBlockRecipes(); registerItemRecipes(); registerFurnaceRecipes(); } private static void registerBlockRecipes() { // Green Zinchorium Light GameRegistry.addShapedRecipe(new ItemStack(EFBlocks.greenZinchoriumLightIdle, 1), "IGI", "GLG", "IGI", 'I', new ItemStack(EFItems.zinchoriumAlloyIngot), 'G', new ItemStack(Blocks.glass), 'L', new ItemStack(EFItems.lightBulb, 1)); // Zinchorium Block GameRegistry.addShapedRecipe(new ItemStack(EFBlocks.blockZinchorium), "ZZZ", "ZZZ", "ZZZ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Solar Panel Tier 1 GameRegistry.addShapedRecipe(new ItemStack(EFBlocks.solarPanelTier1), "MMM", "CFC", "CCC", 'M', new ItemStack(EFItems.mirror), 'C', new ItemStack(Blocks.cobblestone), 'F', new ItemStack(EFItems.basicCapacitor)); // Solar Panel Tier 2 GameRegistry.addShapelessRecipe(new ItemStack(EFBlocks.solarPanelTier2), new ItemStack(EFBlocks.solarPanelTier1), new ItemStack(EFItems.enhancedCapacitor), new ItemStack(EFBlocks.solarPanelTier1)); // Solar Panel Tier 3 GameRegistry.addShapelessRecipe(new ItemStack(EFBlocks.solarPanelTier3), new ItemStack(EFBlocks.solarPanelTier2), new ItemStack(EFItems.energeticCapacitor), new ItemStack(EFBlocks.solarPanelTier1)); // Solar Panel Tier 4 GameRegistry.addShapelessRecipe(new ItemStack(EFBlocks.solarPanelTier4), new ItemStack(EFBlocks.solarPanelTier3), new ItemStack(EFItems.hyperEnergeticCapacitor), new ItemStack(EFBlocks.solarPanelTier3)); // Zinchorium Furnace GameRegistry.addShapedRecipe(new ItemStack(EFBlocks.zinchoriumFurnace), "ZZZ", "ZFZ", "ZZZ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'F', new ItemStack(Blocks.furnace)); } private static void registerItemRecipes() { // Light bulb GameRegistry.addShapedRecipe(new ItemStack(EFItems.lightBulb), "GGG", "GOG", "III", 'G', new ItemStack(Blocks.glass), 'O', new ItemStack(Items.gold_ingot), 'I', new ItemStack(Items.iron_ingot)); // Zinchorium Gem Sword GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumSword), " Z ", " Z ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Gem Pickaxe GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumPickaxe), "ZZZ", " S ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Gem Axe GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumAxe), "ZZ ", "ZS ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Gem Shovel GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumShovel), " Z ", " S ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Gem Hoe GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumHoe), "ZZ ", " S ", " S ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot), 'S', new ItemStack(Items.stick)); // Zinchorium Helmet GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumHelmet), "ZZZ", "Z Z", " ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Zinchorium Chestplate GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumChestplate), "Z Z", "ZZZ", "ZZZ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Zinchoruim Leggings GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumLeggings), "ZZZ", "Z Z", "Z Z", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Zinchorium Boots GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumBoots), "Z Z", "Z Z", " ", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); GameRegistry.addShapedRecipe(new ItemStack(EFItems.zinchoriumBoots), " ", "Z Z", "Z Z", 'Z', new ItemStack(EFItems.zinchoriumAlloyIngot)); // Zinchorium Block -> Zinchorium Alloy Ingot GameRegistry.addShapelessRecipe(new ItemStack(EFItems.zinchoriumAlloyIngot, 9), new ItemStack(EFBlocks.blockZinchorium)); // Mirror GameRegistry.addShapedRecipe(new ItemStack(EFItems.mirror, 3), "GGG", "III", " ", 'G', new ItemStack(Blocks.glass), 'I', new ItemStack(Items.iron_ingot)); // Basic Capacitor GameRegistry.addShapedRecipe(new ItemStack(EFItems.basicCapacitor), " R", " G ", "R ", 'R', new ItemStack(Items.redstone), 'G', Items.gold_nugget); // Enhanced Capacitor GameRegistry.addShapedRecipe(new ItemStack(EFItems.enhancedCapacitor), " B", " R ", "B ", 'B', EFItems.basicCapacitor, 'R', Items.redstone); // Energetic Capacitor GameRegistry.addShapedRecipe(new ItemStack(EFItems.energeticCapacitor), " E", " Z ", "E ", 'E', EFItems.enhancedCapacitor, 'Z', EFItems.zinchoriumAlloyIngot); // Hyper Energetic Capacitor GameRegistry.addShapedRecipe(new ItemStack(EFItems.hyperEnergeticCapacitor), " GE", "GZG", "EG ", 'G', Items.gold_nugget, 'E', EFItems.energeticCapacitor, 'Z', EFItems.zinchoriumAlloyIngot); // Zinchorium Dust GameRegistry.addShapelessRecipe(new ItemStack(EFItems.dustZinchorium), EFItems.dustIron, EFItems.dustPeridot); } private static void registerFurnaceRecipes() { // Copper ore --> copper ingot GameRegistry.addSmelting(EFBlocks.oreCopper, new ItemStack(EFItems.ingotCopper, 1), 0.3f); // Zinchorium ore --> Zinchorium Alloy Ingot GameRegistry.addSmelting(EFBlocks.oreZinchorium, new ItemStack(EFItems.zinchoriumAlloyIngot), 0.5f); // Zinchorium dust --> Zinchorium Alloy Ingot GameRegistry.addSmelting(EFItems.dustZinchorium, new ItemStack(EFItems.zinchoriumAlloyIngot), 0.4f); // Peridot dust --> Peridot Gem GameRegistry.addSmelting(EFItems.dustPeridot, new ItemStack(EFItems.gemPeridot), 0.1f); } public static void registerOreDictThings() { // Blocks OreDictionary.registerOre("oreCopper", EFBlocks.oreCopper); OreDictionary.registerOre("orePeridot", EFBlocks.orePeridot); // Items OreDictionary.registerOre("ingotCopper", EFItems.ingotCopper); OreDictionary.registerOre("gemPeridot", EFItems.gemPeridot); } }
package org.basex.build.xml; import java.lang.reflect.Method; import org.xml.sax.EntityResolver; import org.xml.sax.XMLReader; public final class CatalogResolverWrapper { /** Package declaration for either internal or external CatalogManager. */ private static final String CMP = cminitpackage(); /** Package declaration for either internal or external CatalogResolver. */ private static final String CRP = crinitpackage(); /** Resolver if availiable. */ private static final Object CM = init(); /** private Constructor, no instantiation. */ private CatalogResolverWrapper() {} /** * Searches for presence of the xml resolver packages. * com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver * org.apache.xml.resolver.tools.CatalogResolver * @return found package or default (internal) package on unsupported * platforms. */ private static String crinitpackage() { try { Class.forName("org.apache.xml.resolver.tools.CatalogResolver"); return "org.apache.xml.resolver.tools.CatalogResolver"; } catch(Exception e) { try { Class.forName("com.sun.org.apache.xml.internal." + "resolver.tools.CatalogResolver"); return "com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver"; } catch(Exception e2) { } } return "com.sun.org.apache.xml.internal.resolver.tools.CatalogResolver"; } /** * Searches for presence of the xml resolver packages. * org.apache.xml.resolver.tools.CatalogManager * com.sun.org.apache.xml.internal.resolver.CatalogManager * @return found package or default (internal) package on unsupported * platforms. */ private static String cminitpackage() { // TODO Auto-generated method stub // "com.sun.org.apache.xml.internal.resolver.CatalogManager"; try { Class.forName("org.apache.xml.resolver.CatalogManager"); return "org.apache.xml.resolver.CatalogManager"; } catch(Exception e) { try { Class.forName("com.sun.org.apache.xml.internal." + "resolver.CatalogManager"); return "com.sun.org.apache.xml.internal.resolver.CatalogManager"; } catch(Exception e2) { } } return "com.sun.org.apache.xml.internal.resolver.CatalogManager"; } /** * Initializes the CatalogManager. * @return CatalogManager instance iff found. */ private static Object init() { Object cmm = null; try { cmm = Class.forName(CMP).newInstance(); } catch(Exception e) { } return cmm; } /** * Returns a CatalogResolver instance or null if it could not be found. * @return CatalogResolver if availiable */ public static Object getInstance() { return CM; } /** * Decorates the XMLReader with the catalog resolver if it has been found on * the classpath. Does nothing otherwise. * @param r XMLReader * @param cat path. */ public static void set(final XMLReader r, final String cat) { if(null == CM) return; try { Class<?> clazz = Class.forName(CMP); Method m = clazz.getMethod("setCatalogFiles", String.class); m.invoke(CM, cat); m = clazz.getMethod("setIgnoreMissingProperties", boolean.class); m.invoke(CM, true); m = clazz.getMethod("setPreferPublic", boolean.class); m.invoke(CM, true); m = clazz.getMethod("setUseStaticCatalog", boolean.class); m.invoke(CM, false); m = clazz.getMethod("setVerbosity", int.class); m.invoke(CM, 0); r.setEntityResolver((EntityResolver) Class.forName(CRP).getConstructor( new Class[] { Class.forName(CMP)}).newInstance(CM)); } catch(Exception e) { } } }
package org.cyclops.cyclopscore.helper; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.world.IBlockAccess; import org.cyclops.cyclopscore.datastructure.DimPos; /** * Contains helper methods for various tile entity specific things. * @author rubensworks */ public final class TileHelpers { /** * Safely cast a tile entity. * @param dimPos The dimensional position of the block providing the tile entity. * @param targetClazz The class to cast to. * @param <T> The type of tile to cast at. * @return The tile entity or null. */ public static <T> T getSafeTile(DimPos dimPos, Class<T> targetClazz) { return getSafeTile(dimPos.getWorld(), dimPos.getBlockPos(), targetClazz); } /** * Safely cast a tile entity. * @param world The world. * @param pos The position of the block providing the tile entity. * @param targetClazz The class to cast to. * @param <T> The type of tile to cast at. * @return The tile entity or null. */ public static <T> T getSafeTile(IBlockAccess world, BlockPos pos, Class<T> targetClazz) { TileEntity tile = world.getTileEntity(pos); try { return targetClazz.cast(tile); } catch (ClassCastException e) { return null; } } }
// $Id: TestExternalLinkUtil.java,v 1.11 2006/06/15 22:07:49 grossb Exp $ package org.cytoscape.biopax.internal; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import org.cytoscape.io.BasicCyFileFilter; import org.cytoscape.io.DataCategory; import org.cytoscape.io.util.StreamUtil; /** * BioPax Filer class. Extends CyFileFilter for integration into the Cytoscape ImportHandler * framework. * * @author Ethan Cerami; (refactored by) Jason Montojo and Igor Rodchenkov */ public class BioPaxFilter extends BasicCyFileFilter { private static final String BIOPAX_XML_NAMESPACE = "www.biopax.org"; private static final int DEFAULT_LINES_TO_CHECK = 20; /** * Constructor. */ public BioPaxFilter(StreamUtil streamUtil) { super( new String[] { "xml", "owl", "rdf" }, new String[] { "text/xml", "application/rdf+xml", "application/xml", "text/plain" }, "BioPAX data", DataCategory.NETWORK, streamUtil); } @Override public boolean accepts(InputStream stream, DataCategory category) { if (category != this.category) return false; // file/stream header must contain the biopax declaration try { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); int linesToCheck = DEFAULT_LINES_TO_CHECK; while (linesToCheck > 0) { String line = reader.readLine(); if (line != null && line.contains(BIOPAX_XML_NAMESPACE)) { return true; } linesToCheck } return false; } catch (IOException e) { } return false; } @Override public boolean accepts(URI uri, DataCategory category) { try { return super.accepts(uri, category) && accepts(streamUtil.getInputStream(uri.toURL()), category); } catch (IOException e) { return false; } } }
package simcity.gui; import simcity.PersonAgent; import java.awt.*; import java.util.HashMap; import simcity.DRestaurant.DCustomerRole; public class PersonGui implements Gui { private PersonAgent agent = null; public boolean waiterAtFront() { if(xPos==-20 && yPos==-20) return true; else return false; } private boolean isPresent = false; private boolean isHungry = false; SimCityGui gui; private int tableGoingTo; public static final int x_Offset = 100; private int xPos = 0, yPos = 0;//default waiter position private int xDestination = 0, yDestination = 0;//default start position // private int xFoodDestination, yFoodDestination; private boolean cookedLabelVisible=false; private boolean foodIsFollowingWaiter=false; private boolean madeToCashier=false; private boolean tryingToGetToFront=false; private boolean madeToFront=true; //private String foodReady; // static List<CookLabel> foodz = Collections.synchronizedList(new ArrayList<CookLabel>()); //private int hangout_x = 50, hangout_y=50; public static final int streetWidth = 30; public static final int sidewalkWidth = 20; public static final int housingWidth=30; public static final int housingLength=35; public static final int parkingGap = 22; public static final int yardSpace=11; HashMap<String, Point> myMap = new HashMap<String, Point>(); //int numPlating=1; enum Command {none, GoToRestaurant, GoHome, other}; Command command= Command.none; //public String[] foodReady= new String[nTABLES]; //public boolean[] labelIsShowing = new boolean[nTABLES]; private boolean labelIsShowing=false; String foodReady; // private int seatingAt; private DCustomerRole takingOrderFrom;//, orderFrom; private int seatingAt_x, seatingAt_y; private int tablegoingto_x, tablegoingto_y; //f private void setSeatingAt(int t) { seatingAt=t; } public PersonGui(PersonAgent agent, SimCityGui g) { gui=g; this.agent = agent; madeToFront=true; // for(int i=0; i<labelIsShowing.length;i++) // labelIsShowing[i]=false; //coordinates are from citypanel, find the building you want to ppl to go to and copy/paste coordinates to this map myMap.put("Restaurant 1", new Point(2*yardSpace+2*housingWidth+2*sidewalkWidth+streetWidth+30, streetWidth+sidewalkWidth)); myMap.put("Restaurant 2", new Point(2*yardSpace+2*housingWidth+2*sidewalkWidth+streetWidth+30, streetWidth+4*housingLength+ sidewalkWidth+ 5*parkingGap)); myMap.put("Restaurant 3", new Point(2*yardSpace+3*housingWidth+4*sidewalkWidth+2*streetWidth-10, streetWidth+sidewalkWidth)); myMap.put("Restaurant 4", new Point(3*yardSpace+4*housingWidth+4*sidewalkWidth+2*streetWidth+30, streetWidth+sidewalkWidth)); myMap.put("Restaurant 5", new Point(3*yardSpace+4*housingWidth+4*sidewalkWidth+2*streetWidth+30, streetWidth+4*housingLength+ sidewalkWidth+ 5*parkingGap)); myMap.put("Restaurant 6", new Point(3*yardSpace+5*housingWidth+6*sidewalkWidth+3*streetWidth-10, streetWidth+4*housingLength+ sidewalkWidth+ 5*parkingGap)); myMap.put("House 1", new Point(yardSpace+30, streetWidth+sidewalkWidth)); myMap.put("House 2", new Point(yardSpace+30, streetWidth+sidewalkWidth+2*housingLength+ 2*parkingGap)); myMap.put("House 3", new Point(yardSpace+30, streetWidth+sidewalkWidth+4*housingLength+ 5*parkingGap)); myMap.put("House 4", new Point(yardSpace+housingWidth+2*sidewalkWidth+streetWidth-10, streetWidth+housingLength+ sidewalkWidth + parkingGap)); myMap.put("House 5", new Point(yardSpace+housingWidth+2*sidewalkWidth+streetWidth-10, streetWidth+3*housingLength+ sidewalkWidth+ 3*parkingGap)); myMap.put("House 6", new Point(2*yardSpace+2*housingWidth+2*sidewalkWidth+streetWidth+30, streetWidth+2*housingLength+ sidewalkWidth+ 2*parkingGap)); myMap.put("House 7", new Point(2*yardSpace+3*housingWidth+4*sidewalkWidth+2*streetWidth-10, streetWidth+housingLength+ sidewalkWidth+ parkingGap)); myMap.put("House 8", new Point(2*yardSpace+3*housingWidth+4*sidewalkWidth+2*streetWidth-10, streetWidth+3*housingLength+ sidewalkWidth+ 3*parkingGap)); myMap.put("House 9", new Point(3*yardSpace+4*housingWidth+4*sidewalkWidth+2*streetWidth+30, streetWidth+2*housingLength+ sidewalkWidth+ 2*parkingGap)); myMap.put("House 10", new Point(3*yardSpace+5*housingWidth+6*sidewalkWidth+3*streetWidth-10, streetWidth+housingLength+ sidewalkWidth+ parkingGap)); myMap.put("House 11", new Point(3*yardSpace+5*housingWidth+6*sidewalkWidth+3*streetWidth-10, streetWidth+3*housingLength+ sidewalkWidth+ 3*parkingGap)); myMap.put("House 12", new Point(4*yardSpace+6*housingWidth+6*sidewalkWidth+3*streetWidth+30, streetWidth+housingLength+ sidewalkWidth+ parkingGap)); myMap.put("House 13", new Point(4*yardSpace+6*housingWidth+6*sidewalkWidth+3*streetWidth+30, streetWidth+3*housingLength+ sidewalkWidth+ 3*parkingGap)); myMap.put("House 14", new Point(4*yardSpace+7*housingWidth+8*sidewalkWidth+4*streetWidth-10, streetWidth+housingLength+ sidewalkWidth+ parkingGap)); myMap.put("House 15", new Point(4*yardSpace+7*housingWidth+8*sidewalkWidth+4*streetWidth-10, streetWidth+3*housingLength+ sidewalkWidth+ 3*parkingGap)); myMap.put("Apartment 1", new Point(yardSpace+30, streetWidth+sidewalkWidth+housingLength+ parkingGap)); myMap.put("Apartment 2", new Point(yardSpace+30, streetWidth+sidewalkWidth+3*housingLength+ 3*parkingGap)); myMap.put("Apartment 3", new Point(yardSpace+housingWidth+2*sidewalkWidth+streetWidth-10, streetWidth+2*housingLength+ sidewalkWidth+ 2*parkingGap)); myMap.put("Apartment 4", new Point(2*yardSpace+2*housingWidth+2*sidewalkWidth+streetWidth+30, streetWidth+housingLength + sidewalkWidth+ parkingGap)); myMap.put("Apartment 5", new Point(2*yardSpace+2*housingWidth+2*sidewalkWidth+streetWidth+30, streetWidth+3*housingLength+ sidewalkWidth+ 3*parkingGap)); myMap.put("Apartment 6", new Point(2*yardSpace+3*housingWidth+4*sidewalkWidth+2*streetWidth-10, streetWidth+2*housingLength+ sidewalkWidth+ 2*parkingGap)); myMap.put("Apartment 7", new Point(3*yardSpace+4*housingWidth+4*sidewalkWidth+2*streetWidth+30, streetWidth+housingLength+ sidewalkWidth+ parkingGap)); myMap.put("Apartment 8", new Point(3*yardSpace+4*housingWidth+4*sidewalkWidth+2*streetWidth+30, streetWidth+3*housingLength+ sidewalkWidth+ 3*parkingGap)); myMap.put("Apartment 9", new Point(3*yardSpace+5*housingWidth+6*sidewalkWidth+3*streetWidth-10, streetWidth+2*housingLength+ sidewalkWidth+ 2*parkingGap)); myMap.put("Apartment 10", new Point(4*yardSpace+6*housingWidth+6*sidewalkWidth+3*streetWidth+30, streetWidth+2*housingLength+ sidewalkWidth+ 2*parkingGap)); myMap.put("Apartment 11", new Point(4*yardSpace+7*housingWidth+8*sidewalkWidth+4*streetWidth-10, streetWidth+sidewalkWidth)); myMap.put("Apartment 12", new Point(4*yardSpace+7*housingWidth+8*sidewalkWidth+4*streetWidth-10, streetWidth+2*housingLength+ sidewalkWidth+ 2*parkingGap)); myMap.put("Homeless Shelter", new Point(4*yardSpace+7*housingWidth+8*sidewalkWidth+4*streetWidth-10, streetWidth+4*housingLength+ sidewalkWidth+ 5*parkingGap)); myMap.put("Bank 1", new Point(yardSpace+housingWidth+2*sidewalkWidth+streetWidth-10, streetWidth+sidewalkWidth+4*housingLength+ 5*parkingGap)); myMap.put("Bank 2", new Point(4*yardSpace+6*housingWidth+6*sidewalkWidth+3*streetWidth+30, streetWidth+sidewalkWidth)); myMap.put("Market 1", new Point(yardSpace+housingWidth+2*sidewalkWidth+streetWidth-10, streetWidth+sidewalkWidth)); myMap.put("Market 2", new Point(2*yardSpace+3*housingWidth+4*sidewalkWidth+2*streetWidth-10, streetWidth+4*housingLength+ sidewalkWidth+ 5*parkingGap)); myMap.put("Market 3", new Point(3*yardSpace+5*housingWidth+6*sidewalkWidth+3*streetWidth-10, streetWidth+sidewalkWidth)); myMap.put("Market 4", new Point(4*yardSpace+6*housingWidth+6*sidewalkWidth+3*streetWidth+30, streetWidth+4*housingLength+ sidewalkWidth+ 5*parkingGap)); //Figuring out where the person starts off when created String personAddress=agent.homeAddress; if(personAddress.contains("Apartment")) { // System.err.println("need to truncate"); personAddress=personAddress.substring(0, personAddress.length()-1); //System.err.println(personAddress); } if (personAddress.equals("House 1") || personAddress.equals("House 2") || personAddress.equals("Apartment 1") || personAddress.equals("House 3") || personAddress.equals("Apartment 2") ) { xPos = myMap.get(personAddress).x; yPos = myMap.get(personAddress).y; } else if (personAddress.equals("Market 1") || personAddress.equals("House 4") || personAddress.equals("Apartment 3") || personAddress.equals("House 5") || personAddress.equals("Bank 1") ) { xPos = myMap.get(personAddress).x; yPos = myMap.get(personAddress).y; } else if (personAddress.equals("Restaurant 1") || personAddress.equals("Aparment 4") || personAddress.equals("Apartment 5") || personAddress.equals("House 6") || personAddress.equals("Restaurant 2") ) { xPos = myMap.get(personAddress).x; yPos = myMap.get(personAddress).y; } else if (personAddress.equals("Restaurant 3") || personAddress.equals("House 7") || personAddress.equals("Apartment 6") || personAddress.equals("House 8") || personAddress.equals("Market 2") ) { xPos = myMap.get(personAddress).x; yPos = myMap.get(personAddress).y; } else if (personAddress.equals("Restaurant 4") || personAddress.equals("Apartment 7") || personAddress.equals("House 9") || personAddress.equals("Apartment 8") || personAddress.equals("Restaurant 5") ) { xPos = myMap.get(personAddress).x; yPos = myMap.get(personAddress).y; } else if (personAddress.equals("Market 3") || personAddress.equals("House 10") || personAddress.equals("Apartment 9") || personAddress.equals("House 11") || personAddress.equals("Restaurant 6") ) { xPos = myMap.get(personAddress).x; yPos = myMap.get(personAddress).y; } else if (personAddress.equals("Bank 2") || personAddress.equals("House 12") || personAddress.equals("Apartment 10") || personAddress.equals("House 13") || personAddress.equals("Market 4") ) { xPos = myMap.get(personAddress).x; yPos = myMap.get(personAddress).y; } else if (personAddress.equals("Apartment 11") || personAddress.equals("House 14") || personAddress.equals("Apartment 12") || personAddress.equals("House 15") || personAddress.equals("Homeless Shelter") ) { xPos = myMap.get(personAddress).x; yPos = myMap.get(personAddress).y; } xDestination=xPos; yDestination=yPos; } @Override public void updatePosition() { //System.out.println("x pos: "+ xPos + " // y pos: "+ yPos+" // xDestination: " + xDestination + " // yDestination: " + yDestination); /** if (xPos < xDestination) xPos++; else if (xPos > xDestination) xPos--; */ if (xPos != xDestination && yPos != yDestination) { if (yPos == 30 || yPos == 335) { if (xPos < xDestination) xPos++; else if (xPos > xDestination) xPos } else if (335 - yPos < 0 ) yPos++; else yPos } if (xPos == xDestination && yPos != yDestination) { if (yPos < yDestination) yPos++; else if (yPos > yDestination) yPos } if (xPos == xDestination && yPos == yDestination) { if(command==Command.GoToRestaurant ||command==Command.GoHome||command==Command.other) { agent.msgAnimationArivedAtRestaurant(); System.out.println("msgArrivedat"); } command=Command.none; } } @Override public void draw(Graphics2D g) { g.setColor(Color.magenta); g.fillRect(xPos, yPos, 10, 10); // if(labelIsShowing) { // g.setColor(Color.BLACK); // g.drawString(foodReady.substring(0,2),xFood, yFood); } @Override public boolean isPresent() { return true; } public void setHungry() { isHungry = true; // agent.gotHungry(); setPresent(true); } public void setPresent(boolean p) { isPresent = p; } public int getXPos() { return xPos; } public int getYPos() { return yPos; } public void DoGoTo(String destination) { if(destination.contains("Restaurant")) { Point myDest = myMap.get(destination); xDestination = myDest.x; yDestination = myDest.y; command=Command.GoToRestaurant; } if(destination.contains("Bank")) { Point myDest = myMap.get(destination); xDestination = myDest.x; yDestination = myDest.y; command=Command.GoToRestaurant; } if(destination.contains("House") || destination.contains("Apartment")) { if(destination.contains("Apartment")) { destination=destination.substring(0, destination.length()-1); //System.err.println(destination); } Point myDest = myMap.get(destination); xDestination = myDest.x; yDestination = myDest.y; command=Command.GoHome; } else { Point myDest = myMap.get(destination); xDestination = myDest.x; yDestination = myDest.y; command=Command.other; } } // static class CookLabel { // String food; // int xPos, yPos; // boolean isFollowing; // enum LabelState {ingredient, cooking, cooked, plating, plated}; // LabelState state; // CookLabel(String f, int x, int y) { //// System.err.println(f); // food=f; // xPos=x; // yPos=y; // isFollowing=true; // state=LabelState.ingredient; //// System.err.println("added"); }
package org.dita.dost.module; import org.apache.commons.io.FileUtils; import org.dita.dost.exception.DITAOTException; import org.dita.dost.pipeline.AbstractPipelineInput; import org.dita.dost.pipeline.AbstractPipelineOutput; import org.dita.dost.util.Job; import org.dita.dost.util.Job.FileInfo; import org.dita.dost.util.URLUtils; import org.dita.dost.writer.AbstractXMLFilter; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; import org.xml.sax.helpers.AttributesImpl; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.*; import java.util.stream.Collectors; import static org.dita.dost.util.Constants.*; import static org.dita.dost.util.URLUtils.*; import static org.dita.dost.util.XMLUtils.addOrSetAttribute; import static org.dita.dost.util.XMLUtils.transform; /** * Move temporary files not based on output URI to match output URI structure. * * @since 2.4 */ public class CleanPreprocessModule extends AbstractPipelineModuleImpl { private final LinkFilter filter = new LinkFilter(); private final MapCleanFilter mapFilter = new MapCleanFilter(); @Override public AbstractPipelineOutput execute(final AbstractPipelineInput input) throws DITAOTException { init(); final URI base = getBaseDir(); final Collection<FileInfo> fis = job.getFileInfo().stream() .collect(Collectors.toList()); final Collection<FileInfo> res = new ArrayList<>(fis.size()); for (final FileInfo fi : fis) { try { final FileInfo.Builder builder = new FileInfo.Builder(fi); final File srcFile = new File(job.tempDirURI.resolve(fi.uri)); if (srcFile.exists()) { final URI rel = base.relativize(fi.result); final File destFile = new File(job.tempDirURI.resolve(rel)); final List<XMLFilter> processingPipe = getProcessingPipe(fi, srcFile, destFile); if (fi.format != null && fi.format.equals("coderef")) { logger.debug("Skip coderef"); } else if (!processingPipe.isEmpty()) { logger.info("Processing " + srcFile.toURI() + " to " + destFile.toURI()); transform(srcFile.toURI(), destFile.toURI(), processingPipe); if (!srcFile.equals(destFile)) { logger.debug("Deleting " + srcFile.toURI()); FileUtils.deleteQuietly(srcFile); } } else if (!srcFile.equals(destFile)) { logger.info("Moving " + srcFile.toURI() + " to " + destFile.toURI()); FileUtils.moveFile(srcFile, destFile); } builder.uri(rel); // start map if (fi.src.equals(job.getInputFile())) { job.setProperty(INPUT_DITAMAP_URI, rel.toString()); job.setProperty(INPUT_DITAMAP, toFile(rel).getPath()); } } res.add(builder.build()); } catch (final IOException e) { logger.error("Failed to clean " + job.tempDirURI.resolve(fi.uri) + ": " + e.getMessage(), e); } } fis.stream().forEach(fi -> job.remove(fi)); res.stream().forEach(fi -> job.add(fi)); try { job.write(); } catch (IOException e) { throw new DITAOTException(); } return null; } private URI getBaseDir() { String baseDir = job.getInputDir().toString(); final Collection<FileInfo> fis = job.getFileInfo(); for (final FileInfo fi : fis) { final String res = fi.result.resolve(".").toString(); if (!res.equals(baseDir) && baseDir.startsWith(res)) { baseDir = res; } } return URI.create(baseDir); } private void init() { filter.setJob(job); filter.setLogger(logger); mapFilter.setJob(job); mapFilter.setLogger(logger); } private List<XMLFilter> getProcessingPipe(final FileInfo fi, final File srcFile, final File destFile) { final List<XMLFilter> res = new ArrayList<>(); if (fi.format == null || fi.format.equals(ATTR_FORMAT_VALUE_DITA) || fi.format.equals(ATTR_FORMAT_VALUE_DITAMAP)) { filter.setCurrentFile(srcFile.toURI()); filter.setDestFile(destFile.toURI()); res.add(filter); } if (fi.format != null && fi.format.equals(ATTR_FORMAT_VALUE_DITAMAP)) { res.add(mapFilter); } return res; } private class LinkFilter extends AbstractXMLFilter { private URI destFile; private URI base; @Override public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { Attributes res = atts; if (hasLocalDitaLink(atts)) { final AttributesImpl resAtts = new AttributesImpl(atts); final URI href = toURI(atts.getValue(ATTRIBUTE_NAME_HREF)); final URI resHref = getHref(href); addOrSetAttribute(resAtts, ATTRIBUTE_NAME_HREF, resHref.toString()); res = resAtts; } getContentHandler().startElement(uri, localName, qName, res); } private boolean hasLocalDitaLink(final Attributes atts) { final boolean hasHref = atts.getIndex(ATTRIBUTE_NAME_HREF) != -1; final boolean notExternal = !ATTR_SCOPE_VALUE_EXTERNAL.equals(atts.getValue(ATTRIBUTE_NAME_SCOPE)); if (hasHref && notExternal) { return true; } final URI data = toURI(atts.getValue(ATTRIBUTE_NAME_DATA)); if (data != null && !data.isAbsolute()) { return true; } return false; } private URI getHref(final URI href) { if (href.getFragment() != null && (href.getPath() == null || href.getPath().equals(""))) { return href; } final URI targetAbs = stripFragment(currentFile.resolve(href)); final FileInfo targetFileInfo = job.getFileInfo(targetAbs); if (targetFileInfo != null) { final URI rel = base.relativize(targetFileInfo.result); final URI targetDestFile = job.tempDirURI.resolve(rel); final URI relTarget = URLUtils.getRelativePath(destFile, targetDestFile); return setFragment(relTarget, href.getFragment()); } else { return href; } } public void setDestFile(final URI destFile) { this.destFile = destFile; } @Override public void setJob(final Job job) { super.setJob(job); base = job.getInputDir(); } } private enum Keep { RETAIN, DISCARD, DISCARD_BRANCH } private class MapCleanFilter extends AbstractXMLFilter { private final Deque<Keep> stack = new ArrayDeque<>(); @Override public void startDocument() throws SAXException { stack.clear(); getContentHandler().startDocument(); } @Override public void endDocument() throws SAXException { assert stack.isEmpty(); getContentHandler().endDocument(); } @Override public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException { final String cls = atts.getValue(ATTRIBUTE_NAME_CLASS); if (!stack.isEmpty() && stack.element() == Keep.DISCARD_BRANCH) { stack.addFirst(Keep.DISCARD_BRANCH); } else if (SUBMAP.matches(cls)) { stack.addFirst(Keep.DISCARD); } else if (MAPGROUP_D_KEYDEF.matches(cls)) { stack.addFirst(Keep.DISCARD_BRANCH); } else { stack.addFirst(Keep.RETAIN); } if (stack.isEmpty() || stack.peekFirst() == Keep.RETAIN) { getContentHandler().startElement(uri, localName, qName, atts); } } @Override public void endElement(final String uri, final String localName, final String qName) throws SAXException { if (stack.removeFirst() == Keep.RETAIN) { getContentHandler().endElement(uri, localName, qName); } } @Override public void characters(char ch[], int start, int length) throws SAXException { if (stack.peekFirst() != Keep.DISCARD_BRANCH) { getContentHandler().characters(ch, start, length); } } @Override public void ignorableWhitespace(char ch[], int start, int length) throws SAXException { if (stack.peekFirst() != Keep.DISCARD_BRANCH) { getContentHandler().ignorableWhitespace(ch, start, length); } } @Override public void processingInstruction(String target, String data) throws SAXException { if (stack.isEmpty() || stack.peekFirst() != Keep.DISCARD_BRANCH) { getContentHandler().processingInstruction(target, data); } } @Override public void skippedEntity(String name) throws SAXException { if (stack.peekFirst() != Keep.DISCARD_BRANCH) { getContentHandler().skippedEntity(name); } } // <xsl:template match="*[contains(@class, ' mapgroup-d/topicgroup ')]/*/*[contains(@class, ' topic/navtitle ')]"> // <xsl:call-template name="output-message"> // <xsl:with-param name="id" select="'DOTX072I'"/> // </xsl:call-template> // </xsl:template> } }
package org.g_node.converter; import com.hp.hpl.jena.rdf.model.Model; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.jena.riot.RiotException; import org.apache.log4j.Logger; import org.g_node.micro.commons.CliToolController; import org.g_node.micro.rdf.RdfFileServiceJena; import org.g_node.srv.CliOptionService; import org.g_node.srv.CtrlCheckService; /** * Controller class for the RDF to RDF converter. * * @author Michael Sonntag (sonntag@bio.lmu.de) */ public class ConvCliToolController implements CliToolController { /** * Access to the main LOGGER. */ private static final Logger LOGGER = Logger.getLogger(ConvCliToolController.class.getName()); /** * Method returning the commandline options of the RDF to RDF converter. * @return Available commandline options. */ public final Options options() { final Options options = new Options(); final Option opHelp = CliOptionService.getHelpOpt(""); final Option opIn = CliOptionService.getInFileOpt( "Input RDF file that's supposed to be converted into a different RDF format."); final Option opOut = CliOptionService.getOutFileOpt(""); final Option opFormat = CliOptionService.getOutFormatOpt("", RdfFileServiceJena.RDF_FORMAT_MAP.keySet()); options.addOption(opHelp); options.addOption(opIn); options.addOption(opOut); options.addOption(opFormat); return options; } /** * Method converting data from an input RDF file to an RDF file of a different supported RDF format. * @param cmd User provided {@link CommandLine} input. */ public final void run(final CommandLine cmd) { final Map<String, String> rdfFormatExtensions = RdfFileServiceJena.RDF_FORMAT_EXTENSION; final Set<String> rdfFormatKeys = RdfFileServiceJena.RDF_FORMAT_MAP.keySet(); final String inputFile = cmd.getOptionValue("i"); if (!CtrlCheckService.isExistingFile(inputFile)) { return; } final Set<String> checkExtension = rdfFormatExtensions.values() .stream() .map(c->c.toUpperCase(Locale.ENGLISH)) .collect(Collectors.toSet()); if (!CtrlCheckService.isSupportedInFileType(inputFile, checkExtension)) { return; } if (!RdfFileServiceJena.isValidRdfFile(inputFile)) { return; } final String outputFormat = cmd.getOptionValue("f", "TTL").toUpperCase(Locale.ENGLISH); if (!CtrlCheckService.isSupportedOutputFormat(outputFormat, rdfFormatKeys)) { return; } final int i = inputFile.lastIndexOf('.'); final String defaultOutputFile = String.join("", inputFile.substring(0, i), "_out"); String outputFile = cmd.getOptionValue("o", defaultOutputFile); if (!outputFile.toLowerCase().endsWith(rdfFormatExtensions.get(outputFormat))) { outputFile = String.join("", outputFile, ".", rdfFormatExtensions.get(outputFormat)); } Model convData; try { ConvCliToolController.LOGGER.info("Reading input file..."); convData = RdfFileServiceJena.openModelFromFile(inputFile); } catch (RiotException e) { ConvCliToolController.LOGGER.error(e.getMessage()); // TODO find out how to print stacktrace to log4j logfile e.printStackTrace(); return; } RdfFileServiceJena.saveModelToFile(outputFile, convData, outputFormat); } }
package org.geoscript.js.feature; import java.util.NoSuchElementException; import java.util.logging.Level; import java.util.logging.Logger; import org.geoscript.js.GeoObject; import org.geoscript.js.geom.Bounds; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.process.feature.gs.SimpleProcessingCollection; import org.geotools.util.logging.Logging; import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.NativeArray; import org.mozilla.javascript.NativeGenerator; import org.mozilla.javascript.NativeIterator; import org.mozilla.javascript.NativeObject; import org.mozilla.javascript.ScriptRuntime; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.Wrapper; import org.mozilla.javascript.annotations.JSConstructor; import org.mozilla.javascript.annotations.JSFunction; import org.mozilla.javascript.annotations.JSGetter; import org.mozilla.javascript.annotations.JSSetter; import org.mozilla.javascript.annotations.JSStaticFunction; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; public class FeatureCollection extends GeoObject implements Wrapper { /** serialVersionUID */ private static final long serialVersionUID = 7771735276222136537L; static Logger LOGGER = Logging.getLogger("org.geoserver.script.js"); private SimpleFeatureCollection collection; /** * JavaScript layer associated with this collection (if any). */ private Scriptable layer; /** * Prototype constructor. */ public FeatureCollection() { } /** * Constructor from config object. * @param config */ private FeatureCollection(NativeObject config) { Object obj = config.get("features", config); if (obj instanceof Function) { collection = new JSFeatureCollection(this, config); } else if (obj instanceof NativeArray) { collection = new JSFeatureArray((NativeArray) obj); } } /** * Constructor from array. * @param array */ private FeatureCollection(NativeArray array) { collection = new JSFeatureArray(array); } /** * Constructor from config object (without new keyword). * @param scope * @param config */ public FeatureCollection(Scriptable scope, NativeObject config) { this(config); setParentScope(scope); this.setPrototype(Module.getClassPrototype(FeatureCollection.class)); } /** * Constructor from feature array (without new keyword). * @param scope * @param array */ public FeatureCollection(Scriptable scope, NativeArray array) { this(array); setParentScope(scope); this.setPrototype(Module.getClassPrototype(FeatureCollection.class)); } /** * Constructor with SimpleFeatureCollection (from Java). * @param scope * @param collection */ public FeatureCollection(Scriptable scope, SimpleFeatureCollection collection) { this.collection = collection; setParentScope(scope); this.setPrototype(Module.getClassPrototype(FeatureCollection.class)); } /** * JavaScript constructor. * @param cx * @param args * @param ctorObj * @param inNewExpr * @return */ @JSConstructor public static Object constructor(Context cx, Object[] args, Function ctorObj, boolean inNewExpr) { if (args.length != 1) { throw ScriptRuntime.constructError("Error", "Constructor takes a single argument"); } FeatureCollection collection = null; Object arg = args[0]; if (arg instanceof NativeObject) { NativeObject config = (NativeObject) arg; if (inNewExpr) { collection = new FeatureCollection(config); } else { collection = new FeatureCollection(config.getParentScope(), config); } } else if (arg instanceof NativeArray) { NativeArray array = (NativeArray) arg; if (inNewExpr) { collection = new FeatureCollection(array); } else { collection = new FeatureCollection(array.getParentScope(), array); } } else { throw ScriptRuntime.constructError("Error", "Could not create collection from argument: " + Context.toString(arg)); } return collection; } /** * Set the JavaScript layer associated with this collection. * @param layer */ @JSSetter public void setLayer(Scriptable layer) { this.layer = layer; } @JSGetter public Scriptable getLayer() { return layer; } @JSGetter public int getSize() { return collection.size(); } @JSGetter public Bounds getBounds() { return new Bounds(getParentScope(), collection.getBounds()); } @JSGetter public Schema getSchema() { return new Schema(getParentScope(), collection.getSchema()); } @JSFunction public void forEach(Function function, Scriptable thisArg) { Scriptable scope = getParentScope(); if (thisArg == Context.getUndefinedValue()) { thisArg = scope; } Iterator iterator = (Iterator) __iterator__(true); Context context = Context.enter(); int i = 0; try { while (iterator.hasNext()) { Object[] args = { iterator.next() , i }; Object ret = function.call(context, scope, thisArg, args); if (ret.equals(false)) { break; } ++i; } } finally { iterator.close(); Context.exit(); } } @JSFunction public FeatureCollection map(final Function function) { final Scriptable scope = getParentScope(); final Context context = getCurrentContext(); final SimpleFeatureIterator mappedIterator = new SimpleFeatureIterator() { SimpleFeatureIterator iterator = collection.features(); public SimpleFeature next() throws NoSuchElementException { Object[] args = {iterator.next()}; Object newFeature = function.call(context, scope, scope, args); if (!(newFeature instanceof Feature)) { throw ScriptRuntime.constructError("Error", "Map function must return a feature"); } return (SimpleFeature) ((Feature) newFeature).unwrap(); } public boolean hasNext() { return iterator.hasNext(); } public void close() { iterator.close(); } }; SimpleProcessingCollection mappedCollection = new SimpleProcessingCollection() { @Override public int size() { return collection.size(); } @Override public ReferencedEnvelope getBounds() { return collection.getBounds(); } @Override public SimpleFeatureIterator features() { return mappedIterator; } @Override protected SimpleFeatureType buildTargetFeatureType() { SimpleFeatureIterator iterator = collection.features(); SimpleFeatureType featureType = null; if (iterator.hasNext()) { SimpleFeature feature = iterator.next(); Object[] args = new Object[] {feature}; try { Object newFeature = function.call(context, scope, scope, args); if (!(newFeature instanceof Feature)) { throw ScriptRuntime.constructError("Error", "Map function must return a feature"); } featureType = (SimpleFeatureType) ((Feature) newFeature) .getSchema().unwrap(); } finally { iterator.close(); } } return featureType; } }; return new FeatureCollection(scope, mappedCollection); } @JSFunction public NativeArray get(Scriptable lengthObj) { int length = 1; if (lengthObj != Context.getUndefinedValue()) { length = (int) Context.toNumber(lengthObj); } Context cx = getCurrentContext(); Scriptable scope = getParentScope(); NativeArray features = (NativeArray) cx.newArray(scope, length); Iterator iterator = (Iterator) __iterator__(true); int i=0; while (i<length && iterator.hasNext()) { features.put(i, features, iterator.next()); ++i; } features.put("length", features, i); return features; } @JSFunction public Object __iterator__(boolean b) { Iterator iterator = new Iterator(getParentScope(), collection.features()); if (layer != null) { iterator.setLayer(layer); } return iterator; } @JSStaticFunction public static FeatureCollection from_(Scriptable collectionObj) { SimpleFeatureCollection collection = null; if (collectionObj instanceof Wrapper) { Object obj = ((Wrapper) collectionObj).unwrap(); if (obj instanceof SimpleFeatureCollection) { collection = (SimpleFeatureCollection) obj; } } if (collection == null) { throw ScriptRuntime.constructError("Error", "Cannot create collection from " + Context.toString(collectionObj)); } return new FeatureCollection(getTopLevelScope(collectionObj), collection); } /** * Provides a config object with GeoJSON structure. Note that this will * iterate through and serialize all features. */ @JSGetter public Scriptable getConfig() { Scriptable config = super.getConfig(); // add features Context cx = getCurrentContext(); Scriptable scope = getParentScope(); Scriptable features = cx.newArray(scope, 0); SimpleFeatureIterator iterator = collection.features(); int i = -1; while (iterator.hasNext()) { ++i; Feature feature = new Feature(scope, iterator.next()); Scriptable featureConfig = feature.getConfig(); featureConfig.delete("schema"); // to be added at top level features.put(i, features, featureConfig); } config.put("features", config, features); // add schema Schema schema = new Schema(scope, collection.getSchema()); config.put("schema", config, schema.getConfig()); return config; } public Object unwrap() { return collection; } static class JSFeatureArray extends SimpleProcessingCollection { NativeArray array; public JSFeatureArray(NativeArray array) { this.array = array; } @Override public SimpleFeatureIterator features() { return new JSFeatureArrayIterator(array); } @Override public ReferencedEnvelope getBounds() { return getFeatureBounds(); } @Override protected SimpleFeatureType buildTargetFeatureType() { SimpleFeatureType featureType = null; SimpleFeatureIterator iterator = features(); if (iterator.hasNext()) { SimpleFeature feature = iterator.next(); featureType = feature.getFeatureType(); } return featureType; } @Override public int size() { return array.size(); } } static class JSFeatureArrayIterator implements SimpleFeatureIterator { int current = -1; NativeArray array; public JSFeatureArrayIterator(NativeArray array) { this.array = array; } public boolean hasNext() { return array.size() > current + 1; } public SimpleFeature next() throws NoSuchElementException { SimpleFeature feature = null; if (hasNext()) { ++current; Object obj = array.get(current, array); if (obj instanceof Feature) { feature = (SimpleFeature) ((Feature) obj).unwrap(); } else if (obj instanceof NativeObject) { NativeObject config = (NativeObject) obj; feature = (SimpleFeature) new Feature(config.getParentScope(), config).unwrap(); } else { throw new NoSuchElementException("Expected a feature instance at index " + current); } } else { throw new NoSuchElementException("hasNext() returned false!"); } return feature; } public void close() { current = -1; } } static class JSFeatureCollection extends SimpleProcessingCollection { FeatureCollection collection; Scriptable scope; SimpleFeatureType featureType; Function featuresFunc; Function closeFunc; Function sizeFunc; Function boundsFunc; public JSFeatureCollection(FeatureCollection collection, Scriptable config) { super(); this.collection = collection; scope = config.getParentScope(); // required next function featuresFunc = (Function) getRequiredMember(config, "features", Function.class); // optional close function closeFunc = (Function) getOptionalMember(config, "close", Function.class); // optional size function sizeFunc = (Function) getOptionalMember(config, "size", Function.class); // optional bounds function boundsFunc = (Function) getOptionalMember(config, "bounds", Function.class); } @Override public SimpleFeatureIterator features() { return new JSFeatureIterator(collection, featuresFunc, closeFunc); } @Override public ReferencedEnvelope getBounds() { ReferencedEnvelope refEnv; if (boundsFunc != null) { Context context = Context.enter(); Object retObj; try { retObj = boundsFunc.call(context, scope, collection, new Object[0]); } finally { Context.exit(); } if (retObj instanceof Bounds) { refEnv = (ReferencedEnvelope) ((Bounds) retObj).unwrap(); } else { throw ScriptRuntime.constructError("Error", "The bounds function must return a bounds. Got: " + Context.toString(retObj)); } } else { refEnv = getFeatureBounds(); } return refEnv; } @Override protected SimpleFeatureType buildTargetFeatureType() { if (featureType == null) { JSFeatureIterator iterator = (JSFeatureIterator) features(); try { featureType = iterator.getFeatureType(); } finally { iterator.close(); } } return featureType; } @Override public int size() { int size = 0; if (sizeFunc != null) { Context context = Context.enter(); Object retObj; try { retObj = sizeFunc.call(context, scope, collection, new Object[0]); } finally { Context.exit(); } size = (int) Context.toNumber(retObj); } else { size = getFeatureCount(); } return size; } } static class JSFeatureIterator implements SimpleFeatureIterator { Scriptable scope; FeatureCollection collection; Function featuresFunc; Function closeFunc; NativeGenerator generator; SimpleFeature next; SimpleFeatureType featureType; boolean closed = false; public JSFeatureIterator(FeatureCollection collection, Function featuresFunc, Function closeFunc) { scope = collection.getParentScope(); this.collection = collection; this.featuresFunc = featuresFunc; this.closeFunc = closeFunc; } /** * Get the feature type from the first feature created. * @return */ public SimpleFeatureType getFeatureType() { if (featureType == null) { try { createNextFeature(); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Feature creation failed", e); throw ScriptRuntime.constructError("Error", "Unable to get a feature from the collection"); } if (next != null) { featureType = next.getFeatureType(); } } return featureType; } public boolean hasNext() { createNextFeature(); return next != null; } /** * Call the provided `next` function to create the next feature. */ private void createNextFeature() { if (generator == null) { Context context = Context.enter(); try { Object retObj = featuresFunc.call(context, scope, collection, new Object[0]); if (retObj instanceof NativeGenerator) { generator = (NativeGenerator) retObj; } else { throw ScriptRuntime.constructError("Error", "Expected features method to return a Generator. Got: " + Context.toString(retObj)); } } finally { Context.exit(); } } if (next == null) { SimpleFeature feature = null; Object retObj = null; Context context = Context.enter(); try { retObj = ScriptableObject.callMethod(context, generator, "next", new Object[0]); } catch (JavaScriptException e) { // pass on StopIteration Object stopIteration = NativeIterator.getStopIterationObject(scope); if (!e.getValue().getClass().equals(stopIteration.getClass())) { throw e; } } finally { Context.exit(); } if (retObj != null) { if (retObj instanceof Feature) { feature = (SimpleFeature) ((Feature) retObj).unwrap(); } else { throw ScriptRuntime.constructError("Error", "Expected a feature from next method. Got: " + Context.toString(retObj)); } } next = feature; } } public SimpleFeature next() throws NoSuchElementException { SimpleFeature feature; if (hasNext()) { createNextFeature(); feature = next; next = null; } else { throw new NoSuchElementException("hasNext() returned false!"); } if (feature == null) { throw new NoSuchElementException("No more features to create"); } return feature; } public void close() { if (!closed) { if (closeFunc != null) { Context context = Context.enter(); try { closeFunc.call(context, scope, collection, new Object[0]); } finally { Context.exit(); } } if (generator != null) { ScriptableObject.callMethod(generator, "close", new Object[0]); } } closed = true; } } }
package org.jfrog.hudson; import hudson.Extension; import hudson.maven.MavenBuild; import hudson.maven.MavenBuildProxy; import hudson.maven.MavenBuildProxy.BuildCallable; import hudson.maven.MavenModule; import hudson.maven.MavenReporter; import hudson.maven.MavenReporterDescriptor; import hudson.maven.MojoInfo; import hudson.model.BuildListener; import org.apache.maven.artifact.Artifact; import org.apache.maven.project.MavenProject; import java.io.IOException; import java.util.HashSet; import java.util.Set; /** * Records dependencies used during the build. * * @author Yossi Shaul */ public class MavenDependenciesRecorder extends MavenReporter { /** * All dependencies this module used, including transitive ones. */ private transient Set<MavenDependency> dependencies; @Override public boolean preBuild(MavenBuildProxy build, MavenProject pom, BuildListener listener) { listener.getLogger().println("[HUDSON] Collecting dependencies info"); dependencies = new HashSet<MavenDependency>(); return true; } /** * Mojos perform different dependency resolution, so we add dependencies for each mojo. */ @Override public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener, Throwable error) { //listener.getLogger().println("[MavenDependenciesRecorder] mojo: " + mojo.getClass() + ":" + mojo.getGoal()); //listener.getLogger().println("[MavenDependenciesRecorder] dependencies: " + pom.getArtifacts()); recordMavenDependencies(pom.getArtifacts()); return true; } /** * Sends the collected dependencies over to the master and record them. */ @Override public boolean postBuild(MavenBuildProxy build, MavenProject pom, BuildListener listener) throws InterruptedException, IOException { build.executeAsync(new BuildCallable<Void, IOException>() { // record is transient, so needs to make a copy first private final Set<MavenDependency> d = dependencies; public Void call(MavenBuild build) throws IOException, InterruptedException { // add the action build.getActions().add(new MavenDependenciesRecord(build, d)); return null; } }); return true; } private void recordMavenDependencies(Set<Artifact> artifacts) { if (artifacts != null) { for (Artifact dependency : artifacts) { MavenDependency mavenDependency = new MavenDependency(); mavenDependency.id = dependency.getId(); mavenDependency.groupId = dependency.getGroupId(); mavenDependency.artifactId = dependency.getArtifactId(); mavenDependency.version = dependency.getVersion(); mavenDependency.classifier = dependency.getClassifier(); mavenDependency.scope = dependency.getScope(); mavenDependency.fileName = dependency.getFile().getName(); mavenDependency.type = dependency.getType(); dependencies.add(mavenDependency); } } } @Extension public static final class DescriptorImpl extends MavenReporterDescriptor { @Override public String getDisplayName() { return "Record Maven Dependencies"; } @Override public MavenReporter newAutoInstance(MavenModule module) { return new MavenDependenciesRecorder(); } } private static final long serialVersionUID = 1L; }
package org.komamitsu.fluency.buffer; import com.fasterxml.jackson.databind.ObjectMapper; import org.komamitsu.fluency.sender.Sender; import org.msgpack.core.MessagePack; import org.msgpack.core.MessageUnpacker; import org.msgpack.jackson.dataformat.MessagePackFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Map; import java.util.UUID; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; public class MessageBuffer extends Buffer<MessageBuffer.Config> { private static final Logger LOG = LoggerFactory.getLogger(MessageBuffer.class); private final LinkedBlockingQueue<ByteBuffer> messages = new LinkedBlockingQueue<ByteBuffer>(); private final ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory()); private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); private final Object bufferLock = new Object(); private MessageBuffer(MessageBuffer.Config bufferConfig) { super(bufferConfig); } @Override public void append(String tag, long timestamp, Map<String, Object> data) throws IOException { // TODO: Use ThreadLocal byte[] packedBytes = null; synchronized (outputStream) { outputStream.reset(); objectMapper.writeValue(outputStream, Arrays.asList(tag, timestamp, data)); outputStream.close(); packedBytes = outputStream.toByteArray(); } if (bufferConfig.isAckResponseMode()) { if (packedBytes[0] != (byte)0x93) { throw new IllegalStateException("packedBytes[0] should be 0x93, but " + packedBytes[0]); } packedBytes[0] = (byte)0x94; } // TODO: Refactoring synchronized (bufferLock) { if (allocatedSize.get() + packedBytes.length > bufferConfig.getMaxBufferSize()) { throw new BufferFullException("Buffer is full. bufferConfig=" + bufferConfig + ", allocatedSize=" + allocatedSize); } ByteBuffer byteBuffer = ByteBuffer.wrap(packedBytes); messages.add(byteBuffer); allocatedSize.getAndAdd(packedBytes.length); } } @Override public void flushInternal(Sender sender, boolean force) throws IOException { ByteBuffer message = null; while ((message = messages.poll()) != null) { try { // TODO: Refactoring synchronized (bufferLock) { allocatedSize.addAndGet(-message.capacity()); if (bufferConfig.isAckResponseMode()) { String uuid = UUID.randomUUID().toString(); sender.sendWithAck(Arrays.asList(message), uuid.getBytes(CHARSET)); } else { sender.send(message); } } } catch (Throwable e) { try { messages.put(message); allocatedSize.addAndGet(message.capacity()); } catch (InterruptedException e1) { LOG.error("Interrupted during restoring fetched message. It can be lost. message={}", message); } if (e instanceof IOException) { throw (IOException)e; } else { throw new RuntimeException("Failed to send message to fluentd", e); } } } } @Override public void closeInternal(Sender sender) throws IOException { messages.clear(); } public static class Config extends Buffer.Config<MessageBuffer, Config> { @Override public MessageBuffer createInstance() { return new MessageBuffer(this); } } }
package org.lightmare.config; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.log4j.Logger; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.collections.CollectionUtils; import org.lightmare.utils.io.IOUtils; /** * Configuration utilities in sbtract class * * @author Levan Tsinadze * @since 0.1.4 */ public abstract class AbstractConfiguration implements Cloneable { // Cache for all configuration passed from API or read from file protected final Map<Object, Object> config = new HashMap<Object, Object>(); // Error messages private static final String COULD_NOT_LOAD_CONFIG_ERROR = "Could not load configuration"; private static final String COULD_NOT_OPEN_FILE_ERROR = "Could not open config file"; private static final Logger LOG = Logger .getLogger(AbstractConfiguration.class); /** * Gets value on passed generic key K of passed {@link Map} as {@link Map} * of generic key values * * @param key * @param from * @return {@link Map}<code><K, V></code> */ private <K, V> Map<K, V> getAsMap(Object key, Map<Object, Object> from) { if (from == null) { from = config; } // Gets value associated with key as map Map<K, V> value = ObjectUtils.cast(CollectionUtils.getAsMap(key, from)); return value; } /** * Gets value on passed generic key K of cached configuration as {@link Map} * of generic key values * * @param key * @return {@link Map}<code><K, V></code> */ private <K, V> Map<K, V> getAsMap(Object key) { return getAsMap(key, null); } /** * Sets value of sub {@link Map} on passed sub key contained in cached * configuration on passed key * * @param key * @param subKey * @param value */ private <K, V> void setSubConfigValue(Object key, K subKey, V value) { Map<K, V> subConfig = getAsMap(key); if (subConfig == null) { subConfig = new HashMap<K, V>(); config.put(key, subConfig); } subConfig.put(subKey, value); } /** * Gets value of sub {@link Map} on passed sub key contained in cached * configuration on passed key * * @param key * @param subKey * @param defaultValue * @return V */ private <K, V> V getSubConfigValue(Object key, K subKey, V defaultValue) { V def; Map<K, V> subConfig = getAsMap(key); if (CollectionUtils.valid(subConfig)) { def = subConfig.get(subKey); if (def == null) { def = defaultValue; } } else { def = defaultValue; } return def; } /** * Check if sub {@link Map} contains passed sub key contained in cached * configuration on passed key * * @param key * @param subKey * @return <code>boolean</code> */ private <K> boolean containsSubConfigKey(Object key, K subKey) { boolean valid; Map<K, ?> subConfig = getAsMap(key); valid = CollectionUtils.valid(subConfig); if (valid) { valid = subConfig.containsKey(subKey); } return valid; } /** * Checks if configuration contains passed key * * @param key * @return <code>boolean</code> */ protected <K> boolean containsConfigKey(K key) { return containsSubConfigKey(ConfigKeys.DEPLOY_CONFIG.key, key); } /** * Gets value from sub configuration for passed sub key contained in * configuration for passed key * * @param key * @param subKey * @return <coder>V</code> */ private <K, V> V getSubConfigValue(Object key, K subKey) { return getSubConfigValue(key, subKey, null); } /** * Sets sub configuration configuration value for passed sub key for default * configuration key * * @param subKey * @param value */ protected <K, V> void setConfigValue(K subKey, V value) { setSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, value); } /** * Gets value from sub configuration for passed sub key contained in * configuration for default configuration key and if such not exists * returns passed default value * * @param subKey * @param defaultValue * @return <coder>V</code> */ protected <K, V> V getConfigValue(K subKey, V defaultValue) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey, defaultValue); } /** * Gets value from sub configuration for passed sub key contained in * configuration for default configuration key * * @param subKey * @param defaultValue * @return <coder>V</code> */ protected <K, V> V getConfigValue(K subKey) { return getSubConfigValue(ConfigKeys.DEPLOY_CONFIG.key, subKey); } /** * Gets {@link Map} value from configuration with passed key and if such * does not exists creates and puts new instance * * @param key * @return {@link Map}<code><K, V></code> */ private <K, V> Map<K, V> getWithInitialization(Object key) { Map<K, V> result = getConfigValue(key); if (result == null) { result = new HashMap<K, V>(); setConfigValue(key, result); } return result; } /** * Sets sub configuration configuration value for passed sub key for passed * configuration key (if sub configuration does not exists creates and puts * new instance) * * @param subKey * @param value */ protected <K, V> void setWithInitialization(Object key, K subKey, V value) { Map<K, V> result = getWithInitialization(key); result.put(subKey, value); } protected <K, V> void setIfContains(K key, V value) { boolean contains = containsConfigKey(key); if (Boolean.FALSE.equals(contains)) { setConfigValue(key, value); } } /** * Merges key and value from passed {@link java.util.Map.Entry} and passed * {@link java.util.Map}'s appropriated key and value * * @param map * @param entry */ private void deepMerge(Map<Object, Object> map, Map.Entry<Object, Object> entry) { Object key = entry.getKey(); Object value2 = entry.getValue(); Object mergedValue; if (value2 instanceof Map) { Map<Object, Object> value1 = CollectionUtils.getAsMap(key, map); Map<Object, Object> mapValue2 = ObjectUtils.cast(value2); mergedValue = deepMerge(value1, mapValue2); } else { mergedValue = value2; } // Caches merged value if (ObjectUtils.notNull(mergedValue)) { map.put(key, mergedValue); } } /** * Merges two {@link Map}s and if second {@link Map}'s value is instance of * {@link Map} merges this value with first {@link Map}'s value recursively * * @param map1 * @param map2 * @return <code>{@link Map}<Object, Object></code> */ protected Map<Object, Object> deepMerge(Map<Object, Object> map1, Map<Object, Object> map2) { if (map1 == null) { map1 = map2; } else { Set<Map.Entry<Object, Object>> entries2 = map2.entrySet(); for (Map.Entry<Object, Object> entry2 : entries2) { deepMerge(map1, entry2); } } return map1; } /** * Reads configuration from passed properties * * @param configuration */ public void configure(Map<Object, Object> configuration) { deepMerge(config, configuration); } /** * Gets value associated with particular key as {@link String} instance * * @param key * @return {@link String} */ public String getStringValue(String key) { String textValue; Object value = config.get(key); if (value == null) { textValue = null; } else { textValue = value.toString(); } return textValue; } /** * Gets value associated with particular key as <code>int</code> instance * * @param key * @return {@link String} */ public int getIntValue(String key) { String value = getStringValue(key); return Integer.parseInt(value); } /** * Gets value associated with particular key as <code>long</code> instance * * @param key * @return {@link String} */ public long getLongValue(String key) { String value = getStringValue(key); return Long.parseLong(value); } /** * Gets value associated with particular key as <code>boolean</code> * instance * * @param key * @return {@link String} */ public boolean getBooleanValue(String key) { String value = getStringValue(key); return Boolean.parseBoolean(value); } public void putValue(String key, String value) { config.put(key, value); } /** * Load {@link Configuration} in memory as {@link Map} of parameters * * @param propertiesStream * @throws IOException */ public void loadFromStream(InputStream propertiesStream) throws IOException { try { Properties props = new Properties(); props.load(propertiesStream); for (String propertyName : props.stringPropertyNames()) { config.put(propertyName, props.getProperty(propertyName)); } } catch (IOException ex) { LOG.error(COULD_NOT_LOAD_CONFIG_ERROR, ex); } finally { IOUtils.close(propertiesStream); } } /** * Loads configuration form file * * @throws IOException */ public void loadFromFile() throws IOException { String configFilePath = ConfigKeys.CONFIG_FILE.getValue(); try { File configFile = new File(configFilePath); if (configFile.exists()) { InputStream propertiesStream = new FileInputStream(configFile); loadFromStream(propertiesStream); } else { configFile.mkdirs(); } } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Loads configuration form file by passed file path * * @param configFilename * @throws IOException */ public void loadFromFile(String configFilename) throws IOException { try { InputStream propertiesStream = new FileInputStream(new File( configFilename)); loadFromStream(propertiesStream); } catch (IOException ex) { LOG.error(COULD_NOT_OPEN_FILE_ERROR, ex); } } /** * Copies existed configuration for cloning * * @return {@link Map} copy of existed configuration */ protected Map<Object, Object> copy() { return new HashMap<Object, Object>(config); } /** * Clears existed configuration parameters */ protected void clear() { config.clear(); } @Override public Configuration clone() throws CloneNotSupportedException { // Deep clone for configuration Configuration cloneConfig; Object raw = super.clone(); // Casting cloned object to the appropriated type cloneConfig = ObjectUtils.cast(raw, Configuration.class); // Coping configuration for cloned data Map<Object, Object> copy = copy(); // copyConfig.putAll(this.config); cloneConfig.clear(); cloneConfig.configure(copy); return cloneConfig; } }
package org.lightmare.rest.providers; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.Response.StatusType; import org.apache.log4j.Logger; import org.glassfish.jersey.process.Inflector; import org.glassfish.jersey.server.ContainerRequest; import org.glassfish.jersey.server.model.Parameter; import org.lightmare.cache.MetaData; import org.lightmare.ejb.EjbConnector; import org.lightmare.utils.ObjectUtils; /** * {@link Inflector} implementation for ejb beans * * @author Levan * */ public class RestInflector implements Inflector<ContainerRequestContext, Response> { private Method method; private MetaData metaData; private MediaType type; private List<Parameter> parameters; private static final int PARAMS_DEF_LENGTH = 0; /** * Error status for exception handling * * @author Levan * */ protected static class ErrorStatusType implements StatusType { private String message; public ErrorStatusType(String message) { this.message = message; } public int getStatusCode() { return Status.ACCEPTED.getStatusCode(); } @Override public String getReasonPhrase() { return message; } @Override public Family getFamily() { return Family.SERVER_ERROR; } } private static final Logger LOG = Logger.getLogger(RestInflector.class); public RestInflector(Method method, MetaData metaData, MediaType type, List<Parameter> parameters) { this.method = method; this.metaData = metaData; this.type = type; this.parameters = parameters; } private Object[] getParameters(ContainerRequestContext data) throws IOException { Object[] params; ContainerRequest request = (ContainerRequest) data; request.bufferEntity(); if (ObjectUtils.available(parameters)) { List<Object> paramsList = new ArrayList<Object>(); for (Parameter parameter : parameters) { Object param = request.readEntity(parameter.getRawType(), parameter.getType(), parameter.getAnnotations()); if (ObjectUtils.notNull(param)) { paramsList.add(param); } } params = paramsList.toArray(); } else { params = new Object[PARAMS_DEF_LENGTH]; } return params; } @Override public Response apply(ContainerRequestContext data) { ResponseBuilder responseBuilder; Object value = null; try { EjbConnector connector = new EjbConnector(); InvocationHandler handler = connector.getHandler(metaData); Object bean = connector.connectToBean(metaData); Object[] params = getParameters(data); value = handler.invoke(bean, method, params); if (type == null) { responseBuilder = Response.ok(value); } else { responseBuilder = Response.ok(value, type); } } catch (Throwable ex) { LOG.error(ex.getMessage(), ex); responseBuilder = Response.status(new ErrorStatusType(ex .getMessage())); } return responseBuilder.build(); } }
package org.motechproject.ws.mobile; import java.io.Serializable; import java.util.Date; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import org.motechproject.ws.Care; import org.motechproject.ws.ContactNumberType; import org.motechproject.ws.MediaType; import org.motechproject.ws.MessageStatus; import org.motechproject.ws.NameValuePair; import org.motechproject.ws.Patient; import org.motechproject.ws.PatientMessage; /** * A webservice interface providing functionality for sending messages * * @author Kofi A. Asamoah (yoofi@dreamoval.com) * Date Created 30-07-09 */ @WebService public interface MessageService extends Serializable{ /** * Sends messages to registered patients * * @param messages List of messages to be sent */ @WebMethod public void sendPatientMessages(@WebParam(name="messages") PatientMessage[] messages); /** * Sends a message to a registered patient * * @param messageId Id of the message to send * @param personalInfo List of name value pairs containing patient information * @param patientNumber Patient mobile contact number * @param patientNumberType Type of contact number. Possible values include PERSONAL, SHARED * @param langCode Code representing preferred communication language * @param mediaType Patient's preferred communication medium * @param notificationType Type of message to send to patient * @param startDate Date to begin message sending attempts * @param endDate Date to stop message sending attempts * @param recipientId String unique identifier of the recipient * @return The status of the message */ @WebMethod public MessageStatus sendPatientMessage(@WebParam(name="messageId") String messageId, @WebParam(name="personalInfo") NameValuePair[] personalInfo, @WebParam(name="patientNumber") String patientNumber, @WebParam(name="patientNumberType") ContactNumberType patientNumberType, @WebParam(name="langCode") String langCode, @WebParam(name="mediaType") MediaType mediaType, @WebParam(name="notificationType") Long notificationType, @WebParam(name="startDate")Date startDate, @WebParam(name="endDate")Date endDate, @WebParam(name="recipientId")String recipientId); /** * Sends a message to a registered CHPS worker * * @param messageId Id of the message to send * @param personalInfo List of name value pairs containing patient information * @param workerNumber CHPS worker's mobile contact number * @param patients A List of patients requiring service from CHPS worker * @param langCode Code representing preferred communication language * @param mediaType Patient's preferred communication medium * @param notificationType Type of message to send to patient * @param startDate Date to begin message sending attempts * @param endDate Date to stop message sending attempts * @return The status of the message */ @WebMethod public MessageStatus sendCHPSMessage(@WebParam(name="messageId") String messageId, @WebParam(name="personalInfo") NameValuePair[] personalInfo, @WebParam(name="workerNumber") String workerNumber, @WebParam(name="patients") Patient[] patients, @WebParam(name="langCode") String langCode, @WebParam(name="mediaType") MediaType mediaType, @WebParam(name="notificationType") Long notificationType, @WebParam(name="startDate")Date startDate, @WebParam(name="endDate")Date endDate); /** * Sends a list of care defaulters to a CHPS worker * * @param messageId Id of the message to send * @param workerNumber CHPS worker's mobile contact number * @param cares List of patient care options which have defaulters * @param mediaType Patient's preferred communication medium * @param startDate Date to begin message sending attempts * @param endDate Date to stop message sending attempts * @return The status of the message */ @WebMethod public MessageStatus sendDefaulterMessage(@WebParam(name = "messageId") String messageId, @WebParam(name = "workerNumber") String workerNumber, @WebParam(name = "cares") Care[] cares, @WebParam(name = "media") MediaType mediaType, @WebParam(name = "startDate") Date startDate, @WebParam(name = "endDate") Date endDate); /** * Sends a list of patients within a delivery schedule to a CHPS worker * * @param messageId Id of the message to send * @param workerNumber CHPS worker's mobile contact number * @param patients List of patients with matching delivery status * @param deliveryStatus Status of patient delivery. Expected values are 'Upcoming', 'Recent' and 'Overdue' * @param mediaType Patient's preferred communication medium * @param startDate Date to begin message sending attempts * @param endDate Date to stop message sending attempts * @return The status of the message */ @WebMethod public MessageStatus sendDeliveriesMessage(@WebParam(name = "messageId") String messageId, @WebParam(name = "workerNumber") String workerNumber, @WebParam(name = "patients") Patient[] patients, @WebParam(name = "deliveryStatus") String deliveryStatus, @WebParam(name = "mediaType") MediaType mediaType, @WebParam(name = "startDate") Date startDate, @WebParam(name = "endDate") Date endDate); /** * Sends a list of upcoming care for a particular patient to a CHPS worker * * @param messageId Id of the message to send * @param workerNumber CHPS worker's mobile contact number * @param patient patient due for care * @param mediaType Patient's preferred communication medium * @param startDate Date to begin message sending attempts * @param endDate Date to stop message sending attempts * @return The status of the message */ @WebMethod public MessageStatus sendUpcomingCaresMessage(@WebParam(name = "messageId") String messageId, @WebParam(name = "workerNumber") String workerNumber, @WebParam(name = "patient") Patient patient, @WebParam(name = "mediaType") MediaType mediaType, @WebParam(name = "startDate") Date startDate, @WebParam(name = "endDate") Date endDate); /** * Sends an SMS message * * @param content the message to send * @param recipient the phone number to receive the message * @return */ @WebMethod public MessageStatus sendMessage(@WebParam(name = "content") String content, @WebParam(name = "recipient") String recipient); /** * Sends multiple upcoming care messages to a CHPS worker * * @param messageId Id of the message to send * @param workerNumber CHPS worker's mobile contact number * @param cares List of upcoming care * @param mediaType Patient's preferred communication medium * @param startDate Date to begin message sending attempts * @param endDate Date to stop message sending attempts * @return The status of the message */ @WebMethod public MessageStatus sendBulkCaresMessage(@WebParam(name = "messageId") String messageId, @WebParam(name = "workerNumber") String workerNumber, @WebParam(name = "patient") Care[] cares, @WebParam(name = "mediaType") MediaType mediaType, @WebParam(name = "startDate") Date startDate, @WebParam(name = "endDate") Date endDate); }
package fi.oulu.tol.sqat; public class Item { String name; int sellIn; int quality; public Item(String name, int sellIn, int quality) { this.setName(name); this.setSellIn(sellIn); this.setQuality(quality); } /* Generated getter and setter code */ public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSellIn() { return sellIn; } public void setSellIn(int sellIn) { this.sellIn = sellIn; } public int getQuality() { return quality; } public void setQuality(int quality) { this.quality = quality; } public void decreaseQuality(){ --quality; } public void increaseQuality(){ quality++; } public void decreaseSellIn(){ --sellIn; } public boolean isExpired(){ if (sellIn <0) return true; return false; } public boolean hasReachedMaximumQuality(){ if(quality < 50) return false; return true; } public boolean hasZeroQuality(){ if(quality >0) return false; return true; } }
package tools.ic; import java.util.*; import java.lang.reflect.*; import java.net.URLClassLoader; import java.net.URL; import java.net.MalformedURLException; import java.io.*; public class InterfaceComparer { private static boolean error = false; private static HashMap<String,Boolean> methodMap = null; private static void compareClasses(Class<?> cleanroomClass, Class<?> studentClass) { boolean equals = false; ArrayList<Method> studentMethods = new ArrayList<Method>(Arrays.asList(studentClass.getDeclaredMethods())); // checkMethods for(Method cleanroomMethod : cleanroomClass.getDeclaredMethods()){ // only compare if method was specified in @CompareInterface annotation if(methodMap.get(cleanroomMethod.getName()) == null){ continue; } methodMap.remove(cleanroomMethod.getName()); for(Method studentMethod : studentMethods) { if(cleanroomMethod.toString().equals(studentMethod.toString())) { equals = true; studentMethods.remove(studentMethod); break; } } if(equals){ equals = false; }else{ error = true; System.err.println("ERROR - Method " +cleanroomMethod + " does not exists in student code or does not match with student counterpart"); } } } private static String getSimpleFileName(String path){ int idx = path.lastIndexOf("/"); return idx >= 0 ? path.substring(idx + 1) : path; } private static HashMap<String,Boolean> argsToMap(String[] methods){ HashMap<String,Boolean> methodMap = new HashMap<String,Boolean>(); for(String method : methods){ methodMap.put(method,true); } return methodMap; } public static void main(String args[]){ if(args == null){ System.err.println("Usage: java tools.ic.InterfaceComparer <method1> .. <methodn>"); System.exit(-1); } String cwd = System.getProperty("user.dir"); String pathToCleanroom = cwd + "/cleanroom/"; File f = new File(pathToCleanroom); ClassLoader cl = ClassLoader.getSystemClassLoader(); ClassLoader cleanroomLoader = null; ClassLoader studentLoader = null; methodMap = argsToMap(args); try{ cleanroomLoader = new URLClassLoader(new URL[]{new File(pathToCleanroom).toURI().toURL()}); studentLoader = new URLClassLoader(new URL[]{new File(cwd).toURI().toURL()}); }catch(MalformedURLException mfue){ throw new Error("Error" + mfue.getMessage()); } for(File path : f.listFiles()) { if (path.isFile()) { String pathString = path.toString(); if(pathString.endsWith(".class")){ // get simple Name String fileName = getSimpleFileName(pathString); // strip fileextension fileName = fileName.substring(0, fileName.lastIndexOf('.')); Class<?> cleanroomClass = null; Class<?> studentClass = null; try{ cleanroomClass = cleanroomLoader.loadClass(fileName); studentClass = studentLoader.loadClass(fileName); } catch (ClassNotFoundException cnfe) { throw new Error("Error - class [" + cnfe.getMessage()+"] not found"); } compareClasses(cleanroomClass,studentClass); } } } if(error){ // check if there were methods declared in @CompareInterface which could not be found if(methodMap.size() != 0) { System.err.println("The following methods declared in @CompareInterface could not be found in cleanroom:"); for(String methodName : methodMap.keySet()){ System.out.print(methodName+" "); } } throw new Error(); } } }
package org.sonar.plugins.stash.client; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder; import com.ning.http.client.AsyncHttpClientConfig; import com.ning.http.client.AsyncHttpClientConfigDefaults; import com.ning.http.client.Realm; import com.ning.http.client.Realm.AuthScheme; import com.ning.http.client.Response; import org.apache.commons.lang3.StringUtils; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.sonar.plugins.stash.PluginInfo; import org.sonar.plugins.stash.PluginUtils; import org.sonar.plugins.stash.StashPlugin; import org.sonar.plugins.stash.exceptions.StashClientException; import org.sonar.plugins.stash.exceptions.StashReportExtractionException; import org.sonar.plugins.stash.issue.StashComment; import org.sonar.plugins.stash.issue.StashCommentReport; import org.sonar.plugins.stash.issue.StashDiffReport; import org.sonar.plugins.stash.issue.StashPullRequest; import org.sonar.plugins.stash.issue.StashTask; import org.sonar.plugins.stash.issue.StashUser; import org.sonar.plugins.stash.issue.collector.StashCollector; import java.io.IOException; import java.net.HttpURLConnection; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static java.net.HttpURLConnection.HTTP_CREATED; public class StashClient implements AutoCloseable { private final String baseUrl; private final StashCredentials credentials; private final int stashTimeout; private AsyncHttpClient httpClient; private static final String REST_API = "/rest/api/1.0/"; private static final String USER_API = "{0}users/{1}"; private static final String REPO_API = "{0}projects/{1}/repos/{2}/"; private static final String PULL_REQUESTS_API = REPO_API + "pull-requests/"; private static final String PULL_REQUEST_API = PULL_REQUESTS_API + "{3}"; private static final String COMMENTS_PULL_REQUEST_API = PULL_REQUEST_API + "/comments"; private static final String COMMENT_PULL_REQUEST_API = COMMENTS_PULL_REQUEST_API + "/{4}?version={5}"; private static final String DIFF_PULL_REQUEST_API = PULL_REQUEST_API + "/diff"; private static final String APPROVAL_PULL_REQUEST_API = PULL_REQUEST_API + "/approve"; private static final String TASKS_API = REST_API + "tasks"; private static final String PULL_REQUEST_APPROVAL_POST_ERROR_MESSAGE = "Unable to change status of pull-request {0} private static final String PULL_REQUEST_GET_ERROR_MESSAGE = "Unable to retrieve pull-request {0} private static final String PULL_REQUEST_PUT_ERROR_MESSAGE = "Unable to update pull-request {0} private static final String USER_GET_ERROR_MESSAGE = "Unable to retrieve user {0}."; private static final String COMMENT_POST_ERROR_MESSAGE = "Unable to post a comment to {0} private static final String COMMENT_GET_ERROR_MESSAGE = "Unable to get comment linked to {0} private static final String COMMENT_DELETION_ERROR_MESSAGE = "Unable to delete comment {0} from pull-request {1} private static final String TASK_POST_ERROR_MESSAGE = "Unable to post a task on comment {0}."; private static final String TASK_DELETION_ERROR_MESSAGE = "Unable to delete task {0}."; // FIXME use constants from org.asynchttpclient.util.HttpConstants.Methods private static final String HTTP_POST = "POST", HTTP_GET = "GET", HTTP_PUT = "PUT", HTTP_DELETE = "DELETE"; public StashClient(String url, StashCredentials credentials, int stashTimeout) { this.baseUrl = url; this.credentials = credentials; this.stashTimeout = stashTimeout; this.httpClient = createHttpClient(); } public void postCommentOnPullRequest(String project, String repository, String pullRequestId, String report) throws StashClientException { String request = MessageFormat.format(COMMENTS_PULL_REQUEST_API, baseUrl + REST_API, project, repository, pullRequestId); JSONObject json = new JSONObject(); json.put("text", report); postCreate(request, json, MessageFormat.format(COMMENT_POST_ERROR_MESSAGE, repository, pullRequestId)); } public StashCommentReport getPullRequestComments(String project, String repository, String pullRequestId, String path) throws StashClientException { StashCommentReport result = new StashCommentReport(); long start = 0; boolean isLastPage = false; while (! isLastPage){ try { String request = MessageFormat.format(COMMENTS_PULL_REQUEST_API + "?path={4}&start={5}", baseUrl + REST_API, project, repository, pullRequestId, path, start); JSONObject jsonComments = get(request, MessageFormat.format(COMMENT_GET_ERROR_MESSAGE, repository, pullRequestId)); result.add(StashCollector.extractComments(jsonComments)); // Stash pagination: check if you get all comments linked to the pull-request isLastPage = StashCollector.isLastPage(jsonComments); start = StashCollector.getNextPageStart(jsonComments); } catch (StashReportExtractionException e) { throw new StashClientException(e); } } return result; } public void deletePullRequestComment(String project, String repository, String pullRequestId, StashComment comment) throws StashClientException { String request = MessageFormat.format(COMMENT_PULL_REQUEST_API, baseUrl + REST_API, project, repository, pullRequestId, Long.toString(comment.getId()), Long.toString(comment.getVersion())); BoundRequestBuilder requestBuilder = httpClient.prepareDelete(request); delete(request, MessageFormat.format(COMMENT_DELETION_ERROR_MESSAGE, comment.getId(), repository, pullRequestId)); } public StashDiffReport getPullRequestDiffs(String project, String repository, String pullRequestId) throws StashClientException { StashDiffReport result = new StashDiffReport(); try { String request = MessageFormat.format(DIFF_PULL_REQUEST_API + "?withComments=true", baseUrl + REST_API, project, repository, pullRequestId); JSONObject jsonDiffs = get(request, MessageFormat.format(COMMENT_GET_ERROR_MESSAGE, repository, pullRequestId)); result = StashCollector.extractDiffs(jsonDiffs); } catch (StashReportExtractionException e) { throw new StashClientException(e); } return result; } public StashComment postCommentLineOnPullRequest(String project, String repository, String pullRequestId, String message, String path, long line, String type) throws StashClientException { String request = MessageFormat.format(COMMENTS_PULL_REQUEST_API, baseUrl + REST_API, project, repository, pullRequestId); JSONObject anchor = new JSONObject(); anchor.put("line", line); anchor.put("lineType", type); String fileType = "TO"; if (StringUtils.equals(type, StashPlugin.CONTEXT_ISSUE_TYPE)){ fileType = "FROM"; } anchor.put("fileType", fileType); anchor.put("path", path); JSONObject json = new JSONObject(); json.put("text", message); json.put("anchor", anchor); JSONObject response = postCreate(request, json, MessageFormat.format(COMMENT_POST_ERROR_MESSAGE, repository, pullRequestId)); try { return StashCollector.extractComment(response, path, line); } catch (StashReportExtractionException e) { throw new StashClientException(e); } } public StashUser getUser(String userSlug) throws StashClientException { String request = MessageFormat.format(USER_API, baseUrl + REST_API, userSlug); JSONObject response = get(request, MessageFormat.format(USER_GET_ERROR_MESSAGE, userSlug)); try { return StashCollector.extractUser(response); } catch (StashReportExtractionException e) { throw new StashClientException(e); } } public StashPullRequest getPullRequest(String project, String repository, String pullRequestId) throws StashClientException { String request = MessageFormat.format(PULL_REQUEST_API, baseUrl + REST_API, project, repository, pullRequestId); JSONObject response = get(request, MessageFormat.format(PULL_REQUEST_GET_ERROR_MESSAGE, repository, pullRequestId)); try { return StashCollector.extractPullRequest(project, repository, pullRequestId, response); } catch (StashReportExtractionException e) { throw new StashClientException(e); } } public void addPullRequestReviewer(String project, String repository, String pullRequestId, long pullRequestVersion, ArrayList<StashUser> reviewers) throws StashClientException { String request = MessageFormat.format(PULL_REQUEST_API, baseUrl + REST_API, project, repository, pullRequestId); JSONObject json = new JSONObject(); JSONArray jsonReviewers = new JSONArray(); for (StashUser reviewer: reviewers) { JSONObject reviewerName = new JSONObject(); reviewerName.put("name", reviewer.getName()); JSONObject user = new JSONObject(); user.put("user", reviewerName); jsonReviewers.add(user); } json.put("reviewers", jsonReviewers); json.put("id", pullRequestId); json.put("version", pullRequestVersion); put(request, json, MessageFormat.format(PULL_REQUEST_PUT_ERROR_MESSAGE, repository, pullRequestId)); } public void approvePullRequest(String project, String repository, String pullRequestId) throws StashClientException { String request = MessageFormat.format(APPROVAL_PULL_REQUEST_API, baseUrl + REST_API, project, repository, pullRequestId); post(request, null, MessageFormat.format(PULL_REQUEST_APPROVAL_POST_ERROR_MESSAGE, repository, pullRequestId)); } public void resetPullRequestApproval(String project, String repository, String pullRequestId) throws StashClientException { String request = MessageFormat.format(APPROVAL_PULL_REQUEST_API, baseUrl + REST_API, project, repository, pullRequestId); delete(request, HttpURLConnection.HTTP_OK, MessageFormat.format(PULL_REQUEST_APPROVAL_POST_ERROR_MESSAGE, repository, pullRequestId)); } public void postTaskOnComment(String message, Long commentId) throws StashClientException { String request = baseUrl + TASKS_API; JSONObject anchor = new JSONObject(); anchor.put("id", commentId); anchor.put("type", "COMMENT"); JSONObject json = new JSONObject(); json.put("anchor", anchor); json.put("text", message); postCreate(request, json, MessageFormat.format(TASK_POST_ERROR_MESSAGE, commentId)); } public void deleteTaskOnComment(StashTask task) throws StashClientException { String request = baseUrl + TASKS_API + "/" + task.getId(); delete(request, MessageFormat.format(TASK_DELETION_ERROR_MESSAGE, task.getId())); } void setHttpClient(AsyncHttpClient httpClient) { this.httpClient = httpClient; } @Override public void close() { httpClient.close(); } private JSONObject get(String url, String errorMessage) throws StashClientException { return performRequest(httpClient.prepareGet(url), null, HttpURLConnection.HTTP_OK, errorMessage); } private JSONObject post(String url, JSONObject body, String errorMessage) throws StashClientException { return performRequest(httpClient.preparePost(url), body, HttpURLConnection.HTTP_OK, errorMessage); } private JSONObject postCreate(String url, JSONObject body, String errorMessage) throws StashClientException { return performRequest(httpClient.preparePost(url), body, HTTP_CREATED, errorMessage); } private JSONObject delete(String url, int expectedStatusCode, String errorMessage) throws StashClientException { return performRequest(httpClient.prepareDelete(url), null, expectedStatusCode, errorMessage); } private JSONObject delete(String url, String errorMessage) throws StashClientException { return delete(url, HttpURLConnection.HTTP_NO_CONTENT, errorMessage); } private JSONObject put(String url, JSONObject body, String errorMessage) throws StashClientException { return performRequest(httpClient.preparePut(url), body, HttpURLConnection.HTTP_OK, errorMessage); } private JSONObject performRequest(BoundRequestBuilder requestBuilder, JSONObject body, int expectedStatusCode, String errorMessage) throws StashClientException { if (body != null) { requestBuilder.setBody(body.toString()); } Realm realm = new Realm.RealmBuilder().setPrincipal(credentials.getLogin()).setPassword(credentials.getPassword()) .setUsePreemptiveAuth(true).setScheme(AuthScheme.BASIC).build(); requestBuilder.setRealm(realm); requestBuilder.setFollowRedirects(true); requestBuilder.addHeader("Content-Type", "application/json"); try { Response response = requestBuilder.execute().get(stashTimeout, TimeUnit.MILLISECONDS); validateResponse(response, expectedStatusCode, errorMessage); return extractResponse(response); } catch (ExecutionException | TimeoutException | InterruptedException e) { throw new StashClientException(e); } } private static void validateResponse(Response response, int expectedStatusCode, String message) throws StashClientException { int responseCode = response.getStatusCode(); if (responseCode != expectedStatusCode) { throw new StashClientException(message + " Received " + responseCode + ": " + formatStashApiError(response)); } } private static JSONObject extractResponse(Response response) throws StashClientException { String body = null; try { body = response.getResponseBody(); } catch (IOException e) { throw new StashClientException("Could not load response body", e); } if (StringUtils.isEmpty(body)) { return null; } String contentType = response.getHeader("Content-Type"); if (!"application/json".equals(contentType)) { throw new StashClientException("Received response with type " + contentType + " instead of JSON"); } try { Object obj = new JSONParser().parse(body); return (JSONObject) obj; } catch (ParseException | ClassCastException e) { throw new StashClientException("Could not parse JSON response " + e + "('" + body + "')", e); } } private static String formatStashApiError(Response response) throws StashClientException { JSONArray errors; JSONObject responseJson = extractResponse(response); errors = (JSONArray) responseJson.get("errors"); if (errors == null) { throw new StashClientException("Error response did not contain an errors object '" + responseJson + "'"); } List<String> errorParts = new ArrayList<>(); for (Object o : errors) { try { JSONObject error = (JSONObject) o; errorParts.add((String) error.get("exceptionName") + ": " + (String) error.get("message")); } catch (ClassCastException e) { throw new StashClientException("Error response contained invalid error", e); } } return StringUtils.join(errorParts, ", "); } // We can't test this, as the manifest can only be loaded when deployed from a JAR-archive. // During unit testing this is not the case public static String getUserAgent() { PluginInfo info = PluginUtils.infoForPluginClass(StashPlugin.class); String name, version, sonarQubeVersion; name = version = sonarQubeVersion = "unknown"; if (info != null) { name = info.getName(); version = info.getVersion(); // FIXME: add SonarQube version } return MessageFormat.format("SonarQube/{0} {1}/{2} {3}", sonarQubeVersion, name, version, AsyncHttpClientConfigDefaults.defaultUserAgent()); } AsyncHttpClient createHttpClient(){ return new AsyncHttpClient( new AsyncHttpClientConfig.Builder().setUserAgent(getUserAgent()).build()); } }
package tools.ic; import java.util.*; import java.lang.reflect.*; import java.net.URLClassLoader; import java.net.URL; import java.net.MalformedURLException; import java.io.*; public class InterfaceComparer { private static boolean error = false; private static HashMap<String,HashMap<String,Boolean>> checkMap = null; // check for specified cleanroom methods with student counterpart private static void compareClasses(Class<?> cleanroomClass, Class<?> studentClass) { boolean equals = false; HashMap<String,Boolean> methodMap = checkMap.get(cleanroomClass.getName()); // ArrayList<Method> studentMethods = new ArrayList<Method>(Arrays.asList(studentClass.getDeclaredMethods())); // checkMethods for(Method cleanroomMethod : cleanroomClass.getDeclaredMethods()){ // only compare if method was specified in @CompareInterface annotation if(methodMap.get(cleanroomMethod.getName()) == null){ continue; } methodMap.remove(cleanroomMethod.getName()); Class<?>[] pTypes = cleanroomMethod.getParameterTypes(); Method studentMethod = null; try{ studentMethod = studentClass.getMethod(cleanroomMethod.getName(),pTypes); } catch (NoSuchMethodException nsme){ System.err.println("ERROR - Method " +cleanroomMethod + "["+cleanroomClass.getName()+"] does not exists in student code or does not match with student counterpart"); error = true; continue; } if(!cleanroomMethod.toGenericString().equals(studentMethod.toGenericString())) { error = true; System.err.println("ERROR - Method " +cleanroomMethod + "["+cleanroomClass.getName()+"] does not exists in student code or does not match with student counterpart"); } } // check if there were methods declared in @CompareInterface which could not be found if(methodMap.size() != 0) { System.err.println("Error - The following method(s) declared in @CompareInterface could not be found in cleanroom class [" + cleanroomClass.getName()+"]:"); for(String methodName : methodMap.keySet()){ System.err.print(methodName+" "); } System.err.println(""); error = true; } } // parses the cmd args and save it to HashMap private static void argsToMap(String[] args){ checkMap = new HashMap<String,HashMap<String,Boolean>>(); for(String cm : args){ if(cm.contains(".")){ String[] parts = cm.split("\\."); HashMap<String,Boolean> methodMap = checkMap.get(parts[0]); if(methodMap == null){ methodMap = new HashMap<String,Boolean>(); } methodMap.put(parts[1],true); checkMap.put(parts[0],methodMap); } else { throw new IllegalArgumentException("Error - @CompareInterface args must to look like this: Class.Method, found: " + cm); } } } public static void main(String args[]){ if(args == null){ System.err.println("Usage: java tools.ic.InterfaceComparer <Class.method1> .. <Class.methodn>"); System.exit(-1); } String cwd = System.getProperty("user.dir"); String pathToCleanroom = cwd + "/cleanroom/"; ClassLoader cl = ClassLoader.getSystemClassLoader(); ClassLoader cleanroomLoader = null; ClassLoader studentLoader = null; argsToMap(args); try{ cleanroomLoader = new URLClassLoader(new URL[]{new File(pathToCleanroom).toURI().toURL()}); studentLoader = new URLClassLoader(new URL[]{new File(cwd).toURI().toURL()}); }catch(MalformedURLException mfue){ throw new Error("Error - " + mfue.getMessage()); } for(String className : checkMap.keySet()){ Class<?> cleanroomClass = null; Class<?> studentClass = null; try{ cleanroomClass = cleanroomLoader.loadClass(className); } catch (ClassNotFoundException cnfe) { throw new Error("Error - cleanroom class [" + cnfe.getMessage()+"] not found"); } try{ studentClass = studentLoader.loadClass(className); } catch (ClassNotFoundException cnfe) { throw new Error("Error - student class [" + cnfe.getMessage()+"] not found"); } compareClasses(cleanroomClass,studentClass); } if(error){ throw new Error(); } } }
package org.yaml.snakeyaml.constructor; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.error.YAMLException; import org.yaml.snakeyaml.introspector.FieldProperty; import org.yaml.snakeyaml.introspector.MethodProperty; import org.yaml.snakeyaml.introspector.Property; import org.yaml.snakeyaml.nodes.MappingNode; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.NodeId; import org.yaml.snakeyaml.nodes.NodeTuple; import org.yaml.snakeyaml.nodes.ScalarNode; import org.yaml.snakeyaml.nodes.SequenceNode; import org.yaml.snakeyaml.nodes.Tags; public class Constructor extends SafeConstructor { private final Map<String, Class<? extends Object>> typeTags; private final Map<Class<? extends Object>, TypeDescription> typeDefinitions; public Constructor() { this(Object.class); } public Constructor(Class<? extends Object> theRoot) { if (theRoot == null) { throw new NullPointerException("Root type must be provided."); } this.yamlConstructors.put(null, new ConstructYamlObject()); rootType = theRoot; typeTags = new HashMap<String, Class<? extends Object>>(); typeDefinitions = new HashMap<Class<? extends Object>, TypeDescription>(); yamlClassConstructors.put(NodeId.scalar, new ConstructScalarObject()); yamlClassConstructors.put(NodeId.mapping, new ConstructMappingFromClass()); yamlClassConstructors.put(NodeId.sequence, new ConstructSeqFromClass()); } /** * Create Constructor for a class which does not have to be in the classpath * or for a definition from a Spring ApplicationContext. * * @param theRoot * fully qualified class name of the root JavaBean * @throws ClassNotFoundException */ public Constructor(String theRoot) throws ClassNotFoundException { this(Class.forName(check(theRoot))); } private static final String check(String s) { if (s == null) { throw new NullPointerException("Root type must be provided."); } if (s.trim().length() == 0) { throw new YAMLException("Root type must be provided."); } return s; } /** * Make YAML aware how to parse a custom Class. If there is no root Class * assigned in constructor then the 'root' property of this definition is * respected. * * @param definition * to be added to the Constructor * @return the previous value associated with <tt>definition</tt>, or * <tt>null</tt> if there was no mapping for <tt>definition</tt>. */ public TypeDescription addTypeDescription(TypeDescription definition) { if (definition == null) { throw new NullPointerException("TypeDescription is required."); } if (rootType == Object.class && definition.isRoot()) { rootType = definition.getType(); } String tag = definition.getTag(); typeTags.put(tag, definition.getType()); return typeDefinitions.put(definition.getType(), definition); } private class ConstructMappingFromClass implements Construct { /** * Construct JavaBean. If type safe collections are used please look at * <code>TypeDescription</code>. * * @param node * node where the keys are property names (they can only be * <code>String</code>s) and values are objects to be created * @return constructed JavaBean */ public Object construct(Node node) { MappingNode mnode = (MappingNode) node; if (Map.class.isAssignableFrom(node.getType())) { if (node.isTwoStepsConstruction()) { // TODO when the Map implementation is known it should be // used return createDefaultMap(); } else { return constructMapping((MappingNode) node); } } else if (Set.class.isAssignableFrom(node.getType())) { if (node.isTwoStepsConstruction()) { // TODO when the Set implementation is known it should be // used return createDefaultSet(); } else { return constructSet((MappingNode) node); } } else { if (node.isTwoStepsConstruction()) { return createEmptyJavaBean(mnode); } else { return constructJavaBean2ndStep(mnode, createEmptyJavaBean(mnode)); } } } @SuppressWarnings("unchecked") public void construct2ndStep(Node node, Object object) { if (Map.class.isAssignableFrom(node.getType())) { constructMapping2ndStep((MappingNode) node, (Map<Object, Object>) object); } else if (Set.class.isAssignableFrom(node.getType())) { constructSet2ndStep((MappingNode) node, (Set<Object>) object); } else { constructJavaBean2ndStep((MappingNode) node, object); } } private Object createEmptyJavaBean(MappingNode node) { try { Class<? extends Object> type = node.getType(); if (Modifier.isAbstract(type.getModifiers())) { node.setType(getClassForNode(node)); } /** * Using only default constructor. Everything else will be * initialized on 2nd step. If we do here some partial * initialization, how do we then track what need to be done on * 2nd step? I think it is better to get only object here (to * have it as reference for recursion) and do all other thing on * 2nd step. */ return node.getType().newInstance(); } catch (InstantiationException e) { throw new YAMLException(e); } catch (IllegalAccessException e) { throw new YAMLException(e); } catch (ClassNotFoundException e) { throw new YAMLException(e); } } @SuppressWarnings("unchecked") private Object constructJavaBean2ndStep(MappingNode node, Object object) { Class<? extends Object> beanType = node.getType(); List<NodeTuple> nodeValue = (List<NodeTuple>) node.getValue(); for (NodeTuple tuple : nodeValue) { ScalarNode keyNode; if (tuple.getKeyNode() instanceof ScalarNode) { // key must be scalar keyNode = (ScalarNode) tuple.getKeyNode(); } else { throw new YAMLException("Keys must be scalars but found: " + tuple.getKeyNode()); } Node valueNode = tuple.getValueNode(); // keys can only be Strings keyNode.setType(String.class); String key = (String) constructObject(keyNode); boolean isArray = false; try { Property property = getProperty(beanType, key); valueNode.setType(property.getType()); TypeDescription memberDescription = typeDefinitions.get(beanType); if (memberDescription != null) { switch (valueNode.getNodeId()) { case sequence: SequenceNode snode = (SequenceNode) valueNode; Class<? extends Object> memberType = memberDescription .getListPropertyType(key); if (memberType != null) { snode.setListType(memberType); } else if (property.getType().isArray()) { isArray = true; snode.setListType(property.getType().getComponentType()); } break; case mapping: MappingNode mnode = (MappingNode) valueNode; Class<? extends Object> keyType = memberDescription.getMapKeyType(key); if (keyType != null) { mnode.setKeyType(keyType); mnode.setValueType(memberDescription.getMapValueType(key)); } break; } } Object value = constructObject(valueNode); if (isArray) { List<Object> list = (List<Object>) value; value = list.toArray(createArray(property.getType())); } property.set(object, value); } catch (Exception e) { // TODO use more informative error message, mention // property // name System.err.println("key: " + key + "; valueNode=" + valueNode); throw new YAMLException(e); } } return object; } @SuppressWarnings("unchecked") private <T> T[] createArray(Class<T> type) { return (T[]) Array.newInstance(type.getComponentType(), 0); } private Property getProperty(Class<? extends Object> type, String name) throws IntrospectionException { for (PropertyDescriptor property : Introspector.getBeanInfo(type) .getPropertyDescriptors()) { if (property.getName().equals(name)) { if (property.getWriteMethod() != null) { return new MethodProperty(property); } else { throw new YAMLException("Property '" + name + "' on JavaBean: " + type.getName() + " does not have the write method"); } } } for (Field field : type.getFields()) { int modifiers = field.getModifiers(); if (Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) { continue; } if (field.getName().equals(name)) { return new FieldProperty(field); } } throw new YAMLException("Unable to find property '" + name + "' on class: " + type.getName()); } } private class ConstructYamlObject extends AbstractConstruct { @SuppressWarnings("unchecked") public Object construct(Node node) { Object result = null; try { Class cl = getClassForNode(node); node.setType(cl); Construct constructor = yamlClassConstructors.get(node.getNodeId()); result = constructor.construct(node); } catch (Exception e) { throw new ConstructorException(null, null, "Can't construct a java object for " + node.getTag() + "; exception=" + e.getMessage(), node.getStartMark(), e); } return result; } } /** * Construct scalar instance when the runtime class is known. Recursive * structures are not supported. */ private class ConstructScalarObject extends AbstractConstruct { @SuppressWarnings("unchecked") public Object construct(Node nnode) { ScalarNode node = (ScalarNode) nnode; Class type = node.getType(); Object result; if (type.isPrimitive() || type == String.class || Number.class.isAssignableFrom(type) || type == Boolean.class || Date.class.isAssignableFrom(type) || type == Character.class || type == BigInteger.class || Enum.class.isAssignableFrom(type) || Tags.BINARY.equals(node.getTag())) { // standard classes created directly result = constructStandardJavaInstance(type, node); } else { // there must be only 1 constructor with 1 argument java.lang.reflect.Constructor[] javaConstructors = type.getConstructors(); boolean found = false; java.lang.reflect.Constructor javaConstructor = null; for (java.lang.reflect.Constructor c : javaConstructors) { if (c.getParameterTypes().length == 1) { if (found) { throw new YAMLException( "More then 1 constructor with 1 argument found for " + type); } found = true; javaConstructor = c; } } if (javaConstructor == null) { throw new YAMLException("No single argument constructor found for " + type); } else { Object argument = constructStandardJavaInstance(javaConstructor .getParameterTypes()[0], node); try { result = javaConstructor.newInstance(argument); } catch (Exception e) { throw new ConstructorException(null, null, "Can't construct a java object for scalar " + node.getTag() + "; exception=" + e.getMessage(), node.getStartMark(), e); } } } return result; } @SuppressWarnings("unchecked") private Object constructStandardJavaInstance(Class type, ScalarNode node) { Object result; if (type == String.class) { Construct stringConstructor = yamlConstructors.get(Tags.STR); result = stringConstructor.construct((ScalarNode) node); } else if (type == Boolean.class || type == Boolean.TYPE) { Construct boolConstructor = yamlConstructors.get(Tags.BOOL); result = boolConstructor.construct((ScalarNode) node); } else if (type == Character.class || type == Character.TYPE) { Construct charConstructor = yamlConstructors.get(Tags.STR); String ch = (String) charConstructor.construct((ScalarNode) node); if (ch.length() == 0) { result = null; } else if (ch.length() != 1) { throw new YAMLException("Invalid node Character: '" + ch + "'; length: " + ch.length()); } else { result = new Character(ch.charAt(0)); } } else if (Date.class.isAssignableFrom(type)) { Construct dateConstructor = yamlConstructors.get(Tags.TIMESTAMP); Date date = (Date) dateConstructor.construct((ScalarNode) node); if (type == Date.class) { result = date; } else { try { java.lang.reflect.Constructor<?> constr = type.getConstructor(long.class); result = constr.newInstance(date.getTime()); } catch (Exception e) { throw new YAMLException("Cannot construct: '" + type + "'"); } } } else if (type == Float.class || type == Double.class || type == Float.TYPE || type == Double.TYPE || type == BigDecimal.class) { Construct doubleConstructor = yamlConstructors.get(Tags.FLOAT); result = doubleConstructor.construct(node); if (type == Float.class || type == Float.TYPE) { result = new Float((Double) result); } else if (type == BigDecimal.class) { result = new BigDecimal(((Double) result).doubleValue()); } } else if (type == Byte.class || type == Short.class || type == Integer.class || type == Long.class || type == BigInteger.class || type == Byte.TYPE || type == Short.TYPE || type == Integer.TYPE || type == Long.TYPE) { Construct intConstructor = yamlConstructors.get(Tags.INT); result = intConstructor.construct(node); if (type == Byte.class || type == Byte.TYPE) { result = new Byte(result.toString()); } else if (type == Short.class || type == Short.TYPE) { result = new Short(result.toString()); } else if (type == Integer.class || type == Integer.TYPE) { result = new Integer(result.toString()); } else if (type == Long.class || type == Long.TYPE) { result = new Long(result.toString()); } else { // only BigInteger left result = new BigInteger(result.toString()); } } else if (Enum.class.isAssignableFrom(type)) { String enumValueName = node.getValue(); try { result = Enum.valueOf(type, enumValueName); } catch (Exception ex) { throw new YAMLException("Unable to find enum value '" + enumValueName + "' for enum class: " + type.getName()); } } else if (Tags.BINARY.equals(node.getTag())) { Construct intConstructor = yamlConstructors.get(Tags.BINARY); result = intConstructor.construct(node); } else { throw new YAMLException("Unsupported class: " + type); } return result; } } private class ConstructSeqFromClass implements Construct { @SuppressWarnings("unchecked") public Object construct(Node node) { SequenceNode snode = (SequenceNode) node; if (List.class.isAssignableFrom(node.getType()) || node.getType().isArray()) { if (node.isTwoStepsConstruction()) { return createDefaultList(snode.getValue().size()); } else { return constructSequence(snode); } } else { // create immutable object List<Object> argumentList = (List<Object>) constructSequence(snode); Class[] parameterTypes = new Class[argumentList.size()]; int index = 0; for (Object parameter : argumentList) { parameterTypes[index] = parameter.getClass(); index++; } java.lang.reflect.Constructor javaConstructor; try { Class cl = getClassForNode(node); javaConstructor = cl.getConstructor(parameterTypes); Object[] initargs = argumentList.toArray(); return javaConstructor.newInstance(initargs); } catch (Exception e) { throw new YAMLException(e); } } } @SuppressWarnings("unchecked") public void construct2ndStep(Node node, Object object) { SequenceNode snode = (SequenceNode) node; List<Object> list = (List<Object>) object; if (List.class.isAssignableFrom(node.getType())) { constructSequenceStep2(snode, list); } else { // TODO support arrays throw new UnsupportedOperationException("Immutable objects cannot be recursive."); } } } private Class<?> getClassForNode(Node node) throws ClassNotFoundException { Class<? extends Object> customTag = typeTags.get(node.getTag()); if (customTag == null) { if (node.getTag().length() < Tags.PREFIX.length()) { throw new YAMLException("Unknown tag: " + node.getTag()); } String name = node.getTag().substring(Tags.PREFIX.length()); Class<?> cl = Class.forName(name); typeTags.put(node.getTag(), cl); return cl; } else { return customTag; } } }
package foam.dao; import foam.core.FObject; import foam.core.PropertyInfo; import foam.core.X; import foam.lib.json.Outputter; import foam.mlang.order.Comparator; import foam.mlang.predicate.Predicate; public abstract class AbstractJDAO extends ProxyDAO { protected Journal journal_; public AbstractJDAO(foam.core.X x, DAO delegate, String filename) { setX(x); setOf(delegate.getOf()); setDelegate(delegate); // create journal journal_ = new FileJournal.Builder(getX()) .setFilename(filename) .setCreateFile(true) .build(); // create a composite journal of repo journal // and runtime journal and load them all new CompositeJournal.Builder(getX()) .setDelegates(new Journal[]{ new FileJournal.Builder(getX()) .setFilename(filename + ".0") .build(), new FileJournal.Builder(getX()) .setFilename(filename) .build() }) .build().replay(delegate); } protected abstract Outputter getOutputter(); /** * persists data into FileJournal then calls the delegated DAO. * * @param obj * @returns FObject */ @Override public synchronized FObject put_(X x, FObject obj) { PropertyInfo id = (PropertyInfo) getOf().getAxiomByName("id"); FObject o = getDelegate().find_(x, id.get(obj)); FObject ret = null; if ( o == null ) { // data does not exist ret = getDelegate().put_(x, obj); // stringify to json string journal_.put(ret, null); } else { // compare with old data if old data exists // get difference FObject ret = difference(o, obj); // if no difference, then return if ( ret == null ) return obj; // stringify difference FObject into json string journal_.put(ret, null); // put new data into memory ret = getDelegate().put_(x, obj); } return ret; } @Override public FObject remove_(X x, FObject obj) { FObject ret = getDelegate().remove_(x, obj); if ( ret == null ) { return ret; } // TODO: Would be more efficient to output the ID portion of the object. But // if ID is an alias or multi part id we should only output the // true properties that ID/MultiPartID maps too. FObject r = generateFObject(ret); PropertyInfo idInfo = (PropertyInfo) getOf().getAxiomByName("id"); idInfo.set(r, idInfo.get(ret)); journal_.remove(r, null); return ret; } @Override public void removeAll_(final X x, long skip, final long limit, Comparator order, Predicate predicate) { getDelegate().select_(x, new RemoveSink(x, this), skip, limit, order, predicate); getDelegate().removeAll_(x, skip, limit, order, predicate); } protected FObject difference(FObject o, FObject n) { FObject diff = o.hardDiff(n); // no difference, then return null if ( diff == null ) return null; // get the PropertyInfo for the id PropertyInfo idInfo = (PropertyInfo) getOf().getAxiomByName("id"); // set id property to new instance idInfo.set(diff, idInfo.get(o)); return diff; } // return a new FObject protected FObject generateFObject(FObject o) { try { //create a new Instance return (FObject) o.getClassInfo().getObjClass().newInstance(); } catch ( Throwable t ) { throw new RuntimeException(t); } } }
package pitt.search.semanticvectors; import java.lang.IllegalArgumentException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.Enumeration; import java.util.List; import java.util.logging.Logger; import pitt.search.semanticvectors.LuceneUtils; import pitt.search.semanticvectors.VectorStore; import pitt.search.semanticvectors.vectors.BinaryVectorUtils; import pitt.search.semanticvectors.vectors.IncompatibleVectorsException; import pitt.search.semanticvectors.vectors.Vector; import pitt.search.semanticvectors.vectors.VectorFactory; import pitt.search.semanticvectors.vectors.VectorType; import pitt.search.semanticvectors.vectors.VectorUtils; import pitt.search.semanticvectors.vectors.ZeroVectorException; /** * Class for searching vector stores using different scoring functions. * Each VectorSearcher implements a particular scoring function which is * normally query dependent, so each query needs its own VectorSearcher. */ abstract public class VectorSearcher { private static final Logger logger = Logger.getLogger(VectorSearcher.class.getCanonicalName()); private FlagConfig flagConfig; private VectorStore searchVecStore; private LuceneUtils luceneUtils; /** * Expand search space for dual-predicate searches */ public static VectorStore expandSearchSpace(VectorStore searchVecStore, FlagConfig flagConfig) { VectorStoreRAM nusearchspace = new VectorStoreRAM(flagConfig); Enumeration<ObjectVector> allVectors = searchVecStore.getAllVectors(); ArrayList<ObjectVector> storeVectors = new ArrayList<ObjectVector>(); while (allVectors.hasMoreElements()) { ObjectVector nextObjectVector = allVectors.nextElement(); nusearchspace.putVector(nextObjectVector.getObject(), nextObjectVector.getVector()); storeVectors.add(nextObjectVector); } for (int x=0; x < storeVectors.size()-1; x++) { for (int y=x; y < storeVectors.size(); y++) { Vector vec1 = storeVectors.get(x).getVector().copy(); Vector vec2 = storeVectors.get(y).getVector().copy(); String obj1 = storeVectors.get(x).getObject().toString(); String obj2 = storeVectors.get(y).getObject().toString(); vec1.release(vec2); nusearchspace.putVector(obj2+":"+obj1, vec1); if (flagConfig.vectortype().equals(VectorType.COMPLEX)) { vec2.release(storeVectors.get(x).getVector().copy()); nusearchspace.putVector(obj1+":"+obj2, vec2); } } } System.err.println("Expanding search space from "+storeVectors.size()+" to "+nusearchspace.getNumVectors()); return nusearchspace; } /** * This needs to be filled in for each subclass. It takes an individual * vector and assigns it a relevance score for this VectorSearcher. */ public abstract double getScore(Vector testVector); /** * Performs basic initialization; subclasses should normally call super() to use this. * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) */ public VectorSearcher(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig) { this.flagConfig = flagConfig; this.searchVecStore = searchVecStore; this.luceneUtils = luceneUtils; if (flagConfig.expandsearchspace()) { this.searchVecStore = expandSearchSpace(searchVecStore, flagConfig); } } /** * This nearest neighbor search is implemented in the abstract * VectorSearcher class itself: this enables all subclasses to reuse * the search whatever scoring method they implement. Since query * expressions are built into the VectorSearcher, * getNearestNeighbors no longer takes a query vector as an * argument. * @param numResults the number of results / length of the result list. */ public LinkedList<SearchResult> getNearestNeighbors(int numResults) { final double unsetScore = -Math.PI; final int bufferSize = 1000; final int indexSize = numResults + bufferSize; LinkedList<SearchResult> results = new LinkedList<SearchResult>(); List<SearchResult> tmpResults = new ArrayList<SearchResult>(indexSize); double score = -1; double threshold = flagConfig.searchresultsminscore(); if (flagConfig.stdev()) threshold = 0; //Counters for statistics to calculate standard deviation double sum=0, sumsquared=0; int count=0; int pos = 0; for(int i=0; i < indexSize; i++) { tmpResults.add(new SearchResult(unsetScore, null)); } Enumeration<ObjectVector> vecEnum = searchVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Test this element. ObjectVector testElement = vecEnum.nextElement(); score = getScore(testElement.getVector()); // This is a way of using the Lucene Index to get term and // document frequency information to reweight all results. It // seems to be good at moving excessively common terms further // down the results. Note that using this means that scores // returned are no longer just cosine similarities. if (this.luceneUtils != null && flagConfig.usetermweightsinsearch()) { score = score * luceneUtils.getGlobalTermWeightFromString((String) testElement.getObject()); } if (flagConfig.stdev()) { count++; sum += score; sumsquared += Math.pow(score, 2); } if (score > threshold) { // set existing object in buffer space tmpResults.get(numResults+pos++).set(score, testElement); } if(pos == bufferSize) { pos = 0; Collections.sort(tmpResults); threshold = tmpResults.get(indexSize - 1).getScore(); } } Collections.sort(tmpResults); for(int i = 0; i < numResults; i++) { SearchResult sr = tmpResults.get(i); if(sr.getScore() == unsetScore) { break; } results.add(sr); } if (flagConfig.stdev()) results = transformToStats(results, count, sum, sumsquared); return results; } /** * This search is implemented in the abstract * VectorSearcher class itself: this enables all subclasses to reuse * the search whatever scoring method they implement. Since query * expressions are built into the VectorSearcher, * getAllAboveThreshold does not takes a query vector as an * argument. * * This will retrieve all the results above the threshold score passed * as a parameter. It is more computationally convenient than getNearestNeighbor * when large numbers of results are anticipated * * @param threshold minimum score required to get into results list. */ public LinkedList<SearchResult> getAllAboveThreshold(float threshold) { LinkedList<SearchResult> results = new LinkedList<SearchResult>(); double score; Enumeration<ObjectVector> vecEnum = null; vecEnum = searchVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Test this element. ObjectVector testElement = vecEnum.nextElement(); if (testElement == null) score = Float.MIN_VALUE; else { Vector testVector = testElement.getVector(); score = getScore(testVector); } if (score > threshold || threshold == Float.MIN_VALUE) { results.add(new SearchResult(score, testElement));} } Collections.sort(results); return results; } /** * Class for searching a vector store using cosine similarity. * Takes a sum of positive query terms and optionally negates some terms. */ static public class VectorSearcherCosine extends VectorSearcher { Vector queryVector; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherCosine( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, flagConfig, queryTerms); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryVector Vector representing query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherCosine( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, Vector queryVector) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = queryVector; Vector testVector = searchVecStore.getAllVectors().nextElement().getVector(); IncompatibleVectorsException.checkVectorsCompatible(queryVector, testVector); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } @Override public double getScore(Vector testVector) { return this.queryVector.measureOverlap(testVector); } } /** * Class for searching a vector store using the bound product of a series two vectors. */ static public class VectorSearcherBoundProduct extends VectorSearcher { Vector queryVector; public VectorSearcherBoundProduct(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1, String term2) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, null, flagConfig, term1); queryVector.release(CompoundVectorBuilder.getBoundProductQueryVectorFromString( flagConfig, boundVecStore, term2)); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } public VectorSearcherBoundProduct(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = CompoundVectorBuilder.getBoundProductQueryVectorFromString( flagConfig, queryVecStore, boundVecStore, term1); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } public VectorSearcherBoundProduct(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, ArrayList<Vector> incomingVectors) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); Vector theSuperposition = VectorFactory.createZeroVector( flagConfig.vectortype(), flagConfig.dimension()); for (int q = 0; q < incomingVectors.size(); q++) theSuperposition.superpose(incomingVectors.get(q), 1, null); theSuperposition.normalize(); this.queryVector = theSuperposition; if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryVector Vector representing query * expression. If the string "NOT" appears, terms after this will be negated. */ public VectorSearcherBoundProduct(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, Vector queryVector) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.queryVector = queryVector; Vector testVector = searchVecStore.getAllVectors().nextElement().getVector(); IncompatibleVectorsException.checkVectorsCompatible(queryVector, testVector); if (this.queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } } @Override public double getScore(Vector testVector) { return this.queryVector.measureOverlap(testVector); } } /** * Class for searching a vector store using the bound product of a series two vectors. */ public static class VectorSearcherBoundProductSubSpace extends VectorSearcher { private ArrayList<Vector> disjunctSpace; public VectorSearcherBoundProductSubSpace(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1, String term2) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); disjunctSpace = new ArrayList<Vector>(); Vector queryVector = queryVecStore.getVector(term1).copy(); if (queryVector.isZeroVector()) { throw new ZeroVectorException("Query vector is zero ... no results."); } this.disjunctSpace = CompoundVectorBuilder.getBoundProductQuerySubSpaceFromString( boundVecStore, queryVector, term2); } public VectorSearcherBoundProductSubSpace(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String term1) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); disjunctSpace = new ArrayList<Vector>(); this.disjunctSpace = CompoundVectorBuilder.getBoundProductQuerySubspaceFromString( flagConfig, queryVecStore, boundVecStore, term1); } public VectorSearcherBoundProductSubSpace(VectorStore queryVecStore, VectorStore boundVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, ArrayList<Vector> incomingDisjunctSpace) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctSpace = incomingDisjunctSpace; } @Override public double getScore(Vector testVector) { return VectorUtils.compareWithProjection(testVector, disjunctSpace); } } /** * Class for searching a vector store using quantum disjunction similarity. */ static public class VectorSearcherSubspaceSim extends VectorSearcher { private ArrayList<Vector> disjunctSpace; private VectorType vectorType; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherSubspaceSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctSpace = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { System.out.println("\t" + queryTerms[i]); // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); Vector tmpVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, flagConfig, tmpTerms); if (tmpVector != null) { this.disjunctSpace.add(tmpVector); } } if (this.disjunctSpace.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } if (!vectorType.equals(VectorType.BINARY)) VectorUtils.orthogonalizeVectors(this.disjunctSpace); else BinaryVectorUtils.orthogonalizeVectors(this.disjunctSpace); } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ @Override public double getScore(Vector testVector) { if (!vectorType.equals(VectorType.BINARY)) return VectorUtils.compareWithProjection(testVector, disjunctSpace); else return BinaryVectorUtils.compareWithProjection(testVector, disjunctSpace); } } /** * Class for searching a vector store using minimum distance similarity. */ static public class VectorSearcherMaxSim extends VectorSearcher { private ArrayList<Vector> disjunctVectors; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMaxSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctVectors = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); Vector tmpVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, flagConfig, tmpTerms); if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMaxSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, Vector[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctVectors = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. Vector tmpVector = queryTerms[i]; if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ @Override public double getScore(Vector testVector) { double score = -1; double max_score = -1; for (int i = 0; i < disjunctVectors.size(); ++i) { score = this.disjunctVectors.get(i).measureOverlap(testVector); if (score > max_score) { max_score = score; } } return max_score; } } /** * Class for searching a vector store using minimum distance similarity * (i.e. the minimum across the vector cues, which may * be of use for finding middle terms). */ static public class VectorSearcherMinSim extends VectorSearcher { private ArrayList<Vector> disjunctVectors; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMinSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctVectors = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. String[] tmpTerms = queryTerms[i].split("\\s"); Vector tmpVector = CompoundVectorBuilder.getQueryVector( queryVecStore, luceneUtils, flagConfig, tmpTerms); if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed and used to generate a query subspace. */ public VectorSearcherMinSim(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, Vector[] queryTerms) throws ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); this.disjunctVectors = new ArrayList<Vector>(); for (int i = 0; i < queryTerms.length; ++i) { // There may be compound disjuncts, e.g., "A NOT B" as a single argument. Vector tmpVector = queryTerms[i]; if (tmpVector != null) { this.disjunctVectors.add(tmpVector); } } if (this.disjunctVectors.size() == 0) { throw new ZeroVectorException("No nonzero input vectors ... no results."); } } /** * Scoring works by taking scalar product with disjunctSpace * (which must by now be represented using an orthogonal basis). * @param testVector Vector being tested. */ @Override public double getScore(Vector testVector) { double score = -1; double min_score = Double.MAX_VALUE; for (int i = 0; i < disjunctVectors.size(); ++i) { score = this.disjunctVectors.get(i).measureOverlap(testVector); if (score < min_score) { min_score = score; } } return min_score; } } /** * Class for searching a permuted vector store using cosine similarity. * Uses implementation of rotation for permutation proposed by Sahlgren et al 2008 * Should find the term that appears frequently in the position p relative to the * index term (i.e. sat +1 would find a term occurring frequently immediately after "sat" */ public static class VectorSearcherPerm extends VectorSearcher { Vector theAvg; /** * @param queryVecStore Vector store to use for query generation. * @param searchVecStore The vector store to search. * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "?" appears, terms best fitting into this position will be returned */ public VectorSearcherPerm(VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws IllegalArgumentException, ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); try { theAvg = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(queryVecStore, luceneUtils, flagConfig, queryTerms); } catch (IllegalArgumentException e) { logger.info("Couldn't create permutation VectorSearcher ..."); throw e; } if (theAvg.isZeroVector()) { throw new ZeroVectorException("Permutation query vector is zero ... no results."); } } @Override public double getScore(Vector testVector) { return theAvg.measureOverlap(testVector); } } /** * Test searcher for finding a is to b as c is to ? * * Doesn't do well yet! * * @author dwiddows */ static public class AnalogySearcher extends VectorSearcher { Vector queryVector; public AnalogySearcher( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTriple) { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); Vector term0 = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, luceneUtils, flagConfig, queryTriple[0]); Vector term1 = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, luceneUtils, flagConfig, queryTriple[1]); Vector term2 = CompoundVectorBuilder.getQueryVectorFromString(queryVecStore, luceneUtils, flagConfig, queryTriple[2]); Vector relationVec = term0.copy(); relationVec.bind(term1); this.queryVector = term2.copy(); this.queryVector.release(relationVec); } @Override public double getScore(Vector testVector) { return queryVector.measureOverlap(testVector); } } /** * Class for searching a permuted vector store using cosine similarity. * Uses implementation of rotation for permutation proposed by Sahlgren et al 2008 * Should find the term that appears frequently in the position p relative to the * index term (i.e. sat +1 would find a term occurring frequently immediately after "sat" * This is a variant that takes into account different results obtained when using either * permuted or random index vectors as the cue terms, by taking the mean of the results * obtained with each of these options. */ static public class BalancedVectorSearcherPerm extends VectorSearcher { Vector oneDirection; Vector otherDirection; VectorStore searchVecStore, queryVecStore; // These "special" fields are here to enable non-static construction of these // static inherited classes. It suggests that the inheritance pattern for VectorSearcher // needs to be reconsidered. LuceneUtils specialLuceneUtils; FlagConfig specialFlagConfig; String[] queryTerms; /** * @param queryVecStore Vector store to use for query generation (this is also reversed). * @param searchVecStore The vector store to search (this is also reversed). * @param luceneUtils LuceneUtils object to use for query weighting. (May be null.) * @param queryTerms Terms that will be parsed into a query * expression. If the string "?" appears, terms best fitting into this position will be returned */ public BalancedVectorSearcherPerm( VectorStore queryVecStore, VectorStore searchVecStore, LuceneUtils luceneUtils, FlagConfig flagConfig, String[] queryTerms) throws IllegalArgumentException, ZeroVectorException { super(queryVecStore, searchVecStore, luceneUtils, flagConfig); specialFlagConfig = flagConfig; specialLuceneUtils = luceneUtils; try { oneDirection = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(queryVecStore, luceneUtils, flagConfig, queryTerms); otherDirection = pitt.search.semanticvectors.CompoundVectorBuilder. getPermutedQueryVector(searchVecStore, luceneUtils, flagConfig, queryTerms); } catch (IllegalArgumentException e) { logger.info("Couldn't create balanced permutation VectorSearcher ..."); throw e; } if (oneDirection.isZeroVector()) { throw new ZeroVectorException("Permutation query vector is zero ... no results."); } } /** * This overrides the nearest neighbor class implemented in the abstract * {@code VectorSearcher} class. * * WARNING: This implementation fails to respect flags used by the * {@code VectorSearcher.getNearestNeighbors} method. * * @param numResults the number of results / length of the result list. */ @Override public LinkedList<SearchResult> getNearestNeighbors(int numResults) { LinkedList<SearchResult> results = new LinkedList<SearchResult>(); double score, score1, score2 = -1; double threshold = specialFlagConfig.searchresultsminscore(); if (specialFlagConfig.stdev()) threshold = 0; // Counters for statistics to calculate standard deviation double sum=0, sumsquared=0; int count=0; Enumeration<ObjectVector> vecEnum = searchVecStore.getAllVectors(); Enumeration<ObjectVector> vecEnum2 = queryVecStore.getAllVectors(); while (vecEnum.hasMoreElements()) { // Test this element. ObjectVector testElement = vecEnum.nextElement(); ObjectVector testElement2 = vecEnum2.nextElement(); score1 = getScore(testElement.getVector()); score2 = getScore2(testElement2.getVector()); score = Math.max(score1,score2); // This is a way of using the Lucene Index to get term and // document frequency information to reweight all results. It // seems to be good at moving excessively common terms further // down the results. Note that using this means that scores // returned are no longer just cosine similarities. if ((specialLuceneUtils != null) && specialFlagConfig.usetermweightsinsearch()) { score = score * specialLuceneUtils.getGlobalTermWeightFromString((String) testElement.getObject()); } if (specialFlagConfig.stdev()) { System.out.println("STDEV"); count++; sum += score; sumsquared += Math.pow(score, 2); } if (score > threshold) { boolean added = false; for (int i = 0; i < results.size(); ++i) { // Add to list if this is right place. if (score > results.get(i).getScore() && added == false) { results.add(i, new SearchResult(score, testElement)); added = true; } } // Prune list if there are already numResults. if (results.size() > numResults) { results.removeLast(); threshold = results.getLast().getScore(); } else { if (added == false) { results.add(new SearchResult(score, testElement)); } } } } if (specialFlagConfig.stdev()) results = transformToStats(results, count, sum, sumsquared); return results; } @Override public double getScore(Vector testVector) { testVector.normalize(); return oneDirection.measureOverlap(testVector); } public double getScore2(Vector testVector) { testVector.normalize(); return (otherDirection.measureOverlap(testVector)); } } /** * calculates approximation of standard deviation (using a somewhat imprecise single-pass algorithm) * and recasts top scores as number of standard deviations from the mean (for a single search) * * @return list of results with scores as number of standard deviations from mean */ public LinkedList<SearchResult> transformToStats( LinkedList<SearchResult> rawResults,int count, double sum, double sumsq) { LinkedList<SearchResult> transformedResults = new LinkedList<SearchResult>(); double variancesquared = sumsq - (Math.pow(sum,2)/count); double stdev = Math.sqrt(variancesquared/(count)); double mean = sum/count; Iterator<SearchResult> iterator = rawResults.iterator(); while (iterator.hasNext()) { SearchResult temp = iterator.next(); double score = temp.getScore(); score = new Double((score-mean)/stdev).floatValue(); if (score > flagConfig.searchresultsminscore()) transformedResults.add(new SearchResult(score, temp.getObjectVector())); } return transformedResults; } }
package scrum.client.project; import scrum.client.admin.User; import scrum.client.common.GroupWidget; import scrum.client.common.ItemFieldsWidget; import scrum.client.common.ScrumUtil; import scrum.client.common.editable.AEditableTextWidget; import scrum.client.common.editable.AEditableTextareaWidget; import scrum.client.sprint.Sprint; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; public class ProjectOverviewWidget extends Composite { public ProjectOverviewWidget(final Project project) { ItemFieldsWidget fields = new ItemFieldsWidget(); fields.addField("Label", new AEditableTextWidget() { @Override protected void setText(String text) { project.setLabel(text); } @Override protected String getText() { return project.getLabel(); } }); fields.addField("Description", new AEditableTextareaWidget(true) { @Override protected void setText(String text) { project.setDescription(text); } @Override protected String getText() { return project.getDescription(); } }); User productOwner = project.getProductOwner(); if (productOwner != null) { fields.addField("Product Owner", new Label(productOwner.getName())); } User scrumMaster = project.getScrumMaster(); if (scrumMaster != null) { fields.addField("Scrum Master", new Label(scrumMaster.getName())); } String team = ScrumUtil.toCommataSeperatedString(project.getTeamMembers()); if (team.length() > 0) { fields.addField("Team", new Label(team)); } String admins = ScrumUtil.toCommataSeperatedString(project.getAdmins()); if (admins.length() > 0) { fields.addField("Project Admins", new Label(admins)); } FlowPanel panel = new FlowPanel(); panel.add(new GroupWidget("Project Properties", fields)); Sprint sprint = project.getCurrentSprint(); if (sprint != null) { panel.add(createCurrentSprintOverview(sprint)); } initWidget(panel); } private Widget createCurrentSprintOverview(Sprint sprint) { int width = 500; int height = 300; String url = "../sprintBurndownChart.png?sprintId=" + sprint.getId() + "&width=" + width + "&height=" + height; return new GroupWidget("Current Sprint", new Image(url, 0, 0, width, height)); } }
package server.controller; import java.io.File; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.JSONException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.RequestMapping; import server.compiler.java.JavaCompiler; import server.generator.Generator; import server.generator.java.JavaGenerator; import server.parser.Parser; import server.project.ParsedProgram; import server.utility.Compressor; public class RequestHandlerController { String json; /*@Autowired @Qualifier("javagenerator")*/ Generator generator = new JavaGenerator(); public RequestHandlerController(String json){ this.json = json; } @RequestMapping("/generate") public String HandleGeneratorRequest(/*@RequestParam(value="json") String json*/){ List<String> errors = new ArrayList<String>(); Parser parser = new Parser(); ParsedProgram program = null; try{program = parser.createParsedProgram(json);} catch(JSONException e){ errors.add("Impossible to parse JSONFile"); } List<String> parserErrors = parser.getErrors(); /*if(!parserErrors.isEmpty()){ errors.addAll(parserErrors); } else{*/ generator.generate("1234", program); /*server.compiler.Compiler compiler = new JavaCompiler(); String path = "src/main/resources/ContentFile"; File folder = new File(path); File[] files = folder.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".java"); } }); for(File file : files){ if(file.isFile()){ try{errors.addAll(compiler.compile(file.getAbsolutePath()));} catch(IOException e){errors.add("Error when compiling file "+file.getName());} } } System.out.println(errors); Compressor c = new Compressor(); c.zip();*/ return "ciao"; } public void HandleStereotypesRequest(){}; }
package space.npstr.wolfia.listings; import javax.annotation.Nonnull; import net.dv8tion.jda.api.JDA; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import org.json.JSONObject; import space.npstr.wolfia.App; import space.npstr.wolfia.Launcher; public class DiscordBotsOrg extends Listing { public DiscordBotsOrg(@Nonnull final OkHttpClient httpClient) { super("top.gg", httpClient); } @Nonnull @Override protected String createPayload(@Nonnull final JDA jda) { return new JSONObject() .put("server_count", jda.getGuildCache().size()) .put("shard_id", jda.getShardInfo().getShardId()) .put("shard_count", jda.getShardInfo().getShardTotal()) .toString(); } @Nonnull @Override protected Request.Builder createRequest(final long botId, @Nonnull final String payload) { final RequestBody body = RequestBody.create(JSON, payload); return new Request.Builder() .addHeader("user-agent", "Wolfia DiscordBot (" + App.GITHUB_LINK + ", " + App.VERSION + ")") .url(String.format("https://top.gg/api/bots/%s/stats", botId)) .addHeader("Authorization", Launcher.getBotContext().getListingsConfig().getDblToken()) .post(body); } @Override protected boolean isConfigured() { final String dblToken = Launcher.getBotContext().getListingsConfig().getDblToken(); return dblToken != null && !dblToken.isEmpty(); } }
package stexfires.io.properties; import stexfires.core.consumer.ConsumerException; import stexfires.core.record.KeyValueRecord; import stexfires.io.internal.AbstractWritableConsumer; import java.io.BufferedWriter; import java.io.IOException; import java.util.Date; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.IntStream; import static stexfires.io.properties.PropertiesFileSpec.*; /** * @author Mathias Kalb * @since 0.1 */ public class PropertiesConsumer extends AbstractWritableConsumer<KeyValueRecord> { protected final PropertiesFileSpec fileSpec; public PropertiesConsumer(BufferedWriter writer, PropertiesFileSpec fileSpec) { super(writer); Objects.requireNonNull(fileSpec); this.fileSpec = fileSpec; } protected static String mapCharacter(char character, boolean escapeSpace, boolean escapeUnicode) { switch (character) { case ' ': return escapeSpace ? "\\ " : " "; case '\t': return "\\t"; case '\n': return "\\n"; case '\r': return "\\r"; case '\f': return "\\f"; case '\\': return "\\\\"; case '=': return "\\="; case ':': return "\\:"; case ' return "\\ case '!': return "\\!"; default: if (((character < 0x0020) || (character > 0x007e)) & escapeUnicode) { return "\\u" + String.format("%04X", (int) character); } return Character.toString(character); } } protected static String convertKey(String key, boolean escapeUnicode) { return IntStream.range(0, key.length()) .mapToObj(i -> mapCharacter(key.charAt(i), true, escapeUnicode)) .collect(Collectors.joining()); } protected static String convertValue(String value, boolean escapeUnicode) { return IntStream.range(0, value.length()) .mapToObj(i -> mapCharacter(value.charAt(i), i == 0, escapeUnicode)) .collect(Collectors.joining()); } @Override public void writeBefore() throws IOException { super.writeBefore(); if (fileSpec.isDateComment()) { write(COMMENT_PREFIX); write(new Date().toString()); write(fileSpec.getLineSeparator().getSeparator()); } } @Override public void writeRecord(KeyValueRecord record) throws IOException, ConsumerException { super.writeRecord(record); write(convertKey(record.getValueOfKeyField(), fileSpec.isEscapeUnicode())); write(DELIMITER); write(convertValue(record.getValueField().getValueOrElse(NULL_VALUE), fileSpec.isEscapeUnicode())); write(fileSpec.getLineSeparator().getSeparator()); } }
package tamaized.aov.common.core.abilities; import io.netty.buffer.ByteBuf; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.RayTraceResult; import tamaized.aov.common.capabilities.CapabilityList; import tamaized.aov.common.capabilities.aov.IAoVCapability; import tamaized.aov.common.capabilities.astro.IAstroCapability; import tamaized.aov.common.config.ConfigHandler; import tamaized.tammodized.common.helper.CapabilityHelper; import tamaized.tammodized.common.helper.RayTraceHelper; import javax.annotation.Nullable; import java.util.HashSet; public final class Ability { private AbilityBase ability; private int nextCooldown = -1; private int cooldown; private int charges; private int decay; private int timer = -1; private boolean disabled = false; private int tick = 0; public Ability(AbilityBase ability) { this.ability = ability; } public Ability(AbilityBase ability, IAoVCapability cap, @Nullable IAstroCapability astro) { this.ability = ability; reset(null, cap); } public static Ability construct(ByteBuf stream) { int id = stream.readInt(); if (id < 0) return null; Ability ability = new Ability(AbilityBase.getAbilityFromID(id)); ability.decode(stream); return ability; } public static Ability construct(IAoVCapability cap, @Nullable IAstroCapability astro, NBTTagCompound nbt) { int id = nbt.getInteger("id"); if (id < 0) return null; Ability ability = new Ability(AbilityBase.getAbilityFromID(id), cap, astro); ability.decode(nbt, cap); return ability; } public void encode(ByteBuf stream) { stream.writeInt(ability.getID()); stream.writeInt(cooldown); stream.writeInt(charges); stream.writeInt(decay); stream.writeInt(timer); stream.writeBoolean(disabled); } public void decode(ByteBuf stream) { cooldown = stream.readInt(); charges = stream.readInt(); decay = stream.readInt(); timer = stream.readInt(); disabled = stream.readBoolean(); } @SuppressWarnings("UnusedReturnValue") public NBTTagCompound encode(NBTTagCompound nbt, IAoVCapability cap) { nbt.setInteger("id", ability.getID()); nbt.setInteger("cooldown", cooldown); nbt.setInteger("cooldownfailsafe", cap.getCooldown(ability)); nbt.setInteger("charges", charges); nbt.setInteger("decay", decay); nbt.setInteger("timer", timer); nbt.setBoolean("disabled", disabled); return nbt; } public void decode(NBTTagCompound nbt, IAoVCapability cap) { cooldown = nbt.getInteger("cooldown"); int cooldownfailsafe = nbt.getInteger("cooldownfailsafe"); if (cooldownfailsafe > 0) cap.setCooldown(ability, cooldownfailsafe); charges = nbt.getInteger("charges"); decay = nbt.getInteger("decay"); timer = nbt.getInteger("timer"); disabled = nbt.getBoolean("disabled"); } public void reset(EntityPlayer caster, IAoVCapability cap) { cooldown = cap.getCooldown(ability); nextCooldown = -1; charges = ability.getMaxCharges() < 0 ? -1 : ability.getMaxCharges() + cap.getExtraCharges(); decay = 0; timer = -1; disabled = getAbility().shouldDisable(caster, cap); } public void restoreCharge(IAoVCapability cap, int amount) { charges += (ability.getMaxCharges() > -1 && charges < (ability.getMaxCharges() + cap.getExtraCharges())) ? amount : 0; } public void setNextCooldown(int cd) { nextCooldown = cd; } public void setTimer(int t) { timer = t; } public final void cast(EntityPlayer caster) { if (disabled) return; HashSet<Entity> set = new HashSet<>(); set.add(caster); RayTraceResult ray = RayTraceHelper.tracePath(caster.world, caster, (int) getAbility().getMaxDistance(), 1, set); cast(caster, (ray == null || !(ray.entityHit instanceof EntityLivingBase)) ? null : (EntityLivingBase) ray.entityHit); } public void cast(EntityPlayer caster, EntityLivingBase target) { if (disabled) return; IAoVCapability cap = CapabilityHelper.getCap(caster, CapabilityList.AOV, null); if (cap != null) { if (target != null && !ability.isCastOnTarget(caster, cap, target)) target = null; if (cap.canUseAbility(this) && ((ability.usesInvoke() && cap.getInvokeMass()) || target == null || ability.getMaxDistance() >= caster.getDistance(target))) { if (ability.cast(this, caster, target)) { charges -= ability.getCost(cap); cooldown = (nextCooldown < 0 ? ability.getCoolDown() : nextCooldown) * ((ability.usesInvoke() && cap.getInvokeMass()) ? 2 : 1); } else cooldown = 1; cap.setCooldown(ability, cooldown); nextCooldown = -1; } } } public void castAsAura(EntityPlayer caster, IAoVCapability cap, int life) { if (!disabled && ability instanceof IAura) ((IAura) ability).castAsAura(caster, cap, life); } public boolean canUse(IAoVCapability cap) { return !disabled && cooldown <= 0 && cap.getCooldown(ability) <= 0 && (charges == -1 || charges >= ability.getCost(cap)) && cap.slotsContain(getAbility()); } public AbilityBase getAbility() { return ability; } public int getCooldown() { return cooldown; } public float getCooldownPerc() { return (float) cooldown / (float) ability.getCoolDown(); } public int getCharges() { return charges; } public int getDecay() { return decay; } public void update(EntityPlayer caster, IAoVCapability cap) { tick++; disabled = ability.shouldDisable(caster, cap); if (tick % 20 == 0 && cooldown > 0) cooldown if (decay > 0 && tick % (20 * 20) == 0) decay if (ability.getMaxCharges() >= 0 && ConfigHandler.recharge >= 0 && charges < (ability.getMaxCharges() + cap.getExtraCharges()) && tick % ConfigHandler.recharge == 0) charges++; if (tick % 20 == 0 && timer > 0) timer else if (timer == 0) { timer cooldown = (nextCooldown < 0 ? ability.getCoolDown() : nextCooldown) * ((ability.usesInvoke() && cap.getInvokeMass()) ? 2 : 1); nextCooldown = -1; cap.markDirty(); } } public boolean compare(Ability check) { return check != null && ability == check.ability; } }
package top.quantic.sentry.event; import de.androidpit.colorthief.ColorThief; import de.androidpit.colorthief.MMCQ; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sx.blah.discord.api.internal.json.objects.EmbedObject; import sx.blah.discord.util.EmbedBuilder; import top.quantic.sentry.domain.Streamer; import top.quantic.sentry.web.rest.vm.TwitchStream; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.net.URL; import java.util.LinkedHashMap; import java.util.Map; public class TwitchStreamEvent extends SentryEvent { private static final Logger log = LoggerFactory.getLogger(TwitchStreamEvent.class); private final Streamer streamer; private String announcement; private Map<String, String> resolvedFields; public TwitchStreamEvent(TwitchStream source, Streamer streamer) { super(source); this.streamer = streamer; } @Override public TwitchStream getSource() { return (TwitchStream) super.getSource(); } public Streamer getStreamer() { return streamer; } public String getAnnouncement() { return announcement; } public void setAnnouncement(String announcement) { this.announcement = announcement; } public Map<String, String> getResolvedFields() { return resolvedFields; } public void setResolvedFields(Map<String, String> resolvedFields) { this.resolvedFields = resolvedFields; } @Override public String getContentId() { return "@" + System.currentTimeMillis(); // de-dupe is handled elsewhere } @Override public String asContent(Map<String, Object> dataMap) { TwitchStream stream = getSource(); if (announcement != null && (announcement.contains("{{") || announcement.contains("}}"))) { log.warn("Announcement appears to be badly formatted: {}", announcement); announcement = null; } if (announcement == null) { return "@here " + stream.getChannel().getDisplayName() + getDivisionContent(dataMap) + " is now live on <" + stream.getChannel().getUrl() + "> !"; } else { return announcement; } } private String getDivisionContent(Map<String, Object> dataMap) { String league = streamer.getLeague(); String division = streamer.getDivision(); String hideDivisionRegex = null; if (dataMap != null) { hideDivisionRegex = (String) dataMap.get("hideDivisionRegex"); } if (division != null) { if (hideDivisionRegex != null && division.matches(hideDivisionRegex)) { division = null; } } if (league != null) { return " (" + league + (division != null ? " " + division : "") + ")"; } return ""; } @Override public EmbedObject asEmbed(Map<String, Object> dataMap) { String league = streamer.getLeague(); String division = streamer.getDivision(); String hideDivisionRegex = null; if (league != null && (league.equalsIgnoreCase("all") || league.equalsIgnoreCase("any") || league.equalsIgnoreCase("none") || league.equalsIgnoreCase("*"))) { league = null; division = null; } else { if (dataMap != null) { hideDivisionRegex = (String) dataMap.get("hideDivisionRegex"); } if (division != null) { if (hideDivisionRegex != null && division.matches(hideDivisionRegex)) { division = null; } if (league == null) { division = null; } } } TwitchStream stream = getSource(); EmbedBuilder builder = new EmbedBuilder() .withAuthorIcon(stream.getChannel().getLogo()) .withAuthorName(stream.getChannel().getDisplayName()) .withTitle(stream.getChannel().getStatus()) .withColor(getDominantColor(stream.getChannel().getLogo())) .withThumbnail(stream.getChannel().getLogo()) .withUrl(stream.getChannel().getUrl()) .withImage(stream.getPreview().get("medium")) .withFooterIcon("https: .withFooterText("twitch.tv") .appendField("Playing", stream.getGame(), true) .appendField("Viewers", stream.getViewers() + "", true) .ignoreNullEmptyFields() .appendField("League", league, true) .appendField("Division", division, true); if (resolvedFields != null) { resolvedFields.forEach((title, content) -> { if (content.contains("{{") || content.contains("}}")) { log.warn("Field with key {} was incorrectly resolved: {}", title, content); } else { builder.appendField(title, content, true); } }); } return builder.build(); } @Override public Map<String, Object> asMap(Map<String, Object> dataMap) { TwitchStream stream = getSource(); Map<String, Object> map = new LinkedHashMap<>(); map.put("avatar", stream.getChannel().getLogo()); map.put("name", stream.getChannel().getDisplayName()); map.put("title", stream.getChannel().getStatus()); map.put("game", stream.getGame()); map.put("viewers", stream.getViewers()); map.put("preview", stream.getPreview().get("medium")); map.put("url", stream.getChannel().getUrl()); map.put("createdAt", stream.getCreatedAt()); map.put("league", streamer.getLeague()); map.put("division", streamer.getDivision()); return map; } private Color getDominantColor(String urlStr) { try { URL url = new URL(urlStr); BufferedImage image = ImageIO.read(url); MMCQ.CMap result = ColorThief.getColorMap(image, 5); MMCQ.VBox vBox = result.vboxes.get(0); int[] rgb = vBox.avg(false); return new Color(rgb[0], rgb[1], rgb[2]); } catch (Exception e) { log.warn("Could not analyze image", e); } return new Color(0x6441A4); } }
package tv.mapper.roadstuff.block; import javax.annotation.Nullable; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.HorizontalBlock; import net.minecraft.block.IBucketPickupHandler; import net.minecraft.block.ILiquidContainer; import net.minecraft.entity.item.ItemEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.fluid.Fluid; import net.minecraft.fluid.Fluids; import net.minecraft.fluid.IFluidState; import net.minecraft.item.BlockItemUseContext; import net.minecraft.item.DyeColor; import net.minecraft.item.DyeItem; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.state.BooleanProperty; import net.minecraft.state.DirectionProperty; import net.minecraft.state.EnumProperty; import net.minecraft.state.IntegerProperty; import net.minecraft.state.StateContainer; import net.minecraft.state.properties.BlockStateProperties; import net.minecraft.util.BlockRenderLayer; import net.minecraft.util.Direction; import net.minecraft.util.Hand; import net.minecraft.util.SoundCategory; import net.minecraft.util.SoundEvents; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.util.math.shapes.ISelectionContext; import net.minecraft.util.math.shapes.VoxelShape; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.IBlockReader; import net.minecraft.world.IWorld; import net.minecraft.world.IWorldReader; import net.minecraft.world.World; import tv.mapper.roadstuff.item.BrushItem; import tv.mapper.roadstuff.state.properties.EnumPaintColor; import tv.mapper.roadstuff.util.ModConstants; public class PaintBucketBlock extends Block implements IBucketPickupHandler, ILiquidContainer { private static final int MAX_PAINT = 8; public static final IntegerProperty PAINT = IntegerProperty.create("paint", 0, MAX_PAINT); public static final EnumProperty<EnumPaintColor> COLOR = EnumProperty.create("color", EnumPaintColor.class); public static final DirectionProperty DIRECTION = HorizontalBlock.HORIZONTAL_FACING; public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; private static final VoxelShape PAINT_BUCKET = Block.makeCuboidShape(4.0D, 0.0D, 4.0D, 12.0D, 10.0D, 12.0D); public PaintBucketBlock(Properties properties) { super(properties); this.setDefaultState(this.getDefaultState().with(PAINT, 0).with(COLOR, EnumPaintColor.WHITE).with(DIRECTION, Direction.NORTH).with(WATERLOGGED, Boolean.valueOf(false))); } @Override public boolean isSolid(BlockState state) { return false; } public BlockRenderLayer getRenderLayer() { return BlockRenderLayer.CUTOUT; } public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) { return PAINT_BUCKET; } public VoxelShape getCollisionShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) { return PAINT_BUCKET; } protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) { builder.add(PAINT, COLOR, DIRECTION, WATERLOGGED); } @Nullable public BlockState getStateForPlacement(BlockItemUseContext context) { ItemStack stack = context.getItem(); BlockPos blockpos = context.getPos(); IFluidState ifluidstate = context.getWorld().getFluidState(blockpos); CompoundNBT tagCompound = stack.getTag(); if(tagCompound != null) { return this.getDefaultState().with(PAINT, stack.getTag().getInt("paint")).with(COLOR, EnumPaintColor.values()[stack.getTag().getInt("color")]).with(DIRECTION, context.getPlacementHorizontalFacing()).with(WATERLOGGED, Boolean.valueOf(Boolean.valueOf(ifluidstate.getFluid() == Fluids.WATER))); } return this.getDefaultState().with(PAINT, 0).with(COLOR, EnumPaintColor.WHITE).with(DIRECTION, context.getPlacementHorizontalFacing()).with(WATERLOGGED, Boolean.valueOf(Boolean.valueOf(ifluidstate.getFluid() == Fluids.WATER))); } @Override public boolean onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult result) { if(state.get(WATERLOGGED)) { player.sendStatusMessage(new TranslationTextComponent("roadstuff.message.bucket.underwater"), true); return false; } ItemStack item = player.getHeldItem(hand); if(item.getItem() instanceof BrushItem) { int paint = state.get(PAINT); if(paint <= 0) { if(!world.isRemote) player.sendStatusMessage(new TranslationTextComponent("roadstuff.message.bucket.empty"), true); return false; } if(!item.hasTag()) item.setTag(BrushItem.checkNBT(item)); if((item.getTag().getInt("paint") < ModConstants.BRUSH_MAX_PAINT && paint > 0) || (item.getTag().getInt("paint") == ModConstants.BRUSH_MAX_PAINT && item.getTag().getInt( "color") != state.get(COLOR).getId())) { if(!world.isRemote) { world.setBlockState(pos, state.with(PAINT, state.get(PAINT) - 1)); item.getTag().putInt("paint", ModConstants.BRUSH_MAX_PAINT); item.getTag().putInt("color", state.get(COLOR).getId()); world.playSound(null, pos, SoundEvents.ITEM_BUCKET_EMPTY_LAVA, SoundCategory.BLOCKS, .8F, 1.0F); } return true; } } if(item.getItem() instanceof DyeItem && !world.isRemote) { DyeItem dye = (DyeItem)item.getItem(); if(state.get(PAINT) != 0) { if(dye.getDyeColor() == DyeColor.WHITE && state.get(COLOR) == EnumPaintColor.YELLOW) { player.sendStatusMessage(new TranslationTextComponent("roadstuff.message.bucket.yellow"), true); return false; } else if(dye.getDyeColor() == DyeColor.YELLOW && state.get(COLOR) == EnumPaintColor.WHITE) { player.sendStatusMessage(new TranslationTextComponent("roadstuff.message.bucket.white"), true); return false; } } if(state.get(PAINT) >= MAX_PAINT) { player.sendStatusMessage(new TranslationTextComponent("roadstuff.message.bucket.full"), true); return false; } if(state.get(PAINT) < MAX_PAINT) { if(dye.getDyeColor() == DyeColor.WHITE) world.setBlockState(pos, state.with(PAINT, state.get(PAINT) + 1).with(COLOR, EnumPaintColor.WHITE)); else if(dye.getDyeColor() == DyeColor.YELLOW) world.setBlockState(pos, state.with(PAINT, state.get(PAINT) + 1).with(COLOR, EnumPaintColor.YELLOW)); if(dye.getDyeColor() == DyeColor.WHITE || dye.getDyeColor() == DyeColor.YELLOW) { if(!player.isCreative()) player.getHeldItem(hand).shrink(1); world.playSound(null, pos, SoundEvents.ITEM_BUCKET_FILL_LAVA, SoundCategory.BLOCKS, .8F, 0.9F); } return true; } } return false; } @Override public void onBlockHarvested(World world, BlockPos pos, BlockState state, PlayerEntity player) { if(!world.isRemote && !player.isCreative()) { @SuppressWarnings("deprecation") ItemStack stack = new ItemStack(Item.getItemFromBlock(this)); CompoundNBT nbt = new CompoundNBT(); nbt.putInt("paint", state.getBlockState().get(PAINT)); nbt.putInt("color", state.getBlockState().get(COLOR).ordinal()); stack.setTag(nbt); ItemEntity itementity = new ItemEntity(world, (double)pos.getX() + 0.5, (double)pos.getY() + 0.5, (double)pos.getZ() + 0.5, stack); itementity.setDefaultPickupDelay(); world.addEntity(itementity); } super.onBlockHarvested(world, pos, state, player); } public boolean isValidPosition(BlockState state, IWorldReader worldIn, BlockPos pos) { BlockPos blockpos = pos.down(); BlockState blockstate = worldIn.getBlockState(blockpos); if(blockstate.getBlock() instanceof PaintBucketBlock || !blockstate.isSolid()) return false; return true; } @SuppressWarnings("deprecation") public BlockState updatePostPlacement(BlockState stateIn, Direction facing, BlockState facingState, IWorld worldIn, BlockPos currentPos, BlockPos facingPos) { if(stateIn.get(WATERLOGGED)) { worldIn.getPendingFluidTicks().scheduleTick(currentPos, Fluids.WATER, Fluids.WATER.getTickRate(worldIn)); } return super.updatePostPlacement(stateIn, facing, facingState, worldIn, currentPos, facingPos); } public Fluid pickupFluid(IWorld worldIn, BlockPos pos, BlockState state) { if(state.get(WATERLOGGED)) { worldIn.setBlockState(pos, state.with(WATERLOGGED, Boolean.valueOf(false)), 3); return Fluids.WATER; } else { return Fluids.EMPTY; } } @SuppressWarnings("deprecation") public IFluidState getFluidState(BlockState state) { return state.get(WATERLOGGED) ? Fluids.WATER.getStillFluidState(false) : super.getFluidState(state); } public boolean canContainFluid(IBlockReader worldIn, BlockPos pos, BlockState state, Fluid fluidIn) { return !state.get(WATERLOGGED) && fluidIn == Fluids.WATER; } public boolean receiveFluid(IWorld worldIn, BlockPos pos, BlockState state, IFluidState fluidStateIn) { if(!state.get(WATERLOGGED) && fluidStateIn.getFluid() == Fluids.WATER) { if(!worldIn.isRemote()) { worldIn.setBlockState(pos, state.with(WATERLOGGED, Boolean.valueOf(true)), 3); worldIn.getPendingFluidTicks().scheduleTick(pos, fluidStateIn.getFluid(), fluidStateIn.getFluid().getTickRate(worldIn)); } return true; } else { return false; } } }
package org.smoothbuild.lang.type; import static com.google.common.collect.Multimaps.newSetMultimap; import static org.smoothbuild.util.collect.Lists.list; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.params.provider.Arguments; import org.smoothbuild.lang.type.api.Type; import org.smoothbuild.testing.type.TestingT; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; public record TestingTypeGraph<T extends Type>(ImmutableMultimap<T, T> edges) { public TestingTypeGraph(Multimap<T, T> edges) { this(ImmutableMultimap.copyOf(edges)); } // building graph edges public static <T extends Type> TestingTypeGraph<T> buildGraph( ImmutableList<T> types, int levelCount, TestingT<T> testingT) { TestingTypeGraph<T> graph = baseGraph(types, testingT); for (int i = 0; i < levelCount; i++) { graph = levelUp(graph, testingT); } return graph; } private static <T extends Type> TestingTypeGraph<T> baseGraph( ImmutableList<T> types, TestingT<T> testingT) { Multimap<T, T> graph = newMultimap(); types.forEach(t -> graph.put(testingT.nothing(), t)); types.forEach(t -> graph.put(t, testingT.any())); return new TestingTypeGraph<>(graph); } private static <T extends Type> TestingTypeGraph<T> levelUp(TestingTypeGraph<T> graph, TestingT<T> testingT) { Multimap<T, T> newDimension = newMultimap(); // arrays for (Entry<T, T> entry : graph.edges().entries()) { var lower = entry.getKey(); var upper = entry.getValue(); newDimension.put(testingT.array(lower), testingT.array(upper)); } newDimension.put(testingT.nothing(), testingT.array(testingT.nothing())); newDimension.put(testingT.array(testingT.any()), testingT.any()); // tuples if (testingT.isTupleSupported()) { for (Entry<T, T> entry : graph.edges().entries()) { var lower = entry.getKey(); var upper = entry.getValue(); newDimension.put(testingT.tuple(list(lower)), testingT.tuple(list(upper))); } newDimension.put(testingT.nothing(), testingT.tuple(list(testingT.nothing()))); newDimension.put(testingT.tuple(list(testingT.any())), testingT.any()); } // one param funcs Set<T> allTypes = graph.allTypes(); for (T type : allTypes) { for (Entry<T, T> entry : graph.edges().entries()) { var lower = entry.getKey(); var upper = entry.getValue(); newDimension.put(testingT.func(lower, list(type)), testingT.func(upper, list(type))); newDimension.put(testingT.func(type, list(upper)), testingT.func(type, list(lower))); } } newDimension.put(testingT.nothing(), testingT.func(testingT.nothing(), list(testingT.any()))); newDimension.put(testingT.func(testingT.any(), list(testingT.nothing())), testingT.any()); newDimension.putAll(graph.edges()); return new TestingTypeGraph<>(newDimension); } private Set<T> allTypes() { HashSet<T> types = new HashSet<>(); for (Entry<T, T> entry : edges.entries()) { types.add(entry.getKey()); types.add(entry.getValue()); } return types; } // building test cases public Collection<Arguments> buildTestCases(T rootNode) { ArrayList<T> sorted = typesSortedTopologically(rootNode); int typesCount = sorted.size(); int[][]intEdges = buildIntEdges(sorted); List<Arguments> result = new ArrayList<>(typesCount * typesCount); for (int i = 0; i < typesCount; i++) { for (int j = i; j < typesCount; j++) { result.add(buildTestCase(i, j, intEdges, sorted)); } } return result; } private ArrayList<T> typesSortedTopologically(T rootNode) { var incomingEdgesCount = new HashMap<T, AtomicInteger>(); for (Entry<T, T> entry : edges.entries()) { incomingEdgesCount.computeIfAbsent(entry.getValue(), e -> new AtomicInteger()). incrementAndGet(); } var queue = new LinkedList<T>(); var sorted = new ArrayList<T>(incomingEdgesCount.size() + 1); queue.addLast(rootNode); while (!queue.isEmpty()) { T current = queue.removeFirst(); sorted.add(current); for (T edgeEnd : edges.get(current)) { AtomicInteger count = incomingEdgesCount.get(edgeEnd); if (count.decrementAndGet() == 0) { queue.addLast(edgeEnd); } } } return sorted; } private Arguments buildTestCase(int i, int j, int[][] intEdges, ArrayList<T> indexToType) { if (i == j) { Type type = indexToType.get(i); return Arguments.of(type, type, type); } // This method could be made faster by keeping separate `colors` array for `i` and `j` types. // `colors` array for `i` could be calculated once for the whole graph in outer for loop // in method that call this method. // For now time spent on graph building in negligible compared to time spent in test execution. int[] colors = new int[intEdges.length]; colors[i] = 1; colors[j] = 2; int current = i; while (true) { int currentColor = colors[current]; if (currentColor == 3) { return Arguments.of(indexToType.get(i), indexToType.get(j), indexToType.get(current)); } else { for (int edgeEnd : intEdges[current]) { int endColor = colors[edgeEnd]; if (endColor != 3 && endColor != currentColor) { colors[edgeEnd] = currentColor + endColor; } } } current++; } } private int[][] buildIntEdges(ArrayList<T> sortedTs) { var typeToIndex = typeToIndex(sortedTs); int[][] intEdges = new int[sortedTs.size()][]; for (int i = 0; i < sortedTs.size(); i++) { var type = sortedTs.get(i); intEdges[i] = edges.get(type).stream().mapToInt(typeToIndex::get).toArray(); } return intEdges; } private static <T extends Type> HashMap<T, Integer> typeToIndex(ArrayList<T> sortedTs) { HashMap<T, Integer> typeToInteger = new HashMap<>(); for (int i = 0; i < sortedTs.size(); i++) { typeToInteger.put(sortedTs.get(i), i); } return typeToInteger; } private static <T extends Type> Multimap<T, T> newMultimap() { return newSetMultimap(new HashMap<>(), HashSet::new); } public TestingTypeGraph<T> inverse() { return new TestingTypeGraph<>(edges.inverse()); } }
package gui; import com.badlogic.gdx.*; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.viewport.ScreenViewport; import input.InputHandler; import model.Ant; import model.Universe; import java.awt.Point; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; public class GraphicalFrontend implements ApplicationListener { private static final float ZOOM_PER_SEC = 0.75f; private static final float TRANSLATION_PER_SEC = 10f; private static final float CELL_SIZE = 1f; private static final float INITIAL_VIEW_SIZE = 25 * CELL_SIZE; private static final Color BG_COLOR = new Color(0.4f, 0.4f, 0.4f, 1f); private final File simulationSourceFile; private Universe universe; private boolean running; private float unusedTime; private int stepsPerSec = 10; private Map<Character, Color> stateColors = new HashMap<>(); private Map<String, Color> antTypeColors = new HashMap<>(); private Map<String, FreeTypeFontGenerator> fontGenerators = new HashMap<>(); private OrthographicCamera camera; private SpriteBatch batch; private ShapeRenderer shapeRenderer; private TextureAtlas textureAtlas; private Skin skin; private Stage uiStage; private BitmapFont font; private Label fpsLabel; private byte zooming; private byte horizontalTranslation; private byte verticalTranslation; private boolean drawGridLines = true; private GraphicalFrontend (File simulationSourceFile) { this.simulationSourceFile = simulationSourceFile; readUniverse(); } public static void main (String[] args) throws FileNotFoundException { if (args.length < 1) { System.err.println( "usage: java gui.GraphicalFrontend <simulation_source_file>"); System.exit(1); } File sourceFile = new File(args[0]); if (!sourceFile.exists() || !sourceFile.isFile()) { System.err.println("`" + args[0] + "` is not a file!"); System.exit(1); } LwjglApplicationConfiguration.disableAudio = true; new LwjglApplication(new GraphicalFrontend(sourceFile), "Ants in ~SPACE~", 640, 640); } private void readUniverse () { try { universe = InputHandler .initialiseUniverse(new FileInputStream(simulationSourceFile)); } catch (FileNotFoundException e) { throw new RuntimeException("Simulation source file is unreadable!", e); } stateColors.clear(); antTypeColors.clear(); stateColors.put(universe.defaultState, Color.WHITE); if (universe.states.length > 1) { stateColors.put(universe.states[1], Color.BLACK); if (universe.states.length > 2) { float sector = 360f / (float) (universe.states.length - 2); for (int i = 2; i < universe.states.length; ++i) { stateColors.put(universe.states[i], ColorUtils.HSV_to_RGB(sector * (i - 2), 100f, 100f)); } } } String[] antTypes = universe.species.keySet().toArray(new String[0]); if (antTypes.length > 0) { /*antTypeColors.put(antTypes[0], Color.WHITE); if (antTypes.length > 1) { float sector = 360f / (float) (antTypes.length - 1); for (int i = 1; i < antTypes.length; ++i) { antTypeColors.put(antTypes[i], ColorUtils .HSV_to_RGB(sector * (i - 1), 100f, 100f)); } }*/ float sector = 360f / (float) antTypes.length; for (int i = 0; i < antTypes.length; ++i) { antTypeColors.put(antTypes[i], ColorUtils .HSV_to_RGB(sector * i, 100f, 100f)); } } } /** * Called when the application is started, to load any resources and such. */ @Override public void create () { float w = Gdx.graphics.getWidth(); float h = Gdx.graphics.getHeight(); // Initialise camera. camera = new OrthographicCamera(INITIAL_VIEW_SIZE, INITIAL_VIEW_SIZE * (h / w)); camera.position.set(0, 0, 0); camera.update(); batch = new SpriteBatch(); shapeRenderer = new ShapeRenderer(); // Load assets textureAtlas = new TextureAtlas(Gdx.files.internal("assets.atlas")); skin = new Skin(textureAtlas); skin.add("opensans_14_semibold", generateFont(14, "OpenSans-Semibold")); skin.add("opensans_16_regular", generateFont(16, "OpenSans-Regular")); font = generateFont(16, "OpenSans-Regular", 1, Color.BLACK); skin.add("opensans_16_regular_stroke", font); skin.load(Gdx.files.internal("ui.skin")); uiStage = new Stage(new ScreenViewport()); InputMultiplexer inputMultiplexer = new InputMultiplexer(); inputMultiplexer.addProcessor(uiStage); inputMultiplexer.addProcessor(new InputAdapter() { @Override public boolean keyDown (int keycode) { if (keycode == Input.Keys.PLUS || keycode == Input.Keys.MINUS) { zooming += keycode == Input.Keys.PLUS ? 1 : -1; return true; } else if (keycode == Input.Keys.LEFT || keycode == Input.Keys.RIGHT) { horizontalTranslation += keycode == Input.Keys.RIGHT ? 1 : -1; return true; } else if (keycode == Input.Keys.UP || keycode == Input.Keys.DOWN) { verticalTranslation += keycode == Input.Keys.UP ? 1 : -1; return true; } else if (keycode == Input.Keys.NUM_0 || keycode == Input.Keys.NUMPAD_0) { camera.position.x = 0; camera.position.y = 0; camera.update(); return true; } return false; } @Override public boolean keyUp (int keycode) { if (keycode == Input.Keys.PLUS || keycode == Input.Keys.MINUS) { zooming += keycode == Input.Keys.PLUS ? -1 : 1; return true; } else if (keycode == Input.Keys.LEFT || keycode == Input.Keys.RIGHT) { horizontalTranslation += keycode == Input.Keys.RIGHT ? -1 : 1; return true; } else if (keycode == Input.Keys.UP || keycode == Input.Keys.DOWN) { verticalTranslation += keycode == Input.Keys.UP ? -1 : 1; return true; } return false; } @Override public boolean touchDown (int screenX, int screenY, int pointer, int button) { uiStage.setKeyboardFocus(null); return true; } }); Gdx.input.setInputProcessor(inputMultiplexer); Table table = new Table(); table.setFillParent(true); table.add(new ButtonRow(skin)).pad(5).expand().fillX().align(Align.top); uiStage.addActor(table); fpsLabel = new Label("FPS: ##", skin, "withbg"); fpsLabel.setPosition(10, 10); uiStage.addActor(fpsLabel); } private BitmapFont generateFont (int size, String fontName) { return generateFont(size, fontName, 0, Color.BLACK); } private BitmapFont generateFont (int size, String fontName, float borderWidth, Color borderColor) { FreeTypeFontGenerator generator = fontGenerators.get(fontName); if (generator == null) { generator = new FreeTypeFontGenerator( Gdx.files.internal("fonts/" + fontName + ".ttf")); fontGenerators.put(fontName, generator); } FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter(); parameter.size = size; parameter.borderWidth = borderWidth; parameter.borderColor = borderColor; return generator.generateFont(parameter); } @Override public void resize (int width, int height) { camera.viewportWidth = INITIAL_VIEW_SIZE; camera.viewportHeight = INITIAL_VIEW_SIZE * height / width; camera.update(); uiStage.getViewport().update(width, height, true); } /** * Called each time a frame should be rendered. */ @Override public void render () { float delta = Gdx.graphics.getDeltaTime(); // Do logic logic(delta); // Do drawing draw(delta); } /** * Perform all logic. * * @param delta The time elapsed since the last frame in seconds. */ private void logic (float delta) { // Update FPS label fpsLabel.setText("FPS: " + Gdx.graphics.getFramesPerSecond()); // Run Simulation if (running) { unusedTime += delta; int stepsToDo = MathUtils.floor(stepsPerSec * unusedTime); universe.moveNSteps(stepsToDo); unusedTime -= (float) stepsToDo / (float) stepsPerSec; } // Update UI stage uiStage.act(delta); // Camera zooming if (zooming != 0) { camera.zoom -= zooming * ZOOM_PER_SEC * delta; float viewW = camera.zoom * camera.viewportWidth; float magnification = Gdx.graphics.getWidth() / viewW; /* if (magnification < 10f || magnification > 100f) { magnification = MathUtils.clamp(magnification, 10f, 100f); camera.zoom = Gdx.graphics.getWidth() / magnification / camera.viewportWidth; drawGridLines = false; } else { drawGridLines = true; } */ if (magnification < 10f) { drawGridLines = false; } else { drawGridLines = true; } if (magnification > 500f) { magnification = 500f; camera.zoom = Gdx.graphics.getWidth() / magnification / camera.viewportWidth; } } // Camera translation if (horizontalTranslation != 0 || verticalTranslation != 0) { camera.translate(horizontalTranslation * TRANSLATION_PER_SEC * delta, verticalTranslation * TRANSLATION_PER_SEC * delta); } // Update camera camera.update(); } /** * Perform the frame drawing. * * @param delta The time elapsed since the last frame in seconds. */ private void draw (float delta) { // Update projection matrices batch.setProjectionMatrix(camera.combined); shapeRenderer.setProjectionMatrix(camera.combined); // Clear the screen Gdx.gl.glClearColor(BG_COLOR.r, BG_COLOR.g, BG_COLOR.b, BG_COLOR.a); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Draw cells float viewW = camera.viewportWidth * camera.zoom; float viewH = camera.viewportHeight * camera.zoom; float viewX = camera.position.x - viewW / 2f; float viewY = camera.position.y - viewH / 2f; int xCell = MathUtils.floor(viewX / CELL_SIZE); int yCell = MathUtils.floor(viewY / CELL_SIZE); int visWidthCells = MathUtils.ceil(viewW / CELL_SIZE) + 1; int visHeightCells = MathUtils.ceil(viewH / CELL_SIZE) + 1; if (universe.wrap) { xCell = Math.max(xCell, -universe.width + 1); yCell = Math.max(yCell, -universe.height + 1); visWidthCells = Math.min(visWidthCells, universe.width - xCell); visHeightCells = Math.min(visHeightCells, universe.height - yCell); } shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); char state; for (int y = yCell; y < yCell + visHeightCells; ++y) { for (int x = xCell; x < xCell + visWidthCells; ++x) { state = universe.getState(new Point(x, y)); shapeRenderer.setColor(stateColors.get(state)); if (drawGridLines) { shapeRenderer.rect((x + (1f / 16f) - 0.5f) * CELL_SIZE, (y + (1f / 16f) - 0.5f) * CELL_SIZE, (7f / 8f) * CELL_SIZE, (7f / 8f) * CELL_SIZE); } else { shapeRenderer.rect((x - 0.5f) * CELL_SIZE, (y - 0.5f) * CELL_SIZE, CELL_SIZE, CELL_SIZE); } } } // Draw Ants float radius = (7f / 8f) * (7f / 8f) * CELL_SIZE / 2f; for (Ant ant : universe.population) { shapeRenderer.setColor(Color.BLACK); shapeRenderer .arc(ant.position.x * CELL_SIZE, ant.position.y * CELL_SIZE, radius, 0f, 360f, 36); shapeRenderer.setColor(antTypeColors.get(ant.type.name)); shapeRenderer.arc(ant.position.x * CELL_SIZE, ant.position.y * CELL_SIZE, (7f / 8f) * radius, 0f, 360f, 36); } shapeRenderer.end(); // Draw Legend drawLegend(); // Draw UI uiStage.draw(); } private void drawLegend () { batch.getProjectionMatrix() .setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); shapeRenderer.getProjectionMatrix() .setToOrtho2D(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); shapeRenderer.updateMatrices(); shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); float startY = Gdx.graphics.getHeight() - 120f; float y = startY - 16f; for (char s : universe.states) { shapeRenderer.setColor(Color.BLACK); shapeRenderer.rect(16f, y, 16f, 16f); shapeRenderer.setColor(stateColors.get(s)); shapeRenderer.rect(17f, y + 1f, 14f, 14f); y -= 20f; } y -= 24f; for (String antType : antTypeColors.keySet()) { shapeRenderer.setColor(Color.BLACK); shapeRenderer.arc(24f, y + 8f, 8f, 0f, 360f, 36); shapeRenderer.setColor(antTypeColors.get(antType)); shapeRenderer.arc(24f, y + 8f, 7f, 0f, 360f, 36); y -= 20f; } shapeRenderer.end(); batch.begin(); font.draw(batch, "States:", 16f, startY + 20f); y = startY - 2f; for (char s : universe.states) { font.draw(batch, "= " + s, 36f, y); y -= 20f; } y -= 4f; font.draw(batch, "Species:", 16f, y); y -= 20f; for (String antType : antTypeColors.keySet()) { font.draw(batch, "= " + antType, 36f, y); y -= 20f; } batch.end(); } @Override public void pause () { // NO-OP } @Override public void resume () { // NO-OP } /** * Called when the application is closing, to dispose of any loaded resources. */ @Override public void dispose () { uiStage.dispose(); skin.dispose(); fontGenerators.values().forEach(FreeTypeFontGenerator::dispose); textureAtlas.dispose(); shapeRenderer.dispose(); batch.dispose(); } private class ButtonRow extends Table { private final TextButton resetBtn; private final TextButton playPauseBtn; private final NumberField stepsPerSecField; private final NumberField nStepsField; private final TextButton doNStepsBtn; private ButtonRow (Skin skin) { super(skin); Table left = new Table(skin); resetBtn = new TextButton("Reset", skin); resetBtn.addListener(new ClickListener() { @Override public void clicked (InputEvent event, float x, float y) { readUniverse(); } }); left.add(resetBtn).width(200); add(left).expandY().align(Align.top); Table center = new Table(skin); playPauseBtn = new TextButton("Play", skin); playPauseBtn.addListener(new ClickListener(Input.Buttons.LEFT) { @Override public void clicked (InputEvent event, float x, float y) { if (!running) { stepsPerSec = stepsPerSecField.getValue(); } running = !running; updateButtons(); } }); center.add(playPauseBtn).width(200); center.row(); Table t = new Table(skin); Label l = new Label("Steps / sec:", skin, "white"); l.setAlignment(Align.center); t.add(l).width(100); stepsPerSecField = new NumberField(10, skin); stepsPerSecField.setMin(1); t.add(stepsPerSecField).width(100); center.add(t).width(200); add(center).padLeft(5).padRight(5).expandX(); Table right = new Table(skin); l = new Label("Do n Steps:", skin, "white"); l.setAlignment(Align.center); right.add(l).width(200); right.row(); t = new Table(skin); nStepsField = new NumberField(1, skin); nStepsField.setMin(1); t.add(nStepsField).width(100); doNStepsBtn = new TextButton("Go", skin); doNStepsBtn.addListener(new ClickListener(Input.Buttons.LEFT) { @Override public void clicked (InputEvent event, float x, float y) { if (!doNStepsBtn.isDisabled()) { universe.moveNSteps(nStepsField.getValue()); } } }); t.add(doNStepsBtn).width(100); right.add(t).width(200); add(right).expandY().align(Align.bottom); } private void updateButtons () { playPauseBtn.setText(running ? "Pause" : "Play"); resetBtn.setDisabled(running); stepsPerSecField.setDisabled(running); nStepsField.setDisabled(running); doNStepsBtn.setDisabled(running); } } }
package com.xamoom.android.xamoomsdk; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.location.Location; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.xamoom.android.xamoomsdk.Enums.ContentFlags; import com.xamoom.android.xamoomsdk.Enums.ContentSortFlags; import com.xamoom.android.xamoomsdk.Enums.SpotFlags; import com.xamoom.android.xamoomsdk.Enums.SpotSortFlags; import com.xamoom.android.xamoomsdk.Offline.OfflineEnduserApi; import com.xamoom.android.xamoomsdk.Resource.Content; import com.xamoom.android.xamoomsdk.Resource.ContentBlock; import com.xamoom.android.xamoomsdk.Resource.Marker; import com.xamoom.android.xamoomsdk.Resource.Menu; import com.xamoom.android.xamoomsdk.Resource.Spot; import com.xamoom.android.xamoomsdk.Resource.Style; import com.xamoom.android.xamoomsdk.Resource.System; import com.xamoom.android.xamoomsdk.Resource.SystemSetting; import com.xamoom.android.xamoomsdk.Utils.JsonListUtil; import com.xamoom.android.xamoomsdk.Utils.UrlUtil; import java.io.IOException; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Map; import at.rags.morpheus.Deserializer; import at.rags.morpheus.Error; import at.rags.morpheus.Morpheus; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Retrofit; import static okhttp3.internal.Internal.logger; /** * EnduserApi is the main part of the XamoomSDK. You can use it to send api request to * the xamoom cloud. * * Use {@link #EnduserApi(String, Context)} to initialize. * * Change the requested language by setting {@link #language}. The users language is saved * in {@link #systemLanguage}. * * Get local saved data by setting {@link #setOffline(boolean)} to true. Data must be saved * using {@link com.xamoom.android.xamoomsdk.Storage.OfflineStorageManager}. */ public class EnduserApi implements Parcelable { public static final String SDK_VERSION = "2.2.4"; private static final String TAG = EnduserApi.class.getSimpleName(); private static final String API_URL = "https://xamoom-cloud.appspot.com/"; private static EnduserApi sharedInstance; private Context context; private String apiKey; private EnduserApiInterface enduserApiInterface; private OfflineEnduserApi offlineEnduserApi; private CallHandler callHandler; private String language; private String systemLanguage; private boolean offline; public EnduserApi(final String apikey, Context context) { this.apiKey = apikey; this.context = context; this.offlineEnduserApi = new OfflineEnduserApi(context); initRetrofit(apiKey); initMorpheus(); initVars(); } public EnduserApi(Retrofit retrofit, Context context) { this.enduserApiInterface = retrofit.create(EnduserApiInterface.class); this.context = context; this.offlineEnduserApi = new OfflineEnduserApi(context); initMorpheus(); initVars(); } protected EnduserApi(Parcel in) { apiKey = in.readString(); initRetrofit(apiKey); initMorpheus(); initVars(); language = in.readString(); } private void initRetrofit(final String apiKey) { if (apiKey == null) { throw new NullPointerException("apiKey is null."); } OkHttpClient.Builder builder = new OkHttpClient().newBuilder(); builder.addInterceptor(new HTTPHeaderInterceptor(generateUserAgent(), apiKey)); OkHttpClient httpClient = builder.build(); Retrofit retrofit = new Retrofit.Builder() .client(httpClient) .baseUrl(API_URL) .build(); enduserApiInterface = retrofit.create(EnduserApiInterface.class); } private void initMorpheus() { Morpheus morpheus = new Morpheus(); callHandler = new CallHandler(morpheus); Deserializer.registerResourceClass("contents", Content.class); Deserializer.registerResourceClass("content", Content.class); Deserializer.registerResourceClass("contentblocks", ContentBlock.class); Deserializer.registerResourceClass("spots", Spot.class); Deserializer.registerResourceClass("markers", Marker.class); Deserializer.registerResourceClass("systems", System.class); Deserializer.registerResourceClass("menus", Menu.class); Deserializer.registerResourceClass("settings", SystemSetting.class); Deserializer.registerResourceClass("styles", Style.class); } private void initVars() { systemLanguage = Locale.getDefault().getLanguage(); language = systemLanguage; } /** * Get a content for a specific contentID. * * @param contentID ContentID from xamoom-cloud. * @param callback {@link APICallback}. */ public void getContent(String contentID, APICallback<Content, List<Error>> callback) { getContent(contentID, null, callback); } /** * Get a content for a specific contentID with possible flags. * * @param contentID ContentID from xamoom-cloud. * @param contentFlags Different flags {@link ContentFlags}. * @param callback {@link APICallback}. */ public void getContent(String contentID, EnumSet<ContentFlags> contentFlags, APICallback<Content, List<at.rags.morpheus.Error>> callback) { if (offline) { offlineEnduserApi.getContent(contentID, callback); return; } Map<String, String> params = UrlUtil.addContentParameter(UrlUtil.getUrlParameter(language), contentFlags); Call<ResponseBody> call = enduserApiInterface.getContent(contentID, params); callHandler.enqueCall(call, callback); } /** * Get a content for a specific LocationIdentifier. * * @param locationIdentifier LocationIdentifier from QR or NFC. * @param callback {@link APICallback}. */ public void getContentByLocationIdentifier(String locationIdentifier, APICallback<Content, List<Error>> callback) { getContentByLocationIdentifier(locationIdentifier, null, callback); } /** * Get a content for a specific LocationIdentifier with flags. * * @param locationIdentifier LocationIdentifier from QR or NFC. * @param contentFlags Different flags {@link ContentFlags}. * @param callback {@link APICallback}. */ public void getContentByLocationIdentifier(String locationIdentifier, EnumSet<ContentFlags> contentFlags, APICallback<Content, List<Error>> callback) { if (offline) { offlineEnduserApi.getContentByLocationIdentifier(locationIdentifier, callback); return; } Map<String, String> params = UrlUtil.getUrlParameter(language); params.put("filter[location-identifier]", locationIdentifier); params = UrlUtil.addContentParameter(params, contentFlags); Call<ResponseBody> call = enduserApiInterface.getContents(params); callHandler.enqueCall(call, callback); } /** * Get content for a specific beacon. * * @param major Beacon major ID. * @param minor Beacon minor ID. * @param callback {@link APICallback}. */ public void getContentByBeacon(int major, int minor, APICallback<Content, List<Error>> callback) { getContentByLocationIdentifier(String.format("%s|%s", major, minor), callback); } /** * Get content for a specific beacon. * * @param major Beacon major ID. * @param minor Beacon minor ID. * @param contentFlags Different flags {@link ContentFlags}. * @param callback {@link APICallback}. */ public void getContentByBeacon(int major, int minor, EnumSet<ContentFlags> contentFlags, APICallback<Content, List<Error>> callback) { getContentByLocationIdentifier(String.format("%s|%s", major, minor), contentFlags, callback); } /** * Get list of contents with your location. Geofence radius is 40m. * * @param location Users location. * @param pageSize PageSize for returned contents (max 100). * @param cursor Cursor for paging. * @param sortFlags {@link ContentSortFlags} to sort results. * @param callback {@link APIListCallback}. */ public void getContentsByLocation(Location location, int pageSize, @Nullable String cursor, final EnumSet<ContentSortFlags> sortFlags, APIListCallback<List<Content>, List<Error>> callback) { if (offline) { offlineEnduserApi.getContentsByLocation(location, 10, null, null, null); return; } Map<String, String> params = UrlUtil.addContentSortingParameter(UrlUtil.getUrlParameter(language), sortFlags); params = UrlUtil.addPagingToUrl(params, pageSize, cursor); params.put("filter[lat]", Double.toString(location.getLatitude())); params.put("filter[lon]", Double.toString(location.getLongitude())); Call<ResponseBody> call = enduserApiInterface.getContents(params); callHandler.enqueListCall(call, callback); } /** * Get list of contents with a specific tag. * * @param tags List of strings. * @param pageSize PageSize for returned contents (max 100). * @param cursor Cursor for paging. * @param sortFlags {@link ContentSortFlags} to sort results. * @param callback {@link APIListCallback}. */ public void getContentsByTags(List<String> tags, int pageSize, @Nullable String cursor, EnumSet<ContentSortFlags> sortFlags, APIListCallback<List<Content>, List<Error>> callback) { if (offline) { offlineEnduserApi.getContentsByTags(tags, pageSize, cursor, sortFlags, callback); return; } Map<String, String> params = UrlUtil.addContentSortingParameter(UrlUtil.getUrlParameter(language), sortFlags); params = UrlUtil.addPagingToUrl(params, pageSize, cursor); params.put("filter[tags]", JsonListUtil.listToJsonArray(tags, ",")); Call<ResponseBody> call = enduserApiInterface.getContents(params); callHandler.enqueListCall(call, callback); } /** * Get list of contents with full-text name search. * * @param name Name to search for. * @param pageSize PageSize for returned contents (max 100). * @param cursor Cursor for paging. * @param sortFlags {@link ContentSortFlags} to sort results. * @param callback {@link APIListCallback}. */ public void searchContentsByName(String name, int pageSize, @Nullable String cursor, EnumSet<ContentSortFlags> sortFlags, APIListCallback<List<Content>, List<Error>> callback) { if (offline) { offlineEnduserApi.searchContentsByName(name, pageSize, cursor, sortFlags, callback); return; } Map<String, String> params = UrlUtil.addContentSortingParameter(UrlUtil.getUrlParameter(language), sortFlags); params = UrlUtil.addPagingToUrl(params, pageSize, cursor); params.put("filter[name]", name); Call<ResponseBody> call = enduserApiInterface.getContents(params); callHandler.enqueListCall(call, callback); } /** * Get spot with specific id. * * @param spotId Id of the spot. * @param callback {@link APICallback}. */ public void getSpot(String spotId, APICallback<Spot, List<Error>> callback) { getSpot(spotId, null, callback); } public void getSpot(String spotId, EnumSet<SpotFlags> spotFlags, APICallback<Spot, List<Error>> callback) { if (offline) { offlineEnduserApi.getSpot(spotId, callback); } Map<String, String> params = UrlUtil.getUrlParameter(this.language); params = UrlUtil.addSpotParameter(params, spotFlags); Call<ResponseBody> call = enduserApiInterface.getSpot(spotId, params); callHandler.enqueCall(call, callback); } /** * Get list of spots inside radius of a location. * * @param location User location. * @param radius Radius to search in meter (max 5000). * @param spotFlags {@link SpotFlags}. * @param sortFlags {@link SpotSortFlags} * @param callback {@link APIListCallback} */ public void getSpotsByLocation(Location location, int radius, EnumSet<SpotFlags> spotFlags, @Nullable EnumSet<SpotSortFlags> sortFlags, APIListCallback<List<Spot>, List<Error>> callback) { getSpotsByLocation(location, radius, 0, null, spotFlags, sortFlags, callback); } /** * Get list of spots inside radius of a location. * * @param location User location. * @param radius Radius to search in meter (max 5000). * @param pageSize Size for pages. (max 100) * @param cursor Cursor of last search. * @param spotFlags {@link SpotFlags}. * @param sortFlags {@link SpotSortFlags} * @param callback {@link APIListCallback} */ public void getSpotsByLocation(Location location, int radius, int pageSize, @Nullable String cursor, @Nullable EnumSet<SpotFlags> spotFlags, @Nullable EnumSet<SpotSortFlags> sortFlags, APIListCallback<List<Spot>, List<Error>> callback) { if (offline) { offlineEnduserApi.getSpotsByLocation(location, radius, pageSize, cursor, spotFlags, sortFlags, callback); return; } Map<String, String> params = UrlUtil.addSpotParameter(UrlUtil.getUrlParameter(language), spotFlags); params = UrlUtil.addSpotSortingParameter(params, sortFlags); params = UrlUtil.addPagingToUrl(params, pageSize, cursor); params.put("filter[lat]", Double.toString(location.getLatitude())); params.put("filter[lon]", Double.toString(location.getLongitude())); params.put("filter[radius]", Integer.toString(radius)); Call<ResponseBody> call = enduserApiInterface.getSpots(params); callHandler.enqueListCall(call, callback); } /** * Get list of spots with tags. * Or operation used when searching with tags. * * @param tags List with tag names * @param spotFlags {@link SpotFlags}. * @param sortFlags {@link SpotSortFlags} * @param callback {@link APIListCallback} */ public void getSpotsByTags(List<String> tags, @Nullable EnumSet<SpotFlags> spotFlags, @Nullable EnumSet<SpotSortFlags> sortFlags, APIListCallback<List<Spot>, List<Error>> callback) { getSpotsByTags(tags, 0, null, spotFlags, sortFlags, callback); } /** * Get list of spots with with tags. * Or operation used when searching with tags. * * @param tags List with tag names. * @param pageSize Size for pages. (max 100) * @param cursor Cursor of last search. * @param spotFlags {@link SpotFlags}. * @param sortFlags {@link SpotSortFlags} * @param callback {@link APIListCallback} */ public void getSpotsByTags(List<String> tags, int pageSize, @Nullable String cursor, @Nullable EnumSet<SpotFlags> spotFlags, @Nullable EnumSet<SpotSortFlags> sortFlags, APIListCallback<List<Spot>, List<Error>> callback) { if (offline) { offlineEnduserApi.getSpotsByTags(tags, pageSize, cursor, spotFlags, sortFlags, callback); return; } Map<String, String> params = UrlUtil.addSpotParameter(UrlUtil.getUrlParameter(language), spotFlags); params = UrlUtil.addSpotSortingParameter(params, sortFlags); params = UrlUtil.addPagingToUrl(params, pageSize, cursor); params.put("filter[tags]", JsonListUtil.listToJsonArray(tags, ",")); Call<ResponseBody> call = enduserApiInterface.getSpots(params); callHandler.enqueListCall(call, callback); } /** * Get list of spots with full-text name search. * * @param name Name to searchfor. * @param pageSize Size for pages. (max 100) * @param cursor Cursor of last search. * @param spotFlags {@link SpotFlags}. * @param sortFlags {@link SpotSortFlags} * @param callback {@link APIListCallback} */ public void searchSpotsByName(String name, int pageSize, @Nullable String cursor, @Nullable EnumSet<SpotFlags> spotFlags, @Nullable EnumSet<SpotSortFlags> sortFlags, APIListCallback<List<Spot>, List<Error>> callback) { if (offline) { offlineEnduserApi.searchSpotsByName(name, pageSize, cursor, spotFlags, sortFlags, callback); return; } Map<String, String> params = UrlUtil.addSpotParameter(UrlUtil.getUrlParameter(language), spotFlags); params = UrlUtil.addSpotSortingParameter(params, sortFlags); params = UrlUtil.addPagingToUrl(params, pageSize, cursor); params.put("filter[name]", name); Call<ResponseBody> call = enduserApiInterface.getSpots(params); callHandler.enqueListCall(call, callback); } /** * Get the system connected to your api key. * * @param callback {@link APIListCallback}. */ public void getSystem(final APICallback<System, List<Error>> callback) { if (offline) { offlineEnduserApi.getSystem(callback); return; } Map<String, String> params = UrlUtil.getUrlParameter(language); Call<ResponseBody> call = enduserApiInterface.getSystem(params); callHandler.enqueCall(call, callback); } /** * Get the menu to your system. * * @param systemId Systems systemId. * @param callback {@link APIListCallback}. */ public void getMenu(String systemId, final APICallback<Menu, List<Error>> callback) { if (offline) { offlineEnduserApi.getMenu(systemId, callback); return; } Map<String, String> params = UrlUtil.getUrlParameter(language); Call<ResponseBody> call = enduserApiInterface.getMenu(systemId, params); callHandler.enqueCall(call, callback); } /** * Get the systemSettings to your system. * * @param systemId Systems systemId. * @param callback {@link APIListCallback}. */ public void getSystemSetting(String systemId, final APICallback<SystemSetting, List<Error>> callback) { if (offline) { offlineEnduserApi.getSystemSetting(systemId, callback); return; } Map<String, String> params = UrlUtil.getUrlParameter(language); Call<ResponseBody> call = enduserApiInterface.getSetting(systemId, params); callHandler.enqueCall(call, callback); } /** * Get the style to your system. * * @param systemId Systems systemId. * @param callback {@link APIListCallback}. */ public void getStyle(String systemId, final APICallback<Style, List<Error>> callback) { if (offline) { offlineEnduserApi.getStyle(systemId, callback); return; } Map<String, String> params = UrlUtil.getUrlParameter(language); Call<ResponseBody> call = enduserApiInterface.getStyle(systemId, params); callHandler.enqueCall(call, callback); } //parcelable public static final Creator<EnduserApi> CREATOR = new Creator<EnduserApi>() { @Override public EnduserApi createFromParcel(Parcel in) { return new EnduserApi(in); } @Override public EnduserApi[] newArray(int size) { return new EnduserApi[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(apiKey); dest.writeString(language); } // helper private String generateUserAgent() { if (this.context == null) { return "Xamoom SDK Android"; } StringBuilder builder = new StringBuilder(); builder.append("Xamoom SDK Android"); builder.append("|"); builder.append(context.getApplicationInfo().loadLabel(context.getPackageManager())); builder.append("|"); builder.append(SDK_VERSION); return builder.toString(); } // getters & setters public String getSystemLanguage() { return systemLanguage; } public String getLanguage() { return language; } public EnduserApiInterface getEnduserApiInterface() { return enduserApiInterface; } public void setLanguage(String language) { this.language = language; } public CallHandler getCallHandler() { return callHandler; } public void setCallHandler(CallHandler callHandler) { this.callHandler = callHandler; } /** * Use this to get your instance. It will create a new one with your api key, when * there is no isntance. * * @param apikey Your xamoom api key. * @return EnduserApi instance. */ public static EnduserApi getSharedInstance(@NonNull String apikey, Context context) { if (apikey == null) { throw new NullPointerException("Apikey should not be null."); } if (EnduserApi.sharedInstance == null) { EnduserApi.sharedInstance = new EnduserApi(apikey, context); } return EnduserApi.sharedInstance; } /** * This will you return your current sharedInstance. Even if it is null. * @return EnduserApi instance. */ public static EnduserApi getSharedInstance() { if (EnduserApi.sharedInstance == null) { throw new NullPointerException("Instance is null. Please use getSharedInstance(apikey, context) " + "or setSharedInstance"); } return EnduserApi.sharedInstance; } /** * Set your the sharedInstance with your Instance of EnduserApi. * @param sharedInstance SharedInstance to save. */ public static void setSharedInstance(EnduserApi sharedInstance) { EnduserApi.sharedInstance = sharedInstance; } public OfflineEnduserApi getOfflineEnduserApi() { return offlineEnduserApi; } public void setOfflineEnduserApi(OfflineEnduserApi offlineEnduserApi) { this.offlineEnduserApi = offlineEnduserApi; } public boolean isOffline() { return offline; } /** * Set offline to true to get data saved in local database. * @param offline */ public void setOffline(boolean offline) { this.offline = offline; } }
package com.xpn.xwiki.plugin.packaging; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import net.sf.json.JSONObject; import org.apache.commons.io.input.CloseShieldInputStream; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.dom.DOMDocument; import org.dom4j.dom.DOMElement; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.xwiki.model.reference.SpaceReference; import org.xwiki.observation.ObservationManager; import org.xwiki.query.QueryException; import com.xpn.xwiki.XWiki; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.doc.XWikiAttachment; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.internal.event.XARImportedEvent; import com.xpn.xwiki.internal.xml.XMLWriter; import com.xpn.xwiki.objects.classes.BaseClass; import com.xpn.xwiki.web.Utils; public class Package { public static final int OK = 0; public static final int Right = 1; public static final String DEFAULT_FILEEXT = "xml"; public static final String DefaultPackageFileName = "package.xml"; public static final String DefaultPluginName = "package"; private static final Log LOG = LogFactory.getLog(Package.class); private String name = "My package"; private String description = ""; private String version = "1.0.0"; private String licence = "LGPL"; private String authorName = "XWiki"; private List<DocumentInfo> files = null; private List<DocumentInfo> customMappingFiles = null; private List<DocumentInfo> classFiles = null; private boolean backupPack = false; private boolean preserveVersion = false; private boolean withVersions = true; private List<DocumentFilter> documentFilters = new ArrayList<DocumentFilter>(); public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getVersion() { return this.version; } public void setVersion(String version) { this.version = version; } public String getLicence() { return this.licence; } public void setLicence(String licence) { this.licence = licence; } public String getAuthorName() { return this.authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } /** * If true, the package will preserve the original author during import, rather than updating the author to the * current (importing) user. * * @see #isWithVersions() * @see #isVersionPreserved() */ public boolean isBackupPack() { return this.backupPack; } public void setBackupPack(boolean backupPack) { this.backupPack = backupPack; } public boolean hasBackupPackImportRights(XWikiContext context) { return isFarmAdmin(context); } /** * If true, the package will preserve the current document version during import, regardless of whether or not the * document history is included. * * @see #isWithVersions() * @see #isBackupPack() */ public boolean isVersionPreserved() { return this.preserveVersion; } public void setPreserveVersion(boolean preserveVersion) { this.preserveVersion = preserveVersion; } public List<DocumentInfo> getFiles() { return this.files; } public List<DocumentInfo> getCustomMappingFiles() { return this.customMappingFiles; } public boolean isWithVersions() { return this.withVersions; } /** * If set to true, history revisions in the archive will be imported when importing documents. */ public void setWithVersions(boolean withVersions) { this.withVersions = withVersions; } public void addDocumentFilter(Object filter) throws PackageException { if (filter instanceof DocumentFilter) { this.documentFilters.add((DocumentFilter) filter); } else { throw new PackageException(PackageException.ERROR_PACKAGE_INVALID_FILTER, "Invalid Document Filter"); } } public Package() { this.files = new ArrayList<DocumentInfo>(); this.customMappingFiles = new ArrayList<DocumentInfo>(); this.classFiles = new ArrayList<DocumentInfo>(); } public boolean add(XWikiDocument doc, int defaultAction, XWikiContext context) throws XWikiException { if (!context.getWiki().checkAccess("edit", doc, context)) { return false; } for (int i = 0; i < this.files.size(); i++) { DocumentInfo di = this.files.get(i); if (di.getFullName().equals(doc.getFullName()) && (di.getLanguage().equals(doc.getLanguage()))) { if (defaultAction != DocumentInfo.ACTION_NOT_DEFINED) { di.setAction(defaultAction); } if (!doc.isNew()) { di.setDoc(doc); } return true; } } doc = doc.clone(); try { filter(doc, context); DocumentInfo docinfo = new DocumentInfo(doc); docinfo.setAction(defaultAction); this.files.add(docinfo); BaseClass bclass = doc.getXClass(); if (bclass.getFieldList().size() > 0) { this.classFiles.add(docinfo); } if (bclass.getCustomMapping() != null) { this.customMappingFiles.add(docinfo); } return true; } catch (ExcludeDocumentException e) { LOG.info("Skip the document " + doc.getDocumentReference()); return false; } } public boolean add(XWikiDocument doc, XWikiContext context) throws XWikiException { return add(doc, DocumentInfo.ACTION_NOT_DEFINED, context); } public boolean updateDoc(String docFullName, int action, XWikiContext context) throws XWikiException { XWikiDocument doc = new XWikiDocument(); doc.setFullName(docFullName, context); return add(doc, action, context); } public boolean add(String docFullName, int DefaultAction, XWikiContext context) throws XWikiException { XWikiDocument doc = context.getWiki().getDocument(docFullName, context); add(doc, DefaultAction, context); List<String> languages = doc.getTranslationList(context); for (String language : languages) { if (!((language == null) || (language.equals("")) || (language.equals(doc.getDefaultLanguage())))) { add(doc.getTranslatedDocument(language, context), DefaultAction, context); } } return true; } public boolean add(String docFullName, String language, int DefaultAction, XWikiContext context) throws XWikiException { XWikiDocument doc = context.getWiki().getDocument(docFullName, context); if ((language == null) || (language.equals(""))) { add(doc, DefaultAction, context); } else { add(doc.getTranslatedDocument(language, context), DefaultAction, context); } return true; } public boolean add(String docFullName, XWikiContext context) throws XWikiException { return add(docFullName, DocumentInfo.ACTION_NOT_DEFINED, context); } public boolean add(String docFullName, String language, XWikiContext context) throws XWikiException { return add(docFullName, language, DocumentInfo.ACTION_NOT_DEFINED, context); } public void filter(XWikiDocument doc, XWikiContext context) throws ExcludeDocumentException { for (DocumentFilter docFilter : this.documentFilters) { docFilter.filter(doc, context); } } public String export(OutputStream os, XWikiContext context) throws IOException, XWikiException { if (this.files.size() == 0) { return "No Selected file"; } ZipOutputStream zos = new ZipOutputStream(os); for (int i = 0; i < this.files.size(); i++) { DocumentInfo docinfo = this.files.get(i); XWikiDocument doc = docinfo.getDoc(); addToZip(doc, zos, this.withVersions, context); } addInfosToZip(zos, context); zos.finish(); zos.flush(); return ""; } public String exportToDir(File dir, XWikiContext context) throws IOException, XWikiException { if (!dir.exists()) { if (!dir.mkdirs()) { Object[] args = new Object[1]; args[0] = dir.toString(); throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_MKDIR, "Error creating directory {0}", null, args); } } for (int i = 0; i < this.files.size(); i++) { DocumentInfo docinfo = this.files.get(i); XWikiDocument doc = docinfo.getDoc(); addToDir(doc, dir, this.withVersions, context); } addInfosToDir(dir, context); return ""; } /** * Load this package in memory from a byte array. It may be installed later using {@link #install(XWikiContext)}. * Your should prefer {@link #Import(InputStream, XWikiContext) which may avoid loading the package twice in memory. * * @param file a byte array containing the content of a zipped package file * @param context current XWikiContext * @return an empty string, useless. * @throws IOException while reading the ZipFile * @throws XWikiException when package content is broken */ public String Import(byte file[], XWikiContext context) throws IOException, XWikiException { return Import(new ByteArrayInputStream(file), context); } /** * Load this package in memory from an InputStream. It may be installed later using {@link #install(XWikiContext)}. * * @param file an InputStream of a zipped package file * @param context current XWikiContext * @return an empty string, useless. * @throws IOException while reading the ZipFile * @throws XWikiException when package content is broken * @since 2.3M2 */ public String Import(InputStream file, XWikiContext context) throws IOException, XWikiException { ZipInputStream zis = new ZipInputStream(file); ZipEntry entry; Document description = null; try { zis = new ZipInputStream(file); List<XWikiDocument> docsToLoad = new LinkedList<XWikiDocument>(); /* * Loop 1: Cycle through the zip input stream and load out all of the documents, when we find the * package.xml file we put it aside to so that we only include documents which are in the file. */ while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory() || (entry.getName().indexOf("META-INF") != -1)) { // The entry is either a directory or is something inside of the META-INF dir. continue; } else if (entry.getName().compareTo(DefaultPackageFileName) == 0) { // The entry is the manifest (package.xml). Read this differently. description = fromXml(new CloseShieldInputStream(zis)); } else { XWikiDocument doc = null; try { doc = readFromXML(new CloseShieldInputStream(zis)); } catch (Throwable ex) { LOG.warn("Failed to parse document [" + entry.getName() + "] from XML during import, thus it will not be installed. " + "The error was: " + ex.getMessage()); // It will be listed in the "failed documents" section after the import. addToErrors(entry.getName().replaceAll("/", "."), context); continue; } // Run all of the registered DocumentFilters on this document and // if no filters throw exceptions, add it to the list to import. try { this.filter(doc, context); docsToLoad.add(doc); } catch (ExcludeDocumentException e) { LOG.info("Skip the document '" + doc.getDocumentReference() + "'"); } } } // Make sure a manifest was included in the package... if (description == null) { throw new PackageException(XWikiException.ERROR_XWIKI_UNKNOWN, "Could not find the package definition"); } /* * Loop 2: Cycle through the list of documents and if they are in the manifest then add them, otherwise log * a warning and add them to the skipped list. */ for (XWikiDocument doc : docsToLoad) { if (documentExistInPackageFile(doc.getFullName(), doc.getLanguage(), description)) { this.add(doc, context); } else { LOG.warn("document " + doc.getDocumentReference() + " does not exist in package definition." + " It will not be installed."); // It will be listed in the "skipped documents" section after the // import. addToSkipped(doc.getFullName(), context); } } updateFileInfos(description); } catch (DocumentException e) { throw new PackageException(XWikiException.ERROR_XWIKI_UNKNOWN, "Error when reading the XML"); } return ""; } private boolean documentExistInPackageFile(String docName, String language, Document xml) { Element docFiles = xml.getRootElement(); Element infosFiles = docFiles.element("files"); @SuppressWarnings("unchecked") List<Element> fileList = infosFiles.elements("file"); for (Element el : fileList) { String tmpDocName = el.getStringValue(); if (tmpDocName.compareTo(docName) != 0) { continue; } String tmpLanguage = el.attributeValue("language"); if (tmpLanguage == null) { tmpLanguage = ""; } if (tmpLanguage.compareTo(language) == 0) { return true; } } return false; } private void updateFileInfos(Document xml) { Element docFiles = xml.getRootElement(); Element infosFiles = docFiles.element("files"); @SuppressWarnings("unchecked") List<Element> fileList = infosFiles.elements("file"); for (Element el : fileList) { String defaultAction = el.attributeValue("defaultAction"); String language = el.attributeValue("language"); if (language == null) { language = ""; } String docName = el.getStringValue(); setDocumentDefaultAction(docName, language, Integer.parseInt(defaultAction)); } } private void setDocumentDefaultAction(String docName, String language, int defaultAction) { if (this.files == null) { return; } for (DocumentInfo docInfo : this.files) { if (docInfo.getFullName().equals(docName) && docInfo.getLanguage().equals(language)) { docInfo.setAction(defaultAction); return; } } } public int testInstall(boolean isAdmin, XWikiContext context) { if (LOG.isDebugEnabled()) { LOG.debug("Package test install"); } int result = DocumentInfo.INSTALL_IMPOSSIBLE; try { if (this.files.size() == 0) { return result; } result = this.files.get(0).testInstall(isAdmin, context); for (DocumentInfo docInfo : this.files) { int res = docInfo.testInstall(isAdmin, context); if (res < result) { result = res; } } return result; } finally { if (LOG.isDebugEnabled()) { LOG.debug("Package test install result " + result); } } } public int install(XWikiContext context) throws XWikiException { boolean isAdmin = context.getWiki().getRightService().hasAdminRights(context); if (testInstall(isAdmin, context) == DocumentInfo.INSTALL_IMPOSSIBLE) { setStatus(DocumentInfo.INSTALL_IMPOSSIBLE, context); return DocumentInfo.INSTALL_IMPOSSIBLE; } boolean hasCustomMappings = false; for (DocumentInfo docinfo : this.customMappingFiles) { BaseClass bclass = docinfo.getDoc().getXClass(); hasCustomMappings |= context.getWiki().getStore().injectCustomMapping(bclass, context); } if (hasCustomMappings) { context.getWiki().getStore().injectUpdatedCustomMappings(context); } int status = DocumentInfo.INSTALL_OK; // Determine if the user performing the installation is a farm admin. // We allow author preservation from the package only to farm admins. // In order to prevent sub-wiki admins to take control of a farm with forged packages. // We test it once for the whole import in case one of the document break user during the import process. boolean backup = this.backupPack && isFarmAdmin(context); // Start by installing all documents having a class definition so that their // definitions are available when installing documents using them. for (DocumentInfo classFile : this.classFiles) { if (installDocument(classFile, isAdmin, backup, context) == DocumentInfo.INSTALL_ERROR) { status = DocumentInfo.INSTALL_ERROR; } } // Install the remaining documents (without class definitions). for (DocumentInfo docInfo : this.files) { if (!this.classFiles.contains(docInfo)) { if (installDocument(docInfo, isAdmin, backup, context) == DocumentInfo.INSTALL_ERROR) { status = DocumentInfo.INSTALL_ERROR; } } } setStatus(status, context); // Notify all the listeners about the just done import ObservationManager om = Utils.getComponent(ObservationManager.class); // FIXME: should be able to pass some sort of source here, the name of the attachment or the list of // imported documents. But for the moment it's fine om.notify(new XARImportedEvent(), null, context); return status; } /** * Indicate of the user has amin rights on the farm, i.e. that he has admin rights on the main wiki. * * @param context the XWiki context * @return true if the current user is farm admin */ private boolean isFarmAdmin(XWikiContext context) { String wiki = context.getDatabase(); try { context.setDatabase(context.getMainXWiki()); return context.getWiki().getRightService().hasAdminRights(context); } finally { context.setDatabase(wiki); } } private int installDocument(DocumentInfo doc, boolean isAdmin, boolean backup, XWikiContext context) throws XWikiException { if (this.preserveVersion && this.withVersions) { // Right now importing an archive and the history revisions it contains // without overriding the existing document is not supported. // We fallback on adding a new version to the existing history without importing the // archive's revisions. this.withVersions = false; } int result = DocumentInfo.INSTALL_OK; if (LOG.isDebugEnabled()) { LOG.debug("Package installing document " + doc.getFullName() + " " + doc.getLanguage()); } if (doc.getAction() == DocumentInfo.ACTION_SKIP) { addToSkipped(doc.getFullName() + ":" + doc.getLanguage(), context); return DocumentInfo.INSTALL_OK; } int status = doc.testInstall(isAdmin, context); if (status == DocumentInfo.INSTALL_IMPOSSIBLE) { addToErrors(doc.getFullName() + ":" + doc.getLanguage(), context); return DocumentInfo.INSTALL_IMPOSSIBLE; } if (status == DocumentInfo.INSTALL_OK || status == DocumentInfo.INSTALL_ALREADY_EXIST && doc.getAction() == DocumentInfo.ACTION_OVERWRITE) { XWikiDocument previousdoc = null; if (status == DocumentInfo.INSTALL_ALREADY_EXIST) { previousdoc = context.getWiki().getDocument(doc.getFullName(), context); // if this document is a translation: we should only delete the translation if (doc.getDoc().getTranslation() != 0) { previousdoc = previousdoc.getTranslatedDocument(doc.getLanguage(), context); } // we should only delete the previous document // if we are overridding the versions and/or if this is a backup pack if (!this.preserveVersion || this.withVersions) { try { // This is not a real document delete, it's a upgrade. To be sure to not // generate DELETE notification we directly use {@link XWikiStoreInterface} context.getWiki().getStore().deleteXWikiDoc(previousdoc, context); } catch (Exception e) { // let's log the error but not stop result = DocumentInfo.INSTALL_ERROR; addToErrors(doc.getFullName() + ":" + doc.getLanguage(), context); if (LOG.isErrorEnabled()) { LOG.error("Failed to delete document " + previousdoc.getDocumentReference()); } if (LOG.isDebugEnabled()) { LOG.debug("Failed to delete document " + previousdoc.getDocumentReference(), e); } } } } try { if (!backup) { doc.getDoc().setAuthor(context.getUser()); doc.getDoc().setContentAuthor(context.getUser()); // if the import is not a backup pack we set the date to now Date date = new Date(); doc.getDoc().setDate(date); doc.getDoc().setContentUpdateDate(date); } if (!this.withVersions) { doc.getDoc().setVersion("1.1"); } // Does the document to be imported already exists in the wiki ? boolean isNewDocument = previousdoc == null; // Conserve existing history only if asked for it and if this history exists boolean conserveExistingHistory = this.preserveVersion && !isNewDocument; // Does the document from the package contains history revisions ? boolean packageHasHistory = this.documentContainsHistory(doc); // Reset to initial (1.1) version when we don't want to conserve existing history and either we don't // want the package history or this latter one is empty boolean shouldResetToInitialVersion = !conserveExistingHistory && (!this.withVersions || !packageHasHistory); if (conserveExistingHistory) { // Insert the archive from the existing document doc.getDoc().setDocumentArchive(previousdoc.getDocumentArchive(context)); } else { // Reset or replace history // if there was not history in the source package then we should reset the version number to 1.1 if (shouldResetToInitialVersion) { // Make sure the save will not increment the version to 2.1 doc.getDoc().setContentDirty(false); doc.getDoc().setMetaDataDirty(false); } } // Attachment saving should not generate additional saving for (XWikiAttachment xa : doc.getDoc().getAttachmentList()) { xa.setMetaDataDirty(false); xa.getAttachment_content().setContentDirty(false); } String saveMessage = context.getMessageTool().get("core.importer.saveDocumentComment"); context.getWiki().saveDocument(doc.getDoc(), saveMessage, context); doc.getDoc().saveAllAttachments(false, true, context); addToInstalled(doc.getFullName() + ":" + doc.getLanguage(), context); if ((this.withVersions && packageHasHistory) || conserveExistingHistory) { // we need to force the saving the document archive. if (doc.getDoc().getDocumentArchive() != null) { context.getWiki().getVersioningStore().saveXWikiDocArchive( doc.getDoc().getDocumentArchive(context), true, context); } } if (shouldResetToInitialVersion) { // If we override and do not import version, (meaning reset document to 1.1) // We need manually reset possible existing revision for the document // This means making the history empty (it does not affect the version number) doc.getDoc().resetArchive(context); } } catch (XWikiException e) { addToErrors(doc.getFullName() + ":" + doc.getLanguage(), context); if (LOG.isErrorEnabled()) { LOG.error("Failed to save document " + doc.getFullName()); } if (LOG.isDebugEnabled()) { LOG.debug("Failed to save document " + doc.getFullName(), e); } result = DocumentInfo.INSTALL_ERROR; } } return result; } /** * @return true if the passed document contains a (not-empty) history of previous versions, false otherwise */ private boolean documentContainsHistory(DocumentInfo doc) { if ((doc.getDoc().getDocumentArchive() == null) || (doc.getDoc().getDocumentArchive().getNodes() == null) || (doc.getDoc().getDocumentArchive().getNodes().size() == 0)) { return false; } return true; } private List<String> getStringList(String name, XWikiContext context) { @SuppressWarnings("unchecked") List<String> list = (List<String>) context.get(name); if (list == null) { list = new ArrayList<String>(); context.put(name, list); } return list; } private void addToErrors(String fullName, XWikiContext context) { if (fullName.endsWith(":")) { fullName = fullName.substring(0, fullName.length() - 1); } getErrors(context).add(fullName); } private void addToSkipped(String fullName, XWikiContext context) { if (fullName.endsWith(":")) { fullName = fullName.substring(0, fullName.length() - 1); } getSkipped(context).add(fullName); } private void addToInstalled(String fullName, XWikiContext context) { if (fullName.endsWith(":")) { fullName = fullName.substring(0, fullName.length() - 1); } getInstalled(context).add(fullName); } private void setStatus(int status, XWikiContext context) { context.put("install_status", new Integer((status))); } public List<String> getErrors(XWikiContext context) { return getStringList("install_errors", context); } public List<String> getSkipped(XWikiContext context) { return getStringList("install_skipped", context); } public List<String> getInstalled(XWikiContext context) { return getStringList("install_installed", context); } public int getStatus(XWikiContext context) { Integer status = (Integer) context.get("install_status"); if (status == null) { return -1; } else { return status.intValue(); } } /** * Create a {@link XWikiDocument} from xml stream. * * @param is the xml stream. * @return the {@link XWikiDocument}. * @throws XWikiException error when creating the {@link XWikiDocument}. */ private XWikiDocument readFromXML(InputStream is) throws XWikiException { XWikiDocument doc = new XWikiDocument(); doc.fromXML(is, this.withVersions); return doc; } /** * Create a {@link XWikiDocument} from xml {@link Document}. * * @param domDoc the xml {@link Document}. * @return the {@link XWikiDocument}. * @throws XWikiException error when creating the {@link XWikiDocument}. */ private XWikiDocument readFromXML(Document domDoc) throws XWikiException { XWikiDocument doc = new XWikiDocument(); doc.fromXML(domDoc, this.withVersions); return doc; } /** * You should prefer {@link #toXML(com.xpn.xwiki.internal.xml.XMLWriter)}. If an error occurs, a stacktrace is dump * to logs, and an empty String is returned. * * @return a package.xml file for the this package */ public String toXml(XWikiContext context) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { toXML(baos, context); return baos.toString(context.getWiki().getEncoding()); } catch (IOException e) { e.printStackTrace(); return ""; } } public void toXML(XMLWriter wr) throws IOException { Element docel = new DOMElement("package"); wr.writeOpen(docel); Element elInfos = new DOMElement("infos"); wr.write(elInfos); Element el = new DOMElement("name"); el.addText(this.name); wr.write(el); el = new DOMElement("description"); el.addText(this.description); wr.write(el); el = new DOMElement("licence"); el.addText(this.licence); wr.write(el); el = new DOMElement("author"); el.addText(this.authorName); wr.write(el); el = new DOMElement("version"); el.addText(this.version); wr.write(el); el = new DOMElement("backupPack"); el.addText(new Boolean(this.backupPack).toString()); wr.write(el); el = new DOMElement("preserveVersion"); el.addText(new Boolean(this.preserveVersion).toString()); wr.write(el); Element elfiles = new DOMElement("files"); wr.writeOpen(elfiles); for (DocumentInfo docInfo : this.files) { Element elfile = new DOMElement("file"); elfile.addAttribute("defaultAction", String.valueOf(docInfo.getAction())); elfile.addAttribute("language", String.valueOf(docInfo.getLanguage())); elfile.addText(docInfo.getFullName()); wr.write(elfile); } } /** * Write the package.xml file to an OutputStream * * @param out the OutputStream to write to * @param context curent XWikiContext * @throws IOException when an error occurs during streaming operation * @since 2.3M2 */ public void toXML(OutputStream out, XWikiContext context) throws IOException { XMLWriter wr = new XMLWriter(out, new OutputFormat("", true, context.getWiki().getEncoding())); Document doc = new DOMDocument(); wr.writeDocumentStart(doc); toXML(wr); wr.writeDocumentEnd(doc); } /** * Write the package.xml file to a ZipOutputStream * * @param zos the ZipOutputStream to write to * @param context curent XWikiContext * @throws IOException when an error occurs during streaming operation */ private void addInfosToZip(ZipOutputStream zos, XWikiContext context) throws IOException { try { String zipname = DefaultPackageFileName; ZipEntry zipentry = new ZipEntry(zipname); zos.putNextEntry(zipentry); toXML(zos, context); zos.closeEntry(); } catch (Exception e) { e.printStackTrace(); } } /** * Generate a relative path based on provided document. * * @param doc the document to export. * @return the corresponding path. */ public String getPathFromDocument(XWikiDocument doc, XWikiContext context) { return getDirectoryForDocument(doc) + getFileNameFromDocument(doc, context); } /** * Generate a file name based on provided document. * * @param doc the document to export. * @return the corresponding file name. */ public String getFileNameFromDocument(XWikiDocument doc, XWikiContext context) { StringBuffer fileName = new StringBuffer(doc.getDocumentReference().getName()); // Add language String language = doc.getLanguage(); if ((language != null) && (!language.equals(""))) { fileName.append("."); fileName.append(language); } // Add extension fileName.append('.').append(DEFAULT_FILEEXT); return fileName.toString(); } /** * Generate a relative path based on provided document for the directory where the document should be stored. * * @param doc the document to export * @return the corresponding path */ public String getDirectoryForDocument(XWikiDocument doc) { StringBuilder path = new StringBuilder(); for (SpaceReference space : doc.getDocumentReference().getSpaceReferences()) { path.append(space.getName()).append('/'); } return path.toString(); } /** * Write an XML serialized XWikiDocument to a ZipOutputStream * * @param doc the document to serialize * @param zos the ZipOutputStream to write to * @param withVersions if true, also serialize all document versions * @param context current XWikiContext * @throws XWikiException when an error occurs during documents access * @throws IOException when an error occurs during streaming operation */ public void addToZip(XWikiDocument doc, ZipOutputStream zos, boolean withVersions, XWikiContext context) throws XWikiException, IOException { String zipname = getPathFromDocument(doc, context); doc.addToZip(zos, zipname, withVersions, context); } public void addToDir(XWikiDocument doc, File dir, boolean withVersions, XWikiContext context) throws XWikiException { try { filter(doc, context); File spacedir = new File(dir, getDirectoryForDocument(doc)); if (!spacedir.exists()) { if (!spacedir.mkdirs()) { Object[] args = new Object[1]; args[0] = dir.toString(); throw new XWikiException(XWikiException.MODULE_XWIKI, XWikiException.ERROR_XWIKI_MKDIR, "Error creating directory {0}", null, args); } } String filename = getFileNameFromDocument(doc, context); File file = new File(spacedir, filename); FileOutputStream fos = new FileOutputStream(file); doc.toXML(fos, true, false, true, withVersions, context); fos.flush(); fos.close(); } catch (ExcludeDocumentException e) { LOG.info("Skip the document " + doc.getDocumentReference()); } catch (Exception e) { Object[] args = new Object[1]; args[0] = doc.getDocumentReference(); throw new XWikiException(XWikiException.MODULE_XWIKI_DOC, XWikiException.ERROR_XWIKI_DOC_EXPORT, "Error creating file {0}", e, args); } } private void addInfosToDir(File dir, XWikiContext context) { try { String filename = DefaultPackageFileName; File file = new File(dir, filename); FileOutputStream fos = new FileOutputStream(file); toXML(fos, context); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } protected String getElementText(Element docel, String name) { Element el = docel.element(name); if (el == null) { return ""; } else { return el.getText(); } } protected Document fromXml(InputStream xml) throws DocumentException { SAXReader reader = new SAXReader(); Document domdoc = reader.read(xml); Element docEl = domdoc.getRootElement(); Element infosEl = docEl.element("infos"); this.name = getElementText(infosEl, "name"); this.description = getElementText(infosEl, "description"); this.licence = getElementText(infosEl, "licence"); this.authorName = getElementText(infosEl, "author"); this.version = getElementText(infosEl, "version"); this.backupPack = new Boolean(getElementText(infosEl, "backupPack")).booleanValue(); this.preserveVersion = new Boolean(getElementText(infosEl, "preserveVersion")).booleanValue(); return domdoc; } public void addAllWikiDocuments(XWikiContext context) throws XWikiException { XWiki wiki = context.getWiki(); try { List<String> documentNames = wiki.getStore().getQueryManager().getNamedQuery("getAllDocuments").execute(); for (String docName : documentNames) { add(docName, DocumentInfo.ACTION_OVERWRITE, context); } } catch (QueryException ex) { throw new PackageException(PackageException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH, "Cannot retrieve the list of documents to export", ex); } } public void deleteAllWikiDocuments(XWikiContext context) throws XWikiException { XWiki wiki = context.getWiki(); List<String> spaces = wiki.getSpaces(context); for (int i = 0; i < spaces.size(); i++) { List<String> docNameList = wiki.getSpaceDocsName(spaces.get(i), context); for (String docName : docNameList) { String docFullName = spaces.get(i) + "." + docName; XWikiDocument doc = wiki.getDocument(docFullName, context); wiki.deleteAllDocuments(doc, context); } } } /** * Load document files from provided directory and sub-directories into packager. * * @param dir the directory from where to load documents. * @param context the XWiki context. * @param description the package descriptor. * @return the number of loaded documents. * @throws IOException error when loading documents. * @throws XWikiException error when loading documents. */ public int readFromDir(File dir, XWikiContext context, Document description) throws IOException, XWikiException { File[] files = dir.listFiles(); SAXReader reader = new SAXReader(); int count = 0; for (int i = 0; i < files.length; ++i) { File file = files[i]; if (file.isDirectory()) { count += readFromDir(file, context, description); } else { boolean validWikiDoc = false; Document domdoc = null; try { domdoc = reader.read(new FileInputStream(file)); validWikiDoc = XWikiDocument.containsXMLWikiDocument(domdoc); } catch (DocumentException e1) { } if (validWikiDoc) { XWikiDocument doc = readFromXML(domdoc); try { filter(doc, context); if (documentExistInPackageFile(doc.getFullName(), doc.getLanguage(), description)) { add(doc, context); ++count; } else { throw new PackageException(XWikiException.ERROR_XWIKI_UNKNOWN, "document " + doc.getDocumentReference() + " does not exist in package definition"); } } catch (ExcludeDocumentException e) { LOG.info("Skip the document '" + doc.getDocumentReference() + "'"); } } else if (!file.getName().equals(DefaultPackageFileName)) { LOG.info(file.getAbsolutePath() + " is not a valid wiki document"); } } } return count; } /** * Load document files from provided directory and sub-directories into packager. * * @param dir the directory from where to load documents. * @param context the XWiki context. * @return * @throws IOException error when loading documents. * @throws XWikiException error when loading documents. */ public String readFromDir(File dir, XWikiContext context) throws IOException, XWikiException { if (!dir.isDirectory()) { throw new PackageException(PackageException.ERROR_PACKAGE_UNKNOWN, dir.getAbsolutePath() + " is not a directory"); } int count = 0; try { File infofile = new File(dir, DefaultPackageFileName); Document description = fromXml(new FileInputStream(infofile)); count = readFromDir(dir, context, description); updateFileInfos(description); } catch (DocumentException e) { throw new PackageException(PackageException.ERROR_PACKAGE_UNKNOWN, "Error when reading the XML"); } LOG.info("Package read " + count + " documents"); return ""; } /** * Outputs the content of this package in the JSON format * * @param wikiContext the XWiki context * @return a representation of this package under the JSON format * @since 2.2M1 */ public JSONObject toJSON(XWikiContext wikiContext) { Map<String, Object> json = new HashMap<String, Object>(); Map<String, Object> infos = new HashMap<String, Object>(); infos.put("name", this.name); infos.put("description", this.description); infos.put("licence", this.licence); infos.put("author", this.authorName); infos.put("version", this.version); infos.put("backup", this.isBackupPack()); Map<String, Map<String, List<Map<String, String>>>> files = new HashMap<String, Map<String, List<Map<String, String>>>>(); for (DocumentInfo docInfo : this.files) { Map<String, String> fileInfos = new HashMap<String, String>(); fileInfos.put("defaultAction", String.valueOf(docInfo.getAction())); fileInfos.put("language", String.valueOf(docInfo.getLanguage())); fileInfos.put("fullName", docInfo.getFullName()); // If the space does not exist in the map of spaces, we create it. if (files.get(docInfo.getDoc().getSpace()) == null) { files.put(docInfo.getDoc().getSpace(), new HashMap<String, List<Map<String, String>>>()); } // If the document name does not exists in the space map of docs, we create it. if (files.get(docInfo.getDoc().getSpace()).get(docInfo.getDoc().getName()) == null) { files.get(docInfo.getDoc().getSpace()).put(docInfo.getDoc().getName(), new ArrayList<Map<String, String>>()); } // Finally we add the file infos (language, fullname and action) to the list of translations // for that document. files.get(docInfo.getDoc().getSpace()).get(docInfo.getDoc().getName()).add(fileInfos); } json.put("infos", infos); json.put("files", files); JSONObject jsonObject = JSONObject.fromObject(json); return jsonObject; } }
package net.domesdaybook.matcher.singlebyte; import net.domesdaybook.reader.ByteReader; /** * An immutable {@link SingleByteMatcher} which matches a range of bytes, * or bytes outside the range if inverted. * * @author Matt Palmer * */ public final class ByteRangeMatcher extends InvertibleMatcher implements SingleByteMatcher { private final static String ILLEGAL_ARGUMENTS = "Values must be between 0 and 255 inclusive: min=%d max=%d"; private final int minByteValue; // use int as a byte is signed, but we need values from 0 to 255 private final int maxByteValue; // use int as a byte is signed, but we need values from 0 to 255 public ByteRangeMatcher(final int minValue, final int maxValue, final boolean inverted) { super(inverted); // Preconditions - minValue & maxValue >= 0 and <= 255. MinValue <= MaxValue if (minValue < 0 || minValue > 255 || maxValue < 0 || maxValue > 255 ) { final String error = String.format(ILLEGAL_ARGUMENTS, minValue, maxValue); throw new IllegalArgumentException(error); } if (minValue > maxValue) { minByteValue = maxValue; maxByteValue = minValue; } else { minByteValue = minValue; maxByteValue = maxValue; } } /** * {@inheritDoc} */ @Override public boolean matches(final ByteReader reader, final long matchFrom) { return matches(reader.readByte(matchFrom)); } /** * {@inheritDoc} */ @Override public boolean matches(final byte theByte) { final int byteValue = theByte & 0xFF; final boolean insideRange = (byteValue >= minByteValue && byteValue <= maxByteValue); return insideRange ^ inverted; } /** * {@inheritDoc} */ @Override public String toRegularExpression(final boolean prettyPrint) { final StringBuffer regularExpression = new StringBuffer(); if (prettyPrint) { regularExpression.append(" "); } regularExpression.append( "[" ); if (inverted) { regularExpression.append( "^" ); } final String minValue = ByteUtilities.byteToString(prettyPrint, minByteValue); final String maxValue = ByteUtilities.byteToString(prettyPrint, maxByteValue); regularExpression.append( String.format( "%s-%s]", minValue, maxValue )); if (prettyPrint) { regularExpression.append(" "); } return regularExpression.toString(); } /** * {@inheritDoc} */ @Override public byte[] getMatchingBytes() { byte[] values = new byte[getNumberOfMatchingBytes()]; if (inverted) { int byteIndex = 0; for (int value = 0; value < minByteValue; value++) { values[byteIndex++] = (byte) value; } for (int value = maxByteValue + 1; value < 256; value++) { values[byteIndex++] = (byte) value; } } else { int byteIndex = 0; for (int value = minByteValue; value <= maxByteValue; value++) { values[byteIndex++] = (byte) value; } } return values; } /** * {@inheritDoc} */ @Override public int getNumberOfMatchingBytes() { return inverted ? 255 - maxByteValue + minByteValue : maxByteValue - minByteValue + 1; } }
package net.ssehub.kernel_haven.util.logic; import static net.ssehub.kernel_haven.util.null_checks.NullHelpers.notNull; import java.util.function.Function; import net.ssehub.kernel_haven.util.null_checks.NonNull; /** * Static utility method for simplifying {@link Formula}s. By default, this does nothing. However, a simplifier can be * registered via {@link #setSimplifier(Function)}. * * @author Adam */ public class FormulaSimplifier { private static @NonNull Function<@NonNull Formula, @NonNull Formula> simplifier = f -> f; private static boolean deafultSimplifier = true; /** * Don't allow any instances. */ private FormulaSimplifier() { } /** * Changes the simplifier to be used. Overrides the previous one. * * @param simplifier The new simplifier to use. */ public static void setSimplifier(@NonNull Function<@NonNull Formula, @NonNull Formula> simplifier) { FormulaSimplifier.simplifier = simplifier; deafultSimplifier = false; } /** * Whether we still have the default simplifier that does nothing. * * @return <code>true</code> if we still have the default simplifier; <code>false</code> if * {@link #setSimplifier(Function)} has been called. */ public static boolean hasDefaultSimplifier() { return deafultSimplifier; } /** * Simplifies the given formula. Uses the previously set simplifier (see {@link #setSimplifier(Function)}). * * @param formula The formla to simplify. * @return The simplified formula. */ public static @NonNull Formula simplify(@NonNull Formula formula) { return notNull(simplifier.apply(formula)); } }
package org.frostbite.karren.interactions.Tags; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.frostbite.karren.Karren; import org.frostbite.karren.KarrenUtil; import org.frostbite.karren.interactions.Interaction; import org.frostbite.karren.interactions.Tag; import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent; import sx.blah.discord.handle.obj.Permissions; import sx.blah.discord.util.MessageBuilder; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.EnumSet; import java.util.Optional; public class Battlegrounds extends Tag { @Override public String handleTemplate(String msg, Interaction interaction, MessageBuilder response, MessageReceivedEvent event) { SSLContext sc; if(!interaction.hasParameter()) return interaction.getRandomTemplate("noparam").getTemplate(); String parameter = interaction.getParameter(); String[] params = parameter.split(","); if(params.length>1) { JsonParser json = new JsonParser(); try { sc = SSLContext.getInstance("SSL"); sc.init(null, KarrenUtil.trustAllCertificates, new SecureRandom()); HttpsURLConnection profileRequest = (HttpsURLConnection) new URL("https://pubgtracker.com/api/profile/pc/" + params[0].trim()).openConnection(); profileRequest.setSSLSocketFactory(sc.getSocketFactory()); profileRequest.setRequestProperty("TRN-Api-Key", Karren.conf.getTrackerNetworkAPIKey()); profileRequest.connect(); JsonObject profileData = json.parse(new InputStreamReader((InputStream) profileRequest.getContent())).getAsJsonObject(); JsonObject selectedSeason = null; for (JsonElement jsonElement : profileData.get("Stats").getAsJsonArray()) { if (jsonElement.getAsJsonObject().get("Region").getAsString().equalsIgnoreCase("na") && jsonElement.getAsJsonObject().get("Season").getAsString().equalsIgnoreCase(profileData.get("defaultSeason").getAsString()) && jsonElement.getAsJsonObject().get("Match").getAsString().equalsIgnoreCase(params[1].trim())) { selectedSeason = jsonElement.getAsJsonObject(); break; } } ArrayList<JsonObject> statsArrayList = new ArrayList<>(); if (selectedSeason != null) for (JsonElement jsonObject : selectedSeason.get("Stats").getAsJsonArray()) statsArrayList.add(jsonObject.getAsJsonObject()); msg = msg.replace("%username", profileData.get("PlayerName").getAsString()); msg = msg.replace("%kills", getValueFromJson("Kills", statsArrayList)); msg = msg.replace("%rating", getValueFromJson("Rating", statsArrayList)); msg = msg.replace("%roundsPlayed", getValueFromJson("RoundsPlayed", statsArrayList)); msg = msg.replace("%kdr", getValueFromJson("KillDeathRatio", statsArrayList)); msg = msg.replace("%top10s", getValueFromJson("Top10s", statsArrayList)); msg = msg.replace("%wins", getValueFromJson("Wins", statsArrayList)); msg = msg.replace("%losses", getValueFromJson("Losses", statsArrayList)); } catch (NoSuchAlgorithmException | IOException | KeyManagementException e) { return interaction.getRandomTemplate("fail").getTemplate(); } } else { msg = interaction.getRandomTemplate("noparam").getTemplate(); } return msg; } @Override public String getTagName() { return "battlegrounds"; } @Override public EnumSet<Permissions> getRequiredPermissions() { EnumSet<Permissions> requiredPerms = EnumSet.of(Permissions.SEND_MESSAGES); return requiredPerms; } private String getValueFromJson(String target, ArrayList<JsonObject> statsArrayList){ Optional<JsonObject> object = statsArrayList.stream().filter(x -> x.get("field").getAsString().equalsIgnoreCase(target)).findFirst(); return object.map(jsonObject -> jsonObject.get("value").getAsString()).orElse("0"); } }
package org.jitsi.impl.osgi.framework.launch; import java.util.*; import java.util.concurrent.*; import net.java.sip.communicator.util.*; import org.jitsi.impl.osgi.framework.*; import org.osgi.framework.*; /** * * @author Lyubomir Marinov */ public class EventDispatcher { private static final Logger logger = Logger.getLogger(EventDispatcher.class); private final AsyncExecutor<Command> executor = new AsyncExecutor<Command>(); private final EventListenerList listeners = new EventListenerList(); public <T extends EventListener> boolean addListener( Bundle bundle, Class<T> clazz, T listener) { return listeners.add(bundle, clazz, listener); } void fireBundleEvent(BundleEvent event) { fireEvent(BundleListener.class, event); } private <T extends EventListener> void fireEvent( Class<T> clazz, EventObject event) { T[] listeners = this.listeners.getListeners(clazz); if (listeners.length != 0) try { executor.execute(new Command(clazz, listeners, event)); } catch (RejectedExecutionException ree) { logger.error("Error firing event", ree); } } void fireServiceEvent(ServiceEvent event) { fireEvent(ServiceListener.class, event); } public <T extends EventListener> boolean removeListener( Bundle bundle, Class<T> clazz, T listener) { return listeners.remove(bundle, clazz, listener); } public boolean removeListeners(Bundle bundle) { return listeners.removeAll(bundle); } public void stop() { executor.shutdownNow(); } private class Command implements Runnable { private final Class<? extends EventListener> clazz; private final EventObject event; private final EventListener[] listeners; public <T extends EventListener> Command( Class<T> clazz, T[] listeners, EventObject event) { this.clazz = clazz; this.listeners = listeners; this.event = event; } public void run() { for (EventListener listener : listeners) { try { if (BundleListener.class.equals(clazz)) { ((BundleListener) listener).bundleChanged( (BundleEvent) event); } else if (ServiceListener.class.equals(clazz)) { ((ServiceListener) listener).serviceChanged( (ServiceEvent) event); } } catch (Throwable t) { logger.error("Error dispatching event", t); if (FrameworkListener.class.equals(clazz) && ((FrameworkEvent) event).getType() != FrameworkEvent.ERROR) { // TODO Auto-generated method stub } } } } } }
package org.objectweb.proactive.core.body.rmi; import java.rmi.RemoteException; import org.objectweb.proactive.core.UniqueID; import org.objectweb.proactive.core.body.UniversalBody; import org.objectweb.proactive.core.body.reply.Reply; import org.objectweb.proactive.core.body.request.Request; import org.objectweb.proactive.core.rmi.RandomPortSocketFactory; /** * An adapter for a LocalBody to be able to receive remote calls. This helps isolate RMI-specific * code into a small set of specific classes, thus enabling reuse if we one day decide to switch * to anothe remote objects library. */ public class RemoteBodyImpl extends java.rmi.server.UnicastRemoteObject implements RemoteBody, java.rmi.server.Unreferenced { /** * A custom socket Factory */ protected static RandomPortSocketFactory factory = new RandomPortSocketFactory(37002, 5000); /** * The encapsulated local body * transient to deal with custom serialization of requests. */ protected transient UniversalBody body; public RemoteBodyImpl() throws RemoteException { } public RemoteBodyImpl(UniversalBody body) throws RemoteException { // super(0, factory, factory); this.body = body; } public void receiveRequest(Request r) throws java.io.IOException { // System.out.println("RemoteBodyImpl: receiveRequest() for " + this.localBody); // System.out.println("RemoteBodyImpl: receiveRequest() request is " + r.getMethodName()); body.receiveRequest(r); } public void receiveReply(Reply r) throws java.io.IOException { body.receiveReply(r); } public String getNodeURL() { return body.getNodeURL(); } public UniqueID getID() { return body.getID(); } public void updateLocation(UniqueID id, UniversalBody remoteBody) throws java.io.IOException { body.updateLocation(id, remoteBody); } public void unreferenced() { // System.out.println("RemoteBodyImpl: unreferenced()"); System.gc(); } public void enableAC() throws java.io.IOException { body.enableAC(); } public void disableAC() throws java.io.IOException { body.disableAC(); } public void setImmediateService (String methodName) throws java.io.IOException { body.setImmediateService(methodName); } /* private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { long startTime=System.currentTimeMillis(); out.defaultWriteObject(); long endTime=System.currentTimeMillis(); System.out.println(" SERIALIZATION OF REMOTEBODYIMPL lasted " + (endTime - startTime)); } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { in.defaultReadObject(); } */ }
package org.usfirst.frc4909.STEAMWORKS.commands; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc4909.STEAMWORKS.Robot; public class DriveCommand extends Command { public DriveCommand() { requires(Robot.drivetrain); } protected void initialize() {} protected void execute() { Robot.drivetrain.moveTank(); } protected boolean isFinished() { return false; } protected void end() { Robot.drivetrain.stop(); } protected void interrupted() { end(); } }
import implementation.PhaseOneImpl; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * implementation.PhaseOneImpl Tester. * * @author GeoffreyC * @version 1.0 * @since <pre>Jan 30, 2017</pre> */ public class PhaseOneImplTest { PhaseOneImpl phaseOne; @Before public void before() throws Exception { phaseOne = new PhaseOneImpl(); } @After public void after() throws Exception { } /** * Method: MoveForward() */ @Test public void testMoveForwardOnce() throws Exception { int i = phaseOne.whereIs(); phaseOne.moveForward(); Assert.assertEquals(i + 1, phaseOne.whereIs()); } /** * Method MoveForward() * Move 500 times, * * @throws Exception */ @Test public void testMoveForwardOOB() throws Exception { int i = phaseOne.whereIs(); for (int j = 0; j < 501; j++) { phaseOne.moveForward(); } Assert.assertEquals(500, phaseOne.whereIs()); } /** * Method: MoveBackward() */ @Test public void testMoveBackwardOnce() throws Exception { phaseOne.moveBackward(); Assert.assertEquals(0, phaseOne.whereIs()); } @Test public void testMoveBackwardOOB() throws Exception { int i = phaseOne.whereIs(); phaseOne.moveBackward(); Assert.assertEquals(0, phaseOne.whereIs()); } /** * Method: Park() */ @Test public void testPark() throws Exception { //TODO: Test goes here... } /** * Method: unPark() */ @Test public void testUnPark() throws Exception { //TODO: Test goes here... } /** * Method: Wherels() */ @Test public void testWhereIs() throws Exception { Assert.assertEquals(0, phaseOne.whereIs()); } /** * Method: isEmpty() */ @Test public void testIsEmpty() throws Exception { //Assert.assertEquals(phaseOne.isEmpty(), false); //Assert.assertEquals(instanceOf(Number.class),phaseOne.isEmpty()); Assert.assertEquals(1, phaseOne.isEmpty()); } }
package peergos.server.tests.simulation; import peergos.server.simulation.AccessControl; import peergos.server.simulation.FileSystem; import peergos.server.simulation.Stat; import peergos.shared.user.fs.FileProperties; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.*; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.stream.Collectors; public class NativeFileSystemImpl implements FileSystem { private final Path root; private final String user; private final AccessControl accessControl; public NativeFileSystemImpl(Path root, String user, AccessControl accessControl) { this.root = root; this.user = user; this.accessControl = accessControl; init(); } private void init() { Path userRoot = Paths.get("/" + user); for (Path path : Arrays.asList( userRoot // , sharedRoot, // peergosShare )) { mkdir(path); } } @Override public String user() { return user; } private void ensureCan(Path path, Permission permission) { ensureCan(path, permission, user()); } private void ensureCan(Path path, Permission permission, String user) { Path nativePath = virtualToNative(path); if (! Files.exists(nativePath) && permission == Permission.READ) throw new IllegalStateException("Cannot read "+ path +" : native file "+ nativePath + " does not exist."); if (! accessControl.can(path, user, permission)) throw new IllegalStateException("User " + user() +" not permitted to "+ permission + " " + path); } @Override public byte[] read(Path path, BiConsumer<Long, Long> pc) { Path nativePath = virtualToNative(path); ensureCan(path, Permission.READ); try { return Files.readAllBytes(nativePath); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } @Override public void write(Path path, byte[] data, Consumer<Long> progressConsumer) { Path nativePath = virtualToNative(path); ensureCan(path.getParent(), Permission.READ); ensureCan(path, Permission.WRITE); try { Files.write(nativePath, data); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } @Override public void delete(Path path) { ensureCan(path, Permission.WRITE); walk(path, p -> { try { Files.delete(virtualToNative(p)); } catch (IOException ioe) { throw new IllegalStateException(ioe); } accessControl.remove(p); }); } private boolean isOwner(Path path) { return user().equals(AccessControl.getOwner(path)); } @Override public void grant(Path path, String otherUser, FileSystem.Permission permission) { if (! isOwner(path)) throw new IllegalStateException(); accessControl.add(path, otherUser, permission); } @Override public void revoke(Path path, String user, FileSystem.Permission permission) { if (! isOwner(path)) throw new IllegalStateException(); accessControl.remove(path, user, permission); } @Override public Stat stat(Path path) { return new Stat() { @Override public String user() { return user; } @Override public FileProperties fileProperties() { File file = virtualToNative(path).toFile(); long length = file.length(); file.lastModified(); if (Integer.MAX_VALUE < length) throw new IllegalStateException("Large files not supported"); int sizeLo = (int) length; int sizeHi = 0; LocalDateTime lastModified = LocalDateTime.ofInstant(Instant.ofEpochSecond(file.lastModified() / 1000), ZoneOffset.systemDefault()); // These things are a bit awkward, not supporting them for now Optional<byte[]> thumbnail = Optional.empty(); boolean isHidden = false; String mimeType="NOT_SUPPORTED"; //TODO make files use the new format with a stream secret Optional<byte[]> streamSecret = file.isDirectory() ? Optional.empty() : Optional.empty(); return new FileProperties(file.getName(), file.isDirectory(), false, mimeType, sizeHi, sizeLo, lastModified, isHidden, thumbnail, streamSecret); } @Override public boolean isReadable() { return accessControl.can(path, user(), Permission.READ); } @Override public boolean isWritable() { return accessControl.can(path, user(), Permission.WRITE); } }; } private Path virtualToNative(Path path) { Path relativePath = Paths.get("/").relativize(path); return Paths.get(root.toString(), relativePath.toString()); } @Override public void mkdir(Path path) { if (! path.equals(Paths.get("/"+ user()))) { Path parentDir = path.getParent(); ensureCan(parentDir, Permission.WRITE); } Path nativePath = virtualToNative(path); boolean mkdir = nativePath.toFile().mkdir(); if (! mkdir) throw new IllegalStateException("Could not make dir "+ nativePath); } @Override public List<Path> ls(Path path, boolean showHidden) { ensureCan(path, Permission.READ); if (! showHidden) throw new IllegalStateException(); Path nativePath = virtualToNative(path); try { return Files.list(nativePath) .map(e -> path.resolve(e.getFileName().toString())) .collect(Collectors.toList()); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } public static void main(String[] args) { System.out.println("HELO"); Path p1 = Paths.get("/something/else"); Path p2 = Paths.get("/another/thing"); Path p3 = Paths.get("/").relativize(p2); Path p4 = Paths.get(p1.toString(), p3.toString()); System.out.println(p4); Path p5 = Paths.get("/some/thing/else"); System.out.println(p5.getName(1)); } @Override public void follow(FileSystem other, boolean reciprocate) { return; // this isn't being tested... yet } @Override public Path getRandomSharedPath(Random random, Permission permission, String sharee) { return accessControl.getRandomSharedPath(random, permission, sharee); } @Override public List<String> getSharees(Path path, Permission permission) { return accessControl.get(path, permission); } }