answer
stringlengths
17
10.2M
package org.apache.velocity.test; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Hashtable; import java.util.HashMap; import java.util.Vector; import org.apache.velocity.VelocityContext; import org.apache.velocity.Template; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.test.provider.TestProvider; import org.apache.velocity.util.StringUtils; import org.apache.velocity.app.FieldMethodizer; import junit.framework.TestCase; import org.apache.oro.text.perl.Perl5Util; /** * Base test case that provides a few utility methods for * the rest of the tests. * * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a> * @version $Id: BaseTestCase.java,v 1.10 2001/03/23 15:59:17 geirm Exp $ */ public class BaseTestCase extends TestCase { /** * used for nomalization of output and compare data */ private Perl5Util perl = new Perl5Util(); /** * Default constructor. */ public BaseTestCase(String name) { super(name); } /** * Concatenates the file name parts together appropriately. * * @return The full path to the file. */ protected static String getFileName (String dir, String base, String ext) { StringBuffer buf = new StringBuffer(); if (dir != null) { buf.append(dir).append('/'); } buf.append(base).append('.').append(ext); return buf.toString(); } /** * Assures that the results directory exists. If the results directory * cannot be created, fails the test. */ protected static void assureResultsDirectoryExists (String resultsDirectory) { File dir = new File(resultsDirectory); if (!dir.exists()) { Runtime.info("Template results directory does not exist"); if (dir.mkdirs()) { Runtime.info("Created template results directory"); } else { String errMsg = "Unable to create template results directory"; Runtime.warn(errMsg); fail(errMsg); } } } /** * Normalizes lines to account for platform differences. Macs use * a single \r, DOS derived operating systems use \r\n, and Unix * uses \n. Replace each with a single \n. * * @author <a href="mailto:rubys@us.ibm.com">Sam Ruby</a> * @return source with all line terminations changed to Unix style */ protected String normalizeNewlines (String source) { return perl.substitute("s/\r[\n]/\n/g", source); } /** * Returns whether the processed template matches the * content of the provided comparison file. * * @return Whether the output matches the contents * of the comparison file. * * @exception Exception Test failure condition. */ protected boolean isMatch (String resultsDir, String compareDir, String baseFileName, String resultExt, String compareExt) throws Exception { String result = StringUtils.fileContentsToString (getFileName(resultsDir, baseFileName, resultExt)); String compare = StringUtils.fileContentsToString (getFileName(compareDir, baseFileName, compareExt)); /* * normalize each wrt newline */ return normalizeNewlines(result).equals( normalizeNewlines( compare ) ); } /** * Turns a base file name into a test case name. * * @param s The base file name. * @return The test case name. */ protected static final String getTestCaseName (String s) { StringBuffer name = new StringBuffer(); name.append(Character.toTitleCase(s.charAt(0))); name.append(s.substring(1, s.length()).toLowerCase()); return name.toString(); } }
package org.jivesoftware.spark.ui; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.spark.component.WrappedLabel; import org.jivesoftware.spark.component.borders.PartialLineBorder; import org.jivesoftware.spark.util.GraphicUtils; import org.jivesoftware.spark.util.log.Log; import org.jivesoftware.sparkimpl.plugin.gateways.transports.Transport; import org.jivesoftware.sparkimpl.plugin.gateways.transports.TransportUtils; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.net.MalformedURLException; import java.net.URL; /** * Represents the UI for the "ToolTip" functionallity in the ContactList. * * @author Derek DeMoro */ public class ContactInfo extends JPanel { private final WrappedLabel nicknameLabel = new WrappedLabel(); private final WrappedLabel statusLabel = new WrappedLabel(); private final JLabel fullJIDLabel = new JLabel(); private final JLabel imageLabel = new JLabel(); public ContactInfo() { setLayout(new GridBagLayout()); setBackground(Color.white); add(nicknameLabel, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 5), 0, 0)); add(statusLabel, new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(0, 2, 5, 5), 0, 0)); add(fullJIDLabel, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0)); add(imageLabel, new GridBagConstraints(1, 0, 1, 2, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 0, 5, 5), 0, 0)); nicknameLabel.setFont(new Font("Dialog", Font.BOLD, 12)); statusLabel.setFont(new Font("Dialog", Font.PLAIN, 12)); statusLabel.setForeground(Color.gray); fullJIDLabel.setFont(new Font("Dialog", Font.PLAIN, 12)); fullJIDLabel.setForeground(Color.gray); nicknameLabel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.gray)); fullJIDLabel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.gray)); setBorder(BorderFactory.createEtchedBorder()); } public void setContactItem(ContactItem contactItem) { nicknameLabel.setText(contactItem.getNickname()); statusLabel.setText(contactItem.getStatus()); Transport transport = TransportUtils.getTransport(StringUtils.parseServer(contactItem.getFullJID())); if (transport != null) { fullJIDLabel.setIcon(transport.getIcon()); String name = StringUtils.parseName(contactItem.getFullJID()); fullJIDLabel.setText(transport.getName() + " - " + name); } else { fullJIDLabel.setText(contactItem.getFullJID()); fullJIDLabel.setIcon(null); } imageLabel.setBorder(null); try { URL avatarURL = contactItem.getAvatarURL(); ImageIcon icon = null; if (avatarURL != null) { icon = new ImageIcon(avatarURL); } if (icon != null && icon.getIconHeight() > 1) { icon = GraphicUtils.scaleImageIcon(icon, 96, 96); imageLabel.setIcon(icon); imageLabel.setBorder(new PartialLineBorder(Color.gray, 1)); } else { icon = new ImageIcon(SparkRes.getImageIcon(SparkRes.BLANK_24x24).getImage().getScaledInstance(1, 64, Image.SCALE_SMOOTH)); imageLabel.setIcon(icon); } } catch (MalformedURLException e) { Log.error(e); } } public Dimension getPreferredSize() { final Dimension size = super.getPreferredSize(); size.width = 250; return size; } }
package org.jivesoftware.wildfire.group; import org.jivesoftware.database.DbConnectionManager; import org.jivesoftware.wildfire.XMPPServer; import org.jivesoftware.wildfire.event.GroupEventDispatcher; import org.jivesoftware.util.CacheSizes; import org.jivesoftware.util.Cacheable; import org.jivesoftware.util.Log; import org.xmpp.packet.JID; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * Groups organize users into a single entity for easier management. * * @see GroupManager#createGroup(String) * * @author Matt Tucker */ public class Group implements Cacheable { private static final String LOAD_PROPERTIES = "SELECT name, propValue FROM jiveGroupProp WHERE groupName=?"; private static final String DELETE_PROPERTY = "DELETE FROM jiveGroupProp WHERE groupName=? AND name=?"; private static final String UPDATE_PROPERTY = "UPDATE jiveGroupProp SET propValue=? WHERE name=? AND groupName=?"; private static final String INSERT_PROPERTY = "INSERT INTO jiveGroupProp (groupName, name, propValue) VALUES (?, ?, ?)"; private GroupProvider provider; private GroupManager groupManager; private String name; private String description; private Map<String, String> properties; private Set<JID> members; private Set<JID> administrators; /** * Constructs a new group. Note: this constructor is intended for implementors of the * {@link GroupProvider} interface. To create a new group, use the * {@link GroupManager#createGroup(String)} method. * * @param provider the group provider. * @param name the name. * @param description the description. * @param members a Collection of the group members. * @param administrators a Collection of the group administrators. */ public Group(GroupProvider provider, String name, String description, Collection<JID> members, Collection<JID> administrators) { this.provider = provider; this.groupManager = GroupManager.getInstance(); this.name = name; this.description = description; this.members = new HashSet<JID>(members); this.administrators = new HashSet<JID>(administrators); } /** * Returns the name of the group. For example, 'XYZ Admins'. * * @return the name of the group. */ public String getName() { return name; } public void setName(String name) { try { String originalName = this.name; provider.setName(this.name, name); groupManager.groupCache.remove(this.name); this.name = name; groupManager.groupCache.put(name, this); // Fire event. Map<String, Object> params = new HashMap<String, Object>(); params.put("type", "nameModified"); params.put("originalValue", originalName); GroupEventDispatcher.dispatchEvent(this, GroupEventDispatcher.EventType.group_modified, params); } catch (Exception e) { Log.error(e); } } /** * Returns the description of the group. The description often * summarizes a group's function, such as 'Administrators of the XYZ forum'. * * @return the description of the group. */ public String getDescription() { return description; } public void setDescription(String description) { try { String originalDescription = this.description; provider.setDescription(name, description); this.description = description; // Fire event. Map<String, Object> params = new HashMap<String, Object>(); params.put("type", "descriptionModified"); params.put("originalValue", originalDescription); GroupEventDispatcher.dispatchEvent(this, GroupEventDispatcher.EventType.group_modified, params); } catch (Exception e) { Log.error(e); } } public String toString() { return name; } /** * Returns all extended properties of the group. Groups * have an arbitrary number of extended properties. * * @return the extended properties. */ public Map<String,String> getProperties() { synchronized (this) { if (properties == null) { properties = new ConcurrentHashMap<String, String>(); loadProperties(); } } // Return a wrapper that will intercept add and remove commands. return new PropertiesMap(); } /** * Returns a Collection of the group administrators. * * @return a Collection of the group administrators. */ public Collection<JID> getAdmins() { // Return a wrapper that will intercept add and remove commands. return new MemberCollection(administrators, true); } /** * Returns a Collection of the group members. * * @return a Collection of the group members. */ public Collection<JID> getMembers() { // Return a wrapper that will intercept add and remove commands. return new MemberCollection(members, false); } /** * Returns true if the provided username belongs to a user that is part of the group. * * @param user the JID address of the user to check. * @return true if the specified user is a group user. */ public boolean isUser(JID user) { return user != null && (members.contains(user) || administrators.contains(user)); } /** * Returns true if the provided username belongs to a user of the group. * * @param username the username to check. * @return true if the provided username belongs to a user of the group. */ public boolean isUser(String username) { if (username != null) { return isUser(XMPPServer.getInstance().createJID(username, null)); } else { return false; } } public int getCachedSize() { // Approximate the size of the object in bytes by calculating the size // of each field. int size = 0; size += CacheSizes.sizeOfObject(); // overhead of object size += CacheSizes.sizeOfString(name); size += CacheSizes.sizeOfString(description); return size; } public int hashCode() { return name.hashCode(); } public boolean equals(Object object) { if (this == object) { return true; } if (object != null && object instanceof Group) { return name.equals(((Group)object).getName()); } else { return false; } } /** * Collection implementation that notifies the GroupProvider of any * changes to the collection. */ private class MemberCollection extends AbstractCollection { private Collection<JID> users; private boolean adminCollection; public MemberCollection(Collection<JID> users, boolean adminCollection) { this.users = users; this.adminCollection = adminCollection; } public Iterator<JID> iterator() { return new Iterator() { Iterator<JID> iter = users.iterator(); Object current = null; public boolean hasNext() { return iter.hasNext(); } public Object next() { current = iter.next(); return current; } public void remove() { if (current == null) { throw new IllegalStateException(); } JID user = (JID)current; // Remove the user from the collection in memory. iter.remove(); // Remove the group user from the backend store. provider.deleteMember(name, user); // Fire event. if (adminCollection) { Map<String, String> params = new HashMap<String, String>(); params.put("admin", user.toString()); GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.admin_removed, params); } else { Map<String, String> params = new HashMap<String, String>(); params.put("member", user.toString()); GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.member_removed, params); } } }; } public int size() { return users.size(); } public boolean add(Object member) { JID user = (JID) member; // Find out if the user was already a group user boolean alreadyGroupUser = false; if (adminCollection) { alreadyGroupUser = members.contains(user); } else { alreadyGroupUser = administrators.contains(user); } if (users.add(user)) { if (alreadyGroupUser) { // Update the group user privileges in the backend store. provider.updateMember(name, user, adminCollection); } else { // Add the group user to the backend store. provider.addMember(name, user, adminCollection); } // Fire event. if (adminCollection) { Map<String, String> params = new HashMap<String, String>(); params.put("admin", user.toString()); if (alreadyGroupUser) { GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.member_removed, params); } GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.admin_added, params); } else { Map<String, String> params = new HashMap<String, String>(); params.put("member", user.toString()); if (alreadyGroupUser) { GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.admin_removed, params); } GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.member_added, params); } // If the user was a member that became an admin or vice versa then remove the // user from the other collection if (alreadyGroupUser) { if (adminCollection) { if (members.contains(user)) { members.remove(user); } } else { if (administrators.contains(user)) { administrators.remove(user); } } } return true; } return false; } } /** * Map implementation that updates the database when properties are modified. */ private class PropertiesMap extends AbstractMap { public Object put(Object key, Object value) { if (key == null || value == null) { throw new NullPointerException(); } Map<String, Object> eventParams = new HashMap<String, Object>(); Object answer; String keyString = (String) key; synchronized (keyString.intern()) { if (properties.containsKey(keyString)) { String originalValue = properties.get(keyString); answer = properties.put(keyString, (String)value); updateProperty(keyString, (String)value); // Configure event. eventParams.put("type", "propertyModified"); eventParams.put("propertyKey", key); eventParams.put("originalValue", originalValue); } else { answer = properties.put(keyString, (String)value); insertProperty(keyString, (String)value); // Configure event. eventParams.put("type", "propertyAdded"); eventParams.put("propertyKey", key); } } // Fire event. GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.group_modified, eventParams); return answer; } public Set<Entry> entrySet() { return new PropertiesEntrySet(); } } /** * Set implementation that updates the database when properties are deleted. */ private class PropertiesEntrySet extends AbstractSet { public int size() { return properties.entrySet().size(); } public Iterator iterator() { return new Iterator() { Iterator iter = properties.entrySet().iterator(); Map.Entry current = null; public boolean hasNext() { return iter.hasNext(); } public Object next() { current = (Map.Entry)iter.next(); return current; } public void remove() { if (current == null) { throw new IllegalStateException(); } String key = (String)current.getKey(); deleteProperty(key); iter.remove(); // Fire event. Map<String, Object> params = new HashMap<String, Object>(); params.put("type", "propertyDeleted"); params.put("propertyKey", key); GroupEventDispatcher.dispatchEvent(Group.this, GroupEventDispatcher.EventType.group_modified, params); } }; } } private void loadProperties() { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(LOAD_PROPERTIES); pstmt.setString(1, name); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { String key = rs.getString(1); String value = rs.getString(2); if (key != null) { if (value == null) { value = ""; Log.warn("There is a group property whose value is null of Group: " + name); } properties.put(key, value); } else { Log.warn("There is a group property whose key is null of Group: " + name); } } rs.close(); } catch (SQLException sqle) { Log.error(sqle); } finally { try { if (pstmt != null) pstmt.close(); } catch (Exception e) { Log.error(e); } try { if (con != null) con.close(); } catch (Exception e) { Log.error(e); } } } private void insertProperty(String propName, String propValue) { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(INSERT_PROPERTY); pstmt.setString(1, name); pstmt.setString(2, propName); pstmt.setString(3, propValue); pstmt.executeUpdate(); } catch (SQLException e) { Log.error(e); } finally { try { if (pstmt != null) pstmt.close(); } catch (Exception e) { Log.error(e); } try { if (con != null) con.close(); } catch (Exception e) { Log.error(e); } } } private void updateProperty(String propName, String propValue) { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(UPDATE_PROPERTY); pstmt.setString(1, propValue); pstmt.setString(2, propName); pstmt.setString(3, name); pstmt.executeUpdate(); } catch (SQLException e) { Log.error(e); } finally { try { if (pstmt != null) pstmt.close(); } catch (Exception e) { Log.error(e); } try { if (con != null) con.close(); } catch (Exception e) { Log.error(e); } } } private void deleteProperty(String propName) { Connection con = null; PreparedStatement pstmt = null; try { con = DbConnectionManager.getConnection(); pstmt = con.prepareStatement(DELETE_PROPERTY); pstmt.setString(1, name); pstmt.setString(2, propName); pstmt.executeUpdate(); } catch (SQLException e) { Log.error(e); } finally { try { if (pstmt != null) pstmt.close(); } catch (Exception e) { Log.error(e); } try { if (con != null) con.close(); } catch (Exception e) { Log.error(e); } } } }
package org.opentdc.resources; import java.util.List; import org.opentdc.service.exception.*; public interface ServiceProvider { public abstract List<ResourceModel> listResources( String queryType, String query, int position, int size ); public abstract ResourceModel createResource( ResourceModel resource) throws DuplicateException, ValidationException; public abstract ResourceModel readResource( String id) throws NotFoundException; public abstract ResourceModel updateResource( String id, ResourceModel resource) throws NotFoundException, ValidationException; public abstract void deleteResource( String id) throws NotFoundException, InternalServerErrorException; }
package org.helioviewer.jhv.base.math; public class Vec3 { /** * Predefined Vectors */ public static final Vec3 ZERO = new Vec3(0, 0, 0); public static final Vec3 XAxis = new Vec3(1, 0, 0); public static final Vec3 YAxis = new Vec3(0, 1, 0); public static final Vec3 ZAxis = new Vec3(0, 0, 1); /** * Coordinates */ public double x; public double y; public double z; // Constructors public Vec3(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public Vec3(Vec2 vector) { this.x = vector.x; this.y = vector.y; this.z = 0; } public Vec3(Vec3 vector) { this.x = vector.x; this.y = vector.y; this.z = vector.z; } public Vec3() { this(Vec3.ZERO); } public Vec3(double[] coordinates) { if (coordinates == null || coordinates.length < 3) { throw new IllegalArgumentException("Coordinate Array must contain at least 3 dimensions"); } this.x = coordinates[0]; this.y = coordinates[1]; this.z = coordinates[2]; } public final void set(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public final void set(Vec3 vector) { this.x = vector.x; this.y = vector.y; this.z = vector.z; } public final void setMax(Vec3 vector) { this.x = this.x > vector.x ? this.x : vector.x; this.y = this.y > vector.y ? this.y : vector.y; this.z = this.z > vector.z ? this.z : vector.z; } public final void setMin(Vec3 vector) { this.x = this.x < vector.x ? this.x : vector.x; this.y = this.y < vector.y ? this.y : vector.y; this.z = this.z < vector.z ? this.z : vector.z; } public final void add(Vec3 vec) { this.x += vec.x; this.y += vec.y; this.z += vec.z; } public final void add(double s) { this.x += s; this.y += s; this.z += s; } public final static Vec3 add(Vec3 vec1, Vec3 vec2) { return new Vec3(vec1.x + vec2.x, vec1.y + vec2.y, vec1.z + vec2.z); } public final static Vec3 add(Vec3 vec1, double s) { return new Vec3(vec1.x + s, vec1.y + s, vec1.z + s); } public final Vec3 subtract(Vec3 vec) { this.x -= vec.x; this.y -= vec.y; this.z -= vec.z; return this; } public final void subtract(double s) { this.x -= s; this.y -= s; this.z -= s; } public final static Vec3 subtract(Vec3 vec1, Vec3 vec2) { return new Vec3(vec1.x - vec2.x, vec1.y - vec2.y, vec1.z - vec2.z); } public final static Vec3 subtract(Vec3 vec1, double s) { return new Vec3(vec1.x - s, vec1.y - s, vec1.z - s); } public final void divide(Vec3 vec) { if (vec.x == 0.0 || vec.y == 0.0 || vec.z == 0.0) throw new IllegalArgumentException("Division by 0 not allowed!"); this.x /= vec.x; this.y /= vec.y; this.z /= vec.z; } public final void divide(double s) { if (s == 0.0) throw new IllegalArgumentException("Division by 0 not allowed!"); this.x /= s; this.y /= s; this.z /= s; } public final static Vec3 divide(Vec3 vec1, Vec3 vec2) { if (vec2.x == 0.0 || vec2.y == 0.0 || vec2.z == 0.0) throw new IllegalArgumentException("Division by 0 not allowed!"); return new Vec3(vec1.x / vec2.x, vec1.y / vec2.y, vec1.z / vec2.z); } public final static Vec3 divide(Vec3 vec1, double s) { if (s == 0.0) throw new IllegalArgumentException("Division by 0 not allowed!"); return new Vec3(vec1.x / s, vec1.y / s, vec1.z / s); } public final void multiply(Vec3 vec) { this.x *= vec.x; this.y *= vec.y; this.z *= vec.z; } public final void multiply(double s) { this.x *= s; this.y *= s; this.z *= s; } public final static Vec3 multiply(Vec3 vec1, Vec3 vec2) { return new Vec3(vec1.x * vec2.x, vec1.y * vec2.y, vec1.z * vec2.z); } public final static Vec3 multiply(Vec3 vec1, double s) { return new Vec3(vec1.x * s, vec1.y * s, vec1.z * s); } public final double dot(Vec3 vec) { return Vec3.dot(this, vec); } public final static double dot(Vec3 u, Vec3 v) { return (u.x * v.x) + (u.y * v.y) + (u.z * v.z); } public final Vec3 cross(Vec3 vec) { return Vec3.cross(this, vec); } public final static Vec3 cross(Vec3 u, Vec3 v) { return new Vec3(u.y * v.z - u.z * v.y, u.z * v.x - u.x * v.z, u.x * v.y - u.y * v.x); } public final void negate() { this.x = -this.x; this.y = -this.y; this.z = -this.z; } public final static Vec3 negate(Vec3 vec) { Vec3 vecCopy = vec.copy(); vecCopy.negate(); return vecCopy; } public final boolean isApproxEqual(Vec3 vec, double tolerance) { return Math.abs(this.x - vec.x) <= tolerance && Math.abs(this.y - vec.y) <= tolerance && Math.abs(this.z - vec.z) <= tolerance; } public final double length() { double absmax = Math.max(Math.max(Math.abs(this.x), Math.abs(this.y)), Math.abs(this.z)); if (absmax == 0.0) return 0.0; double tmpx = this.x / absmax; double tmpy = this.y / absmax; double tmpz = this.z / absmax; return absmax * Math.sqrt(tmpx * tmpx + tmpy * tmpy + tmpz * tmpz); } public final double length2() { double len = length(); return len * len; } public final void normalize() { double len = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); if (len == 0.0) return; this.x /= len; this.y /= len; this.z /= len; len = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); if (len <= 1.0) return; // errors up to 2ulp found in testing len = Math.nextAfter(len, len + 1.0); this.x /= len; this.y /= len; this.z /= len; len = Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); if (len <= 1.0) return; // can't happen / something is really messed up this.x = Double.NaN; this.y = Double.NaN; this.z = Double.NaN; } public final double[] toArray() { return new double[] { x, y, z }; } public final Vec2 toVec2() { return new Vec2(x, y); } public final Vec3 copy() { return new Vec3(this); } public final static double[] toArray(Vec3[] vecs) { double[] arr = new double[vecs.length * 3]; for (int i = 0; i < vecs.length; i++) { Vec3 v = vecs[i]; arr[i * 3 + 0] = v.x; arr[i * 3 + 1] = v.y; arr[i * 3 + 2] = v.z; } return arr; } @Override public final boolean equals(Object o) { if (o instanceof Vec3) return isApproxEqual((Vec3) o, 0.0); return false; } @Override public int hashCode() { assert false : "hashCode not designed"; return 42; } @Override public final String toString() { return "(" + x + ", " + y + ", " + z + ")"; } }
package elephantdb.hadoop; import elephantdb.DomainSpec; import elephantdb.persistence.LocalPersistenceFactory; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import java.util.Collection; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.ChecksumFileSystem; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.commons.io.FileUtils; public class LocalElephantManager { public static final String TMP_DIRS_CONF = "elephantdb.local.tmp.dirs"; public static void setTmpDirs(Configuration conf, List<String> dirs) { conf.setStrings(TMP_DIRS_CONF, dirs.toArray(new String[dirs.size()])); } public static List<String> getTmpDirs(Configuration conf) { String[] res = conf.getStrings(TMP_DIRS_CONF, new String[0]); List<String> ret = new ArrayList<String>(); if(res.length==0) { ret.add("/tmp"); } else { for(String s: res) { ret.add(s); } } return ret; } FileSystem _fs; File _dirFlag; String _localRoot; DomainSpec _spec; Map<String, Object> _persistenceOptions; public LocalElephantManager(FileSystem fs, DomainSpec spec, Map<String, Object> persistenceOptions, List<String> tmpDirs) throws IOException { _localRoot = selectAndFlagRoot(tmpDirs); _fs = fs; _spec = spec; _persistenceOptions = persistenceOptions; } /** * Creates a temporary directory, downloads the remotePath (tied to the FS), and returns it. If remotePath is null or doesn't exist, * creates an empty local elephant and closes it. */ public String downloadRemoteShard(String id, String remotePath) throws IOException { LocalPersistenceFactory fact = _spec.getLPFactory(); String returnDir = localTmpDir(id); if(remotePath==null || !_fs.exists(new Path(remotePath))) { fact.createPersistence( returnDir, _persistenceOptions) .close(); } else { _fs.copyToLocalFile(new Path(remotePath), new Path(returnDir)); Collection<File> crcs = FileUtils.listFiles(new File(returnDir), new String[] {"crc"}, true); for(File crc: crcs) { FileUtils.forceDelete(crc); } } return returnDir; } public String localTmpDir(String id) { return _localRoot + "/" + id; } public void progress() { _dirFlag.setLastModified(System.currentTimeMillis()); } public void cleanup() throws IOException { FileSystem.getLocal(new Configuration()).delete(new Path(_localRoot), true); _dirFlag.delete(); } private void clearStaleFlags(List<String> tmpDirs) { //delete any flags more than an hour old for(String tmp: tmpDirs) { File flagDir = new File(flagDir(tmp)); flagDir.mkdirs(); for(File flag: flagDir.listFiles()) { if(flag.lastModified() < System.currentTimeMillis() - 1000*60*60) { flag.delete(); } } } } private String flagDir(String tmpDir) { return tmpDir + "/flags"; } private String selectAndFlagRoot(List<String> tmpDirs) throws IOException { clearStaleFlags(tmpDirs); Map<String, Integer> flagCounts = new HashMap<String, Integer>(); for(String tmp: tmpDirs) { File flagDir = new File(flagDir(tmp)); flagDir.mkdirs(); flagCounts.put(tmp, flagDir.list().length); } String best = null; Integer bestCount = null; for(Entry<String, Integer> e: flagCounts.entrySet()) { if(best==null || e.getValue() < bestCount) { best = e.getKey(); bestCount = e.getValue(); } } String token = UUID.randomUUID().toString(); _dirFlag = new File(flagDir(best) + "/" + token); _dirFlag.createNewFile(); new File(best).mkdirs(); return best + "/" + token; } }
package events; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; import api.ILevel; import utility.Pair; import com.google.common.base.Charsets; import com.google.common.io.Files; import api.IEntitySystem; import voogasalad.u /*** * @author Anirudh Jonnavithula, Carolyn Yao */ public final class EventFactory { public static Pair<Trigger, Action> createEvent(Map<String, String> triggerMapDescription, String scriptPath) { Trigger trigger = null; String className = triggerMapDescription.get("trigger_type"); try { trigger = (Trigger) Class.forName(className).getConstructor(Map.class).newInstance(triggerMapDescription); } catch (InstantiationException e) { } catch (IllegalAccessException e) { System.out.println("illegal access found"); } catch (IllegalArgumentException e) { System.out.println("illegal argument found"); } catch (InvocationTargetException e) { System.out.println("invocation target not found"); } catch (NoSuchMethodException e) { System.out.println("no such method found"); } catch (SecurityException e) { System.out.println("security exception"); } catch (ClassNotFoundException e) { System.out.println(className); System.out.println("class not found"); } Action action = new Action(scriptPath); return new Pair<Trigger, Action>(trigger, action); } public String getScriptFromPath(String scriptPath) { String script = null; try { script = Files.toString(new File(scriptPath), Charsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } return script; } }
package ameba.http.session; import ameba.core.Requests; import ameba.mvc.assets.AssetsResource; import ameba.util.Times; import com.google.common.base.Charsets; import com.google.common.hash.Hashing; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Priority; import javax.inject.Singleton; import javax.ws.rs.Priorities; import javax.ws.rs.container.*; import javax.ws.rs.core.*; import java.lang.invoke.MethodHandle; import java.util.List; import java.util.UUID; /** * @author icode */ @PreMatching @Priority(Priorities.AUTHENTICATION - 500) @Singleton public class SessionFilter implements ContainerRequestFilter, ContainerResponseFilter { private static final Logger logger = LoggerFactory.getLogger(SessionFilter.class); private static final String SET_COOKIE_KEY = SessionFilter.class.getName() + ".__SET_SESSION_COOKIE__"; static String DEFAULT_SESSION_ID_COOKIE_KEY = "s"; static long SESSION_TIMEOUT = Times.parseDuration("2h"); static int COOKIE_MAX_AGE = NewCookie.DEFAULT_MAX_AGE; static MethodHandle METHOD_HANDLE; @Context private UriInfo uriInfo; private boolean isIgnore() { List<Object> resources = uriInfo.getMatchedResources(); return resources.size() != 0 && AssetsResource.class.isAssignableFrom(resources.get(0).getClass()); } @Override @SuppressWarnings("unchecked") public void filter(ContainerRequestContext requestContext) { if (isIgnore()) { return; } Cookie cookie = requestContext.getCookies().get(DEFAULT_SESSION_ID_COOKIE_KEY); boolean isNew = false; if (cookie == null) { isNew = true; cookie = newCookie(requestContext); } AbstractSession session; String host = Requests.getRemoteRealAddr(); if (host == null || host.equals("unknown")) { host = Requests.getRemoteAddr(); } String sessionId = cookie.getValue(); if (METHOD_HANDLE != null) { try { session = (AbstractSession) METHOD_HANDLE.invoke(sessionId, host, SESSION_TIMEOUT, isNew); } catch (Throwable throwable) { throw new SessionExcption("new session instance error"); } } else { session = new CacheSession(sessionId, host, SESSION_TIMEOUT, isNew); } if (!session.isNew()) { try { checkSession(session, requestContext); } catch (Exception e) { logger.warn("get session error", e); } } Session.sessionThreadLocal.set(session); } private void checkSession(AbstractSession session, ContainerRequestContext requestContext) { if (session.isInvalid()) { Cookie cookie = newCookie(requestContext); session.setId(cookie.getValue()); } else { session.touch(); session.flush(); } } protected String newSessionId() { return Hashing.sha1() .hashString( UUID.randomUUID().toString() + Math.random() + this.hashCode() + System.nanoTime(), Charsets.UTF_8 ) .toString(); } private NewCookie newCookie(ContainerRequestContext requestContext) { // URI uri = requestContext.getUriInfo().getBaseUri(); // String domain = uri.getHost(); // // localhost domain must be null // if (domain.equalsIgnoreCase("localhost")) { // domain = null; NewCookie cookie = new NewCookie( DEFAULT_SESSION_ID_COOKIE_KEY, newSessionId(), "/", null, Cookie.DEFAULT_VERSION, null, COOKIE_MAX_AGE, null, requestContext.getSecurityContext().isSecure(), true); requestContext.setProperty(SET_COOKIE_KEY, cookie); return cookie; } @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) { if (isIgnore()) { return; } try { Session.flush(); } catch (Exception e) { logger.warn("flush session error", e); } NewCookie cookie = (NewCookie) requestContext.getProperty(SET_COOKIE_KEY); if (cookie != null) responseContext.getHeaders().add(HttpHeaders.SET_COOKIE, cookie.toString()); Session.sessionThreadLocal.remove(); } }
package cn.momia.mapi.api.admin; import cn.momia.api.course.CourseServiceApi; import cn.momia.api.course.OrderServiceApi; import cn.momia.api.im.ImServiceApi; import cn.momia.api.user.SmsServiceApi; import cn.momia.api.user.UserServiceApi; import cn.momia.api.user.dto.User; import cn.momia.common.core.http.MomiaHttpResponse; import cn.momia.common.core.util.MobileUtil; import cn.momia.mapi.api.AbstractApi; import com.google.common.base.Splitter; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * TODO Admin MAPI */ @RestController @RequestMapping("/admin") public class AdminApi extends AbstractApi { private static final long SYSTEM_PUSH_USERID = 10000; @Autowired private ImServiceApi imServiceApi; @Autowired private CourseServiceApi courseServiceApi; @Autowired private OrderServiceApi orderServiceApi; @Autowired private SmsServiceApi smsServiceApi; @Autowired private UserServiceApi userServiceApi; @RequestMapping(value = "/im/group", method = RequestMethod.POST) public MomiaHttpResponse createGroup(@RequestParam(value = "coid") long courseId, @RequestParam(value = "sid") long courseSkuId, @RequestParam(value = "tids", required = false, defaultValue = "") String teachers, @RequestParam(value = "name") String groupName) { if (courseId <= 0 || courseSkuId <= 0 || StringUtils.isBlank(groupName)) return MomiaHttpResponse.BAD_REQUEST; Set<Long> teacherUserIds = new HashSet<Long>(); for (String teacher : Splitter.on(",").trimResults().omitEmptyStrings().split(teachers)) { teacherUserIds.add(Long.valueOf(teacher)); } if (teacherUserIds.isEmpty()) { teacherUserIds.add(SYSTEM_PUSH_USERID); } return MomiaHttpResponse.SUCCESS(imServiceApi.createGroup(courseId, courseSkuId, teacherUserIds, groupName)); } @RequestMapping(value = "/im/group/join", method = RequestMethod.POST) public MomiaHttpResponse joinGroup(@RequestParam(value = "uid") long userId, @RequestParam(value = "coid") long courseId, @RequestParam(value = "sid") long courseSkuId) { if (userId <= 0 || courseId <= 0 || courseSkuId <= 0) return MomiaHttpResponse.BAD_REQUEST; User user = userServiceApi.get(userId); return MomiaHttpResponse.SUCCESS(imServiceApi.joinGroup(userId, courseId, courseSkuId, user.isTeacher())); } @RequestMapping(value = "/im/group/leave", method = RequestMethod.POST) public MomiaHttpResponse leaveGroup(@RequestParam(value = "uid") long userId, @RequestParam(value = "coid") long courseId, @RequestParam(value = "sid") long courseSkuId) { if (userId <= 0 || courseId <= 0 || courseSkuId <= 0) return MomiaHttpResponse.BAD_REQUEST; return MomiaHttpResponse.SUCCESS(imServiceApi.leaveGroup(userId, courseId, courseSkuId)); } @RequestMapping(value = "/course/booking/batch", method = RequestMethod.POST) public MomiaHttpResponse batchBooking(@RequestParam String uids, @RequestParam(value = "coid") long courseId, @RequestParam(value = "sid") long skuId) { Set<Long> userIds = new HashSet<Long>(); for (String userId : Splitter.on(",").omitEmptyStrings().trimResults().split(uids)) { userIds.add(Long.valueOf(userId)); } List<Long> failedUserIds = courseServiceApi.batchBooking(userIds, courseId, skuId); for (long userId : userIds) { if (!failedUserIds.contains(userId)) imServiceApi.joinGroup(userId, courseId, skuId, false); } return MomiaHttpResponse.SUCCESS(failedUserIds); } @RequestMapping(value = "/course/cancel/batch", method = RequestMethod.POST) public MomiaHttpResponse batchCancel(@RequestParam(required = false, defaultValue = "") String uids, @RequestParam(value = "coid") long courseId, @RequestParam(value = "sid") long skuId) { Set<Long> userIds = new HashSet<Long>(); for (String userId : Splitter.on(",").omitEmptyStrings().trimResults().split(uids)) { userIds.add(Long.valueOf(userId)); } Map<Long, Long> successfulPackageUsers = courseServiceApi.batchCancel(userIds, courseId, skuId); if (!successfulPackageUsers.isEmpty()) { for (Map.Entry<Long, Long> entry : successfulPackageUsers.entrySet()) { orderServiceApi.extendPackageTime(entry.getKey(), 1); imServiceApi.leaveGroup(entry.getValue(), courseId, skuId); } } return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/package/time/extend", method = RequestMethod.POST) public MomiaHttpResponse extendPackageTime(@RequestParam(value = "pid") long packageId, @RequestParam int time) { if (packageId <= 0 || time <= 0) return MomiaHttpResponse.BAD_REQUEST; return MomiaHttpResponse.SUCCESS(orderServiceApi.extendPackageTime(packageId, time)); } @RequestMapping(value = "/push", method = RequestMethod.POST) public MomiaHttpResponse push(@RequestParam(value = "uid") long userId, @RequestParam String content, @RequestParam(required = false, defaultValue = "") String extra) { if (userId <= 0 || StringUtils.isBlank(content)) return MomiaHttpResponse.BAD_REQUEST; return MomiaHttpResponse.SUCCESS(imServiceApi.push(userId, content, extra)); } @RequestMapping(value = "/push/batch", method = RequestMethod.POST) public MomiaHttpResponse pushBatch(@RequestParam(value = "uids") String uids, @RequestParam String content, @RequestParam(required = false, defaultValue = "") String extra) { if (StringUtils.isBlank(uids) || StringUtils.isBlank(content)) return MomiaHttpResponse.BAD_REQUEST; Set<Long> userIds = new HashSet<Long>(); for (String userId : Splitter.on(",").omitEmptyStrings().trimResults().split(uids)) { userIds.add(Long.valueOf(userId)); } return MomiaHttpResponse.SUCCESS(imServiceApi.pushBatch(userIds, content, extra)); } @RequestMapping(value = "/sms/notify", method = RequestMethod.POST) public MomiaHttpResponse smsNotify(@RequestParam String mobile, @RequestParam String message) { if (MobileUtil.isInvalid(mobile) || StringUtils.isBlank(message)) return MomiaHttpResponse.BAD_REQUEST; return MomiaHttpResponse.SUCCESS(smsServiceApi.notify(mobile, message)); } }
package com.adyen.model; import com.google.gson.annotations.SerializedName; import java.util.Objects; import static com.adyen.util.Util.toIndentedString; /** * ThreeDSecureData */ public class ThreeDSecureData { @SerializedName("cavvAlgorithm") private String cavvAlgorithm = null; @SerializedName("threeDSVersion") private String threeDSVersion = null; /** * the enrollment response from the 3D directory server */ public enum DirectoryResponseEnum { @SerializedName("Y") Y("Y"), @SerializedName("U") U("U"), @SerializedName("N") N("N"), @SerializedName("A") A("A"), @SerializedName("C") C("C"), @SerializedName("D") D("D"), @SerializedName("R") R("R"), @SerializedName("I") I("I"), @SerializedName("E") E("E"); private String value; DirectoryResponseEnum(String value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } } @SerializedName("directoryResponse") private DirectoryResponseEnum directoryResponse = null; /** * the authentication response if the shopper was redirected */ public enum AuthenticationResponseEnum { @SerializedName("Y") Y("Y"), @SerializedName("N") N("N"), @SerializedName("U") U("U"), @SerializedName("A") A("A"); private String value; AuthenticationResponseEnum(String value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } } @SerializedName("authenticationResponse") private AuthenticationResponseEnum authenticationResponse = null; @SerializedName("xid") private String xid = null; @SerializedName("cavv") private String cavv = null; @SerializedName("tavv") private String tavv = null; @SerializedName("tokenAuthenticationVerificationValue") private String tokenAuthenticationVerificationValue = null; @SerializedName("eci") private String eci = null; @SerializedName("dsTransID") private String dsTransID = null; @SerializedName("challengeCancel") private String challengeCancel = null; @SerializedName("riskScore") private String riskScore = null; @SerializedName("transStatusReason") private String transStatusReason = null; public ThreeDSecureData cavvAlgorithm(String cavvAlgorithm) { this.cavvAlgorithm = cavvAlgorithm; return this; } /** * the CAVV algorithm used * * @return cavvAlgorithm **/ public String getCavvAlgorithm() { return cavvAlgorithm; } public void setCavvAlgorithm(String cavvAlgorithm) { this.cavvAlgorithm = cavvAlgorithm; } public ThreeDSecureData directoryResponse(DirectoryResponseEnum directoryResponse) { this.directoryResponse = directoryResponse; return this; } /** * the enrollment response from the 3D directory server * * @return directoryResponse **/ public DirectoryResponseEnum getDirectoryResponse() { return directoryResponse; } public void setDirectoryResponse(DirectoryResponseEnum directoryResponse) { this.directoryResponse = directoryResponse; } public ThreeDSecureData authenticationResponse(AuthenticationResponseEnum authenticationResponse) { this.authenticationResponse = authenticationResponse; return this; } public String getThreeDSVersion() { return threeDSVersion; } public void setThreeDSVersion(String threeDSVersion) { this.threeDSVersion = threeDSVersion; } /** * the authentication response if the shopper was redirected * * @return authenticationResponse **/ public AuthenticationResponseEnum getAuthenticationResponse() { return authenticationResponse; } public void setAuthenticationResponse(AuthenticationResponseEnum authenticationResponse) { this.authenticationResponse = authenticationResponse; } public ThreeDSecureData xid(String xid) { this.xid = xid; return this; } /** * the transaction identifier (base64 encoded, 20 bytes in decoded form) * * @return xid **/ public String getXid() { return xid; } public void setXid(String xid) { this.xid = xid; } public ThreeDSecureData cavv(String cavv) { this.cavv = cavv; return this; } /** * Network token cryptogram. * * @return tavv **/ public String getTavv() { return tavv; } public void setTavv(String tavv) { this.tavv = tavv; } /** * Network token authentication verification value (TAVV). The network token cryptogram. * * @return tokenAuthenticationVerificationValue **/ public String getTokenAuthenticationVerificationValue() { return tokenAuthenticationVerificationValue; } public void setTokenAuthenticationVerificationValue(String tokenAuthenticationVerificationValue) { this.tokenAuthenticationVerificationValue = tokenAuthenticationVerificationValue; } /** * the cardholder authentication value (base64 encoded, 20 bytes in decoded form) * * @return cavv **/ public String getCavv() { return cavv; } public void setCavv(String cavv) { this.cavv = cavv; } public ThreeDSecureData eci(String eci) { this.eci = eci; return this; } /** * the electronic commerce indicator * * @return eci **/ public String getEci() { return eci; } public void setEci(String eci) { this.eci = eci; } /** * Supported for 3D Secure 2. The unique transaction identifier assigned by the Directory Server (DS) to identify a single transaction. * * @return dsTransID */ public String getDsTransID() { return dsTransID; } public void setDsTransID(String dsTransID) { this.dsTransID = dsTransID; } public ThreeDSecureData dsTransID(String dsTransID) { this.dsTransID = dsTransID; return this; } /** * Get challengeCancel * * @return challengeCancel */ public String getChallengeCancel() { return challengeCancel; } public void setChallengeCancel(String challengeCancel) { this.challengeCancel = challengeCancel; } public ThreeDSecureData challengeCancel(String challengeCancel) { this.challengeCancel = challengeCancel; return this; } /** * Get riskScore * * @return riskScore */ public String getRiskScore() { return riskScore; } public void setRiskScore(String riskScore) { this.riskScore = riskScore; } public ThreeDSecureData riskScore(String riskScore) { this.riskScore = riskScore; return this; } /** * Get transStatusReason * @return transStatusReason **/ public String getTransStatusReason() { return transStatusReason; } public void setTransStatusReason(String transStatusReason) { this.transStatusReason = transStatusReason; } public ThreeDSecureData transStatusReason(String transStatusReason) { this.transStatusReason = transStatusReason; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ThreeDSecureData threeDSecureData = (ThreeDSecureData) o; return Objects.equals(this.cavvAlgorithm, threeDSecureData.cavvAlgorithm) && Objects.equals(this.directoryResponse, threeDSecureData.directoryResponse) && Objects.equals(this.authenticationResponse, threeDSecureData.authenticationResponse) && Objects.equals(this.xid, threeDSecureData.xid) && Objects.equals(this.cavv, threeDSecureData.cavv) && Objects.equals(this.tavv, threeDSecureData.tavv) && Objects.equals(this.tokenAuthenticationVerificationValue, threeDSecureData.tokenAuthenticationVerificationValue) && Objects.equals(this.eci, threeDSecureData.eci) && Objects.equals(this.dsTransID, threeDSecureData.dsTransID) && Objects.equals(this.challengeCancel, threeDSecureData.challengeCancel) && Objects.equals(this.riskScore, threeDSecureData.riskScore) && Objects.equals(this.transStatusReason, threeDSecureData.transStatusReason); } @Override public int hashCode() { return Objects.hash(cavvAlgorithm, directoryResponse, authenticationResponse, xid, cavv, tavv, tokenAuthenticationVerificationValue, eci, dsTransID, challengeCancel, riskScore, transStatusReason); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ThreeDSecureData {\n"); sb.append(" cavvAlgorithm: ").append(toIndentedString(cavvAlgorithm)).append("\n"); sb.append(" directoryResponse: ").append(toIndentedString(directoryResponse)).append("\n"); sb.append(" authenticationResponse: ").append(toIndentedString(authenticationResponse)).append("\n"); sb.append(" xid: ").append(toIndentedString(xid)).append("\n"); sb.append(" cavv: ").append(toIndentedString(cavv)).append("\n"); sb.append(" tavv: ").append(toIndentedString(tavv)).append("\n"); sb.append(" tokenAuthenticationVerificationValue: ").append(toIndentedString(tokenAuthenticationVerificationValue)).append("\n"); sb.append(" eci: ").append(toIndentedString(eci)).append("\n"); sb.append(" dsTransID: ").append(toIndentedString(dsTransID)).append("\n"); sb.append(" challengeCancel").append(toIndentedString(challengeCancel)).append("\n"); sb.append(" riskScore").append(toIndentedString(riskScore)).append("\n"); sb.append(" transStatusReason").append(toIndentedString(transStatusReason)).append("\n"); sb.append("}"); return sb.toString(); } }
package info.tregmine.commands; import static org.bukkit.ChatColor.*; import org.bukkit.GameMode; import info.tregmine.Tregmine; import info.tregmine.api.TregminePlayer; public class GameModeCommand extends AbstractCommand { private GameMode mode; public GameModeCommand(Tregmine tregmine, String name, GameMode mode) { super(tregmine, name); this.mode = mode; } @Override public boolean handlePlayer(TregminePlayer player, String[] args) { if (!player.getRank().canUseCreative()) { return true; } player.setGameMode(mode); player.sendMessage(YELLOW + "You are now in " + mode.toString().toLowerCase() + " mode."); if (player.getRank().canFly()) { player.setAllowFlight(true); } return true; } }
package com.alexrnl.commons.database; import java.util.Set; /** * Basic CRUD operations on an abstract object. * @author Alex * @param <T> * The class of the object to manipulate. */ public interface DAO<T extends Entity> { /** * Create operation. * @param obj * the object to create. * @return <code>null</code> if the creation of the object has failed, the new reference to the * object if the creation succeeded. */ T create (T obj); /** * Read operation. * @param id * the id of the object to retrieve. * @return The object which matches the <code>id</code> or <code>null</code> if no matches had * been found. */ T find (int id); /** * Update operation. * @param obj * the object to update. * @return <code>true</code> if the update of the object has been successful. */ boolean update (T obj); /** * Delete operation. * @param obj * the object to delete. * @return <code>true</code> if the deletion of the object has been successful. */ boolean delete (T obj); /** * Retrieve all the objects available.<br /> * <em>Use with caution, it can consume a lot of memory.</em> * @return A collection with all the objects. */ Set<T> retrieveAll (); /** * Retrieve a collection of object matching * @param field * the field to search * @param value * the value to test * @return A collection with the object matching the */ Set<T> search (Column field, String value); }
package com.blog.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Scope; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; @Configuration //@EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport { // @Bean // @Profile("company") // @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) // @Qualifier() // public RedisConnectionFactory cacheCompanyFactory(){ // JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); // jedisConnectionFactory.setHostName("192.168.1.192"); // jedisConnectionFactory.setPort(7000); // return jedisConnectionFactory; @Bean @Profile("company") public RedisTemplate<String , String> redisTemplateCompany(){ JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); jedisConnectionFactory.setHostName("192.168.1.192"); jedisConnectionFactory.setPort(7000); RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>(); redisTemplate.setConnectionFactory(jedisConnectionFactory); return redisTemplate; } @Bean @Profile("home") public RedisTemplate<String , String> redisTemplateHome(){ JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); jedisConnectionFactory.setHostName("127.0.0.1"); jedisConnectionFactory.setPort(6379); RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>(); redisTemplate.setConnectionFactory(jedisConnectionFactory); return redisTemplate; } @Bean public CacheManager cacheManager(RedisTemplate redisTemplate){ RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); // cacheManager.setDefaultExpiration(3000); return cacheManager; } // @Bean // public KeyGenerator customKeyGenerator(){ // return (o, method, objects) -> { // StringBuilder sb = new StringBuilder(); // sb.append(o.getClass().getName()); // sb.append(method.getName()); // for (Object obj : objects) { // sb.append(obj.toString()); // return sb.toString(); }
package com.couchbase.lite.router; import com.couchbase.lite.AsyncTask; import com.couchbase.lite.BlobStoreWriter; import com.couchbase.lite.ChangesOptions; import com.couchbase.lite.CouchbaseLiteException; import com.couchbase.lite.Database; import com.couchbase.lite.Document; import com.couchbase.lite.DocumentChange; import com.couchbase.lite.Manager; import com.couchbase.lite.Mapper; import com.couchbase.lite.Misc; import com.couchbase.lite.QueryOptions; import com.couchbase.lite.QueryRow; import com.couchbase.lite.Reducer; import com.couchbase.lite.ReplicationFilter; import com.couchbase.lite.RevisionList; import com.couchbase.lite.Status; import com.couchbase.lite.TransactionalTask; import com.couchbase.lite.View; import com.couchbase.lite.auth.FacebookAuthorizer; import com.couchbase.lite.auth.PersonaAuthorizer; import com.couchbase.lite.internal.AttachmentInternal; import com.couchbase.lite.internal.Body; import com.couchbase.lite.internal.RevisionInternal; import com.couchbase.lite.replicator.Replication; import com.couchbase.lite.replicator.Replication.ChangeEvent; import com.couchbase.lite.replicator.Replication.ChangeListener; import com.couchbase.lite.replicator.Replication.ReplicationStatus; import com.couchbase.lite.replicator.ReplicationState; import com.couchbase.lite.storage.SQLException; import com.couchbase.lite.store.Store; import com.couchbase.lite.support.RevisionUtils; import com.couchbase.lite.support.Version; import com.couchbase.lite.util.Log; import com.couchbase.lite.util.StreamUtils; import org.apache.http.client.HttpResponseException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class Router implements Database.ChangeListener, Database.DatabaseListener { /** * Options for what metadata to include in document bodies */ private enum TDContentOptions { TDIncludeAttachments, TDIncludeConflicts, TDIncludeRevs, TDIncludeRevsInfo, TDIncludeLocalSeq, TDNoBody, TDBigAttachmentsFollow, TDNoAttachments } private Manager manager; private Database db; private URLConnection connection; private Map<String, String> queries; private boolean changesIncludesDocs = false; private boolean changesIncludesConflicts = false; private RouterCallbackBlock callbackBlock; private boolean responseSent = false; private ReplicationFilter changesFilter; Map<String, Object> changesFilterParams = null; private boolean longpoll = false; private boolean waiting = false; public static String getVersionString() { return Version.getVersion(); } public Router(Manager manager, URLConnection connection) { this.manager = manager; this.connection = connection; } public void setCallbackBlock(RouterCallbackBlock callbackBlock) { this.callbackBlock = callbackBlock; } private Map<String, String> getQueries() { if (queries == null) { String queryString = connection.getURL().getQuery(); if (queryString != null && queryString.length() > 0) { queries = new HashMap<String, String>(); for (String component : queryString.split("&")) { int location = component.indexOf('='); if (location > 0) { String key = component.substring(0, location); String value = component.substring(location + 1); queries.put(key, value); } } } } return queries; } private boolean getBooleanValueFromBody(String paramName, Map<String, Object> bodyDict, boolean defaultVal) { boolean value = defaultVal; if (bodyDict.containsKey(paramName)) { value = Boolean.TRUE.equals(bodyDict.get(paramName)); } return value; } private String getQuery(String param) { Map<String, String> queries = getQueries(); if (queries != null) { String value = queries.get(param); if (value != null) { return URLDecoder.decode(value); } } return null; } private boolean getBooleanQuery(String param) { String value = getQuery(param); return (value != null) && !"false".equals(value) && !"0".equals(value); } private int getIntQuery(String param, int defaultValue) { int result = defaultValue; String value = getQuery(param); if (value != null) { try { result = Integer.parseInt(value); } catch (NumberFormatException e) { //ignore, will return default value } } return result; } private Object getJSONQuery(String param) { String value = getQuery(param); if (value == null) { return null; } Object result = null; try { result = Manager.getObjectMapper().readValue(value, Object.class); } catch (Exception e) { Log.w("Unable to parse JSON Query", e); } return result; } private boolean cacheWithEtag(String etag) { String eTag = String.format("\"%s\"", etag); connection.getResHeader().add("Etag", eTag); String requestIfNoneMatch = connection.getRequestProperty("If-None-Match"); return eTag.equals(requestIfNoneMatch); } private Map<String, Object> getBodyAsDictionary() { try { InputStream contentStream = connection.getRequestInputStream(); Map<String, Object> bodyMap = Manager.getObjectMapper().readValue(contentStream, Map.class); return bodyMap; } catch (IOException e) { Log.w(Log.TAG_ROUTER, "WARNING: Exception parsing body into dictionary", e); return null; } } private EnumSet<TDContentOptions> getContentOptions() { EnumSet<TDContentOptions> result = EnumSet.noneOf(TDContentOptions.class); if (getBooleanQuery("attachments")) { result.add(TDContentOptions.TDIncludeAttachments); } if (getBooleanQuery("local_seq")) { result.add(TDContentOptions.TDIncludeLocalSeq); } if (getBooleanQuery("conflicts")) { result.add(TDContentOptions.TDIncludeConflicts); } if (getBooleanQuery("revs")) { result.add(TDContentOptions.TDIncludeRevs); } if (getBooleanQuery("revs_info")) { result.add(TDContentOptions.TDIncludeRevsInfo); } return result; } private boolean getQueryOptions(QueryOptions options) { // http://wiki.apache.org/couchdb/HTTP_view_API#Querying_Options options.setSkip(getIntQuery("skip", options.getSkip())); options.setLimit(getIntQuery("limit", options.getLimit())); options.setGroupLevel(getIntQuery("group_level", options.getGroupLevel())); options.setDescending(getBooleanQuery("descending")); options.setIncludeDocs(getBooleanQuery("include_docs")); options.setUpdateSeq(getBooleanQuery("update_seq")); if (getQuery("inclusive_end") != null) { options.setInclusiveEnd(getBooleanQuery("inclusive_end")); } if (getQuery("reduce") != null) { options.setReduce(getBooleanQuery("reduce")); } options.setGroup(getBooleanQuery("group")); //options.setContentOptions(getContentOptions()); List<Object> keys; Object keysParam = getJSONQuery("keys"); if (keysParam != null && !(keysParam instanceof List)) { return false; } else { keys = (List<Object>) keysParam; } if (keys == null) { Object key = getJSONQuery("key"); if (key != null) { keys = new ArrayList<Object>(); keys.add(key); } } if (keys != null) { options.setKeys(keys); } else { options.setStartKey(getJSONQuery("startkey")); options.setEndKey(getJSONQuery("endkey")); if (getJSONQuery("startkey_docid") != null) { options.setStartKeyDocId(getJSONQuery("startkey_docid").toString()); } if (getJSONQuery("endkey_docid") != null) { options.setEndKeyDocId(getJSONQuery("endkey_docid").toString()); } } return true; } private String getMultipartRequestType() { String accept = connection.getRequestProperty("Accept"); if (accept.startsWith("multipart/")) { return accept; } return null; } private Status openDB() { if (db == null) { return new Status(Status.INTERNAL_SERVER_ERROR); } if (!db.exists()) { return new Status(Status.NOT_FOUND); } try { db.open(); } catch (CouchbaseLiteException e) { return e.getCBLStatus(); } return new Status(Status.OK); } private static List<String> splitPath(URL url) { String pathString = url.getPath(); if (pathString.startsWith("/")) { pathString = pathString.substring(1); } List<String> result = new ArrayList<String>(); //we want empty string to return empty list if (pathString.length() == 0) { return result; } for (String component : pathString.split("/")) { result.add(URLDecoder.decode(component)); } return result; } private void sendResponse() { if (!responseSent) { responseSent = true; if (callbackBlock != null) { callbackBlock.onResponseReady(); } } } public void start() { // We're going to map the request into a method call using reflection based on the method and path. // Accumulate the method name into the string 'message': String method = connection.getRequestMethod(); if ("HEAD".equals(method)) { method = "GET"; } String message = String.format("do_%s", method); // First interpret the components of the request: List<String> path = splitPath(connection.getURL()); if (path == null) { connection.setResponseCode(Status.BAD_REQUEST); try { connection.getResponseOutputStream().close(); } catch (IOException e) { Log.e(Log.TAG_ROUTER, "Error closing empty output stream"); } sendResponse(); return; } int pathLen = path.size(); if (pathLen > 0) { String dbName = path.get(0); if (dbName.startsWith("_")) { message += dbName; // special root path, like /_all_dbs } else { message += "_Database"; if (!Manager.isValidDatabaseName(dbName)) { Header resHeader = connection.getResHeader(); if (resHeader != null) { resHeader.add("Content-Type", "application/json"); } Map<String, Object> result = new HashMap<String, Object>(); result.put("error", "Invalid database"); result.put("status", Status.BAD_REQUEST); connection.setResponseBody(new Body(result)); ByteArrayInputStream bais = new ByteArrayInputStream(connection.getResponseBody().getJson()); connection.setResponseInputStream(bais); connection.setResponseCode(Status.BAD_REQUEST); try { connection.getResponseOutputStream().close(); } catch (IOException e) { Log.e(Log.TAG_ROUTER, "Error closing empty output stream"); } sendResponse(); return; } else { boolean mustExist = false; db = manager.getDatabase(dbName, mustExist); if (db == null) { connection.setResponseCode(Status.BAD_REQUEST); try { connection.getResponseOutputStream().close(); } catch (IOException e) { Log.e(Log.TAG_ROUTER, "Error closing empty output stream"); } sendResponse(); return; } } } } else { message += "Root"; } String docID = null; if (db != null && pathLen > 1) { message = message.replaceFirst("_Database", "_Document"); // Make sure database exists, then interpret doc name: Status status = openDB(); if (!status.isSuccessful()) { connection.setResponseCode(status.getCode()); try { connection.getResponseOutputStream().close(); } catch (IOException e) { Log.e(Log.TAG_ROUTER, "Error closing empty output stream"); } sendResponse(); return; } String name = path.get(1); if (!name.startsWith("_")) { // Regular document if (!Document.isValidDocumentId(name)) { connection.setResponseCode(Status.BAD_REQUEST); try { connection.getResponseOutputStream().close(); } catch (IOException e) { Log.e(Log.TAG_ROUTER, "Error closing empty output stream"); } sendResponse(); return; } docID = name; } else if ("_design".equals(name) || "_local".equals(name)) { if (pathLen <= 2) { connection.setResponseCode(Status.NOT_FOUND); try { connection.getResponseOutputStream().close(); } catch (IOException e) { Log.e(Log.TAG_ROUTER, "Error closing empty output stream"); } sendResponse(); return; } docID = name + "/" + path.get(2); path.set(1, docID); path.remove(2); pathLen } else if (name.startsWith("_design") || name.startsWith("_local")) { // This is also a document, just with a URL-encoded "/" docID = name; } else if (name.equals("_session")) { // There are two possible uri to get a session, /<db>/_session or /_session. // This is for /<db>/_session. message = message.replaceFirst("_Document", name); } else { // Special document name like "_all_docs": message += name; if (pathLen > 2) { List<String> subList = path.subList(2, pathLen - 1); StringBuilder sb = new StringBuilder(); Iterator<String> iter = subList.iterator(); while (iter.hasNext()) { sb.append(iter.next()); if (iter.hasNext()) { sb.append("/"); } } docID = sb.toString(); } } } String attachmentName = null; if (docID != null && pathLen > 2) { message = message.replaceFirst("_Document", "_Attachment"); // Interpret attachment name: attachmentName = path.get(2); if (attachmentName.startsWith("_") && docID.startsWith("_design")) { // Design-doc attribute like _info or _view message = message.replaceFirst("_Attachment", "_DesignDocument"); docID = docID.substring(8); // strip the "_design/" prefix attachmentName = pathLen > 3 ? path.get(3) : null; } else { if (pathLen > 3) { List<String> subList = path.subList(2, pathLen); StringBuilder sb = new StringBuilder(); Iterator<String> iter = subList.iterator(); while (iter.hasNext()) { sb.append(iter.next()); if (iter.hasNext()) { //sb.append("%2F"); sb.append("/"); } } attachmentName = sb.toString(); } } } //Log.d(TAG, "path: " + path + " message: " + message + " docID: " + docID + " attachmentName: " + attachmentName); // Send myself a message based on the components: Status status = null; try { Method m = Router.class.getMethod(message, Database.class, String.class, String.class); status = (Status) m.invoke(this, db, docID, attachmentName); } catch (NoSuchMethodException msme) { try { String errorMessage = String.format("Router unable to route request to %s", message); Log.e(Log.TAG_ROUTER, errorMessage); Map<String, Object> result = new HashMap<String, Object>(); result.put("error", "not_found"); result.put("reason", errorMessage); connection.setResponseBody(new Body(result)); Method m = Router.class.getMethod("do_UNKNOWN", Database.class, String.class, String.class); status = (Status) m.invoke(this, db, docID, attachmentName); } catch (Exception e) { //default status is internal server error Log.e(Log.TAG_ROUTER, "Router attempted do_UNKNWON fallback, but that threw an exception", e); Map<String, Object> result = new HashMap<String, Object>(); result.put("error", "not_found"); result.put("reason", "Router unable to route request"); connection.setResponseBody(new Body(result)); status = new Status(Status.NOT_FOUND); } } catch (Exception e) { String errorMessage = "Router unable to route request to " + message; Log.e(Log.TAG_ROUTER, errorMessage, e); Map<String, Object> result = new HashMap<String, Object>(); result.put("error", "not_found"); result.put("reason", errorMessage + e.toString()); connection.setResponseBody(new Body(result)); if (e instanceof CouchbaseLiteException) { status = ((CouchbaseLiteException) e).getCBLStatus(); } else { status = new Status(Status.NOT_FOUND); } } // If response is ready (nonzero status), tell my client about it: if (status.getCode() != 0) { // NOTE: processRequestRanges() is not implemented for CBL Java Core // Configure response headers: status = sendResponseHeaders(status); connection.setResponseCode(status.getCode()); if (status.isSuccessful() && connection.getResponseBody() == null && connection.getHeaderField("Content-Type") == null) { connection.setResponseBody(new Body("{\"ok\":true}".getBytes())); } if (status.getCode() != 0 && status.isSuccessful() == false && connection.getResponseBody() == null) { Map<String, Object> result = new HashMap<String, Object>(); result.put("status", status.getCode()); connection.setResponseBody(new Body(result)); } setResponse(); sendResponse(); } else { // NOTE code == 0 waiting = true; } if (waiting) { if (db != null) { db.addDatabaseListener(this); } } } /** * implementation of Database.DatabaseListener */ @Override public void databaseClosing() { dbClosing(); } private void dbClosing() { Log.d(Log.TAG_ROUTER, "Database closing! Returning error 500"); Status status = new Status(Status.INTERNAL_SERVER_ERROR); status = sendResponseHeaders(status); connection.setResponseCode(status.getCode()); setResponse(); sendResponse(); } public void stop() { callbackBlock = null; if (db != null) { db.removeChangeListener(this); db.removeDatabaseListener(this); } } public Status do_UNKNOWN(Database db, String docID, String attachmentName) { return new Status(Status.NOT_FOUND); } private void setResponse() { if (connection.getResponseBody() != null) { ByteArrayInputStream bais = new ByteArrayInputStream(connection.getResponseBody().getJson()); connection.setResponseInputStream(bais); } else { try { connection.getResponseOutputStream().close(); } catch (IOException e) { Log.e(Log.TAG_ROUTER, "Error closing empty output stream"); } } } /** * in CBL_Router.m * - (void) sendResponseHeaders */ private Status sendResponseHeaders(Status status) { // NOTE: Line 572-574 of CBL_Router.m is not in CBL Java Core // This check is in sendResponse(); connection.getResHeader().add("Server", String.format("Couchbase Lite %s", getVersionString())); // Check for a mismatch between the Accept request header and the response type: String accept = connection.getRequestProperty("Accept"); if (accept != null && !"*/*".equals(accept)) { String responseType = connection.getBaseContentType(); if (responseType != null && accept.indexOf(responseType) < 0) { Log.e(Log.TAG_ROUTER, "Error 406: Can't satisfy request Accept: %s", accept); status = new Status(Status.NOT_ACCEPTABLE); } } if (connection.getResponseBody() != null && connection.getResponseBody().isValidJSON()) { Header resHeader = connection.getResHeader(); if (resHeader != null) { resHeader.add("Content-Type", "application/json"); } else { Log.w(Log.TAG_ROUTER, "Cannot add Content-Type header because getResHeader() returned null"); } } // NOTE: Line 596-607 of CBL_Router.m is not in CBL Java Core return status; } /** * Router+Handlers */ private void setResponseLocation(URL url) { String location = url.getPath(); String query = url.getQuery(); if (query != null) { int startOfQuery = location.indexOf(query); if (startOfQuery > 0) { location = location.substring(0, startOfQuery); } } connection.getResHeader().add("Location", location); } /** * SERVER REQUESTS: * */ public Status do_GETRoot(Database _db, String _docID, String _attachmentName) { Map<String, Object> info = new HashMap<String, Object>(); info.put("CBLite", "Welcome"); info.put("couchdb", "Welcome"); // for compatibility info.put("version", getVersionString()); connection.setResponseBody(new Body(info)); return new Status(Status.OK); } public Status do_GET_all_dbs(Database _db, String _docID, String _attachmentName) { List<String> dbs = manager.getAllDatabaseNames(); connection.setResponseBody(new Body(dbs)); return new Status(Status.OK); } public Status do_GET_session(Database _db, String _docID, String _attachmentName) { // Send back an "Admin Party"-like response Map<String, Object> session = new HashMap<String, Object>(); Map<String, Object> userCtx = new HashMap<String, Object>(); String[] roles = {"_admin"}; session.put("ok", true); userCtx.put("name", null); userCtx.put("roles", roles); session.put("userCtx", userCtx); connection.setResponseBody(new Body(session)); return new Status(Status.OK); } public Status do_POST_replicate(Database _db, String _docID, String _attachmentName) { Replication replicator; // Extract the parameters from the JSON request body: Map<String, Object> body = getBodyAsDictionary(); if (body == null) { return new Status(Status.BAD_REQUEST); } try { replicator = manager.getReplicator(body); } catch (CouchbaseLiteException e) { Map<String, Object> result = new HashMap<String, Object>(); result.put("error", e.toString()); connection.setResponseBody(new Body(result)); return e.getCBLStatus(); } Boolean cancelBoolean = (Boolean) body.get("cancel"); boolean cancel = (cancelBoolean != null && cancelBoolean.booleanValue()); if (!cancel) { if (!replicator.isRunning()) { final CountDownLatch replicationStarted = new CountDownLatch(1); replicator.addChangeListener(new Replication.ChangeListener() { @Override public void changed(Replication.ChangeEvent event) { if (event.getTransition() != null && event.getTransition().getDestination() == ReplicationState.RUNNING) { replicationStarted.countDown(); } } }); if (!replicator.isContinuous()) { replicator.addChangeListener(new Replication.ChangeListener() { @Override public void changed(Replication.ChangeEvent event) { if (event.getTransition() != null && event.getTransition().getDestination() == ReplicationState.STOPPED) { Status status = new Status(Status.OK); status = sendResponseHeaders(status); connection.setResponseCode(status.getCode()); Map<String, Object> result = new HashMap<String, Object>(); result.put("session_id", event.getSource().getSessionID()); connection.setResponseBody(new Body(result)); setResponse(); sendResponse(); } } }); } replicator.start(); // wait for replication to start, otherwise replicator.getSessionId() will return null try { replicationStarted.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } } if (replicator.isContinuous()) { Map<String, Object> result = new HashMap<String, Object>(); result.put("session_id", replicator.getSessionID()); connection.setResponseBody(new Body(result)); return new Status(Status.OK); } else { return new Status(0); } } else { // Cancel replication: replicator.stop(); return new Status(Status.OK); } } public Status do_GET_uuids(Database _db, String _docID, String _attachmentName) { int count = Math.min(1000, getIntQuery("count", 1)); List<String> uuids = new ArrayList<String>(count); for (int i = 0; i < count; i++) { uuids.add(Misc.CreateUUID()); } Map<String, Object> result = new HashMap<String, Object>(); result.put("uuids", uuids); connection.setResponseBody(new Body(result)); return new Status(Status.OK); } /** * TODO: CBL Java Core codes are out of sync with CBL iOS. Need to catch up CBL iOS */ public Status do_GET_active_tasks(Database _db, String _docID, String _attachmentName) { String feed = getQuery("feed"); longpoll = "longpoll".equals(feed); boolean continuous = !longpoll && "continuous".equals(feed); String session_id = getQuery("session_id"); ChangeListener listener = new ChangeListener() { ChangeListener self = this; @Override public void changed(ChangeEvent event) { Map<String, Object> activity = getActivity(event.getSource()); // NOTE: Followings are not supported by iOS. We might remove them in the future. if (event.getTransition() != null) { // this adds data to the response based on the trigger. activity.put("transition_source", event.getTransition().getSource()); activity.put("transition_destination", event.getTransition().getDestination()); activity.put("trigger", event.getTransition().getTrigger()); Log.d(Log.TAG_ROUTER, "do_GET_active_tasks Transition [" + event.getTransition().getTrigger() + "] Source:" + event.getTransition().getSource() + ", Destination:" + event.getTransition().getDestination()); } if (longpoll) { Log.w(Log.TAG_ROUTER, "Router: Sending longpoll replication response"); sendResponse(); if (callbackBlock != null) { byte[] data = null; try { data = Manager.getObjectMapper().writeValueAsBytes(activity); } catch (Exception e) { Log.w(Log.TAG_ROUTER, "Error serializing JSON", e); } OutputStream os = connection.getResponseOutputStream(); try { os.write(data); os.close(); } catch (IOException e) { Log.e(Log.TAG_ROUTER, "IOException writing to internal streams", e); } } //remove this change listener because a new one will be added when this responds event.getSource().removeChangeListener(self); } else { Log.w(Log.TAG_ROUTER, "Router: Sending continous replication change chunk"); sendContinuousReplicationChanges(activity); } } }; List<Map<String, Object>> activities = new ArrayList<Map<String, Object>>(); for (Database db : manager.allOpenDatabases()) { List<Replication> activeReplicators = db.getActiveReplications(); if (activeReplicators != null) { for (Replication replicator : activeReplicators) { if (replicator.isRunning()) { Map<String, Object> activity = getActivity(replicator); if (session_id != null) { if (replicator.getSessionID().equals(session_id)) { activities.add(activity); } } else { activities.add(activity); } if (continuous || longpoll) { if (session_id != null) { if (replicator.getSessionID().equals(session_id)) { replicator.addChangeListener(listener); } } else { replicator.addChangeListener(listener); } } } } } } if (continuous || longpoll) { connection.setChunked(true); connection.setResponseCode(Status.OK); sendResponse(); if (continuous && !activities.isEmpty()) { for (Map<String, Object> activity : activities) { sendContinuousReplicationChanges(activity); } } // Don't close connection; more data to come return new Status(0); } else { connection.setResponseBody(new Body(activities)); return new Status(Status.OK); } } /** * TODO: To be compatible with CBL iOS, this method should move to Replicator.activeTaskInfo(). * TODO: Reference: - (NSDictionary*) activeTaskInfo in CBL_Replicator.m */ private Map<String, Object> getActivity(Replication replicator) { Map<String, Object> activity = new HashMap<String, Object>(); String source = replicator.getRemoteUrl().toExternalForm(); String target = replicator.getLocalDatabase().getName(); if (!replicator.isPull()) { String tmp = source; source = target; target = tmp; } int processed = replicator.getCompletedChangesCount(); int total = replicator.getChangesCount(); String status = String.format("Processed %d / %d changes", processed, total); if (!replicator.getStatus().equals(ReplicationStatus.REPLICATION_ACTIVE)) { //These values match the values for IOS. if (replicator.getStatus().equals(ReplicationStatus.REPLICATION_IDLE)) { status = "Idle"; // nonstandard } else if (replicator.getStatus().equals(ReplicationStatus.REPLICATION_STOPPED)) { status = "Stopped"; } else if (replicator.getStatus().equals(ReplicationStatus.REPLICATION_OFFLINE)) { status = "Offline"; // nonstandard } } int progress = (total > 0) ? Math.round(100 * processed / (float) total) : 0; activity.put("type", "Replication"); activity.put("task", replicator.getSessionID()); activity.put("source", source); activity.put("target", target); activity.put("status", status); activity.put("progress", progress); activity.put("continuous", replicator.isContinuous()); //NOTE: Need to support "x_active_requests" if (replicator.getLastError() != null) { String msg = String.format("Replicator error: %s. Repl: %s. Source: %s, Target: %s", replicator.getLastError(), replicator, source, target); Log.e(Log.TAG_ROUTER, msg); Throwable error = replicator.getLastError(); int statusCode = 400; if (error instanceof HttpResponseException) { statusCode = ((HttpResponseException) error).getStatusCode(); } Object[] errorObjects = new Object[]{statusCode, replicator.getLastError().toString()}; activity.put("error", errorObjects); } else { // NOTE: Following two parameters: CBL iOS does not support. We might remove them in the future. activity.put("change_count", total); activity.put("completed_change_count", processed); } return activity; } /** * Send a JSON object followed by a newline without closing the connection. * Used by the continuous mode of _changes and _active_tasks. * <p/> * TODO: CBL iOS supports EventSourceFeed in addition to longpoll and continuous. * TODO: Need to catch up CBL iOS: - (void) sendContinuousLine: (NSDictionary*)changeDict in CBL_Router+Handlers.m */ private void sendContinuousReplicationChanges(Map<String, Object> activity) { try { String jsonString = Manager.getObjectMapper().writeValueAsString(activity); if (callbackBlock != null) { byte[] json = (jsonString + "\n").getBytes(); OutputStream os = connection.getResponseOutputStream(); try { os.write(json); os.flush(); } catch (Exception e) { Log.e(Log.TAG_ROUTER, "IOException writing to internal streams", e); } } } catch (Exception e) { Log.w("Unable to serialize change to JSON", e); } } /** * DATABASE REQUESTS: * */ public Status do_GET_Database(Database _db, String _docID, String _attachmentName) { // http://wiki.apache.org/couchdb/HTTP_database_API#Database_Information Status status = openDB(); if (!status.isSuccessful()) { return status; } int num_docs = db.getDocumentCount(); long update_seq = db.getLastSequenceNumber(); long instanceStartTimeMicroseconds = db.getStartTime() * 1000; Map<String, Object> result = new HashMap<String, Object>(); result.put("db_name", db.getName()); result.put("db_uuid", db.publicUUID()); result.put("doc_count", num_docs); result.put("update_seq", update_seq); result.put("disk_size", db.totalDataSize()); result.put("instance_start_time", instanceStartTimeMicroseconds); connection.setResponseBody(new Body(result)); return new Status(Status.OK); } public Status do_PUT_Database(Database _db, String _docID, String _attachmentName) { if (db.exists()) { return new Status(Status.DUPLICATE); } try { db.open(); } catch (CouchbaseLiteException e) { return e.getCBLStatus(); } setResponseLocation(connection.getURL()); return new Status(Status.CREATED); } public Status do_DELETE_Database(Database _db, String _docID, String _attachmentName) throws CouchbaseLiteException { if (getQuery("rev") != null) { return new Status(Status.BAD_REQUEST); // CouchDB checks for this; probably meant to be a document deletion } db.delete(); return new Status(Status.OK); } /** * This is a hack to deal with the fact that there is currently no custom * serializer for QueryRow. Instead, just convert everything to generic Maps. */ private void convertCBLQueryRowsToMaps(Map<String, Object> allDocsResult) { List<Map<String, Object>> rowsAsMaps = new ArrayList<Map<String, Object>>(); List<QueryRow> rows = (List<QueryRow>) allDocsResult.get("rows"); if (rows != null) { for (QueryRow row : rows) { rowsAsMaps.add(row.asJSONDictionary()); } } allDocsResult.put("rows", rowsAsMaps); } public Status do_POST_Database(Database _db, String _docID, String _attachmentName) { Status status = openDB(); if (!status.isSuccessful()) { return status; } Map<String, Object> bodyDict = getBodyAsDictionary(); if (bodyDict == null) { return new Status(Status.BAD_REQUEST); } return update(db, null, new Body(bodyDict), false); } public Status do_GET_Document_all_docs(Database _db, String _docID, String _attachmentName) throws CouchbaseLiteException { QueryOptions options = new QueryOptions(); if (!getQueryOptions(options)) { return new Status(Status.BAD_REQUEST); } Map<String, Object> result = db.getAllDocs(options); convertCBLQueryRowsToMaps(result); if (result == null) { return new Status(Status.INTERNAL_SERVER_ERROR); } connection.setResponseBody(new Body(result)); return new Status(Status.OK); } public Status do_POST_Document_all_docs(Database _db, String _docID, String _attachmentName) throws CouchbaseLiteException { QueryOptions options = new QueryOptions(); if (!getQueryOptions(options)) { return new Status(Status.BAD_REQUEST); } Map<String, Object> body = getBodyAsDictionary(); if (body == null) { return new Status(Status.BAD_REQUEST); } List<Object> keys = (List<Object>) body.get("keys"); options.setKeys(keys); Map<String, Object> result = null; result = db.getAllDocs(options); convertCBLQueryRowsToMaps(result); if (result == null) { return new Status(Status.INTERNAL_SERVER_ERROR); } connection.setResponseBody(new Body(result)); return new Status(Status.OK); } public Status do_POST_facebook_token(Database _db, String _docID, String _attachmentName) { Map<String, Object> body = getBodyAsDictionary(); if (body == null) { return new Status(Status.BAD_REQUEST); } String email = (String) body.get("email"); String remoteUrl = (String) body.get("remote_url"); String accessToken = (String) body.get("access_token"); if (email != null && remoteUrl != null && accessToken != null) { try { URL siteUrl = new URL(remoteUrl); } catch (MalformedURLException e) { Map<String, Object> result = new HashMap<String, Object>(); result.put("error", "invalid remote_url: " + e.getLocalizedMessage()); connection.setResponseBody(new Body(result)); return new Status(Status.BAD_REQUEST); } try { FacebookAuthorizer.registerAccessToken(accessToken, email, remoteUrl); } catch (Exception e) { Map<String, Object> result = new HashMap<String, Object>(); result.put("error", "error registering access token: " + e.getLocalizedMessage()); connection.setResponseBody(new Body(result)); return new Status(Status.BAD_REQUEST); } Map<String, Object> result = new HashMap<String, Object>(); result.put("ok", "registered"); connection.setResponseBody(new Body(result)); return new Status(Status.OK); } else { Map<String, Object> result = new HashMap<String, Object>(); result.put("error", "required fields: access_token, email, remote_url"); connection.setResponseBody(new Body(result)); return new Status(Status.BAD_REQUEST); } } public Status do_POST_persona_assertion(Database _db, String _docID, String _attachmentName) { Map<String, Object> body = getBodyAsDictionary(); if (body == null) { return new Status(Status.BAD_REQUEST); } String assertion = (String) body.get("assertion"); if (assertion == null) { Map<String, Object> result = new HashMap<String, Object>(); result.put("error", "required fields: assertion"); connection.setResponseBody(new Body(result)); return new Status(Status.BAD_REQUEST); } try { String email = PersonaAuthorizer.registerAssertion(assertion); Map<String, Object> result = new HashMap<String, Object>(); result.put("ok", "registered"); result.put("email", email); connection.setResponseBody(new Body(result)); return new Status(Status.OK); } catch (Exception e) { Map<String, Object> result = new HashMap<String, Object>(); result.put("error", "error registering persona assertion: " + e.getLocalizedMessage()); connection.setResponseBody(new Body(result)); return new Status(Status.BAD_REQUEST); } } public Status do_POST_Document_bulk_docs(Database _db, String _docID, String _attachmentName) { Map<String, Object> bodyDict = getBodyAsDictionary(); if (bodyDict == null) { return new Status(Status.BAD_REQUEST); } final List<Map<String, Object>> docs = (List<Map<String, Object>>) bodyDict.get("docs"); final boolean noNewEdits = getBooleanValueFromBody("new_edits", bodyDict, true) == false; final boolean allOrNothing = getBooleanValueFromBody("all_or_nothing", bodyDict, false); final Status status = new Status(Status.OK); final List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); boolean ret = db.getStore().runInTransaction(new TransactionalTask() { @Override public boolean run() { boolean ok = false; try { for (Map<String, Object> doc : docs) { String docID = (String) doc.get("_id"); RevisionInternal rev = null; Body docBody = new Body(doc); if (noNewEdits) { rev = new RevisionInternal(docBody); if (rev.getRevID() == null || rev.getDocID() == null || !rev.getDocID().equals(docID)) { //status = new Status(Status.BAD_REQUEST); status.setCode(Status.BAD_REQUEST); } else { List<String> history = Database.parseCouchDBRevisionHistory(doc); db.forceInsert(rev, history, null); } } else { Status outStatus = new Status(); rev = update(db, docID, docBody, false, allOrNothing, outStatus); status.setCode(outStatus.getCode()); } Map<String, Object> result = null; if (status.isSuccessful()) { result = new HashMap<String, Object>(); result.put("ok", true); result.put("id", rev.getDocID()); if (rev != null) { result.put("rev", rev.getRevID()); } } else if (allOrNothing) { //return status; // all_or_nothing backs out if there's any error return false; } else if (status.getCode() == Status.FORBIDDEN) { result = new HashMap<String, Object>(); result.put("error", "validation failed"); result.put("id", rev.getDocID()); } else if (status.getCode() == Status.CONFLICT) { result = new HashMap<String, Object>(); result.put("error", "conflict"); result.put("id", rev.getDocID()); } else { //return status; // abort the whole thing if something goes badly wrong return false; } if (result != null) { results.add(result); } } Log.w(Log.TAG_ROUTER, "%s finished inserting %d revisions in bulk", this, docs.size()); ok = true; } catch (Exception e) { Log.e(Log.TAG_ROUTER, "%s: Exception inserting revisions in bulk", e, this); } finally { return ok; } } }); if (ret) { connection.setResponseBody(new Body(results)); return new Status(Status.CREATED); } else { return status; } } public Status do_POST_Document_revs_diff(Database _db, String _docID, String _attachmentName) { // Collect all of the input doc/revision IDs as TDRevisions: RevisionList revs = new RevisionList(); Map<String, Object> body = getBodyAsDictionary(); if (body == null) { return new Status(Status.BAD_JSON); } for (String docID : body.keySet()) { List<String> revIDs = (List<String>) body.get(docID); for (String revID : revIDs) { RevisionInternal rev = new RevisionInternal(docID, revID, false); revs.add(rev); } } // Look them up, removing the existing ones from revs: try { db.findMissingRevisions(revs); } catch (SQLException e) { Log.e(Log.TAG_ROUTER, "Exception", e); return new Status(Status.DB_ERROR); } // Return the missing revs in a somewhat different format: Map<String, Object> diffs = new HashMap<String, Object>(); for (RevisionInternal rev : revs) { String docID = rev.getDocID(); List<String> missingRevs = null; Map<String, Object> idObj = (Map<String, Object>) diffs.get(docID); if (idObj != null) { missingRevs = (List<String>) idObj.get("missing"); } else { idObj = new HashMap<String, Object>(); } if (missingRevs == null) { missingRevs = new ArrayList<String>(); idObj.put("missing", missingRevs); diffs.put(docID, idObj); } missingRevs.add(rev.getRevID()); } // FIXME add support for possible_ancestors connection.setResponseBody(new Body(diffs)); return new Status(Status.OK); } public Status do_POST_Document_compact(Database _db, String _docID, String _attachmentName) { Status status = new Status(Status.OK); try { _db.compact(); } catch (CouchbaseLiteException e) { status = e.getCBLStatus(); } if (status.getCode() < 300) { Status outStatus = new Status(); outStatus.setCode(202); // CouchDB returns 202 'cause it's an async operation return outStatus; } else { return status; } } public Status do_POST_Document_purge(Database _db, String ignored1, String ignored2) { Map<String, Object> body = getBodyAsDictionary(); if (body == null) { return new Status(Status.BAD_REQUEST); } // convert from Map<String,Object> -> Map<String, List<String>> - is there a cleaner way? final Map<String, List<String>> docsToRevs = new HashMap<String, List<String>>(); for (String key : body.keySet()) { Object val = body.get(key); if (val instanceof List) { docsToRevs.put(key, (List<String>) val); } } final List<Map<String, Object>> asyncApiCallResponse = new ArrayList<Map<String, Object>>(); // this is run in an async db task to fix the following race condition // found in issue // replicator thread: call db.loadRevisionBody for doc1 // liteserv thread: call db.purge on doc1 // replicator thread: call db.getRevisionHistory for doc1, which returns empty history since it was purged Future future = db.runAsync(new AsyncTask() { @Override public void run(Database database) { Map<String, Object> purgedRevisions = db.purgeRevisions(docsToRevs); asyncApiCallResponse.add(purgedRevisions); } }); try { future.get(60, TimeUnit.SECONDS); } catch (InterruptedException e) { Log.e(Log.TAG_ROUTER, "Exception waiting for future", e); return new Status(Status.INTERNAL_SERVER_ERROR); } catch (ExecutionException e) { Log.e(Log.TAG_ROUTER, "Exception waiting for future", e); return new Status(Status.INTERNAL_SERVER_ERROR); } catch (TimeoutException e) { Log.e(Log.TAG_ROUTER, "Exception waiting for future", e); return new Status(Status.INTERNAL_SERVER_ERROR); } Map<String, Object> purgedRevisions = asyncApiCallResponse.get(0); Map<String, Object> responseMap = new HashMap<String, Object>(); responseMap.put("purged", purgedRevisions); Body responseBody = new Body(responseMap); connection.setResponseBody(responseBody); return new Status(Status.OK); } public Status do_POST_Document_ensure_full_commit(Database _db, String _docID, String _attachmentName) { return new Status(Status.OK); } /** * CHANGES: * */ private Map<String, Object> changesDictForRevision(RevisionInternal rev) { Map<String, Object> changesDict = new HashMap<String, Object>(); changesDict.put("rev", rev.getRevID()); List<Map<String, Object>> changes = new ArrayList<Map<String, Object>>(); changes.add(changesDict); Map<String, Object> result = new HashMap<String, Object>(); result.put("seq", rev.getSequence()); result.put("id", rev.getDocID()); result.put("changes", changes); if (rev.isDeleted()) { result.put("deleted", true); } if (changesIncludesDocs) { result.put("doc", rev.getProperties()); } return result; } private Map<String, Object> responseBodyForChanges(List<RevisionInternal> changes, long since) { List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); for (RevisionInternal rev : changes) { Map<String, Object> changeDict = changesDictForRevision(rev); results.add(changeDict); } if (changes.size() > 0) { since = changes.get(changes.size() - 1).getSequence(); } Map<String, Object> result = new HashMap<String, Object>(); result.put("results", results); result.put("last_seq", since); return result; } private Map<String, Object> responseBodyForChangesWithConflicts(List<RevisionInternal> changes, long since) { // Assumes the changes are grouped by docID so that conflicts will be adjacent. List<Map<String, Object>> entries = new ArrayList<Map<String, Object>>(); String lastDocID = null; Map<String, Object> lastEntry = null; for (RevisionInternal rev : changes) { String docID = rev.getDocID(); if (docID.equals(lastDocID)) { Map<String, Object> changesDict = new HashMap<String, Object>(); changesDict.put("rev", rev.getRevID()); List<Map<String, Object>> inchanges = (List<Map<String, Object>>) lastEntry.get("changes"); inchanges.add(changesDict); } else { lastEntry = changesDictForRevision(rev); entries.add(lastEntry); lastDocID = docID; } } // After collecting revisions, sort by sequence: Collections.sort(entries, new Comparator<Map<String, Object>>() { public int compare(Map<String, Object> e1, Map<String, Object> e2) { return Misc.SequenceCompare((Long) e1.get("seq"), (Long) e2.get("seq")); } }); Long lastSeq; if (entries.size() == 0) { lastSeq = since; } else { lastSeq = (Long) entries.get(entries.size() - 1).get("seq"); if (lastSeq == null) { lastSeq = since; } } Map<String, Object> result = new HashMap<String, Object>(); result.put("results", entries); result.put("last_seq", lastSeq); return result; } private void sendContinuousChange(RevisionInternal rev) { Map<String, Object> changeDict = changesDictForRevision(rev); try { String jsonString = Manager.getObjectMapper().writeValueAsString(changeDict); if (callbackBlock != null) { byte[] json = (jsonString + "\n").getBytes(); OutputStream os = connection.getResponseOutputStream(); try { os.write(json); os.flush(); } catch (Exception e) { Log.e(Log.TAG_ROUTER, "IOException writing to internal streams", e); } } } catch (Exception e) { Log.w("Unable to serialize change to JSON", e); } } /** * Implementation of ChangeListener */ @Override public void changed(Database.ChangeEvent event) { List<DocumentChange> changes = event.getChanges(); for (DocumentChange change : changes) { RevisionInternal rev = change.getAddedRevision(); String winningRevID = change.getWinningRevisionID(); if (!this.changesIncludesConflicts) { if (winningRevID == null) continue; // // this change doesn't affect the winning rev ID, no need to send it else if (!winningRevID.equals(rev.getRevID())) { // This rev made a _different_ rev current, so substitute that one. // We need to emit the current sequence # in the feed, so put it in the rev. // This isn't correct internally (this is an old rev so it has an older sequence) // but consumers of the _changes feed don't care about the internal state. RevisionInternal mRev = db.getDocument(rev.getDocID(), winningRevID, changesIncludesDocs); mRev.setSequence(rev.getSequence()); rev = mRev; } } final boolean allowRevision = event.getSource().runFilter(changesFilter, changesFilterParams, rev); if (!allowRevision) { return; } if (longpoll) { Log.w(Log.TAG_ROUTER, "Router: Sending longpoll response"); sendResponse(); List<RevisionInternal> revs = new ArrayList<RevisionInternal>(); revs.add(rev); Map<String, Object> body = responseBodyForChanges(revs, 0); if (callbackBlock != null) { byte[] data = null; try { data = Manager.getObjectMapper().writeValueAsBytes(body); } catch (Exception e) { Log.w(Log.TAG_ROUTER, "Error serializing JSON", e); } OutputStream os = connection.getResponseOutputStream(); try { os.write(data); os.close(); } catch (IOException e) { Log.e(Log.TAG_ROUTER, "IOException writing to internal streams", e); } } } else { Log.w(Log.TAG_ROUTER, "Router: Sending continous change chunk"); sendContinuousChange(rev); } } } public Status do_GET_Document_changes(Database _db, String docID, String _attachmentName) { // http://wiki.apache.org/couchdb/HTTP_database_API#Changes // Get options: changesIncludesDocs = getBooleanQuery("include_docs"); String style = getQuery("style"); if (style != null && style.equals("all_docs")) changesIncludesConflicts = true; ChangesOptions options = new ChangesOptions(); options.setIncludeDocs(changesIncludesDocs); options.setIncludeConflicts(changesIncludesConflicts); options.setSortBySequence(!options.isIncludeConflicts()); // TODO: descending option is not supported by ChangesOptions options.setLimit(getIntQuery("limit", options.getLimit())); int since = getIntQuery("since", 0); String filterName = getQuery("filter"); if (filterName != null) { changesFilter = db.getFilter(filterName); if (changesFilter == null) { return new Status(Status.NOT_FOUND); } changesFilterParams = new HashMap<String, Object>(queries); Log.v(Log.TAG_ROUTER, "Filter params=" + changesFilterParams); } RevisionList changes = db.changesSince(since, options, changesFilter, changesFilterParams); if (changes == null) { return new Status(Status.INTERNAL_SERVER_ERROR); } String feed = getQuery("feed"); longpoll = "longpoll".equals(feed); boolean continuous = !longpoll && "continuous".equals(feed); if (continuous || (longpoll && changes.size() == 0)) { connection.setChunked(true); connection.setResponseCode(Status.OK); sendResponse(); if (continuous) { for (RevisionInternal rev : changes) { sendContinuousChange(rev); } } db.addChangeListener(this); // Don't close connection; more data to come return new Status(0); } else { if (options.isIncludeConflicts()) { connection.setResponseBody(new Body(responseBodyForChangesWithConflicts(changes, since))); } else { connection.setResponseBody(new Body(responseBodyForChanges(changes, since))); } return new Status(Status.OK); } } /** * DOCUMENT REQUESTS: * */ private String getRevIDFromIfMatchHeader() { String ifMatch = connection.getRequestProperty("If-Match"); if (ifMatch == null) { return null; } // Value of If-Match is an ETag, so have to trim the quotes around it: if (ifMatch.length() > 2 && ifMatch.startsWith("\"") && ifMatch.endsWith("\"")) { return ifMatch.substring(1, ifMatch.length() - 2); } else { return null; } } public Status do_GET_Document(Database _db, String docID, String _attachmentName) { try { // http://wiki.apache.org/couchdb/HTTP_Document_API#GET boolean isLocalDoc = docID.startsWith("_local"); EnumSet<TDContentOptions> options = getContentOptions(); String openRevsParam = getQuery("open_revs"); if (openRevsParam == null || isLocalDoc) { // Regular GET: String revID = getQuery("rev"); // often null RevisionInternal rev = null; if (isLocalDoc) { rev = db.getLocalDocument(docID, revID); } else { /* rev = db.getDocument(docID, revID, options); // Handle ?atts_since query by stubbing out older attachments: //?atts_since parameter - value is a (URL-encoded) JSON array of one or more revision IDs. // The response will include the content of only those attachments that changed since the given revision(s). //(You can ask for this either in the default JSON or as multipart/related, as previously described.) List<String> attsSince = (List<String>) getJSONQuery("atts_since"); if (attsSince != null) { String ancestorId = db.findCommonAncestorOf(rev, attsSince); if (ancestorId != null) { int generation = RevisionInternal.generationFromRevID(ancestorId); db.stubOutAttachmentsIn(rev, generation + 1); } } */ boolean includeAttachments = options.contains(TDContentOptions.TDIncludeAttachments); if (includeAttachments) { options.remove(TDContentOptions.TDIncludeAttachments); } rev = db.getDocument(docID, revID, true); if (rev != null) { rev = applyOptionsToRevision(options, rev); } if (rev == null) { } } if (rev == null) return new Status(Status.NOT_FOUND); if (cacheWithEtag(rev.getRevID())) return new Status(Status.NOT_MODIFIED); // set ETag and check conditional GET // TODO connection.setResponseBody(rev.getBody()); } else { List<Map<String, Object>> result = null; if (openRevsParam.equals("all")) { // Get all conflicting revisions: RevisionList allRevs = db.getStore().getAllRevisions(docID, true); result = new ArrayList<Map<String, Object>>(allRevs.size()); for (RevisionInternal rev : allRevs) { try { db.loadRevisionBody(rev); } catch (CouchbaseLiteException e) { if (e.getCBLStatus().getCode() != Status.INTERNAL_SERVER_ERROR) { Map<String, Object> dict = new HashMap<String, Object>(); dict.put("missing", rev.getRevID()); result.add(dict); } else { throw e; } } Map<String, Object> dict = new HashMap<String, Object>(); dict.put("ok", rev.getProperties()); result.add(dict); } } else { // ?open_revs=[...] returns an array of revisions of the document: List<String> openRevs = (List<String>) getJSONQuery("open_revs"); if (openRevs == null) { return new Status(Status.BAD_REQUEST); } result = new ArrayList<Map<String, Object>>(openRevs.size()); for (String revID : openRevs) { RevisionInternal rev = db.getDocument(docID, revID, true); if (rev != null) { Map<String, Object> dict = new HashMap<String, Object>(); dict.put("ok", rev.getProperties()); result.add(dict); } else { Map<String, Object> dict = new HashMap<String, Object>(); dict.put("missing", revID); result.add(dict); } } } String acceptMultipart = getMultipartRequestType(); if (acceptMultipart != null) { //FIXME figure out support for multipart throw new UnsupportedOperationException(); } else { connection.setResponseBody(new Body(result)); } } return new Status(Status.OK); } catch (CouchbaseLiteException e) { return e.getCBLStatus(); } } /** * in CBL_Router+Handlers.m * - (CBL_Revision*) applyOptions: (CBLContentOptions)options * toRevision: (CBL_Revision*)rev * status: (CBLStatus*)outStatus * 1.1 or earlier => Database.extraPropertiesForRevision() */ private RevisionInternal applyOptionsToRevision(EnumSet<TDContentOptions> options, RevisionInternal rev) { if (options != null && ( options.contains(TDContentOptions.TDIncludeLocalSeq) || options.contains(TDContentOptions.TDIncludeRevs) || options.contains(TDContentOptions.TDIncludeRevsInfo) || options.contains(TDContentOptions.TDIncludeConflicts) || options.contains(TDContentOptions.TDBigAttachmentsFollow))) { Map<String, Object> dst = new HashMap<String, Object>(); dst.putAll(rev.getProperties()); Store store = db.getStore(); if (options.contains(TDContentOptions.TDIncludeLocalSeq)) { dst.put("_local_seq", rev.getSequence()); rev.setProperties(dst); } if (options.contains(TDContentOptions.TDIncludeRevs)) { List<RevisionInternal> revs = db.getRevisionHistory(rev); Map<String, Object> historyDict = RevisionUtils.makeRevisionHistoryDict(revs); dst.put("_revisions", historyDict); rev.setProperties(dst); } if (options.contains(TDContentOptions.TDIncludeRevsInfo)) { List<Object> revsInfo = new ArrayList<Object>(); List<RevisionInternal> revs = db.getRevisionHistory(rev); for (RevisionInternal historicalRev : revs) { Map<String, Object> revHistoryItem = new HashMap<String, Object>(); String status = "available"; if (historicalRev.isDeleted()) { status = "deleted"; } if (historicalRev.isMissing()) { status = "missing"; } revHistoryItem.put("rev", historicalRev.getRevID()); revHistoryItem.put("status", status); revsInfo.add(revHistoryItem); } dst.put("_revs_info", revsInfo); rev.setProperties(dst); } if (options.contains(TDContentOptions.TDIncludeConflicts)) { RevisionList revs = store.getAllRevisions(rev.getDocID(), true); if (revs.size() > 1) { List<String> conflicts = new ArrayList<String>(); for (RevisionInternal aRev : revs) { if (aRev.equals(rev) || aRev.isDeleted()) { // don't add in this case } else { conflicts.add(aRev.getRevID()); } } dst.put("_conflicts", conflicts); } rev.setProperties(dst); } if (options.contains(TDContentOptions.TDBigAttachmentsFollow)) { RevisionInternal nuRev = new RevisionInternal(dst); Status outStatus = new Status(Status.OK); if (!db.expandAttachments(nuRev, 0, false, getBooleanQuery("att_encoding_info"), outStatus)) return null; rev = nuRev; } } return rev; } public Status do_GET_Attachment(Database _db, String docID, String _attachmentName) { try { // http://wiki.apache.org/couchdb/HTTP_Document_API#GET EnumSet<TDContentOptions> options = getContentOptions(); options.add(TDContentOptions.TDNoBody); String revID = getQuery("rev"); // often null RevisionInternal rev = db.getDocument(docID, revID, false); if (rev == null) { return new Status(Status.NOT_FOUND); } if (cacheWithEtag(rev.getRevID())) { return new Status(Status.NOT_MODIFIED); // set ETag and check conditional GET } String type = null; String acceptEncoding = connection.getRequestProperty("accept-encoding"); AttachmentInternal attachment = db.getAttachment(rev, _attachmentName); if (attachment == null) { return new Status(Status.NOT_FOUND); } type = attachment.getContentType(); if (type != null) { connection.getResHeader().add("Content-Type", type); } if (acceptEncoding != null && acceptEncoding.contains("gzip") && attachment.getEncoding() == AttachmentInternal.AttachmentEncoding.AttachmentEncodingGZIP) { connection.getResHeader().add("Content-Encoding", "gzip"); } connection.setResponseInputStream(attachment.getContentInputStream()); return new Status(Status.OK); } catch (CouchbaseLiteException e) { return e.getCBLStatus(); } } private RevisionInternal update(Database _db, String docID, Body body, boolean deleting, boolean allowConflict, Status outStatus) { if (body != null && !body.isValidJSON()) { outStatus.setCode(Status.BAD_JSON); return null; } boolean isLocalDoc = docID != null && docID.startsWith(("_local")); String prevRevID = null; if (!deleting) { Boolean deletingBoolean = (Boolean) body.getPropertyForKey("_deleted"); deleting = (deletingBoolean != null && deletingBoolean.booleanValue()); if (docID == null) { if (isLocalDoc) { outStatus.setCode(Status.METHOD_NOT_ALLOWED); return null; } // POST's doc ID may come from the _id field of the JSON body, else generate a random one. docID = (String) body.getPropertyForKey("_id"); if (docID == null) { if (deleting) { outStatus.setCode(Status.BAD_REQUEST); return null; } docID = Misc.CreateUUID(); } } // PUT's revision ID comes from the JSON body. prevRevID = (String) body.getPropertyForKey("_rev"); } else { // DELETE's revision ID comes from the ?rev= query param prevRevID = getQuery("rev"); } // A backup source of revision ID is an If-Match header: if (prevRevID == null) { prevRevID = getRevIDFromIfMatchHeader(); } RevisionInternal rev = new RevisionInternal(docID, null, deleting); rev.setBody(body); RevisionInternal result = null; try { if (isLocalDoc) { result = _db.putLocalRevision(rev, prevRevID); } else { result = _db.putRevision(rev, prevRevID, allowConflict); } if (deleting) { outStatus.setCode(Status.OK); } else { outStatus.setCode(Status.CREATED); } } catch (CouchbaseLiteException e) { e.printStackTrace(); Log.e(Log.TAG_ROUTER, "Error updating doc: %s", e, docID); outStatus.setCode(e.getCBLStatus().getCode()); } return result; } private Status update(Database _db, String docID, Body body, boolean deleting) { Status status = new Status(); if (docID != null && docID.isEmpty() == false) { // On PUT/DELETE, get revision ID from either ?rev= query or doc body: String revParam = getQuery("rev"); // TODO: If-Match if (revParam != null && body != null) { String revProp = (String) body.getProperties().get("_rev"); if (revProp == null) { // No _rev property in body, so use ?rev= query param instead: body.getProperties().put("_rev", revParam); //body = new Body(bodyDict); } else if (!revParam.equals(revProp)) { throw new IllegalArgumentException("Mismatch between _rev and rev"); } } } RevisionInternal rev = update(_db, docID, body, deleting, false, status); if (status.isSuccessful()) { cacheWithEtag(rev.getRevID()); // set ETag if (!deleting) { URL url = connection.getURL(); String urlString = url.toExternalForm(); if (docID != null) { urlString += "/" + rev.getDocID(); try { url = new URL(urlString); } catch (MalformedURLException e) { Log.w("Malformed URL", e); } } setResponseLocation(url); } Map<String, Object> result = new HashMap<String, Object>(); result.put("ok", true); result.put("id", rev.getDocID()); result.put("rev", rev.getRevID()); connection.setResponseBody(new Body(result)); } return status; } public Status do_PUT_Document(Database _db, String docID, String _attachmentName) throws CouchbaseLiteException { Status status = new Status(Status.CREATED); Map<String, Object> bodyDict = getBodyAsDictionary(); if (bodyDict == null) { throw new CouchbaseLiteException(Status.BAD_REQUEST); } if (getQuery("new_edits") == null || (getQuery("new_edits") != null && (new Boolean(getQuery("new_edits"))))) { // Regular PUT status = update(_db, docID, new Body(bodyDict), false); } else { // PUT with new_edits=false -- forcible insertion of existing revision: Body body = new Body(bodyDict); RevisionInternal rev = new RevisionInternal(body); if (rev.getRevID() == null || rev.getDocID() == null || !rev.getDocID().equals(docID)) { throw new CouchbaseLiteException(Status.BAD_REQUEST); } List<String> history = Database.parseCouchDBRevisionHistory(body.getProperties()); db.forceInsert(rev, history, null); } return status; } public Status do_DELETE_Document(Database _db, String docID, String _attachmentName) { return update(_db, docID, null, true); } private Status updateAttachment(String attachment, String docID, InputStream contentStream) throws CouchbaseLiteException { Status status = new Status(Status.OK); String revID = getQuery("rev"); if (revID == null) { revID = getRevIDFromIfMatchHeader(); } BlobStoreWriter body = new BlobStoreWriter(db.getAttachmentStore()); ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); try { StreamUtils.copyStream(contentStream, dataStream); body.appendData(dataStream.toByteArray()); body.finish(); } catch (Exception e) { throw new CouchbaseLiteException(e.getCause(), Status.BAD_ATTACHMENT); } RevisionInternal rev = db.updateAttachment(attachment, body, connection.getRequestProperty("content-type"), AttachmentInternal.AttachmentEncoding.AttachmentEncodingNone, docID, revID, null); Map<String, Object> resultDict = new HashMap<String, Object>(); resultDict.put("ok", true); resultDict.put("id", rev.getDocID()); resultDict.put("rev", rev.getRevID()); connection.setResponseBody(new Body(resultDict)); cacheWithEtag(rev.getRevID()); if (contentStream != null) { setResponseLocation(connection.getURL()); } return status; } public Status do_PUT_Attachment(Database _db, String docID, String _attachmentName) throws CouchbaseLiteException { return updateAttachment(_attachmentName, docID, connection.getRequestInputStream()); } public Status do_DELETE_Attachment(Database _db, String docID, String _attachmentName) throws CouchbaseLiteException { return updateAttachment(_attachmentName, docID, null); } /** * VIEW QUERIES: * */ private View compileView(String viewName, Map<String, Object> viewProps) { String language = (String) viewProps.get("language"); if (language == null) { language = "javascript"; } String mapSource = (String) viewProps.get("map"); if (mapSource == null) { return null; } Mapper mapBlock = View.getCompiler().compileMap(mapSource, language); if (mapBlock == null) { Log.w(Log.TAG_ROUTER, "View %s has unknown map function: %s", viewName, mapSource); return null; } String reduceSource = (String) viewProps.get("reduce"); Reducer reduceBlock = null; if (reduceSource != null) { reduceBlock = View.getCompiler().compileReduce(reduceSource, language); if (reduceBlock == null) { Log.w(Log.TAG_ROUTER, "View %s has unknown reduce function: %s", viewName, reduceBlock); return null; } } View view = db.getView(viewName); view.setMapReduce(mapBlock, reduceBlock, "1"); String collation = (String) viewProps.get("collation"); if ("raw".equals(collation)) { view.setCollation(View.TDViewCollation.TDViewCollationRaw); } return view; } private Status queryDesignDoc(String designDoc, String viewName, List<Object> keys) throws CouchbaseLiteException { String tdViewName = String.format("%s/%s", designDoc, viewName); View view = db.getExistingView(tdViewName); if (view == null || view.getMap() == null) { // No TouchDB view is defined, or it hasn't had a map block assigned; // see if there's a CouchDB view definition we can compile: RevisionInternal rev = db.getDocument(String.format("_design/%s", designDoc), null, true); if (rev == null) { return new Status(Status.NOT_FOUND); } Map<String, Object> views = (Map<String, Object>) rev.getProperties().get("views"); Map<String, Object> viewProps = (Map<String, Object>) views.get(viewName); if (viewProps == null) { return new Status(Status.NOT_FOUND); } // If there is a CouchDB view, see if it can be compiled from source: view = compileView(tdViewName, viewProps); if (view == null) { return new Status(Status.INTERNAL_SERVER_ERROR); } } QueryOptions options = new QueryOptions(); //if the view contains a reduce block, it should default to reduce=true if (view.getReduce() != null) { options.setReduce(true); } if (!getQueryOptions(options)) { return new Status(Status.BAD_REQUEST); } if (keys != null) { options.setKeys(keys); } view.updateIndex(); long lastSequenceIndexed = view.getLastSequenceIndexed(); // Check for conditional GET and set response Etag header: if (keys == null) { long eTag = options.isIncludeDocs() ? db.getLastSequenceNumber() : lastSequenceIndexed; if (cacheWithEtag(String.format("%d", eTag))) { return new Status(Status.NOT_MODIFIED); } } // convert from QueryRow -> Map List<QueryRow> queryRows = view.query(options); List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>(); for (QueryRow queryRow : queryRows) { rows.add(queryRow.asJSONDictionary()); } Map<String, Object> responseBody = new HashMap<String, Object>(); responseBody.put("rows", rows); responseBody.put("total_rows", view.getCurrentTotalRows()); responseBody.put("offset", options.getSkip()); if (options.isUpdateSeq()) { responseBody.put("update_seq", lastSequenceIndexed); } connection.setResponseBody(new Body(responseBody)); return new Status(Status.OK); } public Status do_GET_DesignDocument(Database _db, String designDocID, String viewName) throws CouchbaseLiteException { return queryDesignDoc(designDocID, viewName, null); } public Status do_POST_DesignDocument(Database _db, String designDocID, String viewName) throws CouchbaseLiteException { Map<String, Object> bodyDict = getBodyAsDictionary(); if (bodyDict == null) { return new Status(Status.BAD_REQUEST); } List<Object> keys = (List<Object>) bodyDict.get("keys"); return queryDesignDoc(designDocID, viewName, keys); } @Override public String toString() { String url = "Unknown"; if (connection != null && connection.getURL() != null) { url = connection.getURL().toExternalForm(); } return String.format("Router [%s]", url); } }
package jade.mtp.iiop; import java.io.*; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.Date; import java.util.Calendar; import java.util.StringTokenizer; import java.util.NoSuchElementException; import org.omg.CORBA.*; import org.omg.CosNaming.*; import FIPA.*; // OMG IDL Stubs import jade.core.AID; import jade.mtp.InChannel; import jade.mtp.OutChannel; import jade.mtp.MTP; import jade.mtp.MTPException; import jade.mtp.TransportAddress; import jade.domain.FIPAAgentManagement.Envelope; import jade.domain.FIPAAgentManagement.ReceivedObject; import jade.domain.FIPAAgentManagement.Property; //FIXME: if we add the method getSize() to all the slots whose value is a set // (e.g. intendedReceiver, userdefProperties, ...) we can improve a lot // performance in marshalling and unmarshalling. /** Implementation of <code><b>fipa.mts.mtp.iiop.std</b></code> specification for delivering ACL messages over the OMG IIOP transport protocol. @author Giovanni Rimassa - Universita` di Parma @version $Date$ $Revision$ */ public class MessageTransportProtocol implements MTP { private static class MTSImpl extends FIPA._MTSImplBase { private final InChannel.Dispatcher dispatcher; public MTSImpl(InChannel.Dispatcher disp) { dispatcher = disp; } public void message(FipaMessage aFipaMessage) { FIPA.Envelope[] envelopes = aFipaMessage.messageEnvelopes; byte[] payload = aFipaMessage.messageBody; Envelope env = new Envelope(); // Read all the envelopes sequentially, so that later slots // overwrite earlier ones. for(int e = 0; e < envelopes.length; e++) { FIPA.Envelope IDLenv = envelopes[e]; // Read in the 'to' slot if(IDLenv.to.length > 0) env.clearAllTo(); for(int i = 0; i < IDLenv.to.length; i++) { AID id = unmarshalAID(IDLenv.to[i]); env.addTo(id); } // Read in the 'from' slot if(IDLenv.from.length > 0) { AID id = unmarshalAID(IDLenv.from[0]); env.setFrom(id); } // Read in the 'intended-receiver' slot if(IDLenv.intendedReceiver.length > 0) env.clearAllIntendedReceiver(); for(int i = 0; i < IDLenv.intendedReceiver.length; i++) { AID id = unmarshalAID(IDLenv.intendedReceiver[i]); env.addIntendedReceiver(id); } // Read in the 'encrypted' slot //if(IDLenv.encrypted.length > 0) // env.clearAllEncrypted(); //for(int i = 0; i < IDLenv.encrypted.length; i++) { // String word = IDLenv.encrypted[i]; // env.addEncrypted(word); // Read in the other slots if(IDLenv.comments.length() > 0) env.setComments(IDLenv.comments); if(IDLenv.aclRepresentation.length() > 0) env.setAclRepresentation(IDLenv.aclRepresentation); if(IDLenv.payloadLength > 0) env.setPayloadLength(new Long(IDLenv.payloadLength)); if(IDLenv.payloadEncoding.length() > 0) env.setPayloadEncoding(IDLenv.payloadEncoding); if(IDLenv.date.length > 0) { Date d = unmarshalDateTime(IDLenv.date[0]); env.setDate(d); } // Read in the 'received' stamp if(IDLenv.received.length > 0) env.addStamp(unmarshalReceivedObj(IDLenv.received[0])); // Read in the 'user-defined properties' slot if(IDLenv.userDefinedProperties.length > 0) env.clearAllProperties(); for(int i = 0; i < IDLenv.userDefinedProperties.length; i++) { env.addProperties(unmarshalProperty(IDLenv.userDefinedProperties[i])); } } //String tmp = "\n\n"+(new java.util.Date()).toString()+" RECEIVED IIOP MESSAGE"+ "\n" + env.toString() + "\n" + new String(payload); //System.out.println(tmp); //MessageTransportProtocol.log(tmp); //Write in a log file for iiop incoming message // Dispatch the message dispatcher.dispatchMessage(env, payload); } private AID unmarshalAID(FIPA.AgentID id) { AID result = new AID(); result.setName(id.name); for(int i = 0; i < id.addresses.length; i++) result.addAddresses(id.addresses[i]); for(int i = 0; i < id.resolvers.length; i++) result.addResolvers(unmarshalAID(id.resolvers[i])); return result; } private Date unmarshalDateTime(FIPA.DateTime d) { Date result = new Date(); return result; } private Property unmarshalProperty(FIPA.Property p) { return new Property(p.keyword, p.value.extract_Value()); } private ReceivedObject unmarshalReceivedObj(FIPA.ReceivedObject ro) { ReceivedObject result = new ReceivedObject(); result.setBy(ro.by); result.setFrom(ro.from); result.setDate(unmarshalDateTime(ro.date)); result.setId(ro.id); result.setVia(ro.via); return result; } } // End of MTSImpl class private static final String[] PROTOCOLS = new String[] { "IOR", "corbaloc", "corbaname" }; private final ORB myORB; private MTSImpl server; private static PrintWriter logFile; public MessageTransportProtocol() { myORB = ORB.init(new String[0], null); } public TransportAddress activate(InChannel.Dispatcher disp) throws MTPException { server = new MTSImpl(disp); myORB.connect(server); IIOPAddress iiop = new IIOPAddress(myORB, server); /* //Open log file String fileName = "iiop"+iiop.getHost()+iiop.getPort()+".log"; try{ logFile = new PrintWriter(new FileWriter(fileName,true)); }catch(java.io.IOException e){e .printStackTrace();} */ return iiop; } public void activate(InChannel.Dispatcher disp, TransportAddress ta) throws MTPException { throw new MTPException("User supplied transport address not supported."); } public void deactivate(TransportAddress ta) throws MTPException { myORB.disconnect(server); } public void deactivate() throws MTPException { myORB.disconnect(server); } public void deliver(String addr, Envelope env, byte[] payload) throws MTPException { try { TransportAddress ta = strToAddr(addr); IIOPAddress iiopAddr = (IIOPAddress)ta; FIPA.MTS objRef = iiopAddr.getObject(); // verifies if the server object really exists (useful if the IOR is // valid, i.e corresponds to a good object) (e.g. old IOR) // FIXME. To check if this call slows down performance if (objRef._non_existent()) throw new MTPException("Bad IIOP server object reference:" + objRef.toString()); // Fill in the 'to' field of the IDL envelope Iterator itTo = env.getAllTo(); List to = new ArrayList(); while(itTo.hasNext()) { AID id = (AID)itTo.next(); to.add(marshalAID(id)); } FIPA.AgentID[] IDLto = new FIPA.AgentID[to.size()]; for(int i = 0; i < to.size(); i++) IDLto[i] = (FIPA.AgentID)to.get(i); // Fill in the 'from' field of the IDL envelope AID from = env.getFrom(); FIPA.AgentID[] IDLfrom = new FIPA.AgentID[] { marshalAID(from) }; // Fill in the 'intended-receiver' field of the IDL envelope Iterator itIntendedReceiver = env.getAllIntendedReceiver(); List intendedReceiver = new ArrayList(); while(itIntendedReceiver.hasNext()) { AID id = (AID)itIntendedReceiver.next(); intendedReceiver.add(marshalAID(id)); } FIPA.AgentID[] IDLintendedReceiver = new FIPA.AgentID[intendedReceiver.size()]; for(int i = 0; i < intendedReceiver.size(); i++) IDLintendedReceiver[i] = (FIPA.AgentID)intendedReceiver.get(i); // Fill in the 'encrypted' field of the IDL envelope //Iterator itEncrypted = env.getAllEncrypted(); //List encrypted = new ArrayList(); //while(itEncrypted.hasNext()) { //String word = (String)itEncrypted.next(); //encrypted.add(word); String[] IDLencrypted = new String[0]; //String[] IDLencrypted = new String[encrypted.size()]; //for(int i = 0; i < encrypted.size(); i++) //IDLencrypted[i] = (String)encrypted.get(i); // Fill in the other fields of the IDL envelope ... String IDLcomments = env.getComments(); String IDLaclRepresentation = env.getAclRepresentation(); Long payloadLength = env.getPayloadLength(); int IDLpayloadLength = payloadLength.intValue(); String IDLpayloadEncoding = env.getPayloadEncoding(); FIPA.DateTime[] IDLdate = new FIPA.DateTime[] { marshalDateTime(env.getDate()) }; FIPA.Property[][] IDLtransportBehaviour = new FIPA.Property[][] { }; // Fill in the 'userdefined-properties' field of the IDL envelope Iterator itUserDefProps = env.getAllProperties(); List userDefProps = new ArrayList(); while(itUserDefProps.hasNext()) { Property p = (Property)itUserDefProps.next(); userDefProps.add(marshalProperty(p)); } FIPA.Property[] IDLuserDefinedProperties = new FIPA.Property[userDefProps.size()]; for(int i = 0; i < userDefProps.size(); i++) IDLuserDefinedProperties[i] = (FIPA.Property)userDefProps.get(i); // Fill in the list of 'received' stamps /* FIXME: Maybe several IDL Envelopes should be generated, one for every 'received' stamp... ReceivedObject[] received = env.getStamps(); FIPA.ReceivedObject[] IDLreceived = new FIPA.ReceivedObject[received.length]; for(int i = 0; i < received.length; i++) IDLreceived[i] = marshalReceivedObj(received[i]); */ // FIXME: For now, only the current 'received' object is considered... ReceivedObject received = env.getReceived(); FIPA.ReceivedObject[] IDLreceived; if(received != null) IDLreceived = new FIPA.ReceivedObject[] { marshalReceivedObj(received) }; else IDLreceived = new FIPA.ReceivedObject[] { }; FIPA.Envelope IDLenv = new FIPA.Envelope(IDLto, IDLfrom, IDLcomments, IDLaclRepresentation, IDLpayloadLength, IDLpayloadEncoding, IDLdate, IDLencrypted, IDLintendedReceiver, IDLreceived, IDLtransportBehaviour, IDLuserDefinedProperties); FipaMessage msg = new FipaMessage(new FIPA.Envelope[] { IDLenv }, payload); //String tmp = "\n\n"+(new java.util.Date()).toString()+" SENT IIOP MESSAGE"+ "\n" + env.toString() + "\n" + new String(payload); //System.out.println(tmp); //MessageTransportProtocol.log(tmp); // write in a log file for sent iiop message objRef.message(msg); } catch(ClassCastException cce) { cce.printStackTrace(); throw new MTPException("Address mismatch: this is not a valid IIOP address."); } catch(Exception cce2) { cce2.printStackTrace(); throw new MTPException("Address mismatch: this is not a valid IIOP address."); } } public TransportAddress strToAddr(String rep) throws MTPException { return new IIOPAddress(myORB, rep); // FIXME: Should cache object references } public String addrToStr(TransportAddress ta) throws MTPException { try { IIOPAddress addr = (IIOPAddress)ta; return addr.getIOR(); } catch(ClassCastException cce) { throw new MTPException("Address mismatch: this is not a valid IIOP address."); } } public String getName() { return jade.domain.FIPANames.MTP.IIOP; } public String[] getSupportedProtocols() { return PROTOCOLS; } private FIPA.Property marshalProperty(Property p) { org.omg.CORBA.Any value = myORB.create_any(); value.insert_Value((Serializable)p.getValue()); return new FIPA.Property(p.getName(), value); } private FIPA.AgentID marshalAID(AID id) { String name = id.getName(); String[] addresses = id.getAddressesArray(); AID[] resolvers = id.getResolversArray(); FIPA.Property[] userDefinedProperties = new FIPA.Property[] { }; int numOfResolvers = resolvers.length; FIPA.AgentID result = new FIPA.AgentID(name, addresses, new AgentID[numOfResolvers], userDefinedProperties); for(int i = 0; i < numOfResolvers; i++) { result.resolvers[i] = marshalAID(resolvers[i]); // Recursively marshal all resolvers, which are, in turn, AIDs. } return result; } private FIPA.DateTime marshalDateTime(Date d) { Calendar cal = Calendar.getInstance(); cal.setTime(d); short year = (short)cal.get(Calendar.YEAR); short month = (short)cal.get(Calendar.MONTH); short day = (short)cal.get(Calendar.DAY_OF_MONTH); short hour = (short)cal.get(Calendar.HOUR_OF_DAY); short minutes = (short)cal.get(Calendar.MINUTE); short seconds = (short)cal.get(Calendar.SECOND); short milliseconds = 0; // FIXME: This is truncated to the second char typeDesignator = ' '; // FIXME: Uses local timezone ? FIPA.DateTime result = new FIPA.DateTime(year, month, day, hour, minutes, seconds, milliseconds, typeDesignator); return result; } private FIPA.ReceivedObject marshalReceivedObj(ReceivedObject ro) { FIPA.ReceivedObject result = new FIPA.ReceivedObject(); result.by = ro.getBy(); result.from = ro.getFrom(); result.date = marshalDateTime(ro.getDate()); result.id = ro.getId(); result.via = ro.getVia(); return result; } //Method to write on a file the iiop message log file /*public static synchronized void log(String str) { logFile.println(str); logFile.flush(); }*/ } // End of class MessageTransportProtocol /** This class represents an IIOP address. Three syntaxes are allowed for an IIOP address (all case-insensitive): <code> IIOPAddress ::= "ior:" (HexDigit HexDigit+) | "corbaname://" NSHost ":" NSPort "/" NSObjectID "#" objectName | "corbaloc:" HostName ":" portNumber "/" objectID </code> Notice that, in the third case, BIG_ENDIAN is assumed by default. In the first and second case, instead, the endianess information is contained within the IOR definition. **/ class IIOPAddress implements TransportAddress { public static final byte BIG_ENDIAN = 0; public static final byte LITTLE_ENDIAN = 1; private static final String FIPA_2000_TYPE_ID = "IDL:FIPA/MTS:1.0"; private static final String NS_TYPE_ID = "IDL:omg.org/CosNaming/NamingContext"; private static final int TAG_INTERNET_IOP = 0; private static final byte IIOP_MAJOR = 1; private static final byte IIOP_MINOR = 0; private static final byte ASCII_PERCENT = getASCIIByte("%"); private static final byte ASCII_UPPER_A = getASCIIByte("A"); private static final byte ASCII_UPPER_Z = getASCIIByte("Z"); private static final byte ASCII_LOWER_A = getASCIIByte("a"); private static final byte ASCII_LOWER_Z = getASCIIByte("z"); private static final byte ASCII_ZERO = getASCIIByte("0"); private static final byte ASCII_NINE = getASCIIByte("9"); private static final byte ASCII_MINUS = getASCIIByte("-"); private static final byte ASCII_UNDERSCORE = getASCIIByte("_"); private static final byte ASCII_DOT = getASCIIByte("."); private static final byte ASCII_BANG = getASCIIByte("!"); private static final byte ASCII_TILDE = getASCIIByte("~"); private static final byte ASCII_STAR = getASCIIByte("*"); private static final byte ASCII_QUOTE = getASCIIByte("'"); private static final byte ASCII_OPEN_BRACKET = getASCIIByte("("); private static final byte ASCII_CLOSED_BRACKET = getASCIIByte("$"); private static final char[] HEX = { '0','1','2','3','4','5','6','7', '8','9','a','b','c','d','e','f' }; private static final byte getASCIIByte(String ch) { try { return (ch.getBytes("US-ASCII"))[0]; } catch(UnsupportedEncodingException uee) { return 0; } } private final ORB orb; private String ior; private String host; private short port; private String objectKey; private String anchor; private CDRCodec codecStrategy; public IIOPAddress(ORB anOrb, FIPA.MTS objRef) throws MTPException { this(anOrb, anOrb.object_to_string(objRef)); } public IIOPAddress(ORB anOrb, String s) throws MTPException { orb = anOrb; if(s.toLowerCase().startsWith("ior:")) initFromIOR(s); else if(s.toLowerCase().startsWith("corbaloc:")) initFromURL(s, BIG_ENDIAN); else if(s.toLowerCase().startsWith("corbaname:")) initFromNS(s); else throw new MTPException("Invalid string prefix"); } private void initFromIOR(String s) throws MTPException { parseIOR(s, FIPA_2000_TYPE_ID); anchor = ""; } private void initFromURL(String s, short endianness) throws MTPException { // Remove 'corbaloc:' prefix to get URL host, port and file s = s.substring(9); if(s.toLowerCase().startsWith("iiop:")) { // Remove an explicit IIOP specification s = s.substring(5); } else if(s.startsWith(":")) { // Remove implicit IIOP specification s = s.substring(1); } else throw new MTPException("Invalid 'corbaloc' URL: neither 'iiop:' nor ':' was specified."); buildIOR(s, FIPA_2000_TYPE_ID, endianness); } private void initFromNS(String s) throws MTPException { // First perform a 'corbaloc::' resolution to get the IOR of the Naming Service. // Replace 'corbaname:' with 'corbaloc::' StringBuffer buf = new StringBuffer(s); // Use 'corbaloc' support to build a reference on the NamingContext // where the real object reference will be looked up. buf.replace(0, 11, "corbaloc::"); buildIOR(s.substring(11), NS_TYPE_ID, BIG_ENDIAN); org.omg.CORBA.Object o = orb.string_to_object(ior); NamingContext ctx = NamingContextHelper.narrow(o); try { // Transform the string after the '#' sign into a COSNaming::Name. StringTokenizer lexer = new StringTokenizer(anchor, "/.", true); List name = new ArrayList(); while(lexer.hasMoreTokens()) { String tok = lexer.nextToken(); NameComponent nc = new NameComponent(); nc.id = tok; name.add(nc); if(!lexer.hasMoreTokens()) break; // Out of the while loop tok = lexer.nextToken(); if(tok.equals(".")) { // An (id, kind) pair tok = lexer.nextToken(); nc.kind = tok; } else if(!tok.equals("/")) // No separator other than '.' or '/' is allowed throw new MTPException("Ill-formed path into the Naming Service: Unknown separator."); } // Get the object reference stored into the naming service... NameComponent[] path = (NameComponent[])name.toArray(new NameComponent[name.size()]); o = ctx.resolve(path); // Stringify it and use the resulting IOR to initialize yourself String realIOR = orb.object_to_string(o); initFromIOR(realIOR); } catch(NoSuchElementException nsee) { throw new MTPException("Ill-formed path into the Naming Service.", nsee); } catch(UserException ue) { throw new MTPException("CORBA Naming Service user exception.", ue); } catch(SystemException se) { throw new MTPException("CORBA Naming Service system exception.", se); } } private void parseIOR(String s, String typeName) throws MTPException { try { // Store stringified IOR ior = new String(s.toUpperCase()); // Remove 'IOR:' prefix to get Hex digits String hexString = ior.substring(4); short endianness = Short.parseShort(hexString.substring(0, 2), 16); switch(endianness) { case BIG_ENDIAN: codecStrategy = new BigEndianCodec(hexString); break; case LITTLE_ENDIAN: codecStrategy = new LittleEndianCodec(hexString); break; default: throw new MTPException("Invalid endianness specifier"); } try { // Read 'string type_id' field String typeID = codecStrategy.readString(); if(!typeID.equalsIgnoreCase(typeName)) throw new MTPException("Invalid type ID" + typeID); } catch (Exception e) { // all exceptions are converted into MTPException throw new MTPException("Invalid type ID"); } // Read 'sequence<TaggedProfile> profiles' field // Read sequence length int seqLen = codecStrategy.readLong(); for(int i = 0; i < seqLen; i++) { // Read 'ProfileId tag' field int tag = codecStrategy.readLong(); byte[] profile = codecStrategy.readOctetSequence(); if(tag == TAG_INTERNET_IOP) { // Process IIOP profile CDRCodec profileBodyCodec; switch(profile[0]) { case BIG_ENDIAN: profileBodyCodec = new BigEndianCodec(profile); break; case LITTLE_ENDIAN: profileBodyCodec = new LittleEndianCodec(profile); break; default: throw new MTPException("Invalid endianness specifier"); } // Read IIOP version byte versionMajor = profileBodyCodec.readOctet(); byte versionMinor = profileBodyCodec.readOctet(); if(versionMajor != 1) throw new MTPException("IIOP version not supported"); try { // Read 'string host' field host = profileBodyCodec.readString(); } catch (Exception e) { throw new MTPException("Invalid host string"); } // Read 'unsigned short port' field port = profileBodyCodec.readShort(); // Read 'sequence<octet> object_key' field and convert it // into a String object byte[] keyBuffer = profileBodyCodec.readOctetSequence(); ByteArrayOutputStream buf = new ByteArrayOutputStream(); // Escape every forbidden character, as for RFC 2396 (URI: Generic Syntax) for(int ii = 0; ii < keyBuffer.length; ii++) { byte b = keyBuffer[ii]; if(isUnreservedURIChar(b)) { // Write the character 'as is' buf.write(b); } else { // Escape it using '%' buf.write(ASCII_PERCENT); buf.write(HEX[(b & 0xF0) >> 4]); // High nibble buf.write(HEX[b & 0x0F]); // Low nibble } } objectKey = buf.toString("US-ASCII"); codecStrategy = null; } } } catch (Exception e) { // all exceptions are converted into MTPException throw new MTPException(e.getMessage()); } } private void buildIOR(String s, String typeName, short endianness) throws MTPException { int colonPos = s.indexOf(':'); int slashPos = s.indexOf('/'); int poundPos = s.indexOf(' if((colonPos == -1) || (slashPos == -1)) throw new MTPException("Invalid URL string"); host = new String(s.substring(0, colonPos)); port = Short.parseShort(s.substring(colonPos + 1, slashPos)); if(poundPos == -1) { objectKey = new String(s.substring(slashPos + 1, s.length())); anchor = ""; } else { objectKey = new String(s.substring(slashPos + 1, poundPos)); anchor = new String(s.substring(poundPos + 1, s.length())); } switch(endianness) { case BIG_ENDIAN: codecStrategy = new BigEndianCodec(new byte[0]); break; case LITTLE_ENDIAN: codecStrategy = new LittleEndianCodec(new byte[0]); break; default: throw new MTPException("Invalid endianness specifier"); } codecStrategy.writeString(typeName); // Write '1' as profiles sequence length codecStrategy.writeLong(1); codecStrategy.writeLong(TAG_INTERNET_IOP); CDRCodec profileBodyCodec; switch(endianness) { case BIG_ENDIAN: profileBodyCodec = new BigEndianCodec(new byte[0]); break; case LITTLE_ENDIAN: profileBodyCodec = new LittleEndianCodec(new byte[0]); break; default: throw new MTPException("Invalid endianness specifier"); } // Write IIOP 1.0 profile to auxiliary CDR codec profileBodyCodec.writeOctet(IIOP_MAJOR); profileBodyCodec.writeOctet(IIOP_MINOR); profileBodyCodec.writeString(host); profileBodyCodec.writeShort(port); try { byte[] objKey = objectKey.getBytes("US-ASCII"); // Remove all the RFC 2396 escape sequences... ByteArrayOutputStream buf = new ByteArrayOutputStream(); for(int i = 0; i < objKey.length; i++) { byte b = objKey[i]; if(b != ASCII_PERCENT) buf.write(b); else { // Get the hex value represented by the two bytes after '%' try { String hexPair = new String(objKey, i + 1, 2, "US-ASCII"); short sh = Short.parseShort(hexPair, 16); if(sh > Byte.MAX_VALUE) b = (byte)(sh + 2*Byte.MIN_VALUE); // Conversion from unsigned to signed else b = (byte)sh; } catch(UnsupportedEncodingException uee) { b = 0; } buf.write(b); i += 2; } } profileBodyCodec.writeOctetSequence(buf.toByteArray()); byte[] encapsulatedProfile = profileBodyCodec.writtenBytes(); // Write encapsulated profile to main IOR codec codecStrategy.writeOctetSequence(encapsulatedProfile); String hexString = codecStrategy.writtenString(); ior = "IOR:" + hexString; codecStrategy = null; } catch(UnsupportedEncodingException uee) { // It should never happen uee.printStackTrace(); } } // This method returns true if and only if the supplied byte, // interpreted as an US-ASCII encoded character, corresponds to an // unreserved URI character. See RFC 2396 for details. private boolean isUnreservedURIChar(byte b) { // An upper case letter? if((ASCII_UPPER_A <= b)&&(ASCII_UPPER_Z >= b)) return true; // A lower case letter? if((ASCII_LOWER_A <= b)&&(ASCII_LOWER_Z >= b)) return true; // A decimal digit? if((ASCII_ZERO <= b)&&(ASCII_NINE >= b)) return true; // An unreserved, but not alphanumeric character? if((b == ASCII_MINUS)||(b == ASCII_UNDERSCORE)||(b == ASCII_DOT)||(b == ASCII_BANG)||(b == ASCII_TILDE)|| (b == ASCII_STAR)||(b == ASCII_QUOTE)||(b == ASCII_OPEN_BRACKET)||(b == ASCII_CLOSED_BRACKET)) return true; // Anything else is not allowed return false; } public String getURL() { int portNum = port; if(portNum < 0) portNum += 65536; return "corbaloc::" + host + ":" + portNum + "/" + objectKey; } public String getIOR() { return ior; } public FIPA.MTS getObject() { return FIPA.MTSHelper.narrow(orb.string_to_object(ior)); } private static abstract class CDRCodec { protected byte[] readBuffer; protected StringBuffer writeBuffer; protected int readIndex = 0; protected int writeIndex = 0; protected CDRCodec(String hexString) { // Put all Hex digits into a byte array readBuffer = bytesFromHexString(hexString); readIndex = 1; writeBuffer = new StringBuffer(255); } protected CDRCodec(byte[] hexDigits) { readBuffer = new byte[hexDigits.length]; System.arraycopy(hexDigits, 0, readBuffer, 0, readBuffer.length); readIndex = 1; writeBuffer = new StringBuffer(255); } public String writtenString() { return new String(writeBuffer); } public byte[] writtenBytes() { return bytesFromHexString(new String(writeBuffer)); } public byte readOctet() { return readBuffer[readIndex++]; } public byte[] readOctetSequence() { int seqLen = readLong(); byte[] result = new byte[seqLen]; System.arraycopy(readBuffer, readIndex, result, 0, seqLen); readIndex += seqLen; return result; } public String readString() { int strLen = readLong(); // This includes '\0' terminator String result = new String(readBuffer, readIndex, strLen - 1); readIndex += strLen; return result; } // These depend on endianness, so are deferred to subclasses public abstract short readShort(); // 16 bits public abstract int readLong(); // 32 bits public abstract long readLongLong(); // 64 bits // Writes a couple of hexadecimal digits representing the given byte. // All other marshalling operations ultimately use this method to modify // the write buffer public void writeOctet(byte b) { char[] digits = new char[2]; digits[0] = HEX[(b & 0xF0) >> 4]; // High nibble digits[1] = HEX[b & 0x0F]; // Low nibble writeBuffer.append(digits); writeIndex++; } public void writeOctetSequence(byte[] seq) { int seqLen = seq.length; writeLong(seqLen); for(int i = 0; i < seqLen; i++) writeOctet(seq[i]); } public void writeString(String s) { int strLen = s.length() + 1; // This includes '\0' terminator writeLong(strLen); byte[] bytes = s.getBytes(); for(int i = 0; i < s.length(); i++) writeOctet(bytes[i]); writeOctet((byte)0x00); } // These depend on endianness, so are deferred to subclasses public abstract void writeShort(short s); // 16 bits public abstract void writeLong(int i); // 32 bits public abstract void writeLongLong(long l); // 64 bits protected void setReadAlignment(int align) { while((readIndex % align) != 0) readIndex++; } protected void setWriteAlignment(int align) { while(writeIndex % align != 0) writeOctet((byte)0x00); } private byte[] bytesFromHexString(String hexString) { int hexLen = hexString.length() / 2; byte[] result = new byte[hexLen]; for(int i = 0; i < hexLen; i ++) { String currentDigit = hexString.substring(2*i, 2*(i + 1)); Short s = Short.valueOf(currentDigit, 16); result[i] = s.byteValue(); } return result; } } // End of CDRCodec class private static class BigEndianCodec extends CDRCodec { public BigEndianCodec(String ior) { super(ior); writeOctet((byte)0x00); // Writes 'Big Endian' magic number } public BigEndianCodec(byte[] hexDigits) { super(hexDigits); writeOctet((byte)0x00); // Writes 'Big Endian' magic number } public short readShort() { setReadAlignment(2); short result = (short)((readBuffer[readIndex++] << 8) + readBuffer[readIndex++]); return result; } public int readLong() { setReadAlignment(4); int result = (readBuffer[readIndex++] << 24) + (readBuffer[readIndex++] << 16); result += (readBuffer[readIndex++] << 8) + readBuffer[readIndex++]; return result; } public long readLongLong() { setReadAlignment(8); long result = (readBuffer[readIndex++] << 56) + (readBuffer[readIndex++] << 48); result += (readBuffer[readIndex++] << 40) + (readBuffer[readIndex++] << 32); result += (readBuffer[readIndex++] << 24) + (readBuffer[readIndex++] << 16); result += (readBuffer[readIndex++] << 8) + readBuffer[readIndex++]; return result; } public void writeShort(short s) { setWriteAlignment(2); writeOctet((byte)((s & 0xFF00) >> 8)); writeOctet((byte)(s & 0x00FF)); } public void writeLong(int i) { setWriteAlignment(4); writeOctet((byte)((i & 0xFF000000) >> 24)); writeOctet((byte)((i & 0x00FF0000) >> 16)); writeOctet((byte)((i & 0x0000FF00) >> 8)); writeOctet((byte)(i & 0x000000FF)); } public void writeLongLong(long l) { setWriteAlignment(8); writeOctet((byte)((l & 0xFF00000000000000L) >> 56)); writeOctet((byte)((l & 0x00FF000000000000L) >> 48)); writeOctet((byte)((l & 0x0000FF0000000000L) >> 40)); writeOctet((byte)((l & 0x000000FF00000000L) >> 32)); writeOctet((byte)((l & 0x00000000FF000000L) >> 24)); writeOctet((byte)((l & 0x0000000000FF0000L) >> 16)); writeOctet((byte)((l & 0x000000000000FF00L) >> 8)); writeOctet((byte)(l & 0x00000000000000FFL)); } } // End of BigEndianCodec class private static class LittleEndianCodec extends CDRCodec { public LittleEndianCodec(String ior) { super(ior); writeOctet((byte)0x01); // Writes 'Little Endian' magic number } public LittleEndianCodec(byte[] hexDigits) { super(hexDigits); writeOctet((byte)0x01); // Writes 'Little Endian' magic number } public short readShort() { setReadAlignment(2); short result = (short)(readBuffer[readIndex++] + (readBuffer[readIndex++] << 8)); return result; } public int readLong() { setReadAlignment(4); int result = readBuffer[readIndex++] + (readBuffer[readIndex++] << 8) + (readBuffer[readIndex++] << 16) + (readBuffer[readIndex++] << 24); return result; } public long readLongLong() { setReadAlignment(8); long result = readBuffer[readIndex++] + (readBuffer[readIndex++] << 8); result += (readBuffer[readIndex++] << 16) + (readBuffer[readIndex++] << 24); result += (readBuffer[readIndex++] << 32) + (readBuffer[readIndex++] << 40); result += (readBuffer[readIndex++] << 48) + (readBuffer[readIndex++] << 56); return result; } public void writeShort(short s) { setWriteAlignment(2); writeOctet((byte)(s & 0x00FF)); writeOctet((byte)((s & 0xFF00) >> 8)); } public void writeLong(int i) { setWriteAlignment(4); writeOctet((byte)(i & 0x000000FF)); writeOctet((byte)((i & 0x0000FF00) >> 8)); writeOctet((byte)((i & 0x00FF0000) >> 16)); writeOctet((byte)((i & 0xFF000000) >> 24)); } public void writeLongLong(long l) { setWriteAlignment(8); writeOctet((byte)(l & 0x00000000000000FFL)); writeOctet((byte)((l & 0x000000000000FF00L) >> 8)); writeOctet((byte)((l & 0x0000000000FF0000L) >> 16)); writeOctet((byte)((l & 0x00000000FF000000L) >> 24)); writeOctet((byte)((l & 0x000000FF00000000L) >> 32)); writeOctet((byte)((l & 0x0000FF0000000000L) >> 40)); writeOctet((byte)((l & 0x00FF000000000000L) >> 48)); writeOctet((byte)((l & 0xFF00000000000000L) >> 56)); } } // End of LittleEndianCodec class public String getProto() { return "iiop"; } public String getHost() { return host; } public String getPort() { return Short.toString(port); } public String getFile() { return objectKey; } public String getAnchor() { return anchor; } } // End of IIOPAddress class
package org.apache.commons.lang.enum; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Abstract superclass for type-safe enums. * <p> * One feature of the C programming language lacking in Java is enumerations. The * C implementation based on ints was poor and open to abuse. The original Java * recommendation and most of the JDK also uses int constants. It has been recognised * however that a more robust type-safe class-based solution can be designed. This * class follows the basic Java type-safe enumeration pattern. * <p> * <em>NOTE:</em>Due to the way in which Java ClassLoaders work, comparing Enum objects * should always be done using the equals() method, not ==. The equals() method will * try == first so in most cases the effect is the same. * * <h4>Simple Enums</h4> * To use this class, it must be subclassed. For example: * * <pre> * public final class ColorEnum extends Enum { * public static final ColorEnum RED = new ColorEnum("Red"); * public static final ColorEnum GREEN = new ColorEnum("Green"); * public static final ColorEnum BLUE = new ColorEnum("Blue"); * * private ColorEnum(String color) { * super(color); * } * * public static ColorEnum getEnum(String color) { * return (ColorEnum) getEnum(ColorEnum.class, color); * } * * public static Map getEnumMap() { * return getEnumMap(ColorEnum.class); * } * * public static List getEnumList() { * return getEnumList(ColorEnum.class); * } * * public static Iterator iterator() { * return iterator(ColorEnum.class); * } * } * </pre> * <p> * As shown, each enum has a name. This can be accessed using <code>getName</code>. * <p> * The <code>getEnum</code> and <code>iterator</code> methods are recommended. * Unfortunately, Java restrictions require these to be coded as shown in each subclass. * An alternative choice is to use the {@link EnumUtils} class. * * <h4>Subclassed Enums</h4> * A hierarchy of Enum classes can be built. In this case, the superclass is * unaffected by the addition of subclasses (as per normal Java). The subclasses * may add additional Enum constants <i>of the type of the superclass</i>. The * query methods on the subclass will return all of the Enum constants from the * superclass and subclass. * * <pre> * public class ExtraColorEnum extends ColorEnum { * // NOTE: Color enum declared above is final, change that to get this * // example to compile. * public static final ColorEnum YELLOW = new ExtraColorEnum("Yellow"); * * private ExtraColorEnum(String color) { * super(color); * } * * public static ColorEnum getEnum(String color) { * return (ColorEnum) getEnum(ExtraColorEnum.class, color); * } * * public static Map getEnumMap() { * return getEnumMap(ExtraColorEnum.class); * } * * public static List getEnumList() { * return getEnumList(ExtraColorEnum.class); * } * * public static Iterator iterator() { * return iterator(ExtraColorEnum.class); * } * } * </pre> * * This example will return RED, GREEN, BLUE, YELLOW from the List and iterator * methods in that order. The RED, GREEN and BLUE instances will be the same (==) * as those from the superclass ColorEnum. Note that YELLOW is declared as a * ColorEnum and not an ExtraColorEnum. * * <h4>Functional Enums</h4> * The enums can have functionality by using anonymous inner classes * [Effective Java, Bloch01]: * * <pre> * public abstract class OperationEnum extends Enum { * public static final OperationEnum PLUS = new OperationEnum("Plus") { * public double eval(double a, double b) { * return (a + b); * } * }; * public static final OperationEnum MINUS = new OperationEnum("Minus") { * public double eval(double a, double b) { * return (a - b); * } * }; * * private OperationEnum(String color) { * super(color); * } * * public abstract double eval(double a, double b); * * public static OperationEnum getEnum(String name) { * return (OperationEnum) getEnum(OperationEnum.class, name); * } * * public static Map getEnumMap() { * return getEnumMap(OperationEnum.class); * } * * public static List getEnumList() { * return getEnumList(OperationEnum.class); * } * * public static Iterator iterator() { * return iterator(OperationEnum.class); * } * } * </pre> * <p> * <em>NOTE:</em> This class originated in the Jakarta Avalon project. * </p> * * @author Stephen Colebourne * @author Chris Webb * @author Mike Bowler * @since 1.0 * @version $Id: Enum.java,v 1.9 2003/02/04 18:42:50 scolebourne Exp $ */ public abstract class Enum implements Comparable, Serializable { /** * An empty map, as JDK1.2 didn't have an empty map */ private static final Map EMPTY_MAP = Collections.unmodifiableMap(new HashMap(1)); /** * Map, key of class name, value of Entry. */ private static final Map cEnumClasses = new HashMap(61); /** * The string representation of the Enum. */ private final String iName; /** * Enable the iterator to retain the source code order */ private static class Entry { /** Map of Enum name to Enum */ final Map map = new HashMap(61); /** List of Enums in source code order */ final List list = new ArrayList(25); /** * Restrictive constructor */ private Entry() { } } protected Enum(String name) { super(); if (name == null || name.length() == 0) { throw new IllegalArgumentException("The Enum name must not be empty or null"); } iName = name; Class enumClass = Enum.getEnumClass(getClass()); Entry entry = (Entry) cEnumClasses.get(enumClass); if (entry == null) { entry = createEntry(getClass()); cEnumClasses.put(enumClass, entry); } if (entry.map.containsKey(name)) { throw new IllegalArgumentException("The Enum name must be unique, '" + name + "' has already been added"); } entry.map.put(name, this); entry.list.add(this); } protected Object readResolve() { Entry entry = (Entry) cEnumClasses.get(Enum.getEnumClass(getClass())); if (entry == null) { return null; } return (Enum) entry.map.get(getName()); } protected static Enum getEnum(Class enumClass, String name) { Entry entry = getEntry(enumClass); if (entry == null) { return null; } return (Enum) entry.map.get(name); } protected static Map getEnumMap(Class enumClass) { Entry entry = getEntry(enumClass); if (entry == null) { return EMPTY_MAP; } return Collections.unmodifiableMap(entry.map); } protected static List getEnumList(Class enumClass) { Entry entry = getEntry(enumClass); if (entry == null) { return Collections.EMPTY_LIST; } return Collections.unmodifiableList(entry.list); } protected static Iterator iterator(Class enumClass) { return Enum.getEnumList(enumClass).iterator(); } /** * Gets an entry from the map of Enums. * * @param enumClass the class of the Enum to get * @return the enum entry */ private static Entry getEntry(Class enumClass) { if (enumClass == null) { throw new IllegalArgumentException("The Enum Class must not be null"); } if (Enum.class.isAssignableFrom(enumClass) == false) { throw new IllegalArgumentException("The Class must be a subclass of Enum"); } Entry entry = (Entry) cEnumClasses.get(enumClass); return entry; } /** * Creates an entry for storing the Enums. * This accounts for subclassed Enums. * * @param enumClass the class of the Enum to get * @return the enum entry */ private static Entry createEntry(Class enumClass) { Entry entry = new Entry(); Class cls = enumClass.getSuperclass(); while (cls != null && cls != Enum.class && cls != ValuedEnum.class) { Entry loopEntry = (Entry) cEnumClasses.get(cls); if (loopEntry != null) { entry.list.addAll(loopEntry.list); entry.map.putAll(loopEntry.map); break; // stop here, as this will already have had superclasses added } cls = cls.getSuperclass(); } return entry; } /** * Convert a class to the actual common enum class. * This accounts for anonymous inner classes. * * @param cls the class to get the name for * @return the class name */ protected static Class getEnumClass(Class cls) { String className = cls.getName(); int index = className.lastIndexOf('$'); if (index > -1) { // is it an anonymous inner class? String inner = className.substring(index + 1); if (inner.length() > 0 && inner.charAt(0) >= '0' && inner.charAt(0) < '9') { return cls.getSuperclass(); } } return cls; } /** * Retrieve the name of this Enum item, set in the constructor. * * @return the <code>String</code> name of this Enum item */ public final String getName() { return iName; } /** * Tests for equality. Two Enum objects are considered equal * if they have the same class names and the same names. * Identity is tested for first, so this method usually runs fast. * * @param other the other object to compare for equality * @return true if the Enums are equal */ public final boolean equals(Object other) { if (other == this) { return true; } else if (other == null) { return false; } else if (other.getClass() == this.getClass()) { // shouldn't happen, but... return iName.equals(((Enum) other).iName); } else if (getEnumClass(other.getClass()).getName().equals(getEnumClass(this.getClass()).getName())) { // different classloaders try { // try to avoid reflection return iName.equals(((Enum) other).iName); } catch (ClassCastException ex) { // use reflection try { Method mth = other.getClass().getMethod("getName", null); String name = (String) mth.invoke(other, null); return iName.equals(name); } catch (NoSuchMethodException ex2) { // ignore - should never happen } catch (IllegalAccessException ex2) { // ignore - should never happen } catch (InvocationTargetException ex2) { // ignore - should never happen } return false; } } else { return false; } } /** * Returns a suitable hashCode for the enumeration. * * @return a hashcode based on the name */ public final int hashCode() { return 7 + iName.hashCode(); } /** * Tests for order. The default ordering is alphabetic by name, but this * can be overridden by subclasses. * * @see java.lang.Comparable#compareTo(Object) * @param other the other object to compare to * @return -ve if this is less than the other object, +ve if greater than, 0 of equal * @throws ClassCastException if other is not an Enum * @throws NullPointerException if other is null */ public int compareTo(Object other) { return iName.compareTo(((Enum) other).iName); } /** * Human readable description of this Enum item. For use when debugging. * * @return String in the form <code>type[name]</code>, for example: * <code>Color[Red]</code>. Note that the package name is stripped from * the type name. */ public String toString() { String shortName = Enum.getEnumClass(getClass()).getName(); int pos = shortName.lastIndexOf('.'); if (pos != -1) { shortName = shortName.substring(pos + 1); } shortName = shortName.replace('$', '.'); return shortName + "[" + getName() + "]"; } }
package com.faforever.api.map; import com.faforever.api.config.FafApiProperties; import com.faforever.api.content.ContentService; import com.faforever.api.data.domain.BanDurationType; import com.faforever.api.data.domain.BanLevel; import com.faforever.api.data.domain.Map; import com.faforever.api.data.domain.MapVersion; import com.faforever.api.data.domain.Player; import com.faforever.api.error.ApiException; import com.faforever.api.error.Error; import com.faforever.api.error.ErrorCode; import com.faforever.api.map.MapNameValidationResponse.FileNames; import com.faforever.api.utils.FilePermissionUtil; import com.faforever.api.utils.NameUtil; import com.faforever.commons.io.Unzipper; import com.faforever.commons.io.Zipper; import com.faforever.commons.map.PreviewGenerator; import com.google.common.annotations.VisibleForTesting; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.compress.archivers.ArchiveException; import org.luaj.vm2.LuaError; import org.luaj.vm2.LuaValue; import org.springframework.cache.annotation.CacheEvict; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import org.springframework.util.FileSystemUtils; import org.springframework.util.StringUtils; import org.springframework.web.client.HttpClientErrorException; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.faforever.api.map.MapService.ScenarioMapInfo.CONFIGURATION_STANDARD_TEAMS_ARMIES; import static com.faforever.api.map.MapService.ScenarioMapInfo.CONFIGURATION_STANDARD_TEAMS_NAME; import static com.faforever.api.map.MapService.ScenarioMapInfo.FILE_DECLARATION_MAP; import static com.faforever.api.map.MapService.ScenarioMapInfo.FILE_DECLARATION_SAVE; import static com.faforever.api.map.MapService.ScenarioMapInfo.FILE_DECLARATION_SCRIPT; import static com.faforever.api.map.MapService.ScenarioMapInfo.FILE_ENDING_MAP; import static com.faforever.api.map.MapService.ScenarioMapInfo.FILE_ENDING_SAVE; import static com.faforever.api.map.MapService.ScenarioMapInfo.FILE_ENDING_SCENARIO; import static com.faforever.api.map.MapService.ScenarioMapInfo.FILE_ENDING_SCRIPT; import static com.faforever.api.map.MapService.ScenarioMapInfo.MANDATORY_FILES; import static com.github.nocatch.NoCatch.noCatch; import static java.text.MessageFormat.format; @Service @Slf4j @AllArgsConstructor public class MapService { private static final Pattern MAP_NAME_INVALID_CHARACTER_PATTERN = Pattern.compile("[a-zA-Z0-9\\- ]+"); private static final Pattern MAP_NAME_DOES_NOT_START_WITH_LETTER_PATTERN = Pattern.compile("^[^a-zA-Z]+"); private static final Pattern ADAPTIVE_MAP_PATTERN = Pattern.compile("AdaptiveMap\\w=\\wtrue"); private static final int MAP_NAME_MINUS_MAX_OCCURENCE = 3; private static final int MAP_NAME_MIN_LENGTH = 4; private static final int MAP_NAME_MAX_LENGTH = 50; private static final String[] ADAPTIVE_REQUIRED_FILES = new String[]{ "_options.lua", "_tables.lua", }; private static final Charset MAP_CHARSET = StandardCharsets.ISO_8859_1; private static final String LEGACY_FOLDER_PREFIX = "maps/"; private final FafApiProperties fafApiProperties; private final MapRepository mapRepository; private final ContentService contentService; public MapNameValidationResponse requestMapNameValidation(String mapName) { Assert.notNull(mapName, "The map name is mandatory."); validateMapName(mapName); MapNameBuilder mapNameBuilder = new MapNameBuilder(mapName); int nextVersion = mapRepository.findOneByDisplayName(mapNameBuilder.getDisplayName()) .map(map -> map.getVersions().stream() .mapToInt(MapVersion::getVersion) .map(i -> i + 1) .max() .orElse(1)) .orElse(1); return MapNameValidationResponse.builder() .displayName(mapNameBuilder.getDisplayName()) .nextVersion(nextVersion) .folderName(mapNameBuilder.buildFolderName(nextVersion)) .fileNames( FileNames.builder() .scmap(mapNameBuilder.buildFileName(FILE_ENDING_MAP)) .scenarioLua(mapNameBuilder.buildFileName(FILE_ENDING_SCENARIO)) .scriptLua(mapNameBuilder.buildFileName(FILE_ENDING_SCRIPT)) .saveLua(mapNameBuilder.buildFileName(FILE_ENDING_SAVE)) .build() ) .build(); } @VisibleForTesting void validateMapName(String mapName) { List<Error> errors = new ArrayList<>(); if (!MAP_NAME_INVALID_CHARACTER_PATTERN.matcher(mapName).matches()) { errors.add(new Error(ErrorCode.MAP_NAME_INVALID_CHARACTER)); } if (mapName.length() < MAP_NAME_MIN_LENGTH) { errors.add(new Error(ErrorCode.MAP_NAME_TOO_SHORT, MAP_NAME_MIN_LENGTH, mapName.length())); } if (mapName.length() > MAP_NAME_MAX_LENGTH) { errors.add(new Error(ErrorCode.MAP_NAME_TOO_LONG, MAP_NAME_MAX_LENGTH, mapName.length())); } if (StringUtils.countOccurrencesOf(mapName, "-") > MAP_NAME_MINUS_MAX_OCCURENCE) { errors.add(new Error(ErrorCode.MAP_NAME_INVALID_MINUS_OCCURENCE, MAP_NAME_MINUS_MAX_OCCURENCE)); } if (MAP_NAME_DOES_NOT_START_WITH_LETTER_PATTERN.matcher(mapName).find()) { errors.add(new Error(ErrorCode.MAP_NAME_DOES_NOT_START_WITH_LETTER)); } if (!errors.isEmpty()) { throw new ApiException(errors.toArray(new Error[0])); } } @VisibleForTesting void validateScenarioLua(String scenarioLua) { try { MapLuaAccessor mapLua = MapLuaAccessor.of(scenarioLua); MapNameBuilder mapNameBuilder = new MapNameBuilder(mapLua.getName() .orElseThrow(() -> ApiException.of(ErrorCode.MAP_NAME_MISSING))); validateScenarioLua(mapLua, mapNameBuilder); } catch (IOException | LuaError e) { throw ApiException.of(ErrorCode.PARSING_LUA_FILE_FAILED, e.getMessage()); } } @Transactional @SneakyThrows @CacheEvict(value = {Map.TYPE_NAME, MapVersion.TYPE_NAME}, allEntries = true) public void uploadMap(InputStream mapDataInputStream, String mapFilename, Player author, boolean isRanked) { Assert.notNull(author, "'author' must not be null"); Assert.isTrue(mapDataInputStream.available() > 0, "'mapData' must not be empty"); checkAuthorVaultBan(author); Path rootTempFolder = contentService.createTempDir(); try (mapDataInputStream) { Path unzippedFileFolder = unzipToTemporaryDirectory(mapDataInputStream, rootTempFolder); Path mapFolder = validateMapFolderStructure(unzippedFileFolder); validateRequiredFiles(mapFolder, MANDATORY_FILES); MapLuaAccessor mapLua = parseScenarioLua(mapFolder); MapNameBuilder mapNameBuilder = new MapNameBuilder(mapLua.getName() .orElseThrow(() -> ApiException.of(ErrorCode.MAP_NAME_MISSING))); mapLua.isAdaptive().ifPresent(isAdaptive -> { if (isAdaptive) { validateRequiredFiles(mapFolder, ADAPTIVE_REQUIRED_FILES); } }); validateScenarioLua(mapLua, mapNameBuilder); Optional<Map> existingMapOptional = validateMapMetadata(mapLua, mapNameBuilder, author); updateHibernateMapEntities(mapLua, existingMapOptional, author, isRanked, mapNameBuilder); Path mapFolderAfterRenaming = unzippedFileFolder.resolveSibling( mapNameBuilder.buildFolderName(mapLua.getMapVersion$())); Files.move(mapFolder, mapFolderAfterRenaming); updateLuaFiles(mapFolder, mapFolderAfterRenaming); generatePreview(mapFolderAfterRenaming); zipMapData(mapFolderAfterRenaming, mapNameBuilder.buildFinalZipPath(mapLua.getMapVersion$())); } finally { FileSystemUtils.deleteRecursively(rootTempFolder); } } private void checkAuthorVaultBan(Player author) { author.getActiveBanOf(BanLevel.VAULT) .ifPresent((banInfo) -> { String message = banInfo.getDuration() == BanDurationType.PERMANENT ? "You are permanently banned from uploading maps to the vault." : format("You are banned from uploading maps to the vault until {0}.", banInfo.getExpiresAt()); throw HttpClientErrorException.create(message, HttpStatus.FORBIDDEN, "Upload forbidden", HttpHeaders.EMPTY, null, null); }); } private Path unzipToTemporaryDirectory(InputStream mapDataInputStream, Path rootTempFolder) throws IOException, ArchiveException { Path unzippedDirectory = Files.createDirectories(rootTempFolder.resolve("unzipped-content")); log.debug("Unzipping uploaded file ''{}'' to: {}", mapDataInputStream, unzippedDirectory); Unzipper.from(mapDataInputStream) .zipBombByteCountThreshold(5_000_000) .zipBombProtectionFactor(200) .to(unzippedDirectory) .unzip(); return unzippedDirectory; } /** * @param zipContentFolder The folder containing the content of the zipped map file * @return the root folder of the map */ private Path validateMapFolderStructure(Path zipContentFolder) throws IOException { Path mapFolder; try (Stream<Path> mapFolderStream = Files.list(zipContentFolder)) { mapFolder = mapFolderStream .filter(Files::isDirectory) .findFirst() .orElseThrow(() -> ApiException.of(ErrorCode.MAP_MISSING_MAP_FOLDER_INSIDE_ZIP)); } try (Stream<Path> mapFolderStream = Files.list(zipContentFolder)) { if (mapFolderStream.count() != 1) { throw ApiException.of(ErrorCode.MAP_INVALID_ZIP); } } return mapFolder; } @SneakyThrows private void validateRequiredFiles(Path mapFolder, String[] requiredFiles) { try (Stream<Path> mapFileStream = Files.list(mapFolder)) { List<String> fileNames = mapFileStream .map(Path::toString) .collect(Collectors.toList()); List<Error> errors = Arrays.stream(requiredFiles) .filter(requiredEnding -> fileNames.stream().noneMatch(fileName -> fileName.endsWith(requiredEnding))) .map(requiredEnding -> new Error(ErrorCode.MAP_FILE_INSIDE_ZIP_MISSING, requiredEnding)) .collect(Collectors.toList()); if (!errors.isEmpty()) { throw ApiException.of(errors); } } } private MapLuaAccessor parseScenarioLua(Path mapFolder) throws IOException { try (Stream<Path> mapFilesStream = Files.list(mapFolder)) { Path scenarioLuaPath = mapFilesStream .filter(myFile -> myFile.toString().endsWith(FILE_ENDING_SCENARIO)) .findFirst() .orElseThrow(() -> ApiException.of(ErrorCode.MAP_SCENARIO_LUA_MISSING)); return MapLuaAccessor.of(scenarioLuaPath); } catch (LuaError e) { throw ApiException.of(ErrorCode.PARSING_LUA_FILE_FAILED, e.getMessage()); } } private void validateScenarioLua(MapLuaAccessor mapLua, MapNameBuilder mapNameBuilder) { List<Error> errors = new ArrayList<>(); validateLuaPathVariable(mapLua, FILE_DECLARATION_MAP, mapNameBuilder, FILE_ENDING_MAP).ifPresent(errors::add); validateLuaPathVariable(mapLua, FILE_DECLARATION_SAVE, mapNameBuilder, FILE_ENDING_SAVE).ifPresent(errors::add); validateLuaPathVariable(mapLua, FILE_DECLARATION_SCRIPT, mapNameBuilder, FILE_ENDING_SCRIPT).ifPresent(errors::add); if (mapLua.getDescription().isEmpty()) { errors.add(new Error(ErrorCode.MAP_DESCRIPTION_MISSING)); } if (mapLua.hasInvalidTeam()) { errors.add(new Error(ErrorCode.MAP_FIRST_TEAM_FFA)); } if (mapLua.getType().isEmpty()) { errors.add(new Error(ErrorCode.MAP_TYPE_MISSING)); } if (mapLua.getSize().isEmpty()) { errors.add(new Error(ErrorCode.MAP_SIZE_MISSING)); } if (mapLua.getMapVersion().isEmpty()) { errors.add(new Error(ErrorCode.MAP_VERSION_MISSING)); } if (mapLua.getNoRushRadius().isEmpty()) { // The game can start without it, but the GPG map editor will crash on opening such a map. errors.add(new Error(ErrorCode.NO_RUSH_RADIUS_MISSING)); } if (!errors.isEmpty()) { throw ApiException.of(errors); } } private Optional<Error> validateLuaPathVariable(MapLuaAccessor mapLua, String variableName, MapNameBuilder mapNameBuilder, String fileEnding) { String mapFileName = mapNameBuilder.buildFileName(fileEnding); String mapFolderNameWithoutVersion = mapNameBuilder.buildFolderNameWithoutVersion(); String regex = format("\\/maps\\/{0}(\\.v\\d{4})?\\/{1}", mapFolderNameWithoutVersion, mapFileName); if (!mapLua.hasVariableMatchingIgnoreCase(regex, variableName)) { return Optional.of(new Error(ErrorCode.MAP_SCRIPT_LINE_MISSING, format("{0} = ''/maps/{1}/{2}''", variableName, mapFolderNameWithoutVersion, mapFileName))); } return Optional.empty(); } private Optional<Map> validateMapMetadata(MapLuaAccessor mapLua, MapNameBuilder mapNameBuilder, Player author) { String displayName = mapNameBuilder.getDisplayName(); validateMapName(displayName); int newVersion = mapLua.getMapVersion() .orElseThrow(() -> ApiException.of(ErrorCode.MAP_VERSION_MISSING)); if (Files.exists(mapNameBuilder.buildFinalZipPath(newVersion))) { throw ApiException.of(ErrorCode.MAP_NAME_CONFLICT, mapNameBuilder.buildFinalZipName(newVersion)); } Optional<Map> existingMapOptional = mapRepository.findOneByDisplayName(displayName); existingMapOptional .ifPresent(existingMap -> { Optional.ofNullable(existingMap.getAuthor()) .filter(existingMapAuthor -> !Objects.equals(existingMapAuthor, author)) .ifPresent(existingMapAuthor -> { throw ApiException.of(ErrorCode.MAP_NOT_ORIGINAL_AUTHOR, existingMap.getDisplayName()); }); if (existingMap.getVersions().stream() .anyMatch(mapVersion -> mapVersion.getVersion() == newVersion)) { throw ApiException.of(ErrorCode.MAP_VERSION_EXISTS, existingMap.getDisplayName(), newVersion); } }); return existingMapOptional; } private Map updateHibernateMapEntities(MapLuaAccessor mapLua, Optional<Map> existingMapOptional, Player author, boolean isRanked, MapNameBuilder mapNameBuilder) { // the scenario lua is supposed to be validate already, thus we call the unwrapping $-methods String mapName = mapNameBuilder.getDisplayName(); Map map = existingMapOptional .orElseGet(() -> new Map() .setDisplayName(mapName) .setAuthor(author) ); LuaValue standardTeamsConfig = mapLua.getFirstTeam$(); map .setMapType(mapLua.getType$()) .setBattleType(standardTeamsConfig.get(CONFIGURATION_STANDARD_TEAMS_NAME).tojstring()); LuaValue size = mapLua.getSize$(); MapVersion version = new MapVersion() .setDescription(mapLua.getDescription$().replaceAll("<LOC .*?>", "")) .setWidth(size.get(1).toint()) .setHeight(size.get(2).toint()) .setHidden(false) .setRanked(isRanked) .setMaxPlayers(standardTeamsConfig.get(CONFIGURATION_STANDARD_TEAMS_ARMIES).length()) .setVersion(mapLua.getMapVersion$()) .setMap(map) .setFilename(LEGACY_FOLDER_PREFIX + mapNameBuilder.buildFinalZipName(mapLua.getMapVersion$())); map.getVersions().add(version); // this triggers validation mapRepository.save(map); return map; } private void updateLuaFiles(Path oldFolderPath, Path newFolderPath) throws IOException { String oldNameFolder = "/maps/" + oldFolderPath.getFileName(); String newNameFolder = "/maps/" + newFolderPath.getFileName(); try (Stream<Path> mapFileStream = Files.list(newFolderPath)) { mapFileStream .filter(path -> path.toString().toLowerCase().endsWith(".lua")) .forEach(path -> noCatch(() -> { List<String> lines = Files.readAllLines(path, MAP_CHARSET).stream() .map(line -> line.replaceAll("(?i)" + oldNameFolder, newNameFolder)) .collect(Collectors.toList()); Files.write(path, lines, MAP_CHARSET); })); } } private void generatePreview(Path newMapFolder) throws IOException { String previewFilename = newMapFolder.getFileName() + ".png"; generateImage( fafApiProperties.getMap().getDirectoryPreviewPathSmall().resolve(previewFilename), newMapFolder, fafApiProperties.getMap().getPreviewSizeSmall()); generateImage( fafApiProperties.getMap().getDirectoryPreviewPathLarge().resolve(previewFilename), newMapFolder, fafApiProperties.getMap().getPreviewSizeLarge()); } private void zipMapData(Path newMapFolder, Path finalZipPath) throws IOException, ArchiveException { Files.createDirectories(finalZipPath.getParent(), FilePermissionUtil.directoryPermissionFileAttributes()); Zipper .of(newMapFolder) .to(finalZipPath) .zip(); // TODO if possible, this should be done using umask instead FilePermissionUtil.setDefaultFilePermission(finalZipPath); } private void generateImage(Path target, Path baseDir, int size) throws IOException { BufferedImage image = PreviewGenerator.generatePreview(baseDir, size, size); if (target.getNameCount() > 0) { Files.createDirectories(target.getParent(), FilePermissionUtil.directoryPermissionFileAttributes()); } ImageIO.write(image, "png", target.toFile()); } static class ScenarioMapInfo { static final String CONFIGURATION_STANDARD_TEAMS_NAME = "name"; static final String CONFIGURATION_STANDARD_TEAMS_ARMIES = "armies"; static final String FILE_DECLARATION_MAP = "map"; static final String FILE_ENDING_SCENARIO = "_scenario.lua"; static final String FILE_ENDING_MAP = ".scmap"; static final String FILE_DECLARATION_SAVE = "save"; static final String FILE_ENDING_SAVE = "_save.lua"; static final String FILE_DECLARATION_SCRIPT = "script"; static final String FILE_ENDING_SCRIPT = "_script.lua"; static final String[] MANDATORY_FILES = new String[]{ FILE_ENDING_SCENARIO, FILE_ENDING_MAP, FILE_ENDING_SAVE, FILE_ENDING_SCRIPT, }; } private class MapNameBuilder { @Getter private final String displayName; private final String normalizedDisplayName; private String folderName; private MapNameBuilder(String displayName) { this.displayName = displayName; this.normalizedDisplayName = NameUtil.normalizeWhitespaces(displayName.toLowerCase()); } String buildFolderNameWithoutVersion() { return normalizedDisplayName; } String buildFolderName(int version) { if (folderName == null) { folderName = String.format("%s.v%04d", normalizedDisplayName, version); } return folderName; } String buildFileName(String fileEnding) { return normalizedDisplayName + fileEnding; } String buildFinalZipName(int version) { return buildFolderName(version) + ".zip"; } Path buildFinalZipPath(int version) { return fafApiProperties.getMap().getTargetDirectory().resolve(buildFinalZipName(version)); } } }
package com.gimranov.zandy.app.data; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.UUID; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import com.gimranov.zandy.app.R; import com.gimranov.zandy.app.task.APIRequest; public class Item { private String id; private String title; private String type; private String owner; private String key; private String etag; private String year; private String children; private String creatorSummary; private JSONObject content; public String dbId; /** * Timestamp of last update from server */ private String timestamp; /** * Queue of dirty items to be sent to the server */ public static ArrayList<Item> queue = new ArrayList<Item>(); private static final String TAG = Item.class.getSimpleName(); /** * The next two types are arrays of information on items that we need * elsewhere */ public static final String[] ITEM_TYPES_EN = {"Artwork", "Audio Recording", "Bill", "Blog Post", "Book", "Book Section", "Case", "Computer Program", "Conference Paper", "Dictionary Entry", "Document", "E-mail", "Encyclopedia Article", "Film", "Forum Post", "Hearing", "Instant Message", "Interview", "Journal Article", "Letter", "Magazine Article", "Manuscript", "Map", "Newspaper Article", "Note", "Patent", "Podcast", "Presentation", "Radio Broadcast", "Report", "Statute", "TV Broadcast", "Thesis", "Video Recording", "Web Page"}; public static final String[] ITEM_TYPES = {"artwork", "audioRecording", "bill", "blogPost", "book", "bookSection", "case", "computerProgram", "conferencePaper", "dictionaryEntry", "document", "email", "encyclopediaArticle", "film", "forumPost", "hearing", "instantMessage", "interview", "journalArticle", "letter", "magazineArticle", "manuscript", "map", "newspaperArticle", "note", "patent", "podcast", "presentation", "radioBroadcast", "report", "statute", "tvBroadcast", "thesis", "videoRecording", "webpage"}; /** * Represents whether the item has been dirtied Dirty items have changes * that haven't been applied to the API */ public String dirty; public Item() { content = new JSONObject(); year = ""; creatorSummary = ""; key = ""; owner = ""; type = ""; title = ""; id = ""; etag = ""; timestamp = ""; children = ""; dirty = APIRequest.API_CLEAN; } public Item(Context c, String type) { this(); content = fieldsForItemType(c, type); key = "zandy:" + UUID.randomUUID().toString(); dirty = APIRequest.API_NEW; this.type = type; } public boolean equals(Item b) { if (b == null) return false; Log.d(TAG, "Comparing myself (" + key + ") to " + b.key); if (b.key == null || key == null) return false; if (b.key.equals(key)) return true; return false; } public String getId() { return id; } public String getTitle() { return title; } public void setTitle(String title) { if (title == null) title = ""; if (!this.title.equals(title)) { this.content.remove("title"); try { this.content.put("title", title); this.title = title; if (!APIRequest.API_CLEAN.equals(this.dirty)) this.dirty = APIRequest.API_DIRTY; } catch (JSONException e) { Log.e(TAG, "Exception setting title", e); } } } /* * These can't be propagated, so they only make sense before the item has * been saved to the API. */ public void setId(String id) { if (this.id != id) { this.id = id; } } public void setOwner(String owner) { if (this.owner != owner) { this.owner = owner; } } public void setKey(String key) { if (this.key != key) { this.key = key; } } public void setEtag(String etag) { if (this.etag != etag) { this.etag = etag; } } public String getOwner() { return owner; } public String getKey() { return key; } public JSONObject getContent() { return content; } public void setContent(JSONObject content) { if (!this.content.toString().equals(content.toString())) { if (!APIRequest.API_CLEAN.equals(this.dirty)) this.dirty = APIRequest.API_DIRTY; this.content = content; } } public void setContent(String content) throws JSONException { JSONObject con = new JSONObject(content); if (this.content != con) { if (!APIRequest.API_CLEAN.equals(this.dirty)) this.dirty = APIRequest.API_DIRTY; this.content = con; } } public void setType(String type) { this.type = type; } public void setChildren(String children) { this.children = children; } public String getChildren() { return children; } public String getType() { return type; } public String getEtag() { return etag; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getCreatorSummary() { return creatorSummary; } public void setCreatorSummary(String creatorSummary) { this.creatorSummary = creatorSummary; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } /** * Makes ArrayList<Bundle> from the present item. This was moved from * ItemDataActivity, but it's most likely to be used by such display * activities */ public ArrayList<Bundle> toBundleArray(Database db) { JSONObject itemContent = this.content; /* * Here we walk through the data and make Bundles to send to the * ArrayAdapter. There should be no real risk of JSON exceptions, since * the JSON was checked when initialized in the Item object. * * Each Bundle has two keys: "label" and "content" */ JSONArray fields = itemContent.names(); ArrayList<Bundle> rows = new ArrayList<Bundle>(); Bundle b; try { JSONArray values = itemContent.toJSONArray(fields); for (int i = 0; i < itemContent.length(); i++) { b = new Bundle(); /* Special handling for some types */ if (fields.getString(i).equals("tags")) { // We display the tags semicolon-delimited StringBuilder sb = new StringBuilder(); try { JSONArray tagArray = values.getJSONArray(i); for (int j = 0; j < tagArray.length(); j++) { sb.append(tagArray.getJSONObject(j) .getString("tag")); if (j < tagArray.length() - 1) sb.append("; "); } b.putString("content", sb.toString()); } catch (JSONException e) { // Fall back to empty Log.e(TAG, "Exception parsing tags, with input: " + values.getString(i), e); b.putString("content", ""); } } else if (fields.getString(i).equals("notes")) { // TODO handle notes continue; } else if (fields.getString(i).equals("creators")) { /* * Creators should be labeled with role and listed nicely * This logic isn't as good as it could be. */ JSONArray creatorArray = values.getJSONArray(i); JSONObject creator; StringBuilder sb = new StringBuilder(); for (int j = 0; j < creatorArray.length(); j++) { creator = creatorArray.getJSONObject(j); if (creator.getString("creatorType").equals("author")) { if (creator.has("name")) sb.append(creator.getString("name")); else sb.append(creator.getString("firstName")).append(" ").append(creator.getString("lastName")); } else { if (creator.has("name")) sb.append(creator.getString("name")); else sb.append(creator.getString("firstName")).append(" ").append(creator.getString("lastName")).append(" (").append(Item.localizedStringForString(creator .getString("creatorType"))).append(")"); } if (j < creatorArray.length() - 1) sb.append(", "); } b.putString("content", sb.toString()); } else if (fields.getString(i).equals("itemType")) { // We want to show the localized or human-readable type b.putString("content", Item.localizedStringForString(values .getString(i))); } else { // All other data is treated as just text b.putString("content", values.getString(i)); } b.putString("label", fields.getString(i)); b.putString("itemKey", getKey()); rows.add(b); } b = new Bundle(); int notes = 0; int atts = 0; ArrayList<Attachment> attachments = Attachment.forItem(this, db); for (Attachment a : attachments) { if ("note".equals(a.getType())) notes++; else atts++; } b.putInt("noteCount", notes); b.putInt("attachmentCount", atts); b.putString("content", "not-empty-so-sorting-works"); b.putString("label", "children"); b.putString("itemKey", getKey()); rows.add(b); b = new Bundle(); int collectionCount = ItemCollection.getCollectionCount(this, db); b.putInt("collectionCount", collectionCount); b.putString("content", "not-empty-so-sorting-works"); b.putString("label", "collections"); b.putString("itemKey", getKey()); rows.add(b); } catch (JSONException e) { /* * We could die here, but I'd rather not, since this shouldn't be * possible. */ Log.e(TAG, "JSON parse exception making bundles!", e); } /* We'd like to put these in a certain order, so let's try! */ Collections.sort(rows, new Comparator<Bundle>() { @Override public int compare(Bundle b1, Bundle b2) { boolean mt1 = (b1.containsKey("content") && b1.getString("content").equals("")); boolean mt2 = (b2.containsKey("content") && b2.getString("content").equals("")); /* Put the empty fields at the bottom, same order */ return ( Item.sortValueForLabel(b1.getString("label")) - Item.sortValueForLabel(b2.getString("label")) - (mt2 ? 300 : 0) + (mt1 ? 300 : 0)); } }); return rows; } /** * Makes ArrayList<Bundle> from the present item's tags Primarily for use * with TagActivity, but who knows? */ public ArrayList<Bundle> tagsToBundleArray() { JSONObject itemContent = this.content; /* * Here we walk through the data and make Bundles to send to the * ArrayAdapter. There should be no real risk of JSON exceptions, since * the JSON was checked when initialized in the Item object. * * Each Bundle has three keys: "itemKey", "tag", and "type" */ ArrayList<Bundle> rows = new ArrayList<Bundle>(); Bundle b = new Bundle(); if (!itemContent.has("tags")) { return rows; } try { JSONArray tags = itemContent.getJSONArray("tags"); Log.d(TAG, tags.toString()); for (int i = 0; i < tags.length(); i++) { b = new Bundle(); // Type is not always specified, but we try to get it // and fall back to 0 when missing. Log.d(TAG, tags.getJSONObject(i).toString()); if (tags.getJSONObject(i).has("type")) b.putInt("type", tags.getJSONObject(i).optInt("type", 0)); b.putString("tag", tags.getJSONObject(i).optString("tag")); b.putString("itemKey", this.key); rows.add(b); } } catch (JSONException e) { Log.e(TAG, "JSON exception caught in tag bundler: ", e); } return rows; } /** * Makes ArrayList<Bundle> from the present item's creators. Primarily for * use with CreatorActivity, but who knows? */ public ArrayList<Bundle> creatorsToBundleArray() { JSONObject itemContent = this.content; /* * Here we walk through the data and make Bundles to send to the * ArrayAdapter. There should be no real risk of JSON exceptions, since * the JSON was checked when initialized in the Item object. * * Each Bundle has six keys: "itemKey", "name", "firstName", "lastName", * "creatorType", "position" * * Field mode is encoded implicitly -- if either of "firstName" and * "lastName" is non-empty ("") or non-null, we treat this as a * two-field name. key The field "name" is the one-field name if the * others are empty, otherwise it's a display version of the two-field * name. */ ArrayList<Bundle> rows = new ArrayList<Bundle>(); Bundle b = new Bundle(); if (!itemContent.has("creators")) { return rows; } try { JSONArray creators = itemContent.getJSONArray("creators"); Log.d(TAG, creators.toString()); for (int i = 0; i < creators.length(); i++) { b = new Bundle(); Log.d(TAG, creators.getJSONObject(i).toString()); b.putString("creatorType", creators.getJSONObject(i).getString( "creatorType")); b.putString("firstName", creators.getJSONObject(i).optString( "firstName")); b.putString("lastName", creators.getJSONObject(i).optString( "lastName")); b.putString("name", creators.getJSONObject(i).optString( "name")); // If name is empty, fill with the others if (b.getString("name").equals("")) b.putString("name", b.getString("firstName") + " " + b.getString("lastName")); b.putString("itemKey", this.key); b.putInt("position", i); rows.add(b); } } catch (JSONException e) { Log.e(TAG, "JSON exception caught in creator bundler: ", e); } return rows; } /** * Saves the item's current state. Marking dirty should happen before this */ public void save(Database db) { Item existing = load(key, db); if (dbId == null && existing == null) { String[] args = {title, key, type, year, creatorSummary, content.toString(), etag, dirty, timestamp, children}; Cursor cur = db .rawQuery( "insert into items (item_title, item_key, item_type, item_year, item_creator, item_content, etag, dirty, timestamp, item_children) " + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", args); if (cur != null) cur.close(); Item fromDB = load(key, db); dbId = fromDB.dbId; } else { if (dbId == null) dbId = existing.dbId; String[] args = {title, type, year, creatorSummary, content.toString(), etag, dirty, timestamp, key, children, dbId}; Log.i(TAG, "Updating existing item"); Cursor cur = db .rawQuery( "update items set item_title=?, item_type=?, item_year=?," + " item_creator=?, item_content=?, etag=?, dirty=?," + " timestamp=?, item_key=?, item_children=? " + " where _id=?", args); if (cur != null) cur.close(); } } /** * Deletes an item from the database, keeping a record of it in the deleteditems table * We will then send out delete requests via the API to propagate the deletion */ public void delete(Database db) { String[] args = {dbId}; db.rawQuery("delete from items where _id=?", args); db.rawQuery("delete from itemtocreators where item_id=?", args); db.rawQuery("delete from itemtocollections where item_id=?", args); ArrayList<Attachment> atts = Attachment.forItem(this, db); for (Attachment a : atts) { a.delete(db); } // Don't prepare deletion requests for unsynced new items if (!APIRequest.API_NEW.equals(dirty)) { String[] args2 = {key, etag}; db.rawQuery("insert into deleteditems (item_key, etag) values (?, ?)", args2); } } /** * Loads and returns an Item for the specified item key Returns null when no * match is found for the specified itemKey * * @param itemKey * @return */ public static Item load(String itemKey, Database db) { String[] cols = Database.ITEMCOLS; String[] args = {itemKey}; Cursor cur = db.query("items", cols, "item_key=?", args, null, null, null, null); Item item = load(cur); if (cur != null) cur.close(); return item; } /** * Loads and returns an Item for the specified item DB ID * Returns null when no match is found for the specified DB ID * * @param itemDbId * @return */ public static Item loadDbId(String itemDbId, Database db) { String[] cols = Database.ITEMCOLS; String[] args = {itemDbId}; Cursor cur = db.query("items", cols, "_id=?", args, null, null, null, null); Item item = load(cur); if (cur != null) cur.close(); return item; } /** * Loads an item from the specified Cursor, where the cursor was created * using the recommended query in Database.ITEMCOLS * <p> * Does not close the cursor! * * @param cur * @return An Item object for the current row of the Cursor */ public static Item load(Cursor cur) { Item item = new Item(); if (cur == null) { Log.e(TAG, "Didn't find an item for update"); return null; } // {"item_title", "item_type", "item_content", "etag", "dirty", "_id", // "item_key", "item_year", "item_creator", "timestamp", "item_children"}; item.setTitle(cur.getString(0)); item.setType(cur.getString(1)); try { item.setContent(cur.getString(2)); } catch (JSONException e) { Log.e(TAG, "JSON error loading item", e); } item.setEtag(cur.getString(3)); item.dirty = cur.getString(4); item.dbId = cur.getString(5); item.setKey(cur.getString(6)); item.setYear(cur.getString(7)); item.setCreatorSummary(cur.getString(8)); item.setTimestamp(cur.getString(9)); item.children = cur.getString(10); if (item.children == null) item.children = ""; return item; } /** * Static method for modification of items in the database */ public static void set(String itemKey, String label, String content, Database db) { // Load the item Item item = load(itemKey, db); // Don't set anything to null if (content == null) content = ""; switch (label) { case "title": item.title = content; break; case "itemType": item.type = content; break; case "children": item.children = content; break; case "date": item.year = content.replaceAll("^.*?(\\d{4}).*$", "$1"); break; } try { item.content.put(label, content); } catch (JSONException e) { Log .e(TAG, "Caught JSON exception when we tried to modify the JSON content"); } item.dirty = APIRequest.API_DIRTY; item.save(db); item = load(itemKey, db); } /** * Static method for setting tags Add a tag, change a tag, or replace an * existing tag. If newTag is empty ("") or null, the old tag is simply * deleted. * <p> * If oldTag is empty or null, the new tag is appended. * <p> * We make it into a user tag, which the desktop client does as well. */ public static void setTag(String itemKey, String oldTag, String newTag, int type, Database db) { // Load the item Item item = load(itemKey, db); try { JSONArray tags = item.content.getJSONArray("tags"); JSONArray newTags = new JSONArray(); Log.d(TAG, "Old: " + tags.toString()); // Allow adding a new tag if (oldTag == null || oldTag.equals("")) { Log.d(TAG, "Adding new tag: " + newTag); newTags = tags.put(new JSONObject().put("tag", newTag).put( "type", type)); } else { // In other cases, we're removing or replacing a tag for (int i = 0; i < tags.length(); i++) { if (tags.getJSONObject(i).getString("tag").equals(oldTag)) { if (newTag != null && !newTag.equals("")) newTags.put(new JSONObject().put("tag", newTag) .put("type", type)); else Log.d(TAG, "Tag removed: " + oldTag); } else { newTags.put(tags.getJSONObject(i)); } } } item.content.put("tags", newTags); } catch (JSONException e) { Log.e(TAG, "Caught JSON exception when we tried to modify the JSON content", e); } item.dirty = APIRequest.API_DIRTY; item.save(db); } /** * Static method for setting creators * <p> * Add, change, or replace a creator. If creator is null, the old creator is * simply deleted. * <p> * If position is -1, the new creator is appended. */ public static void setCreator(String itemKey, Creator c, int position, Database db) { // Load the item Item item = load(itemKey, db); try { JSONArray creators = item.content.getJSONArray("creators"); JSONArray newCreators = new JSONArray(); Log.d(TAG, "Old: " + creators.toString()); // Allow adding a new tag if (position < 0) { newCreators = creators.put(c.toJSON()); } else { if (c == null) { // we have a deletion for (int i = 0; i < creators.length(); i++) { if (i == position) continue; // skip the deleted one newCreators.put(creators.get(i)); } } else { newCreators = creators.put(position, c.toJSON()); } } StringBuilder sb = new StringBuilder(); for (int j = 0; j < creators.length(); j++) { if (j > 0) sb.append(", "); sb.append(((JSONObject) creators.get(j)).optString("lastName", "")); } item.creatorSummary = sb.toString(); item.content.put("creators", newCreators); Log.d(TAG, "New: " + newCreators.toString()); } catch (JSONException e) { Log.e(TAG, "Caught JSON exception when we tried to modify the JSON content"); } item.dirty = APIRequest.API_DIRTY; item.save(db); } /** * Identifies dirty items in the database and queues them for syncing */ public static void queue(Database db) { Log.d(TAG, "Clearing item dirty queue before repopulation"); queue.clear(); Item item; String[] cols = Database.ITEMCOLS; String[] args = {APIRequest.API_CLEAN}; Cursor cur = db.query("items", cols, "dirty!=?", args, null, null, null, null); if (cur == null) { Log.d(TAG, "No dirty items found in database"); queue.clear(); return; } do { Log.d(TAG, "Adding item to dirty queue"); item = load(cur); queue.add(item); } while (cur.moveToNext()); cur.close(); } /** * Maps types to the resources providing images for them. * * @param type * @return A resource representing an image for the item or other type */ public static int resourceForType(String type) { if (type == null || type.equals("")) return R.drawable.page_white; // TODO Complete this list switch (type) { case "artwork": return R.drawable.picture; // if (type.equals("audioRecording")) return // R.drawable.ic_menu_close_clear_cancel; // if (type.equals("bill")) return // R.drawable.ic_menu_close_clear_cancel; // if (type.equals("blogPost")) return // R.drawable.ic_menu_close_clear_cancel; case "book": return R.drawable.book; case "bookSection": return R.drawable.book_open; // if (type.equals("case")) return // R.drawable.ic_menu_close_clear_cancel; // if (type.equals("computerProgram")) return // R.drawable.ic_menu_close_clear_cancel; // if (type.equals("conferencePaper")) return // R.drawable.ic_menu_close_clear_cancel; case "dictionaryEntry": return R.drawable.page_white_width; case "document": return R.drawable.page_white; // if (type.equals("email")) return // R.drawable.ic_menu_close_clear_cancel; case "encyclopediaArticle": return R.drawable.page_white_text_width; case "film": return R.drawable.film; // if (type.equals("forumPost")) return // R.drawable.ic_menu_close_clear_cancel; // if (type.equals("hearing")) return // R.drawable.ic_menu_close_clear_cancel; case "instantMessage": return R.drawable.comment; // if (type.equals("interview")) return // R.drawable.ic_menu_close_clear_cancel; case "journalArticle": return R.drawable.page_white_text; case "letter": return R.drawable.email; case "magazineArticle": return R.drawable.layout; case "manuscript": return R.drawable.script; case "map": return R.drawable.map; case "newspaperArticle": return R.drawable.newspaper; // if (type.equals("patent")) return // R.drawable.ic_menu_close_clear_cancel; // if (type.equals("podcast")) return // R.drawable.ic_menu_close_clear_cancel; case "presentation": return R.drawable.page_white_powerpoint; // if (type.equals("radioBroadcast")) return // R.drawable.ic_menu_close_clear_cancel; case "report": return R.drawable.report; // if (type.equals("statute")) return // R.drawable.ic_menu_close_clear_cancel; case "thesis": return R.drawable.report_user; case "tvBroadcast": return R.drawable.television; case "videoRecording": return R.drawable.film; case "webpage": return R.drawable.page; // Not item types, but still something case "collection": return R.drawable.folder; case "application/pdf": return R.drawable.page_white_acrobat; case "note": return R.drawable.note; // if (type.equals("snapshot")) return // R.drawable.ic_menu_close_clear_cancel; // if (type.equals("link")) return // R.drawable.ic_menu_close_clear_cancel; // Return something generic if all else fails default: return R.drawable.page_white; } } /** * Provides the human-readable equivalent for strings * <p> * TODO This should pull the data from the API as a fallback, but we will * hard-code the list for now * * @param s * @return */ // XXX i18n public static String localizedStringForString(String s) { if (s == null) { Log.e(TAG, "Received null string in localizedStringForString"); return ""; } // Item fields from the API switch (s) { case "numPages": return "# of Pages"; case "numberOfVolumes": return "# of Volumes"; case "abstractNote": return "Abstract"; case "accessDate": return "Accessed"; case "applicationNumber": return "Application Number"; case "archive": return "Archive"; case "artworkSize": return "Artwork Size"; case "assignee": return "Assignee"; case "billNumber": return "Bill Number"; case "blogTitle": return "Blog Title"; case "bookTitle": return "Book Title"; case "callNumber": return "Call Number"; case "caseName": return "Case Name"; case "code": return "Code"; case "codeNumber": return "Code Number"; case "codePages": return "Code Pages"; case "codeVolume": return "Code Volume"; case "committee": return "Committee"; case "company": return "Company"; case "conferenceName": return "Conference Name"; case "country": return "Country"; case "court": return "Court"; case "DOI": return "DOI"; case "date": return "Date"; case "dateDecided": return "Date Decided"; case "dateEnacted": return "Date Enacted"; case "dictionaryTitle": return "Dictionary Title"; case "distributor": return "Distributor"; case "docketNumber": return "Docket Number"; case "documentNumber": return "Document Number"; case "edition": return "Edition"; case "encyclopediaTitle": return "Encyclopedia Title"; case "episodeNumber": return "Episode Number"; case "extra": return "Extra"; case "audioFileType": return "File Type"; case "filingDate": return "Filing Date"; case "firstPage": return "First Page"; case "audioRecordingFormat": return "Format"; case "videoRecordingFormat": return "Format"; case "forumTitle": return "Forum/Listserv Title"; case "genre": return "Genre"; case "history": return "History"; case "ISBN": return "ISBN"; case "ISSN": return "ISSN"; case "institution": return "Institution"; case "issue": return "Issue"; case "issueDate": return "Issue Date"; case "issuingAuthority": return "Issuing Authority"; case "journalAbbreviation": return "Journal Abbr"; case "label": return "Label"; case "language": return "Language"; case "programmingLanguage": return "Language"; case "legalStatus": return "Legal Status"; case "legislativeBody": return "Legislative Body"; case "libraryCatalog": return "Library Catalog"; case "archiveLocation": return "Loc. in Archive"; case "interviewMedium": return "Medium"; case "artworkMedium": return "Medium"; case "meetingName": return "Meeting Name"; case "nameOfAct": return "Name of Act"; case "network": return "Network"; case "pages": return "Pages"; case "patentNumber": return "Patent Number"; case "place": return "Place"; case "postType": return "Post Type"; case "priorityNumbers": return "Priority Numbers"; case "proceedingsTitle": return "Proceedings Title"; case "programTitle": return "Program Title"; case "publicLawNumber": return "Public Law Number"; case "publicationTitle": return "Publication"; case "publisher": return "Publisher"; case "references": return "References"; case "reportNumber": return "Report Number"; case "reportType": return "Report Type"; case "reporter": return "Reporter"; case "reporterVolume": return "Reporter Volume"; case "rights": return "Rights"; case "runningTime": return "Running Time"; case "scale": return "Scale"; case "section": return "Section"; case "series": return "Series"; case "seriesNumber": return "Series Number"; case "seriesText": return "Series Text"; case "seriesTitle": return "Series Title"; case "session": return "Session"; case "shortTitle": return "Short Title"; case "studio": return "Studio"; case "subject": return "Subject"; case "system": return "System"; case "title": return "Title"; case "thesisType": return "Type"; case "mapType": return "Type"; case "manuscriptType": return "Type"; case "letterType": return "Type"; case "presentationType": return "Type"; case "url": return "URL"; case "university": return "University"; case "version": return "Version"; case "volume": return "Volume"; case "websiteTitle": return "Website Title"; case "websiteType": return "Website Type"; // Item fields not in the API case "creators": return "Creators"; case "tags": return "Tags"; case "itemType": return "Item Type"; case "children": return "Attachments"; case "collections": return "Collections"; // And item types case "artwork": return "Artwork"; case "audioRecording": return "Audio Recording"; case "bill": return "Bill"; case "blogPost": return "Blog Post"; case "book": return "Book"; case "bookSection": return "Book Section"; case "case": return "Case"; case "computerProgram": return "Computer Program"; case "conferencePaper": return "Conference Paper"; case "dictionaryEntry": return "Dictionary Entry"; case "document": return "Document"; case "email": return "E-mail"; case "encyclopediaArticle": return "Encyclopedia Article"; case "film": return "Film"; case "forumPost": return "Forum Post"; case "hearing": return "Hearing"; case "instantMessage": return "Instant Message"; case "interview": return "Interview"; case "journalArticle": return "Journal Article"; case "letter": return "Letter"; case "magazineArticle": return "Magazine Article"; case "manuscript": return "Manuscript"; case "map": return "Map"; case "newspaperArticle": return "Newspaper Article"; case "note": return "Note"; case "patent": return "Patent"; case "podcast": return "Podcast"; case "presentation": return "Presentation"; case "radioBroadcast": return "Radio Broadcast"; case "report": return "Report"; case "statute": return "Statute"; case "tvBroadcast": return "TV Broadcast"; case "thesis": return "Thesis"; case "videoRecording": return "Video Recording"; case "webpage": return "Web Page"; // Creator types case "artist": return "Artist"; case "attorneyAgent": return "Attorney/Agent"; case "author": return "Author"; case "bookAuthor": return "Book Author"; case "cartographer": return "Cartographer"; case "castMember": return "Cast Member"; case "commenter": return "Commenter"; case "composer": return "Composer"; case "contributor": return "Contributor"; case "cosponsor": return "Cosponsor"; case "counsel": return "Counsel"; case "director": return "Director"; case "editor": return "Editor"; case "guest": return "Guest"; case "interviewee": return "Interview With"; case "interviewer": return "Interviewer"; case "inventor": return "Inventor"; case "performer": return "Performer"; case "podcaster": return "Podcaster"; case "presenter": return "Presenter"; case "producer": return "Producer"; case "programmer": return "Programmer"; case "recipient": return "Recipient"; case "reviewedAuthor": return "Reviewed Author"; case "scriptwriter": return "Scriptwriter"; case "seriesEditor": return "Series Editor"; case "sponsor": return "Sponsor"; case "translator": return "Translator"; case "wordsBy": return "Words By"; // Or just leave it the way it is default: return s; } } /** * Gets creator types, localized, for specified item type. * * @param s * @return */ public static String[] localizedCreatorTypesForItemType(String s) { String[] types = creatorTypesForItemType(s); String[] local = new String[types.length]; for (int i = 0; i < types.length; i++) { local[i] = localizedStringForString(types[i]); } return local; } /** * Gets valid creator types for the specified item type. Would be good to * have this draw from the API, but probably easier to hard-code the whole * mess. * <p> * Remapping of creator types on item type conversion is a separate issue. * * @param s itemType to provide creatorTypes for * @return */ public static String[] creatorTypesForItemType(String s) { Log.d(TAG, "Getting creator types for item type: " + s); switch (s) { case "artwork": return new String[]{"artist", "contributor"}; case "audioRecording": return new String[]{"performer", "composer", "contributor", "wordsBy"}; case "bill": return new String[]{"sponsor", "contributor", "cosponsor"}; case "blogPost": return new String[]{"author", "commenter", "contributor"}; case "book": return new String[]{"author", "contributor", "editor", "seriesEditor", "translator"}; case "bookSection": return new String[]{"author", "bookAuthor", "contributor", "editor", "seriesEditor", "translator"}; case "case": return new String[]{"author", "contributor", "counsel"}; case "computerProgram": return new String[]{"programmer", "contributor"}; case "conferencePaper": return new String[]{"author", "contributor", "editor", "seriesEditor", "translator"}; case "dictionaryEntry": return new String[]{"author", "contributor", "editor", "seriesEditor", "translator"}; case "document": return new String[]{"author", "contributor", "editor", "reviewedAuthor", "translator"}; case "email": return new String[]{"author", "contributor", "recipient"}; case "encyclopediaArticle": return new String[]{"author", "contributor", "editor", "seriesEditor", "translator"}; case "film": return new String[]{"director", "contributor", "producer", "scriptwriter"}; case "forumPost": return new String[]{"author", "contributor"}; case "hearing": return new String[]{"contributor"}; case "instantMessage": return new String[]{"author", "contributor", "recipient"}; case "interview": return new String[]{"interviewee", "contributor", "interviewer", "translator"}; case "journalArticle": return new String[]{"author", "contributor", "editor", "reviewedAuthor", "translator"}; case "letter": return new String[]{"author", "contributor", "recipient"}; case "magazineArticle": return new String[]{"author", "contributor", "reviewedAuthor", "translator"}; case "manuscript": return new String[]{"author", "contributor", "translator"}; case "map": return new String[]{"cartographer", "contributor", "seriesEditor"}; case "newspaperArticle": return new String[]{"author", "contributor", "reviewedAuthor", "translator"}; case "patent": return new String[]{"inventor", "attorneyAgent", "contributor"}; case "podcast": return new String[]{"podcaster", "contributor", "guest"}; case "presentation": return new String[]{"presenter", "contributor"}; case "radioBroadcast": return new String[]{"director", "castMember", "contributor", "guest", "producer", "scriptwriter"}; case "report": return new String[]{"author", "contributor", "seriesEditor", "translator"}; case "statute": return new String[]{"author", "contributor"}; case "tvBroadcast": return new String[]{"director", "castMember", "contributor", "guest", "producer", "scriptwriter"}; case "thesis": return new String[]{"author", "contributor"}; case "videoRecording": return new String[]{"director", "castMember", "contributor", "producer", "scriptwriter"}; case "webpage": return new String[]{"author", "contributor", "translator"}; default: return null; } } /** * Gets JSON template for the specified item type. * <p> * Remapping of fields on item type conversion is a separate issue. * * @param c Current context, needed to fetch string resources with * templates * @param s itemType to provide fields for * @return */ private static JSONObject fieldsForItemType(Context c, String s) { JSONObject template = new JSONObject(); String json = ""; try { // And item types switch (s) { case "artwork": json = c.getString(R.string.template_artwork); break; case "audioRecording": json = c.getString(R.string.template_audioRecording); break; case "bill": json = c.getString(R.string.template_bill); break; case "blogPost": json = c.getString(R.string.template_blogPost); break; case "book": json = c.getString(R.string.template_book); break; case "bookSection": json = c.getString(R.string.template_bookSection); break; case "case": json = c.getString(R.string.template_case); break; case "computerProgram": json = c.getString(R.string.template_computerProgram); break; case "conferencePaper": json = c.getString(R.string.template_conferencePaper); break; case "dictionaryEntry": json = c.getString(R.string.template_dictionaryEntry); break; case "document": json = c.getString(R.string.template_document); break; case "email": json = c.getString(R.string.template_email); break; case "encyclopediaArticle": json = c.getString(R.string.template_encyclopediaArticle); break; case "film": json = c.getString(R.string.template_film); break; case "forumPost": json = c.getString(R.string.template_forumPost); break; case "hearing": json = c.getString(R.string.template_hearing); break; case "instantMessage": json = c.getString(R.string.template_instantMessage); break; case "interview": json = c.getString(R.string.template_interview); break; case "journalArticle": json = c.getString(R.string.template_journalArticle); break; case "letter": json = c.getString(R.string.template_letter); break; case "magazineArticle": json = c.getString(R.string.template_magazineArticle); break; case "manuscript": json = c.getString(R.string.template_manuscript); break; case "map": json = c.getString(R.string.template_map); break; case "newspaperArticle": json = c.getString(R.string.template_newspaperArticle); break; case "note": json = c.getString(R.string.template_note); break; case "patent": json = c.getString(R.string.template_patent); break; case "podcast": json = c.getString(R.string.template_podcast); break; case "presentation": json = c.getString(R.string.template_presentation); break; case "radioBroadcast": json = c.getString(R.string.template_radioBroadcast); break; case "report": json = c.getString(R.string.template_report); break; case "statute": json = c.getString(R.string.template_statute); break; case "tvBroadcast": json = c.getString(R.string.template_tvBroadcast); break; case "thesis": json = c.getString(R.string.template_thesis); break; case "videoRecording": json = c.getString(R.string.template_videoRecording); break; case "webpage": json = c.getString(R.string.template_webpage); break; } template = new JSONObject(json); JSONArray names = template.names(); for (int i = 0; i < names.length(); i++) { if (names.getString(i).equals("itemType")) continue; if (names.getString(i).equals("tags")) continue; if (names.getString(i).equals("notes")) continue; if (names.getString(i).equals("creators")) { JSONArray roles = template.getJSONArray("creators"); for (int j = 0; j < roles.length(); j++) { roles.put(j, roles.getJSONObject(j).put("firstName", "").put("lastName", "")); } template.put("creators", roles); continue; } template.put(names.getString(i), ""); } Log.d(TAG, "Got JSON template: " + template.toString(4)); } catch (JSONException e) { Log.e(TAG, "JSON exception parsing item template", e); } return template; } private static int sortValueForLabel(String s) { // First type, and the bare minimum... switch (s) { case "itemType": return 0; case "title": return 1; case "creators": return 2; case "date": return 3; // Then container titles, with one value case "publicationTitle": return 5; case "blogTitle": return 5; case "bookTitle": return 5; case "dictionaryTitle": return 5; case "encyclopediaTitle": return 5; case "forumTitle": return 5; case "proceedingsTitle": return 5; case "programTitle": return 5; case "websiteTitle": return 5; case "meetingName": return 5; // Abstracts case "abstractNote": return 10; // Publishing data case "publisher": return 12; case "place": return 13; // Series, publication numbers case "pages": return 14; case "numPages": return 16; case "series": return 16; case "seriesTitle": return 17; case "seriesText": return 18; case "volume": return 19; case "numberOfVolumes": return 20; case "issue": return 20; case "section": return 21; case "publicationNumber": return 22; case "edition": return 23; // Locators case "DOI": return 50; case "archive": return 51; case "archiveLocation": return 52; case "ISBN": return 53; case "ISSN": return 54; case "libraryCatalog": return 55; case "callNumber": return 56; // Housekeeping and navigation, at the very end case "attachments": return 250; case "tags": return 251; case "related": return 252; default: return 200; } } }
package org.archive.wayback.cdx; import java.text.ParseException; import org.apache.commons.httpclient.URIException; import org.archive.net.UURI; import org.archive.net.UURIFactory; import org.archive.wayback.WaybackConstants; import org.archive.wayback.core.SearchResult; /** * * * @author brad * @version $Date$, $Revision$ */ public class CDXRecord { /** * CDX Header line for these fields. not very configurable.. */ public final static String CDX_HEADER_MAGIC = " CDX N b h m s k r V g"; /** * key url for this document */ public String url; /** * date this document was captured, 14-digit */ public String captureDate; /** * original host for this document, URL may have been massaged */ public String origHost = null; /** * guessed mime-type of this document */ public String mimeType = null; /** * HTTP response code for this document */ public String httpResponseCode = null; /** * Digest for this document -- very unclear what it means, is MD5?, partial * MD5?, includes HTTP headers?... */ public String md5Fragment = null; /** * URL that this document redirected to */ public String redirectUrl = null; /** * compressed offset within the ARC file where this document begins */ public long compressedOffset = -1; /** * name of ARC file containing this document, may or may not include .arc.gz */ public String arcFileName = null; /** * Constructor */ public CDXRecord() { super(); } /** * return the canonical string key for the URL argument. * * @param urlString * @return String lookup key for URL argument. * @throws URIException */ public static String urlStringToKey(final String urlString) throws URIException { String searchUrl = urlString; // force add of scheme and possible add '/' with empty path: if (searchUrl.startsWith("http: if (-1 == searchUrl.indexOf('/', 8)) { searchUrl = searchUrl + "/"; } } else { if (-1 == searchUrl.indexOf("/")) { searchUrl = searchUrl + "/"; } searchUrl = "http://" + searchUrl; } // convert to UURI to perform require URI fixup: UURI searchURI = UURIFactory.getInstance(searchUrl); // replace ' ' with '+' (this is only to match Alexa's canonicalization) searchURI.setPath(searchURI.getPath().replace(' ', '+')); return searchURI.getHostBasename() + searchURI.getEscapedPathQuery(); } /** * Attempt to deserialize state from a single text line, fields delimited by * spaces. There are standard ways to do this, and this is not one of * them... for no good reason. * * @param line * @param lineNumber * @throws ParseException */ public void parseLine(final String line, final int lineNumber) throws ParseException { String[] tokens = line.split(" "); if (tokens.length != 9) { throw new ParseException(line, lineNumber); } url = tokens[0]; captureDate = tokens[1]; origHost = tokens[2]; mimeType = tokens[3]; httpResponseCode = tokens[4]; md5Fragment = tokens[5]; redirectUrl = tokens[6]; compressedOffset = Long.parseLong(tokens[7]); arcFileName = tokens[8]; } /** * @return SearchResult with values of this CDXRecord */ public SearchResult toSearchResult() { SearchResult result = new SearchResult(); String origUrl = url; try { UURI uri = UURIFactory.getInstance(WaybackConstants.HTTP_URL_PREFIX + url); origUrl = origHost + uri.getEscapedPathQuery(); } catch (URIException e) { // TODO Auto-generated catch block e.printStackTrace(); } result.put(WaybackConstants.RESULT_URL, origUrl); result.put(WaybackConstants.RESULT_URL_KEY, url); result.put(WaybackConstants.RESULT_CAPTURE_DATE, captureDate); result.put(WaybackConstants.RESULT_ORIG_HOST, origHost); result.put(WaybackConstants.RESULT_MIME_TYPE, mimeType); result.put(WaybackConstants.RESULT_HTTP_CODE, httpResponseCode); result.put(WaybackConstants.RESULT_MD5_DIGEST, md5Fragment); result.put(WaybackConstants.RESULT_REDIRECT_URL, redirectUrl); // HACKHACK: result.put(WaybackConstants.RESULT_OFFSET, String.valueOf(compressedOffset)); result.put(WaybackConstants.RESULT_ARC_FILE, arcFileName); return result; } /** Initialize this CDXRecord values from a SearchResult * @param result */ public void fromSearchResult(final SearchResult result) { url = result.get(WaybackConstants.RESULT_URL_KEY); captureDate = result.get(WaybackConstants.RESULT_CAPTURE_DATE); origHost = result.get(WaybackConstants.RESULT_ORIG_HOST); mimeType = result.get(WaybackConstants.RESULT_MIME_TYPE); httpResponseCode = result.get(WaybackConstants.RESULT_HTTP_CODE); md5Fragment = result.get(WaybackConstants.RESULT_MD5_DIGEST); redirectUrl = result.get(WaybackConstants.RESULT_REDIRECT_URL); compressedOffset = Long.parseLong(result .get(WaybackConstants.RESULT_OFFSET)); arcFileName = result.get(WaybackConstants.RESULT_ARC_FILE); } /** * @return a BDBJE value for this record */ public String toValue() { return url + " " + captureDate + " " + origHost + " " + mimeType + " " + httpResponseCode + " " + md5Fragment + " " + redirectUrl + " " + compressedOffset + " " + arcFileName; } /** * @return a BDBJE key for this record */ public String toKey() { return url + " " + captureDate; } }
package inpro.incremental.sink; import inpro.incremental.unit.EditMessage; import inpro.incremental.unit.IU; import inpro.util.TimeUtil; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import edu.cmu.sphinx.util.props.PropertyException; import edu.cmu.sphinx.util.props.PropertySheet; import edu.cmu.sphinx.util.props.S4Boolean; import edu.cmu.sphinx.util.props.S4String; /** * An IU left buffer that prints its contents to STDOUT. * The format used resembles wavesurfer label files * @author timo */ public class LabelWriter extends FrameAwarePushBuffer { @S4Boolean(defaultValue = false) public final static String PROP_WRITE_FILE = "writeToFile"; @S4Boolean(defaultValue = false) public final static String PROP_COMMITS_ONLY = "commitsOnly"; @S4Boolean(defaultValue = true) public final static String PROP_WRITE_STDOUT = "writeToStdOut"; @S4String(defaultValue = "") public final static String PROP_FILE_PATH= "filePath"; @S4String(defaultValue = "") public final static String PROP_FILE_NAME = "fileName"; private boolean writeToFile; private boolean commitsOnly; private boolean writeToStdOut = true; private String filePath; private static String fileName; int frameOutput = -1; ArrayList<IU> allIUs = new ArrayList<IU>(); @Override public void newProperties(PropertySheet ps) throws PropertyException { writeToFile = ps.getBoolean(PROP_WRITE_FILE); commitsOnly = ps.getBoolean(PROP_COMMITS_ONLY); writeToStdOut = ps.getBoolean(PROP_WRITE_STDOUT); filePath = ps.getString(PROP_FILE_PATH); fileName = ps.getString(PROP_FILE_NAME); } @Override public void hypChange(Collection<? extends IU> ius, List<? extends EditMessage<? extends IU>> edits) { /* Get the time first */ String toOut = String.format(Locale.US, "Time: %.2f", currentFrame * TimeUtil.FRAME_TO_SECOND_FACTOR); /* Then go through all the IUs, ignoring commits */ boolean added = false; for (EditMessage<? extends IU> edit : edits) { IU iu = edit.getIU(); switch (edit.getType()) { case ADD: if (!commitsOnly) { added = true; toOut += "\n" + iu.toLabelLine(); allIUs.add(iu); } break; case COMMIT: if (commitsOnly) { added = true; toOut += "\n" + iu.toLabelLine(); allIUs.add(iu); } break; case REVOKE: allIUs.remove(iu); break; default: break; } } toOut = String.format(Locale.US, "Time: %.2f", currentFrame * TimeUtil.FRAME_TO_SECOND_FACTOR); IU prevIU = null; for (IU iu : allIUs) { if (prevIU != null && (iu.startTime() < prevIU.endTime())) { toOut += "\n" + String.format(Locale.US, "%.2f\t%.2f\t%s", prevIU.endTime(), iu.endTime(), iu.toPayLoad()); } else toOut += "\n" + iu.toLabelLine(); prevIU = iu; } toOut += "\n\n"; /* If there were only commits, or if there are not IUs, then print out as specified */ if (ius.size() > 0 && added) { // && frameOutput != currentFrame) { frameOutput = currentFrame; if (writeToFile) { try { FileWriter writer = new FileWriter( fileName + ".inc_reco", true); writer.write(toOut); writer.close(); } catch (IOException e) { e.printStackTrace(); } } if (writeToStdOut) { System.out.println(toOut); } } } /** A file name can be specified here, if not specified in the config file */ public static void setFileName(String name) { fileName = name; } @Override public void reset() { super.reset(); frameOutput = -1; } }
package org.jdesktop.swingx; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Container; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Enumeration; import java.util.ResourceBundle; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.UIManager; import org.jdesktop.swingx.util.WindowUtils; /** * Common Error Dialog, suitable for representing information about * errors and exceptions happened in application. The common usage of the * <code>JXErrorDialog</code> is to show collected data about the incident and * probably ask customer for a feedback. The data about the incident consists * from the title which will be displayed in the dialog header, short * description of the problem that will be immediately seen after dialog is * became visible, full description of the problem which will be visible after * user clicks "Details" button and Throwable that contains stack trace and * another usable information that may be displayed in the dialog.<p> * * To ask user for feedback extend abstract class <code>ErrorReporter</code> and * set your reporter using <code>setReporter</code> method. Report button will * be added to the dialog automatically.<br> * See {@link MailErrorReporter MailErrorReporter} documentation for the * example of error reporting usage.<p> * For example, to show simple <code>JXErrorDialog</code> call <br> * <code>JXErrorDialog.showDialog(null, "Application Error", * "The application encountered the unexpected error, * please contact developers")</code> * * <p>Internationalization is handled via a resource bundle or via the UIManager * bidi orientation (usefull for right to left languages) is determined in the * same way as the JOptionPane where the orientation of the parent component is * picked. So when showDialog(Component cmp, ...) is invoked the component * orientation of the error dialog will match the component orientation of cmp. * @author Richard Bair * @author Alexander Zuev * @author Shai Almog */ public class JXErrorDialog extends JDialog { /** * Used as a prefix when pulling data out of UIManager for i18n */ private static String CLASS_NAME; /** * Icon for the error dialog (stop sign, etc) */ private static final Icon icon = UIManager.getIcon("OptionPane.warningIcon"); /** * Error message label */ private JLabel errorMessage; /** * details text area */ private JTextArea details; /** * detail button */ private EqualSizeJButton detailButton; /** * details scroll pane */ private JScrollPane detailsScrollPane; /** * report an error button */ private EqualSizeJButton reportButton; /** * Error reporting engine assigned for error reporting for all error dialogs */ private static ErrorReporter reporter; /** * IncidentInfo that contains all the information prepared for * reporting. */ private IncidentInfo incidentInfo; /** * Creates initialize the UIManager with localized strings */ static { // Popuplate UIDefaults with the localizable Strings we will use // in the Login panel. CLASS_NAME = JXErrorDialog.class.getCanonicalName(); String lookup; ResourceBundle res = ResourceBundle.getBundle("org.jdesktop.swingx.plaf.resources.ErrorDialog"); Enumeration<String> keys = res.getKeys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); lookup = CLASS_NAME + "." + key; if (UIManager.getString(lookup) == null) { UIManager.put(lookup, res.getString(key)); } } } /** * Create a new ErrorDialog with the given Frame as the owner * @param owner Owner of this error dialog. */ public JXErrorDialog(Frame owner) { super(owner, true); initGui(); } /** * Create a new ErrorDialog with the given Dialog as the owner * @param owner Owner of this error dialog. */ public JXErrorDialog(Dialog owner) { super(owner, true); initGui(); } /** * initialize the gui. */ private void initGui() { //initialize the gui GridBagLayout layout = new GridBagLayout(); this.getContentPane().setLayout(layout); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbc.gridheight = 1; gbc.insets = new Insets(22, 12, 11, 17); this.getContentPane().add(new JLabel(icon), gbc); errorMessage = new JLabel(); gbc.anchor = GridBagConstraints.LINE_START; gbc.fill = GridBagConstraints.BOTH; gbc.gridheight = 1; gbc.gridwidth = 2; gbc.gridx = 1; gbc.weightx = 1.0; gbc.insets = new Insets(12, 0, 0, 11); this.getContentPane().add(errorMessage, gbc); gbc.fill = GridBagConstraints.NONE; gbc.gridx = 1; gbc.gridy = 1; gbc.gridwidth = 1; gbc.weightx = 1.0; gbc.weighty = 0.0; gbc.anchor = GridBagConstraints.LINE_END; gbc.insets = new Insets(12, 0, 11, 5); EqualSizeJButton okButton = new EqualSizeJButton(UIManager.getString(CLASS_NAME + ".ok_button_text")); this.getContentPane().add(okButton, gbc); reportButton = new EqualSizeJButton(new ReportAction()); gbc.gridx = 2; gbc.weightx = 0.0; gbc.insets = new Insets(12, 0, 11, 5); this.getContentPane().add(reportButton, gbc); reportButton.setVisible(false); // not visible by default detailButton = new EqualSizeJButton(UIManager.getString(CLASS_NAME + ".details_expand_text")); gbc.gridx = 3; gbc.weightx = 0.0; gbc.insets = new Insets(12, 0, 11, 11); this.getContentPane().add(detailButton, gbc); details = new JTextArea(7, 60); detailsScrollPane = new JScrollPane(details); detailsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); details.setEditable(false); gbc.fill = GridBagConstraints.BOTH; gbc.gridwidth = 4; gbc.gridx = 0; gbc.gridy = 2; gbc.weighty = 1.0; gbc.insets = new Insets(6, 11, 11, 11); this.getContentPane().add(detailsScrollPane, gbc); /* * Here i'm going to add invisible empty container to the bottom of the * content pane to fix minimal width of the dialog. It's quite a hack, * but i have not found anything better. */ Dimension spPredictedSize = detailsScrollPane.getPreferredSize(); Dimension newPanelSize = new Dimension(spPredictedSize.width+15, 0); Container widthHolder = new Container(); widthHolder.setMinimumSize(newPanelSize); widthHolder.setPreferredSize(newPanelSize); widthHolder.setMaximumSize(newPanelSize); gbc.gridy = 3; gbc.insets = new Insets(0, 11, 11, 0); this.getContentPane().add(widthHolder, gbc); //make the buttons the same size EqualSizeJButton[] buttons = new EqualSizeJButton[] { detailButton, okButton, reportButton }; okButton.setGroup(buttons); reportButton.setGroup(buttons); detailButton.setGroup(buttons); //set the event handling okButton.addActionListener(new OkClickEvent()); detailButton.addActionListener(new DetailsClickEvent()); } /** * Set the details section of the error dialog. If the details are either * null or an empty string, then hide the details button and hide the detail * scroll pane. Otherwise, just set the details section. * @param details Details to be shown in the detail section of the dialog. This can be null * if you do not want to display the details section of the dialog. */ private void setDetails(String details) { if (details == null || details.equals("")) { setDetailsVisible(false); detailButton.setVisible(false); } else { this.details.setText(details); setDetailsVisible(false); detailButton.setVisible(true); } } /** * Set the details section to be either visible or invisible. Set the * text of the Details button accordingly. * @param b if true details section will be visible */ private void setDetailsVisible(boolean b) { if (b) { details.setCaretPosition(0); detailsScrollPane.setVisible(true); detailButton.setText(UIManager.getString(CLASS_NAME + ".details_contract_text")); detailsScrollPane.applyComponentOrientation(detailButton.getComponentOrientation()); // workaround for bidi bug, if the text is not set "again" and the component orientation has changed // then the text won't be aligned correctly. To reproduce this (in JDK 1.5) show two dialogs in one // use LTOR orientation and in the second use RTOL orientation and press "details" in both. // Text in the text box should be aligned to right/left respectively, without this line this doesn't // occure I assume because bidi properties are tested when the text is set and are not updated later // on when setComponentOrientation is invoked. details.setText(details.getText()); } else { detailsScrollPane.setVisible(false); detailButton.setText(UIManager.getString(CLASS_NAME + ".details_expand_text")); } pack(); repaint(); } /** * Set the error message for the dialog box * @param errorMessage Message for the error dialog */ private void setErrorMessage(String errorMessage) { this.errorMessage.setText(errorMessage); } /** * Sets the IncidentInfo for this dialog * * @param info IncidentInfo that incorporates all the details about the error */ private void setIncidentInfo(IncidentInfo info) { this.incidentInfo = info; this.reportButton.setVisible(getReporter() != null); } /** * Get curent dialog's IncidentInfo * * @return <code>IncidentInfo</code> assigned to this dialog */ private IncidentInfo getIncidentInfo() { return incidentInfo; } /** * Listener for Ok button click events * @author Richard Bair */ private final class OkClickEvent implements ActionListener { /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { //close the window setVisible(false); dispose(); } } /** * Listener for Details click events. Alternates whether the details section * is visible or not. * @author Richard Bair */ private final class DetailsClickEvent implements ActionListener { /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ public void actionPerformed(ActionEvent e) { setDetailsVisible(!detailsScrollPane.isVisible()); } } /** * Constructs and shows the error dialog for the given exception. The exceptions message will be the * errorMessage, and the stacktrace will be the details. * @param owner Owner of this error dialog. Determines the Window in which the dialog * is displayed; if the <code>owner</code> has * no <code>Window</code>, a default <code>Frame</code> is used * @param title Title of the error dialog * @param e Exception that contains information about the error cause and stack trace */ public static void showDialog(Component owner, String title, Throwable e) { IncidentInfo ii = new IncidentInfo(title, null, null, e); showDialog(owner, ii); } /** * Constructs and shows the error dialog for the given exception. The exceptions message is specified, * and the stacktrace will be the details. * @param owner Owner of this error dialog. Determines the Window in which the dialog * is displayed; if the <code>owner</code> has * no <code>Window</code>, a default <code>Frame</code> is used * @param title Title of the error dialog * @param errorMessage Message for the error dialog * @param e Exception that contains information about the error cause and stack trace */ public static void showDialog(Component owner, String title, String errorMessage, Throwable e) { IncidentInfo ii = new IncidentInfo(title, errorMessage, null, e); showDialog(owner, ii); } /** * Show the error dialog. * @param owner Owner of this error dialog. Determines the Window in which the dialog * is displayed; if the <code>owner</code> has * no <code>Window</code>, a default <code>Frame</code> is used * @param title Title of the error dialog * @param errorMessage Message for the error dialog * @param details Details to be shown in the detail section of the dialog. This can be null * if you do not want to display the details section of the dialog. */ public static void showDialog(Component owner, String title, String errorMessage, String details) { IncidentInfo ii = new IncidentInfo(title, errorMessage, details); showDialog(owner, ii); } /** * Show the error dialog. * @param owner Owner of this error dialog. Determines the Window in which the dialog * is displayed; if the <code>owner</code> has * no <code>Window</code>, a default <code>Frame</code> is used * @param title Title of the error dialog * @param errorMessage Message for the error dialog */ public static void showDialog(Component owner, String title, String errorMessage) { IncidentInfo ii = new IncidentInfo(title, errorMessage, (String)null); showDialog(owner, ii); } /** * Show the error dialog. * @param owner Owner of this error dialog. Determines the Window in which the dialog * is displayed; if the <code>owner</code> has * no <code>Window</code>, a default <code>Frame</code> is used * @param info <code>IncidentInfo</code> that incorporates all the information about the error */ public static void showDialog(Component owner, IncidentInfo info) { JXErrorDialog dlg; Window window = WindowUtils.findWindow(owner); if (owner instanceof Dialog) { dlg = new JXErrorDialog((Dialog)owner); } else { dlg = new JXErrorDialog((Frame)owner); } dlg.setTitle(info.getHeader()); dlg.setErrorMessage(info.getBasicErrorMessage()); String details = info.getDetailedErrorMessage(); if(details == null) { if(info.getErrorException() != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); info.getErrorException().printStackTrace(pw); details = sw.toString(); } else { details = ""; } } dlg.setDetails(details); dlg.setIncidentInfo(info); dlg.applyComponentOrientation(owner.getComponentOrientation()); dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dlg.pack(); dlg.setLocationRelativeTo(owner); dlg.setVisible(true); } /** * Returns the current reporting engine that will be used to report a problem if * user clicks on 'Report' button or <code>null</code> if no reporting engine set. * * @return reporting engine */ public static ErrorReporter getReporter() { return reporter; } /** * Set reporting engine which will handle error reporting if user clicks 'report' button. * * @param rep <code>ErrorReporter</code> to be used or <code>null</code> to turn reporting facility off. */ public static void setReporter(ErrorReporter rep) { reporter = rep; } /** * Action for report button */ public class ReportAction extends AbstractAction { public boolean isEnabled() { return (getReporter() != null); } public void actionPerformed(ActionEvent e) { getReporter().reportIncident(getIncidentInfo()); } public Object getValue(String key) { if(key == Action.NAME) { if(getReporter() != null && getReporter().getActionName() != null) { return getReporter().getActionName(); } else { return UIManager.getString(CLASS_NAME + ".report_button_text"); } } return super.getValue(key); } } /** * This is a button that maintains the size of the largest button in the button * group by returning the largest size from the getPreferredSize method. * This is better than using setPreferredSize since this will work regardless * of changes to the text of the button and its language. */ private static class EqualSizeJButton extends JButton { public EqualSizeJButton() { } public EqualSizeJButton(String text) { super(text); } public EqualSizeJButton(Action a) { super(a); } /** * Buttons whose size should be taken into consideration */ private EqualSizeJButton[] group; public void setGroup(EqualSizeJButton[] group) { this.group = group; } /** * Returns the actual preferred size on a different instance of this button */ private Dimension getRealPreferredSize() { return super.getPreferredSize(); } /** * If the <code>preferredSize</code> has been set to a * non-<code>null</code> value just returns it. * If the UI delegate's <code>getPreferredSize</code> * method returns a non <code>null</code> value then return that; * otherwise defer to the component's layout manager. * * @return the value of the <code>preferredSize</code> property * @see #setPreferredSize * @see ComponentUI */ public Dimension getPreferredSize() { int width = 0; int height = 0; for(int iter = 0 ; iter < group.length ; iter++) { Dimension size = group[iter].getRealPreferredSize(); width = Math.max(size.width, width); height = Math.max(size.height, height); } return new Dimension(width, height); } } }
package ir_course; import java.io.IOException; import java.util.LinkedList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class DocumentCollectionParser extends DefaultHandler { private List<DocumentInCollection> docs; private boolean item; private boolean title; private boolean abstractText; private boolean searchTaskNumber; private boolean query; private boolean relevance; private String currentText; private DocumentInCollection currentDoc; public DocumentCollectionParser() { this.docs = new LinkedList<DocumentInCollection>(); this.item = false; this.title = false; this.abstractText = false; this.searchTaskNumber = false; this.query = false; this.relevance = false; } // parses the document collection in the given URI public void parse(String uri) { try { SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); parser.parse(uri, this); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // returns the documents of the collection as a list public List<DocumentInCollection> getDocuments() { return this.docs; } // methods for the SAX parser below public void startElement(String uri, String localName, String qName, Attributes attributes) { this.currentText = ""; if (qName.equals("item")) { this.item = true; this.currentDoc = new DocumentInCollection(); } else if (qName.equals("title")) this.title = true; else if (qName.equals("abstract")) this.abstractText = true; else if (qName.equals("search_task_number")) this.searchTaskNumber = true; else if (qName.equals("query")) this.query = true; else if (qName.equals("relevance")) this.relevance = true; } public void endElement(String uri, String localName, String qName) { this.currentText = this.currentText.trim(); if (qName.equals("item")) { this.item = false; if (this.currentDoc.getTitle() != null) docs.add(this.currentDoc); } else if (qName.equals("title")) { this.currentDoc.setTitle(this.currentText); this.title = false; } else if (qName.equals("abstract")) { this.currentDoc.setAbstractText(this.currentText); this.abstractText = false; } else if (qName.equals("search_task_number")) { this.currentDoc.setSearchTaskNumber(Integer.valueOf(this.currentText)); this.searchTaskNumber = false; } else if (qName.equals("query")) { this.currentDoc.setQuery(this.currentText); this.query = false; } else if (qName.equals("relevance")) { if (Integer.valueOf(this.currentText) == 1) this.currentDoc.setRelevant(true); this.relevance = false; } } public void characters(char[] ch, int start, int length) { String text = ""; for (int i=0; i<length; i++) text += ch[start+i]; this.currentText += text; } }
package com.github.davidmoten.logan; import java.sql.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.TimeZone; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.Iterables; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimaps; import com.google.common.collect.Sets; public class Data { private static Logger log = Logger.getLogger(Data.class.getName()); private static Data instance; private TreeMap<Long, Collection<LogEntry>> map; private ListMultimap<Long, LogEntry> facade; private final TreeSet<String> keys = Sets.newTreeSet(); private final TreeSet<String> sources = Sets.newTreeSet(); private int maxSize = 1000000; public Data() { map = Maps.newTreeMap(); facade = Multimaps.newListMultimap(map, new Supplier<List<LogEntry>>() { @Override public List<LogEntry> get() { return Lists.newArrayList(); } }); } /** * Returns a singleton instance of {@link Data} with some dummy data loaded * for the key <code>specialNumber</code>. * * @return */ public static synchronized Data instance() { if (instance == null) { instance = new Data(); for (int i = 0; i < 10000; i++) instance.add(createRandomLogEntry(i)); } return instance; } private static LogEntry createRandomLogEntry(int i) { Map<String, String> map = Maps.newHashMap(); map.put("specialNumber", Math.random() * 100 + ""); return new LogEntry(System.currentTimeMillis() - TimeUnit.MINUTES.toMillis(i), map); } /** * Adds a {@link LogEntry} to the data. * * @param entry * @return this */ public synchronized Data add(LogEntry entry) { facade.put(entry.getTime(), entry); keys.addAll(entry.getProperties().keySet()); if (facade.size() % 10000 == 0) log.info("data size=" + facade.size()); if (facade.size() > maxSize) map.remove(map.firstKey()); String source = entry.getSource(); if (source != null) sources.add(source); return this; } public synchronized Iterable<LogEntry> find(final long startTime, final long finishTime) { return new Iterable<LogEntry>() { @Override public Iterator<LogEntry> iterator() { return createIterator(startTime, finishTime); } }; } private synchronized Iterator<LogEntry> createIterator( final long startTime, final long finishTime) { return new Iterator<LogEntry>() { Long t = map.ceilingKey(startTime); Long last = map.floorKey(finishTime); Iterator<LogEntry> it = null; @Override public boolean hasNext() { if (it == null || !it.hasNext()) return last != null && t != null && t <= last; else return it.hasNext(); } @Override public LogEntry next() { while (it == null || !it.hasNext()) { it = map.get(t).iterator(); t = map.higherKey(t); } return it.next(); } @Override public void remove() { throw new RuntimeException("not implemented"); } }; } public synchronized Buckets execute(final BucketQuery query) { Iterable<LogEntry> entries = find(query.getStartTime().getTime(), query.getFinishTime()); // filter by field Iterable<LogEntry> filtered = Iterables.filter(entries, new Predicate<LogEntry>() { @Override public boolean apply(LogEntry entry) { return entry.getProperties().containsKey( query.getField()); } }); // filter by source if (query.getSource().isPresent()) filtered = Iterables.filter(entries, new Predicate<LogEntry>() { @Override public boolean apply(LogEntry entry) { String src = entry.getProperties().get(Field.SOURCE); return query.getSource().get().equals(src); } }); Buckets buckets = new Buckets(query); for (LogEntry entry : filtered) { String s = entry.getProperties().get(query.getField()); try { double d = Double.parseDouble(s); buckets.add(entry.getTime(), d); } catch (NumberFormatException e) { // ignored value because non-numeric } } return buckets; } public synchronized long getNumEntries() { return facade.size(); } public NavigableSet<String> getKeys() { return keys; } public void setMaxSize(int maxSize) { this.maxSize = maxSize; } public Iterable<String> getLogs(long startTime, long finishTime) { return Iterables.transform(find(startTime, finishTime), new Function<LogEntry, String>() { @Override public String apply(LogEntry entry) { StringBuilder s = new StringBuilder(); DateFormat df = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSS"); df.setTimeZone(TimeZone.getTimeZone("UTC")); s.append(df.format(new Date(entry.getTime()))); s.append(' '); s.append(entry.getProperties().get(Field.LEVEL)); s.append(' '); s.append(entry.getProperties().get(Field.LOGGER)); s.append(" - "); s.append(entry.getProperties().get(Field.MSG)); return s.toString(); } }); } public NavigableSet<String> getSources() { return sources; } }
// TOTO package org.slf4j.impl; import org.slf4j.Logger; import org.slf4j.Marker; /** * This class serves as base for adapters or native implementations of logging systems * lacking Marker support. In this implementation, methods taking marker data * simply invoke the corresponding method without the Marker argument, ignoring * any Marker data passed as argument. * * @author Ceki Gulcu */ public abstract class MarkerIgnoringBase implements Logger { public boolean isDebugEnabled(Marker marker) { return isDebugEnabled(); } public void debug(Marker marker, String msg) { debug(msg); } public void debug(Marker marker, String format, Object arg) { debug(format, arg); } public void debug(Marker marker, String format, Object arg1, Object arg2) { debug(format, arg1, arg2); } public void debug(Marker marker, String format, Object[] argArray) { debug(format, argArray); } public void debug(Marker marker, String msg, Throwable t) { debug(msg, t); } public boolean isInfoEnabled(Marker marker) { return isInfoEnabled(); } public void info(Marker marker, String msg) { info(msg); } public void info(Marker marker, String format, Object arg) { info(format, arg); } public void info(Marker marker, String format, Object arg1, Object arg2) { info(format, arg1, arg2); } public void info(Marker marker, String format, Object[] argArray) { info(format, argArray); } public void info(Marker marker, String msg, Throwable t) { info(msg, t); } public boolean isWarnEnabled(Marker marker) { return isWarnEnabled(); } public void warn(Marker marker, String msg) { warn(msg); } public void warn(Marker marker, String format, Object arg) { warn(format, arg); } public void warn(Marker marker, String format, Object arg1, Object arg2) { warn(format, arg1, arg2); } public void warn(Marker marker, String format, Object[] argArray) { warn(format, argArray); } public void warn(Marker marker, String msg, Throwable t) { warn(msg, t); } public boolean isErrorEnabled(Marker marker) { return isErrorEnabled(); } public void error(Marker marker, String msg) { error(msg); } public void error(Marker marker, String format, Object arg) { error(format, arg); } public void error(Marker marker, String format, Object arg1, Object arg2) { error(format, arg1, arg2); } public void error(Marker marker, String format, Object[] argArray) { error(format, argArray); } public void error(Marker marker, String msg, Throwable t) { error(msg, t); } }
package com.hpe.caf.api.worker; import com.hpe.caf.api.HealthReporter; import java.io.InputStream; /** * A representation of a generic data store, for reading and writing data * typically used by workers in the course of their computation. */ public abstract class DataStore implements HealthReporter { /** * Get data by reference * @param reference the arbitrary string reference to a piece of data * @return the raw data referred to * @throws DataStoreException if the data store cannot service the request */ public abstract InputStream getData(final String reference) throws DataStoreException; /** * Get the byte size of some data in the DataStore by reference * @param reference the arbitrary string reference to a piece of data * @return the size in bytes of the data being referred to * @throws DataStoreException if the data store cannot service the requeste */ public abstract long getDataSize(final String reference) throws DataStoreException; /** * @return metrics for the data store */ public abstract DataStoreMetricsReporter getMetrics(); /** * Store data by reference * @param reference the arbitrary string reference to store the data by * @param data the raw data to store * @return reference to the stored data, which can be used to retrieve * @throws DataStoreException if the data store cannot service the request */ public abstract String putData(final String reference, final InputStream data) throws DataStoreException; /** * Perform necessary shut down operations. */ public abstract void shutdown(); }
package com.threerings.gwt.ui; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.PushButton; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; /** * Convenience methods for creating and configuring widgets. */ public class Widgets { /** * Creates a SimplePanel with the supplied style and widget */ public static SimplePanel newSimplePanel (Widget widget, String styleName) { SimplePanel panel = new SimplePanel(); if (styleName != null) { panel.addStyleName(styleName); } if (widget != null) { panel.setWidget(widget); } return panel; } /** * Creates a FlowPanel with the supplied widgets. */ public static FlowPanel newFlowPanel (Widget... contents) { return newFlowPanel(null, contents); } /** * Creates a FlowPanel with the provided style and widgets. */ public static FlowPanel newFlowPanel (String styleName, Widget... contents) { FlowPanel panel = new FlowPanel(); if (styleName != null) { panel.addStyleName(styleName); } for (Widget child : contents) { panel.add(child); } return panel; } /** * Creates a AbsolutePanel with the supplied style */ public static AbsolutePanel newAbsolutePanel (String styleName) { AbsolutePanel panel = new AbsolutePanel(); if (styleName != null) { panel.addStyleName(styleName); } return panel; } /** * Creates a row of widgets in a horizontal panel with a 5 pixel gap between them. */ public static HorizontalPanel newRow (Widget... contents) { return newRow(null, contents); } /** * Creates a row of widgets in a horizontal panel with a 5 pixel gap between them. The supplied * style name is added to the container panel. */ public static HorizontalPanel newRow (String styleName, Widget... contents) { HorizontalPanel row = new HorizontalPanel(); if (styleName != null) { row.setStyleName(styleName); } for (Widget widget : contents) { if (row.getWidgetCount() > 0) { row.add(newShim(5, 5)); } row.add(widget); } return row; } /** * Creates a label with the supplied text and style and optional additional styles. */ public static Label newLabel (String text, String styleName, String... auxStyles) { Label label = new Label(text); if (styleName != null) { label.setStyleName(styleName); } for (String auxStyle : auxStyles) { label.addStyleName(auxStyle); } return label; } /** * Creates an inline label with optional additional styles. */ public static Label newInlineLabel (String text, String... auxStyles) { return newLabel(text, "inline", auxStyles); } /** * Creates a label that triggers an action using the supplied text and handler. */ public static Label newActionLabel (String text, ClickHandler onClick) { return newActionLabel(text, null, onClick); } /** * Creates a label that triggers an action using the supplied text and handler. The label will * be styled as specified with an additional style that configures the mouse pointer and adds * underline to the text. */ public static Label newActionLabel (String text, String style, ClickHandler onClick) { Label label = newLabel(text, style); if (onClick != null) { label.addStyleName("actionLabel"); label.addClickHandler(onClick); } return label; } /** * Creates a new HTML element with the specified contents and style. */ public static HTML newHTML (String text, String styleName, String... auxStyles) { HTML html = new HTML(text); if (styleName != null) { html.setStyleName(styleName); } for (String auxStyle : auxStyles) { html.addStyleName(auxStyle); } return html; } /** * Creates an image with the supplied path and style. */ public static Image newImage (String path, String styleName) { Image image = new Image(path); if (styleName != null) { image.addStyleName(styleName); } return image; } /** * Creates an image that responds to clicking. */ public static Image newActionImage (String path, ClickHandler onClick) { return newActionImage(path, null, onClick); } /** * Creates an image that responds to clicking. */ public static Image newActionImage (String path, String tip, ClickHandler onClick) { return makeActionImage(new Image(path), tip, onClick); } /** * Makes an image into one that responds to clicking. */ public static Image makeActionImage (Image image, String tip, ClickHandler onClick) { if (onClick != null) { image.addStyleName("actionLabel"); image.addClickHandler(onClick); } if (tip != null) { image.setTitle(tip); } return image; } /** * Creates an image that will render inline with text (rather than forcing a break). */ public static Image newInlineImage (String path) { Image image = new Image(path); image.setStyleName("inline"); return image; } /** * Creates a text box with all of the configuration that you're bound to want to do. */ public static TextBox newTextBox (String text, int maxLength, int visibleLength) { return initTextBox(new TextBox(), text, maxLength, visibleLength); } /** * Configures a text box with all of the configuration that you're bound to want to do. This is * useful for configuring a PasswordTextBox. */ public static TextBox initTextBox (TextBox box, String text, int maxLength, int visibleLength) { if (text != null) { box.setText(text); } box.setMaxLength(maxLength > 0 ? maxLength : 255); if (visibleLength > 0) { box.setVisibleLength(visibleLength); } return box; } /** * Creates a text area with all of the configuration that you're bound to want to do. * * @param width the width of the text area or -1 to use the default (or CSS styled) width. */ public static TextArea newTextArea (String text, int width, int height) { TextArea area = new TextArea(); if (text != null) { area.setText(text); } if (width > 0) { area.setCharacterWidth(width); } if (height > 0) { area.setVisibleLines(height); } return area; } /** * Creates a limited text area with all of the configuration that you're bound to want to do. * * @param width the width of the text area or -1 to use the default (or CSS styled) width. */ public static LimitedTextArea newTextArea (String text, int width, int height, int maxLength) { LimitedTextArea area = new LimitedTextArea(maxLength, width, height); if (text != null) { area.setText(text); } return area; } /** * Creates a PushButton with default(up), mouseover and mousedown states. */ public static PushButton newPushButton (Image defaultImage, Image overImage, Image downImage, ClickHandler onClick) { PushButton button = new PushButton(defaultImage, downImage, onClick); button.getUpHoveringFace().setImage(overImage); return button; } /** * Creates an image button that changes appearance when you click and hover over it. */ public static PushButton newImageButton (String style, ClickHandler onClick) { PushButton button = new PushButton(); button.setStyleName(style); button.addStyleName("actionLabel"); maybeAddClickHandler(button, onClick); return button; } /** * Makes a widget that takes up horizontal and or vertical space. Shim shimminy shim shim * shiree. */ public static Widget newShim (int width, int height) { Label shim = new Label(""); shim.setWidth(width + "px"); shim.setHeight(height + "px"); return shim; } protected static void maybeAddClickHandler (HasClickHandlers target, ClickHandler onClick) { if (onClick != null) { target.addClickHandler(onClick); } } }
package elephantdb.cascading; import cascading.flow.Flow; import cascading.flow.FlowListener; import cascading.tap.Hfs; import cascading.tap.Tap; import cascading.tap.TapException; import cascading.tuple.Fields; import elephantdb.DomainSpec; import elephantdb.Utils; import elephantdb.hadoop.ElephantInputFormat; import elephantdb.hadoop.ElephantOutputFormat; import elephantdb.hadoop.LocalElephantManager; import elephantdb.index.IdentityIndexer; import elephantdb.index.Indexer; import elephantdb.store.DomainStore; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.JobConf; import org.apache.log4j.Logger; import java.io.IOException; import java.io.Serializable; import java.util.List; import java.util.Map.Entry; import java.util.UUID; public class ElephantDBTap extends Hfs implements FlowListener { public static final Logger LOG = Logger.getLogger(ElephantDBTap.class); public static class Args implements Serializable { //for source and sink public List<String> tmpDirs = null; public int timeoutMs = 2 * 60 * 60 * 1000; // 2 hours public Gateway gateway = new IdentityGateway(); //source specific public Fields sourceFields = Fields.ALL; public Long version = null; //for sourcing //sink specific public Fields sinkFields = Fields.ALL; public Indexer indexer = new IdentityIndexer(); public boolean incremental = false; //for sourcing } String domainDir; DomainSpec spec; Args args; String newVersionPath; public ElephantDBTap(String dir, DomainSpec spec, Args args) throws IOException { domainDir = dir; this.args = args; this.spec = new DomainStore(dir, spec).getSpec(); setStringPath(domainDir); setScheme(new ElephantScheme(this.args.sourceFields, this.args.sinkFields, this.spec, this.args.gateway)); } public DomainStore getDomainStore() throws IOException { return new DomainStore(domainDir, spec); } public DomainSpec getSpec() { return spec; } @Override public void sourceInit(JobConf conf) throws IOException { super.sourceInit(conf); FileInputFormat.setInputPaths(conf, "/" + UUID.randomUUID().toString()); ElephantInputFormat.Args eargs = new ElephantInputFormat.Args(domainDir); eargs.inputDirHdfs = domainDir; if (args.tmpDirs != null) { LocalElephantManager.setTmpDirs(conf, args.tmpDirs); } eargs.version = args.version; conf.setInt("mapred.task.timeout", args.timeoutMs); Utils.setObject(conf, ElephantInputFormat.ARGS_CONF, eargs); } @Override public void sinkInit(JobConf conf) throws IOException { super.sinkInit(conf); ElephantOutputFormat.Args args = outputArgs(conf); // serialize this particular argument off into the JobConf. Utils.setObject(conf, ElephantOutputFormat.ARGS_CONF, args); conf.setInt("mapred.task.timeout", this.args.timeoutMs); conf.setBoolean("mapred.reduce.tasks.speculative.execution", false); conf.setInt("mapred.reduce.tasks", spec.getNumShards()); } public ElephantOutputFormat.Args outputArgs(JobConf conf) throws IOException { DomainStore dstore = getDomainStore(); if (newVersionPath == null) { //working around cascading calling sinkinit twice newVersionPath = dstore.createVersion(); } ElephantOutputFormat.Args eargs = new ElephantOutputFormat.Args(spec, newVersionPath); if (args.tmpDirs != null) { LocalElephantManager.setTmpDirs(conf, args.tmpDirs); } if (args.indexer != null) eargs.indexer = args.indexer; // If incremental is set to true, we go ahead and populate the // update Dir. Else, we leave it blank. if (args.incremental) eargs.updateDirHdfs = dstore.mostRecentVersionPath(); return eargs; } @Override public Path getPath() { return new Path(domainDir); } @Override public boolean makeDirs(JobConf jc) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean deletePath(JobConf jc) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } @Override public long getPathModified(JobConf jc) throws IOException { return System.currentTimeMillis(); } public void onStarting(Flow flow) { } public void onStopping(Flow flow) { } private boolean isSinkOf(Flow flow) { for (Entry<String, Tap> e : flow.getSinks().entrySet()) { if (e.getValue() == this) return true; } return false; } public void onCompleted(Flow flow) { try { if (isSinkOf(flow)) { DomainStore dstore = getDomainStore(); if (flow.getFlowStats().isSuccessful()) { dstore.getFileSystem().mkdirs(new Path(newVersionPath)); // If the user wants to run a incremental, skip version synchronization. if (args.incremental) { dstore.synchronizeInProgressVersion(newVersionPath); } dstore.succeedVersion(newVersionPath); } else { dstore.failVersion(newVersionPath); } } } catch (IOException e) { throw new TapException("Couldn't finalize new elephant domain version", e); } finally { newVersionPath = null; //working around cascading calling sinkinit twice } } public boolean onThrowable(Flow flow, Throwable t) { return false; } }
package org.apache.fop.fonts; //Java import java.util.Map; //FOP import org.apache.fop.render.pdf.FontReader; /** * This class is used to defer the loading of a font until it is really used. */ public class LazyFont extends Font implements FontDescriptor { private String metricsFileName = null; private String fontEmbedPath = null; private boolean useKerning = false; private boolean isMetricsLoaded = false; private Font realFont = null; private FontDescriptor realFontDescriptor = null; /** * Main constructor * @param fontEmbedPath path to embeddable file (may be null) * @param metricsFileName path to the metrics XML file * @param useKerning True, if kerning should be enabled */ public LazyFont(String fontEmbedPath, String metricsFileName, boolean useKerning) { this.metricsFileName = metricsFileName; this.fontEmbedPath = fontEmbedPath; this.useKerning = useKerning; } private void load() { if (!isMetricsLoaded) { isMetricsLoaded = true; try { /**@todo Possible thread problem here */ FontReader reader = new FontReader(metricsFileName); reader.setKerningEnabled(useKerning); reader.setFontEmbedPath(fontEmbedPath); realFont = reader.getFont(); if (realFont instanceof FontDescriptor) { realFontDescriptor = (FontDescriptor) realFont; } // System.out.println("Metrics " + metricsFileName + " loaded."); } catch (Exception ex) { ex.printStackTrace(); /**@todo Log this exception */ //log.error("Failed to read font metrics file " // + metricsFileName // + " : " + ex.getMessage()); } } } /** * Gets the real font. * @return the real font */ public Font getRealFont() { load(); return realFont; } /** * @see org.apache.fop.fonts.Font#getEncoding() */ public String getEncoding() { load(); return realFont.getEncoding(); } /** * @see org.apache.fop.fonts.Font#mapChar(char) */ public char mapChar(char c) { load(); return realFont.mapChar(c); } /** * @see org.apache.fop.fonts.Font#isMultiByte() */ public boolean isMultiByte() { return realFont.isMultiByte(); } /** * @see org.apache.fop.fonts.FontMetrics#getFontName() */ public String getFontName() { load(); return realFont.getFontName(); } /** * @see org.apache.fop.fonts.FontMetrics#getAscender(int) */ public int getAscender(int size) { load(); return realFont.getAscender(size); } /** * @see org.apache.fop.fonts.FontMetrics#getCapHeight(int) */ public int getCapHeight(int size) { load(); return realFont.getCapHeight(size); } /** * @see org.apache.fop.fonts.FontMetrics#getDescender(int) */ public int getDescender(int size) { load(); return realFont.getDescender(size); } /** * @see org.apache.fop.fonts.FontMetrics#getXHeight(int) */ public int getXHeight(int size) { load(); return realFont.getXHeight(size); } /** * @see org.apache.fop.fonts.FontMetrics#getWidth(int, int) */ public int getWidth(int i, int size) { load(); return realFont.getWidth(i, size); } /** * @see org.apache.fop.fonts.FontMetrics#getWidths() */ public int[] getWidths() { load(); return realFont.getWidths(); } /** * @see org.apache.fop.fonts.FontMetrics#hasKerningInfo() */ public boolean hasKerningInfo() { load(); return realFont.hasKerningInfo(); } /** * @see org.apache.fop.fonts.FontMetrics#getKerningInfo() */ public Map getKerningInfo() { load(); return realFont.getKerningInfo(); } /** * @see org.apache.fop.fonts.FontDescriptor#getCapHeight() */ public int getCapHeight() { load(); return realFontDescriptor.getCapHeight(); } /** * @see org.apache.fop.fonts.FontDescriptor#getDescender() */ public int getDescender() { load(); return realFontDescriptor.getDescender(); } /** * @see org.apache.fop.fonts.FontDescriptor#getAscender() */ public int getAscender() { load(); return realFontDescriptor.getAscender(); } /** * @see org.apache.fop.fonts.FontDescriptor#getFlags() */ public int getFlags() { load(); return realFontDescriptor.getFlags(); } /** * @see org.apache.fop.fonts.FontDescriptor#getFontBBox() */ public int[] getFontBBox() { load(); return realFontDescriptor.getFontBBox(); } /** * @see org.apache.fop.fonts.FontDescriptor#getItalicAngle() */ public int getItalicAngle() { load(); return realFontDescriptor.getItalicAngle(); } /** * @see org.apache.fop.fonts.FontDescriptor#getStemV() */ public int getStemV() { load(); return realFontDescriptor.getStemV(); } /** * @see org.apache.fop.fonts.FontDescriptor#getFontType() */ public FontType getFontType() { load(); return realFontDescriptor.getFontType(); } /** * @see org.apache.fop.fonts.FontDescriptor#isEmbeddable() */ public boolean isEmbeddable() { load(); return realFontDescriptor.isEmbeddable(); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAnalyticsService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduleEventService; import com.kaltura.client.services.KalturaScheduleResourceService; import com.kaltura.client.services.KalturaScheduleEventResourceService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:16-06-12"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAnalyticsService analyticsService; public KalturaAnalyticsService getAnalyticsService() { if(this.analyticsService == null) this.analyticsService = new KalturaAnalyticsService(this); return this.analyticsService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduleEventService scheduleEventService; public KalturaScheduleEventService getScheduleEventService() { if(this.scheduleEventService == null) this.scheduleEventService = new KalturaScheduleEventService(this); return this.scheduleEventService; } protected KalturaScheduleResourceService scheduleResourceService; public KalturaScheduleResourceService getScheduleResourceService() { if(this.scheduleResourceService == null) this.scheduleResourceService = new KalturaScheduleResourceService(this); return this.scheduleResourceService; } protected KalturaScheduleEventResourceService scheduleEventResourceService; public KalturaScheduleEventResourceService getScheduleEventResourceService() { if(this.scheduleEventResourceService == null) this.scheduleEventResourceService = new KalturaScheduleEventResourceService(this); return this.scheduleEventResourceService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.services.KalturaAccessControlProfileService; import com.kaltura.client.services.KalturaAccessControlService; import com.kaltura.client.services.KalturaAdminUserService; import com.kaltura.client.services.KalturaAppTokenService; import com.kaltura.client.services.KalturaBaseEntryService; import com.kaltura.client.services.KalturaBulkUploadService; import com.kaltura.client.services.KalturaCategoryEntryService; import com.kaltura.client.services.KalturaCategoryService; import com.kaltura.client.services.KalturaCategoryUserService; import com.kaltura.client.services.KalturaConversionProfileAssetParamsService; import com.kaltura.client.services.KalturaConversionProfileService; import com.kaltura.client.services.KalturaDataService; import com.kaltura.client.services.KalturaDeliveryProfileService; import com.kaltura.client.services.KalturaDocumentService; import com.kaltura.client.services.KalturaEmailIngestionProfileService; import com.kaltura.client.services.KalturaEntryServerNodeService; import com.kaltura.client.services.KalturaFileAssetService; import com.kaltura.client.services.KalturaFlavorAssetService; import com.kaltura.client.services.KalturaFlavorParamsOutputService; import com.kaltura.client.services.KalturaFlavorParamsService; import com.kaltura.client.services.KalturaGroupUserService; import com.kaltura.client.services.KalturaLiveChannelSegmentService; import com.kaltura.client.services.KalturaLiveChannelService; import com.kaltura.client.services.KalturaLiveReportsService; import com.kaltura.client.services.KalturaLiveStatsService; import com.kaltura.client.services.KalturaLiveStreamService; import com.kaltura.client.services.KalturaMediaInfoService; import com.kaltura.client.services.KalturaMediaService; import com.kaltura.client.services.KalturaMixingService; import com.kaltura.client.services.KalturaNotificationService; import com.kaltura.client.services.KalturaPartnerService; import com.kaltura.client.services.KalturaPermissionItemService; import com.kaltura.client.services.KalturaPermissionService; import com.kaltura.client.services.KalturaPlaylistService; import com.kaltura.client.services.KalturaReportService; import com.kaltura.client.services.KalturaResponseProfileService; import com.kaltura.client.services.KalturaSchemaService; import com.kaltura.client.services.KalturaSearchService; import com.kaltura.client.services.KalturaServerNodeService; import com.kaltura.client.services.KalturaSessionService; import com.kaltura.client.services.KalturaStatsService; import com.kaltura.client.services.KalturaStorageProfileService; import com.kaltura.client.services.KalturaSyndicationFeedService; import com.kaltura.client.services.KalturaSystemService; import com.kaltura.client.services.KalturaThumbAssetService; import com.kaltura.client.services.KalturaThumbParamsOutputService; import com.kaltura.client.services.KalturaThumbParamsService; import com.kaltura.client.services.KalturaUiConfService; import com.kaltura.client.services.KalturaUploadService; import com.kaltura.client.services.KalturaUploadTokenService; import com.kaltura.client.services.KalturaUserEntryService; import com.kaltura.client.services.KalturaUserRoleService; import com.kaltura.client.services.KalturaUserService; import com.kaltura.client.services.KalturaWidgetService; import com.kaltura.client.services.KalturaXInternalService; import com.kaltura.client.services.KalturaMetadataService; import com.kaltura.client.services.KalturaMetadataProfileService; import com.kaltura.client.services.KalturaDocumentsService; import com.kaltura.client.services.KalturaSystemPartnerService; import com.kaltura.client.services.KalturaEntryAdminService; import com.kaltura.client.services.KalturaUiConfAdminService; import com.kaltura.client.services.KalturaReportAdminService; import com.kaltura.client.services.KalturaKalturaInternalToolsSystemHelperService; import com.kaltura.client.services.KalturaVirusScanProfileService; import com.kaltura.client.services.KalturaDistributionProfileService; import com.kaltura.client.services.KalturaEntryDistributionService; import com.kaltura.client.services.KalturaDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderService; import com.kaltura.client.services.KalturaGenericDistributionProviderActionService; import com.kaltura.client.services.KalturaCuePointService; import com.kaltura.client.services.KalturaAnnotationService; import com.kaltura.client.services.KalturaQuizService; import com.kaltura.client.services.KalturaShortLinkService; import com.kaltura.client.services.KalturaBulkService; import com.kaltura.client.services.KalturaDropFolderService; import com.kaltura.client.services.KalturaDropFolderFileService; import com.kaltura.client.services.KalturaCaptionAssetService; import com.kaltura.client.services.KalturaCaptionParamsService; import com.kaltura.client.services.KalturaCaptionAssetItemService; import com.kaltura.client.services.KalturaAttachmentAssetService; import com.kaltura.client.services.KalturaTagService; import com.kaltura.client.services.KalturaLikeService; import com.kaltura.client.services.KalturaVarConsoleService; import com.kaltura.client.services.KalturaEventNotificationTemplateService; import com.kaltura.client.services.KalturaExternalMediaService; import com.kaltura.client.services.KalturaScheduledTaskProfileService; import com.kaltura.client.services.KalturaIntegrationService; import com.kaltura.client.types.KalturaBaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class KalturaClient extends KalturaClientBase { public KalturaClient(KalturaConfiguration config) { super(config); this.setClientTag("java:16-04-04"); this.setApiVersion("3.3.0"); } protected KalturaAccessControlProfileService accessControlProfileService; public KalturaAccessControlProfileService getAccessControlProfileService() { if(this.accessControlProfileService == null) this.accessControlProfileService = new KalturaAccessControlProfileService(this); return this.accessControlProfileService; } protected KalturaAccessControlService accessControlService; public KalturaAccessControlService getAccessControlService() { if(this.accessControlService == null) this.accessControlService = new KalturaAccessControlService(this); return this.accessControlService; } protected KalturaAdminUserService adminUserService; public KalturaAdminUserService getAdminUserService() { if(this.adminUserService == null) this.adminUserService = new KalturaAdminUserService(this); return this.adminUserService; } protected KalturaAppTokenService appTokenService; public KalturaAppTokenService getAppTokenService() { if(this.appTokenService == null) this.appTokenService = new KalturaAppTokenService(this); return this.appTokenService; } protected KalturaBaseEntryService baseEntryService; public KalturaBaseEntryService getBaseEntryService() { if(this.baseEntryService == null) this.baseEntryService = new KalturaBaseEntryService(this); return this.baseEntryService; } protected KalturaBulkUploadService bulkUploadService; public KalturaBulkUploadService getBulkUploadService() { if(this.bulkUploadService == null) this.bulkUploadService = new KalturaBulkUploadService(this); return this.bulkUploadService; } protected KalturaCategoryEntryService categoryEntryService; public KalturaCategoryEntryService getCategoryEntryService() { if(this.categoryEntryService == null) this.categoryEntryService = new KalturaCategoryEntryService(this); return this.categoryEntryService; } protected KalturaCategoryService categoryService; public KalturaCategoryService getCategoryService() { if(this.categoryService == null) this.categoryService = new KalturaCategoryService(this); return this.categoryService; } protected KalturaCategoryUserService categoryUserService; public KalturaCategoryUserService getCategoryUserService() { if(this.categoryUserService == null) this.categoryUserService = new KalturaCategoryUserService(this); return this.categoryUserService; } protected KalturaConversionProfileAssetParamsService conversionProfileAssetParamsService; public KalturaConversionProfileAssetParamsService getConversionProfileAssetParamsService() { if(this.conversionProfileAssetParamsService == null) this.conversionProfileAssetParamsService = new KalturaConversionProfileAssetParamsService(this); return this.conversionProfileAssetParamsService; } protected KalturaConversionProfileService conversionProfileService; public KalturaConversionProfileService getConversionProfileService() { if(this.conversionProfileService == null) this.conversionProfileService = new KalturaConversionProfileService(this); return this.conversionProfileService; } protected KalturaDataService dataService; public KalturaDataService getDataService() { if(this.dataService == null) this.dataService = new KalturaDataService(this); return this.dataService; } protected KalturaDeliveryProfileService deliveryProfileService; public KalturaDeliveryProfileService getDeliveryProfileService() { if(this.deliveryProfileService == null) this.deliveryProfileService = new KalturaDeliveryProfileService(this); return this.deliveryProfileService; } protected KalturaDocumentService documentService; public KalturaDocumentService getDocumentService() { if(this.documentService == null) this.documentService = new KalturaDocumentService(this); return this.documentService; } protected KalturaEmailIngestionProfileService EmailIngestionProfileService; public KalturaEmailIngestionProfileService getEmailIngestionProfileService() { if(this.EmailIngestionProfileService == null) this.EmailIngestionProfileService = new KalturaEmailIngestionProfileService(this); return this.EmailIngestionProfileService; } protected KalturaEntryServerNodeService entryServerNodeService; public KalturaEntryServerNodeService getEntryServerNodeService() { if(this.entryServerNodeService == null) this.entryServerNodeService = new KalturaEntryServerNodeService(this); return this.entryServerNodeService; } protected KalturaFileAssetService fileAssetService; public KalturaFileAssetService getFileAssetService() { if(this.fileAssetService == null) this.fileAssetService = new KalturaFileAssetService(this); return this.fileAssetService; } protected KalturaFlavorAssetService flavorAssetService; public KalturaFlavorAssetService getFlavorAssetService() { if(this.flavorAssetService == null) this.flavorAssetService = new KalturaFlavorAssetService(this); return this.flavorAssetService; } protected KalturaFlavorParamsOutputService flavorParamsOutputService; public KalturaFlavorParamsOutputService getFlavorParamsOutputService() { if(this.flavorParamsOutputService == null) this.flavorParamsOutputService = new KalturaFlavorParamsOutputService(this); return this.flavorParamsOutputService; } protected KalturaFlavorParamsService flavorParamsService; public KalturaFlavorParamsService getFlavorParamsService() { if(this.flavorParamsService == null) this.flavorParamsService = new KalturaFlavorParamsService(this); return this.flavorParamsService; } protected KalturaGroupUserService groupUserService; public KalturaGroupUserService getGroupUserService() { if(this.groupUserService == null) this.groupUserService = new KalturaGroupUserService(this); return this.groupUserService; } protected KalturaLiveChannelSegmentService liveChannelSegmentService; public KalturaLiveChannelSegmentService getLiveChannelSegmentService() { if(this.liveChannelSegmentService == null) this.liveChannelSegmentService = new KalturaLiveChannelSegmentService(this); return this.liveChannelSegmentService; } protected KalturaLiveChannelService liveChannelService; public KalturaLiveChannelService getLiveChannelService() { if(this.liveChannelService == null) this.liveChannelService = new KalturaLiveChannelService(this); return this.liveChannelService; } protected KalturaLiveReportsService liveReportsService; public KalturaLiveReportsService getLiveReportsService() { if(this.liveReportsService == null) this.liveReportsService = new KalturaLiveReportsService(this); return this.liveReportsService; } protected KalturaLiveStatsService liveStatsService; public KalturaLiveStatsService getLiveStatsService() { if(this.liveStatsService == null) this.liveStatsService = new KalturaLiveStatsService(this); return this.liveStatsService; } protected KalturaLiveStreamService liveStreamService; public KalturaLiveStreamService getLiveStreamService() { if(this.liveStreamService == null) this.liveStreamService = new KalturaLiveStreamService(this); return this.liveStreamService; } protected KalturaMediaInfoService mediaInfoService; public KalturaMediaInfoService getMediaInfoService() { if(this.mediaInfoService == null) this.mediaInfoService = new KalturaMediaInfoService(this); return this.mediaInfoService; } protected KalturaMediaService mediaService; public KalturaMediaService getMediaService() { if(this.mediaService == null) this.mediaService = new KalturaMediaService(this); return this.mediaService; } protected KalturaMixingService mixingService; public KalturaMixingService getMixingService() { if(this.mixingService == null) this.mixingService = new KalturaMixingService(this); return this.mixingService; } protected KalturaNotificationService notificationService; public KalturaNotificationService getNotificationService() { if(this.notificationService == null) this.notificationService = new KalturaNotificationService(this); return this.notificationService; } protected KalturaPartnerService partnerService; public KalturaPartnerService getPartnerService() { if(this.partnerService == null) this.partnerService = new KalturaPartnerService(this); return this.partnerService; } protected KalturaPermissionItemService permissionItemService; public KalturaPermissionItemService getPermissionItemService() { if(this.permissionItemService == null) this.permissionItemService = new KalturaPermissionItemService(this); return this.permissionItemService; } protected KalturaPermissionService permissionService; public KalturaPermissionService getPermissionService() { if(this.permissionService == null) this.permissionService = new KalturaPermissionService(this); return this.permissionService; } protected KalturaPlaylistService playlistService; public KalturaPlaylistService getPlaylistService() { if(this.playlistService == null) this.playlistService = new KalturaPlaylistService(this); return this.playlistService; } protected KalturaReportService reportService; public KalturaReportService getReportService() { if(this.reportService == null) this.reportService = new KalturaReportService(this); return this.reportService; } protected KalturaResponseProfileService responseProfileService; public KalturaResponseProfileService getResponseProfileService() { if(this.responseProfileService == null) this.responseProfileService = new KalturaResponseProfileService(this); return this.responseProfileService; } protected KalturaSchemaService schemaService; public KalturaSchemaService getSchemaService() { if(this.schemaService == null) this.schemaService = new KalturaSchemaService(this); return this.schemaService; } protected KalturaSearchService searchService; public KalturaSearchService getSearchService() { if(this.searchService == null) this.searchService = new KalturaSearchService(this); return this.searchService; } protected KalturaServerNodeService serverNodeService; public KalturaServerNodeService getServerNodeService() { if(this.serverNodeService == null) this.serverNodeService = new KalturaServerNodeService(this); return this.serverNodeService; } protected KalturaSessionService sessionService; public KalturaSessionService getSessionService() { if(this.sessionService == null) this.sessionService = new KalturaSessionService(this); return this.sessionService; } protected KalturaStatsService statsService; public KalturaStatsService getStatsService() { if(this.statsService == null) this.statsService = new KalturaStatsService(this); return this.statsService; } protected KalturaStorageProfileService storageProfileService; public KalturaStorageProfileService getStorageProfileService() { if(this.storageProfileService == null) this.storageProfileService = new KalturaStorageProfileService(this); return this.storageProfileService; } protected KalturaSyndicationFeedService syndicationFeedService; public KalturaSyndicationFeedService getSyndicationFeedService() { if(this.syndicationFeedService == null) this.syndicationFeedService = new KalturaSyndicationFeedService(this); return this.syndicationFeedService; } protected KalturaSystemService systemService; public KalturaSystemService getSystemService() { if(this.systemService == null) this.systemService = new KalturaSystemService(this); return this.systemService; } protected KalturaThumbAssetService thumbAssetService; public KalturaThumbAssetService getThumbAssetService() { if(this.thumbAssetService == null) this.thumbAssetService = new KalturaThumbAssetService(this); return this.thumbAssetService; } protected KalturaThumbParamsOutputService thumbParamsOutputService; public KalturaThumbParamsOutputService getThumbParamsOutputService() { if(this.thumbParamsOutputService == null) this.thumbParamsOutputService = new KalturaThumbParamsOutputService(this); return this.thumbParamsOutputService; } protected KalturaThumbParamsService thumbParamsService; public KalturaThumbParamsService getThumbParamsService() { if(this.thumbParamsService == null) this.thumbParamsService = new KalturaThumbParamsService(this); return this.thumbParamsService; } protected KalturaUiConfService uiConfService; public KalturaUiConfService getUiConfService() { if(this.uiConfService == null) this.uiConfService = new KalturaUiConfService(this); return this.uiConfService; } protected KalturaUploadService uploadService; public KalturaUploadService getUploadService() { if(this.uploadService == null) this.uploadService = new KalturaUploadService(this); return this.uploadService; } protected KalturaUploadTokenService uploadTokenService; public KalturaUploadTokenService getUploadTokenService() { if(this.uploadTokenService == null) this.uploadTokenService = new KalturaUploadTokenService(this); return this.uploadTokenService; } protected KalturaUserEntryService userEntryService; public KalturaUserEntryService getUserEntryService() { if(this.userEntryService == null) this.userEntryService = new KalturaUserEntryService(this); return this.userEntryService; } protected KalturaUserRoleService userRoleService; public KalturaUserRoleService getUserRoleService() { if(this.userRoleService == null) this.userRoleService = new KalturaUserRoleService(this); return this.userRoleService; } protected KalturaUserService userService; public KalturaUserService getUserService() { if(this.userService == null) this.userService = new KalturaUserService(this); return this.userService; } protected KalturaWidgetService widgetService; public KalturaWidgetService getWidgetService() { if(this.widgetService == null) this.widgetService = new KalturaWidgetService(this); return this.widgetService; } protected KalturaXInternalService xInternalService; public KalturaXInternalService getXInternalService() { if(this.xInternalService == null) this.xInternalService = new KalturaXInternalService(this); return this.xInternalService; } protected KalturaMetadataService metadataService; public KalturaMetadataService getMetadataService() { if(this.metadataService == null) this.metadataService = new KalturaMetadataService(this); return this.metadataService; } protected KalturaMetadataProfileService metadataProfileService; public KalturaMetadataProfileService getMetadataProfileService() { if(this.metadataProfileService == null) this.metadataProfileService = new KalturaMetadataProfileService(this); return this.metadataProfileService; } protected KalturaDocumentsService documentsService; public KalturaDocumentsService getDocumentsService() { if(this.documentsService == null) this.documentsService = new KalturaDocumentsService(this); return this.documentsService; } protected KalturaSystemPartnerService systemPartnerService; public KalturaSystemPartnerService getSystemPartnerService() { if(this.systemPartnerService == null) this.systemPartnerService = new KalturaSystemPartnerService(this); return this.systemPartnerService; } protected KalturaEntryAdminService entryAdminService; public KalturaEntryAdminService getEntryAdminService() { if(this.entryAdminService == null) this.entryAdminService = new KalturaEntryAdminService(this); return this.entryAdminService; } protected KalturaUiConfAdminService uiConfAdminService; public KalturaUiConfAdminService getUiConfAdminService() { if(this.uiConfAdminService == null) this.uiConfAdminService = new KalturaUiConfAdminService(this); return this.uiConfAdminService; } protected KalturaReportAdminService reportAdminService; public KalturaReportAdminService getReportAdminService() { if(this.reportAdminService == null) this.reportAdminService = new KalturaReportAdminService(this); return this.reportAdminService; } protected KalturaKalturaInternalToolsSystemHelperService kalturaInternalToolsSystemHelperService; public KalturaKalturaInternalToolsSystemHelperService getKalturaInternalToolsSystemHelperService() { if(this.kalturaInternalToolsSystemHelperService == null) this.kalturaInternalToolsSystemHelperService = new KalturaKalturaInternalToolsSystemHelperService(this); return this.kalturaInternalToolsSystemHelperService; } protected KalturaVirusScanProfileService virusScanProfileService; public KalturaVirusScanProfileService getVirusScanProfileService() { if(this.virusScanProfileService == null) this.virusScanProfileService = new KalturaVirusScanProfileService(this); return this.virusScanProfileService; } protected KalturaDistributionProfileService distributionProfileService; public KalturaDistributionProfileService getDistributionProfileService() { if(this.distributionProfileService == null) this.distributionProfileService = new KalturaDistributionProfileService(this); return this.distributionProfileService; } protected KalturaEntryDistributionService entryDistributionService; public KalturaEntryDistributionService getEntryDistributionService() { if(this.entryDistributionService == null) this.entryDistributionService = new KalturaEntryDistributionService(this); return this.entryDistributionService; } protected KalturaDistributionProviderService distributionProviderService; public KalturaDistributionProviderService getDistributionProviderService() { if(this.distributionProviderService == null) this.distributionProviderService = new KalturaDistributionProviderService(this); return this.distributionProviderService; } protected KalturaGenericDistributionProviderService genericDistributionProviderService; public KalturaGenericDistributionProviderService getGenericDistributionProviderService() { if(this.genericDistributionProviderService == null) this.genericDistributionProviderService = new KalturaGenericDistributionProviderService(this); return this.genericDistributionProviderService; } protected KalturaGenericDistributionProviderActionService genericDistributionProviderActionService; public KalturaGenericDistributionProviderActionService getGenericDistributionProviderActionService() { if(this.genericDistributionProviderActionService == null) this.genericDistributionProviderActionService = new KalturaGenericDistributionProviderActionService(this); return this.genericDistributionProviderActionService; } protected KalturaCuePointService cuePointService; public KalturaCuePointService getCuePointService() { if(this.cuePointService == null) this.cuePointService = new KalturaCuePointService(this); return this.cuePointService; } protected KalturaAnnotationService annotationService; public KalturaAnnotationService getAnnotationService() { if(this.annotationService == null) this.annotationService = new KalturaAnnotationService(this); return this.annotationService; } protected KalturaQuizService quizService; public KalturaQuizService getQuizService() { if(this.quizService == null) this.quizService = new KalturaQuizService(this); return this.quizService; } protected KalturaShortLinkService shortLinkService; public KalturaShortLinkService getShortLinkService() { if(this.shortLinkService == null) this.shortLinkService = new KalturaShortLinkService(this); return this.shortLinkService; } protected KalturaBulkService bulkService; public KalturaBulkService getBulkService() { if(this.bulkService == null) this.bulkService = new KalturaBulkService(this); return this.bulkService; } protected KalturaDropFolderService dropFolderService; public KalturaDropFolderService getDropFolderService() { if(this.dropFolderService == null) this.dropFolderService = new KalturaDropFolderService(this); return this.dropFolderService; } protected KalturaDropFolderFileService dropFolderFileService; public KalturaDropFolderFileService getDropFolderFileService() { if(this.dropFolderFileService == null) this.dropFolderFileService = new KalturaDropFolderFileService(this); return this.dropFolderFileService; } protected KalturaCaptionAssetService captionAssetService; public KalturaCaptionAssetService getCaptionAssetService() { if(this.captionAssetService == null) this.captionAssetService = new KalturaCaptionAssetService(this); return this.captionAssetService; } protected KalturaCaptionParamsService captionParamsService; public KalturaCaptionParamsService getCaptionParamsService() { if(this.captionParamsService == null) this.captionParamsService = new KalturaCaptionParamsService(this); return this.captionParamsService; } protected KalturaCaptionAssetItemService captionAssetItemService; public KalturaCaptionAssetItemService getCaptionAssetItemService() { if(this.captionAssetItemService == null) this.captionAssetItemService = new KalturaCaptionAssetItemService(this); return this.captionAssetItemService; } protected KalturaAttachmentAssetService attachmentAssetService; public KalturaAttachmentAssetService getAttachmentAssetService() { if(this.attachmentAssetService == null) this.attachmentAssetService = new KalturaAttachmentAssetService(this); return this.attachmentAssetService; } protected KalturaTagService tagService; public KalturaTagService getTagService() { if(this.tagService == null) this.tagService = new KalturaTagService(this); return this.tagService; } protected KalturaLikeService likeService; public KalturaLikeService getLikeService() { if(this.likeService == null) this.likeService = new KalturaLikeService(this); return this.likeService; } protected KalturaVarConsoleService varConsoleService; public KalturaVarConsoleService getVarConsoleService() { if(this.varConsoleService == null) this.varConsoleService = new KalturaVarConsoleService(this); return this.varConsoleService; } protected KalturaEventNotificationTemplateService eventNotificationTemplateService; public KalturaEventNotificationTemplateService getEventNotificationTemplateService() { if(this.eventNotificationTemplateService == null) this.eventNotificationTemplateService = new KalturaEventNotificationTemplateService(this); return this.eventNotificationTemplateService; } protected KalturaExternalMediaService externalMediaService; public KalturaExternalMediaService getExternalMediaService() { if(this.externalMediaService == null) this.externalMediaService = new KalturaExternalMediaService(this); return this.externalMediaService; } protected KalturaScheduledTaskProfileService scheduledTaskProfileService; public KalturaScheduledTaskProfileService getScheduledTaskProfileService() { if(this.scheduledTaskProfileService == null) this.scheduledTaskProfileService = new KalturaScheduledTaskProfileService(this); return this.scheduledTaskProfileService; } protected KalturaIntegrationService integrationService; public KalturaIntegrationService getIntegrationService() { if(this.integrationService == null) this.integrationService = new KalturaIntegrationService(this); return this.integrationService; } /** * @param String $clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return (String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param String $apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return (String) this.clientConfiguration.get("apiVersion"); } return null; } /** * Impersonated partner id * * @param Integer $partnerId */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return (Integer) this.requestConfiguration.get("partnerId"); } return null; } /** * Kaltura API session * * @param String $ks */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Kaltura API session * * @param String $sessionId */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return (String) this.requestConfiguration.get("ks"); } return null; } /** * Response profile - this attribute will be automatically unset after every API call. * * @param KalturaBaseResponseProfile $responseProfile */ public void setResponseProfile(KalturaBaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return KalturaBaseResponseProfile */ public KalturaBaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return (KalturaBaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } /** * Clear all volatile configuration parameters */ protected void resetRequest(){ this.requestConfiguration.remove("responseProfile"); } }
package org.s1.web.pages; import groovy.text.GStringTemplateEngine; import groovy.text.SimpleTemplateEngine; import groovy.text.Template; import org.s1.web.services.WebOperationInput; import org.s1.web.session.RequestScope; import org.s1.web.session.SessionScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class PagesServlet extends HttpServlet { private static final Logger LOG = LoggerFactory.getLogger(PagesServlet.class); private static Map<String, TemplateCacheRecord> templateCache = new ConcurrentHashMap<String, TemplateCacheRecord>(); /** * Layout content variable */ private static final String LAYOUT_CONTENT_VARIABLE = "layout_content"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } /** * Process request * * @param req Request * @param resp Response * @throws ServletException ServletException * @throws IOException IOException */ protected void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = null; try { id = SessionScope.retrieveSessionIdFromRequest(req, resp); SessionScope.start(id); RequestScope.start(new RequestScope.Context(req, resp)); String path = req.getServletContext().getRealPath("/"); if (path.startsWith("WEB-INF")) { resp.setStatus(403); return; } String page = req.getRequestURI().substring(req.getContextPath().length()); resp.setContentType("text/html"); resp.setCharacterEncoding("UTF-8"); String res = ""; res = render("", path, page, new WebOperationInput(req, resp), new HashMap<String, Object>(), req, resp); resp.getOutputStream().write(res.getBytes(Charset.forName("UTF-8"))); } finally { RequestScope.finish(); SessionScope.finish(id); } } private static class TemplateCacheRecord { private Template template; private long updateTime; private long size; public TemplateCacheRecord(Template template, long updateTime, long size) { this.template = template; this.updateTime = updateTime; this.size = size; } } /** * Renders page * * @param currentFileDirectoryPath Current directory path * @param webappDirectoryPath Webapp root path * @param pagePath Requested page path * @param params Request params * @param pageArguments Included page arguments (or for Layout page) * @param req Request * @param resp Response * @return Rendered page */ protected static String render(final String currentFileDirectoryPath, final String webappDirectoryPath, final String pagePath, final WebOperationInput params, final Map<String, Object> pageArguments, final HttpServletRequest req, final HttpServletResponse resp) { String pageRealPath = ""; if (pagePath.startsWith("/")) { //absolute pageRealPath = webappDirectoryPath + "/" + pagePath; } else { //relative pageRealPath = currentFileDirectoryPath + "/" + pagePath; } pageRealPath = pageRealPath.replaceAll("\\\\", "/").replaceAll("/+", "/").replace("/", File.separator); try { final String currentPath = pageRealPath.substring(0, pageRealPath.lastIndexOf(File.separator)); //LOG.debug("Rendering page: " + page); Path p1 = FileSystems.getDefault().getPath(pageRealPath); if (templateCache.containsKey(pageRealPath)) { if (templateCache.get(pageRealPath).updateTime != Files.getLastModifiedTime(p1).toMillis() || templateCache.get(pageRealPath).size != Files.size(p1)) { templateCache.remove(pageRealPath); } } if (!templateCache.containsKey(pageRealPath)) { //GStringTemplateEngine engine = new GStringTemplateEngine(); SimpleTemplateEngine engine = new SimpleTemplateEngine(); String temp = new String(Files.readAllBytes(p1), StandardCharsets.UTF_8); temp = temp.replace("$", "\\$"); Template template = engine.createTemplate( temp); templateCache.put(pageRealPath, new TemplateCacheRecord(template, Files.getLastModifiedTime(p1).toMillis(), Files.size(p1))); } Template template = templateCache.get(pageRealPath).template; if (template == null) { resp.setStatus(404); LOG.warn("Page not found: " + pageRealPath); return ""; } Map<String, Object> ctx = new HashMap<String, Object>(); PageContext pageContext = new PageContext(req, resp, params, currentPath, webappDirectoryPath); ctx.put("page", pageContext); ctx.put("args", pageArguments); String text = template.make(ctx).toString(); if (pageContext.layoutPath != null && !pageContext.layoutPath.isEmpty()) { pageContext.layoutArgs.put(LAYOUT_CONTENT_VARIABLE, text); text = render(currentPath, webappDirectoryPath, pageContext.layoutPath, params, pageContext.layoutArgs, req, resp); } return text; } catch (Throwable e) { LOG.warn("Layout page: " + pageRealPath + " error " + e.getClass().getName() + ": " + e.getMessage(), e); return ""; } } /** * Page context */ public static class PageContext { private HttpServletRequest request; private HttpServletResponse response; private WebOperationInput params; private String currentPath; private String directory; /** * @param request Request * @param response Response * @param params Request params * @param currentPath Current directory path * @param directory Webapp root directory */ public PageContext(HttpServletRequest request, HttpServletResponse response, WebOperationInput params, String currentPath, String directory) { this.request = request; this.response = response; this.params = params; this.currentPath = currentPath; this.directory = directory; } private String layoutPath; private Map<String, Object> layoutArgs = new HashMap<String, Object>(); /** * Do layout * * @param path Path to layout page */ public void layout(String path) { this.layoutPath = path; } /** * Do layout * * @param path Path to layout page * @param args Layout page arguments */ public void layout(String path, Map<String, Object> args) { this.layoutPath = path; this.layoutArgs = args; } /** * Includes page * * @param pagePath Path to page * @param args Page arguments * @return Rendered page */ public String include(String pagePath, Map<String, Object> args) { String t = render(currentPath, directory, pagePath, params, args, request, response); return t; } /** * @return Request */ public HttpServletRequest getRequest() { return request; } /** * @return Response */ public HttpServletResponse getResponse() { return response; } /** * @return Params */ public WebOperationInput getParams() { return params; } } }
package com.matt.forgehax.mods; import static com.matt.forgehax.Helper.getLocalPlayer; import static com.matt.forgehax.Helper.getNetworkManager; import static com.matt.forgehax.Helper.getPlayerController; import static com.matt.forgehax.Helper.getWorld; import static com.matt.forgehax.Helper.printInform; import static com.matt.forgehax.Helper.printWarning; import com.github.lunatrius.core.client.renderer.unique.GeometryMasks; import com.github.lunatrius.core.client.renderer.unique.GeometryTessellator; import com.google.common.base.MoreObjects; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.matt.forgehax.asm.reflection.FastReflection.Fields; import com.matt.forgehax.events.LocalPlayerUpdateEvent; import com.matt.forgehax.events.RenderEvent; import com.matt.forgehax.mods.managers.PositionRotationManager; import com.matt.forgehax.mods.managers.PositionRotationManager.RotationState.Local; import com.matt.forgehax.util.BlockHelper; import com.matt.forgehax.util.BlockHelper.BlockInfo; import com.matt.forgehax.util.Utils; import com.matt.forgehax.util.color.Colors; import com.matt.forgehax.util.command.Options; import com.matt.forgehax.util.command.Setting; import com.matt.forgehax.util.entity.EntityUtils; import com.matt.forgehax.util.entity.LocalPlayerInventory; import com.matt.forgehax.util.entity.LocalPlayerInventory.InvItem; import com.matt.forgehax.util.entity.LocalPlayerUtils; import com.matt.forgehax.util.entity.LocalPlayerUtils.BlockPlacementInfo; import com.matt.forgehax.util.entry.FacingEntry; import com.matt.forgehax.util.key.BindingHelper; import com.matt.forgehax.util.math.Angle; import com.matt.forgehax.util.math.VectorUtils; import com.matt.forgehax.util.mod.Category; import com.matt.forgehax.util.mod.ToggleMod; import com.matt.forgehax.util.mod.loader.RegisterMod; import com.matt.forgehax.util.serialization.ISerializableJson; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.settings.KeyBinding; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.network.play.client.CPacketAnimation; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.apache.commons.lang3.StringUtils; import org.lwjgl.opengl.GL11; @RegisterMod public class AutoPlace extends ToggleMod implements PositionRotationManager.MovementUpdateListener { enum Stage { SELECT_BLOCKS, SELECT_REPLACEMENT, CONFIRM, READY, ; } private final Options<PlaceConfigEntry> config = getCommandStub() .builders() .<PlaceConfigEntry>newOptionsBuilder() .name("config") .description("Saved selection configs") .factory(PlaceConfigEntry::new) .supplier(Lists::newCopyOnWriteArrayList) .build(); private final Options<FacingEntry> sides = getCommandStub() .builders() .<FacingEntry>newOptionsBuilder() .name("sides") .description("Sides to place the blocks on") .defaults(() -> Collections.singleton(new FacingEntry(EnumFacing.UP))) .factory(FacingEntry::new) .supplier(Lists::newCopyOnWriteArrayList) .build(); private final Setting<Boolean> use = getCommandStub() .builders() .<Boolean>newSettingBuilder() .name("use") .description("Will try to use the selected item on the target blocks instead of placing") .defaultTo(false) .build(); private final Setting<Boolean> whitelist = getCommandStub() .builders() .<Boolean>newSettingBuilder() .name("whitelist") .description("Makes the target list function as an inclusive list") .defaultTo(true) .build(); private final Setting<Integer> cooldown = getCommandStub() .builders() .<Integer>newSettingBuilder() .name("cooldown") .description("Block place delay to use after placing a block. Set to 0 to disable") .defaultTo(4) .min(0) .build(); private final Setting<Boolean> render = getCommandStub() .builders() .<Boolean>newSettingBuilder() .name("render") .description("Show which blocks are currently visible and being targeted") .defaultTo(false) .changed(cb -> { if(cb.getTo()) { this.renderingBlocks.clear(); this.currentRenderingTarget = null; } }) .build(); private final Set<BlockPos> renderingBlocks = Sets.newConcurrentHashSet(); private BlockPos currentRenderingTarget = null; private final KeyBinding bindSelect = new KeyBinding("AutoPlace Selection", -100, "ForgeHax"); private final KeyBinding bindFinish = new KeyBinding("AutoPlace Finished", -98, "ForgeHax"); private final AtomicBoolean bindSelectToggle = new AtomicBoolean(false); private final AtomicBoolean bindFinishToggle = new AtomicBoolean(false); private final AtomicBoolean printToggle = new AtomicBoolean(false); private final AtomicBoolean resetToggle = new AtomicBoolean(false); private final List<BlockInfo> targets = Lists.newArrayList(); private ItemStack selectedItem = null; private Runnable resetTask = null; private Stage stage = Stage.SELECT_BLOCKS; public AutoPlace() { super(Category.PLAYER, "AutoPlace", false, "Automatically place blocks on top of other blocks"); this.bindSelect.setKeyConflictContext(BindingHelper.getEmptyKeyConflictContext()); this.bindFinish.setKeyConflictContext(BindingHelper.getEmptyKeyConflictContext()); ClientRegistry.registerKeyBinding(this.bindSelect); ClientRegistry.registerKeyBinding(this.bindFinish); } private void reset() { if (resetToggle.compareAndSet(true, false)) { targets.clear(); selectedItem = null; stage = Stage.SELECT_BLOCKS; printToggle.set(false); if (resetTask != null) { resetTask.run(); resetTask = null; } printInform("AutoPlace data has been reset."); } } private boolean isValidBlock(BlockInfo info) { return whitelist.get() ? targets.stream().anyMatch(info::equals) : targets.stream().noneMatch(info::equals); } private boolean isClickable(BlockInfo info) { return sides .stream() .map(FacingEntry::getFacing) .anyMatch(side -> BlockHelper.isBlockReplaceable(info.getPos().offset(side))); } private EnumFacing getBestFacingMatch(final String input) { return Arrays.stream(EnumFacing.values()) .filter(side -> side.getName2().toLowerCase().contains(input.toLowerCase())) .min( Comparator.comparing( e -> e.getName2().toLowerCase(), Comparator.<String>comparingInt( n -> StringUtils.getLevenshteinDistance(n, input.toLowerCase())) .thenComparing(n -> n.startsWith(input)))) .orElseGet( () -> { EnumFacing[] values = EnumFacing.values(); try { int index = Integer.valueOf(input); return values[MathHelper.clamp(index, 0, values.length - 1)]; } catch (NumberFormatException e) { return values[0]; } }); } private void showInfo(String filter) { MC.addScheduledTask( () -> { if ("selected".startsWith(filter)) printInform( "Selected item %s", this.selectedItem.getItem().getRegistryName().toString() + "{" + this.selectedItem.getMetadata() + "}"); if ("targets".startsWith(filter)) printInform( "Targets: %s", this.targets.stream().map(BlockInfo::toString).collect(Collectors.joining(", "))); if ("sides".startsWith(filter)) printInform( "Sides: %s", this.sides .stream() .map(FacingEntry::getFacing) .map(EnumFacing::getName2) .collect(Collectors.joining(", "))); if ("whitelist".startsWith(filter)) printInform("Whitelist: %s", Boolean.toString(whitelist.get())); if ("use".startsWith(filter)) printInform("Use: %s", Boolean.toString(use.get())); }); } @Override protected void onLoad() { getCommandStub() .builders() .newCommandBuilder() .name("reset") .description("Reset to the setup process") .processor( data -> { resetToggle.set(true); if (getLocalPlayer() == null && getWorld() == null) reset(); }) .build(); getCommandStub() .builders() .newCommandBuilder() .name("info") .description("Print info about the mod") .processor( data -> { String arg = data.getArgumentCount() > 1 ? data.getArgumentAsString(0) : ""; showInfo(arg); }) .build(); sides .builders() .newCommandBuilder() .name("add") .description("Add side to the list") .requiredArgs(1) .processor( data -> { final String name = data.getArgumentAsString(0); EnumFacing facing = getBestFacingMatch(name); if (sides.get(facing) == null) { sides.add(new FacingEntry(facing)); data.write("Added side " + facing.getName2()); data.markSuccess(); sides.serializeAll(); } else { data.write(facing.getName2() + " already exists"); data.markFailed(); } }) .build(); sides .builders() .newCommandBuilder() .name("remove") .description("Remove side from the list") .requiredArgs(1) .processor( data -> { final String name = data.getArgumentAsString(0); EnumFacing facing = getBestFacingMatch(name); if (sides.remove(new FacingEntry(facing))) { data.write("Removed side " + facing.getName2()); data.markSuccess(); sides.serializeAll(); } else { data.write(facing.getName2() + " doesn't exist"); data.markFailed(); } }) .build(); sides .builders() .newCommandBuilder() .name("list") .description("List all the current added sides") .processor( data -> { data.write( "Sides: " + sides .stream() .map(FacingEntry::getFacing) .map(EnumFacing::getName2) .collect(Collectors.joining(", "))); data.markSuccess(); }) .build(); config .builders() .newCommandBuilder() .name("save") .description("Save current setup") .requiredArgs(1) .processor( data -> { String name = data.getArgumentAsString(0); if (config.get(name) == null) { PlaceConfigEntry entry = new PlaceConfigEntry(name); entry.setSides( this.sides.stream().map(FacingEntry::getFacing).collect(Collectors.toSet())); entry.setTargets(this.targets); entry.setSelection(this.selectedItem); entry.setWhitelist(this.whitelist.get()); entry.setUse(this.use.get()); config.add(entry); config.serializeAll(); data.write("Saved current config as " + name); data.markSuccess(); } else { data.write(name + " is already in use!"); data.markFailed(); } }) .build(); config .builders() .newCommandBuilder() .name("load") .description("Load config") .requiredArgs(1) .processor( data -> { String name = data.getArgumentAsString(0); PlaceConfigEntry entry = config.get(name); if (entry != null) { data.write(name + " loaded"); resetTask = () -> { this.targets.clear(); this.targets.addAll(entry.getTargets()); this.sides.clear(); this.sides.addAll( entry .getSides() .stream() .map(FacingEntry::new) .collect(Collectors.toSet())); this.selectedItem = entry.getSelection(); this.whitelist.set(entry.isWhitelist()); this.use.set(entry.isUse()); this.stage = Stage.CONFIRM; this.getCommandStub().serializeAll(); }; this.resetToggle.set(true); } else { data.write(name + " doesn't exist!"); data.markFailed(); } }) .build(); config .builders() .newCommandBuilder() .name("delete") .description("Delete a configuration") .requiredArgs(1) .processor( data -> { String name = data.getArgumentAsString(0); if (config.remove(new PlaceConfigEntry(name))) { config.serializeAll(); data.write("Deleted config " + name); data.markSuccess(); } else { data.write(name + " doesn't exist!"); data.markFailed(); } }) .build(); config .builders() .newCommandBuilder() .name("list") .description("List all the current configs") .processor( data -> { data.write( "Configs: " + config .stream() .map(PlaceConfigEntry::getName) .collect(Collectors.joining(", "))); data.markSuccess(); }) .build(); } @Override protected void onEnabled() { PositionRotationManager.getManager().register(this); } @Override protected void onDisabled() { PositionRotationManager.getManager().unregister(this); printToggle.set(false); } @SubscribeEvent public void onRender(RenderEvent event) { if (!render.get() || MC.getRenderViewEntity() == null) return; Vec3d renderingOffset = EntityUtils.getInterpolatedPos(MC.getRenderViewEntity(), MC.getRenderPartialTicks()); GlStateManager.pushMatrix(); GlStateManager.disableTexture2D(); GlStateManager.enableBlend(); GlStateManager.disableAlpha(); GlStateManager.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0); GlStateManager.shadeModel(GL11.GL_SMOOTH); GlStateManager.disableDepth(); final GeometryTessellator tessellator = event.getTessellator(); final BufferBuilder builder = tessellator.getBuffer(); final double partialTicks = MC.getRenderPartialTicks(); tessellator.beginLines(); tessellator.setTranslation(0, 0, 0); GlStateManager.translate(0, 0, 0); GlStateManager.translate(-renderingOffset.x, -renderingOffset.y, -renderingOffset.z); renderingBlocks.forEach( pos -> { IBlockState state = getWorld().getBlockState(pos); AxisAlignedBB bb = state.getBoundingBox(getWorld(), pos); tessellator.setTranslation(pos.getX(), pos.getY(), pos.getZ()); GeometryTessellator.drawLines( builder, bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ, GeometryMasks.Line.ALL, Colors.GREEN.setAlpha(150).toBuffer()); }); // poz BlockPos current; try { current = new BlockPos(this.currentRenderingTarget); } catch (Throwable t) { current = null; } if (current != null) { IBlockState state = getWorld().getBlockState(current); AxisAlignedBB bb = state.getBoundingBox(getWorld(), current); tessellator.setTranslation(current.getX(), current.getY(), current.getZ()); GeometryTessellator.drawLines( builder, bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ, GeometryMasks.Line.ALL, Colors.RED.setAlpha(150).toBuffer()); } tessellator.draw(); tessellator.setTranslation(0, 0, 0); GlStateManager.shadeModel(GL11.GL_FLAT); GlStateManager.disableBlend(); GlStateManager.enableAlpha(); GlStateManager.enableTexture2D(); GlStateManager.enableDepth(); GlStateManager.enableCull(); GL11.glDisable(GL11.GL_LINE_SMOOTH); GlStateManager.popMatrix(); } @SubscribeEvent public void onUpdate(LocalPlayerUpdateEvent event) { reset(); switch (stage) { case SELECT_BLOCKS: { if (printToggle.compareAndSet(false, true)) { targets.clear(); printInform("Select blocks by pressing %s", BindingHelper.getIndexName(bindSelect)); printInform("Finish this stage by pressing %s", BindingHelper.getIndexName(bindFinish)); } if (bindSelect.isKeyDown() && bindSelectToggle.compareAndSet(false, true)) { RayTraceResult tr = LocalPlayerUtils.getMouseOverBlockTrace(); if (tr == null) return; BlockInfo info = BlockHelper.newBlockInfo(tr.getBlockPos()); if (info.isInvalid()) { printWarning("Invalid block %s", info.toString()); return; } if (!targets.contains(info)) { printInform("Added block %s", info.toString()); targets.add(info); } else { printInform("Removed block %s", info.toString()); targets.remove(info); } } else if (!bindSelect.isKeyDown()) { bindSelectToggle.set(false); } if (bindFinish.isKeyDown() && bindFinishToggle.compareAndSet(false, true)) { if (targets.isEmpty()) { printWarning("No items have been selected yet!"); } else { stage = Stage.SELECT_REPLACEMENT; printToggle.set(false); } } else if (!bindFinish.isKeyDown()) { bindFinishToggle.set(false); } break; } case SELECT_REPLACEMENT: { if (printToggle.compareAndSet(false, true)) printInform( "Hover over the block in your hot bar you want to place and press %s to select", BindingHelper.getIndexName(bindSelect)); if (bindSelect.isKeyDown() && bindSelectToggle.compareAndSet(false, true)) { InvItem selected = LocalPlayerInventory.getSelected(); if (selected.isNull()) { printWarning("No item selected!"); return; } this.selectedItem = new ItemStack(selected.getItem(), 1, selected.getItemStack().getMetadata()); printInform( "Selected item %s", this.selectedItem.getItem().getRegistryName().toString() + "{" + this.selectedItem.getMetadata() + "}"); stage = Stage.CONFIRM; printToggle.set(false); } else if (!bindSelect.isKeyDown()) { bindSelectToggle.set(false); } break; } case CONFIRM: { if (printToggle.compareAndSet(false, true)) { printInform( "Press %s to begin, or '.%s info' to set the current settings", BindingHelper.getIndexName(bindFinish), getModName()); } if (bindFinish.isKeyDown() && selectedItem != null && bindFinishToggle.compareAndSet(false, true)) { printInform("Block place process started"); printInform("Type '.%s reset' to restart the process", getModName()); stage = Stage.READY; } else if (!bindFinish.isKeyDown()) { bindFinishToggle.set(false); } break; } case READY: { if (bindFinish.isKeyDown() && bindFinishToggle.compareAndSet(false, true)) { printInform("Block place process paused"); stage = Stage.CONFIRM; } else if (!bindFinish.isKeyDown()) { bindFinishToggle.set(false); } break; } } } @Override public void onLocalPlayerMovementUpdate(Local state) { if (!Stage.READY.equals(stage)) { renderingBlocks.clear(); currentRenderingTarget = null; return; } if (cooldown.get() > 0 && Fields.Minecraft_rightClickDelayTimer.get(MC) > 0) return; if (render.get()) { renderingBlocks.clear(); currentRenderingTarget = null; } InvItem items = LocalPlayerInventory.getHotbarInventory() .stream() .filter(InvItem::nonNull) .filter(inv -> inv.getItem().equals(selectedItem.getItem())) .filter( item -> !(item.getItem() instanceof ItemBlock) || item.getItemStack().getMetadata() == selectedItem.getMetadata()) .findFirst() .orElse(InvItem.EMPTY); if (items.isNull()) return; final Vec3d eyes = EntityUtils.getEyePos(getLocalPlayer()); final Vec3d dir = LocalPlayerUtils.getViewAngles().getDirectionVector(); List<BlockInfo> blocks = BlockHelper.getBlocksInRadius(eyes, getPlayerController().getBlockReachDistance()) .stream() .map(BlockHelper::newBlockInfo) .filter(this::isValidBlock) .filter(this::isClickable) .sorted( Comparator.comparingDouble( info -> VectorUtils.getCrosshairDistance(eyes, dir, new Vec3d(info.getPos())))) .collect(Collectors.toList()); if (blocks.isEmpty()) return; if (render.get()) { currentRenderingTarget = null; renderingBlocks.clear(); renderingBlocks.addAll(blocks.stream().map(BlockInfo::getPos).collect(Collectors.toSet())); } // find a block that can be placed int index = 0; BlockPlacementInfo info = null; do { if (index >= blocks.size()) break; final BlockInfo at = blocks.get(index++); if (use.get()) { info = sides .stream() .map(FacingEntry::getFacing) .map(side -> new BlockPlacementInfo(at.getPos(), side.getOpposite())) .filter(i -> BlockHelper.isTraceClear(eyes, i.getHitVec())) .filter(i -> LocalPlayerUtils.isInReach(eyes, i.getHitVec())) .min( Comparator.comparingDouble( i -> VectorUtils.getCrosshairDistance(eyes, dir, i.getCenteredPos()))) .orElse(null); } else { info = sides .stream() .map(FacingEntry::getFacing) .map(side -> LocalPlayerUtils.getBlockPlacementInfo(at.getPos().offset(side))) .filter(Objects::nonNull) .findAny() .orElse(null); } } while (info == null); // if the block list is exhausted if (info == null) return; if (render.get()) currentRenderingTarget = info.getPos(); Vec3d hit = info.getHitVec(); Angle va = Utils.getLookAtAngles(hit); state.setServerAngles(va); final BlockPlacementInfo blockInfo = info; state.invokeLater( rs -> { LocalPlayerInventory.setSelected(items); // enable sneaking to prevent unwanted block interactions boolean sneaking = LocalPlayerUtils.isSneaking(); LocalPlayerUtils.setSneaking(true); getPlayerController() .processRightClickBlock( getLocalPlayer(), getWorld(), blockInfo.getPos(), blockInfo.getOppositeSide(), hit, EnumHand.MAIN_HAND); LocalPlayerUtils.setSneaking(sneaking); // stealth send swing packet getNetworkManager().sendPacket(new CPacketAnimation(EnumHand.MAIN_HAND)); // set the block place delay Fields.Minecraft_rightClickDelayTimer.set(MC, cooldown.get()); }); } private static class PlaceConfigEntry implements ISerializableJson { private final String name; private final List<BlockInfo> targets = Lists.newArrayList(); private final List<EnumFacing> sides = Lists.newArrayList(); private ItemStack selection = ItemStack.EMPTY; private boolean use = false; private boolean whitelist = true; private PlaceConfigEntry(String name) { Objects.requireNonNull(name); this.name = name; } public String getName() { return name; } public List<BlockInfo> getTargets() { return Collections.unmodifiableList(targets); } public void setTargets(Collection<BlockInfo> list) { targets.clear(); targets.addAll( list.stream() .filter(info -> !Blocks.AIR.equals(info.getBlock())) .collect(Collectors.toSet())); // collect to set to eliminate duplicates } public List<EnumFacing> getSides() { return Collections.unmodifiableList(sides); } public void setSides(Collection<EnumFacing> list) { sides.clear(); sides.addAll(Sets.newLinkedHashSet(list)); // copy to set to eliminate duplicates } public ItemStack getSelection() { return selection; } public void setSelection(ItemStack selection) { this.selection = Optional.ofNullable(selection) .filter(s -> !Items.AIR.equals(s.getItem())) .orElse(ItemStack.EMPTY); } public boolean isUse() { return use; } public void setUse(boolean use) { this.use = use; } public boolean isWhitelist() { return whitelist; } public void setWhitelist(boolean whitelist) { this.whitelist = whitelist; } @Override public void serialize(JsonWriter writer) throws IOException { writer.beginObject(); writer.name("selection"); writer.beginObject(); { writer.name("item"); writer.value(getSelection().getItem().getRegistryName().toString()); writer.name("metadata"); writer.value(getSelection().getMetadata()); } writer.endObject(); writer.name("targets"); writer.beginArray(); { for (BlockInfo info : getTargets()) { writer.beginObject(); writer.name("block"); writer.value(info.getBlock().getRegistryName().toString()); writer.name("metadata"); writer.value(info.getMetadata()); writer.endObject(); } } writer.endArray(); writer.name("use"); writer.value(isUse()); writer.name("whitelist"); writer.value(isWhitelist()); writer.name("sides"); writer.beginArray(); { for (EnumFacing side : getSides()) writer.value(side.getName2()); } writer.endArray(); writer.endObject(); } @Override public void deserialize(JsonReader reader) throws IOException { reader.beginObject(); while (reader.hasNext()) { switch (reader.nextName()) { case "selection": { reader.beginObject(); reader.nextName(); Item item = ItemSword.getByNameOrId(reader.nextString()); reader.nextName(); int meta = reader.nextInt(); setSelection(new ItemStack(MoreObjects.firstNonNull(item, Items.AIR), 1, meta)); reader.endObject(); break; } case "targets": { reader.beginArray(); List<BlockInfo> blocks = Lists.newArrayList(); while (reader.hasNext()) { reader.beginObject(); // block reader.nextName(); Block block = Block.getBlockFromName(reader.nextString()); // metadata reader.nextName(); int meta = reader.nextInt(); blocks.add(BlockHelper.newBlockInfo(block, meta)); reader.endObject(); } setTargets(blocks); reader.endArray(); break; } case "use": { setUse(reader.nextBoolean()); break; } case "whitelist": { setWhitelist(reader.nextBoolean()); break; } case "sides": { reader.beginArray(); List<EnumFacing> sides = Lists.newArrayList(); while (reader.hasNext()) { sides.add( Optional.ofNullable(reader.nextString()) .map(EnumFacing::byName) .orElse(EnumFacing.UP)); } setSides(sides); reader.endArray(); break; } default: break; } } reader.endObject(); } @Override public boolean equals(Object obj) { return this == obj || (obj instanceof PlaceConfigEntry && getName().equalsIgnoreCase(((PlaceConfigEntry) obj).getName())) || (obj instanceof String && getName().equalsIgnoreCase((String) obj)); } @Override public String toString() { return name; } } }
package org.xins.server; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.Properties; import java.util.StringTokenizer; import javax.servlet.ServletConfig; import org.apache.log4j.LogManager; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.helpers.NullEnumeration; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.Utils; import org.xins.common.collections.InvalidPropertyValueException; import org.xins.common.collections.PropertiesPropertyReader; import org.xins.common.collections.PropertyReader; import org.xins.common.collections.PropertyReaderUtils; import org.xins.common.collections.StatsPropertyReader; import org.xins.common.collections.UniqueProperties; import org.xins.common.io.FileWatcher; import org.xins.common.io.HTTPFileWatcher; import static org.xins.common.text.TextUtils.fuzzyEquals; import static org.xins.common.text.TextUtils.isEmpty; import static org.xins.common.text.TextUtils.quote; import static org.xins.common.text.TextUtils.trim; import org.znerd.logdoc.LogCentral; import org.znerd.logdoc.UnsupportedLocaleException; final class ConfigManager { /** * The name of the system property that determines if the Log4J logging * subsystem is initialized by the XINS/Java Server Framework. Default is * that initialization is indeed done by XINS. Should be either * <code>"true"</code> or <code>"false"</code>, default is * <code>"true"</code>. */ public static final String INIT_LOGGING_SYSTEM_PROPERTY = "org.xins.server.logging.init"; /** * The system/bootstrap/runtime property that controls if context IDs are * generated. In Log4J terminology these are called NDCs (Nested Diagnostic * Context identifiers). */ static final String CONTEXT_ID_PUSH_PROPERTY = "org.xins.server.contextID.push"; /** * Flag that determines if the Log4J logging subsystem should be initialized. */ private static boolean INIT_LOGGING; /** * The name of the system property that specifies the location of the * configuration file. */ static final String CONFIG_FILE_SYSTEM_PROPERTY = "org.xins.server.config"; /** * The name of the runtime property that specifies the interval * for the configuration file modification checks, in seconds. */ static final String CONFIG_RELOAD_INTERVAL_PROPERTY = "org.xins.server.config.reload"; /** * The name of the runtime property that specifies the list of runtime * properties file to include. The paths must be relative to the * current config file. */ static final String CONFIG_INCLUDE_PROPERTY = "org.xins.server.config.include"; /** * The default configuration file modification check interval, in seconds. */ static final int DEFAULT_CONFIG_RELOAD_INTERVAL = 5; // XXX: Consider adding state checking /** * The object to synchronize on when reading and initializing from the * runtime configuration file. */ private static final Object RUNTIME_PROPERTIES_LOCK = new Object(); /** * The <code>Engine</code> that owns this <code>ConfigManager</code>. Never * <code>null</code>. */ private final Engine _engine; /** * Servlet configuration. Never <code>null</code>. */ private final ServletConfig _config; /** * The listener that is notified when the configuration file changes. Only * one instance is created ever. */ private final ConfigurationFileListener _configFileListener; /** * The name of the runtime configuration file. Initially <code>null</code>. */ private String _configFile; /** * The name of the all runtime configuration files included in the main config file. * Can be <code>null</code> or empty. */ private String[] _configFiles; /** * The String representation of the config files. Initialy <code>null</code>. */ private String _configFilesPath; /** * Watcher for the runtime configuration file. Initially <code>null</code>. */ private FileWatcher _configFileWatcher; /** * The set of properties read from the runtime configuration file. Never * <code>null</code>. */ private StatsPropertyReader _runtimeProperties; /** * Flag indicating that the runtime properties were read correcly. */ private boolean _propertiesRead; ConfigManager(Engine engine, ServletConfig config) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("engine", engine, "config", config); // Initialize fields _engine = engine; _config = config; _configFileListener = new ConfigurationFileListener(); } /** * Initializes this class. */ static void systemStartup() { // Determine if the logging subsystem should be initialized INIT_LOGGING = getBoolSystemProperty(INIT_LOGGING_SYSTEM_PROPERTY, true); // Determine if context IDs should be set PUSH_CONTEXT_ID = getBoolSystemProperty(CONTEXT_ID_PUSH_PROPERTY, true); // Configure logger fallback configureLoggerFallback(); } private static boolean getBoolSystemProperty(String propName, boolean fallback) { // TODO: Separate Logdoc entries // Check preconditions MandatoryArgumentChecker.check("propName", propName); String setting; try { setting = System.getProperty(propName); } catch (Throwable exception) { Utils.logError("Failed to retrieve system property " + quote(propName) + ". Assuming \"" + fallback + "\".", exception); return fallback; } boolean value; if (fuzzyEquals("true", setting)) { value = true; } else if (fuzzyEquals("false", setting)) { value = false; } else if (isEmpty(setting)) { Utils.logInfo("System property \"" + propName + "\" is unset or empty. Assuming \"" + fallback + "\"."); value = fallback; } else { Utils.logWarning("System property \"" + propName + "\" has invalid value " + quote(setting) + ". Expected either \"true\" or \"false\". Assuming default, which is \"" + fallback + "\"."); value = fallback; } return value; } /** * Flag that indicates if context IDs should be generated. */ static boolean PUSH_CONTEXT_ID = true; /** * Sets if context IDs should be set. * * @param flag * <code>true</code> if context IDs should be pushed, * <code>false</code> if not. */ static synchronized void setPushContextID(boolean flag) { PUSH_CONTEXT_ID = flag; if (flag) { Utils.logInfo("Context ID pushing enabled."); } else { Utils.logInfo("Context ID pushing disabled."); } } /** * Determines if context IDs should be set. * * @return * <code>true</code> if context IDs should be pushed, * <code>false</code> if not. */ static synchronized boolean isPushContextID() { return PUSH_CONTEXT_ID; } /** * Initializes the logging subsystem with fallback default settings, * if applicable. */ static void configureLoggerFallback() { // TODO: Separate Logdoc entries // Do initialize the logging subsystem if (INIT_LOGGING) { configureLoggerFallbackImpl(); Utils.logInfo("Initialized Log4J configuration."); } else { Utils.logInfo("Skipped Log4J initialization."); } } /** * Initializes the logging subsystem with fallback default settings. */ private static void configureLoggerFallbackImpl() { Properties settings = new Properties(); // Send all log messages to the logger named 'console' settings.setProperty("log4j.rootLogger", "ALL, console"); // Define an appender for the console settings.setProperty("log4j.appender.console", "org.apache.log4j.ConsoleAppender"); // Use a pattern-layout for the appender settings.setProperty("log4j.appender.console.layout", "org.apache.log4j.PatternLayout"); // Define the pattern for the appender settings.setProperty("log4j.appender.console.layout.ConversionPattern", "%6c{1} %-6p %x %m%n"); // Do not show the debug logs produced by XINS. settings.setProperty("log4j.logger.org.xins.", "INFO"); // Perform Log4J configuration PropertyConfigurator.configure(settings); } /** * Determines the name of the runtime configuration file. The system * properties will be queried first. If they do not provide it, then the * servlet initialization properties are tried. Once determined, the name * will be stored internally. */ void determineConfigFile() { // Get the value of the appropriate system property String configFile = null; try { configFile = System.getProperty(CONFIG_FILE_SYSTEM_PROPERTY); } catch (SecurityException exception) { Log.log_3230(exception, CONFIG_FILE_SYSTEM_PROPERTY); } // If the name of the configuration file is not set in a system property // (typically passed on the command-line) try to get it from the servlet // initialization properties (typically set in a web.xml file) if (configFile == null || configFile.length() < 1) { Log.log_3231(CONFIG_FILE_SYSTEM_PROPERTY); configFile = _config.getInitParameter(CONFIG_FILE_SYSTEM_PROPERTY); } // Store the name of the configuration file _configFile = configFile; } /** * Unifies the file separator character on the _configFile property and then * reads the runtime properties file, initializes the logging subsystem * with the read properties and then stores those properties on the engine. * If the _configFile is empty, then an empty set of properties is set on * the engine. */ void readRuntimeProperties() { UniqueProperties properties = new UniqueProperties(); InputStream in = null; // If the value is not set only localhost can access the API. // NOTE: Don't trim the configuration file name, since it may start // with a space or other whitespace character. if (_configFile == null) { // Try to find a xins.properties file in the WEB-INF directory in = _engine.getResourceAsStream("/WEB-INF/xins.properties"); if (in == null) { // Use the default settings Log.log_3205(CONFIG_FILE_SYSTEM_PROPERTY); _runtimeProperties = null; _propertiesRead = true; return; } else { Log.log_3248(); } } boolean propertiesRead = false; _configFilesPath = _configFile; synchronized (ConfigManager.RUNTIME_PROPERTIES_LOCK) { try { if (in != null) { properties.load(in); in.close(); } else if (!_configFile.startsWith("http: // Unify the file separator character _configFile = _configFile.replace('/', File.separatorChar); _configFile = _configFile.replace('\\', File.separatorChar); properties = readLocalRuntimeProperties(); } else { properties = readHTTPRuntimeProperties(); } propertiesRead = true; // Security issue } catch (SecurityException exception) { Log.log_3302(exception, _configFilesPath); // No such file } catch (FileNotFoundException exception) { String detail = trim(exception.getMessage(), null); Log.log_3301(_configFilesPath, detail); // Other I/O error } catch (IOException exception) { Log.log_3303(exception, _configFilesPath); } // Initialize the logging subsystem Log.log_3300(_configFilesPath); // Attempt to configure Log4J configureLogger(properties); if (!properties.isUnique()) { Log.log_3311(_configFilesPath); propertiesRead = false; } if (propertiesRead) { // Convert to a PropertyReader PropertyReader pr = new PropertiesPropertyReader(properties); _runtimeProperties = new StatsPropertyReader(pr); } _propertiesRead = propertiesRead; } } /** * Read the runtime properties files when files are specified locally. * * @return * The runtime properties read from the files, never <code>null</code>. * * @throws IOException * if the file cannot be found or be read. */ private UniqueProperties readLocalRuntimeProperties() throws IOException { UniqueProperties properties = new UniqueProperties(); InputStream in = null; try { // Open file, load properties, close file in = new FileInputStream(_configFile); properties.load(in); // Read the included files if (properties.getProperty(CONFIG_INCLUDE_PROPERTY) != null && !properties.getProperty(CONFIG_INCLUDE_PROPERTY).trim().equals("")) { StringTokenizer stInclude = new StringTokenizer(properties.getProperty(CONFIG_INCLUDE_PROPERTY), ","); File baseFile = new File(_configFile).getParentFile(); _configFiles = new String[stInclude.countTokens() + 1]; _configFiles[0] = _configFile; _configFilesPath += "+ ["; int i = 0; while (stInclude.hasMoreTokens()) { String nextInclude = stInclude.nextToken().trim().replace('/', File.separatorChar).replace('\\', File.separatorChar); File includeFile = new File(baseFile, nextInclude); FileInputStream isInclude = new FileInputStream(includeFile); properties.load(isInclude); isInclude.close(); _configFiles[i + 1] = nextInclude; _configFilesPath += nextInclude + ";"; i++; } _configFilesPath += "]"; } else { _configFiles = new String[1]; _configFiles[0] = _configFile; } // Always close the input stream } finally { if (in != null) { try { in.close(); } catch (Throwable exception) { Utils.logIgnoredException(exception); } } } return properties; } /** * Read the runtime properties files when files are specified locally. * * @return * The runtime properties read from the URLs, never <code>null</code>. * * @throws IOException * if the URL cannot be created or if the connection to the URL failed. */ private UniqueProperties readHTTPRuntimeProperties() throws IOException { UniqueProperties properties = new UniqueProperties(); InputStream in = null; try { // Open file, load properties, close file URL configURL = new URL(_configFile); in = configURL.openStream(); properties.load(in); // Read the included files if (properties.getProperty(CONFIG_INCLUDE_PROPERTY) != null && !properties.getProperty(CONFIG_INCLUDE_PROPERTY).trim().equals("")) { StringTokenizer stInclude = new StringTokenizer(properties.getProperty(CONFIG_INCLUDE_PROPERTY), ","); _configFiles = new String[stInclude.countTokens() + 1]; _configFiles[0] = _configFile; _configFilesPath += "+ ["; int i = 0; while (stInclude.hasMoreTokens()) { String nextInclude = stInclude.nextToken().trim().replace('/', File.separatorChar).replace('\\', File.separatorChar); URL includeFile = new URL(configURL, nextInclude); InputStream isInclude = includeFile.openStream(); properties.load(isInclude); isInclude.close(); _configFiles[i + 1] = nextInclude; _configFilesPath += nextInclude + ";"; i++; } _configFilesPath += "]"; } else { _configFiles = new String[1]; _configFiles[0] = _configFile; } // Always close the input stream } finally { if (in != null) { try { in.close(); } catch (Throwable exception) { Utils.logIgnoredException(exception); } } } return properties; } /** * Gets the runtime properties. * * @return * the runtime properties, never <code>null</code>. */ PropertyReader getRuntimeProperties() { if (_runtimeProperties == null) { return PropertyReaderUtils.EMPTY_PROPERTY_READER; } else { return _runtimeProperties; } } /** * Determines the reload interval for the config file, initializes the API * if the interval has changed and starts the config file watcher. */ void init() { // Determine the reload interval int interval = DEFAULT_CONFIG_RELOAD_INTERVAL; if (_configFile != null) { try { interval = determineConfigReloadInterval(); // If the interval could not be parsed, then use the default } catch (InvalidPropertyValueException exception) { // ignore } } // Initialize the API long startTimeInitialization = System.currentTimeMillis(); boolean initialized = _engine.initAPI(); // Start the configuration file watch interval, if the location of the // file is set and the interval is greater than 0 if (_configFile != null && interval > 0) { startConfigFileWatcher(interval); } // API initialized successfully, so log each unused property... if (initialized) { logUnusedRuntimeProperties(); // ...and log that the framework was (re)initialized int duration = (int) (System.currentTimeMillis() - startTimeInitialization); Log.log_3415(duration); } } /** * Logs the unused runtime properties. Properties for Log4J (those starting * with <code>"log4j."</code> are ignored. */ private void logUnusedRuntimeProperties() { if (_runtimeProperties != null) { for (String name : _runtimeProperties.getUnused().names()) { if (! (isEmpty(name) || name.startsWith("log4j."))) { Log.log_3434(name); } } } } void startConfigFileWatcher(int interval) throws IllegalStateException, IllegalArgumentException { // Check state: Config file must be set if (_configFile == null || _configFile.length() < 1) { throw new IllegalStateException( "Name of runtime configuration file not set."); // Check state: File watcher cannot exist yet } else if (_configFileWatcher != null) { throw new IllegalStateException( "Runtime configuration file watcher exists."); // Check arguments } else if (interval < 1) { throw new IllegalArgumentException("interval (" + interval + ") < 1"); } // Create and start a file watch thread if (_configFile.startsWith("http: _configFileWatcher = new HTTPFileWatcher(_configFiles, interval, _configFileListener); } else { _configFileWatcher = new FileWatcher(_configFiles, interval, _configFileListener); } _configFileWatcher.start(); } /** * Re-initializes the configuration file listener if there is no file * watcher; otherwise interrupts the file watcher. */ void reloadPropertiesIfChanged() { if (_configFileWatcher == null) { _configFileListener.reinit(); } else { synchronized (_configFileWatcher) { _configFileWatcher.notifyAll(); } } } void configureLogger(Properties properties) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("properties", properties); // Short-circuit if logging configuration is done outside XINS if (! INIT_LOGGING) { return; } // Reset Log4J configuration LogManager.getLoggerRepository().resetConfiguration(); // Make possible to have an API specific logger String apiLogger = properties.getProperty("log4j.rootLogger." + _config.getServletName()); if (apiLogger != null) { properties.setProperty("log4j.rootLogger", apiLogger); } // Reconfigure Log4J PropertyConfigurator.configure(properties); // Determine if Log4J is properly initialized Enumeration appenders = LogManager.getLoggerRepository().getRootLogger().getAllAppenders(); // If the properties did not include Log4J configuration settings, then // fallback to default settings if (appenders instanceof NullEnumeration) { Log.log_3304(_configFilesPath); configureLoggerFallback(); // Otherwise log that custom Log4J configuration settings were applied } else { Log.log_3305(); } } /** * Determines the interval for checking the runtime properties file for * modifications. * * @return * the interval to use, always &gt;= 1. * * @throws InvalidPropertyValueException * if the interval cannot be determined because it does not qualify as a * positive 32-bit unsigned integer number. */ int determineConfigReloadInterval() throws InvalidPropertyValueException { // Check state if (_configFile == null || _configFile.length() < 1) { throw new IllegalStateException("Name of runtime configuration file not set."); } // Get the runtime property String prop = CONFIG_RELOAD_INTERVAL_PROPERTY; String s = _runtimeProperties.get(prop); int interval; // If the property is set, parse it if (s != null && s.length() >= 1) { try { interval = Integer.parseInt(s); // Negative value if (interval < 0) { Log.log_3409(_configFilesPath, prop, s); throw new InvalidPropertyValueException(prop, s, "Negative value."); // Non-negative value } else { Log.log_3410(_configFilesPath, s); } // Not a valid number string } catch (NumberFormatException nfe) { Log.log_3409(_configFilesPath, prop, s); throw new InvalidPropertyValueException(prop, s, "Not a 32-bit integer number."); } // Property not set, use the default } else { Log.log_3408(_configFilesPath, prop, DEFAULT_CONFIG_RELOAD_INTERVAL); interval = DEFAULT_CONFIG_RELOAD_INTERVAL; } return interval; } /** * Determines the log locale. * * @return * <code>false</code> if the specified locale is not supported, * <code>true</code> otherwise. */ boolean determineLogLocale() { String newLocale = null; // If we have runtime properties, then get the log locale if (_runtimeProperties != null) { newLocale = _runtimeProperties.get(LogCentral.LOG_LOCALE_PROPERTY); } // If the log locale is set, apply it if (newLocale != null) { String currentLocale = LogCentral.getLocale(); if (! currentLocale.equals(newLocale)) { Log.log_3306(currentLocale, newLocale); try { LogCentral.setLocale(newLocale); Log.log_3307(currentLocale, newLocale); } catch (UnsupportedLocaleException exception) { Log.log_3308(currentLocale, newLocale); return false; } } // No property defines the locale, use the default } else { LogCentral.useDefaultLocale(); } return true; } /** * Configures the log filter using the runtime properties. * * @return * <code>false</code> if there was an error, * <code>true</code> if all was OK. */ boolean determineLogFilter() { // If we have no runtime properties, then skip this altogether if (_runtimeProperties == null) { return true; } // Get the name of the filter class to use String s = _runtimeProperties.get(LogCentral.LOG_FILTER_PROPERTY); // Runtime property is not set, also skip if (isEmpty(s)) { return true; } // Property is set, use this log filter class LogCentral.setLogFilterByClass(s); // Check return s.equals(LogCentral.getLogFilter().getClass().getName()); } /** * Indicates whether the runtime property file was read successfully. * * @return * <code>true</code> if the runtime properties are loaded correctly, * <code>false</code> otherwise. */ boolean propertiesRead() { return _propertiesRead; } /** * Stops the config file watcher thread. */ void destroy() { // Stop the FileWatcher if (_configFileWatcher != null) { try { _configFileWatcher.end(); } catch (Throwable exception) { Utils.logIgnoredException(exception); } _configFileWatcher = null; } } private final class ConfigurationFileListener implements FileWatcher.Listener { /** * Constructs a new <code>ConfigurationFileListener</code> object. */ private ConfigurationFileListener() { // empty } /** * Re-initializes the framework. The run-time properties are re-read, * the configuration file reload interval is determined, the API is * re-initialized and then the new interval is applied to the watch * thread for the configuration file. */ private void reinit() { if (_configFile != null) { Log.log_3407(_configFile); } else { Log.log_3407("/WEB-INF/xins.properties"); } long startTimeInitialization = System.currentTimeMillis(); boolean reinitialized; synchronized (RUNTIME_PROPERTIES_LOCK) { // Apply the new runtime settings to the logging subsystem readRuntimeProperties(); // Re-initialize the API reinitialized = _engine.initAPI(); // Update the file watch interval if needed updateFileWatcher(); } // API re-initialized successfully, so log each unused property... if (reinitialized) { logUnusedRuntimeProperties(); // ...and log that the framework was reinitialized int duration = (int) (System.currentTimeMillis() - startTimeInitialization); Log.log_3415(duration); } } /** * Updates the file watch interval and initializes the file watcher if * needed. */ private void updateFileWatcher() { if (_configFileWatcher == null) { return; } // Determine the interval int newInterval; try { newInterval = determineConfigReloadInterval(); } catch (InvalidPropertyValueException exception) { // Logging is already done in determineConfigReloadInterval() return; } // Update the file watch interval int oldInterval = _configFileWatcher.getInterval(); if (oldInterval != newInterval) { if (newInterval == 0 && _configFileWatcher != null) { _configFileWatcher.end(); _configFileWatcher = null; } else if (newInterval > 0 && _configFileWatcher == null) { if (_configFile.startsWith("http: _configFileWatcher = new HTTPFileWatcher(_configFiles, newInterval, _configFileListener); } else { _configFileWatcher = new FileWatcher(_configFiles, newInterval, _configFileListener); } _configFileWatcher.start(); } else { _configFileWatcher.setInterval(newInterval); Log.log_3403(_configFilesPath, oldInterval, newInterval); } } } /** * Callback method called when the configuration file is found while it * was previously not found. * * <p>This will trigger re-initialization. */ public void fileFound() { reinit(); } /** * Callback method called when the configuration file is (still) not * found. * * <p>The implementation of this method does not perform any actions. */ public void fileNotFound() { Log.log_3400(_configFilesPath); } /** * Callback method called when the configuration file is (still) not * modified. * * <p>The implementation of this method does not perform any actions. */ public void fileNotModified() { } /** * Callback method called when the configuration file could not be * examined due to a <code>SecurityException</code>. * * <p>The implementation of this method does not perform any actions. * * @param exception * the caught security exception, should not be <code>null</code> * (although this is not checked). */ public void securityException(SecurityException exception) { Log.log_3401(exception, _configFilesPath); } /** * Callback method called when the configuration file is modified since * the last time it was checked. * * <p>This will trigger re-initialization. */ public void fileModified() { reinit(); } } }
package com.mauter.httpserver; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.Charset; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This simple HTTP server is intended to be embedded in unit tests. * It sports very few dependencies so your classpath isn't cluttered * just so you can exercise a few HTTP calls. Start the server with * a try-with-resources statement. Before you exit the try, inspect * the requests and responses to verify that your code works. */ public class HTTPServer implements Runnable, Closeable { private static final Logger log = LoggerFactory.getLogger( HTTPServer.class ); static final Charset UTF8 = Charset.forName( "UTF-8" ); Thread thread; ServerSocket serverSocket; boolean isRunning = true; int port = 0; List<HTTPRequest> requests = new ArrayList<>(); List<HTTPResponse> responses = new ArrayList<>(); HTTPRequestHandler handler; /** * Gets the port number bound by the listening socket. The default * is 0 so that the socket will find an open port automatically. After * the socket acquires the port, this value will be updated with the * actual port number used. * * @return the port number */ public int getPort() { return this.port; } /** * Sets the port number to be bound by the listening socket. Passing * in 0 here causes the socket to find an open port automatically. * * @param port the port number to use */ public void setPort( int port ) { this.port = port; } /** * Gets the list of requests that have been made since startup * or the last call to {@linkplain #reset()}. * * @return the List of HTTPRequest objects */ public List<HTTPRequest> getRequests() { return this.requests; } /** * Gets the list of responses that have been returned since startup * or the last call to {@linkplain #reset()}. * * @return the List of HTTPResponse objects */ public List<HTTPResponse> getResponses() { return this.responses; } /** * Gets the request handler used by the server to handle requests. * * @return the HTTPRequestHandler that handles all requests to this server */ public HTTPRequestHandler getHTTPRequestHandler() { return this.handler; } /** * Sets the request handler used by the server to handle requests. * * @param handler the HTTPRequestHandler used to handle all requests to this server */ public void setHTTPRequestHandler( HTTPRequestHandler handler ) { this.handler = handler; } /** * Creates and starts a server that always returns a 200 OK response no * matter the request. * * @return a new HTTPServer that's already started and listening for requests * @throws IOException if an I/O error occurs when opening the socket */ public static HTTPServer always200OK() throws IOException { HTTPServer server = new HTTPServer(); server.setHTTPRequestHandler( new HTTPRequestHandler() { @Override public void handleRequest( HTTPRequest request, HTTPResponse response ) throws IOException { response.setStatus( 200 ); response.setStatusMessage( "OK" ); } } ); server.start(); return server; } /** * Creates and starts a server that serves files out of the given root directory. * * @return a new HTTPServer that's already started and listening for requests * @throws IOException if an I/O error occurs when opening the socket */ public static HTTPServer simpleServer( final File root ) throws IOException { if ( root == null ) throw new NullPointerException( "Root directory cannot be null." ); if ( !root.exists() ) throw new IOException( "Root directory does not exist." ); if ( !root.isDirectory() ) throw new IOException( "Root must be a directory." ); final HTTPServer server = new HTTPServer(); server.setHTTPRequestHandler( new HTTPRequestHandler() { @Override public void handleRequest( HTTPRequest request, HTTPResponse response ) throws IOException { String path = request.getPath(); if ( "/".equals( path ) ) path = "index.html"; response.setHeader( "Server", server.getClass().getSimpleName() + "/" + server.getClass().getPackage().getImplementationVersion() ); File file = new File( root, path ); if ( !file.exists() ) { response.setStatus( 404 ); response.setStatusMessage( "Not Found" ); return; } try ( FileInputStream fis = new FileInputStream( file ) ) { ByteArrayOutputStream body = new ByteArrayOutputStream(); byte[] buffer = new byte[ 1024 ]; int c; while( ( c = fis.read( buffer, 0, buffer.length ) ) > 0 ) { body.write( buffer, 0, c ); } response.setStatus( 200 ); response.setStatusMessage( "OK" ); response.setHeader( "Content-Type", "application/octet-stream" ); response.setBody( body.toByteArray() ); } } } ); server.start(); return server; } /** * Starts the server if not already running. During this call * the socket is created and bound to the port. If the default * port of 0 is used, the socket will find an open port, bind * to it and report it back to the server's port variable. * * @throws IOException if an I/O error occurs when opening the socket */ public void start() throws IOException { if ( isRunning ) return; isRunning = true; reset(); serverSocket = new ServerSocket( this.port ); this.port = serverSocket.getLocalPort(); log.info( "bound to port {}", this.port ); thread = new Thread( this, "HTTPServerThread" ); thread.start(); } /** * Clears the stored requests and responses. */ public void reset() { requests.clear(); responses.clear(); } /** * Stops the server and closes the socket. */ public void stop() { if ( !isRunning ) return; isRunning = false; try { serverSocket.close(); serverSocket = null; } catch ( IOException ioe ) { log.error( "Unable to close server socket.", ioe ); } try { thread.join( 1000 ); thread = null; } catch ( InterruptedException ie ) { log.error( "Interrupted when waiting for server to stop.", ie ); } } /** * Stops the server and closes the socket. * @see #stop() */ public void close() { stop(); } /** * Listens for client connections, reads input and writes output. * This method is what calls {@linkplain HTTPRequestHandler#handleRequest(HTTPRequest, HTTPResponse)}. */ @Override public void run() { while ( isRunning ) { try ( Socket socket = serverSocket.accept(); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream() ) { log.debug( "socket={}, is={}, os={}", socket, is, os ); HTTPRequest request = new HTTPRequest(); this.requests.add( request ); HTTPResponse response = new HTTPResponse(); this.responses.add( response ); read( is, request ); this.handler.handleRequest( request, response ); write( os, response ); } catch ( IOException ioe ) { // only log the exception if we're running. closing the serverSocket // always throws an exception, so ignore that. if ( isRunning ) log.error( "Unable to process request.", ioe ); } } } /** * Reads the given InputStream into the request. * * @param is the InputStream to read * @param request the HTTPRequest to modify * @throws IOException If an I/O error occurs */ static void read( InputStream is, HTTPRequest request ) throws IOException { BufferedInputStream bis = new BufferedInputStream( is ); // read the first line containing method, path and version String line = readLine( bis ); log.debug( "line={}", line ); if ( line == null ) throw new IOException( "Invalid HTTP request." ); StringTokenizer st = new StringTokenizer( line, " " ); if ( st.countTokens() < 3 ) throw new IOException( "Invalid HTTP request." ); request.setMethod( st.nextToken() ); request.setPath( st.nextToken() ); request.setVersion( st.nextToken() ); // read the headers while ( ( line = readLine( bis ) ) != null ) { log.debug( "line={}", line ); if ( "".equals( line ) ) break; int pos = line.indexOf( ": " ); if ( pos < 0 ) continue; request.setHeader( line.substring( 0, pos ), line.substring( pos + ": ".length() ) ); } // read the body of the request String sContentLength = request.getHeader( "Content-length" ); if ( sContentLength != null && !sContentLength.isEmpty() ) { int contentLength = Integer.parseInt( sContentLength ); if ( contentLength > 0 ) { byte[] body = new byte[ contentLength ]; bis.read( body, 0, contentLength ); request.setBody( body ); log.debug( "body={}", request.getBody() ); } } } static String readLine( BufferedInputStream bis ) throws IOException { ByteArrayOutputStream line = new ByteArrayOutputStream(); int b; while( ( b = bis.read() ) >= 0 ) { if ( b == '\n' || b == '\r' ) { // check for two character line endings (LF vs CRLF) bis.mark( 0 ); int b2 = bis.read(); // do we want to keep the second character? // keep it if it's the same line ending character as the first character // or if it's different, only if it's not another line ending character if ( b == b2 || ( b2 != '\n' && b2 != '\r' ) ) { bis.reset(); } break; } else { line.write( b ); } } return line.toString( UTF8.name() ); } /** * Writes the response out to the given OutputStream. * * @param os the OutputStream to write to * @param response the HTTPResponse to write * @throws IOException if an I/O error occurs */ static void write( OutputStream os, HTTPResponse response ) throws IOException { os.write( MessageFormat.format( "HTTP/1.0 {0} {1}\n", response.getStatus(), response.getStatusMessage() ).getBytes( UTF8 ) ); Map<String, String> headers = response.getHeaders(); if ( headers != null ) { for ( Entry<String, String> header : headers.entrySet() ) { os.write( MessageFormat.format( "{0}: {1}", header.getKey(), header.getValue() ).getBytes( UTF8 ) ); } } byte[] body = response.getBody(); if ( body != null ) { os.write( "\n".getBytes( UTF8 ) ); os.write( body ); } os.flush(); } }
package com.metaweb.gridworks.model; import java.io.Serializable; import java.io.Writer; import java.util.Calendar; import java.util.Date; import java.util.Properties; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONWriter; import com.metaweb.gridworks.Jsonizable; import com.metaweb.gridworks.expr.EvalError; import com.metaweb.gridworks.expr.ExpressionUtils; import com.metaweb.gridworks.expr.HasFields; import com.metaweb.gridworks.util.ParsingUtilities; public class Cell implements Serializable, HasFields, Jsonizable { private static final long serialVersionUID = -5891067829205458102L; final public Serializable value; final public Recon recon; public Cell(Serializable value, Recon recon) { this.value = value; this.recon = recon; } public Object getField(String name, Properties bindings) { if ("value".equals(name)) { return value; } else if ("recon".equals(name)) { return recon; } return null; } public void write(JSONWriter writer, Properties options) throws JSONException { writer.object(); if (ExpressionUtils.isError(value)) { writer.key("e"); writer.value(((EvalError) value).message); } else { writer.key("v"); if (value != null) { if (value instanceof Calendar) { writer.value(ParsingUtilities.dateToString(((Calendar) value).getTime())); writer.key("t"); writer.value("date"); } else if (value instanceof Date) { writer.value(ParsingUtilities.dateToString((Date) value)); writer.key("t"); writer.value("date"); } else { writer.value(value); } } else { writer.value(null); } } if (recon != null) { writer.key("r"); recon.write(writer, options); } writer.endObject(); } public void save(Writer writer, Properties options) { JSONWriter jsonWriter = new JSONWriter(writer); try { write(jsonWriter, options); } catch (JSONException e) { e.printStackTrace(); } } static public Cell load(String s) throws Exception { return s.length() == 0 ? null : load(ParsingUtilities.evaluateJsonStringToObject(s)); } static public Cell load(JSONObject obj) throws Exception { Serializable value = null; Recon recon = null; if (obj.has("e")) { value = new EvalError(obj.getString("e")); } else if (obj.has("v") && !obj.isNull("v")) { value = (Serializable) obj.get("v"); if (obj.has("t") && !obj.isNull("t")) { String type = obj.getString("t"); if ("date".equals(type)) { value = ParsingUtilities.stringToDate((String) value); } } } if (obj.has("r") && !obj.isNull("r")) { recon = Recon.load(obj.getJSONObject("r")); } return new Cell(value, recon); } }
package com.mongodb.dibs; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.dibs.model.Order; import io.dropwizard.Application; import io.dropwizard.assets.AssetsBundle; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import io.dropwizard.views.ViewBundle; import org.eclipse.jetty.server.session.SessionHandler; import org.joda.time.DateTime; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.Morphia; public class DibsApplication extends Application<DibsConfiguration> { private MongoClient mongo; private Morphia morphia; @Override public void initialize(final Bootstrap<DibsConfiguration> bootstrap) { bootstrap.addBundle(new ViewBundle()); bootstrap.addBundle(new AssetsBundle("/assets", "/assets", null, "assets")); bootstrap.addBundle(new AssetsBundle("/META-INF/resources/webjars", "/webjars", null, "webjars")); } @Override public void run(final DibsConfiguration configuration, final Environment environment) throws Exception { morphia = new Morphia(); morphia.mapPackage(Order.class.getPackage().getName()); mongo = new MongoClient(); environment.getApplicationContext().setSessionsEnabled(true); environment.getApplicationContext().setSessionHandler(new SessionHandler()); environment.healthChecks().register("dibs", new DibsHealthCheck()); Datastore datastore = morphia.createDatastore(mongo, "mongo-dibs"); datastore.ensureIndexes(); environment.jersey().register(new DibsResource(datastore)); String testdata = System.getProperty("testdata"); if (testdata != null) { System.out.println("*** Generating test data ***"); datastore.getCollection(Order.class).remove(new BasicDBObject()); for (int i = 0; i < 100; i++) { createTestOrder(datastore, i, "Vendor " + (i % 5), true); } for (int i = 0; i < 10; i++) { createTestOrder(datastore, i, "Awesome Vendor " + i, false); } } } private void createTestOrder(final Datastore ds, final int count, final String vendor, final boolean group) { Order order = new Order(); order.setVendor(vendor); order.setGroup(group); order.setExpectedAt(DateTime.now().withTime(11, 45, 0, 0).toDate()); order.setContents("yum " + count); order.setOrderedBy("Employee " + count); ds.save(order); } public static void main(String[] args) throws Exception { new DibsApplication().run(args); } }
package com.squareup.protoparser; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public final class Service { private final String name; private final String fqname; private final String documentation; private final List<Method> methods; public Service(String name, String fqname, String documentation, List<Method> methods) { if (name == null) throw new NullPointerException("name"); if (fqname == null) throw new NullPointerException("fqname"); if (documentation == null) throw new NullPointerException("documentation"); if (methods == null) throw new NullPointerException("methods"); this.name = name; this.fqname = fqname; this.documentation = documentation; this.methods = Collections.unmodifiableList(new ArrayList<Method>(methods)); } public String getName() { return name; } public String getFullyQualifiedName() { return fqname; } public String getDocumentation() { return documentation; } public List<Method> getMethods() { return methods; } @Override public boolean equals(Object other) { if (other instanceof Service) { Service that = (Service) other; return name.equals(that.name) && documentation.equals(that.documentation) && methods.equals(that.methods); } return false; } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append(name); for (Method method : methods) { result.append("\n ").append(method); } return result.toString(); } public static final class Method { private final String name; private final String documentation; private final String requestType; private final String responseType; private final Map<String, Object> options; public Method(String name, String documentation, String requestType, String responseType, Map<String, Object> options) { if (name == null) throw new NullPointerException("name"); if (documentation == null) throw new NullPointerException("documentation"); if (requestType == null) throw new NullPointerException("requestType"); if (responseType == null) throw new NullPointerException("responseType"); if (options == null) throw new NullPointerException("options"); this.name = name; this.documentation = documentation; this.requestType = requestType; this.responseType = responseType; this.options = Collections.unmodifiableMap(new LinkedHashMap<String, Object>(options)); } public String getName() { return name; } public String getDocumentation() { return documentation; } public String getRequestType() { return requestType; } public String getResponseType() { return responseType; } public Map<String, Object> getOptions() { return options; } @Override public boolean equals(Object other) { if (other instanceof Method) { Method that = (Method) other; return name.equals(that.name) && documentation.equals(that.documentation) && requestType.equals(that.requestType) && responseType.equals(that.responseType) && options.equals(that.options); } return false; } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return String.format("rpc %s (%s) returns (%s) %s", name, requestType, responseType, options); } } }
package krasa.mavenhelper.analyzer; import com.intellij.ide.CommonActionsManager; import com.intellij.ide.DefaultTreeExpander; import com.intellij.ide.util.PropertiesComponent; import com.intellij.notification.Notification; import com.intellij.notification.NotificationListener; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.actionSystem.ActionToolbar; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.BuildNumber; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.*; import com.intellij.ui.components.JBList; import com.intellij.util.text.VersionComparatorUtil; import krasa.mavenhelper.ApplicationComponent; import krasa.mavenhelper.analyzer.action.LeftTreePopupHandler; import krasa.mavenhelper.analyzer.action.RightTreePopupHandler; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.maven.model.MavenArtifact; import org.jetbrains.idea.maven.model.MavenArtifactNode; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.server.MavenServerManager; import javax.swing.*; import javax.swing.event.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.lang.reflect.Method; import java.util.*; import java.util.List; /** * @author Vojtech Krasa */ public class GuiForm { private static final Logger LOG = Logger.getInstance("#krasa.mavenrun.analyzer.GuiForm"); public static final String WARNING = "Your settings indicates, that conflicts will not be visible, see IDEA-133331\n" + "If your project is Maven2 compatible, you could try one of the following:\n" + "-use IJ 2016.1+ and configure it to use external Maven 3.1.1+ (File | Settings | Build, Execution, Deployment | Build Tools | Maven | Maven home directory)\n" + "-press Apply Fix button to alter Maven VM options for importer (might cause trouble for IJ 2016.1+)\n" + "-turn off File | Settings | Build, Execution, Deployment | Build Tools | Maven | Importing | Use Maven3 to import project setting\n"; protected static final Comparator<MavenArtifactNode> BY_ARTIFACT_ID = new Comparator<MavenArtifactNode>() { @Override public int compare(MavenArtifactNode o1, MavenArtifactNode o2) { return o1.getArtifact().getArtifactId().toLowerCase().compareTo(o2.getArtifact().getArtifactId().toLowerCase()); } }; private static final String LAST_RADIO_BUTTON = "MavenHelper.lastRadioButton"; private final Project project; private final VirtualFile file; private MavenProject mavenProject; private JBList leftPanelList; private JTree rightTree; private JPanel rootPanel; private JRadioButton conflictsRadioButton; private JRadioButton allDependenciesAsListRadioButton; private JRadioButton allDependenciesAsTreeRadioButton; private JLabel noConflictsLabel; private JScrollPane noConflictsWarningLabelScrollPane; private JTextPane noConflictsWarningLabel; private JButton refreshButton; private JSplitPane splitPane; private SearchTextField searchField; private JButton applyMavenVmOptionsFixButton; private JPanel leftPanelWrapper; private JTree leftTree; private JCheckBox showGroupId; private JPanel buttonsPanel; protected DefaultListModel listDataModel; protected Map<String, List<MavenArtifactNode>> allArtifactsMap; protected final DefaultTreeModel rightTreeModel; protected final DefaultTreeModel leftTreeModel; protected final DefaultMutableTreeNode rightTreeRoot; protected final DefaultMutableTreeNode leftTreeRoot; protected ListSpeedSearch myListSpeedSearch; protected List<MavenArtifactNode> dependencyTree; protected CardLayout leftPanelLayout; private boolean notificationShown; private final SimpleTextAttributes errorBoldAttributes; public GuiForm(final Project project, VirtualFile file, final MavenProject mavenProject) { this.project = project; this.file = file; this.mavenProject = mavenProject; final ActionListener radioButtonListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateLeftPanel(); String value = null; if (allDependenciesAsListRadioButton.isSelected()) { value = "list"; } else if (allDependenciesAsTreeRadioButton.isSelected()) { value = "tree"; } PropertiesComponent.getInstance().setValue(LAST_RADIO_BUTTON, value); } }; conflictsRadioButton.addActionListener(radioButtonListener); allDependenciesAsListRadioButton.addActionListener(radioButtonListener); allDependenciesAsTreeRadioButton.addActionListener(radioButtonListener); refreshButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { initializeModel(); rootPanel.requestFocus(); } }); myListSpeedSearch = new ListSpeedSearch(leftPanelList); searchField.addDocumentListener(new DocumentAdapter() { @Override protected void textChanged(DocumentEvent documentEvent) { updateLeftPanel(); } }); try { Method searchField = this.searchField.getClass().getMethod("getTextEditor"); JTextField invoke = (JTextField) searchField.invoke(this.searchField); invoke.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { if (GuiForm.this.searchField.getText() != null) { GuiForm.this.searchField.addCurrentTextToHistory(); } } }); } catch (Exception e) { throw new RuntimeException(e); } noConflictsWarningLabel.setBackground(null); applyMavenVmOptionsFixButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String mavenEmbedderVMOptions = MavenServerManager.getInstance().getMavenEmbedderVMOptions(); int baselineVersion = ApplicationInfoEx.getInstanceEx().getBuild().getBaselineVersion(); if (baselineVersion >= 140) { mavenEmbedderVMOptions += " -Didea.maven3.use.compat.resolver"; } else { mavenEmbedderVMOptions += " -Dmaven3.use.compat.resolver"; } MavenServerManager.getInstance().setMavenEmbedderVMOptions(mavenEmbedderVMOptions); final MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(project); projectsManager.forceUpdateAllProjectsOrFindAllAvailablePomFiles(); refreshButton.getActionListeners()[0].actionPerformed(e); } }); noConflictsWarningLabel.setText(WARNING); leftPanelLayout = (CardLayout) leftPanelWrapper.getLayout(); rightTreeRoot = new DefaultMutableTreeNode(); rightTreeModel = new DefaultTreeModel(rightTreeRoot); rightTree.setModel(rightTreeModel); rightTree.setRootVisible(false); rightTree.setShowsRootHandles(true); rightTree.expandPath(new TreePath(rightTreeRoot.getPath())); rightTree.setCellRenderer(new TreeRenderer(showGroupId)); rightTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); rightTree.addMouseListener(new RightTreePopupHandler(project, mavenProject, rightTree)); leftTree.addTreeSelectionListener(new LeftTreeSelectionListener()); leftTreeRoot = new DefaultMutableTreeNode(); leftTreeModel = new DefaultTreeModel(leftTreeRoot); leftTree.setModel(leftTreeModel); leftTree.setRootVisible(false); leftTree.setShowsRootHandles(true); leftTree.expandPath(new TreePath(leftTreeRoot.getPath())); leftTree.setCellRenderer(new TreeRenderer(showGroupId)); leftTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); leftTree.addMouseListener(new LeftTreePopupHandler(project, mavenProject, leftTree)); showGroupId.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { leftPanelList.repaint(); TreeUtils.nodesChanged(GuiForm.this.rightTreeModel); TreeUtils.nodesChanged(GuiForm.this.leftTreeModel); } }); final DefaultTreeExpander treeExpander = new DefaultTreeExpander(leftTree); DefaultActionGroup actionGroup = new DefaultActionGroup(); actionGroup.add(CommonActionsManager.getInstance().createExpandAllAction(treeExpander, leftTree)); actionGroup.add(CommonActionsManager.getInstance().createCollapseAllAction(treeExpander, leftTree)); ActionToolbar actionToolbar = ActionManagerEx.getInstance().createActionToolbar("krasa.MavenHelper.buttons", actionGroup, true); buttonsPanel.add(actionToolbar.getComponent(), "1"); errorBoldAttributes = new SimpleTextAttributes(SimpleTextAttributes.STYLE_BOLD, SimpleTextAttributes.ERROR_ATTRIBUTES.getFgColor()); String lastRadioButton = PropertiesComponent.getInstance().getValue(LAST_RADIO_BUTTON); if ("tree".equals(lastRadioButton)) { allDependenciesAsTreeRadioButton.setSelected(true); } else if ("list".equals(lastRadioButton)) { allDependenciesAsListRadioButton.setSelected(true); } else { conflictsRadioButton.setSelected(true); } } private void createUIComponents() { listDataModel = new DefaultListModel(); leftPanelList = new JBList(listDataModel); leftPanelList.addListSelectionListener(new MyListSelectionListener()); // no generics in IJ12 leftPanelList.setCellRenderer(new ColoredListCellRenderer() { @Override protected void customizeCellRenderer(JList jList, Object o, int i, boolean b, boolean b2) { MyListNode value = (MyListNode) o; String rightVersion = value.getRightVersion(); final String[] split = value.key.split(":"); boolean conflict = value.isConflict(); SimpleTextAttributes attributes = SimpleTextAttributes.REGULAR_ATTRIBUTES; SimpleTextAttributes boldAttributes = SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES; if (conflict && allDependenciesAsListRadioButton.isSelected()) { attributes = SimpleTextAttributes.ERROR_ATTRIBUTES; boldAttributes = errorBoldAttributes; } if (showGroupId.isSelected()) { append(split[0] + " : ", attributes); } append(split[1], boldAttributes); append(" : " + rightVersion, attributes); } }); rightTree = new MyHighlightingTree(project, mavenProject); leftTree = new MyHighlightingTree(project, mavenProject); } public static String sortByVersion(List<MavenArtifactNode> value) { Collections.sort(value, new Comparator<MavenArtifactNode>() { @Override public int compare(MavenArtifactNode o1, MavenArtifactNode o2) { DefaultArtifactVersion version = new DefaultArtifactVersion(o1.getArtifact().getVersion()); DefaultArtifactVersion version1 = new DefaultArtifactVersion(o2.getArtifact().getVersion()); return version1.compareTo(version); } }); return value.get(0).getArtifact().getVersion(); } private class LeftTreeSelectionListener implements TreeSelectionListener { @Override public void valueChanged(TreeSelectionEvent e) { TreePath selectionPath = e.getPath(); if (selectionPath != null) { DefaultMutableTreeNode lastPathComponent = (DefaultMutableTreeNode) selectionPath.getLastPathComponent(); MyTreeUserObject userObject = (MyTreeUserObject) lastPathComponent.getUserObject(); final String key = getArtifactKey(userObject.getArtifact()); List<MavenArtifactNode> mavenArtifactNodes = allArtifactsMap.get(key); if (mavenArtifactNodes != null) {// can be null while refreshing fillRightTree(mavenArtifactNodes, sortByVersion(mavenArtifactNodes)); } } } } private class MyListSelectionListener implements ListSelectionListener { @Override public void valueChanged(ListSelectionEvent e) { if (listDataModel.isEmpty() || leftPanelList.getSelectedValue() == null) { return; } final MyListNode myListNode = (MyListNode) leftPanelList.getSelectedValue(); List<MavenArtifactNode> artifacts = myListNode.value; fillRightTree(artifacts, myListNode.getRightVersion()); } } private void fillRightTree(List<MavenArtifactNode> mavenArtifactNodes, String rightVersion) { rightTreeRoot.removeAllChildren(); for (MavenArtifactNode mavenArtifactNode : mavenArtifactNodes) { MyTreeUserObject userObject = MyTreeUserObject.create(mavenArtifactNode, rightVersion); userObject.showOnlyVersion = true; final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(userObject); fillRightTree(mavenArtifactNode, newNode); rightTreeRoot.add(newNode); } rightTreeModel.nodeStructureChanged(rightTreeRoot); TreeUtils.expandAll(rightTree); } private void fillRightTree(MavenArtifactNode mavenArtifactNode, DefaultMutableTreeNode node) { final MavenArtifactNode parent = mavenArtifactNode.getParent(); if (parent == null) { return; } final DefaultMutableTreeNode parentDependencyNode = new DefaultMutableTreeNode(new MyTreeUserObject(parent)); node.add(parentDependencyNode); parentDependencyNode.setParent(node); fillRightTree(parent, parentDependencyNode); } private void initializeModel() { final Object selectedValue = leftPanelList.getSelectedValue(); dependencyTree = mavenProject.getDependencyTree(); allArtifactsMap = createAllArtifactsMap(dependencyTree); updateLeftPanel(); rightTreeRoot.removeAllChildren(); rightTreeModel.reload(); leftPanelWrapper.revalidate(); if (selectedValue != null) { leftPanelList.setSelectedValue(selectedValue, true); } } private void updateLeftPanel() { listDataModel.clear(); leftTreeRoot.removeAllChildren(); final String searchFieldText = searchField.getText(); boolean conflictsWarning = false; boolean showNoConflictsLabel = false; if (conflictsRadioButton.isSelected()) { for (Map.Entry<String, List<MavenArtifactNode>> s : allArtifactsMap.entrySet()) { final List<MavenArtifactNode> nodes = s.getValue(); if (nodes.size() > 1 && hasConflicts(nodes)) { if (contains(searchFieldText, s.getKey())) { listDataModel.addElement(new MyListNode(s)); } } } showNoConflictsLabel = listDataModel.isEmpty(); BuildNumber build = ApplicationInfoEx.getInstanceEx().getBuild(); int baselineVersion = build.getBaselineVersion(); MavenServerManager server = MavenServerManager.getInstance(); boolean useMaven2 = server.isUseMaven2(); boolean containsCompatResolver139 = server.getMavenEmbedderVMOptions().contains("-Dmaven3.use.compat.resolver"); boolean containsCompatResolver140 = server.getMavenEmbedderVMOptions().contains("-Didea.maven3.use.compat.resolver"); boolean newIDE = VersionComparatorUtil.compare(build.asStringWithoutProductCode(), "145.258") >= 0; boolean newMaven = VersionComparatorUtil.compare(server.getCurrentMavenVersion(), "3.1.1") >= 0; if (showNoConflictsLabel && baselineVersion >= 139) { boolean containsProperty = (baselineVersion == 139 && containsCompatResolver139) || (baselineVersion >= 140 && containsCompatResolver140); conflictsWarning = !containsProperty && !useMaven2; if (conflictsWarning && newIDE) { conflictsWarning = conflictsWarning && !newMaven; } } if (!conflictsWarning && newIDE && newMaven && containsCompatResolver140) { if (!notificationShown) { notificationShown = true; final Notification notification = ApplicationComponent.NOTIFICATION.createNotification( "Fix your Maven VM options for importer", "<html>Your settings causes problems in multi-module Maven projects.<br> " + " <a href=\"fix\">Remove -Didea.maven3.use.compat.resolver</a> ", NotificationType.WARNING, new NotificationListener() { @Override public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent hyperlinkEvent) { notification.expire(); String mavenEmbedderVMOptions = MavenServerManager.getInstance().getMavenEmbedderVMOptions(); MavenServerManager.getInstance().setMavenEmbedderVMOptions( mavenEmbedderVMOptions.replace("-Didea.maven3.use.compat.resolver", "")); final MavenProjectsManager projectsManager = MavenProjectsManager.getInstance(project); projectsManager.forceUpdateAllProjectsOrFindAllAvailablePomFiles(); } }); ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { Notifications.Bus.notify(notification, project); } }); } } leftPanelLayout.show(leftPanelWrapper, "list"); } else if (allDependenciesAsListRadioButton.isSelected()) { for (Map.Entry<String, List<MavenArtifactNode>> s : allArtifactsMap.entrySet()) { if (contains(searchFieldText, s.getKey())) { listDataModel.addElement(new MyListNode(s)); } } showNoConflictsLabel = false; leftPanelLayout.show(leftPanelWrapper, "list"); } else { // tree fillLeftTree(leftTreeRoot, dependencyTree, searchFieldText); leftTreeModel.nodeStructureChanged(leftTreeRoot); TreeUtils.expandAll(leftTree); showNoConflictsLabel = false; leftPanelLayout.show(leftPanelWrapper, "allAsTree"); } if (conflictsWarning) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { noConflictsWarningLabelScrollPane.getVerticalScrollBar().setValue(0); } }); leftPanelLayout.show(leftPanelWrapper, "noConflictsWarningLabel"); } buttonsPanel.setVisible(allDependenciesAsTreeRadioButton.isSelected()); noConflictsWarningLabelScrollPane.setVisible(conflictsWarning); applyMavenVmOptionsFixButton.setVisible(conflictsWarning); noConflictsLabel.setVisible(showNoConflictsLabel); } private boolean fillLeftTree(DefaultMutableTreeNode parent, List<MavenArtifactNode> dependencyTree, String searchFieldText) { boolean search = StringUtils.isNotBlank(searchFieldText); Collections.sort(dependencyTree, BY_ARTIFACT_ID); boolean hasAddedNodes = false; for (MavenArtifactNode mavenArtifactNode : dependencyTree) { boolean directMatch = false; MyTreeUserObject treeUserObject = new MyTreeUserObject(mavenArtifactNode, SimpleTextAttributes.REGULAR_ATTRIBUTES); if (search && contains(searchFieldText, mavenArtifactNode)) { directMatch = true; treeUserObject.highlight = true; } final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(treeUserObject); boolean childAdded = fillLeftTree(newNode, mavenArtifactNode.getDependencies(), searchFieldText); if (!search || directMatch || childAdded) { parent.add(newNode); hasAddedNodes = true; } } return hasAddedNodes; } private boolean contains(String searchFieldText, MavenArtifactNode mavenArtifactNode) { MavenArtifact artifact = mavenArtifactNode.getArtifact(); return contains(searchFieldText, getArtifactKey(artifact)); } private boolean contains(String searchFieldText, String artifactKey) { return StringUtils.isBlank(searchFieldText) || StringUtils.containsIgnoreCase(artifactKey, searchFieldText); } private boolean hasConflicts(List<MavenArtifactNode> nodes) { String version = null; for (MavenArtifactNode node : nodes) { if (version != null && !version.equals(node.getArtifact().getVersion())) { return true; } version = node.getArtifact().getVersion(); } return false; } private Map<String, List<MavenArtifactNode>> createAllArtifactsMap(List<MavenArtifactNode> dependencyTree) { final Map<String, List<MavenArtifactNode>> map = new TreeMap<String, List<MavenArtifactNode>>(); addAll(map, dependencyTree, 0); return map; } private void addAll(Map<String, List<MavenArtifactNode>> map, List<MavenArtifactNode> artifactNodes, int i) { if (map == null) { return; } if (i > 100) { final StringBuilder stringBuilder = new StringBuilder(); for (MavenArtifactNode s : artifactNodes) { final String s1 = s.getArtifact().toString(); stringBuilder.append(s1); stringBuilder.append(" "); } LOG.error("Recursion aborted, artifactNodes = [" + stringBuilder + "]"); return; } for (MavenArtifactNode mavenArtifactNode : artifactNodes) { final MavenArtifact artifact = mavenArtifactNode.getArtifact(); final String key = getArtifactKey(artifact); final List<MavenArtifactNode> mavenArtifactNodes = map.get(key); if (mavenArtifactNodes == null) { final ArrayList<MavenArtifactNode> value = new ArrayList<MavenArtifactNode>(1); value.add(mavenArtifactNode); map.put(key, value); } else { mavenArtifactNodes.add(mavenArtifactNode); } addAll(map, mavenArtifactNode.getDependencies(), i + 1); } } @NotNull private String getArtifactKey(MavenArtifact artifact) { return artifact.getGroupId() + " : " + artifact.getArtifactId(); } public JComponent getRootComponent() { return rootPanel; } public JComponent getPreferredFocusedComponent() { return rootPanel; } public void selectNotify() { if (dependencyTree == null) { initializeModel(); splitPane.setDividerLocation(0.5); } } }
package de.fzi.cjunit; import static de.fzi.cjunit.internal.util.LineSeparator.lineSeparator; import gov.nasa.jpf.Property; /** * This exception is thrown to indicate the violation of an user-supplied * property. The exception's message contains the name of the violated * property class and the property's error message. * <p> * Note: The violation of <code>NotDeadLockedProperty</code> is not reported * through this exception, but through <code>DeadlockError</code>. */ public class JPFPropertyViolated extends Error { private static final long serialVersionUID = 1L; private Property violatedProperty; /** * @param violatedProperty the property which was violated during * the test run */ public JPFPropertyViolated(Property violatedProperty) { super(new String("Property '" + violatedProperty.getClass().getName() + "' violated" + lineSeparator + violatedProperty.getErrorMessage())); this.violatedProperty = violatedProperty; } /** * @return the property which was violated during the test run */ public Property getViolatedProperty() { return violatedProperty; } }
package io.github.krymonota.rnvapi; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * Main class used for creating an api provider instance of {@link RNVAPIService}. * @since 1.0.0 * @version 1.0.1 */ public final class RNVAPI { public static final String API_BASE_URL = "http://rnv.the-agent-factory.de:8080/easygo2/api/"; /** * Creates an instance of {@link RNVAPIService}. * @param apiToken The RNV API token * @return The created instance of {@link RNVAPIService} */ public static RNVAPIService createAPIServiceProvider(final String apiToken) { final OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { final Request request = chain.request().newBuilder().addHeader("RNV_API_TOKEN", apiToken).build(); return chain.proceed(request); } }).build(); return RNVAPI.createAPIServiceProvider(apiToken, httpClient); } /** * Creates an instance of {@link RNVAPIService} with a custom {@link OkHttpClient}. * @param apiToken The RNV API token * @param httpClient An instance of {@link OkHttpClient} * @return The created instance of {@link RNVAPIService} */ public static RNVAPIService createAPIServiceProvider(final String apiToken, final OkHttpClient httpClient) { final Retrofit retrofit = new Retrofit.Builder() .client(httpClient) .baseUrl(API_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit.create(RNVAPIService.class); } private RNVAPI() { } }
package com.bitso; import java.math.BigDecimal; import org.json.JSONObject; import com.bitso.exchange.Ticker; import com.bitso.helpers.Helpers; public class BitsoAccountStatus { private String clientId; private String status; private BigDecimal dailyLimit; private BigDecimal monthlyLimit; private BigDecimal dailyRemaining; private BigDecimal monthlyRemaining; private String cellphoneNumber; private String officialId; private String proofOfResidency; private String signedContract; private String originOfFunds; private String firstName; private String lastName; private boolean isCellphoneNumberVerified; private String email; public BitsoAccountStatus(JSONObject o) { clientId = Helpers.getString(o, "client_id"); firstName = Helpers.getString(o, "first_name"); lastName = Helpers.getString(o, "last_name"); status = Helpers.getString(o, "status"); dailyLimit = Helpers.getBD(o, "daily_limit"); monthlyLimit = Helpers.getBD(o, "monthly_limit"); dailyRemaining = Helpers.getBD(o, "daily_remaining"); monthlyRemaining = Helpers.getBD(o, "monthly_remaining"); isCellphoneNumberVerified = Helpers.getString(o, "cellphone_number").equals("verified") ? true : false; officialId = Helpers.getString(o, "official_id"); proofOfResidency = Helpers.getString(o, "proof_of_residency"); signedContract = Helpers.getString(o, "signed_contract"); originOfFunds = Helpers.getString(o, "origin_of_funds"); if ((monthlyLimit.compareTo(new BigDecimal("0")) == 0) && (dailyLimit.compareTo(new BigDecimal("1000000")) == 0)) { monthlyLimit = dailyLimit.multiply(new BigDecimal("31")); } cellphoneNumber = Helpers.getString(o, "cellphone_number_stored"); email = Helpers.getString(o, "email_stored"); } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public BigDecimal getDailyLimit() { return dailyLimit; } public void setDailyLimit(BigDecimal dailyLimit) { this.dailyLimit = dailyLimit; } public BigDecimal getMonthlyLimit() { return monthlyLimit; } public void setMonthlyLimit(BigDecimal monthlyLimit) { this.monthlyLimit = monthlyLimit; } public BigDecimal getDailyRemaining() { return dailyRemaining; } public void setDailyRemaining(BigDecimal dailyRemaining) { this.dailyRemaining = dailyRemaining; } public BigDecimal getMonthlyRemaining() { return monthlyRemaining; } public void setMonthlyRemaining(BigDecimal monthlyRemaining) { this.monthlyRemaining = monthlyRemaining; } public String getCellphoneNumber() { return cellphoneNumber; } public void setCellphoneNumber(String cellphoneNumber) { this.cellphoneNumber = cellphoneNumber; } public String getOfficialId() { return officialId; } public void setOfficialId(String officialId) { this.officialId = officialId; } public String getProofOfResidency() { return proofOfResidency; } public void setProofOfResidency(String proofOfResidency) { this.proofOfResidency = proofOfResidency; } public String getSignedContract() { return signedContract; } public void setSignedContract(String signedContract) { this.signedContract = signedContract; } public String getOriginOfFunds() { return originOfFunds; } public void setOriginOfFunds(String originOfFunds) { this.originOfFunds = originOfFunds; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean isCellphoneNumberVerified() { return isCellphoneNumberVerified; } public String toString() { return Helpers.fieldPrinter(this, BitsoAccountStatus.class); } }
package com.blocklaunch.blwarps; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.Texts; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.util.command.CommandSource; public class Util { public static Text formattedTextWarp(String warpName) { Text text = Texts.builder(warpName).color(TextColors.GOLD).onClick(TextActions.runCommand("/warp " + warpName)) .onHover(TextActions.showText(Texts.of("Warp to ", TextColors.GOLD, warpName))).build(); return text; } public static boolean hasPermission(CommandSource source, Warp warp) { String warpPermission = "blwarps.warp." + warp.getName(); String groupPermissionBase = "blwarps.warp.group."; String wildCardPermission = "blwarps.warp.*"; boolean playerIsValid = false; if (source.hasPermission(warpPermission) || source.hasPermission(wildCardPermission)) { playerIsValid = true; } for (String groupName : warp.getGroups()) { String permission = groupPermissionBase + groupName; if (source.hasPermission(permission)) { playerIsValid = true; } } return playerIsValid; } }
package com.crawljax.util; import java.util.Stack; /** * Class for making presenting HTML without changing it's structure. * * @author Danny * @version $Id: PrettyHTML.java 6276 2009-12-23 15:37:09Z frank $ */ public final class PrettyHTML { private PrettyHTML() { } // private static final Logger LOGGER = // Logger.getLogger(PrettyHTML.class.getName()); /** * Pretty print HTML string. * * @param html * The HTML string. * @param strIndent * The indentation string. * @return The pretty HTML. */ public static String prettyHTML(String html, String strIndent) { String[] elements = html.split("<"); String prettyHTML = ""; int indent = 0; // preparsing for not closing elements elements = fixElements(elements); for (String element : elements) { if (!element.equals("")) { element = element.trim(); if (!element.startsWith("/")) { // open element prettyHTML += repeatString(strIndent, indent); String[] temp = element.split(">"); prettyHTML += "<" + temp[0].trim() + ">\n"; // only indent if element is not a single element (like // <img src='..' />) if (!temp[0].endsWith("/") || temp.length == 1) { if (!temp[0].startsWith("! indent++; } } // if there is text after the element, print it if (temp.length > 1 && !temp[1].trim().equals("")) { prettyHTML += repeatString(strIndent, indent); prettyHTML += temp[1].trim() + "\n"; } } else { // close element indent prettyHTML += repeatString(strIndent, indent); prettyHTML += "<" + element + "\n"; } if (element.endsWith("/>")) { indent } } } return prettyHTML; } /** * @param html * The HTML string. * @return Pretty HTML. */ public static String prettyHTML(String html) { return prettyHTML(html, "\t"); } /** * @param s * @param number * @return s repreated number of times */ private static String repeatString(String s, int number) { String ret = ""; for (int i = 0; i < number; i++) { ret += s; } return ret; } /** * @param openElement * @param closeElement * @return wheter element has a seperate closing element */ private static boolean elementsRelated(String openElement, String closeElement) { openElement = openElement.split(">")[0]; openElement = openElement.split(" ")[0]; closeElement = closeElement.split(">")[0]; return closeElement.startsWith("/" + openElement); } /** * @param stack * @param element * @return whether the element is open */ private static boolean elementIsOpen(Stack<String> stack, String element) { for (int i = stack.size() - 1; i >= 0; i if (elementsRelated(stack.get(i), element)) { return true; } } return false; } /** * @param element * @return wheter the element is a single element (<foo ... />) */ private static boolean isSingleElement(String element) { return element.indexOf("/>") != -1; } /** * @param elements * @return list with elements with added closing elements if needed */ private static String[] fixElements(String[] elements) { Stack<String> stackElements = new Stack<String>(); Stack<Integer> stackIndexElements = new Stack<Integer>(); for (int i = 0; i < elements.length; i++) { elements[i] = elements[i].trim(); String element = elements[i]; if (!element.equals("") && !element.startsWith("!--") && !element.endsWith("-->")) { while (stackElements.size() > 0 && element.startsWith("/") && !elementsRelated(stackElements.peek(), element)) { // found a close element which is not on top of stack, // thus fix if (elementIsOpen(stackElements, element)) { // the element is open --> close element on top of // stack int index = stackIndexElements.peek(); if (!isSingleElement(elements[index])) { // close this element if (elements[index].lastIndexOf(">") != -1) { elements[index] = elements[index].substring(0, elements[index] .lastIndexOf(">")) + "/" + elements[index].substring(elements[index] .lastIndexOf(">")); } } stackElements.pop(); stackIndexElements.pop(); } else { // element is closing element while element is not // open--> remove. elements[i] = ""; element = ""; break; } } if (!element.equals("")) { // open element if (!element.startsWith("/")) { // only add to stack if has an open and close element if (!isSingleElement(element)) { stackElements.push(element); stackIndexElements.push(i); } } else { // close element, pop from stack if possible if (stackElements.size() > 0) { stackElements.pop(); stackIndexElements.pop(); } } } } } return elements; } // /** // * @param args // * Arguments of main method. // */ // public static void main(String[] args) { // String html = "<a><fout></b><!-- comment --></c><c class='foo'>aap<img />jee</c></a>"; // System.out.println(prettyHTML(html)); }
// @author A0112725N package com.epictodo.logic; import com.epictodo.controller.json.Storage; import com.epictodo.model.*; import com.epictodo.util.TaskDueDateComparator; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; public class CRUDLogic { /* * Message Constants */ private static final String MSG_CANT_REMOVE_TASK = "can't remove task"; private static final String MSG_POSTFIX_AS_DONE = "\" as done"; private static final String MSG_FAILED_TO_MARK_TASK = "failed to mark task \""; public static final String MSG_NO_MORE_ACTIONS_TO_BE_REDONE = "no more actions to be redone"; public static final String MSG_NO_MORE_ACTIONS_TO_BE_UNDONE = "no more actions to be undone"; private static final String MSG_POSTFIX_IS_REMOVED = "\" is removed"; private static final String MSG_POSTFIX_IS_UPDATED = "\" is updated"; private static final String MSG_POSTFIX_MARKED_AS_DONE = "\" is marked as done"; private static final String MSG_ERROR = "error!"; private static final String MSG_POSTFIX_IS_ADDED = "\" is added"; private static final String MSG_PREFIX_TASK = "task \""; private static final String MSG_FAILED_IO_ERROR = "failed due to file io error"; private static final String MSG_INVALID_INPUT = "invalid input"; private static final String MSG_ILLEGAL_PRIORITY = "illegal priority"; private static final String MSG_KEYWORD_MUST_NOT_BE_NULL = "keyword must not be <null>"; /* * Constants */ private static final String STRING_LINE_BREAK = "\r\n"; private static final String PATH_DATA_FILE = "storage.txt"; private static final int CONFIG_PRIORITY_MIN = 1; private static final int CONFIG_PRIORITY_MAX = 3; /* * Private Attributes */ private long _nextUid; // to track the next available uid for new Task private ArrayList<Task> _items; // to store all tasks private ArrayList<Command> _undoList; // to store undoable commands private ArrayList<Command> _redoList; // to store undone items private ArrayList<Task> _workingList; // to store previously displayed list /* * Constructor */ public CRUDLogic() { _nextUid = 1; _items = new ArrayList<Task>(); _undoList = new ArrayList<Command>(); _redoList = new ArrayList<Command>(); _workingList = new ArrayList<Task>(); } /* * CRUD Methods */ /** * This method returns the whole list of Tasks regardless of their status * * @return the ArrayList containing all the tasks * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getAllTasks() { /* * the return should only deliver a duplicate of the objects */ ArrayList<Task> retList = new ArrayList<Task>(); for (int i = 0; i < _items.size(); i++) { retList.add(_items.get(i).copy()); } updateWorkingList(retList); // update the working list return retList; } /** * This method returns the whole list of incomplete tasks * * @return the ArrayList containing all the tasks * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getIncompleteTasks() { /* * the return should only deliver a duplicate of the objects */ ArrayList<Task> resultList = new ArrayList<Task>(); for (int i = 0; i < _items.size(); i++) { if (!_items.get(i).getIsDone()) resultList.add(_items.get(i).copy()); } updateWorkingList(resultList); // update the working list return resultList; } /** * This method returns tasks based on whether it has been marked as done * * @return the ArrayList containing selected tasks * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getTasksByName(String keyword) { ArrayList<Task> resultList = new ArrayList<Task>(); /* * Exception handling to make sure param is not null */ if (keyword == null) { throw new NullPointerException(MSG_KEYWORD_MUST_NOT_BE_NULL); } for (int i = 0; i < size(); i++) { if (_items.get(i).getTaskName().toLowerCase() .contains(keyword.trim().toLowerCase()) && !_items.get(i).getIsDone()) { resultList.add(_items.get(i).copy()); } } updateWorkingList(resultList); // update the working list return resultList; } /** * This method returns tasks based on whether it has been marked as done * * @return the ArrayList containing selected tasks * @param boolean when true = Marked as done * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getTasksByStatus(boolean done) throws ParseException, InvalidDateException, InvalidTimeException { ArrayList<Task> resultList = new ArrayList<Task>(); for (int i = 0; i < size(); i++) { if (_items.get(i).getIsDone() == done) { resultList.add(_items.get(i).copy()); } } updateWorkingList(resultList); // update the working list return resultList; } /** * This method returns a list of tasks based on the priority set * * @param p * the priority enum * @return the ArrayList containing the selected tasks * @throws InvalidTimeException * @throws InvalidDateException * @throws ParseException */ public ArrayList<Task> getTasksByPriority(int p) throws IllegalArgumentException, ParseException, InvalidDateException, InvalidTimeException { ArrayList<Task> resultList = new ArrayList<Task>(); /* * Exception handling to make sure the priority is within valid range */ if (p < CONFIG_PRIORITY_MIN || p > CONFIG_PRIORITY_MAX) { throw new IllegalArgumentException(MSG_ILLEGAL_PRIORITY); } for (int i = 0; i < size(); i++) { if (_items.get(i).getPriority() == p && !_items.get(i).getIsDone()) { resultList.add(_items.get(i).copy()); } } updateWorkingList(resultList); // update the working list return resultList; } public ArrayList<Task> getTasksOrderedByDueDate() throws IllegalArgumentException, ParseException, InvalidDateException, InvalidTimeException { ArrayList<Task> resultList = new ArrayList<Task>(); ArrayList<Task> temp = new ArrayList<Task>(); for (int i = 0; i < size(); i++) { if (_items.get(i) instanceof FloatingTask) { // Add floating tasks to list first resultList.add(_items.get(i).copy()); } else { // Dump all other tasks into a temp list temp.add(_items.get(i).copy()); } } // sort the temp list Collections.sort(temp, new TaskDueDateComparator()); // add the ordered temp list to the final list resultList.addAll(temp); updateWorkingList(resultList); // update the working list return resultList; } /** * This method retrieves a list of tasks based on a specific due date * (starting date) * * @param compareDate * due date in the ddmmyy format * @return the list of tasks */ public ArrayList<Task> getTasksByDate(String compareDate) { ArrayList<Task> resultList = new ArrayList<Task>(); ArrayList<Task> incomplete = getIncompleteTasks(); for (int i = 0; i < incomplete.size(); i++) { Task t = incomplete.get(i); String taskDate = ""; if (t instanceof DeadlineTask) { taskDate = ((DeadlineTask) t).getDate(); } else if (t instanceof TimedTask) { taskDate = ((TimedTask) t).getStartDate(); } if (taskDate.equals(compareDate)) { resultList.add(t); } } updateWorkingList(resultList); // update the working list return resultList; } /** * This method retrieves the task item in the working list based on index * * @param index * @return the task object - <null> indicates not found */ public Task translateWorkingListId(String keyword) { try { int index = Integer.valueOf(keyword); return _workingList.get(index - 1); } catch (Exception ex) { return null; } } /* * Other CRUD Methods */ /** * This method adds a Task to the list * * @param t * the Task obj * @return The result in a String */ public String createTask(Task t) throws NullPointerException { if (t == null) { return MSG_INVALID_INPUT; } addToItems(t); /* * Create an undoable command object */ addCommand(Command.CommandType.ADD, t); try { saveToFile(); } catch (IOException ioe) { _items.remove(t); return MSG_FAILED_IO_ERROR; } return MSG_PREFIX_TASK + t.getTaskName() + MSG_POSTFIX_IS_ADDED; } /** * This method adds an Floating Task to the list * * @param ft * the FloatingTask obj * @return The result in a String */ public String createTask(FloatingTask ft) throws NullPointerException { return createTask(ft); } /** * This method adds an Deadline Task to the list * * @param dt * the DeadlineTask obj * @return The result in a String */ public String createTask(DeadlineTask dt) throws NullPointerException { return createTask(dt); } /** * This method adds an Floating Task to the list * * @param tt * the TimedTask obj * @return The result in a String */ public String createTask(TimedTask tt) throws NullPointerException { return createTask(tt); } /** * This method displays the content of all the tasks that matches the * keyword in names * * @param keyword * @return */ public String searchForTasks(String keyword) { return displayList(getTasksByName(keyword)); } public String markAsDone(Task t) { if (t == null) return MSG_INVALID_INPUT; Task found = getTaskByUid(t.getUid()); if (found != null) { int index = _items.indexOf(getTaskByUid(found.getUid())); try { found.setIsDone(true); addCommand(Command.CommandType.MARKDONE, found, index); saveToFile(); return MSG_PREFIX_TASK + t.getTaskName() + MSG_POSTFIX_MARKED_AS_DONE; } catch (IOException ioe) { found.setIsDone(false); return MSG_FAILED_TO_MARK_TASK + t.getTaskName() + MSG_POSTFIX_AS_DONE; } } else { return MSG_FAILED_TO_MARK_TASK + t.getTaskName() + MSG_POSTFIX_AS_DONE; } } /** * This method marks all expired tasks as done */ public void clearExpiredTask() { for (int i = 0; i < size(); i++) { Task t = _items.get(i); long dateTimeNow = System.currentTimeMillis() / 1000L; if (t instanceof TimedTask && !t.getIsDone() && ((TimedTask) t).getEndDateTime() < dateTimeNow) { t.setIsDone(true); } else if (t instanceof DeadlineTask && !t.getIsDone() && ((DeadlineTask) t).getEndDateTime() < dateTimeNow) { t.setIsDone(true); } } try { saveToFile(); } catch (IOException e) { e.printStackTrace(); } } /** * This method updates a task item by replacing it with an updated one * * @param target * @param replacement * @return the message indicating the successfulness of the operation */ public String updateTask(Task target, Task replacement) { int index = _items.indexOf(getTaskByUid(target.getUid())); if (index != -1) { _items.set(index, replacement); /* * create an undoable command */ addCommand(Command.CommandType.UPDATE, target, replacement); /* * save changes to storage */ try { saveToFile(); return MSG_PREFIX_TASK + target.getTaskName() + MSG_POSTFIX_IS_UPDATED; } catch (IOException e) { e.printStackTrace(); return MSG_FAILED_IO_ERROR; } } else { return MSG_INVALID_INPUT; } } /* * Undo and Redo methods */ /** * This method removes a Task by UID * * @param t * @return */ public String deleteTask(Task t) { if (t == null) return MSG_INVALID_INPUT; Task found = getTaskByUid(t.getUid()); int index = _items.indexOf(getTaskByUid(found.getUid())); if (found != null && _items.remove(found)) { try { /* * create an undoable command */ addCommand(Command.CommandType.DELETE, found, index); saveToFile(); return MSG_PREFIX_TASK + t.getTaskName() + MSG_POSTFIX_IS_REMOVED; } catch (IOException ioe) { _items.remove(t); return MSG_FAILED_IO_ERROR; } } else { return MSG_CANT_REMOVE_TASK; } } /** * This method invokes the undo operation on the most recent undoable action * * @return The result in a string */ public String undoMostRecent() { String result = MSG_NO_MORE_ACTIONS_TO_BE_UNDONE; if (_undoList.size() > 0) { Command comm = _undoList.get(_undoList.size() - 1); result = comm.undo(); /* * to enable redo */ _redoList.add(_undoList.remove(_undoList.size() - 1)); } return result; } /** * This method invokes the redo operation on the most recent undoable action * * @return The result in a string */ public String redoMostRecent() { String result = MSG_NO_MORE_ACTIONS_TO_BE_REDONE; if (_redoList.size() > 0) { Command comm = _redoList.get(_redoList.size() - 1); result = comm.redo(); _undoList.add(_redoList.remove(_redoList.size() - 1)); } return result; } /* * Other Methods */ /** * This method returns the number of task obj in the list * * @return int the size of the list of tasks */ public int size() { return _items.size(); } /** * This method returns a string that represent all the tasks in the task * list in RAM * * @return */ public String displayAllTaskList() { return displayList(getAllTasks()); } /** * This method returns a string that represent all incomplete tasks list in * RAM * * @return */ public String displayIncompleteTaskList() { return displayList(getIncompleteTasks()); } /** * This method returns a string that represent all the tasks in a list * * @param li * @return */ public String displayList(ArrayList<Task> li) { String retStr = ""; for (int i = 0; i < li.size(); i++) { retStr += String.valueOf(i + 1) + ". " + li.get(i) + STRING_LINE_BREAK; } return retStr; } /* * Storage handlers */ /** * This method loads all tasks from the text file */ public boolean loadFromFile() throws IOException { _items = Storage.loadDbFile(PATH_DATA_FILE); if (_items == null) { _items = new ArrayList<Task>(); } _nextUid = getMaxUid(); return true; } /** * This method saves all tasks to the text file */ public void saveToFile() throws IOException { String filename = PATH_DATA_FILE; Storage.saveToJson(filename, _items); } /* * Private Methods */ /** * This method assign UID to new Task and add it to the list * * @param t * : the task to add */ private void addToItems(Task t) { t.setUid(_nextUid); _items.add(t); _nextUid++; } /** * This method returns an actual reference to the task with a specific UID * in the item list * * @param uid * @return */ private Task getTaskByUid(long uid) { for (int i = 0; i < _items.size(); i++) { if (_items.get(i).getUid() == uid) { return _items.get(i); } } return null; } /** * This method retrieves the next UID available for newly added Task objects * * @return the UID */ private long getMaxUid() { long max = 0; if (_items != null) { for (int i = 0; i < _items.size(); i++) { if (_items.get(i).getUid() > max) { max = _items.get(i).getUid(); } } } return max + 1; } /** * This method creates an undoable command in the stack * * @param type * @param target */ private void addCommand(Command.CommandType type, Task target) { Command comm = new Command(_items, type, target); _undoList.add(comm); } /** * This method adds a undoable command object to the undo list without * supplying the index of object being affected * * @param type * @param target * @param replacement */ private void addCommand(Command.CommandType type, Task target, Task replacement) { Command comm = new Command(_items, type, target, replacement); _undoList.add(comm); } /** * This method adds a undoable command object to the undo list with index of * affected object supplied as param * * @param type * @param target * @param index */ private void addCommand(Command.CommandType type, Task target, int index) { Command comm = new Command(_items, type, target, index); _undoList.add(comm); } /** * This method updates the working list * * @param li * the previously displayed list */ private void updateWorkingList(ArrayList<Task> li) { _workingList = li; } }
package com.mcjty.rftools; import com.mcjty.rftools.blocks.dimlets.DimletConfiguration; import com.mcjty.rftools.dimension.DimensionInformation; import com.mcjty.rftools.dimension.RfToolsDimensionManager; import net.minecraft.block.BlockBed; import net.minecraft.block.BlockDirectional; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.ChunkCoordinates; import net.minecraft.world.World; public class BedControl { public static int getBedMeta(World world, int x, int y, int z) { int meta = world.getBlockMetadata(x, y, z); if (!BlockBed.isBlockHeadOfBed(meta)) { int j1 = BlockDirectional.getDirection(meta); x += BlockBed.field_149981_a[j1][0]; z += BlockBed.field_149981_a[j1][1]; if (!(world.getBlock(x, y, z) instanceof BlockBed)) { return -1; } meta = world.getBlockMetadata(x, y, z); } return meta; } public static boolean trySleep(World world, EntityPlayer player, int x, int y, int z, int meta) { if (BlockBed.func_149976_c(meta)) { EntityPlayer entityplayer1 = null; for (Object playerEntity : world.playerEntities) { EntityPlayer entityplayer2 = (EntityPlayer) playerEntity; if (entityplayer2.isPlayerSleeping()) { ChunkCoordinates chunkcoordinates = entityplayer2.playerLocation; if (chunkcoordinates.posX == x && chunkcoordinates.posY == y && chunkcoordinates.posZ == z) { entityplayer1 = entityplayer2; } } } if (entityplayer1 != null) { player.addChatComponentMessage(new ChatComponentTranslation("tile.bed.occupied")); return true; } BlockBed.func_149979_a(world, x, y, z, false); } EntityPlayer.EnumStatus enumstatus = player.sleepInBedAt(x, y, z); if (enumstatus == EntityPlayer.EnumStatus.OK) { BlockBed.func_149979_a(world, x, y, z, true); RfToolsDimensionManager manager = RfToolsDimensionManager.getDimensionManager(world); DimensionInformation information = manager.getDimensionInformation(world.provider.dimensionId); if (DimletConfiguration.respawnSameDim || (information != null && information.isRespawnHere())) { player.addChatComponentMessage(new ChatComponentText("Somehow this place feels more like home now.")); } return true; } else { if (enumstatus == EntityPlayer.EnumStatus.NOT_POSSIBLE_NOW) { player.addChatComponentMessage(new ChatComponentTranslation("tile.bed.noSleep")); } else if (enumstatus == EntityPlayer.EnumStatus.NOT_SAFE) { player.addChatComponentMessage(new ChatComponentTranslation("tile.bed.notSafe")); } return true; } } }
package com.muzima; import android.app.Activity; import android.app.Application; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import com.muzima.api.context.Context; import com.muzima.api.context.ContextFactory; import com.muzima.api.service.ConceptService; import com.muzima.api.service.EncounterService; import com.muzima.controller.*; import com.muzima.search.api.util.StringUtil; import com.muzima.service.CohortPrefixPreferenceService; import com.muzima.service.MuzimaSyncService; import com.muzima.util.Constants; import com.muzima.view.forms.FormWebViewActivity; import com.muzima.view.preferences.MuzimaTimer; import org.acra.ACRA; import org.acra.annotation.ReportsCrashes; import java.io.*; import java.security.Security; import static com.muzima.view.preferences.MuzimaTimer.getTimer; @ReportsCrashes(formKey = "ACRA_FORM_KEY") public class MuzimaApplication extends Application { private Context muzimaContext; private Activity currentActivity; private FormController formController; private CohortController cohortController; private PatientController patientConroller; private ConceptController conceptController; private ObservationController observationController; private EncounterController encounterController; private MuzimaSyncService muzimaSyncService; private CohortPrefixPreferenceService prefixesPreferenceService; private MuzimaTimer muzimaTimer; public static final String APP_DIR = "/data/data/com.muzima"; static { Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1); } public void clearApplicationData() { try { File dir = new File(APP_DIR); if (dir.isDirectory()) { deleteDir(dir); } } catch (Exception e) { throw new RuntimeException("Failed to clear the application data", e); } } private static boolean deleteDir(File dir) { if (dir != null && dir.isDirectory()) { String[] children = dir.list(); for (String child : children) { boolean success = deleteDir(new File(dir, child)); if (!success) { return false; } } } return dir.delete(); } @Override public void onCreate() { ACRA.init(this); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.FROYO) { System.setProperty("http.keepAlive", "false"); } muzimaTimer = getTimer(this); super.onCreate(); try { ContextFactory.setProperty(Constants.LUCENE_DIRECTORY_PATH, APP_DIR); ContextFactory.setProperty(Constants.RESOURCE_CONFIGURATION_STRING, getConfigurationString()); muzimaContext = ContextFactory.createContext(); } catch (IOException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } } public Context getMuzimaContext() { return muzimaContext; } public ConceptController getConceptController() { if (conceptController == null) { try { conceptController = new ConceptController(muzimaContext.getService(ConceptService.class)); } catch (IOException e) { throw new RuntimeException(e); } } return conceptController; } public FormController getFormController() { if (formController == null) { try { formController = new FormController(muzimaContext.getFormService(), muzimaContext.getPatientService()); } catch (IOException e) { throw new RuntimeException(e); } } return formController; } public CohortController getCohortController() { if (cohortController == null) { try { cohortController = new CohortController(muzimaContext.getCohortService()); } catch (IOException e) { throw new RuntimeException(e); } } return cohortController; } public PatientController getPatientController() { if (patientConroller == null) { try { patientConroller = new PatientController(muzimaContext.getPatientService(), muzimaContext.getCohortService()); } catch (IOException e) { throw new RuntimeException(e); } } return patientConroller; } public ObservationController getObservationController() { if (observationController == null) { try { observationController = new ObservationController(muzimaContext.getObservationService(), muzimaContext.getService(ConceptService.class), muzimaContext.getService(EncounterService.class)); } catch (IOException e) { throw new RuntimeException(e); } } return observationController; } public EncounterController getEncounterController() { if (encounterController == null) { try { encounterController = new EncounterController(muzimaContext.getService(EncounterService.class)); } catch (IOException e) { throw new RuntimeException(e); } } return encounterController; } public MuzimaSyncService getMuzimaSyncService() { if (muzimaSyncService == null) { muzimaSyncService = new MuzimaSyncService(this); } return muzimaSyncService; } public CohortPrefixPreferenceService getCohortPrefixesPreferenceService() { if (prefixesPreferenceService == null) { prefixesPreferenceService = new CohortPrefixPreferenceService(this); } return prefixesPreferenceService; } public void setTimeOutInMillis(int value) { muzimaTimer.setTimeOutInMillis(value); } public void restartTimer() { muzimaTimer.restart(); } public void logOut() { saveBeforeExit(); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); String passwordKey = getResources().getString(R.string.preference_password); settings.edit().putString(passwordKey, StringUtil.EMPTY).commit(); } public void cancelTimer() { muzimaTimer.cancel(); } public void setCurrentActivity(Activity currentActivity) { this.currentActivity = currentActivity; } private void saveBeforeExit() { if (currentActivity instanceof FormWebViewActivity) { ((FormWebViewActivity) currentActivity).saveDraft(); } } private String getConfigurationString() throws IOException { InputStream inputStream = getResources().openRawResource(R.raw.configuration); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder builder = new StringBuilder(); while ((line = reader.readLine()) != null) { builder.append(line); } reader.close(); return builder.toString(); } }
package com.muzima.utils; import android.graphics.Color; import java.util.Random; public enum CustomColor { DUTCH_TEAL("#1693A5"), MAD_RED("#F02311"), CHRISTMAS_BLUE("#2A8FBD"), DARTH_GREY("#666666"), ROSEWOOD("#901F0F"), DINK_PINK("#FF0066"), CLOCKWORK_ORANGE("#E73525"), ELLE_BELLE("#7FAF1B"), RESPBERRY_SAUCE("#AB0743"), STRAWBERRY_SAUCE("#F20F62"), CENTENARY_BLUE("#7BA5D1"), ALLERGIC_RED("#FF4040"), SOMEWHAT_PURPLE("#C19652"), HUMAN_DRESS("#57553c"), LOST_SOMEWHERE("#48A09B"), HIGH_SKYBLUE("#107FC9"), YUM("#098786"), ROUNGE("#FF6600"), EYES_IN_SKY("#7D96FF"), BLESSING("#DB1750"), ACQUA("#036564"), GRUBBY("#308000"), POOLSIDE("#34BEDA"), CREEP("#0B8C8F"), BUZZ("#6991AA"), BLUSH("#E05D6F"), GRUMMPY("#CC527A"), COOL_AID("#A40778"); private int color; private static final Random random = new Random(); public int getColor() { return color; } private CustomColor(String color){ this.color = Color.parseColor(color); } public static int getRandomColor(){ int numOfColors = CustomColor.values().length; int colorPos = random.nextInt(numOfColors); return CustomColor.values()[colorPos].color; } }
package com.stratio.specs; import com.auth0.jwt.JWTSigner; import com.ning.http.client.cookie.Cookie; import com.stratio.exceptions.DBException; import com.stratio.tests.utils.RemoteSSHConnection; import com.stratio.tests.utils.ThreadProperty; import cucumber.api.DataTable; import cucumber.api.java.en.Given; import org.assertj.core.api.Assertions; import org.openqa.selenium.WebElement; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.UnknownHostException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.stratio.assertions.Assertions.assertThat; /** * Generic Given Specs. */ public class GivenGSpec extends BaseGSpec { public static final int PAGE_LOAD_TIMEOUT = 120; public static final int IMPLICITLY_WAIT = 10; public static final int SCRIPT_TIMEOUT = 30; /** * Generic constructor. * * @param spec */ public GivenGSpec(CommonG spec) { this.commonspec = spec; } /** * Create a basic Index. * * @param index_name index name * @param table the table where index will be created. * @param column the column where index will be saved * @param keyspace keyspace used * @throws Exception */ @Given("^I create a Cassandra index named '(.+?)' in table '(.+?)' using magic_column '(.+?)' using keyspace '(.+?)'$") public void createBasicMapping(String index_name, String table, String column, String keyspace) throws Exception { String query = "CREATE INDEX " + index_name + " ON " + table + " (" + column + ");"; commonspec.getCassandraClient().executeQuery(query); } /** * Create a Cassandra Keyspace. * * @param keyspace */ @Given("^I create a Cassandra keyspace named '(.+)'$") public void createCassandraKeyspace(String keyspace) { commonspec.getCassandraClient().createKeyspace(keyspace); } /** * Connect to cluster. * * @param clusterType DB type (Cassandra|Mongo|Elasticsearch) * @param url url where is started Cassandra cluster */ @Given("^I connect to '(Cassandra|Mongo|Elasticsearch)' cluster at '(.+)'$") public void connect(String clusterType, String url) throws DBException, UnknownHostException { switch (clusterType) { case "Cassandra": commonspec.getCassandraClient().buildCluster(); commonspec.getCassandraClient().connect(); break; case "Mongo": commonspec.getMongoDBClient().connect(); break; case "Elasticsearch": LinkedHashMap<String, Object> settings_map = new LinkedHashMap<String, Object>(); settings_map.put("cluster.name", System.getProperty("ES_CLUSTER", "elasticsearch")); commonspec.getElasticSearchClient().setSettings(settings_map); commonspec.getElasticSearchClient().connect(); break; default: throw new DBException("Unknown cluster type"); } } /** * Create table * * @param table * @param datatable * @param keyspace * @throws Exception */ @Given("^I create a Cassandra table named '(.+?)' using keyspace '(.+?)' with:$") public void createTableWithData(String table, String keyspace, DataTable datatable) { try { commonspec.getCassandraClient().useKeyspace(keyspace); int attrLength = datatable.getGherkinRows().get(0).getCells().size(); Map<String, String> columns = new HashMap<String, String>(); ArrayList<String> pk = new ArrayList<String>(); for (int i = 0; i < attrLength; i++) { columns.put(datatable.getGherkinRows().get(0).getCells().get(i), datatable.getGherkinRows().get(1).getCells().get(i)); if ((datatable.getGherkinRows().size() == 3) && datatable.getGherkinRows().get(2).getCells().get(i).equalsIgnoreCase("PK")) { pk.add(datatable.getGherkinRows().get(0).getCells().get(i)); } } if (pk.isEmpty()) { throw new Exception("A PK is needed"); } commonspec.getCassandraClient().createTableWithData(table, columns, pk); } catch (Exception e) { // TODO Auto-generated catch block commonspec.getLogger().debug("Exception captured"); commonspec.getLogger().debug(e.toString()); commonspec.getExceptions().add(e); } } /** * Insert Data * * @param table * @param datatable * @param keyspace * @throws Exception */ @Given("^I insert in keyspace '(.+?)' and table '(.+?)' with:$") public void insertData(String keyspace, String table, DataTable datatable) { try { commonspec.getCassandraClient().useKeyspace(keyspace); int attrLength = datatable.getGherkinRows().get(0).getCells().size(); Map<String, Object> fields = new HashMap<String, Object>(); for (int e = 1; e < datatable.getGherkinRows().size(); e++) { for (int i = 0; i < attrLength; i++) { fields.put(datatable.getGherkinRows().get(0).getCells().get(i), datatable.getGherkinRows().get(e).getCells().get(i)); } commonspec.getCassandraClient().insertData(keyspace + "." + table, fields); } } catch (Exception e) { // TODO Auto-generated catch block commonspec.getLogger().debug("Exception captured"); commonspec.getLogger().debug(e.toString()); commonspec.getExceptions().add(e); } } @Given("^I save element (in position \'(.+?)\' in )?\'(.+?)\' in environment variable \'(.+?)\'$") public void saveElementEnvironment(String foo, String position, String element, String envVar) throws Exception { Pattern pattern = Pattern.compile("^((.*)(\\.)+)(\\$.*)$"); Matcher matcher = pattern.matcher(element); String json; String parsedElement; if (matcher.find()) { json = matcher.group(2); parsedElement = matcher.group(4); } else { json = commonspec.getResponse().getResponse(); parsedElement = element; } String value = commonspec.getJSONPathString(json, parsedElement, position); if (value == null) { throw new Exception("Element to be saved: " + element + " is null"); } else { this.commonspec.getLogger().debug("Saving element: {} with value: {} in environment variable: {}", new Object[]{element, value, envVar}); ThreadProperty.set(envVar, value); } } /** * Drop all the ElasticSearch indexes. */ @Given("^I drop every existing elasticsearch index$") public void dropElasticsearchIndexes() { commonspec.getElasticSearchClient().dropAllIndexes(); } /** * Drop an specific index of ElasticSearch. * * @param index */ @Given("^I drop an elasticsearch index named '(.+?)'$") public void dropElasticsearchIndex(String index) { commonspec.getElasticSearchClient().dropSingleIndex(index); } /** * Execute a cql file over a Cassandra keyspace. * * @param filename * @param keyspace */ @Given("a Cassandra script with name '(.+?)' and default keyspace '(.+?)'$") public void insertDataOnCassandraFromFile(String filename, String keyspace) { commonspec.getLogger().debug("Inserting data on cassandra from file"); commonspec.getCassandraClient().loadTestData(keyspace, "/scripts/" + filename); } /** * Drop a Cassandra Keyspace. * * @param keyspace */ @Given("^I drop a Cassandra keyspace '(.+)'$") public void dropCassandraKeyspace(String keyspace) { commonspec.getLogger().debug("Dropping a Cassandra keyspace", keyspace); commonspec.getCassandraClient().dropKeyspace(keyspace); } /** * Create a MongoDB dataBase. * * @param databaseName */ @Given("^I create a MongoDB dataBase '(.+?)'$") public void createMongoDBDataBase(String databaseName) { commonspec.getLogger().debug("Creating a database on MongoDB"); commonspec.getMongoDBClient().connectToMongoDBDataBase(databaseName); } /** * Drop MongoDB Database. * * @param databaseName */ @Given("^I drop a MongoDB database '(.+?)'$") public void dropMongoDBDataBase(String databaseName) { commonspec.getLogger().debug("Creating a database on MongoDB"); commonspec.getMongoDBClient().dropMongoDBDataBase(databaseName); } /** * Insert data in a MongoDB table. * * @param dataBase * @param tabName * @param table */ @Given("^I insert into a MongoDB database '(.+?)' and table '(.+?)' this values:$") public void insertOnMongoTable(String dataBase, String tabName, DataTable table) { commonspec.getLogger().debug("Inserting data in a database on MongoDB"); commonspec.getMongoDBClient().connectToMongoDBDataBase(dataBase); commonspec.getMongoDBClient().insertIntoMongoDBCollection(tabName, table); } /** * Truncate table in MongoDB. * * @param database * @param table */ @Given("^I drop every document at a MongoDB database '(.+?)' and table '(.+?)'") public void truncateTableInMongo(String database, String table) { commonspec.getLogger().debug("Truncating a table in MongoDB"); commonspec.getMongoDBClient().connectToMongoDBDataBase(database); commonspec.getMongoDBClient().dropAllDataMongoDBCollection(table); } /** * Browse to {@code url} using the current browser. * * @param path * @throws Exception */ @Given("^I browse to '(.+?)'$") public void seleniumBrowse(String path) throws Exception { assertThat(path).isNotEmpty(); if (commonspec.getWebHost() == null) { throw new Exception("Web host has not been set"); } if (commonspec.getWebPort() == null) { throw new Exception("Web port has not been set"); } String webURL = "http://" + commonspec.getWebHost() + commonspec.getWebPort(); commonspec.getLogger().debug("Browsing to {}{} with {}", webURL, path, commonspec.getBrowserName()); commonspec.getDriver().get(webURL + path); commonspec.setParentWindow(commonspec.getDriver().getWindowHandle()); } /** * Set app host and port {@code host, @code port} * * @param host * @param port */ @Given("^My app is running in '([^:]+?)(:.+?)?'$") public void setupApp(String host, String port) { assertThat(host).isNotEmpty(); assertThat(port).isNotEmpty(); if (port == null) { port = ":80"; } commonspec.setWebHost(host); commonspec.setWebPort(port); commonspec.setRestHost(host); commonspec.setRestPort(port); commonspec.getLogger().debug("Set URL to http://{}{}/", host, port); } /** * Browse to {@code webHost, @code webPort} using the current browser. * * @param webHost * @param webPort * @throws MalformedURLException */ @Given("^I set web base url to '([^:]+?)(:.+?)?'$") public void setupWeb(String webHost, String webPort) throws MalformedURLException { assertThat(webHost).isNotEmpty(); assertThat(webPort).isNotEmpty(); if (webPort == null) { webPort = ":80"; } commonspec.setWebHost(webHost); commonspec.setWebPort(webPort); commonspec.getLogger().debug("Set web base URL to http://{}{}", webHost, webPort); } /** * Send requests to {@code restHost @code restPort}. * * @param restHost * @param restPort */ @Given("^I( securely)? send requests to '([^:]+?)(:.+?)?'$") public void setupRestClient(String isSecured, String restHost, String restPort) { assertThat(restHost).isNotEmpty(); assertThat(restPort).isNotEmpty(); String restProtocol = "http: if (isSecured != null) { restProtocol = "https: } if (restHost == null) { restHost = "localhost"; } if (restPort == null) { restPort = ":80"; } commonspec.setRestProtocol(restProtocol); commonspec.setRestHost(restHost); commonspec.setRestPort(restPort); commonspec.getLogger().debug("Sending requests to {}{}{}", restProtocol, restHost, restPort); } /** * Maximizes current browser window. Mind the current resolution could break a test. */ @Given("^I maximize the browser$") public void seleniumMaximize(String url) { commonspec.getDriver().manage().window().maximize(); } /** * Switches to a frame/ iframe. */ @Given("^I switch to the iframe on index '(\\d+?)'$") public void seleniumSwitchFrame(Integer index) { assertThat(commonspec.getPreviousWebElements()).as("There are less found elements than required") .hasAtLeast(index); WebElement elem = commonspec.getPreviousWebElements().getPreviousWebElements().get(index); commonspec.getDriver().switchTo().frame(elem); } /** * Switches to a parent frame/ iframe. */ @Given("^I switch to a parent frame$") public void seleniumSwitchAParentFrame() { commonspec.getDriver().switchTo().parentFrame(); } /** * Switches to the frames main container. */ @Given("^I switch to the main frame container$") public void seleniumSwitchParentFrame() { commonspec.getDriver().switchTo().frame(commonspec.getParentWindow()); } /* * Opens a ssh connection to remote host * * @param remoteHost * @param user * @param password (required if pemFile null) * @param pemFile (required if password null) * */ @Given("^I open remote ssh connection to host '(.+?)' with user '(.+?)'( and password '(.+?)')?( using pem file '(.+?)')?$") public void openSSHConnection(String remoteHost, String user, String foo, String password, String bar, String pemFile) throws Exception { if ((pemFile == null) || (pemFile.equals(""))) { if (password == null) { throw new Exception("You have to provide a password or a pem file to be used for connection"); } commonspec.getLogger().debug("Openning remote ssh connection to " + remoteHost + " with user " + user + " and password " + password); } else { File pem = new File(pemFile); if (!pem.exists()) { throw new Exception("Pem file: " + pemFile + " does not exist"); } commonspec.getLogger().debug("Openning remote ssh connection to " + remoteHost + " with user " + user + " using pem file " + pemFile); } commonspec.setRemoteSSHConnection(new RemoteSSHConnection(user, password, remoteHost, pemFile)); } /* * Authenticate in a DCOS cluster * * @param remoteHost * @param email * @param user * @param password (required if pemFile null) * @param pemFile (required if password null) * */ @Given("^I want to authenticate in DCOS cluster '(.+?)' with email '(.+?)' with user '(.+?)'( and password '(.+?)')?( using pem file '(.+?)')$") public void authenticateDCOSpem(String remoteHost,String email, String user, String foo, String password, String bar, String pemFile) throws Exception { String DCOSsecret = null; if ((pemFile.equals("") && (password != ""))) { commonspec.setRemoteSSHConnection(new RemoteSSHConnection(user, password, remoteHost, null)); commonspec.getRemoteSSHConnection().runCommand("sudo cat /var/lib/dcos/dcos-oauth/auth-token-secret"); DCOSsecret = commonspec.getRemoteSSHConnection().getResult().trim(); } else if ((password.equals("") && (pemFile != ""))) { File pem = new File(pemFile); if (!pem.exists()) { throw new Exception("Pem file: " + pemFile + " does not exist"); } commonspec.setRemoteSSHConnection(new RemoteSSHConnection(user, null, remoteHost, pemFile)); commonspec.getRemoteSSHConnection().runCommand("sudo cat /var/lib/dcos/dcos-oauth/auth-token-secret"); DCOSsecret = commonspec.getRemoteSSHConnection().getResult().trim(); } else if ((password.equals("") && (pemFile.equals("")))){ throw new Exception("Either password or Pem file must be provided"); } if (DCOSsecret == null){ throw new Exception("There was an error trying to obtain DCOS secret."); } final JWTSigner signer = new JWTSigner(DCOSsecret); final HashMap<String, Object> claims = new HashMap(); claims.put("uid", email); final String jwt = signer.sign(claims); Cookie cookie = new Cookie("dcos-acs-auth-cookie", jwt, false, "", "", 99999, false, false); List<Cookie> cookieList = new ArrayList<Cookie>(); cookieList.add(cookie); commonspec.setCookies(cookieList); } /* * Authenticate in a DCOS cluster * * @param dcosHost * @param user * */ @Given("^I authenticate in DCOS cluster '(.+?)' with email '(.+?)'$") public void authenticateDCOS(String dcosCluster, String user) throws Exception { commonspec.getLogger().debug("Authenticating in DCOS cluster " + dcosCluster + " with user " + user); commonspec.setRemoteSSHConnection(new RemoteSSHConnection("root", "stratio", dcosCluster, null)); commonspec.getRemoteSSHConnection().runCommand("cat /var/lib/dcos/dcos-oauth/auth-token-secret"); String DCOSsecret = commonspec.getRemoteSSHConnection().getResult().trim(); final JWTSigner signer = new JWTSigner(DCOSsecret); final HashMap<String, Object> claims = new HashMap(); claims.put("uid", user); final String jwt = signer.sign(claims); Cookie cookie = new Cookie("dcos-acs-auth-cookie", jwt, false, "", "", 99999, false, false); List<Cookie> cookieList = new ArrayList<Cookie>(); cookieList.add(cookie); commonspec.setCookies(cookieList); } /* * Copies file/s from remote system into local system * * @param remotePath * @param localPath * */ @Given("^I copy '(.+?)' from remote ssh connection and store it in '(.+?)'$") public void copyFromRemoteFile(String remotePath, String localPath) throws Exception { commonspec.getLogger().debug("Copy remote " + remotePath + " to local " + localPath); commonspec.getRemoteSSHConnection().copyFrom(remotePath, localPath); } /* * Copies file/s from local system to remote system * * @param localPath * @param remotePath * */ @Given("^I copy '(.+?)' to remote ssh connection in '(.+?)'$") public void copyToRemoteFile(String localPath, String remotePath) throws Exception { commonspec.getLogger().debug("Copy local " + localPath + " to remote " + remotePath); commonspec.getRemoteSSHConnection().copyTo(localPath, remotePath); } /** * Executes the command specified in local system * * @param command **/ @Given("^I execute command '(.+?)' locally$") public void executeLocalCommand(String command) throws Exception { commonspec.getLogger().debug("Executing command '" + command + "'"); commonspec.runLocalCommand(command); } /** * Executes the command specified in remote system * * @param command **/ @Given("^I execute command '(.+?)' in remote ssh connection( with exit status '(.+?)')?( and save the value in environment variable '(.+?)')?$") public void executeCommand(String command, String foo, Integer exitStatus, String var, String envVar) throws Exception { if (exitStatus == null) { exitStatus = 0; } commonspec.getLogger().debug("Executing command '" + command + "'"); commonspec.getRemoteSSHConnection().runCommand(command); commonspec.setCommandResult(commonspec.getRemoteSSHConnection().getResult()); commonspec.setCommandExitStatus(commonspec.getRemoteSSHConnection().getExitStatus()); List<String> logOutput = Arrays.asList(commonspec.getCommandResult().split("\n")); StringBuffer log = new StringBuffer(); int logLastLines = 25; if (logOutput.size() < 25) { logLastLines = logOutput.size(); } for (String s : logOutput.subList(logOutput.size() - logLastLines, logOutput.size())) { log.append(s).append("\n"); } if (envVar != null){ ThreadProperty.set(envVar, commonspec.getRemoteSSHConnection().getResult()); } commonspec.getLogger().info("Exit status is: {}", commonspec.getRemoteSSHConnection().getExitStatus()); commonspec.getLogger().info("Command last " + logLastLines + " lines stdout:\n{}", log); commonspec.getLogger().debug("Command complete stdout:\n{}", commonspec.getCommandResult()); Assertions.assertThat(commonspec.getRemoteSSHConnection().getExitStatus()).isEqualTo(exitStatus); } /** * Insert document in a MongoDB table. * * @param dataBase * @param collection * @param document */ @Given("^I insert into MongoDB database '(.+?)' and collection '(.+?)' the document from schema '(.+?)'$") public void insertOnMongoTable(String dataBase, String collection, String document) throws Exception { commonspec.getLogger().debug("Inserting data at {}.{} on MongoDB", dataBase, collection); String retrievedDoc = commonspec.retrieveData(document, "json"); commonspec.getMongoDBClient().connectToMongoDBDataBase(dataBase); commonspec.getMongoDBClient().insertDocIntoMongoDBCollection(collection, retrievedDoc); } /** * Get all opened windows and store it. */ @Given("^new window is opened$") public void seleniumGetwindows() { commonspec.getLogger().debug("Getting number of opened windows"); Set<String> wel = commonspec.getDriver().getWindowHandles(); Assertions.assertThat(wel).as("Element count doesnt match").hasSize(2); } /** * Connect to zookeeper. * * @param zookeeperHosts as host:port (comma separated) */ @Given("^I connect to zk cluster at '(.+)'$") public void connectToZk(String zookeeperHosts) { commonspec.getLogger().debug("Connecting to zookeeper at " + zookeeperHosts); commonspec.getZookeeperClient().setZookeeperConnection(zookeeperHosts, 3000); commonspec.getZookeeperClient().connectZk(); } /** * Connect to Kafka. * @param zkHost * @param zkPort * @param zkPath */ @Given("^I connect to kafka cluster at '(.+)':'(.+)' using path '(.+)'$") public void connectKafka(String zkHost, String zkPort, String zkPath) throws UnknownHostException { commonspec.getLogger().debug("Connecting to " + zkHost + " cluster"); if (System.getenv("DCOS_CLUSTER") != null) { commonspec.getKafkaUtils().setZkHost(zkHost, zkPort, zkPath); } else { commonspec.getKafkaUtils().setZkHost(zkHost, zkPort, "dcos-service-" + zkPath); } commonspec.getKafkaUtils().connect(); } }
package com.toomasr.sgf4j.gui; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.toomasr.sgf4j.Sgf; import com.toomasr.sgf4j.SgfProperties; import com.toomasr.sgf4j.board.BoardStone; import com.toomasr.sgf4j.board.CoordinateSquare; import com.toomasr.sgf4j.board.GuiBoardListener; import com.toomasr.sgf4j.board.StoneState; import com.toomasr.sgf4j.board.VirtualBoard; import com.toomasr.sgf4j.filetree.FileTreeView; import com.toomasr.sgf4j.movetree.EmptyTriangle; import com.toomasr.sgf4j.movetree.GlueStone; import com.toomasr.sgf4j.movetree.GlueStoneType; import com.toomasr.sgf4j.movetree.TreeStone; import com.toomasr.sgf4j.parser.Game; import com.toomasr.sgf4j.parser.GameNode; import com.toomasr.sgf4j.parser.Util; import com.toomasr.sgf4j.properties.AppState; import com.toomasr.sgf4j.util.Encoding; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.TilePane; import javafx.scene.layout.VBox; import javafx.scene.text.Font; public class MainUI { private static final Logger logger = LoggerFactory.getLogger(MainUI.class); private Button nextButton; private GameNode currentMove = null; private GameNode prevMove = null; private Game game; private VirtualBoard virtualBoard; private BoardStone[][] board; private GridPane movePane; private GridPane boardPane = new GridPane(); private Map<GameNode, TreeStone> nodeToTreeStone = new HashMap<>(); private TextArea commentArea; private Button previousButton; private ScrollPane treePaneScrollPane; private Label whitePlayerName; private Label blackPlayerName; private Label label; public MainUI() { board = new BoardStone[19][19]; virtualBoard = new VirtualBoard(); virtualBoard.addBoardListener(new GuiBoardListener(this)); } public Pane buildUI() throws Exception { Insets paneInsets = new Insets(5, 0, 0, 0); VBox leftVBox = new VBox(5); leftVBox.setPadding(paneInsets); VBox centerVBox = new VBox(5); centerVBox.setPadding(paneInsets); VBox rightVBox = new VBox(5); rightVBox.setPadding(paneInsets); // constructing the left box VBox fileTreePane = generateFileTreePane(); leftVBox.getChildren().addAll(fileTreePane); // constructing the center box centerVBox.setMaxWidth(640); centerVBox.setMinWidth(640); boardPane = generateBoardPane(boardPane); TilePane buttonPane = generateButtonPane(); ScrollPane treePane = generateMoveTreePane(); centerVBox.getChildren().addAll(boardPane, buttonPane, treePane); // constructing the right box VBox gameMetaInfo = generateGameMetaInfo(); TextArea commentArea = generateCommentPane(); rightVBox.getChildren().addAll(gameMetaInfo, commentArea); HBox rootHBox = new HBox(); enableKeyboardShortcuts(rootHBox); rootHBox.getChildren().addAll(leftVBox, centerVBox, rightVBox); VBox rootVbox = new VBox(); HBox statusBar = generateStatusBar(); rootVbox.getChildren().addAll(rootHBox, statusBar); return rootVbox; } private HBox generateStatusBar() { HBox rtrn = new HBox(); label = new Label("MainUI loaded"); rtrn.getChildren().add(label); return rtrn; } public void updateStatus(String update) { this.label.setText(update); } public void initGame() { String game = "src/main/resources/game.sgf"; Path path = Paths.get(game); // in development it is nice to have a game open on start if (path.toFile().exists()) { initializeGame(Paths.get(game)); } } private VBox generateGameMetaInfo() { VBox vbox = new VBox(); vbox.setMinWidth(250); GridPane pane = new GridPane(); Label blackPlayerLabel = new Label("Black:"); GridPane.setConstraints(blackPlayerLabel, 1, 0); blackPlayerName = new Label("Unknown"); GridPane.setConstraints(blackPlayerName, 2, 0); Label whitePlayerLabel = new Label("White:"); GridPane.setConstraints(whitePlayerLabel, 1, 1); whitePlayerName = new Label("Unknown"); GridPane.setConstraints(whitePlayerName, 2, 1); pane.getChildren().addAll(blackPlayerLabel, blackPlayerName, whitePlayerLabel, whitePlayerName); vbox.getChildren().add(pane); return vbox; } private TextArea generateCommentPane() { commentArea = new TextArea(); commentArea.setFocusTraversable(false); commentArea.setWrapText(true); commentArea.setPrefSize(300, 600); return commentArea; } private void initializeGame(Path pathToSgf) { Font font = Font.getDefault(); java.awt.Font awtFont = new java.awt.Font(font.getName(), java.awt.Font.PLAIN, (int) font.getSize()); String encoding = Encoding.determineEncoding(pathToSgf, awtFont); logger.debug("Determined encoding {}", encoding); updateStatus(String.format("Loaded %s with encoding %s", pathToSgf.getFileName(), encoding)); this.game = Sgf.createFromPath(pathToSgf, encoding); currentMove = this.game.getRootNode(); prevMove = null; // reset our virtual board and actual board virtualBoard = new VirtualBoard(); virtualBoard.addBoardListener(new GuiBoardListener(this)); initEmptyBoard(); // construct the tree of the moves nodeToTreeStone = new HashMap<>(); movePane.getChildren().clear(); movePane.add(new EmptyTriangle(), 0, 0); GameNode rootNode = game.getRootNode(); populateMoveTreePane(rootNode, 0); showMarkersForMove(rootNode); showCommentForMove(rootNode); showMetaInfoForGame(this.game); treePaneScrollPane.setHvalue(0); treePaneScrollPane.setVvalue(0); } private void showMetaInfoForGame(Game game) { whitePlayerName.setText(game.getProperty(SgfProperties.WHITE_PLAYER_NAME)); blackPlayerName.setText(game.getProperty(SgfProperties.BLACK_PLAYER_NAME)); } public void initEmptyBoard() { generateBoardPane(boardPane); placePreGameStones(game); } private void placePreGameStones(Game game) { String blackStones = game.getProperty("AB", ""); String whiteStones = game.getProperty("AW", ""); placePlacementGameStones(blackStones, whiteStones); } private void placePlacementStones(GameNode node) { String blackStones = node.getProperty("AB", ""); String whiteStones = node.getProperty("AW", ""); placePlacementGameStones(blackStones, whiteStones); } private void placePlacementGameStones(String addBlack, String addWhite) { if (addBlack.length() > 0) { String[] blackStones = addBlack.split(","); for (int i = 0; i < blackStones.length; i++) { int[] moveCoords = Util.alphaToCoords(blackStones[i]); virtualBoard.placeStone(StoneState.BLACK, moveCoords[0], moveCoords[1]); } } if (addWhite.length() > 0) { String[] whiteStones = addWhite.split(","); for (int i = 0; i < whiteStones.length; i++) { int[] moveCoords = Util.alphaToCoords(whiteStones[i]); virtualBoard.placeStone(StoneState.WHITE, moveCoords[0], moveCoords[1]); } } } private void removePreGameStones(GameNode node) { String blackStones = node.getProperty("AB", ""); String whiteStones = node.getProperty("AW", ""); removePlacementStones(blackStones, whiteStones); } private void removePlacementStones(String removeBlack, String removeWhite) { if (removeBlack.length() > 0) { String[] blackStones = removeBlack.split(","); for (int i = 0; i < blackStones.length; i++) { int[] moveCoords = Util.alphaToCoords(blackStones[i]); virtualBoard.removeStone(moveCoords[0], moveCoords[1]); } } if (removeWhite.length() > 0) { String[] whiteStones = removeWhite.split(","); for (int i = 0; i < whiteStones.length; i++) { int[] moveCoords = Util.alphaToCoords(whiteStones[i]); virtualBoard.removeStone(moveCoords[0], moveCoords[1]); } } } private void populateMoveTreePane(GameNode node, int depth) { // we draw out only actual moves if (node.isMove()) { TreeStone treeStone = TreeStone.create(node); movePane.add(treeStone, node.getNodeNo(), node.getVisualDepth()); nodeToTreeStone.put(node, treeStone); treeStone.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { TreeStone stone = (TreeStone) event.getSource(); fastForwardTo(stone.getMove()); } }); } // and recursively draw the next node on this line of play if (node.getNextNode() != null) { populateMoveTreePane(node.getNextNode(), depth + node.getVisualDepth()); } // populate the children also if (node.hasChildren()) { Set<GameNode> children = node.getChildren(); // will determine whether the glue stone should be a single // diagonal or a multiple (diagonal and vertical) GlueStoneType gStoneType = children.size() > 1 ? GlueStoneType.MULTIPLE : GlueStoneType.DIAGONAL; for (Iterator<GameNode> ite = children.iterator(); ite.hasNext();) { GameNode childNode = ite.next(); // the last glue shouldn't be a MULTIPLE if (GlueStoneType.MULTIPLE.equals(gStoneType) && !ite.hasNext()) { gStoneType = GlueStoneType.DIAGONAL; } // the visual lines can also be under a the first triangle int nodeVisualDepth = node.getVisualDepth(); int moveNo = node.getMoveNo(); if (moveNo == -1) { moveNo = 0; nodeVisualDepth = 0; } // also draw all the "missing" glue stones for (int i = nodeVisualDepth + 1; i < childNode.getVisualDepth(); i++) { movePane.add(new GlueStone(GlueStoneType.VERTICAL), moveNo, i); } // glue stone for the node movePane.add(new GlueStone(gStoneType), moveNo, childNode.getVisualDepth()); // and recursively draw the actual node populateMoveTreePane(childNode, depth + childNode.getVisualDepth()); } } } /* * Generates the boilerplate for the move tree pane. The * pane is actually populated during game initialization. */ private ScrollPane generateMoveTreePane() { movePane = new GridPane(); movePane.setPadding(new Insets(0, 0, 0, 0)); movePane.setStyle("-fx-background-color: white"); treePaneScrollPane = new ScrollPane(movePane); treePaneScrollPane.setPrefHeight(150); treePaneScrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED); treePaneScrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED); movePane.setMinWidth(640); return treePaneScrollPane; } private void fastForwardTo(GameNode move) { // clear the board for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { board[i][j].removeStone(); } } placePreGameStones(game); deHighLightStoneInTree(currentMove); removeMarkersForNode(currentMove); virtualBoard.fastForwardTo(move); highLightStoneOnBoard(move); } private VBox generateFileTreePane() { VBox vbox = new VBox(); vbox.setMinWidth(250); TreeView<File> treeView = new FileTreeView(); treeView.setFocusTraversable(false); Label label = new Label("Choose SGF File"); vbox.getChildren().addAll(label, treeView); treeView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.getClickCount() == 2) { TreeItem<File> item = treeView.getSelectionModel().getSelectedItem(); File file = item.getValue().toPath().toFile(); if (file.isFile()) { initializeGame(item.getValue().toPath()); } AppState.getInstance().addProperty(AppState.CURRENT_FILE, file.getAbsolutePath()); } } }); return vbox; } private TilePane generateButtonPane() { TilePane pane = new TilePane(); pane.setAlignment(Pos.CENTER); pane.getStyleClass().add("bordered"); TextField moveNoField = new TextField("0"); moveNoField.setFocusTraversable(false); moveNoField.setMaxWidth(40); moveNoField.setEditable(false); nextButton = new Button("Next"); nextButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { handleNextPressed(); } }); previousButton = new Button("Previous"); previousButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { handlePreviousPressed(); } }); pane.setPrefColumns(1); pane.getChildren().add(previousButton); pane.getChildren().add(moveNoField); pane.getChildren().add(nextButton); return pane; } private void handleNextPressed() { if (currentMove.getNextNode() != null) { prevMove = currentMove; currentMove = currentMove.getNextNode(); virtualBoard.makeMove(currentMove, prevMove); // scroll the scrollpane to make // the highlighted move visible ensureVisibleForActiveTreeNode(currentMove); } } private void handleNextBranch() { if (currentMove.hasChildren()) { prevMove = currentMove; currentMove = currentMove.getChildren().iterator().next(); virtualBoard.makeMove(currentMove, prevMove); // scroll the scrollpane to make // the highlighted move visible ensureVisibleForActiveTreeNode(currentMove); } } public void handlePreviousPressed() { if (currentMove.getParentNode() != null) { prevMove = currentMove; currentMove = currentMove.getParentNode(); virtualBoard.undoMove(prevMove, currentMove); } } public void playMove(GameNode move, GameNode prevMove) { this.currentMove = move; this.prevMove = prevMove; // we actually have a previous move! if (prevMove != null) { // de-highlight previously highlighted move if (prevMove.isMove() && !prevMove.isPass()) { deHighLightStoneOnBoard(prevMove); } // even non moves can haver markers removeMarkersForNode(prevMove); } if (move != null && !move.isPass() && !move.isPlacementMove()) { highLightStoneOnBoard(move); } // highlight stone in the tree pane deHighLightStoneInTree(prevMove); highLightStoneInTree(move); if (move != null && (move.getProperty("AB") != null || move.getProperty("AW") != null)) { placePlacementStones(move); } // show the associated comment showCommentForMove(move); // handle the prev and new markers showMarkersForMove(move); nextButton.requestFocus(); } public void undoMove(GameNode move, GameNode prevMove) { this.currentMove = prevMove; this.prevMove = move; if (move != null) { removeMarkersForNode(move); } if (prevMove != null) { showMarkersForMove(prevMove); showCommentForMove(prevMove); if (prevMove.isMove() && !prevMove.isPass()) highLightStoneOnBoard(prevMove); } removePreGameStones(move); deHighLightStoneInTree(move); highLightStoneInTree(prevMove); ensureVisibleForActiveTreeNode(prevMove); // rather have previous move button have focus previousButton.requestFocus(); } private void ensureVisibleForActiveTreeNode(GameNode move) { if (move != null && move.isMove()) { TreeStone stone = nodeToTreeStone.get(move); // the move tree is not yet fully operational and some // points don't exist in the map yet if (stone == null) return; double width = treePaneScrollPane.getContent().getBoundsInLocal().getWidth(); double x = stone.getBoundsInParent().getMaxX(); double scrollTo = ((x) - 11 * 30) / (width - 21 * 30); treePaneScrollPane.setHvalue(scrollTo); // adjust the vertical scroll double height = treePaneScrollPane.getContent().getBoundsInLocal().getHeight(); double y = stone.getBoundsInParent().getMaxY(); double scrollToY = y / height; if (move.getVisualDepth() == 0) { scrollToY = 0d; } treePaneScrollPane.setVvalue(scrollToY); } } private void highLightStoneInTree(GameNode move) { TreeStone stone = nodeToTreeStone.get(move); // can remove the null check at one point when the // tree is fully implemented if (stone != null) { stone.highLight(); stone.requestFocus(); } } private void deHighLightStoneInTree(GameNode node) { if (node != null && node.isMove()) { TreeStone stone = nodeToTreeStone.get(node); if (stone != null) { stone.deHighLight(); } else { throw new RuntimeException("Unable to find node for move " + node); } } } private void showCommentForMove(GameNode move) { String comment = move.getProperty("C"); if (comment == null) { if (move.getPrevNode() == null && game.getProperty("C") != null) { comment = game.getProperty("C"); } else { comment = ""; } } // some helpers I used for parsing needs to be undone - see the Parser.java // in sgf4j project comment = comment.replaceAll("@@@@@", "\\\\\\["); comment = comment.replaceAll(" // lets do some replacing - see http://www.red-bean.com/sgf/sgf4.html#text comment = comment.replaceAll("\\\\\n", ""); comment = comment.replaceAll("\\\\:", ":"); comment = comment.replaceAll("\\\\\\]", "]"); comment = comment.replaceAll("\\\\\\[", "["); commentArea.setText(comment); } private void showMarkersForMove(GameNode move) { // the L property is actually not used in FF3 and FF4 // but I own many SGFs that still have it String markerProp = move.getProperty("L"); if (markerProp != null) { int alphaIdx = 0; String[] markers = markerProp.split("\\]\\["); for (int i = 0; i < markers.length; i++) { int[] coords = Util.alphaToCoords(markers[i]); board[coords[0]][coords[1]].addOverlayText(Util.alphabet[alphaIdx++]); } } // also handle the LB labels Map<String, String> labels = Util.extractLabels(move.getProperty("LB")); for (Iterator<Map.Entry<String, String>> ite = labels.entrySet().iterator(); ite.hasNext();) { Map.Entry<String, String> entry = ite.next(); int[] coords = Util.alphaToCoords(entry.getKey()); board[coords[0]][coords[1]].addOverlayText(entry.getValue()); } } private void removeMarkersForNode(GameNode node) { // the L property is actually not used in FF3 and FF4 // but I own many SGFs that still have it String markerProp = node.getProperty("L"); if (markerProp != null) { String[] markers = markerProp.split("\\]\\["); for (int i = 0; i < markers.length; i++) { int[] coords = Util.alphaToCoords(markers[i]); board[coords[0]][coords[1]].removeOverlayText(); } } // also handle the LB labels Map<String, String> labels = Util.extractLabels(node.getProperty("LB")); for (Iterator<Map.Entry<String, String>> ite = labels.entrySet().iterator(); ite.hasNext();) { Map.Entry<String, String> entry = ite.next(); int[] coords = Util.alphaToCoords(entry.getKey()); board[coords[0]][coords[1]].removeOverlayText(); } } private void highLightStoneOnBoard(GameNode move) { String currentMove = move.getMoveString(); int[] moveCoords = Util.alphaToCoords(currentMove); board[moveCoords[0]][moveCoords[1]].highLightStone(); } private void deHighLightStoneOnBoard(GameNode prevMove) { String prevMoveAsStr = prevMove.getMoveString(); int[] moveCoords = Util.alphaToCoords(prevMoveAsStr); board[moveCoords[0]][moveCoords[1]].deHighLightStone(); } private GridPane generateBoardPane(GridPane boardPane) { boardPane.getChildren().clear(); for (int i = 0; i < 21; i++) { if (i > 1 && i < 20) { board[i - 1] = new BoardStone[19]; } for (int j = 0; j < 21; j++) { if (i == 0 || j == 0 || i == 20 || j == 20) { CoordinateSquare btn = new CoordinateSquare(i, j); boardPane.add(btn, i, j); } else { BoardStone btn = new BoardStone(i, j); boardPane.add(btn, i, j); board[i - 1][j - 1] = btn; } } } return boardPane; } private void enableKeyboardShortcuts(HBox topHBox) { topHBox.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { if (event.getEventType().equals(KeyEvent.KEY_PRESSED)) { if (event.getCode().equals(KeyCode.LEFT)) { handlePreviousPressed(); } else if (event.getCode().equals(KeyCode.RIGHT)) { handleNextPressed(); } else if (event.getCode().equals(KeyCode.DOWN)) { handleNextBranch(); } } } }); } public BoardStone[][] getBoard() { return this.board; } }
package com.toomasr.sgf4j.gui; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.toomasr.sgf4j.SGF4JApp; import com.toomasr.sgf4j.Sgf; import com.toomasr.sgf4j.SgfProperties; import com.toomasr.sgf4j.board.BoardCoordinateLabel; import com.toomasr.sgf4j.board.BoardSquare; import com.toomasr.sgf4j.board.GuiBoardListener; import com.toomasr.sgf4j.board.StoneState; import com.toomasr.sgf4j.board.VirtualBoard; import com.toomasr.sgf4j.filetree.FileTreeView; import com.toomasr.sgf4j.movetree.GameStartNoopStone; import com.toomasr.sgf4j.movetree.GlueStone; import com.toomasr.sgf4j.movetree.GlueStoneType; import com.toomasr.sgf4j.movetree.MoveTreeElement; import com.toomasr.sgf4j.movetree.TreeStone; import com.toomasr.sgf4j.parser.Game; import com.toomasr.sgf4j.parser.GameNode; import com.toomasr.sgf4j.parser.Util; import com.toomasr.sgf4j.properties.AppState; import com.toomasr.sgf4j.util.Encoding; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Bounds; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Control; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Priority; import javafx.scene.layout.StackPane; import javafx.scene.layout.TilePane; import javafx.scene.layout.VBox; import javafx.scene.text.Font; public class MainUI { private static final Logger logger = LoggerFactory.getLogger(MainUI.class); private Button nextButton; private GameNode currentMove = null; private GameNode prevMove = null; private Game game; private VirtualBoard virtualBoard; private BoardSquare[][] board; private GridPane movePane; private GridPane boardPane; private Map<GameNode, MoveTreeElement> nodeToTreeStone = new HashMap<>(); private List<MoveTreeElement> highlightedTreeStone = new ArrayList<>(); private TextArea commentArea; private Button previousButton; private ScrollPane treePaneScrollPane; private Label whitePlayerName; private Label blackPlayerName; private Label label; private TilePane buttonPane; private ScrollPane treePane; private VBox leftVBox; private VBox rightVBox; private SGF4JApp app; public MainUI(SGF4JApp app) { this.app = app; board = new BoardSquare[19][19]; virtualBoard = new VirtualBoard(); virtualBoard.addBoardListener(new GuiBoardListener(this)); } public Pane buildUI() throws Exception { Insets paneInsets = new Insets(5, 0, 0, 0); leftVBox = new VBox(5); leftVBox.setPadding(paneInsets); VBox centerVBox = new VBox(5); centerVBox.setPadding(paneInsets); rightVBox = new VBox(5); rightVBox.setPadding(paneInsets); // constructing the left box VBox fileTreePane = generateFileTreePane(); leftVBox.setMaxWidth(450); leftVBox.getChildren().addAll(fileTreePane); VBox.setVgrow(fileTreePane, Priority.ALWAYS); HBox.setHgrow(fileTreePane, Priority.SOMETIMES); // constructing the center box // centerVBox.setMaxWidth(640); centerVBox.setMinWidth(640); boardPane = new GridPane(); boardPane.setAlignment(Pos.BASELINE_CENTER); boardPane.setHgap(0.0); boardPane.setVgap(0.0); generateBoardPane(boardPane); buttonPane = generateButtonPane(); treePane = generateMoveTreePane(); centerVBox.getChildren().addAll(boardPane, buttonPane, treePane); VBox.setVgrow(boardPane, Priority.ALWAYS); HBox.setHgrow(boardPane, Priority.ALWAYS); VBox.setVgrow(treePane, Priority.ALWAYS); VBox.setVgrow(buttonPane, Priority.NEVER); // constructing the right box VBox gameMetaInfo = generateGameMetaInfo(); TextArea commentArea = generateCommentPane(); rightVBox.getChildren().addAll(gameMetaInfo, commentArea); rightVBox.setMaxWidth(450); VBox.setVgrow(commentArea, Priority.ALWAYS); // lets put everything into a rootbox! HBox rootHBox = new HBox(); enableKeyboardShortcuts(rootHBox); rootHBox.getChildren().addAll(leftVBox, centerVBox, rightVBox); HBox.setHgrow(centerVBox, Priority.ALWAYS); HBox.setHgrow(leftVBox, Priority.ALWAYS); HBox.setHgrow(rightVBox, Priority.SOMETIMES); MenuBar menuBar = buildTopMenu(); final String os = System.getProperty ("os.name"); if (os != null && os.startsWith ("Mac")) { menuBar.useSystemMenuBarProperty ().set (true); } VBox rootVbox = new VBox(menuBar); HBox statusBar = generateStatusBar(); rootVbox.getChildren().addAll(rootHBox, statusBar); VBox.setVgrow(rootHBox, Priority.ALWAYS); VBox.setVgrow(statusBar, Priority.NEVER); rootVbox.layoutBoundsProperty().addListener((observable, oldValue, newValue) -> { int newSize = resizeBoardPane(boardPane, oldValue, newValue); buttonPane.setPrefWidth(newSize * 21); treePane.setPrefWidth(newSize * 21); }); return rootVbox; } private MenuBar buildTopMenu() { MenuBar menuBar = new MenuBar(); Menu fileMenu = new Menu("File"); MenuItem restartUIMenuItem = new MenuItem("Restart UI"); restartUIMenuItem.setOnAction(e -> { System.out.println("Restarting UI"); app.scheduleRestartUI(); }); fileMenu.getItems().add(restartUIMenuItem); menuBar.getMenus().add(fileMenu); return menuBar; } private HBox generateStatusBar() { HBox rtrn = new HBox(); label = new Label("MainUI loaded"); rtrn.getChildren().add(label); return rtrn; } public void updateStatus(String update) { this.label.setText(update); } public void initGame() { String game = "src/main/resources/game.sgf"; Path path = Paths.get(game); // in development it is nice to have a game open on start if (path.toFile().exists()) { initializeGame(Paths.get(game)); } } private VBox generateGameMetaInfo() { VBox vbox = new VBox(); vbox.setMinWidth(250); GridPane pane = new GridPane(); Label blackPlayerLabel = new Label("Black:"); GridPane.setConstraints(blackPlayerLabel, 1, 0); blackPlayerName = new Label("Unknown"); GridPane.setConstraints(blackPlayerName, 2, 0); Label whitePlayerLabel = new Label("White:"); GridPane.setConstraints(whitePlayerLabel, 1, 1); whitePlayerName = new Label("Unknown"); GridPane.setConstraints(whitePlayerName, 2, 1); pane.getChildren().addAll(blackPlayerLabel, blackPlayerName, whitePlayerLabel, whitePlayerName); vbox.getChildren().add(pane); return vbox; } private TextArea generateCommentPane() { commentArea = new TextArea(); commentArea.setFocusTraversable(false); commentArea.setWrapText(true); commentArea.setPrefSize(300, 600); return commentArea; } private void initializeGame(Path pathToSgf) { Font font = Font.getDefault(); java.awt.Font awtFont = new java.awt.Font(font.getName(), java.awt.Font.PLAIN, (int) font.getSize()); String encoding = Encoding.determineEncoding(pathToSgf, awtFont); logger.debug("Determined encoding {}", encoding); updateStatus(String.format("Loaded %s with encoding %s", pathToSgf.getFileName(), encoding)); this.game = Sgf.createFromPath(pathToSgf, encoding); currentMove = this.game.getRootNode(); prevMove = null; // reset our virtual board and actual board virtualBoard = new VirtualBoard(); virtualBoard.addBoardListener(new GuiBoardListener(this)); initNewBoard(); // construct the tree of the moves nodeToTreeStone = new HashMap<>(); movePane.getChildren().clear(); GameStartNoopStone rootStone = new GameStartNoopStone(currentMove); movePane.add(rootStone, 0, 0); configureMoveTreeElement(currentMove, rootStone); highLightStoneInTree(currentMove); GameNode rootNode = game.getRootNode(); populateMoveTreePane(rootNode, 0); showMarkersForMove(rootNode); showCommentForMove(rootNode); showMetaInfoForGame(this.game); treePaneScrollPane.setHvalue(0); treePaneScrollPane.setVvalue(0); } private void showMetaInfoForGame(Game game) { String whiteRating = game.getProperty(SgfProperties.WHITE_PLAYER_RATING); String whiteLabel = game.getProperty(SgfProperties.WHITE_PLAYER_NAME); if (whiteRating != null) { whiteLabel = whiteLabel + " [" + whiteRating + "]"; } whitePlayerName.setText(whiteLabel); String blackRating = game.getProperty(SgfProperties.BLACK_PLAYER_RATING); String blackLabel = game.getProperty(SgfProperties.BLACK_PLAYER_NAME); if (blackRating != null) { blackLabel = blackLabel + " [" + blackRating + "]"; } blackPlayerName.setText(blackLabel); } public void initNewBoard() { generateBoardPane(boardPane); placePreGameStones(game); } private void placePreGameStones(Game game) { String blackStones = game.getProperty("AB", ""); String whiteStones = game.getProperty("AW", ""); placePlacementGameStones(blackStones, whiteStones); } private void placePlacementStones(GameNode node) { String blackStones = node.getProperty("AB", ""); String whiteStones = node.getProperty("AW", ""); placePlacementGameStones(blackStones, whiteStones); } private void placePlacementGameStones(String addBlack, String addWhite) { if (addBlack.length() > 0) { String[] blackStones = addBlack.split(","); // actually the stones can also contain not just points but sequences // of points so instead of a coordinate like dq, dr, ds it might contain // dq:ds. Let us translate those to actual single coordinates! if (addBlack.contains(":")) { blackStones = Util.coordSequencesToSingle(addBlack); } for (int i = 0; i < blackStones.length; i++) { int[] moveCoords = Util.alphaToCoords(blackStones[i]); virtualBoard.placeStone(StoneState.BLACK, moveCoords[0], moveCoords[1]); } } if (addWhite.length() > 0) { String[] whiteStones = addWhite.split(","); // actually the stones can also contain not just points but sequences // of points so instead of a coordinate like dq, dr, ds it might contain // dq:ds. Let us translate those to actual single coordinates! if (addWhite.contains(":")) { whiteStones = Util.coordSequencesToSingle(addWhite); } for (int i = 0; i < whiteStones.length; i++) { int[] moveCoords = Util.alphaToCoords(whiteStones[i]); virtualBoard.placeStone(StoneState.WHITE, moveCoords[0], moveCoords[1]); } } } private void removePreGameStones(GameNode node) { String blackStones = node.getProperty("AB", ""); String whiteStones = node.getProperty("AW", ""); removePlacementStones(blackStones, whiteStones); } private void removePlacementStones(String removeBlack, String removeWhite) { if (removeBlack.length() > 0) { String[] blackStones = removeBlack.split(","); for (int i = 0; i < blackStones.length; i++) { int[] moveCoords = Util.alphaToCoords(blackStones[i]); virtualBoard.removeStone(moveCoords[0], moveCoords[1]); } } if (removeWhite.length() > 0) { String[] whiteStones = removeWhite.split(","); for (int i = 0; i < whiteStones.length; i++) { int[] moveCoords = Util.alphaToCoords(whiteStones[i]); virtualBoard.removeStone(moveCoords[0], moveCoords[1]); } } } private void populateMoveTreePane(GameNode node, int depth) { // we draw out only actual moves if (node.isMove() || (node.getMoveNo() == -1 && node.getVisualDepth() > -1)) { MoveTreeElement treeStone = TreeStone.create(node); if (node.getMoveNo() == -1) { treeStone = new GameStartNoopStone(node); } movePane.add((StackPane) treeStone, node.getNodeNo(), node.getVisualDepth()); configureMoveTreeElement(node, treeStone); } // and recursively draw the next node on this line of play if (node.getNextNode() != null) { populateMoveTreePane(node.getNextNode(), depth + node.getVisualDepth()); } // populate the children also if (node.hasChildren()) { Set<GameNode> children = node.getChildren(); // will determine whether the glue stone should be a single // diagonal or a multiple (diagonal and vertical) GlueStoneType gStoneType = children.size() > 1 ? GlueStoneType.MULTIPLE : GlueStoneType.DIAGONAL; for (Iterator<GameNode> ite = children.iterator(); ite.hasNext();) { GameNode childNode = ite.next(); // the last glue shouldn't be a MULTIPLE if (GlueStoneType.MULTIPLE.equals(gStoneType) && !ite.hasNext()) { gStoneType = GlueStoneType.DIAGONAL; } // the visual lines can also be under a the first triangle int nodeVisualDepth = node.getVisualDepth(); int moveNo = node.getNodeNo(); if (moveNo == -1) { moveNo = 0; nodeVisualDepth = 0; } else if (nodeVisualDepth == -1) { nodeVisualDepth = 0; } // also draw all the "missing" glue stones for (int i = nodeVisualDepth + 1; i < childNode.getVisualDepth(); i++) { movePane.add(new GlueStone(GlueStoneType.VERTICAL), moveNo, i); } // glue stone for the node movePane.add(new GlueStone(gStoneType), moveNo, childNode.getVisualDepth()); // and recursively draw the actual node populateMoveTreePane(childNode, depth + childNode.getVisualDepth()); } } } private void configureMoveTreeElement(GameNode node, MoveTreeElement treeStone) { nodeToTreeStone.put(node, treeStone); ((StackPane) treeStone).addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { MoveTreeElement stone = (MoveTreeElement) event.getSource(); fastForwardTo(stone.getMove()); } }); } /* * Generates the boilerplate for the move tree pane. The * pane is actually populated during game initialization. */ private ScrollPane generateMoveTreePane() { movePane = new GridPane(); movePane.setPadding(new Insets(0, 0, 0, 0)); movePane.setStyle("-fx-background-color: white"); treePaneScrollPane = new ScrollPane(movePane); treePaneScrollPane.setPrefHeight(150); treePaneScrollPane.setHbarPolicy(ScrollBarPolicy.AS_NEEDED); treePaneScrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED); movePane.setMinWidth(640); movePane.setMaxWidth(Control.USE_PREF_SIZE); return treePaneScrollPane; } private void fastForwardTo(GameNode move) { // clear the board for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { board[i][j].removeStone(); } } placePreGameStones(game); deHighLightStoneInTree(); removeMarkersForNode(currentMove); if (move.getMoveNo() != -1) { virtualBoard.fastForwardTo(move); highLightStoneOnBoard(move); } else { virtualBoard.fastForwardTo(move); highLightStoneInTree(move); } } private VBox generateFileTreePane() { VBox vbox = new VBox(); vbox.setMinWidth(250); TreeView<File> treeView = new FileTreeView(); treeView.setFocusTraversable(false); Label label = new Label("Choose SGF File"); vbox.getChildren().addAll(label, treeView); VBox.setVgrow(treeView, Priority.ALWAYS); treeView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.getClickCount() == 2) { TreeItem<File> item = treeView.getSelectionModel().getSelectedItem(); File file = item.getValue().toPath().toFile(); if (file.isFile()) { initializeGame(item.getValue().toPath()); } AppState.getInstance().addProperty(AppState.CURRENT_FILE, file.getAbsolutePath()); } } }); return vbox; } private TilePane generateButtonPane() { TilePane pane = new TilePane(); pane.setAlignment(Pos.CENTER); pane.getStyleClass().add("bordered"); TextField moveNoField = new TextField("0"); moveNoField.setFocusTraversable(false); moveNoField.setMaxWidth(40); moveNoField.setEditable(false); nextButton = new Button("Next"); nextButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { handleNextPressed(); } }); previousButton = new Button("Previous"); previousButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { handlePreviousPressed(); } }); pane.setPrefColumns(1); pane.getChildren().add(previousButton); pane.getChildren().add(moveNoField); pane.getChildren().add(nextButton); pane.setMaxWidth(Control.USE_PREF_SIZE); return pane; } private void handleNextPressed() { if (currentMove.getNextNode() != null) { prevMove = currentMove; currentMove = currentMove.getNextNode(); virtualBoard.makeMove(currentMove, prevMove); // scroll the scrollpane to make // the highlighted move visible ensureVisibleForActiveTreeNode(currentMove); } } private void handleNextBranch() { if (currentMove.hasChildren()) { prevMove = currentMove; currentMove = currentMove.getChildren().iterator().next(); virtualBoard.makeMove(currentMove, prevMove); // scroll the scrollpane to make // the highlighted move visible ensureVisibleForActiveTreeNode(currentMove); } } public void handlePreviousPressed() { if (currentMove.getParentNode() != null) { prevMove = currentMove; currentMove = currentMove.getParentNode(); virtualBoard.undoMove(prevMove, currentMove); } } public void playMove(GameNode move, GameNode prevMove) { this.currentMove = move; this.prevMove = prevMove; // we actually have a previous move! if (prevMove != null) { // de-highlight previously highlighted move if (prevMove.isMove() && !prevMove.isPass()) { deHighLightStoneOnBoard(prevMove); } // even non moves can haver markers removeMarkersForNode(prevMove); } if (move != null && !move.isPass() && !move.isPlacementMove() && move.getMoveString() != null) { highLightStoneOnBoard(move); } // highlight stone in the tree pane deHighLightStoneInTree(); highLightStoneInTree(move); if (move != null && (move.getProperty("AB") != null || move.getProperty("AW") != null)) { placePlacementStones(move); } // show the associated comment showCommentForMove(move); // handle the prev and new markers showMarkersForMove(move); nextButton.requestFocus(); } public void undoMove(GameNode move, GameNode prevMove) { this.currentMove = prevMove; this.prevMove = move; if (move != null) { removeMarkersForNode(move); } if (prevMove != null) { showMarkersForMove(prevMove); showCommentForMove(prevMove); if (prevMove.isMove() && !prevMove.isPass()) highLightStoneOnBoard(prevMove); } removePreGameStones(move); deHighLightStoneInTree(); highLightStoneInTree(prevMove); ensureVisibleForActiveTreeNode(prevMove); // rather have previous move button have focus previousButton.requestFocus(); } private void ensureVisibleForActiveTreeNode(GameNode move) { if (move != null && move.isMove()) { StackPane stone = (StackPane) nodeToTreeStone.get(move); // the move tree is not yet fully operational and some // points don't exist in the map yet if (stone == null) return; double width = treePaneScrollPane.getContent().getBoundsInLocal().getWidth(); double x = stone.getBoundsInParent().getMaxX(); double scrollTo = ((x) - 11 * 30) / (width - 21 * 30); treePaneScrollPane.setHvalue(scrollTo); // adjust the vertical scroll double height = treePaneScrollPane.getContent().getBoundsInLocal().getHeight(); double y = stone.getBoundsInParent().getMaxY(); double scrollToY = y / height; if (move.getVisualDepth() == 0) { scrollToY = 0d; } treePaneScrollPane.setVvalue(scrollToY); } } private void highLightStoneInTree(GameNode move) { MoveTreeElement stone = nodeToTreeStone.get(move); // can remove the null check at one point when the // tree is fully implemented if (stone != null) { stone.highLight(); stone.requestFocus(); highlightedTreeStone.add(stone); } } private void deHighLightStoneInTree(GameNode node) { if (node != null && node.isMove()) { MoveTreeElement stone = nodeToTreeStone.get(node); if (stone != null) { stone.deHighLight(); } else { throw new RuntimeException("Unable to find node for move " + node); } } } private void deHighLightStoneInTree() { for (MoveTreeElement stone : highlightedTreeStone) { stone.deHighLight(); } highlightedTreeStone.clear(); } private void showCommentForMove(GameNode move) { String comment = move.getProperty("C"); if (comment == null) { if (move.getParentNode() == null && game.getProperty("C") != null) { comment = game.getProperty("C"); } else { comment = ""; } } // some helpers I used for parsing needs to be undone - see the Parser.java // in sgf4j project comment = comment.replaceAll("@@@@@", "\\\\\\["); comment = comment.replaceAll(" // lets do some replacing - see http://www.red-bean.com/sgf/sgf4.html#text comment = comment.replaceAll("\\\\\n", ""); comment = comment.replaceAll("\\\\:", ":"); comment = comment.replaceAll("\\\\\\]", "]"); comment = comment.replaceAll("\\\\\\[", "["); commentArea.setText(comment); } private void showMarkersForMove(GameNode move) { // the L property is actually not used in FF3 and FF4 // but I own many SGFs that still have it String markerProp = move.getProperty("L"); if (markerProp != null) { int alphaIdx = 0; String[] markers = markerProp.split("\\]\\["); for (int i = 0; i < markers.length; i++) { int[] coords = Util.alphaToCoords(markers[i]); board[coords[0]][coords[1]].addOverlayText(Util.alphabet[alphaIdx++]); } } // also handle the LB labels Map<String, String> labels = Util.extractLabels(move.getProperty("LB")); for (Iterator<Map.Entry<String, String>> ite = labels.entrySet().iterator(); ite.hasNext();) { Map.Entry<String, String> entry = ite.next(); int[] coords = Util.alphaToCoords(entry.getKey()); board[coords[0]][coords[1]].addOverlayText(entry.getValue()); } } private void removeMarkersForNode(GameNode node) { // the L property is actually not used in FF3 and FF4 // but I own many SGFs that still have it String markerProp = node.getProperty("L"); if (markerProp != null) { String[] markers = markerProp.split("\\]\\["); for (int i = 0; i < markers.length; i++) { int[] coords = Util.alphaToCoords(markers[i]); board[coords[0]][coords[1]].removeOverlayText(); } } // also handle the LB labels Map<String, String> labels = Util.extractLabels(node.getProperty("LB")); for (Iterator<Map.Entry<String, String>> ite = labels.entrySet().iterator(); ite.hasNext();) { Map.Entry<String, String> entry = ite.next(); int[] coords = Util.alphaToCoords(entry.getKey()); board[coords[0]][coords[1]].removeOverlayText(); } } private void highLightStoneOnBoard(GameNode move) { String currentMove = move.getMoveString(); int[] moveCoords = Util.alphaToCoords(currentMove); board[moveCoords[0]][moveCoords[1]].highLightStone(); } private void deHighLightStoneOnBoard(GameNode prevMove) { String prevMoveAsStr = prevMove.getMoveString(); int[] moveCoords = Util.alphaToCoords(prevMoveAsStr); board[moveCoords[0]][moveCoords[1]].deHighLightStone(); } private void generateBoardPane(GridPane boardPane) { boardPane.getChildren().clear(); for (int i = 0; i < 21; i++) { if (i > 1 && i < 20) { board[i - 1] = new BoardSquare[19]; } for (int j = 0; j < 21; j++) { if (i == 0 || j == 0 || i == 20 || j == 20) { BoardCoordinateLabel btn = new BoardCoordinateLabel(i, j); boardPane.add(btn, i, j); } else { BoardSquare btn = new BoardSquare(i, j); boardPane.add(btn, i, j); board[i - 1][j - 1] = btn; } } } } private int resizeBoardPane(GridPane boardPane, Bounds oldValue, Bounds newValue) { // I calculate the high because for some reason the // rightVBox and leftVBox in certain circumstances will // overflow the centerHBox - by subtracting from total // I'll get the visual width of the center box double width = newValue.getWidth() - leftVBox.getWidth() - rightVBox.getWidth(); double height = boardPane.getHeight(); // when resized super quickly with the mouse then // sometimes the width can become negative even // this is dumb but just in case lets have a minimum if (width < 650) { width = 650; } int newSize = (int) Math.floor(height / 21); if ((int) Math.floor(width / 21) < newSize) newSize = (int) Math.floor(width / 21); // anything less than 29 will look ugly with the // current code if (newSize < 29) { newSize = 29; } BoardSquare stone = (BoardSquare) boardPane.getChildren().get(23); // if size actually hasn't changed then no need to resize everything if (stone.getSize() == newSize) { return newSize; } for (int i = 0; i < 21 * 21; i++) { if ((i < 22 || i > 418 || i % 21 == 0 || (i + 1) % 21 == 0)) { BoardCoordinateLabel sq = (BoardCoordinateLabel) boardPane.getChildren().get(i); sq.resizeTo(newSize); } else { stone = (BoardSquare) boardPane.getChildren().get(i); stone.resizeTo(newSize); } } return newSize; } private void enableKeyboardShortcuts(HBox topHBox) { topHBox.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { if (event.getEventType().equals(KeyEvent.KEY_PRESSED)) { if (event.getCode().equals(KeyCode.LEFT)) { handlePreviousPressed(); } else if (event.getCode().equals(KeyCode.RIGHT)) { handleNextPressed(); } else if (event.getCode().equals(KeyCode.DOWN)) { handleNextBranch(); } } } }); } public BoardSquare[][] getBoard() { return this.board; } }
package com.vdurmont.semver4j; import java.util.Objects; public class Semver implements Comparable<Semver> { private final String originalValue; private final String value; private final Integer major; private final Integer minor; private final Integer patch; private final String[] suffixTokens; private final String build; private final SemverType type; public Semver(String value) { this(value, SemverType.STRICT); } public Semver(String value, SemverType type) { this.originalValue = value; this.type = type; value = value.trim(); if (type == SemverType.NPM && (value.startsWith("v") || value.startsWith("V"))) { value = value.substring(1).trim(); } this.value = value; String[] tokens = value.split("-"); String build = null; Integer minor = null; Integer patch = null; try { String[] mainTokens; if (tokens.length == 1) { // The build version may be in the main tokens if (tokens[0].endsWith("+")) { throw new SemverException("The build cannot be empty."); } String[] tmp = tokens[0].split("\\+"); mainTokens = tmp[0].split("\\."); if (tmp.length == 2) { build = tmp[1]; } } else { mainTokens = tokens[0].split("\\."); } try { this.major = Integer.valueOf(mainTokens[0]); } catch (NumberFormatException | IndexOutOfBoundsException e) { throw new SemverException("Invalid version (no major version): " + value); } try { minor = Integer.valueOf(mainTokens[1]); } catch (IndexOutOfBoundsException e) { if (type == SemverType.STRICT) { throw new SemverException("Invalid version (no minor version): " + value); } } catch (NumberFormatException e) { if (type != SemverType.NPM || (!"x".equalsIgnoreCase(mainTokens[1]) && !"*".equals(mainTokens[1]))) { throw new SemverException("Invalid version (no minor version): " + value); } } try { patch = Integer.valueOf(mainTokens[2]); } catch (IndexOutOfBoundsException e) { if (type == SemverType.STRICT) { throw new SemverException("Invalid version (no patch version): " + value); } } catch (NumberFormatException e) { if (type != SemverType.NPM || (!"x".equalsIgnoreCase(mainTokens[2]) && !"*".equals(mainTokens[2]))) { throw new SemverException("Invalid version (no patch version): " + value); } } } catch (NumberFormatException | IndexOutOfBoundsException e) { throw new SemverException("The version is invalid: " + value); } this.minor = minor; this.patch = patch; String[] suffix = new String[0]; try { // The build version may be in the suffix tokens if (tokens[1].endsWith("+")) { throw new SemverException("The build cannot be empty."); } String[] tmp = tokens[1].split("\\+"); if (tmp.length == 2) { suffix = tmp[0].split("\\."); build = tmp[1]; } else { suffix = tokens[1].split("\\."); } } catch (IndexOutOfBoundsException ignored) { } this.suffixTokens = suffix; this.build = build; this.validate(type); } private void validate(SemverType type) { if (this.minor == null && type == SemverType.STRICT) { throw new SemverException("Invalid version (no minor version): " + value); } if (this.patch == null && type == SemverType.STRICT) { throw new SemverException("Invalid version (no patch version): " + value); } } /** * Check if the version satisfies a requirement * * @param requirement the requirement * * @return true if the version satisfies the requirement */ public boolean satisfies(Requirement requirement) { return requirement.isSatisfiedBy(this); } /** * Check if the version satisfies a requirement * * @param requirement the requirement * * @return true if the version satisfies the requirement */ public boolean satisfies(String requirement) { Requirement req; switch (this.type) { case STRICT: req = Requirement.buildStrict(requirement); break; case LOOSE: req = Requirement.buildLoose(requirement); break; case NPM: req = Requirement.buildNPM(requirement); break; default: throw new SemverException("Invalid requirement type: " + type); } return this.satisfies(req); } /** * @see #isGreaterThan(Semver) */ public boolean isGreaterThan(String version) { return this.isGreaterThan(new Semver(version, this.getType())); } /** * Checks if the version is greater than another version * * @param version the version to compare * * @return true if the current version is greater than the provided version */ public boolean isGreaterThan(Semver version) { // Compare the main part if (this.getMajor() > version.getMajor()) return true; else if (this.getMajor() < version.getMajor()) return false; int otherMinor = version.getMinor() != null ? version.getMinor() : 0; if (this.getMinor() != null && this.getMinor() > otherMinor) return true; else if (this.getMinor() != null && this.getMinor() < otherMinor) return false; int otherPatch = version.getPatch() != null ? version.getPatch() : 0; if (this.getPatch() != null && this.getPatch() > otherPatch) return true; else if (this.getPatch() != null && this.getPatch() < otherPatch) return false; // Let's take a look at the suffix String[] tokens1 = this.getSuffixTokens(); String[] tokens2 = version.getSuffixTokens(); // If one of the versions has no suffix, it's greater! if (tokens1.length == 0 && tokens2.length > 0) return true; if (tokens2.length == 0 && tokens1.length > 0) return false; // Let's see if one of suffixes is greater than the other int i = 0; while (i < tokens1.length && i < tokens2.length) { int cmp; try { // Trying to resolve the suffix part with an integer int t1 = Integer.valueOf(tokens1[i]); int t2 = Integer.valueOf(tokens2[i]); cmp = t1 - t2; } catch (NumberFormatException e) { // Else, do a string comparison cmp = tokens1[i].compareToIgnoreCase(tokens2[i]); } if (cmp < 0) return false; else if (cmp > 0) return true; i++; } // If one of the versions has some remaining suffixes, it's greater return tokens1.length > tokens2.length; } /** * @see #isLowerThan(Semver) */ public boolean isLowerThan(String version) { return this.isLowerThan(new Semver(version)); } /** * Checks if the version is lower than another version * * @param version the version to compare * * @return true if the current version is lower than the provided version */ public boolean isLowerThan(Semver version) { return !this.isGreaterThan(version) && !this.isEquivalentTo(version); } /** * @see #isEquivalentTo(Semver) */ public boolean isEquivalentTo(String version) { return this.isEquivalentTo(new Semver(version)); } /** * Checks if the version equals another version, without taking the build into account. * * @param version the version to compare * * @return true if the current version equals the provided version (build excluded) */ public boolean isEquivalentTo(Semver version) { // Get versions without build Semver sem1 = this.getBuild() == null ? this : new Semver(this.getValue().replace("+" + this.getBuild(), "")); Semver sem2 = version.getBuild() == null ? version : new Semver(version.getValue().replace("+" + version.getBuild(), "")); // Compare those new versions return sem1.isEqualTo(sem2); } /** * @see #isEqualTo(Semver) */ public boolean isEqualTo(String version) { return this.isEqualTo(new Semver(version)); } /** * Checks if the version equals another version * * @param version the version to compare * * @return true if the current version equals the provided version */ public boolean isEqualTo(Semver version) { return this.equals(version); } /** * Determines if the current version is stable or not. * Stable version have a major version number strictly positive and no suffix tokens. * * @return true if the current version is stable */ public boolean isStable() { return (this.getMajor() != null && this.getMajor() > 0) && (this.getSuffixTokens() == null || this.getSuffixTokens().length == 0); } /** * @see #diff(Semver) */ public VersionDiff diff(String version) { return this.diff(new Semver(version)); } /** * Returns the greatest difference between 2 versions. * For example, if the current version is "1.2.3" and compared version is "1.3.0", the biggest difference * is the 'MINOR' number. * * @param version the version to compare * * @return the greatest difference */ public VersionDiff diff(Semver version) { if (!Objects.equals(this.major, version.getMajor())) return VersionDiff.MAJOR; if (!Objects.equals(this.minor, version.getMinor())) return VersionDiff.MINOR; if (!Objects.equals(this.patch, version.getPatch())) return VersionDiff.PATCH; if (!areSameSuffixes(version.getSuffixTokens())) return VersionDiff.SUFFIX; if (!Objects.equals(this.build, version.getBuild())) return VersionDiff.BUILD; return VersionDiff.NONE; } private boolean areSameSuffixes(String[] suffixTokens) { if (this.suffixTokens == null && suffixTokens == null) return true; else if (this.suffixTokens == null || suffixTokens == null) return false; else if (this.suffixTokens.length != suffixTokens.length) return false; for (int i = 0; i < this.suffixTokens.length; i++) { if (!this.suffixTokens[i].equals(suffixTokens[i])) return false; } return true; } public Semver withIncMajor() { return this.withIncMajor(1); } public Semver withIncMajor(int increment) { return this.withInc(increment, 0, 0); } public Semver withIncMinor() { return this.withIncMinor(1); } public Semver withIncMinor(int increment) { return this.withInc(0, increment, 0); } public Semver withIncPatch() { return this.withIncPatch(1); } public Semver withIncPatch(int increment) { return this.withInc(0, 0, increment); } private Semver withInc(int majorInc, int minorInc, int patchInc) { Integer minor = this.minor; Integer patch = this.patch; if (this.minor != null) { minor += minorInc; } if (this.patch != null) { patch += patchInc; } return with(this.major + majorInc, minor, patch, true, true); } public Semver withClearedSuffix() { return with(this.major, this.minor, this.patch, false, true); } public Semver withClearedBuild() { return with(this.major, this.minor, this.patch, true, false); } public Semver withClearedSuffixAndBuild() { return with(this.major, this.minor, this.patch, false, false); } public Semver nextMajor() { return with(this.major + 1, 0, 0, false, false); } public Semver nextMinor() { return with(this.major, this.minor + 1, 0, false, false); } public Semver nextPatch() { return with(this.major, this.minor, this.patch + 1, false, false); } private Semver with(int major, Integer minor, Integer patch, boolean suffix, boolean build) { StringBuilder sb = new StringBuilder() .append(major); if (this.minor != null) { sb.append(".").append(minor); } if (this.patch != null) { sb.append(".").append(patch); } if (suffix) { boolean first = true; for (String suffixToken : this.suffixTokens) { if (first) { sb.append("-"); first = false; } else { sb.append("."); } sb.append(suffixToken); } } if (this.build != null && build) { sb.append("+").append(this.build); } return new Semver(sb.toString(), this.type); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Semver)) return false; Semver version = (Semver) o; return value.equals(version.value); } @Override public int hashCode() { return value.hashCode(); } @Override public int compareTo(Semver version) { if (this.isGreaterThan(version)) return 1; else if (this.equals(version)) return 0; return -1; } @Override public String toString() { return "Semver(" + this.value + ")"; } /** * Get the original value as a string * * @return the original string passed in the constructor */ public String getOriginalValue() { return originalValue; } /** * Returns the version as a String * * @return the version as a String */ public String getValue() { return value; } /** * Returns the major part of the version. * Example: for "1.2.3" = 1 * * @return the major part of the version */ public Integer getMajor() { return this.major; } /** * Returns the minor part of the version. * Example: for "1.2.3" = 2 * * @return the minor part of the version */ public Integer getMinor() { return this.minor; } /** * Returns the patch part of the version. * Example: for "1.2.3" = 3 * * @return the patch part of the version */ public Integer getPatch() { return this.patch; } /** * Returns the suffix of the version. * Example: for "1.2.3-beta.4+sha98450956" = {"beta", "4"} * * @return the suffix of the version */ public String[] getSuffixTokens() { return suffixTokens; } /** * Returns the build of the version. * Example: for "1.2.3-beta.4+sha98450956" = "sha98450956" * * @return the build of the version */ public String getBuild() { return build; } public SemverType getType() { return type; } /** * The types of diffs between two versions. */ public enum VersionDiff { NONE, MAJOR, MINOR, PATCH, SUFFIX, BUILD } /** * The different types of supported version systems. */ public enum SemverType { /** * The default type of version. * Major, minor and patch parts are required. * Suffixes and build are optional. */ STRICT, /** * The default type of version. * Major part is required. * Minor, patch, suffixes and build are optional. */ LOOSE, NPM, COCOAPODS } }
package control; import data.Camera; import data.CameraShot; import data.DirectorShot; import data.Instrument; import data.Shot; import gui.centerarea.CameraShotBlock; import gui.centerarea.DirectorShotBlock; import gui.centerarea.ShotBlock; import gui.events.CameraShotBlockUpdatedEvent; import gui.headerarea.DetailView; import gui.headerarea.DirectorDetailView; import gui.misc.TweakingHelper; import gui.styling.StyledCheckbox; import gui.styling.StyledMenuButton; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.event.EventHandler; import javafx.scene.control.CustomMenuItem; import javafx.scene.input.KeyCode; import javafx.scene.input.MouseEvent; import lombok.Getter; import lombok.Setter; import lombok.extern.log4j.Log4j2; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Controller for the DetailView. */ @Log4j2 public class DetailViewController { @Getter private DetailView detailView; private ControllerManager manager; @Getter @Setter private DirectorShotBlock activeDirectorBlock; @Getter @Setter private CameraShotBlock activeCameraBlock; @Getter @Setter private List<StyledCheckbox> activeCameraBoxes; @Getter @Setter private List<StyledCheckbox> activeInstrumentBoxes; /** * Constructor. * * @param manager - the controller manager this controller belongs to */ public DetailViewController(ControllerManager manager) { this.detailView = manager.getRootPane().getRootHeaderArea().getDetailView(); this.manager = manager; initDescription(); initName(); initBeginCount(); initEndCount(); } /** * Re-init the tool view for when a camera block is selected. */ public void reInitForCameraBlock() { initDescription(); initName(); initBeginCount(); initEndCount(); initCameraInstrumentDropdown(); } /** * Re-init the tool view for when a director block is selected. */ public void reInitForDirectorBlock() { reInitForCameraBlock(); initBeginPadding(); initEndPadding(); initDirectorCameraDropdown(); } /** * Initialize the handlers for the begin padding field. */ private void initBeginPadding() { ((DirectorDetailView) detailView).getPaddingBeforeField() .focusedProperty().addListener(this::beforePaddingFocusListener); ((DirectorDetailView) detailView).getPaddingBeforeField().setOnKeyPressed(event -> { if (event.getCode().equals(KeyCode.ENTER)) { this.beforePaddingUpdateHelper(); } }); } /** * Listener for focus change on before padding field. * * @param observable the observable value * @param oldValue If there was an old value * @param newValue If there was a new value */ protected void beforePaddingFocusListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!newValue) { this.beforePaddingUpdateHelper(); } } /** * Update method for the before padding field. */ protected void beforePaddingUpdateHelper() { if (manager.getActiveShotBlock() != null) { String newValue = CountUtilities.parseCountNumber( ((DirectorDetailView) detailView).getPaddingBeforeField().getText()); ((DirectorDetailView) detailView).getPaddingBeforeField().setText(newValue); double newVal = Double.parseDouble(newValue); DirectorShotBlock directorShotBlock = ((DirectorShotBlock) manager.getActiveShotBlock()); directorShotBlock.setPaddingBefore(newVal); DirectorShot directorShot = ((DirectorShot) manager.getActiveShotBlock().getShot()); directorShot.setFrontShotPadding(newVal); directorShot.getCameraShots().forEach(e -> { CameraShotBlock shotBlock = manager.getTimelineControl().getShotBlockForShot(e); shotBlock.setBeginCount(directorShot.getBeginCount() - newVal, true); manager.getTimelineControl().modifyCameraShot( (CameraShotBlockUpdatedEvent) shotBlock.getShotBlockUpdatedEvent(), shotBlock); manager.setActiveShotBlock(directorShotBlock); }); manager.getTimelineControl().recomputeAllCollisions(); } } /** * Initialize the handlers for end padding field. */ private void initEndPadding() { ((DirectorDetailView) detailView).getPaddingAfterField().focusedProperty() .addListener(this::afterPaddingFocusListener); ((DirectorDetailView) detailView).getPaddingAfterField().setOnKeyPressed( event -> { if (event.getCode().equals(KeyCode.ENTER)) { this.afterPaddingUpdateHelper(); } }); } /** * Listener for focus change on end padding field. * * @param observable the observable value * @param oldValue if there is an old value * @param newValue if there is a new value */ protected void afterPaddingFocusListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (!newValue) { this.afterPaddingUpdateHelper(); } } /** * Update method for the after padding. */ protected void afterPaddingUpdateHelper() { if (manager.getActiveShotBlock() != null) { String newValue = CountUtilities.parseCountNumber( ((DirectorDetailView) detailView).getPaddingAfterField().getText()); ((DirectorDetailView) detailView).getPaddingAfterField().setText(newValue); double newVal = Double.parseDouble(newValue); DirectorShotBlock directorShotBlock = ((DirectorShotBlock) manager.getActiveShotBlock()); directorShotBlock.setPaddingAfter(newVal); ((DirectorShot) manager.getActiveShotBlock().getShot()).setEndShotPadding(newVal); ((DirectorShot) manager.getActiveShotBlock().getShot()).getCameraShots().forEach(e -> { CameraShotBlock shotBlock = manager.getTimelineControl().getShotBlockForShot(e); shotBlock.setEndCount(((DirectorShot) manager.getActiveShotBlock().getShot()) .getEndCount() + newVal, true); manager.getTimelineControl().modifyCameraShot( (CameraShotBlockUpdatedEvent) shotBlock.getShotBlockUpdatedEvent(), shotBlock); manager.setActiveShotBlock(directorShotBlock); }); manager.getTimelineControl().recomputeAllCollisions(); } } /** * Listener for changes in checked indices for instruments dropdown. * * @param c the change that happened */ protected void instrumentsDropdownChangeListener(ListChangeListener.Change c) { Shot shot = manager.getActiveShotBlock().getShot(); c.next(); if (c.wasAdded()) { instrumentAddedInDropdown((int) c.getAddedSubList().get(0)); } else { instrumentDeletedInDropdown((int) c.getRemoved().get(0)); } } /** * Handler for a unchecked index in instrument dropdown. * * @param index the index that got unchecked */ private void instrumentDeletedInDropdown(int index) { ShotBlock shotBlock = manager.getActiveShotBlock(); shotBlock.getInstruments().remove(manager.getScriptingProject().getInstruments() .get(index)); shotBlock.getShot().getInstruments().remove(manager.getScriptingProject() .getInstruments().get(index)); shotBlock.getTimetableBlock().removeInstrument(manager.getScriptingProject() .getInstruments().get(index)); shotBlock.recompute(); } /** * Handler for a checked index in instrument dropdown. * * @param index the index that got unchecked */ private void instrumentAddedInDropdown(int index) { ShotBlock shotBlock = manager.getActiveShotBlock(); shotBlock.getInstruments().add(manager.getScriptingProject().getInstruments().get(index)); shotBlock.getTimetableBlock().addInstrument(manager.getScriptingProject() .getInstruments().get(index)); shotBlock.recompute(); } /** * Change listener for the dropdown. Fires whenever a box is selected or deselected. * * @param c The Change with information about what changed. */ protected void camerasDropdownChangeListener(ListChangeListener.Change c) { DirectorShot shot = ((DirectorShot) manager.getActiveShotBlock().getShot()); c.next(); if (c.wasAdded()) { cameraAddedInDropdown((int) c.getAddedSubList().get(0)); } else { cameraDeletedInDropdown((int) c.getRemoved().get(0)); } } /** * Method for handling a deselect in the drop down. * * @param index the index of the deselected camera. */ private void cameraDeletedInDropdown(int index) { DirectorShotBlock dShotBlock = ((DirectorShotBlock) manager.getActiveShotBlock()); DirectorShot dShot = ((DirectorShot) manager.getActiveShotBlock().getShot()); Iterator<CameraShot> iterator = dShot.getCameraShots().iterator(); CameraShot toRemove = null; while (iterator.hasNext()) { CameraShot shot = iterator.next(); if (manager.getTimelineControl() .getShotBlockForShot(shot).getTimetableNumber() == index) { toRemove = shot; break; } } manager.getTimelineControl().removeCameraShot(toRemove); dShot.getCameraShots().remove(toRemove); dShot.getTimelineIndices().remove(index); manager.getTimelineControl().recomputeAllCollisions(); manager.getDirectorTimelineControl().recomputeAllCollisions(); } /** * Method for handling a select in the dropdown. * * @param index the index of the camera that was selected. */ private void cameraAddedInDropdown(int index) { CameraShot shot = new CameraShot(); DirectorShot dShot = ((DirectorShot) manager.getActiveShotBlock().getShot()); // Set shot variables shot.setName(dShot.getName()); shot.setDescription(dShot.getDescription()); shot.setBeginCount(dShot.getBeginCount() - dShot.getFrontShotPadding()); shot.setEndCount(dShot.getEndCount() + dShot.getEndShotPadding()); shot.setDirectorShot(dShot); // Add shot where needed dShot.getCameraShots().add(shot); dShot.getTimelineIndices().add(index); DirectorShotBlock dShotBlock = ((DirectorShotBlock) manager.getActiveShotBlock()); manager.getScriptingProject().getCameraTimelines().get(index).addShot(shot); manager.getTimelineControl().initShotBlock(index, shot, false); manager.setActiveShotBlock(dShotBlock); manager.getTimelineControl().recomputeAllCollisions(); manager.getDirectorTimelineControl().recomputeAllCollisions(); } /** * Init the begincount handlers. */ private void initBeginCount() { detailView.getBeginCountField().focusedProperty() .addListener(this::beginCountFocusListener); detailView.getBeginCountField().setOnKeyPressed( event -> { if (event.getCode().equals(KeyCode.ENTER)) { this.beginCountUpdateHelper(); } }); } /** * Changelistener for when focus on begincountfield changes. * * @param observable - the observable * @param oldValue - the old value of focus * @param newValue - the new value of focus */ void beginCountFocusListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { // exiting focus if (!newValue) { this.beginCountUpdateHelper(); } } /** * Helper for when the begincount field is edited. * Parses entry to quarters and updates all the values */ void beginCountUpdateHelper() { if (manager.getActiveShotBlock() != null) { String newValue = CountUtilities.parseCountNumber( detailView.getBeginCountField().getText()); detailView.getBeginCountField().setText(newValue); double newVal = Double.parseDouble(newValue); manager.getActiveShotBlock().setBeginCount(newVal); manager.getActiveShotBlock().getShot().setBeginCount(newVal); } } /** * Init the endcuont handlers. */ private void initEndCount() { detailView.getEndCountField().focusedProperty() .addListener(this::endCountFocusListener); detailView.getEndCountField().setOnKeyPressed( event -> { if (event.getCode().equals(KeyCode.ENTER)) { endCountUpdateHelper(); } }); } /** * Changelistener for when focus on endcountfield changes. * * @param observable - the observable * @param oldValue - the old value of focus * @param newValue - the new value of focus */ void endCountFocusListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { // exiting focus if (!newValue) { this.endCountUpdateHelper(); } } /** * Helper for when the endcount field is edited. * Parses entry to quarters and updates all the values */ private void endCountUpdateHelper() { if (manager.getActiveShotBlock() != null) { String newValue = CountUtilities.parseCountNumber( detailView.getEndCountField().getText()); double newVal = Double.parseDouble(newValue); detailView.getEndCountField().setText(newValue); manager.getActiveShotBlock().setEndCount(newVal); manager.getActiveShotBlock().getShot().setEndCount(newVal); } } /** * Init the description handlers. */ private void initDescription() { detailView.getDescriptionField().textProperty() .addListener(this::descriptionTextChangedListener); } /** * Changelistener for when the text in descriptionfield changes. * * @param observable - the observable * @param oldValue - the old value of the field * @param newValue - the new value of the field */ void descriptionTextChangedListener(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (manager.getActiveShotBlock() != null) { manager.getActiveShotBlock().setDescription(newValue); manager.getActiveShotBlock().getShot().setDescription(newValue); } } /** * Init the name handler. */ private void initName() { detailView.getNameField().textProperty() .addListener(this::nameTextChangedListener); } /** * Changelistener for when the text in namefield changes. * * @param observable - the observable * @param oldValue - the old value of the field * @param newValue - the new value of the field */ void nameTextChangedListener(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (manager.getActiveShotBlock() != null) { manager.getActiveShotBlock().setName(newValue); manager.getActiveShotBlock().getShot().setName(newValue); } } /** * Method to signal that the active block is changed so we can update it. */ public void activeBlockChanged() { if (manager.getActiveShotBlock() != null) { if (manager.getActiveShotBlock() instanceof CameraShotBlock) { activeBlockChangedCamera(); } else { activeBlockChangedDirector(); } } else { detailView.resetDetails(); detailView.setInvisible(); } } /** * Handler for when the active block is now a camera shot. */ private void activeBlockChangedCamera() { detailView = new DetailView(); detailView.setDescription(manager.getActiveShotBlock().getDescription()); detailView.setName(manager.getActiveShotBlock().getName()); detailView.setBeginCount(manager.getActiveShotBlock().getBeginCount()); detailView.setEndCount(manager.getActiveShotBlock().getEndCount()); activeCameraBlock = (CameraShotBlock) manager.getActiveShotBlock(); detailView.setVisible(); // Re-init the detail view with new data manager.getRootPane().getRootHeaderArea().reInitHeaderBar(detailView); this.reInitForCameraBlock(); } /** * Handler for when the active block is now a director shot. */ private void activeBlockChangedDirector() { DirectorShotBlock shotBlock = (DirectorShotBlock) manager.getActiveShotBlock(); detailView = new DirectorDetailView(); // Set detail view variables detailView.setDescription(shotBlock.getDescription()); detailView.setName(shotBlock.getName()); detailView.setBeginCount(shotBlock.getBeginCount()); detailView.setEndCount(shotBlock.getEndCount()); ((DirectorDetailView) detailView).getPaddingBeforeField() .setText(detailView.formatDouble(shotBlock.getPaddingBefore())); ((DirectorDetailView) detailView).getPaddingAfterField() .setText(detailView.formatDouble(shotBlock.getPaddingAfter())); activeDirectorBlock = shotBlock; detailView.setVisible(); // Re-init the detail view with new data manager.getRootPane().getRootHeaderArea().reInitHeaderBar(detailView); this.reInitForDirectorBlock(); } /** * Initialize drop down menu for director camera selection. */ private void initDirectorCameraDropdown() { StyledMenuButton cameraButtons = ((DirectorDetailView) detailView).getSelectCamerasButton(); cameraButtons.setBorderColor(TweakingHelper.getColor(0)); cameraButtons.setFillColor(TweakingHelper.getBackgroundColor()); activeCameraBoxes = new ArrayList<>(); cameraButtons.showingProperty().addListener((observable, oldValue, newValue) -> cameraDropdownListener(observable, oldValue, newValue, cameraButtons)); } /** * Initialize drop down menu for camera instrument selection. */ private void initCameraInstrumentDropdown() { StyledMenuButton instrumentsButtons = ((DetailView) detailView).getSelectInstrumentsButton(); instrumentsButtons.setBorderColor(TweakingHelper.getColor(0)); instrumentsButtons.setFillColor(TweakingHelper.getBackgroundColor()); activeInstrumentBoxes = new ArrayList<>(); instrumentsButtons.showingProperty().addListener((observable, oldValue, newValue) -> instrumentsDropdownListener(observable, oldValue, newValue, instrumentsButtons)); } /** * Creates ChangeListener for the Instruments Dropdown checkboxes. * * @param observable - the observable * @param oldValue - the old value * @param newValue - the new value * @param buttons - the buttons */ protected void instrumentsDropdownListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue, StyledMenuButton buttons) { if (newValue) { // show the list and give it content instrumentsDropdownListenerHelper(buttons); } else { // empty the list when not shown activeInstrumentBoxes.clear(); buttons.getItems().clear(); } } /** * Creates ChangeListener for the Camera Dropdown checkboxes. * @param observable - the observable * @param oldValue - the old value * @param newValue - the new avlue * @param buttons - the buttons */ protected void cameraDropdownListener(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue, StyledMenuButton buttons) { if (newValue) { // show the list and give it content cameraDropdownListenerHelper(buttons); } else { // empty the list when not shown activeCameraBoxes.clear(); buttons.getItems().clear(); } } /** * Helper method for showing the Camera Dropdown. * * @param buttons the dropdown menu containing buttons. */ private void cameraDropdownListenerHelper(StyledMenuButton buttons) { // loop thourhgh all cameras for the active director block, when the list is shown Set<Integer> indices = activeDirectorBlock.getTimelineIndices(); for (int i = 0; i < manager.getScriptingProject().getCameras().size(); i++) { Camera camera = manager.getScriptingProject().getCameras().get(i); // create and add checkbox for camera with on/off toggling loaded in. StyledCheckbox checkbox = getStyledCheckbox(camera.getName(), indices.contains(i)); activeCameraBoxes.add(checkbox); CustomMenuItem item = new CustomMenuItem(checkbox); item.setHideOnClick(false); buttons.getItems().add(item); // add event handler for mouse clicks on the checkbox checkbox.setOnMouseClicked(createCameraDropdownHandler(checkbox, i)); } } /** * Helper method for showing the Instruments Dropdown. * * @param buttons the dropdown menu containing buttons. */ private void instrumentsDropdownListenerHelper(StyledMenuButton buttons) { // loop thourhgh all instruments for the active block, when the list is shown List<Instrument> instruments = activeCameraBlock.getInstruments(); for (int i = 0; i < manager.getScriptingProject().getInstruments().size(); i++) { Instrument instrument = manager.getScriptingProject() .getInstruments().get(i); // create and add checkbox for instrument with on/off toggling loaded in. StyledCheckbox checkbox = getStyledCheckbox(instrument.getName(), instruments.contains(instrument)); activeInstrumentBoxes.add(checkbox); CustomMenuItem item = new CustomMenuItem(checkbox); item.setHideOnClick(false); buttons.getItems().add(item); // add event handler for mouse clicks on the checkbox checkbox.setOnMouseClicked(createInstrumentDropdownHandler(checkbox, i)); } } protected StyledCheckbox getStyledCheckbox(String name, Boolean checked) { return new StyledCheckbox(name, checked); } /** * Event handler for when a checkbox in the camera dropdown is clicked. * * @param box the checkbox that was clicked. * @param i index of the checkbox. * @return the Event Handler. */ private EventHandler<MouseEvent> createCameraDropdownHandler(StyledCheckbox box, int i) { return e -> { if (box.isSelected()) { cameraAddedInDropdown(i); } else { cameraDeletedInDropdown(i); } }; } /** * Event handler for when a checkbox in the instruments dropdown is clicked. * * @param box the checkbox that was clicked. * @param i index of the checkbox. * @return the Event Handler. */ private EventHandler<MouseEvent> createInstrumentDropdownHandler(StyledCheckbox box, int i) { return e -> { if (box.isSelected()) { instrumentAddedInDropdown(i); } else { instrumentDeletedInDropdown(i); } }; } }
package coyote.commons.csv; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import coyote.commons.cli.ArgumentException; /** * A CSV parser which splits a single line into fields using a field delimiter. */ public class CSVParser { private final char _separator; private final char _quotechar; private final char _escape; private final boolean _usestrictquotes; private String _pending; private boolean _isinfield = false; private final boolean _ignoreleadingwhitespace; /** The default separator to use if none is supplied to the constructor. */ public static final char SEPARATOR = ','; public static final int INITIAL_READ_SIZE = 128; /** The default quote character to use if none is supplied to the constructor. */ public static final char QUOTE_CHARACTER = '"'; /** The default escape character to use if none is supplied to the constructor. */ public static final char ESCAPE_CHARACTER = '\\'; /** The default strict quote behavior to use if none is supplied to the constructor */ public static final boolean STRICT_QUOTES = false; /** The default leading whitespace behavior to use if none is supplied to the constructor */ public static final boolean IGNORE_LEADING_WHITESPACE = true; /** This is the "null" character - if a value is set to this then it is ignored. I.E. if the quote character is set to null then there is no quote character. */ public static final char NULL_CHARACTER = '\0'; /** * Constructs CSVParser. */ public CSVParser() { this( SEPARATOR, QUOTE_CHARACTER, ESCAPE_CHARACTER ); } /** * Constructs CSVParser. * * @param separator the delimiter to use for separating entries. */ public CSVParser( final char separator ) { this( separator, QUOTE_CHARACTER, ESCAPE_CHARACTER ); } /** * Constructs CSVParser. * * @param separator the delimiter to use for separating entries * @param quotechar the character to use for quoted elements */ public CSVParser( final char separator, final char quotechar ) { this( separator, quotechar, ESCAPE_CHARACTER ); } /** * Constructs CSVParser. * * @param separator the delimiter to use for separating entries * @param quotechar the character to use for quoted elements * @param escape the character to use for escaping a separator or quote */ public CSVParser( final char separator, final char quotechar, final char escape ) { this( separator, quotechar, escape, STRICT_QUOTES ); } /** * Constructs CSVParser. * * @param separator the delimiter to use for separating entries * @param quotechar the character to use for quoted elements * @param escape the character to use for escaping a separator or quote * @param strictQuotes if true, characters outside the quotes are ignored */ public CSVParser( final char separator, final char quotechar, final char escape, final boolean strictQuotes ) { this( separator, quotechar, escape, strictQuotes, IGNORE_LEADING_WHITESPACE ); } /** * Constructs CSVParser. * * @param separator the delimiter to use for separating entries * @param quotechar the character to use for quoted elements * @param escape the character to use for escaping a separator or quote * @param strictQuotes if true, characters outside the quotes are ignored * @param ignoreLeadingWhiteSpace if true, white space in front of a quote in a field is ignored */ public CSVParser( final char separator, final char quotechar, final char escape, final boolean strictQuotes, final boolean ignoreLeadingWhiteSpace ) { if ( anyCharactersAreTheSame( separator, quotechar, escape ) ) { throw new UnsupportedOperationException( "The separator, quote, and escape characters must be different!" ); } if ( separator == NULL_CHARACTER ) { throw new UnsupportedOperationException( "The separator character must be defined!" ); } this._separator = separator; this._quotechar = quotechar; this._escape = escape; this._usestrictquotes = strictQuotes; this._ignoreleadingwhitespace = ignoreLeadingWhiteSpace; } public String[] parseLineMulti( final String nextLine ) throws ParseException { return parseLine( nextLine, true ); } public String[] parseLine( final String nextLine ) throws ParseException { return parseLine( nextLine, false ); } /** * Parses an incoming String and returns an array of elements. * * @param nextLine the string to parse * @param multi support multiple lines in values * * @return the comma delimited list of elements, or null if nextLine is null * * @throws ArgumentException Un-terminated quoted field at end of CSV line */ private String[] parseLine( final String nextLine, final boolean multi ) throws ParseException { if ( !multi && ( _pending != null ) ) { _pending = null; } if ( nextLine == null ) { if ( _pending != null ) { final String s = _pending; _pending = null; return new String[] { s }; } else { return null; } } final List<String> tokensOnThisLine = new ArrayList<String>(); StringBuilder sb = new StringBuilder( INITIAL_READ_SIZE ); boolean inQuotes = false; if ( _pending != null ) { sb.append( _pending ); _pending = null; inQuotes = true; } for ( int i = 0; i < nextLine.length(); i++ ) { final char c = nextLine.charAt( i ); if ( c == this._escape ) { if ( isNextCharacterEscapable( nextLine, inQuotes || _isinfield, i ) ) { sb.append( nextLine.charAt( i + 1 ) ); i++; } } else if ( c == _quotechar ) { if ( isNextCharacterEscapedQuote( nextLine, inQuotes || _isinfield, i ) ) { sb.append( nextLine.charAt( i + 1 ) ); i++; } else { if ( !_usestrictquotes ) { if ( ( i > 2 ) && ( nextLine.charAt( i - 1 ) != this._separator ) && ( nextLine.length() > ( i + 1 ) ) && ( nextLine.charAt( i + 1 ) != this._separator ) ) { if ( _ignoreleadingwhitespace && ( sb.length() > 0 ) && isAllWhiteSpace( sb ) ) { sb.setLength( 0 ); } else { sb.append( c ); } } } inQuotes = !inQuotes; } _isinfield = !_isinfield; } else if ( ( c == _separator ) && !inQuotes ) { tokensOnThisLine.add( sb.toString() ); sb.setLength( 0 ); _isinfield = false; } else { if ( !_usestrictquotes || inQuotes ) { sb.append( c ); _isinfield = true; } } } if ( inQuotes ) { if ( multi ) { sb.append( "\n" ); _pending = sb.toString(); sb = null; } else { throw new ParseException( "Un-terminated quoted field at end of CSV line", -1 ); } } if ( sb != null ) { tokensOnThisLine.add( sb.toString() ); } return tokensOnThisLine.toArray( new String[tokensOnThisLine.size()] ); } /** * precondition: the current character is a quote or an escape * * @param nextLine the current line * @param inQuotes true if the current context is quoted * @param i current index in line * * @return true if the following character is a quote */ private boolean isNextCharacterEscapedQuote( final String nextLine, final boolean inQuotes, final int i ) { return inQuotes && ( nextLine.length() > ( i + 1 ) ) && ( nextLine.charAt( i + 1 ) == _quotechar ); } /** * precondition: the current character is an escape * * @param nextLine the current line * @param inQuotes true if the current context is quoted * @param i current index in line * * @return true if the following character is a quote */ protected boolean isNextCharacterEscapable( final String nextLine, final boolean inQuotes, final int i ) { return inQuotes && ( nextLine.length() > ( i + 1 ) ) && ( ( nextLine.charAt( i + 1 ) == _quotechar ) || ( nextLine.charAt( i + 1 ) == this._escape ) ); } /** * @return true if something was left over from last call(s) */ boolean isPending() { return _pending != null; } /** * precondition: sb.length() > 0 * * @param cs A sequence of characters to examine * * @return true if every character in the sequence is whitespace */ protected boolean isAllWhiteSpace( final CharSequence cs ) { final boolean result = true; for ( int i = 0; i < cs.length(); i++ ) { final char c = cs.charAt( i ); if ( !Character.isWhitespace( c ) ) { return false; } } return result; } private boolean anyCharactersAreTheSame( final char separator, final char quotechar, final char escape ) { return isSameCharacter( separator, quotechar ) || isSameCharacter( separator, escape ) || isSameCharacter( quotechar, escape ); } private boolean isSameCharacter( final char c1, final char c2 ) { return ( c1 != NULL_CHARACTER ) && ( c1 == c2 ); } }
package de.prob2.ui.consoles; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import java.util.stream.Collectors; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.control.IndexRange; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCombination; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseButton; import javafx.scene.input.TransferMode; import org.fxmisc.richtext.StyleClassedTextArea; import org.fxmisc.wellbehaved.event.EventPattern; import org.fxmisc.wellbehaved.event.InputMap; import org.fxmisc.wellbehaved.event.Nodes; public abstract class Console extends StyleClassedTextArea { public static class ConfigData { private List<String> instructions; private String text; private List<int[]> errorRanges; protected ConfigData() {} } private static final Set<KeyCode> REST = EnumSet.of(KeyCode.ESCAPE, KeyCode.SCROLL_LOCK, KeyCode.PAUSE, KeyCode.NUM_LOCK, KeyCode.INSERT, KeyCode.CONTEXT_MENU, KeyCode.CAPS, KeyCode.TAB, KeyCode.ALT); private final ResourceBundle bundle; private final List<ConsoleInstruction> instructions; protected int charCounterInLine = 0; protected int currentPosInLine = 0; protected int posInList = -1; private final ConsoleSearchHandler searchHandler; private final List<IndexRange> errors; private final Executable interpreter; private final String header; private final StringProperty prompt; protected Console(ResourceBundle bundle, String header, String prompt, Executable interpreter) { this.bundle = bundle; this.instructions = new ArrayList<>(); this.searchHandler = new ConsoleSearchHandler(this, bundle); this.errors = new ArrayList<>(); this.interpreter = interpreter; this.header = header; this.prompt = new SimpleStringProperty(this, "prompt", prompt); this.requestFollowCaret(); setEvents(); setDragDrop(); this.reset(); this.setWrapText(true); this.getStyleClass().add("console"); this.promptProperty().addListener((o, from, to) -> this.replace(this.getLineNumber(), 0, this.getLineNumber(), from.length(), to, this.getStyleAtPosition(this.getLineNumber(), 0))); } public void setEvents() { Nodes.addInputMap(this, InputMap.consume(EventPattern.mouseClicked(MouseButton.PRIMARY), e -> this.mouseClicked())); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(), this::keyPressed)); // GUI-style shortcuts, these should use the Shortcut key (i. e. Command on Mac, Control on other systems). Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.C, KeyCombination.SHORTCUT_DOWN), e-> this.copy())); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.V, KeyCombination.SHORTCUT_DOWN), e-> this.paste())); // Shell/Emacs-style shortcuts, these should always use Control as the modifier, even on Mac (this is how it works in a normal terminal window). Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.R, KeyCombination.CONTROL_DOWN), e-> this.controlR())); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.A, KeyCombination.CONTROL_DOWN), e-> this.controlA())); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.E, KeyCombination.CONTROL_DOWN), e-> this.controlE())); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.K, KeyCombination.CONTROL_DOWN), e-> this.reset())); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.UP), e-> this.handleUp())); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.DOWN), e-> this.handleDown())); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.LEFT), e-> this.handleLeft())); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.RIGHT), e-> this.handleRight())); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.DELETE), this::handleDeletion)); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.BACK_SPACE), this::handleDeletion)); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.ENTER, KeyCombination.SHIFT_DOWN), KeyEvent::consume)); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.ESCAPE, KeyCombination.SHIFT_DOWN), KeyEvent::consume)); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.ENTER, KeyCombination.ALT_DOWN), KeyEvent::consume)); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.BACK_SPACE, KeyCombination.ALT_DOWN), KeyEvent::consume)); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.DELETE, KeyCombination.ALT_DOWN), KeyEvent::consume)); Nodes.addInputMap(this, InputMap.consume(EventPattern.keyPressed(KeyCode.ENTER), e-> this.handleEnter())); } private void setDragDrop() { this.setOnDragOver(e-> { Dragboard dragboard = e.getDragboard(); if (dragboard.hasFiles()) { e.acceptTransferModes(TransferMode.COPY); } else { e.consume(); } }); this.setOnDragDropped(e-> { Dragboard dragboard = e.getDragboard(); boolean success = false; if (dragboard.hasFiles() && this.getCaretPosition() >= this.getInputStart()) { success = true; for (File file : dragboard.getFiles()) { String path = file.getAbsolutePath(); int caretPosition = this.getCaretPosition(); this.insertText(this.getCaretPosition(), path); charCounterInLine += path.length(); currentPosInLine += path.length(); this.moveTo(caretPosition + path.length()); } } e.setDropCompleted(success); e.consume(); }); } @Override public void paste() { if (searchHandler.isActive()) { return; } if (this.getLength() - 1 - this.getCaretPosition() >= charCounterInLine) { goToLastPos(); } final int oldLength = this.getLength(); super.paste(); final int diff = this.getLength() - oldLength; charCounterInLine += diff; currentPosInLine += diff; } @Override public void copy() { super.copy(); goToLastPos(); } private void mouseClicked() { if (this.getLength() - 1 - this.getCaretPosition() < charCounterInLine) { currentPosInLine = charCounterInLine - (this.getLength() - this.getCaretPosition()); } } public void controlR() { if (searchHandler.isActive()) { searchHandler.searchNext(); } else { activateSearch(); } } protected void keyPressed(KeyEvent e) { if (REST.contains(e.getCode())) { return; } if (!e.getCode().isFunctionKey() && !e.getCode().isMediaKey() && !e.getCode().isModifierKey()) { handleInsertChar(e); } } private void handleInsertChar(KeyEvent e) { if (this.getLength() - this.getCaretPosition() > charCounterInLine) { goToLastPos(); } if (e.isControlDown() || e.isMetaDown() || e.getText().isEmpty()) { return; } charCounterInLine++; currentPosInLine++; posInList = instructions.size() - 1; searchHandler.handleKey(e); } private void controlA() { if (!searchHandler.isActive()) { this.moveTo(this.getCaretPosition() - currentPosInLine); currentPosInLine = 0; } } private void controlE() { if (!searchHandler.isActive()) { this.moveTo(this.getLength()); currentPosInLine = charCounterInLine; } } protected void activateSearch() { final String input = this.getInput(); this.deleteText(getLineNumber(), 0, getLineNumber(), this.getParagraphLength(getLineNumber())); this.appendText(String.format(bundle.getString("consoles.prompt.backwardSearch"), "", input)); this.moveTo(getLineNumber(), this.getLine().lastIndexOf('\'')); currentPosInLine = 0; charCounterInLine = 0; searchHandler.activateSearch(); } protected void deactivateSearch() { if (searchHandler.isActive()) { String searchResult = searchHandler.getCurrentSearchResult(); this.deleteText(getLineNumber(), 0, getLineNumber(), this.getParagraphLength(getLineNumber())); this.appendText(prompt.get() + searchResult); this.moveTo(this.getLength()); charCounterInLine = searchResult.length(); currentPosInLine = charCounterInLine; searchHandler.deactivateSearch(); } } private void goToLastPos() { this.moveTo(this.getLength()); deselect(); currentPosInLine = charCounterInLine; } public void reset() { this.errors.clear(); this.replaceText(header + '\n' + prompt.get()); } protected void handleEnter() { charCounterInLine = 0; currentPosInLine = 0; final String currentLine; if (searchHandler.isActive()) { currentLine = searchHandler.getCurrentSearchResult(); } else { currentLine = this.getInput(); } if (!currentLine.isEmpty()) { if (!instructions.isEmpty() && instructions.get(instructions.size() - 1).getOption() != ConsoleInstructionOption.ENTER) { instructions.set(instructions.size() - 1, new ConsoleInstruction(currentLine, ConsoleInstructionOption.ENTER)); } else { instructions.add(new ConsoleInstruction(currentLine, ConsoleInstructionOption.ENTER)); } posInList = instructions.size() - 1; ConsoleInstruction instruction = instructions.get(posInList); ConsoleExecResult execResult = interpreter.exec(instruction); if (execResult.getResultType() == ConsoleExecResultType.CLEAR) { reset(); return; } this.appendText("\n" + execResult); if (execResult.getResultType() == ConsoleExecResultType.ERROR) { final int begin = this.getAbsolutePosition(getLineNumber(), 0); final int end = this.getLength(); this.setStyle(getLineNumber(), Collections.singletonList("error")); errors.add(new IndexRange(begin, end)); } } searchHandler.handleEnter(); this.appendText('\n' + prompt.get()); this.setStyle(getLineNumber(), Collections.singletonList("current")); this.scrollYToPixel(Double.MAX_VALUE); goToLastPos(); } private void handleDown() { deactivateSearch(); if (instructions.isEmpty() || posInList == instructions.size() - 1) { return; } posInList = Math.min(posInList+1, instructions.size() - 1); setTextAfterArrowKey(); } private void handleUp() { deactivateSearch(); if (instructions.isEmpty() || posInList == -1) { return; } if (posInList == instructions.size() - 1) { String lastinstruction = instructions.get(instructions.size()-1).getInstruction(); if (!lastinstruction.equals(this.getInput()) && posInList == instructions.size() - 1) { if (instructions.get(posInList).getOption() == ConsoleInstructionOption.UP) { instructions.set(instructions.size() - 1, new ConsoleInstruction(this.getInput(), ConsoleInstructionOption.UP)); } else { instructions.add(new ConsoleInstruction(this.getInput(), ConsoleInstructionOption.UP)); setTextAfterArrowKey(); return; } } } posInList = Math.max(posInList - 1, 0); setTextAfterArrowKey(); } private void handleLeft() { deactivateSearch(); if (currentPosInLine > 0 && this.getLength() - this.getCaretPosition() <= charCounterInLine) { currentPosInLine this.moveTo(this.getCaretPosition() - 1); } else if (currentPosInLine == 0) { super.deselect(); } } private void handleRight() { deactivateSearch(); if (currentPosInLine < charCounterInLine && this.getLength() - this.getCaretPosition() <= charCounterInLine) { currentPosInLine++; this.moveTo(this.getCaretPosition() + 1); } } private void setTextAfterArrowKey() { String currentLine = instructions.get(posInList).getInstruction(); this.deleteText(this.getInputStart(), this.getLength()); this.appendText(currentLine); charCounterInLine = currentLine.length(); currentPosInLine = charCounterInLine; this.scrollYToPixel(Double.MAX_VALUE); } private void handleDeletion(KeyEvent e) { int maxPosInLine = charCounterInLine; if (searchHandler.handleDeletion(e)) { return; } if (searchHandler.isActive()) { maxPosInLine = charCounterInLine + 2 + searchHandler.getCurrentSearchResult().length(); } if (!this.getSelectedText().isEmpty() || this.getLength() - this.getCaretPosition() > maxPosInLine) { return; } if (e.getCode().equals(KeyCode.BACK_SPACE)) { handleBackspace(); } else { handleDelete(); } } private void handleBackspace() { if (currentPosInLine > 0) { currentPosInLine = Math.max(currentPosInLine - 1, 0); charCounterInLine = Math.max(charCounterInLine - 1, 0); this.deletePreviousChar(); } } private void handleDelete() { if (currentPosInLine < charCounterInLine) { charCounterInLine = Math.max(charCounterInLine - 1, 0); this.deleteNextChar(); } } public StringProperty promptProperty() { return this.prompt; } public String getPrompt() { return this.promptProperty().get(); } public void setPrompt(final String prompt) { this.promptProperty().set(prompt); } public int getLineNumber() { return this.getParagraphs().size()-1; } public int getLineStart() { return this.getAbsolutePosition(getLineNumber(), 0); } public String getLine() { return this.getParagraph(this.getLineNumber()).getText(); } public int getInputStart() { return this.getLineStart() + this.getPrompt().length(); } public String getInput() { return this.getLine().substring(this.getPrompt().length()); } public Console.ConfigData getSettings() { final Console.ConfigData configData = new Console.ConfigData(); configData.instructions = instructions.stream().map(ConsoleInstruction::getInstruction).collect(Collectors.toList()); // Do not include the last line (prompt and user input) when saving the console text. // Otherwise there are problems when the text is reloaded and the prompt is not the same as the one saved in the text. configData.text = getText(0, 0, this.getParagraphs().size()-1, 0); configData.errorRanges = new ArrayList<>(); for (final IndexRange indexRange : errors) { configData.errorRanges.add(new int[] {indexRange.getStart(), indexRange.getEnd()}); } return configData; } public void applySettings(Console.ConfigData settings) { if (settings == null) { return; } instructions.clear(); for (final String instruction : settings.instructions) { instructions.add(new ConsoleInstruction(instruction, ConsoleInstructionOption.ENTER)); } posInList = instructions.size(); this.replaceText(settings.text + this.getPrompt()); this.charCounterInLine = 0; this.currentPosInLine = 0; this.moveTo(this.getLength()-1); errors.clear(); for (final int[] range : settings.errorRanges) { errors.add(new IndexRange(range[0], range[1])); this.setStyleClass(range[0], range[1], "error"); } } public int getCurrentPosInLine() { return currentPosInLine; } public List<ConsoleInstruction> getInstructions() { return instructions; } }
package dk.itu.kelvin.util; // General utilities import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; /** * Array list class. * * @param <E> The type of elements stored within the list. * * @version 1.0.0 */ public class ArrayList<E> extends DynamicArray implements List<E> { /** * UID for identifying serialized objects. */ private static final long serialVersionUID = 47; /** * internal element storage. */ private E[] elements; /** * Initialize an array list with the default initial capacity. */ public ArrayList() { this(2); } /** * Initialize an array list with the specified initial capacity. * * @param capacity The initial capacity of the array list. */ @SuppressWarnings("unchecked") public ArrayList(final int capacity) { super( capacity, 1.0f, // Upper load factor 2.0f, // Upper resize factor 0.25f, // Lower load factor 0.5f // Lower resize factor ); this.elements = (E[]) new Object[capacity]; } /** * Initialize an array list using the elements of an existing collection. * * @param collection The collection whose elements to initialize the list * with. */ public ArrayList(final Collection<? extends E> collection) { this(collection.size()); this.addAll(collection); } /** * Resize the internal storage of the list to the specified capacity. * * @param capacity The new capacity of the internal storage of the list. */ @SuppressWarnings("unchecked") protected final void resize(final int capacity) { E[] elements = (E[]) new Object[capacity]; for (int i = 0; i < this.size(); i++) { elements[i] = this.elements[i]; } this.elements = elements; } private void shiftLeft(final int index) { int shifts = this.size() - index - 1; if (shifts <= 0) { return; } System.arraycopy(this.elements, index + 1, this.elements, index, shifts); } private void shiftRight(final int index) { int shifts = this.size() - index; System.arraycopy(this.elements, index, this.elements, index + 1, shifts); } /** * Return the index of the specified element. * * @param element The value to look up the index of. * @return The index of the specified element or -1 if the element * wasn't found within the list. */ public final int indexOf(final Object element) { if (element == null) { return -1; } for (int i = 0; i < this.size(); i++) { if (element.equals(this.elements[i])) { return i; } } return -1; } /** * Get a element by index from the list. * * @param index The index of the element to get. * @return The element if found. */ public final E get(final int index) { if (index < 0 || index >= this.size()) { return null; } return this.elements[index]; } /** * Check if the specified element exists within the list. * * @param element The element to check for. * @return A boolean indicating whether or not the list contains the * specified element. */ public final boolean contains(final Object element) { return this.indexOf(element) != -1; } /** * Add an element to the list. * * @param element The element to add to the list. * @return A boolean indicating whether or not the list changed as a * result of the call. */ public final boolean add(final E element) { if (element == null) { return false; } this.elements[this.size()] = element; this.grow(); return true; } /** * Add an element to the list at the specified index. * * <p> * If an element already exists at the specified index, the old element will * be shifted one index to the right alongside subsequent elements. * * @param index The index at which to add the element. * @param element The element to add to the list. * @return A boolean indicating whether or not the list changed as a * result of the call. */ public final boolean add(final int index, final E element) { if (element == null) { return false; } this.shiftRight(index); this.elements[index] = element; this.grow(); return true; } /** * Add a collection of elements to the list. * * @param elements The elements to add to the list. * @return A boolean indicating whether or not the list changed as a * result of the call. */ public final boolean addAll(final Collection<? extends E> elements) { if (elements == null || elements.isEmpty()) { return false; } boolean changed = false; for (E element: elements) { changed = this.add(element) || changed; } return changed; } /** * Remove an element from the list. * * <p> * When removing an element, any subsequent elements to the right of the * removed element will be shifted one index to the left. * * @param index The index of the element to remove. * @return The removed element. */ public final E remove(final int index) { if (index < 0 || index >= this.size()) { return null; } E element = this.elements[index]; this.shiftLeft(index); this.elements[this.size() - 1] = null; this.shrink(); return element; } /** * Remove an element from the list. * * @param element The element to remove. * @return A boolean inidicating whether or not the list contained the * element to remove. */ public final boolean remove(final Object element) { return this.remove(this.indexOf(element)) != null; } /** * Trim the size of the internal storage to the actual size of the list. */ public final void trimToSize() { // Bail out if we've already reached the capacity of the internal storage. // In this case there won't be anything to trim. if (this.elements.length >= this.size()) { return; } // We add an extra slot for the next element addition since we call // shrink() after having added an element to the array. this.elements = Arrays.copyOf(this.elements, this.size() + 1); } /** * Iterate over the elements of the list. * * @return An iterator over the elements of the list. */ public final Iterator<E> iterator() { return new Iterator<E>() { /** * Keep track of the position within the array. */ private int i = 0; /** * Keep track of the last element that was returned. */ private int last = -1; /** * Check if there are elements left to iterate over. * * @return A boolean indicating whether or not there are elements left * to iterate over. */ public boolean hasNext() { return this.i < ArrayList.this.size(); } /** * Get the next element. * * @return The next element. */ public E next() { if (!this.hasNext()) { throw new NoSuchElementException(); } this.last = this.i++; return ArrayList.this.elements[this.last]; } /** * The the last returned element. */ public void remove() { if (this.last < 0) { throw new IllegalStateException(); } ArrayList.this.remove(this.last); this.i = this.last; this.last = -1; } }; } }
/* *\ ** SICU Stress Measurement System ** ** Project P04 | C380 Team A ** ** EBME 380: Biomedical Engineering Design Experience ** ** Case Western Reserve University ** ** 2016 Fall Semester ** \* */ package edu.cwru.sicu_sms; import javafx.application.Platform; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.LineChart; import javafx.scene.chart.NumberAxis; import javafx.scene.control.*; import java.io.FileWriter; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Random; import java.util.concurrent.Executors; import jssc.SerialPort; /** * The controller for the front-end program. * * @since October 13, 2016 * @author Ted Frohlich <ttf10@case.edu> * @author Abby Walker <amw138@case.edu> */ public class Controller { @FXML private Menu connectMenu; @FXML private ToggleButton recordButton; private FileWriter fileWriter; private SerialPort serialPort; @FXML private void confirmExit() throws Exception { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirm Exit"); alert.setHeaderText("Are you sure you want to exit?"); ButtonType result = alert.showAndWait().orElse(ButtonType.CANCEL); if (result == ButtonType.OK) { Platform.exit(); } } @FXML public void connect(ActionEvent actionEvent) { serialPort = new SerialPort(((MenuItem) actionEvent.getTarget()).getText()); } @FXML private void onMouseEnteredRecordButton() { recordButton.setText((isRecording() ? "Stop" : "Start") + " Recording"); } @FXML private void onMouseExitedRecordButton() { recordButton.setText("Record" + (isRecording() ? "ing..." : "")); } @FXML private void onMousePressedRecordButton() { recordButton.setStyle("-fx-background-color: darkred"); } @FXML private void onMouseReleasedRecordButton() { recordButton.setStyle("-fx-background-color: red"); } @FXML public void onShowingConnectMenu(Event event) { // connectMenu.getItems().clear(); // String[] portNames = SerialPortList.getPortNames(); // problem with Windows OS? // if (portNames.length == 0) { // MenuItem dummy = new MenuItem("<no ports available>"); // dummy.setDisable(true); // connectMenu.getItems().add(dummy); // return; // for (String portName : portNames) { // connectMenu.getItems().add(new RadioMenuItem(portName)); } @FXML private void record() { if (isRecording()) { // start recording... //TODO: Run thread for saving data to file. } else { // stop recording... //TODO: End thread for saving data to file. } onMouseEnteredRecordButton(); // indicate what next click would do } private boolean isRecording() { return recordButton.isSelected(); } /** * A controller for the EEG tab. */ private class EEGController { @FXML private LineChart<String, Number> leftRostralChart, rightRostralChart, leftCaudalChart, rightCaudalChart; private CategoryAxis xAxis; private NumberAxis yAxis; private ObservableList<String> xAxisCategories; private LineChart.Series<String, Number>[] electrodes; private ObservableList<LineChart.Data<String, Number>> leftRostralList, rightRostralList, leftCaudalList, rightCaudalList; private int lastObservedChangelistSize, changesBeforeUpdate = 10; private Task<Date> chartUpdateTask; private EEGController() { initObservableLists(); getObservableLists().forEach(list -> list.addListener(dataListChangeListener())); initAxes(); xAxis.setCategories(xAxisCategories); // xAxis.setAutoRanging(false); //TODO: instantiate and add data series initChartUpdateTask(); Executors.newSingleThreadExecutor().submit(chartUpdateTask); } private void initAxes() { xAxis = new CategoryAxis(); yAxis = new NumberAxis(); xAxis.setLabel("Time (sec)"); yAxis.setLabel("Relative Amplitude"); } private void initChartUpdateTask() { chartUpdateTask = new Task<Date>() { @Override protected Date call() throws Exception { while (true) { try { Thread.sleep(1000); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } if (isCancelled()) break; updateValue(new Date()); } return new Date(); } }; chartUpdateTask.valueProperty().addListener(new ChangeListener<Date>() { SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); //TODO: eventually just want seconds Random random = new Random(); @Override public void changed(ObservableValue<? extends Date> observableDate, Date oldDate, Date newDate) { String strDate = dateFormat.format(newDate); xAxisCategories.add(strDate); getObservableLists().forEach(list -> list.add(new LineChart.Data(strDate, newDate.getMinutes() + random.nextInt(100500)))); } }); } private void initObservableLists() { leftRostralList = rightRostralList = leftCaudalList = rightCaudalList = FXCollections.observableArrayList(); xAxisCategories = FXCollections.observableArrayList(); } private List<LineChart<String, Number>> getCharts() { List<LineChart<String, Number>> charts = Collections.emptyList(); charts.add(leftRostralChart); charts.add(rightRostralChart); charts.add(leftCaudalChart); charts.add(rightCaudalChart); return charts; } private List<ObservableList<LineChart.Data<String, Number>>> getObservableLists() { List<ObservableList<LineChart.Data<String, Number>>> lists = Collections.emptyList(); lists.add(leftRostralList); lists.add(rightRostralList); lists.add(leftCaudalList); lists.add(rightCaudalList); return lists; } private ListChangeListener<LineChart.Data<String, Number>> dataListChangeListener() { return change -> { if (change.getList().size() - lastObservedChangelistSize > changesBeforeUpdate) { lastObservedChangelistSize += changesBeforeUpdate; xAxis.getCategories().remove(0, changesBeforeUpdate); } }; } } /** * A controller for the EKG tab. */ private class EKGController { //TODO: } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.msu.nscl.olog; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import java.util.*; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.*; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; /** * * @author berryman */ public class LogManager { private static EntityManager em = null; private LogManager() { } /** * Returns the list of logs in the database. * * @return Logs * @throws CFException wrapping an SQLException */ public static Logs findAll() throws CFException { em = JPAUtil.getEntityManagerFactory().createEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Log> cq = cb.createQuery(Log.class); Root<Log> from = cq.from(Log.class); CriteriaQuery<Log> select = cq.select(from); Predicate statusPredicate = cb.equal(from.get(Log_.state), State.Active); select.where(statusPredicate); select.orderBy(cb.desc(from.get(Log_.modifiedDate))); TypedQuery<Log> typedQuery = em.createQuery(select); JPAUtil.startTransaction(em); try { Logs result = new Logs(); List<Log> rs = typedQuery.getResultList(); if (rs != null) { Iterator<Log> iterator = rs.iterator(); while (iterator.hasNext()) { result.addLog(iterator.next()); } } return result; } catch (Exception e) { throw new CFException(Response.Status.INTERNAL_SERVER_ERROR, "JPA exception: " + e); } finally { JPAUtil.finishTransacton(em); } } public static Logs findLog(MultivaluedMap<String, String> matches) throws CFException { List<String> log_patterns = new ArrayList(); List<String> logbook_matches = new ArrayList(); List<String> logbook_patterns = new ArrayList(); List<String> tag_matches = new ArrayList(); List<String> tag_patterns = new ArrayList(); List<String> property_matches = new ArrayList(); List<String> property_patterns = new ArrayList(); Multimap<String, String> date_matches = ArrayListMultimap.create(); Multimap<String, String> paginate_matches = ArrayListMultimap.create(); Multimap<String, String> value_patterns = ArrayListMultimap.create(); Boolean empty = false; em = JPAUtil.getEntityManagerFactory().createEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Log> cq = cb.createQuery(Log.class); Root<Log> from = cq.from(Log.class); Join<Log, Entry> entry = from.join(Log_.entry, JoinType.LEFT); SetJoin<Log, Tag> tags = from.join(Log_.tags, JoinType.LEFT); SetJoin<Log, Logbook> logbooks = from.join(Log_.logbooks, JoinType.LEFT); Join<Attribute, Property> property = from.join(Log_.attributes, JoinType.LEFT).join(LogAttribute_.attribute, JoinType.LEFT).join(Attribute_.property, JoinType.LEFT); Join<LogAttribute, Attribute> attribute = from.join(Log_.attributes, JoinType.LEFT).join(LogAttribute_.attribute, JoinType.LEFT); Join<Log, LogAttribute> logAttribute = from.join(Log_.attributes, JoinType.LEFT); for (Map.Entry<String, List<String>> match : matches.entrySet()) { String key = match.getKey().toLowerCase(); Collection<String> matchesValues = match.getValue(); if (key.equals("search")) { for (String m : matchesValues) { if (m.contains("?") || m.contains("*")) { if (m.contains("\\?") || m.contains("\\*")) { m = m.replace("\\", ""); log_patterns.add(m); } else { m = m.replace("*", "%"); m = m.replace("?", "_"); log_patterns.add(m); } } else { log_patterns.add(m); } } } else if (key.equals("tag")) { for (String m : matchesValues) { if (m.contains("?") || m.contains("*")) { if (m.contains("\\?") || m.contains("\\*")) { m = m.replace("\\", ""); tag_matches.add(m); } else { m = m.replace("*", "%"); m = m.replace("?", "_"); tag_patterns.add(m); } } else { tag_matches.add(m); } } if (tag_matches.size() == 1) { String match1 = tag_matches.get(0); tag_matches.clear(); tag_matches.addAll(Arrays.asList(match1.split(","))); } } else if (key.equals("logbook")) { for (String m : matchesValues) { if (m.contains("?") || m.contains("*")) { if (m.contains("\\?") || m.contains("\\*")) { m = m.replace("\\", ""); logbook_matches.add(m); } else { m = m.replace("*", "%"); m = m.replace("?", "_"); logbook_patterns.add(m); } } else { logbook_matches.add(m); } } if (logbook_matches.size() == 1) { String match1 = logbook_matches.get(0); logbook_matches.clear(); logbook_matches.addAll(Arrays.asList(match1.split(","))); } } else if (key.equals("property")) { for (String m : matchesValues) { if (m.contains("?") || m.contains("*")) { if (m.contains("\\?") || m.contains("\\*")) { m = m.replace("\\", ""); property_matches.add(m); } else { m = m.replace("*", "%"); m = m.replace("?", "_"); property_patterns.add(m); } } else { property_matches.add(m); } } } else if (key.equals("page")) { paginate_matches.putAll(key, match.getValue()); } else if (key.equals("limit")) { paginate_matches.putAll(key, match.getValue()); } else if (key.equals("start")) { date_matches.putAll(key, match.getValue()); } else if (key.equals("end")) { date_matches.putAll(key, match.getValue()); } else if (key.equals("empty")) { empty = true; } else { Collection<String> cleanedMatchesValues = new HashSet<String>(); for (String m : matchesValues) { if (m.contains("?") || m.contains("*")) { if (m.contains("\\?") || m.contains("\\*")) { m = m.replace("\\", ""); cleanedMatchesValues.add(m); } else { m = m.replace("*", "%"); m = m.replace("?", "_"); cleanedMatchesValues.add(m); } } else { cleanedMatchesValues.add(m); } } value_patterns.putAll(key, cleanedMatchesValues); } } //cb.or() causes an error in eclipselink with p1 as first argument Predicate tagPredicate = cb.disjunction(); if (!tag_matches.isEmpty()) { tagPredicate = cb.or(tags.get(Tag_.name).in(tag_matches), tagPredicate); } for (String s : tag_patterns) { tagPredicate = cb.or(cb.like(tags.get(Tag_.name), s), tagPredicate); } Predicate logbookPredicate = cb.disjunction(); if (!logbook_matches.isEmpty()) { logbookPredicate = cb.and(logbookPredicate, logbooks.get(Logbook_.name).in(logbook_matches)); } for (String s : logbook_patterns) { logbookPredicate = cb.and(logbookPredicate, cb.like(logbooks.get(Logbook_.name), s)); } Predicate propertyPredicate = cb.disjunction(); if (!property_matches.isEmpty()) { propertyPredicate = cb.and(propertyPredicate, property.get(Property_.name).in(property_matches)); } for (String s : property_patterns) { propertyPredicate = cb.and(propertyPredicate, cb.like(property.get(Property_.name), s)); } Predicate propertyAttributePredicate = cb.disjunction(); for (Map.Entry<String, String> match : value_patterns.entries()) { // Key is coming in as property.attribute List<String> group = Arrays.asList(match.getKey().split("\\.")); if (group.size() == 2) { propertyAttributePredicate = cb.and(propertyAttributePredicate, cb.like(logAttribute.get(LogAttribute_.value), match.getValue()), property.get(Property_.name).in(group.get(0), attribute.get(Attribute_.name).in(group.get(1)))); } } Predicate searchPredicate = cb.disjunction(); for (String s : log_patterns) { searchPredicate = cb.or(cb.like(from.get(Log_.description), s), searchPredicate); List<Long> ids = AttachmentManager.findAll(s); if (!ids.isEmpty()) { searchPredicate = cb.or(entry.get(Entry_.id).in(ids), searchPredicate); } } Predicate datePredicate = cb.disjunction(); if (!date_matches.isEmpty()) { String start = null, end = null; for (Map.Entry<String, Collection<String>> match : date_matches.asMap().entrySet()) { if (match.getKey().toLowerCase().equals("start")) { start = match.getValue().iterator().next(); } if (match.getKey().toLowerCase().equals("end")) { end = match.getValue().iterator().next(); } } if (start != null && end == null) { Date jStart = new java.util.Date(Long.valueOf(start) * 1000); Date jEndNow = new java.util.Date(Calendar.getInstance().getTime().getTime()); datePredicate = cb.between(entry.get(Entry_.createdDate), jStart, jEndNow); } else if (start == null && end != null) { Date jStart1970 = new java.util.Date(0); Date jEnd = new java.util.Date(Long.valueOf(end) * 1000); datePredicate = cb.between(entry.get(Entry_.createdDate), jStart1970, jEnd); } else { Date jStart = new java.util.Date(Long.valueOf(start) * 1000); Date jEnd = new java.util.Date(Long.valueOf(end) * 1000); datePredicate = cb.between(entry.get(Entry_.createdDate), jStart, jEnd); } } cq.distinct(true); Predicate statusPredicate = cb.equal(from.get(Log_.state), State.Active); Predicate finalPredicate = cb.and(statusPredicate, logbookPredicate, tagPredicate, propertyPredicate, propertyAttributePredicate, datePredicate, searchPredicate); cq.where(finalPredicate); cq.orderBy(cb.desc(entry.get(Entry_.createdDate))); TypedQuery<Log> typedQuery = em.createQuery(cq); if (!paginate_matches.isEmpty()) { String page = null, limit = null; for (Map.Entry<String, Collection<String>> match : paginate_matches.asMap().entrySet()) { if (match.getKey().toLowerCase().equals("limit")) { limit = match.getValue().iterator().next(); } if (match.getKey().toLowerCase().equals("page")) { page = match.getValue().iterator().next(); } } if (limit != null && page != null) { Integer offset = Integer.valueOf(page) * Integer.valueOf(limit) - Integer.valueOf(limit); typedQuery.setFirstResult(offset); typedQuery.setMaxResults(Integer.valueOf(limit)); } } JPAUtil.startTransaction(em); try { Logs result = new Logs(); result.setCount(JPAUtil.count(em, cq)); if (empty) { return result; } List<Log> rs = typedQuery.getResultList(); if (rs != null) { Iterator<Log> iterator = rs.iterator(); while (iterator.hasNext()) { Log log = iterator.next(); Entry e = log.getEntry(); Collection<Log> logs = e.getLogs(); log.setVersion(String.valueOf(logs.size())); log.setXmlAttachments(AttachmentManager.findAll(log.getEntryId()).getAttachments()); Iterator<LogAttribute> iter = log.getAttributes().iterator(); Set<XmlProperty> xmlProperties = new HashSet<XmlProperty>(); while (iter.hasNext()) { XmlProperty xmlProperty = new XmlProperty(); Map<String, String> map = new HashMap<String, String>(); LogAttribute logattr = iter.next(); Attribute attr = logattr.getAttribute(); xmlProperty.setName(attr.getProperty().getName()); xmlProperty.setId(attr.getProperty().getId()); for (XmlProperty prevXmlProperty : xmlProperties) { if (prevXmlProperty.getId().equals(xmlProperty.getId())) { map = prevXmlProperty.getAttributes(); } } map.put(attr.getName(), logattr.getValue()); xmlProperty.setAttributes(map); xmlProperties.add(xmlProperty); } log.setXmlProperties(xmlProperties); result.addLog(log); } } return result; } catch (Exception e) { throw new CFException(Response.Status.INTERNAL_SERVER_ERROR, "JPA exception: " + e); } finally { JPAUtil.finishTransacton(em); } } /** * Finds a log and edits in the database by id. * * @return Log * @throws CFException wrapping an SQLException */ public static Log findLog(Long id) throws CFException { try { Entry entry = (Entry) JPAUtil.findByID(Entry.class, id); Collection<Log> logs = entry.getLogs(); Log result = Collections.max(logs); result.setVersion(String.valueOf(logs.size())); result.setXmlAttachments(AttachmentManager.findAll(result.getEntryId()).getAttachments()); Iterator<LogAttribute> iter = result.getAttributes().iterator(); Set<XmlProperty> xmlProperties = new HashSet<XmlProperty>(); while (iter.hasNext()) { XmlProperty xmlProperty = new XmlProperty(); Map<String, String> map = new HashMap<String, String>(); LogAttribute logattr = iter.next(); Attribute attr = logattr.getAttribute(); xmlProperty.setName(attr.getProperty().getName()); xmlProperty.setId(attr.getProperty().getId()); for (XmlProperty prevXmlProperty : xmlProperties) { if (prevXmlProperty.getId().equals(xmlProperty.getId())) { map = prevXmlProperty.getAttributes(); } } map.put(attr.getName(), logattr.getValue()); xmlProperty.setAttributes(map); xmlProperties.add(xmlProperty); } result.setXmlProperties(xmlProperties); return result; } catch (Exception e) { throw new CFException(Response.Status.INTERNAL_SERVER_ERROR, "JPA exception: " + e); } } /** * Creates a Log in the database. * * @param name name of tag * @param owner owner of tag * @throws CFException wrapping an SQLException */ public static Log create(Log log) throws CFException { em = JPAUtil.getEntityManagerFactory().createEntityManager(); JPAUtil.startTransaction(em); Log newLog = new Log(); newLog.setState(State.Active); newLog.setLevel(log.getLevel()); newLog.setOwner(log.getOwner()); newLog.setDescription(log.getDescription()); newLog.setSource(log.getSource()); em.persist(newLog); if (!log.getLogbooks().isEmpty()) { Iterator<Logbook> iterator = log.getLogbooks().iterator(); Set<Logbook> logbooks = new HashSet<Logbook>(); while (iterator.hasNext()) { String logbookName = iterator.next().getName(); Logbook logbook = LogbookManager.findLogbook(logbookName); if (logbook != null) { logbook = em.merge(logbook); logbook.addLog(newLog); logbooks.add(logbook); } else { throw new CFException(Response.Status.NOT_FOUND, "Log entry " + log.getId() + " logbook:" + logbookName + " does not exists."); } } newLog.setLogbooks(logbooks); } else { throw new CFException(Response.Status.NOT_FOUND, "Log entry " + log.getId() + " must be in at least one logbook."); } if (log.getTags() != null) { Iterator<Tag> iterator2 = log.getTags().iterator(); Set<Tag> tags = new HashSet<Tag>(); while (iterator2.hasNext()) { String tagName = iterator2.next().getName(); Tag tag = TagManager.findTag(tagName); if (tag != null) { tag = em.merge(tag); tag.addLog(newLog); tags.add(tag); } else { throw new CFException(Response.Status.NOT_FOUND, "Log entry " + log.getId() + " tag:" + tagName + " does not exists."); } } newLog.setTags(tags); } try { if (log.getEntryId() != null) { Entry entry = (Entry) JPAUtil.findByID(Entry.class, log.getEntryId()); if (entry.getLogs() != null) { List<Log> logs = entry.getLogs(); ListIterator<Log> iterator = logs.listIterator(); while (iterator.hasNext()) { Log sibling = iterator.next(); sibling = em.merge(sibling); sibling.setState(State.Inactive); iterator.set(sibling); } entry.addLog(newLog); } newLog.setState(State.Active); newLog.setEntry(entry); em.merge(entry); } else { Entry entry = new Entry(); newLog.setState(State.Active); entry.addLog(newLog); newLog.setEntry(entry); em.persist(entry); } em.flush(); if (log.getXmlProperties() != null) { Set<LogAttribute> logattrs = new HashSet<LogAttribute>(); Long i = 0L; for (XmlProperty p : log.getXmlProperties()) { Property prop = PropertyManager.findProperty(p.getName()); if(prop==null) { throw new CFException(Response.Status.BAD_REQUEST, "Log entry " + log.getId() + " property:" + p.getName() + " does not exists."); } else { for (Map.Entry<String, String> att : p.getAttributes().entrySet()) { Attribute newAtt = AttributeManager.findAttribute(prop, att.getKey()); if (newAtt.getId() == null) { throw new CFException(Response.Status.BAD_REQUEST, "Log entry " + log.getId() + " attribute:" + att.getKey() + " does not exists for property " + p.getName() + "."); } else { LogAttribute logattr = new LogAttribute(); logattr.setAttribute(newAtt); logattr.setLog(newLog); logattr.setAttributeId(newAtt.getId()); logattr.setLogId(newLog.getId()); logattr.setValue(att.getValue()); logattr.setGroupingNum(i); em.persist(logattr); logattrs.add(logattr); } } } newLog.setAttributes(logattrs); i++; } } newLog.setXmlProperties(log.getXmlProperties()); JPAUtil.finishTransacton(em); return newLog; } catch (Exception e) { JPAUtil.transactionFailed(em); throw new CFException(Response.Status.INTERNAL_SERVER_ERROR, "JPA exception: " + e); } } /** * Remove a tag (mark as Inactive). * * @param name tag name */ public static void remove(Long id) throws CFException { try { Entry entry = (Entry) JPAUtil.findByID(Entry.class, id); if (entry != null) { if (entry.getLogs() != null) { List<Log> logs = entry.getLogs(); ListIterator<Log> iterator = logs.listIterator(); while (iterator.hasNext()) { Log sibling = iterator.next(); sibling.setState(State.Inactive); iterator.set(sibling); JPAUtil.update(sibling); } } } } catch (Exception e) { throw new CFException(Response.Status.INTERNAL_SERVER_ERROR, "JPA exception: " + e); } } }
package eu.amidst.scai2015; import eu.amidst.core.datastream.*; import eu.amidst.core.distribution.Multinomial; import eu.amidst.core.inference.InferenceAlgorithmForBN; import eu.amidst.core.inference.messagepassing.VMP; import eu.amidst.core.io.DataStreamLoader; import eu.amidst.core.learning.StreamingVariationalBayesVMP; import eu.amidst.core.models.BayesianNetwork; import eu.amidst.core.models.DAG; import eu.amidst.core.utils.Utils; import eu.amidst.core.variables.StaticVariables; import eu.amidst.core.variables.Variable; import weka.classifiers.evaluation.NominalPrediction; import weka.classifiers.evaluation.Prediction; import weka.classifiers.evaluation.ThresholdCurve; import weka.core.Instances; import java.io.IOException; import java.util.*; public class wrapperBN { int seed = 0; Variable classVariable; Variable classVariable_PM; Attribute SEQUENCE_ID; Attribute TIME_ID; static int DEFAULTER_VALUE_INDEX = 1; static int NON_DEFAULTER_VALUE_INDEX = 0; int NbrClients= 50000; HashMap<Integer, Multinomial> posteriorsGlobal = new HashMap<>(); static boolean usePRCArea = false; //By default ROCArea is used static boolean dynamicNB = false; static boolean onlyPrediction = false; public static boolean isDynamicNB() { return dynamicNB; } public static void setDynamicNB(boolean dynamicNB) { wrapperBN.dynamicNB = dynamicNB; } public static boolean isOnlyPrediction() { return onlyPrediction; } public static void setOnlyPrediction(boolean onlyPrediction) { wrapperBN.onlyPrediction = onlyPrediction; } HashMap<Integer, Integer> defaultingClients = new HashMap<>(); public static boolean isUsePRCArea() { return usePRCArea; } public static void setUsePRCArea(boolean usePRCArea) { wrapperBN.usePRCArea = usePRCArea; } public Attribute getSEQUENCE_ID() { return SEQUENCE_ID; } public void setSEQUENCE_ID(Attribute SEQUENCE_ID) { this.SEQUENCE_ID = SEQUENCE_ID; } public Attribute getTIME_ID() { return TIME_ID; } public void setTIME_ID(Attribute TIME_ID) { this.TIME_ID = TIME_ID; } public Variable getClassVariable_PM() { return classVariable_PM; } public void setClassVariable_PM(Variable classVariable_PM) { this.classVariable_PM = classVariable_PM; } public int getSeed() { return seed; } public void setSeed(int seed) { this.seed = seed; } public Variable getClassVariable() { return classVariable; } public void setClassVariable(Variable classVariable) { this.classVariable = classVariable; } public BayesianNetwork wrapperBNOneMonthNB(DataOnMemory<DataInstance> data){ StaticVariables Vars = new StaticVariables(data.getAttributes()); //Split the whole data into training and testing List<DataOnMemory<DataInstance>> splitData = this.splitTrainAndTest(data,66.0); DataOnMemory<DataInstance> trainingData = splitData.get(0); DataOnMemory<DataInstance> testData = splitData.get(1); List<Variable> NSF = new ArrayList<>(Vars.getListOfVariables()); // NSF: non selected features NSF.remove(classVariable); //remove C NSF.remove(classVariable_PM); // remove C' int nbrNSF = NSF.size(); List<Variable> SF = new ArrayList(); // SF:selected features Boolean stop = false; //Learn the initial BN with training data including only the class variable BayesianNetwork bNet = train(trainingData, Vars, SF,false); //System.out.println(bNet.toString()); //Evaluate the initial BN with testing data including only the class variable, i.e., initial score or initial auc double score = testFS(testData, bNet); int cont=0; //iterate until there is no improvement in score while (nbrNSF > 0 && stop == false ){ //System.out.print("Iteration: " + cont + ", Score: "+score +", Number of selected variables: "+ SF.size() + ", "); //SF.stream().forEach(v -> System.out.print(v.getName() + ", ")); //System.out.println(); Map<Variable, Double> scores = new HashMap<>(); //scores for each considered feature for(Variable V:NSF) { //if (V.getVarID()>5) // break; //System.out.println("Testing "+V.getName()); SF.add(V); //train bNet = train(trainingData, Vars, SF, false); //evaluate scores.put(V, testFS(testData, bNet)); SF.remove(V); } //determine the Variable V with max score double maxScore = (Collections.max(scores.values())); //returns max value in the Hashmap if (maxScore - score > 0.001){ score = maxScore; //Variable with best score for (Map.Entry<Variable, Double> entry : scores.entrySet()) { if (entry.getValue()== maxScore){ Variable SelectedV = entry.getKey(); SF.add(SelectedV); NSF.remove(SelectedV); break; } } nbrNSF = nbrNSF - 1; } else{ stop = true; } cont++; } //Final training with the winning SF and the full initial data bNet = train(data, Vars, SF, true); //System.out.println(bNet.getDAG().toString()); return bNet; } List<DataOnMemory<DataInstance>> splitTrainAndTest(DataOnMemory<DataInstance> data, double trainPercentage) { Random random = new Random(this.seed); DataOnMemoryListContainer<DataInstance> train = new DataOnMemoryListContainer(data.getAttributes()); DataOnMemoryListContainer<DataInstance> test = new DataOnMemoryListContainer(data.getAttributes()); for (DataInstance dataInstance : data) { if (dataInstance.getValue(classVariable) == DEFAULTER_VALUE_INDEX) continue; if (random.nextDouble()<trainPercentage/100.0) train.add(dataInstance); else test.add(dataInstance); } for (DataInstance dataInstance : data) { if (dataInstance.getValue(classVariable) != DEFAULTER_VALUE_INDEX) continue; if (random.nextDouble()<trainPercentage/100.0) train.add(dataInstance); else test.add(dataInstance); } Collections.shuffle(train.getList(), random); Collections.shuffle(test.getList(), random); return Arrays.asList(train, test); } public BayesianNetwork train(DataOnMemory<DataInstance> data, StaticVariables allVars, List<Variable> SF, boolean includeClassVariablePM){ DAG dag = new DAG(allVars); if(includeClassVariablePM) dag.getParentSet(classVariable).addParent(classVariable_PM); /* Add classVariable to all SF*/ dag.getParentSets().stream() .filter(parent -> SF.contains(parent.getMainVar())) .filter(w -> w.getMainVar().getVarID() != classVariable.getVarID()) .forEach(w -> w.addParent(classVariable)); StreamingVariationalBayesVMP vmp = new StreamingVariationalBayesVMP(); vmp.setDAG(dag); vmp.setDataStream(data); vmp.setWindowsSize(100); vmp.runLearning(); return vmp.getLearntBayesianNetwork(); } public BayesianNetwork train(DataOnMemory<DataInstance> data, StaticVariables allVars, List<Variable> SF){ DAG dag = new DAG(allVars); if(data.getDataInstance(0).getValue(TIME_ID)!=0) dag.getParentSet(classVariable).addParent(classVariable_PM); /* Add classVariable to all SF*/ dag.getParentSets().stream() .filter(parent -> SF.contains(parent.getMainVar())) .filter(w -> w.getMainVar().getVarID() != classVariable.getVarID()) .forEach(w -> w.addParent(classVariable)); StreamingVariationalBayesVMP vmp = new StreamingVariationalBayesVMP(); vmp.setDAG(dag); vmp.setDataStream(data); vmp.setWindowsSize(100); vmp.runLearning(); return vmp.getLearntBayesianNetwork(); } public double testFS(DataOnMemory<DataInstance> data, BayesianNetwork bn){ InferenceAlgorithmForBN vmp = new VMP(); ArrayList<Prediction> predictions = new ArrayList<>(); int currentMonthIndex = (int)data.getDataInstance(0).getValue(TIME_ID); for (DataInstance instance : data) { int clientID = (int) instance.getValue(SEQUENCE_ID); double classValue = instance.getValue(classVariable); Prediction prediction; Multinomial posterior; vmp.setModel(bn); instance.setValue(classVariable, Utils.missingValue()); vmp.setEvidence(instance); vmp.runInference(); posterior = vmp.getPosterior(classVariable); instance.setValue(classVariable, classValue); prediction = new NominalPrediction(classValue, posterior.getProbabilities()); predictions.add(prediction); } ThresholdCurve thresholdCurve = new ThresholdCurve(); Instances tcurve = thresholdCurve.getCurve(predictions); if(usePRCArea) return ThresholdCurve.getPRCArea(tcurve); else return ThresholdCurve.getROCArea(tcurve); } public double test(DataOnMemory<DataInstance> data, BayesianNetwork bn, HashMap<Integer, Multinomial> posteriors, boolean updatePosteriors){ InferenceAlgorithmForBN vmp = new VMP(); ArrayList<Prediction> predictions = new ArrayList<>(); int currentMonthIndex = (int)data.getDataInstance(0).getValue(TIME_ID); for (DataInstance instance : data) { int clientID = (int) instance.getValue(SEQUENCE_ID); double classValue = instance.getValue(classVariable); Prediction prediction; Multinomial posterior; /*Propagates*/ bn.setConditionalDistribution(classVariable_PM, posteriors.get(clientID)); /* Multinomial_MultinomialParents distClass = bn.getConditionalDistribution(classVariable); Multinomial deterministic = new Multinomial(classVariable); deterministic.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 1.0); deterministic.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.0); distClass.setMultinomial(DEFAULTER_VALUE_INDEX, deterministic); */ vmp.setModel(bn); double classValue_PM = instance.getValue(classVariable_PM); instance.setValue(classVariable, Utils.missingValue()); instance.setValue(classVariable_PM, Utils.missingValue()); vmp.setEvidence(instance); vmp.runInference(); posterior = vmp.getPosterior(classVariable); instance.setValue(classVariable, classValue); instance.setValue(classVariable_PM, classValue_PM); prediction = new NominalPrediction(classValue, posterior.getProbabilities()); predictions.add(prediction); if (classValue == DEFAULTER_VALUE_INDEX) { defaultingClients.putIfAbsent(clientID, currentMonthIndex); } if(updatePosteriors) { Multinomial multi_PM = posterior.toEFUnivariateDistribution().deepCopy(classVariable_PM).toUnivariateDistribution(); if (classValue == DEFAULTER_VALUE_INDEX) { multi_PM.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 1.0); multi_PM.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0); } posteriors.put(clientID, multi_PM); } } ThresholdCurve thresholdCurve = new ThresholdCurve(); Instances tcurve = thresholdCurve.getCurve(predictions); if(usePRCArea) return ThresholdCurve.getPRCArea(tcurve); else return ThresholdCurve.getROCArea(tcurve); } public double propagateAndTest(Queue<DataOnMemory<DataInstance>> data, BayesianNetwork bn){ HashMap<Integer, Multinomial> posteriors = new HashMap<>(); InferenceAlgorithmForBN vmp = new VMP(); ArrayList<Prediction> predictions = new ArrayList<>(); /* for (int i = 0; i < NbrClients ; i++){ Multinomial uniform = new Multinomial(classVariable_PM); uniform.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 0.5); uniform.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.5); posteriors.put(i, uniform); } */ boolean firstMonth = true; Iterator<DataOnMemory<DataInstance>> iterator = data.iterator(); while(iterator.hasNext()){ Prediction prediction = null; Multinomial posterior = null; DataOnMemory<DataInstance> batch = iterator.next(); int currentMonthIndex = (int)batch.getDataInstance(0).getValue(TIME_ID); for (DataInstance instance : batch) { int clientID = (int) instance.getValue(SEQUENCE_ID); double classValue = instance.getValue(classVariable); /*Propagates*/ double classValue_PM = -1; if(!firstMonth){ bn.setConditionalDistribution(classVariable_PM, posteriors.get(clientID)); classValue_PM = instance.getValue(classVariable_PM); instance.setValue(classVariable_PM, Utils.missingValue()); } vmp.setModel(bn); instance.setValue(classVariable, Utils.missingValue()); vmp.setEvidence(instance); vmp.runInference(); posterior = vmp.getPosterior(classVariable); instance.setValue(classVariable, classValue); if(!firstMonth) { instance.setValue(classVariable_PM, classValue_PM); } if(!iterator.hasNext()) { //Last month or present prediction = new NominalPrediction(classValue, posterior.getProbabilities()); predictions.add(prediction); } Multinomial multi_PM = posterior.toEFUnivariateDistribution().deepCopy(classVariable_PM).toUnivariateDistribution(); posteriors.put(clientID, multi_PM); } firstMonth = false; if(!iterator.hasNext()) {//Last month or present time ThresholdCurve thresholdCurve = new ThresholdCurve(); Instances tcurve = thresholdCurve.getCurve(predictions); if(usePRCArea) return ThresholdCurve.getPRCArea(tcurve); else return ThresholdCurve.getROCArea(tcurve); } } throw new UnsupportedOperationException("Something went wrong: The method should have stopped at some point in the loop."); } void learnCajamarModel(DataStream<DataInstance> data) { StaticVariables Vars = new StaticVariables(data.getAttributes()); classVariable = Vars.getVariableById(Vars.getNumberOfVars()-1); classVariable_PM = Vars.getVariableById(Vars.getNumberOfVars()-2); TIME_ID = data.getAttributes().getAttributeByName("TIME_ID"); SEQUENCE_ID = data.getAttributes().getAttributeByName("SEQUENCE_ID"); int count = 0; double averageAUC = 0; /* for (int i = 0; i < NbrClients ; i++){ Multinomial uniform = new Multinomial(classVariable_PM); uniform.setProbabilityOfState(DEFAULTER_VALUE_INDEX, 0.5); uniform.setProbabilityOfState(NON_DEFAULTER_VALUE_INDEX, 0.5); posteriorsGlobal.put(i, uniform); } */ Iterable<DataOnMemory<DataInstance>> iteratable = data.iterableOverBatches(NbrClients); Iterator<DataOnMemory<DataInstance>> iterator = iteratable.iterator(); Queue<DataOnMemory<DataInstance>> monthsMinus12to0 = new LinkedList<>(); iterator.next(); //First month is discarded //Take 13 batches at a time - 1 for training and 12 for testing //for (int i = 0; i < 12; i++) { for (int i = 0; i < 2; i++) { monthsMinus12to0.add(iterator.next()); } while(iterator.hasNext()){ DataOnMemory<DataInstance> currentMonth = iterator.next(); monthsMinus12to0.add(currentMonth); int idMonthMinus12 = (int)monthsMinus12to0.peek().getDataInstance(0).getValue(TIME_ID); BayesianNetwork bn = null; if(isOnlyPrediction()){ DataOnMemory<DataInstance> batch = monthsMinus12to0.poll(); StaticVariables vars = new StaticVariables(batch.getAttributes()); bn = train(batch, vars, vars.getListOfVariables(),this.isDynamicNB()); double auc = propagateAndTest(monthsMinus12to0, bn); System.out.println( idMonthMinus12 + "\t" + auc); averageAUC += auc; } else { bn = wrapperBNOneMonthNB(monthsMinus12to0.poll()); double auc = propagateAndTest(monthsMinus12to0, bn); System.out.print( idMonthMinus12 + "\t" + auc); bn.getDAG().getParentSets().stream().filter(p -> p.getNumberOfParents()>0).forEach(p-> System.out.print("\t" + p.getMainVar().getName())); System.out.println(); averageAUC += auc; } count += NbrClients; } System.out.println("Average Accuracy: " + averageAUC / (count / NbrClients)); } public static void main(String[] args) throws IOException { //DataStream<DataInstance> data = DataStreamLoader.loadFromFile("datasets/BankArtificialDataSCAI2015_DEFAULTING_PM.arff"); DataStream<DataInstance> data = DataStreamLoader.loadFromFile(args[0]); for (int i = 1; i < args.length ; i++) { if(args[i].equalsIgnoreCase("PRCArea")) setUsePRCArea(true); if(args[i].equalsIgnoreCase("onlyPrediction")) setOnlyPrediction(true); if(args[i].equalsIgnoreCase("dynamic")) setDynamicNB(true); } wrapperBN wbnet = new wrapperBN(); wbnet.learnCajamarModel(data); } }
package hudson.plugins.jira; import com.atlassian.event.api.EventPublisher; import com.atlassian.httpclient.apache.httpcomponents.DefaultHttpClientFactory; import com.atlassian.httpclient.api.HttpClient; import com.atlassian.httpclient.api.factory.HttpClientOptions; import com.atlassian.jira.rest.client.api.AuthenticationHandler; import com.atlassian.jira.rest.client.api.JiraRestClient; import com.atlassian.jira.rest.client.api.JiraRestClientFactory; import com.atlassian.jira.rest.client.api.RestClientException; import com.atlassian.jira.rest.client.api.domain.Issue; import com.atlassian.jira.rest.client.api.domain.Version; import com.atlassian.jira.rest.client.auth.BasicHttpAuthenticationHandler; import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClient; import com.atlassian.jira.rest.client.internal.async.AtlassianHttpClientDecorator; import com.atlassian.jira.rest.client.internal.async.DisposableHttpClient; import com.atlassian.sal.api.ApplicationProperties; import com.atlassian.sal.api.UrlMode; import com.atlassian.sal.api.executor.ThreadLocalContextManager; import com.cloudbees.hudson.plugins.folder.AbstractFolder; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardUsernameListBoxModel; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials; import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import hudson.Extension; import hudson.Util; import hudson.model.AbstractDescribableImpl; import hudson.model.Descriptor; import hudson.model.Item; import hudson.model.ItemGroup; import hudson.model.Job; import hudson.plugins.jira.model.JiraIssue; import hudson.security.ACL; import hudson.security.AccessControlled; import hudson.util.FormValidation; import hudson.util.ListBoxModel; import hudson.util.Secret; import jenkins.model.Jenkins; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.interceptor.RequirePOST; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.apache.commons.lang.StringUtils.isNotEmpty; /** * Represents an external JIRA installation and configuration * needed to access this JIRA. * * @author Kohsuke Kawaguchi */ public class JiraSite extends AbstractDescribableImpl<JiraSite> { private static final Logger LOGGER = Logger.getLogger(JiraSite.class.getName()); /** * Regexp pattern that identifies JIRA issue token. * If this pattern changes help pages (help-issue-pattern_xy.html) must be updated * First char must be a letter, then at least one letter, digit or underscore. * See issue JENKINS-729, JENKINS-4092 */ public static final Pattern DEFAULT_ISSUE_PATTERN = Pattern.compile("([a-zA-Z][a-zA-Z0-9_]+-[1-9][0-9]*)([^.]|\\.[^0-9]|\\.$|$)"); /** * Default rest api client calls timeout, in seconds * See issue JENKINS-31113 */ public static final int DEFAULT_TIMEOUT = 10; public static final int DEFAULT_READ_TIMEOUT = 30; public static final int DEFAULT_THREAD_EXECUTOR_NUMBER = 10; public final URL url; public final URL alternativeUrl; /** * JIRA requires HTTP Authentication for login */ public final boolean useHTTPAuth; /** * The id of the credentials to use. Optional. */ public String credentialsId; /** * Transient stash of the credentials to use, mostly just for providing floating user object. */ public final transient UsernamePasswordCredentials credentials; /** * User name needed to login. Optional. * @deprecated use credentialsId */ @Deprecated private transient String userName; /** * Password needed to login. Optional. * @deprecated use credentialsId */ @Deprecated private transient Secret password; /** * Group visibility to constrain the visibility of the added comment. Optional. */ public final String groupVisibility; /** * Role visibility to constrain the visibility of the added comment. Optional. */ public final String roleVisibility; /** * True if this JIRA is configured to allow Confluence-style Wiki comment. */ public final boolean supportsWikiStyleComment; /** * to record scm changes in jira issue * * @since 1.21 */ public final boolean recordScmChanges; /** * Disable annotating the changelogs * * @since todo */ public boolean disableChangelogAnnotations; /** * user defined pattern * * @since 1.22 */ private final String userPattern; private transient Pattern userPat; /** * updated jira issue for all status * * @since 1.22 */ public final boolean updateJiraIssueForAllStatus; /** * connection timeout used when calling jira rest api, in seconds */ public int timeout = DEFAULT_TIMEOUT; /** * response timeout for jira rest call * @since 3.0.3 */ private int readTimeout = DEFAULT_READ_TIMEOUT; /** * thread pool number * @since 3.0.3 */ private int threadExecutorNumber = DEFAULT_THREAD_EXECUTOR_NUMBER; /** * Configuration for formatting (date -> text) in jira comments. */ private String dateTimePattern; /** * To add scm entry change date and time in jira comments. * */ private Boolean appendChangeTimestamp; /** * List of project keys (i.e., "MNG" portion of "MNG-512"), * last time we checked. Copy on write semantics. */ // TODO: seems like this is never invalidated (never set to null) // should we implement to invalidate this (say every hour)? private transient volatile Set<String> projects; private transient Cache<String, Optional<Issue>> issueCache = makeIssueCache(); /** * Used to guard the computation of {@link #projects} */ private transient Lock projectUpdateLock = new ReentrantLock(); private transient JiraSession jiraSession; private transient ExecutorService executorService; // Deprecate the previous constructor but leave it in place for Java-level compatibility. @Deprecated public JiraSite(URL url, @CheckForNull URL alternativeUrl, @CheckForNull String credentialsId, boolean supportsWikiStyleComment, boolean recordScmChanges, @CheckForNull String userPattern, boolean updateJiraIssueForAllStatus, @CheckForNull String groupVisibility, @CheckForNull String roleVisibility, boolean useHTTPAuth) { this(url, alternativeUrl, CredentialsHelper.lookupSystemCredentials(credentialsId, url), supportsWikiStyleComment, recordScmChanges, userPattern, updateJiraIssueForAllStatus, groupVisibility, roleVisibility, useHTTPAuth); } // Deprecate the previous constructor but leave it in place for Java-level compatibility. @Deprecated public JiraSite(URL url, @CheckForNull URL alternativeUrl, String userName, String password, boolean supportsWikiStyleComment, boolean recordScmChanges, @CheckForNull String userPattern, boolean updateJiraIssueForAllStatus, @CheckForNull String groupVisibility, @CheckForNull String roleVisibility, boolean useHTTPAuth) { this(url, alternativeUrl, CredentialsHelper.migrateCredentials(userName, password, url), supportsWikiStyleComment, recordScmChanges, userPattern, updateJiraIssueForAllStatus, groupVisibility, roleVisibility, useHTTPAuth); } // Deprecate the previous constructor but leave it in place for Java-level compatibility. @Deprecated public JiraSite(URL url, URL alternativeUrl, StandardUsernamePasswordCredentials credentials, boolean supportsWikiStyleComment, boolean recordScmChanges, String userPattern, boolean updateJiraIssueForAllStatus, String groupVisibility, String roleVisibility, boolean useHTTPAuth) { this( url, alternativeUrl, credentials, supportsWikiStyleComment, recordScmChanges, userPattern, updateJiraIssueForAllStatus, groupVisibility, roleVisibility, useHTTPAuth, DEFAULT_TIMEOUT, DEFAULT_READ_TIMEOUT, DEFAULT_THREAD_EXECUTOR_NUMBER); } @DataBoundConstructor public JiraSite(URL url, URL alternativeUrl, String credentialsId, boolean supportsWikiStyleComment, boolean recordScmChanges, String userPattern, boolean updateJiraIssueForAllStatus, String groupVisibility, String roleVisibility, boolean useHTTPAuth, int timeout, int readTimeout, int threadExecutorNumber){ this(url, alternativeUrl, CredentialsHelper.lookupSystemCredentials(credentialsId, url), supportsWikiStyleComment, recordScmChanges, userPattern, updateJiraIssueForAllStatus, groupVisibility, roleVisibility, useHTTPAuth, timeout, readTimeout, threadExecutorNumber); } public JiraSite(URL url, URL alternativeUrl, StandardUsernamePasswordCredentials credentials, boolean supportsWikiStyleComment, boolean recordScmChanges, String userPattern, boolean updateJiraIssueForAllStatus, String groupVisibility, String roleVisibility, boolean useHTTPAuth, int timeout, int readTimeout, int threadExecutorNumber) { if (url != null && !url.toExternalForm().endsWith("/")) try { url = new URL(url.toExternalForm() + "/"); } catch (MalformedURLException e) { throw new AssertionError(e); } if (alternativeUrl != null && !alternativeUrl.toExternalForm().endsWith("/")) try { alternativeUrl = new URL(alternativeUrl.toExternalForm() + "/"); } catch (MalformedURLException e) { throw new AssertionError(e); } this.url = url; this.timeout = timeout; this.readTimeout = readTimeout; this.threadExecutorNumber = threadExecutorNumber; this.alternativeUrl = alternativeUrl; this.credentials = credentials; this.credentialsId = credentials != null ? credentials.getId() : null; this.supportsWikiStyleComment = supportsWikiStyleComment; this.recordScmChanges = recordScmChanges; this.userPattern = Util.fixEmpty(userPattern); if (this.userPattern != null) { this.userPat = Pattern.compile(this.userPattern); } else { this.userPat = null; } this.updateJiraIssueForAllStatus = updateJiraIssueForAllStatus; this.groupVisibility = Util.fixEmpty(groupVisibility); this.roleVisibility = Util.fixEmpty(roleVisibility); this.useHTTPAuth = useHTTPAuth; this.jiraSession = null; } @DataBoundSetter public void setDisableChangelogAnnotations(boolean disableChangelogAnnotations) { this.disableChangelogAnnotations = disableChangelogAnnotations; } public boolean getDisableChangelogAnnotations() { return disableChangelogAnnotations; } /** * Sets connect timeout (in seconds). * If not specified, a default timeout will be used. * @param timeoutSec Timeout in seconds */ @DataBoundSetter public void setTimeout(int timeoutSec) { this.timeout = timeoutSec; } public int getTimeout() { return timeout; } /** * Sets read timeout (in seconds). * If not specified, a default timeout will be used. * @param readTimeout Timeout in seconds */ @DataBoundSetter public void setReadTimeout( int readTimeout ) { this.readTimeout = readTimeout; } public int getReadTimeout() { return readTimeout; } public String getCredentialsId() { return credentialsId; } @DataBoundSetter public void setCredentialsId(String credentialsId) { this.credentialsId = credentialsId; } @DataBoundSetter public void setDateTimePattern(String dateTimePattern) { this.dateTimePattern = dateTimePattern; } @DataBoundSetter public void setThreadExecutorNumber( int threadExecutorNumber ) { this.threadExecutorNumber = threadExecutorNumber; } public int getThreadExecutorNumber() { return threadExecutorNumber; } @DataBoundSetter public void setAppendChangeTimestamp(Boolean appendChangeTimestamp) { this.appendChangeTimestamp = appendChangeTimestamp; } public String getDateTimePattern() { return dateTimePattern; } public boolean isAppendChangeTimestamp() { return this.appendChangeTimestamp != null && this.appendChangeTimestamp.booleanValue(); } @SuppressWarnings("unused") protected Object readResolve() { JiraSite jiraSite; if (credentialsId == null && userName != null && password != null) { // Migrate credentials jiraSite = new JiraSite(url, alternativeUrl, userName, password.getPlainText(), supportsWikiStyleComment, recordScmChanges, userPattern, updateJiraIssueForAllStatus, groupVisibility, roleVisibility, useHTTPAuth); } else { jiraSite = new JiraSite( url, alternativeUrl, credentialsId, supportsWikiStyleComment, recordScmChanges, userPattern, updateJiraIssueForAllStatus, groupVisibility, roleVisibility, useHTTPAuth, timeout, readTimeout, threadExecutorNumber ); } jiraSite.setAppendChangeTimestamp( appendChangeTimestamp ); jiraSite.setDisableChangelogAnnotations( disableChangelogAnnotations ); jiraSite.setDateTimePattern( dateTimePattern ); return jiraSite; } private static Cache<String, Optional<Issue>> makeIssueCache() { return CacheBuilder.newBuilder().concurrencyLevel(2).expireAfterAccess(2, TimeUnit.MINUTES).build(); } public String getName() { return url.toExternalForm(); } /** * Gets a remote access session to this JIRA site. * Creates one if none exists already. * * @return null if remote access is not supported. */ @Nullable public JiraSession getSession() { if (jiraSession == null) { jiraSession = createSession(); } return jiraSession; } /** * Creates a remote access session to this JIRA. * * @return null if remote access is not supported. */ protected JiraSession createSession() { if (credentials == null) { return null; // remote access not supported } final URI uri; try { uri = url.toURI(); } catch (URISyntaxException e) { LOGGER.warning("convert URL to URI error: " + e.getMessage()); throw new RuntimeException("failed to create JiraSession due to convert URI error"); } LOGGER.fine("creating JIRA Session: " + uri); String userName = credentials.getUsername(); Secret password = credentials.getPassword(); final HttpClientOptions options = new HttpClientOptions(); options.setRequestTimeout(readTimeout, TimeUnit.SECONDS); options.setSocketTimeout(timeout, TimeUnit.SECONDS); if (executorService==null){ executorService = Executors.newFixedThreadPool( threadExecutorNumber, new ThreadFactory() { final AtomicInteger threadNumber = new AtomicInteger( 0 ); @Override public Thread newThread( Runnable r ) { return new Thread( r, "jira-plugin-http-request-" + threadNumber.getAndIncrement() + "-thread" ); } } ); } options.setCallbackExecutor(executorService); final JiraRestClient jiraRestClient = new AsynchronousJiraRestClientFactory() .create(uri, new BasicHttpAuthenticationHandler( userName, password.getPlainText()),options); return new JiraSession(this, new JiraRestService(uri, jiraRestClient, userName, password.getPlainText(), readTimeout)); } // internal classes we want to override private static class AsynchronousJiraRestClientFactory implements JiraRestClientFactory { public JiraRestClient create(final URI serverUri, final AuthenticationHandler authenticationHandler, HttpClientOptions options) { final DisposableHttpClient httpClient = createClient(serverUri, authenticationHandler, options); return new AsynchronousJiraRestClient( serverUri, httpClient); } @Override public JiraRestClient create(final URI serverUri, final AuthenticationHandler authenticationHandler) { final DisposableHttpClient httpClient = createClient(serverUri, authenticationHandler, new HttpClientOptions()); return new AsynchronousJiraRestClient( serverUri, httpClient); } @Override public JiraRestClient createWithBasicHttpAuthentication(final URI serverUri, final String username, final String password) { return create(serverUri, new BasicHttpAuthenticationHandler( username, password)); } @Override public JiraRestClient createWithAuthenticationHandler(final URI serverUri, final AuthenticationHandler authenticationHandler) { return create(serverUri, authenticationHandler); } @Override public JiraRestClient create(final URI serverUri, final HttpClient httpClient) { final DisposableHttpClient disposableHttpClient = createClient(httpClient); return new AsynchronousJiraRestClient(serverUri, disposableHttpClient); } } private static DisposableHttpClient createClient(final URI serverUri, final AuthenticationHandler authenticationHandler, HttpClientOptions options) { final DefaultHttpClientFactory defaultHttpClientFactory = new DefaultHttpClientFactory( new NoOpEventPublisher(), new RestClientApplicationProperties( serverUri), new ThreadLocalContextManager() { @Override public Object getThreadLocalContext() { return null; } @Override public void setThreadLocalContext(Object context) { } @Override public void clearThreadLocalContext() { } }); final HttpClient httpClient = defaultHttpClientFactory.create(options); return new AtlassianHttpClientDecorator( httpClient, authenticationHandler) { @Override public void destroy() throws Exception { defaultHttpClientFactory.dispose(httpClient); } }; } private static DisposableHttpClient createClient(final HttpClient client) { return new AtlassianHttpClientDecorator(client, null) { @Override public void destroy() throws Exception { // This should never be implemented. This is simply creation of a wrapper // for AtlassianHttpClient which is extended by a destroy method. // Destroy method should never be called for AtlassianHttpClient coming from // a client! Imagine you create a RestClient, pass your own HttpClient there // and it gets destroy. } }; } private static class NoOpEventPublisher implements EventPublisher { @Override public void publish(Object o) { } @Override public void register(Object o) { } @Override public void unregister(Object o) { } @Override public void unregisterAll() { } } @SuppressWarnings("deprecation") private static class RestClientApplicationProperties implements ApplicationProperties { private final String baseUrl; private RestClientApplicationProperties(URI jiraURI) { this.baseUrl = jiraURI.getPath(); } @Override public String getBaseUrl() { return baseUrl; } /** * We'll always have an absolute URL as a client. */ @Nonnull @Override public String getBaseUrl( UrlMode urlMode) { return baseUrl; } @Nonnull @Override public String getDisplayName() { return "Atlassian JIRA Rest Java Client"; } @Nonnull @Override public String getPlatformId() { return ApplicationProperties.PLATFORM_JIRA; } @Nonnull @Override public String getVersion() { return ""; } @Nonnull @Override public Date getBuildDate() { throw new UnsupportedOperationException(); } @Nonnull @Override public String getBuildNumber() { return String.valueOf(0); } @Override public File getHomeDirectory() { return new File("."); } @Override public String getPropertyValue(final String s) { throw new UnsupportedOperationException("Not implemented"); } } /** * @return the server URL */ @Nullable public URL getUrl() { return Objects.firstNonNull(this.url, this.alternativeUrl); } /** * Computes the URL to the given issue. */ public URL getUrl(JiraIssue issue) throws IOException { return getUrl(issue.getKey()); } /** * Computes the URL to the given issue. */ public URL getUrl(String id) throws MalformedURLException { return new URL(url, "browse/" + id.toUpperCase()); } /** * Computes the alternative link URL to the given issue. */ public URL getAlternativeUrl(String id) throws MalformedURLException { return alternativeUrl == null ? null : new URL(alternativeUrl, "browse/" + id.toUpperCase()); } /** * Gets the user-defined issue pattern if any. * * @return the pattern or null */ public Pattern getUserPattern() { if (userPattern == null) { return null; } if (userPat == null) { // We don't care about any thread race- or visibility issues here. // The worst thing which could happen, is that the pattern // is compiled multiple times. userPat = Pattern.compile(userPattern); } return userPat; } public Pattern getIssuePattern() { Pattern result = getUserPattern(); return result == null ? DEFAULT_ISSUE_PATTERN : result; } /** * Gets the list of project IDs in this JIRA. * This information could be bit old, or it can be null. */ public Set<String> getProjectKeys() { if (projects == null) { try { if (projectUpdateLock.tryLock(3, TimeUnit.SECONDS)) { try { JiraSession session = getSession(); if (session != null) { projects = Collections.unmodifiableSet(session.getProjectKeys()); } } finally { projectUpdateLock.unlock(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); // process this interruption later } } // fall back to empty if failed to talk to the server Set<String> p = projects; if (p == null) { return Collections.emptySet(); } return p; } /** * Gets the effective {@link JiraSite} associated with the given project. * * @return null * if no such was found. */ public static JiraSite get(Job<?, ?> p) { JiraProjectProperty jpp = p.getProperty(JiraProjectProperty.class); if (jpp != null) { // Looks in global configuration for the site configured JiraSite site = jpp.getSite(); if (site != null) { return site; } } // Check up the folder chain if a site is defined there // This only supports one site per folder ItemGroup parent = p.getParent(); while (parent != null) { if (parent instanceof AbstractFolder) { AbstractFolder folder = (AbstractFolder) parent; JiraFolderProperty jfp = (JiraFolderProperty) folder.getProperties().get(JiraFolderProperty.class); if (jfp != null) { JiraSite[] sites = jfp.getSites(); if (sites != null && sites.length > 0) { return sites[0]; } } } if (parent instanceof Item) { parent = ((Item) parent).getParent(); } else { parent = null; } } // if only one is configured, that must be it. JiraSite[] sites = JiraProjectProperty.DESCRIPTOR.getSites(); if (sites.length == 1) { return sites[0]; } return null; } /** * Returns the remote issue with the given id or <code>null</code> if it wasn't found. */ @CheckForNull public JiraIssue getIssue(final String id) throws IOException { try { Optional<Issue> issue = issueCache.get(id, () -> { JiraSession session = getSession(); if (session == null) { return null; } return Optional.fromNullable(session.getIssue(id)); }); if (!issue.isPresent()) { return null; } return new JiraIssue(issue.get()); } catch (ExecutionException e) { throw new IOException(e); } } @Deprecated public boolean existsIssue(String id) { try { return getIssue(id) != null; } catch ( IOException e ) { // restoring backward compat means even avoid exception throw new RuntimeException( e.getMessage(),e ); } } /** * Returns all versions for the given project key. * * @param projectKey Project Key * @return A set of JiraVersions */ public Set<Version> getVersions(String projectKey) { JiraSession session = getSession(); if (session == null) { LOGGER.warning("JIRA session could not be established"); return Collections.emptySet(); } return new HashSet<>(session.getVersions(projectKey)); } /** * Generates release notes for a given version. * * @param projectKey * @param versionName * @param filter Additional JQL Filter. Example: status in (Resolved,Closed) * @return release notes * @throws TimeoutException */ public String getReleaseNotesForFixVersion(String projectKey, String versionName, String filter) throws TimeoutException { JiraSession session = getSession(); if (session == null) { LOGGER.warning("JIRA session could not be established"); return ""; } List<Issue> issues = session.getIssuesWithFixVersion(projectKey, versionName, filter); if (issues.isEmpty()) { return ""; } Map<String, Set<String>> releaseNotes = new HashMap<>(); for (Issue issue : issues) { String key = issue.getKey(); String summary = issue.getSummary(); String status = issue.getStatus().getName(); String type = issue.getIssueType().getName(); Set<String> issueSet; if (releaseNotes.containsKey(type)) { issueSet = releaseNotes.get(type); } else { issueSet = new HashSet<>(); releaseNotes.put(type, issueSet); } issueSet.add(String.format(" - [%s] %s (%s)", key, summary, status)); } StringBuilder sb = new StringBuilder(); for (String type : releaseNotes.keySet()) { sb.append(String.format("# %s\n", type)); for (String issue : releaseNotes.get(type)) { sb.append(issue); sb.append("\n"); } } return sb.toString(); } /** * Migrates issues matching the jql query provided to a new fix version. * * @param projectKey The project key * @param toVersion The new fixVersion * @param query A JQL Query * @throws TimeoutException */ public void replaceFixVersion(String projectKey, String fromVersion, String toVersion, String query) throws TimeoutException { JiraSession session = getSession(); if (session == null) { LOGGER.warning("JIRA session could not be established"); return; } session.replaceFixVersion(projectKey, fromVersion, toVersion, query); } /** * Migrates issues matching the jql query provided to a new fix version. * * @param projectKey The project key * @param versionName The new fixVersion * @param query A JQL Query * @throws TimeoutException */ public void migrateIssuesToFixVersion(String projectKey, String versionName, String query) throws TimeoutException { JiraSession session = getSession(); if (session == null) { LOGGER.warning("JIRA session could not be established"); return; } session.migrateIssuesToFixVersion(projectKey, versionName, query); } /** * Adds new fix version to issues matching the jql. * * @param projectKey * @param versionName * @param query * @throws TimeoutException */ public void addFixVersionToIssue(String projectKey, String versionName, String query) throws TimeoutException { JiraSession session = getSession(); if (session == null) { LOGGER.warning("JIRA session could not be established"); return; } session.addFixVersion(projectKey, versionName, query); } /** * Progresses all issues matching the JQL search, using the given workflow action. Optionally * adds a comment to the issue(s) at the same time. * * @param jqlSearch * @param workflowActionName * @param comment * @param console * @throws TimeoutException */ public boolean progressMatchingIssues(String jqlSearch, String workflowActionName, String comment, PrintStream console) throws TimeoutException { JiraSession session = getSession(); if (session == null) { LOGGER.warning("JIRA session could not be established"); console.println(Messages.FailedToConnect()); return false; } boolean success = true; List<Issue> issues = session.getIssuesFromJqlSearch(jqlSearch); if (isEmpty(workflowActionName)) { console.println("[JIRA] No workflow action was specified, " + "thus no status update will be made for any of the matching issues."); } for (Issue issue : issues) { String issueKey = issue.getKey(); if (isNotEmpty(comment)) { session.addComment(issueKey, comment, null, null); } if (isEmpty(workflowActionName)) { continue; } Integer actionId = session.getActionIdForIssue(issueKey, workflowActionName); if (actionId == null) { LOGGER.fine(String.format("Invalid workflow action %s for issue %s; issue status = %s", workflowActionName, issueKey, issue.getStatus())); console.println(Messages.JiraIssueUpdateBuilder_UnknownWorkflowAction(issueKey, workflowActionName)); success = false; continue; } String newStatus = session.progressWorkflowAction(issueKey, actionId); console.println(String.format("[JIRA] Issue %s transitioned to \"%s\" due to action \"%s\".", issueKey, newStatus, workflowActionName)); } return success; } public void destroy() { try { if(this.executorService!=null&&!this.executorService.isShutdown()){ this.executorService.shutdownNow(); } } catch ( Exception e ) { LOGGER.log(Level.INFO, "skip error stopping executorService:" + e.getMessage(), e ); } } @Extension public static class DescriptorImpl extends Descriptor<JiraSite> { @Override public String getDisplayName() { return "JIRA Site"; } /** * Checks if the user name and password are valid. */ @RequirePOST public FormValidation doValidate(@QueryParameter String url, @QueryParameter String credentialsId, @QueryParameter String groupVisibility, @QueryParameter String roleVisibility, @QueryParameter boolean useHTTPAuth, @QueryParameter String alternativeUrl, @QueryParameter int timeout, @QueryParameter int readTimeout, @QueryParameter int threadExecutorNumber, @AncestorInPath Item item) { if (item == null) { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); } else { item.checkPermission(Item.CONFIGURE); } url = Util.fixEmpty(url); alternativeUrl = Util.fixEmpty(alternativeUrl); URL mainURL, alternativeURL = null; try{ if (url == null) { return FormValidation.error("No URL given"); } mainURL = new URL(url); } catch (MalformedURLException e){ return FormValidation.error(String.format("Malformed URL (%s)", url), e ); } try { if (alternativeUrl != null) { alternativeURL = new URL(alternativeUrl); } }catch (MalformedURLException e){ return FormValidation.error(String.format("Malformed alternative URL (%s)",alternativeUrl), e ); } credentialsId = Util.fixEmpty(credentialsId); JiraSite site = getJiraSiteBuilder() .withMainURL(mainURL) .withAlternativeURL(alternativeURL) .withCredentialsId(credentialsId) .withGroupVisibility(groupVisibility) .withRoleVisibility(roleVisibility) .withUseHTTPAuth(useHTTPAuth) .build(); site.setTimeout(timeout==0?DEFAULT_TIMEOUT:timeout); site.setReadTimeout(readTimeout==0?DEFAULT_READ_TIMEOUT:readTimeout); site.setThreadExecutorNumber(threadExecutorNumber==0?DEFAULT_THREAD_EXECUTOR_NUMBER:threadExecutorNumber); try { JiraSession session = site.createSession(); session.getMyPermissions(); return FormValidation.ok("Success"); } catch (RestClientException e) { LOGGER.log(Level.WARNING, "Failed to login to JIRA at " + url, e); } finally { if(site!=null){ site.destroy(); } } return FormValidation.error("Failed to login to JIRA"); } public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, @QueryParameter String url) { AccessControlled _context = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance()); if (_context == null || !_context.hasPermission(Jenkins.ADMINISTER)) { return new StandardUsernameListBoxModel(); } return new StandardUsernameListBoxModel() .withEmptySelection() .withAll( CredentialsProvider.lookupCredentials( StandardUsernamePasswordCredentials.class, Jenkins.getInstance(), ACL.SYSTEM, URIRequirementBuilder.fromUri(url).build() ) ); } JiraSiteBuilder getJiraSiteBuilder() { return new JiraSiteBuilder(); } } static class JiraSiteBuilder { private URL mainURL; private URL alternativeURL; private String credentialsId; private boolean supportsWikiStyleComment; private boolean recordScmChanges; private String userPattern; private boolean updateJiraIssueForAllStatus; private String groupVisibility; private String roleVisibility; private boolean useHTTPAuth; public JiraSiteBuilder withMainURL(URL mainURL) { this.mainURL = mainURL; return this; } public JiraSiteBuilder withAlternativeURL(URL alternativeURL) { this.alternativeURL = alternativeURL; return this; } public JiraSiteBuilder withCredentialsId(String credentialsId) { this.credentialsId = credentialsId; return this; } public JiraSiteBuilder withSupportsWikiStyleComment(boolean supportsWikiStyleComment) { this.supportsWikiStyleComment = supportsWikiStyleComment; return this; } public JiraSiteBuilder withRecordScmChanges(boolean recordScmChanges) { this.recordScmChanges = recordScmChanges; return this; } public JiraSiteBuilder withUserPattern(String userPattern) { this.userPattern = userPattern; return this; } public JiraSiteBuilder withUpdateJiraIssueForAllStatus(boolean updateJiraIssueForAllStatus) { this.updateJiraIssueForAllStatus = updateJiraIssueForAllStatus; return this; } public JiraSiteBuilder withGroupVisibility(String groupVisibility) { this.groupVisibility = groupVisibility; return this; } public JiraSiteBuilder withRoleVisibility(String roleVisibility) { this.roleVisibility = roleVisibility; return this; } public JiraSiteBuilder withUseHTTPAuth(boolean useHTTPAuth) { this.useHTTPAuth = useHTTPAuth; return this; } public JiraSite build() { return new JiraSite(mainURL, alternativeURL, credentialsId, supportsWikiStyleComment, recordScmChanges, userPattern, updateJiraIssueForAllStatus, groupVisibility, roleVisibility, useHTTPAuth); } } }
package javaslang.collection; import javaslang.Tuple; import javaslang.Tuple2; import javaslang.control.None; import javaslang.control.Option; import javaslang.control.Some; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.*; import java.util.HashSet; import java.util.function.*; import java.util.regex.PatternSyntaxException; import java.util.stream.Collector; /** * TODO javadoc */ public final class CharSeq implements CharSequence, IndexedSeq<Character>, Serializable { private static final long serialVersionUID = 1L; private static final CharSeq EMPTY = new CharSeq(""); private final java.lang.String back; private CharSeq(java.lang.String javaString) { this.back = javaString; } public static CharSeq empty() { return EMPTY; } /** * Returns a {@link java.util.stream.Collector} which may be used in conjunction with * {@link java.util.stream.Stream#collect(java.util.stream.Collector)} to obtain a {@link CharSeq}. * * @return A {@code CharSeq} Collector. */ public static Collector<Character, ArrayList<Character>, CharSeq> collector() { final Supplier<ArrayList<Character>> supplier = ArrayList::new; final BiConsumer<ArrayList<Character>, Character> accumulator = ArrayList::add; final BinaryOperator<ArrayList<Character>> combiner = (left, right) -> { left.addAll(right); return left; }; final Function<ArrayList<Character>, CharSeq> finisher = CharSeq::ofAll; return Collector.of(supplier, accumulator, combiner, finisher); } /** * Returns a singleton {@code CharSeq}, i.e. a {@code CharSeq} of one character. * * @param character A character. * @return A new {@code CharSeq} instance containing the given element */ public static CharSeq of(char character) { return new CharSeq(new java.lang.String(new char[] { character })); } /** * Creates a String of the given characters. * * @param characters Zero or more characters. * @return A string containing the given characters in the same order. * @throws NullPointerException if {@code elements} is null */ public static CharSeq of(char... characters) { Objects.requireNonNull(characters, "characters is null"); final char[] chrs = new char[characters.length]; for (int i = 0; i < characters.length; i++) { chrs[i] = characters[i]; } return new CharSeq(new java.lang.String(chrs)); } /** * Creates a String of {@code CharSequence}. * * @param sequence {@code CharSequence} instance. * @return A new {@code javaslang.String} */ public static CharSeq of(CharSequence sequence) { Objects.requireNonNull(sequence, "sequence is null"); if (sequence instanceof CharSeq) { return (CharSeq) sequence; } else { return sequence.length() == 0 ? empty() : new CharSeq(sequence.toString()); } } /** * Creates a String of the given elements. * * The resulting string has the same iteration order as the given iterable of elements * if the iteration order of the elements is stable. * * @param elements An Iterable of elements. * @return A string containing the given elements in the same order. * @throws NullPointerException if {@code elements} is null */ public static CharSeq ofAll(java.lang.Iterable<? extends Character> elements) { Objects.requireNonNull(elements, "elements is null"); final StringBuilder sb = new StringBuilder(); for (Character character : elements) { sb.append(character); } return sb.length() == 0 ? EMPTY : of(sb.toString()); } /** * Creates a CharSeq based on the elements of a char array. * * @param array a char array * @return A new List of Character values */ public static CharSeq ofAll(char[] array) { Objects.requireNonNull(array, "array is null"); return new CharSeq(String.valueOf(array)); } /** * Creates a CharSeq starting from character {@code from}, extending to character {@code toExclusive - 1}. * <p> * Examples: * <pre> * <code> * CharSeq.range('a', 'c') // = "ab" * CharSeq.range('c', 'a') // = "" * </code> * </pre> * * @param from the first character * @param toExclusive the successor of the last character * @return a range of characters as specified or the empty range if {@code from >= toExclusive} */ public static CharSeq range(char from, char toExclusive) { return new CharSeq(Iterator.range(from ,toExclusive).mkString()); } public static CharSeq rangeBy(char from, char toExclusive, int step){ return new CharSeq(Iterator.rangeBy(from, toExclusive, step).mkString()); } /** * Creates a CharSeq starting from character {@code from}, extending to character {@code toInclusive}. * <p> * Examples: * <pre> * <code> * CharSeq.rangeClosed('a', 'c') // = "abc" * CharSeq.rangeClosed('c', 'a') // = "" * </code> * </pre> * * @param from the first character * @param toInclusive the last character * @return a range of characters as specified or the empty range if {@code from > toInclusive} */ public static CharSeq rangeClosed(char from, char toInclusive) { return new CharSeq(Iterator.rangeClosed(from, toInclusive).mkString()); } public static CharSeq rangeClosedBy(char from, char toInclusive, int step) { return new CharSeq(Iterator.rangeClosedBy(from, toInclusive, step).mkString()); } /** * Repeats a character {@code times} times. * * @param character A character * @param times Repetition count * @return A CharSeq representing {@code character * times} */ public static CharSeq repeat(char character, int times) { final int length = Math.max(times, 0); final char[] characters = new char[length]; Arrays.fill(characters, character); return new CharSeq(String.valueOf(characters)); } /** * Repeats this CharSeq {@code times} times. * <p> * Example: {@code CharSeq.of("ja").repeat(13) = "jajajajajajajajajajajajaja"} * * @param times Repetition count * @return A CharSeq representing {@code this * times} */ public CharSeq repeat(int times) { final StringBuilder builder = new StringBuilder(); for (int i = 0; i < times; i++) { builder.append(back); } return new CharSeq(builder.toString()); } // IndexedSeq @Override public CharSeq append(Character element) { return of(back + element); } @Override public CharSeq appendAll(java.lang.Iterable<? extends Character> elements) { Objects.requireNonNull(elements, "elements is null"); final StringBuilder sb = new StringBuilder(back); for (char element : elements) { sb.append(element); } return of(sb.toString()); } @Override public CharSeq clear() { return EMPTY; } @Override public Vector<Tuple2<Character, Character>> crossProduct() { return crossProduct(this); } @Override public Vector<IndexedSeq<Character>> crossProduct(int power) { return toStream().crossProduct(power).toVector(); } @Override public <U> Vector<Tuple2<Character, U>> crossProduct(java.lang.Iterable<? extends U> that) { Objects.requireNonNull(that, "that is null"); final Vector<U> other = Vector.ofAll(that); return flatMap(a -> other.map(b -> Tuple.of(a, b))); } @Override public Vector<CharSeq> combinations() { return Vector.rangeClosed(0, length()).map(this::combinations).flatMap(Function.identity()); } @Override public Vector<CharSeq> combinations(int k) { class Recursion { Vector<CharSeq> combinations(CharSeq elements, int k) { return (k == 0) ? Vector.of(CharSeq.empty()) : elements.zipWithIndex().flatMap(t -> combinations(elements.drop(t._2 + 1), (k - 1)) .map((CharSeq c) -> c.prepend(t._1))); } } return new Recursion().combinations(this, Math.max(k, 0)); } @Override public CharSeq distinct() { return distinctBy(Function.identity()); } @Override public CharSeq distinctBy(Comparator<? super Character> comparator) { Objects.requireNonNull(comparator, "comparator is null"); final java.util.Set<Character> seen = new java.util.TreeSet<>(comparator); return filter(seen::add); } @Override public <U> CharSeq distinctBy(Function<? super Character, ? extends U> keyExtractor) { Objects.requireNonNull(keyExtractor, "keyExtractor is null"); final java.util.Set<U> seen = new java.util.HashSet<>(); return filter(t -> seen.add(keyExtractor.apply(t))); } @Override public CharSeq drop(int n) { if (n >= length()) { return EMPTY; } if (n <= 0) { return this; } else { return of(back.substring(n)); } } @Override public CharSeq dropRight(int n) { if (n >= length()) { return EMPTY; } if (n <= 0) { return this; } else { return of(back.substring(0, length() - n)); } } @Override public CharSeq dropWhile(Predicate<? super Character> predicate) { Objects.requireNonNull(predicate, "predicate is null"); int index = 0; while (index < length() && predicate.test(charAt(index))) { index++; } return index < length() ? (index == 0 ? this : of(back.substring(index))) : empty(); } @Override public CharSeq filter(Predicate<? super Character> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < back.length(); i++) { final char ch = back.charAt(i); if (predicate.test(ch)) { sb.append(ch); } } return sb.length() == 0 ? EMPTY : sb.length() == length() ? this : of(sb.toString()); } @Override public <U> Vector<U> flatMap(Function<? super Character, ? extends java.lang.Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); if (isEmpty()) { return Vector.empty(); } else { Vector<U> result = Vector.empty(); for (int i = 0; i < length(); i++) { for (U u : mapper.apply(get(i))) { result = result.append(u); } } return result; } } public CharSeq flatMapChars(CharFunction<? extends CharSequence> mapper) { Objects.requireNonNull(mapper, "mapper is null"); if (isEmpty()) { return this; } else { final StringBuilder builder = new StringBuilder(); back.chars().forEach(c -> builder.append(mapper.apply((char) c))); return new CharSeq(builder.toString()); } } @Override public Vector<Object> flatten() { return Vector.ofAll(iterator()); } @Override public <C> Map<C, CharSeq> groupBy(Function<? super Character, ? extends C> classifier) { Objects.requireNonNull(classifier, "classifier is null"); return iterator().groupBy(classifier).map((c, it) -> Map.Entry.of(c, CharSeq.ofAll(it))); } @Override public boolean hasDefiniteSize() { return true; } @Override public CharSeq init() { if (isEmpty()) { throw new UnsupportedOperationException("init of empty string"); } else { return of(back.substring(0, length() - 1)); } } @Override public Option<CharSeq> initOption() { if (isEmpty()) { return None.instance(); } else { return new Some<>(init()); } } @Override public CharSeq insert(int index, Character element) { if (index < 0) { throw new IndexOutOfBoundsException("insert(" + index + ", e)"); } if (index > length()) { throw new IndexOutOfBoundsException("insert(" + index + ", e) on String of length " + length()); } return of(new StringBuilder(back).insert(index, element).toString()); } @Override public CharSeq insertAll(int index, java.lang.Iterable<? extends Character> elements) { Objects.requireNonNull(elements, "elements is null"); if (index < 0) { throw new IndexOutOfBoundsException("insertAll(" + index + ", elements)"); } if (index > length()) { throw new IndexOutOfBoundsException("insertAll(" + index + ", elements) on String of length " + length()); } final java.lang.String javaString = back; final StringBuilder sb = new StringBuilder(javaString.substring(0, index)); for (Character element : elements) { sb.append(element); } sb.append(javaString.substring(index)); return of(sb.toString()); } @Override public Iterator<Character> iterator() { return new Iterator<Character>() { private int index = 0; @Override public boolean hasNext() { return index < back.length(); } @Override public Character next() { if (index >= back.length()) { throw new NoSuchElementException(); } return back.charAt(index++); } }; } @Override public CharSeq intersperse(Character element) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < length(); i++) { if (i > 0) { sb.append(element); } sb.append(get(i)); } return sb.length() == 0 ? EMPTY : of(sb.toString()); } @Override public <U> Vector<U> map(Function<? super Character, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); Vector<U> result = Vector.empty(); for (int i = 0; i < length(); i++) { result = result.append(mapper.apply(get(i))); } return result; } @Override public CharSeq padTo(int length, Character element) { if (length <= back.length()) { return this; } final StringBuilder sb = new StringBuilder(back); final int limit = length - back.length(); for (int i = 0; i < limit; i++) { sb.append(element); } return new CharSeq(sb.toString()); } @Override public CharSeq patch(int from, java.lang.Iterable<? extends Character> that, int replaced) { from = from < 0 ? 0 : from > length() ? length() : from; replaced = replaced < 0 ? 0 : replaced; final StringBuilder sb = new StringBuilder(back.substring(0, from)); for (Character character : that) { sb.append(character); } from += replaced; if (from < length()) { sb.append(back.substring(from)); } return new CharSeq(sb.toString()); } public CharSeq mapChars(CharUnaryOperator mapper) { Objects.requireNonNull(mapper, "mapper is null"); if (isEmpty()) { return this; } else { final char[] chars = back.toCharArray(); for (int i = 0; i < chars.length; i++) { chars[i] = mapper.apply(chars[i]); } return CharSeq.ofAll(chars); } } @Override public Tuple2<CharSeq, CharSeq> partition(Predicate<? super Character> predicate) { Objects.requireNonNull(predicate, "predicate is null"); if (isEmpty()) { return Tuple.of(EMPTY, EMPTY); } final StringBuilder left = new StringBuilder(); final StringBuilder right = new StringBuilder(); for (int i = 0; i < length(); i++) { Character t = get(i); (predicate.test(t) ? left : right).append(t); } if (left.length() == 0) { return Tuple.of(EMPTY, of(right.toString())); } else if (right.length() == 0) { return Tuple.of(of(left.toString()), EMPTY); } else { return Tuple.of(of(left.toString()), of(right.toString())); } } @Override public CharSeq peek(Consumer<? super Character> action) { Objects.requireNonNull(action, "action is null"); if (!isEmpty()) { action.accept(back.charAt(0)); } return this; } @Override public Vector<CharSeq> permutations() { if (isEmpty()) { return Vector.empty(); } else { if (length() == 1) { return Vector.of(this); } else { Vector<CharSeq> result = Vector.empty(); for (Character t : distinct()) { for (CharSeq ts : remove(t).permutations()) { result = result.append(ts); } } return result; } } } @Override public CharSeq prepend(Character element) { return of(element + back); } @Override public CharSeq prependAll(java.lang.Iterable<? extends Character> elements) { Objects.requireNonNull(elements, "elements is null"); final StringBuilder sb = new StringBuilder(); for (Character element : elements) { sb.append(element); } sb.append(back); return sb.length() == 0 ? EMPTY : of(sb.toString()); } @Override public CharSeq remove(Character element) { final StringBuilder sb = new StringBuilder(); boolean found = false; for (int i = 0; i < length(); i++) { char c = get(i); if (!found && c == element) { found = true; } else { sb.append(c); } } return sb.length() == 0 ? EMPTY : sb.length() == length() ? this : of(sb.toString()); } @Override public CharSeq removeFirst(Predicate<Character> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final StringBuilder sb = new StringBuilder(); boolean found = false; for (int i = 0; i < back.length(); i++) { final char ch = back.charAt(i); if (predicate.test(ch)) { if (found) { sb.append(ch); } found = true; } else { sb.append(ch); } } return found ? (sb.length() == 0 ? EMPTY : of(sb.toString())) : this; } @Override public CharSeq removeLast(Predicate<Character> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (int i = length() - 1; i >= 0; i if (predicate.test(back.charAt(i))) { return removeAt(i); } } return this; } @Override public CharSeq removeAt(int index) { final java.lang.String removed = back.substring(0, index) + back.substring(index + 1); return removed.isEmpty() ? EMPTY : of(removed); } @Override public CharSeq removeAll(Character element) { final StringBuilder sb = new StringBuilder(); for (int i = 0; i < length(); i++) { final char c = back.charAt(i); if (c != element) { sb.append(c); } } return sb.length() == 0 ? EMPTY : sb.length() == length() ? this : of(sb.toString()); } @Override public CharSeq removeAll(java.lang.Iterable<? extends Character> elements) { Objects.requireNonNull(elements, "elements is null"); final java.util.Set<Character> distinct = new HashSet<>(); for (Character element : elements) { distinct.add(element); } final StringBuilder sb = new StringBuilder(); for (int i = 0; i < length(); i++) { final char c = back.charAt(i); if (!distinct.contains(c)) { sb.append(c); } } return sb.length() == 0 ? EMPTY : sb.length() == length() ? this : of(sb.toString()); } @Override public CharSeq replace(Character currentElement, Character newElement) { final StringBuilder sb = new StringBuilder(); boolean found = false; for (int i = 0; i < length(); i++) { final char c = back.charAt(i); if (c == currentElement && !found) { sb.append(newElement); found = true; } else { sb.append(c); } } return found ? (sb.length() == 0 ? EMPTY : of(sb.toString())) : this; } @Override public CharSeq replaceAll(Character currentElement, Character newElement) { final StringBuilder sb = new StringBuilder(); boolean found = false; for (int i = 0; i < length(); i++) { final char c = back.charAt(i); if (c == currentElement) { sb.append(newElement); found = true; } else { sb.append(c); } } return found ? (sb.length() == 0 ? EMPTY : of(sb.toString())) : this; } @Override public CharSeq replaceAll(UnaryOperator<Character> operator) { Objects.requireNonNull(operator, "operator is null"); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < length(); i++) { sb.append(operator.apply(back.charAt(i))); } return sb.length() == 0 ? EMPTY : of(sb.toString()); } @Override public CharSeq retainAll(java.lang.Iterable<? extends Character> elements) { Objects.requireNonNull(elements, "elements is null"); final java.util.Set<Character> keeped = new HashSet<>(); for (Character element : elements) { keeped.add(element); } final StringBuilder sb = new StringBuilder(); for (int i = 0; i < length(); i++) { final char c = back.charAt(i); if (keeped.contains(c)) { sb.append(c); } } return sb.length() == 0 ? EMPTY : of(sb.toString()); } @Override public CharSeq reverse() { return of(new StringBuilder(back).reverse().toString()); } @Override public CharSeq slice(int beginIndex) { if (beginIndex < 0) { throw new IndexOutOfBoundsException("slice(" + beginIndex + ")"); } if (beginIndex > length()) { throw new IndexOutOfBoundsException("slice(" + beginIndex + ")"); } return of(back.substring(beginIndex)); } @Override public CharSeq slice(int beginIndex, int endIndex) { if (beginIndex < 0 || beginIndex > endIndex || endIndex > length()) { throw new IndexOutOfBoundsException( java.lang.String.format("slice(%s, %s) on List of length %s", beginIndex, endIndex, length())); } if (beginIndex == endIndex) { return EMPTY; } return of(back.substring(beginIndex, endIndex)); } @Override public CharSeq sort() { return isEmpty() ? this : toJavaStream().sorted().collect(CharSeq.collector()); } @Override public CharSeq sort(Comparator<? super Character> comparator) { Objects.requireNonNull(comparator, "comparator is null"); return isEmpty() ? this : toJavaStream().sorted(comparator).collect(CharSeq.collector()); } @Override public Tuple2<CharSeq, CharSeq> span(Predicate<? super Character> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < length(); i++) { final char c = back.charAt(i); if (predicate.test(c)) { sb.append(c); } else { break; } } if (sb.length() == 0) { return Tuple.of(EMPTY, this); } else if (sb.length() == length()) { return Tuple.of(this, EMPTY); } else { return Tuple.of(of(sb.toString()), of(back.substring(sb.length()))); } } @Override public Spliterator<Character> spliterator() { return Spliterators.spliterator(iterator(), length(), Spliterator.ORDERED | Spliterator.IMMUTABLE); } @Override public CharSeq tail() { if (isEmpty()) { throw new UnsupportedOperationException("tail of empty string"); } else { return of(back.substring(1)); } } @Override public Option<CharSeq> tailOption() { if (isEmpty()) { return None.instance(); } else { return new Some<>(of(back.substring(1))); } } @Override public CharSeq take(int n) { if (n >= length()) { return this; } if (n <= 0) { return EMPTY; } else { return of(back.substring(0, n)); } } @Override public CharSeq takeRight(int n) { if (n >= length()) { return this; } if (n <= 0) { return EMPTY; } else { return of(back.substring(length() - n)); } } @Override public CharSeq takeUntil(Predicate<? super Character> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return takeWhile(predicate); } @Override public CharSeq takeWhile(Predicate<? super Character> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final StringBuilder sb = new StringBuilder(); for (int i = 0; i < length(); i++) { char c = back.charAt(i); if (!predicate.test(c)) { break; } sb.append(c); } return sb.length() == length() ? this : sb.length() == 0 ? EMPTY : of(sb.toString()); } @Override public <U> Vector<U> unit(java.lang.Iterable<? extends U> iterable) { Objects.requireNonNull(iterable, "iterable is null"); return Vector.ofAll(iterable); } @Override public <T1, T2> Tuple2<Vector<T1>, Vector<T2>> unzip(Function<? super Character, Tuple2<? extends T1, ? extends T2>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); Vector<T1> xs = Vector.empty(); Vector<T2> ys = Vector.empty(); for (int i = 0; i < length(); i++) { final Tuple2<? extends T1, ? extends T2> t = unzipper.apply(back.charAt(i)); xs = xs.append(t._1); ys = ys.append(t._2); } return Tuple.of(xs.length() == 0 ? Vector.<T1> empty() : xs, ys.length() == 0 ? Vector.<T2> empty() : ys); } @Override public CharSeq update(int index, Character element) { if (index < 0) { throw new IndexOutOfBoundsException("update(" + index + ")"); } if (index >= length()) { throw new IndexOutOfBoundsException("update(" + index + ")"); } return of(back.substring(0, index) + element + back.substring(index + 1)); } @Override public <U> Vector<Tuple2<Character, U>> zip(java.lang.Iterable<U> that) { Objects.requireNonNull(that, "that is null"); Vector<Tuple2<Character, U>> result = Vector.empty(); Iterator<Character> list1 = iterator(); java.util.Iterator<U> list2 = that.iterator(); while (list1.hasNext() && list2.hasNext()) { result = result.append(Tuple.of(list1.next(), list2.next())); } return result; } @Override public <U> Vector<Tuple2<Character, U>> zipAll(java.lang.Iterable<U> that, Character thisElem, U thatElem) { Objects.requireNonNull(that, "that is null"); Vector<Tuple2<Character, U>> result = Vector.empty(); Iterator<Character> list1 = iterator(); java.util.Iterator<U> list2 = that.iterator(); while (list1.hasNext() || list2.hasNext()) { final Character elem1 = list1.hasNext() ? list1.next() : thisElem; final U elem2 = list2.hasNext() ? list2.next() : thatElem; result = result.append(Tuple.of(elem1, elem2)); } return result; } @Override public Vector<Tuple2<Character, Integer>> zipWithIndex() { Vector<Tuple2<Character, Integer>> result = Vector.empty(); for (int i = 0; i < length(); i++) { result = result.append(Tuple.of(get(i), i)); } return result; } @Override public Character get(int index) { return back.charAt(index); } @Override public int indexOf(Character element, int from) { return back.indexOf(element, from); } @Override public int lastIndexOf(Character element, int end) { return back.lastIndexOf(element, end); } @Override public Tuple2<CharSeq, CharSeq> splitAt(int n) { if (n <= 0) { return Tuple.of(EMPTY, this); } else if (n >= length()) { return Tuple.of(this, EMPTY); } else { return Tuple.of(of(back.substring(0, n)), of(back.substring(n))); } } @Override public Tuple2<CharSeq, CharSeq> splitAt(Predicate<? super Character> predicate) { Objects.requireNonNull(predicate, "predicate is null"); if (isEmpty()) { return Tuple.of(EMPTY, EMPTY); } final StringBuilder left = new StringBuilder(); for (int i = 0; i < length(); i++) { Character t = get(i); if (!predicate.test(t)) { left.append(t); } else { break; } } if (left.length() == 0) { return Tuple.of(EMPTY, this); } else if (left.length() == length()) { return Tuple.of(this, EMPTY); } else { return Tuple.of(of(left.toString()), of(back.substring(left.length()))); } } @Override public Tuple2<CharSeq, CharSeq> splitAtInclusive(Predicate<? super Character> predicate) { Objects.requireNonNull(predicate, "predicate is null"); if (isEmpty()) { return Tuple.of(EMPTY, EMPTY); } final StringBuilder left = new StringBuilder(); for (int i = 0; i < length(); i++) { Character t = get(i); left.append(t); if (predicate.test(t)) { break; } } if (left.length() == 0) { return Tuple.of(EMPTY, this); } else if (left.length() == length()) { return Tuple.of(this, EMPTY); } else { return Tuple.of(of(left.toString()), of(back.substring(left.length()))); } } @Override public boolean startsWith(Iterable<? extends Character> that, int offset) { return startsWith(CharSeq.ofAll(that), offset); } @Override public Character head() { if (isEmpty()) { throw new NoSuchElementException("head of empty string"); } else { return back.charAt(0); } } @Override public Option<Character> headOption() { if (isEmpty()) { return None.instance(); } else { return new Some<>(back.charAt(0)); } } @Override public boolean isEmpty() { return back.isEmpty(); } @Override public boolean isTraversableAgain() { return true; } private Object readResolve() { return isEmpty() ? EMPTY : this; } @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof CharSeq) { return ((CharSeq) o).back.equals(back); } else { return false; } } @Override public int hashCode() { return back.hashCode(); } // java.lang.CharSequence /** * Returns the {@code char} value at the * specified index. An index ranges from {@code 0} to * {@code length() - 1}. The first {@code char} value of the sequence * is at index {@code 0}, the next at index {@code 1}, * and so on, as for array indexing. * * <p>If the {@code char} value specified by the index is a * <a href="Character.html#unicode">surrogate</a>, the surrogate * value is returned. * * @param index the index of the {@code char} value. * @return the {@code char} value at the specified index of this string. * The first {@code char} value is at index {@code 0}. * @throws IndexOutOfBoundsException if the {@code index} * argument is negative or not less than the length of this * string. */ @Override public char charAt(int index) { return back.charAt(index); } /** * Returns the length of this string. * The length is equal to the number of <a href="Character.html#unicode">Unicode * code units</a> in the string. * * @return the length of the sequence of characters represented by this * object. */ @Override public int length() { return back.length(); } // java.lang.String /** * Returns the character (Unicode code point) at the specified * index. The index refers to {@code char} values * (Unicode code units) and ranges from {@code 0} to * {@link #length()}{@code - 1}. * * <p> If the {@code char} value specified at the given index * is in the high-surrogate range, the following index is less * than the length of this {@code CharSeq}, and the * {@code char} value at the following index is in the * low-surrogate range, then the supplementary code point * corresponding to this surrogate pair is returned. Otherwise, * the {@code char} value at the given index is returned. * * @param index the index to the {@code char} values * @return the code point value of the character at the * {@code index} * @throws IndexOutOfBoundsException if the {@code index} * argument is negative or not less than the length of this * string. */ public int codePointAt(int index) { return back.codePointAt(index); } /** * Returns the character (Unicode code point) before the specified * index. The index refers to {@code char} values * (Unicode code units) and ranges from {@code 1} to {@link * CharSequence#length() length}. * * <p> If the {@code char} value at {@code (index - 1)} * is in the low-surrogate range, {@code (index - 2)} is not * negative, and the {@code char} value at {@code (index - * 2)} is in the high-surrogate range, then the * supplementary code point value of the surrogate pair is * returned. If the {@code char} value at {@code index - * 1} is an unpaired low-surrogate or a high-surrogate, the * surrogate value is returned. * * @param index the index following the code point that should be returned * @return the Unicode code point value before the given index. * @throws IndexOutOfBoundsException if the {@code index} * argument is less than 1 or greater than the length * of this string. */ public int codePointBefore(int index) { return back.codePointBefore(index); } /** * Returns the number of Unicode code points in the specified text * range of this {@code CharSeq}. The text range begins at the * specified {@code beginIndex} and extends to the * {@code char} at index {@code endIndex - 1}. Thus the * length (in {@code char}s) of the text range is * {@code endIndex-beginIndex}. Unpaired surrogates within * the text range count as one code point each. * * @param beginIndex the index to the first {@code char} of * the text range. * @param endIndex the index after the last {@code char} of * the text range. * @return the number of Unicode code points in the specified text * range * @throws IndexOutOfBoundsException if the * {@code beginIndex} is negative, or {@code endIndex} * is larger than the length of this {@code CharSeq}, or * {@code beginIndex} is larger than {@code endIndex}. */ public int codePointCount(int beginIndex, int endIndex) { return back.codePointCount(beginIndex, endIndex); } /** * Returns the index within this {@code CharSeq} that is * offset from the given {@code index} by * {@code codePointOffset} code points. Unpaired surrogates * within the text range given by {@code index} and * {@code codePointOffset} count as one code point each. * * @param index the index to be offset * @param codePointOffset the offset in code points * @return the index within this {@code CharSeq} * @throws IndexOutOfBoundsException if {@code index} * is negative or larger then the length of this * {@code CharSeq}, or if {@code codePointOffset} is positive * and the substring starting with {@code index} has fewer * than {@code codePointOffset} code points, * or if {@code codePointOffset} is negative and the substring * before {@code index} has fewer than the absolute value * of {@code codePointOffset} code points. */ public int offsetByCodePoints(int index, int codePointOffset) { return back.offsetByCodePoints(index, codePointOffset); } /** * Copies characters from this string into the destination character * array. * <p> * The first character to be copied is at index {@code srcBegin}; * the last character to be copied is at index {@code srcEnd-1} * (thus the total number of characters to be copied is * {@code srcEnd-srcBegin}). The characters are copied into the * subarray of {@code dst} starting at index {@code dstBegin} * and ending at index: * <blockquote><pre> * dstbegin + (srcEnd-srcBegin) - 1 * </pre></blockquote> * * @param srcBegin index of the first character in the string * to copy. * @param srcEnd index after the last character in the string * to copy. * @param dst the destination array. * @param dstBegin the start offset in the destination array. * @throws IndexOutOfBoundsException If any of the following * is true: * <ul><li>{@code srcBegin} is negative. * <li>{@code srcBegin} is greater than {@code srcEnd} * <li>{@code srcEnd} is greater than the length of this * string * <li>{@code dstBegin} is negative * <li>{@code dstBegin+(srcEnd-srcBegin)} is larger than * {@code dst.length}</ul> */ public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) { back.getChars(srcBegin, srcEnd, dst, dstBegin); } /** * Encodes this {@code CharSeq} into a sequence of bytes using the named * charset, storing the result into a new byte array. * * <p> The behavior of this method when this string cannot be encoded in * the given charset is unspecified. The {@link * java.nio.charset.CharsetEncoder} class should be used when more control * over the encoding process is required. * * @param charsetName The name of a supported {@linkplain java.nio.charset.Charset * charset} * @return The resultant byte array * @throws UnsupportedEncodingException If the named charset is not supported */ public byte[] getBytes(java.lang.String charsetName) throws UnsupportedEncodingException { return back.getBytes(charsetName); } /** * Encodes this {@code CharSeq} into a sequence of bytes using the given * {@linkplain java.nio.charset.Charset charset}, storing the result into a * new byte array. * * <p> This method always replaces malformed-input and unmappable-character * sequences with this charset's default replacement byte array. The * {@link java.nio.charset.CharsetEncoder} class should be used when more * control over the encoding process is required. * * @param charset The {@linkplain java.nio.charset.Charset} to be used to encode * the {@code CharSeq} * @return The resultant byte array */ public byte[] getBytes(Charset charset) { return back.getBytes(charset); } /** * Encodes this {@code CharSeq} into a sequence of bytes using the * platform's default charset, storing the result into a new byte array. * * <p> The behavior of this method when this string cannot be encoded in * the default charset is unspecified. The {@link * java.nio.charset.CharsetEncoder} class should be used when more control * over the encoding process is required. * * @return The resultant byte array */ public byte[] getBytes() { return back.getBytes(); } /** * Compares this string to the specified {@code StringBuffer}. The result * is {@code true} if and only if this {@code CharSeq} represents the same * sequence of characters as the specified {@code StringBuffer}. This method * synchronizes on the {@code StringBuffer}. * * @param sb The {@code StringBuffer} to compare this {@code CharSeq} against * @return {@code true} if this {@code CharSeq} represents the same * sequence of characters as the specified {@code StringBuffer}, * {@code false} otherwise */ public boolean contentEquals(StringBuffer sb) { return back.contentEquals(sb); } /** * Compares this string to the specified {@code CharSequence}. The * result is {@code true} if and only if this {@code CharSeq} represents the * same sequence of char values as the specified sequence. Note that if the * {@code CharSequence} is a {@code StringBuffer} then the method * synchronizes on it. * * @param cs The sequence to compare this {@code CharSeq} against * @return {@code true} if this {@code CharSeq} represents the same * sequence of char values as the specified sequence, {@code * false} otherwise */ public boolean contentEquals(CharSequence cs) { return back.contentEquals(cs); } /** * Compares this {@code CharSeq} to another {@code CharSeq}, ignoring case * considerations. Two strings are considered equal ignoring case if they * are of the same length and corresponding characters in the two strings * are equal ignoring case. * * <p> Two characters {@code c1} and {@code c2} are considered the same * ignoring case if at least one of the following is true: * <ul> * <li> The two characters are the same (as compared by the * {@code ==} operator) * <li> Applying the method {@link * java.lang.Character#toUpperCase(char)} to each character * produces the same result * <li> Applying the method {@link * java.lang.Character#toLowerCase(char)} to each character * produces the same result * </ul> * * @param anotherString The {@code CharSeq} to compare this {@code CharSeq} against * @return {@code true} if the argument is not {@code null} and it * represents an equivalent {@code CharSeq} ignoring case; {@code * false} otherwise * @see #equals(Object) */ public boolean equalsIgnoreCase(CharSeq anotherString) { return back.equalsIgnoreCase(anotherString.back); } /** * Compares two strings lexicographically. * The comparison is based on the Unicode value of each character in * the strings. The character sequence represented by this * {@code CharSeq} object is compared lexicographically to the * character sequence represented by the argument string. The result is * a negative integer if this {@code CharSeq} object * lexicographically precedes the argument string. The result is a * positive integer if this {@code CharSeq} object lexicographically * follows the argument string. The result is zero if the strings * are equal; {@code compareTo} returns {@code 0} exactly when * the {@link #equals(Object)} method would return {@code true}. * <p> * This is the definition of lexicographic ordering. If two strings are * different, then either they have different characters at some index * that is a valid index for both strings, or their lengths are different, * or both. If they have different characters at one or more index * positions, let <i>k</i> be the smallest such index; then the string * whose character at position <i>k</i> has the smaller value, as * determined by using the &lt; operator, lexicographically precedes the * other string. In this case, {@code compareTo} returns the * difference of the two character values at position {@code k} in * the two string -- that is, the value: * <blockquote><pre> * this.charAt(k)-anotherString.charAt(k) * </pre></blockquote> * If there is no index position at which they differ, then the shorter * string lexicographically precedes the longer string. In this case, * {@code compareTo} returns the difference of the lengths of the * strings -- that is, the value: * <blockquote><pre> * this.length()-anotherString.length() * </pre></blockquote> * * @param anotherString the {@code CharSeq} to be compared. * @return the value {@code 0} if the argument string is equal to * this string; a value less than {@code 0} if this string * is lexicographically less than the string argument; and a * value greater than {@code 0} if this string is * lexicographically greater than the string argument. */ public int compareTo(CharSeq anotherString) { return back.compareTo(anotherString.back); } /** * Compares two strings lexicographically, ignoring case * differences. This method returns an integer whose sign is that of * calling {@code compareTo} with normalized versions of the strings * where case differences have been eliminated by calling * {@code Character.toLowerCase(Character.toUpperCase(character))} on * each character. * <p> * Note that this method does <em>not</em> take locale into account, * and will result in an unsatisfactory ordering for certain locales. * The java.text package provides <em>collators</em> to allow * locale-sensitive ordering. * * @param str the {@code CharSeq} to be compared. * @return a negative integer, zero, or a positive integer as the * specified String is greater than, equal to, or less * than this String, ignoring case considerations. */ public int compareToIgnoreCase(CharSeq str) { return back.compareToIgnoreCase(str.back); } /** * Tests if two string regions are equal. * <p> * A substring of this {@code CharSeq} object is compared to a substring * of the argument other. The result is true if these substrings * represent identical character sequences. The substring of this * {@code CharSeq} object to be compared begins at index {@code toffset} * and has length {@code len}. The substring of other to be compared * begins at index {@code ooffset} and has length {@code len}. The * result is {@code false} if and only if at least one of the following * is true: * <ul><li>{@code toffset} is negative. * <li>{@code ooffset} is negative. * <li>{@code toffset+len} is greater than the length of this * {@code CharSeq} object. * <li>{@code ooffset+len} is greater than the length of the other * argument. * <li>There is some nonnegative integer <i>k</i> less than {@code len} * such that: * {@code this.charAt(toffset + }<i>k</i>{@code ) != other.charAt(ooffset + } * <i>k</i>{@code )} * </ul> * * @param toffset the starting offset of the subregion in this string. * @param other the string argument. * @param ooffset the starting offset of the subregion in the string * argument. * @param len the number of characters to compare. * @return {@code true} if the specified subregion of this string * exactly matches the specified subregion of the string argument; * {@code false} otherwise. */ public boolean regionMatches(int toffset, CharSeq other, int ooffset, int len) { return back.regionMatches(toffset, other.back, ooffset, len); } /** * Tests if two string regions are equal. * <p> * A substring of this {@code CharSeq} object is compared to a substring * of the argument {@code other}. The result is {@code true} if these * substrings represent character sequences that are the same, ignoring * case if and only if {@code ignoreCase} is true. The substring of * this {@code CharSeq} object to be compared begins at index * {@code toffset} and has length {@code len}. The substring of * {@code other} to be compared begins at index {@code ooffset} and * has length {@code len}. The result is {@code false} if and only if * at least one of the following is true: * <ul><li>{@code toffset} is negative. * <li>{@code ooffset} is negative. * <li>{@code toffset+len} is greater than the length of this * {@code CharSeq} object. * <li>{@code ooffset+len} is greater than the length of the other * argument. * <li>{@code ignoreCase} is {@code false} and there is some nonnegative * integer <i>k</i> less than {@code len} such that: * <blockquote><pre> * this.charAt(toffset+k) != other.charAt(ooffset+k) * </pre></blockquote> * <li>{@code ignoreCase} is {@code true} and there is some nonnegative * integer <i>k</i> less than {@code len} such that: * <blockquote><pre> * Character.toLowerCase(this.charAt(toffset+k)) != * Character.toLowerCase(other.charAt(ooffset+k)) * </pre></blockquote> * and: * <blockquote><pre> * Character.toUpperCase(this.charAt(toffset+k)) != * Character.toUpperCase(other.charAt(ooffset+k)) * </pre></blockquote> * </ul> * * @param ignoreCase if {@code true}, ignore case when comparing * characters. * @param toffset the starting offset of the subregion in this * string. * @param other the string argument. * @param ooffset the starting offset of the subregion in the string * argument. * @param len the number of characters to compare. * @return {@code true} if the specified subregion of this string * matches the specified subregion of the string argument; * {@code false} otherwise. Whether the matching is exact * or case insensitive depends on the {@code ignoreCase} * argument. */ public boolean regionMatches(boolean ignoreCase, int toffset, CharSeq other, int ooffset, int len) { return back.regionMatches(ignoreCase, toffset, other.back, ooffset, len); } @Override public CharSeq subSequence(int beginIndex, int endIndex) { return slice(beginIndex, endIndex); } /** * Tests if the substring of this string beginning at the * specified index starts with the specified prefix. * * @param prefix the prefix. * @param toffset where to begin looking in this string. * @return {@code true} if the character sequence represented by the * argument is a prefix of the substring of this object starting * at index {@code toffset}; {@code false} otherwise. * The result is {@code false} if {@code toffset} is * negative or greater than the length of this * {@code CharSeq} object; otherwise the result is the same * as the result of the expression * <pre> * this.substring(toffset).startsWith(prefix) * </pre> */ public boolean startsWith(CharSeq prefix, int toffset) { return back.startsWith(prefix.back, toffset); } /** * Tests if this string starts with the specified prefix. * * @param prefix the prefix. * @return {@code true} if the character sequence represented by the * argument is a prefix of the character sequence represented by * this string; {@code false} otherwise. * Note also that {@code true} will be returned if the * argument is an empty string or is equal to this * {@code CharSeq} object as determined by the * {@link #equals(Object)} method. */ public boolean startsWith(CharSeq prefix) { return back.startsWith(prefix.back); } /** * Tests if this string ends with the specified suffix. * * @param suffix the suffix. * @return {@code true} if the character sequence represented by the * argument is a suffix of the character sequence represented by * this object; {@code false} otherwise. Note that the * result will be {@code true} if the argument is the * empty string or is equal to this {@code CharSeq} object * as determined by the {@link #equals(Object)} method. */ public boolean endsWith(CharSeq suffix) { return back.endsWith(suffix.back); } /** * Returns the index within this string of the first occurrence of * the specified character. If a character with value * {@code ch} occurs in the character sequence represented by * this {@code CharSeq} object, then the index (in Unicode * code units) of the first such occurrence is returned. For * values of {@code ch} in the range from 0 to 0xFFFF * (inclusive), this is the smallest value <i>k</i> such that: * <blockquote><pre> * this.charAt(<i>k</i>) == ch * </pre></blockquote> * is true. For other values of {@code ch}, it is the * smallest value <i>k</i> such that: * <blockquote><pre> * this.codePointAt(<i>k</i>) == ch * </pre></blockquote> * is true. In either case, if no such character occurs in this * string, then {@code -1} is returned. * * @param ch a character (Unicode code point). * @return the index of the first occurrence of the character in the * character sequence represented by this object, or * {@code -1} if the character does not occur. */ public int indexOf(int ch) { return back.indexOf(ch); } /** * Returns the index within this string of the first occurrence of the * specified character, starting the search at the specified index. * <p> * If a character with value {@code ch} occurs in the * character sequence represented by this {@code CharSeq} * object at an index no smaller than {@code fromIndex}, then * the index of the first such occurrence is returned. For values * of {@code ch} in the range from 0 to 0xFFFF (inclusive), * this is the smallest value <i>k</i> such that: * <blockquote><pre> * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &gt;= fromIndex) * </pre></blockquote> * is true. For other values of {@code ch}, it is the * smallest value <i>k</i> such that: * <blockquote><pre> * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &gt;= fromIndex) * </pre></blockquote> * is true. In either case, if no such character occurs in this * string at or after position {@code fromIndex}, then * {@code -1} is returned. * * <p> * There is no restriction on the value of {@code fromIndex}. If it * is negative, it has the same effect as if it were zero: this entire * string may be searched. If it is greater than the length of this * string, it has the same effect as if it were equal to the length of * this string: {@code -1} is returned. * * <p>All indices are specified in {@code char} values * (Unicode code units). * * @param ch a character (Unicode code point). * @param fromIndex the index to start the search from. * @return the index of the first occurrence of the character in the * character sequence represented by this object that is greater * than or equal to {@code fromIndex}, or {@code -1} * if the character does not occur. */ public int indexOf(int ch, int fromIndex) { return back.indexOf(ch, fromIndex); } /** * Returns the index within this string of the last occurrence of * the specified character. For values of {@code ch} in the * range from 0 to 0xFFFF (inclusive), the index (in Unicode code * units) returned is the largest value <i>k</i> such that: * <blockquote><pre> * this.charAt(<i>k</i>) == ch * </pre></blockquote> * is true. For other values of {@code ch}, it is the * largest value <i>k</i> such that: * <blockquote><pre> * this.codePointAt(<i>k</i>) == ch * </pre></blockquote> * is true. In either case, if no such character occurs in this * string, then {@code -1} is returned. The * {@code CharSeq} is searched backwards starting at the last * character. * * @param ch a character (Unicode code point). * @return the index of the last occurrence of the character in the * character sequence represented by this object, or * {@code -1} if the character does not occur. */ public int lastIndexOf(int ch) { return back.lastIndexOf(ch); } /** * Returns the index within this string of the last occurrence of * the specified character, searching backward starting at the * specified index. For values of {@code ch} in the range * from 0 to 0xFFFF (inclusive), the index returned is the largest * value <i>k</i> such that: * <blockquote><pre> * (this.charAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &lt;= fromIndex) * </pre></blockquote> * is true. For other values of {@code ch}, it is the * largest value <i>k</i> such that: * <blockquote><pre> * (this.codePointAt(<i>k</i>) == ch) {@code &&} (<i>k</i> &lt;= fromIndex) * </pre></blockquote> * is true. In either case, if no such character occurs in this * string at or before position {@code fromIndex}, then * {@code -1} is returned. * * <p>All indices are specified in {@code char} values * (Unicode code units). * * @param ch a character (Unicode code point). * @param fromIndex the index to start the search from. There is no * restriction on the value of {@code fromIndex}. If it is * greater than or equal to the length of this string, it has * the same effect as if it were equal to one less than the * length of this string: this entire string may be searched. * If it is negative, it has the same effect as if it were -1: * -1 is returned. * @return the index of the last occurrence of the character in the * character sequence represented by this object that is less * than or equal to {@code fromIndex}, or {@code -1} * if the character does not occur before that point. */ public int lastIndexOf(int ch, int fromIndex) { return back.lastIndexOf(ch, fromIndex); } /** * Returns the index within this string of the first occurrence of the * specified substring. * * <p>The returned index is the smallest value <i>k</i> for which: * <blockquote><pre> * this.startsWith(str, <i>k</i>) * </pre></blockquote> * If no such value of <i>k</i> exists, then {@code -1} is returned. * * @param str the substring to search for. * @return the index of the first occurrence of the specified substring, * or {@code -1} if there is no such occurrence. */ public int indexOf(CharSeq str) { return back.indexOf(str.back); } /** * Returns the index within this string of the first occurrence of the * specified substring, starting at the specified index. * * <p>The returned index is the smallest value <i>k</i> for which: * <blockquote><pre> * <i>k</i> &gt;= fromIndex {@code &&} this.startsWith(str, <i>k</i>) * </pre></blockquote> * If no such value of <i>k</i> exists, then {@code -1} is returned. * * @param str the substring to search for. * @param fromIndex the index from which to start the search. * @return the index of the first occurrence of the specified substring, * starting at the specified index, * or {@code -1} if there is no such occurrence. */ public int indexOf(CharSeq str, int fromIndex) { return back.indexOf(str.back, fromIndex); } /** * Returns the index within this string of the last occurrence of the * specified substring. The last occurrence of the empty string "" * is considered to occur at the index value {@code this.length()}. * * <p>The returned index is the largest value <i>k</i> for which: * <blockquote><pre> * this.startsWith(str, <i>k</i>) * </pre></blockquote> * If no such value of <i>k</i> exists, then {@code -1} is returned. * * @param str the substring to search for. * @return the index of the last occurrence of the specified substring, * or {@code -1} if there is no such occurrence. */ public int lastIndexOf(CharSeq str) { return back.lastIndexOf(str.back); } /** * Returns the index within this string of the last occurrence of the * specified substring, searching backward starting at the specified index. * * <p>The returned index is the largest value <i>k</i> for which: * <blockquote><pre> * <i>k</i> {@code <=} fromIndex {@code &&} this.startsWith(str, <i>k</i>) * </pre></blockquote> * If no such value of <i>k</i> exists, then {@code -1} is returned. * * @param str the substring to search for. * @param fromIndex the index to start the search from. * @return the index of the last occurrence of the specified substring, * searching backward from the specified index, * or {@code -1} if there is no such occurrence. */ public int lastIndexOf(CharSeq str, int fromIndex) { return back.lastIndexOf(str.back, fromIndex); } /** * Returns a string that is a substring of this string. The * substring begins with the character at the specified index and * extends to the end of this string. <p> * Examples: * <blockquote><pre> * "unhappy".substring(2) returns "happy" * "Harbison".substring(3) returns "bison" * "emptiness".substring(9) returns "" (an empty string) * </pre></blockquote> * * @param beginIndex the beginning index, inclusive. * @return the specified substring. * @throws IndexOutOfBoundsException if * {@code beginIndex} is negative or larger than the * length of this {@code CharSeq} object. */ public CharSeq substring(int beginIndex) { return of(back.substring(beginIndex)); } /** * Returns a string that is a substring of this string. The * substring begins at the specified {@code beginIndex} and * extends to the character at index {@code endIndex - 1}. * Thus the length of the substring is {@code endIndex-beginIndex}. * <p> * Examples: * <blockquote><pre> * "hamburger".substring(4, 8) returns "urge" * "smiles".substring(1, 5) returns "mile" * </pre></blockquote> * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @throws IndexOutOfBoundsException if the * {@code beginIndex} is negative, or * {@code endIndex} is larger than the length of * this {@code CharSeq} object, or * {@code beginIndex} is larger than * {@code endIndex}. */ public CharSeq substring(int beginIndex, int endIndex) { return of(back.substring(beginIndex, endIndex)); } /** * Returns a string containing the characters in this sequence in the same * order as this sequence. The length of the string will be the length of * this sequence. * * @return a string consisting of exactly this sequence of characters */ @Override public java.lang.String toString() { return back; } /** * Concatenates the specified string to the end of this string. * <p> * If the length of the argument string is {@code 0}, then this * {@code CharSeq} object is returned. Otherwise, a * {@code CharSeq} object is returned that represents a character * sequence that is the concatenation of the character sequence * represented by this {@code CharSeq} object and the character * sequence represented by the argument string.<p> * Examples: * <blockquote><pre> * "cares".concat("s") returns "caress" * "to".concat("get").concat("her") returns "together" * </pre></blockquote> * * @param str the {@code CharSeq} that is concatenated to the end * of this {@code CharSeq}. * @return a string that represents the concatenation of this object's * characters followed by the string argument's characters. */ public CharSeq concat(CharSeq str) { return of(back.concat(str.back)); } /** * Tells whether or not this string matches the given <a * href="../util/regex/Pattern.html#sum">regular expression</a>. * * <p> An invocation of this method of the form * <i>str</i>{@code .matches(}<i>regex</i>{@code )} yields exactly the * same result as the expression * * <blockquote> * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#matches(java.lang.String, CharSequence) * matches(<i>regex</i>, <i>str</i>)} * </blockquote> * * @param regex the regular expression to which this string is to be matched * @return {@code true} if, and only if, this string matches the * given regular expression * @throws PatternSyntaxException if the regular expression's syntax is invalid * @see java.util.regex.Pattern */ public boolean matches(java.lang.String regex) { return back.matches(regex); } /** * Returns true if and only if this string contains the specified * sequence of char values. * * @param s the sequence to search for * @return true if this string contains {@code s}, false otherwise */ public boolean contains(CharSequence s) { return back.contains(s); } /** * Replaces the first substring of this string that matches the given <a * href="../util/regex/Pattern.html#sum">regular expression</a> with the * given replacement. * * <p> An invocation of this method of the form * <i>str</i>{@code .replaceFirst(}<i>regex</i>{@code ,} <i>repl</i>{@code )} * yields exactly the same result as the expression * * <blockquote> * <code> * {@link java.util.regex.Pattern}.{@link * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link * java.util.regex.Matcher#replaceFirst replaceFirst}(<i>repl</i>) * </code> * </blockquote> * * <p> * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the * replacement string may cause the results to be different than if it were * being treated as a literal replacement string; see * {@link java.util.regex.Matcher#replaceFirst}. * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special * meaning of these characters, if desired. * * @param regex the regular expression to which this string is to be matched * @param replacement the string to be substituted for the first match * @return The resulting {@code CharSeq} * @throws PatternSyntaxException if the regular expression's syntax is invalid * @see java.util.regex.Pattern */ public CharSeq replaceFirst(java.lang.String regex, java.lang.String replacement) { return of(back.replaceFirst(regex, replacement)); } /** * Replaces each substring of this string that matches the given <a * href="../util/regex/Pattern.html#sum">regular expression</a> with the * given replacement. * * <p> An invocation of this method of the form * <i>str</i>{@code .replaceAll(}<i>regex</i>{@code ,} <i>repl</i>{@code )} * yields exactly the same result as the expression * * <blockquote> * <code> * {@link java.util.regex.Pattern}.{@link * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link * java.util.regex.Pattern#matcher(java.lang.CharSequence) matcher}(<i>str</i>).{@link * java.util.regex.Matcher#replaceAll replaceAll}(<i>repl</i>) * </code> * </blockquote> * * <p> * Note that backslashes ({@code \}) and dollar signs ({@code $}) in the * replacement string may cause the results to be different than if it were * being treated as a literal replacement string; see * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}. * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special * meaning of these characters, if desired. * * @param regex the regular expression to which this string is to be matched * @param replacement the string to be substituted for each match * @return The resulting {@code CharSeq} * @throws PatternSyntaxException if the regular expression's syntax is invalid * @see java.util.regex.Pattern */ public CharSeq replaceAll(java.lang.String regex, java.lang.String replacement) { return of(back.replaceAll(regex, replacement)); } /** * Replaces each substring of this string that matches the literal target * sequence with the specified literal replacement sequence. The * replacement proceeds from the beginning of the string to the end, for * example, replacing "aa" with "b" in the string "aaa" will result in * "ba" rather than "ab". * * @param target The sequence of char values to be replaced * @param replacement The replacement sequence of char values * @return The resulting string */ public CharSeq replace(CharSequence target, CharSequence replacement) { return of(back.replace(target, replacement)); } /** * Splits this string around matches of the given * <a href="../util/regex/Pattern.html#sum">regular expression</a>. * * <p> The array returned by this method contains each substring of this * string that is terminated by another substring that matches the given * expression or is terminated by the end of the string. The substrings in * the array are in the order in which they occur in this string. If the * expression does not match any part of the input then the resulting array * has just one element, namely this string. * * <p> When there is a positive-width match at the beginning of this * string then an empty leading substring is included at the beginning * of the resulting array. A zero-width match at the beginning however * never produces such empty leading substring. * * <p> The {@code limit} parameter controls the number of times the * pattern is applied and therefore affects the length of the resulting * array. If the limit <i>n</i> is greater than zero then the pattern * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's * length will be no greater than <i>n</i>, and the array's last entry * will contain all input beyond the last matched delimiter. If <i>n</i> * is non-positive then the pattern will be applied as many times as * possible and the array can have any length. If <i>n</i> is zero then * the pattern will be applied as many times as possible, the array can * have any length, and trailing empty strings will be discarded. * * <p> The string {@code "boo:and:foo"}, for example, yields the * following results with these parameters: * * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result"> * <tr> * <th>Regex</th> * <th>Limit</th> * <th>Result</th> * </tr> * <tr><td align=center>:</td> * <td align=center>2</td> * <td>{@code { "boo", "and:foo" }}</td></tr> * <tr><td align=center>:</td> * <td align=center>5</td> * <td>{@code { "boo", "and", "foo" }}</td></tr> * <tr><td align=center>:</td> * <td align=center>-2</td> * <td>{@code { "boo", "and", "foo" }}</td></tr> * <tr><td align=center>o</td> * <td align=center>5</td> * <td>{@code { "b", "", ":and:f", "", "" }}</td></tr> * <tr><td align=center>o</td> * <td align=center>-2</td> * <td>{@code { "b", "", ":and:f", "", "" }}</td></tr> * <tr><td align=center>o</td> * <td align=center>0</td> * <td>{@code { "b", "", ":and:f" }}</td></tr> * </table></blockquote> * * <p> An invocation of this method of the form * <i>str.</i>{@code split(}<i>regex</i>{@code ,}&nbsp;<i>n</i>{@code )} * yields the same result as the expression * * <blockquote> * <code> * {@link java.util.regex.Pattern}.{@link * java.util.regex.Pattern#compile compile}(<i>regex</i>).{@link * java.util.regex.Pattern#split(java.lang.CharSequence, int) split}(<i>str</i>,&nbsp;<i>n</i>) * </code> * </blockquote> * * @param regex the delimiting regular expression * @param limit the result threshold, as described above * @return the array of strings computed by splitting this string * around matches of the given regular expression * @throws PatternSyntaxException if the regular expression's syntax is invalid * @see java.util.regex.Pattern */ public CharSeq[] split(java.lang.String regex, int limit) { final java.lang.String[] javaStrings = back.split(regex, limit); final CharSeq[] strings = new CharSeq[javaStrings.length]; for (int i = 0; i < strings.length; i++) { strings[i] = of(javaStrings[i]); } return strings; } /** * Splits this string around matches of the given <a * href="../util/regex/Pattern.html#sum">regular expression</a>. * * <p> This method works as if by invoking the two-argument {@link * #split(java.lang.String, int) split} method with the given expression and a limit * argument of zero. Trailing empty strings are therefore not included in * the resulting array. * * <p> The string {@code "boo:and:foo"}, for example, yields the following * results with these expressions: * * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result"> * <tr> * <th>Regex</th> * <th>Result</th> * </tr> * <tr><td align=center>:</td> * <td>{@code { "boo", "and", "foo" }}</td></tr> * <tr><td align=center>o</td> * <td>{@code { "b", "", ":and:f" }}</td></tr> * </table></blockquote> * * @param regex the delimiting regular expression * @return the array of strings computed by splitting this string * around matches of the given regular expression * @throws PatternSyntaxException if the regular expression's syntax is invalid * @see java.util.regex.Pattern */ public CharSeq[] split(java.lang.String regex) { return split(regex, 0); } /** * Converts all of the characters in this {@code CharSeq} to lower * case using the rules of the given {@code Locale}. Case mapping is based * on the Unicode Standard version specified by the {@link java.lang.Character Character} * class. Since case mappings are not always 1:1 char mappings, the resulting * {@code CharSeq} may be a different length than the original {@code CharSeq}. * <p> * Examples of lowercase mappings are in the following table: * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description"> * <tr> * <th>Language Code of Locale</th> * <th>Upper Case</th> * <th>Lower Case</th> * <th>Description</th> * </tr> * <tr> * <td>tr (Turkish)</td> * <td>&#92;u0130</td> * <td>&#92;u0069</td> * <td>capital letter I with dot above -&gt; small letter i</td> * </tr> * <tr> * <td>tr (Turkish)</td> * <td>&#92;u0049</td> * <td>&#92;u0131</td> * <td>capital letter I -&gt; small letter dotless i </td> * </tr> * <tr> * <td>(all)</td> * <td>French Fries</td> * <td>french fries</td> * <td>lowercased all chars in String</td> * </tr> * <tr> * <td>(all)</td> * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi"> * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil"> * <img src="doc-files/capsigma.gif" alt="capsigma"></td> * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi"> * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon"> * <img src="doc-files/sigma1.gif" alt="sigma"></td> * <td>lowercased all chars in String</td> * </tr> * </table> * * @param locale use the case transformation rules for this locale * @return the {@code CharSeq}, converted to lowercase. * @see java.lang.String#toLowerCase() * @see java.lang.String#toUpperCase() * @see java.lang.String#toUpperCase(Locale) */ public CharSeq toLowerCase(Locale locale) { return of(back.toLowerCase(locale)); } /** * Converts all of the characters in this {@code CharSeq} to lower * case using the rules of the default locale. This is equivalent to calling * {@code toLowerCase(Locale.getDefault())}. * <p> * <b>Note:</b> This method is locale sensitive, and may produce unexpected * results if used for strings that are intended to be interpreted locale * independently. * Examples are programming language identifiers, protocol keys, and HTML * tags. * For instance, {@code "TITLE".toLowerCase()} in a Turkish locale * returns {@code "t\u005Cu0131tle"}, where '\u005Cu0131' is the * LATIN SMALL LETTER DOTLESS I character. * To obtain correct results for locale insensitive strings, use * {@code toLowerCase(Locale.ROOT)}. * <p> * * @return the {@code CharSeq}, converted to lowercase. * @see java.lang.String#toLowerCase(Locale) */ public CharSeq toLowerCase() { return toLowerCase(Locale.getDefault()); } /** * Converts all of the characters in this {@code CharSeq} to upper * case using the rules of the given {@code Locale}. Case mapping is based * on the Unicode Standard version specified by the {@link java.lang.Character Character} * class. Since case mappings are not always 1:1 char mappings, the resulting * {@code CharSeq} may be a different length than the original {@code CharSeq}. * <p> * Examples of locale-sensitive and 1:M case mappings are in the following table. * * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description."> * <tr> * <th>Language Code of Locale</th> * <th>Lower Case</th> * <th>Upper Case</th> * <th>Description</th> * </tr> * <tr> * <td>tr (Turkish)</td> * <td>&#92;u0069</td> * <td>&#92;u0130</td> * <td>small letter i -&gt; capital letter I with dot above</td> * </tr> * <tr> * <td>tr (Turkish)</td> * <td>&#92;u0131</td> * <td>&#92;u0049</td> * <td>small letter dotless i -&gt; capital letter I</td> * </tr> * <tr> * <td>(all)</td> * <td>&#92;u00df</td> * <td>&#92;u0053 &#92;u0053</td> * <td>small letter sharp s -&gt; two letters: SS</td> * </tr> * <tr> * <td>(all)</td> * <td>Fahrvergn&uuml;gen</td> * <td>FAHRVERGN&Uuml;GEN</td> * <td></td> * </tr> * </table> * * @param locale use the case transformation rules for this locale * @return the {@code CharSeq}, converted to uppercase. * @see java.lang.String#toUpperCase() * @see java.lang.String#toLowerCase() * @see java.lang.String#toLowerCase(Locale) */ public CharSeq toUpperCase(Locale locale) { return of(back.toUpperCase(locale)); } /** * Converts all of the characters in this {@code CharSeq} to upper * case using the rules of the default locale. This method is equivalent to * {@code toUpperCase(Locale.getDefault())}. * <p> * <b>Note:</b> This method is locale sensitive, and may produce unexpected * results if used for strings that are intended to be interpreted locale * independently. * Examples are programming language identifiers, protocol keys, and HTML * tags. * For instance, {@code "title".toUpperCase()} in a Turkish locale * returns {@code "T\u005Cu0130TLE"}, where '\u005Cu0130' is the * LATIN CAPITAL LETTER I WITH DOT ABOVE character. * To obtain correct results for locale insensitive strings, use * {@code toUpperCase(Locale.ROOT)}. * <p> * * @return the {@code CharSeq}, converted to uppercase. * @see java.lang.String#toUpperCase(Locale) */ public CharSeq toUpperCase() { return toUpperCase(Locale.getDefault()); } /** * Returns a string whose value is this string, with any leading and trailing * whitespace removed. * <p> * If this {@code CharSeq} object represents an empty character * sequence, or the first and last characters of character sequence * represented by this {@code CharSeq} object both have codes * greater than {@code '\u005Cu0020'} (the space character), then a * reference to this {@code CharSeq} object is returned. * <p> * Otherwise, if there is no character with a code greater than * {@code '\u005Cu0020'} in the string, then a * {@code CharSeq} object representing an empty string is * returned. * <p> * Otherwise, let <i>k</i> be the index of the first character in the * string whose code is greater than {@code '\u005Cu0020'}, and let * <i>m</i> be the index of the last character in the string whose code * is greater than {@code '\u005Cu0020'}. A {@code CharSeq} * object is returned, representing the substring of this string that * begins with the character at index <i>k</i> and ends with the * character at index <i>m</i>-that is, the result of * {@code this.substring(k, m + 1)}. * <p> * This method may be used to trim whitespace (as defined above) from * the beginning and end of a string. * * @return A string whose value is this string, with any leading and trailing white * space removed, or this string if it has no leading or * trailing white space. */ public CharSeq trim() { return of(back.trim()); } /** * Converts this string to a new character array. * * @return a newly allocated character array whose length is the length * of this string and whose contents are initialized to contain * the character sequence represented by this string. */ public char[] toCharArray() { return back.toCharArray(); } @FunctionalInterface interface CharUnaryOperator { char apply(char c); } @FunctionalInterface interface CharFunction<R> { R apply(char c); } }
package com.deftlabs.core.util; // Java import java.util.Map; import java.util.Set; import java.util.Collection; import java.util.LinkedHashMap; import java.util.concurrent.locks.ReentrantLock; /** * An lru linked hash map. Access to this map is thread-safe. This class also * supports an optional eviction handler. To handle old data that is removed * from the map. */ public class LruMap<K,V> implements Map<K, V> { private final LinkedHashMap<K,V> _map; private final LruMap.EvictionHandler<K, V> _handler; private final int _size; private final ReentrantLock _lock = new ReentrantLock(); private static final float LOAD_FACTOR = 0.75f; /** * Create a new lru map. * @param pSize The max size of the map. */ public LruMap(final int pSize) { this(pSize, null); } /** * Create a new lru linked hash map. * @param pSize The max size of the map. * @param pHandler The optional eviction handler. */ public LruMap( final int pSize, final LruMap.EvictionHandler<K, V> pHandler) { _size = pSize; _handler = pHandler; final int capacity = (int)Math.ceil(_size / LOAD_FACTOR) + 1; _map = new LinkedHashMap<K,V>(capacity, LOAD_FACTOR, true) { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry(Map.Entry<K,V> pEldest) { final boolean remove = (size() > LruMap.this._size); if (!remove) return remove; if (_handler == null) return remove; LruMap.this._handler.execute(pEldest); return remove; } }; } @Override public void clear() { try { _lock.lock(); _map.clear(); } finally { _lock.unlock(); } } @Override public int size() { try { _lock.lock(); return _map.size(); } finally { _lock.unlock(); } } @Override public Collection<V> values() { try { _lock.lock(); return _map.values(); } finally { _lock.unlock(); } } @Override public int hashCode() { try { _lock.lock(); return _map.hashCode(); } finally { _lock.unlock(); } } @Override public V get (final Object pKey) { try { _lock.lock(); return _map.get(pKey); } finally { _lock.unlock(); } } @Override public boolean containsKey(final Object pKey) { try { _lock.lock(); return _map.containsKey(pKey); } finally { _lock.unlock(); } } @Override public boolean containsValue(final Object pValue) { try { _lock.lock(); return _map.containsValue(pValue); } finally { _lock.unlock(); } } @Override public Set<Map.Entry<K,V>> entrySet() { try { _lock.lock(); return _map.entrySet(); } finally { _lock.unlock(); } } @Override public boolean isEmpty() { try { _lock.lock(); return _map.isEmpty(); } finally { _lock.unlock(); } } @Override public Set<K> keySet() { try { _lock.lock(); return _map.keySet(); } finally { _lock.unlock(); } } @Override public V put (K pKey, V pValue) { try { _lock.lock(); return _map.put(pKey, pValue); } finally { _lock.unlock(); } } @Override public V remove(final Object pKey) { try { _lock.lock(); return _map.remove(pKey); } finally { _lock.unlock(); } } @Override public void putAll(Map <? extends K, ? extends V> pValues) { try { _lock.lock(); _map.putAll(pValues); } finally { _lock.unlock(); } } @Override public boolean equals(final Object pValue) { try { _lock.lock(); return _map.equals(pValue); } finally { _lock.unlock(); } } /** * The eviction handler interface. Implement this interface to work with * the removed entry. */ public static interface EvictionHandler<K, V> { /** * The eldest entry removed from the lru. * @param pEldest The entry being removed. */ public void execute(Map.Entry<K,V> pEldest); } }
package mcjty.rftoolsdim; import mcjty.rftoolsdim.blocks.ModBlocks; import mcjty.rftoolsdim.config.GeneralConfiguration; import mcjty.rftoolsdim.dimensions.dimlets.DimletObjectMapping; import mcjty.rftoolsdim.dimensions.dimlets.KnownDimletConfiguration; import mcjty.rftoolsdim.dimensions.dimlets.types.DimletType; import mcjty.rftoolsdim.items.ModItems; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.registry.GameRegistry; public class ModCrafting { public static void init() { initDimletRecipes(); initBlockRecipes(); Item dimensionalShard = GameRegistry.findItem("rftools", "dimensional_shard"); GameRegistry.addRecipe(new ItemStack(ModItems.emptyDimensionTabItem), "prp", "rpr", "prp", 'p', Items.paper, 'r', Items.redstone); GameRegistry.addRecipe(new ItemStack(ModItems.dimletTemplateItem), "sss", "sps", "sss", 's', dimensionalShard, 'p', Items.paper); GameRegistry.addRecipe(new ItemStack(ModItems.rfToolsDimensionManualItem), "r r", " b ", "r r", 'r', Items.redstone, 'b', Items.book); GameRegistry.addRecipe(new ItemStack(ModItems.dimensionMonitorItem), " u ", "rCr", " r ", 'u', dimensionalShard, 'r', Items.redstone, 'C', Items.comparator); } private static void initBlockRecipes() { Block machineFrame = GameRegistry.findBlock("rftools", "machine_frame"); ItemStack inkSac = new ItemStack(Items.dye, 1, 0); Item dimensionalShard = GameRegistry.findItem("rftools", "dimensional_shard"); GameRegistry.addRecipe(new ItemStack(ModBlocks.activityProbeBlock), "sss", "oMo", "sss", 'o', Items.ender_pearl, 's', dimensionalShard, 'M', machineFrame); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionEnscriberBlock), "rpr", "bMb", "iii", 'r', Items.redstone, 'p', Items.paper, 'b', inkSac, 'M', machineFrame, 'i', Items.iron_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimletWorkbenchBlock), "gug", "cMc", "grg", 'M', machineFrame, 'u', ModItems.dimletBaseItem, 'c', Blocks.crafting_table, 'r', Items.redstone, 'g', Items.gold_nugget); if (GeneralConfiguration.enableDimensionBuilderRecipe) { GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionBuilderBlock), "oEo", "DMD", "ggg", 'o', Items.ender_pearl, 'E', Items.emerald, 'D', Items.diamond, 'M', machineFrame, 'g', Items.gold_ingot); } initCosmeticRecipes(); } private static void initCosmeticRecipes() { Item dimensionalShard = GameRegistry.findItem("rftools", "dimensional_shard"); ItemStack inkSac = new ItemStack(Items.dye, 1, 0); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalBlankBlock, 8), "bbb", "b*b", "bbb", 'b', Blocks.stone, '*', dimensionalShard); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.dimensionalBlock), new ItemStack(ModBlocks.dimensionalBlankBlock)); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalSmallBlocks, 4), "bb ", "bb ", " ", 'b', ModBlocks.dimensionalBlankBlock); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalCrossBlock, 5), " b ", "bbb", " b ", 'b', ModBlocks.dimensionalBlankBlock); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalCross2Block, 5), "b b", " b ", "b b", 'b', ModBlocks.dimensionalBlankBlock); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalPattern1Block, 7), "bxb", "bbb", "bxb", 'b', ModBlocks.dimensionalBlankBlock, 'x', inkSac); ItemStack bonemealStack = new ItemStack(Items.dye, 1, 15); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalPattern2Block, 7), "bxb", "bbb", "bxb", 'b', ModBlocks.dimensionalBlankBlock, 'x', bonemealStack); } private static void initDimletRecipes() { Block redstoneTorch = Blocks.redstone_torch; addRecipe(DimletType.DIMLET_EFFECT, DimletObjectMapping.NONE_ID, " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Items.apple, 'p', Items.paper); addRecipe(DimletType.DIMLET_FEATURE, DimletObjectMapping.NONE_ID, " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Items.string, 'p', Items.paper); addRecipe(DimletType.DIMLET_STRUCTURE, DimletObjectMapping.NONE_ID, " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Items.bone, 'p', Items.paper); addRecipe(DimletType.DIMLET_TERRAIN, "Void", " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Items.brick, 'p', Items.paper); if (!GeneralConfiguration.voidOnly) { addRecipe(DimletType.DIMLET_TERRAIN, "Flat", " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Items.brick, 'p', ModItems.dimletTemplateItem); } addRecipe(DimletType.DIMLET_CONTROLLER, DimletObjectMapping.DEFAULT_ID, " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Items.comparator, 'p', Items.paper); addRecipe(DimletType.DIMLET_CONTROLLER, "Single", " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Items.comparator, 'p', ModItems.dimletTemplateItem); addRecipe(DimletType.DIMLET_MATERIAL, DimletObjectMapping.DEFAULT_ID, " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Blocks.dirt, 'p', Items.paper); addRecipe(DimletType.DIMLET_LIQUID, DimletObjectMapping.DEFAULT_ID, " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Items.bucket, 'p', Items.paper); addRecipe(DimletType.DIMLET_SKY, "Normal", " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Items.feather, 'p', ModItems.dimletTemplateItem); addRecipe(DimletType.DIMLET_SKY, "Normal Day", " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Items.glowstone_dust, 'p', ModItems.dimletTemplateItem); addRecipe(DimletType.DIMLET_SKY, "Normal Night", " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Items.coal, 'p', Items.paper); addRecipe(DimletType.DIMLET_MOB, DimletObjectMapping.DEFAULT_ID, " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Items.rotten_flesh, 'p', ModItems.dimletTemplateItem); addRecipe(DimletType.DIMLET_TIME, "Normal", " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Items.clock, 'p', ModItems.dimletTemplateItem); addRecipe(DimletType.DIMLET_WEATHER, DimletObjectMapping.DEFAULT_ID, " r ", "rwr", "ppp", 'r', Items.redstone, 'w', Items.snowball, 'p', Items.paper); addRecipe(DimletType.DIMLET_DIGIT, "0", " r ", "rtr", "ppp", 'r', Items.redstone, 't', redstoneTorch, 'p', Items.paper); addRecipe(DimletType.DIMLET_DIGIT, "1", "d", 'd', KnownDimletConfiguration.getDimletStack(DimletType.DIMLET_DIGIT, "0")); addRecipe(DimletType.DIMLET_DIGIT, "2", "d", 'd', KnownDimletConfiguration.getDimletStack(DimletType.DIMLET_DIGIT, "1")); addRecipe(DimletType.DIMLET_DIGIT, "3", "d", 'd', KnownDimletConfiguration.getDimletStack(DimletType.DIMLET_DIGIT, "2")); addRecipe(DimletType.DIMLET_DIGIT, "4", "d", 'd', KnownDimletConfiguration.getDimletStack(DimletType.DIMLET_DIGIT, "3")); addRecipe(DimletType.DIMLET_DIGIT, "5", "d", 'd', KnownDimletConfiguration.getDimletStack(DimletType.DIMLET_DIGIT, "4")); addRecipe(DimletType.DIMLET_DIGIT, "6", "d", 'd', KnownDimletConfiguration.getDimletStack(DimletType.DIMLET_DIGIT, "5")); addRecipe(DimletType.DIMLET_DIGIT, "7", "d", 'd', KnownDimletConfiguration.getDimletStack(DimletType.DIMLET_DIGIT, "6")); addRecipe(DimletType.DIMLET_DIGIT, "8", "d", 'd', KnownDimletConfiguration.getDimletStack(DimletType.DIMLET_DIGIT, "7")); addRecipe(DimletType.DIMLET_DIGIT, "9", "d", 'd', KnownDimletConfiguration.getDimletStack(DimletType.DIMLET_DIGIT, "8")); addRecipe(DimletType.DIMLET_DIGIT, "0", "d", 'd', KnownDimletConfiguration.getDimletStack(DimletType.DIMLET_DIGIT, "9")); } private static void addRecipe(DimletType type, String id, Object... params) { GameRegistry.addRecipe(KnownDimletConfiguration.getDimletStack(type, id), params); } }
package me.nithanim.mmf4j; import com.sun.jna.Pointer; import io.netty.util.AbstractReferenceCounted; public class MemoryView extends AbstractReferenceCounted { public static MemoryView getInstance(MemoryMap memoryMap, Pointer pointer, long offset, int size) { return new MemoryView(memoryMap, pointer, offset, size); } private final MemoryMap memoryMap; private Pointer pointer; private final long offset; private final int size; private boolean valid = true; private PointerChangeListener listener; private MemoryView(MemoryMap memoryMap, Pointer pointer, long offset, int size) { this.memoryMap = memoryMap; this.pointer = pointer; this.offset = offset; this.size = size; } public void setPointer(Pointer pointer) { this.pointer = pointer; listener.onPointerChange(pointer); } public void setPointerChangeListener(PointerChangeListener listener) { this.listener = listener; } public Pointer getPointer() { return pointer; } public long getOffset() { return offset; } public int getSize() { return size; } public boolean isValid() { return valid; } void setValid(boolean valid) { this.valid = valid; } @Override public int hashCode() { int hash = 3; hash = 59 * hash + (this.pointer != null ? this.pointer.hashCode() : 0); hash = 59 * hash + (int) (this.offset ^ (this.offset >>> 32)); hash = 59 * hash + this.size; return hash; } @Override public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } final MemoryView other = (MemoryView) obj; return (this.pointer == other.pointer || (this.pointer != null && this.pointer.equals(other.pointer))) && this.offset == other.offset && this.size == other.size; } @Override protected void deallocate() { memoryMap.destroyView(this); } public interface PointerChangeListener { void onPointerChange(Pointer p); } }
// HttpRequest.java package ed.net.httpserver; import java.net.*; import java.util.*; import java.util.regex.*; import ed.js.*; import ed.util.*; public class HttpRequest extends JSObjectLame { public static HttpRequest getDummy( String url ){ return getDummy( url , "" ); } public static HttpRequest getDummy( String url , String extraHeaders ){ return new HttpRequest( null , "GET " + url + " HTTP/1.0\n" + extraHeaders + "\n" ); } HttpRequest( HttpServer.HttpSocketHandler handler , String header ){ _handler = handler; _rawHeader = header; int idx = header.indexOf( "\n" ); if ( idx < 0 ) throw new RuntimeException( "something is very wrong" ); _firstLine = header.substring( 0 , idx ).trim(); int start = idx + 1; while ( ( idx = header.indexOf( "\n" , start ) ) >= 0 ) { final String line = header.substring( start , idx ).trim(); start = idx + 1; int foo = line.indexOf( ":" ); if ( foo > 0 ) _headers.put( line.substring( 0 , foo ).trim() , line.substring( foo + 1 ).trim() ); } // parse first line idx = _firstLine.indexOf( " " ); if ( idx < 0 ) throw new RuntimeException( "malformed" ); _command = _firstLine.substring( 0 , idx ); int endURL = _firstLine.indexOf( " " , idx + 1 ); if ( endURL < 0 ){ _url = _firstLine.substring( idx + 1 ).trim(); _http11 = false; } else { _url = _firstLine.substring( idx + 1 , endURL ).trim(); _http11 = _firstLine.indexOf( "1.1" , endURL ) > 0; } int endURI = _url.indexOf( "?" ); if ( endURI < 0 ){ _uri = _url; _queryString = null; } else { _uri = _url.substring( 0 , endURI ); _queryString = _url.substring( endURI + 1 ); } } public String getURI(){ return _uri; } public String getURL(){ return _url; } public String getRawHeader(){ return _rawHeader; } public String getMethod(){ return _command; } public String getQueryString(){ return _queryString; } public int totalSize(){ int size = _rawHeader.length(); size += getIntHeader( "Content-Length" , 0 ); return size; } public String toString(){ _finishParsing(); return _command + " " + _uri + " HTTP/1." + ( _http11 ? "1" : "" ) + " : " + _headers + " " + _parameters; } public boolean keepAlive(){ String c = getHeader( "connection" ); if ( c != null ) return ! c.equalsIgnoreCase( "close" ); return _http11; } // header stuff public String getHost(){ String host = getHeader( "Host" ); if ( host == null ) return null; host = host.trim(); if ( host.length() == 0 ) return null; int idx = host.indexOf( ":" ); if ( idx == 0 ) return null; if ( idx > 0 ){ host = host.substring( 0 , idx ).trim(); if ( host.length() == 0 ) return null; } return host; } public int getPort(){ String host = getHeader( "Host" ); if ( host == null ) return 0; int idx = host.indexOf( ":" ); if ( idx < 0 ) return 0; return StringParseUtil.parseInt( host.substring( idx + 1 ) , 0 ); } public String getHeader( String h ){ return _headers.get( h ); } public int getIntHeader( String h , int def ){ return StringParseUtil.parseInt( getHeader( h ) , def ); } public JSArray getHeaderNames(){ JSArray a = new JSArray(); a.addAll( _headers.keySet() ); return a; } // cookies public String getCookie( String s ){ if ( _cookies == null ){ Map<String,String> m = new StringMap<String>(); String temp = getHeader( "Cookie" ); if ( temp != null ){ for ( String thing : temp.split( ";" ) ){ int idx = thing.indexOf("="); if ( idx < 0 ) continue; m.put( thing.substring( 0 , idx ).trim() , thing.substring( idx + 1 ).trim() ); } } _cookies = m; } return _cookies.get( s ); } public JSArray getCookieNames(){ getCookie( "" ); JSArray a = new JSArray(); a.addAll( _cookies.keySet() ); return a; } // param stuff public JSArray getParameterNames(){ _finishParsing(); JSArray a = new JSArray(); a.addAll( _parameters.keySet() ); return a; } public boolean getBoolean( String n , boolean def ){ return StringParseUtil.parseBoolean( getParameter( n ) , def ); } public int getInt( String n , int def ){ return StringParseUtil.parseInt( getParameter( n ) , def ); } public List<String> getParameters( String name ){ return _parameters.get( name ); } public String getParameter( String name ){ return getParameter( name , null ); } public String getParameter( String name , String def ){ _finishParsing(); List<String> s = _parameters.get( name ); if ( s != null && s.size() > 0 ) return s.get(0); return def; } public Object set( Object n , Object v ){ String name = n.toString(); _finishParsing(); Object prev = getParameter( name ); _addParm( name , v == null ? null : v.toString() ); return prev; } public Object get( Object n ){ String foo = getParameter( n.toString() , null ); if ( foo == null ) return null; return new ed.js.JSString( foo ); } public UploadFile getFile( String name ){ if ( _postData == null ) return null; return _postData._files.get( name ); } public Object setInt( int n , Object v ){ throw new RuntimeException( "can't set things on an HttpRequest" ); } public Object getInt( int n ){ throw new RuntimeException( "you're stupid" ); } public Set<String> keySet(){ return _parameters.keySet(); } private final String _urlDecode( String s ){ try { return URLDecoder.decode( s , "UTF-8" ); } catch ( Exception e ){} try { return URLDecoder.decode( s , _characterEncoding ); } catch ( Exception e ){} try { return URLDecoder.decode( s ); } catch ( Exception e ){} return s; } public boolean applyServletParams( JSRegex regex , JSArray names ){ Matcher m = regex.getCompiled().matcher( getURI() ); if ( ! m.find() ) return false; for ( int i=1; i<=m.groupCount() && ( i - 1 ) < names.size() ; i++ ) _addParm( names.get( i - 1 ).toString() , m.group( i ) ); return true; } private void _finishParsing(){ if ( ! _parsedURL ){ _parsedURL = true; if ( _queryString != null ){ int start = 0; while ( start < _queryString.length() ){ int amp = _queryString.indexOf("&",start ); String thing = null; if ( amp < 0 ){ thing = _queryString.substring( start ); start = _queryString.length(); } else { thing = _queryString.substring( start , amp ); start = amp + 1; while ( start < _queryString.length() && _queryString.charAt( start ) == '&' ) start++; } int eq = thing.indexOf( "=" ); if ( eq < 0 ) _addParm( thing , null ); else _addParm( thing.substring( 0 , eq ) , thing.substring( eq + 1 ) ); } } } if ( ! _parsedPost && _postData != null && _command.equalsIgnoreCase( "POST" ) ){ _parsedPost = true; _postData.go( this ); } } void _addParm( String n , String val ){ n = n.trim(); List<String> lst = _parameters.get( n ); if ( lst == null ){ lst = new ArrayList<String>(); _parameters.put( n , lst ); } if ( val == null ){ lst.add( val ); return; } val = val.trim(); val = _urlDecode( val ); lst.add( val ); } public Object getAttachment(){ return _attachment; } public void setAttachment( Object o ){ if ( _attachment != null ) throw new RuntimeException( "attachment already set" ); _attachment = o; } public PostData getPostData(){ return _postData; } public JSDate getStart(){ return _start; } public long[] getRange(){ if ( _rangeChecked ) return _range; String s = getHeader( "Range" ); if ( s != null ) _range = _parseRange( s ); _rangeChecked = true; return _range; } public String getRemoteIP(){ if ( _remoteIP != null ) return _remoteIP; String ip = getHeader( "X-Cluster-Client-Ip" ); if ( ip == null ) ip = _handler.getInetAddress().getHostAddress(); _remoteIP = ip; return _remoteIP; } public static long[] _parseRange( String s ){ if ( s == null ) return null; s = s.trim(); if ( ! s.startsWith( "bytes=" ) ) return null; s = s.substring( 6 ).trim(); if ( s.length() == 0 ) return null; if ( s.matches( "\\d+" ) ) return new long[]{ Long.parseLong( s ) , Long.MAX_VALUE }; String pcs[] = s.split( "," ); if ( pcs.length == 0 ) return null; if ( pcs.length == 1 ){ // either has to be // -100 s = pcs[0].trim(); if ( s.length() == 0 ) return null; if ( s.charAt( 0 ) == '-' ) // we don't support this return null; Matcher m = Pattern.compile( "(\\d+)\\-(\\d+)" ).matcher( s ); if ( m.find() ) return new long[]{ Long.parseLong( m.group(1) ) , Long.parseLong( m.group(2) ) }; return null; } long min = Long.MAX_VALUE; long max = -1; for ( int i=0; i<pcs.length; i++ ){ String foo = pcs[i]; Matcher m = Pattern.compile( "(\\d+)\\-(\\d+)" ).matcher( s ); if ( ! m.find() ) return null; long l = Long.parseLong( m.group(1) ); long h = Long.parseLong( m.group(2) ); min = Math.min( min , l ); max = Math.max( min , h ); } if ( max < 0 ) return null; return new long[]{ min , max }; } final HttpServer.HttpSocketHandler _handler; final String _firstLine; final Map<String,String> _headers = new StringMap<String>(); final JSDate _start = new JSDate(); Map<String,String> _cookies; String _remoteIP; boolean _parsedPost = false; PostData _postData; boolean _parsedURL = false; final Map<String,List<String>> _parameters = new StringMap<List<String>>(); final String _rawHeader; final String _command; final String _url; final String _uri; final String _queryString; final boolean _http11; Object _attachment; private boolean _rangeChecked = false; private long[] _range; private String _characterEncoding = "ISO-8859-1"; }
package me.pandora.image; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; /** * A singleton implementing various image processing methods. * * @author Akis Papadopoulos */ public final class Transformer { /** * A method scaling down a given image in the target size in pixels * regarding the original ratio retaining the proportions and an optional * stepwise mode in terms of better quality. * * @param image the image to be scaled down. * @param target the target size in pixels. * @param stepwise apply stepwise scaling for better quality. * @return a buffered image. */ public static BufferedImage downscale(BufferedImage image, int target, boolean stepwise) { int type = image.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : image.getType(); int width = image.getWidth(); int height = image.getHeight(); long size = width * height; if (target < size) { // Calculating the scale ratio and target dims double ratio = Math.sqrt((double) target / size); int targetWidth = (int) (width * ratio); int targetHeight = (int) (height * ratio); // Initiating width and height regarding a stepwised process or not int w = stepwise ? width : targetWidth; int h = stepwise ? height : targetHeight; BufferedImage scaled = (BufferedImage) image; do { // Calculating the new dims for the next step if (stepwise) { // Downscaling in a half for each step until reach target if (w > targetWidth) { w /= 2; // Restoring the minimum target value if (w < targetWidth) { w = targetWidth; } } if (h > targetHeight) { h /= 2; // Restoring the minimum target value if (h < targetHeight) { h = targetHeight; } } } // Drawing the temporary scaled image regarding rendering parameters BufferedImage temp = new BufferedImage(w, h, type); Graphics2D graphics = temp.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); graphics.drawImage(scaled, 0, 0, w, h, null); graphics.dispose(); // Saving scaled image for the next step if any scaled = temp; } while (w != targetWidth || h != targetHeight); return scaled; } else { return image; } } /** * A method compressing a given image using JPEG algorithm regarding the * size of quality after compression, where 0 means full compression and 1 * full of quality. * * @param image the image to be compressed. * @param quality size of quality after compression. * @return a compressed buffered image. * @throws IOException throws unknown exceptions. */ public static BufferedImage compress(BufferedImage image, float quality) throws IOException { // Setting up the compression algorithm ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); ImageWriteParam parameters = writer.getDefaultWriteParam(); parameters.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); parameters.setCompressionQuality(quality); // Compressing the image ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(bos); writer.setOutput(ios); writer.write(null, new IIOImage(image, null, null), parameters); ios.flush(); ByteArrayInputStream in = new ByteArrayInputStream(bos.toByteArray()); BufferedImage compressed = ImageIO.read(in); bos.close(); ios.close(); writer.dispose(); return compressed; } }
package algorithms; import algorithms.util.ObjectSpaceEstimator; import gnu.trove.map.TLongLongMap; import gnu.trove.map.TLongObjectMap; import gnu.trove.map.hash.TLongLongHashMap; import gnu.trove.map.hash.TLongObjectHashMap; import java.util.Arrays; import thirdparty.edu.princeton.cs.algs4.RedBlackBSTLongInt2; import thirdparty.ods.Longizer; import thirdparty.ods.XFastTrieLong; import thirdparty.ods.XFastTrieNodeLong; public class YFastTrieLong { /* designing from browsing a few different lecture notes online. the yfast trie uses same w and maxC as the XFastTrie. YFastTrie let w = max bit length specified by user, else is default 62 bits. a few examples here with data in mind for image pixel indexes, in which the maximum pixel index = width * height: If instead, one uses binSz = w to get the suggested yfasttrie runtime, one would have nEntries/binSz number of representatives. This is fewer entries into xfasttrie than if using xfasttrie alone so is conserving space. The calculations above for the suggested yfasttrie model: binsz = w mem is in MB: width=5000, height=7000 n= 35000000 mem= 61507: 505405 w=62 rt= 6 width=5000, height=7000 n= 35000000 mem= 9111: 14213 w=25 rt= 5 width=5000, height=7000 n= 3500000 mem= 53336: 492908 w=62 rt= 6 width=5000, height=7000 n= 3500000 mem= 940: 1716 w=25 rt= 5 width=1024, height=1024 n= 1048576 mem= 52700: 491936 w=62 rt= 6 width=1024, height=1024 n= 1048576 mem= 273: 428 w=20 rt= 4 width=1024, height=1024 n= 104858 mem= 52456: 491561 w=62 rt= 6 width=1024, height=1024 n= 104858 mem= 28: 54 w=20 rt= 4 width= 512, height= 512 n= 262144 mem= 52496: 491624 w=62 rt= 6 width= 512, height= 512 n= 262144 mem= 68: 107 w=18 rt= 4 width= 512, height= 512 n= 26214 mem= 52435: 491530 w=62 rt= 6 width= 512, height= 512 n= 26214 mem= 7: 13 w=18 rt= 4 width= 256, height= 256 n= 65536 mem= 52445: 491546 w=62 rt= 6 width= 256, height= 256 n= 65536 mem= 17: 27 w=16 rt= 4 width= 256, height= 256 n= 6554 mem= 52430: 491522 w=62 rt= 6 width= 256, height= 256 n= 6554 mem= 1: 3 w=16 rt= 4 width= 128, height= 128 n= 16384 mem= 52433: 491526 w=62 rt= 6 width= 128, height= 128 n= 16384 mem= 4: 6 w=14 rt= 4 width= 128, height= 128 n= 1638 mem= 52429: 491520 w=62 rt= 6 width= 128, height= 128 n= 1638 mem= 0: 0 w=14 rt= 4 width= 64, height= 64 n= 4096 mem= 52429: 491521 w=62 rt= 6 width= 64, height= 64 n= 4096 mem= 1: 1 w=12 rt= 4 width= 64, height= 64 n= 4096 mem= 1: 1 w=12 rt= 4 width= 64, height= 64 n= 410 mem= 52428: 491520 w=62 rt= 6 width= 64, height= 64 n= 410 mem= 0: 0 w=12 rt= 4 */ private int n = 0; private final int w; private final long maxC; private final long binSz; private long nBins; /** the minimum of each bin range, if it is populated, is the representative node, and that is held in 2 data structures: xft holds the number, allowing fast repr prev and next lookups. xftReps holds the repr as the value, found by key = binNumber. * the max number of trie entries will be nBins but there will be prefix trie nodes too */ private final XFastTrieLong<XFastTrieNodeLong<Long>, Long> xft; // key = bin index (which is node/binSz), value = repr value. // each repr value is the minimum stored in the bin. // * the max number of map entries will be nBins. private final TLongLongMap xftReps = new TLongLongHashMap(); // all inserts of this class are held in // * at most nBins number of trees which each // hold at most binSz number of entries. // each list item is a sorted binary search tree of numbers in that bin. // the value in the tree holds multiplicity of the number. // each list index can be found by node/binSz // each sorted tree has // key = node (inserted number), w/ value= // the number of times that number is present (multiplicity). private final TLongObjectMap<RedBlackBSTLongInt2> rbs; /** * constructor specifying the maximum number of bits of any future add or * find, etc, and is by default choosing the model for the fast runtime * which may be expensive in space requirements. * * @param wBits */ public YFastTrieLong(int wBits) { if (wBits < 63 && wBits > 1) { this.w = wBits; } else { throw new IllegalStateException("wBits " + " shoulw be greater than 1 and less than 32"); } maxC = (1L << w) - 1; binSz = w; nBins = (long)Math.ceil((double)maxC/(double)binSz); //System.out.println("nBins=" + nBins + " rt of ops=" + // (Math.log(binSz)/Math.log(2))); rbs = new TLongObjectHashMap<RedBlackBSTLongInt2>(); XFastTrieNodeLong<Long> clsNode = new XFastTrieNodeLong<Long>(); Longizer<Long> it = new Longizer<Long>() { @Override public long longValue(Long x) { return x; } }; xft = new XFastTrieLong<XFastTrieNodeLong<Long>, Long>(clsNode, it, w); } /** * constructor using the the maximum number of bits of 62 * and the default model for the fast runtime * which may be expensive in space requirements. * */ public YFastTrieLong() { this.w = 62; maxC = (1L << w) - 1; binSz = w; nBins = (long)Math.ceil((double)maxC/(double)binSz); //System.out.println("nBins=" + nBins + " rt of ops=" + // (Math.log(binSz)/Math.log(2))); rbs = new TLongObjectHashMap<RedBlackBSTLongInt2>(); XFastTrieNodeLong<Long> clsNode = new XFastTrieNodeLong<Long>(); Longizer<Long> it = new Longizer<Long>() { @Override public long longValue(Long x) { return x; } }; xft = new XFastTrieLong<XFastTrieNodeLong<Long>, Long>(clsNode, it, w); } protected RedBlackBSTLongInt2 getTreeMap(long index) { RedBlackBSTLongInt2 tree = rbs.get(index); if (tree == null) { tree = new RedBlackBSTLongInt2(); rbs.put(index, tree); } return tree; } /** * * @param node * @param index */ private void addToRBTree(long node, long index) { RedBlackBSTLongInt2 tree = getTreeMap(index); assert(tree != null); int[] output = new int[2]; tree.get(node, output); int multiplicity; if (output[0] == -1) { multiplicity = 1; } else { multiplicity = 1 + output[1]; } tree.put(node, multiplicity); } /** * * @param node * @param index */ private boolean deleteFromRBTree(long node, long index) { RedBlackBSTLongInt2 tree = getTreeMap(index); assert(tree != null); int[] output = new int[2]; tree.get(node, output); if (output[0] == -1) { return false; } int multiplicity = output[1]; if (multiplicity > 0) { multiplicity = output[1] - 1; if (multiplicity > 0) { tree.put(node, multiplicity); } } if (multiplicity == 0) { tree.delete(node); } return true; } /** * add node to the data structure. * * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * @param node a number >= 0 and having bit length * less than or equal to w. * @return true if successfully added node. */ public boolean add(long node) { if (node < 0) { throw new IllegalArgumentException("node must " + "be greater than or equal to 0"); } else if (node > maxC) { throw new IllegalArgumentException("node.key must " + "be less than " + maxC + " node=" + node); } long index = node/binSz; long existingRepr = xftReps.get(index); if (!xftReps.containsKey(index)) { // insert is O(log_2(w)) + O(l-w) xft.add(Long.valueOf(node)); xftReps.put(index, node); } else if (node < existingRepr) { // delete is O(log_2(w)) + O(l-w) // insert is O(log_2(w)) + O(l-w) xft.remove(Long.valueOf(existingRepr)); xft.add(Long.valueOf(node)); xftReps.put(index, node); } addToRBTree(node, index); n++; return true; } /** * remove node from the data structure. * * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * * @param node * @return */ public boolean remove(long node) { if (node < 0) { throw new IllegalArgumentException("node must " + "be greater than or equal to 0"); } else if (node > maxC) { throw new IllegalArgumentException("node must " + "be less than " + maxC); } long index = node/binSz; boolean removed = deleteFromRBTree(node, index); if (!removed) { return false; } if (!xftReps.containsKey(index)) { return false; } RedBlackBSTLongInt2 tree = getTreeMap(index); long existingRepr = xftReps.get(index); if (tree.isEmpty()) { // just deleted the last item so remove from rbs // delete is O(log_2(w)) + O(w-l) if (xftReps.containsKey(index)) { xft.remove(Long.valueOf(existingRepr)); xftReps.remove(index); } } else if (node == existingRepr) { //existingRepr is maintained as the minimum in the bin, // so if a node w/ this value is removed and the multiplicity // was 1, need to assign a new repr int[] output = new int[2]; tree.get(node, output); int multiplicity = output[1]; if (output[0] == -1) { // remove the current repr and assign a new one // delete is O(log_2(w)) + O(w-l) xft.remove(Long.valueOf(existingRepr)); xftReps.remove(index); // O(log_2(N/w)) long[] kOutput = new long[2]; tree.min(kOutput); // tree is not empty assert(kOutput[0] != -1); long minKey = kOutput[1]; xft.add(minKey); xftReps.put(index, minKey); } } n return true; } /** * find node in the data structure and return it, else return -1. * * runtime complexity is at most O(log_2(w)) but since the map might not * be completely populated, the complexity might be smaller. * * @param node * @return the value of the node if present, else -1 */ public long find(long node) { if (node < 0) { throw new IllegalArgumentException("node must " + "be greater than or equal to 0"); } else if (node > maxC) { throw new IllegalArgumentException("node must " + "be less than " + maxC + ". node=" + node); } long index = node/binSz; RedBlackBSTLongInt2 tree = getTreeMap(index); int[] output = new int[2]; tree.get(node, output); if (output[0] == -1) { return -1; } return node; } /** * find the largest node smaller in value than node in the datastructure. * * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * @param node * @return value preceding node, else -1 if there is not one */ public long predecessor(long node) { if (node < 0) { throw new IllegalArgumentException("node must " + "be greater than or equal to 0"); } else if (node > maxC) { throw new IllegalArgumentException("node must " + "be less than " + maxC); } long nodeIndex = node/binSz; // the repr is stored in xft and it is always the minium for the bin boolean isAMinimum = xft.find(Long.valueOf(node)) != null; /* if the node is not a minima, the answer is in the node's map if its size is larger > 1 */ RedBlackBSTLongInt2 tree = getTreeMap(nodeIndex); if (!isAMinimum && (tree.size() > 1)) { long[] output = new long[2]; //tree.printPreOrderTraversal(); tree.lower(node, output); if (output[0] != -1) { return output[1]; } } // else, predeccessor is in the closest bin < nodeIndex that has // items in it. Long prev = xft.predecessor(Long.valueOf(node)); if (prev == null) { return -1; } long prev0Index = prev.longValue()/binSz; tree = getTreeMap(prev0Index); if (tree.isEmpty()) { return -1; } long[] kOutput = new long[2]; tree.max(kOutput); // tree is not empty assert(kOutput[0] != -1); long lastKey = kOutput[1]; return lastKey; } /** * find the smallest value larger than node in the data structure. * * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * @param node * @return the next node in the ordered data strucure, else -1 if no such * node exists. */ public long successor(long node) { if (node < 0) { throw new IllegalArgumentException("node must " + "be greater than or equal to 0"); } else if (node > maxC) { throw new IllegalArgumentException("node must " + "be less than " + maxC); } Long nodeKey = Long.valueOf(node); long nodeIndex = node/binSz; boolean isAMinimum = xft.find(nodeKey) != null; RedBlackBSTLongInt2 tree = getTreeMap(nodeIndex); if (tree.size() > 1) { // if tree size > 1, the next key is the successor // else, the xft sucessor to nodeIndex is the successor final long[] output = new long[2]; tree.higher(node, output); if (isAMinimum) { assert(output[0] != -1); return output[1]; } // else, the node is not a repr // if there is a tree successor to the node, that is the successor // else, the xft successor to nodeIndex is the successor if (output[0] != -1) { return output[1]; } } Long successorRepr = xft.successor(nodeKey); if (successorRepr == null) { return -1; } // the successor representative is then the next value return successorRepr; } /** * find the smallest node in the datastructure. * * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * @return minimum, else -1 if empty */ public long minimum() { if (xft.size() == 0) { return -1; } Long repr = xft.minimum(); // cannot be null if size > 0 assert(repr != null); return repr.longValue(); } /** * find the largest node in the data structure. * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * @return maximum, else -1 if empty */ public long maximum() { if (xft.size() == 0) { return -1; } Long maxRepr = xft.maximum(); assert(maxRepr != null); long index = maxRepr.longValue()/binSz; RedBlackBSTLongInt2 tree = getTreeMap(index); assert(tree != null); assert(!tree.isEmpty()); long[] kOutput = new long[2]; tree.max(kOutput); assert(kOutput[0] != -1); long lastKey = kOutput[1]; return lastKey; } /** * find and remove the smallest value in the data structure. * * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * @return minimum, else -1 if empty */ public long extractMinimum() { //O(log_2(w)) long min = minimum(); if (min == -1) { assert(xft.size() == 0); return -1; } remove(min); return min; } /** * find and remove the largest value in the data structure. * runtime complexity should usually be O(log_2(w)) but * filling the prefix tree in the xfasttrie can sometimes add a small amount * + O(l-w) * where w is the maximum bit length and l is a level in the prefix tree. * * @return maximum, else -1 if empty */ public long extractMaximum() { long max = maximum(); if (max == -1) { assert(xft.size() == 0); return -1; } remove(max); return max; } /** * get the current number of values stored in the data structure. * @return */ public int size() { return n; } protected long getBinSz() { return binSz; } /** * estimate the size that an instance of YFastTrieLong with * n added entries, maxNumberOfBits, and * use binSzModel * would occupy in heap space in Bytes. * * NOTE: there are some varying components to estimating the memory that * depend upon the properties of the numbers inserted. * For example: * <pre> * -- xft is an XFastTrie instantiated with maxNumberOfBits. * It will have at most, * * nBins number of entries, where nBins * is determined by the BinSizeModel. * In addition to the number of inserted items (which is only one * per bin of numberOfEntries), there will be some undetermined * number of prefix nodes created in the process. * A factor of 5 more is assumed here to over estimate the total * number of trie nodes that includes the internal prefix nodes. * -- THE LOGIC is still in progress to determine * an upper and lower limit to estimate the number of populated * nBins w/o knowing properties of the numbers, such as whether * they are sequential, or have large gaps, etc. * -- xftReps is a hashMap with same number of inserts as xft, * so has the same need for an upper and lower estimate. * </pre> * * @param numberOfEntries amount of space for this object's instance * with n entries in Bytes on the heap. * @param maxNumberOfBits all entries must have bit lengths .lte. this * * @return array with 2 estimates, (1) estimate using all bins and a * factor of 5 for creating trie prefix nodes, (2) estimate from using 1/4 of the bins and a factor of 3 for creating the trie prefix nodes. */ public static long[] estimateSizeOnHeap(int numberOfEntries, int maxNumberOfBits) { long ww = maxNumberOfBits; long maxNumber = (1L << ww) - 1; long binSz = maxNumberOfBits; int nBins = (int)Math.ceil((double)maxNumber/(double)binSz); long total = 0; ObjectSpaceEstimator est = new ObjectSpaceEstimator(); est.setNIntFields(2); est.setNLongFields(3); est.setNBooleanFields(1); //objects: xft, xftReps, rbs est.setNObjRefsFields(3); total += est.estimateSizeOnHeap(); /* the minimum of each bin range, if it is populated, is the representative node, and that is held in 2 data structures: xft holds the number, allowing fast repr prev and next lookups. xftReps holds the repr as the value, found by key = binNumber. * the max number of trie entries will be nBins but there will be prefix trie nodes too private final XFastTrieLong<XFastTrieNodeLong<Long>, Long> xft; // key = bin index (which is node/binSz), value = repr value. // each repr value is the minimum stored in the bin. // * the max number of map entries will be nBins. private final TLongLongMap xftReps = new TLongLongHashMap(); // all inserts of this class are held in // * at most nBins number of trees which each // hold at most binSz number of entries. // each list item is a sorted binary search tree of numbers in that bin. // the value in the tree holds multiplicity of the number. // each list index can be found by node/binSz // each sorted tree has // key = node (inserted number), w/ value= // the number of times that number is present (multiplicity). TLongObjectMap<RedBlackBSTLongInt2> rbs; */ // returning 2 estimates // (1) estimate using all bins w/ factor 5 for tries // (2) estimate from using nBinsSparse of the nBins w/ factor 3 for tries int nBinsSparse = nBins/10; if (nBinsSparse < 1) { nBinsSparse = 1; } // using factor of 5 for total w/ prefix nodes long total2_1 = numberOfEntries * 5 * XFastTrieNodeLong.estimateSizeOnHeap(); // all nBins are filled w/ a repr total2_1 += XFastTrieLong.estimateSizeOnHeap(nBins, maxNumberOfBits); long total2_2 = numberOfEntries * 3 * XFastTrieNodeLong.estimateSizeOnHeap(); // nBinsSparse of nBins are filled w/ a repr total2_2 += XFastTrieLong.estimateSizeOnHeap(nBinsSparse, maxNumberOfBits); //TLongLongMap total2_1 += ObjectSpaceEstimator.estimateTLongLongHashMap(); //nBins number of repr entries in map total2_1 += (2 * nBins * ObjectSpaceEstimator.estimateLongSize()); //TLongLongMap total2_2 += ObjectSpaceEstimator.estimateTLongLongHashMap(); //nBins/4 number of repr entries in map total2_2 += (2 * nBinsSparse * ObjectSpaceEstimator.estimateLongSize()); // 1 TLongObjectMap<RedBlackBSTLongInt> rbs; total2_1 += ObjectSpaceEstimator.estimateTLongObjectHashMap(); total2_2 += ObjectSpaceEstimator.estimateTLongObjectHashMap(); // nBins number of RedBlackBSTLongInt long rbtree = RedBlackBSTLongInt2.estimateSizeOnHeap(0); long rbtreeNodes = RedBlackBSTLongInt2.estimateSizeOnHeap(numberOfEntries) - rbtree; total2_1 += (nBins * rbtree); total2_2 += (nBinsSparse * rbtree); // nEntries number of long, int nodes total2_1 += rbtreeNodes; total2_2 += rbtreeNodes; return new long[]{total2_1 + total, total2_2 + total}; } /** * print all entries in data structure to standard out. */ public void debugPrint() { long[] binIndexes = rbs.keys(); Arrays.sort(binIndexes); for (long binIdx : binIndexes) { System.out.println("binNumber=" + binIdx); RedBlackBSTLongInt2 rbt = rbs.get(binIdx); rbt.printPreOrderTraversal(); } } }
package net.caseif.flint.arena; import net.caseif.flint.component.Component; import net.caseif.flint.component.ComponentOwner; import net.caseif.flint.component.exception.OrphanedComponentException; import net.caseif.flint.lobby.LobbySign; import net.caseif.flint.lobby.type.ChallengerListingLobbySign; import net.caseif.flint.lobby.type.StatusLobbySign; import net.caseif.flint.metadata.MetadataHolder; import net.caseif.flint.minigame.Minigame; import net.caseif.flint.round.LifecycleStage; import net.caseif.flint.round.Round; import net.caseif.flint.util.physical.Boundary; import net.caseif.flint.util.physical.Location3D; import com.google.common.base.Optional; import com.google.common.collect.BiMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.util.LinkedHashSet; @SuppressWarnings("DuplicateThrows") public interface Arena extends MetadataHolder, ComponentOwner, Component<Minigame> { /** * Gets the {@link Minigame} this {@link Arena} is owned by. * * <p><strong>Note:</strong> This a convenience method for * {@link Arena#getOwner()}.</p> * * @return The {@link Minigame} this {@link Arena} is owned by * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ Minigame getMinigame() throws OrphanedComponentException; /** * Gets the identifier of this {@link Arena}. * * @return The identifier of this {@link Arena} * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ String getId() throws OrphanedComponentException; /** * Gets the "friendly" name of this {@link Arena}, as displayed to users. * * @return The "friendly" name of this {@link Arena}, as displayed to users, * or its ID if one is not set * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ String getName() throws OrphanedComponentException; /** * Gets the name of the world which contains this {@link Arena}. * * @return The name of the world which contains this {@link Arena} * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ String getWorld() throws OrphanedComponentException; /** * Gets the {@link Boundary} which this {@link Arena} is contained within. * * @return The {@link Boundary} which this {@link Arena} is contained * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * within * @since 1.0 */ Boundary getBoundary() throws OrphanedComponentException; /** * Sets the {@link Boundary} which this {@link Arena} is contained within. * * @param bound The new {@link Boundary} which this {@link Arena} is to be * contained within * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ void setBoundary(Boundary bound) throws OrphanedComponentException; /** * Returns an {@link ImmutableMap} of points at which players may spawn * upon entering this arena, mapped to their respective IDs. * * @return An immutable {@link BiMap} of points at which players may spawn * upon entering this arena, mapped to their respective IDs * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ ImmutableMap<Integer, Location3D> getSpawnPoints() throws OrphanedComponentException; int addSpawnPoint(Location3D spawn) throws IllegalArgumentException, OrphanedComponentException; void removeSpawnPoint(int index) throws OrphanedComponentException; void removeSpawnPoint(Location3D location) throws OrphanedComponentException; /** * Gets the {@link Round} contained by this {@link Arena}. * * @return The {@link Round} contained by this {@link Arena} * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ Optional<Round> getRound() throws OrphanedComponentException; Round createRound(ImmutableSet<LifecycleStage> stages) throws IllegalArgumentException, IllegalStateException, OrphanedComponentException; Round createRound() throws IllegalStateException, OrphanedComponentException; Round getOrCreateRound(ImmutableSet<LifecycleStage> stages) throws IllegalArgumentException, OrphanedComponentException; /** * Attempts to get the {@link Round} contained by this arena, or if not * present, creates and returns a new one with the default lifecycle stages. * * @return The retrieved or newly-created {@link Round} * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) */ Round getOrCreateRound() throws OrphanedComponentException; /** * Gets an {@link ImmutableList} of {@link LobbySign}s registered for this * {@link Arena}. * * @return An {@link ImmutableList} of {@link LobbySign}s registered for * this {@link Arena} * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ ImmutableList<LobbySign> getLobbySigns() throws OrphanedComponentException; Optional<LobbySign> getLobbySignAt(Location3D location) throws IllegalArgumentException, OrphanedComponentException; Optional<StatusLobbySign> createStatusLobbySign(Location3D location) throws IllegalArgumentException, OrphanedComponentException; Optional<ChallengerListingLobbySign> createChallengerListingLobbySign(Location3D location, int index) throws IllegalArgumentException, OrphanedComponentException; void markForRollback(Location3D location) throws IllegalArgumentException, OrphanedComponentException; void rollback() throws IllegalStateException, OrphanedComponentException; }
package be.isach.joinitems; import org.bukkit.Bukkit; public class Async { public static void run(Runnable runnable) { Bukkit.getScheduler().runTaskAsynchronously(JoinItems.instance, runnable); } }
package net.caseif.flint.round; import net.caseif.flint.arena.Arena; import net.caseif.flint.arena.SpawningMode; import net.caseif.flint.challenger.Challenger; import net.caseif.flint.challenger.Team; import net.caseif.flint.component.Component; import net.caseif.flint.component.ComponentOwner; import net.caseif.flint.config.RoundConfigNode; import net.caseif.flint.component.exception.OrphanedComponentException; import net.caseif.flint.exception.round.RoundJoinException; import net.caseif.flint.metadata.MetadataHolder; import net.caseif.flint.util.annotation.Orphaner; import net.caseif.flint.util.physical.Location3D; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.util.UUID; @SuppressWarnings("DuplicateThrows") public interface Round extends MetadataHolder, ComponentOwner, Component<Arena> { /** * Gets the {@link Arena} this {@link Round} is owned by. * * <p><strong>Note:</strong> This a convenience method for * {@link Round#getOwner()}.</p> * * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @return The {@link Arena} this {@link Round} is owned by * @since 1.0 */ Arena getArena() throws OrphanedComponentException; /** * Returns an {@link ImmutableList} of {@link Challenger}s in this * {@link Round}. * * @return An {@link ImmutableList} of {@link Challenger}s in this * {@link Round} * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ ImmutableList<Challenger> getChallengers() throws OrphanedComponentException; /** * Gets the {@link Challenger} from this {@link Round} with the given * {@link UUID}. * * @param uuid The {@link UUID} to look up * @return The {@link Challenger} from this {@link Round} with the given * {@link UUID}. * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ Optional<Challenger> getChallenger(UUID uuid) throws OrphanedComponentException; @SuppressWarnings({"deprecation", "unused"}) @Deprecated Challenger _INVALID_addChallenger(UUID uuid) throws RoundJoinException, OrphanedComponentException; JoinResult addChallenger(UUID uuid) throws OrphanedComponentException; @Orphaner void removeChallenger(UUID uuid) throws IllegalArgumentException, OrphanedComponentException; @Orphaner void removeChallenger(Challenger challenger) throws IllegalArgumentException, OrphanedComponentException; /** * Retrieves the next available spawn point. * * <p>If the round's spawning mode is set to {@link SpawningMode#RANDOM}, a * random point will be selected. Otherwise, if it is set to * {@link SpawningMode#SEQUENTIAL}, the next point in sequence will be * selected and the selection counter will be incremented.</p> * * @return The next available spawn point. * @since 1.1 */ Location3D nextSpawnPoint(); /** * Returns an {@link ImmutableList} of {@link Team}s in this {@link Round}. * * @return An {@link ImmutableList} of {@link Team}s in this {@link Round} * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ ImmutableList<Team> getTeams() throws OrphanedComponentException; /** * Gets the {@link Team} from this {@link Round} with the given identifier. * * @param id The identifier to look up * @return The {@link Team} with the given identifier * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ Optional<Team> getTeam(String id) throws OrphanedComponentException; Team createTeam(String id) throws IllegalArgumentException, OrphanedComponentException; /** * Gets the {@link Team} from this {@link Round} with the given identifer, * or creates it if it does not already exist. * * @param id The identifier to look up * @return The fetched or newly created {@link Team}. * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ Team getOrCreateTeam(String id) throws OrphanedComponentException; @Orphaner void removeTeam(String id) throws IllegalArgumentException, OrphanedComponentException; @Orphaner void removeTeam(Team team) throws IllegalArgumentException, OrphanedComponentException; /** * Returns the subset of {@link Challenger}s in this {@link Round} who are * marked as spectating. * * @return The subset of {@link Challenger}s in this {@link Round} who are * marked as spectating * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ ImmutableList<Challenger> getSpectators() throws OrphanedComponentException; /** * Broadcasts the string {@code message} to all {@link Challenger}s in * this {@link Round}. * * @param message The string to broadcast * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ void broadcast(String message) throws OrphanedComponentException; /** * Gets an immutable {@link ImmutableSet} of this {@link Round}'s defined * lifecycle stages. * * @return This {@link Round}'s defined lifecycle stages * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ ImmutableSet<LifecycleStage> getLifecycleStages() throws OrphanedComponentException; /** * Gets this {@link Round}'s current {@link LifecycleStage}. * * @return This {@link Round}'s current {@link LifecycleStage} * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ LifecycleStage getLifecycleStage() throws OrphanedComponentException; void setLifecycleStage(LifecycleStage stage, boolean resetTimer) throws IllegalArgumentException, OrphanedComponentException; void setLifecycleStage(LifecycleStage stage) throws IllegalArgumentException, OrphanedComponentException; /** * Gets the {@link LifecycleStage} by the given ID in this {@link Round}. * * @param id The ID of the {@link LifecycleStage} to get * @return The {@link LifecycleStage} by the given ID in this {@link Round}, * or {@link Optional#absent()} if one does not exist * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ Optional<LifecycleStage> getLifecycleStage(String id) throws OrphanedComponentException; /** * Gets the {@link LifecycleStage} at the given index for this * {@link Round}. * * @param index The index of the {@link LifecycleStage} to get * @return The {@link LifecycleStage} at the given index * @throws IndexOutOfBoundsException If {@code index} is greater than * the highest defined index * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ LifecycleStage getLifecycleStage(int index) throws IndexOutOfBoundsException, OrphanedComponentException; /** * Gets this {@link Round}'s next {@link LifecycleStage}, if applicable. * * @return This {@link Round}'s next {@link LifecycleStage}, or * {@link Optional#absent()} if the current stage is the final defined * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ Optional<LifecycleStage> getNextLifecycleStage() throws OrphanedComponentException; void nextLifecycleStage() throws IllegalStateException, OrphanedComponentException; /** * Gets the current state of this {@link Round}'s timer in seconds. * * <p>Typically, this represents the time since its last lifecycle stage * change, although this is not absolute.</p> * * @return The current state of this {@link Round}'s timer in seconds * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ long getTime() throws OrphanedComponentException; /** * Sets the current state of this {@link Round}'s timer in seconds. * * @param time The current state of this {@link Round}'s timer in seconds * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ void setTime(long time) throws OrphanedComponentException; /** * Gets the time in seconds until this {@link Round} is due to change * its {@link LifecycleStage lifecycle stage}. * * @return The time in seconds until this {@link Round} is due to change * its {@link LifecycleStage lifecycle stage}, or {@code -1} if the * current stage is untimed * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ long getRemainingTime() throws OrphanedComponentException; /** * Returns whether this {@link Round}'s timer is currently ticking. * * @return Whether this {@link Round}'s timer is currently ticking * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ boolean isTimerTicking() throws OrphanedComponentException; /** * Sets whether this {@link Round}'s timer is currently ticking. * * @param ticking Whether this {@link Round}'s timer is currently ticking * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ void setTimerTicking(boolean ticking) throws OrphanedComponentException; /** * Sets this {@link Round}'s lifecycle stage to its initial state and resets * and stops the timer. * * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ void resetTimer() throws OrphanedComponentException; @Orphaner void end() throws IllegalStateException, OrphanedComponentException; @Orphaner void end(boolean rollback) throws IllegalStateException, OrphanedComponentException; /** * Returns whether this {@link Round} is currently ending. This method * returns true during and only during the period between the {@link Round} * being requested to end, and the {@link Round} being fully ended and * orphaned. * * @return Whether this {@link Round} is currently in the process of ending. * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.1 */ boolean isEnding() throws OrphanedComponentException; /** * Gets the value of the given {@link RoundConfigNode} for this * {@link Round}, or the server value if it is not set. * * @param node The {@link RoundConfigNode} to look up * @param <T> The value type associated with {@code node} * @return The value associated with {@code node} * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ <T> T getConfigValue(RoundConfigNode<T> node) throws OrphanedComponentException; /** * Sets the value of the given {@link RoundConfigNode} for this * {@link Round}. * * @param node The {@link RoundConfigNode} to set * @param value The new value associated with {@code node} * @param <T> The value type associated with {@code node} * @throws OrphanedComponentException If this object is orphaned (see * {@link Component} for details) * @since 1.0 */ <T> void setConfigValue(RoundConfigNode<T> node, T value) throws OrphanedComponentException; }
package com.couchbase.lite; import com.couchbase.lite.internal.InterfaceAudience; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Future; /** * Represents a query of a CouchbaseLite 'view', or of a view-like resource like _all_documents. */ public class Query { public enum IndexUpdateMode { NEVER, BEFORE, AFTER } public enum AllDocsMode { ALL_DOCS, INCLUDE_DELETED, SHOW_CONFLICTS, ONLY_CONFLICTS } /** * The database that contains this view. */ private Database database; /** * The view object associated with this query */ private View view; // null for _all_docs query /** * Is this query based on a temporary view? */ private boolean temporaryView; /** * The number of initial rows to skip. Default value is 0. * Should only be used with small values. For efficient paging, use startKey and limit. */ private int skip; /** * The maximum number of rows to return. Default value is 0, meaning 'unlimited'. */ private int limit = Integer.MAX_VALUE; /** * If non-nil, the key value to start at. */ private Object startKey; /** * If non-nil, the key value to end after. */ private Object endKey; /** * If non-nil, the document ID to start at. * (Useful if the view contains multiple identical keys, making .startKey ambiguous.) */ private String startKeyDocId; /** * If non-nil, the document ID to end at. * (Useful if the view contains multiple identical keys, making .endKey ambiguous.) */ private String endKeyDocId; /** * If set, the view will not be updated for this query, even if the database has changed. * This allows faster results at the expense of returning possibly out-of-date data. */ private IndexUpdateMode indexUpdateMode; private AllDocsMode allDocsMode; /** * Should the rows be returned in descending key order? Default value is NO. */ private boolean descending; /** * If set to YES, the results will include the entire document contents of the associated rows. * These can be accessed via QueryRow's -documentProperties property. * This slows down the query, but can be a good optimization if you know you'll need the entire * contents of each document. (This property is equivalent to "include_docs" in the CouchDB API.) */ private boolean prefetch; /** * If set to YES, disables use of the reduce function. * (Equivalent to setting "?reduce=false" in the REST API.) */ private boolean mapOnly; private boolean includeDeleted; /** * If non-nil, the query will fetch only the rows with the given keys. */ private List<Object> keys; /** * If non-zero, enables grouping of results, in views that have reduce functions. */ private int groupLevel; /** * If a query is running and the user calls stop() on this query, the future * will be used in order to cancel the query in progress. */ protected Future updateQueryFuture; private long lastSequence; /** * Constructor */ @InterfaceAudience.Private Query(Database database, View view) { this.database = database; this.view = view; limit = Integer.MAX_VALUE; mapOnly = (view != null && view.getReduce() == null); indexUpdateMode = IndexUpdateMode.NEVER; allDocsMode = AllDocsMode.ALL_DOCS; } /** * Constructor */ @InterfaceAudience.Private Query(Database database, Mapper mapFunction) { this(database, database.makeAnonymousView()); temporaryView = true; view.setMap(mapFunction, ""); } /** * Constructor */ @InterfaceAudience.Private Query(Database database, Query query) { this(database, query.getView()); limit = query.limit; skip = query.skip; startKey = query.startKey; endKey = query.endKey; descending = query.descending; prefetch = query.prefetch; keys = query.keys; groupLevel = query.groupLevel; mapOnly = query.mapOnly; startKeyDocId = query.startKeyDocId; endKeyDocId = query.endKeyDocId; indexUpdateMode = query.indexUpdateMode; allDocsMode = query.allDocsMode; } /** * The database this query is associated with */ @InterfaceAudience.Public public Database getDatabase() { return database; } @InterfaceAudience.Public public int getLimit() { return limit; } @InterfaceAudience.Public public void setLimit(int limit) { this.limit = limit; } @InterfaceAudience.Public public int getSkip() { return skip; } @InterfaceAudience.Public public void setSkip(int skip) { this.skip = skip; } @InterfaceAudience.Public public boolean isDescending() { return descending; } @InterfaceAudience.Public public void setDescending(boolean descending) { this.descending = descending; } @InterfaceAudience.Public public Object getStartKey() { return startKey; } @InterfaceAudience.Public public void setStartKey(Object startKey) { this.startKey = startKey; } @InterfaceAudience.Public public Object getEndKey() { return endKey; } @InterfaceAudience.Public public void setEndKey(Object endKey) { this.endKey = endKey; } @InterfaceAudience.Public public String getStartKeyDocId() { return startKeyDocId; } @InterfaceAudience.Public public void setStartKeyDocId(String startKeyDocId) { this.startKeyDocId = startKeyDocId; } @InterfaceAudience.Public public String getEndKeyDocId() { return endKeyDocId; } @InterfaceAudience.Public public void setEndKeyDocId(String endKeyDocId) { this.endKeyDocId = endKeyDocId; } @InterfaceAudience.Public public IndexUpdateMode getIndexUpdateMode() { return indexUpdateMode; } @InterfaceAudience.Public public void setIndexUpdateMode(IndexUpdateMode indexUpdateMode) { this.indexUpdateMode = indexUpdateMode; } @InterfaceAudience.Public public AllDocsMode getAllDocsMode() { return allDocsMode; } @InterfaceAudience.Public public void setAllDocsMode(AllDocsMode allDocsMode) { this.allDocsMode = allDocsMode; } @InterfaceAudience.Public public List<Object> getKeys() { return keys; } @InterfaceAudience.Public public void setKeys(List<Object> keys) { this.keys = keys; } @InterfaceAudience.Public public boolean isMapOnly() { return mapOnly; } @InterfaceAudience.Public public void setMapOnly(boolean mapOnly) { this.mapOnly = mapOnly; } @InterfaceAudience.Public public int getGroupLevel() { return groupLevel; } @InterfaceAudience.Public public void setGroupLevel(int groupLevel) { this.groupLevel = groupLevel; } @InterfaceAudience.Public public boolean shouldPrefetch() { return prefetch; } @InterfaceAudience.Public public void setPrefetch(boolean prefetch) { this.prefetch = prefetch; } @InterfaceAudience.Public public boolean shouldIncludeDeleted() { return allDocsMode == AllDocsMode.INCLUDE_DELETED; } @InterfaceAudience.Public public void setIncludeDeleted(boolean includeDeletedParam) { allDocsMode = (includeDeletedParam == true) ? AllDocsMode.INCLUDE_DELETED : AllDocsMode.ALL_DOCS; } /** * Sends the query to the server and returns an enumerator over the result rows (Synchronous). * If the query fails, this method returns nil and sets the query's .error property. */ @InterfaceAudience.Public public QueryEnumerator run() throws CouchbaseLiteException { List<Long> outSequence = new ArrayList<Long>(); String viewName = (view != null) ? view.getName() : null; List<QueryRow> rows = database.queryViewNamed(viewName, getQueryOptions(), outSequence); lastSequence = outSequence.get(0); return new QueryEnumerator(database, rows, lastSequence); } /** * Returns a live query with the same parameters. */ @InterfaceAudience.Public public LiveQuery toLiveQuery() { if (view == null) { throw new IllegalStateException("Cannot convert a Query to LiveQuery if the view is null"); } return new LiveQuery(this); } /** * Starts an asynchronous query. Returns immediately, then calls the onLiveQueryChanged block when the * query completes, passing it the row enumerator. If the query fails, the block will receive * a non-nil enumerator but its .error property will be set to a value reflecting the error. * The originating Query's .error property will NOT change. */ @InterfaceAudience.Public public Future runAsync(final QueryCompleteListener onComplete) { return runAsyncInternal(onComplete); } @InterfaceAudience.Private Future runAsyncInternal(final QueryCompleteListener onComplete) { return database.getManager().runAsync(new Runnable() { @Override public void run() { try { String viewName = view.getName(); QueryOptions options = getQueryOptions(); List<Long> outSequence = new ArrayList<Long>(); List<QueryRow> rows = database.queryViewNamed(viewName, options, outSequence); long sequenceNumber = outSequence.get(0); QueryEnumerator enumerator = new QueryEnumerator(database, rows, sequenceNumber); onComplete.completed(enumerator, null); } catch (Throwable t) { onComplete.completed(null, t); } } }); } public View getView() { return view; } private QueryOptions getQueryOptions() { QueryOptions queryOptions = new QueryOptions(); queryOptions.setStartKey(getStartKey()); queryOptions.setEndKey(getEndKey()); queryOptions.setStartKey(getStartKey()); queryOptions.setKeys(getKeys()); queryOptions.setSkip(getSkip()); queryOptions.setLimit(getLimit()); queryOptions.setReduce(!isMapOnly()); queryOptions.setReduceSpecified(true); queryOptions.setGroupLevel(getGroupLevel()); queryOptions.setDescending(isDescending()); queryOptions.setIncludeDocs(shouldPrefetch()); queryOptions.setUpdateSeq(true); queryOptions.setInclusiveEnd(true); queryOptions.setStale(getIndexUpdateMode()); queryOptions.setAllDocsMode(getAllDocsMode()); return queryOptions; } @Override protected void finalize() throws Throwable { super.finalize(); if (temporaryView) { view.delete(); } } public static interface QueryCompleteListener { public void completed(QueryEnumerator rows, Throwable error); } }
package net.jodah.lyra.config; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import net.jodah.lyra.ConnectionOptions; import net.jodah.lyra.Connections; import net.jodah.lyra.event.ChannelListener; import net.jodah.lyra.event.ConnectionListener; import net.jodah.lyra.event.ConsumerListener; import net.jodah.lyra.internal.util.Assert; import net.jodah.lyra.retry.RetryPolicy; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; /** * Lyra configuration. Changes are reflected in the resources created with this configuration. * * @author Jonathan Halterman */ public class Config implements ConnectionConfig { private final Config parent; private RetryPolicy retryPolicy; private RetryPolicy recoveryPolicy; private RetryPolicy connectRetryPolicy; private RetryPolicy connectionRecoveryPolicy; private RetryPolicy connectionRetryPolicy; private RetryPolicy channelRecoveryPolicy; private RetryPolicy channelRetryPolicy; private Boolean consumerRecovery; private Collection<ConnectionListener> connectionListeners = Collections.emptyList(); private Collection<ChannelListener> channelListeners = Collections.emptyList(); private Collection<ConsumerListener> consumerListeners = Collections.emptyList(); public Config() { parent = null; } /** * Creates a new Config object that inherits configuration from the {@code parent}. */ public Config(Config parent) { this.parent = parent; } @Override public Collection<ChannelListener> getChannelListeners() { return channelListeners != null ? channelListeners : parent != null ? parent.getChannelListeners() : null; } @Override public RetryPolicy getChannelRecoveryPolicy() { RetryPolicy result = channelRecoveryPolicy == null ? recoveryPolicy : channelRecoveryPolicy; return result != null ? result : parent != null ? parent.getChannelRecoveryPolicy() : null; } @Override public RetryPolicy getChannelRetryPolicy() { RetryPolicy result = channelRetryPolicy == null ? retryPolicy : channelRetryPolicy; return result != null ? result : parent != null ? parent.getChannelRetryPolicy() : null; } @Override public Collection<ConnectionListener> getConnectionListeners() { return connectionListeners != null ? connectionListeners : parent != null ? parent.getConnectionListeners() : null; } @Override public RetryPolicy getConnectionRecoveryPolicy() { RetryPolicy result = connectionRecoveryPolicy == null ? recoveryPolicy : connectionRecoveryPolicy; return result != null ? result : parent != null ? parent.getConnectionRecoveryPolicy() : null; } @Override public RetryPolicy getConnectionRetryPolicy() { RetryPolicy result = connectionRetryPolicy == null ? retryPolicy : connectionRetryPolicy; return result != null ? result : parent != null ? parent.getConnectionRetryPolicy() : null; } /** * Sets the policy to use for handling {@link Connections#create(ConnectionOptions, Config) * connection attempt} errors. Overrides the {@link #withRetryPolicy(RetryPolicy) global retry * policy}. */ public RetryPolicy getConnectRetryPolicy() { RetryPolicy result = connectRetryPolicy == null ? retryPolicy : connectRetryPolicy; return result != null ? result : parent != null ? parent.getConnectRetryPolicy() : null; } @Override public Collection<ConsumerListener> getConsumerListeners() { return consumerListeners != null ? consumerListeners : parent != null ? parent.getConsumerListeners() : null; } @Override public boolean isConsumerRecoveryEnabled() { Boolean result = isConsumerRecoveryEnabledInternal(); if (result != null) return result; RetryPolicy policy = getChannelRecoveryPolicy(); return policy != null && policy.allowsRetries(); } @Override public Config withChannelListeners(ChannelListener... channelListeners) { this.channelListeners = Arrays.asList(channelListeners); return this; } @Override public Config withChannelRecoveryPolicy(RetryPolicy channelRecoveryPolicy) { this.channelRecoveryPolicy = channelRecoveryPolicy; return this; } @Override public Config withChannelRetryPolicy(RetryPolicy channelRetryPolicy) { this.channelRetryPolicy = channelRetryPolicy; return this; } @Override public Config withConnectionListeners(ConnectionListener... connectionListeners) { this.connectionListeners = Arrays.asList(connectionListeners); return this; } @Override public Config withConnectionRecoveryPolicy(RetryPolicy connectionRecoveryPolicy) { this.connectionRecoveryPolicy = connectionRecoveryPolicy; return this; } @Override public Config withConnectionRetryPolicy(RetryPolicy connectionRetryPolicy) { this.connectionRetryPolicy = connectionRetryPolicy; return this; } /** * Sets the policy to use for handling {@link Connections#create(ConnectionOptions, Config) * connection attempt} errors. Overrides the {@link #withRetryPolicy(RetryPolicy) global retry * policy}. */ public Config withConnectRetryPolicy(RetryPolicy connectRetryPolicy) { this.connectRetryPolicy = connectRetryPolicy; return this; } @Override public Config withConsumerListeners(ConsumerListener... consumerListeners) { this.consumerListeners = Arrays.asList(consumerListeners); return this; } @Override public Config withConsumerRecovery(boolean enabled) { consumerRecovery = Boolean.valueOf(enabled); return this; } /** * Sets the policy to use for the recovery of Connections/Channels/Consumers after an unexpected * Connection/Channel closure. Can be overridden with specific policies via * {@link #withConnectionRecoveryPolicy(RetryPolicy)} and * {@link #withChannelRecoveryPolicy(RetryPolicy)}. */ public Config withRecoveryPolicy(RetryPolicy recoveryPolicy) { this.recoveryPolicy = recoveryPolicy; return this; } /** * Sets the policy to use for handling {@link Connections#create(ConnectionOptions, Config) * connection attempt}, {@link Connection} invocation, and {@link Channel} invocation errors. Can * be overridden with specific policies via {@link #withConnectRetryPolicy(RetryPolicy)}, * {@link #withConnectionRetryPolicy(RetryPolicy)}, and * {@link #withChannelRetryPolicy(RetryPolicy)}. */ public Config withRetryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } private Boolean isConsumerRecoveryEnabledInternal() { return consumerRecovery != null ? consumerRecovery : parent != null ? parent.isConsumerRecoveryEnabled() : null; } public static ConfigurableChannel of(Channel channel) { Assert.isTrue(channel instanceof ConfigurableChannel, "The channel {} was not created by Lyra", channel); return (ConfigurableChannel) channel; } public static ConfigurableConnection of(Connection connection) { Assert.isTrue(connection instanceof ConfigurableConnection, "The connection {} was not created by Lyra", connection); return (ConfigurableConnection) connection; } }
/** * @author ElecEntertainment * @team Larry1123, Joshtmathews, Sinzo, Xalbec * @lastedit Apr 18, 2013 2:12:20 AM */ package net.larry1123.lib; import net.canarymod.api.entity.living.humanoid.Player; import net.larry1123.lib.customPacket.BungeeCord; import net.larry1123.lib.plugin.UtilPlugin; import net.larry1123.lib.plugin.commands.Commands; public class CanaryUtil extends UtilPlugin { public static class CoustomPacket { public String getRealPlayerIp(Player player) { return BungeeCord.getRealPlayerIp(player); } } static CoustomPacket coustompacket = new CoustomPacket(); static Commands commands = new Commands(); public static CoustomPacket coustomPacket() { return coustompacket; } public static Commands commands() { return commands; } protected String version = "0.0.1"; protected String author = "Larry1123"; @Override public void disable() { logger.logCustom(pluginLoggerLevel, "Plugin Disabled"); endLogger(); } @Override public boolean enable() { logger.logCustom(pluginLoggerLevel, "Plugin Enabled"); return true; } }
package oktareport; import org.apache.commons.cli.*; import java.io.BufferedReader; import java.io.Console; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class UniqueLoginReport { private static String tenantUrl = null; private static String token = null; private static final Logger logger = LogManager.getLogger(UniqueLoginReport.class); private static final Logger reportLog = LogManager.getLogger("loginreport"); private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); private static long HOURS24 = 86400000L; private static Pattern linkMatcher = Pattern.compile("^<(.*)>; rel=\"(.*)\"$"); public static String[] get(String resource, String token) { boolean tryAgain = true; String result = ""; String nextUrl = ""; URL url; HttpURLConnection conn; BufferedReader rd; String line; String[] response = new String[2]; logger.debug("URL = " + resource); try { url = new URL(resource); while (tryAgain) { result = ""; nextUrl = ""; try { conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "SSWS " + token); conn.setRequestMethod("GET"); String ret = conn.getResponseMessage(); int retCode = conn.getResponseCode(); if (retCode == 200) { tryAgain = false; rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); while ((line = rd.readLine()) != null) { result += line; } response[0] = result; List<String> links = conn.getHeaderFields().get("Link"); links.forEach( (link) -> { Matcher linkMatch = linkMatcher.matcher(link); if(linkMatch.matches()) { if(linkMatch.group(2).equals("next")) { response[1] = linkMatch.group(1); } } }); rd.close(); } else if (retCode == 404) { tryAgain = false; rd = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8")); while ((line = rd.readLine()) != null) { result += line; } rd.close(); } else { tryAgain = false; rd = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8")); while ((line = rd.readLine()) != null) { result += line; } rd.close(); logger.error(new Date() + " GET " + resource + " RETURNED " + retCode + ":" + ret); logger.error(new Date() + " ERRORSTREAM = " + result); } } catch (SocketTimeoutException e) { tryAgain = true; logger.debug(new Date() + " GET " + resource + " " + e.getLocalizedMessage()); e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); logger.error("error with API processing", e); } return response; } public static void eventsAPI(String startDate, String endDate) throws UnsupportedEncodingException{ String[] ret = get(tenantUrl + "/events?filter=published%20gt%20%22" + URLEncoder.encode(startDate, "UTF-8") + "%22%20and%20published%20lt%20%22" + URLEncoder.encode(endDate, "UTF-8") + "%22%20and%20%28action.objectType%20eq%20%22core.user_auth.login_success%22%20or%20" + "action.objectType%20eq%20%22core.user_auth.idp.saml.login_success%22%20or%20action.objectType%20eq%20" +"" + "%22core.user_auth.idp.saml.login_success%22+or+action.objectType+eq+%22app.ldap.login.success%22+or+action.objectType+eq+%22app.ad.login.success%22%29", token); while(!ret[0].equals("[]")) { getUniqueUsersFromEvent(ret[0]); if(ret[1] != null && !ret[1].trim().equals("")) { ret = get(ret[1], token); } } UniqueUsers.getCSV(tenantUrl); UniqueUsers.getRawCSV(tenantUrl); } public static void getUniqueUsersFromEvent(String ret) { //Check to make sure there is a login JSONArray eventAftArr = new JSONArray(ret); for (int i = 0; i < eventAftArr.length(); i++) { if (eventAftArr.getJSONObject(i).getJSONObject("action").getString("objectType").equals("core.user_auth.login_success")) { try { String login = eventAftArr.getJSONObject(i).getJSONArray("targets").getJSONObject(0).getString("login"); String requestId = eventAftArr.getJSONObject(i).getString("requestId"); String published = eventAftArr.getJSONObject(i).getString("published"); try { UniqueUsers.addUser(login, formatter.parse(published.replaceAll("Z$", "+0000")), requestId); } catch (java.text.ParseException pe) { logger.error("Date Parse issue for " + login + " date: " + published, pe); System.exit(-1); } } catch (JSONException je) { logger.debug(je); logger.debug(eventAftArr.getJSONObject(i).toString()); } } else { if (!eventAftArr.getJSONObject(i).getJSONArray("targets").getJSONObject(0).isNull("login")) { String login = eventAftArr.getJSONObject(i).getJSONArray("targets").getJSONObject(0).getString("login"); String idpSource = eventAftArr.getJSONObject(i).getJSONArray("targets").getJSONObject(1).getString("displayName"); String requestId = eventAftArr.getJSONObject(i).getString("requestId"); UniqueUsers.addIdpSource(login, requestId, idpSource); } } } return; } public static void main(String[] args) throws Exception { logger.info("Entering Application..."); // create the command line parser CommandLineParser parser = new DefaultParser(); // create the Options Options options = new Options(); options.addOption(Option.builder().longOpt("oktaorg") .hasArg() .required() .desc("enter your okta org i.e. https://youroktaorg.okta.com") .build()); options.addOption(Option.builder().longOpt("apikey") .hasArg() .desc("enter your apikey if not present you will be asked when program starts") .build()); options.addOption(Option.builder().longOpt("startDate") .hasArg() .required() .desc("start date in the following format YYYY-MM-DDTHH:MM:SS.sssZ") .build()); options.addOption(Option.builder().longOpt("endDate") .hasArg() .required() .desc("end date in the following format YYYY-MM-DDTHH:MM:SS.sssZ") .build()); boolean displayApiKeyEnterMsg = true; String startEntered = ""; String endEntered = ""; try { // parse the command line arguments CommandLine line = parser.parse( options, args ); // validate that block-size has been set if( line.hasOption( "apikey" ) ) { displayApiKeyEnterMsg = false; } Console console = System.console(); //tenantUrl = console.readLine("Enter BCBSA Okta org url:"); tenantUrl = line.getOptionValue("oktaorg"); tenantUrl = tenantUrl + "/api/v1"; if(displayApiKeyEnterMsg) { token = console.readLine("Enter API Token:"); } else { token = line.getOptionValue("apikey"); } startEntered = line.getOptionValue("startDate"); endEntered = line.getOptionValue("endDate"); //startEntered = console.readLine("Enter Report Start Date in this format :YYYY-MM-DDT00:00:00.000Z:"); //endEntered = console.readLine("Enter Report End Date in this format :YYYY-MM-DDT00:00:00.000Z:"); eventsAPI(startEntered, endEntered); } catch( ParseException exp ) { System.out.println(exp.getMessage()); logger.error( exp.getMessage() ); System.exit(-1); } } }
package com.hide23.ivyrun; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.io.IOException; import java.io.Writer; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Execute an executable jar from artifactory */ public class IvyRun { Path setting; /** * @param repos repositories. will be used as resolvers in a chain resolver. * if it is empty, default BintrayResolver will be used */ public IvyRun(List<URI> repos) { try { setting = Files.createTempFile("", ""); try (Writer w = Files.newBufferedWriter(setting, StandardCharsets.UTF_8)) { XMLStreamWriter x = XMLOutputFactory.newInstance().createXMLStreamWriter(w); x.writeStartDocument(); x.writeStartElement("ivysettings"); x.writeStartElement("settings"); x.writeAttribute("defaultResolver", "chain"); x.writeEndElement(); x.writeStartElement("caches"); x.writeEndElement(); x.writeStartElement("resolvers"); x.writeStartElement("chain"); x.writeAttribute("name", "chain"); if (repos.isEmpty()) { x.writeStartElement("bintray"); x.writeEndElement(); } else { for (URI u : repos) { x.writeStartElement("ibiblio"); x.writeAttribute("m2compatible", "true"); x.writeAttribute("root", u.toString()); x.writeEndElement(); } } x.writeEndElement(); x.writeEndElement(); x.writeEndDocument(); } } catch (IOException | XMLStreamException e) { e.printStackTrace(); } } public IvyRun(URI... repos) { this(Arrays.asList(repos)); } public void run(String organization, String name, String rev, String mainClass, String... args) throws Exception { List<String> a = new ArrayList<>(8 + args.length); a.add("-settings"); a.add(setting.toFile().getPath()); a.add("-dependency"); a.add(organization); a.add(name); a.add(rev); a.add("-main"); a.add(mainClass); a.addAll(Arrays.asList(args)); org.apache.ivy.Main.main(a.toArray(new String[0])); } }
package org.basex.query; import static org.basex.core.Text.*; import static org.basex.query.QueryTokens.*; import static org.basex.query.util.Err.*; import static org.basex.util.Token.*; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import org.basex.core.Context; import org.basex.core.Progress; import org.basex.core.Prop; import org.basex.core.User; import org.basex.core.Commands.CmdPerm; import org.basex.core.cmd.Check; import org.basex.core.cmd.Close; import org.basex.core.cmd.Open; import org.basex.data.Data; import org.basex.data.FTPosData; import org.basex.data.Nodes; import org.basex.data.Result; import org.basex.data.Serializer; import org.basex.data.SerializerProp; import org.basex.io.IO; import org.basex.query.expr.Expr; import org.basex.query.ft.FTOpt; import org.basex.query.ft.Scoring; import org.basex.query.item.DBNode; import org.basex.query.item.Dat; import org.basex.query.item.Dtm; import org.basex.query.item.Item; import org.basex.query.item.Seq; import org.basex.query.item.Tim; import org.basex.query.item.Uri; import org.basex.query.item.Value; import org.basex.query.iter.Iter; import org.basex.query.iter.NodIter; import org.basex.query.iter.ItemIter; import org.basex.query.up.Updates; import org.basex.query.util.Err; import org.basex.query.util.Functions; import org.basex.query.util.Namespaces; import org.basex.query.util.Variables; import org.basex.util.Array; import org.basex.util.InputInfo; import org.basex.util.IntList; import org.basex.util.StringList; import org.basex.util.Token; import org.basex.util.TokenBuilder; import org.basex.util.Tokenizer; import org.basex.util.Util; public final class QueryContext extends Progress { /** Functions. */ public final Functions funcs = new Functions(); /** Variables. */ public final Variables vars = new Variables(); /** Scoring instance. */ public final Scoring score = new Scoring(); /** Namespaces. */ public Namespaces ns = new Namespaces(); /** Database context. */ public final Context context; /** Query string. */ public String query; /** XQuery version flag. */ public boolean xquery11; /** Cached stop word files. */ public HashMap<String, String> stop; /** Cached thesaurus files. */ public HashMap<String, String> thes; /** Reference to the root expression. */ public Expr root; /** Current context value. */ public Value value; /** Current context position. */ public long pos; /** Current context size. */ public long size; /** Used documents. */ public DBNode[] doc = new DBNode[1]; /** Number of documents. */ public int docs; /** Full-text position data (for visualization). */ public FTPosData ftpos; /** Full-text token counter (for visualization). */ public byte ftoknum; /** Current full-text options. */ public FTOpt ftopt; /** Current full-text token. */ public Tokenizer fttoken; /** Current Date. */ public Dat date; /** Current DateTime. */ public Dtm dtm; /** Current Time. */ public Tim time; /** Default function namespace. */ public byte[] nsFunc = FNURI; /** Default element namespace. */ public byte[] nsElem = EMPTY; /** Static Base URI. */ public Uri baseURI = Uri.EMPTY; /** Default collation. */ public Uri collation = Uri.uri(URLCOLL); /** Default boundary-space. */ public boolean spaces; /** Empty Order mode. */ public boolean orderGreatest; /** Preserve Namespaces. */ public boolean nsPreserve = true; /** Inherit Namespaces. */ public boolean nsInherit = true; /** Ordering mode. */ public boolean ordered; /** Construction mode. */ public boolean construct; /** String container for query background information. */ private final TokenBuilder info = new TokenBuilder(); /** Info flag. */ private final boolean inf; /** Optimization flag. */ private boolean firstOpt = true; /** Evaluation flag. */ private boolean firstEval = true; /** Serializer options. */ SerializerProp serProp; /** List of modules. */ final StringList modules = new StringList(); /** List of loaded modules. */ final StringList modLoaded = new StringList(); /** Initial context set (default: null). */ Nodes nodes; /** Collections. */ private NodIter[] collect = new NodIter[1]; /** Collection names. */ private byte[][] collName = new byte[1][]; /** Collection counter. */ private int colls; /** Initial number of documents. */ private int rootDocs; /** Pending updates. */ public Updates updates = new Updates(false); /** Indicates if this query performs updates. */ public boolean updating; /** Compilation flag: current node has leaves. */ public boolean leaf; /** Compilation flag: FLWOR clause performs grouping. */ public boolean grouping; /** Compilation flag: full-text evaluation can be stopped after first hit. */ public boolean ftfast = true; /** * Constructor. * @param ctx context reference */ public QueryContext(final Context ctx) { context = ctx; nodes = ctx.current; ftopt = new FTOpt(ctx.prop); xquery11 = ctx.prop.is(Prop.XQUERY11); inf = ctx.prop.is(Prop.QUERYINFO); if(ctx.query != null) baseURI = Uri.uri(token(ctx.query.url())); } /** * Parses the specified query. * @param q input query * @throws QueryException query exception */ public void parse(final String q) throws QueryException { root = new QueryParser(q, this).parse(file(), null); query = q; } /** * Parses the specified module. * @param q input query * @throws QueryException query exception */ public void module(final String q) throws QueryException { new QueryParser(q, this).parse(file(), Uri.EMPTY); } /** * Optimizes the expression. * @throws QueryException query exception */ public void compile() throws QueryException { // add full-text container reference if(nodes != null && nodes.ftpos != null) ftpos = new FTPosData(); try { // cache the initial context nodes if(nodes != null) { final Data data = nodes.data; if(!context.perm(User.READ, data.meta)) Err.PERMNO.thrw(null, CmdPerm.READ); final int s = (int) nodes.size(); if(nodes.doc) { // create document nodes doc = new DBNode[s]; for(int n = 0; n < s; ++n) { addDoc(new DBNode(data, nodes.nodes[n], Data.DOC)); } } else { for(final int p : data.doc()) addDoc(new DBNode(data, p, Data.DOC)); } rootDocs = docs; // create initial context items if(nodes.doc) { value = Seq.get(doc, docs); } else { // otherwise, add all context items final ItemIter ir = new ItemIter(s); for(int n = 0; n < s; ++n) { ir.add(new DBNode(data, nodes.nodes[n])); } value = ir.finish(); } // add collection instances addColl(new NodIter(doc, docs), token(data.meta.name)); } // dump compilation info if(inf) compInfo(NL + QUERYCOMP); // cache initial context final boolean empty = value == null; if(empty) value = Item.DUMMY; // compile global functions. // variables will be compiled if called for the first time funcs.comp(this); // compile the expression root = root.comp(this); // reset initial context if(empty) value = null; // dump resulting query if(inf) info.add(NL + QUERYRESULT + funcs + root + NL); } catch(final StackOverflowError ex) { Util.debug(ex); XPSTACK.thrw(null); } } /** * Evaluates the expression with the specified context set. * @return resulting value * @throws QueryException query exception */ protected Result eval() throws QueryException { // evaluates the query final Iter it = iter(); final ItemIter ir = new ItemIter(); Item i; // check if all results belong to the database of the input context if(nodes != null) { final Data data = nodes.data; final IntList pre = new IntList(); while((i = it.next()) != null) { checkStop(); if(!(i instanceof DBNode)) break; final DBNode n = (DBNode) i; if(n.data != data) break; pre.add(((DBNode) i).pre); } // completed... return standard nodeset with full-text positions if(i == null) return new Nodes(pre.toArray(), data, ftpos); // otherwise, add nodes to standard iterator final int ps = pre.size(); for(int p = 0; p < ps; ++p) ir.add(new DBNode(data, pre.get(p))); ir.add(i); } // use standard iterator while((i = it.next()) != null) { checkStop(); ir.add(i); } return ir; } /** * Returns a result iterator. * @return result iterator * @throws QueryException query exception */ public Iter iter() throws QueryException { try { final Iter iter = iter(root); if(!updating) return iter; final Value v = iter.finish(); updates.apply(this); if(context.data != null) context.update(); return v.iter(this); } catch(final StackOverflowError ex) { Util.debug(ex); XPSTACK.thrw(null); return null; } } /** * Recursively serializes the query plan. * @param ser serializer * @throws Exception exception */ protected void plan(final Serializer ser) throws Exception { // only show root node if functions or variables exist final boolean r = funcs.size() != 0 || vars.global().size != 0; if(r) ser.openElement(PLAN); funcs.plan(ser); //vars.plan(ser); root.plan(ser); if(r) ser.closeElement(); } /** * Evaluates the specified expression and returns an iterator. * @param e expression to be evaluated * @return iterator * @throws QueryException query exception */ public Iter iter(final Expr e) throws QueryException { checkStop(); return e.iter(this); } /** * Closes the context. * @throws IOException I/O exception */ void close() throws IOException { for(int d = rootDocs; d < docs; ++d) Close.close(context, doc[d].data); docs = 0; } /** * Copies properties of the specified context. * @param ctx context */ public void copy(final QueryContext ctx) { baseURI = ctx.baseURI; spaces = ctx.spaces; construct = ctx.construct; nsInherit = ctx.nsInherit; nsPreserve = ctx.nsPreserve; collation = ctx.collation; nsElem = ctx.nsElem; nsFunc = ctx.nsFunc; orderGreatest = ctx.orderGreatest; ordered = ctx.ordered; } /** * Adds some optimization info. * @param string evaluation info * @param ext text text extensions */ public void compInfo(final String string, final Object... ext) { if(!inf) return; if(!firstOpt) info.add(QUERYSEP); firstOpt = false; info.addExt(string, ext); info.add(NL); } /** * Adds some evaluation info. * @param string evaluation info * @param msg message */ public void evalInfo(final byte[] string, final String msg) { if(!inf) return; if(firstEval) info.add(NL + QUERYEVAL + NL); info.add(QUERYSEP); info.add(string); info.add(' '); info.add(msg); info.add(NL); firstEval = false; } /** * Opens an existing document/collection, or creates a new database instance. * @param input database name or file path * @param coll collection flag * @param db database flag * @param ii input info * @return database instance * @throws QueryException query exception */ public DBNode doc(final byte[] input, final boolean coll, final boolean db, final InputInfo ii) throws QueryException { if(contains(input, '<') || contains(input, '>')) INVDOC.thrw(ii, input); // check if the existing collections contain the document for(int c = 0; c < colls; ++c) { for(int n = 0; n < collect[c].size(); ++n) { if(eq(input, collect[c].get(n).base())) { return (DBNode) collect[c].get(n); } } } // check if the database has already been opened final String in = string(input); for(int d = 0; d < docs; ++d) if(doc[d].data.meta.name.equals(in)) return doc[d]; // check if the document has already been opened final IO io = IO.get(in); for(int d = 0; d < docs; ++d) if(doc[d].data.meta.file.eq(io)) return doc[d]; // get database instance Data data = null; if(db) { try { data = Open.open(in, context); } catch(final IOException ex) { NODB.thrw(ii, in); } } else { final IO file = file(); data = doc(in, file == null, coll, ii); if(data == null) data = doc(file.merge(in).path(), true, coll, ii); } // add document to array final DBNode node = new DBNode(data, 0, Data.DOC); addDoc(node); return node; } /** * Adds a document to the document array. * @param node node to be added */ private void addDoc(final DBNode node) { if(docs == doc.length) { final DBNode[] tmp = new DBNode[Array.newSize(docs)]; System.arraycopy(doc, 0, tmp, 0, docs); doc = tmp; } doc[docs++] = node; } /** * Opens the database or creates a new database instance for the specified * document. * @param path document path * @param err error flag * @param coll collection flag * @param ii input info * @return data instance * @throws QueryException query exception */ private Data doc(final String path, final boolean err, final boolean coll, final InputInfo ii) throws QueryException { try { return Check.check(context, path); } catch(final IOException ex) { if(err) (coll ? NOCOLL : NODOC).thrw(ii, ex.getMessage()); return null; } } /** * Adds a collection instance or returns an existing one. * @param input name of the collection to be returned * @param ii input info * @return collection * @throws QueryException query exception */ public NodIter coll(final byte[] input, final InputInfo ii) throws QueryException { // no collection specified.. return default collection/current context set int c = 0; if(input == null) { // no default collection was defined if(colls == 0) NODEFCOLL.thrw(ii); } else { // invalid collection reference if(contains(input, '<') || contains(input, '\\')) COLLINV.thrw(ii, input); // find specified collection while(c < colls && !eq(collName[c], input)) ++c; // add new collection if not found if(c == colls) { final int s = indexOf(input, '/'); if(s == -1) { addDocs(doc(input, true, false, ii), EMPTY); } else { addDocs(doc(substring(input, 0, s), true, false, ii), substring(input, s + 1)); } } } return new NodIter(collect[c].item, (int) collect[c].size()); } /** * Adds database documents as a collection. * @param db database reference * @param input inner collection path */ private void addDocs(final DBNode db, final byte[] input) { final NodIter col = new NodIter(); final Data data = db.data; final boolean rt = input.length == 0; if(!rt) doc = new DBNode[1]; docs = 0; for(int p = 0; p < data.meta.size; p += data.size(p, data.kind(p))) { final DBNode dbn = new DBNode(data, p); final String tmp = "/" + Token.string(input) + "/"; if(rt) { col.add(dbn); } else if(eq(lc(data.text(p, true)), lc(input)) || contains(lc(data.text(p, true)), lc(token(tmp)))) { col.add(dbn); // [AW] could lead to unexpected side effects addDoc(dbn); } } addColl(col, token(data.meta.name)); } /** * Adds a collection. * @param ni collection nodes * @param name name */ public void addColl(final NodIter ni, final byte[] name) { if(colls == collect.length) { collect = Arrays.copyOf(collect, colls << 1); collName = Array.copyOf(collName, colls << 1); } collect[colls] = ni; collName[colls++] = name; } /** * Returns the common database reference of all items or null. * @return database reference or null * @throws QueryException query exception */ public Data data() throws QueryException { if(value == null) return null; if(docNodes()) return doc[0].data; final Iter iter = value.iter(this); Data data = null; Item it; while((it = iter.next()) != null) { if(!(it instanceof DBNode)) return null; final Data d = ((DBNode) it).data; if(data != null && d != data) return null; data = d; } return data; } /** * Returns true if the current context item contains all root document nodes. * @return result of check */ public boolean docNodes() { return value instanceof Seq && value.sameAs(Seq.get(doc, docs)); } /** * Returns an IO representation of the base uri. * @return IO reference */ IO file() { return baseURI != Uri.EMPTY ? IO.get(string(baseURI.atom())) : null; } /** * Returns info on query compilation and evaluation. * @return query info */ String info() { return info.toString(); } @Override public String tit() { return QUERYEVAL; } @Override public String det() { return QUERYEVAL; } @Override public double prog() { return 0; } @Override public String toString() { return Util.name(this) + '[' + file() + ']'; } }
package org.codice.nitf; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import difflib.Delta; import difflib.DiffUtils; import difflib.Patch; import org.codice.nitf.filereader.FileType; import org.codice.nitf.filereader.ImageCompression; import org.codice.nitf.filereader.ImageCoordinatePair; import org.codice.nitf.filereader.ImageCoordinatesRepresentation; import org.codice.nitf.filereader.NitfDataExtensionSegment; import org.codice.nitf.filereader.NitfFile; import org.codice.nitf.filereader.NitfImageSegment; import org.codice.nitf.filereader.NitfSecurityClassification; import org.codice.nitf.filereader.RasterProductFormatUtilities; import org.codice.nitf.filereader.Tre; import org.codice.nitf.filereader.TreCollection; import org.codice.nitf.filereader.TreEntry; import org.codice.nitf.filereader.TreGroup; public class FileComparer { static final String OUR_OUTPUT_EXTENSION = ".OURS.txt"; static final String THEIR_OUTPUT_EXTENSION = ".THEIRS.txt"; private String filename = null; private NitfFile nitf = null; private NitfImageSegment segment1 = null; private NitfDataExtensionSegment des1 = null; private BufferedWriter out = null; FileComparer(String fileName) { filename = fileName; generateGdalMetadata(); generateOurMetadata(); compareMetadataFiles(); } private void generateOurMetadata() { try { nitf = new NitfFile(); nitf.parse(new FileInputStream(filename)); } catch (ParseException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } if (nitf.getNumberOfImageSegments() >= 1) { segment1 = nitf.getImageSegment(1); } if (nitf.getNumberOfDataExtensionSegments() >= 1) { des1 = nitf.getDataExtensionSegment(1); } outputData(); } private void outputData() { try { FileWriter fstream = new FileWriter(filename + OUR_OUTPUT_EXTENSION); out = new BufferedWriter(fstream); out.write("Driver: NITF/National Imagery Transmission Format\n"); out.write("Files: " + filename + "\n"); if (segment1 == null) { out.write(String.format("Size is 1, 1\n")); } else { out.write(String.format("Size is %d, %d\n", segment1.getNumberOfColumns(), segment1.getNumberOfRows())); } outputCoordinateSystem(); outputBaseMetadata(); outputTRExml(); outputImageStructure(); outputSubdatasets(); outputRPCs(); out.close(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } private void outputCoordinateSystem() throws IOException { boolean haveRPC = false; if (segment1 != null) { TreCollection treCollection = segment1.getTREsRawStructure(); for (Tre tre : treCollection.getTREs()) { if (tre.getName().equals("RPC00B")) { haveRPC = true; } } } if (segment1 == null) { out.write("Coordinate System is `'\n"); } else if (segment1.getImageCoordinatesRepresentation() == ImageCoordinatesRepresentation.UTMUPSNORTH) { out.write("Coordinate System is:\n"); out.write("PROJCS[\"unnamed\",\n"); out.write(" GEOGCS[\"WGS 84\",\n"); out.write(" DATUM[\"WGS_1984\",\n"); out.write(" SPHEROID[\"WGS 84\",6378137,298.257223563,\n"); out.write(" AUTHORITY[\"EPSG\",\"7030\"]],\n"); out.write(" TOWGS84[0,0,0,0,0,0,0],\n"); out.write(" AUTHORITY[\"EPSG\",\"6326\"]],\n"); out.write(" PRIMEM[\"Greenwich\",0,\n"); out.write(" AUTHORITY[\"EPSG\",\"8901\"]],\n"); out.write(" UNIT[\"degree\",0.0174532925199433,\n"); out.write(" AUTHORITY[\"EPSG\",\"9108\"]],\n"); out.write(" AUTHORITY[\"EPSG\",\"4326\"]],\n"); out.write(" PROJECTION[\"Transverse_Mercator\"],\n"); out.write(" PARAMETER[\"latitude_of_origin\",-0],\n"); out.write(" PARAMETER[\"central_meridian\",33],\n"); out.write(" PARAMETER[\"scale_factor\",0.9996],\n"); out.write(" PARAMETER[\"false_easting\",500000],\n"); out.write(" PARAMETER[\"false_northing\",0]]\n"); } else if (haveRPC || (segment1.getImageCoordinatesRepresentation() == ImageCoordinatesRepresentation.NONE)) { out.write("Coordinate System is `'\n"); } else { out.write("Coordinate System is:\n"); out.write("GEOGCS[\"WGS 84\",\n"); out.write(" DATUM[\"WGS_1984\",\n"); out.write(" SPHEROID[\"WGS 84\",6378137,298.257223563,\n"); out.write(" AUTHORITY[\"EPSG\",\"7030\"]],\n"); out.write(" TOWGS84[0,0,0,0,0,0,0],\n"); out.write(" AUTHORITY[\"EPSG\",\"6326\"]],\n"); out.write(" PRIMEM[\"Greenwich\",0,\n"); out.write(" AUTHORITY[\"EPSG\",\"8901\"]],\n"); out.write(" UNIT[\"degree\",0.0174532925199433,\n"); out.write(" AUTHORITY[\"EPSG\",\"9108\"]],\n"); out.write(" AUTHORITY[\"EPSG\",\"4326\"]]\n"); } } private void outputBaseMetadata() throws IOException, ParseException { TreeMap <String, String> metadata = new TreeMap<String, String>(); metadata.put("NITF_CLEVEL", String.format("%02d", nitf.getComplexityLevel())); metadata.put("NITF_ENCRYP", "0"); switch (nitf.getFileType()) { case NSIF_ONE_ZERO: metadata.put("NITF_FHDR", "NSIF01.00"); break; case NITF_TWO_ZERO: metadata.put("NITF_FHDR", "NITF02.00"); break; case NITF_TWO_ONE: metadata.put("NITF_FHDR", "NITF02.10"); break; } metadata.put("NITF_FSCAUT", nitf.getFileSecurityMetadata().getClassificationAuthority()); metadata.put("NITF_FSCLAS", nitf.getFileSecurityMetadata().getSecurityClassification().getTextEquivalent()); metadata.put("NITF_FSCODE", nitf.getFileSecurityMetadata().getCodewords()); metadata.put("NITF_FSCTLH", nitf.getFileSecurityMetadata().getControlAndHandling()); metadata.put("NITF_FSCTLN", nitf.getFileSecurityMetadata().getSecurityControlNumber()); metadata.put("NITF_FSREL", nitf.getFileSecurityMetadata().getReleaseInstructions()); if (nitf.getFileType() == FileType.NITF_TWO_ZERO) { metadata.put("NITF_FDT", new SimpleDateFormat("ddHHmmss'Z'MMMyy").format(nitf.getFileDateTime()).toString().toUpperCase()); metadata.put("NITF_FSDWNG", nitf.getFileSecurityMetadata().getDowngradeDateOrSpecialCase().trim()); if (nitf.getFileSecurityMetadata().getDowngradeEvent() != null) { metadata.put("NITF_FSDEVT", nitf.getFileSecurityMetadata().getDowngradeEvent()); } } else { metadata.put("NITF_FBKGC", (String.format("%3d,%3d,%3d", (int)(nitf.getFileBackgroundColour().getRed() & 0xFF), (int)(nitf.getFileBackgroundColour().getGreen() & 0xFF), (int)(nitf.getFileBackgroundColour().getBlue() & 0xFF)))); metadata.put("NITF_FDT", new SimpleDateFormat("yyyyMMddHHmmss").format(nitf.getFileDateTime())); metadata.put("NITF_FSCATP", nitf.getFileSecurityMetadata().getClassificationAuthorityType()); metadata.put("NITF_FSCLSY", nitf.getFileSecurityMetadata().getSecurityClassificationSystem()); metadata.put("NITF_FSCLTX", nitf.getFileSecurityMetadata().getClassificationText()); metadata.put("NITF_FSCRSN", nitf.getFileSecurityMetadata().getClassificationReason()); metadata.put("NITF_FSDCDT", nitf.getFileSecurityMetadata().getDeclassificationDate()); metadata.put("NITF_FSDCTP", nitf.getFileSecurityMetadata().getDeclassificationType()); if (nitf.getFileSecurityMetadata().getDeclassificationExemption().length() > 0) { metadata.put("NITF_FSDCXM", String.format("%4s", nitf.getFileSecurityMetadata().getDeclassificationExemption())); } else { metadata.put("NITF_FSDCXM", ""); } metadata.put("NITF_FSDG", nitf.getFileSecurityMetadata().getDowngrade()); metadata.put("NITF_FSDGDT", nitf.getFileSecurityMetadata().getDowngradeDate()); metadata.put("NITF_FSSRDT", nitf.getFileSecurityMetadata().getSecuritySourceDate()); } metadata.put("NITF_FSCOP", nitf.getFileSecurityMetadata().getFileCopyNumber()); metadata.put("NITF_FSCPYS", nitf.getFileSecurityMetadata().getFileNumberOfCopies()); metadata.put("NITF_FTITLE", nitf.getFileTitle()); metadata.put("NITF_ONAME", nitf.getOriginatorsName()); metadata.put("NITF_OPHONE", nitf.getOriginatorsPhoneNumber()); metadata.put("NITF_OSTAID", nitf.getOriginatingStationId()); metadata.put("NITF_STYPE", nitf.getStandardType()); TreCollection treCollection = nitf.getTREsRawStructure(); addOldStyleMetadata(metadata, treCollection); if (segment1 != null) { addFirstSegmentMetadata(metadata); } out.write("Metadata:\n"); for (String key : metadata.keySet()) { out.write(String.format(" %s=%s\n", key, metadata.get(key))); } } private void addFirstSegmentMetadata(TreeMap <String, String> metadata) throws IOException, ParseException { RasterProductFormatUtilities rpfUtils = new RasterProductFormatUtilities(); metadata.put("NITF_ABPP", String.format("%02d", segment1.getActualBitsPerPixelPerBand())); metadata.put("NITF_CCS_COLUMN", String.format("%d", segment1.getImageLocationColumn())); metadata.put("NITF_CCS_ROW", String.format("%d", segment1.getImageLocationRow())); metadata.put("NITF_IALVL", String.format("%d", segment1.getImageAttachmentLevel())); metadata.put("NITF_IC", segment1.getImageCompression().getTextEquivalent()); metadata.put("NITF_ICAT", segment1.getImageCategory().getTextEquivalent()); if (nitf.getFileType() == FileType.NITF_TWO_ZERO) { metadata.put("NITF_IDATIM", new SimpleDateFormat("ddHHmmss'Z'MMMyy").format(segment1.getImageDateTime()).toString().toUpperCase()); metadata.put("NITF_ICORDS", segment1.getImageCoordinatesRepresentation().getTextEquivalent(nitf.getFileType())); } else { metadata.put("NITF_IDATIM", new SimpleDateFormat("yyyyMMddHHmmss").format(segment1.getImageDateTime())); if (segment1.getImageCoordinatesRepresentation() == ImageCoordinatesRepresentation.NONE) { metadata.put("NITF_ICORDS", ""); } else { metadata.put("NITF_ICORDS", segment1.getImageCoordinatesRepresentation().getTextEquivalent(nitf.getFileType())); } } metadata.put("NITF_IDLVL", String.format("%d", segment1.getImageDisplayLevel())); if (segment1.getImageCoordinatesRepresentation() != ImageCoordinatesRepresentation.NONE) { metadata.put("NITF_IGEOLO", String.format("%s%s%s%s", segment1.getImageCoordinates().getCoordinate00().getSourceFormat(), segment1.getImageCoordinates().getCoordinate0MaxCol().getSourceFormat(), segment1.getImageCoordinates().getCoordinateMaxRowMaxCol().getSourceFormat(), segment1.getImageCoordinates().getCoordinateMaxRow0().getSourceFormat())); } metadata.put("NITF_IID1", segment1.getImageIdentifier1()); if (nitf.getFileType() == FileType.NITF_TWO_ZERO) { metadata.put("NITF_ITITLE", segment1.getImageIdentifier2()); } else { metadata.put("NITF_IID2", segment1.getImageIdentifier2()); } String rpfAbbreviation = rpfUtils.getAbbreviationForFileName(segment1.getImageIdentifier2()); if (rpfAbbreviation != null) { metadata.put("NITF_SERIES_ABBREVIATION", rpfAbbreviation); } String rpfName = rpfUtils.getNameForFileName(segment1.getImageIdentifier2()); if (rpfName != null) { metadata.put("NITF_SERIES_NAME", rpfName); } metadata.put("NITF_ILOC_COLUMN", String.format("%d", segment1.getImageLocationColumn())); metadata.put("NITF_ILOC_ROW", String.format("%d", segment1.getImageLocationRow())); metadata.put("NITF_IMAG", segment1.getImageMagnification()); if (segment1.getNumberOfImageComments() > 0) { StringBuilder commentBuilder = new StringBuilder(); for (int i = 0; i < segment1.getNumberOfImageComments(); ++i) { commentBuilder.append(String.format("%-80s", segment1.getImageCommentZeroBase(i))); } metadata.put("NITF_IMAGE_COMMENTS", commentBuilder.toString()); } metadata.put("NITF_IMODE", segment1.getImageMode().getTextEquivalent()); metadata.put("NITF_IREP", segment1.getImageRepresentation().getTextEquivalent()); metadata.put("NITF_ISCAUT", segment1.getSecurityMetadata().getClassificationAuthority()); metadata.put("NITF_ISCLAS", segment1.getSecurityMetadata().getSecurityClassification().getTextEquivalent()); metadata.put("NITF_ISCODE", segment1.getSecurityMetadata().getCodewords()); metadata.put("NITF_ISCTLH", segment1.getSecurityMetadata().getControlAndHandling()); metadata.put("NITF_ISCTLN", segment1.getSecurityMetadata().getSecurityControlNumber()); if (nitf.getFileType() == FileType.NITF_TWO_ZERO) { metadata.put("NITF_ISDWNG", segment1.getSecurityMetadata().getDowngradeDateOrSpecialCase().trim()); if (segment1.getSecurityMetadata().getDowngradeEvent() != null) { metadata.put("NITF_ISDEVT", segment1.getSecurityMetadata().getDowngradeEvent()); } } else { metadata.put("NITF_ISCATP", segment1.getSecurityMetadata().getClassificationAuthorityType()); metadata.put("NITF_ISCLSY", segment1.getSecurityMetadata().getSecurityClassificationSystem()); metadata.put("NITF_ISCLTX", segment1.getSecurityMetadata().getClassificationText()); metadata.put("NITF_ISDCDT", segment1.getSecurityMetadata().getDeclassificationDate()); metadata.put("NITF_ISDCTP", segment1.getSecurityMetadata().getDeclassificationType()); metadata.put("NITF_ISCRSN", segment1.getSecurityMetadata().getClassificationReason()); if ((segment1.getSecurityMetadata().getDeclassificationExemption() != null) && (segment1.getSecurityMetadata().getDeclassificationExemption().length() > 0)) { metadata.put("NITF_ISDCXM", String.format("%4s", segment1.getSecurityMetadata().getDeclassificationExemption())); } else { metadata.put("NITF_ISDCXM", ""); } metadata.put("NITF_ISDG", segment1.getSecurityMetadata().getDowngrade()); metadata.put("NITF_ISDGDT", segment1.getSecurityMetadata().getDowngradeDate()); metadata.put("NITF_ISSRDT", segment1.getSecurityMetadata().getSecuritySourceDate()); } metadata.put("NITF_ISORCE", segment1.getImageSource()); metadata.put("NITF_ISREL", segment1.getSecurityMetadata().getReleaseInstructions()); metadata.put("NITF_PJUST", segment1.getPixelJustification().getTextEquivalent()); metadata.put("NITF_PVTYPE", segment1.getPixelValueType().getTextEquivalent()); if (segment1.getImageTargetId().length() > 0) { metadata.put("NITF_TGTID", segment1.getImageTargetId()); } else { metadata.put("NITF_TGTID", ""); } addOldStyleMetadata(metadata, segment1.getTREsRawStructure()); } private void outputImageStructure() throws IOException { if (segment1 != null) { switch (segment1.getImageCompression()) { case JPEG: case JPEGMASK: out.write("Image Structure Metadata:\n"); out.write(" COMPRESSION=JPEG\n"); break; case BILEVEL: case BILEVELMASK: case DOWNSAMPLEDJPEG: out.write("Image Structure Metadata:\n"); out.write(" COMPRESSION=BILEVEL\n"); break; case LOSSLESSJPEG: out.write("Image Structure Metadata:\n"); out.write(" COMPRESSION=LOSSLESS JPEG\n"); break; case JPEG2000: case JPEG2000MASK: out.write("Image Structure Metadata:\n"); out.write(" COMPRESSION=JPEG2000\n"); break; case VECTORQUANTIZATION: case VECTORQUANTIZATIONMASK: out.write("Image Structure Metadata:\n"); out.write(" COMPRESSION=VECTOR QUANTIZATION\n"); break; } } } private void outputSubdatasets() throws IOException { if (nitf.getNumberOfImageSegments() > 1) { out.write("Subdatasets:\n"); for (int i = 0; i < nitf.getNumberOfImageSegments(); ++i) { out.write(String.format(" SUBDATASET_%d_NAME=NITF_IM:%d:%s\n", i+1, i, filename)); out.write(String.format(" SUBDATASET_%d_DESC=Image %d of %s\n", i+1, i+1, filename)); } } } private void outputTRExml() throws IOException { if ((nitf.getTREsRawStructure().hasTREs()) || ((segment1 != null) && (segment1.getTREsRawStructure().hasTREs())) || ((des1 != null) && (des1.getTREsRawStructure().hasTREs()))) { out.write("Metadata (xml:TRE):\n"); out.write("<tres>\n"); TreCollection treCollection = nitf.getTREsRawStructure(); for (Tre tre : treCollection.getTREs()) { outputThisTre(out, tre, "file"); } if (segment1 != null) { treCollection = segment1.getTREsRawStructure(); for (Tre tre : treCollection.getTREs()) { outputThisTre(out, tre, "image"); } } if (des1 != null) { treCollection = des1.getTREsRawStructure(); for (Tre tre : treCollection.getTREs()) { outputThisTre(out, tre, "des TRE_OVERFLOW"); } } out.write("</tres>\n\n"); } } private void outputRPCs() throws IOException { TreeMap <String, String> rpc = new TreeMap<String, String>(); if (segment1 != null) { // Walk the segment1 TRE collection and add RPC entries here TreCollection treCollection = segment1.getTREsRawStructure(); for (Tre tre : treCollection.getTREs()) { if (tre.getName().equals("RPC00B")) { for (TreEntry entry : tre.getEntries()) { if (entry.getName().equals("SUCCESS")) { continue; } if (entry.getName().equals("ERR_BIAS") || entry.getName().equals("ERR_RAND")) { continue; } if (entry.getFieldValue() != null) { if (entry.getName().equals("LONG_OFF") || entry.getName().equals("LONG_SCALE") || entry.getName().equals("LAT_OFF") || entry.getName().equals("LAT_SCALE")) { // skip this, we're filtering it out for both cases } else { Integer rpcValue = Integer.parseInt(entry.getFieldValue()); rpc.put(entry.getName(), rpcValue.toString()); } } else if ((entry.getGroups() != null) && (entry.getGroups().size() > 0)) { StringBuilder builder = new StringBuilder(); for (TreGroup group : entry.getGroups()) { for (TreEntry groupEntry : group.getEntries()) { try { double fieldVal = Double.parseDouble(groupEntry.getFieldValue()); builder.append(cleanupNumberString(fieldVal)); builder.append(" "); } catch (NumberFormatException e) { builder.append(String.format("%s ", groupEntry.getFieldValue())); } } } // These are too sensitive to number formatting issues, and we're already checking // the value in the real TRE. // rpc.put(entry.getName(), builder.toString()); } } try { double longOff = Double.parseDouble(tre.getFieldValue("LONG_OFF")); double longScale = Double.parseDouble(tre.getFieldValue("LONG_SCALE")); double longMin = longOff - (longScale / 2.0); double longMax = longOff + (longScale / 2.0); rpc.put("MAX_LONG", cleanupNumberString(longMax)); rpc.put("MIN_LONG", cleanupNumberString(longMin)); double latOff = Double.parseDouble(tre.getFieldValue("LAT_OFF")); double latScale = Double.parseDouble(tre.getFieldValue("LAT_SCALE")); double latMin = latOff - (latScale / 2.0); double latMax = latOff + (latScale / 2.0); rpc.put("MAX_LAT", cleanupNumberString(latMax)); rpc.put("MIN_LAT", cleanupNumberString(latMin)); } catch (ParseException e) { e.printStackTrace(); } } } } if (rpc.keySet().size() > 0) { out.write("RPC Metadata:\n"); for (String tagname : rpc.keySet()) { out.write(String.format(" %s=%s\n", tagname, rpc.get(tagname))); } } } static private String cleanupNumberString(double fieldVal) { if (fieldVal == (int)fieldVal) { return String.format("%d", (int)fieldVal); } String naiveString = String.format("%.12g", fieldVal); if (naiveString.contains("e-")) { return naiveString.replaceAll("\\.?0*e", "e"); } else if (naiveString.contains(".")) { return naiveString.replaceAll("\\.?0*$", ""); } return naiveString; } private static void addOldStyleMetadata(TreeMap <String, String> metadata, TreCollection treCollection) { for (Tre tre : treCollection.getTREs()) { if (tre.getPrefix() != null) { // if it has a prefix, its probably an old-style NITF metadata field List<TreEntry> entries = tre.getEntries(); for (TreEntry entry: entries) { metadata.put(tre.getPrefix() + entry.getName(), rightTrim(entry.getFieldValue())); } } else if ("ICHIPB".equals(tre.getName())) { // special case List<TreEntry> entries = tre.getEntries(); for (TreEntry entry: entries) { if ("XFRM_FLAG".equals(entry.getName())) { // GDAL skips this one continue; } BigDecimal value = new BigDecimal(entry.getFieldValue().trim()).stripTrailingZeros(); if ("ANAMRPH_CORR".equals(entry.getName())) { // Special case for GDAL metadata.put("ICHIP_ANAMORPH_CORR", value.toPlainString()); } else { metadata.put("ICHIP_" + entry.getName(), value.toPlainString()); } } } } } private static void outputThisTre(BufferedWriter out, Tre tre, String location) throws IOException { doIndent(out, 1); out.write("<tre name=\"" + tre.getName().trim() + "\" location=\"" + location + "\">\n"); for (TreEntry entry : tre.getEntries()) { outputThisEntry(out, entry, 2); } doIndent(out, 1); out.write("</tre>\n"); } private static void outputThisEntry(BufferedWriter out, TreEntry entry, int indentLevel) throws IOException { if (entry.getFieldValue() != null) { doIndent(out, indentLevel); out.write("<field name=\"" + entry.getName() + "\" value=\"" + rightTrim(entry.getFieldValue()) + "\" />\n"); } if ((entry.getGroups() != null) && (entry.getGroups().size() > 0)) { doIndent(out, indentLevel); out.write("<repeated name=\"" + entry.getName() + "\" number=\"" + entry.getGroups().size() + "\">\n"); int i = 0; for (TreGroup group : entry.getGroups()) { doIndent(out, indentLevel + 1); out.write(String.format("<group index=\"%d\">\n", i)); for (TreEntry groupEntry : group.getEntries()) { outputThisEntry(out, groupEntry, indentLevel + 2); } doIndent(out, indentLevel + 1); out.write(String.format("</group>\n")); i = i + 1; } doIndent(out, indentLevel); out.write("</repeated>\n"); } } private static String rightTrim(final String s) { int i = s.length() - 1; while ((i >= 0) && Character.isWhitespace(s.charAt(i))) { i } return s.substring(0, i + 1); } private static void doIndent(BufferedWriter out, int indentLevel) throws IOException { for (int i = 0; i < indentLevel; ++i) { out.write(" "); } } // This is ugly - feel free to fix it any time. private static String makeGeoString(ImageCoordinatePair coords) { double latitude = coords.getLatitude(); double longitude = coords.getLongitude(); String northSouth = "N"; if (latitude < 0.0) { northSouth = "S"; latitude = Math.abs(latitude); } String eastWest = "E"; if (longitude < 0.0) { eastWest = "W"; longitude = Math.abs(longitude); } int latDegrees = (int)Math.floor(latitude); double minutesAndSecondsPart = (latitude -latDegrees) * 60; int latMinutes = (int)Math.floor(minutesAndSecondsPart); double secondsPart = (minutesAndSecondsPart - latMinutes) * 60; int latSeconds = (int)Math.round(secondsPart); if (latSeconds == 60) { latMinutes++; latSeconds = 0; } if (latMinutes == 60) { latDegrees++; latMinutes = 0; } int lonDegrees = (int)Math.floor(longitude); minutesAndSecondsPart = (longitude - lonDegrees) * 60; int lonMinutes = (int)Math.floor(minutesAndSecondsPart); secondsPart = (minutesAndSecondsPart - lonMinutes) * 60; int lonSeconds = (int)Math.round(secondsPart); if (lonSeconds == 60) { lonMinutes++; lonSeconds = 0; } if (lonMinutes == 60) { lonDegrees++; lonMinutes = 0; } return String.format("%02d%02d%02d%s%03d%02d%02d%s", latDegrees, latMinutes, latSeconds, northSouth, lonDegrees, lonMinutes, lonSeconds, eastWest); } private void generateGdalMetadata() { try { ProcessBuilder processBuilder = new ProcessBuilder("gdalinfo", "-nogcp", "-mdd", "xml:TRE", filename); processBuilder.environment().put("NITF_OPEN_UNDERLYING_DS", "NO"); Process process = processBuilder.start(); BufferedWriter out = null; try { FileWriter fstream = new FileWriter(filename + THEIR_OUTPUT_EXTENSION); out = new BufferedWriter(fstream); } catch (IOException e) { e.printStackTrace(); } BufferedReader infoOutputReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"), 1000000); boolean done = false; try { do { do { String line = infoOutputReader.readLine(); if (line == null) { done = true; break; } if (line.startsWith("Origin = (")) { // System.out.println("Filtering on Origin"); continue; } if (line.startsWith("Pixel Size = (")) { // System.out.println("Filtering on Pixel Size"); continue; } if (line.startsWith(" LINE_DEN_COEFF=") || line.startsWith(" LINE_NUM_COEFF=") || line.startsWith(" SAMP_DEN_COEFF=") || line.startsWith(" SAMP_NUM_COEFF=")) { // System.out.println("Filtering out RPC coefficients"); continue; } if (line.startsWith(" LAT_SCALE=") || line.startsWith(" LONG_SCALE=") || line.startsWith(" LAT_OFF=") || line.startsWith(" LONG_OFF=")) { // System.out.println("Filtering out RPC coefficients"); continue; } if (line.startsWith("Corner Coordinates:")) { // System.out.println("Exiting on Corner Coordinates"); done = true; break; } if (line.startsWith("Band 1 Block=")) { // System.out.println("Exiting on Band 1 Block"); done = true; break; } out.write(line + "\n"); } while (infoOutputReader.ready() && (!done)); Thread.sleep(100); } while (!done); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } out.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void compareMetadataFiles() { List<String> theirs = fileToLines(filename + THEIR_OUTPUT_EXTENSION); List<String> ours = fileToLines(filename + OUR_OUTPUT_EXTENSION); Patch patch = DiffUtils.diff(theirs, ours); if (patch.getDeltas().size() > 0) { for (Delta delta: patch.getDeltas()) { System.out.println(delta); } System.out.println(" * Done"); } else { new File(filename + THEIR_OUTPUT_EXTENSION).delete(); new File(filename + OUR_OUTPUT_EXTENSION).delete(); } } private static List<String> fileToLines(String filename) { List<String> lines = new LinkedList<String>(); String line = ""; try { BufferedReader in = new BufferedReader(new FileReader(filename)); while ((line = in.readLine()) != null) { lines.add(line); } } catch (IOException e) { e.printStackTrace(); } return lines; } }
package com.rultor.agents; import co.stateful.Locks; import co.stateful.Sttc; import com.jcabi.aspects.Immutable; import com.jcabi.github.Github; import com.jcabi.immutable.Array; import com.jcabi.manifests.Manifests; import com.jcabi.s3.Region; import com.jcabi.s3.retry.ReRegion; import com.rultor.agents.daemons.ArchivesDaemon; import com.rultor.agents.daemons.EndsDaemon; import com.rultor.agents.daemons.KillsDaemon; import com.rultor.agents.daemons.StartsDaemon; import com.rultor.agents.daemons.StopsDaemon; import com.rultor.agents.github.CommentsTag; import com.rultor.agents.github.Question; import com.rultor.agents.github.ReleaseBinaries; import com.rultor.agents.github.Reports; import com.rultor.agents.github.Stars; import com.rultor.agents.github.StartsTalks; import com.rultor.agents.github.Understands; import com.rultor.agents.github.UnlocksRepo; import com.rultor.agents.github.qtn.QnAlone; import com.rultor.agents.github.qtn.QnAskedBy; import com.rultor.agents.github.qtn.QnByArchitect; import com.rultor.agents.github.qtn.QnConfig; import com.rultor.agents.github.qtn.QnDeploy; import com.rultor.agents.github.qtn.QnFollow; import com.rultor.agents.github.qtn.QnHello; import com.rultor.agents.github.qtn.QnIfCollaborator; import com.rultor.agents.github.qtn.QnIfContains; import com.rultor.agents.github.qtn.QnMerge; import com.rultor.agents.github.qtn.QnNotSelf; import com.rultor.agents.github.qtn.QnParametrized; import com.rultor.agents.github.qtn.QnReferredTo; import com.rultor.agents.github.qtn.QnRelease; import com.rultor.agents.github.qtn.QnSince; import com.rultor.agents.github.qtn.QnStatus; import com.rultor.agents.github.qtn.QnStop; import com.rultor.agents.github.qtn.QnVersion; import com.rultor.agents.req.EndsRequest; import com.rultor.agents.req.StartsRequest; import com.rultor.agents.shells.RegistersShell; import com.rultor.agents.shells.RemovesShell; import com.rultor.agents.twitter.OAuthTwitter; import com.rultor.agents.twitter.Tweets; import com.rultor.spi.Agent; import com.rultor.spi.Profile; import com.rultor.spi.SuperAgent; import com.rultor.spi.Talk; import java.io.IOException; import java.util.concurrent.TimeUnit; import lombok.EqualsAndHashCode; import lombok.ToString; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.CharEncoding; /** * Agents. * * @author Yegor Bugayenko (yegor@tpc2.com) * @version $Id$ * @since 1.0 * @checkstyle ClassDataAbstractionCouplingCheck (500 lines) * @checkstyle ClassFanOutComplexityCheck (500 lines) * @checkstyle MultipleStringLiteralsCheck (500 lines) */ @Immutable @ToString @EqualsAndHashCode(of = { "github", "sttc" }) @SuppressWarnings("PMD.ExcessiveImports") public final class Agents { /** * Github client. */ private final transient Github github; /** * Sttc client. */ private final transient Sttc sttc; /** * Ctor. * @param ghub Github client * @param stc Sttc client */ public Agents(final Github ghub, final Sttc stc) { this.github = ghub; this.sttc = stc; } /** * Create super agent, starter. * @return The starter */ public SuperAgent starter() { return new SuperAgent.Iterative( new Array<>( new StartsTalks(this.github), new IndexesRequests() ) ); } /** * Create super agent, closer. * @return The closer * @throws IOException If fails */ public SuperAgent closer() throws IOException { return new SuperAgent.Iterative( new Array<>( new UnlocksRepo(this.sttc.locks(), this.github), new DeactivatesTalks() ) ); } /** * Create it for a talk. * @param talk Talk itself * @param profile Profile * @return The agent * @throws IOException If fails */ public Agent agent(final Talk talk, final Profile profile) throws IOException { final Locks locks = this.sttc.locks(); final Question question = new QnSince( // @checkstyle MagicNumber (1 line) 49092213, new QnNotSelf( new QnReferredTo( this.github.users().self().login(), new QnParametrized( new Question.FirstOf( new Array<>( new QnIfContains( "config", new QnConfig(profile) ), new QnIfContains("status", new QnStatus(talk)), new QnIfContains("version", new QnVersion()), new QnIfContains("hello", new QnHello()), new QnIfContains( "stop", new QnAskedBy( profile, Agents.commanders("stop"), new QnStop() ) ), new QnFollow( new QnIfCollaborator( new QnAlone( talk, locks, this.commands(profile) ) ) ) ) ) ) ) ) ); return new Agent.Iterative( new Array<Agent>( new Understands(this.github, question), new StartsRequest(profile), new RegistersShell( profile, // @checkstyle MagicNumber (1 line) "b3.rultor.com", 22, "rultor", IOUtils.toString( this.getClass().getResourceAsStream("rultor.key"), CharEncoding.UTF_8 ) ), new StartsDaemon(profile), new KillsDaemon(TimeUnit.HOURS.toMinutes(2L)), new StopsDaemon(), new EndsDaemon(), new EndsRequest(), new Tweets( this.github, new OAuthTwitter( Manifests.read("Rultor-TwitterKey"), Manifests.read("Rultor-TwitterSecret"), Manifests.read("Rultor-TwitterToken"), Manifests.read("Rultor-TwitterTokenSecret") ) ), new CommentsTag(this.github), new ReleaseBinaries(this.github, profile), new Reports(this.github), new RemovesShell(), new ArchivesDaemon( new ReRegion( new Region.Simple( Manifests.read("Rultor-S3Key"), Manifests.read("Rultor-S3Secret") ) ).bucket(Manifests.read("Rultor-S3Bucket")) ), new Publishes(profile), new Stars(this.github) ) ); } /** * Handle main commands. * @param profile Profile to uuse * @return Array of questions. */ private Question commands(final Profile profile) { return new QnByArchitect( profile, "/p/entry[@key='architect']/item/text()", new Question.FirstOf( new Array<Question>( new QnIfContains( "merge", new QnAskedBy( profile, Agents.commanders("merge"), new QnMerge() ) ), new QnIfContains( "deploy", new QnAskedBy( profile, Agents.commanders("deploy"), new QnDeploy() ) ), new QnIfContains( "release", new QnAskedBy( profile, Agents.commanders("release"), new QnRelease() ) ) ) ) ); } /** * XPath for commanders. * @param entry Entry * @return XPath */ private static String commanders(final String entry) { return String.format( "/p/entry[@key='%s']/entry[@key='commanders']/item/text()", entry ); } }
package org.cojen.tupl.rows; import java.io.IOException; import java.lang.invoke.VarHandle; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.function.Consumer; import java.util.function.Supplier; import org.cojen.tupl.CorruptDatabaseException; import org.cojen.tupl.Cursor; import org.cojen.tupl.DurabilityMode; import org.cojen.tupl.EventListener; import org.cojen.tupl.EventType; import org.cojen.tupl.Index; import org.cojen.tupl.LockFailureException; import org.cojen.tupl.LockMode; import org.cojen.tupl.Table; import org.cojen.tupl.Transaction; import org.cojen.tupl.UniqueConstraintException; import org.cojen.tupl.View; import org.cojen.tupl.core.CoreDatabase; import org.cojen.tupl.core.LHashTable; import org.cojen.tupl.core.RowPredicateLock; import org.cojen.tupl.core.ScanVisitor; import org.cojen.tupl.util.Runner; import static org.cojen.tupl.rows.RowUtils.*; /** * Main class for managing row persistence via tables. * * @author Brian S O'Neill */ public class RowStore { private final WeakReference<RowStore> mSelfRef; final CoreDatabase mDatabase; /* Schema metadata for all types. (indexId) -> int current schemaVersion, ColumnSet[] alternateKeys, (a type of secondary index) ColumnSet[] secondaryIndexes (indexId, schemaVersion) -> primary ColumnSet (indexId, hash(primary ColumnSet)) -> schemaVersion[] // hash collision chain (indexId, 0, K_SECONDARY, descriptor) -> secondaryIndexId, state (indexId, 0, K_TYPE_NAME) -> current type name (UTF-8) (secondaryIndexId, 0, K_DROPPED) -> primaryIndexId, descriptor (0L, indexId, taskType) -> ... workflow task against an index The schemaVersion is limited to 2^31, and the hash is encoded with bit 31 set, preventing collisions. In addition, schemaVersion cannot be 0, and so the extended keys won't collide, although the longer overall key length prevents collisions as well. Because indexId 0 is reserved (for the registry), it won't be used for row storage, and so it can be used for tracking workflow tasks. */ private final Index mSchemata; private final WeakCache<Index, TableManager<?>> mTableManagers; private final LHashTable.Obj<RowPredicateLock<?>> mIndexLocks; // Extended key for referencing secondary indexes. private static final int K_SECONDARY = 1; // Extended key to store the fully qualified type name. private static final int K_TYPE_NAME = 2; // Extended key to track secondary indexes which are being dropped. private static final int K_DROPPED = 3; private static final int TASK_DELETE_SCHEMA = 1, TASK_NOTIFY_SCHEMA = 2; public RowStore(CoreDatabase db, Index schemata) throws IOException { mSelfRef = new WeakReference<>(this); mDatabase = db; mSchemata = schemata; mTableManagers = new WeakCache<>(); mIndexLocks = new LHashTable.Obj<>(8); registerToUpdateSchemata(); // Finish any tasks left over from when the RowStore was last used. finishAllWorkflowTasks(); } WeakReference<RowStore> ref() { return mSelfRef; } public Index schemata() { return mSchemata; } /** * Scans the schemata and all table secondary indexes. Doesn't scan table primary indexes. */ public void scanAllIndexes(ScanVisitor visitor) throws IOException { visitor.apply(mSchemata); try (Cursor c = mSchemata.newCursor(null)) { byte[] key; for (c.first(); (key = c.key()) != null; ) { if (key.length <= 8) { c.next(); continue; } long indexId = decodeLongBE(key, 0); if (indexId == 0 || decodeIntBE(key, 8) != 0 || decodeIntBE(key, 8 + 4) != K_SECONDARY) { if (++indexId == 0) { break; } c.findNearbyGe(key(indexId)); } else { Index secondaryIndex = mDatabase.indexById(decodeLongLE(c.value(), 0)); if (secondaryIndex != null) { visitor.apply(secondaryIndex); } c.next(); } } } } /** * Try to find a table which is bound to the given index, and return a partially decoded * row. Returns null if not found. */ public Object asRow(Index ix, byte[] key) { var manager = (TableManager<?>) mTableManagers.get(ix); if (manager != null) { AbstractTable<?> table = manager.mostRecentTable(); if (table != null) { try { return table.asRow(key); } catch (Throwable e) { // Ignore any decoding errors. } } } return null; } private TableManager<?> tableManager(Index ix) { var manager = (TableManager<?>) mTableManagers.get(ix); if (manager == null) { synchronized (mTableManagers) { manager = (TableManager<?>) mTableManagers.get(ix); if (manager == null) { manager = new TableManager<>(ix); mTableManagers.put(ix, manager); } } } return manager; } /** * @return null if predicate lock is unsupported */ <R> RowPredicateLock<R> indexLock(Index index) { return indexLock(index.id()); } /** * @return null if predicate lock is unsupported */ @SuppressWarnings("unchecked") <R> RowPredicateLock<R> indexLock(long indexId) { var lock = mIndexLocks.getValue(indexId); if (lock == null) { lock = makeIndexLock(indexId); } return (RowPredicateLock<R>) lock; } private RowPredicateLock<?> makeIndexLock(long indexId) { synchronized (mIndexLocks) { var lock = mIndexLocks.getValue(indexId); if (lock == null) { lock = mDatabase.newRowPredicateLock(indexId); VarHandle.storeStoreFence(); mIndexLocks.insert(indexId).value = lock; } return lock; } } private void removeIndexLock(long indexId) { synchronized (mIndexLocks) { mIndexLocks.remove(indexId); } } @SuppressWarnings("unchecked") public <R> Table<R> asTable(Index ix, Class<R> type) throws IOException { return ((TableManager<R>) tableManager(ix)).asTable(this, ix, type); } /** * Called by TableManager via asTable. * * @param doubleCheck invoked with schema lock held, to double check before making the table * @param consumer called with lock held, to accept the newly made table */ @SuppressWarnings("unchecked") <R> AbstractTable<R> makeTable(TableManager<R> manager, Index ix, Class<R> type, Supplier<AbstractTable<R>> doubleCheck, Consumer<AbstractTable<R>> consumer) throws IOException { // Throws an exception if type is malformed. RowInfo info = RowInfo.find(type); AbstractTable<R> table; // Can use NO_FLUSH because transaction will be only used for reading data. Transaction txn = mSchemata.newTransaction(DurabilityMode.NO_FLUSH); try { txn.lockMode(LockMode.REPEATABLE_READ); // Acquire the lock, but don't check for schema changes just yet. RowInfo currentInfo = decodeExisting(txn, null, ix.id()); if (doubleCheck != null && (table = doubleCheck.get()) != null) { // Found the table, so just use that. return table; } // With a txn lock held, check if the schema has changed incompatibly. if (currentInfo != null) { checkSchema(type.getName(), currentInfo, info); } RowPredicateLock<R> indexLock = indexLock(ix); try { var mh = new TableMaker(this, type, info.rowGen(), ix.id(), indexLock != null).finish(); table = (AbstractTable) mh.invoke(manager, ix, indexLock); } catch (Throwable e) { throw rethrow(e); } if (consumer != null) { consumer.accept(table); } } finally { txn.reset(); } // Attempt to eagerly update schema metadata and secondary indexes. try { // Pass false for notify because examineSecondaries will be invoked by caller. schemaVersion(info, true, ix.id(), false); } catch (IOException e) { // Ignore and try again when storing rows or when the leadership changes. } return table; } private static boolean checkSchema(String typeName, RowInfo oldInfo, RowInfo newInfo) { if (oldInfo.matches(newInfo) && matches(oldInfo.alternateKeys, newInfo.alternateKeys) && matches(oldInfo.secondaryIndexes, newInfo.secondaryIndexes)) { return true; } if (!oldInfo.keyColumns.equals(newInfo.keyColumns)) { // FIXME: Better exception. throw new IllegalStateException("Cannot alter primary key: " + typeName); } // Checks for alternate keys and secondary indexes is much more strict. Any change to // a column used by one is considered incompatible. checkIndexes(typeName, "alternate keys", oldInfo.alternateKeys, newInfo.alternateKeys); checkIndexes(typeName, "secondary indexes", oldInfo.secondaryIndexes, newInfo.secondaryIndexes); return false; } /** * Checks if the set of indexes has changed incompatibly. */ private static void checkIndexes(String typeName, String which, NavigableSet<ColumnSet> oldSet, NavigableSet<ColumnSet> newSet) { // Quick check. if (oldSet.isEmpty() || newSet.isEmpty() || matches(oldSet, newSet)) { return; } // Create mappings keyed by index descriptor, which isn't the most efficient approach, // but it matches how secondaries are persisted. So it's safe and correct. The type // descriptor prefix is fake, but that's okay. This isn't actually persisted. var encoder = new Encoder(64); NavigableMap<byte[], ColumnSet> oldMap = indexMap('_', encoder, oldSet); NavigableMap<byte[], ColumnSet> newMap = indexMap('_', encoder, newSet); Iterator<Map.Entry<byte[], ColumnSet>> oldIt = oldMap.entrySet().iterator(); Iterator<Map.Entry<byte[], ColumnSet>> newIt = newMap.entrySet().iterator(); Map.Entry<byte[], ColumnSet> oldEntry = null, newEntry = null; while (true) { if (oldEntry == null) { if (!oldIt.hasNext()) { break; } oldEntry = oldIt.next(); } if (newEntry == null) { if (!newIt.hasNext()) { break; } newEntry = newIt.next(); } int cmp = Arrays.compareUnsigned(oldEntry.getKey(), newEntry.getKey()); if (cmp == 0) { // Same descriptor, so check if the index has changed. if (!oldEntry.getValue().matches(newEntry.getValue())) { // FIXME: Better exception. throw new IllegalStateException("Cannot alter " + which + ": " + typeName); } oldEntry = null; newEntry = null; } else if (cmp < 0) { // This index will be dropped, so not an incompatibility. oldEntry = null; } else { // This index will be added, so not an incompatibility. newEntry = null; } } } private static boolean matches(NavigableSet<ColumnSet> a, NavigableSet<ColumnSet> b) { var ia = a.iterator(); var ib = b.iterator(); while (ia.hasNext()) { if (!ib.hasNext() || !ia.next().matches(ib.next())) { return false; } } return !ib.hasNext(); } private static NavigableMap<byte[], ColumnSet> indexMap(char type, Encoder encoder, NavigableSet<ColumnSet> set) { var map = new TreeMap<byte[], ColumnSet>(Arrays::compareUnsigned); for (ColumnSet cs : set) { map.put(EncodedRowInfo.encodeDescriptor(type, encoder, cs), cs); } return map; } public <R> Table<R> indexTable(AbstractTable<R> primaryTable, boolean alt, String... columns) throws IOException { Object key = ArrayKey.make(alt, columns); WeakCache<Object, AbstractTable<R>> indexTables = primaryTable.mTableManager.indexTables(); AbstractTable<R> table = indexTables.get(key); if (table == null) { synchronized (indexTables) { table = indexTables.get(key); if (table == null) { table = makeIndexTable(indexTables, primaryTable, alt, columns); if (table == null) { throw new IllegalStateException ((alt ? "Alternate key" : "Secondary index") + " not found: " + Arrays.toString(columns)); } indexTables.put(key, table); } } } return table; } @SuppressWarnings("unchecked") private <R> AbstractTable<R> makeIndexTable(WeakCache<Object, AbstractTable<R>> indexTables, AbstractTable<R> primaryTable, boolean alt, String... columns) throws IOException { Class<R> rowType = primaryTable.rowType(); RowInfo rowInfo = RowInfo.find(rowType); ColumnSet cs = rowInfo.examineIndex(null, columns, alt); if (cs == null) { throw new IllegalStateException ((alt ? "Alternate key" : "Secondary index") + " not found: " + Arrays.toString(columns)); } var encoder = new Encoder(columns.length * 16); char type = alt ? 'A' : 'I'; byte[] search = EncodedRowInfo.encodeDescriptor(type, encoder, cs); View secondariesView = viewExtended(primaryTable.mSource.id(), K_SECONDARY); secondariesView = secondariesView.viewPrefix(new byte[] {(byte) type}, 0); // Identify the first match. Ascending order is encoded with bit 7 clear (see // ColumnInfo), and so matches for ascending order are generally found first when an // unspecified order was given. long indexId; RowInfo indexRowInfo; byte[] descriptor; find: { try (Cursor c = secondariesView.newCursor(null)) { for (c.first(); c.key() != null; c.next()) { if (!descriptorMatches(search, c.key())) { continue; } if (c.value()[8] != 'A') { // Not active. return null; } indexId = decodeLongLE(c.value(), 0); indexRowInfo = indexRowInfo(RowInfo.find(rowType), c.key()); descriptor = c.key(); break find; } } return null; } Object key = ArrayKey.make(descriptor); AbstractTable<R> table = indexTables.get(key); if (table != null) { return table; } Index ix = mDatabase.indexById(indexId); if (ix == null) { return null; } // Indexes don't have indexes. indexRowInfo.alternateKeys = Collections.emptyNavigableSet(); indexRowInfo.secondaryIndexes = Collections.emptyNavigableSet(); RowPredicateLock<R> indexLock = indexLock(ix); try { var maker = new TableMaker(this, rowType, rowInfo.rowGen(), indexRowInfo.rowGen(), descriptor, ix.id(), indexLock != null); var mh = maker.finish(); table = (AbstractTable<R>) mh.invoke(primaryTable.mTableManager, ix, indexLock); } catch (Throwable e) { throw rethrow(e); } indexTables.put(key, table); return table; } /** * Compares descriptors as encoded by EncodedRowInfo.encodeDescriptor. Column types are * ignored except for comparing key column ordering. * * @param search typeCode can be -1 for unspecified orderings * @param found should not have any unspecified orderings */ private static boolean descriptorMatches(byte[] search, byte[] found) { if (search.length != found.length) { return false; } int offset = 1; // skip the type prefix for (int part=1; part<=2; part++) { // part 1 is keys section, part 2 is values section int numColumns = decodePrefixPF(search, offset); if (numColumns != decodePrefixPF(found, offset)) { return false; } offset += lengthPrefixPF(numColumns); for (int i=0; i<numColumns; i++) { if (part == 1) { // Only examine the key column ordering. int searchTypeCode = decodeIntBE(search, offset) ^ (1 << 31); if (searchTypeCode != -1) { // is -1 when unspecified int foundTypeCode = decodeIntBE(found, offset) ^ (1 << 31); if ((searchTypeCode & ColumnInfo.TYPE_DESCENDING) != (foundTypeCode & ColumnInfo.TYPE_DESCENDING)) { // Ordering doesn't match. return false; } } } else { // Ignore value column type codes. } offset += 4; // Now compare the column name. int nameLength = decodePrefixPF(search, offset); if (nameLength != decodePrefixPF(found, offset)) { return false; } if (!Arrays.equals(search, offset, offset + nameLength, found, offset, offset + nameLength)) { return false; } offset += lengthPrefixPF(nameLength); offset += nameLength; } } return offset == search.length; // should always be true unless descriptor is malformed } private void registerToUpdateSchemata() { // The second task is invoked when leadership is lost, which sets things up for when // leadership is acquired again. mDatabase.uponLeader(this::updateSchemata, this::registerToUpdateSchemata); } /** * Called when database has become the leader, providing an opportunity to update the * schema for all tables currently in use. */ private void updateSchemata() { List<TableManager<?>> managers = mTableManagers.copyValues(); if (managers != null) { try { for (var manager : managers) { AbstractTable<?> table = manager.mostRecentTable(); if (table != null) { RowInfo info = RowInfo.find(table.rowType()); long indexId = manager.mPrimaryIndex.id(); schemaVersion(info, true, indexId, true); // notify = true } } } catch (IOException e) { // Ignore and try again when storing rows or when the leadership changes. } catch (Throwable e) { uncaught(e); } } } private void uncaught(Throwable e) { if (!mDatabase.isClosed()) { RowUtils.uncaught(e); } } /** * Called in response to a redo log message. Implementation should examine the set of * secondary indexes associated with the table and perform actions to build or drop them. */ public void notifySchema(long indexId) throws IOException { byte[] taskKey = newTaskKey(TASK_NOTIFY_SCHEMA, indexId); Transaction txn = beginWorkflowTask(taskKey); // Must launch from a separate thread because locks are held by this thread until the // transaction finishes. Runner.start(() -> { try { try { doNotifySchema(null, null, indexId); mSchemata.delete(txn, taskKey); txn.commit(); } finally { txn.reset(); } } catch (Throwable e) { uncaught(e); } }); } /** * @param txn if non-null, pass to mSchemata.delete when false is returned * @param taskKey is non-null if this is a recovered workflow task * @return true if workflow task (if any) can be immediately deleted */ private boolean doNotifySchema(Transaction txn, byte[] taskKey, long indexId) throws IOException { Index ix = mDatabase.indexById(indexId); // Index won't be found if it was concurrently dropped. if (ix != null) { examineSecondaries(tableManager(ix)); } return true; } /** * Called in response to a redo log message. * * @return null or a Lock, or an array of Locks * @see RowPredicateLock#acquireLocksNoPush */ public Object acquireLocksNoPush(Transaction txn, long indexId, byte[] key, byte[] value) throws LockFailureException { return indexLock(indexId).acquireLocksNoPush(txn, key, value); } /** * Called when an index is deleted. If the indexId refers to a known secondary index, then * it gets deleted by the returned Runnable. Otherwise, null is returned and the caller * should perform the delete. * * @param taskFactory returns a task which performs the actual delete */ public Runnable redoDeleteIndex(long indexId, Supplier<Runnable> taskFactory) throws IOException { byte[] value = viewExtended(indexId, K_DROPPED).load(Transaction.BOGUS, EMPTY_BYTES); if (value == null) { return null; } long primaryIndexId = decodeLongLE(value, 0); byte[] descriptor = Arrays.copyOfRange(value, 8, value.length); return deleteIndex(primaryIndexId, indexId, descriptor, null, taskFactory); } /** * Also called from TableManager.asTable. */ <R> void examineSecondaries(TableManager<R> manager) throws IOException { long indexId = manager.mPrimaryIndex.id(); // Can use NO_FLUSH because transaction will be only used for reading data. Transaction txn = mDatabase.newTransaction(DurabilityMode.NO_FLUSH); try { txn.lockTimeout(-1, null); // Lock to prevent changes and to allow one thread to call examineSecondaries. mSchemata.lockUpgradable(txn, key(indexId)); txn.lockMode(LockMode.READ_COMMITTED); manager.update(this, txn, viewExtended(indexId, K_SECONDARY)); } finally { txn.reset(); } } /** * Called by IndexBackfill when an index backfill has finished. */ void activateSecondaryIndex(IndexBackfill backfill, boolean success) throws IOException { long indexId = backfill.mManager.mPrimaryIndex.id(); long secondaryId = backfill.mSecondaryIndex.id(); boolean activated = false; // Use NO_REDO it because this method can be called by a replica. Transaction txn = mDatabase.newTransaction(DurabilityMode.NO_REDO); try { txn.lockTimeout(-1, null); // Lock to prevent changes and to allow one thread to call examineSecondaries. mSchemata.lockUpgradable(txn, key(indexId)); View secondariesView = viewExtended(indexId, K_SECONDARY); if (success) { try (Cursor c = secondariesView.newCursor(txn)) { c.find(backfill.mSecondaryDescriptor); byte[] value = c.value(); if (value != null && value[8] == 'B' && decodeLongLE(value, 0) == secondaryId) { // Switch to "active" state. value[8] = 'A'; c.store(value); activated = true; } } } backfill.mManager.update(this, txn, secondariesView); txn.commit(); } finally { txn.reset(); } if (activated) { // With NO_REDO, need a checkpoint to ensure durability. If the database is closed // before it finishes, the whole backfill process starts over when the database is // later reopened. mDatabase.checkpoint(); } } /** * Should be called when the index is being dropped. Does nothing if index wasn't used for * storing rows. * * This method should be called with the shared commit lock held, and it * non-transactionally stores task metadata which indicates that the schema should be * deleted. The caller should run the returned object without holding the commit lock. * * If no checkpoint occurs, then the expectation is that the deleteSchema method is called * again, which allows the deletion to run again. This means that deleteSchema should * only really be called from removeFromTrash, which automatically runs again if no * checkpoint occurs. * * @param indexKey long index id, big-endian encoded * @return an optional task to run without commit lock held */ public Runnable deleteSchema(byte[] indexKey) throws IOException { try (Cursor c = mSchemata.viewPrefix(indexKey, 0).newCursor(Transaction.BOGUS)) { c.autoload(false); c.first(); if (c.key() == null) { return null; } } byte[] taskKey = newTaskKey(TASK_DELETE_SCHEMA, indexKey); Transaction txn = beginWorkflowTask(taskKey); return () -> { try { try { doDeleteSchema(null, null, indexKey); mSchemata.delete(txn, taskKey); txn.commit(); } finally { txn.reset(); } } catch (IOException e) { throw rethrow(e); } }; } /** * @param txn if non-null, pass to mSchemata.delete when false is returned * @param taskKey is non-null if this is a recovered workflow task * @return true if workflow task (if any) can be immediately deleted */ private boolean doDeleteSchema(Transaction txn, byte[] taskKey, byte[] indexKey) throws IOException { List<Runnable> deleteTasks = null; try (Cursor c = mSchemata.viewPrefix(indexKey, 0).newCursor(Transaction.BOGUS)) { c.autoload(false); byte[] key; for (c.first(); (key = c.key()) != null; c.next()) { if (key.length >= (8 + 4 + 4) && decodeIntBE(key, 8) == 0 && decodeIntBE(key, 8 + 4) == K_SECONDARY) { // Delete a secondary index. c.load(); // autoload is false, so load the value now byte[] value = c.value(); if (value != null && value.length >= 8) { Index secondaryIndex = mDatabase.indexById(decodeLongLE(c.value(), 0)); if (secondaryIndex != null) { long primaryIndexId = decodeLongBE(indexKey, 0); byte[] descriptor = Arrays.copyOfRange(key, 8 + 4 + 4, key.length); Runnable task = deleteIndex (primaryIndexId, 0, descriptor, secondaryIndex, null); if (deleteTasks == null) { deleteTasks = new ArrayList<>(); } deleteTasks.add(task); } } } c.delete(); } } if (deleteTasks == null) { return true; } final var tasks = deleteTasks; Runner.start(() -> { try { try { for (Runnable task : tasks) { task.run(); } mSchemata.delete(txn, taskKey); txn.commit(); } finally { txn.reset(); } } catch (Throwable e) { uncaught(e); } }); return false; } /** * @param indexKey long index id, big-endian encoded */ private byte[] newTaskKey(int taskType, byte[] indexKey) { var taskKey = new byte[8 + 8 + 4]; System.arraycopy(indexKey, 0, taskKey, 8, 8); encodeIntBE(taskKey, 8 + 8, taskType); return taskKey; } private byte[] newTaskKey(int taskType, long indexKey) { var taskKey = new byte[8 + 8 + 4]; encodeLongBE(taskKey, 8, indexKey); encodeIntBE(taskKey, 8 + 8, taskType); return taskKey; } /** * @return a transaction to commit and reset when task is done */ private Transaction beginWorkflowTask(byte[] taskKey) throws IOException { // Use a transaction to lock the task, and so finishAllWorkflowTasks will skip it. Transaction txn = mDatabase.newTransaction(DurabilityMode.NO_REDO); try { mSchemata.store(txn, taskKey, EMPTY_BYTES); } catch (Throwable e) { txn.reset(e); throw e; } return txn; } private void finishAllWorkflowTasks() throws IOException { // Use transaction locks to identity tasks which should be skipped. Transaction txn = mDatabase.newTransaction(DurabilityMode.NO_REDO); try { txn.lockMode(LockMode.UNSAFE); // don't auto acquire locks; is auto-commit var prefix = new byte[8]; // 0L is the prefix for all workflow tasks try (Cursor c = mSchemata.viewPrefix(prefix, 0).newCursor(txn)) { c.autoload(false); for (c.first(); c.key() != null; c.next()) { if (!txn.tryLockExclusive(mSchemata.id(), c.key(), 0).isHeld()) { // Skip it. continue; } // Load and check the value again, in case another thread deleted it // before the lock was acquired. c.load(); byte[] taskValue = c.value(); if (taskValue != null) { if (runRecoveredWorkflowTask(txn, c.key(), taskValue)) { c.delete(); } else { // Need a replacement transaction. txn = mDatabase.newTransaction(DurabilityMode.NO_REDO); txn.lockMode(LockMode.UNSAFE); c.link(txn); continue; } } txn.unlock(); } } } finally { txn.reset(); } } /** * @param txn must pass to mSchemata.delete when false is returned * @param taskKey (0L, indexId, taskType) * @return true if task can be immediately deleted */ private boolean runRecoveredWorkflowTask(Transaction txn, byte[] taskKey, byte[] taskValue) throws IOException { var indexKey = new byte[8]; System.arraycopy(taskKey, 8, indexKey, 0, 8); int taskType = decodeIntBE(taskKey, 8 + 8); return switch (taskType) { default -> throw new CorruptDatabaseException("Unknown task: " + taskType); case TASK_DELETE_SCHEMA -> doDeleteSchema(txn, taskKey, indexKey); case TASK_NOTIFY_SCHEMA -> doNotifySchema(txn, taskKey, decodeLongBE(indexKey, 0)); }; } /** * @param secondaryIndexId ignored when secondaryIndex is provided * @param secondaryIndex required when no taskFactory is provided * @param taskFactory can be null when a secondaryIndex is provided */ private Runnable deleteIndex(long primaryIndexId, long secondaryIndexId, byte[] descriptor, Index secondaryIndex, Supplier<Runnable> taskFactory) throws IOException { if (secondaryIndex != null) { secondaryIndexId = secondaryIndex.id(); } // Remove it from the cache. tableManager(mDatabase.indexById(primaryIndexId)).removeFromIndexTables(secondaryIndexId); EventListener listener = mDatabase.eventListener(); String eventStr; if (listener == null) { eventStr = null; } else { SecondaryInfo secondaryInfo = null; try { RowInfo primaryInfo = decodeExisting(null, null, primaryIndexId); secondaryInfo = indexRowInfo(primaryInfo, descriptor); } catch (Exception e) { } if (secondaryInfo == null) { eventStr = String.valueOf(secondaryIndexId); } else { eventStr = secondaryInfo.eventString(); } } RowPredicateLock<?> lock = indexLock(secondaryIndexId); if (lock == null) { if (listener != null) { listener.notify(EventType.TABLE_INDEX_INFO, "Dropping %1$s", eventStr); } Runnable task; if (taskFactory == null) { task = mDatabase.deleteIndex(secondaryIndex); } else { task = taskFactory.get(); } if (listener == null) { return task; } return () -> { task.run(); listener.notify(EventType.TABLE_INDEX_INFO, "Finished dropping %1$s", eventStr); }; } final long fSecondaryIndexId = secondaryIndexId; return () -> { try { Transaction txn = mDatabase.newTransaction(); try { // Acquire the predicate lock to wait for all scans to complete, and to // prevent new ones from starting. txn.lockTimeout(-1, null); Runnable mustWait = null; if (listener != null) { mustWait = () -> listener.notify (EventType.TABLE_INDEX_INFO, "Waiting to drop %1$s", eventStr); } lock.withExclusiveNoRedo(txn, mustWait, () -> { try { if (listener != null) { listener.notify(EventType.TABLE_INDEX_INFO, "Dropping %1$s", eventStr); } Runnable task; if (taskFactory == null) { task = mDatabase.deleteIndex(secondaryIndex); } else { task = taskFactory.get(); } task.run(); if (listener != null) { listener.notify(EventType.TABLE_INDEX_INFO, "Finished dropping %1$s", eventStr); } } catch (Throwable e) { uncaught(e); } }); txn.commit(); } finally { txn.exit(); } removeIndexLock(fSecondaryIndexId); } catch (Throwable e) { uncaught(e); } }; } /** * Returns the schema version for the given row info, creating a new version if necessary. * * @param mostRecent true if the given info is known to be the most recent definition * @param notify true to call notifySchema if anything changed */ int schemaVersion(RowInfo info, boolean mostRecent, long indexId, boolean notify) throws IOException { int schemaVersion; Map<Index, byte[]> secondariesToDelete = null; Transaction txn = mSchemata.newTransaction(DurabilityMode.SYNC); try (Cursor current = mSchemata.newCursor(txn)) { txn.lockTimeout(-1, null); current.find(key(indexId)); if (current.value() != null) { // Check if the schema has changed. schemaVersion = decodeIntLE(current.value(), 0); RowInfo currentInfo = decodeExisting (txn, info.name, indexId, current.value(), schemaVersion); if (checkSchema(info.name, currentInfo, info)) { // Exactly the same, so don't create a new version. return schemaVersion; } if (!mostRecent) { RowInfo info2 = info.withIndexes(currentInfo); if (info2 != info) { // Don't change the indexes. info = info2; if (checkSchema(info.name, currentInfo, info)) { // Don't create a new version. return schemaVersion; } } } } // Find an existing schemaVersion or create a new one. final boolean isTempIndex = mDatabase.isInTrash(txn, indexId); if (isTempIndex) { // Temporary trees are always in the trash, and they don't replicate. For this // reason, don't attempt to replicate schema metadata either. txn.durabilityMode(DurabilityMode.NO_REDO); } final var encoded = new EncodedRowInfo(info); assignVersion: try (Cursor byHash = mSchemata.newCursor(txn)) { byHash.find(key(indexId, encoded.primaryHash | (1 << 31))); byte[] schemaVersions = byHash.value(); if (schemaVersions != null) { for (int pos=0; pos<schemaVersions.length; pos+=4) { schemaVersion = decodeIntLE(schemaVersions, pos); RowInfo existing = decodeExisting (txn, info.name, indexId, null, schemaVersion); if (info.matches(existing)) { break assignVersion; } } } // Create a new version. View versionView = mSchemata.viewGt(key(indexId)).viewLt(key(indexId, 1 << 31)); try (Cursor highest = versionView.newCursor(txn)) { highest.autoload(false); highest.last(); if (highest.value() == null) { // First version. schemaVersion = 1; } else { byte[] key = highest.key(); schemaVersion = decodeIntBE(key, key.length - 4) + 1; } highest.findNearby(key(indexId, schemaVersion)); highest.store(encoded.primaryData); } if (schemaVersions == null) { schemaVersions = new byte[4]; } else { schemaVersions = Arrays.copyOfRange (schemaVersions, 0, schemaVersions.length + 4); } encodeIntLE(schemaVersions, schemaVersions.length - 4, schemaVersion); byHash.store(schemaVersions); } encodeIntLE(encoded.currentData, 0, schemaVersion); current.store(encoded.currentData); // Store the type name, which is usually the same as the class name. In case the // table isn't currently open, this name can be used for reporting background // status updates. Although the index name could be used, it's not required to be // the same as the class name. View nameView = viewExtended(indexId, K_TYPE_NAME); try (Cursor c = nameView.newCursor(txn)) { c.find(EMPTY_BYTES); byte[] nameBytes = encodeStringUTF(info.name); if (!Arrays.equals(nameBytes, c.value())) { c.store(nameBytes); } } // Start with the full set of secondary descriptors and later prune it down to // those that need to be created. TreeSet<byte[]> secondaries = encoded.secondaries; // Access a view of persisted secondary descriptors to index ids and states. View secondariesView = viewExtended(indexId, K_SECONDARY); // Find and update secondary indexes that should be deleted. TableManager<?> manager = null; try (Cursor c = secondariesView.newCursor(txn)) { byte[] key; for (c.first(); (key = c.key()) != null; c.next()) { byte[] value = c.value(); Index secondaryIndex = mDatabase.indexById(decodeLongLE(value, 0)); if (secondaryIndex == null) { c.store(null); // already deleted, so remove the entry } else if (!secondaries.contains(key)) { if (value[8] != 'D') { value[8] = 'D'; // "deleting" state c.store(value); } // Encode primaryIndexId and secondary descriptor. This entry is only // required with replication, allowing it to quickly identify a deleted // index as being a secondary index. This entry is deleted when // doDeleteSchema is called. var droppedEntry = new byte[8 + key.length]; encodeLongLE(droppedEntry, 0, indexId); System.arraycopy(key, 0, droppedEntry, 8, key.length); View droppedView = viewExtended(secondaryIndex.id(), K_DROPPED); droppedView.store(txn, EMPTY_BYTES, droppedEntry); if (manager == null) { manager = tableManager(mDatabase.indexById(indexId)); } // This removes entries from a cache, so not harmful if txn fails. manager.removeFromIndexTables(secondaryIndex.id()); if (secondariesToDelete == null) { secondariesToDelete = new LinkedHashMap<>(); } secondariesToDelete.put(secondaryIndex, c.key()); } } } // Find and update secondary indexes to create. try (Cursor c = secondariesView.newCursor(txn)) { Iterator<byte[]> it = secondaries.iterator(); while (it.hasNext()) { c.findNearby(it.next()); byte[] value = c.value(); if (value != null) { // Secondary index already exists. it.remove(); // If state is "deleting", switch it to "backfill". if (value[8] == 'D') { value[8] = 'B'; c.store(value); } } else if (isTempIndex) { // Secondary index doesn't exist, but temporary ones can be // immediately created because they're not replicated. it.remove(); value = new byte[8 + 1]; encodeLongLE(value, 0, mDatabase.newTemporaryIndex().id()); value[8] = 'B'; // "backfill" state c.store(value); } } } // The newly created index ids are copied into the array. Note that the array can // be empty, in which case calling createSecondaryIndexes is still necessary for // informing any replicas that potential changes have been made. The state of some // secondary indexes might have changed from "backfill" to "deleting", or vice // versa. If nothing changed, there's no harm in sending the notification anyhow. var ids = new long[secondaries.size()]; // Transaction is committed as a side-effect. mDatabase.createSecondaryIndexes(txn, indexId, ids, () -> { try { int i = 0; for (byte[] desc : secondaries) { byte[] value = new byte[8 + 1]; encodeLongLE(value, 0, ids[i++]); value[8] = 'B'; // "backfill" state if (!secondariesView.insert(txn, desc, value)) { // Not expected. throw new UniqueConstraintException(); } } } catch (IOException e) { rethrow(e); } }); } finally { txn.reset(); } if (secondariesToDelete != null) { for (var entry : secondariesToDelete.entrySet()) { try { Index secondaryIndex = entry.getKey(); byte[] descriptor = entry.getValue(); Runner.start(deleteIndex(indexId, 0, descriptor, secondaryIndex, null)); } catch (IOException e) { // Assume leadership was lost. } } } if (notify) { // We're currently the leader, and so this method must be invoked directly. notifySchema(indexId); } return schemaVersion; } /** * Finds a RowInfo for a specific schemaVersion. If not the same as the current version, * the alternateKeys and secondaryIndexes will be null (not just empty sets). * * If the given schemaVersion is 0, then the returned RowInfo only consists a primary key * and no value columns. * * @param rowType can pass null if not available (unless schemaVersion is 0) * @throws CorruptDatabaseException if not found */ RowInfo rowInfo(Class<?> rowType, long indexId, int schemaVersion) throws IOException, CorruptDatabaseException { if (schemaVersion == 0) { // No value columns to decode, and the primary key cannot change. RowInfo fullInfo = RowInfo.find(rowType); if (fullInfo.valueColumns.isEmpty()) { return fullInfo; } RowInfo info = new RowInfo(fullInfo.name); info.keyColumns = fullInfo.keyColumns; info.valueColumns = Collections.emptyNavigableMap(); info.allColumns = new TreeMap<>(info.keyColumns); return info; } // Can use NO_FLUSH because transaction will be only used for reading data. Transaction txn = mSchemata.newTransaction(DurabilityMode.NO_FLUSH); txn.lockMode(LockMode.REPEATABLE_READ); try (Cursor c = mSchemata.newCursor(txn)) { // Check if the indexId matches and the schemaVersion is the current one. c.autoload(false); c.find(key(indexId)); RowInfo current = null; if (c.value() != null && rowType != null) { var buf = new byte[4]; if (decodeIntLE(buf, 0) == schemaVersion) { // Matches, but don't simply return it. The current one might not have been // updated yet. current = RowInfo.find(rowType); } } c.autoload(true); c.findNearby(key(indexId, schemaVersion)); String typeName = rowType == null ? null : rowType.getName(); RowInfo info = decodeExisting(typeName, null, c.value()); if (current != null && current.allColumns.equals(info.allColumns)) { // Current one matches, so use the canonical RowInfo instance. return current; } else if (info == null) { throw new CorruptDatabaseException ("Schema version not found: " + schemaVersion + ", indexId=" + indexId); } else { return info; } } finally { txn.reset(); } } static SecondaryInfo indexRowInfo(RowInfo primaryInfo, byte[] desc) { byte type = desc[0]; int offset = 1; var info = new SecondaryInfo(primaryInfo, type == 'A'); int numKeys = decodePrefixPF(desc, offset); offset += lengthPrefixPF(numKeys); info.keyColumns = new LinkedHashMap<>(numKeys); for (int i=0; i<numKeys; i++) { offset = decodeIndexColumn(primaryInfo, desc, offset, info.keyColumns); } int numValues = decodePrefixPF(desc, offset); if (numValues == 0) { info.valueColumns = Collections.emptyNavigableMap(); } else { offset += lengthPrefixPF(numValues); info.valueColumns = new TreeMap<>(); offset = decodeIndexColumn(primaryInfo, desc, offset, info.valueColumns); } info.allColumns = new TreeMap<>(info.keyColumns); info.allColumns.putAll(info.valueColumns); return info; } /** * @param columns decoded column goes here * @return updated offset */ private static int decodeIndexColumn(RowInfo primaryInfo, byte[] desc, int offset, Map<String, ColumnInfo> columns) { int typeCode = decodeIntBE(desc, offset) ^ (1 << 31); offset += 4; int nameLength = decodePrefixPF(desc, offset); offset += lengthPrefixPF(nameLength); String name = decodeStringUTF(desc, offset, nameLength); offset += nameLength; ColumnInfo column = primaryInfo.allColumns.get(name); makeColumn: { if (column == null) { name = name.intern(); column = new ColumnInfo(); column.name = name; } else if (column.typeCode != typeCode) { column = column.copy(); } else { break makeColumn; } column.typeCode = typeCode; column.assignType(); } columns.put(column.name, column); return offset; } /** * Decodes a set of secondary index RowInfo objects. */ static SecondaryInfo[] indexRowInfos(RowInfo primaryInfo, byte[][] descriptors) { var infos = new SecondaryInfo[descriptors.length]; for (int i=0; i<descriptors.length; i++) { infos[i] = indexRowInfo(primaryInfo, descriptors[i]); } return infos; } /** * Returns a primary RowInfo or a secondary RowInfo, for the current schema version. Only * key columns are stable across schema versions. * * @param indexId can be the primaryIndexId or a secondary index id * @return RowInfo or SecondaryInfo, or null if not found */ RowInfo currentRowInfo(Class<?> rowType, long primaryIndexId, long indexId) throws IOException { RowInfo primaryInfo = RowInfo.find(rowType); if (primaryIndexId == indexId) { return primaryInfo; } Index primaryIndex = mDatabase.indexById(primaryIndexId); if (primaryIndex == null) { return null; } TableManager<?> manager = tableManager(primaryIndex); // Scan the set of secondary indexes to find it. Not the most efficient approach, but // tables aren't expected to have tons of secondaries. View secondariesView = viewExtended(primaryIndexId, K_SECONDARY); try (Cursor c = secondariesView.newCursor(null)) { for (c.first(); c.key() != null; c.next()) { if (indexId == decodeLongLE(c.value(), 0)) { return manager.secondaryInfo(primaryInfo, c.key()); } } } return null; } /** * @param key K_SECONDARY, etc */ private View viewExtended(long indexId, int key) { var prefix = new byte[8 + 4 + 4]; encodeLongBE(prefix, 0, indexId); encodeIntBE(prefix, 8 + 4, key); return mSchemata.viewPrefix(prefix, prefix.length); } /** * Decode the existing RowInfo for the current schema version. * * @param typeName pass null to decode the current type name * @return null if not found */ RowInfo decodeExisting(Transaction txn, String typeName, long indexId) throws IOException { byte[] currentData = mSchemata.load(txn, key(indexId)); if (currentData == null) { return null; } return decodeExisting(txn, typeName, indexId, currentData, decodeIntLE(currentData, 0)); } /** * Decode the existing RowInfo for the given schema version. * * @param typeName pass null to decode the current type name * @param currentData can be null if not the current schema * @return null if not found */ private RowInfo decodeExisting(Transaction txn, String typeName, long indexId, byte[] currentData, int schemaVersion) throws IOException { byte[] primaryData = mSchemata.load(txn, key(indexId, schemaVersion)); if (typeName == null) { byte[] currentName = viewExtended(indexId, K_TYPE_NAME).load(txn, EMPTY_BYTES); if (currentName == null) { typeName = String.valueOf(indexId); } else { typeName = decodeStringUTF(currentName, 0, currentName.length); } } return decodeExisting(typeName, currentData, primaryData); } /** * @param currentData if null, then alternateKeys and secondaryIndexes won't be decoded * @param primaryData if null, then null is returned * @return null only if primaryData is null */ private static RowInfo decodeExisting(String typeName, byte[] currentData, byte[] primaryData) throws CorruptDatabaseException { if (primaryData == null) { return null; } int pos = 0; int encodingVersion = primaryData[pos++] & 0xff; if (encodingVersion != 1) { throw new CorruptDatabaseException("Unknown encoding version: " + encodingVersion); } var info = new RowInfo(typeName); info.allColumns = new TreeMap<>(); var names = new String[decodePrefixPF(primaryData, pos)]; pos += lengthPrefixPF(names.length); for (int i=0; i<names.length; i++) { int nameLen = decodePrefixPF(primaryData, pos); pos += lengthPrefixPF(nameLen); String name = decodeStringUTF(primaryData, pos, nameLen).intern(); pos += nameLen; names[i] = name; var ci = new ColumnInfo(); ci.name = name; ci.typeCode = decodeIntLE(primaryData, pos); pos += 4; info.allColumns.put(name, ci); } info.keyColumns = new LinkedHashMap<>(); pos = decodeColumns(primaryData, pos, names, info.keyColumns); info.valueColumns = new TreeMap<>(); pos = decodeColumns(primaryData, pos, names, info.valueColumns); if (info.valueColumns.isEmpty()) { info.valueColumns = Collections.emptyNavigableMap(); } if (pos < primaryData.length) { throw new CorruptDatabaseException ("Trailing primary data: " + pos + " < " + primaryData.length); } if (currentData != null) { info.alternateKeys = new TreeSet<>(ColumnSetComparator.THE); pos = decodeColumnSets(currentData, 4, names, info.alternateKeys); if (info.alternateKeys.isEmpty()) { info.alternateKeys = Collections.emptyNavigableSet(); } info.secondaryIndexes = new TreeSet<>(ColumnSetComparator.THE); pos = decodeColumnSets(currentData, pos, names, info.secondaryIndexes); if (info.secondaryIndexes.isEmpty()) { info.secondaryIndexes = Collections.emptyNavigableSet(); } if (pos < currentData.length) { throw new CorruptDatabaseException ("Trailing current data: " + pos + " < " + currentData.length); } } return info; } /** * @param columns to be filled in * @return updated position */ private static int decodeColumns(byte[] data, int pos, String[] names, Map<String, ColumnInfo> columns) { int num = decodePrefixPF(data, pos); pos += lengthPrefixPF(num); for (int i=0; i<num; i++) { int columnNumber = decodePrefixPF(data, pos); pos += lengthPrefixPF(columnNumber); var ci = new ColumnInfo(); ci.name = names[columnNumber]; ci.typeCode = decodeIntLE(data, pos); pos += 4; ci.assignType(); columns.put(ci.name, ci); } return pos; } /** * @param columnSets to be filled in * @return updated position */ private static int decodeColumnSets(byte[] data, int pos, String[] names, Set<ColumnSet> columnSets) { int size = decodePrefixPF(data, pos); pos += lengthPrefixPF(size); for (int i=0; i<size; i++) { var cs = new ColumnSet(); cs.allColumns = new TreeMap<>(); pos = decodeColumns(data, pos, names, cs.allColumns); cs.keyColumns = new LinkedHashMap<>(); pos = decodeColumns(data, pos, names, cs.keyColumns); cs.valueColumns = new TreeMap<>(); pos = decodeColumns(data, pos, names, cs.valueColumns); if (cs.valueColumns.isEmpty()) { cs.valueColumns = Collections.emptyNavigableMap(); } columnSets.add(cs); } return pos; } private static byte[] key(long indexId) { var key = new byte[8]; encodeLongBE(key, 0, indexId); return key; } private static byte[] key(long indexId, int suffix) { var key = new byte[8 + 4]; encodeLongBE(key, 0, indexId); encodeIntBE(key, 8, suffix); return key; } private static class EncodedRowInfo { // All the column names, in lexicographical order. final String[] names; // Primary ColumnSet. final byte[] primaryData; // Hash code over the primary data. final int primaryHash; // Current schemaVersion (initially zero), alternateKeys, and secondaryIndexes. final byte[] currentData; // Set of descriptors. final TreeSet<byte[]> secondaries; /** * Constructor for encoding and writing. */ EncodedRowInfo(RowInfo info) { names = new String[info.allColumns.size()]; var columnNameMap = new HashMap<String, Integer>(); var encoder = new Encoder(names.length * 16); // with initial capacity guess encoder.writeByte(1); // encoding version encoder.writePrefixPF(names.length); int columnNumber = 0; for (ColumnInfo column : info.allColumns.values()) { String name = column.name; columnNameMap.put(name, columnNumber); names[columnNumber++] = name; encoder.writeStringUTF(name); encoder.writeIntLE(column.typeCode); } encodeColumns(encoder, info.keyColumns.values(), columnNameMap); encodeColumns(encoder, info.valueColumns.values(), columnNameMap); primaryData = encoder.toByteArray(); primaryHash = Arrays.hashCode(primaryData); encoder.reset(0); encoder.writeIntLE(0); // slot for current schemaVersion encodeColumnSets(encoder, info.alternateKeys, columnNameMap); encodeColumnSets(encoder, info.secondaryIndexes, columnNameMap); currentData = encoder.toByteArray(); secondaries = new TreeSet<>(Arrays::compareUnsigned); info.alternateKeys.forEach(cs -> secondaries.add(encodeDescriptor('A', encoder, cs))); info.secondaryIndexes.forEach(cs -> secondaries.add(encodeDescriptor('I', encoder,cs))); } /** * Encode columns using name indexes instead of strings. */ private static void encodeColumns(Encoder encoder, Collection<ColumnInfo> columns, Map<String, Integer> columnNameMap) { encoder.writePrefixPF(columns.size()); for (ColumnInfo column : columns) { encoder.writePrefixPF(columnNameMap.get(column.name)); encoder.writeIntLE(column.typeCode); } } /** * Encode column sets using name indexes instead of strings. */ private static void encodeColumnSets(Encoder encoder, Collection<ColumnSet> columnSets, Map<String, Integer> columnNameMap) { encoder.writePrefixPF(columnSets.size()); for (ColumnSet cs : columnSets) { encodeColumns(encoder, cs.allColumns.values(), columnNameMap); encodeColumns(encoder, cs.keyColumns.values(), columnNameMap); encodeColumns(encoder, cs.valueColumns.values(), columnNameMap); } } /** * Encode a secondary index descriptor. * * @param type 'A' or 'I'; alternate key descriptors are ordered first */ private static byte[] encodeDescriptor(char type, Encoder encoder, ColumnSet cs) { encoder.reset(0); encoder.writeByte((byte) type); encodeColumns(encoder, cs.keyColumns); encodeColumns(encoder, cs.valueColumns); return encoder.toByteArray(); } private static void encodeColumns(Encoder encoder, Map<String, ColumnInfo> columns) { encoder.writePrefixPF(columns.size()); for (ColumnInfo column : columns.values()) { encoder.writeIntBE(column.typeCode ^ (1 << 31)); encoder.writeStringUTF(column.name); } } } }
package com.vmware.vim25.mo; import com.vmware.vim25.*; import java.rmi.RemoteException; import java.text.MessageFormat; import java.util.concurrent.TimeUnit; public class Task extends ExtensibleManagedObject { public static final String PROPNAME_INFO = "info"; public static final String SUCCESS = "success"; private static final long DEFAULT_MAX_WAIT_TIME_MILLIS = TimeUnit.MINUTES.toMillis(10); private static final int DEFAULT_RUNNING_SLEEP_TIME_MILLIS = 500; private static final int DEFAULT_QUEUED_SLEEP_TIME_MILLIS = 1000; public Task(ServerConnection serverConnection, ManagedObjectReference mor) { super(serverConnection, mor); } public TaskInfo getTaskInfo() throws InvalidProperty, RuntimeFault, RemoteException { return (TaskInfo) getCurrentProperty(PROPNAME_INFO); } public ManagedEntity getAssociatedManagedEntity() { return (ManagedEntity) getManagedObject("info.entity"); } public ManagedEntity[] getLockedManagedEntities() { return (ManagedEntity[]) getManagedObjects("info.locked"); } public void cancelTask() throws RuntimeFault, RemoteException { getVimService().cancelTask(getMOR()); } public void setTaskState(TaskInfoState tis, Object result, LocalizedMethodFault fault) throws InvalidState, RuntimeFault, RemoteException { getVimService().setTaskState(getMOR(), tis, result, fault); } public void updateProgress(int percentDone) throws InvalidState, OutOfBounds, RuntimeFault, RemoteException { getVimService().updateProgress(getMOR(), percentDone); } /** * @since SDK4.0 */ public void setTaskDescription(LocalizableMessage description) throws RuntimeFault, RemoteException { getVimService().setTaskDescription(getMOR(), description); } /** * If there is another thread or client calling waitForUpdate(), the behavior of this * method is not predictable. This usually happens with VI Client plug-in which shares * the session with the VI Client which use waitForUpdate() extensively. * The safer way is to poll the related info.state and check its value. * * @return * @throws InvalidProperty * @throws RuntimeFault * @throws java.rmi.RemoteException * @deprecated */ public String waitForMe() throws InvalidProperty, RuntimeFault, RemoteException { Object[] result = waitForValues( new String[]{"info.state", "info.error"}, new String[]{"state"}, new Object[][]{new Object[]{TaskInfoState.success, TaskInfoState.error}}); if (result[0].equals(TaskInfoState.success)) { return SUCCESS; } else { TaskInfo tinfo = (TaskInfo) getCurrentProperty(PROPNAME_INFO); LocalizedMethodFault fault = tinfo.getError(); String error = "Error Occured"; if (fault != null) { MethodFault mf = fault.getFault(); throw mf; } return error; } } public String waitForTask() throws RemoteException, InterruptedException { return waitForTask(DEFAULT_RUNNING_SLEEP_TIME_MILLIS, DEFAULT_QUEUED_SLEEP_TIME_MILLIS, DEFAULT_MAX_WAIT_TIME_MILLIS); } public String waitForTask(int runningDelayInMillSecond, int queuedDelayInMillSecond) throws RemoteException, InterruptedException { return waitForTask(runningDelayInMillSecond, queuedDelayInMillSecond, DEFAULT_MAX_WAIT_TIME_MILLIS); } public String waitForTask(long maxWaitInMillSecond) throws RemoteException, InterruptedException { return waitForTask(DEFAULT_RUNNING_SLEEP_TIME_MILLIS, DEFAULT_QUEUED_SLEEP_TIME_MILLIS, maxWaitInMillSecond); } public String waitForTask(int runningDelayInMillSecond, int queuedDelayInMillSecond, long maxWaitInMillSecond) throws RemoteException, InterruptedException { TaskInfoState tState = null; int tries; int maxTries = 3; Exception getInfoException; long start = System.currentTimeMillis(); long elapsed; while ((tState == null) || tState.equals(TaskInfoState.running) || tState.equals(TaskInfoState.queued)) { tState = null; getInfoException = null; tries = 0; // under load getTaskInfo may return null when there really is valid task info, so we try 3 times to get it. while (tState == null) { tries++; if (tries > maxTries) { if (getInfoException == null) { throw new NullPointerException(); } else if (getInfoException instanceof RuntimeFault) { throw (RuntimeFault) getInfoException; } else if (getInfoException instanceof RemoteException) { throw (RemoteException) getInfoException; } else { throw new RuntimeException(getInfoException); } } try { tState = getTaskInfo().getState(); } catch (Exception e) { //silently catch 3 exceptions getInfoException = e; } } // sleep for a specified time based on task state. if (tState.equals(TaskInfoState.running)) { Thread.sleep(runningDelayInMillSecond); } else { Thread.sleep(queuedDelayInMillSecond); } // check elapsed time elapsed = System.currentTimeMillis() - start; if ((elapsed > maxWaitInMillSecond)) { throw new IllegalStateException(MessageFormat.format("Task {0} timed out ({1}ms) while TaskInfoState is: {2}", this.toString(), elapsed, tState)); } } return tState.toString(); } }
package dk.itu.donkey; // General utilities import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; // Reflection utilities import java.lang.reflect.Field; // SQL utilities import java.sql.SQLException; /** * The Model Query class is used for querying database rows related to models * and, in contrast to a raw {@link Query}, returns {@link Model}s rather than * {@link Row}s. * * @param <T> The type of model to query. * * @since 1.0.0 Initial release. */ public final class ModelQuery<T extends Model> { /** * The model to query. */ private Class<T> type; /** * The table to query. */ private String table; /** * The query to build and perform. */ private Query query; /** * Keep track of tables that have been joined into the query. */ private Set<String> tables = new HashSet<>(); /** * Initialize a model query. * * @param type The model subclass to query. */ public ModelQuery(final Class<T> type) { T model = Model.instantiate(type); this.type = type; this.query = model.query(); this.table = model.table(); } /** * Prefix a column with the table name of the model being queried if needed. * * <p> * If the column has already been prefixed with another table name, the * column will simply pass through without being touched. * * @param column The column to prefix. * @return The prefixed column. */ private String prefixColumn(final String column) { if (!column.matches(".*\\..*")) { return String.format("%s.%s", this.table, column); } else { return column; } } /** * Add a where clause to the query. * * @param column The column to compare. * @param operator The logical operator to use for the comparison. * @param value The value to compare against. * @return The current {@link ModelQuery} object, for chaining. */ public ModelQuery where( final String column, final String operator, final Object value ) { this.query.where(this.prefixColumn(column), operator, value); return this; } /** * Add a where clause to the query. * * @param column The column to compare. * @param value The value to compare against. * @return The current {@link ModelQuery} object, for chaining. */ public ModelQuery where(final String column, final Object value) { this.query.where(this.prefixColumn(column), value); return this; } /** * Add a or where clause to the query. * * @param column The column to compare. * @param operator The logical operator to use for the comparison. * @param value The value to compare against. * @return The current {@link ModelQuery} object, for chaining. */ public ModelQuery orWhere( final String column, final String operator, final Object value ) { this.query.orWhere(this.prefixColumn(column), operator, value); return this; } /** * Add a or where clause to the query. * * @param column The column to compare. * @param value The value to compare against. * @return The current {@link ModelQuery} object, for chaining. */ public ModelQuery orWhere(final String column, final Object value) { this.query.orWhere(this.prefixColumn(column), value); return this; } /** * Add an order by clause to the query. * * @param column The column to order by. * @param direction The ordering direction. Either "asc" or "desc". * @return The current {@link ModelQuery} object, for chaining. */ public ModelQuery orderBy(final String column, final String direction) { this.query.orderBy(this.prefixColumn(column), direction); return this; } /** * Add an order by clause to the query. * * @param column The column to order by. * @return The current {@link ModelQuery} object, for chaining. */ public ModelQuery orderBy(final String column) { this.query.orderBy(this.prefixColumn(column)); return this; } /** * Recursively traverse a model and initialize its relations based on a * database response. * * @param context The context of the relation. * @param type The type of model to traverse. * @param rows The database rows to use for initializing the models. * @return A list of models initialized with their relations. */ private List<T> getRelations( final T context, final Class<?> type, final List<Row> rows ) { if (rows == null) { return null; } // Create a map for tracking model instances by their ID. When joining data, // the same instance of a model might appear several times in the query // response (e.g. the same post for several comments). The map will ensure // that only the first occurence of each unique model is instantiated. Map<Integer, T> models = new LinkedHashMap<>(); // Map model IDs to their associated rows. E.g. a list of posts joined with // their comments would result in a map of post IDs mapped to the database // rows containing the comments associated with that post ID. Map<Integer, List<Row>> modelRows = new LinkedHashMap<>(); // Partition the rows according to the specified type. for (Row row: rows) { T model = Model.instantiate(type); // Grab the ID of the current model table from the row. Integer id = (Integer) row.get( String.format("%s_%s", model.table(), "id") ); if (id == null || id <= 0) { continue; } // List of database rows associated with a given model. List<Row> subRows; if (!models.containsKey(id)) { subRows = new ArrayList<>(); subRows.add(row); // Set the current row on the model. Since each column in the response // is prefixed with the table name of the model, only columns specific // to the model will be set on it. model.setRow(row); models.put(id, model); } else { subRows = modelRows.get(id); subRows.add(row); } modelRows.put(id, subRows); } for (T model: models.values()) { // Run through each of the fields of the model and look for further // relations. for (Field field: model.getFields()) { String fieldName = field.getName(); Class<?> fieldType = model.getFieldType(field); boolean isList = false; // If the field being looked at is a list, get the generic type of the // list. if (List.class.isAssignableFrom(fieldType)) { fieldType = Model.getGenericType(field); // Remember that the field type was a list. isList = true; } if (Model.class.isAssignableFrom(fieldType)) { // If the field is of the same type as the context, bail out. This is // to avoid an infinite loop where two models both have fields of // oneanother's type, e.g. a post with a list of comments and a // comment that belongs to a post. if (context != null && fieldType == context.getClass()) { model.setField(fieldName, model.parseIncomingFieldValue( field, context )); } else { List<T> relations = this.getRelations( model, fieldType, modelRows.get(model.id()) ); if (relations == null) { continue; } Object value = relations; if (!isList) { value = relations.get(0); } model.setField(fieldName, model.parseIncomingFieldValue( field, value )); } } } } return new ArrayList<T>(models.values()); } /** * Recursively traverse a model and join in its relations on the current * query object. * * @param type The model type to traverse. */ private void setRelations(final Class<?> type) { T outer = Model.instantiate(type); // Remember that this model has already been added as a relation. this.tables.add(outer.table()); // Select the ID column of the model in the format "table_id". this.query.select(String.format("%s.id as %1$s_id", outer.table())); for (Field field: outer.getFields()) { String fieldName = field.getName(); Class<?> fieldType = outer.getFieldType(field); boolean isList = false; // If the field being looked at is a list, get the generic type of the // list. if (List.class.isAssignableFrom(fieldType)) { fieldType = Model.getGenericType(field); // Remember that the field type was a list. isList = true; } if (Model.class.isAssignableFrom(fieldType)) { T inner = Model.instantiate(fieldType); // If the model hasn't already been added as a relation, join it into // the query if it represents a single field, e.g. a comment belonging // to a post, and look for further relations... // Example: // [...] from showtimes join movies on showtimes.movie = movies.id if (!this.tables.contains(inner.table())) { if (!isList) { this.query.leftJoin( inner.table(), String.format("%s.%s", outer.table(), fieldName), String.format("%s.%s", inner.table(), "id") ); // Remember that this table has already been added as a relation. this.tables.add(inner.table()); } // Look for further relations. this.setRelations(fieldType); } // ...otherwise, assume that the model is a relation of an already // joined model. This will be the case in a two-way relation (either // One-to-One or One-to-Many) and so a reverse join is performed if the // field isn't a list, e.g. joining a single post with a list of // comments. // Example: // [...] from showtimes join tickets on showtimes.id = tickets.showtime else if (!isList) { this.query.leftJoin( outer.table(), String.format("%s.%s", inner.table(), "id"), String.format("%s.%s", outer.table(), fieldName) ); } } else { // Prefix all the columns of the model with its table name to ensure // that non-unique columns can be differentiated if other data is // joined in. I.e. people.name becomes people_name. this.query.select(String.format( "%s.%s as %1$s_%2$s", outer.table(), fieldName.toLowerCase() )); } } } /** * Perform the query and return a list of matching models. * * @return A list of models. * * @throws SQLException In case of a SQL error. */ public List<T> get() throws SQLException { this.setRelations(this.type); return this.getRelations(null, this.type, this.query.get()); } }
package org.kohsuke.github; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import javax.xml.bind.DatatypeConverter; /** * A Content of a repository. * * @author Alexandre COLLIGNON * @see GHRepository#getFileContent(String) */ @SuppressWarnings({"UnusedDeclaration"}) public class GHContent { /* In normal use of this class, repository field is set via wrap(), but in the code search API, there's a nested 'repository' field that gets populated from JSON. */ private GHRepository repository; private GitHub root; private String type; private String encoding; private long size; private String sha; private String name; private String path; private String content; private String url; // this is the API url private String git_url; // this is the Blob url private String html_url; // this is the UI private String download_url; public GHRepository getOwner() { return repository; } public String getType() { return type; } public String getEncoding() { return encoding; } public long getSize() { return size; } public String getSha() { return sha; } public String getName() { return name; } public String getPath() { return path; } /** * Retrieve the decoded content that is stored at this location. * * <p> * Due to the nature of GitHub's API, you're not guaranteed that * the content will already be populated, so this may trigger * network activity, and can throw an IOException. * * @deprecated * Use {@link #read()} */ @SuppressFBWarnings("DM_DEFAULT_ENCODING") public String getContent() throws IOException { return new String(DatatypeConverter.parseBase64Binary(getEncodedContent())); } /** * Retrieve the base64-encoded content that is stored at this location. * * <p> * Due to the nature of GitHub's API, you're not guaranteed that * the content will already be populated, so this may trigger * network activity, and can throw an IOException. * * @deprecated * Use {@link #read()} */ public String getEncodedContent() throws IOException { if (content!=null) return content; else return Base64.encodeBase64String(IOUtils.toByteArray(read())); } public String getUrl() { return url; } public String getGitUrl() { return git_url; } public String getHtmlUrl() { return html_url; } /** * Retrieves the actual content stored here. */ public InputStream read() throws IOException { return new Requester(root).asStream(getDownloadUrl()); } /** * URL to retrieve the raw content of the file. Null if this is a directory. */ public String getDownloadUrl() throws IOException { populate(); return download_url; } public boolean isFile() { return "file".equals(type); } public boolean isDirectory() { return "dir".equals(type); } /** * Fully populate the data by retrieving missing data. * * Depending on the original API call where this object is created, it may not contain everything. */ protected synchronized void populate() throws IOException { if (download_url!=null) return; // already populated root.retrieve().to(url, this); } /** * List immediate children of this directory. */ public PagedIterable<GHContent> listDirectoryContent() throws IOException { if (!isDirectory()) throw new IllegalStateException(path+" is not a directory"); return new PagedIterable<GHContent>() { public PagedIterator<GHContent> iterator() { return new PagedIterator<GHContent>(root.retrieve().asIterator(url, GHContent[].class)) { @Override protected void wrapUp(GHContent[] page) { GHContent.wrap(page, repository); } }; } }; } @SuppressFBWarnings("DM_DEFAULT_ENCODING") public GHContentUpdateResponse update(String newContent, String commitMessage) throws IOException { return update(newContent.getBytes(), commitMessage, null); } @SuppressFBWarnings("DM_DEFAULT_ENCODING") public GHContentUpdateResponse update(String newContent, String commitMessage, String branch) throws IOException { return update(newContent.getBytes(), commitMessage, branch); } public GHContentUpdateResponse update(byte[] newContentBytes, String commitMessage) throws IOException { return update(newContentBytes, commitMessage, null); } public GHContentUpdateResponse update(byte[] newContentBytes, String commitMessage, String branch) throws IOException { String encodedContent = DatatypeConverter.printBase64Binary(newContentBytes); Requester requester = new Requester(root) .with("path", path) .with("message", commitMessage) .with("sha", sha) .with("content", encodedContent) .method("PUT"); if (branch != null) { requester.with("branch", branch); } GHContentUpdateResponse response = requester.to(getApiRoute(), GHContentUpdateResponse.class); response.getContent().wrap(repository); response.getCommit().wrapUp(repository); this.content = encodedContent; return response; } public GHContentUpdateResponse delete(String message) throws IOException { return delete(message, null); } public GHContentUpdateResponse delete(String commitMessage, String branch) throws IOException { Requester requester = new Requester(root) .with("path", path) .with("message", commitMessage) .with("sha", sha) .method("DELETE"); if (branch != null) { requester.with("branch", branch); } GHContentUpdateResponse response = requester.to(getApiRoute(), GHContentUpdateResponse.class); response.getCommit().wrapUp(repository); return response; } private String getApiRoute() { return "/repos/" + repository.getOwnerName() + "/" + repository.getName() + "/contents/" + path; } GHContent wrap(GHRepository owner) { this.repository = owner; this.root = owner.root; return this; } GHContent wrap(GitHub root) { this.root = root; if (repository!=null) repository.wrap(root); return this; } public static GHContent[] wrap(GHContent[] contents, GHRepository repository) { for (GHContent unwrappedContent : contents) { unwrappedContent.wrap(repository); } return contents; } }
package dump; import it.cnr.isti.hpc.io.reader.JsonRecordParser; import it.cnr.isti.hpc.io.reader.RecordReader; import it.cnr.isti.hpc.wikipedia.article.Article; import it.cnr.isti.hpc.wikipedia.reader.filter.TypeFilter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class RecordReaderWrapper { private RecordReader<Article> reader; private RecordReader<Article> listReader; public RecordReaderWrapper(String filename) { reader = new RecordReader<Article>(filename, new JsonRecordParser<Article>(Article.class)); listReader = reader.filter(new TypeFilter(Article.Type.LIST)); } public List<Article> getArticlesList() { List<Article> articleList = new ArrayList<Article>(); for (Article article : listReader) { articleList.add(article); } return articleList; } public Iterator<Article> iterator() { return listReader.iterator(); } }
package org.lantern; import java.nio.charset.Charset; /** * Constants for Lantern. */ public class LanternConstants { public static final int DASHCACHE_MAXAGE = 60 * 5; public static final String API_VERSION = "0.0.1"; public static final String BUILD_TIME = "build_time_tok"; public static final String UNCENSORED_ID = "-lan-"; /** * We make range requests of the form "bytes=x-y" where * y <= x + CHUNK_SIZE * in order to chunk and parallelize downloads of large entities. This * is especially important for requests to laeproxy since it is subject * to GAE's response size limits. * Because "bytes=x-y" requests bytes x through y _inclusive_, * this actually requests y - x + 1 bytes, * i.e. CHUNK_SIZE + 1 bytes * when x = 0 and y = CHUNK_SIZE. * This currently corresponds to laeproxy's RANGE_REQ_SIZE of 2000000. */ public static final long CHUNK_SIZE = 2000000 - 1; public static final String VERSION_KEY = "v"; public static final String OS_KEY = "os"; public static final String ARCH_KEY = "ar"; public static final int LANTERN_LOCALHOST_HTTP_PORT = 8787; public static final String USER_NAME = "un"; public static final String PASSWORD = "pwd"; public static final String DIRECT_BYTES = "db"; public static final String BYTES_PROXIED = "bp"; public static final String REQUESTS_PROXIED = "rp"; public static final String DIRECT_REQUESTS = "dr"; public static final String MACHINE_ID = "m"; public static final String COUNTRY_CODE = "cc"; public static final String WHITELIST_ADDITIONS = "wa"; public static final String WHITELIST_REMOVALS = "wr"; public static final String SERVERS = "s"; public static final String UPDATE_TIME = "ut"; public static final String ROSTER = "roster"; /** * The following are keys in the properties files. */ public static final String FORCE_CENSORED = "forceCensored"; /** * maps to a version id (e.g. "1.0.0-rc1") * Should really be called VERSION_KEY; when client sends to server * it maps to its version, when server sends to client it maps to the * latest version. */ public static final String UPDATE_KEY = "uk"; public static final String UPDATE_VERSION_KEY = "number"; public static final String UPDATE_URL_KEY = "url"; public static final String UPDATE_RELEASE_DATE_KEY = "rd"; public static final String UPDATE_MESSAGE_KEY = "message"; public static final String INVITES_KEY = "invites"; public static final String INVITED_EMAIL = "invem"; public static final String INVITEE_NAME = "inv_name"; public static final String INVITER_NAME = "invr_name"; // Transitioning out; newer clients will use REFRESH_TOKEN... public static final String INVITER_REFRESH_TOKEN = "invr_refrtok"; public static final String INVITED = "invd"; public static final String INVITED_KEY = "invited"; public static final String FAILED_INVITES_KEY = "failed_invites"; public static final String INVITE_FAILED_REASON = "reason"; public static final String NEED_REFRESH_TOKEN = "need_refrtok"; // Old value kept around for compatibility with old clients. public static final String REFRESH_TOKEN = INVITER_REFRESH_TOKEN; public static final String HOST_AND_PORT = "host_and_port"; public static final String FALLBACK_HOST_AND_PORT = "fallback_host_and_port"; public static final String IS_FALLBACK_PROXY = "is_fallback_proxy"; /** * The length of keys in translation property files. */ public static final int I18N_KEY_LENGTH = 40; public static final String CONNECT_ON_LAUNCH = "connectOnLaunch"; public static final String START_AT_LOGIN = "startAtLogin"; public static final String FRIENDS = "friends"; public static final String FRIEND = "friend"; public static final String FRIENDED_BY_LAST_UPDATED = "fblu"; public static final String FRIENDED_BY = "fb"; public static final String UNFRIENDED_BY = "ufb"; public static final String LANTERN_VERSION_HTTP_HEADER_NAME = "Lantern-Version"; public static final boolean ON_APP_ENGINE; public static final int KSCOPE_ADVERTISEMENT = 0x2111; public static final String KSCOPE_ADVERTISEMENT_KEY = "ksak"; public static final Charset UTF8 = Charset.forName("UTF8"); static { boolean tempAppEngine; try { Class.forName("org.lantern.LanternControllerUtils"); tempAppEngine = true; } catch (final ClassNotFoundException e) { tempAppEngine = false; } ON_APP_ENGINE = tempAppEngine; } }
package eu.digitisation.DA; import eu.digitisation.layout.SortPageXML; import eu.digitisation.log.Messages; import eu.digitisation.text.WordScanner; import eu.digitisation.xml.DocumentParser; import eu.digitisation.xml.XPathFilter; import java.io.File; import java.io.IOException; import java.text.Collator; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.xml.xpath.XPathExpressionException; import org.w3c.dom.Document; import org.w3c.dom.Element; public class Split { static XPathFilter filter; // Selects XML elements with relevant content final static Collator collator; // Defines the lexicographic order final static String lemmaRE; // Regex for one lemma final static String headRE; // Regex for multiword lemmas static { String[] inclusions = {"TextRegion[@type='paragraph']"}; try { filter = new XPathFilter(inclusions, null); } catch (XPathExpressionException ex) { Messages.severe(ex.getMessage()); } collator = Collator.getInstance(Locale.FRENCH); // Create old Spanish rules lemmaRE = "(\\p{Lu}|[ñ])+"; headRE = lemmaRE + "([,]?\\p{Space}" + lemmaRE + ")*"; } /** * * @param e * @return uppercase prefix or null if none found * @throws IOException */ private static String header(Element e) throws IOException { String text = e.getTextContent().trim(); WordScanner scanner = new WordScanner(text, "^" + headRE); String prefix = scanner.nextWord(); System.out.println(text + "\n -> " + prefix); return prefix; } public static List<String> headers(Document doc) throws IOException { List<String> list = new ArrayList<String>(); for (Element e : filter.selectElements(doc)) { String head = header(e); if (head != null && !head.isEmpty()) { list.add(head); } } return list; } /** * Function for debugging * * @param file */ public static void view(File file) throws IOException { Document doc = SortPageXML.isSorted(file) ? DocumentParser.parse(file) : SortPageXML.sorted(DocumentParser.parse(file)); for (String head : headers(doc)) { System.out.println(head); } } public static void split(File ifile) throws IOException { Document doc = SortPageXML.isSorted(ifile) ? DocumentParser.parse(ifile) : SortPageXML.sorted(DocumentParser.parse(ifile)); System.out.println(ifile); String last = ""; for (Element e : filter.selectElements(doc)) { String text = e.getTextContent().replaceAll("\\p{Space}+", " ").trim(); if (!text.isEmpty()) { String head = text.split("\\p{Space}|\\p{Punct}")[0]; //System.out.println(text); if (head.matches(lemmaRE)) { int n = collator.compare(last, head); if (n < 0) { System.out.println(head); } else if (n == 0) { System.out.println("\t" + head.toLowerCase()); } else if (isParticiple(head, last)) { System.out.println("*Participle*" + head); } else { System.out.println("***" + head); } last = head; } else if (head.replaceAll("l", "I").matches(lemmaRE)) { // wrong transcription System.out.println(">" + head); } else if (head.matches(lemmaRE + "\\p{L}" + lemmaRE)) { // a single mismatch System.out.println(">>>" + head); } else if (head.matches(headRE)) { System.out.println("<<<<" + head); } else { ;//System.out.println(">>>" + text); } } } } public static void main(String[] args) throws IOException { for (String arg : args) { Split.view(new File(arg)); } } private static boolean isParticiple(String head, String last) { return last.replaceFirst("AR$", "") .equals(head.replaceFirst("ADO$", "")); } }
package org.lightmare.cache; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Stack; import java.util.concurrent.atomic.AtomicBoolean; import javax.ejb.TransactionAttributeType; import javax.ejb.TransactionManagementType; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceUnit; import org.lightmare.ejb.handlers.BeanHandler; import org.lightmare.utils.CollectionUtils; /** * Container class to save bean {@link Field} with annotation * {@link PersistenceContext} and bean class * * @author Levan Tsinadze * @since 0.0.45-SNAPSHOT * @see org.lightmare.deploy.BeanLoader#loadBean(org.lightmare.deploy.BeanLoader.BeanParameters) * @see org.lightmare.ejb.EjbConnector#connectToBean(MetaData) * @see org.lightmare.ejb.EjbConnector#createRestHandler(MetaData) * @see org.lightmare.ejb.handlers.BeanHandler */ public class MetaData { // EJB bean class private Class<?> beanClass; // EJB bean implementation interfaces private Class<?>[] interfaceClasses; // All EJB local interfaces private Class<?>[] localInterfaces; // All EJB remote interfaces private Class<?>[] remoteInterfaces; // EJB bean's Field to set JTA UserTransaction instance private Field transactionField; // All connections for appropriated EJB bean private Collection<ConnectionData> connections; // Appropriated ClassLoader with loaded EJB bean class private ClassLoader loader; // Check if appropriated EJB bean is in deployment progress private AtomicBoolean inProgress = new AtomicBoolean(); // Check if appropriated EJB bean has bean managed or container managed // transactions private boolean transactional; // TransactionAttributeType annotation or default value for appropriated // EJB bean private TransactionAttributeType transactionAttrType; // TransactionManagementType annotation or defaulr value for appropriated // EJB bean class private TransactionManagementType transactionManType; private List<InjectionData> injects; private Collection<Field> unitFields; private Queue<InterceptorData> interceptors; private BeanHandler handler; public Class<?> getBeanClass() { return beanClass; } public void setBeanClass(Class<?> beanClass) { this.beanClass = beanClass; } public Class<?>[] getInterfaceClasses() { return interfaceClasses; } public void setInterfaceClasses(Class<?>[] interfaceClasses) { this.interfaceClasses = interfaceClasses; } public Class<?>[] getLocalInterfaces() { return localInterfaces; } public void setLocalInterfaces(Class<?>[] localInterfaces) { this.localInterfaces = localInterfaces; } public Class<?>[] getRemoteInterfaces() { return remoteInterfaces; } public void setRemoteInterfaces(Class<?>[] remoteInterfaces) { this.remoteInterfaces = remoteInterfaces; } public Field getTransactionField() { return transactionField; } public void setTransactionField(Field transactionField) { this.transactionField = transactionField; } public Collection<ConnectionData> getConnections() { return connections; } public void setConnections(Collection<ConnectionData> connections) { this.connections = connections; } /** * Caches passed connection information * * @param connection */ public void addConnection(ConnectionData connection) { if (connections == null) { connections = new ArrayList<ConnectionData>(); } connections.add(connection); } /** * Caches {@link javax.persistence.PersistenceUnit} annotated field and unit * name to cache * * @param unitName * @param unitField */ private void addUnitField(String unitName, Field unitField) { for (ConnectionData connection : connections) { if (unitName.equals(connection.getUnitName())) { connection.setUnitField(unitField); } } } /** * Adds {@link javax.ejb.PersistenceUnit} annotated field to * {@link MetaData} for cache * * @param unitFields */ public void addUnitFields(Collection<Field> unitFields) { if (CollectionUtils.validAll(connections, unitFields)) { String unitName; for (Field unitField : unitFields) { unitName = unitField.getAnnotation(PersistenceUnit.class) .unitName(); addUnitField(unitName, unitField); } this.unitFields = unitFields; } } public ClassLoader getLoader() { return loader; } public void setLoader(ClassLoader loader) { this.loader = loader; } public boolean isInProgress() { return inProgress.get(); } public void setInProgress(boolean inProgress) { this.inProgress.getAndSet(inProgress); } public boolean isTransactional() { return transactional; } public void setTransactional(boolean transactional) { this.transactional = transactional; } public TransactionAttributeType getTransactionAttrType() { return transactionAttrType; } public void setTransactionAttrType( TransactionAttributeType transactionAttrType) { this.transactionAttrType = transactionAttrType; } public TransactionManagementType getTransactionManType() { return transactionManType; } public void setTransactionManType( TransactionManagementType transactionManType) { this.transactionManType = transactionManType; } public List<InjectionData> getInjects() { return injects; } /** * Adds passed {@link InjectionData} to cache * * @param inject */ public void addInject(InjectionData inject) { if (injects == null) { injects = new ArrayList<InjectionData>(); } injects.add(inject); } public Collection<Field> getUnitFields() { return this.unitFields; } /** * Offers {@link InterceptorData} to {@link Stack} to process request by * order * * @param interceptor */ public void addInterceptor(InterceptorData interceptor) { if (interceptors == null) { interceptors = new LinkedList<InterceptorData>(); } interceptors.offer(interceptor); } public Collection<InterceptorData> getInterceptors() { return interceptors; } public BeanHandler getHandler() { return handler; } public void setHandler(BeanHandler handler) { this.handler = handler; } }
package infovis.gui; import static infovis.data.BusTime.*; import infovis.ctrl.BusVisualization; import infovis.ctrl.Controller; import infovis.data.BusStation; import infovis.data.BusTime; import infovis.embed.Embedders; import infovis.routing.RoutingAlgorithm; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Comparator; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** * A control panel to access the controller via GUI. * * @author Joschi <josua.krause@googlemail.com> */ public final class ControlPanel extends JPanel implements BusVisualization { /** SVUID. */ private static final long serialVersionUID = 1644268841480928696L; /** The station box. */ protected final JComboBox box; /** The bus start time hours. */ protected final JSpinner startHours; /** The bus start time minutes. */ protected final JSpinner startMinutes; /** The last start minute time (used for changing the hours). */ protected int lastStartMin = -1; /** The bus time label. */ private final JLabel btLabel; /** The check box to select now as start time. */ protected final JCheckBox now; /** Bus change time spinner. */ protected final JSpinner changeMinutes; /** Bus change time slider. */ protected final JSlider changeMinutesSlider; /** The time window spinner. */ protected final JSpinner timeWindow; /** The time windows slider. */ protected final JSlider timeWindowSlider; /** Walk time in hours. */ protected final JSpinner timeWalkHours; /** Walk time in minutes. */ protected final JSpinner timeWalkMinutes; /** Walk time slider. */ protected final JSlider timeWalkSlider; /** Minutes for the last walk. */ protected int lastWalkMin = -1; /** Maps bus station ids to indices in the combo box. */ private final int[] indexMap; /** The algorithm box. */ protected final JComboBox algoBox; /** The technique box. */ protected final JComboBox embedBox; /** * A thin wrapper for the bus station name. Also allows the <code>null</code> * bus station, representing no selection. * * @author Joschi <josua.krause@googlemail.com> */ private static final class BusStationName { /** The associated bus station. */ public final BusStation station; /** The name of the station. */ private final String name; /** * Creates a bus station name object. * * @param station The station. */ public BusStationName(final BusStation station) { this.station = station; name = station != null ? station.getName() : "(no selection)"; } @Override public String toString() { return name; } } /** * Creates a list of all bus station names. * * @param ctrl The controller. * @return All bus station names. */ private static BusStationName[] getStations(final Controller ctrl) { final Collection<BusStation> s = ctrl.getStations(); final BusStation[] arr = s.toArray(new BusStation[s.size()]); Arrays.sort(arr, new Comparator<BusStation>() { @Override public int compare(final BusStation a, final BusStation b) { return a.getName().compareTo(b.getName()); } }); final BusStationName[] res = new BusStationName[arr.length + 1]; res[0] = new BusStationName(null); for(int i = 0; i < arr.length; ++i) { res[i + 1] = new BusStationName(arr[i]); } return res; } /** * Cyclic mouse wheel listener that corresponds to a JSpinner. Increases / * descreases the spinner value depending on the direction of the mousewheel * movement. * * @author Marc Spicker */ private class CyclicMouseWheelListener implements MouseWheelListener { /** Parent spinner. */ final JSpinner parent; /** * Constructor. * * @param parent The parent spinner. */ public CyclicMouseWheelListener(final JSpinner parent) { this.parent = parent; } @Override public void mouseWheelMoved(final MouseWheelEvent e) { if(e.getWheelRotation() < 0) { parent.setValue(parent.getNextValue()); } else { parent.setValue(parent.getPreviousValue()); } } } /** * Mouse wheel listener that corresponds to a JSpinner. Increases / descreases * the spinner value depending on the direction of the mousewheel movement. * * @author Marc Spicker */ private class SimpleMouseWheelListener implements MouseWheelListener { /** Parent spinner. */ final JSpinner parent; /** Minimum value. */ final int minVal; /** Maximum value. */ final int maxVal; /** * Constructor. * * @param parent Corresponding spinner. * @param minVal Minimum value. * @param maxVal Maximum value. */ public SimpleMouseWheelListener(final JSpinner parent, final int minVal, final int maxVal) { this.parent = parent; this.minVal = minVal; this.maxVal = maxVal; } @Override public void mouseWheelMoved(final MouseWheelEvent e) { if(e.getWheelRotation() < 0) { if(!parent.getValue().equals(maxVal)) { parent.setValue(parent.getNextValue()); } } else { if(!parent.getValue().equals(minVal)) { parent.setValue(parent.getPreviousValue()); } } } } /** * Creates a control panel. * * @param ctrl The corresponding controller. */ public ControlPanel(final Controller ctrl) { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); final Component space = Box.createRigidArea(new Dimension(5, 5)); // routing selection final RoutingAlgorithm[] algos = Controller.getRoutingAlgorithms(); if(algos.length != 1) { algoBox = new JComboBox(algos); algoBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final RoutingAlgorithm routing = (RoutingAlgorithm) algoBox.getSelectedItem(); if(routing != ctrl.getRoutingAlgorithm()) { ctrl.setRoutingAlgorithm(routing); } } }); algoBox.setMaximumSize(algoBox.getPreferredSize()); addHor(new JLabel("Routing:"), algoBox); } else { algoBox = null; } // embedder selection final Embedders[] embeds = Controller.getEmbedders(); if(embeds.length != 1) { embedBox = new JComboBox(embeds); embedBox.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent ae) { final Embedders e = (Embedders) embedBox.getSelectedItem(); if(e != ctrl.getEmbedder()) { ctrl.setEmbedder(e); } } }); final Dimension size = embedBox.getPreferredSize(); embedBox.setMaximumSize(new Dimension(200, size.height)); addHor(new JLabel("Positioning:"), embedBox); } else { embedBox = null; } // station selection final BusStationName[] stations = getStations(ctrl); indexMap = new int[ctrl.maxId() + 1]; for(int i = 0; i < stations.length; ++i) { if(stations[i].station == null) { continue; } indexMap[stations[i].station.getId()] = i; } box = new JComboBox(stations); box.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final BusStation station = ((BusStationName) box.getSelectedItem()).station; if(station != ctrl.getSelectedStation()) { ctrl.selectStation(station); ctrl.focusStation(); } } }); box.setMaximumSize(box.getPreferredSize()); addHor(new JLabel("Stations:"), box); add(new JSeparator(SwingConstants.HORIZONTAL)); // start time final CyclicNumberModel hours = new CyclicNumberModel(0, 0, 23); startHours = new JSpinner(hours); startHours.setMaximumSize(new Dimension(60, 40)); startHours.setPreferredSize(new Dimension(60, 40)); startHours.addMouseWheelListener(new CyclicMouseWheelListener(startHours)); final CyclicNumberModel minutes = new CyclicNumberModel(0, 0, 59); startMinutes = new JSpinner(minutes); startMinutes.setMaximumSize(new Dimension(60, 40)); startMinutes.setPreferredSize(new Dimension(60, 40)); startMinutes.addMouseWheelListener(new CyclicMouseWheelListener(startMinutes)); startHours.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { final BusTime startTime = getStartTime(); if(!ctrl.getTime().equals(startTime)) { ctrl.setTime(startTime); } } }); startMinutes.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { final BusTime startTime = getStartTime(); if(ctrl.getTime().equals(startTime)) return; if(lastStartMin == 59 && startMinutes.getValue().equals(0)) { startHours.setValue(startHours.getNextValue()); } else if(lastStartMin == 0 && startMinutes.getValue().equals(59)) { startHours.setValue(startHours.getPreviousValue()); } ctrl.setTime(getStartTime()); lastStartMin = startTime.getMinute(); } }); btLabel = new JLabel(); now = new JCheckBox("now"); now.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { final boolean b = ctrl.isStartTimeNow(); if(now.isSelected()) { if(!b) { ctrl.setNow(); } } else { if(b) { ctrl.setTime(getStartTime()); } } } }); addHor(new JLabel("Start Time:"), startHours, startMinutes, btLabel, now, space); add(new JSeparator(SwingConstants.HORIZONTAL)); // change time changeMinutesSlider = new JSlider(-5, 60, 0); changeMinutesSlider.setMajorTickSpacing(20); changeMinutesSlider.setMinorTickSpacing(5); changeMinutesSlider.setPaintTicks(true); changeMinutesSlider.setPaintLabels(true); changeMinutesSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { final int changeTime = changeMinutesSlider.getValue(); if(changeTime != ctrl.getChangeTime()) { changeMinutes.setValue(changeTime); ctrl.setChangeTime(changeTime); } } }); final SpinnerNumberModel cMinutes = new SpinnerNumberModel(0, -5, 60, 1); changeMinutes = new JSpinner(cMinutes); changeMinutes.setMaximumSize(new Dimension(60, 40)); changeMinutes.setPreferredSize(new Dimension(60, 40)); changeMinutes.addMouseWheelListener(new SimpleMouseWheelListener(changeMinutes, -5, 60)); changeMinutes.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { final int changeTime = getChangeTime(); if(changeTime != ctrl.getChangeTime()) { changeMinutesSlider.setValue(changeTime); ctrl.setChangeTime(getChangeTime()); } } }); addHor(new JLabel("Change Time:"), changeMinutes, new JLabel("min"), changeMinutesSlider, space); add(new JSeparator(SwingConstants.HORIZONTAL)); // time window final SpinnerNumberModel tWindow = new SpinnerNumberModel(0, 0, 24, 1); timeWindow = new JSpinner(tWindow); timeWindow.setMaximumSize(new Dimension(60, 40)); timeWindow.setPreferredSize(new Dimension(60, 40)); timeWindow.addMouseWheelListener(new SimpleMouseWheelListener(timeWindow, 0, 24)); timeWindow.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { final int time = (Integer) timeWindow.getValue(); if(ctrl.getMaxTimeHours() != time) { timeWindowSlider.setValue(time); ctrl.setMaxTimeHours(time); } } }); timeWindowSlider = new JSlider(0, 24, 0); timeWindowSlider.setMajorTickSpacing(3); timeWindowSlider.setMinorTickSpacing(1); timeWindowSlider.setPaintTicks(true); timeWindowSlider.setPaintLabels(true); timeWindowSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { final int time = timeWindowSlider.getValue(); if(time != ctrl.getMaxTimeHours()) { timeWindow.setValue(time); ctrl.setMaxTimeHours(time); } } }); addHor(new JLabel("Max Wait:"), timeWindow, new JLabel("h"), timeWindowSlider, space); add(new JSeparator(SwingConstants.HORIZONTAL)); // walk time window final SpinnerNumberModel walkHours = new SpinnerNumberModel(0, 0, 1, 1); timeWalkHours = new JSpinner(walkHours); timeWalkHours.setMaximumSize(new Dimension(60, 40)); timeWalkHours.setPreferredSize(new Dimension(60, 40)); timeWalkHours.addMouseWheelListener(new SimpleMouseWheelListener(timeWalkHours, 0, 1)); final CyclicNumberModel walkMinutes = new CyclicNumberModel(0, 0, 59); timeWalkMinutes = new JSpinner(walkMinutes); timeWalkMinutes.setMaximumSize(new Dimension(60, 40)); timeWalkMinutes.setPreferredSize(new Dimension(60, 40)); timeWalkMinutes.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(final MouseWheelEvent e) { if(e.getWheelRotation() < 0) { if(!(timeWalkHours.getValue().equals(1) && timeWalkMinutes.getValue().equals(59))) { timeWalkMinutes.setValue(timeWalkMinutes.getNextValue()); } } else { if(!(timeWalkHours.getValue().equals(0) && timeWalkMinutes.getValue().equals(0))) { timeWalkMinutes.setValue(timeWalkMinutes.getPreviousValue()); } } } }); timeWalkHours.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { final int walkTime = getWalkTime(); if(!(ctrl.getWalkTime() == walkTime)) { timeWalkSlider.setValue(walkTime); ctrl.setWalkTime(walkTime); } } }); timeWalkMinutes.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { if(lastWalkMin % 60 == 59 && timeWalkMinutes.getValue().equals(0)) { if(timeWalkHours.getValue().equals(1)) { timeWalkMinutes.setValue(59); } timeWalkHours.setValue(timeWalkHours.getNextValue()); } else if(lastWalkMin % 60 == 0 && timeWalkMinutes.getValue().equals(59)) { timeWalkHours.setValue(timeWalkHours.getPreviousValue()); } final int walkTime = getWalkTime(); if(ctrl.getWalkTime() != walkTime) { ctrl.setWalkTime(getWalkTime()); } timeWalkSlider.setValue(getWalkTime()); lastWalkMin = walkTime; } }); timeWalkSlider = new JSlider(0, 119, 0); timeWalkSlider.setMajorTickSpacing(20); timeWalkSlider.setMinorTickSpacing(5); timeWalkSlider.setPaintTicks(true); timeWalkSlider.setPaintLabels(true); timeWalkSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent e) { final int walkTime = timeWalkSlider.getValue(); if(ctrl.getWalkTime() != walkTime) { timeWalkHours.setValue(walkTime / 60); timeWalkMinutes.setValue(walkTime % 60); ctrl.setWalkTime(walkTime); } } }); addHor(new JLabel("Max Walk:"), timeWalkHours, timeWalkMinutes, new JLabel("h"), timeWalkSlider, space); // end of layout add(Box.createVerticalGlue()); ctrl.addBusVisualization(this); } /** * A cyclic number spinner for a JSpinner. * * @author Marc Spicker */ private class CyclicNumberModel extends SpinnerNumberModel { /** * Serial version ID. */ private static final long serialVersionUID = 3042013777179841232L; /** * Constructor. * * @param value Initial value. * @param min Minimum. * @param max Maximum. */ public CyclicNumberModel(final int value, final int min, final int max) { super(value, min, max, 1); } @Override public Object getNextValue() { if(super.getValue().equals(super.getMaximum())) return super.getMinimum(); return super.getNextValue(); } @Override public Object getPreviousValue() { if(super.getValue().equals(super.getMinimum())) return super.getMaximum(); return super.getPreviousValue(); } @Override public Object getValue() { return super.getValue(); } } /** * Returns the start time that is currently entered in the two spinners. * * @return The current bus starting time. */ protected BusTime getStartTime() { final int hour = ((Integer) startHours.getValue()).intValue(); final int minute = ((Integer) startMinutes.getValue()).intValue(); return new BusTime(hour, minute); } /** * Returns the walk time that is currently entered in the two spinners. * * @return The current walk time. */ protected int getWalkTime() { final int hour = ((Integer) timeWalkHours.getValue()).intValue(); final int minute = ((Integer) timeWalkMinutes.getValue()).intValue(); return hour * 60 + minute; } /** * Returns the change time that is currently entered in the two spinners. * * @return The current bus change time. */ protected int getChangeTime() { return ((Integer) changeMinutes.getValue()).intValue(); } /** * Adds a number of components to the panel. * * @param comps The components to add. */ private void addHor(final Component... comps) { final JPanel hor = new JPanel(); hor.setLayout(new BoxLayout(hor, BoxLayout.X_AXIS)); for(final Component c : comps) { hor.add(Box.createRigidArea(new Dimension(5, 5))); if(c != null) { hor.add(c); } } hor.setAlignmentX(Component.LEFT_ALIGNMENT); add(hor); } @Override public void selectBusStation(final BusStation station) { box.setSelectedIndex(station != null ? indexMap[station.getId()] : 0); } @Override public void setStartTime(final BusTime time) { if(time == null) { startHours.setEnabled(false); startMinutes.setEnabled(false); now.setSelected(true); final Calendar cal = Calendar.getInstance(); btLabel.setText(BusTime.fromCalendar(cal).pretty(isBlinkSecond(cal))); return; } startHours.setEnabled(true); startMinutes.setEnabled(true); now.setSelected(false); startHours.setValue(time.getHour()); startMinutes.setValue(time.getMinute()); btLabel.setText(time.pretty()); } @Override public void overwriteDisplayedTime(final BusTime time, final boolean blink) { btLabel.setText(time.pretty(blink)); } @Override public void setChangeTime(final int minutes) { changeMinutes.setValue(minutes); changeMinutesSlider.setValue(minutes); } @Override public void setEmbedder(final Embedders embed) { if(embedBox != null) { embedBox.setSelectedItem(embed); } } @Override public void undefinedChange(final Controller ctrl) { final int mth = ctrl.getMaxTimeHours(); timeWindow.setValue(mth); timeWindowSlider.setValue(mth); final int walkTime = ctrl.getWalkTime(); timeWalkHours.setValue(walkTime / 60); timeWalkMinutes.setValue(walkTime % 60); timeWalkSlider.setValue(walkTime); if(algoBox != null) { algoBox.setSelectedItem(ctrl.getRoutingAlgorithm()); } } @Override public void focusStation() { // already covered by select bus station } }
package org.made.neohabitat.mods; import org.elkoserver.foundation.json.JSONMethod; import org.elkoserver.foundation.json.OptBoolean; import org.elkoserver.foundation.json.OptInteger; import org.elkoserver.json.EncodeControl; import org.elkoserver.json.JSONLiteral; import org.elkoserver.server.context.User; import org.made.neohabitat.Copyable; import org.made.neohabitat.HabitatMod; /** * Habitat Key Mod (attached to an Elko Item.) * * A Key has a code-number that unlocks objects with the matching code. The only * way to use it is for the Avatar to be holding (slot:HANDS) and pointing at * the object and using the appropriate verb. Any lock/unlock operation will be * a side effect on the pointed object. For example, a Bag's OPENCONTAINER * operation will test any Key while attempting to open it. * * @author randy * */ public class Key extends HabitatMod implements Copyable { public int HabitatClass() { return CLASS_KEY; } public String HabitatModName() { return "Key"; } public int capacity() { return 0; } public int pc_state_bytes() { return 2; }; public boolean known() { return true; } public boolean opaque_container() { return false; } public boolean filler() { return false; } /** * Least significant byte in a 16 bit value to match against a lock in order * to lock/unlock the item. */ public int key_number_lo = 0; /** * Most significant byte in a 16 bit value to match against a lock in order * to lock/unlock the item. */ public int key_number_hi = 0; @JSONMethod({ "style", "x", "y", "orientation", "gr_state", "restricted", "key_number_lo", "key_number_hi" }) public Key(OptInteger style, OptInteger x, OptInteger y, OptInteger orientation, OptInteger gr_state, OptBoolean restricted, OptInteger key_number_lo, OptInteger key_number_hi) { super(style, x, y, orientation, gr_state, restricted); setKeyState (key_number_lo.value(0), key_number_hi.value(0)); } public Key(int style, int x, int y, int orientation, int gr_state, boolean restricted, int key_number_lo, int key_number_hi) { super(style, x, y, orientation, gr_state, restricted); setKeyState (key_number_lo, key_number_hi); } protected void setKeyState (int key_number_lo, int key_number_hi) { this.key_number_lo = key_number_lo; this.key_number_hi = key_number_hi; } @Override public HabitatMod copyThisMod() { return new Key(style, x, y, orientation, gr_state, restricted, key_number_lo, key_number_hi); } @Override public JSONLiteral encode(EncodeControl control) { JSONLiteral result = super.encodeCommon(new JSONLiteral(HabitatModName(), control)); if (0 != key_number_lo) { result.addParameter("key_number_lo", key_number_lo); } if (0 != key_number_hi) { result.addParameter("key_number_hi", key_number_hi); } result.finish(); return result; } /** * Verb (Generic): Pick this item up. * * @param from * User representing the connection making the request. */ @JSONMethod public void GET(User from) { generic_GET(from); } /** * Verb (Generic): Put this item into some container or on the ground. * * @param from * User representing the connection making the request. * @param containerNoid * The Habitat Noid for the target container THE_REGION is * default. * @param x * If THE_REGION is the new container, the horizontal position. * Otherwise ignored. * @param y * If THE_REGION: the vertical position, otherwise the target * container slot (e.g. HANDS/HEAD or other.) * @param orientation * The new orientation for the object being PUT. */ @JSONMethod({ "containerNoid", "x", "y", "orientation" }) public void PUT(User from, OptInteger containerNoid, OptInteger x, OptInteger y, OptInteger orientation) { generic_PUT(from, containerNoid.value(THE_REGION), x.value(avatar(from).x), y.value(avatar(from).y), orientation.value(avatar(from).orientation)); } /** * Verb (Generic): Throw this across the Region * * @param from * User representing the connection making the request. * @param x * Destination horizontal position * @param y * Destination vertical position (lower 7 bits) */ @JSONMethod({ "target", "x", "y" }) public void THROW(User from, int target, int x, int y) { generic_THROW(from, target, x, y); } /** * Return a string describing the key number. * * @param key * Key mod containing the key number. */ public String key_vendo_info(Key key) { return ("Key #" + ( key.key_number_hi * 256 + key.key_number_lo ) + "."); } }
package javaschool.app; import asg.cliche.Command; import asg.cliche.Shell; import asg.cliche.ShellDependent; import asg.cliche.ShellFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class PhoneBook implements ShellDependent { private List<Record> list = new ArrayList<>(); private Shell theShell; @Override public void cliSetShell(Shell theShell) { this.theShell = theShell; } @Command(description = "Add a new person") public void addPerson(String name) { list.add(new Person(name)); } @Command(description = "Add a new note") public void addNote(String name) { list.add(new Note(name)); } @Command(description = "Edit a record by id") public void edit(Integer id) throws IOException { Optional<Record> result = lookup(id); if (result.isPresent()) { Record record = result.get(); ShellFactory.createSubshell(record.getName(), theShell, "Editing " + record.getName(), result) .commandLoop(); } else { System.out.printf("Record with id \"%d\" not found.\n", id); } } @Command public List<Record> list() { return list; } @Command public void clear() { list.clear(); } @Command(description = "Search in records") public List<Record> search(String criteria) { return list.stream().filter((r) -> r.contains(criteria.toLowerCase())).collect(Collectors.toList()); } private Optional<Record> lookup(Integer id) { return list.stream().filter((r) -> r.getId().equals(id)).findFirst(); } }
package org.myrobotlab.service; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.LoggingFactory; import org.slf4j.Logger; import org.myrobotlab.service.interfaces.ServoControl; public class Intro extends Service { private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(Intro.class); public Intro(String n, String id) { super(n, id); } /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(Intro.class); meta.addDescription("Introduction to MyRobotlab"); meta.setAvailable(true); meta.addCategory("general"); meta.addPeer("servo", "Servo", "servo"); meta.addPeer("controller", "Arduino", "Arduino controller for this servo"); return meta; } public static void main(String[] args) { try { LoggingFactory.init(Level.INFO); Runtime.start("intro", "Intro"); Runtime.start("servo", "Servo"); Runtime.start("gui", "SwingGui"); } catch (Exception e) { log.error("main threw", e); } } transient ServoControl servo; boolean isServoActivated = false; public boolean isServoActivated() { return isServoActivated; } public Servo startServo(String port) { return startServo(port, 3); } public Servo startServo(String port, int pin) { if (servo == null) { speakBlocking("starting servo"); isServoActivated = true; servo = (Servo) startPeer("servo"); if (port != null) { try { speakBlocking(port); Arduino controller = (Arduino) startPeer("controller"); controller.connect(port); controller.attach(controller, pin); } catch (Exception e) { error(e); } } } return servo; } public void stopServo() { speakBlocking("stopping servo"); releasePeer("servo"); isServoActivated = false; } }
package net.amigocraft.pore; import net.amigocraft.pore.implementation.PoreServer; import org.bukkit.Bukkit; import org.spongepowered.api.event.Event; import org.spongepowered.api.event.SpongeEventHandler; import org.spongepowered.api.event.state.SpongeInitializationEvent; import org.spongepowered.api.event.state.SpongeServerStoppingEvent; import org.spongepowered.api.plugin.Plugin; @Plugin(id = "Pore", name = "Pore") public class Main { private PoreServer server; @SpongeEventHandler public void onInitialization(SpongeInitializationEvent event) { server = new PoreServer(((Event)event).getGame()); Bukkit.setServer(server); //Set the Bukkit API to use our server instance System.out.println("[Pore] Loading Bukkit plugins, please wait..."); // Load plugins server.loadPlugins(); server.enablePlugins(); System.out.println("[Pore] Finished loading Bukkit plugins!"); System.out.println("Enabling loaded plugins..."); } @SpongeEventHandler public void onShutdown(SpongeServerStoppingEvent event){ // clear static references server.disablePlugins(); server = null; } }
package org.nkjmlab.gis.datum; import java.text.NumberFormat; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * * * * @author nkjm * */ public class LatLon { protected final double lat; protected final double lon; protected final Unit unit; protected final Detum detum; public enum Unit { DEGREE, MILLI_DEGREE, DMS, SECOND } public enum Detum { TOKYO, WGS84 } protected LatLon(double lat, double lon, Unit unit, Detum detum) { this.lat = lat; this.lon = lon; this.unit = unit; this.detum = detum; } public LatLon(double lat, double lon, Basis basis) { this(lat, lon, basis.getUnit(), basis.getDetum()); } public Unit getUnit() { return this.unit; } public Detum getDetum() { return this.detum; } @Override public boolean equals(Object obj) { if (!(obj instanceof LatLon)) { return false; } LatLon l = (LatLon) obj; return this.lat == l.lat && this.lon == l.lon && this.unit == l.unit && this.detum == l.detum; } @Override public int hashCode() { return (int) (lat + lon); } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } public String toSimpleString() { NumberFormat format = NumberFormat.getInstance(); format.setGroupingUsed(false); format.setMaximumFractionDigits(2); return format.format(lat) + "," + format.format(lon) + "," + unit + "," + detum; } /** * * * @return */ public double getLat() { return lat; } /** * * * @return */ public double getLon() { return lon; } /** * * * @param basis * * @return */ public double getLat(Basis basis) { return getLat(basis.getUnit(), basis.getDetum()); } /** * * * @param basis * * @return */ public double getLon(Basis basis) { return getLon(basis.getUnit(), basis.getDetum()); } /** * * * @return */ public double getLat(Unit toUnit, Detum toDetum) { return BasisConverter.changeBasisOfLat(lat, lon, this.unit, this.detum, toUnit, toDetum); } /** * * * @return */ public double getLon(Unit toUnit, Detum toDetum) { return BasisConverter.changeBasisOfLon(lat, lon, this.unit, this.detum, toUnit, toDetum); } /** * * * @return */ public double getLon(Unit toUnit) { return BasisConverter.changeBasisOfLon(lat, lon, this.unit, this.detum, toUnit, this.detum); } /** * * * @return */ public double getLat(Unit toUnit) { return BasisConverter.changeBasisOfLat(lat, lon, this.unit, this.detum, toUnit, this.detum); } /** * * * @return */ public double getLat(Detum toDetum) { return BasisConverter.changeBasisOfLat(lat, lon, this.unit, this.detum, this.unit, toDetum); } /** * * * @return */ public double getLon(Detum toDetum) { return BasisConverter.changeBasisOfLon(lat, lon, this.unit, this.detum, this.unit, toDetum); } public LatLon copyOn(Basis toBasis) { return BasisConverter.changeBasis(lat, lon, getBasis(), toBasis); } public Basis getBasis() { return new Basis(unit, detum); } /** * toLatLon * * @param toLatLon * @return */ public double distance(LatLon toLatLon) { return Math.abs(lat - toLatLon.getLat(getBasis()) + lon - toLatLon.getLon(getBasis())); } /** * toLatLon * * @param toLatLon * @return */ public double distance(LatLon toLatLon, Unit toUnit) { return LatLonUnitConverter.change(distance(toLatLon), getUnit(), toUnit); } }
package ninja.joshdavis; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.File; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map.Entry; /** * Main window manager * */ public class AppFrame extends JFrame { private FileListPane srcFileListPane; private FileListPane destFileListPane; private Editor editor; private TextField searchInput; private TextField replaceInput; private JButton dirBrowseButton; private JFileChooser dirChooser; private File currentDir; private TextField currentDirInput; private JCheckBox showHidden; private JCheckBox globalSearch; private JCheckBox caseInsensitiveSearch; private JCheckBox regexSearch; private JButton alterFiles; private LinkedHashMap<File,File> renameMap; private class InputListener implements ActionListener { public void actionPerformed(ActionEvent ev) { updateEditor(); updateFilePanes(); } } private class DirChooserListener implements ActionListener { public void actionPerformed(ActionEvent ev) { dirChooser.setFileHidingEnabled(!showHidden.isSelected()); dirChooser.showDialog(AppFrame.this, null); File file = dirChooser.getSelectedFile(); if(file != null) { setCurrentDir(file); } } } private class AlterFilesListener implements ActionListener { public void actionPerformed(ActionEvent ev) { int confirmOption = JOptionPane.showConfirmDialog(null, "Confirm file modifications?", "Are you sure?", JOptionPane.OK_CANCEL_OPTION); if(confirmOption == JOptionPane.OK_OPTION) { for(Entry<File,File> entry: renameMap.entrySet()) { entry.getKey().renameTo(entry.getValue()); } searchInput.setText(""); replaceInput.setText(""); updateEditor(); updateFilePanes(); } } } private void updateEditor() { String searchInputString = searchInput.getText(); String replaceInputString = replaceInput.getText(); //TODO: sanitize inputs editor.setSearchString(searchInputString); editor.setReplaceString(replaceInputString); editor.setGlobalSearch(globalSearch.isSelected()); editor.setCaseInsensitiveSearch(caseInsensitiveSearch.isSelected()); editor.setLiteralSearch(!regexSearch.isSelected()); } private void updateRenameMap() { renameMap.clear(); File[] allFiles = currentDir.listFiles(); for(File srcFile: allFiles) { if( !srcFile.isHidden() || showHidden.isSelected() ) { String destName = editor.edit(srcFile.getName()); if(destName != null && !destName.isEmpty()) { File destFile = new File(currentDir,destName); renameMap.put(srcFile,destFile); } } } } private void updateFilePanes() { updateRenameMap(); String srcText = ""; String destText = ""; for(Entry<File,File> entry: renameMap.entrySet()) { srcText = srcText + entry.getKey().getName() + "\n"; destText = destText + entry.getValue().getName() + "\n"; } srcFileListPane.setText(srcText); destFileListPane.setText(destText); } private void setCurrentDir(File file) { if(file.exists() && file.isDirectory()) { currentDir = file; currentDirInput.setText(file.getAbsolutePath()); updateFilePanes(); } } public AppFrame() { super("Remoniker"); setLayout(new FlowLayout()); srcFileListPane = new FileListPane(); addWithTitledBorder(srcFileListPane, "Files"); destFileListPane = new FileListPane(); addWithTitledBorder(destFileListPane, "Preview"); editor = new Editor(); currentDirInput = new TextField(20); add(currentDirInput); dirChooser = new JFileChooser(); dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); ActionListener dirChooserListener = new DirChooserListener(); dirBrowseButton = new JButton("Browse"); dirBrowseButton.addActionListener(dirChooserListener); add(dirBrowseButton); ActionListener inputListener = new InputListener(); searchInput = addNewTextField("Search", inputListener); replaceInput = addNewTextField("Replace", inputListener); showHidden = new JCheckBox("Show hidden files"); showHidden.addActionListener(inputListener); add(showHidden); globalSearch = new JCheckBox("Global search"); globalSearch.addActionListener(inputListener); add(globalSearch); caseInsensitiveSearch = new JCheckBox("Case insensitive"); caseInsensitiveSearch.addActionListener(inputListener); add(caseInsensitiveSearch); regexSearch = new JCheckBox("Use regular expressions"); regexSearch.addActionListener(inputListener); add(regexSearch); alterFiles = new JButton("Rename files"); add(alterFiles); ActionListener alterFilesListener = new AlterFilesListener(); alterFiles.addActionListener(alterFilesListener); renameMap = new LinkedHashMap<File,File>(); setCurrentDir(new File(System.getProperty("user.home"))); } private void addWithTitledBorder(Component comp, String title) { JPanel pane = new JPanel(); pane.setBorder(BorderFactory.createTitledBorder(title)); pane.add(comp); add(pane); } private TextField addNewTextField(String title, ActionListener listener) { TextField res = new TextField(20); res.addActionListener(listener); addWithTitledBorder(res,title); return res; } }
package org.opennars.io; import com.google.common.io.Resources; import org.opennars.interfaces.pub.Reasoner; import org.opennars.main.Parameters; import org.opennars.main.MiscFlags; import org.opennars.plugin.Plugin; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.nio.file.Path; import java.nio.file.Paths; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; public class ConfigReader { public static List<Plugin> loadParamsFromFileAndReturnPlugins(final String filepath, final Reasoner reasoner, final Parameters parameters) throws IOException, IllegalAccessException, ParseException, ParserConfigurationException, SAXException, ClassNotFoundException, NoSuchMethodException, InstantiationException, InvocationTargetException { System.out.println("Got relative path for loading the config: " + filepath); List<Plugin> ret = new ArrayList<Plugin>(); File file = null; File classPath = null; try { classPath = new File(ConfigReader.class.getProtectionDomain().getCodeSource().getLocation().toURI()); } catch (URISyntaxException e) {} // we need to walk two levels down ("./target/classes") File absolutePathOfRoot = null; try { absolutePathOfRoot = new File(new File(classPath.getParent()).getParent()); } catch (NullPointerException e) {} // walk to convert it to absolute path file = new File(absolutePathOfRoot, filepath); InputStream stream = null; // if this failed, then load from resources if(!file.exists()) { file = null; URL n = Resources.getResource("config/defaultConfig.xml"); /* try { file = new File(n.toURI()); } catch (URISyntaxException ex) { Logger.getLogger(ConfigReader.class.getName()).log(Level.SEVERE, null, ex); } */ /* try { System.out.println(n.toURI().toString()); } catch (URISyntaxException ex) { // Logger.getLogger(ConfigReader.class.getName()).log(Level.SEVERE, null, ex); } */ ClassLoader classloader = ConfigReader.class.getClassLoader(); try { System.out.println(n.toURI().toString()); URLConnection connection = n.openConnection(); stream = connection.getInputStream(); //file = new File(classloader.getResource(filepath).toURI()); // commented because it is old way //stream = classloader.getResourceAsStream(n.toURI().toString()); } catch (URISyntaxException ex) { Logger.getLogger(ConfigReader.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(stream != null); System.out.println("Loading config " + "config/defaultConfig.xml" +" from resources"); } else { System.out.println("Loading config " + file.getName() +" from file"); } final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); final Document document = stream != null ? documentBuilder.parse(stream) : documentBuilder.parse(file); final NodeList config = document.getElementsByTagName("config").item(0).getChildNodes(); for (int iterationConfigIdx = 0; iterationConfigIdx < config.getLength(); iterationConfigIdx++) { final Node iConfig = config.item(iterationConfigIdx); if (iConfig.getNodeType() != Node.ELEMENT_NODE) { continue; } final String nodeName = iConfig.getNodeName(); if( nodeName.equals("plugins") ) { final NodeList plugins = iConfig.getChildNodes(); for (int iterationPluginIdx = 0; iterationPluginIdx < plugins.getLength(); iterationPluginIdx++) { final Node iPlugin = plugins.item(iterationPluginIdx); if (iPlugin.getNodeType() != Node.ELEMENT_NODE) { continue; } final String pluginClassPath = iPlugin.getAttributes().getNamedItem("classpath").getNodeValue(); final NodeList arguments = iPlugin.getChildNodes(); Plugin createdPlugin = createPluginByClassnameAndArguments(pluginClassPath, arguments, reasoner); ret.add(createdPlugin); } } else { final String propertyName = iConfig.getAttributes().getNamedItem("name").getNodeValue(); final String propertyValueAsString = iConfig.getAttributes().getNamedItem("value").getNodeValue(); boolean wasConfigValueAssigned = false; try { final Field fieldOfProperty = Parameters.class.getField(propertyName); if (fieldOfProperty.getType() == int.class) { fieldOfProperty.set(parameters, Integer.parseInt(propertyValueAsString)); } else if (fieldOfProperty.getType() == float.class) { fieldOfProperty.set(parameters, Float.parseFloat(propertyValueAsString)); } else if (fieldOfProperty.getType() == double.class) { fieldOfProperty.set(parameters, Double.parseDouble(propertyValueAsString)); } else if (fieldOfProperty.getType() == boolean.class) { fieldOfProperty.set(parameters, Boolean.parseBoolean(propertyValueAsString)); } else { throw new ParseException("Unknown type", 0); } wasConfigValueAssigned = true; } catch (NoSuchFieldException e) { // ignore } if (!wasConfigValueAssigned) { try { final Field fieldOfProperty = MiscFlags.class.getDeclaredField(propertyName); if (fieldOfProperty.getType() == int.class) { fieldOfProperty.set(null, Integer.parseInt(propertyValueAsString)); } else if (fieldOfProperty.getType() == float.class) { fieldOfProperty.set(null, Float.parseFloat(propertyValueAsString)); } else { throw new ParseException("Unknown type", 0); } wasConfigValueAssigned = true; } catch (NoSuchFieldException e) { // ignore } } } } return ret; } private static Plugin createPluginByClassnameAndArguments(String pluginClassPath, NodeList arguments, Reasoner reasoner) throws ParseException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { List<Class> types = new ArrayList<>(); List<Object> values = new ArrayList<>(); for (int parameterIdx = 0; parameterIdx < arguments.getLength(); parameterIdx++) { final Node iParameter = arguments.item(parameterIdx); if (iParameter.getNodeType() != Node.ELEMENT_NODE) { continue; } String typeString = null; String valueString = null; final boolean specialIsReasoner = iParameter.getAttributes().getNamedItem("isReasoner") != null; if (!specialIsReasoner) { typeString = iParameter.getAttributes().getNamedItem("type").getNodeValue(); valueString = iParameter.getAttributes().getNamedItem("value").getNodeValue(); } if (specialIsReasoner) { types.add(Reasoner.class); values.add(reasoner); } else if (typeString.equals("int.class")) { types.add(int.class); values.add(Integer.parseInt(valueString)); } else if (typeString.equals("float.class")) { types.add(float.class); values.add(Float.parseFloat(valueString)); } else if (typeString.equals("boolean.class")) { types.add(boolean.class); values.add(Boolean.parseBoolean(valueString)); } else if (typeString.equals("String.class")) { types.add(java.lang.String.class); values.add(valueString); } else { throw new ParseException("Unknown type", 0); } } Class[] typesAsArr = types.toArray(new Class[types.size()]); Object[] valuesAsArr = values.toArray(new Object[values.size()]); Class c = Class.forName(pluginClassPath); Plugin createdPlugin = (Plugin)c.getConstructor(typesAsArr).newInstance(valuesAsArr); return createdPlugin; } }
package org.osiam.client.query; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.osiam.client.exception.InvalidAttributeException; import org.osiam.client.query.metamodel.Attribute; import org.osiam.client.query.metamodel.Comparison; import org.osiam.resources.scim.Resource; /** * This class represents a query as it is run against the OSIAM service. * @deprecated See {@link org.osiam.client.nquery.Query} */ @Deprecated public class Query { private static final int DEFAULT_COUNT = 100; private static final int DEFAULT_INDEX = 1; private static final Pattern INDEX_PATTERN = Pattern.compile("startIndex=(\\d+)&?"); private static final Pattern COUNT_PATTERN = Pattern.compile("count=(\\d+)&?"); private final String queryString; private Matcher indexMatcher; private Matcher countMatcher; /** * @deprecated See {@link org.osiam.client.nquery.QueryBuilder} */ @Deprecated public Query(String queryString) { this.queryString = queryString; indexMatcher = INDEX_PATTERN.matcher(queryString); countMatcher = COUNT_PATTERN.matcher(queryString); } /** * Returns the number of items per page this query is configured for. If no explicit number was given, the default * number of items per page is returned, which is 100. * * @return The number of Items this Query is configured for. */ public int getCountPerPage() { if (queryStringContainsCount()) { return Integer.parseInt(countMatcher.group(1)); } return DEFAULT_COUNT; } /** * Returns the startIndex of this query. If no startIndex was set, it returns the default, which is 1. * * @return The startIndex of this query. */ public int getStartIndex() { if (queryStringContainsIndex()) { return Integer.parseInt(indexMatcher.group(1)); } return DEFAULT_INDEX; } /** * Create a new query that is moved forward in the result set by one page. * * @return A new query paged forward by one. */ public Query nextPage() { String nextIndex = "startIndex=" + (getCountPerPage() + getStartIndex()); if (queryStringContainsIndex()) { return new Query(indexMatcher.replaceFirst(nextIndex)); } return new Query(queryString + "&" + nextIndex); } public Query previousPage() { if(getStartIndex() <= DEFAULT_INDEX){ throw new IllegalStateException("StartIndex < " + DEFAULT_INDEX + " is not possible."); } int newIndex = getStartIndex() - getCountPerPage(); if (newIndex < DEFAULT_INDEX) { newIndex = DEFAULT_INDEX; } return new Query(indexMatcher.replaceFirst("startIndex=" + newIndex)); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || getClass() != other.getClass()) { return false; } Query query = (Query) other; return queryString.equals(query.queryString); } @Override public int hashCode() { return queryString.hashCode(); } /** * @return The query as a String that can be used in a web request. */ @Override public String toString() { return queryString; } private boolean queryStringContainsIndex() { return indexMatcher.find(0); } private boolean queryStringContainsCount() { return countMatcher.find(0); } /** * The Builder is used to construct instances of the {@link Query} */ public static final class Builder { private Class<? extends Resource> clazz; private String filter; private String sortBy; private SortOrder sortOrder; private int startIndex = DEFAULT_INDEX; private int countPerPage = DEFAULT_COUNT; /** * The Constructor of the QueryBuilder * * @param clazz The class of Resources to query for. */ public Builder(Class<? extends Resource> clazz) { this.clazz = clazz; } /** * Add a filter on the given Attribute. * * @param filter The filter of the attributes to filter on. * @return The Builder with this filter added. */ public Builder setFilter(Filter filter) { this.filter = filter.toString(); return this; } /** * Add a filter on the given Attribute. * * @param filter The filter of the attributes to filter on. * @return The Builder with this filter added. */ public Builder setFilter(String filter) { this.filter = filter; return this; } /** * Adds the given {@link SortOrder} to the query * * @param sortOrder The order in which to sort the result * @return The Builder with this sort order added. */ public Builder setSortOrder(SortOrder sortOrder) { this.sortOrder = sortOrder; return this; } /** * Add the start Index from where on the list will be returned to the query * * @param startIndex The position to use as the first entry in the result. * @return The Builder with this start Index added. */ public Builder setStartIndex(int startIndex) { this.startIndex = startIndex; return this; } /** * Add the number of wanted results per page to the query * * @param count The number of items displayed per page. * @return The Builder with this count per page added. */ public Builder setCountPerPage(int count) { countPerPage = count; return this; } /** * Add the wanted attribute names to the sortBy statement. * * @param attribute attributes to sort by the query * @return The Builder with sortBy added. */ public Builder setSortBy(Attribute attribute) { if (!isAttributeValid(attribute.toString())) { throw new InvalidAttributeException("Sorting for this attribute is not supported");//TODO } sortBy = attribute.toString(); return this; } /** * Build the query String to use against OSIAM. * * @return The query as a String */ public Query build() { StringBuilder builder = new StringBuilder(); if (filter != null) { try{ ensureQueryParamIsSeparated(builder); builder.append("filter=").append(URLEncoder.encode(filter, "UTF-8")); }catch(UnsupportedEncodingException e) { throw new RuntimeException(e); // NOSONAR - The UnsupportedEncodingException will in real time "never" happen and if yes a runtime exception will catch the problem } } if (sortBy != null) { ensureQueryParamIsSeparated(builder); builder.append("sortBy=") .append(sortBy); } if (sortOrder != null) { ensureQueryParamIsSeparated(builder); builder.append("sortOrder=") .append(sortOrder); } if (countPerPage != DEFAULT_COUNT) { ensureQueryParamIsSeparated(builder); builder.append("count=") .append(countPerPage); } if (startIndex != DEFAULT_INDEX) { ensureQueryParamIsSeparated(builder); builder.append("startIndex=") .append(startIndex); } return new Query(builder.toString()); } private void ensureQueryParamIsSeparated(StringBuilder builder) { if (builder.length() != 0) { builder.append("&"); } } private boolean isAttributeValid(String attribute) { return isAttributeValid(attribute, clazz); } private static boolean isAttributeValid(String attribute, Class<?> clazz) { String compositeField = ""; if (attribute.contains(".")) { compositeField = attribute.substring(attribute.indexOf('.') + 1); } if (attribute.startsWith("meta.")) { return isAttributeValid(compositeField, org.osiam.resources.scim.Meta.class); } if (attribute.startsWith("emails.")) { return isAttributeValid(compositeField, org.osiam.resources.scim.Email.class); } if (attribute.startsWith("name.")) { return isAttributeValid(compositeField, org.osiam.resources.scim.Name.class); } if (attribute.startsWith("groups.") || attribute.startsWith("members.")) { return isAttributeValid(compositeField, org.osiam.resources.scim.MemberRef.class); } List<String> fields = getAllClassFields(clazz); if(fields.contains(attribute)){ return true; } return false; } } private static List<String> getAllClassFields(Class<?> clazz){ ArrayList<String> fields = new ArrayList<>(); for (Field actField : clazz.getDeclaredFields()) { fields.add(actField.getName()); } addFieldsFromSuperClass(fields, clazz.getSuperclass()); return fields; } private static void addFieldsFromSuperClass(List<String> fields, Class<?> clazz){ if(clazz == null){ return; } for (Field actField : clazz.getDeclaredFields()) { fields.add(actField.getName()); } addFieldsFromSuperClass(fields, clazz.getSuperclass()); } /** * A Filter is used to produce filter criteria for the query. */ public static final class Filter { private Class<?> clazz; private StringBuilder filterBuilder; //TODO this constructor is only valid for the not operator. Will be changed when revising the connector api. /** * The Constructor for the not operator of the Filter, will create invalid queries for other operators. * * @param clazz The class of Resources to filter for. */ public Filter(Class<?> clazz) { filterBuilder = new StringBuilder(); this.clazz = clazz; } /** * The Constructor of the Filter * * @param clazz The class of Resources to filter for. * @param filter First inner Filter that has to be added to a new Filter */ public Filter(Class<?> clazz, Filter filter) { filterBuilder = new StringBuilder(); this.clazz = clazz; filterBuilder.append(" (").append(filter.toString()).append(")"); } /** * The Constructor of the Filter * * @param clazz The class of Resources to filter for. * @param comparison First Comparison that has to be added to a new Filter */ public Filter(Class<?> clazz, Comparison comparison) { filterBuilder = new StringBuilder(); this.clazz = clazz; query(comparison); } /** * Add an 'logical and' operation to the comparison with another attribute to comparison on. * * @param comparison The name of the attribute to comparison the and clause on. * @return A {@link org.osiam.client.query.metamodel.Comparison} to specify the filtering criteria * @throws org.osiam.client.exception.InvalidAttributeException if the given attribute is not valid for a query */ public Filter and(Comparison comparison) { filterBuilder.append(" and "); return query(comparison); } /** * Adds the query of the given Builder with an 'logical and' into an ( ... ) to the filter * * @param innerFilter the inner filter * @return The Builder with the inner filter added. */ public Filter and(Filter innerFilter) { if (innerFilter.toString().startsWith("not (")) { filterBuilder.append(" and ").append(innerFilter.toString()); } else { filterBuilder.append(" and (").append(innerFilter.toString()).append(")"); } return this; } /** * Add an 'logical or' operation to the comparison with another attribute to comparison on. * * @param comparison The name of the attribute to comparison the and clause on. * @return A {@link org.osiam.client.query.metamodel.Comparison} to specify the filtering criteria * @throws org.osiam.client.exception.InvalidAttributeException if the given attribute is not valid for a query */ public Filter or(Comparison comparison) { filterBuilder.append(" or "); return query(comparison); } /** * Adds the query of the given Builder an 'logical or' into ( ... ) to the filter * * @param innerFilter the inner filter * @return The Builder with the inner filter added. */ public Filter or(Filter innerFilter) { if (innerFilter.toString().startsWith("not (")) { filterBuilder.append(" or ").append(innerFilter.toString()); } else { filterBuilder.append(" or (").append(innerFilter.toString()).append(")"); } return this; } /** * Appends the not operator to the filter and adds the given parameter into ( ... ) * @param comparison A filter string with valid attribute, operator and value to search for * @return The Builder with the filter added. * @throws org.osiam.client.exception.InvalidAttributeException if the given attribute is not valid for a query */ public Filter not(Comparison comparison) { filterBuilder.append("not ("); query(comparison); filterBuilder.append(")"); return this; } /** * Appends the not operator to the filter and adds the query of the given Builder into ( ... ) * @param innerFilter the inner filter * @return The Builder with the inner filter added. */ public Filter not(Filter innerFilter) { filterBuilder.append("not (").append(innerFilter.toString()).append(")"); return this; } private boolean isAttributeValid(Comparison comparison) { String attribute = comparison.toString().substring(0, comparison.toString().indexOf(" ")); return Builder.isAttributeValid(attribute, clazz); } /** * provides all appended Comparisons as String * @return the build together filter */ @Override public String toString(){ return filterBuilder.toString(); } private Filter query(Comparison comparison) { if (!isAttributeValid(comparison)) { throw new InvalidAttributeException("Querying for this attribute is not supported"); } filterBuilder.append(comparison.toString()); return this; } } }
package org.agmip.ace; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.agmip.ace.util.AceFunctions; /** * A container class that holds the complete set of {@link AceExperiment}s, * {@link AceSoil}s and {@link AceWeather}s and handles the mapping * between these components. */ public class AceDataset { private Map<String, AceWeather> weatherMap; private Map<String, AceSoil> soilMap; private Map<String, AceExperiment> experimentMap; private Map<String, String> widMap; private Map<String, String> sidMap; private Map<String, String> eidMap; private byte majorVersion = 0; private byte minorVersion = 0; private byte revision = 0; /** * Create a blank dataset */ public AceDataset() { this.weatherMap = new HashMap<>(); this.soilMap = new HashMap<>(); this.experimentMap = new LinkedHashMap<>(); this.widMap = new HashMap<>(); this.sidMap = new HashMap<>(); this.eidMap = new HashMap<>(); } public void setMajorVersion(byte major) { this.majorVersion = major; } public void setMinorVersion(byte minor) { this.minorVersion = minor; } public void setRevision(byte revision) { this.revision = revision; } public byte getMajorVersion() { return this.majorVersion; } public byte getMinorVersion() { return this.minorVersion; } public byte getRevision() { return this.revision; } public String getVersion() { return this.majorVersion+"."+this.minorVersion+"."+this.revision; } /** * Add a Weather Station to the dataset. * <p> * Add a new Weather Station from a {@code byte[]} consisting of the JSON * for that weather station data. * * @param source JSON weather station data */ public void addWeather(byte[] source) throws IOException { AceWeather weather = new AceWeather(source); String wstId = weather.getValue("wst_id"); this.weatherMap.put(weather.getId(), weather); this.widMap.put(wstId, weather.getId()); } /** * Add a Soil to the dataset. * <p> * Add a new Soil from a {@code byte[]} consisting of the JSON * for that soil data. * * @param source JSON soil data */ public void addSoil(byte[] source) throws IOException { AceSoil soil = new AceSoil(source); String soilId = soil.getValue("soil_id"); this.soilMap.put(soil.getId(), soil); this.sidMap.put(soilId, soil.getId()); } /** * Add an Experiment to the dataset. * <p> * Add a new Experiment from a {@code byte[]} consisting of the JSON * for that experiment data. * * @param source JSON experiment data */ public void addExperiment(byte[] source) throws IOException { AceExperiment experiment = new AceExperiment(source); String eid = experiment.getId(); this.experimentMap.put(eid, experiment); this.eidMap.put(experiment.getValueOr("exname", ""), eid); } /** * Return a list of all Weather Stations. * * @return a list of {@link AceWeather} */ public List<AceWeather> getWeathers() { return new ArrayList<AceWeather>(this.weatherMap.values()); } /** * Return a list of all Weather Stations as {@link IAceBaseComponent}s. * * @return a list of {@link IAceBaseComponent} for weathers. */ public List<IAceBaseComponent> getWeatherComponents() { return new ArrayList<IAceBaseComponent>(this.weatherMap.values()); } /** * Return the original Weather Station mapping. * <p> * This returns the original binding information ({@code wst_id}) for * all weather stations. This should not be used by developers * of translators, instead use {@code AceExperiment#getWeather}. * * @return a map of all Weather Stations to {@code wst_id} */ public Map<String, AceWeather> getWeatherMap() { return this.weatherMap; } /** * Return a list of all Soil Profiles. * * @return a list of {@link AceSoil}s */ public List<AceSoil> getSoils() { return new ArrayList<AceSoil>(this.soilMap.values()); } /** * Return a list of all Soil Profiles as {@link IAceBaseComponent}s. * * @return a list of {@link IAceBaseComponent} for soils */ public List<IAceBaseComponent> getSoilComponents() { return new ArrayList<IAceBaseComponent>(this.soilMap.values()); } /** * Return the original Soil Profile map. * <p> * This returns the original binding information ({@code soil_id} for * all soil profiles. This should not be used by translator developers, * instead user {@code AceExperiment#getSoil}. * * @return a map of all Soil Profiles to {@code soil_id} */ public Map<String, AceSoil> getSoilMap() { return this.soilMap; } /** * Return a list of all Experiments. * * @return a list of {@link AceExperiment}s */ public List<AceExperiment> getExperiments() { return new ArrayList<AceExperiment>(this.experimentMap.values()); } /** * Return a list of all Experiments as {@link IAceBaseComponent}s. * * @return a list of {@link IAceBaseComponent}s for experiments */ public List<IAceBaseComponent> getExperimentComponents() { return new ArrayList<IAceBaseComponent>(this.experimentMap.values()); } /** * Return the original Experiment map. * <p> * This returns the original binding information ({@code exname}) for * all experiment. This should not be used by translator developers. * instead use {@link #getExperiments}. * * @return a map of all Experiments to {@code exname} */ public Map<String, AceExperiment> getExperimentMap() { return this.experimentMap; } /** * Return a Experiment by given experiment name. * * @param exname the experiment name * * @return {@link AceExperiment} */ public AceExperiment getExperiment(String exname) { if (this.eidMap.containsKey(exname)) { return this.experimentMap.get(eidMap.get(exname)); } else { return null; } } /** * Link all Experiments to the assocaited Soil Profile and Weather Station. * <p> * <strong>NOTE:</strong>This must be called prior to calling * {@link AceExperiment#getWeather} or {@link AceExperiment#getSoil} or * a {@code NullPointerException} will be thrown. * <p> * Loops through all the experiments to link the Soil Profile and Weather * station to each experiment. It first attempts to bind to the {@code wid} * or {@code sid} of the experiment, falling back on the {@code wst_id} * or {@code soil_id}. If no association is found, * {@link AceFunctions#getBlankComponent} is called. */ public void linkDataset() throws IOException { for(AceExperiment e : this.getExperiments()) { String wid = e.getValue("wid"); String sid = e.getValue("sid"); if (wid != null) { AceWeather w = this.weatherMap.get(wid); if (w != null) { e.setWeather(w); } else { e.setWeather(new AceWeather(AceFunctions.getBlankComponent())); } } else { String wstId = e.getValue("wst_id"); wid = this.widMap.get(wstId); if (wstId != null && wid != null) { e.setWeather(this.weatherMap.get(wid)); } else { e.setWeather(new AceWeather(AceFunctions.getBlankComponent())); } } if (sid != null) { AceSoil s = this.soilMap.get(sid); if (s != null) { e.setSoil(s); } else { e.setSoil(new AceSoil(AceFunctions.getBlankComponent())); } } else { String soilId = e.getValue("soil_id"); sid = this.sidMap.get(soilId); if (soilId != null && sid != null) { e.setSoil(this.soilMap.get(sid)); } else { e.setSoil(new AceSoil(AceFunctions.getBlankComponent())); } } } } /** * Fix Experiment to Soil Profile/Weather Station mapping after updates. * <p> * <strong>NOTE:</strong> This must be called after updating values which * will affect the hash. * <p> * <strong>NOTE:</strong> This method is called prior to generating a JSON * using any method found in {@link org.agmip.ace.io.AceGenerator}. * <p> * Re-associates and regenerates all ID's based on the hash for each * container. */ public void fixAssociations() throws IOException { for (AceWeather w : this.getWeathers()) { w.getId(true); } for (AceSoil s: this.getSoils()) { s.getId(true); } // Reassociate the ids and regenerate the experiment ID for (AceExperiment e: this.getExperiments()) { String wid = e.getWeather().getId(); String sid = e.getSoil().getId(); e.update("wid", wid, true); e.update("sid", sid, true); e.getId(true); } } }
package org.spigotmc.builder; import com.google.common.base.Charsets; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import com.google.common.io.ByteStreams; import com.google.common.io.Files; import com.google.common.io.Resources; import difflib.DiffUtils; import difflib.Patch; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.net.URL; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import lombok.RequiredArgsConstructor; import org.apache.commons.io.FileUtils; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.ResetCommand; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.revwalk.RevCommit; public class Builder { public static final boolean IS_WINDOWS = System.getProperty( "os.name" ).startsWith( "Windows" ); public static final boolean IS_MAC = System.getProperty( "os.name" ).startsWith( "Mac" ); public static final File CWD = new File( "." ); public static final String MC_VERSION = "1.8"; private static final File jacobeDir = new File( "jacobe" ); public static void main(String[] args) throws Exception { if ( IS_MAC ) { System.out.println( "Sorry, but Macintosh is not currently a supported platform for compilation at this time." ); System.out.println( "Please run this script on a Windows or Linux PC and then copy the jars to this computer." ); System.exit( 1 ); } try { runProcess( "bash -c exit", CWD ); } catch ( Exception ex ) { System.out.println( "You must run this jar through bash (msysgit)" ); System.exit( 1 ); } try { runProcess( "git config --global user.name", CWD ); } catch ( Exception ex ) { System.out.println( "Git name not set, setting it to default value." ); runProcess( "git config --global user.name BuildTools", CWD ); } try { runProcess( "git config --global user.email", CWD ); } catch ( Exception ex ) { System.out.println( "Git email not set, setting it to default value." ); runProcess( "git config --global user.email unconfigured@null.spigotmc.org", CWD ); } File workDir = new File( "work" ); workDir.mkdir(); File bukkit = new File( "Bukkit" ); if ( !bukkit.exists() ) { clone( "https://hub.spigotmc.org/stash/scm/spigot/bukkit.git", bukkit ); } File craftBukkit = new File( "CraftBukkit" ); if ( !craftBukkit.exists() ) { clone( "https://hub.spigotmc.org/stash/scm/spigot/craftbukkit.git", craftBukkit ); } File spigot = new File( "Spigot" ); if ( !spigot.exists() ) { clone( "https://hub.spigotmc.org/stash/scm/spigot/spigot.git", spigot ); } File buildData = new File( "BuildData" ); if ( !buildData.exists() ) { clone( "https://hub.spigotmc.org/stash/scm/spigot/builddata.git", buildData ); } if ( !jacobeDir.exists() ) { System.out.println( "Jacobe does not exist, downloading" ); getJacobe(); } File maven = new File( "apache-maven-3.2.3" ); if ( !maven.exists() ) { System.out.println( "Maven does not exist, downloading. Please wait." ); File mvnTemp = new File( "mvn.zip" ); mvnTemp.deleteOnExit(); download( "http://static.spigotmc.org/maven/apache-maven-3.2.3-bin.zip", mvnTemp ); unzip( mvnTemp, new File( "." ) ); } String mvnCmd = maven.getAbsolutePath() + "/bin/mvn"; if ( IS_WINDOWS ) { mvnCmd += ".bat"; } else { mvnCmd = "/bin/sh " + mvnCmd; } Git bukkitGit = Git.open( bukkit ); Git craftBukkitGit = Git.open( craftBukkit ); Git spigotGit = Git.open( spigot ); Git buildGit = Git.open( buildData ); pull( bukkitGit ); pull( craftBukkitGit ); pull( spigotGit ); pull( buildGit ); File vanillaJar = new File( workDir, "minecraft_server." + MC_VERSION + ".jar" ); if ( !vanillaJar.exists() ) { download( String.format( "https://s3.amazonaws.com/Minecraft.Download/versions/%1$s/minecraft_server.%1$s.jar", MC_VERSION ), vanillaJar ); } Iterable<RevCommit> mappings = buildGit.log() .addPath( "mappings/bukkit-1.8.at" ) .addPath( "mappings/bukkit-1.8-cl.csrg" ) .addPath( "mappings/bukkit-1.8-members.csrg" ) .addPath( "mappings/package.srg" ) .setMaxCount( 1 ).call(); Hasher mappingsHash = Hashing.md5().newHasher(); for ( RevCommit rev : mappings ) { mappingsHash.putString( rev.getName(), Charsets.UTF_8 ); } String mappingsVersion = mappingsHash.hash().toString().substring( 24 ); // Last 8 chars File finalMappedJar = new File( workDir, "mapped." + mappingsVersion + ".jar" ); if ( !finalMappedJar.exists() ) { System.out.println( "Final mapped jar: " + finalMappedJar + " does not exist, creating!" ); File clMappedJar = new File( finalMappedJar + "-cl" ); File mMappedJar = new File( finalMappedJar + "-m" ); runProcess( "java -jar BuildData/bin/SpecialSource.jar -i " + vanillaJar + " -m BuildData/mappings/bukkit-1.8-cl.csrg -o " + clMappedJar, CWD ); runProcess( "java -jar BuildData/bin/SpecialSource-2.jar map -i " + clMappedJar + " -m " + "BuildData/mappings/bukkit-1.8-members.csrg -o " + mMappedJar, CWD ); runProcess( "java -jar BuildData/bin/SpecialSource.jar -i " + mMappedJar + " --access-transformer BuildData/mappings/bukkit-1.8.at " + "-m BuildData/mappings/package.srg -o " + finalMappedJar, CWD ); } runProcess( mvnCmd + " install:install-file -Dfile=" + finalMappedJar + " -Dpackaging=jar -DgroupId=org.spigotmc -DartifactId=minecraft-server -Dversion=1.8-SNAPSHOT", CWD ); File decompileDir = new File( workDir, "decompile-" + mappingsVersion ); if ( !decompileDir.exists() ) { decompileDir.mkdir(); File clazzDir = new File( decompileDir, "classes" ); unzip( finalMappedJar, clazzDir, new Predicate<String>() { @Override public boolean apply(String input) { return input.startsWith( "net/minecraft/server" ); } } ); runProcess( "java -jar BuildData/bin/fernflower.jar -dgs=1 -hdc=0 -rbr=0 -asc=1 " + clazzDir + " " + decompileDir, CWD ); String jacobePath = jacobeDir.getPath() + "/jacobe"; if ( IS_WINDOWS ) { jacobePath += ".exe"; } runProcess( jacobePath + " -cfg=BuildData/bin/jacobe.cfg -nobackup -overwrite -outext=java " + decompileDir + "/net/minecraft/server", CWD ); } System.out.println( "Applying CraftBukkit Patches" ); File nmsDir = new File( craftBukkit, "src/main/java/net" ); if ( nmsDir.exists() ) { System.out.println( "Backing up NMS dir" ); FileUtils.moveDirectory( nmsDir, new File( workDir, "nms.old." + System.currentTimeMillis() ) ); } File patchDir = new File( craftBukkit, "nms-patches" ); for ( File file : patchDir.listFiles() ) { String targetFile = "net/minecraft/server/" + file.getName().replaceAll( ".patch", ".java" ); File clean = new File( decompileDir, targetFile ); File t = new File( nmsDir.getParentFile(), targetFile ); t.getParentFile().mkdirs(); System.out.println( "Patching with " + file.getName() ); Patch parsedPatch = DiffUtils.parseUnifiedDiff( Files.readLines( file, Charsets.UTF_8 ) ); List<?> modifiedLines = DiffUtils.patch( Files.readLines( clean, Charsets.UTF_8 ), parsedPatch ); BufferedWriter bw = new BufferedWriter( new FileWriter( t ) ); for ( String line : (List<String>) modifiedLines ) { bw.write( line ); bw.newLine(); } bw.close(); } File tmpNms = new File( craftBukkit, "tmp-nms" ); FileUtils.copyDirectory( nmsDir, tmpNms ); craftBukkitGit.branchDelete().setBranchNames( "patched" ).setForce( true ).call(); craftBukkitGit.checkout().setCreateBranch( true ).setForce( true ).setName( "patched" ).call(); craftBukkitGit.add().addFilepattern( "src/main/java/net/" ).call(); craftBukkitGit.commit().setMessage( "CraftBukkit $ " + new Date() ).call(); craftBukkitGit.checkout().setName( "master" ).call(); FileUtils.moveDirectory( tmpNms, nmsDir ); File spigotApi = new File( spigot, "Bukkit" ); if ( !spigotApi.exists() ) { clone( "file://" + bukkit.getAbsolutePath(), spigotApi ); } File spigotServer = new File( spigot, "CraftBukkit" ); if ( !spigotServer.exists() ) { clone( "file://" + craftBukkit.getAbsolutePath(), spigotServer ); } // Git spigotApiGit = Git.open( spigotApi ); // Git spigotServerGit = Git.open( spigotServer ); System.out.println( "Compiling Bukkit" ); runProcess( mvnCmd + " clean install", bukkit ); System.out.println( "Compiling CraftBukkit" ); runProcess( mvnCmd + " clean install", craftBukkit ); try { runProcess( "bash applyPatches.sh", spigot ); System.out.println( "*** Spigot patches applied!" ); System.out.println( "Compiling Spigot & Spigot-API" ); runProcess( mvnCmd + " clean install", spigot ); } catch ( Exception ex ) { System.err.println( "Error compiling Spigot, are you running this jar via msysgit?" ); ex.printStackTrace(); System.exit( 1 ); } } public static void getJacobe() throws Exception { if ( IS_WINDOWS ) { File jacobeWindows = new File( "jacobe.win32.zip" ); download( "http: unzip( jacobeWindows, jacobeDir ); } else { File jacobeLinux = new File( "jacobe.linux.tar.gz" ); download( "http: jacobeDir.mkdir(); runProcess( "tar xzvf " + jacobeLinux.getPath() + " -C " + jacobeDir.getPath(), CWD ); } } public static void pull(Git repo) throws Exception { System.out.println( "Pulling updates for " + repo.getRepository().getDirectory() ); repo.reset().setRef( "origin/master" ).setMode( ResetCommand.ResetType.HARD ).call(); boolean result = repo.pull().call().isSuccessful(); if ( !result ) { throw new RuntimeException( "Could not pull updates!" ); } System.out.println( "Successfully pulled updates!" ); } public static int runProcess(String command, File workDir) throws Exception { final Process ps = new ProcessBuilder( command.split( " " ) ).directory( workDir ).start(); new Thread( new StreamRedirector( ps.getInputStream(), System.out ) ).start(); new Thread( new StreamRedirector( ps.getErrorStream(), System.err ) ).start(); int status = ps.waitFor(); if ( status != 0 ) { throw new RuntimeException( "Error running command, return status !=0: " + command ); } return status; } @RequiredArgsConstructor private static class StreamRedirector implements Runnable { private final InputStream in; private final PrintStream out; @Override public void run() { BufferedReader br = new BufferedReader( new InputStreamReader( in ) ); try { String line; while ( ( line = br.readLine() ) != null ) { out.println( line ); } } catch ( IOException ex ) { throw Throwables.propagate( ex ); } } } public static void unzip(File zipFile, File targetFolder) throws IOException { unzip( zipFile, targetFolder, null ); } public static void unzip(File zipFile, File targetFolder, Predicate<String> filter) throws IOException { targetFolder.mkdir(); ZipFile zip = new ZipFile( zipFile ); for ( Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements(); ) { ZipEntry entry = entries.nextElement(); if ( filter != null ) { if ( !filter.apply( entry.getName() ) ) { continue; } } File outFile = new File( targetFolder, entry.getName() ); if ( entry.isDirectory() ) { outFile.mkdirs(); continue; } if ( outFile.getParentFile() != null ) { outFile.getParentFile().mkdirs(); } InputStream is = zip.getInputStream( entry ); OutputStream os = new FileOutputStream( outFile ); try { ByteStreams.copy( is, os ); } finally { is.close(); os.close(); } System.out.println( "Extracted: " + outFile ); } } public static void clone(String url, File target) throws GitAPIException { System.out.println( "Starting clone of " + url + " to " + target ); Git result = Git.cloneRepository().setURI( url ).setDirectory( target ).call(); try { System.out.println( "Cloned git repository " + url + " to " + url + ". Current HEAD: " + commitHash( result ) ); } finally { result.close(); } } public static String commitHash(Git repo) throws GitAPIException { return Iterables.getOnlyElement( repo.log().setMaxCount( 1 ).call() ).getName(); } public static File download(String url, File target) throws IOException { System.out.println( "Starting download of " + url ); byte[] bytes = Resources.toByteArray( new URL( url ) ); System.out.println( "Downloaded file: " + target + " with md5: " + Hashing.md5().hashBytes( bytes ).toString() ); Files.write( bytes, target ); return target; } }
package org.lantern; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.net.URI; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.UnresolvedAddressException; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Queue; import java.util.Random; import java.util.TreeSet; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import javax.net.SocketFactory; import net.sf.ehcache.store.chm.ConcurrentHashMap; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.URIException; import org.apache.commons.io.IOExceptionWithCause; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.SystemUtils; import org.apache.commons.lang.math.RandomUtils; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpMessage; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpRequestEncoder; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.ConnectionListener; import org.jivesoftware.smack.PacketCollector; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.PacketIDFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.IQ.Type; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.provider.ProviderManager; import org.json.simple.JSONArray; import org.lantern.xmpp.GenericIQProvider; import org.lastbamboo.common.offer.answer.NoAnswerException; import org.lastbamboo.common.p2p.P2PClient; import org.littleshoot.proxy.ProxyUtils; import org.littleshoot.util.ByteBufferUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Utility methods for use with Lantern. */ public class LanternUtils { private static final Logger LOG = LoggerFactory.getLogger(LanternUtils.class); private static String MAC_ADDRESS; private static final File CONFIG_DIR = new File(System.getProperty("user.home"), ".lantern"); private static final File DATA_DIR; private static final File LOG_DIR; private static final File PROPS_FILE = new File(CONFIG_DIR, "lantern.properties"); private static final Properties PROPS = new Properties(); static { ProviderManager.getInstance().addIQProvider( "query", "google:shared-status", new GenericIQProvider()); if (SystemUtils.IS_OS_WINDOWS) { //logDirParent = CommonUtils.getDataDir(); DATA_DIR = new File(System.getenv("APPDATA"), "Lantern"); LOG_DIR = new File(DATA_DIR, "logs"); } else if (SystemUtils.IS_OS_MAC_OSX) { final File homeLibrary = new File(System.getProperty("user.home"), "Library"); DATA_DIR = new File(homeLibrary, "Logs"); LOG_DIR = new File(DATA_DIR, "Lantern"); } else { DATA_DIR = new File(SystemUtils.getUserHome(), ".lantern"); LOG_DIR = new File(DATA_DIR, "logs"); } if (!DATA_DIR.isDirectory()) { if (!DATA_DIR.mkdirs()) { System.err.println("Could not create parent at: " + DATA_DIR); } } if (!LOG_DIR.isDirectory()) { if (!LOG_DIR.mkdirs()) { System.err.println("Could not create dir at: " + LOG_DIR); } } if (!CONFIG_DIR.isDirectory()) { if (!CONFIG_DIR.mkdirs()) { LOG.error("Could not make config directory at: "+CONFIG_DIR); } } if (!PROPS_FILE.isFile()) { try { if (!PROPS_FILE.createNewFile()) { LOG.error("Could not create props file!!"); } } catch (final IOException e) { LOG.error("Could not create props file!!", e); } } InputStream is = null; try { is = new FileInputStream(PROPS_FILE); PROPS.load(is); } catch (final IOException e) { LOG.error("Error loading props file: "+PROPS_FILE, e); } finally { IOUtils.closeQuietly(is); } } public static final ClientSocketChannelFactory clientSocketChannelFactory = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); /** * Helper method that ensures all written requests are properly recorded. * * @param request The request. */ public static void writeRequest(final Queue<HttpRequest> httpRequests, final HttpRequest request, final ChannelFuture cf) { httpRequests.add(request); LOG.info("Writing request: {}", request); LanternUtils.genericWrite(request, cf); } public static void genericWrite(final Object message, final ChannelFuture future) { final Channel ch = future.getChannel(); if (ch.isConnected()) { ch.write(message); } else { future.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture cf) throws Exception { if (cf.isSuccess()) { ch.write(message); } } }); } } public static Socket openRawOutgoingPeerSocket( final Channel browserToProxyChannel, final URI uri, final ProxyStatusListener proxyStatusListener, final P2PClient p2pClient, final Map<URI, AtomicInteger> peerFailureCount, final boolean recordStats) throws IOException { return openOutgoingPeerSocket(browserToProxyChannel, uri, proxyStatusListener, p2pClient, peerFailureCount, true, recordStats); } public static Socket openOutgoingPeerSocket( final Channel browserToProxyChannel, final URI uri, final ProxyStatusListener proxyStatusListener, final P2PClient p2pClient, final Map<URI, AtomicInteger> peerFailureCount, final boolean recordStats) throws IOException { return openOutgoingPeerSocket(browserToProxyChannel, uri, proxyStatusListener, p2pClient, peerFailureCount, false, recordStats); } private static Socket openOutgoingPeerSocket( final Channel browserToProxyChannel, final URI uri, final ProxyStatusListener proxyStatusListener, final P2PClient p2pClient, final Map<URI, AtomicInteger> peerFailureCount, final boolean raw, final boolean recordStats) throws IOException { // Start the connection attempt. try { LOG.info("Creating a new socket to {}", uri); final Socket sock; if (raw) { sock = p2pClient.newRawSocket(uri); } else { sock = p2pClient.newSocket(uri); } LOG.info("Got outgoing peer socket: {}", sock); startReading(sock, browserToProxyChannel, recordStats); return sock; } catch (final NoAnswerException nae) { // This is tricky, as it can mean two things. First, it can mean // the XMPP message was somehow lost. Second, it can also mean // the other side is actually not there and didn't respond as a // result. LOG.info("Did not get answer!! Closing channel from browser", nae); final AtomicInteger count = peerFailureCount.get(uri); if (count == null) { LOG.info("Incrementing failure count"); peerFailureCount.put(uri, new AtomicInteger(0)); } else if (count.incrementAndGet() > 5) { LOG.info("Got a bunch of failures in a row to this peer. " + "Removing it."); // We still reset it back to zero. Note this all should // ideally never happen, and we should be able to use the // XMPP presence alerts to determine if peers are still valid // or not. peerFailureCount.put(uri, new AtomicInteger(0)); proxyStatusListener.onCouldNotConnectToPeer(uri); } throw new IOExceptionWithCause(nae); } catch (final IOException ioe) { proxyStatusListener.onCouldNotConnectToPeer(uri); LOG.warn("Could not connect to peer", ioe); throw ioe; } } private static void startReading(final Socket sock, final Channel channel, final boolean recordStats) { final Runnable runner = new Runnable() { @Override public void run() { final byte[] buffer = new byte[4096]; long count = 0; int n = 0; try { final InputStream is = sock.getInputStream(); while (-1 != (n = is.read(buffer))) { //LOG.info("Writing response data: {}", new String(buffer, 0, n)); // We need to make a copy of the buffer here because // the writes are asynchronous, so the bytes can // otherwise get scrambled. final ChannelBuffer buf = ChannelBuffers.copiedBuffer(buffer, 0, n); channel.write(buf); if (recordStats) { LanternHub.statsTracker().addBytesProxied(n); } count += n; } ProxyUtils.closeOnFlush(channel); } catch (final IOException e) { LOG.info("Exception relaying peer data back to browser",e); ProxyUtils.closeOnFlush(channel); // The other side probably just closed the connection!! //channel.close(); //proxyStatusListener.onError(peerUri); } } }; final Thread peerReadingThread = new Thread(runner, "Peer-Data-Reading-Thread"); peerReadingThread.setDaemon(true); peerReadingThread.start(); } public static String getMacAddress() { if (MAC_ADDRESS != null) { return MAC_ADDRESS; } final Enumeration<NetworkInterface> nis; try { nis = NetworkInterface.getNetworkInterfaces(); } catch (final SocketException e1) { throw new Error("Could not read network interfaces?"); } while (nis.hasMoreElements()) { final NetworkInterface ni = nis.nextElement(); try { if (!ni.isUp()) { LOG.info("Ignoring interface that's not up: {}", ni.getDisplayName()); continue; } final byte[] mac = ni.getHardwareAddress(); if (mac != null && mac.length > 0) { LOG.info("Returning 'normal' MAC address"); MAC_ADDRESS = Base64.encodeBase64String(mac).trim(); return MAC_ADDRESS; } } catch (final SocketException e) { LOG.warn("Could not get MAC address?"); } } try { LOG.warn("Returning custom MAC address"); MAC_ADDRESS = Base64.encodeBase64String( InetAddress.getLocalHost().getAddress()) + System.currentTimeMillis(); return MAC_ADDRESS; } catch (final UnknownHostException e) { final byte[] bytes = new byte[24]; new Random().nextBytes(bytes); return Base64.encodeBase64String(bytes); } } public static File configDir() { return CONFIG_DIR; } public static File dataDir() { return DATA_DIR; } public static File logDir() { return LOG_DIR; } public static File propsFile() { return PROPS_FILE; } public static boolean isTransferEncodingChunked(final HttpMessage m) { final List<String> chunked = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); if (chunked.isEmpty()) { return false; } for (String v: chunked) { if (v.equalsIgnoreCase(HttpHeaders.Values.CHUNKED)) { return true; } } return false; } public static JSONArray toJsonArray(final Collection<String> strs) { final JSONArray json = new JSONArray(); synchronized (strs) { json.addAll(strs); } return json; } public static boolean newInstall() { return getBooleanProperty("newInstall"); } public static void installed() { setBooleanProperty("newInstall", false); } public static void setBooleanProperty(final String key, final boolean value) { PROPS.setProperty(key, String.valueOf(value)); persistProps(); } public static boolean getBooleanProperty(final String key) { final String val = PROPS.getProperty(key); if (StringUtils.isBlank(val)) { return false; } LOG.info("Checking property: {}", val); return "true".equalsIgnoreCase(val.trim()); } public static boolean isConfigured() { if (!PROPS_FILE.isFile()) { return false; } final Properties props = new Properties(); InputStream is = null; try { is = new FileInputStream(PROPS_FILE); props.load(is); final String un = props.getProperty("google.user"); final String pwd = props.getProperty("google.pwd"); return (StringUtils.isNotBlank(un) && StringUtils.isNotBlank(pwd)); } catch (final IOException e) { LOG.error("Error loading props file: "+PROPS_FILE, e); } finally { IOUtils.closeQuietly(is); } return false; } public static Collection<RosterEntry> getRosterEntries(final String email, final String pwd, final int attempts) throws IOException { final XMPPConnection conn = persistentXmppConnection(email, pwd, "lantern", attempts); final Roster roster = conn.getRoster(); final Collection<RosterEntry> unordered = roster.getEntries(); final Comparator<RosterEntry> comparator = new Comparator<RosterEntry>() { @Override public int compare(final RosterEntry re1, final RosterEntry re2) { final String name1 = re1.getName(); final String name2 = re2.getName(); if (name1 == null) { return 1; } else if (name2 == null) { return -1; } return name1.compareToIgnoreCase(name2); } }; final Collection<RosterEntry> entries = new TreeSet<RosterEntry>(comparator); for (final RosterEntry entry : unordered) { entries.add(entry); } return entries; } private static final Map<String, XMPPConnection> xmppConnections = new ConcurrentHashMap<String, XMPPConnection>(); private static XMPPConnection persistentXmppConnection(final String username, final String password, final String id) throws IOException { return persistentXmppConnection(username, password, id, 4); } public static XMPPConnection persistentXmppConnection(final String username, final String password, final String id, final int attempts) throws IOException { final String key = username+password; if (xmppConnections.containsKey(key)) { final XMPPConnection conn = xmppConnections.get(key); if (conn.isAuthenticated() && conn.isConnected()) { LOG.info("Returning existing xmpp connection"); return conn; } else { LOG.info("Removing stale connection"); xmppConnections.remove(key); } } XMPPException exc = null; for (int i = 0; i < attempts; i++) { try { LOG.info("Attempting XMPP connection..."); final XMPPConnection conn = singleXmppConnection(username, password, id); // Make sure we signify gchat support. LanternUtils.getSharedStatus(conn); LOG.info("Created offerer"); xmppConnections.put(key, conn); return conn; } catch (final XMPPException e) { final String msg = "Error creating XMPP connection"; LOG.error(msg, e); exc = e; } // Gradual backoff. try { Thread.sleep(i * 600); } catch (final InterruptedException e) { LOG.info("Interrupted?", e); } } if (exc != null) { throw new IOException("Could not log in!!", exc); } else { throw new IOException("Could not log in?"); } } private static XMPPConnection singleXmppConnection(final String username, final String password, final String id) throws XMPPException { final ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com", 5222, "gmail.com"); //new ConnectionConfiguration(this.host, this.port, this.serviceName); config.setCompressionEnabled(true); config.setRosterLoadedAtLogin(false); config.setReconnectionAllowed(false); config.setExpiredCertificatesCheckEnabled(true); config.setNotMatchingDomainCheckEnabled(true); config.setSendPresence(false); config.setSocketFactory(new SocketFactory() { @Override public Socket createSocket(final InetAddress host, final int port, final InetAddress localHost, final int localPort) throws IOException { // We ignore the local port binding. return createSocket(host, port); } @Override public Socket createSocket(final String host, final int port, final InetAddress localHost, final int localPort) throws IOException, UnknownHostException { // We ignore the local port binding. return createSocket(host, port); } @Override public Socket createSocket(final InetAddress host, final int port) throws IOException { LOG.info("Creating socket"); final Socket sock = new Socket(); sock.connect(new InetSocketAddress(host, port), 40000); LOG.info("Socket connected"); return sock; } @Override public Socket createSocket(final String host, final int port) throws IOException, UnknownHostException { LOG.info("Creating socket"); return createSocket(InetAddress.getByName(host), port); } }); return newConnection(username, password, config, id); } private static XMPPConnection newConnection(final String username, final String password, final ConnectionConfiguration config, final String id) throws XMPPException { final XMPPConnection conn = new XMPPConnection(config); conn.connect(); LOG.info("Connection is Secure: {}", conn.isSecureConnection()); LOG.info("Connection is TLS: {}", conn.isUsingTLS()); conn.login(username, password, id); while (!conn.isAuthenticated()) { LOG.info("Waiting for authentication"); try { Thread.sleep(400); } catch (final InterruptedException e1) { LOG.error("Exception during sleep?", e1); } } conn.addConnectionListener(new ConnectionListener() { public void reconnectionSuccessful() { LOG.info("Reconnection successful..."); } public void reconnectionFailed(final Exception e) { LOG.info("Reconnection failed", e); } public void reconnectingIn(final int time) { LOG.info("Reconnecting to XMPP server in "+time); } public void connectionClosedOnError(final Exception e) { LOG.info("XMPP connection closed on error", e); try { persistentXmppConnection(username, password, id); } catch (final IOException e1) { LOG.error("Could not re-establish connection?", e1); } } public void connectionClosed() { LOG.info("XMPP connection closed. Creating new connection."); try { persistentXmppConnection(username, password, id); } catch (final IOException e1) { LOG.error("Could not re-establish connection?", e1); } } }); return conn; } public static void writeCredentials(final String email, final String pwd) { LOG.info("Writing credentials..."); PROPS.setProperty("google.user", email); PROPS.setProperty("google.pwd", pwd); persistProps(); } public static void clearCredentials() { LOG.info("Clearing credentials..."); PROPS.remove("google.user"); PROPS.remove("google.pwd"); persistProps(); } public static String getStringProperty(final String key) { return PROPS.getProperty(key); } public static void clear(final String key) { PROPS.remove(key); persistProps(); } private static void persistProps() { FileWriter fw = null; try { fw = new FileWriter(PROPS_FILE); PROPS.store(fw, ""); } catch (final IOException e) { LOG.error("Could not store props?"); } finally { IOUtils.closeQuietly(fw); } } /** * We subclass here purely to expose the encoding method of the built-in * request encoder. */ private static final class RequestEncoder extends HttpRequestEncoder { private ChannelBuffer encode(final HttpRequest request, final Channel ch) throws Exception { return (ChannelBuffer) super.encode(null, ch, request); } } public static byte[] toByteBuffer(final HttpRequest request, final ChannelHandlerContext ctx) throws Exception { // We need to convert the Netty message to raw bytes for sending over // the socket. final RequestEncoder encoder = new RequestEncoder(); final ChannelBuffer cb = encoder.encode(request, ctx.getChannel()); return toRawBytes(cb); } public static byte[] toRawBytes(final ChannelBuffer cb) { final ByteBuffer buf = cb.toByteBuffer(); return ByteBufferUtils.toRawBytes(buf); } public static String jidToUser(final String jid) { return StringUtils.substringBefore(jid, "/"); } public static void setGoogleTalkInvisible(final XMPPConnection conn, final String to) { final IQ iq = new IQ() { @Override public String getChildElementXML() { return "<query xmlns='google:shared-status' version='2'><invisible value='true'/></query>"; } }; iq.setType(Type.SET); iq.setTo(to); LOG.info("Setting invisible with XML packet:\n"+iq.toXML()); conn.sendPacket(iq); } public static Packet getSharedStatus(final XMPPConnection conn) { LOG.info("Getting shared status..."); final IQ iq = new IQ() { @Override public String getChildElementXML() { return "<query xmlns='google:shared-status' version='2'/>"; } }; final String jid = conn.getUser(); iq.setTo(LanternUtils.jidToUser(jid)); iq.setFrom(jid); final PacketCollector collector = conn.createPacketCollector( new PacketIDFilter(iq.getPacketID())); LOG.info("Sending shared status packet:\n"+iq.toXML()); conn.sendPacket(iq); final Packet response = collector.nextResult(40000); return response; } public static Collection<String> toHttpsCandidates(final String uriStr) { final Collection<String> segments = new LinkedHashSet<String>(); try { final org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(uriStr, false); final String host = uri.getHost(); LOG.info("Using host: {}", host); segments.add(host); final String[] segmented = host.split("\\."); LOG.info("Testing segments: {}", Arrays.asList(segmented)); for (int i = 0; i < segmented.length; i++) { final String tmp = segmented[i]; segmented[i] = "*"; final String segment = StringUtils.join(segmented, '.'); LOG.info("Adding segment: {}", segment); segments.add(segment); segmented[i] = tmp; } for (int i = 1; i < segmented.length - 1; i++) { final String segment = "*." + StringUtils.join(segmented, '.', i, segmented.length);//segmented.slice(i,segmented.length).join("."); LOG.info("Checking segment: {}", segment); segments.add(segment); } } catch (final URIException e) { LOG.error("Could not create URI?", e); } return segments; } public static void waitForInternet() { while (true) { try { final DatagramChannel channel = DatagramChannel.open(); final SocketAddress server = new InetSocketAddress("time-a.nist.gov", 37); channel.connect(server); return; } catch (final IOException e) { LOG.error("Could not create channel!", e); } catch (final UnresolvedAddressException e) { LOG.error("Could not resolve address", e); } try { Thread.sleep(250); } catch (final InterruptedException e) { LOG.error("Interrupted?", e); } } } public static int randomPort() { try { final ServerSocket sock = new ServerSocket(); sock.bind(null); final int port = sock.getLocalPort(); sock.close(); return port; } catch (final IOException e) { return 1024 + (RandomUtils.nextInt() % 60000); } } /** * Execute keytool, returning the output. */ public static String runKeytool(final String... args) { final CommandLine command = new CommandLine(findKeytoolPath(), args); command.execute(); final String output = command.getStdOut(); if (!command.isSuccessful()) { LOG.warn("Command failed!! -- {}", args); } return output; } private static String findKeytoolPath() { final File defaultLocation = new File("/usr/bin/keytool"); if (defaultLocation.exists()) { return defaultLocation.getAbsolutePath(); } final String networkSetupBin = CommandLine.findExecutable("keytool"); if (networkSetupBin != null) { return networkSetupBin; } LOG.error("Could not fine keytool?!?!?!?"); return null; } }
package org.udger.parser; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.UnknownHostException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.sqlite.SQLiteConfig; /** * Main parser's class handles parser requests for user agent or IP. */ public class UdgerParser implements Closeable { private static final String DB_FILENAME = "udgerdb_v3.dat"; private static final String UDGER_UA_DEV_BRAND_LIST_URL = "https://udger.com/resources/ua-list/devices-brand-detail?brand="; private static final String ID_CRAWLER = "crawler"; private static final Pattern PAT_UNPERLIZE = Pattern.compile("^/?(.*?)/si$"); private static class ClientInfo { private Integer clientId; private Integer classId; } private static class IdRegString { int id; int wordId1; int wordId2; Pattern pattern; } private static WordDetector clientWordDetector; private static WordDetector deviceWordDetector; private static WordDetector osWordDetector; private static List<IdRegString> clientRegstringList; private static List<IdRegString> osRegstringList; private static List<IdRegString> deviceRegstringList; private Connection connection; private String dbFileName = DB_FILENAME; private final Map<String, Pattern> regexCache = new HashMap<>(); private Matcher lastPatternMatcher; private Map<String, PreparedStatement> preparedStmtMap = new HashMap<>(); private LRUCache cache; private boolean osParserEnabled = true; private boolean deviceParserEnabled = true; private boolean deviceBrandParserEnabled = true; private boolean inMemoryEnabled = false; /** * Instantiates a new udger parser with LRU cache with capacity of 10.000 items * * @param dbFileName the udger database file name */ public UdgerParser(String dbFileName) { this(dbFileName, 10000); } /** * Instantiates a new udger parser. Parser must be prepared by prepare() method call before it is used. * * @param dbFileName the udger database file name * @param cacheCapacity the LRU cache capacity */ public UdgerParser(String dbFileName, int cacheCapacity) { this.dbFileName = dbFileName; if (cacheCapacity > 0) { cache = new LRUCache(cacheCapacity); } } /** * Instantiates a new udger parser with a in-memory SQLite DB if inMemoryEnabled is set to true. * * @param dbFileName the udger database file name * @param inMemoryEnabled set true to enable in memory DB */ public UdgerParser(String dbFileName, boolean inMemoryEnabled, int cacheCapacity) { this(dbFileName, cacheCapacity); this.inMemoryEnabled = inMemoryEnabled; } @Override public void close() throws IOException { try { for (PreparedStatement preparedStmt: preparedStmtMap.values()) { preparedStmt.close(); } preparedStmtMap.clear(); if (connection != null && !connection.isClosed()) { connection.close(); connection = null; } } catch (SQLException e) { throw new IOException(e.getMessage()); } } /** * Parses the user agent string and stores results of parsing in UdgerUaResult. * If the parser was initialized to use an in memory DB, then the DB is not set to read only. * This does not matter since the connection is internal to this client, as such there are * no chance of external modifications. * * @param uaString the user agent string * @return the intance of UdgerUaResult storing results of parsing * @throws SQLException the SQL exception */ public UdgerUaResult parseUa(String uaString) throws SQLException { UdgerUaResult ret; if (cache != null) { ret = cache.get(uaString); if (ret != null) { return ret; } } ret = new UdgerUaResult(uaString); prepare(); ClientInfo clientInfo = clientDetector(uaString, ret); if (osParserEnabled) { osDetector(uaString, ret, clientInfo); } if (deviceParserEnabled) { deviceDetector(uaString, ret, clientInfo); } if (deviceBrandParserEnabled) { if (ret.getOsFamilyCode() != null && !ret.getOsFamilyCode().isEmpty()) { fetchDeviceBrand(uaString, ret); } } if (cache != null) { cache.put(uaString, ret); } return ret; } /** * Parses the IP string and stores results of parsing in UdgerIpResult. * * @param ipString the IP string * @return the instance of UdgerIpResult storing results of parsing * @throws SQLException the SQL exception * @throws UnknownHostException the unknown host exception */ public UdgerIpResult parseIp(String ipString) throws SQLException, UnknownHostException { UdgerIpResult ret = new UdgerIpResult(ipString); InetAddress addr = InetAddress.getByName(ipString); Long ipv4int = null; String normalizedIp = null; if (addr instanceof Inet4Address) { ipv4int = 0L; for (byte b: addr.getAddress()) { ipv4int = ipv4int << 8 | (b & 0xFF); } normalizedIp = addr.getHostAddress(); } else if (addr instanceof Inet6Address) { normalizedIp = addr.getHostAddress().replaceAll("((?:(?:^|:)0+\\b){2,}):?(?!\\S*\\b\\1:0+\\b)(\\S*)", "::$2"); } ret.setIpClassification("Unrecognized"); ret.setIpClassificationCode("unrecognized"); if (normalizedIp != null) { prepare(); ResultSet ipRs = getFirstRow(UdgerSqlQuery.SQL_IP, normalizedIp); if (ipRs != null) { try { if (ipRs.next()) { fetchUdgerIp(ipRs, ret); if (!ID_CRAWLER.equals(ret.getIpClassificationCode())) { ret.setCrawlerFamilyInfoUrl(""); } } } finally { ipRs.close(); } } if (ipv4int != null) { ret.setIpVer(4); ResultSet dataCenterRs = getFirstRow(UdgerSqlQuery.SQL_DATACENTER, ipv4int, ipv4int); if (dataCenterRs != null) { try { if (dataCenterRs.next()) { fetchDataCenter(dataCenterRs, ret); } } finally { dataCenterRs.close(); } } } else { ret.setIpVer(6); int[] ipArray = ip6ToArray((Inet6Address) addr); ResultSet dataCenterRs = getFirstRow(UdgerSqlQuery.SQL_DATACENTER_RANGE6, ipArray[0], ipArray[0], ipArray[1], ipArray[1], ipArray[2], ipArray[2], ipArray[3], ipArray[3], ipArray[4], ipArray[4], ipArray[5], ipArray[5], ipArray[6], ipArray[6], ipArray[7], ipArray[7] ); if (dataCenterRs != null) { try { if (dataCenterRs.next()) { fetchDataCenter(dataCenterRs, ret); } } finally { dataCenterRs.close(); } } } } return ret; } /** * Checks if is OS parser enabled. OS parser is enabled by default * * @return true, if is OS parser enabled */ public boolean isOsParserEnabled() { return osParserEnabled; } /** * Enable/disable the OS parser. OS parser is enabled by default. If enabled following fields * of UdgerUaResult are processed by the OS parser: * <ul> * <li>osFamily, osFamilyCode, OS, osCode, osHomePage, osIcon, osIconBig</li> * <li>osFamilyVendor, osFamilyVendorCode, osFamilyVedorHomepage, osInfoUrl</li> * </ul> * * If the OSs fields are not necessary then disabling this feature can increase * the parser's performance. * * @param osParserEnabled the true if os parser is to be enabled */ public void setOsParserEnabled(boolean osParserEnabled) { this.osParserEnabled = osParserEnabled; } /** * Checks if is device parser enabled. Device parser is enabled by default * * @return true, if device parser is enabled */ public boolean isDeviceParserEnabled() { return deviceParserEnabled; } /** * Enable/disable the device parser. Device parser is enabled by default. If enabled following fields * of UdgerUaResult are filled by the device parser: * <ul> * <li>deviceClass, deviceClassCode, deviceClassIcon</li> * <li>deviceClassIconBig, deviceClassInfoUrl</li> * </ul> * * If the DEVICEs fields are not necessary then disabling this feature can increase * the parser's performance. * * @param deviceParserEnabled the true if device parser is to be enabled */ public void setDeviceParserEnabled(boolean deviceParserEnabled) { this.deviceParserEnabled = deviceParserEnabled; } /** * Checks if is device brand parser enabled. Device brand parser is enabled by default. * * @return true, if device brand parser is enabled */ public boolean isDeviceBrandParserEnabled() { return deviceBrandParserEnabled; } /** * Enable/disable the device brand parser. Device brand parser is enabled by default. If enabled following fields * of UdgerUaResult are filled by the device brand parser: * <ul> * <li>deviceMarketname, deviceBrand, deviceBrandCode, deviceBrandHomepage</li> * <li>deviceBrandIcon, deviceBrandIconBig, deviceBrandInfoUrl</li> * </ul> * * If the BRANDs fields are not necessary then disabling this feature can increase * the parser's performance. * * @param deviceBrandParserEnabled the true if device brand parser is to be enabled */ public void setDeviceBrandParserEnabled(boolean deviceBrandParserEnabled) { this.deviceBrandParserEnabled = deviceBrandParserEnabled; } private static synchronized void initStaticStructures(Connection connection) throws SQLException { if (clientRegstringList == null) { clientRegstringList = prepareRegexpStruct(connection, "udger_client_regex"); osRegstringList = prepareRegexpStruct(connection, "udger_os_regex"); deviceRegstringList = prepareRegexpStruct(connection, "udger_deviceclass_regex"); clientWordDetector = createWordDetector(connection, "udger_client_regex", "udger_client_regex_words"); deviceWordDetector = createWordDetector(connection, "udger_deviceclass_regex", "udger_deviceclass_regex_words"); osWordDetector = createWordDetector(connection, "udger_os_regex", "udger_os_regex_words"); } } private static WordDetector createWordDetector(Connection connection, String regexTableName, String wordTableName) throws SQLException { Set<Integer> usedWords = new HashSet<>(); addUsedWords(usedWords, connection, regexTableName, "word_id"); addUsedWords(usedWords, connection, regexTableName, "word2_id"); WordDetector result = new WordDetector(); ResultSet rs = connection.createStatement().executeQuery("SELECT * FROM " + wordTableName); if (rs != null) { try { while (rs.next()) { int id = rs.getInt("id"); if (usedWords.contains(id)) { String word = rs.getString("word").toLowerCase(); result.addWord(id, word); } } } finally { rs.close(); } } return result; } private static void addUsedWords(Set<Integer> usedWords, Connection connection, String regexTableName, String wordIdColumn) throws SQLException { ResultSet rs = connection.createStatement().executeQuery("SELECT " + wordIdColumn + " FROM " + regexTableName); if (rs != null) { try { while (rs.next()) { usedWords.add(rs.getInt(wordIdColumn)); } } finally { rs.close(); } } } private int findIdFromList(String uaString, Set<Integer> foundClientWords, List<IdRegString> list) { lastPatternMatcher = null; for (IdRegString irs: list) { if ((irs.wordId1 == 0 || foundClientWords.contains(irs.wordId1)) && (irs.wordId2 == 0 || foundClientWords.contains(irs.wordId2))) { Matcher matcher = irs.pattern.matcher(uaString); if (matcher.find()) { lastPatternMatcher = matcher; return irs.id; } } } return -1; } private int findIdFromListFullScan(String uaString, List<IdRegString> list) { lastPatternMatcher = null; for (IdRegString irs: list) { Matcher matcher = irs.pattern.matcher(uaString); if (matcher.find()) { lastPatternMatcher = matcher; return irs.id; } } return -1; } private static List<IdRegString> prepareRegexpStruct(Connection connection, String regexpTableName) throws SQLException { List<IdRegString> ret = new ArrayList<>(); ResultSet rs = connection.createStatement().executeQuery("SELECT rowid, regstring, word_id, word2_id FROM " + regexpTableName + " ORDER BY sequence"); if (rs != null) { try { while (rs.next()) { IdRegString irs = new IdRegString(); irs.id = rs.getInt("rowid"); irs.wordId1 = rs.getInt("word_id"); irs.wordId2 = rs.getInt("word2_id"); String regex = rs.getString("regstring"); Matcher m = PAT_UNPERLIZE.matcher(regex); if (m.matches()) { regex = m.group(1); } irs.pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); ret.add(irs); } } finally { rs.close(); } } return ret; } private ClientInfo clientDetector(String uaString, UdgerUaResult ret) throws SQLException { ClientInfo clientInfo = new ClientInfo(); ResultSet userAgentRs1 = getFirstRow(UdgerSqlQuery.SQL_CRAWLER, uaString); ResultSet userAgentRs2 = null; try { if (userAgentRs1 != null && userAgentRs1.next()) { fetchUserAgent(userAgentRs1, ret); clientInfo.classId = 99; clientInfo.clientId = -1; } else { int rowid = findIdFromList(uaString, clientWordDetector.findWords(uaString), clientRegstringList); if (rowid != -1) { userAgentRs2 = getFirstRow(UdgerSqlQuery.SQL_CLIENT, rowid); if (userAgentRs2 != null) { userAgentRs2.next(); fetchUserAgent(userAgentRs2, ret); clientInfo.classId = ret.getClassId(); clientInfo.clientId = ret.getClientId(); patchVersions(ret); } } else { ret.setUaClass("Unrecognized"); ret.setUaClassCode("unrecognized"); } } } finally { if (userAgentRs1 != null) { userAgentRs1.close(); } if (userAgentRs2 != null) { userAgentRs2.close(); } } return clientInfo; } private void osDetector(String uaString, UdgerUaResult ret, ClientInfo clientInfo) throws SQLException { int rowid = findIdFromList(uaString, osWordDetector.findWords(uaString), osRegstringList); if (rowid != -1) { ResultSet opSysRs = getFirstRow(UdgerSqlQuery.SQL_OS, rowid); if (opSysRs != null) { try { opSysRs.next(); fetchOperatingSystem(opSysRs, ret); } finally { opSysRs.close(); } } } else { if (clientInfo.clientId != null && clientInfo.clientId != 0) { ResultSet opSysRs = getFirstRow(UdgerSqlQuery.SQL_CLIENT_OS, clientInfo.clientId.toString()); if (opSysRs != null) { try { if (opSysRs.next()) { fetchOperatingSystem(opSysRs, ret); } } finally { opSysRs.close(); } } } } } private void deviceDetector(String uaString, UdgerUaResult ret, ClientInfo clientInfo) throws SQLException { // int rowid = findIdFromList(uaString, deviceWordDetector.findWords(uaString), deviceRegstringList); int rowid = findIdFromListFullScan(uaString, deviceRegstringList); if (rowid != -1) { ResultSet devRs = getFirstRow(UdgerSqlQuery.SQL_DEVICE, rowid); if (devRs != null) { try { devRs.next(); fetchDevice(devRs, ret); } finally { devRs.close(); } } } else { if (clientInfo.classId != null && clientInfo.classId != -1) { ResultSet devRs = getFirstRow(UdgerSqlQuery.SQL_CLIENT_CLASS, clientInfo.classId.toString()); if (devRs != null) { try { if (devRs.next()) { fetchDevice(devRs, ret); } } finally { devRs.close(); } } } } } private void fetchDeviceBrand(String uaString, UdgerUaResult ret) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement(UdgerSqlQuery.SQL_DEVICE_REGEX); preparedStatement.setObject(1, ret.getOsFamilyCode()); preparedStatement.setObject(2, ret.getOsCode()); ResultSet devRegexRs = preparedStatement.executeQuery(); if (devRegexRs != null) { try { while (devRegexRs.next()) { String devId = devRegexRs.getString("id"); String regex = devRegexRs.getString("regstring"); if (devId != null && regex != null) { Pattern patRegex = getRegexFromCache(regex); Matcher matcher = patRegex.matcher(uaString); if (matcher.find()) { ResultSet devNameListRs = getFirstRow(UdgerSqlQuery.SQL_DEVICE_NAME_LIST, devId, matcher.group(1)); if (devNameListRs != null) { try { if (devNameListRs.next()) { ret.setDeviceMarketname(devNameListRs.getString("marketname")); ret.setDeviceBrand(devNameListRs.getString("brand")); ret.setDeviceBrandCode(devNameListRs.getString("brand_code")); ret.setDeviceBrandHomepage(devNameListRs.getString("brand_url")); ret.setDeviceBrandIcon(devNameListRs.getString("icon")); ret.setDeviceBrandIconBig(devNameListRs.getString("icon_big")); ret.setDeviceBrandInfoUrl(UDGER_UA_DEV_BRAND_LIST_URL + devNameListRs.getString("brand_code")); break; } } finally { devNameListRs.close(); } } } } } } finally { devRegexRs.close(); } } } private int[] ip6ToArray(Inet6Address addr) { int ret[] = new int[8]; byte[] bytes = addr.getAddress(); for (int i=0; i < 8; i++) { ret[i] = ((bytes [i*2] << 8 ) & 0xff00 )| (bytes[i*2+1] & 0xff); } return ret; } private void prepare() throws SQLException { connect(); if (clientRegstringList == null) { initStaticStructures(connection); } } private void connect() throws SQLException { if (connection == null) { SQLiteConfig config = new SQLiteConfig(); config.setReadOnly(true); if (inMemoryEnabled) { // we cannot use read only for in memory DB since we need to populate this DB from the file. connection = DriverManager.getConnection("jdbc:sqlite::memory:"); File dbfile = new File(dbFileName); Statement statement = connection.createStatement(); try { statement.executeUpdate("restore from " + dbfile.getPath()); } catch (Exception e) { System.out.println("Error re-constructing in memory data base from Db file."); } } else { connection = DriverManager.getConnection("jdbc:sqlite:" + dbFileName, config.toProperties()); } } } private Pattern getRegexFromCache(String regex) { Pattern patRegex = regexCache.get(regex); if (patRegex == null) { Matcher m = PAT_UNPERLIZE.matcher(regex); if (m.matches()) { regex = m.group(1); } patRegex = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.DOTALL); regexCache.put(regex, patRegex); } return patRegex; } private ResultSet getFirstRow(String query, Object ... params) throws SQLException { PreparedStatement preparedStatement = preparedStmtMap.get(query); if (preparedStatement == null) { preparedStatement = connection.prepareStatement(query); preparedStmtMap.put(query, preparedStatement); } for (int i=0; i < params.length; i++) { preparedStatement.setObject(i + 1, params[i]); } preparedStatement.setMaxRows(1); return preparedStatement.executeQuery(); } private void fetchUserAgent(ResultSet rs, UdgerUaResult ret) throws SQLException { ret.setClassId(rs.getInt("class_id")); ret.setClientId(rs.getInt("client_id")); ret.setCrawlerCategory(nvl(rs.getString("crawler_category"))); ret.setCrawlerCategoryCode(nvl(rs.getString("crawler_category_code"))); ret.setCrawlerLastSeen(nvl(rs.getString("crawler_last_seen"))); ret.setCrawlerRespectRobotstxt(nvl(rs.getString("crawler_respect_robotstxt"))); ret.setUa(nvl(rs.getString("ua"))); ret.setUaClass(nvl(rs.getString("ua_class"))); ret.setUaClassCode(nvl(rs.getString("ua_class_code"))); ret.setUaEngine(nvl(rs.getString("ua_engine"))); ret.setUaFamily(nvl(rs.getString("ua_family"))); ret.setUaFamilyCode(nvl(rs.getString("ua_family_code"))); ret.setUaFamilyHomepage(nvl(rs.getString("ua_family_homepage"))); ret.setUaFamilyIcon(nvl(rs.getString("ua_family_icon"))); ret.setUaFamilyIconBig(nvl(rs.getString("ua_family_icon_big"))); ret.setUaFamilyInfoUrl(nvl(rs.getString("ua_family_info_url"))); ret.setUaFamilyVendor(nvl(rs.getString("ua_family_vendor"))); ret.setUaFamilyVendorCode(nvl(rs.getString("ua_family_vendor_code"))); ret.setUaFamilyVendorHomepage(nvl(rs.getString("ua_family_vendor_homepage"))); ret.setUaUptodateCurrentVersion(nvl(rs.getString("ua_uptodate_current_version"))); ret.setUaVersion(nvl(rs.getString("ua_version"))); ret.setUaVersionMajor(nvl(rs.getString("ua_version_major"))); } private void fetchOperatingSystem(ResultSet rs, UdgerUaResult ret) throws SQLException { ret.setOsFamily(nvl(rs.getString("os_family"))); ret.setOs(nvl(rs.getString("os"))); ret.setOsCode(nvl(rs.getString("os_code"))); ret.setOsFamilyCode(nvl(rs.getString("os_family_code"))); ret.setOsFamilyVedorHomepage(nvl(rs.getString("os_family_vedor_homepage"))); ret.setOsFamilyVendor(nvl(rs.getString("os_family_vendor"))); ret.setOsFamilyVendorCode(nvl(rs.getString("os_family_vendor_code"))); ret.setOsHomePage(nvl(rs.getString("os_home_page"))); ret.setOsIcon(nvl(rs.getString("os_icon"))); ret.setOsIconBig(nvl(rs.getString("os_icon_big"))); ret.setOsInfoUrl(nvl(rs.getString("os_info_url"))); } private void fetchDevice(ResultSet rs, UdgerUaResult ret) throws SQLException { ret.setDeviceClass(nvl(rs.getString("device_class"))); ret.setDeviceClassCode(nvl(rs.getString("device_class_code"))); ret.setDeviceClassIcon(nvl(rs.getString("device_class_icon"))); ret.setDeviceClassIconBig(nvl(rs.getString("device_class_icon_big"))); ret.setDeviceClassInfoUrl(nvl(rs.getString("device_class_info_url"))); } private void patchVersions(UdgerUaResult ret) { if (lastPatternMatcher != null) { String version = ""; if (lastPatternMatcher.groupCount()>=1) { version = lastPatternMatcher.group(1); } ret.setUaVersion(version); ret.setUaVersionMajor(version.split("\\.")[0]); ret.setUa((ret.getUa() != null ? ret.getUa() : "") + " " + version); } else { ret.setUaVersion(""); ret.setUaVersionMajor(""); } } private void fetchUdgerIp(ResultSet rs, UdgerIpResult ret) throws SQLException { ret.setCrawlerCategory(nvl(rs.getString("crawler_category"))); ret.setCrawlerCategoryCode(nvl(rs.getString("crawler_category_code"))); ret.setCrawlerFamily(nvl(rs.getString("crawler_family"))); ret.setCrawlerFamilyCode(nvl(rs.getString("crawler_family_code"))); ret.setCrawlerFamilyHomepage(nvl(rs.getString("crawler_family_homepage"))); ret.setCrawlerFamilyIcon(nvl(rs.getString("crawler_family_icon"))); ret.setCrawlerFamilyInfoUrl(nvl(rs.getString("crawler_family_info_url"))); ret.setCrawlerFamilyVendor(nvl(rs.getString("crawler_family_vendor"))); ret.setCrawlerFamilyVendorCode(nvl(rs.getString("crawler_family_vendor_code"))); ret.setCrawlerFamilyVendorHomepage(nvl(rs.getString("crawler_family_vendor_homepage"))); ret.setCrawlerLastSeen(nvl(rs.getString("crawler_last_seen"))); ret.setCrawlerName(nvl(rs.getString("crawler_name"))); ret.setCrawlerRespectRobotstxt(nvl(rs.getString("crawler_respect_robotstxt"))); ret.setCrawlerVer(nvl(rs.getString("crawler_ver"))); ret.setCrawlerVerMajor(nvl(rs.getString("crawler_ver_major"))); ret.setIpCity(nvl(rs.getString("ip_city"))); ret.setIpClassification(nvl(rs.getString("ip_classification"))); ret.setIpClassificationCode(nvl(rs.getString("ip_classification_code"))); ret.setIpCountry(nvl(rs.getString("ip_country"))); ret.setIpCountryCode(nvl(rs.getString("ip_country_code"))); ret.setIpHostname(nvl(rs.getString("ip_hostname"))); ret.setIpLastSeen(nvl(rs.getString("ip_last_seen"))); } private String nvl(String v) { return v != null ? v : ""; } private void fetchDataCenter(ResultSet rs, UdgerIpResult ret) throws SQLException { ret.setDataCenterHomePage(nvl(rs.getString("datacenter_homepage"))); ret.setDataCenterName(nvl(rs.getString("datacenter_name"))); ret.setDataCenterNameCode(nvl(rs.getString("datacenter_name_code"))); } }
package org.mvel.sh; import org.mvel.MVEL; import static org.mvel.MVEL.*; import org.mvel.integration.impl.DefaultLocalVariableResolverFactory; import org.mvel.integration.impl.MapVariableResolverFactory; import org.mvel.sh.command.basic.BasicCommandSet; import org.mvel.sh.command.file.FileCommandSet; import org.mvel.templates.TemplateRuntime; import static org.mvel.util.PropertyTools.contains; import org.mvel.util.StringAppender; import java.io.*; import static java.lang.Boolean.parseBoolean; import static java.lang.Runtime.getRuntime; import static java.lang.System.arraycopy; import static java.lang.System.getProperty; import java.util.*; import static java.util.ResourceBundle.getBundle; /** * @author Christopher Brock */ public class ShellSession { public static final String PROMPT_VAR = "$PROMPT"; private static final String[] EMPTY = new String[0]; private final Map<String, Command> commands = new HashMap<String, Command>(); private Map<String, Object> variables; private Map<String, String> env; private Object ctxObject; DefaultLocalVariableResolverFactory lvrf; private int depth; private boolean multi = false; private int multiIndentSize = 0; private PrintStream out = System.out; private String prompt; private String commandBuffer; public ShellSession() { System.out.println("Starting session..."); variables = new HashMap<String, Object>(); env = new HashMap<String, String>(); commands.putAll(new BasicCommandSet().load()); commands.putAll(new FileCommandSet().load()); env.put(PROMPT_VAR, DefaultEnvironment.PROMPT); env.put("$OS_NAME", getProperty("os.name")); env.put("$OS_VERSION", getProperty("os.version")); env.put("$JAVA_VERSION", getProperty("java.version")); env.put("$CWD", new File(".").getAbsolutePath()); env.put("$COMMAND_PASSTRU", "false"); env.put("$PRINTOUTPUT", "true"); env.put("$ECHO", "false"); env.put("$SHOW_TRACES", "true"); env.put("$USE_OPTIMIZER_ALWAYS", "false"); env.put("$PATH", ""); try { ResourceBundle bundle = getBundle(".mvelsh.properties"); Enumeration<String> enumer = bundle.getKeys(); String key; while (enumer.hasMoreElements()) { env.put(key = enumer.nextElement(), bundle.getString(key)); } } catch (MissingResourceException e) { System.out.println("No config file found. Loading default config."); if (!contains(getProperty("os.name").toLowerCase(), "windows")) { env.put("$PATH", "/bin:/usr/bin:/sbin:/usr/sbin"); } } lvrf = new DefaultLocalVariableResolverFactory(variables); lvrf.appendFactory(new MapVariableResolverFactory(env)); } public ShellSession(String init) { this(); exec(init); } //todo: fix this public void run() { StringAppender inBuffer = new StringAppender(); String[] inTokens; Object outputBuffer; final PrintStream sysPrintStream = System.out; final PrintStream sysErrorStream = System.err; final InputStream sysInputStream = System.in; // final InputStreamReader readBuffer = new InputStreamReader(System.in); final BufferedReader readBuffer = new BufferedReader(new InputStreamReader(System.in)); File execFile; try { //noinspection InfiniteLoopStatement while (true) { printPrompt(); if (commandBuffer == null) { commandBuffer = readBuffer.readLine(); } if ("true".equals(env.get("$ECHO"))) { out.println(">" + commandBuffer); out.flush(); } if (commands.containsKey((inTokens = inBuffer.append(commandBuffer).toString().split("\\s"))[0])) { commandBuffer = null; String[] passParameters; if (inTokens.length > 1) { arraycopy(inTokens, 1, passParameters = new String[inTokens.length - 1], 0, passParameters.length); } else { passParameters = EMPTY; } try { commands.get(inTokens[0]).execute(this, passParameters); } catch (CommandException e) { out.append("Error: ").append(e.getMessage()).append("\n"); } } else { commandBuffer = null; outputBuffer = null; try { if (shouldDefer(inBuffer)) { multi = true; continue; } else { multi = false; } if (parseBoolean(env.get("$USE_OPTIMIZER_ALWAYS"))) { outputBuffer = executeExpression(compileExpression(inBuffer.toString()), ctxObject, lvrf); } else { outputBuffer = eval(inBuffer.toString(), ctxObject, lvrf); } } catch (Exception e) { if ("true".equals(env.get("$COMMAND_PASSTHRU"))) { String[] paths; String s; if ((s = inTokens[0]).startsWith("./")) { s = new File(env.get("$CWD")).getAbsolutePath() + s.substring(s.indexOf('/')); paths = new String[]{s}; } else { paths = env.get("$PATH").split("(:|;)"); } boolean successfulExec = false; for (String execPath : paths) { if ((execFile = new File(execPath + "/" + s)).exists() && execFile.isFile()) { successfulExec = true; String[] execString = new String[inTokens.length]; execString[0] = execFile.getAbsolutePath(); System.arraycopy(inTokens, 1, execString, 1, inTokens.length - 1); try { final Process p = getRuntime().exec(execString); final OutputStream outStream = p.getOutputStream(); final InputStream inStream = p.getInputStream(); final InputStream errStream = p.getErrorStream(); final RunState runState = new RunState(this); final Thread pollingThread = new Thread(new Runnable() { public void run() { byte[] buf = new byte[25]; int read; while (true) { try { while ((read = inStream.read(buf)) > 0) { for (int i = 0; i < read; i++) { sysPrintStream.print((char) buf[i]); } sysPrintStream.flush(); } if (!runState.isRunning()) break; } catch (Exception e) { break; } } sysPrintStream.flush(); if (!multi) { multiIndentSize = (prompt = String.valueOf(TemplateRuntime.eval(env.get("$PROMPT"), variables))).length(); out.append(prompt); } else { out.append(">").append(indent((multiIndentSize - 1) + (depth * 4))); } } }); final Thread watchThread = new Thread(new Runnable() { public void run() { Thread runningThread = new Thread(new Runnable() { public void run() { try { String read; while (runState.isRunning()) { while ((read = readBuffer.readLine()) != null) { if (runState.isRunning()) { for (char c : read.toCharArray()) { outStream.write((byte) c); } } else { runState.getSession().setCommandBuffer(read); break; } } } outStream.write((byte) '\n'); outStream.flush(); } catch (Exception e2) { } } }); runningThread.setPriority(Thread.MIN_PRIORITY); runningThread.start(); try { p.waitFor(); } catch (InterruptedException e) { // nothing; } sysPrintStream.flush(); runState.setRunning(false); try { runningThread.join(); } catch (InterruptedException e) { // nothing; } } }); pollingThread.setPriority(Thread.MIN_PRIORITY); pollingThread.start(); watchThread.setPriority(Thread.MIN_PRIORITY); watchThread.start(); watchThread.join(); try { pollingThread.notify(); } catch (Exception ne) { } } catch (Exception e2) { // fall through; } } } if (successfulExec) { inBuffer.reset(); continue; } } ByteArrayOutputStream stackTraceCap = new ByteArrayOutputStream(); PrintStream capture = new PrintStream(stackTraceCap); e.printStackTrace(capture); capture.flush(); env.put("$LAST_STACK_TRACE", new String(stackTraceCap.toByteArray())); if (parseBoolean(env.get("$SHOW_TRACE"))) { out.println(env.get("$LAST_STACK_TRACE")); } else { out.println(e.toString()); } inBuffer.reset(); continue; } if (outputBuffer != null && "true".equals(env.get("$PRINTOUTPUT"))) { out.println(String.valueOf(outputBuffer)); } } inBuffer.reset(); } } catch (Exception e) { e.printStackTrace(); System.out.println("unexpected exception. exiting."); } } public void printPrompt() { if (!multi) { multiIndentSize = (prompt = String.valueOf(TemplateRuntime.eval(env.get("$PROMPT"), variables))).length(); out.append(prompt); } else { out.append(">").append(indent((multiIndentSize - 1) + (depth * 4))); } } public boolean shouldDefer(StringAppender inBuf) { char[] buffer = new char[inBuf.length()]; inBuf.getChars(0, inBuf.length(), buffer, 0); depth = 0; for (char aBuffer : buffer) { switch (aBuffer) { case '{': depth++; break; case '}': depth break; } } return depth > 0; } public String indent(int size) { StringBuffer sbuf = new StringBuffer(); for (int i = 0; i < size; i++) sbuf.append(" "); return sbuf.toString(); } public Map<String, Command> getCommands() { return commands; } public Map<String, Object> getVariables() { return variables; } public Map<String, String> getEnv() { return env; } public Object getCtxObject() { return ctxObject; } public void setCtxObject(Object ctxObject) { this.ctxObject = ctxObject; } public String getCommandBuffer() { return commandBuffer; } public void setCommandBuffer(String commandBuffer) { this.commandBuffer = commandBuffer; } public void exec(String command) { MVEL.eval(command, ctxObject, lvrf); } public static final class RunState { private boolean running = true; private ShellSession session; public RunState(ShellSession session) { this.session = session; } public ShellSession getSession() { return session; } public void setSession(ShellSession session) { this.session = session; } public boolean isRunning() { return running; } public void setRunning(boolean running) { this.running = running; } } }
package org.scm4j.vcs.svn; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.scm4j.vcs.api.*; import org.scm4j.vcs.api.exceptions.*; import org.scm4j.vcs.api.workingcopy.IVCSLockedWorkingCopy; import org.scm4j.vcs.api.workingcopy.IVCSRepositoryWorkspace; import org.tmatesoft.svn.core.*; import org.tmatesoft.svn.core.auth.BasicAuthenticationManager; import org.tmatesoft.svn.core.auth.SVNAuthentication; import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication; import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.core.io.SVNRepositoryFactory; import org.tmatesoft.svn.core.wc.*; import org.tmatesoft.svn.core.wc2.SvnDiff; import org.tmatesoft.svn.core.wc2.SvnDiffSummarize; import org.tmatesoft.svn.core.wc2.SvnOperationFactory; import org.tmatesoft.svn.core.wc2.SvnTarget; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileWriter; import java.nio.charset.StandardCharsets; import java.util.*; public class SVNVCS implements IVCS { private static final int SVN_PATH_IS_NOT_WORKING_COPY_ERROR_CODE = 155007; private static final int SVN_ITEM_EXISTS_ERROR_CODE = 160020; private static final int SVN_FILE_NOT_FOUND_ERROR_CODE = 160013; public static final String MASTER_PATH= "trunk/"; public static final String BRANCHES_PATH = "branches/"; public static final String TAGS_PATH = "tags/"; public static final String SVN_VCS_TYPE_STRING = "svn"; private BasicAuthenticationManager authManager; private SVNRepository repository; private final ISVNOptions options; private SVNClientManager clientManager; private SVNURL trunkSVNUrl; private SVNAuthentication userPassAuth; private IVCSRepositoryWorkspace repo; private String repoUrl; public void setClientManager(SVNClientManager clientManager) { this.clientManager = clientManager; } public SVNClientManager getClientManager() { return clientManager; } public ISVNOptions getOptions() { return options; } public SVNURL getTrunkSVNUrl() { return trunkSVNUrl; } public SVNRepository getSVNRepository() { return repository; } public void setSVNRepository(SVNRepository repository) { this.repository = repository; } public void setRepo(IVCSRepositoryWorkspace repo) { this.repo = repo; } public SVNVCS(IVCSRepositoryWorkspace repo, String user, String password) { this.repo = repo; repoUrl = repo.getRepoUrl().trim(); if (!repoUrl.endsWith("/") && !repoUrl.endsWith("\\")) { repoUrl += "/"; } options = SVNWCUtil.createDefaultOptions(true); try { trunkSVNUrl = SVNURL.parseURIEncoded(repo.getRepoUrl().replace("\\", "/")); repository = SVNRepositoryFactory.create(trunkSVNUrl); } catch (SVNException e) { throw new EVCSException(e); } userPassAuth = SVNPasswordAuthentication.newInstance(user, (password == null ? null : password.toCharArray()), true, trunkSVNUrl, false); authManager = new BasicAuthenticationManager(new SVNAuthentication[] {userPassAuth}); repository.setAuthenticationManager(authManager); clientManager = SVNClientManager.newInstance( options, repository.getAuthenticationManager()); } public SVNURL getBranchUrl(String branchPath) throws SVNException { return SVNURL.parseURIEncoded(repoUrl + getBranchName(branchPath)); } @Override public void createBranch(String srcBranchName, String dstBranchName, String commitMessage) throws EVCSBranchExists { try { SVNURL fromUrl = getBranchUrl(srcBranchName); SVNURL toUrl = getBranchUrl(dstBranchName); SVNCopyClient copyClient = clientManager.getCopyClient(); SVNCopySource copySource = new SVNCopySource(SVNRevision.HEAD, SVNRevision.HEAD, fromUrl); copySource.setCopyContents(false); copyClient.doCopy(new SVNCopySource[] { copySource }, toUrl, false, // isMove true, // make parents true, // failWhenDstExists commitMessage, // commit message null); // SVNProperties } catch (SVNException e) { if (e.getErrorMessage().getErrorCode().getCode() == SVN_ITEM_EXISTS_ERROR_CODE) { throw new EVCSBranchExists(dstBranchName); } throw new EVCSException(e); } } @Override public void deleteBranch(String branchName, String commitMessage) { try { clientManager .getCommitClient() .doDelete(new SVNURL[] { getBranchUrl(branchName) }, commitMessage); } catch (SVNException e) { throw new EVCSException(e); } } @Override public VCSMergeResult merge(String srcBranchName, String dstBranchName, String commitMessage) { SVNDiffClient diffClient = clientManager.getDiffClient(); try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy()) { checkout(getBranchUrl(dstBranchName), wc.getFolder(), null); DefaultSVNOptions options = (DefaultSVNOptions) diffClient.getOptions(); final List<String> conflictingFiles = new ArrayList<>(); options.setConflictHandler(conflictDescription -> { conflictingFiles.add(conflictDescription.getMergeFiles().getLocalPath()); return new SVNConflictResult(SVNConflictChoice.POSTPONE, conflictDescription.getMergeFiles().getResultFile()); }); SVNRevisionRange range = new SVNRevisionRange(SVNRevision.create(1), SVNRevision.HEAD); try { diffClient.doMerge(getBranchUrl(srcBranchName), SVNRevision.HEAD, Collections.singleton(range), wc.getFolder(), SVNDepth.UNKNOWN, true, false, false, false); Boolean success = conflictingFiles.isEmpty(); if (success) { clientManager .getCommitClient() .doCommit(new File[] {wc.getFolder()}, false, commitMessage, new SVNProperties(), null, true, true, SVNDepth.INFINITY); } else { try { SVNWCClient wcClient = getRevertClient(options); wcClient.doRevert(new File[] {wc.getFolder()}, SVNDepth.INFINITY, null); } catch (Exception e) { // It doesn't matter if we failed to revert. Just make the workspace corrupted. wc.setCorrupted(true); } } return new VCSMergeResult(success, conflictingFiles); } catch (SVNException e) { wc.setCorrupted(true); throw e; } } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } SVNWCClient getRevertClient(DefaultSVNOptions options) { return new SVNWCClient(authManager, options); } private void checkout(SVNURL sourceUrl, File destPath, String revision) throws SVNException { SVNUpdateClient updateClient = clientManager.getUpdateClient(); updateClient.setIgnoreExternals(false); SVNRevision svnRevision = revision == null ? SVNRevision.HEAD : SVNRevision.parse(revision); if (isWorkingCopyInited(destPath)) { updateClient.doSwitch(destPath, sourceUrl, svnRevision, svnRevision, SVNDepth.INFINITY, false, false); } else { updateClient.doCheckout(sourceUrl, destPath, svnRevision, svnRevision, SVNDepth.UNKNOWN, false); } } public boolean isWorkingCopyInited(File destPath) { try { clientManager.getStatusClient().doStatus(destPath, false); return true; } catch (SVNException e) { if (e.getErrorMessage().getErrorCode().getCode() == SVN_PATH_IS_NOT_WORKING_COPY_ERROR_CODE) { return false; } else { throw new EVCSException(e); } } } @Override public void setCredentials(String user, String password) { userPassAuth = SVNPasswordAuthentication.newInstance(user, password == null ? null : password.toCharArray(), true, trunkSVNUrl, false); authManager.setAuthentications(new SVNAuthentication[] {userPassAuth}); clientManager = SVNClientManager.newInstance( options, repository.getAuthenticationManager()); } @Override public void setProxy(String host, int port, String proxyUser, String proxyPassword) { authManager.setProxy(host, port, proxyUser, proxyPassword.toCharArray()); } @Override public String getFileContent(String branchName, String filePath, String revision) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { repository.getFile(new File(getBranchName(branchName), filePath).getPath().replace("\\", "/"), (revision == null || revision.isEmpty()) ? -1 : Long.parseLong(revision), new SVNProperties(), baos); return baos.toString(StandardCharsets.UTF_8.name()); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode().getCode() == SVN_FILE_NOT_FOUND_ERROR_CODE) { try { if (repository.checkPath(getBranchName(branchName), -1L) == SVNNodeKind.NONE) { throw new EVCSBranchNotFound(getRepoUrl(), getBranchName(branchName)); } } catch (SVNException e1) { throw new EVCSException(e1); } throw new EVCSFileNotFound(getRepoUrl(), getBranchName(branchName), filePath, revision); } throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } private String getBranchName(String branchName) { return branchName == null ? MASTER_PATH : BRANCHES_PATH + branchName; } @Override public VCSCommit setFileContent(String branchName, String filePath, String content, String commitMessage) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy()) { checkout(getBranchUrl(branchName), wc.getFolder(), null); File file = new File(wc.getFolder(), filePath); Boolean needToAdd = !file.exists(); if (!file.exists()) { FileUtils.forceMkdir(file.getParentFile()); file.createNewFile(); } FileWriter writer = new FileWriter(file); writer.write(content); writer.close(); if (needToAdd) { clientManager .getWCClient() .doAdd(file, true /* force, avoiding "file is already under version control" exception */, false, false, SVNDepth.EMPTY, false, true); } try { SVNCommitInfo newCommit = clientManager .getCommitClient() .doCommit(new File[] { wc.getFolder() }, false, commitMessage, new SVNProperties(), null, false, false, SVNDepth.INFINITY); return newCommit == SVNCommitInfo.NULL ? VCSCommit.EMPTY : new VCSCommit(Long.toString(newCommit.getNewRevision()), commitMessage, newCommit.getAuthor()); } catch (SVNException e) { wc.setCorrupted(true); throw e; } } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public String getRepoUrl() { return repo.getRepoUrl(); } private List<VCSDiffEntry> fillUnifiedDiffs(final String srcBranchName, final String dstBranchName, List<VCSDiffEntry> entries) throws Exception { List<VCSDiffEntry> res = new ArrayList<>(); for (VCSDiffEntry entry : entries) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); final SvnOperationFactory svnOperationFactory = new SvnOperationFactory(); final SvnDiff diff = svnOperationFactory.createDiff(); if (entry.getChangeType() == VCSChangeType.ADD) { SVNLogEntry firstCommit = getBranchFirstCommit(dstBranchName); diff.setSource(SvnTarget.fromURL(getBranchUrl(srcBranchName).appendPath(entry.getFilePath(), true), SVNRevision.HEAD), SVNRevision.create(firstCommit.getRevision()), SVNRevision.create(repository.info(getBranchName(dstBranchName), -1).getRevision())); } else if (entry.getChangeType() == VCSChangeType.DELETE) { SVNLogEntry firstCommit = getBranchFirstCommit(dstBranchName); diff.setSource(SvnTarget.fromURL(getBranchUrl(dstBranchName).appendPath(entry.getFilePath(), true), SVNRevision.HEAD), SVNRevision.create(repository.info(getBranchName(dstBranchName), -1).getRevision()), SVNRevision.create(firstCommit.getRevision())); } else { diff.setSources( SvnTarget.fromURL(getBranchUrl(dstBranchName).appendPath(entry.getFilePath(), true), SVNRevision.HEAD), SvnTarget.fromURL(getBranchUrl(srcBranchName).appendPath(entry.getFilePath(), true), SVNRevision.HEAD)); } diff.setOutput(baos); diff.run(); res.add(new VCSDiffEntry(entry.getFilePath(), entry.getChangeType(), baos.toString("UTF-8"))); } return res; } private SVNLogEntry getDirFirstCommit(final String dir) throws SVNException { @SuppressWarnings("unchecked") Collection<SVNLogEntry> entries = repository.log(new String[] { dir }, null, 0 /* start from first commit */, -1 /* to the head commit */, true, true); return entries.iterator().next(); } SVNLogEntry getBranchFirstCommit(final String branchPath) throws SVNException { return getDirFirstCommit(getBranchName(branchPath)); } private List<VCSDiffEntry> getDiffEntries(final String srcBranchName, final String dstBranchName) throws Exception { final SvnOperationFactory svnOperationFactory = new SvnOperationFactory(); final SvnDiffSummarize summarizeDiff = svnOperationFactory.createDiffSummarize(); final List<VCSDiffEntry> res = new ArrayList<>(); summarizeDiff.setSources( SvnTarget.fromURL(getBranchUrl(dstBranchName), SVNRevision.HEAD), SvnTarget.fromURL(getBranchUrl(srcBranchName), SVNRevision.HEAD)); summarizeDiff.setReceiver((target, diffStatus) -> { if (diffStatus.getPath().length() == 0) { return; } VCSDiffEntry entry = new VCSDiffEntry(diffStatus.getPath(), SVNChangeTypeToVCSChangeType(diffStatus.getModificationType()), null); res.add(entry); }); summarizeDiff.run(); return res; } public VCSChangeType SVNChangeTypeToVCSChangeType(SVNStatusType modificationType) { if (SVNStatusType.STATUS_ADDED.equals(modificationType)) { return VCSChangeType.ADD; } else if (SVNStatusType.STATUS_DELETED.equals(modificationType)) { return VCSChangeType.DELETE; } else if (SVNStatusType.STATUS_MODIFIED.equals(modificationType)) { return VCSChangeType.MODIFY; } else { return VCSChangeType.UNKNOWN; } } @Override public List<VCSDiffEntry> getBranchesDiff(final String srcBranchName, final String dstBranchName) { try (IVCSLockedWorkingCopy wc = repo.getVCSLockedWorkingCopy()) { checkout(getBranchUrl(dstBranchName), wc.getFolder(), null); List<VCSDiffEntry> entries = getDiffEntries(srcBranchName, dstBranchName); entries = fillUnifiedDiffs(srcBranchName, dstBranchName, entries); return entries; } catch (SVNException e) { throw new EVCSException(e); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Set<String> getBranches(String path) { try { List<String> entries = listEntries(SVNVCS.BRANCHES_PATH + (path == null ? "" : path)); Set<String> tempRes = new HashSet<>(entries); if (repository.checkPath(MASTER_PATH, -1) == SVNNodeKind.DIR) { if (path == null || MASTER_PATH.startsWith(path) ) { tempRes.add(MASTER_PATH.replace("/", "")); } } Set<String> res = new HashSet<>(); for (String str : tempRes) { res.add(StringUtils.removeStart(str, SVNVCS.BRANCHES_PATH)); } return res; } catch (SVNException e) { throw new EVCSException(e); } } @SuppressWarnings("unchecked") List<String> listEntries(String path) throws SVNException { List<String> res = new ArrayList<>(); if (path == null) { return res; } path = path.trim(); String lastFolder; String folderPrefix; int lastSlashIndex = path.lastIndexOf("/"); lastFolder = lastSlashIndex > 0 ? path.substring(0, lastSlashIndex) : path; folderPrefix = lastSlashIndex > 0 ? path.substring(lastSlashIndex + 1) : ""; Collection<SVNDirEntry> entries = repository.getDir(lastFolder, -1 , null , (Collection<SVNDirEntry>) null); List<SVNDirEntry> entriesList = new ArrayList<>(entries); Collections.sort(entriesList, (o1, o2) -> { if (o1.getRevision() < o2.getRevision()) { return -1; } if (o1.getRevision() > o2.getRevision()) { return 1; } return 0; }); for (SVNDirEntry entry : entriesList) { if (entry.getKind() == SVNNodeKind.DIR && entry.getName().startsWith(folderPrefix)) { String branchName = (path.isEmpty() ? "" : StringUtils.appendIfMissing(lastFolder, "/")) + entry.getName(); res.add(branchName); } } return res; } @Override public List<VCSCommit> log(String branchName, int limit) { final List<VCSCommit> res = new ArrayList<>(); try { getBranchUrl(branchName); // for exception test only repository.log(new String[] { getBranchName(branchName) }, -1L /* start from head descending */, 0L, true, true, limit, logEntry -> res.add(svnLogEntryToVCSCommit(logEntry))); return res; } catch (SVNException e) { throw new EVCSException(e); } } @Override public String getVCSTypeString() { return SVN_VCS_TYPE_STRING; } @Override public VCSCommit removeFile(String branchName, String filePath, String commitMessage) { try { SVNCommitInfo res = clientManager .getCommitClient() .doDelete(new SVNURL[] {getBranchUrl(branchName).appendPath(filePath, true)}, commitMessage); return new VCSCommit(Long.toString(res.getNewRevision()), commitMessage, res.getAuthor()); } catch (SVNException e) { throw new EVCSException(e); } } @Override public List<VCSCommit> getCommitsRange(String branchName, String startRevision, WalkDirection direction, int limit) { final List<VCSCommit> res = new ArrayList<>(); try { Long startRevisionLong; Long endRevisionLong; if (direction == WalkDirection.ASC) { startRevisionLong = startRevision == null ? getBranchFirstCommit(branchName).getRevision() : Long.parseLong(startRevision); endRevisionLong = Long.parseLong(getHeadCommit(branchName).getRevision()); } else { startRevisionLong = startRevision == null ? Long.parseLong(getHeadCommit(branchName).getRevision()) : Long.parseLong(startRevision); endRevisionLong = getBranchFirstCommit(branchName).getRevision(); } repository.log(new String[] { getBranchName(branchName) }, startRevisionLong, endRevisionLong, true, true, limit, logEntry -> { VCSCommit commit = svnLogEntryToVCSCommit(logEntry); res.add(commit); }); return res; } catch (SVNException e) { throw new EVCSException(e); } } private VCSCommit svnLogEntryToVCSCommit(SVNLogEntry logEntry) { return new VCSCommit(Long.toString(logEntry.getRevision()), logEntry.getMessage(), logEntry.getAuthor()); } @Override public List<VCSCommit> getCommitsRange(String branchName, String startRevision, String endRevision) { final List<VCSCommit> res = new ArrayList<>(); try { Long startRevisionLong = startRevision == null ? getBranchFirstCommit(branchName).getRevision() : Long.parseLong(startRevision); Long endRevisionLong = endRevision == null ? -1L : Long.parseLong(endRevision); repository.log(new String[] { getBranchName(branchName) }, startRevisionLong, endRevisionLong, true, true, 0 /* limit */, logEntry -> res.add(svnLogEntryToVCSCommit(logEntry))); return res; } catch (SVNException e) { throw new EVCSException(e); } } @Override public VCSCommit getHeadCommit(String branchName) { try { SVNLogEntry headEntry = getDirHeadLogEntry(getBranchName(branchName)); return new VCSCommit(Long.toString(headEntry.getRevision()), headEntry.getMessage(), headEntry.getAuthor()); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode().getCode() == SVN_FILE_NOT_FOUND_ERROR_CODE) { return null; } throw new EVCSException(e); } } SVNLogEntry getDirHeadLogEntry(String dir) throws SVNException { @SuppressWarnings("unchecked") Collection<SVNLogEntry> entries = repository.log(new String[] { dir }, null, -1 /* start from head commit */, 0 /* to the first commit */, true, true); return entries.iterator().next(); } @Override public String toString() { return "SVNVCS [url=" + repo.getRepoUrl() + "]"; } @Override public Boolean fileExists(String branchName, String filePath) { try { SVNNodeKind nodeKind = repository.checkPath( new File(getBranchName(branchName), filePath).getPath().replace("\\", "/") , -1 ); return nodeKind == SVNNodeKind.FILE; } catch (SVNException e) { throw new EVCSException(e); } } @Override public VCSTag createTag(String branchName, String tagName, String tagMessage, String revisionToTag) throws EVCSTagExists { try { SVNURL srcURL = getBranchUrl(branchName); SVNURL dstURL = SVNURL.parseURIEncoded(repoUrl + TAGS_PATH + tagName); SVNLogEntry copyFromEntry = revToSVNEntry(getBranchName(branchName), revisionToTag == null ? SVNRevision.HEAD.getNumber() : Long.parseLong(revisionToTag)); SVNCopySource copySource = revisionToTag == null ? new SVNCopySource(SVNRevision.HEAD, SVNRevision.create(copyFromEntry.getRevision()), srcURL) : new SVNCopySource(SVNRevision.parse(revisionToTag), SVNRevision.parse(revisionToTag), srcURL); clientManager.getCopyClient().doCopy(new SVNCopySource[] {copySource}, dstURL, false, false, true, tagMessage, null); SVNDirEntry entry = repository.info(TAGS_PATH + tagName, -1); return new VCSTag(tagName, tagMessage, entry.getAuthor(), svnLogEntryToVCSCommit(copyFromEntry)); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode().getCode() == SVN_ITEM_EXISTS_ERROR_CODE) { throw new EVCSTagExists(e); } throw new EVCSException(e); } } SVNLogEntry revToSVNEntry(String branchName, Long rev) throws SVNException { SVNDirEntry info = repository.info(branchName, rev); @SuppressWarnings("unchecked") Collection<SVNLogEntry> entries = repository.log(new String[] {branchName}, null, info.getRevision(), info.getRevision(), true, true); if (entries != null) { return entries.iterator().next(); } return null; } @Override public List<VCSTag> getTags() { try { return getTags(null); } catch (SVNException e) { throw new EVCSException(e); } } @Override public void removeTag(String tagName) { try { clientManager .getCommitClient() .doDelete(new SVNURL[] { SVNURL.parseURIEncoded(repoUrl + TAGS_PATH + tagName) }, null); } catch (SVNException e) { throw new EVCSException(e); } } @Override public void checkout(String branchName, String targetPath, String revision) { try { checkout(getBranchUrl(branchName), new File(targetPath), revision); } catch (SVNException e) { throw new EVCSException(e); } } List<VCSTag> getTags(String onRevision) throws SVNException { List<VCSTag> res = new ArrayList<>(); @SuppressWarnings("unchecked") Collection<SVNDirEntry> dirEntries = repository.getDir(TAGS_PATH, -1 , null, (Collection<SVNDirEntry>) null); for (SVNDirEntry dirEntry : dirEntries) { long tagCopyFrom = 0; SVNLogEntry tagEntry = getDirFirstCommit(TAGS_PATH + dirEntry.getName()); for (SVNLogEntryPath entryPath : tagEntry.getChangedPaths().values()) { tagCopyFrom = entryPath.getCopyRevision(); } if (onRevision == null || tagCopyFrom == Long.parseLong(onRevision)) { SVNProperties props = repository.getRevisionProperties(tagCopyFrom, null); res.add(new VCSTag(dirEntry.getName(), tagEntry.getMessage(), tagEntry.getAuthor(), new VCSCommit(Long.toString(tagCopyFrom), props.getStringValue(SVNRevisionProperty.LOG), props.getStringValue(SVNRevisionProperty.AUTHOR)))); } } return res; } @Override public List<VCSTag> getTagsOnRevision(String revision) { try { return getTags(revision); } catch (SVNException e) { if (e.getErrorMessage().getErrorCode().getCode() == SVN_FILE_NOT_FOUND_ERROR_CODE) { return new ArrayList<>(); } throw new EVCSException(e); } } }