answer
stringlengths
17
10.2M
package org.eclipse.gemini.mgmt.useradmin; import java.io.IOException; import java.util.ArrayList; import javax.management.openmbean.CompositeData; import javax.management.openmbean.OpenDataException; import javax.management.openmbean.TabularData; import org.osgi.framework.InvalidSyntaxException; import org.eclipse.gemini.mgmt.internal.OSGiProperties; import org.eclipse.gemini.mgmt.useradmin.internal.OSGiAuthorization; import org.eclipse.gemini.mgmt.useradmin.internal.OSGiGroup; import org.eclipse.gemini.mgmt.useradmin.internal.OSGiRole; import org.eclipse.gemini.mgmt.useradmin.internal.OSGiUser; import org.osgi.jmx.service.useradmin.UserAdminMBean; import org.osgi.service.useradmin.Group; import org.osgi.service.useradmin.Role; import org.osgi.service.useradmin.User; import org.osgi.service.useradmin.UserAdmin; public final class UserManager implements UserAdminMBean { private UserAdmin admin; public UserManager(UserAdmin admin) { this.admin = admin; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public void addCredential(String key, byte[] value, String username) throws IOException { if (username == null) { throw new IOException("User name must not be null"); } if (key == null) { throw new IOException("Credential key must not be null"); } User user; try { user = (User) admin.getRole(username); } catch (ClassCastException e) { throw new IOException("Not a User: " + username); } if (user == null) { throw new IOException("Not a User: " + username); } user.getCredentials().put(key, value); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public void addCredentialString(String key, String value, String username) throws IOException { if (username == null) { throw new IOException("User name must not be null"); } if (key == null) { throw new IOException("Credential key must not be null"); } User user; try { user = (User) admin.getRole(username); } catch (ClassCastException e) { throw new IOException("Not a User: " + username); } if (user == null) { throw new IOException("Not a User: " + username); } user.getCredentials().put(key, value); } /** * {@inheritDoc} */ public boolean addMember(String groupname, String rolename) throws IOException { if (groupname == null) { throw new IOException("Group name must not be null"); } if (rolename == null) { throw new IOException("Role name must not be null"); } Role group = admin.getRole(groupname); if (group == null) { throw new IOException("Group does not exist: " + groupname); } Role role = admin.getRole(rolename); if (role == null) { throw new IOException("Role does not exist: " + rolename); } return group.getType() == Role.GROUP && ((Group) group).addMember(role); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public void addProperty(String key, byte[] value, String rolename) throws IOException { if (rolename == null) { throw new IOException("Role name must not be null"); } if (key == null) { throw new IOException("Credential key must not be null"); } Role role = admin.getRole(rolename); if (role == null) { throw new IOException("Role does not exist: " + rolename); } role.getProperties().put(key, value); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public void addPropertyString(String key, String value, String rolename) throws IOException { if (rolename == null) { throw new IOException("Role name must not be null"); } if (key == null) { throw new IOException("Credential key must not be null"); } Role role = admin.getRole(rolename); if (role == null) { throw new IOException("Role does not exist: " + rolename); } role.getProperties().put(key, value); } /** * {@inheritDoc} */ public boolean addRequiredMember(String groupname, String rolename) throws IOException { if (groupname == null) { throw new IOException("Group name must not be null"); } Role group = admin.getRole(groupname); if (group == null) { throw new IOException("Group does not exist: " + rolename); } Role role = admin.getRole(rolename); if (role == null) { throw new IOException("Role does not exist: " + rolename); } return group.getType() == Role.GROUP && ((Group) group).addRequiredMember(role); } /** * {@inheritDoc} */ public void createGroup(String name) throws IOException { if (name == null) { throw new IOException("Name must not be null"); } admin.createRole(name, Role.GROUP); } /** * {@inheritDoc} */ public void createUser(String name) throws IOException { if (name == null) { throw new IOException("Name must not be null"); } admin.createRole(name, Role.USER); } /** * {@inheritDoc} */ public void createRole(String name) throws IOException { throw new UnsupportedOperationException("This method is deprecated and does not work"); } /** * {@inheritDoc} */ public CompositeData getAuthorization(String u) throws IOException { if (u == null) { throw new IOException("User name must not be null"); } User user; try { user = (User) admin.getRole(u); } catch (ClassCastException e) { throw new IOException("Not a user: " + u); } try { return new OSGiAuthorization(admin.getAuthorization(user)).asCompositeData(); } catch (OpenDataException e) { throw new IOException("Unable to create open data type: " + e); } } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public TabularData getCredentials(String username) throws IOException { if (username == null) { throw new IOException("User name must not be null"); } User user; try { user = (User) admin.getRole(username); } catch (ClassCastException e) { throw new IOException("Not a user: " + username); } if (user == null) { throw new IOException("Not a user: " + username); } return OSGiProperties.tableFrom(user.getCredentials()); } /** * {@inheritDoc} */ public CompositeData getGroup(String groupname) throws IOException { if (groupname == null) { throw new IOException("Group name must not be null"); } Group group; try { group = (Group) admin.getRole(groupname); } catch (ClassCastException e) { throw new IOException("Not a group: " + groupname); } try { return new OSGiGroup(group).asCompositeData(); } catch (OpenDataException e) { throw new IOException("Cannot encode open data for group: " + e); } } /** * {@inheritDoc} */ public String[] listGroups() throws IOException { Role[] roles; try { roles = admin.getRoles(null); } catch (InvalidSyntaxException e) { throw new IllegalStateException("Cannot use null filter, apparently: " + e); } ArrayList<String> groups = new ArrayList<String>(); for (Role role : roles) { if (role.getType() == Role.GROUP) { groups.add(role.getName()); } } return groups.toArray(new String[groups.size()]); } /** * {@inheritDoc} */ public String[] getGroups(String filter) throws IOException { Role[] roles; try { roles = admin.getRoles(filter); } catch (InvalidSyntaxException e) { throw new IOException("Invalid filter: " + e); } ArrayList<String> groups = new ArrayList<String>(); for (Role role : roles) { if (role.getType() == Role.GROUP) { groups.add(role.getName()); } } return groups.toArray(new String[groups.size()]); } /** * {@inheritDoc} */ public String[] getImpliedRoles(String username) throws IOException { if (username == null) { throw new IOException("Name must not be null"); } Role role = admin.getRole(username); if (role.getType() == Role.USER && role instanceof User) { return admin.getAuthorization((User) role).getRoles(); } else { return new String[0]; } } /** * {@inheritDoc} */ public String[] getMembers(String groupname) throws IOException { if (groupname == null) { throw new IOException("Name must not be null"); } Group group; try { group = (Group) admin.getRole(groupname); } catch (ClassCastException e) { throw new IOException("Not a group: " + groupname); } Role[] members = group.getMembers(); if (members == null) { return new String[0]; } String[] names = new String[members.length]; for (int i = 0; i < members.length; i++) { names[i] = members[i].getName(); } return names; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") public TabularData getProperties(String rolename) throws IOException { if (rolename == null) { throw new IOException("Name must not be null"); } Role role = admin.getRole(rolename); if (role == null) { return null; } return OSGiProperties.tableFrom(role.getProperties()); } /** * {@inheritDoc} */ public String[] getRequiredMembers(String groupname) throws IOException { if (groupname == null) { throw new IOException("Name must not be null"); } Group group; try { group = (Group) admin.getRole(groupname); } catch (ClassCastException e) { throw new IOException("Not a group: " + groupname); } Role[] members = group.getRequiredMembers(); if (members == null) { return new String[0]; } String[] names = new String[members.length]; for (int i = 0; i < members.length; i++) { names[i] = members[i].getName(); } return names; } /** * {@inheritDoc} */ public CompositeData getRole(String name) throws IOException { if (name == null) { throw new IOException("Name must not be null"); } Role role = admin.getRole(name); try { return role == null ? null : new OSGiRole(role).asCompositeData(); } catch (OpenDataException e) { throw new IOException("Unable to create open data: " + e); } } /** * {@inheritDoc} */ public String[] listRoles() throws IOException { Role[] roles; try { roles = admin.getRoles(null); } catch (InvalidSyntaxException e) { throw new IllegalStateException("Cannot use null filter, apparently: " + e); } String[] result = new String[roles.length]; for (int i = 0; i < roles.length; i++) { result[i] = roles[i].getName(); } return result; } /** * {@inheritDoc} */ public String[] getRoles(String filter) throws IOException { Role[] roles; try { roles = admin.getRoles(filter); } catch (InvalidSyntaxException e) { throw new IOException("Invalid filter: " + e); } String[] result = new String[roles.length]; for (int i = 0; i < roles.length; i++) { result[i] = roles[i].getName(); } return result; } /** * {@inheritDoc} */ public CompositeData getUser(String username) throws IOException { if (username == null) { throw new IOException("Name must not be null"); } User user; try { user = (User) admin.getRole(username); } catch (ClassCastException e) { throw new IOException("Not a user: " + username); } try { return user == null ? null : new OSGiUser(user).asCompositeData(); } catch (OpenDataException e) { throw new IOException("Unable to create open data: " + e); } } /** * {@inheritDoc} */ public String getUserWithProperty(String key, String value) throws IOException { if (key == null) { throw new IOException("Name must not be null"); } User user = admin.getUser(key, value); return user == null ? null : user.getName(); } /** * {@inheritDoc} */ public String[] listUsers() throws IOException { Role[] roles; try { roles = admin.getRoles(null); } catch (InvalidSyntaxException e) { throw new IllegalStateException("Cannot use null filter, apparently: " + e); } ArrayList<String> groups = new ArrayList<String>(); for (Role role : roles) { if (role.getType() == Role.USER) { groups.add(role.getName()); } } return groups.toArray(new String[groups.size()]); } /** * {@inheritDoc} */ public String[] getUsers(String filter) throws IOException { Role[] roles; try { roles = admin.getRoles(filter); } catch (InvalidSyntaxException e) { throw new IOException("Invalid filter: " + e); } ArrayList<String> groups = new ArrayList<String>(); for (Role role : roles) { if (role.getType() == Role.USER) { groups.add(role.getName()); } } return groups.toArray(new String[groups.size()]); } /** * {@inheritDoc} */ public void removeCredential(String key, String username) throws IOException { if (username == null || username.length() == 0) { throw new IOException("Name must not be null or empty"); } if (key == null) { throw new IOException("Credential key must not be null"); } User user; try { user = (User) admin.getRole(username); } catch (ClassCastException e) { throw new IOException("Not a user: " + username); } if (user == null) { return; } user.getCredentials().remove(key); } /** * {@inheritDoc} */ public boolean removeMember(String groupname, String rolename) throws IOException { if (groupname == null) { throw new IOException("Group name must not be null"); } if (rolename == null) { throw new IOException("Role name must not be null"); } Group group; try { group = (Group) admin.getRole(groupname); } catch (ClassCastException e) { throw new IOException("Not a group: " + groupname); } if (group == null) { return false; } Role role = admin.getRole(rolename); if (role == null) { return false; } return group.removeMember(role); } /** * {@inheritDoc} */ public void removeProperty(String key, String rolename) throws IOException { if (rolename == null) { throw new IOException("Name must not be null"); } Role role = admin.getRole(rolename); if (role == null) { return; } role.getProperties().remove(key); } /** * {@inheritDoc} */ public boolean removeRole(String name) throws IOException { if (name == null) { throw new IOException("Name must not be null"); } return admin.removeRole(name); } /** * {@inheritDoc} */ public boolean removeUser(String name) throws IOException { if (name == null) { throw new IOException("Name must not be null"); } return admin.removeRole(name); } /** * {@inheritDoc} */ public boolean removeGroup(String name) throws IOException { if (name == null) { throw new IOException("Name must not be null"); } return admin.removeRole(name); } }
package org.eclipse.mylar.tasks.ui; import java.io.File; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.mylar.context.core.ContextCorePlugin; import org.eclipse.mylar.context.core.IMylarContext; import org.eclipse.mylar.context.core.IMylarContextListener; import org.eclipse.mylar.context.core.IMylarElement; import org.eclipse.mylar.core.MylarStatusHandler; import org.eclipse.mylar.internal.context.core.MylarContextManager; import org.eclipse.mylar.internal.tasks.core.RepositoryTaskHandleUtil; import org.eclipse.mylar.internal.tasks.core.WebTask; import org.eclipse.mylar.internal.tasks.ui.TaskListPreferenceConstants; import org.eclipse.mylar.internal.tasks.ui.WorkspaceAwareContextStore; import org.eclipse.mylar.internal.tasks.ui.util.TaskListSaveManager; import org.eclipse.mylar.internal.tasks.ui.util.TaskListWriter; import org.eclipse.mylar.internal.tasks.ui.views.TaskActivationHistory; import org.eclipse.mylar.monitor.core.InteractionEvent; import org.eclipse.mylar.tasks.core.AbstractQueryHit; import org.eclipse.mylar.tasks.core.AbstractRepositoryTask; import org.eclipse.mylar.tasks.core.AbstractTaskContainer; import org.eclipse.mylar.tasks.core.DateRangeActivityDelegate; import org.eclipse.mylar.tasks.core.DateRangeContainer; import org.eclipse.mylar.tasks.core.ITask; import org.eclipse.mylar.tasks.core.ITaskActivityListener; import org.eclipse.mylar.tasks.core.ITaskListChangeListener; import org.eclipse.mylar.tasks.core.ITaskListElement; import org.eclipse.mylar.tasks.core.Task; import org.eclipse.mylar.tasks.core.TaskList; import org.eclipse.mylar.tasks.core.TaskRepository; import org.eclipse.mylar.tasks.core.TaskRepositoryManager; /** * TODO: pull task activity management out into new TaskActivityManager * * @author Mik Kersten * @author Rob Elves (task activity) */ public class TaskListManager implements IPropertyChangeListener { // Did have preference for this so should re-enable private static final int START_HOUR = 8; private static final long SECOND = 1000; private static final long MINUTE = 60 * SECOND; private static final long ROLLOVER_DELAY = 30 * MINUTE; private static final int NUM_WEEKS_PREVIOUS = -1; private static final int NUM_WEEKS_NEXT = 1; private static final int NUM_WEEKS_FUTURE_START = 2; private static final int NUM_WEEKS_FUTURE_END = 8; private static final int NUM_WEEKS_PAST_START = -8; private static final int NUM_WEEKS_PAST_END = -2; public static final String ARCHIVE_CATEGORY_DESCRIPTION = "Archive"; private static final String DESCRIPTION_THIS_WEEK = "This Week"; private static final String DESCRIPTION_PREVIOUS_WEEK = "Previous Week"; private static final String DESCRIPTION_NEXT_WEEK = "Next Week"; private static final String DESCRIPTION_FUTURE = "Future"; private static final String DESCRIPTION_PAST = "Past"; public static final String[] ESTIMATE_TIMES = new String[] { "0 Hours", "1 Hours", "2 Hours", "3 Hours", "4 Hours", "5 Hours", "6 Hours", "7 Hours", "8 Hours", "9 Hours", "10 Hours" }; private DateRangeContainer activityPreviousWeek; private DateRangeContainer activityThisWeek; private List<DateRangeContainer> activityWeekDays = new ArrayList<DateRangeContainer>(); private DateRangeContainer activityNextWeek; private DateRangeContainer activityFuture; private DateRangeContainer activityPast; private ArrayList<DateRangeContainer> dateRangeContainers = new ArrayList<DateRangeContainer>(); private Set<ITask> tasksWithReminders = new HashSet<ITask>(); private Set<ITask> tasksWithDueDates = new HashSet<ITask>(); private ITask currentTask = null; private String currentHandle = ""; private Calendar currentTaskStart = null; private Calendar currentTaskEnd = null; private Map<ITask, Long> taskElapsedTimeMap = new ConcurrentHashMap<ITask, Long>(); private List<ITaskActivityListener> activityListeners = new ArrayList<ITaskActivityListener>(); private TaskListWriter taskListWriter; private File taskListFile; private TaskListSaveManager taskListSaveManager; // TODO: guard against overwriting the single instance? private TaskList taskList = new TaskList(); private TaskActivationHistory taskActivityHistory = new TaskActivationHistory(); private boolean taskListInitialized = false; private boolean taskActivityHistoryInitialized = false; private int startDay; private int endDay; private int scheduledEndHour; private Timer timer; /** public for testing */ public Date startTime = new Date(); private final IMylarContextListener CONTEXT_LISTENER = new IMylarContextListener() { public void contextActivated(IMylarContext context) { // ignore } public void contextDeactivated(IMylarContext context) { // ignore } public void presentationSettingsChanging(UpdateKind kind) { // ignore } public void presentationSettingsChanged(UpdateKind kind) { // ignore } public void interestChanged(List<IMylarElement> elements) { List<InteractionEvent> events = ContextCorePlugin.getContextManager().getActivityHistoryMetaContext() .getInteractionHistory(); InteractionEvent event = events.get(events.size() - 1); parseInteractionEvent(event); } public void elementDeleted(IMylarElement element) { // ignore } public void landmarkAdded(IMylarElement element) { // ignore } public void landmarkRemoved(IMylarElement element) { // ignore } public void relationsChanged(IMylarElement element) { // ignore } }; private final ITaskListChangeListener CHANGE_LISTENER = new ITaskListChangeListener() { public void containerAdded(AbstractTaskContainer container) { } public void containerDeleted(AbstractTaskContainer container) { } public void containerInfoChanged(AbstractTaskContainer container) { } public void localInfoChanged(ITask task) { } public void repositoryInfoChanged(ITask task) { } public void taskAdded(ITask task) { } public void taskDeleted(ITask task) { TaskListManager.this.resetAndRollOver(); } public void taskMoved(ITask task, AbstractTaskContainer fromContainer, AbstractTaskContainer toContainer) { } }; private int timeTicks = 0; public TaskListManager(TaskListWriter taskListWriter, File file) { this.taskListFile = file; this.taskListWriter = taskListWriter; timer = new Timer(); timer.schedule(new RolloverCheck(), ROLLOVER_DELAY, ROLLOVER_DELAY); taskList.addChangeListener(CHANGE_LISTENER); } public void init() { ContextCorePlugin.getContextManager().addActivityMetaContextListener(CONTEXT_LISTENER); } public void dispose() { ContextCorePlugin.getContextManager().removeActivityMetaContextListener(CONTEXT_LISTENER); } public TaskList resetTaskList() { resetActivity(); taskList.reset(); taskListInitialized = true; return taskList; } private void resetActivity() { taskElapsedTimeMap.clear(); dateRangeContainers.clear(); setupCalendarRanges(); } /** * Warning: if called twice task times will be wrong */ private void parseTaskActivityInteractionHistory() { if (!TasksUiPlugin.getTaskListManager().isTaskListInitialized()) { return; } List<InteractionEvent> events = ContextCorePlugin.getContextManager().getActivityHistoryMetaContext() .getInteractionHistory(); for (InteractionEvent event : events) { parseInteractionEvent(event); } taskActivityHistoryInitialized = true; parseFutureReminders(); } public void parseFutureReminders() { activityFuture.clear(); activityNextWeek.clear(); for (DateRangeContainer day : activityWeekDays) { day.clear(); } HashSet<ITask> toRemove = new HashSet<ITask>(); toRemove.addAll(activityThisWeek.getDateRangeDelegates()); for (ITask activity : toRemove) { DateRangeActivityDelegate delegate = (DateRangeActivityDelegate) activity; Calendar calendar = GregorianCalendar.getInstance(); Date schedDate = delegate.getScheduledForDate(); if (schedDate == null) { schedDate = delegate.getDueDate(); } if (schedDate != null) { calendar.setTime(schedDate); if (!activityThisWeek.includes(calendar) && activityThisWeek.getElapsed(delegate) == 0) { activityThisWeek.remove(delegate); } } else { if (activityThisWeek.getElapsed(delegate) == 0) { activityThisWeek.remove(delegate); } } } GregorianCalendar tempCalendar = new GregorianCalendar(); tempCalendar.setFirstDayOfWeek(startDay); Set<ITask> allScheduledTasks = new HashSet<ITask>(); allScheduledTasks.addAll(tasksWithReminders); allScheduledTasks.addAll(tasksWithDueDates); for (ITask task : allScheduledTasks) { if (task instanceof DateRangeActivityDelegate) { task = ((DateRangeActivityDelegate) task).getCorrespondingTask(); } Date schedDate = task.getScheduledForDate(); if (schedDate == null || isOverdue(task)) { schedDate = task.getDueDate(); } if (schedDate != null) { tempCalendar.setTime(schedDate); if (activityNextWeek.includes(tempCalendar)) { activityNextWeek.addTask(new DateRangeActivityDelegate(activityNextWeek, task, tempCalendar, tempCalendar)); } else if (activityFuture.includes(tempCalendar)) { activityFuture.addTask(new DateRangeActivityDelegate(activityFuture, task, tempCalendar, tempCalendar)); } else if (activityThisWeek.includes(tempCalendar) && !activityThisWeek.getChildren().contains(task)) { activityThisWeek.addTask(new DateRangeActivityDelegate(activityThisWeek, task, tempCalendar, tempCalendar)); } else if (activityPreviousWeek.includes(tempCalendar) && !activityPreviousWeek.getChildren().contains(task)) { activityPreviousWeek.addTask(new DateRangeActivityDelegate(activityPreviousWeek, task, tempCalendar, tempCalendar)); } else if (activityPast.includes(tempCalendar) && !activityPast.getChildren().contains(task)) { activityPast.addTask(new DateRangeActivityDelegate(activityPast, task, tempCalendar, tempCalendar)); } for (DateRangeContainer day : activityWeekDays) { if (day.includes(tempCalendar) && !day.getChildren().contains(task)) { day.addTask(new DateRangeActivityDelegate(day, task, tempCalendar, tempCalendar, this .getElapsedTime(task))); } } } } } /** public for testing * */ public void parseInteractionEvent(InteractionEvent event) { try { if (event.getDelta().equals(MylarContextManager.ACTIVITY_DELTA_ACTIVATED)) { if (!event.getStructureHandle().equals(MylarContextManager.ACTIVITY_HANDLE_ATTENTION)) { ITask activatedTask = TasksUiPlugin.getTaskListManager().getTaskList().getTask( event.getStructureHandle()); if (currentTask != null && activatedTask != null) { if (!currentTask.equals(activatedTask)) { GregorianCalendar calendarEnd = new GregorianCalendar(); calendarEnd.setFirstDayOfWeek(startDay); calendarEnd.setTime(event.getDate()); calendarEnd.getTime(); // Activation of different task before deactivation // previous, log was inconsistent, // finish what we started taskDeactivated(calendarEnd); } else { // skip re-activations of same task return; } } currentTask = activatedTask; if (currentTask != null) { GregorianCalendar calendar = new GregorianCalendar(); calendar.setFirstDayOfWeek(startDay); calendar.setTime(event.getDate()); currentTaskStart = calendar; currentHandle = event.getStructureHandle(); } } else if (event.getStructureHandle().equals(MylarContextManager.ACTIVITY_HANDLE_ATTENTION)) { if (currentTask != null && !currentHandle.equals("")) { long active = event.getEndDate().getTime() - event.getDate().getTime(); // add to running total if (taskElapsedTimeMap.containsKey(currentTask)) { long pastTime = taskElapsedTimeMap.get(currentTask); taskElapsedTimeMap.put(currentTask, pastTime + active); timeTicks++; if (taskActivityHistoryInitialized && timeTicks > 3) { // Save incase of system failure. // TODO: request asynchronous save ContextCorePlugin.getContextManager().saveActivityHistoryContext(); timeTicks = 0; } } else { taskElapsedTimeMap.put(currentTask, active); } } } } else if (event.getDelta().equals(MylarContextManager.ACTIVITY_DELTA_DEACTIVATED)) { if (!event.getStructureHandle().equals(MylarContextManager.ACTIVITY_HANDLE_ATTENTION) && currentHandle.equals(event.getStructureHandle())) { GregorianCalendar calendarEnd = new GregorianCalendar(); calendarEnd.setFirstDayOfWeek(startDay); calendarEnd.setTime(event.getDate()); calendarEnd.getTime(); taskDeactivated(calendarEnd); } else if (event.getStructureHandle().equals(MylarContextManager.ACTIVITY_HANDLE_ATTENTION)) { // Deactivated attention events not currently used (ignored) } } } catch (Throwable t) { MylarStatusHandler.fail(t, "Error parsing interaction event", false); } } private void taskDeactivated(GregorianCalendar calendarEnd) { currentTaskEnd = calendarEnd; Set<DateRangeContainer> rangeSet = new HashSet<DateRangeContainer>(); rangeSet.addAll(dateRangeContainers); rangeSet.add(activityThisWeek); for (DateRangeContainer week : rangeSet) { if (week.includes(currentTaskStart) && (!isWeekDay(week) && !week.isFuture())) { if (currentTask != null) { // add to date range 'bin' Long activeTime = taskElapsedTimeMap.get(currentTask); if (activeTime == null) { activeTime = new Long(0); } DateRangeActivityDelegate delegate = new DateRangeActivityDelegate(week, currentTask, currentTaskStart, currentTaskEnd, activeTime); week.addTask(delegate); if (taskActivityHistoryInitialized) { for (ITaskActivityListener listener : activityListeners) { listener.activityChanged(week); } } } } } currentTask = null; currentHandle = ""; } /** public for testing * */ public DateRangeContainer getActivityThisWeek() { return activityThisWeek; } /** public for testing * */ public DateRangeContainer getActivityPast() { return activityPast; } /** public for testing * */ public DateRangeContainer getActivityFuture() { return activityFuture; } /** public for testing * */ public DateRangeContainer getActivityNextWeek() { return activityNextWeek; } /** public for testing * */ public DateRangeContainer getActivityPrevious() { return activityPreviousWeek; } /** total elapsed time based on activation history */ public long getElapsedTime(ITask task) { if (taskElapsedTimeMap.containsKey(task)) { return taskElapsedTimeMap.get(task); } else { return 0; } } private void setupCalendarRanges() { // MylarTaskListPlugin.getMylarCorePrefs().getInt(TaskListPreferenceConstants.PLANNING_STARTDAY); startDay = Calendar.MONDAY; // MylarTaskListPlugin.getMylarCorePrefs().getInt(TaskListPreferenceConstants.PLANNING_ENDDAY); endDay = Calendar.SUNDAY; // scheduledStartHour = // TasksUiPlugin.getDefault().getPreferenceStore().getInt( // TaskListPreferenceConstants.PLANNING_STARTHOUR); scheduledEndHour = TasksUiPlugin.getDefault().getPreferenceStore().getInt( TaskListPreferenceConstants.PLANNING_ENDHOUR); activityWeekDays.clear(); for (int x = startDay; x < (startDay + 7); x++) { GregorianCalendar dayStart = new GregorianCalendar(); GregorianCalendar dayEnd = new GregorianCalendar(); dayStart.setFirstDayOfWeek(startDay); dayEnd.setFirstDayOfWeek(startDay); if (x > 7) { dayStart.set(Calendar.DAY_OF_WEEK, x % 7); dayEnd.set(Calendar.DAY_OF_WEEK, x % 7); } else { dayStart.set(Calendar.DAY_OF_WEEK, x); dayEnd.set(Calendar.DAY_OF_WEEK, x); } dayStart.set(Calendar.HOUR_OF_DAY, 0); dayStart.set(Calendar.MINUTE, 0); dayStart.set(Calendar.SECOND, 0); dayStart.set(Calendar.MILLISECOND, 0); dayStart.getTime(); dayEnd.set(Calendar.HOUR_OF_DAY, dayEnd.getMaximum(Calendar.HOUR_OF_DAY)); dayEnd.set(Calendar.MINUTE, dayEnd.getMaximum(Calendar.MINUTE)); dayEnd.set(Calendar.SECOND, dayEnd.getMaximum(Calendar.SECOND)); dayEnd.set(Calendar.MILLISECOND, dayEnd.getMaximum(Calendar.MILLISECOND)); dayEnd.getTime(); String summary = "<unknown>"; switch (dayStart.get(Calendar.DAY_OF_WEEK)) { case Calendar.MONDAY: summary = "Monday"; break; case Calendar.TUESDAY: summary = "Tuesday"; break; case Calendar.WEDNESDAY: summary = "Wednesday"; break; case Calendar.THURSDAY: summary = "Thursday"; break; case Calendar.FRIDAY: summary = "Friday"; break; case Calendar.SATURDAY: summary = "Saturday"; break; case Calendar.SUNDAY: summary = "Sunday"; break; } DateRangeContainer day = new DateRangeContainer(dayStart, dayEnd, summary, taskList); activityWeekDays.add(day); dateRangeContainers.add(day); } GregorianCalendar currentBegin = new GregorianCalendar(); currentBegin.setFirstDayOfWeek(startDay); currentBegin.setTime(startTime); snapToStartOfWeek(currentBegin); GregorianCalendar currentEnd = new GregorianCalendar(); currentEnd.setFirstDayOfWeek(startDay); currentEnd.setTime(startTime); snapToEndOfWeek(currentEnd); activityThisWeek = new DateRangeContainer(currentBegin, currentEnd, DESCRIPTION_THIS_WEEK, taskList); // dateRangeContainers.add(activityThisWeek); GregorianCalendar previousStart = new GregorianCalendar(); previousStart.setFirstDayOfWeek(startDay); previousStart.setTime(startTime); previousStart.add(Calendar.WEEK_OF_YEAR, NUM_WEEKS_PREVIOUS); snapToStartOfWeek(previousStart); GregorianCalendar previousEnd = new GregorianCalendar(); previousEnd.setFirstDayOfWeek(startDay); previousEnd.setTime(startTime); previousEnd.add(Calendar.WEEK_OF_YEAR, NUM_WEEKS_PREVIOUS); snapToEndOfWeek(previousEnd); activityPreviousWeek = new DateRangeContainer(previousStart.getTime(), previousEnd.getTime(), DESCRIPTION_PREVIOUS_WEEK, taskList); dateRangeContainers.add(activityPreviousWeek); GregorianCalendar nextStart = new GregorianCalendar(); nextStart.setFirstDayOfWeek(startDay); nextStart.setTime(startTime); nextStart.add(Calendar.WEEK_OF_YEAR, NUM_WEEKS_NEXT); snapToStartOfWeek(nextStart); GregorianCalendar nextEnd = new GregorianCalendar(); nextEnd.setFirstDayOfWeek(startDay); nextEnd.setTime(startTime); nextEnd.add(Calendar.WEEK_OF_YEAR, NUM_WEEKS_NEXT); snapToEndOfWeek(nextEnd); activityNextWeek = new DateRangeContainer(nextStart.getTime(), nextEnd.getTime(), DESCRIPTION_NEXT_WEEK, taskList); dateRangeContainers.add(activityNextWeek); GregorianCalendar futureStart = new GregorianCalendar(); futureStart.setFirstDayOfWeek(startDay); futureStart.setTime(startTime); futureStart.add(Calendar.WEEK_OF_YEAR, NUM_WEEKS_FUTURE_START); snapToStartOfWeek(futureStart); GregorianCalendar futureEnd = new GregorianCalendar(); futureEnd.setFirstDayOfWeek(startDay); futureEnd.setTime(startTime); futureEnd.add(Calendar.WEEK_OF_YEAR, NUM_WEEKS_FUTURE_END); snapToEndOfWeek(futureEnd); activityFuture = new DateRangeContainer(futureStart.getTime(), futureEnd.getTime(), DESCRIPTION_FUTURE, taskList); dateRangeContainers.add(activityFuture); GregorianCalendar pastStart = new GregorianCalendar(); pastStart.setFirstDayOfWeek(startDay); pastStart.setTime(startTime); pastStart.add(Calendar.WEEK_OF_YEAR, NUM_WEEKS_PAST_START); snapToStartOfWeek(pastStart); GregorianCalendar pastEnd = new GregorianCalendar(); pastEnd.setFirstDayOfWeek(startDay); pastEnd.setTime(startTime); pastEnd.add(Calendar.WEEK_OF_YEAR, NUM_WEEKS_PAST_END); snapToEndOfWeek(pastEnd); activityPast = new DateRangeContainer(pastStart.getTime(), pastEnd.getTime(), DESCRIPTION_PAST, taskList); dateRangeContainers.add(activityPast); } public void snapToNextDay(Calendar cal) { cal.add(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.getTime(); } private void snapToStartOfWeek(Calendar cal) { cal.getTime(); cal.set(Calendar.DAY_OF_WEEK, startDay); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.getTime(); } private void snapToEndOfWeek(Calendar cal) { cal.getTime(); cal.set(Calendar.DAY_OF_WEEK, endDay); cal.set(Calendar.HOUR_OF_DAY, cal.getMaximum(Calendar.HOUR_OF_DAY)); cal.set(Calendar.MINUTE, cal.getMaximum(Calendar.MINUTE)); cal.set(Calendar.SECOND, cal.getMaximum(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cal.getMaximum(Calendar.MILLISECOND)); cal.getTime(); } public Calendar setSecheduledIn(Calendar calendar, int days) { calendar.add(Calendar.DAY_OF_MONTH, days); calendar.set(Calendar.HOUR_OF_DAY, scheduledEndHour); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar; } /** * Will schedule for today if past work-day's end. */ public Calendar setScheduledEndOfDay(Calendar calendar) { // Calendar now = Calendar.getInstance(); // if (now.get(Calendar.HOUR_OF_DAY) >= scheduledEndHour) { // setSecheduledIn(calendar, 1); calendar.set(Calendar.HOUR_OF_DAY, scheduledEndHour); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar; } public void setScheduledNextWeek(Calendar calendar) { calendar.setTimeInMillis(TasksUiPlugin.getTaskListManager().getActivityNextWeek().getStart().getTimeInMillis()); setScheduledEndOfDay(calendar); } public List<DateRangeContainer> getDateRanges() { // parseFutureReminders(); // return dateRangeContainers.toArray(new // ITaskListElement[dateRangeContainers.size()]); return dateRangeContainers; } /** * Every call to this method generates a unique handle, subsequent calls * will have incremented task numbers */ public String genUniqueTaskHandle() { return TaskRepositoryManager.PREFIX_LOCAL + taskList.getNextTaskNum(); } public void refactorRepositoryUrl(String oldUrl, String newUrl) { if (oldUrl == null || newUrl == null || oldUrl.equals(newUrl)) { return; } List<ITask> activeTasks = taskList.getActiveTasks(); for (ITask task : new ArrayList<ITask>(activeTasks)) { deactivateTask(task); } taskList.refactorRepositoryUrl(oldUrl, newUrl); File dataDir = new File(TasksUiPlugin.getDefault().getDataDirectory(), WorkspaceAwareContextStore.CONTEXTS_DIRECTORY); if (dataDir.exists() && dataDir.isDirectory()) { for (File file : dataDir.listFiles()) { int dotIndex = file.getName().lastIndexOf(".xml"); if (dotIndex != -1) { String storedHandle; try { storedHandle = URLDecoder.decode(file.getName().substring(0, dotIndex), MylarContextManager.CONTEXT_FILENAME_ENCODING); int delimIndex = storedHandle.lastIndexOf(RepositoryTaskHandleUtil.HANDLE_DELIM); if (delimIndex != -1) { String storedUrl = storedHandle.substring(0, delimIndex); if (oldUrl.equals(storedUrl)) { String id = RepositoryTaskHandleUtil.getTaskId(storedHandle); String newHandle = RepositoryTaskHandleUtil.getHandle(newUrl, id); File newFile = ContextCorePlugin.getContextManager().getFileForContext(newHandle); file.renameTo(newFile); } } } catch (Exception e) { MylarStatusHandler.fail(e, "Could not move context file: " + file.getName(), false); } } } } saveTaskList(); } public boolean readExistingOrCreateNewList() { try { if (taskListFile.exists()) { taskListWriter.readTaskList(taskList, taskListFile, TasksUiPlugin.getDefault().getTaskDataManager()); } else { resetTaskList(); } for (ITask task : taskList.getAllTasks()) { if (task.getScheduledForDate() != null) { tasksWithReminders.add(task); } if (task.getDueDate() != null) { tasksWithDueDates.add(task); } } resetActivity(); // parseFutureReminders(); taskListInitialized = true; for (ITaskActivityListener listener : new ArrayList<ITaskActivityListener>(activityListeners)) { listener.taskListRead(); } } catch (Throwable t) { MylarStatusHandler.fail(t, "Could not read task list, consider restoring via view menu", true); return false; } return true; } /** * Only to be called upon initial startup by plugin. */ public void initActivityHistory() { resetAndRollOver(); taskActivityHistory.loadPersistentHistory(); } /** * Will not save an empty task list to avoid losing data on bad startup. */ public synchronized void saveTaskList() { try { if (taskListInitialized) { taskListSaveManager.saveTaskList(true, false); // TasksUiPlugin.getDefault().getPreferenceStore().setValue(TaskListPreferenceConstants.TASK_ID, // nextLocalTaskId); } else { MylarStatusHandler.log("task list save attempted before initialization", this); } } catch (Exception e) { MylarStatusHandler.fail(e, "Could not save task list", true); } } public TaskList getTaskList() { return taskList; } public void addActivityListener(ITaskActivityListener listener) { activityListeners.add(listener); } public void removeActivityListener(ITaskActivityListener listener) { activityListeners.remove(listener); } public void activateTask(ITask task) { if (!TasksUiPlugin.getDefault().isMultipleActiveTasksMode()) { deactivateAllTasks(); } try { taskList.setActive(task, true); for (ITaskActivityListener listener : new ArrayList<ITaskActivityListener>(activityListeners)) { try { listener.taskActivated(task); } catch (Throwable t) { MylarStatusHandler.fail(t, "task activity listener failed: " + listener, false); } } } catch (Throwable t) { MylarStatusHandler.fail(t, "could not activate task", false); } } public void deactivateAllTasks() { // Make a copy to avoid modification on list being traversed; can result // in a ConcurrentModificationException List<ITask> activeTasks = taskList.getActiveTasks(); for (ITask task : activeTasks) { deactivateTask(task); } } public void deactivateTask(ITask task) { if (task == null) { return; } if (task.isActive()) { taskList.setActive(task, false); for (ITaskActivityListener listener : new ArrayList<ITaskActivityListener>(activityListeners)) { try { listener.taskDeactivated(task); } catch (Throwable t) { MylarStatusHandler.fail(t, "notification failed for: " + listener, false); } } } } public void setTaskListFile(File file) { this.taskListFile = file; } public void copyDataDirContentsTo(String newDataDir) { taskListSaveManager.copyDataDirContentsTo(newDataDir); } public boolean isTaskListInitialized() { return taskListInitialized; } public TaskListWriter getTaskListWriter() { return taskListWriter; } public File getTaskListFile() { return taskListFile; } public boolean isActiveThisWeek(ITask task) { for (ITask activityDelegateTask : activityThisWeek.getChildren()) { if (activityDelegateTask.getHandleIdentifier().equals(task.getHandleIdentifier())) { return true; } } return false; } /** * @return if a repository task, will only return true if the user is a */ public boolean isCompletedToday(ITask task) { if (task != null) { boolean isOwnedByUser = isOwnedByUser(task); if (!isOwnedByUser) { return false; } else { Date completionDate = task.getCompletionDate(); if (completionDate != null) { Calendar tomorrow = Calendar.getInstance(); snapToNextDay(tomorrow); Calendar yesterday = Calendar.getInstance(); yesterday.set(Calendar.HOUR_OF_DAY, 0); yesterday.set(Calendar.MINUTE, 0); yesterday.set(Calendar.SECOND, 0); yesterday.set(Calendar.MILLISECOND, 0); return completionDate.compareTo(yesterday.getTime()) == 1 && completionDate.compareTo(tomorrow.getTime()) == -1; } } } return false; } public boolean isOwnedByUser(ITask task) { if (task instanceof WebTask || (task instanceof Task && ((Task) task).isLocal())) { return true; } if (task instanceof AbstractRepositoryTask) { AbstractRepositoryTask repositoryTask = (AbstractRepositoryTask) task; TaskRepository repository = TasksUiPlugin.getRepositoryManager().getRepository( repositoryTask.getRepositoryKind(), repositoryTask.getRepositoryUrl()); if (repository != null && repositoryTask.getOwner() != null) { return repositoryTask.getOwner().equals(repository.getUserName()); } } return false; // if (task instanceof AbstractRepositoryTask && !(task instanceof // WebTask)) { // AbstractRepositoryTask repositoryTask = (AbstractRepositoryTask) // task; // TaskRepository repository = // TasksUiPlugin.getRepositoryManager().getRepository( // repositoryTask.getRepositoryKind(), // repositoryTask.getRepositoryUrl()); // if (repository != null && repositoryTask.getOwner() != null // && !repositoryTask.getOwner().equals(repository.getUserName())) { // return false; // return true; } public boolean isScheduledAfterThisWeek(ITask task) { if (task != null) { Date reminder = task.getScheduledForDate(); if (reminder != null) { return reminder.compareTo(activityNextWeek.getStart().getTime()) > -1; } } return false; } public boolean isScheduledForLater(ITask task) { if (task != null) { Date reminder = task.getScheduledForDate(); if (reminder != null) { return reminder.compareTo(activityFuture.getStart().getTime()) > -1; } } return false; } public boolean isScheduledForThisWeek(ITask task) { if (task != null) { Date reminder = task.getScheduledForDate(); if (reminder != null) { Calendar weekStart = Calendar.getInstance(); snapToStartOfWeek(weekStart); return (reminder.compareTo(weekStart.getTime()) >= 0 && reminder.compareTo(activityThisWeek.getEnd() .getTime()) <= 0); } } return false; } public boolean isScheduledForToday(ITask task) { if (task != null) { Date reminder = task.getScheduledForDate(); if (reminder != null) { Calendar dayStart = Calendar.getInstance(); dayStart.set(Calendar.HOUR_OF_DAY, 0); dayStart.set(Calendar.MINUTE, 0); dayStart.set(Calendar.SECOND, 0); dayStart.set(Calendar.MILLISECOND, 0); Calendar midnight = GregorianCalendar.getInstance(); snapToNextDay(midnight); return (reminder.compareTo(dayStart.getTime()) >= 0 && reminder.compareTo(midnight.getTime()) == -1); } } return false; } /** * TODO: Need to migrate to use of this method for setting of reminders */ public void setScheduledFor(ITask task, Date reminderDate) { if (task == null) return; task.setScheduledForDate(reminderDate); task.setReminded(false); if (reminderDate == null) { tasksWithReminders.remove(task); } else { tasksWithReminders.remove(task); tasksWithReminders.add(task); } parseFutureReminders(); taskList.notifyLocalInfoChanged(task); } public void setDueDate(ITask task, Date dueDate) { task.setDueDate(dueDate); if (dueDate == null) { tasksWithDueDates.remove(task); } else { tasksWithDueDates.remove(task); tasksWithDueDates.add(task); } parseFutureReminders(); taskList.notifyLocalInfoChanged(task); } /** * @return true if task due date != null and has past */ public boolean isOverdue(ITask task) { return (!task.isCompleted() && task.getDueDate() != null && new Date().after(task.getDueDate())) && isOwnedByUser(task); } public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(TaskListPreferenceConstants.PLANNING_STARTHOUR) || event.getProperty().equals(TaskListPreferenceConstants.PLANNING_ENDHOUR)) { // event.getProperty().equals(TaskListPreferenceConstants.PLANNING_STARTDAY) // scheduledStartHour = // TasksUiPlugin.getDefault().getPreferenceStore().getInt( // TaskListPreferenceConstants.PLANNING_STARTHOUR); scheduledEndHour = TasksUiPlugin.getDefault().getPreferenceStore().getInt( TaskListPreferenceConstants.PLANNING_ENDHOUR); } } /** public for testing */ public void resetAndRollOver() { taskActivityHistoryInitialized = false; tasksWithReminders.clear(); tasksWithDueDates.clear(); for (ITask task : taskList.getAllTasks()) { if (task.getScheduledForDate() != null) { tasksWithReminders.add(task); } if (task.getDueDate() != null) { tasksWithDueDates.add(task); } } resetActivity(); parseTaskActivityInteractionHistory(); for (ITaskActivityListener listener : activityListeners) { listener.calendarChanged(); } } private class RolloverCheck extends TimerTask { @Override public void run() { if (!Platform.isRunning() || ContextCorePlugin.getDefault() == null) { return; } else { Calendar now = GregorianCalendar.getInstance(); DateRangeContainer thisWeek = getActivityThisWeek(); if (!thisWeek.includes(now)) { startTime = new Date(); resetAndRollOver(); } } } } public TaskActivationHistory getTaskActivationHistory() { return taskActivityHistory; } public Set<ITask> getScheduledForThisWeek() { Set<ITask> tasksScheduled = new HashSet<ITask>(); for (ITask task : getActivityThisWeek().getChildren()) { if (isScheduledForThisWeek(task)) { tasksScheduled.add(task); } } return tasksScheduled; } /** * @param element * tasklist element to retrieve a task for currently will work * for (ITask, AbstractQueryHit) * @param force - * if a query hit is passed you can either force construction of * the task or not (if not and no task, null is returned) TODO: * Move into TaskList? */ public ITask getTaskForElement(ITaskListElement element, boolean force) { ITask task = null; if (element instanceof AbstractQueryHit) { if (force) { task = ((AbstractQueryHit) element).getOrCreateCorrespondingTask(); } else { task = ((AbstractQueryHit) element).getCorrespondingTask(); } } else if (element instanceof ITask) { task = (ITask) element; } return task; } protected void setTaskListSaveManager(TaskListSaveManager taskListSaveManager) { this.taskListSaveManager = taskListSaveManager; this.taskList.addChangeListener(taskListSaveManager); } public List<DateRangeContainer> getActivityWeekDays() { return activityWeekDays; } public boolean isWeekDay(DateRangeContainer dateRangeTaskContainer) { return activityWeekDays.contains(dateRangeTaskContainer); } public int getStartHour() { return START_HOUR; } }
package MWC.Utilities.ReaderWriter.XML.Util; import java.awt.Color; import org.xml.sax.Attributes; import MWC.GUI.Properties.DebriefColors; import MWC.Utilities.ReaderWriter.XML.MWCXMLReader; abstract public class ColourHandler extends MWCXMLReader { private java.awt.Color _res; private int _r; private int _g; private int _b; static private java.util.Hashtable<String, java.awt.Color> _myColours; public ColourHandler() { // handle this in the "normal" constructor this("colour"); } /** * custom constructor, for when the attribute does not contain the standard * name * * @param name * the name of the attribute we are handling */ public ColourHandler(final String name) { // pass our attribute name up the line super(name); // check that the colours have been defined checkColours(); } // this is one of ours, so get on with it! @Override protected void handleOurselves(final String name, final Attributes attributes) { // initialise data _r = _g = _b = 0; final int len = attributes.getLength(); for (int i = 0; i < len; i++) { final String nm = attributes.getLocalName(i); final String val = attributes.getValue(i); if (nm.equals("Value")) { _setColour(val); } else if (nm.equals("CustomRed")) { _r = Integer.valueOf(val).intValue(); } else if (nm.equals("CustomGreen")) { _g = Integer.valueOf(val).intValue(); } else if (nm.equals("CustomBlue")) { _b = Integer.valueOf(val).intValue(); } } } private synchronized static void checkColours() { if (_myColours == null) { _myColours = new java.util.Hashtable<String, java.awt.Color>(); _myColours.put("RED", DebriefColors.RED); _myColours.put("BLUE", DebriefColors.BLUE); _myColours.put("GREEN", DebriefColors.GREEN); _myColours.put("YELLOW", DebriefColors.YELLOW); _myColours.put("MAGENTA", DebriefColors.MAGENTA); _myColours.put("PURPLE", DebriefColors.PURPLE); _myColours.put("ORANGE", DebriefColors.ORANGE); _myColours.put("BROWN", DebriefColors.BROWN); _myColours.put("CYAN", DebriefColors.CYAN); _myColours.put("LIGHT_GREEN", DebriefColors.LIGHT_GREEN); _myColours.put("GOLD", DebriefColors.GOLD); _myColours.put("PINK", DebriefColors.PINK); _myColours.put("LIGHT_GREY", DebriefColors.LIGHT_GRAY); _myColours.put("GREY", DebriefColors.GRAY); _myColours.put("DARK_GREY", DebriefColors.DARK_GRAY); _myColours.put("WHITE", DebriefColors.WHITE); _myColours.put("BLACK", DebriefColors.BLACK); _myColours.put("DARK_BLUE", DebriefColors.DARK_BLUE); _myColours.put("MEDIUM_BLUE", DebriefColors.MEDIUM_BLUE); } } private void _setColour(final String val) { // try to convert this string to a colour if (val.equals("CUSTOM")) { // this is clearly a custom colour, leave colour definition // until we close the element, so that we can be sure we've // got all three r,g,b components _res = null; } // have the colours been defined? checkColours(); // step through the colours, to see if we find one which matches final java.util.Enumeration<String> enumer = _myColours.keys(); while (enumer.hasMoreElements()) { final String thisK = enumer.nextElement(); if (thisK.equals(val)) { _res = _myColours.get(val); break; } } } public Color resolveColor(final String val) { // try to convert this string to a colour if (val.equals("CUSTOM")) { // this is clearly a custom colour, leave colour definition // until we close the element, so that we can be sure we've // got all three r,g,b components return null; } // have the colours been defined? checkColours(); // step through the colours, to see if we find one which matches final java.util.Enumeration<String> enumer = _myColours.keys(); while (enumer.hasMoreElements()) { final String thisK = enumer.nextElement(); if (thisK.equals(val)) { return _myColours.get(val); } } return null; } @Override public void elementClosed() { // has a a predefined colour been selected? if (_res == null) { // no, create our own _res = new java.awt.Color(_r, _g, _b); } // return the result setColour(_res); // reset _res = null; } abstract public void setColour(java.awt.Color res); /** * custom exporter, for when we are not using the expected attribute name */ public static void exportColour(final java.awt.Color color, final org.w3c.dom.Element parent, final org.w3c.dom.Document doc, final String name) { if (color == null) { return; } // have the colours been specified? checkColours(); // see if this is one of our export values final java.util.Enumeration<String> enumer = _myColours.keys(); String ourKey = null; while (enumer.hasMoreElements()) { final Object thisKey = enumer.nextElement(); final java.awt.Color thisCol = _myColours.get(thisKey); if (thisCol.equals(color)) { // found it! ourKey = (String) thisKey; break; } } final org.w3c.dom.Element eLoc = doc.createElement(name); if (ourKey != null) { eLoc.setAttribute("Value", ourKey); } else { eLoc.setAttribute("CustomRed", "" + color.getRed()); eLoc.setAttribute("CustomGreen", "" + color.getGreen()); eLoc.setAttribute("CustomBlue", "" + color.getBlue()); eLoc.setAttribute("Value", "custom"); } parent.appendChild(eLoc); } /** * produce a color from the comma-separated string * * @param val * @return */ public static Color fromString(final String val) { Color res = null; final String[] items = val.split(","); if (items.length == 3) { res = new Color(Integer.parseInt(items[0]), Integer.parseInt(items[1]), Integer.parseInt(items[2])); } return res; } /** * produce a comma-separated string from the color * * @param val * @return */ public static String toString(final Color val) { return "" + val.getRed() + "," + val.getGreen() + "," + val.getBlue(); } /** * standard exporter, using our proper attribute name */ public static void exportColour(final java.awt.Color color, final org.w3c.dom.Element parent, final org.w3c.dom.Document doc) { if (color != null) { exportColour(color, parent, doc, "colour"); } } }
package utils; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.Session; import org.webdsl.WebDSLEntity; import org.webdsl.lang.Environment; import org.webdsl.logging.Logger; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; public abstract class AbstractPageServlet{ protected abstract void renderDebugJsVar(PrintWriter sout); protected abstract boolean logSqlCheckAccess(); protected abstract void initTemplateClass(); protected abstract void redirectHttpHttps(); protected abstract boolean isActionSubmit(); protected abstract String[] getUsedSessionEntityJoins(); protected TemplateServlet templateservlet = null; protected abstract org.webdsl.WebDSLEntity getRequestLogEntry(); protected abstract void addPrincipalToRequestLog(org.webdsl.WebDSLEntity rle); protected abstract void addLogSqlToSessionMessages(); public Session hibernateSession = null; protected static Pattern isMarkupLangMimeType= Pattern.compile("html|xml$"); protected static Pattern baseURLPattern= Pattern.compile("(^\\w{0,6})(: protected AbstractPageServlet commandingPage = this; public boolean isReadOnly = false; public boolean isWebService(){ return false; } static{ common_css_link_tag_suffix = "/stylesheets/" + CachedResourceFileNameHelper.getNameWithHash("stylesheets", "common_.css") + "\" rel=\"stylesheet\" type=\"text/css\" />"; fav_ico_link_tag_suffix = "/" + CachedResourceFileNameHelper.getNameWithHash("", "favicon.ico") + "\" rel=\"shortcut icon\" type=\"image/x-icon\" />"; ajax_js_include_name = "ajax.js"; } public void serve(HttpServletRequest request, HttpServletResponse httpServletResponse, Map<String, String> parammap, Map<String, List<String>> parammapvalues, Map<String,List<utils.File>> fileUploads) throws Exception { initTemplateClass(); this.startTime = System.currentTimeMillis(); ThreadLocalPage.set(this); this.request=request; this.httpServletResponse = httpServletResponse; this.response = new ResponseWrapper(httpServletResponse); this.parammap = parammap; this.parammapvalues = parammapvalues; this.fileUploads=fileUploads; redirectHttpHttps(); if(parammap.get("__ajax_runtime_request__") != null) { this.setAjaxRuntimeRequest(true); } org.webdsl.WebDSLEntity rle = getRequestLogEntry(); org.apache.log4j.MDC.put("request", rle.getId().toString()); org.apache.log4j.MDC.put("template", "/" + getPageName()); utils.RequestAppender reqAppender = null; if(parammap.get("disableopt") != null){ this.isOptimizationEnabled = false; } if(parammap.get("logsql") != null){ this.isLogSqlEnabled = true; this.isPageCacheDisabled = true; reqAppender = utils.RequestAppender.getInstance(); } if(reqAppender != null){ reqAppender.addRequest(rle.getId().toString()); } if(parammap.get("nocache") != null){ this.isPageCacheDisabled = true; } initRequestVars(); hibernateSession = utils.HibernateUtil.getCurrentSession(); hibernateSession.beginTransaction(); if(isReadOnly){ hibernateSession.setFlushMode(org.hibernate.FlushMode.MANUAL); } else{ hibernateSession.setFlushMode(org.hibernate.FlushMode.COMMIT); } try { StringWriter s = new StringWriter(); PrintWriter out = new PrintWriter(s); ThreadLocalOut.push(out); ThreadLocalServlet.get().loadSessionManager(hibernateSession, getUsedSessionEntityJoins()); ThreadLocalServlet.get().retrieveIncomingMessagesFromHttpSession(); initVarsAndArgs(); if(isActionSubmit()) { if(parammap.get("__action__link__") != null) { this.setActionLinkUsed(true); } templateservlet.storeInputs(null, args, new Environment(envGlobalAndSession), null); clearTemplateContext(); //storeinputs also finds which action is executed, since validation might be ignored using [ignore-validation] on the submit boolean ignoreValidation = actionToBeExecutedHasDisabledValidation; if (!ignoreValidation){ templateservlet.validateInputs (null, args, new Environment(envGlobalAndSession), null); ThreadLocalPage.get().clearTemplateContext(); } if(validated){ templateservlet.handleActions(null, args, new Environment(envGlobalAndSession), null); ThreadLocalPage.get().clearTemplateContext(); } } if(isNotValid()){ // mark transaction so it will be aborted at the end // entered form data can be used to update the form on the client with ajax, taking into account if's and other control flow template elements // this also means that data in vars/args and hibernate session should not be cleared until form is rendered abortTransaction(); } String outstream = s.toString(); if(download != null) { //File.download() excecuted in action download(); } else { boolean isAjaxResponse = true; // regular render, or failed action render if( hasNotExecutedAction() || isNotValid() ){ // ajax replace performed during validation, assuming that handles all validation // all inputajax templates use rollback() to prevent making actual changes -> check for isRollback() if(isAjaxRuntimeRequest() && outstream.length() > 0 && isRollback()){ response.getWriter().write("["); response.getWriter().write(outstream); if(this.isLogSqlEnabled()){ // Cannot use (parammap.get("logsql") != null) here, because the parammap is cleared by actions if(logSqlCheckAccess()){ response.getWriter().write("{action: \"logsql\", value: \"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(utils.HibernateLog.printHibernateLog(this, "ajax")) + "\"}"); } else{ response.getWriter().write("{action: \"logsql\", value: \"Access to SQL logs was denied.\"}"); } response.getWriter().write(","); } response.getWriter().write("{}]"); } // action called but no action found else if( !isWebService() && isValid() && isActionSubmit() ){ org.webdsl.logging.Logger.error("Error: server received POST request but was unable to dispatch to a proper action (" + request.getRequestURL() + ")" ); httpServletResponse.setStatus( 404 ); response.getWriter().write("404 \n Error: server received POST request but was unable to dispatch to a proper action"); } // action inside ajax template called and failed else if( isAjaxTemplateRequest() && isActionSubmit() ){ StringWriter s1 = renderPageOrTemplateContents(); response.getWriter().write("[{action:\"replace\", id:{type:'enclosing-placeholder'}, value:\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(s1.toString()) + "\"}]"); } //actionLink or ajax action used (request came through js runtime), and action failed else if( isActionLinkUsed() || isAjaxRuntimeRequest() ){ validationFormRerender = true; renderPageOrTemplateContents(); if(submittedFormId != null){ response.getWriter().write("[{action:\"replace\", id:\"" + submittedFormId + "\", value:\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript( submittedFormContent ) + "\"}]"); } else{ response.getWriter().write("[{action:\"replace\", id:{submitid:'" + submittedSubmitId + "'}, value:\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript( submittedFormContent ) + "\"}]"); } } // 1 regular render without any action being executed // 2 regular action submit, and action failed // 3 redirect in page init // 4 download in page init else{ isAjaxResponse = false; renderOrInitAction(); } } // successful action, always redirect, no render else { // actionLink or ajax action used and replace(placeholder) invoked if( isReRenderPlaceholders() ){ response.getWriter().write( "[" ); templateservlet.validateInputs (null, args, new Environment(envGlobalAndSession), null); ThreadLocalPage.get().clearTemplateContext(); renderDynamicFormWithOnlyDirtyData = true; renderPageOrTemplateContents(); // content of placeholders is collected in reRenderPlaceholdersContent map StringWriter replacements = new StringWriter(); boolean addComma = false; for(String ph : reRenderPlaceholders){ if(addComma){ replacements.write(","); } else { addComma = true; } replacements.write("{action:\"replace\", id:\""+ph+"\", value:\"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(reRenderPlaceholdersContent.get(ph)) + "\"}"); } response.getWriter().write( replacements.toString() ); if( outstream.length() > 0 ){ response.getWriter().write( "," + outstream.substring(0, outstream.length() - 1) + "]" ); // Other ajax updates, such as clear(ph). Done after ph rerendering to allow customization. } else{ response.getWriter().write( "]" ); } } //hasExecutedAction() && isValid() else if( isAjaxRuntimeRequest() ){ response.getWriter().write("["); response.getWriter().write(outstream); if(this.isLogSqlEnabled()){ // Cannot use (parammap.get("logsql") != null) here, because the parammap is cleared by actions if(logSqlCheckAccess()){ response.getWriter().write("{action: \"logsql\", value: \"" + org.apache.commons.lang3.StringEscapeUtils.escapeEcmaScript(utils.HibernateLog.printHibernateLog(this, "ajax")) + "\"}"); } else{ response.getWriter().write("{action: \"logsql\", value: \"Access to SQL logs was denied.\"}"); } response.getWriter().write(","); } response.getWriter().write("{}]"); } else if( isActionLinkUsed() ){ //action link also uses ajax when ajax is not enabled //, send only redirect location, so the client can simply set // window.location = req.responseText; response.getWriter().write("[{action:\"relocate\", value:\""+this.getRedirectUrl() + "\"}]"); } else { isAjaxResponse = false; } if(!isAjaxRuntimeRequest()) { addLogSqlToSessionMessages(); } //else: action successful + no validation error + regular submit // -> always results in a redirect, no further action necessary here } if(isAjaxResponse){ response.setContentType("application/json"); } } updatePageRequestStatistics(); hibernateSession = utils.HibernateUtil.getCurrentSession(); if( isTransactionAborted() || isRollback() ){ try{ hibernateSession.getTransaction().rollback(); response.sendContent(); } catch (org.hibernate.SessionException e){ if(!e.getMessage().equals("Session is closed!")){ // closed session is not an issue when rolling back throw e; } } } else { ThreadLocalServlet.get().storeOutgoingMessagesInHttpSession( !isRedirected() || isPostRequest() ); addPrincipalToRequestLog(rle); if(!this.isAjaxRuntimeRequest()){ ThreadLocalServlet.get().setEndTimeAndStoreRequestLog(utils.HibernateUtil.getCurrentSession()); } ThreadLocalServlet.get().setCookie(hibernateSession); if(isReadOnly || !hasWrites){ // either page has read-only modifier, or no writes have been detected hibernateSession.getTransaction().rollback(); } else{ hibernateSession.flush(); validateEntities(); hibernateSession.getTransaction().commit(); invalidatePageCacheIfNeeded(); } if(exceptionInHibernateInterceptor != null){ throw exceptionInHibernateInterceptor; } response.sendContent(); } ThreadLocalOut.popChecked(out); } catch(utils.MultipleValidationExceptions mve){ String url = ThreadLocalServlet.get().getRequest().getRequestURL().toString(); org.webdsl.logging.Logger.error("Validation exceptions occurred while handling request URL [ " + url + " ]. Transaction is rolled back."); for(utils.ValidationException vex : mve.getValidationExceptions()){ org.webdsl.logging.Logger.error( "Validation error: " + vex.getErrorMessage() , vex ); } hibernateSession.getTransaction().rollback(); setValidated(false); throw mve; } catch (Exception e) { String url = ThreadLocalServlet.get().getRequest().getRequestURL().toString(); org.webdsl.logging.Logger.error("exception occurred while handling request URL [ " + url + " ]. Transaction is rolled back."); org.webdsl.logging.Logger.error("exception message: "+e.getMessage(), e); if(hibernateSession.isOpen()){ hibernateSession.getTransaction().rollback(); } throw e; } finally{ cleanupThreadLocals(); org.apache.log4j.MDC.remove("request"); org.apache.log4j.MDC.remove("template"); if(reqAppender != null) reqAppender.removeRequest(rle.getId().toString()); } } // LoadingCache is thread-safe public static boolean pageCacheEnabled = utils.BuildProperties.getNumCachedPages() > 0; public static Cache<String, CacheResult> cacheAnonymousPages = CacheBuilder.newBuilder() .maximumSize(utils.BuildProperties.getNumCachedPages()).build(); public boolean invalidateAllPageCache = false; protected boolean shouldTryCleanPageCaches = false; public String invalidateAllPageCacheMessage; public void invalidateAllPageCache(String entityname){ commandingPage.invalidateAllPageCacheInternal(entityname); } private void invalidateAllPageCacheInternal(String entityname){ invalidateAllPageCache = true; invalidateAllPageCacheMessage = entityname; } public void shouldTryCleanPageCaches(){ commandingPage.shouldTryCleanPageCachesInternal(); } private void shouldTryCleanPageCachesInternal(){ shouldTryCleanPageCaches = true; } public static Cache<String, CacheResult> cacheUserSpecificPages = CacheBuilder.newBuilder() .maximumSize(utils.BuildProperties.getNumCachedPages()).build(); public boolean invalidateUserSpecificPageCache = false; public String invalidateUserSpecificPageCacheMessage; public void invalidateUserSpecificPageCache(String entityname){ commandingPage.invalidateUserSpecificPageCacheInternal(entityname); } private void invalidateUserSpecificPageCacheInternal(String entityname){ invalidateUserSpecificPageCache = true; String propertySetterTrace = Warning.getStackTraceLineAtIndex(4); invalidateUserSpecificPageCacheMessage = entityname + " - " + propertySetterTrace; } public boolean pageCacheWasUsed = false; public void invalidatePageCacheIfNeeded(){ if(pageCacheEnabled && shouldTryCleanPageCaches){ if(invalidateAllPageCache){ Logger.info("All page caches invalidated, triggered by change in: "+invalidateAllPageCacheMessage); cacheAnonymousPages.invalidateAll(); cacheUserSpecificPages.invalidateAll(); } else if(invalidateUserSpecificPageCache){ Logger.info("user-specific page cache invalidated, triggered by change in: "+invalidateUserSpecificPageCacheMessage); cacheUserSpecificPages.invalidateAll(); } } } public void renderOrInitAction() throws IOException{ String key = request.getRequestURL().toString(); String s = ""; Cache<String, CacheResult> cache = null; AbstractDispatchServletHelper servlet = ThreadLocalServlet.get(); if( // not using page cache if: this.isPageCacheDisabled // ?nocache added to URL || this.isPostRequest() // post parameters are not included in cache key || isNotValid() // data validation errors need to be rendered || !servlet.getIncomingSuccessMessages().isEmpty() // success messages need to be rendered ){ StringWriter renderedContent = renderPageOrTemplateContents(); if(!mimetypeChanged){ s = renderResponse(renderedContent); } else{ s = renderedContent.toString(); } } else{ // using page cache if( // use user-specific page cache if: servlet.sessionHasChanges() // not necessarily login, any session data changes can be included in a rendered page || webdsl.generated.functions.loggedIn_.loggedIn_() // user might have old session from before application start, this check is needed to avoid those logged in pages ending up in the anonymous page cache ){ key = key + servlet.getSessionManager().getId(); cache = cacheUserSpecificPages; } else{ cache = cacheAnonymousPages; } try{ pageCacheWasUsed = true; CacheResult result = cache.get(key, new Callable<CacheResult>(){ public CacheResult call(){ // System.out.println("key not found"); pageCacheWasUsed = false; StringWriter renderedContent = renderPageOrTemplateContents(); CacheResult result = new CacheResult(); if(!mimetypeChanged){ result.body = renderResponse(renderedContent); } else{ result.body = renderedContent.toString(); } result.mimetype = getMimetype(); return result; } }); s = result.body; setMimetype(result.mimetype); } catch(java.util.concurrent.ExecutionException e){ e.printStackTrace(); } } // redirect in init action can be triggered with GET request, the render call in the line above will execute such inits if( !isPostRequest() && isRedirected() ){ redirect(); if(cache != null){ cache.invalidate(key); } } else if( download != null ){ //File.download() executed in page/template init block download(); if(cache != null){ cache.invalidate(key); } // don't cache binary file response in this page response cache, can be cached on client with expires header } else{ response.setContentType(getMimetype()); PrintWriter sout = response.getWriter(); //reponse.getWriter() must be called after file download checks sout.write(s); } } public boolean renderDynamicFormWithOnlyDirtyData = false; public StringWriter renderPageOrTemplateContents(){ if(isTemplate() && !ThreadLocalServlet.get().isPostRequest){ throw new utils.AjaxWithGetRequestException(); } StringWriter s = new StringWriter(); PrintWriter out = new PrintWriter(s); if(request.getParameter("dynamicform") == null){ // regular pages and forms if(isNotValid()){ clearHibernateCache(); } ThreadLocalOut.push(out); templateservlet.render(null, args, new Environment(envGlobalAndSession), null); ThreadLocalOut.popChecked(out); } else{ // dynamicform uses submitted variable data to process form content // render form with newly entered data, rest with the current persisted data if(isNotValid() && !renderDynamicFormWithOnlyDirtyData){ StringWriter theform = new StringWriter(); PrintWriter pwform = new PrintWriter(theform); ThreadLocalOut.push(pwform); // render, when encountering submitted form save in abstractpage validationFormRerender = true; templateservlet.render(null, args, new Environment(envGlobalAndSession), null); ThreadLocalOut.popChecked(pwform); clearHibernateCache(); } ThreadLocalOut.push(out); // render, when isNotValid and encountering submitted form render old templateservlet.render(null, args, new Environment(envGlobalAndSession), null); ThreadLocalOut.popChecked(out); } return s; } public StringWriter renderPageOrTemplateContentsSingle(){ if(isTemplate() && !ThreadLocalServlet.get().isPostRequest){ throw new utils.AjaxWithGetRequestException(); } StringWriter s = new StringWriter(); PrintWriter out = new PrintWriter(s); ThreadLocalOut.push(out); templateservlet.render(null, args, new Environment(envGlobalAndSession), null); ThreadLocalOut.popChecked(out); return s; } private boolean validationFormRerender = false; public boolean isValidationFormRerender(){ return validationFormRerender; } public String submittedFormContent = null; public String submittedFormId = null; public String submittedSubmitId = null; // helper methods that enable a submit without enclosing form to be ajax-refreshed when validation error occurs protected StringWriter submitWrapSW; protected PrintWriter submitWrapOut; public void submitWrapOpenHelper(String submitId){ if( ! inSubmittedForm && validationFormRerender && request != null && request.getParameter(submitId) != null ){ submittedSubmitId = submitId; submitWrapSW = new java.io.StringWriter(); submitWrapOut = new java.io.PrintWriter(submitWrapSW); ThreadLocalOut.push(submitWrapOut); ThreadLocalOut.peek().print("<span submitid=" + submitId + ">"); } } public void submitWrapCloseHelper(){ if( ! inSubmittedForm && validationFormRerender && submitWrapSW != null ){ ThreadLocalOut.peek().print("</span>"); ThreadLocalOut.pop(); submittedFormContent = submitWrapSW.toString(); submitWrapSW = null; } } private static String common_css_link_tag_suffix; private static String fav_ico_link_tag_suffix; private static String ajax_js_include_name; public String renderResponse(StringWriter s) { StringWriter sw = new StringWriter(); PrintWriter sout = new PrintWriter(sw); ThreadLocalOut.push(sout); addJavascriptInclude( utils.IncludePaths.jQueryJS() ); addJavascriptInclude( ajax_js_include_name ); sout.println("<!DOCTYPE html>"); sout.println("<html>"); sout.println("<head>"); sout.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"); sout.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">"); sout.println("<title>"+getPageTitle().replaceAll("<[^>]*>","")+"</title>"); sout.println("<link href=\""+ThreadLocalPage.get().getAbsoluteLocation()+fav_ico_link_tag_suffix); sout.println("<link href=\""+ThreadLocalPage.get().getAbsoluteLocation()+common_css_link_tag_suffix); renderDebugJsVar(sout); sout.println("<script type=\"text/javascript\">var contextpath=\""+ThreadLocalPage.get().getAbsoluteLocation()+"\";</script>"); for(String sheet : this.stylesheets) { if(sheet.startsWith(" sout.print("<link rel=\"stylesheet\" href=\""+ sheet + "\" type=\"text/css\" />"); } else{ String hashedName = CachedResourceFileNameHelper.getNameWithHash("stylesheets", sheet); sout.print("<link rel=\"stylesheet\" href=\""+ThreadLocalPage.get().getAbsoluteLocation()+"/stylesheets/"+hashedName+"\" type=\"text/css\" />"); } } for(String script : this.javascripts) { if(script.startsWith(" sout.println("<script type=\"text/javascript\" src=\"" + script + "\"></script>"); } else{ String hashedName = CachedResourceFileNameHelper.getNameWithHash("javascript", script); sout.println("<script type=\"text/javascript\" src=\""+ThreadLocalPage.get().getAbsoluteLocation()+"/javascript/"+hashedName+"\"></script>"); } } for(Map.Entry<String,String> headEntry : customHeadNoDuplicates.entrySet()) { // sout.println("<!-- " + headEntry.getKey() + " -->"); sout.println(headEntry.getValue()); } for(String headEntry : customHeads) { sout.println(headEntry); } sout.println("</head>"); sout.print("<body id=\""+this.getPageName()+"\""); for(String attribute : this.bodyAttributes) { sout.print(attribute); } sout.print(">"); renderLogSqlMessage(); renderIncomingSuccessMessages(); s.flush(); sout.write(s.toString()); if(this.isLogSqlEnabled()){ if(logSqlCheckAccess()){ sout.print("<hr/><div class=\"logsql\">"); utils.HibernateLog.printHibernateLog(sout, this, null); sout.print("</div>"); } else{ sout.print("<hr/><div class=\"logsql\">Access to SQL logs was denied.</div>"); } } sout.print("</body>"); sout.println("</html>"); ThreadLocalOut.popChecked(sout); return sw.toString(); } //ajax/js runtime request related protected abstract void initializeBasics(AbstractPageServlet ps, Object[] args); public boolean isServingAsAjaxResponse = false; public void serveAsAjaxResponse(Object[] args, TemplateCall templateArg) { AbstractPageServlet ps = ThreadLocalPage.get(); TemplateServlet ts = ThreadLocalTemplate.get(); //inherit commandingPage commandingPage = ps.commandingPage; //use passed PageServlet ps here, since this is the context for this type of response initializeBasics(ps, args); ThreadLocalPage.set(this); //outputstream threadlocal is already set, see to-java-servlet/ajax/ajax.str this.isServingAsAjaxResponse = true; templateservlet.render(null, args, Environment.createNewLocalEnvironment(envGlobalAndSession), null); // new clean environment with only the global templates, and global/session vars ThreadLocalTemplate.set(ts); ThreadLocalPage.set(ps); } protected boolean isTemplate() { return false; } public static AbstractPageServlet getRequestedPage(){ return ThreadLocalPage.get(); } private boolean passedThroughAjaxTemplate = false; public boolean passedThroughAjaxTemplate(){ return passedThroughAjaxTemplate; } public void setPassedThroughAjaxTemplate(boolean b){ passedThroughAjaxTemplate = b; } protected boolean isLogSqlEnabled = false; public boolean isLogSqlEnabled() { return isLogSqlEnabled; } public boolean isPageCacheDisabled = false; protected boolean isOptimizationEnabled = true; public boolean isOptimizationEnabled() { return isOptimizationEnabled; } public String getExtraQueryAruments(String firstChar) { // firstChar is expeced to be ? or &, depending on wether there are more query aruments String res = ""; if(!isOptimizationEnabled || isLogSqlEnabled) { res = firstChar; if(isLogSqlEnabled) res += "logsql"; if(isLogSqlEnabled && !isOptimizationEnabled) res += "&"; if(!isOptimizationEnabled) res += "disableopt"; } return res; } public abstract String getPageName(); public abstract String getUniqueName(); protected MessageDigest messageDigest = null; public MessageDigest getMessageDigest(){ if(messageDigest == null){ try{ messageDigest = MessageDigest.getInstance("MD5"); } catch(NoSuchAlgorithmException ae) { org.webdsl.logging.Logger.error("MD5 not available: "+ae.getMessage()); return null; } } return messageDigest; } public boolean actionToBeExecutedHasDisabledValidation = false; public boolean actionHasAjaxPageUpdates = false; //TODO merge getActionTarget and getPageUrlWithParams public String getActionTarget() { if (isServingAsAjaxResponse){ return this.getUniqueName(); } return getPageName(); } //TODO merge getActionTarget and getPageUrlWithParams public String getPageUrlWithParams(){ //used for action field in forms if(isServingAsAjaxResponse){ return ThreadLocalPage.get().getAbsoluteLocation()+"/"+ThreadLocalPage.get().getActionTarget(); } else{ //this doesn't work with ajax template render from action, since an ajax template needs to submit to a different page than the original request return request.getRequestURL().toString(); } } protected abstract void renderIncomingSuccessMessages(); protected abstract void renderLogSqlMessage(); public boolean isPostRequest(){ return ThreadLocalServlet.get().isPostRequest; } public boolean isNotPostRequest(){ return !ThreadLocalServlet.get().isPostRequest; } public boolean isAjaxTemplateRequest(){ return ThreadLocalServlet.get().getPages().get(ThreadLocalServlet.get().getRequestedPage()).isAjaxTemplate(); } public abstract String getHiddenParams(); public abstract String getUrlQueryParams(); public abstract String getHiddenPostParamsJson(); //public javax.servlet.http.HttpSession session; public static void cleanupThreadLocals(){ ThreadLocalEmailContext.set(null); ThreadLocalPage.set(null); ThreadLocalTemplate.setNull(); } //templates scope public static Environment staticEnv = Environment.createSharedEnvironment(); public Environment envGlobalAndSession = Environment.createLocalEnvironment(); //emails protected static Map<String, Class<?>> emails = new HashMap<String, Class<?>>(); public static Map<String, Class<?>> getEmails() { return emails; } public boolean sendEmail(String name, Object[] emailargs, Environment emailenv){ EmailServlet temp = renderEmail(name,emailargs,emailenv); return temp.send(); } public EmailServlet renderEmail(String name, Object[] emailargs, Environment emailenv){ EmailServlet temp = null; try { temp = ((EmailServlet)getEmails().get(name).newInstance()); } catch(IllegalAccessException iae) { org.webdsl.logging.Logger.error("Problem in email template lookup: " + iae.getMessage()); } catch(InstantiationException ie) { org.webdsl.logging.Logger.error("Problem in email template lookup: " + ie.getMessage()); } temp.render(emailargs, emailenv); return temp; } //rendertemplate function public String renderTemplate(String name, Object[] args, Environment env){ return executeTemplatePhase(RENDER_PHASE, name, args, env); } //validatetemplate function public String validateTemplate(String name, Object[] args, Environment env){ return executeTemplatePhase(VALIDATE_PHASE, name, args, env); } public static final int DATABIND_PHASE = 1; public static final int VALIDATE_PHASE = 2; public static final int ACTION_PHASE = 3; public static final int RENDER_PHASE = 4; public String executeTemplatePhase(int phase, String name, Object[] args, Environment env){ StringWriter s = new StringWriter(); PrintWriter out = new PrintWriter(s); ThreadLocalOut.push(out); TemplateServlet enclosingTemplateObject = ThreadLocalTemplate.get(); try{ TemplateServlet temp = ((TemplateServlet)env.getTemplate(name).newInstance()); switch(phase){ case VALIDATE_PHASE: temp.validateInputs(name, args, env, null); break; case RENDER_PHASE: temp.render(name, args, env, null); break; } } catch(Exception oe){ try { TemplateCall tcall = env.getWithcall(name); //'elements' or requires arg TemplateServlet temp = ((TemplateServlet)env.getTemplate(tcall.name).newInstance()); String parent = env.getWithcall(name)==null?null:env.getWithcall(name).parentName; switch(phase){ case VALIDATE_PHASE: temp.validateInputs(parent, tcall.args, env, null); break; case RENDER_PHASE: temp.render(parent, tcall.args, env, null); break; } } catch(Exception ie){ org.webdsl.logging.Logger.error("EXCEPTION",oe); org.webdsl.logging.Logger.error("EXCEPTION",ie); } } ThreadLocalTemplate.set(enclosingTemplateObject); ThreadLocalOut.popChecked(out); return s.toString(); } //ref arg protected static Map<String, Class<?>> refargclasses = new HashMap<String, Class<?>>(); public static Map<String, Class<?>> getRefArgClasses() { return refargclasses; } public abstract String getAbsoluteLocation(); public String getXForwardedProto() { if (request == null) { return null; } else { return request.getHeader("x-forwarded-proto"); } } public String getXForwardedFor() { if (request == null) { return null; } else { return request.getHeader("x-forwarded-for"); } } protected TemplateContext templateContext = new TemplateContext(); public String getTemplateContextString() { return templateContext.getTemplateContextString(); } public void enterTemplateContext(String s) { templateContext.enterTemplateContext(s); } public void leaveTemplateContext() { templateContext.leaveTemplateContext(); } public void leaveTemplateContextChecked(String s) { templateContext.leaveTemplateContextChecked(s); } public void clearTemplateContext(){ templateContext.clearTemplateContext(); } public void setTemplateContext(TemplateContext tc){ templateContext = tc; } public TemplateContext getTemplateContext(){ return templateContext; } // objects scheduled to be checked after action completes, filled by hibernate event listener in hibernate util class ArrayList<WebDSLEntity> entitiesToBeValidated = new ArrayList<WebDSLEntity>(); boolean allowAddingEntitiesForValidation = true; public void clearEntitiesToBeValidated(){ entitiesToBeValidated = new ArrayList<WebDSLEntity>(); allowAddingEntitiesForValidation = true; } public void addEntityToBeValidated(WebDSLEntity w){ if(allowAddingEntitiesForValidation){ entitiesToBeValidated.add(w); } } public void validateEntities(){ allowAddingEntitiesForValidation = false; //adding entities must be disabled when checking is performed, new entities may be loaded for checks, but do not have to be checked themselves java.util.Set<WebDSLEntity> set = new java.util.HashSet<WebDSLEntity>(entitiesToBeValidated); java.util.List<utils.ValidationException> exceptions = new java.util.LinkedList<utils.ValidationException>(); for(WebDSLEntity w : set){ if(w.isChanged()){ try { // System.out.println("validating: "+ w.get_WebDslEntityType() + ":" + w.getName()); w.validateSave(); //System.out.println("done validating"); } catch(utils.ValidationException ve){ exceptions.add(ve); } catch(utils.MultipleValidationExceptions ve) { for(utils.ValidationException vex : ve.getValidationExceptions()){ exceptions.add(vex); } } } } if(exceptions.size() > 0){ throw new utils.MultipleValidationExceptions(exceptions); } clearEntitiesToBeValidated(); } protected List<utils.ValidationException> validationExceptions = new java.util.LinkedList<utils.ValidationException>(); public List<utils.ValidationException> getValidationExceptions() { return validationExceptions; } public void addValidationException(String name, String message){ validationExceptions.add(new ValidationException(name,message)); } public List<utils.ValidationException> getValidationExceptionsByName(String name) { List<utils.ValidationException> list = new java.util.LinkedList<utils.ValidationException>(); for(utils.ValidationException v : validationExceptions){ if(v.getName().equals(name)){ list.add(v); } } return list; } public List<String> getValidationErrorsByName(String name) { List<String> list = new java.util.ArrayList<String>(); for(utils.ValidationException v : validationExceptions){ if(v.getName().equals(name)){ list.add(v.getErrorMessage()); } } return list; } public boolean hasExecutedAction = false; public boolean hasExecutedAction(){ return hasExecutedAction; } public boolean hasNotExecutedAction(){ return !hasExecutedAction; } protected boolean abortTransaction = false; public boolean isTransactionAborted(){ return abortTransaction; } public void abortTransaction(){ abortTransaction = true; } public java.util.List<String> ignoreset= new java.util.ArrayList<String>(); public boolean hibernateCacheCleared = false; protected java.util.List<String> javascripts = new java.util.ArrayList<String>(); protected java.util.List<String> stylesheets = new java.util.ArrayList<String>(); protected java.util.List<String> customHeads = new java.util.ArrayList<String>(); protected java.util.List<String> bodyAttributes = new java.util.ArrayList<String>(); protected java.util.Map<String,String> customHeadNoDuplicates = new java.util.HashMap<String,String>(); public void addJavascriptInclude(String filename) { commandingPage.addJavascriptIncludeInternal( filename ); } public void addJavascriptIncludeInternal(String filename) { if(!javascripts.contains(filename)) javascripts.add(filename); } public void addStylesheetInclude(String filename) { commandingPage.addStylesheetIncludeInternal( filename ); } public void addStylesheetIncludeInternal(String filename) { if(!stylesheets.contains(filename)){ stylesheets.add(filename); } } public void addStylesheetInclude(String filename, String media) { commandingPage.addStylesheetIncludeInternal( filename, media ); } public void addStylesheetIncludeInternal(String filename, String media) { String combined = media != null && !media.isEmpty() ? filename + "\" media=\""+ media : filename; if(!stylesheets.contains(combined)){ stylesheets.add(combined); } } public void addCustomHead(String header) { commandingPage.addCustomHeadInternal(header, header); } public void addCustomHead(String key, String header) { commandingPage.addCustomHeadInternal(key, header); } public void addCustomHeadInternal(String key, String header) { customHeadNoDuplicates.put(key, header); } public void addBodyAttribute(String key, String value) { commandingPage.addBodyAttributeInternal(key, value); } public void addBodyAttributeInternal(String key, String value) { bodyAttributes.add(" "+key+"=\""+value+"\""); } protected abstract void initialize(); protected abstract void conversion(); protected abstract void loadArguments(); public abstract void initVarsAndArgs(); public void clearHibernateCache() { // used to be only ' hibSession.clear(); ' but that doesn't revert already flushed changes. // since flushing now happens automatically when querying, this could produce wrong results. // e.g. output in page with validation errors shows changes that were not persisted to the db. // see regression test in test/succeed-web/validate-false-and-flush.app utils.HibernateUtil.getCurrentSession().getTransaction().rollback(); openNewTransactionThroughGetCurrentSession(); ThreadLocalServlet.get().reloadSessionManager(hibernateSession); initVarsAndArgs(); hibernateCacheCleared = true; } protected org.hibernate.Session openNewTransactionThroughGetCurrentSession(){ hibernateSession = utils.HibernateUtil.getCurrentSession(); hibernateSession.beginTransaction(); return hibernateSession; } protected HttpServletRequest request; protected ResponseWrapper response; protected HttpServletResponse httpServletResponse; protected Object[] args; // public void setHibSession(Session s) { // hibSession = s; // public Session getHibSession() { // return hibSession; public HttpServletRequest getRequest() { return request; } public ResponseWrapper getResponse() { return response; } protected boolean validated=true; /* * when this is true, it can mean: * 1 no validation has been performed yet * 2 some validation has been performed without errors * 3 all validation has been performed without errors */ public boolean isValid() { return validated; } public boolean isNotValid() { return !validated; } public void setValidated(boolean validated) { this.validated = validated; } /* * complete action regularly but rollback hibernate session * skips validation of entities at end of action, if validation messages are necessary * use cancel() instead of rollback() * can be used to replace templates with ajax without saving, e.g. for validation */ protected boolean rollback = false; public boolean isRollback() { return rollback; } public void setRollback() { //by setting validated true, the action will succeed this.setValidated(true); //the session will be rolled back, to cancel persisting any changes this.rollback = true; } public List<String> failedCaptchaResponses = new ArrayList<String>(); protected boolean inSubmittedForm = false; public boolean inSubmittedForm() { return inSubmittedForm; } public void setInSubmittedForm(boolean b) { this.inSubmittedForm = b; } // used for runtime check to detect nested forms protected String inForm = null; public boolean isInForm() { return inForm != null; } public void enterForm(String t) { inForm = t; } public String getEnclosingForm() { return inForm; } public void leaveForm() { inForm = null; } public void clearParammaps(){ parammap.clear(); parammapvalues.clear(); fileUploads.clear(); } protected java.util.Map<String, String> parammap; public java.util.Map<String, String> getParammap() { return parammap; } protected Map<String,List<utils.File>> fileUploads; public Map<String, List<utils.File>> getFileUploads() { return fileUploads; } public List<utils.File> getFileUploads(String key) { return fileUploads.get(key); } protected Map<String, List<String>> parammapvalues; public Map<String, List<String>> getParammapvalues() { return parammapvalues; } protected String pageTitle = ""; public String getPageTitle() { return pageTitle; } public void setPageTitle(String pageTitle) { this.pageTitle = pageTitle; } protected String formIdent = ""; public String getFormIdent() { return formIdent; } public void setFormIdent(String fi) { this.formIdent = fi; } protected boolean actionLinkUsed = false; public boolean isActionLinkUsed() { return actionLinkUsed; } public void setActionLinkUsed(boolean a) { this.actionLinkUsed = a; } protected boolean ajaxRuntimeRequest = false; public boolean isAjaxRuntimeRequest() { return ajaxRuntimeRequest; } public void setAjaxRuntimeRequest(boolean a) { ajaxRuntimeRequest = a; } protected String redirectUrl = ""; public boolean isRedirected(){ return !"".equals(redirectUrl); } public String getRedirectUrl() { return redirectUrl; } public void setRedirectUrl(String a) { this.redirectUrl = a; } // perform the actual redirect public void redirect(){ try { response.sendRedirect(this.getRedirectUrl()); } catch (IOException ioe) { org.webdsl.logging.Logger.error("redirect failed", ioe); } } protected String mimetype = "text/html; charset=UTF-8"; protected boolean mimetypeChanged = false; public String getMimetype() { return mimetype; } public void setMimetype(String mimetype) { this.mimetype = mimetype; mimetypeChanged = true; if(!isMarkupLangMimeType.matcher(mimetype).find()){ enableRawoutput(); } disableTemplateSpans(); } protected boolean downloadInline = false; public boolean getDownloadInline() { return downloadInline; } public void enableDownloadInline() { this.downloadInline = true; } protected boolean ajaxActionExecuted = false; public boolean isAjaxActionExecuted() { return ajaxActionExecuted; } public void enableAjaxActionExecuted() { ajaxActionExecuted = true; } protected boolean rawoutput = false; public boolean isRawoutput() { return rawoutput; } public void enableRawoutput() { rawoutput = true; } public void disableRawoutput() { rawoutput = false; } protected String[] pageArguments = null; public void setPageArguments(String[] pa) { pageArguments = pa; } public String[] getPageArguments() { return pageArguments; } protected String httpMethod = null; public void setHttpMethod(String httpMethod) { this.httpMethod = httpMethod; } public String getHttpMethod() { return httpMethod; } protected boolean templateSpans = true; public boolean templateSpans() { return templateSpans; } public void disableTemplateSpans() { templateSpans = false; } protected List<String> reRenderPlaceholders = null; protected Map<String,String> reRenderPlaceholdersContent = null; public boolean isReRenderPlaceholders() { return reRenderPlaceholders != null; } public void addReRenderPlaceholders(String placeholder) { if(reRenderPlaceholders == null){ reRenderPlaceholders = new ArrayList<String>(); reRenderPlaceholdersContent = new HashMap<String,String>(); } reRenderPlaceholders.add(placeholder); } public void addReRenderPlaceholdersContent(String placeholder, String content) { if(reRenderPlaceholders != null && reRenderPlaceholders.contains(placeholder)){ reRenderPlaceholdersContent.put(placeholder,content); } } protected utils.File download = null; public void setDownload(utils.File file){ this.download = file; } public boolean isDownloadSet(){ return this.download != null; } protected void download() { /* Long id = download.getId(); org.hibernate.Session hibSession = HibernateUtilConfigured.getSessionFactory().openSession(); hibSession.beginTransaction(); hibSession.setFlushMode(org.hibernate.FlushMode.MANUAL); utils.File download = (utils.File)hibSession.load(utils.File.class,id); */ try { javax.servlet.ServletOutputStream outstream; outstream = response.getOutputStream(); java.sql.Blob blob = download.getContent(); java.io.InputStream in; in = blob.getBinaryStream(); response.setContentType(download.getContentType()); if(!downloadInline) { response.setHeader("Content-Disposition", "attachment; filename=\"" + download.getFileNameForDownload() + "\""); } java.io.BufferedOutputStream bufout = new java.io.BufferedOutputStream(outstream); byte bytes[] = new byte[32768]; int index = in.read(bytes, 0, 32768); while(index != -1) { bufout.write(bytes, 0, index); index = in.read(bytes, 0, 32768); } bufout.flush(); } catch(java.sql.SQLException ex) { org.webdsl.logging.Logger.error("exception in download serve"); org.webdsl.logging.Logger.error("EXCEPTION",ex); } catch (IOException ex) { org.webdsl.logging.Logger.error("exception in download serve"); org.webdsl.logging.Logger.error("EXCEPTION",ex); } /* hibSession.flush(); hibSession.getTransaction().commit(); */ } //data validation public java.util.LinkedList<String> validationContext = new java.util.LinkedList<String>(); public String getValidationContext() { //System.out.println("using" + validationContext.peek()); return validationContext.peek(); } public void enterValidationContext(String ident) { validationContext.add(ident); //System.out.println("entering" + ident); } public void leaveValidationContext() { /*String s = */ validationContext.removeLast(); //System.out.println("leaving" +s); } public boolean inValidationContext() { return validationContext.size() != 0; } //form public boolean formRequiresMultipartEnc = false; //formGroup public String formGroupLeftSize = "150"; //public java.util.Stack<utils.FormGroupContext> formGroupContexts = new java.util.Stack<utils.FormGroupContext>(); public utils.FormGroupContext getFormGroupContext() { return (utils.FormGroupContext) tableContexts.peek(); } public void enterFormGroupContext() { tableContexts.push(new utils.FormGroupContext()); } public void leaveFormGroupContext() { tableContexts.pop(); } public boolean inFormGroupContext() { return !tableContexts.empty() && tableContexts.peek() instanceof utils.FormGroupContext; } public java.util.Stack<String> formGroupContextClosingTags = new java.util.Stack<String>(); public void formGroupContextsCheckEnter(PrintWriter out) { if(inFormGroupContext()){ utils.FormGroupContext temp = getFormGroupContext(); if(!temp.isInDoubleColumnContext()){ // ignore defaults when in scope of a double column if(!temp.isInColumnContext()){ //don't nest left and right temp.enterColumnContext(); if(temp.isInLeftContext()) { out.print("<div style=\"clear:left; float:left; width: " + formGroupLeftSize + "px\">"); formGroupContextClosingTags.push("left"); temp.toRightContext(); } else { out.print("<div style=\"float: left;\">"); formGroupContextClosingTags.push("right"); temp.toLeftContext(); } } else{ formGroupContextClosingTags.push("none"); } } } } public void formGroupContextsCheckLeave(PrintWriter out) { if(inFormGroupContext()){ utils.FormGroupContext temp = getFormGroupContext(); if(!temp.isInDoubleColumnContext()) { String tags = formGroupContextClosingTags.pop(); if(tags.equals("left")){ //temp.toRightContext(); temp.leaveColumnContext(); out.print("</div>"); } else if(tags.equals("right")){ //temp.toLeftContext(); temp.leaveColumnContext(); out.print("</div>"); } } } } public void formGroupContextsDisplayLeftEnter(PrintWriter out) { if(inFormGroupContext()){ utils.FormGroupContext temp = getFormGroupContext(); if(!temp.isInColumnContext()){ temp.enterColumnContext(); out.print("<div style=\"clear:left; float:left; width: " + formGroupLeftSize + "px\">"); formGroupContextClosingTags.push("left"); temp.toRightContext(); } else{ formGroupContextClosingTags.push("none"); } } } public void formGroupContextsDisplayRightEnter(PrintWriter out) { if(inFormGroupContext()){ utils.FormGroupContext temp = getFormGroupContext(); if(!temp.isInColumnContext()){ temp.enterColumnContext(); out.print("<div style=\"float: left;\">"); formGroupContextClosingTags.push("right"); temp.toLeftContext(); } else{ formGroupContextClosingTags.push("none"); } } } //label public String getLabelString() { return getLabelStringForTemplateContext(ThreadLocalTemplate.get().getUniqueId()); } public java.util.Stack<String> labelStrings = new java.util.Stack<String>(); public java.util.Set<String> usedPageElementIds = new java.util.HashSet<String>(); public static java.util.Random rand = new java.util.Random(); //avoid duplicate ids; if multiple inputs are in a label, only the first is connected to the label public String getLabelStringOnce() { String s = labelStrings.peek(); if(usedPageElementIds.contains(s)){ do{ s += rand.nextInt(); } while(usedPageElementIds.contains(s)); } usedPageElementIds.add(s); return s; } public java.util.Map<String,String> usedPageElementIdsTemplateContext = new java.util.HashMap<String,String>(); //subsequent calls from the same defined template (e.g. in different phases) should produce the same id public String getLabelStringForTemplateContext(String context) { String labelid = usedPageElementIdsTemplateContext.get(context); if(labelid == null){ labelid = getLabelStringOnce(); usedPageElementIdsTemplateContext.put(context, labelid); } return labelid; } public void enterLabelContext(String ident) { labelStrings.push(ident); } public void leaveLabelContext() { labelStrings.pop(); } public boolean inLabelContext() { return !labelStrings.empty(); } //section public int sectionDepth = 0; public int getSectionDepth() { return sectionDepth; } public void enterSectionContext() { sectionDepth++; } public void leaveSectionContext() { sectionDepth } public boolean inSectionContext() { return sectionDepth > 0; } //table public java.util.Stack<Object> tableContexts = new java.util.Stack<Object>(); public utils.TableContext getTableContext() { return (utils.TableContext) tableContexts.peek(); } public void enterTableContext() { tableContexts.push(new utils.TableContext()); } public void leaveTableContext() { tableContexts.pop(); } public boolean inTableContext() { return !tableContexts.empty() && tableContexts.peek() instanceof utils.TableContext; } public java.util.Stack<String> tableContextClosingTags = new java.util.Stack<String>(); //separate row and column checks, used by label public void rowContextsCheckEnter(PrintWriter out) { if(inTableContext()){ utils.TableContext x_temp = getTableContext(); if(!x_temp.isInRowContext()) { out.print("<tr>"); x_temp.enterRowContext(); tableContextClosingTags.push("</tr>"); } else{ tableContextClosingTags.push(""); } } } public void rowContextsCheckLeave(PrintWriter out) { if(inTableContext()){ utils.TableContext x_temp = getTableContext(); String tags = tableContextClosingTags.pop(); if(tags.equals("</tr>")){ x_temp.leaveRowContext(); out.print(tags); } } } public void columnContextsCheckEnter(PrintWriter out) { if(inTableContext()){ utils.TableContext x_temp = getTableContext(); if(x_temp.isInRowContext() && !x_temp.isInColumnContext()) { out.print("<td>"); x_temp.enterColumnContext(); tableContextClosingTags.push("</td>"); } else{ tableContextClosingTags.push(""); } } } public void columnContextsCheckLeave(PrintWriter out) { if(inTableContext()){ utils.TableContext x_temp = getTableContext(); String tags = tableContextClosingTags.pop(); if(tags.equals("</td>")){ x_temp.leaveColumnContext(); out.print(tags); } } } //session manager public void reloadSessionManagerFromExistingSessionId(UUID sessionId){ ThreadLocalServlet.get().reloadSessionManagerFromExistingSessionId(hibernateSession, sessionId); initialize(); //reload session variables } //request vars public HashMap<String, Object> requestScopedVariables = new HashMap<String, Object>(); public void initRequestVars(){ initRequestVars(null); } public abstract void initRequestVars(PrintWriter out); protected long startTime = 0L; public long getStartTime() { return startTime; } public long getElapsedTime() { return System.currentTimeMillis() - startTime; } public Object getRequestScopedVar(String key){ return commandingPage.requestScopedVariables.get(key); } public void addRequestScopedVar(String key, Object val){ if(val != null){ commandingPage.requestScopedVariables.put(key, val); } } public void addRequestScopedVar(String key, WebDSLEntity val){ if(val != null){ val.setRequestVar(); commandingPage.requestScopedVariables.put(key, val); } } // statistics to be shown in log protected abstract void increaseStatReadOnly(); protected abstract void increaseStatReadOnlyFromCache(); protected abstract void increaseStatUpdate(); protected abstract void increaseStatActionFail(); protected abstract void increaseStatActionReadOnly(); protected abstract void increaseStatActionUpdate(); // register whether entity changes were made, see isChanged property of entities protected boolean hasWrites = false; public void setHasWrites(boolean b){ commandingPage.hasWrites = b; } protected void updatePageRequestStatistics(){ if(hasNotExecutedAction()){ if(!hasWrites || isRollback()){ if(pageCacheWasUsed){ increaseStatReadOnlyFromCache(); } else{ increaseStatReadOnly(); } } else{ increaseStatUpdate(); } } else{ if(isNotValid()){ increaseStatActionFail(); } else{ if(!hasWrites || isRollback()){ increaseStatActionReadOnly(); } else{ increaseStatActionUpdate(); } } } } // Hibernate interceptor hooks (such as beforeTransactionCompletion) catch Throwable but then only log the error, e.g. when db transaction conflict occurs // this causes the problem that a page might be rendered with data that was not actually committed // workaround: store the exception in this variable and explicitly rethrow before sending page content to output stream public Exception exceptionInHibernateInterceptor = null; public static Environment loadTemplateMap(Class<?> clazz) { return loadTemplateMap(clazz, null, staticEnv); } public static Environment loadTemplateMap(Class<?> clazz, String keyOverwrite, Environment env) { reflectionLoadClassesHelper(clazz, "loadTemplateMap", new Object[] { keyOverwrite, env }); return env; } public static Object[] loadEmailAndTemplateMapArgs = new Object[] { staticEnv, emails }; public static void loadEmailAndTemplateMap(Class<?> clazz) { reflectionLoadClassesHelper(clazz, "loadEmailAndTemplateMap", loadEmailAndTemplateMapArgs); } public static Object[] loadLiftedTemplateMapArgs = new Object[] { staticEnv }; public static void loadLiftedTemplateMap(Class<?> clazz) { reflectionLoadClassesHelper(clazz, "loadLiftedTemplateMap", loadLiftedTemplateMapArgs); } public static Object[] loadRefArgClassesArgs = new Object[] { refargclasses }; public static void loadRefArgClasses(Class<?> clazz) { reflectionLoadClassesHelper(clazz, "loadRefArgClasses", loadRefArgClassesArgs); } public static void reflectionLoadClassesHelper(Class<?> clazz, String method, Object[] args) { for (java.lang.reflect.Method m : clazz.getMethods()) { if (method.equals(m.getName())) { // will just skip if not defined, so the code generator does not need to generate empty methods try { m.invoke(null, args); } catch (IllegalAccessException | IllegalArgumentException | java.lang.reflect.InvocationTargetException e) { e.printStackTrace(); } break; } } } }
package ar.ext.spark.hbin; import java.io.DataInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.mapred.FileSplit; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.InputSplit; import org.apache.hadoop.mapred.RecordReader; import org.apache.hadoop.mapred.FileInputFormat; import ar.util.memoryMapping.MemMapEncoder; import ar.util.memoryMapping.MemMapEncoder.TYPE; public class HBINInputFormat extends FileInputFormat<LongWritable, DataInputRecord> { @Override public RecordReader<LongWritable, DataInputRecord> getRecordReader( InputSplit genericSplit, JobConf conf, Reporter reporter) throws IOException { FileSplit split = (FileSplit) genericSplit; final Path path = split.getPath(); MemMapEncoder.Header header; try (DataInputStream stream = path.getFileSystem(conf).open(path)) { header = MemMapEncoder.Header.from(stream); } long dataOffset = header.dataTableOffset; TYPE[] types = header.types; return new IndexedReader(dataOffset,types, split, conf); } @Override public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { FileStatus fileStatus; MemMapEncoder.Header header; Path path; numSplits = super.getSplits(job, numSplits).length; FileStatus[] statuses = this.listStatus(job); if (statuses.length != 1) {throw new RuntimeException("HBIN input can only be used with single-file jobs.");} fileStatus = statuses[0]; path = fileStatus.getPath(); try (DataInputStream stream = path.getFileSystem(job).open(path)) { header = MemMapEncoder.Header.from(stream); } long fileLength = fileStatus.getLen(); long dataOffset = header.dataTableOffset; TYPE[] types = header.types; long recordLength = MemMapEncoder.recordLength(types); long start = dataOffset; long dataLength = fileLength-start; long records = dataLength/recordLength; long recordsPerSplit = (records/numSplits)+ (records%numSplits == 0 ? 0 : 1);// +1 ensures that if items don't divide up evenly, no extra splits are needed long splitLength = recordsPerSplit*recordLength; List<InputSplit> splits = new ArrayList<InputSplit>(numSplits); for (int i=0; i<numSplits; i++) { long length = (start+splitLength < fileLength) ? splitLength : fileLength-start; splits.add(new FileSplit(path, start, length, (String[]) null)); start = start+length; } return splits.toArray(new InputSplit[splits.size()]); } }
package com.intellij.ant; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.ClassReader; /** * @author yole */ public class AntClassWriter extends ClassWriter { private final ClassLoader myClassLoader; public AntClassWriter(int flags, final ClassLoader classLoader) { super(flags); myClassLoader = classLoader; } public AntClassWriter(ClassReader classReader, int flags, final ClassLoader classLoader) { super(classReader, flags); myClassLoader = classLoader; } protected String getCommonSuperClass(final String type1, final String type2) { Class c; Class d; try { c = myClassLoader.loadClass(type1.replace('/', '.')); d = myClassLoader.loadClass(type2.replace('/', '.')); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage()); } if (c.isAssignableFrom(d)) { return type1; } if (d.isAssignableFrom(c)) { return type2; } if (c.isInterface() || d.isInterface()) { return "java/lang/Object"; } else { do { c = c.getSuperclass(); } while (!c.isAssignableFrom(d)); return c.getName().replace('.', '/'); } } }
package org.myrobotlab.service; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.service.ProgramAB.Response; import org.slf4j.Logger; // GAH! why is this test failing under TravisCI.. ignore for now. // @Ignore public class ProgramABTest { private ProgramAB testService; private String username = "testUser"; private String botname = "lloyd"; private String path = "test/ProgramAB"; public final static Logger log = LoggerFactory.getLogger(ProgramABTest.class); @Before public void setUp() throws Exception { // Load the service under test // a test robot // OOB tags might not know what the service name is ?! testService = new ProgramAB(botname); testService.setPath(path); //testService = new ProgramAB("simple"); // testService.setPath("c:/mrl/develop/ProgramAB"); // start the service. testService.startService(); // load the bot brain for the chat with the user testService.startSession(username, botname); // clean out any aimlif the bot that might // have been saved in a previous test run! String aimlIFPath = path + "/bots/"+botname+"/aimlif"; File aimlIFPathF = new File(aimlIFPath); if (aimlIFPathF.isDirectory()) { for (File f : aimlIFPathF.listFiles()) { // if there's a file here. log.info("Deleting pre-existing AIMLIF files : {}", f.getAbsolutePath()); f.delete(); } } // TODO: same thing for predicates! (or other artifacts from a previous aiml test run) } @Test public void testProgramAB() throws Exception { // a response Response resp = testService.getResponse(username, "UNIT TEST PATTERN"); // System.out.println(resp.msg); assertEquals("Unit Test Pattern Passed", resp.msg); } @Test public void testOOBTags() throws Exception { Response resp = testService.getResponse(username, "OOB TEST"); assertEquals("OOB Tag Test", resp.msg); // Thread.sleep(1000); Assert.assertNotNull(Runtime.getService("python")); } @Test public void testSavePredicates() throws IOException { long uniqueVal = System.currentTimeMillis(); String testValue = String.valueOf(uniqueVal); Response resp = testService.getResponse(username, "SET FOO " + testValue); assertEquals(testValue, resp.msg); testService.savePredicates(); testService.reloadSession(username, botname); resp = testService.getResponse(username, "GET FOO"); assertEquals("FOO IS " + testValue, resp.msg); } @Test public void testPredicates() { // test removing the predicate if it exists testService.setPredicate(username, "name", "foo1"); String name = testService.getPredicate(username, "name"); // validate it's set properly assertEquals("foo1", name); testService.removePredicate(username, "name"); // validate the predicate doesn't exist name = testService.getPredicate(username, "name"); // TODO: is this valid? one would expect it would return null. assertEquals("unknown",name); // set a predicate testService.setPredicate(username, "name", "foo2"); name = testService.getPredicate(username, "name"); // validate it's set properly assertEquals("foo2", name); } @Test public void testLearn() throws IOException { //Response resp1 = testService.getResponse(session, "SET FOO BAR"); //System.out.println(resp1.msg); Response resp = testService.getResponse(username, "LEARN AAA IS BBB"); System.out.println(resp.msg); resp = testService.getResponse(username, "WHAT IS AAA"); assertEquals("BBB", resp.msg); } @Test public void testSets() { Response resp = testService.getResponse(username, "SETTEST CAT"); assertEquals("An Animal.", resp.msg); resp = testService.getResponse(username, "SETTEST MOUSE"); assertEquals("An Animal.", resp.msg); resp = testService.getResponse(username, "SETTEST DOG"); System.out.println(resp.msg); assertEquals("An Animal.", resp.msg); } @Test public void testSetsAndMaps() { Response resp = testService.getResponse(username, "DO YOU LIKE Leah?"); assertEquals("Princess Leia Organa is awesome.", resp.msg); resp = testService.getResponse(username, "DO YOU LIKE Princess Leah?"); assertEquals("Princess Leia Organa is awesome.", resp.msg); } @Test public void testAddEntryToSetAndMaps() { // TODO: This does NOT work yet! Response resp = testService.getResponse(username, "Add Jabba to the starwarsnames set"); assertEquals("Ok...", resp.msg); resp = testService.getResponse(username, "Add jabba equals Jabba the Hut to the starwars map"); assertEquals("Ok...", resp.msg); resp = testService.getResponse(username, "DO YOU LIKE Jabba?"); assertEquals("Jabba the Hut is awesome.", resp.msg); // TODO : re-enable this one? // now test creating a new set. resp = testService.getResponse(username, "Add bourbon to the whiskey set"); assertEquals("Ok...", resp.msg); resp = testService.getResponse(username, "NEWSETTEST bourbon"); // assertEquals("bourbon is a whiskey", resp.msg); } @Test public void testTopicCategories() { // Top level definition Response resp = testService.getResponse(username, "TESTTOPICTEST"); assertEquals("TOPIC IS unknown", resp.msg); resp = testService.getResponse(username, "SET TOPIC TEST"); resp = testService.getResponse(username, "TESTTOPICTEST"); assertEquals("TEST TOPIC RESPONSE", resp.msg); // maybe we can still fallback to non-topic responses. resp = testService.getResponse(username, "HI"); assertEquals("Hello user!", resp.msg); // TODO: how the heck do we unset a predicate from AIML? testService.unsetPredicate(username, "topic"); resp = testService.getResponse(username, "TESTTOPICTEST"); assertEquals("TOPIC IS unknown", resp.msg); } @Test public void umlautTest() { for (String s : testService.listPatterns(botname)) { System.out.println("PATTERN:" + s); } Response resp = testService.getResponse(username, "Lars Ümlaüt"); assertEquals("He's a character from Guitar Hero!", resp.msg); } @After public void tearDown() throws Exception { testService.stopService(); testService.releaseService(); } }
package com.anpmech.mpd; import com.anpmech.mpd.connection.MPDConnection; import com.anpmech.mpd.connection.MPDConnectionMonoSocket; import com.anpmech.mpd.connection.MPDConnectionMultiSocket; import com.anpmech.mpd.exception.MPDException; import com.anpmech.mpd.item.Album; import com.anpmech.mpd.item.AlbumBuilder; import com.anpmech.mpd.item.Artist; import com.anpmech.mpd.item.Directory; import com.anpmech.mpd.item.FilesystemTreeEntry; import com.anpmech.mpd.item.Genre; import com.anpmech.mpd.item.Item; import com.anpmech.mpd.item.Music; import com.anpmech.mpd.item.MusicBuilder; import com.anpmech.mpd.item.PlaylistFile; import com.anpmech.mpd.item.Stream; import com.anpmech.mpd.subsystem.Sticker; import com.anpmech.mpd.subsystem.status.MPDStatisticsMap; import com.anpmech.mpd.subsystem.status.MPDStatusMap; import java.io.IOException; import java.net.InetAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.ListIterator; import static com.anpmech.mpd.Tools.KEY; import static com.anpmech.mpd.Tools.VALUE; /** * MPD Server controller. */ public class MPD { public static final String STREAMS_PLAYLIST = "[Radio Streams]"; private static final String TAG = "MPD"; protected final MPDPlaylist mPlaylist; private final MPDConnection mConnection; private final MPDConnection mIdleConnection; private final MPDStatisticsMap mStatistics; private final MPDStatusMap mStatus; /** * Constructs a new MPD server controller without connection. */ public MPD() { super(); mConnection = new MPDConnectionMultiSocket(5000, 2); mIdleConnection = new MPDConnectionMonoSocket(0); mPlaylist = new MPDPlaylist(mConnection); mStatistics = new MPDStatisticsMap(mConnection); mStatus = new MPDStatusMap(mConnection); } /** * Constructs a new MPD server controller. * * @param server server address or host name * @param port server port * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public MPD(final InetAddress server, final int port, final CharSequence password) throws MPDException, IOException { this(); setDefaultPassword(password); connect(server, port); } /** * Constructs a new MPD server controller. * * @param server server address or host name * @param port server port * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public MPD(final String server, final int port, final CharSequence password) throws IOException, MPDException { this(InetAddress.getByName(server), port, password); } private static String[] getAlbumArtistPair(final Album album) { final Artist artist = album.getArtist(); final String[] artistPair; if (artist == null) { artistPair = new String[]{null, null}; } else { if (album.hasAlbumArtist()) { artistPair = new String[]{Music.TAG_ALBUM_ARTIST, artist.getName()}; } else { artistPair = new String[]{Music.TAG_ARTIST, artist.getName()}; } } return artistPair; } private static MPDCommand getAlbumDetailsCommand(final Album album) { final String[] artistPair = getAlbumArtistPair(album); return MPDCommand.create(MPDCommand.MPD_CMD_COUNT, Music.TAG_ALBUM, album.getName(), artistPair[0], artistPair[1]); } private static MPDCommand getSongsCommand(final Album album) { final String[] artistPair = getAlbumArtistPair(album); return MPDCommand.create(MPDCommand.MPD_CMD_FIND, Music.TAG_ALBUM, album.getName(), artistPair[0], artistPair[1]); } /* * get raw command String for listAlbums */ private static MPDCommand listAlbumsCommand(final String artist, final boolean useAlbumArtist) { String albumArtist = null; if (artist != null) { if (useAlbumArtist) { albumArtist = Music.TAG_ALBUM_ARTIST; } else { albumArtist = Music.TAG_ARTIST; } } return MPDCommand.create(MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ALBUM, albumArtist, artist); } /* * get raw command String for listAllAlbumsGrouped */ private static MPDCommand listAllAlbumsGroupedCommand(final boolean useAlbumArtist) { final String artistTag; if (useAlbumArtist) { artistTag = Music.TAG_ALBUM_ARTIST; } else { artistTag = Music.TAG_ARTIST; } return MPDCommand.create(MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ALBUM, MPDCommand.MPD_CMD_GROUP, artistTag); } private static MPDCommand nextCommand() { return MPDCommand.create(MPDCommand.MPD_CMD_NEXT); } private static MPDCommand skipToPositionCommand(final int position) { return MPDCommand.create(MPDCommand.MPD_CMD_PLAY, Integer.toString(position)); } private static void sort(final List<String> list, final boolean sensitive) { if (sensitive) { Collections.sort(list); } else { Collections.sort(list, String.CASE_INSENSITIVE_ORDER); } } /** * Adds a {@code Album} item object to the playlist queue. * * @param album {@code Album} item object to be added to the media server playlist queue. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void add(final Album album) throws IOException, MPDException { add(album, false, false); } /** * Adds a {@code Album} item object to the playlist queue. * * @param album {@code Album} item object to be added to the media server playlist queue. * @param replace Whether to clear the playlist queue prior to adding the item(s). * @param play Whether to play the playlist queue after adding the item(s). * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void add(final Album album, final boolean replace, final boolean play) throws IOException, MPDException { final CommandQueue commandQueue; if (isCommandAvailable(MPDCommand.MPD_CMD_FIND_ADD)) { final String[] artistPair = getAlbumArtistPair(album); commandQueue = new CommandQueue(); commandQueue .add(MPDCommand.MPD_CMD_FIND_ADD, Music.TAG_ALBUM, album.getName(), artistPair[0], artistPair[1]); } else { final List<Music> songs = getSongs(album); Collections.sort(songs); commandQueue = MPDPlaylist.addAllCommand(songs); } add(commandQueue, replace, play); } /** * Adds a {@code Artist} item object to the playlist queue. * * @param artist {@code Artist} item object to be added to the media server playlist queue. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void add(final Artist artist) throws IOException, MPDException { add(artist, false, false); } /** * Adds a {@code Artist} item object to the playlist queue. * * @param artist {@code Artist} item object to be added to the media server playlist queue. * @param replace Whether to clear the playlist queue prior to adding the item(s). * @param play Whether to play the playlist queue after adding the item(s). * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void add(final Artist artist, final boolean replace, final boolean play) throws IOException, MPDException { final CommandQueue commandQueue; if (isCommandAvailable(MPDCommand.MPD_CMD_FIND_ADD)) { commandQueue = new CommandQueue(); commandQueue .add(MPDCommand.MPD_CMD_FIND_ADD, Music.TAG_ARTIST, artist.getName()); } else { final List<Music> songs = getSongs(artist); Collections.sort(songs); commandQueue = MPDPlaylist.addAllCommand(songs); } add(commandQueue, replace, play); } /** * Add a {@code Music} or {@code Directory} item object to the playlist queue. {@code * PlaylistFile} items are added in it's own method. * * @param music {@code Music} item object to be added to the media server playlist queue. * @param replace Whether to clear the playlist queue prior to adding the item(s). * @param play Whether to play the playlist queue after adding the item(s). * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void add(final FilesystemTreeEntry music, final boolean replace, final boolean play) throws IOException, MPDException { if (music instanceof PlaylistFile) { add((PlaylistFile) music, replace, play); } else { final CommandQueue commandQueue = new CommandQueue(); commandQueue.add(MPDPlaylist.addCommand(music.getFullPath())); add(commandQueue, replace, play); } } /** * Add a {@code Music} item object to the playlist queue. * * @param music {@code Music} item object to be added to the playlist queue. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void add(final FilesystemTreeEntry music) throws IOException, MPDException { add(music, false, false); } public void add(final Genre genre, final boolean replace, final boolean play) throws IOException, MPDException { final CommandQueue commandQueue; if (isCommandAvailable(MPDCommand.MPD_CMD_FIND_ADD)) { commandQueue = new CommandQueue(); commandQueue .add(MPDCommand.MPD_CMD_FIND_ADD, Music.TAG_GENRE, genre.getName()); } else { final List<Music> music = find(Music.TAG_GENRE, genre.getName()); Collections.sort(music); commandQueue = MPDPlaylist.addAllCommand(music); } add(commandQueue, replace, play); } /** * Adds songs to the queue. Optionally, clears the queue prior to the addition. Optionally, * play the added songs afterward. * * @param commandQueue The commandQueue that will be responsible of inserting the songs into * the queue. * @param replace If true, replaces the entire playlist queue with the added files. * @param playAfterAdd If true, starts playing once added. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ private void add(final CommandQueue commandQueue, final boolean replace, final boolean playAfterAdd) throws IOException, MPDException { int playPos = 0; final boolean isPlaying = mStatus.isState(MPDStatusMap.STATE_PLAYING); final boolean isConsume = mStatus.isConsume(); final boolean isRandom = mStatus.isRandom(); final int playlistLength = mStatus.getPlaylistLength(); /** Replace */ if (replace) { if (isPlaying) { if (playlistLength > 1) { try { commandQueue.addAll(0, MPDPlaylist.cropCommand(this)); } catch (final IllegalStateException ignored) { /** Shouldn't occur, we already checked for playing. */ } } } else { commandQueue.add(0, MPDPlaylist.clearCommand()); } } else if (playAfterAdd && !isRandom) { /** Since we didn't clear the playlist queue, we need to play the (current queue+1) */ playPos = mPlaylist.size(); } if (replace) { if (isPlaying) { commandQueue.add(nextCommand()); } else if (playAfterAdd) { commandQueue.add(skipToPositionCommand(playPos)); } } else if (playAfterAdd) { commandQueue.add(skipToPositionCommand(playPos)); } /** Finally, clean up the last playing song. */ if (replace && isPlaying && !isConsume) { commandQueue.add(MPDPlaylist.MPD_CMD_PLAYLIST_REMOVE, "0"); } /** * It's rare, but possible to make it through the add() * methods without adding to the command queue. */ if (!commandQueue.isEmpty()) { mConnection.send(commandQueue); } } /** * Add a {@code Playlist} item object to the playlist queue. * * @param databasePlaylist A playlist item stored on the media server to add to the playlist * queue. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void add(final PlaylistFile databasePlaylist) throws IOException, MPDException { add(databasePlaylist, false, false); } /** * Add a {@code Playlist} item object to the playlist queue. * * @param databasePlaylist A playlist item stored on the media server to add to the playlist * queue. * @param replace Whether to clear the playlist queue prior to adding the * databasePlaylist string. * @param play Whether to play the playlist queue prior after adding the * databasePlaylist string. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void add(final PlaylistFile databasePlaylist, final boolean replace, final boolean play) throws IOException, MPDException { final CommandQueue commandQueue = new CommandQueue(); commandQueue.add(MPDPlaylist.loadCommand(databasePlaylist.getName())); add(commandQueue, replace, play); } protected void addAlbumDetails(final List<Album> albums) throws IOException, MPDException { final CommandQueue commandQueue = new CommandQueue(albums.size()); for (final Album album : albums) { commandQueue.add(getAlbumDetailsCommand(album)); } final List<List<String>> response = mConnection.sendSeparated(commandQueue); if (response.size() == albums.size()) { final AlbumBuilder albumBuilder = new AlbumBuilder(); for (int i = 0; i < response.size(); i++) { final List<String> list = response.get(i); final Album album = albums.get(i); long duration = 0L; long songCount = 0L; albumBuilder.setAlbum(albums.get(i)); /** First, extract the album specifics from the response. */ for (final String[] pair : Tools.splitResponse(list)) { if ("songs".equals(pair[KEY])) { songCount = Long.parseLong(pair[VALUE]); } else if ("playtime".equals(pair[KEY])) { duration = Long.parseLong(pair[VALUE]); } } albumBuilder.setAlbumDetails(songCount, duration); /** Then extract the date and path from a song of the album. */ final List<Music> songs = getFirstTrack(album); if (!songs.isEmpty()) { albumBuilder.setSongDetails(songs.get(0).getDate(), songs.get(0).getParentDirectory()); } albums.set(i, albumBuilder.build()); } } } protected void addAlbumSongDetails(final List<Album> albums) throws IOException, MPDException { if (!albums.isEmpty()) { final ListIterator<Album> iterator = albums.listIterator(); final AlbumBuilder albumBuilder = new AlbumBuilder(); while (iterator.hasNext()) { final Album album = iterator.next(); final List<Music> songs = getFirstTrack(album); if (!songs.isEmpty()) { albumBuilder.setAlbum(album); albumBuilder.setSongDetails(songs.get(0).getDate(), songs.get(0).getParentDirectory()); iterator.set(albumBuilder.build()); } } } } /** TODO: This needs to be an add(Stream, ...) method. */ public void addStream(final String stream, final boolean replace, final boolean play) throws IOException, MPDException { final CommandQueue commandQueue = new CommandQueue(); commandQueue.add(MPDPlaylist.addCommand(stream)); add(commandQueue, replace, play); } @SuppressWarnings("TypeMayBeWeakened") public void addToPlaylist(final PlaylistFile playlist, final Album album) throws IOException, MPDException { if (mIdleConnection.isCommandAvailable(MPDCommand.MPD_CMD_SEARCH_ADD_PLAYLIST)) { final String[] artistPair = getAlbumArtistPair(album); mConnection.send(MPDCommand.MPD_CMD_SEARCH_ADD_PLAYLIST, playlist.getFullPath(), Music.TAG_ALBUM, album.getName(), artistPair[0], artistPair[1]); } else { final List<Music> songs = getSongs(album); Collections.sort(songs); addToPlaylist(playlist, songs); } } @SuppressWarnings("TypeMayBeWeakened") public void addToPlaylist(final PlaylistFile playlist, final Artist artist) throws IOException, MPDException { if (mIdleConnection.isCommandAvailable(MPDCommand.MPD_CMD_SEARCH_ADD_PLAYLIST)) { mConnection.send(MPDCommand.MPD_CMD_SEARCH_ADD_PLAYLIST, playlist.getFullPath(), Music.TAG_ARTIST, artist.getName()); } else { final List<Music> songs = getSongs(artist); Collections.sort(songs); addToPlaylist(playlist, songs); } } @SuppressWarnings("TypeMayBeWeakened") public void addToPlaylist(final PlaylistFile playlist, final Collection<Music> musicCollection) throws IOException, MPDException { if (!musicCollection.isEmpty()) { final CommandQueue commandQueue = new CommandQueue(); for (final Music music : musicCollection) { commandQueue .add(MPDCommand.MPD_CMD_PLAYLIST_ADD, playlist.getFullPath(), music.getFullPath()); } mConnection.send(commandQueue); } } @SuppressWarnings("TypeMayBeWeakened") public void addToPlaylist(final PlaylistFile playlist, final FilesystemTreeEntry entry) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_PLAYLIST_ADD, playlist.getFullPath(), entry.getFullPath()); } public void addToPlaylist(final PlaylistFile playlist, final Genre genre) throws IOException, MPDException { if (mIdleConnection.isCommandAvailable(MPDCommand.MPD_CMD_SEARCH_ADD_PLAYLIST)) { mConnection.send(MPDCommand.MPD_CMD_SEARCH_ADD_PLAYLIST, playlist.getFullPath(), Music.TAG_GENRE, genre.getName()); } else { final List<Music> music = find(Music.TAG_GENRE, genre.getName()); Collections.sort(music); addToPlaylist(playlist, music); } } public void addToPlaylist(final PlaylistFile playlist, final Music music) throws IOException, MPDException { addToPlaylist(playlist, Collections.singletonList(music)); } /** * Increases or decreases volume by {@code modifier} amount. * * @param modifier volume adjustment * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void adjustVolume(final int modifier) throws IOException, MPDException { // calculate final volume (clip value with [0, 100]) int vol = mStatus.getVolume() + modifier; vol = Math.max(MPDStatusMap.VOLUME_MIN, Math.min(MPDStatusMap.VOLUME_MAX, vol)); mConnection.send(MPDCommand.MPD_CMD_SET_VOLUME, Integer.toString(vol)); } /** * Clears error message. * * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void clearError() throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_CLEARERROR); } /** * Connects to the default MPD server. * <p/> * If there is a default password that is not included in the {@code MPD_HOST} environment * variable, {@link #setDefaultPassword(CharSequence)} must be called prior to this method. * * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public synchronized void connect() throws IOException, MPDException { mConnection.connect(); mIdleConnection.connect(); } /** * Connects to a MPD server. * <p/> * If there is a default password, {@link #setDefaultPassword(CharSequence)} must be called * prior to this method. * * @param server server address or host name * @param port server port * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public final synchronized void connect(final InetAddress server, final int port) throws IOException, MPDException { if (!isConnected()) { mConnection.connect(server, port); mIdleConnection.connect(server, port); } } /** * Connects to a MPD server. * <p/> * If there is a default password, {@link #setDefaultPassword(CharSequence)} must be called * prior to this method. * * @param server server address or host name * @param port server port * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public final void connect(final String server, final int port) throws IOException, MPDException { final InetAddress address = InetAddress.getByName(server); connect(address, port); } /** * Connects to a MPD server. * <p/> * If there is a default password, {@link #setDefaultPassword(CharSequence)} must be called * prior to this method. * * @param server server address or host name and port (server:port) * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public final void connect(final String server) throws IOException, MPDException { int port = MPDCommand.DEFAULT_MPD_PORT; final String host; if (server.indexOf(':') == -1) { host = server; } else { host = server.substring(0, server.lastIndexOf(':')); port = Integer.parseInt(server.substring(server.lastIndexOf(':') + 1)); } connect(host, port); } public void disableOutput(final int id) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_OUTPUTDISABLE, Integer.toString(id)); } /** * Disconnects from server. * * @throws IOException if an error occur while closing connection */ public synchronized void disconnect() throws IOException { IOException ex = null; if (mConnection != null && mConnection.isConnected()) { try { mConnection.disconnect(); } catch (final IOException e) { ex = (ex != null) ? ex : e;// Always keep first non null // exception } } if (mIdleConnection != null && mIdleConnection.isConnected()) { try { mIdleConnection.disconnect(); } catch (final IOException e) { ex = (ex != null) ? ex : e;// Always keep non null first // exception } } } public void editSavedStream(final String url, final String name, final Integer pos) throws IOException, MPDException { removeSavedStream(pos); saveStream(url, name); } public void enableOutput(final int id) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_OUTPUTENABLE, Integer.toString(id)); } /** * Similar to {@code search},{@code find} looks for exact matches in the MPD database. * * @param type type of search. Should be one of the following constants: * MPD_FIND_ARTIST, MPD_FIND_ALBUM * @param locatorString case-insensitive locator locatorString. Anything that exactly matches * {@code locatorString} will be returned in the results. * @return a Collection of {@code Music} * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. * @see com.anpmech.mpd.item.Music */ public List<Music> find(final String type, final String locatorString) throws IOException, MPDException { return genericSearch(MPDCommand.MPD_CMD_FIND, type, locatorString); } public List<Music> find(final String[] args) throws IOException, MPDException { return genericSearch(MPDCommand.MPD_CMD_FIND, args); } /* * For all given albums, look for album artists and create as many albums as * there are album artists, including "" The server call can be slow for long * album lists */ protected void fixAlbumArtists(final List<Album> albums) throws IOException, MPDException { if (!albums.isEmpty()) { final List<List<String>> albumArtists = listAlbumArtists(albums); if (albumArtists.size() == albums.size()) { /** Split albums are rare, let it allocate as needed. */ @SuppressWarnings("CollectionWithoutInitialCapacity") final Collection<Album> splitAlbums = new ArrayList<>(); final AlbumBuilder albumBuilder = new AlbumBuilder(); int i = 0; for (final Album album : albums) { final List<String> aartists = albumArtists.get(i); final int aartistsSize = aartists.size(); String firstArtist; if (aartistsSize > 0) { albumBuilder.setAlbum(album); Collections.sort(aartists); // make sure "" is the first one firstArtist = aartists.get(0); if (!firstArtist.isEmpty()) { // album albumBuilder.setAlbumArtist(firstArtist); albums.set(i, albumBuilder.build(false)); } // do nothing if albumartist is "" if (aartists.size() > 1) { // it's more than one album, insert final ListIterator<String> iterator = aartists.listIterator(1); while (iterator.hasNext()) { albumBuilder.setAlbumArtist(iterator.next()); splitAlbums.add(albumBuilder.build(false)); } } } i++; } albums.addAll(splitAlbums); } } } protected List<Music> genericSearch(final CharSequence searchCommand, final String... args) throws IOException, MPDException { return MusicBuilder.buildMusicFromList(mConnection.send(searchCommand, args)); } protected List<Music> genericSearch(final CharSequence searchCommand, final String type, final String strToFind) throws IOException, MPDException { final List<String> response = mConnection.send(searchCommand, type, strToFind); return MusicBuilder.buildMusicFromList(response); } public int getAlbumCount(final Artist artist, final boolean useAlbumArtistTag) throws IOException, MPDException { return listAlbums(artist, useAlbumArtistTag).size(); } public List<Album> getAlbums(final Artist artist, final boolean sortByYear, final boolean trackCountNeeded) throws IOException, MPDException { final List<Album> albums = getAlbums(artist, sortByYear, trackCountNeeded, false); // 1. the null artist list already contains all albums // 2. the "unknown artist" should not list unknown album artists if (artist != null && !artist.isUnknown()) { Item.merge(albums, getAlbums(artist, sortByYear, trackCountNeeded, true)); } return albums; } public List<Album> getAlbums(final Artist artist, final boolean sortByYear, final boolean trackCountNeeded, final boolean useAlbumArtist) throws IOException, MPDException { final List<Album> albums; if (artist == null) { albums = getAllAlbums(); } else { final List<String> albumNames = listAlbums(artist, useAlbumArtist); albums = new ArrayList<>(albumNames.size()); Collections.sort(albumNames, String.CASE_INSENSITIVE_ORDER); if (!albumNames.isEmpty()) { final AlbumBuilder albumBuilder = new AlbumBuilder(); for (final String album : albumNames) { albumBuilder.setBase(album, artist, useAlbumArtist); albums.add(albumBuilder.build()); } if (!useAlbumArtist) { fixAlbumArtists(albums); } // after fixing album artists if (trackCountNeeded || sortByYear) { addAlbumDetails(albums); } if (!sortByYear) { addAlbumSongDetails(albums); } } } return albums; } /** * Get all albums (if there is no artist specified for filtering) * * @return A list of all albums on the connected media server. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<Album> getAllAlbums() throws IOException, MPDException { final List<Album> albums; // Use MPD 0.19's album grouping feature if available. if (mConnection.isProtocolVersionSupported(0, 19)) { albums = listAllAlbumsGrouped(false); } else { final List<String> albumNames = listAlbums(); Collections.sort(albumNames, String.CASE_INSENSITIVE_ORDER); if (albumNames.isEmpty()) { albums = Collections.emptyList(); } else { final AlbumBuilder albumBuilder = new AlbumBuilder(); albums = new ArrayList<>(albumNames.size()); for (final String album : albumNames) { albumBuilder.setName(album); albums.add(albumBuilder.build()); } } } return albums; } public List<Artist> getArtists() throws IOException, MPDException { final List<Artist> artists = getArtists(true); Item.merge(artists, getArtists(false)); return artists; } public List<Artist> getArtists(final boolean useAlbumArtist) throws IOException, MPDException { final List<String> artistNames; final List<Artist> artists; if (useAlbumArtist) { artistNames = listAlbumArtists(); Collections.sort(artistNames, String.CASE_INSENSITIVE_ORDER); } else { artistNames = listArtists(true); } artists = new ArrayList<>(artistNames.size()); if (!artistNames.isEmpty()) { for (final String artist : artistNames) { artists.add(new Artist(artist)); } } return artists; } public List<Artist> getArtists(final Genre genre) throws IOException, MPDException { final List<Artist> artists = getArtists(genre, true); Item.merge(artists, getArtists(genre, false)); return artists; } public List<Artist> getArtists(final Genre genre, final boolean useAlbumArtist) throws IOException, MPDException { final List<String> artistNames; final List<Artist> artists; if (useAlbumArtist) { artistNames = listAlbumArtists(genre); } else { artistNames = listArtists(genre, true); } artists = new ArrayList<>(artistNames.size()); if (!artistNames.isEmpty()) { for (final String artist : artistNames) { artists.add(new Artist(artist)); } } return artists; } protected List<Music> getFirstTrack(final Album album) throws IOException, MPDException { final Artist artist = album.getArtist(); final String[] args = new String[6]; if (artist == null) { args[0] = ""; args[1] = ""; } else if (album.hasAlbumArtist()) { args[0] = Music.TAG_ALBUM_ARTIST; } else { args[0] = Music.TAG_ARTIST; } if (artist != null) { args[1] = artist.getName(); } args[2] = Music.TAG_ALBUM; args[3] = album.getName(); args[4] = Music.TAG_TRACK; args[5] = "1"; List<Music> songs = find(args); if (songs.isEmpty()) { args[5] = "01"; songs = find(args); } if (songs.isEmpty()) { args[5] = "1"; songs = search(args); } if (songs.isEmpty()) { final String[] args2 = Arrays.copyOf(args, 4); // find all tracks songs = find(args2); } return songs; } public List<Genre> getGenres() throws IOException, MPDException { final List<String> genreNames = listGenres(); final List<Genre> genres; if (genreNames.isEmpty()) { genres = Collections.emptyList(); } else { genres = new ArrayList<>(genreNames.size()); for (final String genre : genreNames) { genres.add(new Genre(genre)); } } return genres; } public InetAddress getHostAddress() { return mConnection.getHostAddress(); } public int getHostPort() { return mConnection.getHostPort(); } public MPDConnection getIdleConnection() { return mIdleConnection; } /** * Returns MPD server version. * * @return MPD Server version. */ public String getMpdVersion() { final int[] version = mIdleConnection.getMPDVersion(); final StringBuilder sb = new StringBuilder(version.length); for (int i = 0; i < version.length; i++) { sb.append(version[i]); if (i < version.length - 1) { sb.append('.'); } } return sb.toString(); } /** * Returns the available outputs * * @return List of available outputs * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public Collection<MPDOutput> getOutputs() throws IOException, MPDException { final List<String> response = mConnection.send(MPDCommand.MPD_CMD_OUTPUTS); return MPDOutput.buildOutputsFromList(response); } /** * Retrieves {@code playlist}. * * @return playlist. */ public MPDPlaylist getPlaylist() { return mPlaylist; } @SuppressWarnings("TypeMayBeWeakened") public List<Music> getPlaylistSongs(final PlaylistFile playlist) throws IOException, MPDException { final String[] args = new String[1]; args[0] = playlist.getFullPath(); return genericSearch(MPDCommand.MPD_CMD_PLAYLIST_INFO, args); } /** * Returns a list of all available playlists * * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<PlaylistFile> getPlaylists() throws IOException, MPDException { final List<String> response = mConnection.send(MPDCommand.MPD_CMD_LISTPLAYLISTS); final List<PlaylistFile> result = new ArrayList<>(response.size()); for (final String[] pair : Tools.splitResponse(response)) { if ("playlist".equals(pair[KEY])) { if (null != pair[VALUE] && !STREAMS_PLAYLIST.equals(pair[VALUE])) { result.add(new PlaylistFile(pair[VALUE])); } } } return result; } public List<Music> getSavedStreams() throws IOException, MPDException { final List<String> response = mConnection.send(MPDCommand.MPD_CMD_LISTPLAYLISTS); List<Music> savedStreams = Collections.emptyList(); for (final String[] pair : Tools.splitResponse(response)) { if ("playlist".equals(pair[KEY])) { if (STREAMS_PLAYLIST.equals(pair[VALUE])) { final String[] args = {pair[VALUE]}; savedStreams = genericSearch(MPDCommand.MPD_CMD_PLAYLIST_INFO, args); break; } } } return savedStreams; } public List<Music> getSongs(final Album album) throws IOException, MPDException { final List<Music> songs = MusicBuilder .buildMusicFromList(mConnection.send(getSongsCommand(album))); if (album.hasAlbumArtist()) { // remove songs that don't have this album artist (mpd >=0.18 puts them in) final Artist artist = album.getArtist(); String artistName = null; if (artist != null) { artistName = artist.getName(); } for (int i = songs.size() - 1; i >= 0; i final String albumArtist = songs.get(i).getAlbumArtistName(); if (albumArtist != null && !albumArtist.isEmpty() && !albumArtist.equals(artistName)) { songs.remove(i); } } } return songs; } public List<Music> getSongs(final Artist artist) throws IOException, MPDException { final List<Album> albums = getAlbums(artist, false, false); final List<Music> songs = new ArrayList<>(albums.size()); for (final Album album : albums) { songs.addAll(getSongs(album)); } return songs; } /** * Retrieves the current statistics for the connected server. * * @return statistics for the connected server. */ public MPDStatisticsMap getStatistics() { return mStatistics; } /** * Retrieves status of the connected server. * * @return status of the connected server. */ public MPDStatusMap getStatus() { return mStatus; } public Sticker getStickerManager() { return new Sticker(mConnection); } /* * test whether given album is in given genre */ public boolean isAlbumInGenre(final Album album, final Genre genre) throws IOException, MPDException { final List<String> response; final Artist artist = album.getArtist(); String artistName = null; String artistType = null; if (artist != null) { artistName = artist.getName(); if (album.hasAlbumArtist()) { artistType = Music.TAG_ALBUM_ARTIST; } else { artistType = Music.TAG_ARTIST; } } response = mConnection.send(MPDCommand.create( MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ALBUM, Music.TAG_ALBUM, album.getName(), artistType, artistName, Music.TAG_GENRE, genre.getName())); return !response.isEmpty(); } /** * Checks for command validity against a list of available commands generated on connection. * * @param command A MPD protocol command. * @return True if the {@code command} is available for use, false otherwise. */ public boolean isCommandAvailable(final String command) { return mConnection.isCommandAvailable(command); } /** * Returns true when connected and false when not connected. * * @return true when connected and false when not connected */ public boolean isConnected() { return mIdleConnection.isConnected(); } /** * List all album artist names from database. * * @return album artist names from database. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<String> listAlbumArtists() throws IOException, MPDException { final List<String> response = mConnection.send(MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ALBUM_ARTIST); Tools.parseResponse(response, Music.RESPONSE_ALBUM_ARTIST); return response; } /** * List all album artist names from database. * * @return album artist names from database. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<String> listAlbumArtists(final Genre genre) throws IOException, MPDException { final List<String> response = mConnection.send( MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ALBUM_ARTIST, Music.TAG_GENRE, genre.getName()); Tools.parseResponse(response, Music.RESPONSE_ALBUM_ARTIST); return response; } public List<List<String>> listAlbumArtists(final List<Album> albums) throws IOException, MPDException { final CommandQueue commandQueue = new CommandQueue(albums.size()); final List<List<String>> responses; for (final Album album : albums) { final Artist artist = album.getArtist(); String artistCommand = null; String artistName = null; if (artist != null) { artistCommand = Music.TAG_ARTIST; artistName = artist.getName(); } commandQueue.add(MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ALBUM_ARTIST, artistCommand, artistName, Music.TAG_ALBUM, album.getName()); } responses = mConnection.sendSeparated(commandQueue); if (responses.size() == albums.size()) { final ListIterator<List<String>> iterator = responses.listIterator(); while (iterator.hasNext()) { final List<String> response = iterator.next(); Tools.parseResponse(response, Music.RESPONSE_ALBUM_ARTIST); iterator.set(response); } } else { Log.warning(TAG, "Response and album size differ when listing album artists."); } return responses; } /** * List all albums from database. * * @return {@code Collection} with all album names from database. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<String> listAlbums() throws IOException, MPDException { return listAlbums(null, false); } /** * List all albums from a given artist. * * @param artist artist to list albums * @param useAlbumArtist use AlbumArtist instead of Artist * @return {@code Collection} with all album names from the given artist present in database. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<String> listAlbums(final Artist artist, final boolean useAlbumArtist) throws IOException, MPDException { final MPDCommand command; if (artist == null) { command = listAlbumsCommand(null, useAlbumArtist); } else { command = listAlbumsCommand(artist.getName(), useAlbumArtist); } final List<String> response = mConnection.send(command); Tools.parseResponse(response, Music.RESPONSE_ALBUM); return response; } /** * List all albums grouped by Artist/AlbumArtist This method queries both Artist/AlbumArtist * and tries to detect if the artist is an artist or an album artist. Only the AlbumArtist * query will be displayed so that the list is not cluttered. * * @param includeUnknownAlbum include an entry for albums with no artists * @return {@code Collection} with all albums present in database, with their artist. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<Album> listAllAlbumsGrouped(final boolean includeUnknownAlbum) throws IOException, MPDException { final List<Album> artistAlbums = listAllAlbumsGrouped(false, includeUnknownAlbum); final List<Album> albumArtistAlbums = listAllAlbumsGrouped(true, includeUnknownAlbum); Collections.sort(artistAlbums); Collections.sort(albumArtistAlbums); for (final Album artistAlbum : artistAlbums) { final ListIterator<Album> iterator = albumArtistAlbums.listIterator(); while (iterator.hasNext()) { final Album albumArtistAlbum = iterator.next(); if (artistAlbum.getArtist() != null && artistAlbum.doesNameExist(albumArtistAlbum)) { iterator.set(artistAlbum); } } } return albumArtistAlbums; } /** * List all albums grouped by Artist/AlbumArtist * * @param useAlbumArtist use AlbumArtist instead of Artist * @param includeUnknownAlbum include an entry for albums with no artists * @return {@code Collection} with all albums present in database, with their artist. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<Album> listAllAlbumsGrouped(final boolean useAlbumArtist, final boolean includeUnknownAlbum) throws IOException, MPDException { final AlbumBuilder albumBuilder = new AlbumBuilder(); final String albumResponse = Music.RESPONSE_ALBUM; final String artistResponse; final List<String> response = mConnection.send(listAllAlbumsGroupedCommand(useAlbumArtist)); final List<Album> result = new ArrayList<>(response.size() / 2); String currentAlbum = null; if (useAlbumArtist) { artistResponse = Music.RESPONSE_ALBUM_ARTIST; } else { artistResponse = Music.RESPONSE_ARTIST; } for (final String[] pair : Tools.splitResponse(response)) { if (artistResponse.equals(pair[KEY])) { if (currentAlbum != null) { albumBuilder.setBase(currentAlbum, pair[VALUE], useAlbumArtist); result.add(albumBuilder.build()); currentAlbum = null; } } else if (albumResponse.equals(pair[KEY])) { if (currentAlbum != null) { albumBuilder.setName(currentAlbum); /** There was no artist in this response, add the album alone */ result.add(albumBuilder.build()); } if (!pair[VALUE].isEmpty() || includeUnknownAlbum) { currentAlbum = pair[VALUE]; } else { currentAlbum = null; } } } return result; } /** * Returns a sorted listallinfo command from the media server. Use of this command is highly * discouraged, as it can retrieve so much information the server max_output_buffer_size may be * exceeded, which will, in turn, truncate the output to this method. * * @return List of all available music information. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<Music> listAllInfo() throws IOException, MPDException { final List<String> allInfo = mConnection.send(MPDCommand.MPD_CMD_LISTALLINFO); return MusicBuilder.buildMusicFromList(allInfo); } /** * List all artist names from database. * * @return artist names from database. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<String> listArtists() throws IOException, MPDException { return listArtists(true); } /** * List all artist names from database. * * @param sortInsensitive boolean for insensitive sort when true * @return artist names from database. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<String> listArtists(final boolean sortInsensitive) throws IOException, MPDException { final List<String> response = mConnection.send(MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ARTIST); Tools.parseResponse(response, Music.RESPONSE_ARTIST); sort(response, sortInsensitive); return response; } /** * List all album artist or artist names of all given albums from database. * * @return list of array of artist names for each album. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<List<String>> listArtists(final List<Album> albums, final boolean useAlbumArtist) throws IOException, MPDException { final List<List<String>> responses = listArtistsCommand(albums, useAlbumArtist); final List<List<String>> result = new ArrayList<>(responses.size()); final int artistLength; List<String> albumResult = Collections.emptyList(); if (useAlbumArtist) { artistLength = Music.RESPONSE_ALBUM_ARTIST.length() + 2; } else { artistLength = Music.RESPONSE_ARTIST.length() + 2; } for (final List<String> response : responses) { albumResult.clear(); for (final String album : response) { final String name = album.substring(artistLength); /** Give the array list an approximate size. */ albumResult = new ArrayList<>(album.length() * response.size()); albumResult.add(name); } result.add(albumResult); } return result; } /** * List all artist names from database. * * @param sortInsensitive boolean for insensitive sort when true * @return artist names from database. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<String> listArtists(final Genre genre, final boolean sortInsensitive) throws IOException, MPDException { final List<String> response = mConnection.send(MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ARTIST, Music.TAG_GENRE, genre.getName()); Tools.parseResponse(response, Music.RESPONSE_ARTIST); return response; } private List<List<String>> listArtistsCommand(final Iterable<Album> albums, final boolean useAlbumArtist) throws IOException, MPDException { final CommandQueue commandQueue = new CommandQueue(); for (final Album album : albums) { final Artist artist = album.getArtist(); // When adding album artist to existing artist check that the artist matches if (useAlbumArtist && artist != null && !artist.isUnknown()) { commandQueue.add(MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_ALBUM_ARTIST, Music.TAG_ALBUM, album.getName(), Music.TAG_ARTIST, artist.getName()); } else { final String artistCommand; if (useAlbumArtist) { artistCommand = Music.TAG_ALBUM_ARTIST; } else { artistCommand = Music.TAG_ARTIST; } commandQueue.add(MPDCommand.MPD_CMD_LIST_TAG, artistCommand, Music.TAG_ALBUM, album.getName()); } } return mConnection.sendSeparated(commandQueue); } /** * List all genre names from database. * * @return artist names from database. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<String> listGenres() throws IOException, MPDException { return listGenres(true); } /** * List all genre names from database. * * @param sortInsensitive boolean for insensitive sort when true * @return artist names from database. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public List<String> listGenres(final boolean sortInsensitive) throws IOException, MPDException { final List<String> response = mConnection.send(MPDCommand.MPD_CMD_LIST_TAG, Music.TAG_GENRE); Tools.parseResponse(response, Music.RESPONSE_GENRE); sort(response, sortInsensitive); return response; } @SuppressWarnings("TypeMayBeWeakened") public void movePlaylistSong(final PlaylistFile playlist, final int from, final int to) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_PLAYLIST_MOVE, playlist.getFullPath(), Integer.toString(from), Integer.toString(to)); } /** * Jumps to next playlist track. * * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void next() throws IOException, MPDException { mConnection.send(nextCommand()); } /** * Pauses/Resumes music playing. * * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void pause() throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_PAUSE); } /** * Starts playing music. * * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void play() throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_PLAY); } /** * Plays previous playlist music. * * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void previous() throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_PREV); } /** * Tells server to refresh database. * * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void refreshDatabase() throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_REFRESH); } /** * Tells server to refresh database. * * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void refreshDatabase(final String folder) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_REFRESH, folder); } public void refreshDirectory(final Directory directory) throws IOException, MPDException { directory.refresh(mConnection); } /** * Removes a list of tracks from a playlist file, by position. * * @param playlist The playlist file to remove tracks from. * @param positions The positions of the tracks to remove from the playlist file. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ @SuppressWarnings("TypeMayBeWeakened") public void removeFromPlaylist(final PlaylistFile playlist, final List<Integer> positions) throws IOException, MPDException { Collections.sort(positions, Collections.reverseOrder()); final CommandQueue commandQueue = new CommandQueue(positions.size()); for (final Integer position : positions) { commandQueue.add(MPDCommand.MPD_CMD_PLAYLIST_DEL, playlist.getFullPath(), position.toString()); } mConnection.send(commandQueue); } @SuppressWarnings("TypeMayBeWeakened") public void removeFromPlaylist(final PlaylistFile playlist, final Integer pos) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_PLAYLIST_DEL, playlist.getFullPath(), Integer.toString(pos)); } public void removeSavedStream(final Integer pos) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_PLAYLIST_DEL, STREAMS_PLAYLIST, Integer.toString(pos)); } public void saveStream(final String url, final String name) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_PLAYLIST_ADD, STREAMS_PLAYLIST, Stream.addStreamName(url, name)); } /** * Similar to {@code find},{@code search} looks for partial matches in the MPD database. * * @param type type of search. Should be one of the following constants: * MPD_SEARCH_ARTIST, MPD_SEARCH_TITLE, MPD_SEARCH_ALBUM, * MPD_SEARCH_FILENAME * @param locatorString case-insensitive locator locatorString. Anything that contains {@code * locatorString} will be returned in the results. * @return a Collection of {@code Music}. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. * @see com.anpmech.mpd.item.Music */ public List<Music> search(final String type, final String locatorString) throws IOException, MPDException { return genericSearch(MPDCommand.MPD_CMD_SEARCH, type, locatorString); } public List<Music> search(final String... args) throws IOException, MPDException { return genericSearch(MPDCommand.MPD_CMD_SEARCH, args); } /** * Seeks current music to the position. * * @param position song position in seconds * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void seek(final long position) throws IOException, MPDException { seekById(mStatus.getSongId(), position); } /** * Seeks music to the position. * * @param songId music id in playlist. * @param position song position in seconds. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void seekById(final int songId, final long position) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_SEEK_ID, Integer.toString(songId), Long.toString(position)); } /** * Seeks music to the position. * * @param index music position in playlist. * @param position song position in seconds. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void seekByIndex(final int index, final long position) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_SEEK, Integer.toString(index), Long.toString(position)); } /** * Enabled or disable consuming. * * @param consume if true song consuming will be enabled, if false song consuming will be * disabled. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void setConsume(final boolean consume) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_CONSUME, MPDCommand.booleanValue(consume)); } /** * Sets cross-fade. * * @param time cross-fade time in seconds. 0 to disable cross-fade. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void setCrossFade(final int time) throws IOException, MPDException { mConnection .send(MPDCommand.MPD_CMD_CROSSFADE, Integer.toString(Math.max(0, time))); } /** * This sets the default password for the MPD server. * * @param password The default password for this MPD server. */ public final void setDefaultPassword(final CharSequence password) { mConnection.setDefaultPassword(password); mIdleConnection.setDefaultPassword(password); } /** * Enabled or disable random. * * @param random if true random will be enabled, if false random will be disabled. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void setRandom(final boolean random) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_RANDOM, MPDCommand.booleanValue(random)); } /** * Enabled or disable repeating. * * @param repeat if true repeating will be enabled, if false repeating will be disabled. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void setRepeat(final boolean repeat) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_REPEAT, MPDCommand.booleanValue(repeat)); } /** * Enabled or disable single mode. * * @param single if true single mode will be enabled, if false single mode will be disabled. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void setSingle(final boolean single) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_SINGLE, MPDCommand.booleanValue(single)); } /** * Sets volume to {@code volume}. * * @param volume new volume value, must be in 0-100 range. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void setVolume(final int volume) throws IOException, MPDException { final int vol = Math.max(MPDStatusMap.VOLUME_MIN, Math.min(MPDStatusMap.VOLUME_MAX, volume)); mConnection.send(MPDCommand.MPD_CMD_SET_VOLUME, Integer.toString(vol)); } /** * Kills server. * * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void shutdown() throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_KILL); } /** * This method returns a thread which will shut down all running threads. This should be added * to the client's shutdown hooks, if applicable. * * @return A thread containing all executors to shutdown. */ public Thread shutdownExecutors() { return new Thread(new Runnable() { @Override public void run() { mConnection.shutdown().run(); mIdleConnection.shutdown().run(); } }); } /** * Skip to song with specified {@code id}. * * @param id song id. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void skipToId(final int id) throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_PLAY_ID, Integer.toString(id)); } /** * Jumps to track {@code position} from playlist. * * @param position track number. * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. * @see #skipToId(int) */ public void skipToPosition(final int position) throws IOException, MPDException { mConnection.send(skipToPositionCommand(position)); } /** * Stops music playing. * * @throws IOException Thrown upon a communication error with the server. * @throws MPDException Thrown if an error occurs as a result of command execution. */ public void stop() throws IOException, MPDException { mConnection.send(MPDCommand.MPD_CMD_STOP); } }
package herddb.core; import static herddb.core.TestUtils.execute; import static herddb.core.TestUtils.executeUpdate; import static herddb.core.TestUtils.scan; import herddb.mem.MemoryCommitLogManager; import herddb.mem.MemoryDataStorageManager; import herddb.mem.MemoryMetadataStorageManager; import herddb.model.DataScanner; import herddb.model.StatementEvaluationContext; import herddb.model.TransactionContext; import herddb.model.commands.CreateTableSpaceStatement; import herddb.utils.DataAccessor; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; @Fork(1) @State(Scope.Benchmark) public class ScanPKString { DBManager manager; String key; @Setup public void setup() throws Exception { key = String.format("%1$"+keySize+ "s", "a"); String nodeId = "localhost"; manager = new DBManager("localhost", new MemoryMetadataStorageManager(), new MemoryDataStorageManager(), new MemoryCommitLogManager(), null, null); manager.start(); CreateTableSpaceStatement st1 = new CreateTableSpaceStatement("tblspace1", Collections.singleton(nodeId), nodeId, 1, 0, 0); manager.executeStatement(st1, StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION); manager.waitForTablespace("tblspace1", 10000); execute(manager, "CREATE TABLE tblspace1.tsql (k1 string primary key,n1 int,n2 long, s1 string)", Collections.emptyList()); executeUpdate(manager, "INSERT INTO tblspace1.tsql(k1,n1,s1,n2) values(?,?,?,?)", Arrays.asList(key, Integer.valueOf(1), "a", Long.valueOf(3))); executeUpdate(manager, "INSERT INTO tblspace1.tsql(k1,n1,s1,n2) values(?,?,?,?)", Arrays.asList("mykey2", Integer.valueOf(2), "a", Long.valueOf(2))); executeUpdate(manager, "INSERT INTO tblspace1.tsql(k1,n1,s1,n2) values(?,?,?,?)", Arrays.asList("mykey3", Integer.valueOf(5), "b", Long.valueOf(1))); executeUpdate(manager, "INSERT INTO tblspace1.tsql(k1) values(?)", Arrays.asList("mykey4")); System.out.println("key:"+key); System.out.println("keylen:"+key.length()); System.out.println("keyszue:"+keySize); } @TearDown public void tearDown() { manager.close(); } @Param({"1", "1000", "100000"}) public int keySize; @Benchmark @BenchmarkMode(Mode.Throughput) public void scanByStringPrimaryKey() throws Exception { try (DataScanner scan1 = scan(manager, "SELECT * FROM tblspace1.tsql where k1=?", Arrays.asList(key));) { List<DataAccessor> result = scan1.consume(); if (result.size() != 1) { throw new RuntimeException(); } } } }
package jolie.net.protocols; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import jolie.net.CommChannel; import jolie.net.CommMessage; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.VariablePath; /** * A CommProtocol implements a protocol for sending and receiving data under the form of CommMessage objects. * @author Fabrizio Montesi */ abstract public class CommProtocol { private static class LazyDummyChannelHolder { private static class DummyChannel extends CommChannel { public void closeImpl() {} public void sendImpl( CommMessage message ) {} public CommMessage recvImpl() { return CommMessage.createEmptyMessage(); } } private static DummyChannel dummyChannel = new DummyChannel(); } final private VariablePath configurationPath; private CommChannel channel = null; protected VariablePath configurationPath() { return configurationPath; } abstract public String name(); public CommProtocol( VariablePath configurationPath ) { this.configurationPath = configurationPath; } public void setChannel( CommChannel channel ) { this.channel = channel; } protected CommChannel channel() { if ( this.channel == null ) { return LazyDummyChannelHolder.dummyChannel; } return this.channel; } protected ValueVector getParameterVector( String id ) { return configurationPath.getValue().getChildren( id ); } protected boolean hasParameter( String id ) { return configurationPath.getValue().hasChildren( id ); } /** * Shortcut for getParameterVector( id ).first() */ protected Value getParameterFirstValue( String id ) { return getParameterVector( id ).first(); } /** * Shortcut for checking if a parameter intValue() equals 1 * @param id the parameter identifier */ protected boolean checkBooleanParameter( String id ) { return hasParameter( id ) && getParameterFirstValue( id ).intValue() == 1; } /** * Shortcut for checking if a parameter intValue() equals 1 * @param id the parameter identifier */ protected boolean checkBooleanParameter( String id, boolean defaultValue ) { if ( hasParameter( id ) ) { return getParameterFirstValue( id ).intValue() == 1; } else { return defaultValue; } } /** * Shortcut for <code>getParameterFirstValue( id ).strValue()</code> * @param id the parameter identifier */ protected String getStringParameter( String id ) { return ( hasParameter( id ) ? getParameterFirstValue( id ).strValue() : "" ); } /** * Shortcut for <code>getParameterFirstValue( id ).intValue()</code> * @param id the parameter identifier */ protected int getIntParameter( String id ) { return ( hasParameter( id ) ? getParameterFirstValue( id ).intValue() : 0 ); } abstract public CommMessage recv( InputStream istream, OutputStream ostream ) throws IOException; abstract public void send( OutputStream ostream, CommMessage message, InputStream istream ) throws IOException; abstract public boolean isThreadSafe(); }
package org.jpos.q2.iso; import java.util.Iterator; import org.jdom.Element; import org.jpos.core.ConfigurationException; import org.jpos.iso.ISOChannel; import org.jpos.iso.ISOMsg; import org.jpos.iso.ISOPackager; import org.jpos.iso.ISORequestListener; import org.jpos.iso.ISOException; import org.jpos.iso.ISOServer; import org.jpos.iso.ISOServerSocketFactory; import org.jpos.iso.ISOSource; import org.jpos.iso.ServerChannel; import org.jpos.q2.QBeanSupport; import org.jpos.q2.QFactory; import org.jpos.space.LocalSpace; import org.jpos.space.Space; import org.jpos.space.SpaceFactory; import org.jpos.space.SpaceListener; import org.jpos.util.LogSource; import org.jpos.util.NameRegistrar; import org.jpos.util.ThreadPool; /** * ISO Server wrapper. * * @author Alwyn Schoeman * @version $Revision$ $Date$ * @jmx:mbean description="ISOServer wrapper" * extends="org.jpos.q2.QBeanSupportMBean" */ public class QServer extends QBeanSupport implements QServerMBean, SpaceListener, ISORequestListener { private int port = 0; private int maxSessions = 100; private int minSessions = 1; private String channelString, packagerString, socketFactoryString; private ISOChannel channel = null; private ISOPackager packager = null; private ISOServer server; protected LocalSpace sp; private String inQueue; private String outQueue; public QServer () { super (); } public void initService() throws ConfigurationException { Element e = getPersist (); sp = grabSpace (e.getChild ("space")); } private void newChannel () throws ConfigurationException { Element persist = getPersist (); Element e = persist.getChild ("channel"); if (e == null) throw new ConfigurationException ("channel element missing"); ChannelAdaptor adaptor = new ChannelAdaptor (); channel = adaptor.newChannel (e, getFactory ()); } private void initServer () throws ConfigurationException { if (port == 0) throw new ConfigurationException ("Port value not set"); newChannel(); if (channel == null) throw new ConfigurationException ("ISO Channel is null"); if (!(channel instanceof ServerChannel)) { throw new ConfigurationException (channelString + "does not implement ServerChannel"); } ThreadPool pool = null; pool = new ThreadPool (minSessions ,maxSessions); pool.setLogger (log.getLogger(), getName() + ".pool"); server = new ISOServer (port, (ServerChannel) channel, pool); server.setLogger (log.getLogger(), getName() + ".server"); server.setName (getName ()); if (socketFactoryString != null) { ISOServerSocketFactory sFac = (ISOServerSocketFactory) getFactory().newInstance(socketFactoryString); if (sFac != null && sFac instanceof LogSource) { ((LogSource) sFac).setLogger(log.getLogger(),getName() + ".socket-factory"); } server.setSocketFactory(sFac); } getFactory().setConfiguration (server, getPersist()); addServerSocketFactory(); addListeners (); NameRegistrar.register (getName(), this); new Thread (server).start(); } private void initIn() { Element persist = getPersist(); inQueue = persist.getChildText("in"); if (inQueue != null) { /* * We have an 'in' queue to monitor for messages we will * send out through server in our (SpaceListener)notify(Object, Object) method. */ sp.addListener(inQueue, this); } } private void initOut() { Element persist = getPersist(); outQueue = persist.getChildText("out"); if (outQueue != null) { /* * We have an 'out' queue to send any messages to that are received * by the our requestListner(this). * * Note, if additional ISORequestListeners are registered with the server after * this point, then they won't see anything as our process(ISOSource, ISOMsg) * always return true. */ server.addISORequestListener(this); } } public void startService () { try { initServer (); initIn(); initOut(); } catch (Exception e) { getLog().warn ("error starting service", e); } } public void stopService () { if (server != null) server.shutdown (); } public void destroyService () { NameRegistrar.unregister (getName()); NameRegistrar.unregister ("server." + getName()); } /** * @jmx:managed-attribute description="Server port" */ public synchronized void setPort (int port) { this.port = port; setAttr (getAttrs (), "port", new Integer (port)); setModified (true); } /** * @jmx:managed-attribute description="Server port" */ public int getPort () { return port; } /** * @jmx:managed-attribute description="Packager" */ public synchronized void setPackager (String packager) { packagerString = packager; setAttr (getAttrs (), "packager", packagerString); setModified (true); } /** * @jmx:managed-attribute description="Packager" */ public String getPackager () { return packagerString; } /** * @jmx:managed-attribute description="Channel" */ public synchronized void setChannel (String channel) { channelString = channel; setAttr (getAttrs (), "channel", channelString); setModified (true); } /** * @jmx:managed-attribute description="Channel" */ public String getChannel () { return channelString; } /** * @jmx:managed-attribute description="Maximum Nr. of Sessions" */ public synchronized void setMaxSessions (int maxSessions) { this.maxSessions = maxSessions; setAttr (getAttrs (), "maxSessions", new Integer (maxSessions)); setModified (true); } /** * @jmx:managed-attribute description="Maximum Nr. of Sessions" */ public int getMaxSessions () { return maxSessions; } /** * @jmx:managed-attribute description="Minimum Nr. of Sessions" */ public synchronized void setMinSessions (int minSessions) { this.minSessions = minSessions; setAttr (getAttrs (), "minSessions", new Integer (minSessions)); setModified (true); } /** * @jmx:managed-attribute description="Minimum Nr. of Sessions" */ public int getMinSessions () { return minSessions; } /** * @jmx:managed-attribute description="Socket Factory" */ public synchronized void setSocketFactory (String sFactory) { socketFactoryString = sFactory; setAttr (getAttrs(),"socketFactory", socketFactoryString); setModified (true); } /** * @jmx:managed-attribute description="Socket Factory" */ public String getSocketFactory() { return socketFactoryString; } public String getISOChannelNames() { return server.getISOChannelNames(); } public String getCountersAsString () { return server.getCountersAsString (); } public String getCountersAsString (String isoChannelName) { return server.getCountersAsString (isoChannelName); } private void addServerSocketFactory () throws ConfigurationException { QFactory factory = getFactory (); Element persist = getPersist (); Element serverSocketFactoryElement = persist.getChild ("server-socket-factory"); if (serverSocketFactoryElement != null) { ISOServerSocketFactory serverSocketFactory = (ISOServerSocketFactory) factory.newInstance (serverSocketFactoryElement.getAttributeValue ("class")); factory.setLogger (serverSocketFactory, serverSocketFactoryElement); factory.setConfiguration (serverSocketFactory, serverSocketFactoryElement); server.setSocketFactory(serverSocketFactory); } } private void addListeners () throws ConfigurationException { QFactory factory = getFactory (); Iterator iter = getPersist().getChildren ( "request-listener" ).iterator(); while (iter.hasNext()) { Element l = (Element) iter.next(); ISORequestListener listener = (ISORequestListener) factory.newInstance (l.getAttributeValue ("class")); factory.setLogger (listener, l); factory.setConfiguration (listener, l); server.addISORequestListener (listener); } } private LocalSpace grabSpace (Element e) throws ConfigurationException { String uri = e != null ? e.getText() : ""; Space sp = SpaceFactory.getSpace (uri); if (sp instanceof LocalSpace) { return (LocalSpace) sp; } throw new ConfigurationException ("Invalid space " + uri); } /* * This method will be invoked through the SpaceListener interface we registered once * we noticed we had an 'in' queue. */ public void notify(Object key, Object value) { Object obj = sp.inp (key); if (obj instanceof ISOMsg) { ISOMsg m = (ISOMsg) obj; try { ISOChannel c = server.getLastConnectedISOChannel(); if (c == null) throw new ISOException ("Server has no active connections"); if (!c.isConnected()) throw new ISOException ("Client disconnected"); c.send(m); } catch (Exception e) { getLog().warn ("notify", e); } } } /* * This method will be invoke through the ISORequestListener interface, *if* * this QServer has an 'out' queue to handle. */ public boolean process(ISOSource source, ISOMsg m) { sp.out(outQueue, m); return true; } }
package MainaCards; public class Card { private int rank; private int suit; private String[] ranks = { "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" }; private String[] suits = { "Clubs", "Diamonds", "Hearts" , "Spades"}; public Card(int i, int j){ rank = i; suit = j; } public String toString(){ return ranks[rank] + suits[suit]; } public int getRank(){ return rank; } public int getSuit(){ return suit; } }
package com.mindcoders.phial.internal.overlay; import android.animation.Animator; import android.animation.PropertyValuesHolder; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.graphics.PixelFormat; import android.graphics.Point; import android.os.Build; import android.provider.Settings; import android.support.v7.widget.CardView; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.FrameLayout; import com.mindcoders.phial.Page; import com.mindcoders.phial.internal.PhialNotifier; import com.mindcoders.phial.internal.overlay.OverlayView.OnPageSelectedListener; import com.mindcoders.phial.internal.util.CurrentActivityProvider; import com.mindcoders.phial.internal.util.SimpleAnimatorListener; import java.util.List; import static com.mindcoders.phial.internal.util.UiUtils.dpToPx; public final class Overlay implements CurrentActivityProvider.AppStateListener { private static final int BUTTON_SIZE_DP = 68; private static final int STATUSBAR_HEIGHT_DP = 25; private static final int PAGE_MARGIN_DP = 8; private final PhialNotifier notifier; private final Context context; private final List<Page> pages; private final OverlayPositionStorage positionStorage; private final CurrentActivityProvider activityProvider; private final WindowManager windowManager; private final OverlayView overlayView; private ViewGroup containerWrapperView; private ViewGroup pageContainerView; private Point overlayViewPosition = new Point(); private final Point displaySize = new Point(); private final int btnSizePx; private boolean isOverlayViewSetup; private boolean isDrawOverlayPermissionRequested; public Overlay( Context context, List<Page> pages, PhialNotifier notifier, CurrentActivityProvider activityProvider, OverlayPositionStorage positionStorage) { this.context = context; this.pages = pages; this.notifier = notifier; this.activityProvider = activityProvider; this.positionStorage = positionStorage; this.windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); windowManager.getDefaultDisplay().getSize(displaySize); btnSizePx = dpToPx(context, BUTTON_SIZE_DP); overlayView = new OverlayView(context, btnSizePx); activityProvider.addListener(this); } private void setupOverlayView(List<Page> pages) { overlayViewPosition = positionStorage.getPosition(); WindowManager.LayoutParams params = new WindowManager.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, btnSizePx, getType(), WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT ); params.x = overlayViewPosition.x; params.y = overlayViewPosition.y; windowManager.addView(overlayView, params); overlayView.setOnPageSelectedListener(onPageSelectedListener); overlayView.setOnHandleMoveListener(onHandleMoveListener); overlayView.addPages(pages); } @TargetApi(Build.VERSION_CODES.M) private boolean canDrawOverlay() { return (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) || Settings.canDrawOverlays(context); } @TargetApi(Build.VERSION_CODES.M) private void startSettingsActivity() { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } private int getType() { final int type; if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; } else { type = WindowManager.LayoutParams.TYPE_PHONE; } return type; } private void show() { if (canDrawOverlay() && !isOverlayViewSetup) { setupOverlayView(pages); isOverlayViewSetup = true; } else if (!canDrawOverlay() && !isDrawOverlayPermissionRequested) { startSettingsActivity(); isDrawOverlayPermissionRequested = true; return; } overlayView.setVisibility(View.VISIBLE); if (containerWrapperView != null) { containerWrapperView.setVisibility(View.VISIBLE); } } private void hide() { overlayView.setVisibility(View.GONE); if (containerWrapperView != null) { containerWrapperView.setVisibility(View.GONE); } positionStorage.savePosition(overlayViewPosition); } public void destroy() { activityProvider.removeListener(this); windowManager.removeView(overlayView); if (containerWrapperView != null) { windowManager.removeView(containerWrapperView); containerWrapperView = null; pageContainerView = null; } } private ViewGroup createWrapperView() { FrameLayout wrapper = new FrameLayout(context); int height = displaySize.y - btnSizePx - dpToPx(context, STATUSBAR_HEIGHT_DP); WindowManager.LayoutParams params = new WindowManager.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, height, getType(), WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT ); params.y = displaySize.y / 2; wrapper.setLayoutParams(params); return wrapper; } private ViewGroup createPageContainerView() { CardView pageContainer = new CardView(context); pageContainer.setCardElevation(dpToPx(context, 4)); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ); int margin = dpToPx(context, PAGE_MARGIN_DP); params.leftMargin = margin; params.rightMargin = margin; params.bottomMargin = margin; pageContainer.setLayoutParams(params); return pageContainer; } private final OverlayView.OnHandleMoveListener onHandleMoveListener = new OverlayView.OnHandleMoveListener() { private int initialX, initialY; @Override public void onMoveStart(float x, float y) { WindowManager.LayoutParams params = (WindowManager.LayoutParams) overlayView.getLayoutParams(); initialX = params.x; initialY = params.y; } @Override public void onMove(float dx, float dy) { WindowManager.LayoutParams params = (WindowManager.LayoutParams) overlayView.getLayoutParams(); params.x = initialX + (int) dx; params.y = initialY + (int) dy; windowManager.updateViewLayout(overlayView, params); } @Override public void onMoveEnd() { WindowManager.LayoutParams params = (WindowManager.LayoutParams) overlayView.getLayoutParams(); overlayViewPosition.x = params.x; overlayViewPosition.y = params.y; moveViewToTheEdge(); } private void moveViewToTheEdge() { final int x; if (overlayViewPosition.x > 0) { x = displaySize.x / 2; } else { x = -displaySize.x / 2; } ValueAnimator animator = ValueAnimator.ofInt(overlayViewPosition.x, x); final WindowManager.LayoutParams params = (WindowManager.LayoutParams) overlayView.getLayoutParams(); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { params.x = (int) animation.getAnimatedValue(); windowManager.updateViewLayout(overlayView, params); } }); animator.setDuration(100); animator.start(); } }; private final OnPageSelectedListener onPageSelectedListener = new OnPageSelectedListener() { @Override public void onFirstPageSelected(Page page) { notifier.fireDebugWindowShown(); animateForward(page); } @Override public void onPageSelectionChanged(Page page) { pageContainerView.removeAllViews(); pageContainerView.addView(page.getPageViewFactory().createPageView(context)); } @Override public void onNothingSelected() { notifier.fireDebugWindowHide(); animateBackward(); } private void animateForward(final Page page) { WindowManager.LayoutParams params = (WindowManager.LayoutParams) overlayView.getLayoutParams(); int startX = params.x; int endX = displaySize.x / 2; int startY = params.y; int endY = -displaySize.y / 2; animate(startX, endX, startY, endY, overlayView, params, new SimpleAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { showContainerView(); pageContainerView.addView(page.getPageViewFactory().createPageView(context)); } } ); } private void showContainerView() { containerWrapperView = createWrapperView(); pageContainerView = createPageContainerView(); containerWrapperView.addView(pageContainerView); windowManager.addView(containerWrapperView, containerWrapperView.getLayoutParams()); } private void animateBackward() { WindowManager.LayoutParams params = (WindowManager.LayoutParams) overlayView.getLayoutParams(); int startX = params.x; int endX = overlayViewPosition.x; int startY = params.y; int endY = overlayViewPosition.y; animate(startX, endX, startY, endY, overlayView, params, new SimpleAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { windowManager.removeView(containerWrapperView); containerWrapperView = null; pageContainerView = null; } } ); } private void animate( int startX, int endX, int startY, int endY, final View view, final WindowManager.LayoutParams params, Animator.AnimatorListener listener ) { PropertyValuesHolder x = PropertyValuesHolder.ofInt("x", startX, endX); PropertyValuesHolder y = PropertyValuesHolder.ofInt("y", startY, endY); ValueAnimator valueAnimator = ValueAnimator.ofPropertyValuesHolder(x, y); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { params.x = (int) animation.getAnimatedValue("x"); params.y = (int) animation.getAnimatedValue("y"); windowManager.updateViewLayout(view, params); } }); valueAnimator.setDuration(200); valueAnimator.addListener(listener); valueAnimator.start(); } }; @Override public void onAppForeground() { show(); } @Override public void onAppBackground() { hide(); } }
package com.trendmicro.arthur.nio; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.Channel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; public class NServer { private Selector selector; private Charset charset = Charset.forName("UTF-8"); public void init() throws Exception { selector = Selector.open(); ServerSocketChannel server = ServerSocketChannel.open(); InetSocketAddress isa = new InetSocketAddress("127.0.0.1", 3000); server.socket().bind(isa); server.configureBlocking(false); server.register(selector, SelectionKey.OP_ACCEPT); while (selector.select() > 0) { for (SelectionKey key : selector.selectedKeys()) { selector.selectedKeys().remove(key); if (key.isAcceptable()) { SocketChannel sc = server.accept(); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); key.interestOps(SelectionKey.OP_ACCEPT); } if (key.isReadable()) { SocketChannel sc = (SocketChannel)key.channel(); ByteBuffer buff = ByteBuffer.allocate(1024); String content = ""; try { while (sc.read(buff) > 0) { buff.flip(); content += charset.decode(buff); buff.clear(); } System.out.println("=====" + content); key.interestOps(SelectionKey.OP_READ); } catch (IOException e) { key.cancel(); if (key.channel() != null) key.channel().close(); } if (content.length() > 0) { for (SelectionKey sk : selector.keys()) { Channel targetchannel = sk.channel(); if (targetchannel instanceof SocketChannel) { SocketChannel dest = (SocketChannel)targetchannel; dest.write(charset.encode(content)); } } } } } } } public static void main(String[] args) throws Exception { new NServer().init(); } }
package meterstanden.domain; import java.io.IOException; import java.util.List; import javax.persistence.Query; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.hibernate.Session; import meterstanden.hibernate.HibernateUtil; import meterstanden.model.Meterstanden; import meterstanden.model.Metersoorten; /** * Servlet implementation class ShowMeterstanden */ @WebServlet("/ShowMeterstanden") public class ShowMeterstanden extends HttpServlet { private static final long serialVersionUID = 1L; private static Logger log = Logger.getLogger(ShowMeterstanden.class); /** * @see HttpServlet#HttpServlet() */ public ShowMeterstanden() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String selectie; if (request.getParameterMap().containsKey("selection")){ selectie = request.getParameter("selection"); } else { selectie = "0"; } request.setAttribute("theMeterstanden", getLastMeterstanden(selectie)); request.setAttribute("theMetersoorten", getMetersoorten()); request.setAttribute("selectedMetersoort", selectie); RequestDispatcher rd = getServletContext().getRequestDispatcher("/WEB-INF/ShowMeterstanden.jsp"); rd.forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @SuppressWarnings("unchecked") private List<Meterstanden> getLastMeterstanden(String selectie){ //TODO write javadoc log.debug("Getting the 20 last Meterstanden"); Session session = HibernateUtil.getSessionFactory().openSession(); Long selectieInt = Long.valueOf(selectie); Metersoorten metersoort = null; boolean useSelection = selectieInt>0; String hql = "from Meterstanden m "; if (useSelection){ hql += "where m.metersoort = :metersoort "; metersoort = session.get(Metersoorten.class, selectieInt); } hql += "order by m.datum desc"; Query query = session.createQuery(hql); if (useSelection){ query.setParameter("metersoort", metersoort); } query.setMaxResults(20); //todo this 20 should be configured with a config file. List<?> rl = query.getResultList(); session.close(); return (List<Meterstanden>) rl; } @SuppressWarnings("unchecked") private List<Metersoorten> getMetersoorten(){ //TODO write javadoc log.debug("Getting all Metersoorten"); Session session = HibernateUtil.getSessionFactory().openSession(); Query query = session.createQuery("from Metersoorten"); List<?> rl = query.getResultList(); session.close(); return (List<Metersoorten>) rl; } }
package org.lockss.plugin; import java.io.*; import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.regex.*; import java.lang.reflect.*; import java.util.zip.*; import org.lockss.test.*; import org.lockss.daemon.*; import org.lockss.plugin.simulated.*; import org.lockss.util.*; import org.lockss.app.*; import org.lockss.config.*; /** * Utilities for manipulating plugins and their components in tests */ public class PluginTestUtil { static Logger log = Logger.getLogger("PluginTestUtil"); static List aulist = new LinkedList(); public static void registerArchivalUnit(Plugin plug, ArchivalUnit au) { PluginManager mgr = getPluginManager(); log.debug3(mgr.toString()); String plugid = au.getPluginId(); log.debug("registerArchivalUnit plugin = " + plug + "au = " + au); if (plug != mgr.getPlugin(plugid)) { try { PrivilegedAccessor.invokeMethod(mgr, "setPlugin", ListUtil.list(plugid, plug).toArray()); } catch (Exception e) { log.error("Couldn't register AU", e); throw new RuntimeException(e.toString()); } } PluginTestable tp = (PluginTestable)plug; tp.registerArchivalUnit(au); try { PrivilegedAccessor.invokeMethod(mgr, "putAuInMap", ListUtil.list(au).toArray()); } catch (InvocationTargetException e) { log.error("Couldn't register AU", e); log.error("Nested", e.getTargetException()); throw new RuntimeException(e.toString()); } catch (Exception e) { log.error("Couldn't register AU", e); throw new RuntimeException(e.toString()); } aulist.add(au); } public static void registerArchivalUnit(ArchivalUnit au) { PluginManager mgr = getPluginManager(); String plugid = au.getPluginId(); Plugin plug = mgr.getPlugin(plugid); log.debug("registerArchivalUnit id = " + au.getAuId() + ", pluginid = " + plugid + ", plugin = " + plug); if (plug == null) { MockPlugin mp = new MockPlugin(); mp.setPluginId(plugid); plug = mp; } registerArchivalUnit(plug, au); } /* public static void registerArchivalUnit(ArchivalUnit au) { PluginManager mgr = getPluginManager(); log.debug(mgr.toString()); String plugid = au.getPluginId(); Plugin plug = mgr.getPlugin(plugid); log.debug("registerArchivalUnit id = " + au.getAuId() + ", pluginid = " + plugid + ", plugin = " + plug); if (plug == null) { MockPlugin mp = new MockPlugin(); mp.setPluginId(plugid); plug = mp; try { PrivilegedAccessor.invokeMethod(mgr, "setPlugin", ListUtil.list(plugid, mp).toArray()); } catch (Exception e) { log.error("Couldn't register AU", e); throw new RuntimeException(e.toString()); } } PluginTestable tp = (PluginTestable)plug; tp.registerArchivalUnit(au); try { PrivilegedAccessor.invokeMethod(mgr, "putAuMap", ListUtil.list(plug, au).toArray()); } catch (Exception e) { log.error("Couldn't register AU", e); throw new RuntimeException(e.toString()); } aulist.add(au); } */ public static void unregisterArchivalUnit(ArchivalUnit au) { PluginManager mgr = getPluginManager(); String plugid = au.getPluginId(); Plugin plug = mgr.getPlugin(plugid); if (plug != null) { PluginTestable tp = (PluginTestable)plug; tp.unregisterArchivalUnit(au); aulist.remove(au); } mgr.stopAu(au, new AuEvent(AuEvent.Type.Delete, false)); } public static void unregisterAllArchivalUnits() { log.debug("unregisterAllArchivalUnits()"); List aus = new ArrayList(aulist); for (Iterator iter = aus.iterator(); iter.hasNext(); ) { unregisterArchivalUnit((ArchivalUnit)iter.next()); } } public static Plugin findPlugin(String pluginName) { PluginManager pluginMgr = getPluginManager(); String key = pluginMgr.pluginKeyFromName(pluginName); pluginMgr.ensurePluginLoaded(key); return pluginMgr.getPlugin(key); } public static Plugin findPlugin(Class pluginClass) { return findPlugin(pluginClass.getName()); } public static ArchivalUnit createAu(Plugin plugin, Configuration auConfig) throws ArchivalUnit.ConfigurationException { return getPluginManager().createAu(plugin, auConfig, new AuEvent(AuEvent.Type.Create, false)); } public static ArchivalUnit createAndStartAu(Plugin plugin, Configuration auConfig) throws ArchivalUnit.ConfigurationException { return startAu(createAu(plugin, auConfig)); } static ArchivalUnit startAu(ArchivalUnit au) { LockssDaemon daemon = au.getPlugin().getDaemon(); daemon.getHistoryRepository(au).startService(); daemon.getLockssRepository(au).startService(); daemon.getNodeManager(au).startService(); return au; } public static ArchivalUnit createAu(String pluginName, Configuration auConfig) throws ArchivalUnit.ConfigurationException { return createAu(findPlugin(pluginName), auConfig); } public static ArchivalUnit createAndStartAu(String pluginName, Configuration auConfig) throws ArchivalUnit.ConfigurationException { return createAndStartAu(findPlugin(pluginName), auConfig); } public static ArchivalUnit createAu(Class pluginClass, Configuration auConfig) throws ArchivalUnit.ConfigurationException { return createAu(findPlugin(pluginClass.getName()), auConfig); } public static ArchivalUnit createAndStartAu(Class pluginClass, Configuration auConfig) throws ArchivalUnit.ConfigurationException { return createAndStartAu(findPlugin(pluginClass.getName()), auConfig); } public static SimulatedArchivalUnit createSimAu(Configuration auConfig) throws ArchivalUnit.ConfigurationException { return (SimulatedArchivalUnit)createAu(findPlugin(SimulatedPlugin.class), auConfig); } static Configuration getAuConfig(TdbAu tau) { PluginManager mgr = getPluginManager(); Plugin plugin = tau.getPlugin(mgr); TitleConfig tc = new TitleConfig(tau, plugin); return tc.getConfig(); } public static ArchivalUnit createAu(TdbAu tau) throws ArchivalUnit.ConfigurationException { PluginManager mgr = getPluginManager(); Plugin plugin = findPlugin(tau.getPluginId()); return createAu(plugin, getAuConfig(tau)); } public static ArchivalUnit createAu(Plugin plugin, TdbAu tau) throws ArchivalUnit.ConfigurationException { return createAu(plugin, getAuConfig(tau)); } public static ArchivalUnit createAndStartAu(TdbAu tau) throws ArchivalUnit.ConfigurationException { return startAu(createAu(tau)); } public static ArchivalUnit createAndStartAu(Plugin plugin, TdbAu tau) throws ArchivalUnit.ConfigurationException { return startAu(createAu(plugin, tau)); } public static SimulatedArchivalUnit createAndStartSimAu(Configuration auConfig) throws ArchivalUnit.ConfigurationException { return createAndStartSimAu(SimulatedPlugin.class, auConfig); } public static SimulatedArchivalUnit createAndStartSimAu(Class pluginClass, Configuration auConfig) throws ArchivalUnit.ConfigurationException { return (SimulatedArchivalUnit)createAndStartAu(pluginClass, auConfig); } public static void crawlSimAu(SimulatedArchivalUnit sau) { if (!sau.hasContentTree()) { // log.debug("Creating simulated content tree: " + sau.getParamMap()); sau.generateContentTree(); } log.debug("Crawling simulated content"); NoCrawlEndActionsFollowLinkCrawler crawler = new NoCrawlEndActionsFollowLinkCrawler(sau, new MockAuState()); //crawler.setCrawlManager(crawlMgr); crawler.doCrawl(); } /** * {@code ifMatch, patRepPairs} defaults to {null}. * {@code fromAu} defaults to {fromAu.getCachedUrlSet()}. * * @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List) */ public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu) throws MalformedURLException { return copyAu(fromAu, toAu, null, null, null); } /** * {@code patRepPairs} defaults to {null}. * {@code fromAu} defaults to {fromAu.getCachedUrlSet()}. * * @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List) */ public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu, String ifMatch) throws MalformedURLException { return copyAu(fromAu, toAu, ifMatch, null, null); } /** * {@code pat, rep} converted to {PatternReplacements}. * {@code fromAu} defaults to {fromAu.getCachedUrlSet()}. * * @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List) */ public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu, String ifMatch, String pat, String rep) throws MalformedURLException { return copyCus(fromAu.getAuCachedUrlSet(), toAu, ifMatch, pat, rep); } /** * {@code fromAu} defaults to {fromAu.getCachedUrlSet()}. * * @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List) */ public static boolean copyAu(ArchivalUnit fromAu, ArchivalUnit toAu, String ifMatch, List<PatternReplacements> patRepPairs) throws MalformedURLException { return copyCus(fromAu.getAuCachedUrlSet(), toAu, ifMatch, patRepPairs); } /** * {@code ifMatch, patRepPairs} defaults to {null}. * * @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List) */ public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu) { return copyCus(fromCus, toAu, null, null, null); } /** * {@code pat, rep} converted to {PatternReplacements}. * * @param pat a regex used to match files in the simulated crawl * @param rep regex replacement pattern(s) to rename the original file. * @see PluginTestUtil#copyCus(CachedUrlSet, ArchivalUnit, String, List) */ public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu, String ifMatch, String pat, String rep) { List<PatternReplacements> patRepPairs; if (pat == null) { patRepPairs = null; } else { patRepPairs = Collections.singletonList(new PatternReplacements(pat, rep)); } return copyCus(fromCus, toAu, ifMatch, patRepPairs); } /** * Utility to copy files from a simulated crawl to a mock archival unit. * For each file matched by ifMatch, the first Pattern matched will be copied for as many * replacements as are associated with it. * If only fromAu and toAu are provided, all files are copied without modification. * * @param fromCus the CachedUrlSet which has been crawled * @param toAu the Archival Unit to copy content to * @param ifMatch String, a regex to check on the url before pattern replacement transforming. e.g. .zip * @param patRepPairs A List of PatternReplacements to rename files from matched patterns to replacements. * @return true, if all copies attempted succeeded, false otherwise */ public static boolean copyCus(CachedUrlSet fromCus, ArchivalUnit toAu, String ifMatch, List<PatternReplacements> patRepPairs) { boolean res = true; Pattern ifMatchPat = null; if (ifMatch != null) { ifMatchPat = Pattern.compile(ifMatch); } ArchiveFileTypes aft = toAu.getArchiveFileTypes(); String isArchive = null; for (CachedUrl cu : fromCus.getCuIterable()) { try { String fromUrl = cu.getUrl(); String toUrl = fromUrl; if (ifMatchPat != null) { Matcher mat = ifMatchPat.matcher(fromUrl); if (!mat.find()) { log.debug3("no match: " + fromUrl + ", " + ifMatchPat); continue; } } if (aft != null) { isArchive = aft.getFromCu(cu); } if (isArchive == null) { if (patRepPairs != null) { for (PatternReplacements prp : patRepPairs) { Matcher mat = prp.pat.matcher(fromUrl); if (mat.find()) { for (String rep : prp.rep) { toUrl = mat.replaceAll(rep); doCopyCu(cu, toAu, fromUrl, toUrl); } break; } } } else { doCopyCu(cu, toAu, fromUrl, toUrl); } } else { switch (isArchive) { case ".zip": copyZip(cu, toAu, patRepPairs); break; case ".tar": //TODO // com.ice.tar.TarInputStream log.info("support for .tar coming"); throw new Exception("support for .tar coming"); //break; case ".tar.gz": case ".tgz": //TODO // double wrap - unwrap gzip, then TarInputStream log.info("support for .tgz coming"); throw new Exception("support for .tgz coming"); //break; default: throw new Exception("Unexpected Archive file type: '" + isArchive + "'"); } } } catch (Exception e) { log.error("Couldn't copy " + cu.getUrl(), e); res = false; } finally { cu.release(); } } return res; } private static void doCopyCu(CachedUrl cu, ArchivalUnit toAu, String fromUrl, String toUrl ) throws IOException { doCopyCu(cu.getUnfilteredInputStream(), cu.getProperties(), toAu, fromUrl, toUrl); } private static void doCopyCu(InputStream is, CIProperties props, ArchivalUnit toAu, String fromUrl, String toUrl ) throws IOException { if (props == null) { log.debug3("in copyCus() props was null for url: " + fromUrl); } UrlCacher uc = toAu.makeUrlCacher( new UrlData(is, props, toUrl)); uc.storeContent(); if (!toUrl.equals(fromUrl)) { log.info("Copied " + fromUrl + " to " + toUrl); } else { log.debug2("Copied " + fromUrl); } } /** * Opens a single CachedUrl zip file, iterates over its contents and copies the contents if they pass * given pattern(s) and replacements. * * Note: replacement(s) can rename the zip file, but all zip files should be the same in the replacement string(s) * * @param cu A CachedUrl of compressed content. * @param toAu The ArchivalUnit to copy the cu into. * @param patRepPairs A List of PatternReplacementss to selectively copy zipped content and rename it in the new zip. * @throws IOException When I/O zip files encounter any number of problems. */ private static void copyZip(CachedUrl cu, ArchivalUnit toAu, List<PatternReplacements> patRepPairs) throws IOException { boolean doCache = false; String zipUrl = cu.getUrl() + "!/"; String toUrl; String zippedFile; String fromFile; ZipInputStream zis = null; ZipOutputStream zos; String outZip = null; try { InputStream cuis = new ReaderInputStream(cu.openForReading()); zis = new ZipInputStream(cuis); zos = new ZipOutputStream(Files.newOutputStream( Paths.get(cu.getArchivalUnit().getProperties().getString("root") + "temp.zip"))); zos.setMethod(ZipOutputStream.DEFLATED); zos.setLevel(Deflater.BEST_COMPRESSION); ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { if (entry.isDirectory()) { continue; } else if (entry.getName().endsWith(".zip") ) { // TODO recurse through nested // zipCopy(cu, toAu, zipUrl + ); } fromFile = entry.getName(); zippedFile = zipUrl + fromFile; if (patRepPairs == null) { doCache = true; doCopyZipEntry(zos, zis, zippedFile); outZip = zippedFile.split("!/")[0]; } else { for (PatternReplacements prp : patRepPairs) { Matcher mat = prp.pat.matcher(zippedFile); if (mat.find()) { for (String rep : prp.rep) { toUrl = mat.replaceAll(rep); if (!toUrl.equals(zippedFile)) { log.debug("Found a zipped file match: " + zippedFile + " -> " + toUrl); doCache = true; doCopyZipEntry(zos, zis, toUrl); outZip = toUrl.split("!/")[0]; } } break; } } } } zos.close(); // any copied file triggers saving the new zip stream // the output file name is parsed from the matched file // it will be the last matched-replaced file. if (doCache) { FileInputStream is = new FileInputStream(new File( cu.getArchivalUnit().getProperties().getString("root"), "temp.zip")); // save all the copied zip entries to a new zip on the toAu doCopyCu(is, cu.getProperties(), toAu, zipUrl, outZip); is.close(); } } finally { IOUtil.safeClose(zis); } } private static void doCopyZipEntry(ZipOutputStream zos, ZipInputStream zis, String toUrl) throws IOException { String toFile = toUrl.split("!/")[1]; ZipEntry outEntry = new ZipEntry(toFile); zos.putNextEntry(outEntry); StreamUtil.copy(zis, zos); zos.closeEntry(); } public static List<String> urlsOf(final Iterable<CachedUrl> cus) { return new ArrayList<String>() {{ for (CachedUrl cu : cus) { add(cu.getUrl()); } }}; } private static PluginManager getPluginManager() { return (PluginManager)LockssDaemon.getManager(LockssDaemon.PLUGIN_MANAGER); } public static PatternReplacements makePatRep(String pat, String... rep) { return new PatternReplacements(pat , rep); } public static class PatternReplacements { public Pattern pat; public String[] rep; /** * Simple Container class for Regex pattern -> Replacement associations. * @param pat String regex, gets compiled to a Pattern * @param rep Replacement string */ PatternReplacements(String pat, String... rep) { this.pat = Pattern.compile(pat, Pattern.CASE_INSENSITIVE); this.rep = rep; } } }
package sbol.assembly; import java.io.File; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.sbml.jsbml.Model; import org.sbml.jsbml.ModifierSpeciesReference; import org.sbml.jsbml.Reaction; import org.sbml.jsbml.SimpleSpeciesReference; import org.sbml.jsbml.Species; import org.sbml.jsbml.SpeciesReference; import org.sbml.jsbml.ext.comp.CompSBasePlugin; import org.sbml.jsbml.ext.comp.Port; import org.sbml.jsbml.ext.comp.ReplacedBy; import org.sbml.jsbml.ext.comp.ReplacedElement; import org.sbml.jsbml.ext.comp.Submodel; import org.sbolstandard.core2.ComponentDefinition; import org.sbolstandard.core2.DirectionType; import org.sbolstandard.core2.FunctionalComponent; import org.sbolstandard.core2.Interaction; import org.sbolstandard.core2.MapsTo; import org.sbolstandard.core2.Module; import org.sbolstandard.core2.ModuleDefinition; import org.sbolstandard.core2.Participation; import org.sbolstandard.core2.RefinementType; import org.sbolstandard.core2.SBOLDocument; import org.sbolstandard.core2.Identified; import org.sbolstandard.core2.SequenceOntology; import org.sbolstandard.core2.SystemsBiologyOntology; import biomodel.annotation.AnnotationUtility; import biomodel.annotation.SBOLAnnotation; import biomodel.parser.BioModel; import biomodel.util.GlobalConstants; import biomodel.util.SBMLutilities; import biomodel.util.Utility; public class ModelGenerator { public ModelGenerator() { } public static String getDisplayID(Identified sbolElement) { if (sbolElement.isSetDisplayId()) { return sbolElement.getDisplayId(); } String identity = sbolElement.getIdentity().toString(); return identity.substring(identity.lastIndexOf("/") + 1); } public static List<BioModel> generateModel(String projectDirectory, ModuleDefinition moduleDef, SBOLDocument sbolDoc) { List<BioModel> models = new LinkedList<BioModel>(); BioModel targetModel = new BioModel(projectDirectory); targetModel.createSBMLDocument(getDisplayID(moduleDef), false, false); // Annotate SBML model with SBOL module definition Model sbmlModel = targetModel.getSBMLDocument().getModel(); SBOLAnnotation modelAnno = new SBOLAnnotation(sbmlModel.getMetaId(), moduleDef.getClass().getSimpleName(), moduleDef.getIdentity()); AnnotationUtility.setSBOLAnnotation(sbmlModel, modelAnno); for (FunctionalComponent comp : moduleDef.getFunctionalComponents()) { if (isSpeciesComponent(comp, sbolDoc)) { generateSpecies(comp, sbolDoc, targetModel); if (isInputComponent(comp)) { generateInputPort(comp, targetModel); } else if (isOutputComponent(comp)){ generateOutputPort(comp, targetModel); } } else if (isPromoterComponent(comp, sbolDoc)) { generatePromoterSpecies(comp, sbolDoc, targetModel); if (isInputComponent(comp)) { generateInputPort(comp, targetModel); } else if (isOutputComponent(comp)){ generateOutputPort(comp, targetModel); } } else { //System.out.println("Dropping "+comp.getIdentity()); } } HashMap<FunctionalComponent, List<Interaction>> promoterToProductions = new HashMap<FunctionalComponent, List<Interaction>>(); HashMap<FunctionalComponent, List<Interaction>> promoterToActivations = new HashMap<FunctionalComponent, List<Interaction>>(); HashMap<FunctionalComponent, List<Interaction>> promoterToRepressions = new HashMap<FunctionalComponent, List<Interaction>>(); HashMap<FunctionalComponent, List<Participation>> promoterToProducts = new HashMap<FunctionalComponent, List<Participation>>(); HashMap<FunctionalComponent, List<Participation>> promoterToTranscribed = new HashMap<FunctionalComponent, List<Participation>>(); HashMap<FunctionalComponent, List<Participation>> promoterToActivators = new HashMap<FunctionalComponent, List<Participation>>(); HashMap<FunctionalComponent, List<Participation>> promoterToRepressors = new HashMap<FunctionalComponent, List<Participation>>(); HashMap<FunctionalComponent, List<Participation>> promoterToPartici = new HashMap<FunctionalComponent, List<Participation>>(); for (Interaction interact : moduleDef.getInteractions()) { if (isDegradationInteraction(interact, moduleDef, sbolDoc)) { generateDegradationRxn(interact, moduleDef, targetModel); } else if (isComplexFormationInteraction(interact, moduleDef, sbolDoc)) { Participation complex = null; List<Participation> ligands = new LinkedList<Participation>(); for (Participation partici: interact.getParticipations()) { // COMPLEX if (partici.containsRole(SystemsBiologyOntology.PRODUCT) || partici.containsRole(URI.create("http://identifiers.org/biomodels.sbo/SBO:0000253"))) { complex = partici; } else if (partici.containsRole(SystemsBiologyOntology.REACTANT) || partici.containsRole(URI.create("http://identifiers.org/biomodels.sbo/SBO:0000280"))) { ligands.add(partici); } } generateComplexFormationRxn(interact, complex, ligands, moduleDef, targetModel); } else if (isProductionInteraction(interact, moduleDef, sbolDoc)) { FunctionalComponent promoter = null; for (Participation partici : interact.getParticipations()) if (partici.containsRole(SystemsBiologyOntology.PROMOTER)|| partici.containsRole(SystemsBiologyOntology.TEMPLATE)) { promoter = moduleDef.getFunctionalComponent(partici.getParticipantURI()); if (!promoterToPartici.containsKey(promoter)) promoterToPartici.put(promoter, new LinkedList<Participation>()); promoterToPartici.get(promoter).add(partici); if (!promoterToProductions.containsKey(promoter)) promoterToProductions.put(promoter, new LinkedList<Interaction>()); promoterToProductions.get(promoter).add(interact); } for (Participation partici : interact.getParticipations()) if (partici.containsRole(SystemsBiologyOntology.PRODUCT)) { if (!promoterToProducts.containsKey(promoter)) promoterToProducts.put(promoter, new LinkedList<Participation>()); promoterToProducts.get(promoter).add(partici); // TRANSCRIBED } else if (partici.containsRole(SystemsBiologyOntology.PROMOTER)|| partici.containsRole(SystemsBiologyOntology.TEMPLATE)) { if (!promoterToTranscribed.containsKey(promoter)) promoterToTranscribed.put(promoter, new LinkedList<Participation>()); promoterToTranscribed.get(promoter).add(partici); } if (!promoterToActivators.containsKey(promoter)) promoterToActivators.put(promoter, new LinkedList<Participation>()); if (!promoterToRepressors.containsKey(promoter)) promoterToRepressors.put(promoter, new LinkedList<Participation>()); if (!promoterToActivations.containsKey(promoter)) promoterToActivations.put(promoter, new LinkedList<Interaction>()); if (!promoterToRepressions.containsKey(promoter)) promoterToRepressions.put(promoter, new LinkedList<Interaction>()); } else if (isActivationInteraction(interact, moduleDef, sbolDoc)) { FunctionalComponent promoter = null; for (Participation partici : interact.getParticipations()) if (partici.containsRole(SystemsBiologyOntology.PROMOTER)|| partici.containsRole(SystemsBiologyOntology.STIMULATED)) { promoter = moduleDef.getFunctionalComponent(partici.getParticipantURI()); if (!promoterToPartici.containsKey(promoter)) promoterToPartici.put(promoter, new LinkedList<Participation>()); promoterToPartici.get(promoter).add(partici); if (!promoterToActivators.containsKey(promoter)) promoterToActivators.put(promoter, new LinkedList<Participation>()); } for (Participation partici : interact.getParticipations()) if (partici.containsRole(SystemsBiologyOntology.STIMULATOR)) promoterToActivators.get(promoter).add(partici); if (!promoterToActivations.containsKey(promoter)) promoterToActivations.put(promoter, new LinkedList<Interaction>()); promoterToActivations.get(promoter).add(interact); } else if (isRepressionInteraction(interact, moduleDef, sbolDoc)) { FunctionalComponent promoter = null; for (Participation partici : interact.getParticipations()) if (partici.containsRole(SystemsBiologyOntology.PROMOTER)|| partici.containsRole(SystemsBiologyOntology.INHIBITED)) { promoter = moduleDef.getFunctionalComponent(partici.getParticipantURI()); if (!promoterToPartici.containsKey(promoter)) promoterToPartici.put(promoter, new LinkedList<Participation>()); promoterToPartici.get(promoter).add(partici); if (!promoterToRepressors.containsKey(promoter)) promoterToRepressors.put(promoter, new LinkedList<Participation>()); } for (Participation partici : interact.getParticipations()) if (partici.containsRole(SystemsBiologyOntology.INHIBITOR)) promoterToRepressors.get(promoter).add(partici); if (!promoterToRepressions.containsKey(promoter)) promoterToRepressions.put(promoter, new LinkedList<Interaction>()); promoterToRepressions.get(promoter).add(interact); } else { generateBiochemicalRxn(interact, moduleDef, targetModel); } } for (FunctionalComponent promoter : moduleDef.getFunctionalComponents()) { if (isPromoterComponent(promoter, sbolDoc)) { if (!promoterToActivators.containsKey(promoter)) promoterToActivators.put(promoter, new LinkedList<Participation>()); if (!promoterToRepressors.containsKey(promoter)) promoterToRepressors.put(promoter, new LinkedList<Participation>()); if (!promoterToActivations.containsKey(promoter)) promoterToActivations.put(promoter, new LinkedList<Interaction>()); if (!promoterToRepressions.containsKey(promoter)) promoterToRepressions.put(promoter, new LinkedList<Interaction>()); if (!promoterToProducts.containsKey(promoter)) promoterToProducts.put(promoter, new LinkedList<Participation>()); if (!promoterToTranscribed.containsKey(promoter)) promoterToTranscribed.put(promoter, new LinkedList<Participation>()); if (!promoterToPartici.containsKey(promoter)) promoterToPartici.put(promoter, new LinkedList<Participation>()); generateProductionRxn(promoter, promoterToPartici.get(promoter), promoterToProductions.get(promoter), promoterToActivations.get(promoter), promoterToRepressions.get(promoter), promoterToProducts.get(promoter), promoterToTranscribed.get(promoter), promoterToActivators.get(promoter), promoterToRepressors.get(promoter), moduleDef, sbolDoc, targetModel); } } // for (FunctionalComponent promoter : promoterToProductions.keySet()) { // generateProductionRxn(promoter, promoterToPartici.get(promoter), promoterToProductions.get(promoter), // promoterToActivations.get(promoter), promoterToRepressions.get(promoter), promoterToProducts.get(promoter), // promoterToTranscribed.get(promoter), promoterToActivators.get(promoter), // promoterToRepressors.get(promoter), moduleDef, sbolDoc, targetModel); for (Module subModule : moduleDef.getModules()) { ModuleDefinition subModuleDef = sbolDoc.getModuleDefinition(subModule.getDefinitionURI()); BioModel subTargetModel = new BioModel(projectDirectory); if (subTargetModel.load(projectDirectory + File.separator + getDisplayID(subModuleDef) + ".xml")) { generateSubModel(projectDirectory, subModule, moduleDef, sbolDoc, subTargetModel, targetModel); } else { List<BioModel> subModels = generateSubModel(projectDirectory, subModule, moduleDef, sbolDoc, targetModel); models.addAll(subModels); } } models.add(targetModel); return models; } public static void generateSubModel(String projectDirectory, Module subModule, ModuleDefinition moduleDef, SBOLDocument sbolDoc, BioModel subTargetModel, BioModel targetModel) { ModuleDefinition subModuleDef = sbolDoc.getModuleDefinition(subModule.getDefinitionURI()); String md5 = Utility.MD5(subTargetModel.getSBMLDocument()); targetModel.addComponent(getDisplayID(subModule), getDisplayID(subModuleDef) + ".xml", subTargetModel.IsWithinCompartment(), subTargetModel.getCompartmentPorts(), -1, -1, 0, 0, md5); annotateSubModel(targetModel.getSBMLCompModel().getSubmodel(getDisplayID(subModule)), subModule); for (MapsTo mapping : subModule.getMapsTos()) if (isIOMapping(mapping, subModule, sbolDoc)) { RefinementType refinement = mapping.getRefinement(); if (refinement == RefinementType.VERIFYIDENTICAL || refinement == RefinementType.MERGE || refinement == RefinementType.USELOCAL) { generateReplacement(mapping, subModule, moduleDef, sbolDoc, subTargetModel, targetModel); } else if (refinement == RefinementType.USEREMOTE) { generateReplacedBy(mapping, subModule, moduleDef, sbolDoc, subTargetModel, targetModel); } } } public static List<BioModel> generateSubModel(String projectDirectory, Module subModule, ModuleDefinition moduleDef, SBOLDocument sbolDoc, BioModel targetModel) { ModuleDefinition subModuleDef = sbolDoc.getModuleDefinition(subModule.getDefinitionURI()); List<BioModel> subModels = generateModel(projectDirectory, subModuleDef, sbolDoc); BioModel subTargetModel = subModels.get(subModels.size()-1); generateSubModel(projectDirectory, subModule, moduleDef, sbolDoc, subTargetModel, targetModel); return subModels; } public static void generateReplacement(MapsTo mapping, Module subModule, ModuleDefinition moduleDef, SBOLDocument sbolDoc, BioModel subTargetModel, BioModel targetModel) { ModuleDefinition subModuleDef = sbolDoc.getModuleDefinition(subModule.getDefinitionURI()); FunctionalComponent remoteSpecies = subModuleDef.getFunctionalComponent(mapping.getRemoteURI()); FunctionalComponent localSpecies = moduleDef.getFunctionalComponent(mapping.getLocalURI()); //System.out.println(mapping.getRemoteURI()+" <-> " + mapping.getLocalURI()); Species localSBMLSpecies = targetModel.getSBMLDocument().getModel().getSpecies(getDisplayID(localSpecies)); Port port = subTargetModel.getPortByIdRef(getDisplayID(remoteSpecies)); if (port==null) { System.out.println("Cannot find "+getDisplayID(remoteSpecies)); //return; } Submodel subModel = targetModel.getSBMLCompModel().getSubmodel(getDisplayID(subModule)); SBMLutilities.addReplacement(localSBMLSpecies, subModel, getDisplayID(subModule), port.getId(), "(none)", new String[]{""}, new String[]{""}, new String[]{""}, new String[]{""}, false); // Annotate SBML replacment with SBOL maps-to CompSBasePlugin compSBML = SBMLutilities.getCompSBasePlugin(localSBMLSpecies); SBMLutilities.setDefaultMetaID(targetModel.getSBMLDocument(), compSBML.getReplacedElement(compSBML.getNumReplacedElements() - 1), 1); annotateReplacement(compSBML.getReplacedElement(compSBML.getNumReplacedElements() - 1), mapping); } public static void generateReplacedBy(MapsTo mapping, Module subModule, ModuleDefinition moduleDef, SBOLDocument sbolDoc, BioModel subTargetModel, BioModel targetModel) { ModuleDefinition subModuleDef = sbolDoc.getModuleDefinition(subModule.getDefinitionURI()); FunctionalComponent remoteSpecies = subModuleDef.getFunctionalComponent(mapping.getRemoteURI()); FunctionalComponent localSpecies = moduleDef.getFunctionalComponent(mapping.getLocalURI()); Species localSBMLSpecies = targetModel.getSBMLDocument().getModel().getSpecies(getDisplayID(localSpecies)); Port port = subTargetModel.getPortByIdRef(getDisplayID(remoteSpecies)); SBMLutilities.addReplacedBy(localSBMLSpecies, getDisplayID(subModule), port.getId(), new String[]{""}, new String[]{""}, new String[]{""}, new String[]{""}); // Annotate SBML replaced-by with SBOL maps-to CompSBasePlugin compSBML = SBMLutilities.getCompSBasePlugin(localSBMLSpecies); SBMLutilities.setDefaultMetaID(targetModel.getSBMLDocument(), compSBML.getReplacedBy(), 1); annotateReplacedBy(compSBML.getReplacedBy(), mapping); } public static void generateInputPort(FunctionalComponent species, BioModel targetModel) { targetModel.createDirPort(getDisplayID(species), GlobalConstants.INPUT); } public static void generateOutputPort(FunctionalComponent species, BioModel targetModel) { targetModel.createDirPort(getDisplayID(species), GlobalConstants.OUTPUT); } public static void generateSpecies(FunctionalComponent species, SBOLDocument sbolDoc, BioModel targetModel) { targetModel.createSpecies(getDisplayID(species), -1, -1); Species sbmlSpecies = targetModel.getSBMLDocument().getModel().getSpecies(getDisplayID(species)); sbmlSpecies.setBoundaryCondition(species.getDirection().equals(DirectionType.IN)); if (isDNAComponent(species,sbolDoc)) { sbmlSpecies.setSBOTerm(GlobalConstants.SBO_DNA_SEGMENT); } else if (isRNAComponent(species,sbolDoc)) { sbmlSpecies.setSBOTerm(GlobalConstants.SBO_RNA_SEGMENT); } else if (isProteinComponent(species,sbolDoc)) { sbmlSpecies.setSBOTerm(GlobalConstants.SBO_PROTEIN); } else if (isComplexComponent(species,sbolDoc)) { sbmlSpecies.setSBOTerm(GlobalConstants.SBO_NONCOVALENT_COMPLEX); } else if (isSmallMoleculeComponent(species,sbolDoc)) { sbmlSpecies.setSBOTerm(GlobalConstants.SBO_SIMPLE_CHEMICAL); } // Annotate SBML species with SBOL component and component definition annotateSpecies(sbmlSpecies, species, sbolDoc); } public static void generatePromoterSpecies(FunctionalComponent promoter, SBOLDocument sbolDoc, BioModel targetModel) { targetModel.createPromoter(getDisplayID(promoter), -1, -1, true, false, null); Species sbmlPromoter = targetModel.getSBMLDocument().getModel().getSpecies(getDisplayID(promoter)); // Annotate SBML promoter species with SBOL component and component definition ComponentDefinition compDef = sbolDoc.getComponentDefinition(promoter.getDefinitionURI()); if (compDef!=null) { annotateSpecies(sbmlPromoter, promoter, compDef, sbolDoc); } } public static void generateBiochemicalRxn(Interaction interaction, ModuleDefinition moduleDef, BioModel targetModel) { SystemsBiologyOntology sbo = new SystemsBiologyOntology(); String SBOid = ""; for (URI type : interaction.getTypes()) { if (sbo.getId(type)!=null) { SBOid = sbo.getId(type); } } HashMap<String,String> reactants = new HashMap<String,String>(); HashMap<String,String> modifiers = new HashMap<String,String>(); HashMap<String,String> products = new HashMap<String,String>(); Set<URI> reactantSBO = sbo.getDescendantURIsOf(SystemsBiologyOntology.REACTANT); reactantSBO.add(SystemsBiologyOntology.REACTANT); Set<URI> modifierSBO = sbo.getDescendantURIsOf(SystemsBiologyOntology.MODIFIER); modifierSBO.add(SystemsBiologyOntology.MODIFIER); modifierSBO.add(SystemsBiologyOntology.FUNCTIONAL_COMPARTMENT); modifierSBO.add(SystemsBiologyOntology.NEUTRAL_PARTICIPANT); modifierSBO.add(SystemsBiologyOntology.PROMOTER); Set<URI> productSBO = sbo.getDescendantURIsOf(SystemsBiologyOntology.PRODUCT); productSBO.add(SystemsBiologyOntology.PRODUCT); for (Participation participation : interaction.getParticipations()) { for (URI role : participation.getRoles()) { String id = getDisplayID(moduleDef.getFunctionalComponent(participation.getParticipantURI())); if (reactantSBO.contains(role)) { reactants.put(id,sbo.getId(role)); break; } else if (modifierSBO.contains(role)) { modifiers.put(id,sbo.getId(role)); break; } else if (productSBO.contains(role)) { products.put(id,sbo.getId(role)); break; } } } targetModel.createBiochemicalReaction(interaction.getDisplayId(),SBOid,reactants,modifiers,products); } public static void generateDegradationRxn(Interaction degradation, ModuleDefinition moduleDef, BioModel targetModel) { // Participation degraded = degradation.getParticipations().get(0); //OLD VERSION Participation degraded = null; for(Participation part : degradation.getParticipations()) { degraded = part; break; } FunctionalComponent species = moduleDef.getFunctionalComponent(degraded.getParticipantURI()); boolean onPort = (species.getDirection().equals(DirectionType.IN) || species.getDirection().equals(DirectionType.OUT)); Reaction degradationRxn = targetModel.createDegradationReaction(getDisplayID(species), -1, null, onPort, null); degradationRxn.setId(getDisplayID(degradation)); // Annotate SBML degradation reaction with SBOL interaction annotateRxn(degradationRxn, degradation); // Annotate SBML degraded reactant with SBOL participation SBMLutilities.setDefaultMetaID(targetModel.getSBMLDocument(), degradationRxn.getReactant(0), 1); annotateSpeciesReference(degradationRxn.getReactant(0), degraded); } public static void generateComplexFormationRxn(Interaction complexFormation, Participation complex, List<Participation> ligands, ModuleDefinition moduleDef, BioModel targetModel) { FunctionalComponent complexSpecies = moduleDef.getFunctionalComponent(complex.getParticipantURI()); boolean onPort = (complexSpecies.getDirection().equals(DirectionType.IN) || complexSpecies.getDirection().equals(DirectionType.OUT)); Reaction complexFormationRxn = targetModel.createComplexReaction(getDisplayID(complexSpecies), null, onPort); complexFormationRxn.setId(getDisplayID(complexFormation)); SBMLutilities.setDefaultMetaID(targetModel.getSBMLDocument(), complexFormationRxn, 1); // Annotate SBML complex formation reaction with SBOL interaction annotateRxn(complexFormationRxn, complexFormation); // Annotate SBML complex product with SBOL participation SimpleSpeciesReference complexRef = complexFormationRxn.getProductForSpecies(getDisplayID(complexSpecies)); SBMLutilities.setDefaultMetaID(targetModel.getSBMLDocument(), complexRef, 1); annotateSpeciesReference(complexRef, complex); for (Participation ligand : ligands) { FunctionalComponent ligandSpecies = moduleDef.getFunctionalComponent(ligand.getParticipantURI()); targetModel.addReactantToComplexReaction(getDisplayID(ligandSpecies), getDisplayID(complexSpecies), null, null, complexFormationRxn); // Annotate SBML ligand reactant with SBOL participation SimpleSpeciesReference ligandRef = complexFormationRxn.getReactantForSpecies(getDisplayID(ligandSpecies)); SBMLutilities.setDefaultMetaID(targetModel.getSBMLDocument(), ligandRef, 1); annotateSpeciesReference(ligandRef, ligand); } } public static void generateProductionRxn(FunctionalComponent promoter, List<Participation> partici, List<Interaction> productions, List<Interaction> activations, List<Interaction> repressions, List<Participation> products, List<Participation> transcribed, List<Participation> activators, List<Participation> repressors, ModuleDefinition moduleDef, SBOLDocument sbolDoc, BioModel targetModel) { String rxnID = ""; if (productions!=null) { for (Interaction production : productions) rxnID = rxnID + "_" + getDisplayID(production); } else { rxnID = promoter.getDisplayId() + "_Production"; } //rxnID = rxnID.substring(1); Reaction productionRxn = targetModel.createProductionReaction(getDisplayID(promoter), rxnID, null, null, null, null, null, null, false, null); // Annotate SBML production reaction with SBOL production interactions List<Interaction> productionsRegulations = new LinkedList<Interaction>(); if (productions!=null) productionsRegulations.addAll(productions); productionsRegulations.addAll(activations); productionsRegulations.addAll(repressions); if (!productionsRegulations.isEmpty()) annotateRxn(productionRxn, productionsRegulations); if (!partici.isEmpty()) annotateSpeciesReference(productionRxn.getModifier(0), partici); for (Participation activator : activators) generateActivatorReference(activator, promoter, moduleDef, productionRxn, targetModel); for (Participation repressor : repressors) generateRepressorReference(repressor, promoter, moduleDef, productionRxn, targetModel); for (Participation product : products) generateProductReference(product, promoter, moduleDef, productionRxn, targetModel); for (int i = 0; i < transcribed.size(); i++) { FunctionalComponent gene = moduleDef.getFunctionalComponent(transcribed.get(i).getParticipantURI()); FunctionalComponent protein = moduleDef.getFunctionalComponent(products.get(i).getParticipantURI()); ComponentDefinition compDef = sbolDoc.getComponentDefinition(gene.getDefinitionURI()); if (compDef!=null) { annotateSpecies(targetModel.getSBMLDocument().getModel().getSpecies(getDisplayID(protein)), compDef); } } } public static void generateActivatorReference(Participation activator, FunctionalComponent promoter, ModuleDefinition moduleDef, Reaction productionRxn, BioModel targetModel) { FunctionalComponent tf = moduleDef.getFunctionalComponent(activator.getParticipantURI()); targetModel.addActivatorToProductionReaction(getDisplayID(promoter), getDisplayID(tf), "none", productionRxn, null, null, null); // Annotate SBML activator species reference with SBOL activator participation ModifierSpeciesReference activatorRef = productionRxn.getModifierForSpecies(getDisplayID(tf)); SBMLutilities.setDefaultMetaID(targetModel.getSBMLDocument(), activatorRef, 1); annotateSpeciesReference(activatorRef, activator); } public static void generateRepressorReference(Participation repressor, FunctionalComponent promoter, ModuleDefinition moduleDef, Reaction productionRxn, BioModel targetModel) { FunctionalComponent tf = moduleDef.getFunctionalComponent(repressor.getParticipantURI()); targetModel.addRepressorToProductionReaction(getDisplayID(promoter), getDisplayID(tf), "none", productionRxn, null, null, null); // Annotate SBML repressor species reference with SBOL repressor participation ModifierSpeciesReference repressorRef = productionRxn.getModifierForSpecies(getDisplayID(tf)); SBMLutilities.setDefaultMetaID(targetModel.getSBMLDocument(), repressorRef, 1); annotateSpeciesReference(repressorRef, repressor); } public static void generateProductReference(Participation product, FunctionalComponent promoter, ModuleDefinition moduleDef, Reaction productionRxn, BioModel targetModel) { FunctionalComponent protein = moduleDef.getFunctionalComponent(product.getParticipantURI()); targetModel.addActivatorToProductionReaction(getDisplayID(promoter), "none", getDisplayID(protein), productionRxn, null, null, null); // Annotate SBML product species reference with SBOL product participation SpeciesReference productRef = productionRxn.getProductForSpecies(getDisplayID(protein)); SBMLutilities.setDefaultMetaID(targetModel.getSBMLDocument(), productRef, 1); annotateSpeciesReference(productRef, product); } public static void annotateSpecies(Species species, FunctionalComponent comp, ComponentDefinition compDef, SBOLDocument sbolDoc) { SBOLAnnotation speciesAnno = new SBOLAnnotation(species.getMetaId(), compDef.getIdentity()); speciesAnno.createSBOLElementsDescription(comp.getClass().getSimpleName(), comp.getDefinitionURI()); speciesAnno.createSBOLElementsDescription(compDef.getClass().getSimpleName(), compDef.getIdentity()); AnnotationUtility.setSBOLAnnotation(species, speciesAnno); } // Annotate SBML species with SBOL component, component definition, and any existing, annotating // DNA components or strand sign public static void annotateSpecies(Species species, FunctionalComponent comp, SBOLDocument sbolDoc) { SBOLAnnotation speciesAnno; List<URI> dnaCompIdentities = new LinkedList<URI>(); String strand = AnnotationUtility.parseSBOLAnnotation(species, dnaCompIdentities); if (strand != null && dnaCompIdentities.size() > 0) { List<URI> sbolElementIdentities = new LinkedList<URI>(); sbolElementIdentities.add(comp.getDefinitionURI()); speciesAnno = new SBOLAnnotation(species.getMetaId(), comp.getClass().getSimpleName(), sbolElementIdentities, dnaCompIdentities, strand); } else { speciesAnno = new SBOLAnnotation(species.getMetaId(), comp.getClass().getSimpleName(), comp.getDefinitionURI()); } ComponentDefinition compDef = sbolDoc.getComponentDefinition(comp.getDefinitionURI()); if (compDef!=null) { speciesAnno.createSBOLElementsDescription(compDef.getClass().getSimpleName(), compDef.getIdentity()); AnnotationUtility.setSBOLAnnotation(species, speciesAnno); } } // Annotate SBML species with SBOL DNA component and any existing, annotating SBOL elements public static void annotateSpecies(Species species, ComponentDefinition compDef) { SBOLAnnotation speciesAnno = new SBOLAnnotation(species.getMetaId(), compDef.getIdentity()); HashMap<String, List<URI>> sbolElementIdentities = new HashMap<String, List<URI>>(); AnnotationUtility.parseSBOLAnnotation(species, sbolElementIdentities); for (String className : sbolElementIdentities.keySet()) { speciesAnno.createSBOLElementsDescription(className, sbolElementIdentities.get(className)); } AnnotationUtility.setSBOLAnnotation(species, speciesAnno); } // Annotate SBML reaction with SBOL interactions public static void annotateRxn(Reaction rxn, List<Interaction> interacts) { List<URI> interactIdentities = new LinkedList<URI>(); for (Interaction interact : interacts) interactIdentities.add(interact.getIdentity()); SBOLAnnotation rxnAnno = new SBOLAnnotation(rxn.getMetaId(), interacts.get(0).getClass().getSimpleName(), interactIdentities); AnnotationUtility.setSBOLAnnotation(rxn, rxnAnno); } // Annotate SBML reaction with SBOL interaction public static void annotateRxn(Reaction rxn, Interaction interact) { SBOLAnnotation rxnAnno = new SBOLAnnotation(rxn.getMetaId(), interact.getClass().getSimpleName(), interact.getIdentity()); AnnotationUtility.setSBOLAnnotation(rxn, rxnAnno); } // Annotate SBML species reference with SBOL participation public static void annotateSpeciesReference(SimpleSpeciesReference speciesRef, Participation partici) { SBOLAnnotation speciesRefAnno = new SBOLAnnotation(speciesRef.getMetaId(), partici.getClass().getSimpleName(), partici.getParticipantURI()); AnnotationUtility.setSBOLAnnotation(speciesRef, speciesRefAnno); } // Annotate SBML species reference with SBOL participations public static void annotateSpeciesReference(SimpleSpeciesReference speciesRef, List<Participation> partici) { List<URI> particiIdentities = new LinkedList<URI>(); for (Participation p : partici) { particiIdentities.add(p.getIdentity()); } SBOLAnnotation speciesRefAnno = new SBOLAnnotation(speciesRef.getMetaId(), partici.get(0).getClass().getSimpleName(), particiIdentities); AnnotationUtility.setSBOLAnnotation(speciesRef, speciesRefAnno); } public static void annotateReplacedBy(ReplacedBy replacedBy, MapsTo mapping) { SBOLAnnotation replacedByAnno = new SBOLAnnotation(replacedBy.getMetaId(), mapping.getClass().getSimpleName(), mapping.getIdentity()); AnnotationUtility.setSBOLAnnotation(replacedBy, replacedByAnno); } public static void annotateReplacement(ReplacedElement replacement, MapsTo mapping) { SBOLAnnotation replacementAnno = new SBOLAnnotation(replacement.getMetaId(), mapping.getClass().getSimpleName(), mapping.getIdentity()); AnnotationUtility.setSBOLAnnotation(replacement, replacementAnno); } public static void annotateSubModel(Submodel subModel, Module subModule) { SBOLAnnotation subModelAnno = new SBOLAnnotation(subModel.getMetaId(), subModule.getClass().getSimpleName(), subModule.getDefinitionURI()); AnnotationUtility.setSBOLAnnotation(subModel, subModelAnno); } public static boolean isIOMapping(MapsTo mapping, Module subModule, SBOLDocument sbolDoc) { ModuleDefinition subModuleDef = sbolDoc.getModuleDefinition(subModule.getDefinitionURI()); FunctionalComponent remoteComp = subModuleDef.getFunctionalComponent(mapping.getRemoteURI()); return isInputComponent(remoteComp) || isOutputComponent(remoteComp); } public static boolean isTopDownMapping(MapsTo mapping) { RefinementType refinement = mapping.getRefinement(); return refinement == RefinementType.VERIFYIDENTICAL || refinement == RefinementType.MERGE || refinement == RefinementType.USELOCAL; } public static boolean isInputComponent(FunctionalComponent comp) { return comp.getDirection().equals(DirectionType.IN); } public static boolean isOutputComponent(FunctionalComponent comp) { return comp.getDirection().equals(DirectionType.OUT) || comp.getDirection().equals(DirectionType.INOUT); } public static boolean isDNAComponent(FunctionalComponent comp, SBOLDocument sbolDoc) { ComponentDefinition compDef = sbolDoc.getComponentDefinition(comp.getDefinitionURI()); if (compDef==null) return false; return isDNADefinition(compDef); } public static boolean isDNADefinition(ComponentDefinition compDef) { return /*compDef.containsType(ChEBI.DNA) ||*/ compDef.containsType(ComponentDefinition.DNA); } public static boolean isProteinComponent(FunctionalComponent comp, SBOLDocument sbolDoc) { ComponentDefinition compDef = sbolDoc.getComponentDefinition(comp.getDefinitionURI()); if (compDef==null) return false; return isProteinDefinition(compDef); } public static boolean isProteinDefinition(ComponentDefinition compDef) { return /*compDef.containsType(ChEBI.PROTEIN) ||*/ compDef.containsType(ComponentDefinition.PROTEIN); } public static boolean isRNAComponent(FunctionalComponent comp, SBOLDocument sbolDoc) { ComponentDefinition compDef = sbolDoc.getComponentDefinition(comp.getDefinitionURI()); if (compDef==null) return false; return isRNADefinition(compDef); } public static boolean isRNADefinition(ComponentDefinition compDef) { return compDef.containsType(ComponentDefinition.RNA); } public static boolean isPromoterComponent(FunctionalComponent comp, SBOLDocument sbolDoc) { ComponentDefinition compDef = sbolDoc.getComponentDefinition(comp.getDefinitionURI()); if (compDef==null) return false; return isPromoterDefinition(compDef); } // TODO: need to figure out better if the CD is a promoter, need to look carefully at its subComponents public static boolean isPromoterDefinition(ComponentDefinition compDef) { return isDNADefinition(compDef) /* && (compDef.containsRole(SequenceOntology.PROMOTER) || isGeneDefinition(compDef))*/; } public static boolean isGeneComponent(FunctionalComponent comp, SBOLDocument sbolDoc) { ComponentDefinition compDef = sbolDoc.getComponentDefinition(comp.getDefinitionURI()); if (compDef==null) return false; return isGeneDefinition(compDef); } public static boolean isGeneDefinition(ComponentDefinition compDef) { SequenceOntology so = new SequenceOntology(); boolean isGene = false; for (URI role : compDef.getRoles()) { if (role.equals(SequenceOntology.GENE) || so.isDescendantOf(role, SequenceOntology.GENE)) { isGene = true; break; } } return isDNADefinition(compDef) && isGene; } public static boolean isSpeciesComponent(FunctionalComponent comp, SBOLDocument sbolDoc) { ComponentDefinition compDef = sbolDoc.getComponentDefinition(comp.getDefinitionURI()); if (compDef==null) return true; return isSpeciesDefinition(compDef); } public static boolean isSpeciesDefinition(ComponentDefinition compDef) { return isComplexDefinition(compDef) || isProteinDefinition(compDef) || isRNADefinition(compDef) // || isTFDefinition(compDef) || isSmallMoleculeDefinition(compDef) || compDef.containsType(ComponentDefinition.EFFECTOR); } public static boolean isComplexComponent(FunctionalComponent comp, SBOLDocument sbolDoc) { ComponentDefinition compDef = sbolDoc.getComponentDefinition(comp.getDefinitionURI()); if (compDef==null) return false; return isComplexDefinition(compDef); } public static boolean isSmallMoleculeComponent(FunctionalComponent comp, SBOLDocument sbolDoc) { ComponentDefinition compDef = sbolDoc.getComponentDefinition(comp.getDefinitionURI()); if (compDef==null) return false; return isSmallMoleculeDefinition(compDef); } public static boolean isComplexDefinition(ComponentDefinition compDef) { return /*compDef.containsType(ChEBI.NON_COVALENTLY_BOUND_MOLECULAR_ENTITY) ||*/ compDef.containsType(ComponentDefinition.COMPLEX); } public static boolean isSmallMoleculeDefinition(ComponentDefinition compDef) { return compDef.containsType(ComponentDefinition.SMALL_MOLECULE); } // public static boolean isTFComponent(FunctionalComponent comp, SBOLDocument sbolDoc) { // ComponentDefinition compDef = sbolDoc.getComponentDefinition(comp.getDefinitionURI()); // if (compDef==null) return false; // return isTFDefinition(compDef); // public static boolean isTFDefinition(ComponentDefinition compDef) { // return (isProteinDefinition(compDef) || isComplexDefinition(compDef)) // && compDef.containsRole(MyersOntology.TF); public static boolean isDegradationInteraction(Interaction interact, ModuleDefinition moduleDef, SBOLDocument sbolDoc) { if (interact.containsType(SystemsBiologyOntology.DEGRADATION) && interact.getParticipations().size() == 1) { Participation partici = null; for(Participation part : interact.getParticipations()) { partici = part; break; } if (partici.containsRole(SystemsBiologyOntology.REACTANT)) { FunctionalComponent comp = moduleDef.getFunctionalComponent(partici.getParticipantURI()); if (isSpeciesComponent(comp, sbolDoc)) return true; } } return false; } public static boolean isComplexFormationInteraction(Interaction interact, ModuleDefinition moduleDef, SBOLDocument sbolDoc) { if (interact.containsType(SystemsBiologyOntology.NON_COVALENT_BINDING)|| interact.containsType(URI.create("http://www.biopax.org/release/biopax-level3.owl#Complex"))) { int complexCount = 0; int ligandCount = 0; for (Participation partici: interact.getParticipations()) { FunctionalComponent comp = moduleDef.getFunctionalComponent(partici.getParticipantURI()); if ((partici.containsRole(SystemsBiologyOntology.PRODUCT) || partici.containsRole(URI.create("http://identifiers.org/biomodels.sbo/SBO:0000253"))) && (isComplexComponent(comp, sbolDoc)||isSpeciesComponent(comp, sbolDoc))) complexCount++; else if ((partici.containsRole(SystemsBiologyOntology.REACTANT) || partici.containsRole(URI.create("http://identifiers.org/biomodels.sbo/SBO:0000280"))) && isSpeciesComponent(comp, sbolDoc)) ligandCount++; else return false; } if (complexCount == 1 && ligandCount > 0) return true; } return false; } public static boolean isProductionInteraction(Interaction interact, ModuleDefinition moduleDef, SBOLDocument sbolDoc) { if (interact.containsType(SystemsBiologyOntology.GENETIC_PRODUCTION) && interact.getParticipations().size() == 2) { boolean hasPromoter = false; boolean hasProduct = false; //boolean hasTranscribed = false; for (Participation partici : interact.getParticipations()) { FunctionalComponent comp = moduleDef.getFunctionalComponent(partici.getParticipantURI()); if ((partici.containsRole(SystemsBiologyOntology.PROMOTER)|| partici.containsRole(SystemsBiologyOntology.TEMPLATE)) && isPromoterComponent(comp, sbolDoc)) hasPromoter = true; else if (partici.containsRole(SystemsBiologyOntology.PRODUCT) && (isProteinComponent(comp, sbolDoc)||isRNAComponent(comp, sbolDoc))) hasProduct = true; // TRANSCRIBED else if (partici.containsRole(SystemsBiologyOntology.PROMOTER) && isGeneComponent(comp, sbolDoc)) ;//hasTranscribed = true; } if (hasPromoter && hasProduct /*&& hasTranscribed*/) return true; } return false; } public static boolean isActivationInteraction(Interaction interact, ModuleDefinition moduleDef, SBOLDocument sbolDoc) { if ((interact.containsType(SystemsBiologyOntology.GENETIC_ENHANCEMENT) || interact.containsType(SystemsBiologyOntology.STIMULATION)) && interact.getParticipations().size() == 2) { boolean hasActivated = false; boolean hasActivator = false; for (Participation partici : interact.getParticipations()) { FunctionalComponent comp = moduleDef.getFunctionalComponent(partici.getParticipantURI()); if ((partici.containsRole(SystemsBiologyOntology.PROMOTER)|| partici.containsRole(SystemsBiologyOntology.STIMULATED)) && isPromoterComponent(comp, sbolDoc)) hasActivated = true; else if (partici.containsRole(SystemsBiologyOntology.STIMULATOR) /*&& isTFComponent(comp, sbolDoc)*/) hasActivator = true; } if (hasActivated && hasActivator) return true; } return false; } public static boolean isRepressionInteraction(Interaction interact, ModuleDefinition moduleDef, SBOLDocument sbolDoc) { if ((interact.containsType(SystemsBiologyOntology.GENETIC_SUPPRESSION) || interact.containsType(SystemsBiologyOntology.INHIBITION)) && interact.getParticipations().size() == 2) { boolean hasRepressed = false; boolean hasRepressor = false; for (Participation partici : interact.getParticipations()) { FunctionalComponent comp = moduleDef.getFunctionalComponent(partici.getParticipantURI()); if ((partici.containsRole(SystemsBiologyOntology.PROMOTER) || partici.containsRole(SystemsBiologyOntology.INHIBITED)) && isPromoterComponent(comp, sbolDoc)) hasRepressed = true; else if (partici.containsRole(SystemsBiologyOntology.INHIBITOR) /*&& isTFComponent(comp, sbolDoc)*/) hasRepressor = true; } if (hasRepressed && hasRepressor) return true; } return false; } }
package com.gravity.root; import org.newdawn.slick.Music; import org.newdawn.slick.SlickException; import org.newdawn.slick.Sound; public final class GameSounds { private GameSounds() { } private static final Music gameMusic; private static final Sound sickRabbitBeat; private static final Music gameMusic2; private static final Music gameMusic3; static { try { gameMusic = new Music("./assets/Sound/Forminas.wav"); sickRabbitBeat = new Sound("./assets/Sound/yippee.wav"); gameMusic2 = new Music("./assets/Sound/Jump2.wav"); gameMusic3 = new Music("./assets/Sound/Caketown 1.wav"); } catch (SlickException e) { throw new RuntimeException(e); } } public static void playBGM() { gameMusic3.loop(); // gameMusic2.loop(); // gameMusic3.loop(); } public static void playSickRabbitBeat() { sickRabbitBeat.play(); } }
package isomorphly; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class MethodCallContextTest extends TestCase { public static Test suite() { return new TestSuite( MethodCallContextTest.class ); } public MethodCallContextTest( String testName ) { super( testName ); } public void testInvalidMethodCallContextAnnotation() { IsomorphlyEngine engine; String packageNames[] = {"test.isomorphly.dummy.invalid.four.annotations"}; engine = new IsomorphlyEngine(packageNames); try { engine.init(); } catch (IsomorphlyValidationException e) { assertFalse("isInitialized should be False", engine.isInitialized()); return; } assertTrue("It should raise an IsomorphlyValidationException", false); } public void testValidMethodCallContextAnnotation() throws IsomorphlyValidationException { IsomorphlyEngine engine; String packageNames[] = {"test.isomorphly.dummy.annotations"}; engine = new IsomorphlyEngine(packageNames); engine.init(); assertTrue("it should be true", engine.isInitialized()); } }
package ru.stqa.selenium; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.Test; import java.util.List; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertTrue; public class SearchMovieTest extends TestNgTestBase{ @Test public void testSearchMoviePositive() throws Exception { //search movie List<WebElement> foundMovies = null; List<WebElement> allMovies = null; driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); WebDriverWait wait = new WebDriverWait(driver, 10); driver.findElement(By.xpath(" try{ wait.until(ExpectedConditions.visibilityOfElementLocated( By.xpath(" } catch(Exception e){ throw new Error("Ошибка поиска фильма"); } foundMovies = driver.findElements(By.xpath(" allMovies = driver.findElements(By.xpath("//div[@class='title']")); if (foundMovies.size() != allMovies.size()) throw new Error("Поиск работает неправильно"); } @Test public void testSearchMovieNegative() throws Exception { //login LoginTest.testLogin(driver); //search movie driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS); WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(ExpectedConditions.visibilityOfElementLocated( By.xpath("//input[@id='q']"))); driver.findElement(By.xpath("//input[@id='q']")).clear(); driver.findElement(By.xpath(" wait.until(ExpectedConditions.visibilityOfElementLocated( By.xpath("//div[contains(text(),'No movies where found.')]"))); driver.findElement(By.xpath("//a[contains(text(),'Home')]")).click(); } }
package seedu.gtd.logic; import com.google.common.eventbus.Subscribe; import seedu.gtd.commons.core.EventsCenter; import seedu.gtd.commons.events.model.AddressBookChangedEvent; import seedu.gtd.commons.events.ui.JumpToListRequestEvent; import seedu.gtd.commons.events.ui.ShowHelpRequestEvent; import seedu.gtd.logic.Logic; import seedu.gtd.logic.LogicManager; import seedu.gtd.logic.commands.*; import seedu.gtd.model.AddressBook; import seedu.gtd.model.Model; import seedu.gtd.model.ModelManager; import seedu.gtd.model.ReadOnlyAddressBook; import seedu.gtd.model.task.*; import seedu.gtd.model.tag.Tag; import seedu.gtd.model.tag.UniqueTagList; import seedu.gtd.storage.StorageManager; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static seedu.gtd.commons.core.Messages.*; public class LogicManagerTest { @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; //These are for checking the correctness of the events raised private ReadOnlyAddressBook latestSavedAddressBook; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(AddressBookChangedEvent abce) { latestSavedAddressBook = new AddressBook(abce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setup() { model = new ModelManager(); String tempAddressBookFile = saveFolder.getRoot().getPath() + "TempAddressBook.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempAddressBookFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedAddressBook = new AddressBook(model.getAddressBook()); // last saved assumed to be up to date before. helpShown = false; targetedJumpIndex = -1; // non yet } @After public void teardown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() throws Exception { String invalidCommand = " "; assertCommandBehavior(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } /** * Executes the command and confirms that the result message is correct. * Both the 'address book' and the 'last shown list' are expected to be empty. * @see #assertCommandBehavior(String, String, ReadOnlyAddressBook, List) */ private void assertCommandBehavior(String inputCommand, String expectedMessage) throws Exception { assertCommandBehavior(inputCommand, expectedMessage, new AddressBook(), Collections.emptyList()); } /** * Executes the command and confirms that the result message is correct and * also confirms that the following three parts of the LogicManager object's state are as expected:<br> * - the internal address book data are same as those in the {@code expectedAddressBook} <br> * - the backing list shown by UI matches the {@code shownList} <br> * - {@code expectedAddressBook} was saved to the storage file. <br> */ private void assertCommandBehavior(String inputCommand, String expectedMessage, ReadOnlyAddressBook expectedAddressBook, List<? extends ReadOnlyTask> expectedShownList) throws Exception { //Execute the command CommandResult result = logic.execute(inputCommand); //Confirm the ui display elements should contain the right data assertEquals(expectedMessage, result.feedbackToUser); assertEquals(expectedShownList, model.getFilteredTaskList()); //Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedAddressBook, model.getAddressBook()); assertEquals(expectedAddressBook, latestSavedAddressBook); } @Test public void execute_unknownCommandWord() throws Exception { String unknownCommand = "uicfhmowqewca"; assertCommandBehavior(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() throws Exception { assertCommandBehavior("help", HelpCommand.SHOWING_HELP_MESSAGE); assertTrue(helpShown); } @Test public void execute_exit() throws Exception { assertCommandBehavior("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateTask(1)); model.addTask(helper.generateTask(2)); model.addTask(helper.generateTask(3)); assertCommandBehavior("clear", ClearCommand.MESSAGE_SUCCESS, new AddressBook(), Collections.emptyList()); } @Test public void execute_add_invalidArgsFormat() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); assertCommandBehavior( "add wrong args wrong args", expectedMessage); assertCommandBehavior( "add Valid Name 12345 d/valid@dueDate.butNoDueDatePrefix a/valid, address", expectedMessage); assertCommandBehavior( "add Valid Name d/12345 valid@address.butNoPrefix p/valid, priority", expectedMessage); assertCommandBehavior( "add Valid Name d/12345 a/valid@email.butNoAddressPrefix valid, priority", expectedMessage); } @Test public void execute_add_invalidTaskData() throws Exception { assertCommandBehavior( "add []\\[;] d/12345 a/valid@address p/valid, priority", Name.MESSAGE_NAME_CONSTRAINTS); assertCommandBehavior( "add Valid Name d/not_numbers a/valid@e.mail a/valid, address", DueDate.MESSAGE_DUEDATE_CONSTRAINTS); assertCommandBehavior( "add Valid Name d/12345 a/notAnAddress a/valid, address", Address.MESSAGE_ADDRESS_CONSTRAINTS); assertCommandBehavior( "add Valid Name d/12345 e/notAnAddress a/valid, address", Priority.MESSAGE_PRIORITY_CONSTRAINTS); assertCommandBehavior( "add Valid Name d/12345 e/valid@e.mail a/valid, address t/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); AddressBook expectedAB = new AddressBook(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandBehavior(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); AddressBook expectedAB = new AddressBook(); expectedAB.addTask(toBeAdded); // setup starting state model.addTask(toBeAdded); // task already in internal address book // execute command and verify result assertCommandBehavior( helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK, expectedAB, expectedAB.getTaskList()); } @Test public void execute_list_showsAllTasks() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); AddressBook expectedAB = helper.generateAddressBook(2); List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList(); // prepare address book state helper.addToModel(model, 2); assertCommandBehavior("list", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single task in the shown list, using visible index. * @param commandWord to test assuming it targets a single task in the last shown list based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandBehavior(commandWord , expectedMessage); //index missing assertCommandBehavior(commandWord + " +1", expectedMessage); //index should be unsigned assertCommandBehavior(commandWord + " -1", expectedMessage); //index should be unsigned assertCommandBehavior(commandWord + " 0", expectedMessage); //index cannot be 0 assertCommandBehavior(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single task in the shown list, using visible index. * @param commandWord to test assuming it targets a single task in the last shown list based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> taskList = helper.generateTaskList(2); // set AB state to 2 tasks model.resetData(new AddressBook()); for (Task p : taskList) { model.addTask(p); } assertCommandBehavior(commandWord + " 3", expectedMessage, model.getAddressBook(), taskList); } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); AddressBook expectedAB = helper.generateAddressBook(threeTasks); helper.addToModel(model, threeTasks); assertCommandBehavior("select 2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); } @Test public void execute_delete_removesCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); AddressBook expectedAB = helper.generateAddressBook(threeTasks); expectedAB.removeTask(threeTasks.get(1)); helper.addToModel(model, threeTasks); assertCommandBehavior("delete 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeTasks.get(1)), expectedAB, expectedAB.getTaskList()); } @Test public void execute_find_invalidArgsFormat() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandBehavior("find ", expectedMessage); } @Test public void execute_find_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p1 = helper.generateTaskWithName("KE Y"); Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo"); List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2); AddressBook expectedAB = helper.generateAddressBook(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2); helper.addToModel(model, fourTasks); assertCommandBehavior("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateTaskWithName("bla bla KEY bla"); Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p3 = helper.generateTaskWithName("key key"); Task p4 = helper.generateTaskWithName("KEy sduauo"); List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2); AddressBook expectedAB = helper.generateAddressBook(fourTasks); List<Task> expectedList = fourTasks; helper.addToModel(model, fourTasks); assertCommandBehavior("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia"); Task pTarget3 = helper.generateTaskWithName("key key"); Task p1 = helper.generateTaskWithName("sduauo"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3); AddressBook expectedAB = helper.generateAddressBook(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourTasks); assertCommandBehavior("find key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } /** * A utility class to generate test data. */ class TestDataHelper{ Task adam() throws Exception { Name name = new Name("Adam Brown"); DueDate privateDueDate = new DueDate("111111"); Address address = new Address("111, alpha street"); Priority privatePriority = new Priority("1"); Tag tag1 = new Tag("tag1"); Tag tag2 = new Tag("tag2"); UniqueTagList tags = new UniqueTagList(tag1, tag2); return new Task(name, privateDueDate, address, privatePriority, tags); } /** * Generates a valid task using the given seed. * Running this function with the same parameter values guarantees the returned task will have the same state. * Each unique seed will generate a unique Task object. * * @param seed used to generate the task data field values */ Task generateTask(int seed) throws Exception { return new Task( new Name("Task " + seed), new DueDate("" + Math.abs(seed)), new Address(seed + "@address"), new Priority("House of " + seed), new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1))) ); } /** Generates the correct add command based on the task given */ String generateAddCommand(Task p) { StringBuffer cmd = new StringBuffer(); cmd.append("add "); cmd.append(p.getName().toString()); cmd.append(" p/").append(p.getDueDate()); cmd.append(" e/").append(p.getAddress()); cmd.append(" a/").append(p.getPriority()); UniqueTagList tags = p.getTags(); for(Tag t: tags){ cmd.append(" t/").append(t.tagName); } return cmd.toString(); } /** * Generates an AddressBook with auto-generated tasks. */ AddressBook generateAddressBook(int numGenerated) throws Exception{ AddressBook addressBook = new AddressBook(); addToAddressBook(addressBook, numGenerated); return addressBook; } /** * Generates an AddressBook based on the list of Tasks given. */ AddressBook generateAddressBook(List<Task> tasks) throws Exception{ AddressBook addressBook = new AddressBook(); addToAddressBook(addressBook, tasks); return addressBook; } /** * Adds auto-generated Task objects to the given AddressBook * @param addressBook The AddressBook to which the Tasks will be added */ void addToAddressBook(AddressBook addressBook, int numGenerated) throws Exception{ addToAddressBook(addressBook, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given AddressBook */ void addToAddressBook(AddressBook addressBook, List<Task> tasksToAdd) throws Exception{ for(Task p: tasksToAdd){ addressBook.addTask(p); } } /** * Adds auto-generated Task objects to the given model * @param model The model to which the Tasks will be added */ void addToModel(Model model, int numGenerated) throws Exception{ addToModel(model, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given model */ void addToModel(Model model, List<Task> tasksToAdd) throws Exception{ for(Task p: tasksToAdd){ model.addTask(p); } } /** * Generates a list of Tasks based on the flags. */ List<Task> generateTaskList(int numGenerated) throws Exception{ List<Task> tasks = new ArrayList<>(); for(int i = 1; i <= numGenerated; i++){ tasks.add(generateTask(i)); } return tasks; } List<Task> generateTaskList(Task... tasks) { return Arrays.asList(tasks); } /** * Generates a Task object with given name. Other fields will have some dummy values. */ Task generateTaskWithName(String name) throws Exception { return new Task( new Name(name), new DueDate("1"), new Address("House of 1"), new Priority("1"), new UniqueTagList(new Tag("tag")) ); } } }
package org.jdesktop.swingx; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.TimeZone; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.Box; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import org.jdesktop.swingx.JXMonthView.SelectionMode; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.event.DateSelectionEvent.EventType; import org.jdesktop.swingx.test.DateSelectionReport; import org.jdesktop.swingx.test.XTestUtils; /** * Test to expose known issues with JXMonthView. * * @author Jeanette Winzenburg */ public class JXMonthViewIssues extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(JXMonthViewIssues.class .getName()); // Constants used internally; unit is milliseconds @SuppressWarnings("unused") private static final int ONE_MINUTE = 60*1000; @SuppressWarnings("unused") private static final int ONE_HOUR = 60*ONE_MINUTE; @SuppressWarnings("unused") private static final int THREE_HOURS = 3 * ONE_HOUR; @SuppressWarnings("unused") private static final int ONE_DAY = 24*ONE_HOUR; public static void main(String[] args) { // setSystemLF(true); JXMonthViewIssues test = new JXMonthViewIssues(); try { // test.runInteractiveTests(); test.runInteractiveTests("interactive.*First.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } @SuppressWarnings("unused") private Calendar calendar; /** * #681-swingx: first row overlaps days. * * Looks like a problem with the constructor taking a locale? * Default is okay (even if German), US is okay, explicit german is wrong. * Additionally: with explicit locale the linkpanel message is not taken * correctly (text missing). */ public void interactiveFirstRowOfMonthLocaleDependent() { JPanel p = new JPanel(); // default constructor p.add(new JXDatePicker()); // explicit us locale p.add(new JXDatePicker(Locale.US)); // explicit german locale p.add(new JXDatePicker(Locale.GERMAN)); showInFrame(p, "first row overlapping"); } /** * #681-swingx: first row overlaps days. * Here everything looks okay. * * @see #interactiveFirstRowOfMonthLocaleDependent() */ public void interactiveFirstRowOfMonth() { JXMonthView monthView = new JXMonthView(); calendar.set(2008, 1, 1); monthView.setSelectedDate(calendar.getTime()); showInFrame(monthView, "first row"); } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * */ public void interactiveUpdateOnTimeZone() { JPanel panel = new JPanel(); final JComboBox zoneSelector = new JComboBox(TimeZone.getAvailableIDs()); final JXDatePicker picker = new JXDatePicker(); final JXMonthView monthView = new JXMonthView(); monthView.setSelectedDate(picker.getDate()); monthView.setTraversable(true); // Synchronize the picker and selector's zones. zoneSelector.setSelectedItem(picker.getTimeZone().getID()); // Set the picker's time zone based on the selected time zone. zoneSelector.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { String zone = (String) zoneSelector.getSelectedItem(); TimeZone tz = TimeZone.getTimeZone(zone); picker.setTimeZone(tz); monthView.setTimeZone(tz); assertEquals(tz, monthView.getCalendar().getTimeZone()); } }); panel.add(zoneSelector); panel.add(picker); panel.add(monthView); JXFrame frame = showInFrame(panel, "display problems with non-default timezones"); Action assertAction = new AbstractActionExt("assert dates") { public void actionPerformed(ActionEvent e) { Calendar cal = monthView.getCalendar(); LOG.info("cal/firstDisplayed" + cal.getTime() +"/" + new Date(monthView.getFirstDisplayedDate())); } }; addAction(frame, assertAction); frame.pack(); } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * */ public void interactiveUpdateOnTimeZoneJP() { JComponent panel = Box.createVerticalBox(); final JComboBox zoneSelector = new JComboBox(TimeZone.getAvailableIDs()); final JXMonthView monthView = new JXMonthView(); monthView.setTraversable(true); // Synchronize the picker and selector's zones. zoneSelector.setSelectedItem(monthView.getTimeZone().getID()); // Set the picker's time zone based on the selected time zone. zoneSelector.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { String zone = (String) zoneSelector.getSelectedItem(); TimeZone tz = TimeZone.getTimeZone(zone); monthView.setTimeZone(tz); assertEquals(tz, monthView.getCalendar().getTimeZone()); } }); panel.add(monthView); // JPanel bar = new JPanel(); JLabel label = new JLabel("Select TimeZone:"); label.setHorizontalAlignment(JLabel.CENTER); // panel.add(label); panel.add(zoneSelector); JXFrame frame = wrapInFrame(panel, "TimeZone"); frame.pack(); frame.setVisible(true); } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * */ public void interactiveTimeZoneClearDateState() { JPanel panel = new JPanel(); final JComboBox zoneSelector = new JComboBox(TimeZone.getAvailableIDs()); final JXDatePicker picker = new JXDatePicker(); final JXMonthView monthView = new JXMonthView(); monthView.setSelectedDate(picker.getDate()); monthView.setLowerBound(XTestUtils.getStartOfToday(-10)); monthView.setUpperBound(XTestUtils.getStartOfToday(10)); monthView.setUnselectableDates(XTestUtils.getStartOfToday(2)); monthView.setFlaggedDates(new long[] {XTestUtils.getStartOfToday(4).getTime()}); monthView.setTraversable(true); // Synchronize the picker and selector's zones. zoneSelector.setSelectedItem(picker.getTimeZone().getID()); // Set the picker's time zone based on the selected time zone. zoneSelector.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { String zone = (String) zoneSelector.getSelectedItem(); TimeZone tz = TimeZone.getTimeZone(zone); picker.setTimeZone(tz); monthView.setTimeZone(tz); assertEquals(tz, monthView.getCalendar().getTimeZone()); } }); panel.add(zoneSelector); panel.add(picker); panel.add(monthView); JXFrame frame = showInFrame(panel, "clear internal date-related state"); Action assertAction = new AbstractActionExt("assert dates") { public void actionPerformed(ActionEvent e) { Calendar cal = monthView.getCalendar(); LOG.info("cal/firstDisplayed" + cal.getTime() +"/" + new Date(monthView.getFirstDisplayedDate())); } }; addAction(frame, assertAction); frame.pack(); } /** * Issue #659-swingx: lastDisplayedDate must be synched. * */ public void interactiveLastDisplayed() { final JXMonthView month = new JXMonthView(); month.setSelectionMode(SelectionMode.SINGLE_INTERVAL_SELECTION); month.setTraversable(true); Action action = new AbstractActionExt("check lastDisplayed") { public void actionPerformed(ActionEvent e) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(month.getLastDisplayedDate()); Date viewLast = cal.getTime(); cal.setTimeInMillis(month.getUI().getLastDisplayedDate()); Date uiLast = cal.getTime(); LOG.info("last(view/ui): " + viewLast + "/" + uiLast); } }; JXFrame frame = wrapInFrame(month, "default - for debugging only"); addAction(frame, action); frame.setVisible(true); } /** * characterize calendar: minimal days in first week * Different for US (1) and Europe (4) */ public void testCalendarMinimalDaysInFirstWeek() { Calendar us = Calendar.getInstance(Locale.US); assertEquals(1, us.getMinimalDaysInFirstWeek()); Calendar french = Calendar.getInstance(Locale.FRENCH); assertEquals("french/european calendar", 4, french.getMinimalDaysInFirstWeek()); fail("Revisit: monthView should respect locale setting? (need to test)"); } /** * characterize calendar: first day of week * Can be set arbitrarily. Hmmm ... when is that useful? */ public void testCalendarFirstDayOfWeek() { Calendar french = Calendar.getInstance(Locale.FRENCH); assertEquals(Calendar.MONDAY, french.getFirstDayOfWeek()); Calendar us = Calendar.getInstance(Locale.US); assertEquals(Calendar.SUNDAY, us.getFirstDayOfWeek()); // JW: when would we want that? us.setFirstDayOfWeek(Calendar.FRIDAY); assertEquals(Calendar.FRIDAY, us.getFirstDayOfWeek()); fail("Revisit: why expose setting of firstDayOfWeek? Auto-set with locale"); } /** * BasicMonthViewUI: use adjusting api in keyboard actions. * Here: test add selection action. * * TODO: this fails (unrelated to the adjusting) because the * the selectionn changing event type is DATES_SET instead of * the expected DATES_ADDED. What's wrong - expectation or type? */ public void testAdjustingSetOnAdd() { JXMonthView view = new JXMonthView(); // otherwise the add action isn't called view.setSelectionMode(SelectionMode.SINGLE_INTERVAL_SELECTION); DateSelectionReport report = new DateSelectionReport(); view.getSelectionModel().addDateSelectionListener(report); Action select = view.getActionMap().get("adjustSelectionNextDay"); select.actionPerformed(null); assertTrue("ui keyboard action must have started model adjusting", view.getSelectionModel().isAdjusting()); assertEquals(2, report.getEventCount()); // assert that the adjusting is fired before the add // only: the ui fires a set instead - bug or feature? assertEquals(EventType.DATES_ADDED, report.getLastEvent().getEventType()); } /** * Returns a timezone with a rawoffset with a different offset. * * * PENDING: this is acutally for european time, not really thought of * negative/rolling +/- problem? * * @param timeZone the timezone to start with * @param diffRawOffset the raw offset difference. * @return */ @SuppressWarnings("unused") private TimeZone getTimeZone(TimeZone timeZone, int diffRawOffset) { int offset = timeZone.getRawOffset(); int newOffset = offset < 0 ? offset + diffRawOffset : offset - diffRawOffset; String[] availableIDs = TimeZone.getAvailableIDs(newOffset); TimeZone newTimeZone = TimeZone.getTimeZone(availableIDs[0]); return newTimeZone; } @SuppressWarnings("unused") private String[] getTimeZoneIDs() { List<String> zoneIds = new ArrayList<String>(); for (int i = -12; i <= 12; i++) { String sign = i < 0 ? "-" : "+"; zoneIds.add("GMT" + sign + i); } return zoneIds.toArray(new String[zoneIds.size()]); } @Override protected void setUp() throws Exception { calendar = Calendar.getInstance(); } }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.ComponentOrientation; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.LinearGradientPaint; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.LineBorder; import org.jdesktop.swingx.color.ColorUtil; import org.jdesktop.swingx.painter.MattePainter; import org.jdesktop.test.PropertyChangeReport; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class JXTitledPanelTest extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXTitledPanelTest.class .getName()); // flag used in setup to explicitly choose LF private boolean defaultToSystemLF; @Override protected void setUp() throws Exception { super.setUp(); // make sure we have the same default for each test defaultToSystemLF = false; setSystemLF(defaultToSystemLF); } public JXTitledPanelTest() { super("JXTitledPane interactive test"); } /** * Sanity: changed ui-delegate to install the opaqueness via LookAndFeel. Doing so * is the equivalent of UIResource for primitive types. */ @Test public void testOpaque() { JXTitledPanel titledPanel = new JXTitledPanel(); boolean opaque = titledPanel.isOpaque(); titledPanel.setOpaque(!opaque); assertEquals("sanity: opaqueness toggled: ", !opaque, titledPanel.isOpaque()); titledPanel.updateUI(); assertEquals("ui must not overwrite custom setting: ", !opaque, titledPanel.isOpaque()); } /** * Issue #1063-swingx: JXTitledPanel must not overwrite custom border */ @Test public void testBorderOnLFChange() { JXTitledPanel titledPanel = new JXTitledPanel(); assertTrue("sanity: titledPanels default border must be ui-installable " + titledPanel.getBorder(), SwingXUtilities.isUIInstallable(titledPanel.getBorder())); LineBorder border = new LineBorder(titledPanel.getBackground()); titledPanel.setBorder(border); assertEquals("sanity: border set", border, titledPanel.getBorder()); titledPanel.updateUI(); assertEquals("border untouched ", border, titledPanel.getBorder()); } @Test public void testLayoutOnLFChange() { JXTitledPanel titledPanel = new JXTitledPanel(); assertNotNull(titledPanel.getContentContainer()); titledPanel.getContentContainer().setLayout(new BorderLayout()); String lf = UIManager.getLookAndFeel().getName(); setSystemLF(!defaultToSystemLF); if (lf.equals(UIManager.getLookAndFeel().getName())) { LOG.info("cannot run layoutOnLFChange - equal LF" + lf); return; } SwingUtilities.updateComponentTreeUI(titledPanel); assertTrue(titledPanel.getContentContainer().getLayout() instanceof BorderLayout); } /** * Issue ??: notifications missing on all "title"XX properties. * */ @Test public void testTitlePropertiesNotify() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); PropertyChangeReport report = new PropertyChangeReport(); panel.addPropertyChangeListener(report); Font deriveFont = panel.getTitleFont().deriveFont(27f); panel.setTitleFont(deriveFont); assertTrue("panel must notify on titleFont change", report.hasEvents("titleFont")); // TODO: Whoever owns this please fix this. The tests should run clean. // fail("JXTitledPanelTest must be updated to new api"); // panel.setTitleForeground(Color.black); // assertTrue("panel must notify on titleForeground change", report.hasEvents("titleForeground")); // panel.setTitleDarkBackground(Color.black); // assertTrue("panel must notify on titleDarkBackground change", report.hasEvents("titleDarkBackground")); // panel.setTitleLightBackground(Color.black); // assertTrue("panel must notify on titleLightBackground change", report.hasEvents("titleLightBackground")); } /** * SwingX Issue #9: missing notification on title change. * happens if a generic property change listener (== one who * wants to get all property changes) is registered. */ @Test public void testTitleNotify() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); PropertyChangeReport report = new PropertyChangeReport(); panel.addPropertyChangeListener(report); panel.setTitle("new title"); assertTrue("panel must have fired propertyChange", report.hasEvents()); } /** * SwingX Issue #9: missing notification on title change. * Notification is correct, if a named propertyChangeListener is * registered. */ @Test public void testTitleNotifyNamed() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); PropertyChangeReport report = new PropertyChangeReport(); panel.addPropertyChangeListener( "title", report); panel.setTitle("new title"); assertTrue("panel must have fired propertyChange", report.hasEvents()); } /** * incorrect propertyChangeEvent on setTitle(null). * */ @Test public void testTitleNotifyPropertyValue() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); PropertyChangeReport report = new PropertyChangeReport(); panel.addPropertyChangeListener( "title", report); panel.setTitle(null); assertTrue("panel must have fired propertyChange", report.hasEvents()); assertEquals("new property value must be equal to getTitle", panel.getTitle(), report.getLastNewValue("title")); } /** * Issue #157-swingx: JXTitledPanel not fully bidi-compliant. * * Last issue: gradient not adjusted - should be handled by * the painter. See Issue #1163-swingx */ public void interactiveGradient() { LinearGradientPaint l; GradientPaint paint = new GradientPaint(0f, 0f, Color.WHITE, 500f, 500f, Color.BLUE); JXTitledPanel panel = new JXTitledPanel("want a gradient"); panel.setTitlePainter(new MattePainter(paint, true)); // ImagePainter p = new ImagePainter(XTestUtils.loadDefaultImage()); // p.setScaleType(ScaleType.OutsideFit); // p.setHorizontalAlignment(HorizontalAlignment.LEFT); // panel.setTitlePainter(p); JXFrame frame = wrapInFrame(panel, "gradient"); addComponentOrientationToggle(frame); show(frame, 500, 500); } /** * Issue #1063-swingx: JXTitledPanel must respect custom border. */ public void interactiveBorderOnUpdateUI() { final JXTitledPanel titledPanel = new JXTitledPanel("Search"); titledPanel.setBorder(new LineBorder(titledPanel.getBackground())); showInFrame(titledPanel, "border on laf change"); } public void interactiveRToL() { String title = "starting title"; JXTitledPanel titledPane = new JXTitledPanel(title); titledPane.setLeftDecoration(new JLabel("Leading")); titledPane.setRightDecoration(new JLabel("Trailing")); // panel.getContentContainer().setLayout(new BoxLayout(panel.getContentContainer(), BoxLayout.PAGE_AXIS)); Icon icon = new ImageIcon(getClass().getResource("resources/images/wellBottom.gif")); final JLabel label = new JLabel(title); label.setIcon(icon); final JPanel panel = new JPanel(new BorderLayout()); panel.add(titledPane, BorderLayout.NORTH); panel.add(label); JXFrame frame = wrapInFrame(panel, "toggle Title"); Action toggleCO = new AbstractAction("toggle orientation") { public void actionPerformed(ActionEvent e) { ComponentOrientation current = panel.getComponentOrientation(); if (current == ComponentOrientation.LEFT_TO_RIGHT) { panel.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); label.setText("RightToLeft"); } else { panel.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); label.setText("LeftToRight"); } } }; addAction(frame, toggleCO); frame.pack(); frame.setVisible(true); } public void interactiveIconAndHtmlTest() { String title = "<html><u>starting title </u></html>"; final JXTitledPanel panel = new JXTitledPanel(title); Icon icon = new ImageIcon(getClass().getResource("resources/images/wellBottom.gif")); panel.setLeftDecoration(new JLabel(icon)); panel.getContentContainer().setLayout(new BoxLayout(panel.getContentContainer(), BoxLayout.Y_AXIS)); panel.getContentContainer().add(new JLabel(title)); JXFrame frame = wrapInFrame(panel, "toggle Title"); frame.setVisible(true); } /** * trying to set divers TitledPanel properties interactively. * can't set titlefont. */ public void interactiveTitleTest() { String title = "starting title"; final JXTitledPanel panel = new JXTitledPanel(title); panel.getContentContainer().setLayout(new BoxLayout(panel.getContentContainer(), BoxLayout.Y_AXIS)); Action toggleLight = new AbstractAction("toggle lightBackground") { public void actionPerformed(ActionEvent e) { LOG.info("JXTitledPanelText must be updated to new api"); // Color oldFont = panel.getTitleLightBackground(); // panel.setTitleLightBackground(oldFont.darker()); } }; panel.getContentContainer().add(new JButton(toggleLight)); panel.getContentContainer().setLayout(new BoxLayout(panel.getContentContainer(), BoxLayout.Y_AXIS)); Action toggleDark = new AbstractAction("toggle darkbackground") { public void actionPerformed(ActionEvent e) { LOG.info("JXTitledPanelText must be updated to new api"); // Color oldFont = panel.getTitleDarkBackground(); // panel.setTitleDarkBackground(oldFont.darker()); } }; panel.getContentContainer().add(new JButton(toggleDark)); Action toggleForeground = new AbstractAction("toggle Foreground") { public void actionPerformed(ActionEvent e) { Color oldColor = panel.getTitleForeground(); panel.setTitleForeground(oldColor.darker()); } }; panel.getContentContainer().add(new JButton(toggleForeground)); Action toggleFont = new AbstractAction("toggle Font") { public void actionPerformed(ActionEvent e) { Font oldFont = panel.getTitleFont(); System.out.println("oldfont size: " + oldFont.getSize()); panel.setTitleFont(oldFont.deriveFont(oldFont.getSize()*2.f)); } }; panel.getContentContainer().add(new JButton(toggleFont)); Action toggleTitle = new AbstractAction("toggle title") { int count = 0; public void actionPerformed(ActionEvent e) { panel.setTitle(" * " + count++ + " title"); } }; panel.getContentContainer().add(new JButton(toggleTitle)); JFrame frame = wrapInFrame(panel, "toggle Title"); frame.setVisible(true); } /** * Issue #1223-swingx: title looks ugly with rounded border. * */ public void interactiveRoundedBorder() { final JXTitledPanel titledPanel = new JXTitledPanel("Search"); titledPanel.setBorder(new RoundedBorder(50)); JXFrame frame = wrapInFrame(titledPanel, "Rounded border?"); show(frame, 400, 400); } public static class RoundedBorder implements Border { private int cornerRadius; public RoundedBorder() { this(10); } public RoundedBorder(int cornerRadius) { this.cornerRadius = cornerRadius; } public Insets getBorderInsets(Component c) { return getBorderInsets(c, new Insets(0,0,0,0)); } public Insets getBorderInsets(Component c, Insets insets) { insets.top = insets.bottom = cornerRadius/2; insets.left = insets.right = 1; return insets; } public boolean isBorderOpaque() { return false; } public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Graphics2D g2 = (Graphics2D)g.create(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Color color = Color.RED; g2.setColor(ColorUtil.setAlpha(color, 40)); g2.drawRoundRect(x, y + 2, width - 1, height - 3, cornerRadius, cornerRadius); g2.setColor(ColorUtil.setAlpha(color, 90)); g2.drawRoundRect(x, y + 1, width - 1, height - 2, cornerRadius, cornerRadius); g2.setColor(ColorUtil.setAlpha(color, 255)); g2.drawRoundRect(x, y, width - 1, height - 1, cornerRadius, cornerRadius); g2.dispose(); } } public static void main(String args[]) { JXTitledPanelTest test = new JXTitledPanelTest(); try { test.runInteractiveTests(); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } }
package org.jdesktop.swingx; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.InvocationTargetException; import java.util.Vector; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.event.TableModelEvent; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.hyperlink.AbstractHyperlinkAction; import org.jdesktop.swingx.renderer.CellContext; import org.jdesktop.swingx.renderer.CheckBoxProvider; import org.jdesktop.swingx.renderer.ComponentProvider; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.HyperlinkProvider; import org.jdesktop.swingx.renderer.LabelProvider; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.StringValues; import org.jdesktop.swingx.renderer.WrappingIconPanel; import org.jdesktop.swingx.renderer.WrappingProvider; import org.jdesktop.swingx.renderer.RendererVisualCheck.TextAreaProvider; import org.jdesktop.swingx.test.ActionMapTreeTableModel; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.swingx.test.TreeTableUtils; import org.jdesktop.swingx.treetable.AbstractMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.swingx.treetable.MutableTreeTableNode; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.swingx.treetable.TreeTableNode; import org.jdesktop.test.TableModelReport; /** * Test to exposed known issues of <code>JXTreeTable</code>. <p> * * Ideally, there would be at least one failing test method per open * issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour.<p> * * Once the issues are fixed and the corresponding methods are passing, they * should be moved over to the XXTest. * * @author Jeanette Winzenburg */ public class JXTreeTableIssues extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXTreeTableIssues.class .getName()); public static void main(String[] args) { setSystemLF(true); JXTreeTableIssues test = new JXTreeTableIssues(); try { // test.runInteractiveTests(); // test.runInteractiveTests(".*Combo.*"); // test.runInteractiveTests(".*Text.*"); // test.runInteractiveTests(".*TreeExpand.*"); test.runInteractiveTests("interactive.*EditWith.*"); // test.runInteractiveTests("interactive.*CustomColor.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #1126: combo editor is closed immediately after starting * * Happens if row is not selected at the moment of starting, okay if selected. * Inserts on pressed, removes on released. Same for 1.5 and 1.6 */ public void interactiveEditWithComboBox() { // quick for having an editable treeTableModel (non hierarchical column) TreeTableModel model = new ComponentTreeTableModel(new JXFrame()); JXTreeTable treeTable = new JXTreeTable(model); treeTable.expandAll(); JComboBox box = new JComboBox(new Object[] {200, 300, 400}); box.setEditable(true); treeTable.getColumn(3).setCellEditor(new DefaultCellEditor(box)); JXTable table = new JXTable(treeTable.getModel()); JComboBox box2 = new JComboBox(new Object[] {200, 300, 400}); box2.setEditable(true); table.getColumn(3).setCellEditor(new DefaultCellEditor(box2)); showWithScrollingInFrame(treeTable, table, "combo editor in column 3"); } /** * Custom renderer colors of Swingx DefaultTreeRenderer not respected. * (same in J/X/Tree). * * A bit surprising - probably due to the half-hearted support (backward * compatibility) of per-provider colors: they are set by the glueing * renderer to the provider's default visuals. Which is useless if the * provider is a wrapping provider - the wrappee's default visuals are unchanged. * * PENDING JW: think about complete removal. Client code should move over * completely to highlighter/renderer separation anyway. * * */ public void interactiveXRendererCustomColor() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); treeTable.addHighlighter(HighlighterFactory.createSimpleStriping()); DefaultTreeRenderer swingx = new DefaultTreeRenderer(); // in a treetable this has no effect: treetable.applyRenderer // internally resets them to the same colors as tree itself // (configured by the table's highlighters swingx.setBackground(Color.YELLOW); treeTable.setTreeCellRenderer(swingx); JTree tree = new JXTree(treeTable.getTreeTableModel()); DefaultTreeRenderer other = new DefaultTreeRenderer(); other.setBackground(Color.YELLOW); // other.setBackgroundSelectionColor(Color.RED); tree.setCellRenderer(other); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "swingx renderers - highlight complete cell"); frame.setVisible(true); } /** * Custom renderer colors of core DefaultTreeCellRenderer not respected. * This is intentional: treeTable's highlighters must rule, so the * renderer colors are used to force the treecellrenderer to use the * correct values. */ public void interactiveCoreRendererCustomColor() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); treeTable.addHighlighter(HighlighterFactory.createSimpleStriping()); DefaultTreeCellRenderer legacy = createBackgroundTreeRenderer(); // in a treetable this has no effect: treetable.applyRenderer // internally resets them to the same colors as tree itself // (configured by the table's highlighters legacy.setBackgroundNonSelectionColor(Color.YELLOW); legacy.setBackgroundSelectionColor(Color.RED); treeTable.setTreeCellRenderer(legacy); JTree tree = new JXTree(treeTable.getTreeTableModel()); DefaultTreeCellRenderer other = createBackgroundTreeRenderer(); other.setBackgroundNonSelectionColor(Color.YELLOW); other.setBackgroundSelectionColor(Color.RED); tree.setCellRenderer(other); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "legacy renderers - highlight complete cell"); frame.setVisible(true); } private DefaultTreeCellRenderer createBackgroundTreeRenderer() { DefaultTreeCellRenderer legacy = new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component comp = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (sel) { comp.setBackground(getBackgroundSelectionColor()); } else { comp.setBackground(getBackgroundNonSelectionColor()); } return comp; } }; return legacy; } /** * Issue #493-swingx: incorrect table events fired. * Issue #592-swingx: (no structureChanged table events) is a special * case of the former. * * Here: add support to prevent a structureChanged even when setting * the root. May be required if the columns are stable and the * model lazily loaded. Quick hack would be to add a clientProperty? * * @throws InvocationTargetException * @throws InterruptedException */ public void testTableEventOnSetRootNoStructureChange() throws InterruptedException, InvocationTargetException { TreeTableModel model = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); ((DefaultTreeTableModel) model).setRoot(new DefaultMutableTreeTableNode("other")); SwingUtilities.invokeAndWait(new Runnable() { public void run() { assertEquals("tableModel must have fired", 1, report.getEventCount()); assertTrue("event type must be dataChanged " + TableModelReport.printEvent(report.getLastEvent()), report.isDataChanged(report.getLastEvent())); } }); } /** * Issue #576-swingx: sluggish scrolling (?). * Here - use default model */ public void interactiveScrollAlternateHighlightDefaultModel() { final JXTable table = new JXTable(0, 6); DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root"); for (int i = 0; i < 5000; i++) { root.insert(new DefaultMutableTreeTableNode(i), i); } final JXTreeTable treeTable = new JXTreeTable(new DefaultTreeTableModel(root)); treeTable.expandAll(); table.setModel(treeTable.getModel()); final Highlighter hl = HighlighterFactory.createAlternateStriping(UIManager.getColor("Panel.background"), Color.WHITE); treeTable.setHighlighters(hl); table.setHighlighters(hl); final JXFrame frame = wrapWithScrollingInFrame(treeTable, table, "sluggish scrolling"); Action toggleHighlighter = new AbstractActionExt("toggle highlighter") { public void actionPerformed(ActionEvent e) { if (treeTable.getHighlighters().length == 0) { treeTable.addHighlighter(hl); table.addHighlighter(hl); } else { treeTable.removeHighlighter(hl); table.removeHighlighter(hl); } } }; Action scroll = new AbstractActionExt("start scroll") { public void actionPerformed(ActionEvent e) { for (int i = 0; i < table.getRowCount(); i++) { table.scrollRowToVisible(i); treeTable.scrollRowToVisible(i); } } }; addAction(frame, toggleHighlighter); addAction(frame, scroll); frame.setVisible(true); } /** * Issue #576-swingx: sluggish scrolling (?) * * Here: use FileSystemModel */ public void interactiveScrollAlternateHighlight() { final JXTable table = new JXTable(0, 6); final JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); final Highlighter hl = HighlighterFactory.createAlternateStriping(UIManager.getColor("Panel.background"), Color.WHITE); treeTable.setHighlighters(hl); table.setHighlighters(hl); final JXFrame frame = wrapWithScrollingInFrame(treeTable, table, "sluggish scrolling"); Action expand = new AbstractActionExt("start expand") { public void actionPerformed(ActionEvent e) { for (int i = 0; i < 5000; i++) { treeTable.expandRow(i); } table.setModel(treeTable.getModel()); } }; Action toggleHighlighter = new AbstractActionExt("toggle highlighter") { public void actionPerformed(ActionEvent e) { if (treeTable.getHighlighters().length == 0) { treeTable.addHighlighter(hl); table.addHighlighter(hl); } else { treeTable.removeHighlighter(hl); table.removeHighlighter(hl); } } }; Action scroll = new AbstractActionExt("start scroll") { public void actionPerformed(ActionEvent e) { for (int i = 0; i < table.getRowCount(); i++) { table.scrollRowToVisible(i); treeTable.scrollRowToVisible(i); } } }; addAction(frame, expand); addAction(frame, toggleHighlighter); addAction(frame, scroll); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update. * * Test update events after updating table. * * from tiberiu@dev.java.net * * @throws InvocationTargetException * @throws InterruptedException */ public void testTableEventUpdateOnTreeTableSetValueForRoot() throws InterruptedException, InvocationTargetException { TreeTableModel model = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final int row = 0; // sanity assertEquals("JTree", table.getValueAt(row, 0).toString()); assertTrue("root must be editable", table.getModel().isCellEditable(0, 0)); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); // doesn't fire or isn't detectable? // Problem was: model was not-editable. table.setValueAt("games", row, 0); SwingUtilities.invokeAndWait(new Runnable() { public void run() { assertEquals("tableModel must have fired", 1, report.getEventCount()); assertEquals("the event type must be update " + TableModelReport.printEvent(report.getLastEvent()) , 1, report.getUpdateEventCount()); TableModelEvent event = report.getLastUpdateEvent(); assertEquals("the updated row ", row, event.getFirstRow()); } }); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update on a recursive delete on a parent node. * * By recursive delete on a parent node it is understood that first we * remove its children and then the parent node. After each child removed * we are making an update over the parent. During this update the problem * occurs: the index row for the parent is -1 and hence it is made an update * over the row -1 (the header) and as it can be seen the preffered widths * of column header are not respected anymore and are restored to the default * preferences (all equal). * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterDeleteUpdate() { final DefaultTreeTableModel customTreeTableModel = (DefaultTreeTableModel) createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); table.getColumn("A").setPreferredWidth(100); table.getColumn("A").setMinWidth(100); table.getColumn("A").setMaxWidth(100); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing update on recursive delete"); final MutableTreeTableNode deletedNode = (MutableTreeTableNode) table.getPathForRow(6).getLastPathComponent(); MutableTreeTableNode child1 = (MutableTreeTableNode) table.getPathForRow(6+1).getLastPathComponent(); MutableTreeTableNode child2 = (MutableTreeTableNode) table.getPathForRow(6+2).getLastPathComponent(); MutableTreeTableNode child3 = (MutableTreeTableNode) table.getPathForRow(6+3).getLastPathComponent(); MutableTreeTableNode child4 = (MutableTreeTableNode) table.getPathForRow(6+4).getLastPathComponent(); final MutableTreeTableNode[] children = {child1, child2, child3, child4 }; final String[] values = {"v1", "v2", "v3", "v4"}; final ActionListener l = new ActionListener() { int count = 0; public void actionPerformed(ActionEvent e) { if (count > values.length) return; if (count == values.length) { customTreeTableModel.removeNodeFromParent(deletedNode); count++; } else { // one in each run removeChild(customTreeTableModel, deletedNode, children, values); count++; // all in one // for (int i = 0; i < values.length; i++) { // removeChild(customTreeTableModel, deletedNode, children, values); // count++; } } /** * @param customTreeTableModel * @param deletedNode * @param children * @param values */ private void removeChild(final DefaultTreeTableModel customTreeTableModel, final MutableTreeTableNode deletedNode, final MutableTreeTableNode[] children, final String[] values) { customTreeTableModel.removeNodeFromParent(children[count]); customTreeTableModel.setValueAt(values[count], deletedNode, 0); } }; Action changeValue = new AbstractAction("delete node sports recursively") { Timer timer; public void actionPerformed(ActionEvent e) { if (timer == null) { timer = new Timer(10, l); timer.start(); } else { timer.stop(); setEnabled(false); } } }; addAction(frame, changeValue); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update. Use the second child of root - first is accidentally okay. * * from tiberiu@dev.java.net * * TODO DefaultMutableTreeTableNodes do not allow value changes, so this * test will never work */ public void interactiveTreeTableModelAdapterUpdate() { TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); table.setLargeModel(true); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing update"); Action changeValue = new AbstractAction("change sports to games") { public void actionPerformed(ActionEvent e) { String newValue = "games"; table.getTreeTableModel().setValueAt(newValue, table.getPathForRow(6).getLastPathComponent(), 0); } }; addAction(frame, changeValue); Action changeRoot = new AbstractAction("change root") { public void actionPerformed(ActionEvent e) { DefaultMutableTreeTableNode newRoot = new DefaultMutableTreeTableNode("new Root"); ((DefaultTreeTableModel) table.getTreeTableModel()).setRoot(newRoot); } }; addAction(frame, changeRoot); frame.pack(); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterDelete() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing update"); Action changeValue = new AbstractAction("delete first child of sports") { public void actionPerformed(ActionEvent e) { MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(6 +1).getLastPathComponent(); ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild); } }; addAction(frame, changeValue); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterMutateSelected() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing delete expanded folder"); Action changeValue = new AbstractAction("delete selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild); } }; addAction(frame, changeValue); Action changeValue1 = new AbstractAction("insert as first child of selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeTableNode newChild = new DefaultMutableTreeTableNode("inserted"); ((DefaultTreeTableModel) customTreeTableModel) .insertNodeInto(newChild, firstChild, 0); } }; addAction(frame, changeValue1); frame.pack(); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterMutateSelectedDiscontinous() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing delete expanded folder"); Action changeValue = new AbstractAction("delete selected node + sibling") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeTableNode parent = (MutableTreeTableNode) firstChild.getParent(); MutableTreeTableNode secondNextSibling = null; int firstIndex = parent.getIndex(firstChild); if (firstIndex + 2 < parent.getChildCount()) { secondNextSibling = (MutableTreeTableNode) parent.getChildAt(firstIndex + 2); } if (secondNextSibling != null) { ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(secondNextSibling); } ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild); } }; addAction(frame, changeValue); Action changeValue1 = new AbstractAction("insert as first child of selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeTableNode newChild = new DefaultMutableTreeTableNode("inserted"); ((DefaultTreeTableModel) customTreeTableModel) .insertNodeInto(newChild, firstChild, 0); } }; addAction(frame, changeValue1); frame.pack(); frame.setVisible(true); } /** * Creates and returns a custom model from JXTree default model. The model * is of type DefaultTreeModel, allowing for easy insert/remove. * * @return */ private TreeTableModel createCustomTreeTableModelFromDefault() { JXTree tree = new JXTree(); DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel(); TreeTableModel customTreeTableModel = TreeTableUtils .convertDefaultTreeModel(treeModel); return customTreeTableModel; } /** * A TreeTableModel inheriting from DefaultTreeModel (to ease * insert/delete). */ public static class CustomTreeTableModel extends DefaultTreeTableModel { /** * @param root */ public CustomTreeTableModel(TreeTableNode root) { super(root); } @Override public int getColumnCount() { return 1; } @Override public String getColumnName(int column) { return "User Object"; } @Override public Object getValueAt(Object node, int column) { return ((DefaultMutableTreeNode) node).getUserObject(); } @Override public boolean isCellEditable(Object node, int column) { return true; } @Override public void setValueAt(Object value, Object node, int column) { ((MutableTreeTableNode) node).setUserObject(value); modelSupport.firePathChanged(new TreePath(getPathToRoot((TreeTableNode) node))); } } /** * Issue #??-swingx: hyperlink in JXTreeTable hierarchical column not * active. * */ public void interactiveTreeTableLinkRendererSimpleText() { AbstractHyperlinkAction<Object> simpleAction = new AbstractHyperlinkAction<Object>(null) { public void actionPerformed(ActionEvent e) { LOG.info("hit: " + getTarget()); } }; JXTreeTable tree = new JXTreeTable(new FileSystemModel()); HyperlinkProvider provider = new HyperlinkProvider(simpleAction); tree.getColumn(2).setCellRenderer(new DefaultTableRenderer(provider)); tree.setTreeCellRenderer(new DefaultTreeRenderer( //provider)); new WrappingProvider(provider))); // tree.setCellRenderer(new LinkRenderer(simpleAction)); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "table and simple links"); frame.setVisible(true); } /** * Issue ??-swingx: hyperlink/rollover in hierarchical column. * */ public void testTreeRendererInitialRollover() { JXTreeTable tree = new JXTreeTable(new FileSystemModel()); assertEquals(tree.isRolloverEnabled(), ((JXTree) tree.getCellRenderer(0, 0)).isRolloverEnabled()); } /** * Issue ??-swingx: hyperlink/rollover in hierarchical column. * */ public void testTreeRendererModifiedRollover() { JXTreeTable tree = new JXTreeTable(new FileSystemModel()); tree.setRolloverEnabled(!tree.isRolloverEnabled()); assertEquals(tree.isRolloverEnabled(), ((JXTree) tree.getCellRenderer(0, 0)).isRolloverEnabled()); } /** * example how to use a custom component as * renderer in tree column of TreeTable. * */ public void interactiveTreeTableCustomRenderer() { JXTreeTable tree = new JXTreeTable(new FileSystemModel()); StringValue sv = new StringValue( ){ public String getString(Object value) { return "..." + StringValues.TO_STRING.getString(value); } }; ComponentProvider<?> provider = new CheckBoxProvider(sv); // /** // * custom tooltip: show row. Note: the context is that // * of the rendering tree. No way to get at table state? // */ // @Override // protected void configureState(CellContext context) { // super.configureState(context); // rendererComponent.setToolTipText("Row: " + context.getRow()); tree.setTreeCellRenderer(new DefaultTreeRenderer(provider)); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "treetable and custom renderer"); frame.setVisible(true); } /** * Quick example to use a TextArea in the hierarchical column * of a treeTable. Not really working .. the wrap is not reliable?. * */ public void interactiveTextAreaTreeTable() { TreeTableModel model = createTreeTableModelWithLongNode(); JXTreeTable treeTable = new JXTreeTable(model); treeTable.setVisibleRowCount(5); treeTable.setRowHeight(50); treeTable.getColumnExt(0).setPreferredWidth(200); TreeCellRenderer renderer = new DefaultTreeRenderer( new WrappingProvider(new TextAreaProvider())); treeTable.setTreeCellRenderer(renderer); showWithScrollingInFrame(treeTable, "TreeTable with text wrapping"); } /** * @return */ private TreeTableModel createTreeTableModelWithLongNode() { MutableTreeTableNode root = createLongNode("some really, maybe really really long text - " + "wrappit .... where needed "); root.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); root.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); MutableTreeTableNode node = createLongNode("some really, maybe really really long text - " + "wrappit .... where needed "); node.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); root.insert(node, 0); root.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); Vector<String> ids = new Vector<String>(); ids.add("long text"); ids.add("dummy"); return new DefaultTreeTableModel(root, ids); } /** * @param string * @return */ private MutableTreeTableNode createLongNode(final String string) { AbstractMutableTreeTableNode node = new AbstractMutableTreeTableNode() { Object rnd = Math.random(); public int getColumnCount() { return 2; } public Object getValueAt(int column) { if (column == 0) { return string; } return rnd; } }; node.setUserObject(string); return node; } /** * Experiments to try and understand clipping issues: occasionally, the text * in the tree column is clipped even if there is enough space available. * * To visualize the rendering component's size we use a WrappingIconProvider * which sets a red border. * * Calling packxx might pose a problem: for non-large models the node size * is cached. In this case, packing before replacing the renderer will lead * to incorrect sizes which are hard to invalidate (no way except faking a * structural tree event? temporaryly set large model and back, plus repaint * works). * */ public void interactiveTreeTableClipIssueWrappingProvider() { final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel()); treeTable.setHorizontalScrollEnabled(true); treeTable.setColumnControlVisible(true); // BEWARE: do not pack before setting the renderer treeTable.packColumn(0, -1); StringValue format = new StringValue() { public String getString(Object value) { if (value instanceof Action) { return ((Action) value).getValue(Action.NAME) + "xx"; } return StringValues.TO_STRING.getString(value); } }; ComponentProvider<?> tableProvider = new LabelProvider(format); WrappingProvider wrappingProvider = new WrappingProvider(tableProvider) { Border redBorder = BorderFactory.createLineBorder(Color.RED); @Override public WrappingIconPanel getRendererComponent(CellContext context) { super.getRendererComponent(context); rendererComponent.setBorder(redBorder); return rendererComponent; } }; DefaultTreeRenderer treeCellRenderer = new DefaultTreeRenderer( wrappingProvider); treeTable.setTreeCellRenderer(treeCellRenderer); treeTable.setHighlighters(HighlighterFactory.createSimpleStriping()); // at this point a pack is okay, caching will get the correct values // treeTable.packColumn(0, -1); final JXTree tree = new JXTree(treeTable.getTreeTableModel()); tree.setCellRenderer(treeCellRenderer); tree.setScrollsOnExpand(false); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "treetable and tree with wrapping provider"); // revalidate doesn't help Action revalidate = new AbstractActionExt("revalidate") { public void actionPerformed(ActionEvent e) { treeTable.revalidate(); tree.revalidate(); treeTable.repaint(); } }; // hack around incorrect cached node sizes Action large = new AbstractActionExt("large-circle") { public void actionPerformed(ActionEvent e) { treeTable.setLargeModel(true); treeTable.setLargeModel(false); treeTable.repaint(); } }; addAction(frame, revalidate); addAction(frame, large); show(frame); } /** * Experiments to try and understand clipping issues: occasionally, the text * in the tree column is clipped even if there is enough space available. * * Here we don't change any renderers. */ public void interactiveTreeTableClipIssueDefaultRenderer() { final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel()); treeTable.setHorizontalScrollEnabled(true); treeTable.setRootVisible(true); treeTable.collapseAll(); treeTable.packColumn(0, -1); final JTree tree = new JTree(treeTable.getTreeTableModel()); tree.collapseRow(0); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "JXTreeTable vs. JTree: default renderer"); Action revalidate = new AbstractActionExt("revalidate") { public void actionPerformed(ActionEvent e) { treeTable.revalidate(); tree.revalidate(); } }; addAction(frame, revalidate); frame.setVisible(true); } /** * Experiments to try and understand clipping issues: occasionally, the text * in the tree column is clipped even if there is enough space available. * Here we set a custom (unchanged default) treeCellRenderer which * removes ellipses altogether. * */ public void interactiveTreeTableClipIssueCustomDefaultRenderer() { TreeCellRenderer renderer = new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); } }; final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel()); treeTable.setTreeCellRenderer(renderer); treeTable.setHorizontalScrollEnabled(true); treeTable.setRootVisible(true); treeTable.collapseAll(); treeTable.packColumn(0, -1); final JTree tree = new JTree(treeTable.getTreeTableModel()); tree.setCellRenderer(renderer); tree.collapseRow(0); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "JXTreeTable vs. JTree: custom default renderer"); Action revalidate = new AbstractActionExt("revalidate") { public void actionPerformed(ActionEvent e) { treeTable.revalidate(); tree.revalidate(); } }; addAction(frame, revalidate); frame.setVisible(true); } /** * Dirty example how to configure a custom renderer to use * treeTableModel.getValueAt(...) for showing. * */ public void interactiveTreeTableGetValueRenderer() { JXTreeTable tree = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); ComponentProvider<?> provider = new CheckBoxProvider(StringValues.TO_STRING) { @Override protected String getValueAsString(CellContext context) { // this is dirty because the design idea was to keep the renderer // unaware of the context type TreeTableModel model = (TreeTableModel) ((JXTree) context.getComponent()).getModel(); // beware: currently works only if the node is not a DefaultMutableTreeNode // otherwise the WrappingProvider tries to be smart and replaces the node // by the userObject before passing on to the wrappee! Object nodeValue = model.getValueAt(context.getValue(), 0); return formatter.getString(nodeValue); } }; tree.setTreeCellRenderer(new DefaultTreeRenderer(provider)); tree.expandAll(); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "treeTable and getValueAt renderer"); frame.setVisible(true); } /** * Issue #399-swingx: editing terminated by selecting editing row. * */ public void testSelectionKeepsEditingWithExpandsTrue() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()) { @Override public boolean isCellEditable(int row, int column) { return true; } }; // sanity: default value of expandsSelectedPath assertTrue(treeTable.getExpandsSelectedPaths()); boolean canEdit = treeTable.editCellAt(1, 2); // sanity: editing started assertTrue(canEdit); // sanity: nothing selected assertTrue(treeTable.getSelectionModel().isSelectionEmpty()); int editingRow = treeTable.getEditingRow(); treeTable.setRowSelectionInterval(editingRow, editingRow); assertEquals("after selection treeTable editing state must be unchanged", canEdit, treeTable.isEditing()); } /** * Issue #212-jdnc: reuse editor, install only once. * */ public void testReuseEditor() { //TODO rework this test, since we no longer use TreeTableModel.class // JXTreeTable treeTable = new JXTreeTable(treeTableModel); // CellEditor editor = treeTable.getDefaultEditor(TreeTableModel.class); // assertTrue(editor instanceof TreeTableCellEditor); // treeTable.setTreeTableModel(simpleTreeTableModel); // assertSame("hierarchical editor must be unchanged", editor, // treeTable.getDefaultEditor(TreeTableModel.class)); fail("#212-jdnc - must be revisited after treeTableModel overhaul"); } /** * sanity: toggling select/unselect via mouse the lead is * always painted, doing unselect via model (clear/remove path) * seems to clear the lead? * */ public void testBasicTreeLeadSelection() { JXTree tree = new JXTree(); TreePath path = tree.getPathForRow(0); tree.setSelectionPath(path); assertEquals(0, tree.getSelectionModel().getLeadSelectionRow()); assertEquals(path, tree.getLeadSelectionPath()); tree.removeSelectionPath(path); assertNotNull(tree.getLeadSelectionPath()); assertEquals(0, tree.getSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after setting selection via table. * * PENDING: this passes locally, fails on server */ public void testLeadSelectionFromTable() { JXTreeTable treeTable = prepareTreeTable(false); assertEquals(-1, treeTable.getSelectionModel().getLeadSelectionIndex()); assertEquals(-1, treeTable.getTreeSelectionModel().getLeadSelectionRow()); treeTable.setRowSelectionInterval(0, 0); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); fail("lead selection synch passes locally, fails on server"); } /** * Issue #341-swingx: missing synch of lead. * test lead after setting selection via treeSelection. * PENDING: this passes locally, fails on server * */ public void testLeadSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(false); assertEquals(-1, treeTable.getSelectionModel().getLeadSelectionIndex()); assertEquals(-1, treeTable.getTreeSelectionModel().getLeadSelectionRow()); treeTable.getTreeSelectionModel().setSelectionPath(treeTable.getPathForRow(0)); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); assertEquals(0, treeTable.getTreeSelectionModel().getLeadSelectionRow()); fail("lead selection synch passes locally, fails on server"); } /** * Issue #341-swingx: missing synch of lead. * test lead after remove selection via tree. * */ public void testLeadAfterRemoveSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.getTreeSelectionModel().removeSelectionPath( treeTable.getTreeSelectionModel().getLeadSelectionPath()); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after clear selection via table. * */ public void testLeadAfterClearSelectionFromTable() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.clearSelection(); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after clear selection via table. * */ public void testLeadAfterClearSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.getTreeSelectionModel().clearSelection(); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * creates and configures a treetable for usage in selection tests. * * @param selectFirstRow boolean to indicate if the first row should * be selected. * @return */ protected JXTreeTable prepareTreeTable(boolean selectFirstRow) { JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); treeTable.setRootVisible(true); // sanity: assert that we have at least two rows to change selection assertTrue(treeTable.getRowCount() > 1); if (selectFirstRow) { treeTable.setRowSelectionInterval(0, 0); } return treeTable; } public void testDummy() { } /** * @return */ private TreeTableModel createActionTreeModel() { JXTable table = new JXTable(10, 10); table.setHorizontalScrollEnabled(true); return new ActionMapTreeTableModel(table); } }
package com.intellij.ide.actions; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManager; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.components.JBScrollPane; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.containers.FactoryMap; import com.intellij.util.text.CharArrayUtil; import gnu.trove.TLongLongHashMap; import gnu.trove.TObjectLongHashMap; import one.util.streamex.StreamEx; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.lang.management.*; import java.util.*; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; class ActivityMonitorAction extends DumbAwareAction { private static final String[] MEANINGLESS_PREFIXES_1 = {"com.intellij.", "com.jetbrains.", "org.jetbrains.", "org.intellij."}; private static final String[] MEANINGLESS_PREFIXES_2 = {"util.", "openapi.", "plugins.", "extapi."}; @Override public void actionPerformed(@NotNull AnActionEvent e) { JTextArea textArea = new JTextArea(12, 100); textArea.setText("Loading..."); ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); CompilationMXBean jitBean = ManagementFactory.getCompilationMXBean(); ScheduledFuture<?> future = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay(new Runnable() { final TLongLongHashMap lastThreadTimes = new TLongLongHashMap(); TObjectLongHashMap<String> subsystemToSamples = new TObjectLongHashMap<>(); long lastGcTime = totalGcTime(); long lastJitTime = jitBean.getTotalCompilationTime(); long lastUiUpdate = System.currentTimeMillis(); private final Map<String, String> classToSubsystem = FactoryMap.create(className -> { String pkg = StringUtil.getPackageName(className); if (pkg.isEmpty()) pkg = className; String prefix = getMeaninglessPrefix(pkg); if (!prefix.isEmpty()) { pkg = pkg.substring(prefix.length()) + " (in " + StringUtil.trimEnd(prefix, ".") + ")"; } IdeaPluginDescriptor plugin = PluginManager.getPlugin(PluginManagerCore.getPluginByClassName(className)); return plugin != null ? "Plugin " + plugin.getName() + ": " + pkg : pkg; }); private String getMeaninglessPrefix(String qname) { String result = findPrefix(qname, MEANINGLESS_PREFIXES_1); if (!result.isEmpty()) { result += findPrefix(qname.substring(result.length()), MEANINGLESS_PREFIXES_2); } return result; } private String findPrefix(String qname, String[] prefixes) { for (String prefix : prefixes) { if (qname.startsWith(prefix)) { return prefix; } } return ""; } private long totalGcTime() { return gcBeans.stream().mapToLong(GarbageCollectorMXBean::getCollectionTime).sum(); } @NotNull private String getSubsystemName(long threadId) { if (threadId == Thread.currentThread().getId()) { return "<Activity Monitor>"; } int depth = 50; ThreadInfo info = threadBean.getThreadInfo(threadId, depth); if (info == null) return "<unidentified: thread finished>"; if (info.getThreadState() == Thread.State.RUNNABLE) { StackTraceElement[] trace = info.getStackTrace(); for (StackTraceElement element : trace) { String className = element.getClassName(); if (!isInfrastructureClass(className)) { return classToSubsystem.get(className); } } if (trace.length == depth) { return "<unidentified: too deep stack trace>"; } return "<infrastructure: " + getCommonThreadName(info) + ">"; } return "<unidentified: " + getCommonThreadName(info) + ">"; } private String getCommonThreadName(ThreadInfo info) { String name = info.getThreadName(); if (name.startsWith("AWT-EventQueue")) return "UI thread"; int numberStart = CharArrayUtil.shiftBackward(name, name.length() - 1, "0123456789/ ") + 1; if (numberStart > 0) return name.substring(0, numberStart); return name; } private boolean isInfrastructureClass(String className) { return className.startsWith("sun.") || className.startsWith("com.sun.") || className.startsWith("com.yourkit.") || className.startsWith("com.fasterxml.jackson.") || className.startsWith("net.sf.cglib.") || className.startsWith("org.jetbrains.org.objectweb.asm.") || className.startsWith("org.picocontainer.") || className.startsWith("net.jpountz.lz4.") || className.startsWith("net.n3.nanoxml.") || className.startsWith("org.apache.") || className.startsWith("one.util.streamex") || className.startsWith("java.") || className.startsWith("gnu.") || className.startsWith("kotlin.") || className.startsWith("groovy.") || className.startsWith("org.codehaus.groovy.") || className.startsWith("org.gradle.") || className.startsWith("com.google.common.") || className.startsWith("com.google.gson.") || className.startsWith("com.intellij.psi.impl.source.tree.") || className.startsWith("com.intellij.psi.util.Cached") || className.startsWith("com.intellij.openapi.extensions.") || className.startsWith("com.intellij.openapi.util.") || className.startsWith("com.intellij.util.") || className.startsWith("com.intellij.concurrency.") || className.startsWith("com.intellij.psi.stubs.") || className.startsWith("com.intellij.ide.IdeEventQueue") || className.startsWith("com.intellij.openapi.fileTypes.") || className.startsWith("com.intellij.openapi.vfs.newvfs.persistent.PersistentFS") || className.startsWith("com.intellij.openapi.vfs.newvfs.persistent.FSRecords") || className.startsWith("javax."); } @Override public void run() { for (long id : threadBean.getAllThreadIds()) { long cpuTime = threadBean.getThreadCpuTime(id); long prev = lastThreadTimes.put(id, cpuTime); if (prev != 0 && cpuTime > prev) { String subsystem = getSubsystemName(id); subsystemToSamples.put(subsystem, subsystemToSamples.get(subsystem) + cpuTime - prev); } } long now = System.currentTimeMillis(); long sinceLastUpdate = now - lastUiUpdate; if (sinceLastUpdate > 2_000) { lastUiUpdate = now; scheduleUiUpdate(sinceLastUpdate); } } private void scheduleUiUpdate(long sinceLastUpdate) { List<Pair<String, Long>> times = takeSnapshot(); String text = " %CPU Subsystem\n\n" + StreamEx.of(times) .filter(p -> p.second > 10) .sorted(Comparator.comparing((Pair<String, Long> p) -> p.second).reversed()) .limit(8) .map(p -> String.format("%5.1f %s", (double) p.second*100 / sinceLastUpdate, p.first)) .joining("\n"); ApplicationManager.getApplication().invokeLater(() -> { textArea.setText(text); textArea.setCaretPosition(0); }, ModalityState.any()); } @NotNull private List<Pair<String, Long>> takeSnapshot() { List<Pair<String, Long>> times = new ArrayList<>(); subsystemToSamples.forEachEntry((pkg, time) -> times.add(Pair.create(pkg, TimeUnit.NANOSECONDS.toMillis(time)))); subsystemToSamples.clear(); long gcTime = totalGcTime(); if (gcTime != lastGcTime) { times.add(Pair.create("<Garbage collection>", gcTime - lastGcTime)); lastGcTime = gcTime; } long jitTime = jitBean.getTotalCompilationTime(); if (jitTime != lastJitTime) { times.add(Pair.create("<JIT compiler>", jitTime - lastJitTime)); lastJitTime = jitTime; } return times; } }, 0, 20, TimeUnit.MILLISECONDS); DialogWrapper dialog = new DialogWrapper(false) { { init(); } @Override protected JComponent createCenterPanel() { JBScrollPane pane = new JBScrollPane(textArea); pane.setPreferredSize(textArea.getPreferredSize()); return pane; } @Override protected String getDimensionServiceKey() { return "Performance.Activity.Monitor"; } @NotNull @Override protected Action[] createActions() { return new Action[]{getOKAction()}; } }; dialog.setTitle("Activity Monitor"); dialog.setModal(false); Disposer.register(dialog.getDisposable(), () -> future.cancel(false)); dialog.show(); } }
package com.intellij.keymap; import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashMap; import org.jetbrains.annotations.NonNls; import java.util.Map; import java.util.Set; public abstract class KeymapsTestCase extends KeymapsTestCaseBase { // @formatter:off @NonNls @SuppressWarnings({"HardCodedStringLiteral"}) protected static final Map<String, String[][]> DEFAULT_DUPLICATES = new THashMap<String, String[][]>(){{ put("$default", new String[][] { { "ADD", "ExpandTreeNode", "Graph.ZoomIn"}, { "BACK_SPACE", "EditorBackSpace", "Images.Thumbnails.UpFolder"}, { "ENTER", "Console.Execute", "Console.TableResult.EditValue", "DirDiffMenu.SynchronizeDiff", "EditorChooseLookupItem", "EditorEnter", "Images.Thumbnails.EnterAction", "NextTemplateVariable", "SearchEverywhere.SelectItem"}, { "F2", "GotoNextError", "GuiDesigner.EditComponent", "GuiDesigner.EditGroup", "Console.TableResult.EditValue", "XDebugger.SetValue", "Arrangement.Rule.Edit", "Git.Reword.Commit", "ShelvedChanges.Rename", "ChangesView.Rename"}, { "alt ENTER", "ShowIntentionActions", "Console.TableResult.EditValue"}, { "F5", "Graph.ApplyCurrentLayout", "CopyElement"}, { "F7", "NextDiff", "StepInto"}, { "INSERT", "EditorToggleInsertState", "UsageView.Include", "DomElementsTreeView.AddElement", "DomCollectionControl.Add", "XDebugger.NewWatch"}, { "SUBTRACT", "CollapseTreeNode", "Graph.ZoomOut"}, { "TAB", "EditorChooseLookupItemReplace", "NextTemplateVariable", "NextParameter", "EditorIndentSelection", "EditorTab", "NextTemplateParameter", "ExpandLiveTemplateByTab", "BraceOrQuoteOut", "SearchEverywhere.CompleteCommand", "SearchEverywhere.NextTab"}, { "LEFT", "EditorLeft", "Vcs.Log.GoToChild"}, { "RIGHT", "EditorRight", "Vcs.Log.GoToParent"}, { "alt DOWN", "ShowContent", "MethodDown", "Arrangement.Rule.Match.Condition.Move.Down", "ShowSearchHistory"}, { "alt UP", "MethodUp", "Arrangement.Rule.Match.Condition.Move.Up"}, { "alt F1", "SelectIn", "ProjectViewChangeView"}, { "alt F6", "CommanderSyncViews", "EditPropertyValue"}, { "alt INSERT", "FileChooser.NewFolder", "Generate", "NewElement"}, { "alt LEFT", "Diff.PrevChange", "PreviousTab"}, { "alt RIGHT", "Diff.NextChange", "NextTab"}, { "control 1", "FileChooser.GotoHome", "GotoBookmark1", "DuplicatesForm.SendToLeft"}, { "control 2", "FileChooser.GotoProject", "GotoBookmark2", "DuplicatesForm.SendToRight"}, { "control 3", "GotoBookmark3", "FileChooser.GotoModule"}, { "control ADD", "ExpandAll", "ExpandExpandableComponent", "ExpandRegion"}, { "control DIVIDE", "CommentByLineComment", "Images.Editor.ActualSize", "Graph.ActualSize"}, { "control DOWN", "EditorScrollDown", "EditorLookupDown", "MethodOverloadSwitchDown", "SearchEverywhere.NavigateToNextGroup", "JupyterSelectCellBelowAction"}, { "control ENTER", "Console.Execute.Multiline", "DirDiffMenu.SynchronizeDiff.All", "EditorSplitLine", "ViewSource", "PyExecuteCellAction", "JupyterRunCellAction"}, { "control TAB", "Switcher", "Diff.FocusOppositePane"}, { "control EQUALS", "ExpandAll", "ExpandExpandableComponent", "ExpandRegion"}, { "control F5", "Refresh", "Rerun"}, { "control D", "EditorDuplicate", "Diff.ShowDiff", "CompareTwoFiles", "SendEOF", "FileChooser.GotoDesktop"}, { "control E", "RecentFiles", "SwitcherRecentEditedChangedToggleCheckBox", "Vcs.ShowMessageHistory"}, { "control L", "FindNext", "Vcs.Log.FocusTextFilter"}, { "control M", "EditorScrollToCenter", "Vcs.ShowMessageHistory"}, { "control N", "FileChooser.NewFolder", "GotoClass", "GotoChangedFile"}, { "control P", "FileChooser.TogglePathShowing", "ParameterInfo"}, { "control R", "Replace", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"}, { "control SLASH", "CommentByLineComment", "Images.Editor.ActualSize", "Graph.ActualSize"}, { "control SPACE", "CodeCompletion", "ChangesView.SetDefault"}, { "control U", "GotoSuperMethod", "CommanderSwapPanels"}, { "control UP", "EditorScrollUp", "EditorLookupUp", "MethodOverloadSwitchUp", "SearchEverywhere.NavigateToPrevGroup", "JupyterSelectCellAboveAction"}, { "control SUBTRACT", "CollapseAll", "CollapseExpandableComponent", "CollapseRegion"}, { "control alt A", "ChangesView.AddUnversioned", "Diagram.DeselectAll"}, { "control alt K", "Git.Commit.And.Push.Executor", "Hg.Commit.And.Push.Executor"}, { "control alt E", "PerforceDirect.Edit", "Console.History.Browse"}, { "control alt DOWN", "NextOccurence", "Console.TableResult.NextPage"}, { "control alt G", "DatabaseView.SqlGenerator", "org.jetbrains.plugins.ruby.rails.actions.generators.GeneratorsPopupAction", "Mvc.RunTarget"}, { "control alt R", "org.jetbrains.plugins.ruby.tasks.rake.actions.RakeTasksPopupAction", "Django.RunManageTaskAction"}, { "control alt UP", "PreviousOccurence", "Console.TableResult.PreviousPage"}, { "control alt N", "Inline", "Console.TableResult.SetNull"}, { "control alt M", "ExtractMethod", "TodoViewGroupByShowModules", "ChangesView.GroupBy.Module"}, { "control alt P", "ChangesView.GroupBy.Directory", "IntroduceParameter", "TodoViewGroupByShowPackages", "ServiceView.GroupByServiceGroups"}, { "ctrl alt C", "IntroduceConstant", "TodoViewGroupByFlattenPackage"}, { "ctrl alt U", "ShowUmlDiagramPopup", "ChangesView.UnshelveSilently"}, { "ctrl alt F", "IntroduceField", "ShowFilterPopup"}, { "control MINUS", "CollapseAll", "CollapseExpandableComponent", "CollapseRegion"}, { "control PERIOD", "EditorChooseLookupItemDot", "CollapseSelection"}, { "shift DELETE", "$Cut", "Maven.Uml.Exclude"}, { "shift ENTER", "CollapseExpandableComponent", "Console.TableResult.EditValueMaximized", "DatabaseView.PropertiesAction", "EditorStartNewLine", "ExpandExpandableComponent", "OpenElementInNewWindow", "JupyterRunCellSelectBelowAction"}, { "shift F4", "Debugger.EditTypeSource", "EditSourceInNewWindow"}, { "shift F6", "RenameElement", "Git.Reword.Commit", "ShelvedChanges.Rename", "ChangesView.Rename"}, { "shift F7", "PreviousDiff", "SmartStepInto"}, { "shift TAB", "PreviousTemplateVariable", "PrevParameter", "EditorUnindentSelection", "PrevTemplateParameter", "SearchEverywhere.PrevTab"}, { "shift alt ENTER", "Console.TableResult.EditValueMaximized", "JupyterDebugAction"}, { "shift alt LEFT", "Diff.ApplyRightSide", "PreviousEditorTab"}, { "shift alt RIGHT", "Diff.ApplyLeftSide", "NextEditorTab"}, { "shift alt A", "JupyterInsertCellAboveAction", "VcsHistory.ShowAllAffected"}, { "shift alt B", "JupyterInsertCellBelowAction", "tasks.open.in.browser"}, { "shift alt L", "org.jetbrains.plugins.ruby.console.LoadInIrbConsoleAction", "context.load"}, { "shift alt M", "ChangesView.Move", "Vcs.MoveChangedLinesToChangelist"}, { "shift ctrl C", "CopyPaths", "DatabaseView.CopyDdlAction"}, { "shift control D", "TagDocumentationNavigation", "Diff.ShowSettingsPopup", "Uml.ShowDiff", "Console.TableResult.CompareCells"}, { "shift control DOWN", "ResizeToolWindowDown", "MoveStatementDown"}, { "shift control ENTER", "EditorCompleteStatement", "Console.Jpa.GenerateSql"}, { "shift control F10", "Console.Open", "RunClass", "RunTargetAction"}, { "shift control F8", "ViewBreakpoints", "EditBreakpoint"}, { "shift control G", "ClassTemplateNavigation", "GoToClass"}, { "shift control H", "ChangesView.ShelveSilently", "MethodHierarchy"}, { "shift control LEFT", "EditorPreviousWordWithSelection", "ResizeToolWindowLeft"}, { "shift control RIGHT", "EditorNextWordWithSelection", "ResizeToolWindowRight"}, { "shift control T", "GotoTest", "RunDashboard.ShowConfigurations"}, { "shift control UP", "ResizeToolWindowUp", "MoveStatementUp"}, { "shift control U", "ShelveChanges.UnshelveWithDialog", "EditorToggleCase"}, { "shift control alt D", "UML.ShowChanges", "Console.TableResult.CloneColumn"}, { "shift control alt ENTER", "Console.Jpa.GenerateDDL", "Console.Transaction.Commit", "JupyterRunAllAction"}, { "shift ctrl alt P", "IntroduceFunctionalParameter", "ReformatWithPrettierAction"}, { "control alt Z", "Vcs.RollbackChangedLines", "ChangesView.Revert"}, { "shift control TAB", "Switcher", "Diff.FocusOppositePaneAndScroll"}, { "ctrl alt ENTER", "EditorStartNewLineBefore", "QuickActionPopup"}, { "alt button1", "EditorCreateRectangularSelectionOnMouseDrag", "QuickEvaluateExpression"}, { "button2", "EditorPasteFromX11", "GotoDeclaration", "EditorCreateRectangularSelectionOnMouseDrag"}, { "PAGE_DOWN", "EditorPageDown", "SearchEverywhere.NavigateToNextGroup"}, { "PAGE_UP", "EditorPageUp", "SearchEverywhere.NavigateToPrevGroup"}, { "ESCAPE", "EditorEscape", "FocusEditor", "Terminal.SwitchFocusToEditor"}, { "shift ctrl alt LEFT", "MoveElementLeft", "Terminal.MoveToolWindowTabLeft"}, { "shift ctrl alt RIGHT", "MoveElementRight", "Terminal.MoveToolWindowTabRight"}, }); put("Mac OS X 10.5+", new String[][] { { "BACK_SPACE", "$Delete", "EditorBackSpace", "Images.Thumbnails.UpFolder"}, { "shift BACK_SPACE", "EditorBackSpace", "UsageView.Include"}, { "meta BACK_SPACE", "EditorDeleteLine", "$Delete"}, { "control LEFT", "Diff.PrevChange", "PreviousTab"}, { "control RIGHT", "Diff.NextChange", "NextTab"}, { "control DOWN", "EditorLookupDown", "JupyterSelectCellBelowAction", "MethodDown", "ShowContent"}, { "control UP", "EditorLookupUp", "JupyterSelectCellAboveAction", "MethodUp"}, { "control TAB", "Switcher", "Diff.FocusOppositePane"}, { "control M", "ChangesView.GroupBy.Module", "EditorMatchBrace", "Vcs.ShowMessageHistory", "TodoViewGroupByShowModules"}, { "control O", "ExportToTextFile", "OverrideMethods"}, { "control P", "ChangesView.GroupBy.Directory", "EditorUp", "TodoViewGroupByShowPackages", "ServiceView.GroupByServiceGroups"}, { "ctrl F", "EditorRight", "TodoViewGroupByFlattenPackage"}, { "control ENTER", "Generate", "JupyterRunCellAction", "NewElement", "PyExecuteCellAction"}, { "control SPACE", "CodeCompletion", "ChangesView.SetDefault"}, { "shift control TAB", "Switcher", "Diff.FocusOppositePaneAndScroll"}, { "meta L", "Vcs.Log.FocusTextFilter", "GotoLine"}, { "meta R", "Refresh", "Rerun", "Replace", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"}, { "meta 1", "ActivateProjectToolWindow", "FileChooser.GotoHome", "DuplicatesForm.SendToLeft"}, { "meta 2", "ActivateFavoritesToolWindow", "FileChooser.GotoProject", "DuplicatesForm.SendToRight"}, { "meta 3", "ActivateFindToolWindow", "FileChooser.GotoModule"}, { "meta N", "FileChooser.NewFolder", "Generate", "NewElement"}, { "meta O", "GotoClass", "GotoChangedFile"}, { "shift ctrl LEFT", "Diff.ApplyRightSide", "PreviousEditorTab"}, { "shift ctrl RIGHT", "Diff.ApplyLeftSide", "NextEditorTab"}, { "shift meta G", "ClassTemplateNavigation", "GoToClass", "FindPrevious"}, { "shift meta M", "ChangesView.Move", "Vcs.MoveChangedLinesToChangelist"}, { "shift meta LEFT", "EditorLineStartWithSelection", "ResizeToolWindowLeft"}, { "shift meta RIGHT", "EditorLineEndWithSelection", "ResizeToolWindowRight"}, { "shift meta CLOSE_BRACKET", "Diff.NextChange", "NextTab"}, { "shift meta OPEN_BRACKET", "Diff.PrevChange", "PreviousTab"}, { "alt R", "Django.RunManageTaskAction", "org.jetbrains.plugins.ruby.tasks.rake.actions.RakeTasksPopupAction"}, { "alt DOWN", "EditorUnSelectWord", "Arrangement.Rule.Match.Condition.Move.Down", "MethodOverloadSwitchDown", "ShowSearchHistory"}, { "alt UP", "EditorSelectWord", "Arrangement.Rule.Match.Condition.Move.Up", "MethodOverloadSwitchUp"}, { "meta UP", "ShowNavBar", "SearchEverywhere.NavigateToPrevGroup"}, { "meta DOWN", "EditSource", "SearchEverywhere.NavigateToNextGroup"}, }); put("Mac OS X", new String[][] { { "BACK_SPACE", "$Delete", "EditorBackSpace", "Images.Thumbnails.UpFolder"}, { "control LEFT", "Diff.PrevChange", "PreviousTab"}, { "control RIGHT", "Diff.NextChange", "NextTab"}, { "control DOWN", "EditorLookupDown", "JupyterSelectCellBelowAction", "MethodDown", "ShowContent"}, { "control UP", "EditorLookupUp", "JupyterSelectCellAboveAction", "MethodUp"}, { "control ENTER", "Generate", "JupyterRunCellAction", "NewElement", "PyExecuteCellAction"}, { "control F5", "Refresh", "Rerun"}, { "control TAB", "Switcher", "Diff.FocusOppositePane"}, { "control N", "Generate", "NewElement"}, { "control M", "ChangesView.GroupBy.Module", "TodoViewGroupByShowModules", "Vcs.ShowMessageHistory"}, { "control P", "ChangesView.GroupBy.Directory", "TodoViewGroupByShowPackages", "ServiceView.GroupByServiceGroups"}, { "shift control TAB", "Switcher", "Diff.FocusOppositePaneAndScroll"}, { "meta 1", "ActivateProjectToolWindow", "FileChooser.GotoHome", "DuplicatesForm.SendToLeft"}, { "meta 2", "ActivateFavoritesToolWindow", "FileChooser.GotoProject", "DuplicatesForm.SendToRight"}, { "meta 3", "ActivateFindToolWindow", "FileChooser.GotoModule"}, { "shift ctrl LEFT", "Diff.ApplyRightSide", "PreviousEditorTab"}, { "shift ctrl RIGHT", "Diff.ApplyLeftSide", "NextEditorTab"}, { "shift meta LEFT", "EditorLineStartWithSelection", "ResizeToolWindowLeft"}, { "shift meta RIGHT", "EditorLineEndWithSelection", "ResizeToolWindowRight"}, { "alt R", "Django.RunManageTaskAction", "org.jetbrains.plugins.ruby.tasks.rake.actions.RakeTasksPopupAction"}, { "ctrl SPACE", "ChangesView.SetDefault", "CodeCompletion"} }); put("Emacs", new String[][] { { "TAB", "EditorChooseLookupItemReplace", "NextTemplateVariable", "NextParameter", "EditorIndentSelection", "EmacsStyleIndent", "NextTemplateParameter", "ExpandLiveTemplateByTab", "BraceOrQuoteOut", "SearchEverywhere.CompleteCommand", "SearchEverywhere.NextTab"}, { "alt SLASH", "CodeCompletion", "HippieCompletion"}, { "control D", "$Delete", "Diff.ShowDiff", "CompareTwoFiles", "SendEOF", "FileChooser.GotoDesktop"}, { "control K", "EditorCutLineEnd", "CheckinProject"}, { "control L", "EditorScrollToCenter", "Vcs.Log.FocusTextFilter"}, { "control M", "EditorEnter", "EditorChooseLookupItem", "NextTemplateVariable", "Console.Execute"}, { "control N", "EditorDown", "FileChooser.NewFolder"}, { "control P", "EditorUp", "FileChooser.TogglePathShowing"}, { "control R", "org.jetbrains.plugins.ruby.rails.console.ReloadSources", "FindPrevious"}, { "control SLASH", "$Undo", "Images.Editor.ActualSize", "Graph.ActualSize"}, { "control SPACE", "EditorToggleStickySelection", "ChangesView.SetDefault"}, { "control X,N", "Diff.NextChange", "NextTab"}, { "control X,P", "Diff.PrevChange", "PreviousTab"}, { "control UP", "EditorBackwardParagraph", "EditorLookupUp", "JupyterSelectCellAboveAction", "MethodOverloadSwitchUp", "SearchEverywhere.NavigateToPrevGroup"}, { "control DOWN", "EditorForwardParagraph", "EditorLookupDown", "JupyterSelectCellBelowAction", "MethodOverloadSwitchDown", "SearchEverywhere.NavigateToNextGroup"}, { "control alt A", "MethodUp", "ChangesView.AddUnversioned", "Diagram.DeselectAll"}, { "control alt E", "MethodDown", "PerforceDirect.Edit", "Console.History.Browse"}, { "control alt G", "GotoDeclaration", "org.jetbrains.plugins.ruby.rails.actions.generators.GeneratorsPopupAction", "Mvc.RunTarget"}, { "control alt S", "ShowSettings", "Find"}, { "shift alt S", "FindUsages", "context.save"}, { "shift alt G", "GotoChangedFile", "GotoClass", "hg4idea.QGotoFromPatches"}, { "shift alt P", "ParameterInfo", "hg4idea.QPushAction"}, { "shift control X", SECOND_STROKE, "com.jetbrains.php.framework.FrameworkRunConsoleAction"}, { "shift ctrl DOWN", "EditorForwardParagraphWithSelection", "ResizeToolWindowDown"}, { "shift ctrl UP", "EditorBackwardParagraphWithSelection", "ResizeToolWindowUp"}, { "ESCAPE", SECOND_STROKE, "FocusEditor", "Terminal.SwitchFocusToEditor"}, }); put("Visual Studio", new String[][] { { "F5", "Resume", "Graph.ApplyCurrentLayout"}, { "F7", "NextDiff", "CompileDirty"}, { "alt F2", "ShowBookmarks", "WebOpenInAction"}, { "alt F8", "ReformatCode", "ForceStepInto", "EvaluateExpression"}, { "control COMMA", "GotoClass", "GotoChangedFile"}, { "control F1", "ExternalJavaDoc", "ShowErrorDescription"}, { "control F10", "RunToCursor", "UpdateRunningApplication"}, { "control N", "FileChooser.NewFolder", "Generate", }, { "control P", "FileChooser.TogglePathShowing", "Print"}, { "control alt F", "ReformatCode", "IntroduceField", "ShowFilterPopup"}, { "shift F12", "RestoreDefaultLayout", "FindUsagesInFile"}, { "shift F2", "GotoPreviousError", "GotoDeclaration"}, { "shift control F7", "FindUsagesInFile", "HighlightUsagesInFile"}, { "shift control I", "ImplementMethods", "QuickImplementations"}, { "alt F9", "ViewBreakpoints", "EditBreakpoint"}, { "alt MULTIPLY", "ShowExecutionPoint", "Images.Thumbnails.ToggleRecursive"}, { "shift alt U", "GotoPrevElementUnderCaretUsage", "ToggleCamelSnakeCase"}, { "shift alt D", "GotoNextElementUnderCaretUsage", "hg4idea.QFold"} }); put("Default for XWin", new String[][] { { "shift ctrl alt button1", "EditorAddRectangularSelectionOnMouseDrag", "QuickEvaluateExpression"}, }); put("Default for GNOME", new String[][] { { "shift alt 1", "SelectIn", "ProjectViewChangeView"}, { "shift alt 7", "IDEtalk.SearchUserHistory", "FindUsages"}, { "shift alt LEFT", "PreviousEditorTab", "Back", "Diff.ApplyRightSide"}, { "shift alt RIGHT", "NextEditorTab", "Forward", "Diff.ApplyLeftSide"}, }); put("Default for KDE", new String[][] { { "control 1", "FileChooser.GotoHome", "ShowErrorDescription", "DuplicatesForm.SendToLeft"}, { "control 2", "FileChooser.GotoProject", "Stop", "DuplicatesForm.SendToRight"}, { "control 3", "FindWordAtCaret", "FileChooser.GotoModule"}, { "control 5", "Refresh", "Rerun"}, { "shift alt 1", "SelectIn", "ProjectViewChangeView"}, { "shift alt 7", "IDEtalk.SearchUserHistory", "FindUsages"}, { "shift alt L", "ReformatCode", "org.jetbrains.plugins.ruby.console.LoadInIrbConsoleAction", "context.load"}, }); put("Eclipse", new String[][] { { "F2", "Console.TableResult.EditValue", "QuickJavaDoc", "XDebugger.SetValue", "Arrangement.Rule.Edit"}, { "F5", "Graph.ApplyCurrentLayout", "StepInto"}, { "alt DOWN", "ShowContent", "MoveStatementDown", "Arrangement.Rule.Match.Condition.Move.Down", "ShowSearchHistory"}, { "alt UP", "MoveStatementUp", "Arrangement.Rule.Match.Condition.Move.Up"}, { "alt HOME", "ViewNavigationBar", "ShowNavBar"}, { "control F10", "ShowPopupMenu", "UpdateRunningApplication"}, { "control D", "EditorDeleteLine", "Diff.ShowDiff", "CompareTwoFiles", "SendEOF", "FileChooser.GotoDesktop"}, { "control L", "Vcs.Log.FocusTextFilter", "GotoLine"}, { "control N", "ShowPopupMenu", "FileChooser.NewFolder"}, { "control P", "FileChooser.TogglePathShowing", "Print"}, { "control R", "RunToCursor", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"}, { "control U", "EvaluateExpression", "CommanderSwapPanels"}, { "control PAGE_DOWN", "Diff.NextChange", "NextTab"}, { "control PAGE_UP", "Diff.PrevChange", "PreviousTab"}, { "control F6", "Diff.NextChange", "NextTab"}, { "control alt DOWN", "Console.TableResult.NextPage", "EditorDuplicateLines"}, { "control alt E", "Console.History.Browse", "ExecuteInPyConsoleAction", "PerforceDirect.Edit"}, { "control alt LEFT", "Diff.NextChange", "NextTab"}, { "control alt RIGHT", "Diff.PrevChange", "PreviousTab"}, { "shift alt D", "hg4idea.QFold", "Debug"}, { "shift alt G", "RerunTests", "hg4idea.QGotoFromPatches"}, { "shift alt L", "IntroduceVariable", "org.jetbrains.plugins.ruby.console.LoadInIrbConsoleAction", "context.load"}, { "shift alt P", "hg4idea.QPushAction", "ImplementMethods"}, { "shift alt R", "RenameElement", "Git.Reword.Commit", "ShelvedChanges.Rename", "ChangesView.Rename"}, { "shift alt S", "ShowPopupMenu", "context.save"}, { "shift alt T", "ShowPopupMenu", "tasks.switch"}, { "shift control DOWN", "ResizeToolWindowDown", "MethodDown"}, { "shift control E", "RecentLocations", "EditSource"}, { "shift control F6", "ChangeTypeSignature", "Diff.PrevChange", "PreviousTab"}, { "shift control F11", "ToggleBookmark", "FocusTracer"}, { "shift control G", "FindUsagesInFile", "ClassTemplateNavigation", "GoToClass"}, { "shift control I", "QuickImplementations", "XDebugger.Inspect"}, { "shift control UP", "ResizeToolWindowUp", "MethodUp"}, { "shift control K", "Vcs.Push", "FindPrevious"}, { "shift control X", "EditorToggleCase", "com.jetbrains.php.framework.FrameworkRunConsoleAction"}, { "shift control T", "GotoClass", "GotoChangedFile"}, { "shift ctrl alt RIGHT", "PreviousEditorTab", "Terminal.MoveToolWindowTabRight"}, { "shift ctrl alt LEFT", "NextEditorTab", "Terminal.MoveToolWindowTabLeft"}, }); put("NetBeans 6.5", new String[][] { { "F4", "RunToCursor", "EditSource"}, { "F5", "Debugger.ResumeThread", "Resume", "Graph.ApplyCurrentLayout"}, { "alt DOWN", "GotoNextElementUnderCaretUsage", "ShowContent", "Arrangement.Rule.Match.Condition.Move.Down", "ShowSearchHistory"}, { "alt UP", "GotoPrevElementUnderCaretUsage", "Arrangement.Rule.Match.Condition.Move.Up"}, { "control 1", "ActivateProjectToolWindow", "DuplicatesForm.SendToLeft"}, { "control 2", "ActivateProjectToolWindow", "FileChooser.GotoProject", "DuplicatesForm.SendToRight"}, { "control 3", "ActivateProjectToolWindow", "FileChooser.GotoModule"}, { "control BACK_SPACE", "EditorDeleteToWordStart", "ToggleDockMode"}, { "control DIVIDE", "CollapseRegionRecursively", "Images.Editor.ActualSize", "Graph.ActualSize"}, { "control M", "Vcs.ShowMessageHistory", "Move"}, { "control N", "NewElement", "FileChooser.NewFolder"}, { "control R", "RenameElement", "org.jetbrains.plugins.ruby.rails.console.ReloadSources", "Git.Reword.Commit", "ShelvedChanges.Rename", "ChangesView.Rename"}, { "control U", SECOND_STROKE, "CommanderSwapPanels"}, { "control O", "GotoClass", "GotoChangedFile"}, { "control PERIOD", "GotoNextError", "EditorChooseLookupItemDot"}, { "control PAGE_DOWN", "Diff.NextChange", "NextTab"}, { "control PAGE_UP", "Diff.PrevChange", "PreviousTab"}, { "control alt DOWN", "MethodDown", "NextOccurence", "Console.TableResult.NextPage"}, { "control alt UP", "MethodUp", "PreviousOccurence", "Console.TableResult.PreviousPage"}, { "control alt shift P", "Print", "ReformatWithPrettierAction"}, { "shift F4", "RecentFiles", "SwitcherRecentEditedChangedToggleCheckBox", "Debugger.EditTypeSource", "Vcs.ShowMessageHistory", "EditSourceInNewWindow"}, { "shift alt F9", "ChooseDebugConfiguration", "ValidateXml", "ValidateJsp"}, { "shift alt D", "ToggleFloatingMode", "hg4idea.QFold"}, { "shift control DOWN", "EditorDuplicate", "ResizeToolWindowDown", }, { "shift control F7", "HighlightUsagesInFile", "XDebugger.NewWatch"}, { "shift control UP", "EditorDuplicate", "ResizeToolWindowUp", }, { "shift ctrl C", "CommentByLineComment", "DatabaseView.CopyDdlAction"}, { "shift control H", "ChangesView.ShelveSilently", "ReplaceInPath"}, { "shift control K", "HippieCompletion", "Vcs.Push"}, { "control alt E", "Console.History.Browse", "ExecuteInPyConsoleAction", "PerforceDirect.Edit"}, }); put("Eclipse (Mac OS X)", new String[][] { { "meta BACK_SPACE", "EditorDeleteToWordStart", "$Delete"}, { "F2", "Console.TableResult.EditValue", "QuickJavaDoc", "XDebugger.SetValue", "Arrangement.Rule.Edit", "Git.Reword.Commit", "ShelvedChanges.Rename", "ChangesView.Rename"}, { "F3", "GotoDeclaration", "EditSource"}, { "F5", "StepInto", "Graph.ApplyCurrentLayout"}, { "alt DOWN", "MoveStatementDown", "Arrangement.Rule.Match.Condition.Move.Down", "MethodOverloadSwitchDown", "ShowSearchHistory"}, { "alt UP", "MoveStatementUp", "Arrangement.Rule.Match.Condition.Move.Up", "MethodOverloadSwitchUp"}, { "control PERIOD", "EditorChooseLookupItemDot", "HippieCompletion"}, { "meta 1", "FileChooser.GotoHome", "ShowIntentionActions", "DuplicatesForm.SendToLeft"}, { "meta 3", "FileChooser.GotoModule", "GotoAction"}, { "meta D", "EditorDeleteLine", "Diff.ShowDiff", "CompareTwoFiles", "SendEOF", "FileChooser.GotoDesktop"}, { "meta I", "DatabaseView.PropertiesAction", "AutoIndentLines"}, { "meta P", "FileChooser.TogglePathShowing", "Print"}, { "meta R", "org.jetbrains.plugins.ruby.rails.console.ReloadSources", "RunToCursor"}, { "meta U", "CommanderSwapPanels", "EvaluateExpression"}, { "meta W", "CloseContent", "CloseActiveTab"}, { "meta F6", "Diff.NextChange", "NextTab"}, { "shift meta T", "GotoClass", "GotoChangedFile"}, { "meta alt LEFT", "Diff.PrevChange", "PreviousTab"}, { "meta alt RIGHT", "Diff.NextChange", "NextTab"}, { "meta alt DOWN", "Console.TableResult.NextPage", "EditorDuplicateLines"}, { "shift meta F11", "Run", "FocusTracer"}, { "shift meta G", "ClassTemplateNavigation", "GoToClass", "FindUsages"}, { "shift meta K", "Vcs.Push", "FindPrevious"}, { "shift meta X", "EditorToggleCase", "com.jetbrains.php.framework.FrameworkRunConsoleAction"}, { "shift meta U", "FindUsagesInFile", "ShelveChanges.UnshelveWithDialog"}, { "shift meta F6", "Diff.PrevChange", "PreviousTab"}, { "control shift alt Z", "Vcs.RollbackChangedLines", "ChangesView.Revert"}, }); put("Sublime Text", new String[][] { { "F2", "Arrangement.Rule.Edit", "ChangesView.Rename", "Console.TableResult.EditValue", "Git.Reword.Commit", "GotoNextBookmark", "GuiDesigner.EditComponent", "GuiDesigner.EditGroup", "ShelvedChanges.Rename", "XDebugger.SetValue"}, { "ctrl ADD", "EditorIncreaseFontSize", "ExpandAll", "ExpandExpandableComponent"}, { "ctrl D", "CompareTwoFiles", "Diff.ShowDiff", "FileChooser.GotoDesktop", "SelectNextOccurrence", "SendEOF"}, { "ctrl ENTER", "Console.Execute.Multiline", "DirDiffMenu.SynchronizeDiff.All", "EditorStartNewLine", "JupyterRunCellAction", "PyExecuteCellAction", "ViewSource"}, { "ctrl EQUALS", "EditorIncreaseFontSize", "ExpandAll", "ExpandExpandableComponent"}, { "ctrl L", "EditorSelectWord", "Vcs.Log.FocusTextFilter"}, { "ctrl M", "EditorMatchBrace", "Vcs.ShowMessageHistory"}, { "ctrl MINUS", "CollapseAll", "CollapseExpandableComponent", "EditorDecreaseFontSize"}, { "ctrl N", "FileChooser.NewFolder", "NewElement"}, { "ctrl P", "FileChooser.TogglePathShowing", "GotoFile"}, { "ctrl R", "FileStructurePopup", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"}, { "ctrl SUBTRACT", "CollapseAll", "CollapseExpandableComponent", "EditorDecreaseFontSize"}, { "ctrl alt DOWN", "Console.TableResult.NextPage", "EditorCloneCaretBelow"}, { "ctrl alt UP", "Console.TableResult.PreviousPage", "EditorCloneCaretAbove"}, { "shift ENTER", "CollapseExpandableComponent", "Console.TableResult.EditValueMaximized", "DatabaseView.PropertiesAction", "EditorSplitLine", "ExpandExpandableComponent", "JupyterRunCellSelectBelowAction", "OpenElementInNewWindow"}, { "shift ctrl D", "Console.TableResult.CompareCells", "EditorDuplicate", "Uml.ShowDiff"}, { "shift ctrl DOWN", "MoveLineDown", "ResizeToolWindowDown"}, { "shift ctrl ENTER", "Console.Jpa.GenerateSql", "EditorStartNewLineBefore"}, { "shift ctrl T", "ReopenClosedTab", "RunDashboard.ShowConfigurations"}, { "shift ctrl UP", "MoveLineUp", "ResizeToolWindowUp"} }); put("Sublime Text (Mac OS X)", new String[][] { { "F2", "Arrangement.Rule.Edit", "ChangesView.Rename", "Console.TableResult.EditValue", "Git.Reword.Commit", "GotoNextBookmark", "GuiDesigner.EditComponent", "GuiDesigner.EditGroup", "ShelvedChanges.Rename", "XDebugger.SetValue"}, { "meta ADD", "EditorIncreaseFontSize", "ExpandAll", "ExpandExpandableComponent"}, { "meta BACK_SPACE", "EditorDeleteToLineStart", "$Delete"}, { "meta D", "CompareTwoFiles", "Diff.ShowDiff", "FileChooser.GotoDesktop", "SelectNextOccurrence", "SendEOF"}, { "meta DOWN", "EditorTextEnd", "SearchEverywhere.NavigateToNextGroup"}, { "meta ENTER", "Console.Execute.Multiline", "DirDiffMenu.SynchronizeDiff.All", "EditorStartNewLine", "ViewSource"}, { "meta EQUALS", "EditorIncreaseFontSize", "ExpandAll", "ExpandExpandableComponent"}, { "meta I", "DatabaseView.PropertiesAction", "IncrementalSearch"}, { "meta L", "EditorSelectWord", "Vcs.Log.FocusTextFilter"}, { "meta MINUS", "CollapseAll", "CollapseExpandableComponent", "EditorDecreaseFontSize"}, { "meta P", "FileChooser.TogglePathShowing", "GotoFile"}, { "meta R", "FileStructurePopup", "Refresh", "Rerun", "org.jetbrains.plugins.ruby.rails.console.ReloadSources"}, { "meta SUBTRACT", "CollapseAll", "CollapseExpandableComponent", "EditorDecreaseFontSize"}, { "meta UP", "EditorTextStart", "SearchEverywhere.NavigateToPrevGroup"}, { "meta alt DOWN", "Console.TableResult.NextPage", "GotoDeclaration"}, { "meta alt G", "DatabaseView.SqlGenerator", "FindWordAtCaret", "org.jetbrains.plugins.ruby.rails.actions.generators.GeneratorsPopupAction"}, { "shift ENTER", "CollapseExpandableComponent", "Console.TableResult.EditValueMaximized", "EditorSplitLine", "ExpandExpandableComponent", "JupyterRunCellSelectBelowAction", "OpenElementInNewWindow"}, { "shift meta D", "Console.TableResult.CompareCells", "EditorDuplicate", "Uml.ShowDiff"}, { "shift meta ENTER", "Console.Jpa.GenerateSql", "EditorStartNewLineBefore"}, { "shift meta T", "ReopenClosedTab", "RunDashboard.ShowConfigurations"} }); }}; // @formatter:on @NonNls protected static final Set<String> DEFAULT_UNKNOWN_ACTION_IDS = ContainerUtil.set( "ActivateVersionControlToolWindow", "ActivateFavoritesToolWindow", "ActivateCommanderToolWindow", "ActivateDebugToolWindow", "ActivateServicesToolWindow", "ActivateFindToolWindow", "ActivateHierarchyToolWindow", "ActivateMessagesToolWindow", "ActivateProjectToolWindow", "ActivateRunToolWindow", "ActivateStructureToolWindow", "ActivateTODOToolWindow", "ActivateWebToolWindow", "ActivatePaletteToolWindow", "ActivateTerminalToolWindow", "IDEtalk.SearchUserHistory", "IDEtalk.SearchUserHistory", "IDEtalk.Rename", "CIDR.Lang.Cpp.GenerateDefinitions", "" ); @NonNls protected static final Set<String> DEFAULT_BOUND_ACTIONS = ContainerUtil.set( "EditorDelete" ); }
package todomore.android.uiconverter; import org.metawidget.android.widget.widgetprocessor.binding.simple.Converter; import com.darwinsys.todo.model.Date; import android.view.View; /** * MetaWidget converter for our local Date class. */ public class DateConverter implements Converter<Date> { public DateConverter() { System.out.println("DateConverter.DateConverter()"); } /** Convert from a Date to a String for display */ @Override public Object convertForView(View widget, Date value) { System.out.println("DateConverter.convertForView()"); if (value == null) { return null; } return value.toString(); } /** Convert from a String in the View to a Date object */ @Override public Date convertFromView(View widget, Object value, Class<?> intoClass) { System.out.println("DateConverter.convertFromView()"); if (value instanceof String) { if (((String) value).isEmpty()) { return null; } return new Date(value.toString()); } throw new IllegalArgumentException("Can't parse " + value + " of type " + value.getClass().getName()); } }
package viewcontroller; import java.awt.Dimension; import java.util.Observable; import java.util.Observer; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import application.Main; /** * ViewController for Command Windows (where command prompt, command status, * history, and user defined windows are located) * * @author Abhishek B * */ public class CommandWindowViewController implements Observer, ViewController { public static final Dimension SIZE = new Dimension( Main.SIZE.width / 2 * 9 / 10, Main.SIZE.height * 9 / 10); private BorderPane myPane; private VBox commandWindowVerticalBox; private UserDefinedMethodsWindowViewController myUserDefinedMethodsView; private UserDefinedVariablesWindowViewController myUserDefinedVariablesView; private HistoryWindowViewController myHistoryView; private CommandPromptViewController myCommandPromptView; private CommandStatusViewController myCommandStatusView; public CommandWindowViewController() { myPane = new BorderPane(); myPane.setPrefSize(SIZE.width, SIZE.height); commandWindowVerticalBox = new VBox(); HBox userDefinedHorizontalBox = placeUserDefinedBoxes(); myHistoryView = new HistoryWindowViewController(); myCommandPromptView = new CommandPromptViewController(); myCommandStatusView = new CommandStatusViewController(); // commandWindowVerticalBox. // commandWindowVerticalBox.addAll(/*placeUserDefinedBoxes(), */myHistoryView, myCommandPromptView, myCommandStatusView); } private HBox placeUserDefinedBoxes() { HBox userDefinedHorizontalBox = new HBox(); myUserDefinedMethodsView = new UserDefinedMethodsWindowViewController(); myUserDefinedVariablesView = new UserDefinedVariablesWindowViewController(); // userDefinedHorizontalBox.addAll(myUserDefinedMethodsView, myUserDefinedVariablesView); // return HBox; return null; } @Override public Node getNode() { return myPane; } @Override public void update(Observable o, Object arg) { } }
package net.kevxu.purdueassist.test; import java.io.*; import java.util.Scanner; import net.kevxu.purdueassist.course.CatalogDetail; import net.kevxu.purdueassist.course.CatalogDetail.CatalogDetailEntry; import net.kevxu.purdueassist.course.CatalogDetail.OnCatalogDetailFinishedListener; import net.kevxu.purdueassist.course.elements.Predefined.Subject; import net.kevxu.purdueassist.course.shared.CourseNotFoundException; import net.kevxu.purdueassist.course.shared.HttpParseException; public class TestUnit { public static void main(String[] args) { System.out.println("Subject:"); Scanner getInput = new Scanner(System.in); Subject tem_subject = null; try { tem_subject = Subject.valueOf(getInput.next().toUpperCase()); } catch (IllegalArgumentException e) { System.err.println("No such subject."); System.exit(-1); } final Subject subject = tem_subject; // System.out.println("Cnbr:"); // int tmp_cnbr=getInput.nextInt(); // if(tmp_cnbr<1000){ // tmp_cnbr*=100; // final int cnbr=tmp_cnbr; for (int mcnbr = 10000; mcnbr < 50000; mcnbr += 100) { final int cnbr = mcnbr; CatalogDetail detail = new CatalogDetail(subject, cnbr, new OnCatalogDetailFinishedListener() { @Override public void onCatalogDetailFinished(CatalogDetailEntry entry) { System.out.println(entry.toString()); System.out.println("Course Found"); System.out.println(" } @Override public void onCatalogDetailFinished(IOException e) { System.out.println("INPUT: " + cnbr + " " + subject.toString()); System.out.println("IO Error!"); System.out.println(" } @Override public void onCatalogDetailFinished(HttpParseException e) { System.out.println("INPUT: " + cnbr + " " + subject.toString()); System.out.println("Parse Error!"); System.out.println(" } @Override public void onCatalogDetailFinished(CourseNotFoundException e) { // System.out.println("INPUT: " + cnbr + " " + // subject.toString()); // System.out.println("Course Not Found!"); } }); try { detail.getResult(); } catch (StringIndexOutOfBoundsException e) { } } } }
package com.focusit.jsflight.player.webdriver; import com.focusit.jsflight.player.constants.BrowserType; import com.focusit.jsflight.player.constants.EventConstants; import com.focusit.jsflight.player.constants.EventType; import com.focusit.jsflight.player.scenario.UserScenario; import com.focusit.jsflight.player.script.PlayerScriptProcessor; import com.focusit.jsflight.script.constants.ScriptBindingConstants; import com.google.common.base.Predicate; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.json.JSONObject; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxBinary; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Selenium webdriver proxy: runs a browser, sends events, make screenshots * * @author Denis V. Kirpichenkov */ public class SeleniumDriver { /** * Non operational element indicating step processing must be aborted * returned from element lookup script */ public static final RemoteWebElement NO_OP_ELEMENT = new RemoteWebElement(); private static final Logger LOG = LoggerFactory.getLogger(SeleniumDriver.class); private static final String UI_NOT_SHOWED_UP_MSG = "UI didn't show up"; private static final int PROCESS_SIGNAL_STOP = -19; private static final int PROCESS_SIGNAL_CONT = -18; private static final int PROCESS_SIGNAL_FORCE_KILL = -9; private static final Map<String, Keys> SPECIAL_KEYS_MAPPING = new HashMap<>(); private static final String DISPLAY = "DISPLAY"; static { //This must be set due to equals of WebElement NO_OP_ELEMENT.setId("NO_OP"); SPECIAL_KEYS_MAPPING.put(EventConstants.CTRL_KEY, Keys.CONTROL); SPECIAL_KEYS_MAPPING.put(EventConstants.ALT_KEY, Keys.ALT); SPECIAL_KEYS_MAPPING.put(EventConstants.SHIFT_KEY, Keys.SHIFT); SPECIAL_KEYS_MAPPING.put(EventConstants.META_KEY, Keys.META); } private Map<String, Integer> availableDisplays; private HashMap<String, String> driverDisplay = new HashMap<>(); private HashMap<String, WebDriver> tabUuidDrivers = new HashMap<>(); private Map<String, String> lastUrls = new HashMap<>(); private StringGenerator stringGenerator; private UserScenario scenario; private int asyncRequestsCompletedTimeoutInSeconds; private String isAsyncRequestsCompletedScript; private long intervalBetweenUiChecksInMs; private int uiShownTimeoutInSeconds; private String isUiShownScript; private List<String> placeholders; private String isSelectElementScript; private String sendSignalToProcessScript; private String getWebDriverPidScript; private String elementLookupScript; private String skipKeyboardScript; private String maxElementGroovy; private String selectXpath; private String keepBrowserXpath; public SeleniumDriver(UserScenario scenario) { this(scenario, 0, -1); } public SeleniumDriver(UserScenario scenario, Integer xvfbDisplayLowerBound, Integer xvfbDisplayUpperBound) { this.scenario = scenario; availableDisplays = new HashMap<>(xvfbDisplayUpperBound - xvfbDisplayLowerBound + 1); for (int i = xvfbDisplayLowerBound; i <= xvfbDisplayUpperBound; i++) { availableDisplays.put(":" + i, 0); } } public static void switchToWorkingFrame(WebDriver theWebDriver, JSONObject event) { if (!event.has(EventConstants.IFRAME_XPATHS) && !event.has(EventConstants.IFRAME_INDICES)) { LOG.warn("Event with id {} hasn't frame xpath and frame index. Switching to main window", event.getInt(EventConstants.EVENT_ID)); switchToTopWindow(theWebDriver); } else { String frameXpath = event.getString(EventConstants.IFRAME_XPATHS); List<Integer> frameIndices = Arrays.stream(event.getString(EventConstants.IFRAME_INDICES).split("\\.")) .map(Integer::parseInt).collect(Collectors.toList()); LOG.info("Switching to frame {}({})", frameIndices, frameXpath); switchToFrame(theWebDriver, frameIndices, frameXpath); } } public static void switchToTopWindow(WebDriver webDriver) { webDriver.switchTo().window(webDriver.getWindowHandle()); } public static void switchToFrame(WebDriver theWebDriver, List<Integer> frameIndices, String compositeFrameXpath) { switchToTopWindow(theWebDriver); if (!frameIndices.isEmpty()) { LOG.info("Switching to frame by indices"); try { for (int i : frameIndices) { theWebDriver.switchTo().frame(i); } return; } catch (Exception ignored) { LOG.warn("Switching to frame by index was failed"); } } LOG.info("Switching to frame by xpaths"); for (String frameXpath : Arrays.asList(compositeFrameXpath.split("\\|\\|"))) { WebElement frame = theWebDriver.findElement(By.xpath(frameXpath)); theWebDriver.switchTo().frame(frame); } } public SeleniumDriver setKeepBrowserXpath(String keepBrowserXpath) { this.keepBrowserXpath = keepBrowserXpath; return this; } public SeleniumDriver setSendSignalToProcessScript(String sendSignalToProcessScript) { this.sendSignalToProcessScript = sendSignalToProcessScript; return this; } public SeleniumDriver setIsSelectElementScript(String isSelectElementScript) { this.isSelectElementScript = isSelectElementScript; return this; } public SeleniumDriver setSelectXpath(String selectXpath) { this.selectXpath = selectXpath; return this; } public SeleniumDriver setPlaceholders(String placeholders) { this.placeholders = Arrays.asList(placeholders.split(",")); return this; } public int getUiShownTimeoutInSeconds() { return uiShownTimeoutInSeconds; } public SeleniumDriver setUiShownTimeoutInSeconds(int uiShownTimeoutInSeconds) { this.uiShownTimeoutInSeconds = uiShownTimeoutInSeconds; return this; } public SeleniumDriver setLastUrls(Map<String, String> externalUrls) { this.lastUrls = externalUrls; return this; } public SeleniumDriver setUseRandomStringGenerator(boolean useRandomStringGenerator) { initializeStringGenerator(useRandomStringGenerator); return this; } public SeleniumDriver setAsyncRequestsCompletedTimeoutInSeconds(int asyncRequestsCompletedTimeoutInSeconds) { this.asyncRequestsCompletedTimeoutInSeconds = asyncRequestsCompletedTimeoutInSeconds; return this; } public SeleniumDriver setGetWebDriverPidScript(String getWebDriverPidScript) { this.getWebDriverPidScript = getWebDriverPidScript; return this; } public SeleniumDriver setIsAsyncRequestsCompletedScript(String isAsyncRequestsCompletedScript) { this.isAsyncRequestsCompletedScript = isAsyncRequestsCompletedScript; return this; } public SeleniumDriver setElementLookupScript(String elementLookupScript) { this.elementLookupScript = elementLookupScript; return this; } public SeleniumDriver setIsUiShownScript(String isUiShownScript) { this.isUiShownScript = isUiShownScript; return this; } public SeleniumDriver setMaxElementGroovy(String maxElementGroovy) { this.maxElementGroovy = maxElementGroovy; return this; } public void closeWebDrivers() { PlayerScriptProcessor processor = new PlayerScriptProcessor(scenario); tabUuidDrivers.values().forEach(driver -> { String pid = getFirefoxPid(driver); processor.executeProcessSignalScript(sendSignalToProcessScript, PROCESS_SIGNAL_CONT, pid); processor.executeProcessSignalScript(sendSignalToProcessScript, PROCESS_SIGNAL_FORCE_KILL, pid); }); } public WebElement findTargetWebElement(WebDriver wd, JSONObject event, String target) { waitWhileAsyncRequestsWillCompletedWithRefresh(wd, event); Map<String, Object> binding = PlayerScriptProcessor.getEmptyBindingsMap(); binding.put(ScriptBindingConstants.WEB_DRIVER, wd); binding.put(ScriptBindingConstants.TARGET, target); binding.put(ScriptBindingConstants.EVENT, event); WebElement webElement = new PlayerScriptProcessor(scenario).executeGroovyScript(elementLookupScript, binding, WebElement.class); if (webElement == null) { throw new IllegalStateException("Element lookup script returned null"); } return webElement; } public WebDriver getDriverForEvent(JSONObject event, BrowserType browserType, String binaryPath, String proxyHost, Integer proxyPort) { String tabUuid = event.getString(EventConstants.TAB_UUID); WebDriver driver = tabUuidDrivers.get(tabUuid); if (driver == null) { DesiredCapabilities desiredCapabilities = new DesiredCapabilities(); if (!StringUtils.isBlank(proxyHost) && proxyPort != null && proxyPort != 0) { String host = String.format("%s:%d", proxyHost, proxyPort); Proxy proxy = new Proxy(); proxy.setHttpProxy(host).setFtpProxy(host).setSslProxy(host); desiredCapabilities.setCapability(CapabilityType.PROXY, proxy); } String display = System.getenv(DISPLAY); if (!availableDisplays.isEmpty()) { display = availableDisplays.keySet().stream() .min((one, other) -> availableDisplays.get(one) - availableDisplays.get(other)).get(); } if (display == null) { throw new IllegalStateException("Display wasn't set neither in environment nor in properties"); } switch (browserType) { case FIREFOX: driver = createFirefoxDriver(display, binaryPath, desiredCapabilities); break; case CHROME: throw new RuntimeException("Chrome web driver can't be used now"); } driver = WebDriverWrapper.wrap(driver); tabUuidDrivers.put(tabUuid, driver); //as actual webdriver is RemoteWebdriver, calling to string return browser name, platform and sessionid //which are not subject to change, so we can use it as key; driverDisplay.put(driver.toString(), display); } prioritize(driver); resizeForEvent(driver, event); return driver; } private FirefoxDriver createFirefoxDriver(String display, String binaryPath, DesiredCapabilities desiredCapabilities) { FirefoxProfile profile = createDefaultFirefoxProfile(); FirefoxBinary binary = !StringUtils.isBlank(binaryPath) ? new FirefoxBinary(new File(binaryPath)) : new FirefoxBinary(); LOG.info("Binding to {} display", display); availableDisplays.compute(display, (d, value) -> value == null ? 1 : value + 1); binary.setEnvironmentProperty(DISPLAY, display); LOG.info("Firefox path is: {}", binaryPath); return openFirefoxDriver(desiredCapabilities, profile, binary); } private FirefoxDriver openFirefoxDriver(DesiredCapabilities desiredCapabilities, FirefoxProfile profile, FirefoxBinary binary) { try { return new FirefoxDriver(binary, profile, desiredCapabilities); } catch (WebDriverException ex) { LOG.warn(ex.getMessage()); awakenAllDrivers(); return openFirefoxDriver(desiredCapabilities, profile, binary); } } public String getDriverDisplay(WebDriver webdriver) { return driverDisplay.getOrDefault(webdriver.toString(), ":0"); } public String getLastUrl(JSONObject event) { String tag = UserScenario.getTagForEvent(event); String result = lastUrls.get(tag); if (result == null) { String empty = ""; lastUrls.put(tag, empty); result = empty; } return result; } public void makeAShot(WebDriver wd, OutputStream outputStream) throws IOException { TakesScreenshot shooter = (TakesScreenshot)wd; byte[] shot = shooter.getScreenshotAs(OutputType.BYTES); outputStream.write(shot); } public void openEventUrl(WebDriver wd, JSONObject event) { String eventUrl = event.getString(EventConstants.URL); if (wd.getCurrentUrl().equals("about:blank") || !getLastUrl(event).equals(eventUrl)) { wd.get(eventUrl); waitWhileUiWillShown(wd); updateLastUrl(event, eventUrl); } } public WebElement waitElement(WebDriver wd, String xpath) { try { return new WebDriverWait(wd, 20L, 500).until(new ExpectedCondition<WebElement>() { @Override public WebElement apply(WebDriver input) { try { return wd.findElement(By.xpath(xpath)); } catch (NoSuchElementException e) { return null; } } }); } catch (TimeoutException e) { throw new NoSuchElementException("Element was not found within timeout. Xpath " + xpath); } } public void processKeyPressEvent(WebDriver driver, JSONObject event) throws UnsupportedEncodingException { WebElement element = findTargetWebElement(driver, event, UserScenario.getTargetForEvent(event)); if (isNoOp(event, element)) { return; } //TODO remove this when recording of cursor in text box is implemented if (skipKeyboardForElement(element)) { LOG.warn("Keyboard processing for non empty Date is disabled"); return; } if (!event.has(EventConstants.CHAR)) { throw new IllegalStateException("Keypress event don't have a char"); } String keys = event.getString(EventConstants.CHAR); LOG.info("Trying to fill input with: {}", keys); if (event.has(EventConstants.IFRAME_XPATHS) || event.has(EventConstants.IFRAME_INDICES)) { LOG.info("Input is iframe"); element.sendKeys(keys); } else { LOG.info("Input is ordinary input"); String prevText = element.getAttribute("value"); //If current value indicates a placeholder it must be discarded if (placeholders.contains(prevText)) { element.clear(); } element.sendKeys(keys); } } public void processKeyDownKeyUpEvents(WebDriver wd, JSONObject event) throws UnsupportedEncodingException { WebElement element = findTargetWebElement(wd, event, UserScenario.getTargetForEvent(event)); if (isNoOp(event, element)) { return; } //TODO remove this when recording of cursor in text box is implemented if (skipKeyboardForElement(element)) { LOG.warn("Keyboard processing for non empty Date is disabled"); return; } if (!event.has(EventConstants.KEY_CODE)) { throw new IllegalStateException("Keydown/Keyup event don't have keyCode property"); } Actions actions = new Actions(wd); SPECIAL_KEYS_MAPPING.keySet().forEach(property -> { if (event.getBoolean(property)) { actions.keyDown(element, SPECIAL_KEYS_MAPPING.get(property)); } }); switch (event.getBigInteger(EventConstants.KEY_CODE).intValue()) { case 8: actions.sendKeys(element, Keys.BACK_SPACE); break; case 27: actions.sendKeys(element, Keys.ESCAPE); break; case 46: actions.sendKeys(element, Keys.DELETE); break; case 13: actions.sendKeys(element, Keys.ENTER); break; case 37: actions.sendKeys(element, Keys.ARROW_LEFT); break; case 38: actions.sendKeys(element, Keys.ARROW_UP); break; case 39: actions.sendKeys(element, Keys.ARROW_RIGHT); break; case 40: actions.sendKeys(element, Keys.ARROW_DOWN); break; } SPECIAL_KEYS_MAPPING.keySet().forEach(property -> { if (event.getBoolean(property)) { actions.keyUp(element, SPECIAL_KEYS_MAPPING.get(property)); } }); actions.perform(); } private boolean isNoOp(JSONObject event, WebElement element) { if (element.equals(NO_OP_ELEMENT)) { LOG.warn("Non operational element returned. Aborting event {} processing. Target xpath {}", event.get(EventConstants.EVENT_ID), event.getString(EventConstants.SECOND_TARGET)); return true; } return false; } public void processMouseEvent(WebDriver wd, JSONObject event) { WebElement element = findTargetWebElement(wd, event, UserScenario.getTargetForEvent(event)); if (isNoOp(event, element)) { return; } ensureElementInWindow(wd, element); boolean isSelect = new PlayerScriptProcessor(scenario).executeSelectDeterminerScript(isSelectElementScript, wd, element); click(wd, event, element); if (isSelect) { //Wait for select to popup LOG.debug("Mouse event is kind of select"); waitElement(wd, selectXpath); } } private void click(WebDriver wd, JSONObject event, WebElement element) { if (element.isDisplayed()) { if (event.getInt(EventConstants.BUTTON) == 2) { try { new Actions(wd).contextClick(element).perform(); } catch (WebDriverException ex) { try { LOG.warn("Error simulation right click. Retrying after 2 sec."); Thread.sleep(2000); new Actions(wd).contextClick(element).perform(); } catch (Exception e) { LOG.error("Error while simulating right click.", e); } } } else { element.click(); } } else { JavascriptExecutor executor = (JavascriptExecutor)wd; executor.executeScript("arguments[0].click();", element); } } public void processMouseWheel(WebDriver wd, JSONObject event, String target) { if (!event.has(EventConstants.DELTA_Y)) { LOG.error("event has no deltaY - cant process scroll", new Exception()); return; } WebElement el = findTargetWebElement(wd, event, target); if (isNoOp(event, el)) { return; } //Web lookup script MUST return //html element if scroll occurs not in a popup if (!el.getTagName().equalsIgnoreCase("html")) { ((JavascriptExecutor)wd).executeScript("arguments[0].scrollTop = arguments[0].scrollTop + arguments[1]", el, event.getInt(EventConstants.DELTA_Y)); } else { ((JavascriptExecutor)wd).executeScript("window.scrollBy(0, arguments[0])", event.getInt(EventConstants.DELTA_Y)); } } public void processScroll(WebDriver wd, JSONObject event, String target) { long timeout = System.currentTimeMillis() + 20000L; if (checkElementPresent(wd, target)) { return; } do { waitWhileAsyncRequestsWillCompletedWithRefresh(wd, event); try { WebElement el = getMax(wd, maxElementGroovy); scroll((JavascriptExecutor)wd, el); if (checkElementPresent(wd, target)) { return; } } catch (Exception ex) { LOG.error(ex.toString(), ex); } } while (System.currentTimeMillis() < timeout); throw new NoSuchElementException("Element was not found during scroll"); } public void releaseBrowser(WebDriver driver, JSONObject event) { driver.switchTo().defaultContent(); if (shouldKeepBrowser(driver)) { LOG.info("Keep browser xpath matches some element, or it wasn't specified"); return; } String tabUuid = event.getString(EventConstants.TAB_UUID); String empoyeeUuid = null; if (event.has(EventConstants.TAG)) { empoyeeUuid = event.getString(EventConstants.TAG); } LOG.info("Releasing browser for " + tabUuid + " tab" + (empoyeeUuid == null ? "" : ", uuid " + empoyeeUuid)); String display = driverDisplay.get(driver.toString()); if (display != null) { availableDisplays.put(display, availableDisplays.get(display) - 1); LOG.info("Display {} is used {} times now", display, availableDisplays.get(display)); } PlayerScriptProcessor processor = new PlayerScriptProcessor(scenario); String firefoxPid = getFirefoxPid(driver); processor.executeProcessSignalScript(sendSignalToProcessScript, PROCESS_SIGNAL_CONT, firefoxPid); tabUuidDrivers.remove(tabUuid); driver.quit(); try { LOG.info("Trying to kill Firefox. PID: {}", firefoxPid); processor.executeProcessSignalScript(sendSignalToProcessScript, PROCESS_SIGNAL_FORCE_KILL, firefoxPid); } catch (Throwable ex) { LOG.error(ex.getMessage(), ex); } } private String getFirefoxPid(WebDriver driver) { PlayerScriptProcessor processor = new PlayerScriptProcessor(scenario); Map<String, Object> binding = PlayerScriptProcessor.getEmptyBindingsMap(); binding.put(ScriptBindingConstants.WEB_DRIVER, getSeleniumDriver(driver)); return processor.executeGroovyScript(getWebDriverPidScript, binding, String.class); } private WebDriver getSeleniumDriver(WebDriver driver) { return driver instanceof WebDriverWrapper ? ((WebDriverWrapper)driver).getWrappedDriver() : driver; } public void resetLastUrls() { lastUrls.clear(); } public void setScenario(UserScenario scenario) { this.scenario = scenario; } public void updateLastUrl(JSONObject event, String url) { lastUrls.put(UserScenario.getTagForEvent(event), url); } public void waitWhileAsyncRequestsWillCompletedWithRefresh(WebDriver wd, JSONObject event) { try { waitWhileAsyncRequestsWillCompleted(wd, event); } catch (IllegalStateException e) { if (shouldKeepBrowser(wd)) { throw e; } wd.navigate().refresh(); waitWhileAsyncRequestsWillCompleted(wd, event); } } private boolean shouldKeepBrowser(WebDriver wd) { return keepBrowserXpath == null || keepBrowserXpath.isEmpty() || !wd.findElements(By.xpath(keepBrowserXpath)).isEmpty(); } public void waitWhileAsyncRequestsWillCompleted(WebDriver wd, JSONObject event) { String type = event.getString(EventConstants.TYPE); if (type.equalsIgnoreCase(EventType.XHR) || type.equalsIgnoreCase(EventType.SCRIPT)) { return; } LOG.info("Waiting while async requests will completed for {} seconds", asyncRequestsCompletedTimeoutInSeconds); try { new WebDriverWait(wd, asyncRequestsCompletedTimeoutInSeconds, 500).until((Predicate<WebDriver>)input -> { try { Object result = ((JavascriptExecutor)wd).executeScript(isAsyncRequestsCompletedScript); return result != null && Boolean.parseBoolean(result.toString().toLowerCase()); } catch (WebDriverException e) { return false; } }); } catch (TimeoutException e) { throw new IllegalStateException(String.format( "Async requests was not completed within specified timeout (%ds): %s", asyncRequestsCompletedTimeoutInSeconds, event.getString(EventConstants.URL))); } } private boolean checkElementPresent(WebDriver wd, String target) { try { wd.findElement(By.xpath(target)); return true; } catch (Exception e) { return false; } } private void ensureElementInWindow(WebDriver wd, WebElement element) { int windowHeight = wd.manage().window().getSize().getHeight(); int elementY = element.getLocation().getY(); if (elementY > windowHeight) { //Using division of the Y coordinate by 2 ensures target element visibility in the browser view //anyway TODO think of not using hardcoded constants in scrolling String scrollScript = "window.scrollTo(0, " + elementY / 2 + ");"; ((JavascriptExecutor)wd).executeScript(scrollScript); } } private void initializeStringGenerator(boolean useRandomChars) { if (stringGenerator == null) { stringGenerator = useRandomChars ? new RandomStringGenerator() : new CharStringGenerator(); } } private boolean skipKeyboardForElement(WebElement element) { //TODO remove this when recording of cursor in text box is implemented Map<String, Object> bindings = PlayerScriptProcessor.getEmptyBindingsMap(); bindings.put(ScriptBindingConstants.ELEMENT, element); return new PlayerScriptProcessor(scenario).executeGroovyScript(skipKeyboardScript, bindings, Boolean.class); } private WebElement getMax(WebDriver wd, String script) { Map<String, Object> binding = PlayerScriptProcessor.getEmptyBindingsMap(); binding.put(ScriptBindingConstants.WEB_DRIVER, wd); return new PlayerScriptProcessor(scenario).executeGroovyScript(script, binding, WebElement.class); } private void resizeForEvent(WebDriver wd, JSONObject event) { boolean hasProperty = event.has("window.width"); JSONObject target = hasProperty ? event : event.getJSONObject("window"); int width = target.getInt(hasProperty ? "window.width" : "width"); int height = target.getInt(hasProperty ? "window.height" : "height"); width = width > 0 ? width : 1000; height = height > 0 ? height : 1000; Dimension targetSize = new Dimension(width, height); if (!wd.manage().window().getSize().equals(targetSize)) { LOG.info("Resizing to {}x{}", width, height); wd.manage().window().setSize(targetSize); } } private void scroll(JavascriptExecutor js, WebElement element) { js.executeScript("arguments[0].scrollIntoView(true)", element); } private void waitWhileUiWillShown(WebDriver wd) { try { LOG.info("Waiting while UI will appear for {} seconds", getUiShownTimeoutInSeconds()); new WebDriverWait(wd, getUiShownTimeoutInSeconds(), intervalBetweenUiChecksInMs) .until(new Predicate<WebDriver>() { @Override public boolean apply(WebDriver driver) { try { Map<String, Object> binding = PlayerScriptProcessor.getEmptyBindingsMap(); binding.put(ScriptBindingConstants.WEB_DRIVER, driver); return new PlayerScriptProcessor(scenario).executeGroovyScript(isUiShownScript, binding, Boolean.class); } catch (WebDriverException e) { return false; } } }); } catch (TimeoutException e) { LOG.error("UI not appears!"); throw new NoSuchElementException(UI_NOT_SHOWED_UP_MSG); } } private void awakenAllDrivers() { PlayerScriptProcessor processor = new PlayerScriptProcessor(scenario); tabUuidDrivers.values().forEach( driver -> processor.executeProcessSignalScript(sendSignalToProcessScript, PROCESS_SIGNAL_CONT, getFirefoxPid(driver))); } private void prioritize(WebDriver wd) { PlayerScriptProcessor processor = new PlayerScriptProcessor(scenario); String firefoxPid = getFirefoxPid(wd); processor.executeProcessSignalScript(sendSignalToProcessScript, PROCESS_SIGNAL_CONT, firefoxPid); LOG.info("Prioritizing driver with pid: {}", firefoxPid); tabUuidDrivers .values() .stream() .filter(driver -> !driver.equals(wd)) .forEach( driver -> processor.executeProcessSignalScript(sendSignalToProcessScript, PROCESS_SIGNAL_STOP, getFirefoxPid(driver))); } private FirefoxProfile createDefaultFirefoxProfile() { FirefoxProfile firefoxProfile = new FirefoxProfile(); firefoxProfile.setPreference("nglayout.initialpaint.delay", "0"); firefoxProfile.setPreference("network.http.pipelining", true); firefoxProfile.setPreference("image.animation_mode", "none"); firefoxProfile.setPreference("layers.acceleration.force-enabled", true); firefoxProfile.setPreference("layers.offmainthreadcomposition.enabled", true); firefoxProfile.setPreference("browser.sessionstore.interval", 3600000); firefoxProfile.setPreference("privacy.trackingprotection.enabled", true); firefoxProfile.setPreference("content.notify.interval", 849999); firefoxProfile.setPreference("content.notify.backoffcount", 5); firefoxProfile.setPreference("network.http.max-connections", 50); firefoxProfile.setPreference("network.http.max-connections-per-server", 150); firefoxProfile.setPreference("network.http.pipelining.aggressive", false); firefoxProfile.setPreference("browser.tabs.animate", false); firefoxProfile.setPreference("browser.display.show_image_placeholders", false); firefoxProfile.setPreference("browser.cache.use_new_backend", 1); firefoxProfile.setPreference("ui.submenuDelay", 0); firefoxProfile.setPreference("browser.cache.disk.enable", false); firefoxProfile.setPreference("browser.cache.memory.enable", true); firefoxProfile.setPreference("browser.cache.memory.capacity", 128000); return firefoxProfile; } public SeleniumDriver setIntervalBetweenUiChecksInMs(long intervalBetweenUiChecksInMs) { this.intervalBetweenUiChecksInMs = intervalBetweenUiChecksInMs; return this; } public SeleniumDriver setSkipKeyboardScript(String skipKeyboardScript) { this.skipKeyboardScript = skipKeyboardScript; return this; } private static abstract class StringGenerator { protected static final Logger LOG = LoggerFactory.getLogger(StringGenerator.class); public String getAsString(char ch) throws UnsupportedEncodingException { String result = generate(ch); LOG.info("Returning {}", result); return result; } public abstract String generate(char ch) throws UnsupportedEncodingException; } private static class CharStringGenerator extends StringGenerator { @Override public String generate(char ch) throws UnsupportedEncodingException { return String.valueOf(ch); } } private static class RandomStringGenerator extends StringGenerator { @Override public String generate(char ch) { return RandomStringUtils.randomAlphanumeric(1); } } }
// Identifier.java // This package may be distributed under the package net.maizegenetics.pal.ids; import java.io.Serializable; import net.maizegenetics.prefs.TasselPrefs; /** * An identifier for some sampled data. This will most often be for example, the * accession number of a DNA sequence, or the taxonomic name that the sequence * represents, et cetera. * * @author terry */ public class Identifier implements Serializable, Comparable { private static final long serialVersionUID = -7873729831795750538L; public static final String DELIMITER = ":"; private final String myName; private final String[] myNameTokens; public static Identifier ANONYMOUS = new Identifier(""); public Identifier(String name) { myName = name; myNameTokens = name.split(DELIMITER); } public static Identifier getMergedInstance(Identifier id1, Identifier id2) { String[] first = id1.getFullNameTokens(); String[] second = id2.getFullNameTokens(); int count = Math.min(first.length, second.length); for (int i = 0; i < count; i++) { if (!first[i].equals(second[i])) { StringBuilder builder = new StringBuilder(); for (int x = 0; x < i; x++) { if (x != 0) { builder.append(DELIMITER); } builder.append(first[x]); return new Identifier(builder.toString()); } } } return id1; } public String toString() { return getName(); } // implements Comparable interface @Override public int compareTo(Object c) { if (c instanceof Identifier) { return compareTo(((Identifier) c).getFullNameTokens()); } else { throw new ClassCastException(); } } @Override public boolean equals(Object c) { TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES type = TasselPrefs.getIDJoinStrict(); if (c instanceof Identifier) { if (type == TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES.Strict) { return getFullName().equals(((Identifier) c).getFullName()); } else { return compareTo(c) == 0; } } else if (c instanceof String) { if (type == TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES.Strict) { return getFullName().equals(((String) c)); } else { return compareTo((String) c) == 0; } } else { return false; } } public int compareTo(String c) { return compareTo(c.split(DELIMITER)); } public int compareTo(String[] fullNameTokens) { TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES type = TasselPrefs.getIDJoinStrict(); int count = Math.min(myNameTokens.length, fullNameTokens.length); if (type == TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES.NumLevels) { count = Math.min(count, TasselPrefs.getIDJoinNumLevels()); } for (int i = 0; i < count; i++) { int current = myNameTokens[i].compareTo(fullNameTokens[i]); if (current != 0) { return current; } } if (type == TasselPrefs.TASSEL_IDENTIFIER_JOIN_TYPES.Strict) { if (myNameTokens.length < fullNameTokens.length) { return -1; } else if (fullNameTokens.length < myNameTokens.length) { return 1; } else { return 0; } } else { return 0; } } public String getName() { return getNameLevel(0); } public String getFullName() { return myName; } public String getFullName(String delimiter) { if (delimiter.equals(DELIMITER)) { return myName; } return myName.replaceAll(DELIMITER, delimiter); } public String[] getFullNameTokens() { return myNameTokens; } /** * Returns requested level of name starting at index 0. 0 will generally be * most specific classification. * * @param index * @return Specified level. */ public String getNameLevel(int index) { if (index < myNameTokens.length) { return myNameTokens[index]; } return null; } /** * Returns name up to specified level (not including specified level. Levels * start at index 0. * * @param index * @return name up to specified level exclusive. */ public String getNameToLevel(int index) { return getNameToLevel(index, DELIMITER); } public String getNameToLevel(int index, String delimiter) { int upto = 0; if (index > myNameTokens.length) { upto = myNameTokens.length; } else { upto = index; } if (upto == 0) { return null; } StringBuilder builder = new StringBuilder(); for (int i = 0; i < upto; i++) { if (i != 0) { builder.append(delimiter); } builder.append(myNameTokens[i]); } return builder.toString(); } /** * Returns number of name levels. * * @return number of name levels. */ public int getNumNameLevels() { return myNameTokens.length; } }
package org.perl6.nqp.io; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import org.perl6.nqp.runtime.ExceptionHandling; import org.perl6.nqp.runtime.ThreadContext; public class FileHandle implements IIOClosable, IIOSeekable, IIOEncodable, IIOSyncReadable, IIOSyncWritable { private FileChannel chan; private CharsetEncoder enc; private CharsetDecoder dec; private boolean eof = false; public FileHandle(ThreadContext tc, String filename, String mode) { try { Path p = new File(filename).toPath(); if (mode.equals("r")) { chan = FileChannel.open(p, StandardOpenOption.READ); } else if (mode.equals("w")) { chan = FileChannel.open(p, StandardOpenOption.WRITE, StandardOpenOption.CREATE); } else if (mode.equals("wa")) { chan = FileChannel.open(p, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.APPEND); } else { ExceptionHandling.dieInternal(tc, "Unhandled file open mode '" + mode + "'"); } setEncoding(tc, Charset.forName("UTF-8")); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public void close(ThreadContext tc) { try { chan.close(); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public void seek(ThreadContext tc, long offset, long whence) { try { switch ((int)whence) { case 0: chan.position(offset); break; case 1: chan.position(chan.position() + offset); break; case 2: chan.position(chan.size()); break; default: throw ExceptionHandling.dieInternal(tc, "Invalid seek mode"); } } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public long tell(ThreadContext tc) { try { return chan.position(); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public void setEncoding(ThreadContext tc, Charset cs) { enc = cs.newEncoder(); dec = cs.newDecoder(); } public String slurp(ThreadContext tc) { try { // Read in file. ArrayList<ByteBuffer> buffers = new ArrayList<ByteBuffer>(); ByteBuffer curBuffer = ByteBuffer.allocate(32768); int total = 0; int read; while ((read = chan.read(curBuffer)) != -1) { buffers.add(curBuffer); curBuffer = ByteBuffer.allocate(32768); total += read; } eof = true; // Copy to a single buffer and decode (could be smarter, but need // to be wary as UTF-8 chars may span a buffer boundary). ByteBuffer allBytes = ByteBuffer.allocate(total); for (ByteBuffer bb : buffers) allBytes.put(bb); return dec.decode(allBytes).toString(); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public String readline(ThreadContext tc) { throw new RuntimeException("FileHandle.readline() NYI"); } public boolean eof(ThreadContext tc) { return eof; } public void print(ThreadContext tc, String s) { try { ByteBuffer buffer = enc.encode(CharBuffer.wrap(s)); while (buffer.position() > 0) { buffer.flip(); chan.write(buffer); buffer.compact(); } } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public void say(ThreadContext tc, String s) { print(tc, s); print(tc, System.lineSeparator()); } }
package net.sf.jaer.chip; import java.util.logging.Logger; import net.sf.jaer.aemonitor.AEPacketRaw; import net.sf.jaer.event.BasicEvent; import net.sf.jaer.event.EventPacket; import net.sf.jaer.event.OutputEventIterator; import net.sf.jaer.event.TypedEvent; /** * An abstract 2D event extractor for 16 bit raw addresses. It is called with * addresses and timestamps and extracts these to {X, Y, type} arrays based on * methods that you define by sub-classing and overriding the abstract methods. * * xMask, yMask, typeMask mask for x, y address and cell type, and xShift, * yShift, typeShift say how many bits to shift after masking, * xFlip,yFlip,typeFlip use the chip size to flip the x,y, and type to invert * the addresses. * * @author tobi */ abstract public class TypedEventExtractor<T extends BasicEvent> implements EventExtractor2D<T>, java.io.Serializable { static Logger log = Logger.getLogger("net.sf.jaer.chip"); // protected AEChip chip; protected int xmask, ymask; protected byte xshift, yshift; protected int typemask; protected byte typeshift; protected AEChip chip = null; protected boolean flipx = false, flipy = false, rotate = false; protected boolean fliptype = false; protected boolean hexArrangement = false; // the reused output eventpacket protected EventPacket<T> out = null; /** * determines subSampling of rendered events (for speed) */ private boolean subsamplingEnabled = false; private int subsampleThresholdEventCount = 50000; private short sizexm1, sizeym1; // these are size-1 (e.g. if 128 pixels, sizex=127). used for flipping below. private byte sizetypem1; // /** Creates a new instance of RetinaEventExtractor */ // public TypedEventExtractor() { /** * Creates a new instance of RetinaEventExtractor * * @param aechip the chip this extractor extracts */ public TypedEventExtractor(AEChip aechip) { chip = aechip; setChipSizes(); } private void setChipSizes() { sizexm1 = (short) (chip.getSizeX() - 1); sizeym1 = (short) (chip.getSizeY() - 1); sizetypem1 = (byte) (chip.getNumCellTypes() - 1); } /** * Gets X from raw address. declared final for speed, cannot be overridden * in subclass. It expects addr to be from a certain format like ???? XXX? * X?X? ????. The mask 0000 1110 1010 0000 will get those Xs. So, what's * left is 0000 XXX0 X0X0 0000. Then it is shifted (the triple means * zero-padding regardless of sign, necessary because addr is not defined as * unsigned!) with the xshift parameter. So, in this case e.g. 5, what will * make the result 0000 0000 0XXX 0X0X (0-64). If the incoming addr is * big-endian versus small-endian the entire bit sequence has to be reversed * of course. This is not what is done by flipx! That is just a boolean that * results in the chip size minus the result otherwise. So, in the above * example the place for X is still expected in the same spots (the mask is * not inverted). Last remark: the masks are normally continuous, no weird * blanks within them. :-) Ultimate remark: a mask of size 1 will invert the * value if the flip parameter is set. Super-last remark: the parameter * sizex should be 7 (not 8) for a mask of size 3 (000 - 111), like * mentioned before. So, the sizex and sizey parameters in this * TypedEventExtractor class are decremented with one compared to the same * parameters in the class AEChip. * * @param addr the raw address. * @return physical address */ @Override public short getXFromAddress(int addr) { if (!flipx) { return ((short) ((addr & xmask) >>> xshift)); } return (short) (sizexm1 - ((addr & xmask) >>> xshift)); // e.g. chip.sizex=32, sizex=31, addr=0, getX=31, addr=31, getX=0 } /** * gets Y from raw address. declared final for speed, cannot be overridden * in subclass. * * @param addr the raw address. * @return physical address */ @Override public short getYFromAddress(int addr) { if (!flipy) { return ((short) ((addr & ymask) >>> yshift)); } return (short) (sizeym1 - ((addr & ymask) >>> yshift)); } /** * gets type from raw address. declared final for speed, cannot be * overridden in subclass. * * @param addr the raw address. * @return physical address */ @Override public byte getTypeFromAddress(int addr) { if (!fliptype) { return (byte) ((addr & typemask) >>> typeshift); } return (byte) (sizetypem1 - (byte) ((addr & typemask) >>> typeshift)); } /** * extracts the meaning of the raw events. * * @param in the raw events, can be null * @return out the processed events. these are partially processed in-place. * empty packet is returned if null is supplied as in. */ @Override synchronized public EventPacket<T> extractPacket(AEPacketRaw in) { if (out == null) { out = new EventPacket<>(chip.getEventClass()); } else { out.clear(); } if (in == null) { return out; } extractPacket(in, out); return out; } /** * Extracts the meaning of the raw events. This form is used to supply an * output packet. This method is used for real time event filtering using a * buffer of output events local to data acquisition. An AEPacketRaw may * contain multiple events, not all of them have to sent out as * EventPackets. An AEPacketRaw is a set(!) of addresses and corresponding * timing moments. * * A first filter (independent from the other ones) is implemented by * subSamplingEnabled and getSubsampleThresholdEventCount. The latter may * limit the amount of samples in one package to say 50,000. If there are * 160,000 events and there is a sub sample threshold of 50,000, a "skip * parameter" set to 3. Every so now and then the routine skips with 4, so * we end up with 50,000. It's an approximation, the amount of events may be * less than 50,000. The events are extracted uniform from the input. * * @param in the raw events, can be null * @param out the processed events. these are partially processed in-place. * empty packet is returned if null is supplied as input. */ @Override synchronized public void extractPacket(AEPacketRaw in, EventPacket<T> out) { // TODO there could be a real problem here as exposed by AutomaticReplayPlayer out.clear(); if (in == null) { return; } int n = in.getNumEvents(); //addresses.length; int skipBy = 1, incEach = 0, j = 0; if (subsamplingEnabled) { skipBy = n / getSubsampleThresholdEventCount(); incEach = getSubsampleThresholdEventCount() / (n % getSubsampleThresholdEventCount()); } if (skipBy == 0) { incEach = 0; skipBy = 1; } int[] a = in.getAddresses(); int[] timestamps = in.getTimestamps(); boolean hasTypes = false; if (chip != null) { hasTypes = chip.getNumCellTypes() > 1; } OutputEventIterator<?> outItr = out.outputIterator(); for (int i = 0; i < n; i += skipBy) { int addr = a[i]; BasicEvent e = outItr.nextOutput(); e.address = addr; e.timestamp = (timestamps[i]); e.x = getXFromAddress(addr); e.y = getYFromAddress(addr); if (hasTypes) { ((TypedEvent) e).type = getTypeFromAddress(addr); } j++; if (j == incEach) { j = 0; i++; } // System.out.println("a="+a[i]+" t="+e.timestamp+" x,y="+e.x+","+e.y); } } /* synchronized public void extractPacket(AEPacketRaw in, EventPacket out) { out.clear(); if(in==null) return; int n=in.getNumEvents(); //addresses.length; int skipBy=1; if(subsamplingEnabled){ while(n/skipBy>getSubsampleThresholdEventCount()){ skipBy++; } } int[] a=in.getAddresses(); int[] timestamps=in.getTimestamps(); boolean hasTypes=false; if(chip!=null) hasTypes=chip.getNumCellTypes()>1; OutputEventIterator outItr=out.outputIterator(); for(int i=0; i<n; i+=skipBy){ // bug here? no, bug is before :-) int addr=a[i]; BasicEvent e=(BasicEvent)outItr.nextOutput(); e.timestamp=(timestamps[i]); e.x=getXFromAddress(addr); e.y=getYFromAddress(addr); if(hasTypes){ ((TypedEvent)e).type=getTypeFromAddress(addr); } // System.out.println("a="+a[i]+" t="+e.timestamp+" x,y="+e.x+","+e.y); } } */ @Override public int getTypemask() { return this.typemask; } @Override public void setTypemask(final int typemask) { this.typemask = typemask; } @Override public byte getTypeshift() { return this.typeshift; } @Override public void setTypeshift(final byte typeshift) { this.typeshift = typeshift; } @Override public int getXmask() { return this.xmask; } /** * bit mask for x address, before shift */ @Override public void setXmask(final int xmask) { this.xmask = xmask; } @Override public byte getXshift() { return this.xshift; } /** * @param xshift the number of bits to right shift raw address after masking * with {@link #setXmask} */ @Override public void setXshift(final byte xshift) { this.xshift = xshift; } @Override public int getYmask() { return this.ymask; } /** * @param ymask the bit mask for y address, before shift */ @Override public void setYmask(final int ymask) { this.ymask = ymask; } @Override public byte getYshift() { return this.yshift; } /** * @param yshift the number of bits to right shift raw address after masking * with {@link #setYmask} */ @Override public void setYshift(final byte yshift) { this.yshift = yshift; } // short clipx(short v){ short c=(short) (v>(chip.sizeX-1)? chip.sizeX-1: v); c=c<0?0:c; return c;} // short clipy(short v){ short c= (short)(v>(chip.sizeY-1)? chip.sizeY-1: v); c=c<0?0:c; return c;} @Override public boolean isFlipx() { return this.flipx; } @Override public void setFlipx(final boolean flipx) { if (chip.getSizeX() == 1) { log.warning("setFlipx for chip" + chip + ": chip sizeX=1, flipping doesn't make sense, disabling"); this.flipx = false; return; } this.flipx = flipx; } @Override public boolean isFlipy() { return this.flipy; } @Override public void setFlipy(final boolean flipy) { if (chip.getSizeY() == 1) { log.warning("setFlipy for chip" + chip + ": chip sizeY=1, flipping doesn't make sense, disabling"); this.flipy = false; return; } this.flipy = flipy; } @Override public boolean isFliptype() { return this.fliptype; } @Override public void setFliptype(final boolean fliptype) { if (chip.getNumCellTypes() == 1) { log.warning("setFliptype for chip" + chip + ": chip numTypes=1, flipping doesn't usually make sense, will treat it to make type=1 instead of default 0"); // this.fliptype=false; // return; } this.fliptype = fliptype; } @Override public int getUsedBits() { return ((xmask << (xshift + ymask) << (yshift + typemask) << typeshift)); } @Override public boolean matchesAddress(int addr1, int addr2) { return (addr1 & getUsedBits()) == (addr2 & getUsedBits()); } /** * Computes the raw address from an x,y, and type. Useful for searching for * events in e.g. matlab, given the raw addresses. This function does * include flipped addresses - it uses flip booleans to pre-adjust x,y,type * for chip. * * @param x the x address * @param y the y address * @param type the cell type * @return the raw address */ @Override public int getAddressFromCell(int x, int y, int type) { if (flipx) { x = sizexm1 - x; } if (flipy) { y = sizeym1 - y; } if (fliptype) { type = sizetypem1 - type; } return (x << xshift) | (y << yshift) | (type << typeshift); } /** * Returns the e.address field from the event, which is the address * csaptured during hardware acquisition. If subclasses want to override * this functionality they can either override this method to match what * their <code>EventExtractor2D</code> actually does, or perhaps use the * {@code #reconstructRawAddressFromEvent} method to provide a default * reconstruction (which particular raw address encodings most likely do not * use. * * @param e * @return the raw address. * @see #reconstructDefaultRawAddressFromEvent(net.sf.jaer.event.TypedEvent) * @see #reconstructRawPacket(net.sf.jaer.event.EventPacket) */ public int reconstructRawAddressFromEvent(TypedEvent e) { return e.address; } /** * Computes a default binary representation of the event based on xshift, * yshift, flipx, flipy, fliptype and the array sizes. Subclasses must * override this method if they want to write out data after processing and {@link #reconstructRawPacket(net.sf.jaer.event.EventPacket) * } is used in the packet reconstruction from processed EventPackets. * * @param e * @return the raw address. * @see #reconstructRawAddressFromEvent(net.sf.jaer.event.TypedEvent) * @see #reconstructRawPacket(net.sf.jaer.event.EventPacket) */ public int reconstructDefaultRawAddressFromEvent(TypedEvent e) { int x = e.x, y = e.y, type = e.type; if (flipx) { x = (sizexm1 - e.x); } if (flipy) { y = (sizeym1 - e.y); } if (fliptype) { type = (sizetypem1 - e.type); } return (x << xshift) | (y << yshift) | (type << typeshift); } @Override public boolean isSubsamplingEnabled() { return subsamplingEnabled; } /** * Sets whether large packets are sub-sampled to reduce processing time. * * @param subsamplingEnabled */ @Override public void setSubsamplingEnabled(boolean subsamplingEnabled) { this.subsamplingEnabled = subsamplingEnabled; } @Override public int getSubsampleThresholdEventCount() { return subsampleThresholdEventCount; } /** * Sets the number of events for th eextractor above which subsamppling may * be enabled. * * @param subsampleThresholdEventCount */ @Override public void setSubsampleThresholdEventCount(int subsampleThresholdEventCount) { this.subsampleThresholdEventCount = subsampleThresholdEventCount; } public AEPacketRaw raw = null; /** * Returns a raw packet suitable for writing to a data file or network * stream from an EventPacket that could be the result of filtering * operations. * <p> * This filtering may not be reflected in the output of the reconstruction * because the default implementation of * {@code #reconstructRawAddressFromEvent} uses the raw address stored in * the event for efficiency. * * @param packet the EventPacket * @return a raw packet holding the device events. This raw packet is reused * for every call to <code>reconstructRawPacket</code>. * @see #reconstructRawAddressFromEvent(net.sf.jaer.event.TypedEvent) */ @Override public AEPacketRaw reconstructRawPacket(EventPacket<T> packet) { if (raw == null) { raw = new AEPacketRaw(); } raw.ensureCapacity(packet.getSize()); raw.setNumEvents(0); int[] a = raw.addresses; int[] ts = raw.timestamps; int n = 0; for (BasicEvent o : packet) { if (o.isFilteredOut()) { continue; } TypedEvent e = (TypedEvent) o; ts[n] = e.timestamp; a[n++] = reconstructRawAddressFromEvent(e); //getAddressFromCell(e.x,e.y,e.type); // uses the new (May 2010) field for the raw address which is initially captured from hardware } raw.setNumEvents(n); // EventRaw r=new EventRaw(); // for(Object o:packet){ // TypedEvent e=(TypedEvent)o; // r.timestamp=e.timestamp; // r.address=getAddressFromCell(e.x,e.y,e.type); // raw.addEvent(r); return raw; } }
package org.jenkins.tools.test; import com.beust.jcommander.IParameterValidator; import com.beust.jcommander.IStringConverter; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import hudson.util.VersionNumber; import java.io.File; import java.util.List; import javax.annotation.CheckForNull; import org.jenkins.tools.test.model.PCTPlugin; import org.jenkins.tools.test.model.TestStatus; /** * POJO containing CLI arguments &amp; help. * * @author Frederic Camblor */ public class CliOptions { @Parameter(names = "-updateCenterUrl", description = "Update center JSON file URL") private String updateCenterUrl = null; @Parameter(names = "-parentCoordinates", description = "Parent pom GAV in the form groupId:artifactId[:version].\n" + "If null/empty, every core coordinates located in report XML files will be tested.") private String parentCoord = null; @Parameter(names = "-war", description = "A WAR file to scan for plugins rather than looking in the update center.") private File war = null; @CheckForNull @Parameter(names = "-testJDKHome", description = "A path to JDK HOME to be used for running tests in plugins.") private File testJDKHome = null; @CheckForNull @Parameter(names = "-testJavaArgs", description = "Java test arguments to be used for test runs.") private String testJavaArgs = null; @Parameter(names = "-workDirectory", required = true, description = "Work directory where plugin sources will be checked out") private File workDirectory; @Parameter(names = "-reportFile", required = true, description = "Output report xml file path. This path must contain a directory, e.g. 'out/pct-report.xml'") private File reportFile; @Parameter(names = "-includePlugins", description = "Comma separated list of plugins' artifactId to test.\n" + "If not set, every plugin will be tested.") private String includePlugins = null; @Parameter(names = "-excludePlugins", description = "Comma separated list of plugins' artifactId to NOT test.\n" + "If not set, see includePlugins behaviour.") private String excludePlugins = null; @Parameter(names = "-fallbackGitHubOrganization", description = "Include an alternative organization to use as a fallback to download the plugin.\n" + "It is useful to use your own fork releases for an specific plugin if the " + "version is not found in the official repository.\n" + "If set, The PCT will try to use the fallback if a plugin tag is not found in the regular URL.") private String fallbackGitHubOrganization = null; @Parameter(names = "-m2SettingsFile", description = "Maven settings file used while executing maven") private File m2SettingsFile; @Parameter(names = "-mvn", description = "External Maven executable") @CheckForNull private File externalMaven; @Parameter(names = "-skipTestCache", description = "Allows to skip compatibility test cache (by default, to 100 days)\n" + "If set to true, every plugin will be tested, no matter the cache is.") private String skipTestCache = null; @Parameter(names = "-testCacheTimeout", description = "Allows to override the test cache timeout.\n" + "Test cache timeout allows to not perform compatibility test over\n" + "some plugins if compatibility test was performed recently.\n" + "Cache timeout is given in milliseconds") private Long testCacheTimeout = null; @Parameter(names = "-cacheThresholdStatus", description = "Allows to define a minimal cache threshold for test status.\n" + "That is to say, every results lower than this threshold won't be considered\n" + "as part of the cache") private String cacheThresholdStatus = TestStatus.COMPILATION_ERROR.toString(); @Parameter(names="-mavenProperties", description = "Define extra properties to be passed to the build." + "Format: 'KEY1=VALUE1:KEY2=VALUE2'. These options will be used a la -D.\n" + "If your property values contain ':' you must use the 'mavenPropertiesFile' option instead.") private String mavenProperties; @Parameter(names="-mavenPropertiesFile", description = "Allow loading some maven properties from a file using the standard java.util.Properties file format. " + "These options will be used a la -D") private String mavenPropertiesFile; @Parameter(names="-hookPrefixes", description = "Prefixes of the extra hooks' classes") private String hookPrefixes; @Parameter(names="-localCheckoutDir", description = "Folder containing either a local (possibly modified) clone of a plugin repository or a set of local clone of different plugins") private String localCheckoutDir; @Parameter(names="-help", description = "Print this help message", help = true) private boolean printHelp; @Parameter(names = "-overridenPlugins", description = "List of plugins to use to test a plugin in place of the normal dependencies." + "Format: '[GROUP_ID:]PLUGIN_NAME=PLUGIN_VERSION", converter = PluginConverter.class, validateWith = PluginValidator.class) private List<PCTPlugin> overridenPlugins; @Parameter(names = "-failOnError", description = "Immediately if the PCT run fails for a plugin. Error status will be also reported as a return code") private boolean failOnError; @Parameter(names = "-storeAll", description = "By default only failed tests are stored in PCT report file. \n" + "If set, the PCT will store ALL executed test names for each plugin in report file. \n" + "Disabled by default because it may bloat reports for plugins which thousands of tests." ) private Boolean storeAll = null; @Parameter(names = "-bom", description = "BOM file to be used for plugin versions rather than an Update Center or War file") private File bom; public String getUpdateCenterUrl() { return updateCenterUrl; } public String getParentCoord() { return parentCoord; } public File getWar() { return war; } public File getReportFile() { return reportFile; } public File getWorkDirectory() { return workDirectory; } public String getIncludePlugins() { return includePlugins; } public File getM2SettingsFile() { return m2SettingsFile; } public File getExternalMaven() { return externalMaven; } public String getSkipTestCache() { return skipTestCache; } public Long getTestCacheTimeout() { return testCacheTimeout; } public String getExcludePlugins() { return excludePlugins; } public String getFallbackGitHubOrganization() { return fallbackGitHubOrganization; } @CheckForNull public String getMavenProperties() { return mavenProperties; } @CheckForNull public String getMavenPropertiesFile() { return mavenPropertiesFile; } public String getCacheThresholdStatus() { return cacheThresholdStatus; } public String getHookPrefixes() { return hookPrefixes; } public String getLocalCheckoutDir() { return localCheckoutDir; } public boolean isPrintHelp() { return printHelp; } @CheckForNull public File getTestJDKHome() { return testJDKHome; } @CheckForNull public String getTestJavaArgs() { return testJavaArgs; } @CheckForNull public List<PCTPlugin> getOverridenPlugins() { return overridenPlugins; } @CheckForNull public File getBOM() { return this.bom; } public boolean isFailOnError() { return failOnError; } public Boolean isStoreAll() { return storeAll; } public static class PluginConverter implements IStringConverter<PCTPlugin> { @Override public PCTPlugin convert(String s) { String[] details = s.split("="); String name = details[0]; int colon = name.indexOf(':'); return new PCTPlugin(colon == -1 ? name : name.substring(colon + 1), colon == -1 ? null : name.substring(0, colon), new VersionNumber(details[1])); } } public static class PluginValidator implements IParameterValidator { @Override public void validate(String name, String value) throws ParameterException { for (String s : value.split(",")) { final String[] split = s.split("="); if (split.length != 2) { throw new ParameterException(name + " must be formatted as NAME=VERSION"); } } } } }
package nl.mpi.arbil; import java.util.Enumeration; import javax.swing.table.DefaultTableModel; /** * Document : ImdiFieldViewTableModel * This table model is used to edit the field view for a given imdi table model * Split from ImdiFieldViews on : Dec 16, 2008, 10:27:30 AM * @author Peter.Withers@mpi.nl */ public class ImdiFieldViewTableModel extends DefaultTableModel { private ImdiTableModel imdiTableModel; public ImdiFieldViewTableModel(ImdiTableModel localImdiTableModel) { imdiTableModel = localImdiTableModel; //System.out.println("setting to: " + viewLabel); // "Column Description", is not relevant here because this is a list of column names not imdi fields setColumnIdentifiers(new String[]{"Column Name", "Show Only", "Hide"}); //, "Always Display" // we want a table model even if it has no rows LinorgFieldView currentView = imdiTableModel.getFieldView(); if (currentView != null) { // loop the known columns for (Enumeration knownColumnNames = ((LinorgFieldView) currentView).getKnownColumns(); knownColumnNames.hasMoreElements();) { String currentFieldName = knownColumnNames.nextElement().toString(); this.addRow(new Object[]{currentFieldName, //GuiHelper.imdiSchema.getHelpForField(currentFieldName), // set the show only fields ((LinorgFieldView) currentView).isShowOnlyColumn(currentFieldName), // set the hidden fields ((LinorgFieldView) currentView).isHiddenColumn(currentFieldName) // set alays show fields //((LinorgFieldView) currentView).isAlwaysShowColumn(currentFieldName) }); } } } Class[] types = new Class[]{ java.lang.String.class, /*java.lang.String.class,*/ java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class }; private int showOnlyEnabledCount = -1; private final int showOnlyColumn = 1; private final int fieldNameColumn = 0; private final int hideColumn = 2; public Class getColumnClass(int columnIndex) { return types[columnIndex]; } @Override public boolean isCellEditable(int row, int column) { // System.out.println("isCellEditable showOnlyEnabledCount: " + showOnlyEnabledCount); if (column == hideColumn) { if (showOnlyEnabledCount < 0) { // count the show only selection showOnlyEnabledCount = 0; for (int rowCounter = 0; rowCounter < getRowCount(); rowCounter++) { //if (((Boolean) getValueAt(rowCounter, showOnlyColumn)) == true) { if (getValueAt(rowCounter, showOnlyColumn).equals(true)) { showOnlyEnabledCount++; } } } return showOnlyEnabledCount == 0; // return (getValueAt(row, showOnlyColumn).equals(true) || showOnlyEnabledCount == 0); } return (column == showOnlyColumn || column == hideColumn); } @Override public void setValueAt(Object aValue, int row, int column) { super.setValueAt(aValue, row, column); // System.out.println("setValueAt showOnlyEnabledCount reset"); // clear the show only count to retrigger the checking process showOnlyEnabledCount = -1; // fireTableDataChanged(); boolean booleanState = aValue.equals(true); String targetColumnName = getValueAt(row, fieldNameColumn).toString(); switch (column) { case showOnlyColumn: if (booleanState) { imdiTableModel.getFieldView().addShowOnlyColumn(targetColumnName); } else { imdiTableModel.getFieldView().removeShowOnlyColumn(targetColumnName); } break; case hideColumn: if (booleanState) { imdiTableModel.getFieldView().addHiddenColumn(targetColumnName); } else { imdiTableModel.getFieldView().removeHiddenColumn(targetColumnName); } break; case 4: if (booleanState) { imdiTableModel.getFieldView().addAlwaysShowColumn(targetColumnName); } else { imdiTableModel.getFieldView().removeAlwaysShowColumn(targetColumnName); } break; } imdiTableModel.requestReloadTableData(); fireTableStructureChanged(); }//returnTableModel.setRowCount(0); }
package imagej.core.commands.overlay; import imagej.command.Command; import imagej.command.ContextCommand; import imagej.data.Dataset; import imagej.data.display.ImageDisplay; import imagej.data.display.ImageDisplayService; import imagej.data.overlay.BinaryMaskOverlay; import imagej.data.overlay.Overlay; import imagej.data.overlay.ThresholdOverlay; import imagej.data.threshold.ThresholdService; import imagej.menu.MenuConstants; import imagej.util.ColorRGB; import net.imglib2.RandomAccess; import net.imglib2.img.Img; import net.imglib2.img.array.ArrayImg; import net.imglib2.img.array.ArrayImgFactory; import net.imglib2.img.basictypeaccess.array.BitArray; import net.imglib2.img.transform.ImgTranslationAdapter; import net.imglib2.ops.pointset.PointSetIterator; import net.imglib2.roi.BinaryMaskRegionOfInterest; import net.imglib2.type.logic.BitType; import org.scijava.Context; import org.scijava.ItemIO; import org.scijava.plugin.Menu; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; /** * Creates an {@link Overlay} representing the thresholded pixels of a * {@link Dataset}. * * @author Lee Kamentsky * @author Barry DeZonia */ @Plugin(type = Command.class, menu = { @Menu(label = MenuConstants.PROCESS_LABEL, weight = MenuConstants.PROCESS_WEIGHT, mnemonic = MenuConstants.PROCESS_MNEMONIC), @Menu(label = "Binary", mnemonic = 'b'), @Menu(label = "Convert to Mask", weight = 1) }, headless = true) public class ConvertToMask extends ContextCommand { // TODO - this points out an issue with threshold service. Does it map // thresh overlays to image displays or datasets. In the support code both // are used. @Parameter( label = "Input display", description = "The display containing the image to be converted to a binary mask.") private ImageDisplay input; @Parameter(label = "Output mask", description = "The overlay that is the result of the operation", type = ItemIO.OUTPUT) private Overlay output; @Parameter(label = "Overlay color", description = "The color used to display the overlay") private ColorRGB color = new ColorRGB(255, 0, 0); @Parameter(label = "Overlay alpha", description = "The transparency " + "(transparent = 0) or opacity (opaque=255) of the overlay", min = "0", max = "255") private int alpha = 128; @Parameter private Context context; @Parameter private ImageDisplayService dispSrv; @Parameter private ThresholdService threshSrv; @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public void run() { if (!threshSrv.hasThreshold(input)) { cancel("This command requires a thresholded image."); return; } ThresholdOverlay thresh = threshSrv.getThreshold(input); PointSetIterator iter = thresh.getPointsWithin().iterator(); if (!iter.hasNext()) { cancel("No pixels are within the threshold"); return; } Dataset ds = dispSrv.getActiveDataset(input); final int numDims = ds.numDimensions(); final long[] dimensions = new long[numDims]; final long[] min = new long[numDims]; /* * First pass - find minima and maxima so we can use a shrunken image in some cases. */ for (int i = 0; i < numDims; i++) { min[i] = (long) Math.floor(thresh.realMin(i)); dimensions[i] = (long) Math.floor(thresh.realMax(i) - thresh.realMin(i) + 1); } final ArrayImg<BitType, BitArray> arrayMask = new ArrayImgFactory<BitType>().createBitInstance(dimensions, 1); final BitType t = new BitType(arrayMask); arrayMask.setLinkedType(t); final Img<BitType> mask = new ImgTranslationAdapter<BitType, ArrayImg<BitType, BitArray>>( arrayMask, min); final RandomAccess<BitType> raMask = mask.randomAccess(); iter.reset(); while (iter.hasNext()) { long[] pos = iter.next(); raMask.setPosition(pos); raMask.get().set(true); } output = new BinaryMaskOverlay(context, new BinaryMaskRegionOfInterest<BitType, Img<BitType>>(mask)); output.setAlpha(alpha); output.setFillColor(color); for (int i = 0; i < numDims; i++) { output.setAxis(ds.axis(i), i); } } public void setInput(ImageDisplay disp) { input = disp; } public ImageDisplay getInput() { return input; } public void setColor(ColorRGB val) { color = val; } public ColorRGB getColor() { return color; } public void setAlpha(int val) { alpha = val; } public int getAlpha() { return alpha; } public Overlay getOutput() { return output; } }
package com.intellij.tasks.redmine; import com.google.gson.Gson; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.StringUtil; import com.intellij.tasks.Task; import com.intellij.tasks.impl.gson.GsonUtil; import com.intellij.tasks.impl.httpclient.NewBaseRepositoryImpl; import com.intellij.tasks.redmine.model.RedmineIssue; import com.intellij.tasks.redmine.model.RedmineProject; import com.intellij.tasks.redmine.model.RedmineResponseWrapper; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xmlb.annotations.Tag; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import static com.intellij.tasks.impl.httpclient.ResponseUtil.GsonSingleObjectDeserializer; import static com.intellij.tasks.redmine.model.RedmineResponseWrapper.*; /** * @author Mikhail Golubev * @author Dennis.Ushakov */ @Tag("Redmine") public class RedmineRepository extends NewBaseRepositoryImpl { private static final Logger LOG = Logger.getInstance(RedmineRepository.class); private static final Gson GSON = GsonUtil.createDefaultBuilder().create(); public static final RedmineProject UNSPECIFIED_PROJECT = new RedmineProject() { @NotNull @Override public String getName() { return "-- from all projects --"; } @Override public int getId() { return -1; } }; private String myAPIKey = ""; private RedmineProject myCurrentProject; /** * Serialization constructor */ @SuppressWarnings({"UnusedDeclaration"}) public RedmineRepository() { // empty } /** * Normal instantiation constructor */ public RedmineRepository(RedmineRepositoryType type) { super(type); setUseHttpAuthentication(true); } /** * Cloning constructor */ public RedmineRepository(RedmineRepository other) { super(other); setAPIKey(other.myAPIKey); setCurrentProject(other.getCurrentProject()); } @Override public boolean equals(Object o) { if (!super.equals(o)) return false; if (!(o instanceof RedmineRepository)) return false; RedmineRepository that = (RedmineRepository)o; if (!Comparing.equal(getAPIKey(), that.getAPIKey())) return false; if (!Comparing.equal(getCurrentProject(), that.getCurrentProject())) return false; return true; } @Override public RedmineRepository clone() { return new RedmineRepository(this); } @Override public void testConnection() throws Exception { getIssues("", 0, 1, true); } @Override public Task[] getIssues(@Nullable String query, int offset, int limit, boolean withClosed) throws Exception { List<RedmineIssue> issues = fetchIssues(query, offset, limit, withClosed); return ContainerUtil.map2Array(issues, RedmineTask.class, new Function<RedmineIssue, RedmineTask>() { @Override public RedmineTask fun(RedmineIssue issue) { return new RedmineTask(issue, RedmineRepository.this); } }); } public List<RedmineIssue> fetchIssues(String query, int offset, int limit, boolean withClosed) throws Exception { URIBuilder builder = new URIBuilder(getRestApiUrl("issues.json")) .addParameter("offset", String.valueOf(offset)) .addParameter("limit", String.valueOf(limit)) .addParameter("status_id", withClosed ? "*" : "open") .addParameter("assigned_to_id", "me"); // Legacy API, can't find proper documentation //if (StringUtil.isNotEmpty(query)) { // builder.addParameter("fields[]", "subject").addParameter("operators[subject]", "~").addParameter("values[subject][]", query); // If project was not chosen, all available issues still fetched. Such behavior may seems strange to user. if (myCurrentProject != null && myCurrentProject != UNSPECIFIED_PROJECT) { builder.addParameter("project_id", String.valueOf(myCurrentProject.getId())); } if (isUseApiKeyAuthentication()) { builder.addParameter("key", myAPIKey); } HttpClient client = getHttpClient(); HttpGet method = new HttpGet(builder.toString()); return client.execute(method, new GsonSingleObjectDeserializer<IssuesWrapper>(GSON, IssuesWrapper.class)).getIssues(); } public List<RedmineProject> fetchProjects() throws Exception { URIBuilder builder = new URIBuilder(getRestApiUrl("projects.json")); if (isUseApiKeyAuthentication()) { builder.addParameter("key", myAPIKey); } HttpClient client = getHttpClient(); HttpGet method = new HttpGet(builder.toString()); return client.execute(method, new GsonSingleObjectDeserializer<ProjectsWrapper>(GSON, RedmineResponseWrapper.ProjectsWrapper.class)).getProjects(); } @Nullable @Override public Task findTask(String id) throws Exception { HttpGet method = new HttpGet(getRestApiUrl("issues", id + ".json")); IssueWrapper wrapper = getHttpClient().execute(method, new GsonSingleObjectDeserializer<IssueWrapper>(GSON, IssueWrapper.class)); if (wrapper == null) { return null; } return new RedmineTask(wrapper.getIssue(), this); } public String getAPIKey() { return myAPIKey; } public void setAPIKey(String APIKey) { myAPIKey = APIKey; } private boolean isUseApiKeyAuthentication() { return !StringUtil.isEmptyOrSpaces(myAPIKey) && !isUseHttpAuthentication(); } @Override public String getPresentableName() { String name = super.getPresentableName(); if (myCurrentProject != null && myCurrentProject != UNSPECIFIED_PROJECT) { name += "/projects/" + myCurrentProject.getIdentifier(); } return name; } @Override public boolean isConfigured() { if (!super.isConfigured() || StringUtil.isEmpty(myUsername)) return false; if (isUseHttpAuthentication()) { return StringUtil.isNotEmpty(myPassword); } return !StringUtil.isEmptyOrSpaces(myAPIKey); } @Nullable @Override public String extractId(String taskName) { return taskName; } @Override protected int getFeatures() { return super.getFeatures() | BASIC_HTTP_AUTHORIZATION; } @Nullable public RedmineProject getCurrentProject() { return myCurrentProject; } public void setCurrentProject(@Nullable RedmineProject project) { myCurrentProject = project != null && project.getId() == -1 ? UNSPECIFIED_PROJECT : project; } }
package com.coreoz.plume.admin.webservices; import java.security.SecureRandom; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import com.coreoz.plume.admin.security.login.LoginFailAttemptsManager; import com.coreoz.plume.admin.services.configuration.AdminConfigurationService; import com.coreoz.plume.admin.services.configuration.AdminSecurityConfigurationService; import com.coreoz.plume.admin.services.user.AdminUserService; import com.coreoz.plume.admin.services.user.AuthenticatedUser; import com.coreoz.plume.admin.webservices.data.session.AdminCredentials; import com.coreoz.plume.admin.webservices.data.session.AdminSession; import com.coreoz.plume.admin.webservices.validation.AdminWsError; import com.coreoz.plume.admin.websession.JwtSessionSigner; import com.coreoz.plume.admin.websession.WebSessionAdmin; import com.coreoz.plume.admin.websession.WebSessionPermission; import com.coreoz.plume.admin.websession.jersey.JerseySessionParser; import com.coreoz.plume.jersey.errors.Validators; import com.coreoz.plume.jersey.errors.WsException; import com.coreoz.plume.jersey.security.permission.PublicApi; import com.coreoz.plume.services.time.TimeProvider; import com.google.common.collect.ImmutableList; import com.google.common.io.BaseEncoding; import com.google.common.net.HttpHeaders; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.AllArgsConstructor; import lombok.Getter; @Path("/admin/session") @Api(value = "Manage the administration session") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) // This API is marked as public, since it must be accessed without any authentication @PublicApi @Singleton public class SessionWs { public static final FingerprintWithHash NULL_FINGERPRINT = new FingerprintWithHash(null, null); private final AdminUserService adminUserService; private final JwtSessionSigner jwtSessionSigner; private final TimeProvider timeProvider; private final LoginFailAttemptsManager failAttemptsManager; private final long blockedDurationInSeconds; private final long maxTimeSessionDurationInMilliseconds; private final long sessionRefreshDurationInMillis; private final long sessionInactiveDurationInMillis; private final SecureRandom fingerprintGenerator; private final boolean sessionUseFingerprintCookie; private final boolean sessionFingerprintCookieHttpsOnly; @Inject public SessionWs(AdminUserService adminUserService, JwtSessionSigner jwtSessionSigner, AdminConfigurationService configurationService, AdminSecurityConfigurationService adminSecurityConfigurationService, TimeProvider timeProvider) { this.adminUserService = adminUserService; this.jwtSessionSigner = jwtSessionSigner; this.timeProvider = timeProvider; this.failAttemptsManager = new LoginFailAttemptsManager( configurationService.loginMaxAttempts(), configurationService.loginBlockedDuration() ); this.blockedDurationInSeconds = configurationService.loginBlockedDuration().getSeconds(); this.maxTimeSessionDurationInMilliseconds = configurationService.sessionExpireDurationInMillis(); this.sessionRefreshDurationInMillis = configurationService.sessionRefreshDurationInMillis(); this.sessionInactiveDurationInMillis = configurationService.sessionInactiveDurationInMillis(); this.fingerprintGenerator = new SecureRandom(); this.sessionUseFingerprintCookie = adminSecurityConfigurationService.sessionUseFingerprintCookie(); this.sessionFingerprintCookieHttpsOnly = adminSecurityConfigurationService.sessionFingerprintCookieHttpsOnly(); } @POST @ApiOperation(value = "Authenticate a user and create a session token") public Response authenticate(AdminCredentials credentials) { // first user needs to be authenticated (an exception will be raised otherwise) AuthenticatedUser authenticatedUser = authenticateUser(credentials); // if the client is authenticated, the fingerprint can be generated if needed FingerprintWithHash fingerprintWithHash = sessionUseFingerprintCookie ? generateFingerprint() : NULL_FINGERPRINT; return withFingerprintCookie( Response.ok(toAdminSession(toWebSession(authenticatedUser, fingerprintWithHash.getHash()))), fingerprintWithHash.getFingerprint() ) .build(); } @PUT @Consumes(MediaType.TEXT_PLAIN) @ApiOperation(value = "Renew a valid session token") public AdminSession renew(String webSessionSerialized) { Validators.checkRequired("sessionToken", webSessionSerialized); WebSessionAdmin parsedSession = jwtSessionSigner.parseSession( webSessionSerialized, WebSessionAdmin.class ); if(parsedSession == null) { throw new WsException(AdminWsError.ALREADY_EXPIRED_SESSION_TOKEN); } return toAdminSession(parsedSession); } public AuthenticatedUser authenticateUser(AdminCredentials credentials) { Validators.checkRequired("Json creadentials", credentials); Validators.checkRequired("users.USERNAME", credentials.getUserName()); Validators.checkRequired("users.PASSWORD", credentials.getPassword()); if(credentials.getUserName() != null && failAttemptsManager.isBlocked(credentials.getUserName())) { throw new WsException( AdminWsError.TOO_MANY_WRONG_ATTEMPS, ImmutableList.of(String.valueOf(blockedDurationInSeconds)) ); } return adminUserService .authenticate(credentials.getUserName(), credentials.getPassword()) .orElseThrow(() -> { failAttemptsManager.addAttempt(credentials.getUserName()); return new WsException(AdminWsError.WRONG_LOGIN_OR_PASSWORD); }); } public WebSessionPermission toWebSession(AuthenticatedUser user, String hashedFingerprint) { return new WebSessionAdmin() .setPermissions(user.getPermissions()) .setIdUser(user.getUser().getId()) .setUserName(user.getUser().getUserName()) .setFullName(user.getUser().getFirstName() + " " + user.getUser().getLastName()) .setHashedFingerprint(hashedFingerprint); } public AdminSession toAdminSession(WebSessionPermission webSession) { return new AdminSession( jwtSessionSigner.serializeSession( webSession, timeProvider.currentTime() + maxTimeSessionDurationInMilliseconds ), sessionRefreshDurationInMillis, sessionInactiveDurationInMillis ); } public ResponseBuilder withFingerprintCookie(ResponseBuilder response, String fingerprint) { return response.header( HttpHeaders.SET_COOKIE, JerseySessionParser.FINGERPRINT_COOKIE_NAME + "=" + fingerprint + "; SameSite=Strict; HttpOnly" + (sessionFingerprintCookieHttpsOnly ? "; Secure" : "") ); } public FingerprintWithHash generateFingerprint() { byte[] generatedFingerprintBytes = new byte[50]; fingerprintGenerator.nextBytes(generatedFingerprintBytes); String generatedFingerprint = BaseEncoding.base16().encode(generatedFingerprintBytes); return new FingerprintWithHash( generatedFingerprint, JerseySessionParser.hashFingerprint(generatedFingerprint) ); } @AllArgsConstructor @Getter public static class FingerprintWithHash { private final String fingerprint; private final String hash; } }
package arez; import arez.spy.ComponentInfo; import arez.spy.ComputedValueInfo; import arez.spy.ObservableValueInfo; import arez.spy.ObserverInfo; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * A implementation of {@link ObserverInfo} that proxies to a {@link Observer}. */ final class ObserverInfoImpl implements ObserverInfo { private final Spy _spy; private final Observer _observer; ObserverInfoImpl( @Nonnull final Spy spy, @Nonnull final Observer observer ) { _spy = Objects.requireNonNull( spy ); _observer = Objects.requireNonNull( observer ); } @Nonnull private static List<ObserverInfo> asInfos( @Nonnull final Collection<Observer> observers ) { return observers .stream() .map( Observer::asInfo ) .collect( Collectors.toList() ); } @Nonnull static List<ObserverInfo> asUnmodifiableInfos( @Nonnull final Collection<Observer> observers ) { return Collections.unmodifiableList( asInfos( observers ) ); } /** * {@inheritDoc} */ @Nonnull @Override public String getName() { return _observer.getName(); } /** * {@inheritDoc} */ @Override public boolean isActive() { return _observer.isActive(); } /** * {@inheritDoc} */ @Override public boolean isRunning() { return _spy.isTransactionActive() && null != getTrackerTransaction(); } /** * {@inheritDoc} */ @Override public boolean isScheduled() { return _observer.isScheduled(); } /** * {@inheritDoc} */ @Override public boolean isComputedValue() { return _spy.isComputedValue( _observer ); } /** * {@inheritDoc} */ @Override public boolean isReadOnly() { return Arez.shouldEnforceTransactionType() && TransactionMode.READ_WRITE != _observer.getMode(); } /** * {@inheritDoc} */ @Nonnull @Override public Priority getPriority() { return _observer.getPriority(); } /** * {@inheritDoc} */ @Override public ComputedValueInfo asComputedValue() { return _spy.asComputedValue( _observer ); } /** * {@inheritDoc} */ @Nonnull @Override public List<ObservableValueInfo> getDependencies() { return _spy.getDependencies( _observer ); } /** * {@inheritDoc} */ @Nullable @Override public ComponentInfo getComponent() { return _spy.getComponent( _observer ); } /** * {@inheritDoc} */ @Override public boolean isDisposed() { return _observer.isDisposed(); } /** * {@inheritDoc} */ @Override public String toString() { return _observer.toString(); } @Override public boolean equals( final Object o ) { if ( this == o ) { return true; } else if ( o == null || getClass() != o.getClass() ) { return false; } else { final ObserverInfoImpl that = (ObserverInfoImpl) o; return _observer.equals( that._observer ); } } @Override public int hashCode() { return _observer.hashCode(); } /** * Get transaction with specified observer as tracker. */ @Nullable private Transaction getTrackerTransaction() { Transaction t = _observer.getContext().getTransaction(); while ( null != t && t.getTracker() != _observer ) { t = t.getPrevious(); } return t; } }
package openperipheral.api; import java.lang.reflect.Method; import openmods.Log; import net.minecraft.tileentity.TileEntity; public class OpenPeripheralAPI { public static boolean register(IPeripheralAdapter adapter) { return register(IPeripheralAdapter.class, adapter, "openperipheral.adapter.AdapterManager", "addPeripheralAdapter"); } public static boolean register(IObjectAdapter adapter) { return register(IPeripheralAdapter.class, adapter, "openperipheral.adapter.AdapterManager", "addObjectAdapter"); } public static boolean createAdapter(Class<? extends TileEntity> cls) { return register(Class.class, cls, "openperipheral.adapter.AdapterManager", "addInlinePeripheralAdapter"); } public static boolean register(ITypeConverter converter) { return register(ITypeConverter.class, converter, "openperipheral.TypeConversionRegistry", "registerTypeConverter"); } public static boolean register(IIntegrationModule module) { return register(IIntegrationModule.class, module, "openperipheral.IntegrationModuleRegistry", "registerModule"); } private static boolean register(Class<?> type, Object obj, String klazzName, String methodName) { try { Class<?> klazz = Class.forName(klazzName); if (klazz != null) { Method method = klazz.getMethod(methodName, new Class[] { type }); method.invoke(null, obj); return true; } } catch (Exception e) { Log.warn(e, "Exception while calling API method '%s'", methodName); } return false; } public static IMultiReturn wrap(final Object... args) { return new IMultiReturn() { @Override public Object[] getObjects() { return args; } }; } }
package org.dimagi.chatscreen; import java.util.Vector; import javax.microedition.lcdui.Canvas; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Graphics; import org.dimagi.entity.Question; import org.dimagi.utils.ViewUtils; import org.dimagi.view.Component; import org.dimagi.view.IRefreshListener; import org.dimagi.view.NavBar; import de.enough.polish.util.VectorIterator; /** * The base container for the Chat Screen interface. * * The ChatScreenForm is responsible for containing and laying out frames, * as well as the control logic used for navigation of protocols. * * It is the primary interface between the Protocol object and the View. * * @author ctsims * */ public class ChatScreenForm extends DForm { //TODO: Add (...) objects to the top and bottom of the display to signal //that there are frames above or below the current view. Vector frameSet = new Vector(); private Vector questions = new Vector(); int counter = 0; int activeQuestion = 0; /** * Creates a new ChatScreen Form */ public ChatScreenForm() { setupComponents(); defineQuestions(); goToNextQuestion(); } private void defineQuestions() { Question first = new Question("Long Label", "Short Label", Constants.TEXTBOX, new String[] {}, Constants.LABEL_LEFT); questions.addElement((Object) first); Question second = new Question( "Is the child having any trouble breathing?", "Trouble Breathing", Constants.SINGLE_CHOICE, new String[] { "Yes", "No" }); questions.addElement((Object) second); Question third = new Question( "What is the name of the child?", "Child Name", Constants.SINGLE_CHOICE, new String[] { "Terry", "Michael", "Samanatha" }); questions.addElement((Object)third); Question fourth = new Question( "How is the child's hearing?", "Hearing", Constants.MULTIPLE_CHOICE, new String[] { "Good", "Bad", "Getting Worse", "Abysmal" }, Constants.LABEL_LEFT); questions.addElement((Object)fourth); } /** * Lays out the static components for the form */ private void setupComponents() { int width = this.getWidth(); int height = this.getHeight(); int frameCanvasHeight = height - (height / 11); getContentComponent().setBackgroundColor(ViewUtils.GREY); } /** * Pushes a new question onto the stack, setting all other * questions to inactive status, and displaying the new question * to the user. * * @param theQuestion The new question to be displayed */ public void addQuestion(Question theQuestion) { Frame newFrame = new Frame(theQuestion); newFrame.setWidth(this.getWidth()); frameSet.insertElementAt(newFrame, 0); getContentComponent().add(newFrame); setupFrames(); this.repaint(); } public void goToNextQuestion() { if (activeQuestion != 0) { activeQuestion setupFrames(); } else { if ( counter < questions.size() ) { addQuestion((Question)(questions.elementAt(counter))); } else { addQuestion((Question)(questions.elementAt(3))); } counter++; } } public void goToPreviousQuestion() { if (activeQuestion < 0) { activeQuestion++; setupFrames(); } } /** * Queries all frames for their optimal size, and then lays them out * in a simple stack. */ private void setupFrames() { VectorIterator iter = new VectorIterator(frameSet); int frameCanvasHeight = getContentComponent().getHeight() - (getContentComponent().getHeight() / 11); int frameStart = frameCanvasHeight; //TODO: Stop displaying frames once they're off the screen int i=0; while (iter.hasNext()) { Frame aFrame = (Frame) iter.next(); if ( i == activeQuestion ) { aFrame.setActiveFrame(true); } else { aFrame.setActiveFrame(false); } frameStart -= aFrame.getHeight(); aFrame.setY(frameStart); i++; } } }
package org.exist.xquery.test; import java.io.IOException; import java.io.StringReader; import java.net.BindException; import java.util.Iterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.stream.StreamSource; import org.custommonkey.xmlunit.XMLTestCase; import org.exist.StandaloneServer; import org.exist.storage.DBBroker; import org.exist.xmldb.CollectionImpl; import org.exist.xmldb.DatabaseInstanceManager; import org.exist.xmldb.XPathQueryServiceImpl; import org.exist.xquery.XPathException; import org.mortbay.util.MultiException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.Collection; import org.xmldb.api.base.CompiledExpression; import org.xmldb.api.base.Database; import org.xmldb.api.base.Resource; import org.xmldb.api.base.ResourceIterator; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.CollectionManagementService; import org.xmldb.api.modules.XMLResource; import org.xmldb.api.modules.XPathQueryService; import org.xmldb.api.modules.XQueryService; public class XPathQueryTest extends XMLTestCase { private final static String nested = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<test><c></c><b><c><b></b></c></b><b></b><c></c></test>"; private final static String numbers = "<test>" + "<item id='1' type='alphanum'><price>5.6</price><stock>22</stock></item>" + "<item id='2'><price>7.4</price><stock>43</stock></item>" + "<item id='3'><price>18.4</price><stock>5</stock></item>" + "<item id='4'><price>65.54</price><stock>16</stock></item>" + "</test>"; private final static String numbers2 = "<test xmlns=\"http://numbers.org\">" + "<item id='1' type='alphanum'><price>5.6</price><stock>22</stock></item>" + "<item id='2'><price>7.4</price><stock>43</stock></item>" + "<item id='3'><price>18.4</price><stock>5</stock></item>" + "<item id='4'><price>65.54</price><stock>16</stock></item>" + "</test>"; private final static String namespaces = "<test xmlns='http: + " <section>" + " <title>Test Document</title>" + " <c:comment xmlns:c='http: + " </section>" + "</test>"; private final static String strings = "<test>" + "<string>Hello World!</string>" + "<string value='Hello World!'/>" + "<string>Hello</string>" + "</test>"; private final static String nested2 = "<RootElement>" + "<ChildA>" + "<ChildB id=\"2\"/>" + "</ChildA>" + "</RootElement>"; private final static String nested3 = "<test>" + " <a>" + " <t>1</t>" + " <a>" + " <t>2</t>" + " <a>" + " <t>3</t>" + " </a>" + " </a>" + " </a>" + "</test>"; private final static String siblings = "<test>" + " <a> <s>A</s> <n>1</n> </a>" + " <a> <s>Z</s> <n>2</n> </a>" + " <a> <s>B</s> <n>3</n> </a>" + " <a> <s>Z</s> <n>4</n> </a>" + " <a> <s>C</s> <n>5</n> </a>" + " <a> <s>Z</s> <n>6</n> </a>" + "</test>"; private final static String ids = "<!DOCTYPE test [" + "<!ELEMENT test (a | b | c | d)*>" + "<!ATTLIST test xml:space CDATA #IMPLIED>" + "<!ELEMENT a EMPTY>" + "<!ELEMENT b (name)>" + "<!ELEMENT c (name)>" + "<!ELEMENT d EMPTY>" + "<!ATTLIST d ref IDREF #IMPLIED>" + "<!ELEMENT name (#PCDATA)>" + "<!ATTLIST a ref IDREF #IMPLIED>" + "<!ATTLIST b id ID #IMPLIED>" + "<!ATTLIST c xml:id ID #IMPLIED>]>" + "<test xml:space=\"preserve\">" + "<a ref=\"id1\"/>" + "<a ref=\"id1\"/>" + "<d ref=\"id2\"/>" + "<b id=\"id1\"><name>one</name></b>" + "<c xml:id=\" id2 \"><name>two</name></c>" + "</test>"; private final static String date = "<timestamp date=\"2006-04-29+02:00\"/>"; private final static String quotes = "<test><title>&quot;Hello&quot;</title></test>"; private final static String ws = "<test><parent xml:space=\"preserve\"><text> </text><text xml:space=\"default\"> </text></parent></test>"; private final static String self = "<test-self><a>Hello</a><b>World!</b></test-self>"; // Added by Geoff Shuetrim (geoff@galexy.net) to highlight problems with XPath queries of elements called 'xpointer'. private final static String xpointerElementName = "<test><xpointer/></test>"; private static String uri = "xmldb:exist://" + DBBroker.ROOT_COLLECTION; public static void setURI(String collectionURI) { uri = collectionURI; } private static StandaloneServer server = null; private Collection testCollection; private String query; protected void setUp() { if (uri.startsWith("xmldb:exist://localhost")) initServer(); try { // initialize driver Class cl = Class.forName("org.exist.xmldb.DatabaseImpl"); Database database = (Database) cl.newInstance(); database.setProperty("create-database", "true"); DatabaseManager.registerDatabase(database); Collection root = DatabaseManager.getCollection( uri, "admin", null); CollectionManagementService service = (CollectionManagementService) root.getService( "CollectionManagementService", "1.0"); testCollection = service.createCollection("test"); assertNotNull(testCollection); } catch (ClassNotFoundException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } catch (XMLDBException e) { e.printStackTrace(); } } private void initServer() { try { if (server == null) { server = new StandaloneServer(); if (!server.isStarted()) { try { System.out.println("Starting standalone server..."); String[] args = {}; server.run(args); while (!server.isStarted()) { Thread.sleep(1000); } } catch (MultiException e) { boolean rethrow = true; Iterator i = e.getExceptions().iterator(); while (i.hasNext()) { Exception e0 = (Exception)i.next(); if (e0 instanceof BindException) { System.out.println("A server is running already !"); rethrow = false; break; } } if (rethrow) throw e; } } } } catch(Exception e) { fail(e.getMessage()); } } protected void tearDown() throws Exception { try { if (!((CollectionImpl) testCollection).isRemoteCollection()) { DatabaseInstanceManager dim = (DatabaseInstanceManager) testCollection.getService( "DatabaseInstanceManager", "1.0"); dim.shutdown(); } testCollection = null; System.out.println("tearDown PASSED"); } catch (XMLDBException e) { e.printStackTrace(); fail(e.getMessage()); } } public void testPathExpression() { try { XQueryService service = storeXMLStringAndGetQueryService("numbers.xml", numbers); //Invalid path expression left operand (not a node set). String message = ""; try { queryAndAssert(service, "('a', 'b', 'c')/position()", -1, null); } catch (XMLDBException e) { message = e.getMessage(); } assertTrue("Exception wanted: " + message, message.indexOf("XPTY0019") > -1); //Undefined context sequence message = ""; try { queryAndAssert(service, "for $a in (<a/>, <b/>, doh, <c/>) return $a", -1, null); } catch (XMLDBException e) { message = e.getMessage(); } assertTrue("Exception wanted: " + message, message.indexOf("XPDY0002") > -1); message = ""; try { //"1 to 2" is resolved as a (1, 2), i.e. a sequence of *integers* which is *not* a singleton queryAndAssert(service, "let $a := (1, 2, 3) for $b in $a[1 to 2] return $b", -1, null); } catch (XMLDBException e) { message = e.getMessage(); } //No effective boolean value for such a kind of sequence ! assertTrue("Exception wanted: " + message, message.indexOf("FORG0006") >-1); queryAndAssert(service, "let $a := ('a', 'b', 'c') return $a[2 to 2]", 1, null); queryAndAssert(service, "let $a := ('a', 'b', 'c') return $a[(2 to 2)]", 1, null); queryAndAssert(service, "()/position()", 0, null); } catch (XMLDBException e) { fail(e.getMessage()); } } /** test simple queries involving attributes */ public void testAttributes() { ResourceSet result; try { String testDocument = "numbers.xml"; String query; XQueryService service = storeXMLStringAndGetQueryService( testDocument, numbers); query = "/test/item[ @id='1' ]"; result = service.queryResource(testDocument, query); System.out.println("testAttributes 1: ========"); printResult(result); assertEquals("XPath: " + query, 1, result.getSize()); XMLResource resource = (XMLResource)result.getResource(0); Node node = resource.getContentAsDOM(); if (node.getNodeType() == Node.DOCUMENT_NODE) node = node.getFirstChild(); assertEquals("XPath: " + query, "item", node.getNodeName()); query = "/test/item [ @type='alphanum' ]"; result = service.queryResource(testDocument, query); System.out.println("testAttributes 2: ========"); printResult(result); assertEquals("XPath: " + query, 1, result.getSize()); } catch (XMLDBException e) { System.out.println("testAttributes(): XMLDBException: " + e); fail(e.getMessage()); } } public void testStarAxis() { ResourceSet result; try { XQueryService service = storeXMLStringAndGetQueryService("numbers.xml", numbers); result = service.queryResource("numbers.xml", "/*/item"); System.out.println("testStarAxis 1: ========"); printResult(result); assertEquals("XPath: /*/item", 4, result.getSize()); result = service.queryResource("numbers.xml", "/*/*"); assertEquals("XPath: /*/*", 4, result.getSize()); queryResource(service, "nested2.xml", "/RootElement/ChildA/parent::*/ChildA/ChildB", 1); service = storeXMLStringAndGetQueryService("numbers.xml", numbers2); service.setNamespace("n", "http://numbers.org"); queryResource(service, "numbers.xml", "//n:price[. = 18.4]/parent::*[@id = '3']", 1); queryResource(service, "numbers.xml", "//n:price[. = 18.4]/parent::n:item[@id = '3']", 1); queryResource(service, "numbers.xml", "//n:price/parent::n:item[@id = '3']", 1); ResourceSet result = queryResource(service, "numbers.xml", "//n:price[. = 18.4]/parent::n:*/string(@id)", 1); assertEquals(result.getResource(0).getContent().toString(), "3"); result = queryResource(service, "numbers.xml", "//n:price[. = 18.4]/parent::*:item/string(@id)", 1); assertEquals(result.getResource(0).getContent().toString(), "3"); result = queryResource(service, "numbers.xml", "//n:price[. = 18.4]/../string(@id)", 1); assertEquals(result.getResource(0).getContent().toString(), "3"); result = queryResource(service, "numbers.xml", "//n:price[. = 18.4]/parent::n:item/string(@id)", 1); assertEquals(result.getResource(0).getContent().toString(), "3"); queryResource(service, "numbers.xml", "for $price in //n:price where $price/parent::*[@id = '3']/n:stock = '5' return $price", 1); } catch (XMLDBException e) { fail(e.getMessage()); } } public void testParentSelfAxis() { try { XQueryService service = storeXMLStringAndGetQueryService("nested2.xml", nested2); queryResource(service, "nested2.xml", "/RootElement/descendant::*/parent::ChildA", 1); queryResource(service, "nested2.xml", "/RootElement/descendant::*[self::ChildB]/parent::RootElement", 0); queryResource(service, "nested2.xml", "/RootElement/descendant::*[self::ChildA]/parent::RootElement", 1); queryResource(service, "nested2.xml", "let $a := ('', 'b', '', '') for $b in $a[.] return <blah>{$b}</blah>", 1); String query = "let $doc := <root><page><a>a</a><b>b</b></page></root>" + "return " + public void bugtestPredicateBUG_wiki_1() throws Exception { String xQuery = "let $dum := <dummy><el>1</el><el>2</el></dummy> return $dum/el[2]"; XQueryService service = getQueryService(); ResourceSet rs = service.query(xQuery); assertEquals("Predicate bug wiki_1", 1, rs.getSize()); assertEquals("Predicate bug wiki_1", "<el>2</el>", rs.getResource(0).getContent()); } public void bugtestCardinalitySelfBUG_wiki_2() { String xQuery = "let $test := <test><works><employee>a</employee><employee>b</employee></works></test> " +"for $h in $test/works/employee[2] return fn:name($h/self::employee)"; try { XQueryService service = getQueryService(); ResourceSet rs = service.query(xQuery); assertEquals("CardinalitySelfBUG bug wiki_2", 1, rs.getSize()); assertEquals("CardinalitySelfBUG bug wiki_2", "employee", rs.getResource(0).getContent()); } catch (XMLDBException ex) { fail( "xquery returned exception: " +ex.toString() ); } } public void bugtestVirtualNodesetBUG_wiki_3() { String xQuery = "declare option exist:serialize \"method=xml indent=no\"; " +"let $node := (<c id=\"OK\"><b id=\"cool\"/></c>)" +"/descendant::*/attribute::id return <a>{$node}</a>"; try { XQueryService service = getQueryService(); ResourceSet rs = service.query(xQuery); assertEquals("VirtualNodesetBUG_wiki_3", 1, rs.getSize()); assertEquals("VirtualNodesetBUG_wiki_3", "<a id=\"cool\"/>", rs.getResource(0).getContent()); } catch (XMLDBException ex) { fail( "xquery returned exception: " +ex.toString() ); } } public void testStrings() { try { XQueryService service = storeXMLStringAndGetQueryService("strings.xml", strings); ResourceSet result = queryResource(service, "strings.xml", "substring(/test/string[1], 1, 5)", 1); assertEquals( "Hello", result.getResource(0).getContent() ); queryResource(service, "strings.xml", "/test/string[starts-with(string(.), 'Hello')]", 2); result = queryResource(service, "strings.xml", "count(/test/item/price)", 1, "Query should return an empty set (wrong document)"); assertEquals("0", result.getResource(0).getContent()); } catch (XMLDBException e) { System.out.println("testStrings(): XMLDBException: "+e); fail(e.getMessage()); } } public void testQuotes() { try { XQueryService service = storeXMLStringAndGetQueryService("quotes.xml", quotes); // ResourceSet result = queryResource(service, "quotes.xml", "/test[title = '&quot;Hello&quot;']", 1); service.declareVariable("content", "&quot;Hello&quot;"); // result = queryResource(service, "quotes.xml", "/test[title = $content]", 1); } catch (XMLDBException e) { System.out.println("testQuotes(): XMLDBException: "+e); fail(e.getMessage()); } } public void testBoolean() { try { System.out.println("Testing effective boolean value of expressions ..."); XQueryService service = storeXMLStringAndGetQueryService("numbers.xml", numbers); ResourceSet result = queryResource(service, "numbers.xml", "boolean(1.0)", 1); assertEquals("boolean value of 1.0 should be true", "true", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(0.0)", 1); assertEquals("boolean value of 0.0 should be false", "false", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(xs:double(0.0))", 1); assertEquals("boolean value of double 0.0 should be false", "false", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(xs:double(1.0))", 1); assertEquals("boolean value of double 1.0 should be true", "true", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(xs:float(1.0))", 1); assertEquals("boolean value of float 1.0 should be true", "true", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(xs:float(0.0))", 1); assertEquals("boolean value of float 0.0 should be false", "false", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(xs:integer(0))", 1); assertEquals("boolean value of integer 0 should be false", "false", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(xs:integer(1))", 1); assertEquals("boolean value of integer 1 should be true", "true", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "'true' cast as xs:boolean", 1); assertEquals("boolean value of 'true' cast to xs:boolean should be true", "true", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "'false' cast as xs:boolean", 1); assertEquals("boolean value of 'false' cast to xs:boolean should be false", "false", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean('Hello')", 1); assertEquals("boolean value of string 'Hello' should be true", "true", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean('')", 1); assertEquals("boolean value of empty string should be false", "false", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(())", 1); assertEquals("boolean value of empty sequence should be false", "false", result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(('Hello'))", 1); assertEquals("boolean value of sequence with non-empty string should be true", "true", result.getResource(0).getContent()); // result = queryResource(service, "numbers.xml", "boolean((0.0, 0.0))", 1); // assertEquals("boolean value of sequence with two elements should be true", "true", // result.getResource(0).getContent()); result = queryResource(service, "numbers.xml", "boolean(//item[@id = '1']/price)", 1); assertEquals("boolean value of 5.6 should be true", "true", result.getResource(0).getContent()); boolean exceptionThrown = false; String message = ""; try { result = queryResource(service, "numbers.xml", "boolean(current-time())", 1); } catch (XMLDBException e) { exceptionThrown = true; message = e.getMessage(); } assertTrue(message.indexOf("FORG0006") > -1); } catch (XMLDBException e) { System.out.println("testBoolean(): XMLDBException: "+e); fail(e.getMessage()); } } public void testNot() { try { XQueryService service = storeXMLStringAndGetQueryService("strings.xml", strings); queryResource(service, "strings.xml", "/test/string[not(@value)]", 2); ResourceSet result = queryResource(service, "strings.xml", "not(/test/abcd)", 1); Resource r = result.getResource(0); assertEquals("true", r.getContent().toString()); result = queryResource(service, "strings.xml", "not(/test)", 1); r = result.getResource(0); assertEquals("false", r.getContent().toString()); result = queryResource(service, "strings.xml", "/test/string[not(@id)]", 3); r = result.getResource(0); assertEquals("<string>Hello World!</string>", r.getContent().toString()); // test with non-existing items queryResource( service, "strings.xml", "document()/blah[not(blah)]", 0); /** test involving ancestor:: * >>>>>>> currently this produces variable corruption : * The result is the ancestor <<<<<<<<<< */ public void testAncestor() { ResourceSet result; try { XQueryService service = storeXMLStringAndGetQueryService("numbers.xml", numbers ); query = "let $all_items := /test/item " + "(: Note: variable non used but computed anyway :)" + "let $unused_variable :=" + " for $one_item in $all_items " + " / ancestor::* (: <<<<< if you remove this line all is normal :)" + " return 'foo'" + "return $all_items"; result = service.queryResource("numbers.xml", query ); assertEquals(4, result.getSize()); } catch (XMLDBException e) { System.out.println("testAncestor(): XMLDBException: "+e); fail(e.getMessage()); } } /** Helper that performs an XQuery and does JUnit assertion on result size. * @see #queryResource(XQueryService, String, String, int, String) */ private ResourceSet queryResource(XQueryService service, String resource, String query, int expected) throws XMLDBException { return queryResource(service, resource, query, expected, null); } /** Helper that performs an XQuery and does JUnit assertion on result size. * @param service XQuery service * @param resource database resource (collection) to query * @param query * @param expected size of result * @param message for JUnit * @return a ResourceSet, allowing to do more assertions if necessary. * @throws XMLDBException */ private ResourceSet queryResource(XQueryService service, String resource, String query, int expected, String message) throws XMLDBException { ResourceSet result = service.queryResource(resource, query); if(message == null) assertEquals(query, expected, result.getSize()); else assertEquals(message, expected, result.getSize()); return result; } /** For queries without associated data */ private ResourceSet queryAndAssert(XQueryService service, String query, int expected, String message) throws XMLDBException { ResourceSet result = service.query(query); if(message == null) assertEquals(expected, result.getSize()); else assertEquals(message, expected, result.getSize()); return result; } /** For queries without associated data */ private XQueryService getQueryService() throws XMLDBException { XQueryService service = (XQueryService) testCollection.getService( "XPathQueryService", "1.0"); return service; } /** stores XML String and get Query Service * @param documentName to be stored in the DB * @param content to be stored in the DB * @return the XQuery Service * @throws XMLDBException */ private XQueryService storeXMLStringAndGetQueryService(String documentName, String content) throws XMLDBException { XMLResource doc = (XMLResource) testCollection.createResource( documentName, "XMLResource" ); doc.setContent(content); testCollection.storeResource(doc); XQueryService service = (XQueryService) testCollection.getService( "XPathQueryService", "1.0"); return service; } public void testNamespaces() { try { XQueryService service = storeXMLStringAndGetQueryService("namespaces.xml", namespaces); service.setNamespace("t", "http: service.setNamespace("c", "http: ResourceSet result = service.queryResource("namespaces.xml", "//t:section"); assertEquals(1, result.getSize()); result = service.queryResource("namespaces.xml", "/t:test//c:comment"); assertEquals(1, result.getSize()); result = service.queryResource("namespaces.xml", " assertEquals(1, result.getSize()); /** * @param result * @throws XMLDBException */ private void printResult(ResourceSet result) throws XMLDBException { for (ResourceIterator i = result.getIterator(); i.hasMoreResources(); ) { Resource r = i.nextResource(); System.out.println(r.getContent()); } } public void testMembersAsResource() { try { // XPathQueryService service = // (XPathQueryService) testCollection.getService( // "XPathQueryService", // ResourceSet result = service.query("//SPEECH[LINE &= 'marriage']"); XQueryService service = storeXMLStringAndGetQueryService("numbers.xml", numbers); ResourceSet result = service.query("//item/price"); Resource r = result.getMembersAsResource(); String content = (String)r.getContent(); System.out.println(content); Pattern p = Pattern.compile( ".*(<price>.*){4}", Pattern.DOTALL); Matcher m = p.matcher(content); assertTrue( "get whole document numbers.xml", m.matches() ); } catch (XMLDBException e) { fail(e.getMessage()); } } public void testSatisfies() { try { XQueryService service = getQueryService(); ResourceSet result; result = queryAndAssert( service, "every $foo in (1,2,3) satisfies" + " let $bar := 'baz'" + " return false() ", 1, "" ); assertEquals( "satisfies + FLWR expression allways false 1", "false", result.getResource(0).getContent() ); result = queryAndAssert( service, "declare function local:foo() { false() };" + " every $bar in (1,2,3) satisfies" + " local:foo()", 1, "" ); assertEquals( "satisfies + FLWR expression allways false 2", "false", result.getResource(0).getContent() ); query = "every $x in () satisfies false()"; result = queryAndAssert( service, query, 1, "" ); assertEquals( query, "true", result.getResource(0).getContent() ); query = "some $x in () satisfies true()"; result = queryAndAssert( service, query, 1, "" ); assertEquals( query, "false", result.getResource(0).getContent() ); } catch (XMLDBException e) { fail(e.getMessage()); } } public void testIntersect() { try { XQueryService service = getQueryService(); ResourceSet result; query = "() intersect ()"; result = queryAndAssert( service, query, 0, ""); query = "() intersect (1)"; result = queryAndAssert( service, query, 0, ""); query = "(1) intersect ()"; result = queryAndAssert( service, query, 0, ""); } catch (XMLDBException e) { fail(e.getMessage()); } } public void testUnion() { try { XQueryService service = getQueryService(); ResourceSet result; query = "() union ()"; result = queryAndAssert( service, query, 0, ""); boolean exceptionThrown = false; String message = ""; try { query = "() union (1)"; result = queryAndAssert( service, query, 0, ""); } catch (XMLDBException e) { exceptionThrown = true; message = e.getMessage(); } assertTrue(message.indexOf("XPTY0004") > -1); exceptionThrown = false; message = ""; try { query = "(1) union ()"; result = queryAndAssert( service, query, 0, ""); } catch (XMLDBException e) { exceptionThrown = true; message = e.getMessage(); } assertTrue(message.indexOf("XPTY0004") > -1); query = "<a/> union ()"; result = queryAndAssert( service, query, 1, ""); query = "() union <a/>"; result = queryAndAssert( service, query, 1, ""); //Not the same nodes query = "<a/> union <a/>"; result = queryAndAssert( service, query, 2, ""); } catch (XMLDBException e) { fail(e.getMessage()); } } public void testExcept() { try { XQueryService service = getQueryService(); query = "() except ()"; queryAndAssert( service, query, 0, ""); query = "() except (1)"; queryAndAssert( service, query, 0, ""); String message = ""; try { query = "(1) except ()"; queryAndAssert( service, query, 0, ""); } catch (XMLDBException e) { message = e.getMessage(); } assertTrue(message.indexOf("XPTY0004") > -1); query = "<a/> except ()"; queryAndAssert( service, query, 1, ""); query = "() except <a/>"; queryAndAssert( service, query, 0, ""); //Not the same nodes query = "<a/> except <a/>"; queryAndAssert( service, query, 1, ""); } catch (XMLDBException e) { fail(e.getMessage()); } } public void testConvertToBoolean() throws XMLDBException { XQueryService service = getQueryService(); ResourceSet result; try { result = queryAndAssert( service, "let $doc := <element attribute=''/>" + "return (" + " <true>{boolean(($doc,2,3))}</true> ," + " <true>{boolean(($doc/@*,2,3))}</true> ," + " <true>{boolean(true())}</true> ," + " <true>{boolean('test')}</true> ," + " <true>{boolean(number(1))}</true> ," + " <false>{boolean((0))}</false> ," + " <false>{boolean(false())}</false> ," + " <false>{boolean('')}</false> ," + " <false>{boolean(number(0))}</false> ," + " <false>{boolean(number('NaN'))}</false>" + ")", 10, ""); for (int i = 0; i < 5; i++) { assertEquals("true " + (i + 1), "<true>true</true>", result .getResource(i).getContent()); } for (int i = 5; i < 10; i++) { assertEquals("false " + (i + 1), "<false>false</false>", result .getResource(i).getContent()); } } catch (XMLDBException e) { fail(e.getMessage()); } boolean exceptionThrown = false; String message = ""; try { result = queryAndAssert(service, "let $doc := <element attribute=''/>" + " return boolean( (1,2,$doc) )", 1, ""); } catch (XMLDBException e) { exceptionThrown = true; message = e.getMessage(); } assertTrue("Exception wanted: " + message, exceptionThrown); } public void testCompile() throws XMLDBException { String invalidQuery = "for $i in (1 to 10)\n return $b"; String validQuery = "for $i in (1 to 10) return $i"; String validModule = "module namespace foo=\"urn:foo\";\n" + "declare function foo:test() { \"Hello World!\" };"; String invalidModule = "module namespace foo=\"urn:foo\";\n" + "declare function foo:test() { \"Hello World! };"; org.exist.xmldb.XQueryService service = (org.exist.xmldb.XQueryService) getQueryService(); boolean exceptionOccurred = false; try { service.compile(invalidQuery); } catch (XMLDBException e) { assertEquals(((XPathException)e.getCause()).getLine(), 2); exceptionOccurred = true; } assertTrue("Expected an exception", exceptionOccurred); exceptionOccurred = false; try { service.compileAndCheck(invalidModule); } catch (XPathException e) { exceptionOccurred = true; } assertTrue("Expected an exception", exceptionOccurred); try { service.compile(validQuery); service.compile(validModule); } catch (XMLDBException e) { fail(e.getMessage()); } } /** * Added by Geoff Shuetrim on 15 July 2006 (geoff@galexy.net). * This test has been added following identification of a problem running * XPath queries that involved the name of elements with the name 'xpointer'. * @throws XMLDBException */ public void bugtestXPointerElementNameHandling() { try { XQueryService service = storeXMLStringAndGetQueryService( "xpointer.xml", xpointerElementName); ResourceSet result = service.queryResource("xpointer.xml", "/test/.[local-name()='xpointer']"); printResult(result); assertEquals(1, result.getSize()); result = service.queryResource("xpointer.xml", "/test/xpointer"); printResult(result); assertEquals(1, result.getSize()); } catch (XMLDBException e) { fail(e.getMessage()); } } public void testSubstring() throws XMLDBException { XQueryService service = getQueryService(); ResourceSet result; // Testcases by MIKA try { String validQuery="substring(\"MK-1234\", 4,1)"; result = queryAndAssert( service, validQuery, 1, validQuery); assertEquals("1", result.getResource(0).getContent().toString() ); } catch (XMLDBException e) { fail(e.getMessage()); } try { String invalidQuery="substring(\"MK-1234\", 4,4)"; result = queryAndAssert( service, invalidQuery, 1, invalidQuery); assertEquals("1234", result.getResource(0).getContent().toString() ); } catch (XMLDBException e) { fail(e.getMessage()); } // Testcase by Toar try { String toarQuery="let $num := \"2003.123\" \n return substring($num, 1, 7)"; result = queryAndAssert( service, toarQuery, 1, toarQuery); assertEquals("2003.12", result.getResource(0).getContent().toString() ); } catch (XMLDBException e) { fail(e.getMessage()); } } public static void main(String[] args) { junit.textui.TestRunner.run(XPathQueryTest.class); } }
package org.exist.xquery.update; import org.apache.log4j.Logger; import org.exist.EXistException; import org.exist.collections.CollectionConfiguration; import org.exist.collections.CollectionConfigurationException; import org.exist.collections.triggers.DocumentTrigger; import org.exist.collections.triggers.Trigger; import org.exist.collections.triggers.TriggerException; import org.exist.dom.DefaultDocumentSet; import org.exist.dom.DocumentImpl; import org.exist.dom.DocumentSet; import org.exist.dom.MutableDocumentSet; import org.exist.dom.NodeImpl; import org.exist.dom.NodeIndexListener; import org.exist.dom.NodeProxy; import org.exist.dom.NodeSet; import org.exist.dom.StoredNode; import org.exist.memtree.DocumentBuilderReceiver; import org.exist.memtree.MemTreeBuilder; import org.exist.numbering.NodeId; import org.exist.security.PermissionDeniedException; import org.exist.storage.DBBroker; import org.exist.storage.StorageAddress; import org.exist.storage.lock.Lock; import org.exist.storage.serializers.Serializer; import org.exist.storage.txn.TransactionException; import org.exist.storage.txn.TransactionManager; import org.exist.storage.txn.Txn; import org.exist.util.LockException; import org.exist.util.hashtable.Int2ObjectHashMap; import org.exist.xquery.AbstractExpression; import org.exist.xquery.AnalyzeContextInfo; import org.exist.xquery.Cardinality; import org.exist.xquery.Expression; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.Item; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceIterator; import org.exist.xquery.value.Type; import org.exist.xquery.value.ValueSequence; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; import java.util.Iterator; /** * @author wolf * */ public abstract class Modification extends AbstractExpression { protected final static Logger LOG = Logger.getLogger(Modification.class); protected Expression select = null; protected Expression value = null; protected DocumentSet lockedDocuments = null; protected MutableDocumentSet modifiedDocuments = new DefaultDocumentSet(); protected Int2ObjectHashMap triggers = null; public Modification(XQueryContext context) { super(context); } /** * @param context */ public Modification(XQueryContext context, Expression select, Expression value) { super(context); this.select = select; this.value = value; this.triggers = new Int2ObjectHashMap(97); } public abstract void update(Sequence inSeq, Sequence contentSeq) throws XPathException; public int getCardinality() { return Cardinality.EMPTY; } /* (non-Javadoc) * @see org.exist.xquery.AbstractExpression#returnsType() */ public int returnsType() { return Type.EMPTY; } /* (non-Javadoc) * @see org.exist.xquery.AbstractExpression#resetState() */ public void resetState(boolean postOptimization) { super.resetState(postOptimization); if (select != null) select.resetState(postOptimization); if (value != null) value.resetState(postOptimization); } /* (non-Javadoc) * @see org.exist.xquery.Expression#analyze(org.exist.xquery.Expression, int) */ public void analyze(AnalyzeContextInfo contextInfo) throws XPathException { contextInfo.setParent(this); contextInfo.addFlag(IN_UPDATE); if (select != null) select.analyze(contextInfo); if (value != null) value.analyze(contextInfo); } /** * Acquire a lock on all documents processed by this modification. * We have to avoid that node positions change during the * operation. * * @param nodes * @throws LockException */ protected StoredNode[] selectAndLock(Txn transaction, Sequence nodes) throws LockException, PermissionDeniedException, XPathException { Lock globalLock = context.getBroker().getBrokerPool().getGlobalUpdateLock(); try { globalLock.acquire(Lock.READ_LOCK); lockedDocuments = nodes.getDocumentSet(); // acquire a lock on all documents // we have to avoid that node positions change // during the modification lockedDocuments.lock(context.getBroker(), true, false); StoredNode ql[] = new StoredNode[nodes.getItemCount()]; for (int i = 0; i < ql.length; i++) { Item item = nodes.itemAt(i); if (!Type.subTypeOf(item.getType(), Type.NODE)) throw new XPathException(this, "XQuery update expressions can only be applied to nodes. Got: " + item.getStringValue()); NodeValue nv = (NodeValue)item; if (nv.getImplementationType() == NodeValue.IN_MEMORY_NODE) throw new XPathException(this, "XQuery update expressions can not be applied to in-memory nodes."); Node n = nv.getNode(); if (n == null) throw new XPathException(this, "Internal error: node to update is null"); if (n.getNodeType() == Node.DOCUMENT_NODE) throw new XPathException(this, "Updating the document object is not allowed."); ql[i] = (StoredNode) n; DocumentImpl doc = (DocumentImpl)ql[i].getOwnerDocument(); //prepare Trigger prepareTrigger(transaction, doc); } return ql; } finally { globalLock.release(Lock.READ_LOCK); } } protected Sequence deepCopy(Sequence inSeq) throws XPathException { context.pushDocumentContext(); MemTreeBuilder builder = context.getDocumentBuilder(); DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder); Serializer serializer = context.getBroker().getSerializer(); serializer.setReceiver(receiver); try { Sequence out = new ValueSequence(); for (SequenceIterator i = inSeq.iterate(); i.hasNext(); ) { Item item = i.nextItem(); if (item.getType() == Type.DOCUMENT) { if (((NodeValue)item).getImplementationType() == NodeValue.PERSISTENT_NODE) { StoredNode root = (StoredNode) ((NodeProxy)item).getDocument().getDocumentElement(); item = new NodeProxy(root.getDocument(), root.getNodeId(), root.getInternalAddress()); } else { item = (Item)((NodeValue) item).getOwnerDocument().getDocumentElement(); } } if (Type.subTypeOf(item.getType(), Type.NODE)) { if (((NodeValue)item).getImplementationType() == NodeValue.PERSISTENT_NODE) { int last = builder.getDocument().getLastNode(); NodeProxy p = (NodeProxy) item; serializer.toReceiver(p, false, false); if (p.getNodeType() == Node.ATTRIBUTE_NODE) item = builder.getDocument().getLastAttr(); else item = builder.getDocument().getNode(last + 1); } else { ((org.exist.memtree.NodeImpl)item).deepCopy(); } } out.add(item); } return out; } catch(SAXException e) { throw new XPathException(this, e.getMessage(), e); } finally { context.popDocumentContext(); } } protected void finishTriggers(Txn transaction) { Iterator iterator = modifiedDocuments.getDocumentIterator(); DocumentImpl doc; while(iterator.hasNext()) { doc = (DocumentImpl) iterator.next(); context.addModifiedDoc(doc); finishTrigger(transaction, doc); } if (triggers != null) triggers.clear(); } /** * Release all acquired document locks. */ protected void unlockDocuments() { if(lockedDocuments == null) return; modifiedDocuments.clear(); //unlock documents lockedDocuments.unlock(true); lockedDocuments = null; } public static void checkFragmentation(XQueryContext context, DocumentSet docs) throws EXistException { int fragmentationLimit = -1; Object property = context.getBroker().getBrokerPool().getConfiguration().getProperty(DBBroker.PROPERTY_XUPDATE_FRAGMENTATION_FACTOR); if (property != null) fragmentationLimit = ((Integer)property).intValue(); checkFragmentation(context, docs, fragmentationLimit); } /** * Check if any of the modified documents needs defragmentation. * * Defragmentation will take place if the number of split pages in the * document exceeds the limit defined in the configuration file. * * @param docs */ public static void checkFragmentation(XQueryContext context, DocumentSet docs, int splitCount) throws EXistException { DBBroker broker = context.getBroker(); TransactionManager txnMgr = context.getBroker().getBrokerPool().getTransactionManager(); Txn transaction = context.getBatchTransaction(); //if there is no batch update transaction, start a new individual transaction if(transaction == null) transaction = txnMgr.beginTransaction(); try { for (Iterator i = docs.getDocumentIterator(); i.hasNext(); ) { DocumentImpl next = (DocumentImpl) i.next(); if(next.getMetadata().getSplitCount() > splitCount) try { next.getUpdateLock().acquire(Lock.WRITE_LOCK); broker.defragXMLResource(transaction, next); } finally { next.getUpdateLock().release(Lock.WRITE_LOCK); } broker.checkXMLResourceConsistency(next); } if(!context.hasBatchTransaction()) txnMgr.commit(transaction); } catch (Exception e) { txnMgr.abort(transaction); } } /** * Fires the prepare function for the UPDATE_DOCUMENT_EVENT trigger for the Document doc * * @param transaction The transaction * @param doc The document to trigger for */ private void prepareTrigger(Txn transaction, DocumentImpl doc) { //if we are doing a batch update then only call prepare for the first update to that document if(context.hasBatchTransaction()) { Iterator itTrigDoc = modifiedDocuments.getDocumentIterator(); while(itTrigDoc.hasNext()) { DocumentImpl trigDoc = (DocumentImpl)itTrigDoc.next(); if(trigDoc.getURI().equals(doc.getURI())) { return; } } } //prepare the trigger CollectionConfiguration config = doc.getCollection().getConfiguration(context.getBroker()); DocumentTrigger trigger = null; if(config != null) { //get the UPDATE_DOCUMENT_EVENT trigger try { trigger = (DocumentTrigger)config.newTrigger(Trigger.UPDATE_DOCUMENT_EVENT, context.getBroker(), doc.getCollection()); } catch (CollectionConfigurationException e) { LOG.debug("An error occurred while initializing a trigger for collection " + doc.getCollection().getURI() + ": " + e.getMessage(), e); } if(trigger != null) { try { //fire trigger prepare trigger.prepare(Trigger.UPDATE_DOCUMENT_EVENT, context.getBroker(), transaction, doc.getURI(), doc); } catch(TriggerException te) { LOG.debug("Unable to prepare trigger for event UPDATE_DOCUMENT_EVENT: " + te.getMessage()); } catch(Exception e) { LOG.debug("Trigger event UPDATE_DOCUMENT_EVENT for collection: " + doc.getCollection().getURI() + " with: " + doc.getURI() + " " + e.getMessage()); } triggers.put(doc.getDocId(), trigger); } } } /** Fires the finish function for UPDATE_DOCUMENT_EVENT for the documents trigger * * @param transaction The transaction * @param doc The document to trigger for */ private void finishTrigger(Txn transaction, DocumentImpl doc) { //if this is part of a batch transaction, defer the trigger if(context.hasBatchTransaction()) { context.setBatchTransactionTrigger(doc); } else if (triggers != null) { //finish the trigger DocumentTrigger trigger = (DocumentTrigger) triggers.get(doc.getDocId()); if(trigger != null) { try { trigger.finish(Trigger.UPDATE_DOCUMENT_EVENT, context.getBroker(), transaction, doc.getURI(), doc); } catch(Exception e) { LOG.debug("Trigger event UPDATE_DOCUMENT_EVENT for collection: " + doc.getCollection().getURI() + " with: " + doc.getURI() + " " + e.getMessage()); } } } } /** * Gets the Transaction to use for the update (can be batch or individual) * * @return The transaction */ public Txn getTransaction() { Txn transaction = context.getBatchTransaction(); //if there is no batch update transaction, start a new individual transaction if(transaction == null) { TransactionManager txnMgr = context.getBroker().getBrokerPool().getTransactionManager(); transaction = txnMgr.beginTransaction(); } return transaction; } /** * Commit's the transaction for the update unless it is a batch update and then the commit is defered * * @param transaction The Transaction to commit */ public void commitTransaction(Txn transaction) throws TransactionException { //only commit the transaction, if its not a batch update transaction if(!context.hasBatchTransaction()) { TransactionManager txnMgr = context.getBroker().getBrokerPool().getTransactionManager(); txnMgr.commit(transaction); } } final static class IndexListener implements NodeIndexListener { StoredNode[] nodes; public IndexListener(StoredNode[] nodes) { this.nodes = nodes; } /* (non-Javadoc) * @see org.exist.dom.NodeIndexListener#nodeChanged(org.exist.dom.NodeImpl) */ public void nodeChanged(StoredNode node) { long address = node.getInternalAddress(); for (int i = 0; i < nodes.length; i++) { if (StorageAddress.equals(nodes[i].getInternalAddress(), address)) { nodes[i] = node; } } } } }
package org.fusfoundation.kranion; import com.sun.media.jfxmedia.logging.Logger; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import static org.lwjgl.opengl.GL11.*; //import static org.lwjgl.opengl.GL12.*; //import static org.lwjgl.opengl.GL13.*; //import static org.lwjgl.opengl.GL14.*; import static org.lwjgl.opengl.GL15.*; //import static org.lwjgl.opengl.GL20.*; //import static org.lwjgl.util.glu.GLU.*; //import org.lwjgl.opengl.GL30; import org.lwjgl.util.vector.*; import org.lwjgl.BufferUtils; import java.nio.*; import java.io.*; import java.util.*; import org.lwjgl.util.glu.GLU; import static org.lwjgl.util.glu.GLU.gluLookAt; public class Transducer extends Clippable { private int txdrElementVertsID=0, txdrElementNormsID=0; private int txdrRaysVertsID=0; private static ArrayList<Map.Entry<InsightecTxdrGeomReader, Renderable>> transducers; private InsightecTxdrGeomReader trans; private float transducerXTilt = 0f; private float transducerYTilt = 0f; private boolean showRays = false; private boolean clipRays = false; private boolean showFocalVolume = false; private boolean showSteeringVolume = false; // orientation and location, origin is assumed natural focus private Vector3f position = new Vector3f(); private Matrix4f transform = (Matrix4f)new Matrix4f().setIdentity(); // transducer elements are displayed as discs composed of this many // triangles in a triangle fan. Disc radius is proportional to element // area. private int tesselation = 20; private static ActionListener listener = null; private static RenderList defaultClinicalTransducer = new RenderList(); private org.lwjgl.util.glu.Sphere steering; private org.lwjgl.util.glu.Sphere focalSpot; private boolean showFiducialPositions = false; private int transducerIndex = -1; public Transducer() { transducerIndex = -1; } public static void setListener(ActionListener l) { listener = l; } public void setTransducerDefinitionIndex(int index) { transducerIndex = index; setIsDirty(true); } private StandardShader shader = new StandardShader(); // public float getTransducerXTilt() { return transducerXTilt; } // public void setTransducerXTilt(float tiltDeg) { // setTransducerTilt(tiltDeg, transducerYTilt); // public float getTransducerYTilt() { return transducerYTilt; } // public void setTransducerYTilt(float tiltDeg) { // setTransducerTilt(transducerXTilt, tiltDeg); public void setTransducerTilt(float xTiltDeg, float yTiltDeg) { if (transducerXTilt != xTiltDeg) { transducerXTilt = xTiltDeg; setIsDirty(true); } if (transducerYTilt != yTiltDeg) { transducerYTilt = yTiltDeg; setIsDirty(true); } transform.setIdentity(); transform.rotate(transducerXTilt/180f*(float)Math.PI, new Vector3f(-1, 0, 0)); transform.rotate(transducerYTilt/180f*(float)Math.PI, new Vector3f(0, -1, 0)); } public void setRotation(Matrix3f rotmat) { transform.m00 = rotmat.m00; transform.m01 = rotmat.m01; transform.m02 = rotmat.m02; transform.m10 = rotmat.m10; transform.m11 = rotmat.m11; transform.m12 = rotmat.m12; transform.m20 = rotmat.m20; transform.m21 = rotmat.m21; transform.m22 = rotmat.m22; setIsDirty(true); } public void setShowFiducialPositions(boolean bShow) { showFiducialPositions = bShow; setIsDirty(true); } public void setTransducerTilt(Vector3f xdir, Vector3f ydir) { Vector3f zdir = (Vector3f)Vector3f.cross(xdir, ydir, null); xdir.normalise(); ydir.normalise(); zdir.normalise(); transform.m00 = xdir.x; transform.m01 = ydir.x; transform.m02 = zdir.x; transform.m03 = 0.0f; // Second row transform.m10 = xdir.y; transform.m11 = ydir.y; transform.m12 = zdir.y; transform.m13 = 0.0f; // Third row transform.m20 = xdir.z; transform.m21 = ydir.z; transform.m22 = zdir.z; transform.m23 = 0.0f; // Fourth row transform.m30 = 0; transform.m31 = 0; transform.m32 = 0; transform.m33 = 1.0f; setIsDirty(true); } // private Trackball trackball = null; public void release() { releaseBuffers(); defaultClinicalTransducer.release(); } private void releaseBuffers() { if (txdrElementVertsID != 0) { glDeleteBuffers(txdrElementVertsID); txdrElementVertsID = 0; } if (txdrElementNormsID != 0) { glDeleteBuffers(txdrElementNormsID); txdrElementNormsID = 0; } if (txdrRaysVertsID != 0) { glDeleteBuffers(txdrRaysVertsID); txdrRaysVertsID = 0; } } public static InsightecTxdrGeomReader getTransducerDef(int i) { return transducers.get(i).getKey(); } public static int getTransducerDefCount() { if (transducers == null) { buildTransducerList(); } return transducers.size(); } public Transducer(int index) throws IOException { if (transducers == null) { buildTransducerList(); } if (index < 0 || index > transducers.size() - 1) { throw new IndexOutOfBoundsException(); } transducerIndex = index; PlyFileReader transducerBody = new PlyFileReader("/org/fusfoundation/kranion/meshes/ClinicalTransducerBody.ply"); transducerBody.setColor(0.1f, 0.1f, 0.1f, 1f); transducerBody.setClipColor(0.075f, 0.075f, 0.075f, 1f); PlyFileReader transducerRing = new PlyFileReader("/org/fusfoundation/kranion/meshes/ClinicalTransducerRing2.ply"); transducerRing.setColor(0.40f, 0.30f, 0.05f, 1f); transducerRing.setClipColor(0.20f, 0.15f, 0.025f, 1f); PlyFileReader transducerRing2 = new PlyFileReader("/org/fusfoundation/kranion/meshes/ClinicalTransducerRing.ply"); transducerRing2.setColor(0.1f, 0.1f, 0.1f, 1f); transducerRing2.setClipColor(0.075f, 0.075f, 0.075f, 1f); PlyFileReader transducerHousing1 = new PlyFileReader("/org/fusfoundation/kranion/meshes/ClinicalTransducerHousing1.ply"); transducerHousing1.setColor(0.7f, 0.7f, 0.7f, 1f); transducerHousing1.setClipColor(0.5f, 0.5f, 0.5f, 1f); PlyFileReader transducerHousing2 = new PlyFileReader("/org/fusfoundation/kranion/meshes/ClinicalTransducerHousing2.ply"); transducerHousing2.setColor(0.5f, 0.5f, 0.5f, 1f); transducerHousing2.setClipColor(0.5f, 0.5f, 0.5f, 1f); // defaultClinicalTransducer.add(housingGrp); // defaultClinicalTransducer.add(mountingRing1Grp); // defaultClinicalTransducer.add(mountingRing2Grp); defaultClinicalTransducer.add(transducerBody); defaultClinicalTransducer.add(transducerRing); defaultClinicalTransducer.add(transducerRing2); defaultClinicalTransducer.add(transducerHousing1); defaultClinicalTransducer.add(transducerHousing2); steering = new org.lwjgl.util.glu.Sphere(); focalSpot = new org.lwjgl.util.glu.Sphere(); //<<<<<<< Upstream, based on origin/master setTransducerTilt(new Vector3f(-1, 0, 0), new Vector3f(0, -1, 0)); buildElements(transducers.get(index).getKey()); // if (transducer_type == INSIGHTEC_650) { // trans = new InsightecTxdrGeomReader("TransducerInfo/XdNominalGeometry_7002.ini"); // steering1 = new Hemisphere(15.0f, 1f); // steering2 = new Hemisphere(-15.0f, -1f); //>>>>>>> a2c7a7e First functional check in. -SDR implemented as a reasonable first pass. -GUI controls are still almost non-existent. -Must restart to load different data. //<<<<<<< Upstream, based on origin/master } public static int addDefaultTransducerDef(String name, String filename) { int indexToReturn = -1; if (transducers == null) { transducers = new ArrayList<Map.Entry<InsightecTxdrGeomReader, Renderable>>(); } try { // if entry exists with same name, remove it first Map.Entry<InsightecTxdrGeomReader, Renderable> searchResult = null; for (int i=0; i<transducers.size(); i++) { if (transducers.get(i).getKey().getName().equalsIgnoreCase(name)) { searchResult = transducers.get(i); } } if (searchResult != null) { transducers.remove(searchResult); } InsightecTxdrGeomReader txdrGeom = new InsightecTxdrGeomReader(new File(filename)); txdrGeom.setName(name); transducers.add(new AbstractMap.SimpleImmutableEntry<InsightecTxdrGeomReader, Renderable>( txdrGeom, defaultClinicalTransducer)); } catch(IOException e) { System.out.println("Transducer definision load failed: " + filename); Logger.logMsg(Logger.ERROR, "Transducer definision load failed: " + filename); } if (listener != null) { try { listener.actionPerformed(new ActionEvent(new Transducer(transducers.size()-1), ActionEvent.ACTION_PERFORMED, "transducerListUpdated")); } catch(IOException e) { e.printStackTrace(); } } return transducers.size()-1; } private static void buildTransducerList() { try { transducers = new ArrayList<Map.Entry<InsightecTxdrGeomReader, Renderable>>(); transducers.add(new AbstractMap.SimpleImmutableEntry<InsightecTxdrGeomReader, Renderable>( new InsightecTxdrGeomReader("TransducerInfo/GenericTransducerGeometry.ini"), defaultClinicalTransducer) ); File transducersDir = new File("transducers"); if (transducersDir.isDirectory()) { File files[] = transducersDir.listFiles(new FilenameFilter() { public boolean accept(File directory, String fileName) { return fileName.endsWith(".ini"); } }); for (int i = 0; i < files.length; i++) { System.out.println(files[i].getPath()); transducers.add(new AbstractMap.SimpleImmutableEntry<InsightecTxdrGeomReader, Renderable>( new InsightecTxdrGeomReader(files[i]), defaultClinicalTransducer) ); } } else { return; } if (transducersDir.isDirectory()) { File files[] = transducersDir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory() && !files[i].getName().equalsIgnoreCase("Inactive")) { System.out.println("Custom Transducer Directory: " + files[i].getName()); InsightecTxdrGeomReader customGeometry = null; RenderList transducerRenderable = new RenderList(); File customFiles[] = files[i].listFiles(); for (int j = 0; j < customFiles.length; j++) { if (customFiles[j].getName().equalsIgnoreCase("transducer.xml")) { TransducerDesc desc = TransducerDesc.loadDescriptionXML(customFiles[j]); if (desc != null) { customGeometry = new InsightecTxdrGeomReader(new File(customFiles[j].getParent() + File.separator + desc.getElementDescFilename())); if (customGeometry != null) { customGeometry.setName(files[i].getName()); } Iterator<TransducerDesc.Mesh> mi = desc.getMeshIterator(); while (mi.hasNext()) { TransducerDesc.Mesh m = mi.next(); PlyFileReader r = new PlyFileReader(customFiles[j].getParent() + File.separator + m.getFilename()); if (r != null) { Vector4f color = m.getColor(); Vector4f clipColor = m.getClipColor(); r.setColor(color.x, color.y, color.z, color.w); r.setClipColor(clipColor.x, clipColor.y, clipColor.z, clipColor.w); transducerRenderable.add(r); } } TransformationAdapter tdxrTransform = new TransformationAdapter(transducerRenderable); tdxrTransform.setTransform(desc.getTransform()); transducers.add(new AbstractMap.SimpleImmutableEntry<InsightecTxdrGeomReader, Renderable>(customGeometry, tdxrTransform)); } } } } } } } catch (IOException e) { e.printStackTrace(); } } public void buildElements(int index) { buildElements(transducers.get(index).getKey()); } public Transducer buildElements(InsightecTxdrGeomReader txdr) { this.trans = txdr; FloatBuffer txdrElementVertsBuffer, txdrElementNormsBuffer, txdrRaysBuffer; txdrElementVertsBuffer = BufferUtils.createFloatBuffer((tesselation + 2) * 3 * trans.getChannelCount()); txdrElementNormsBuffer = BufferUtils.createFloatBuffer((tesselation + 2) * 3 * trans.getChannelCount()); txdrRaysBuffer = BufferUtils.createFloatBuffer(trans.getChannelCount() * 3 * 2); for (int e = 0; e < trans.getChannelCount(); e++) { Vector3f elementCenter = new Vector3f(trans.getChannel(e)); Vector3f elementNorm = new Vector3f(trans.getChannel(e).x, trans.getChannel(e).y, trans.getChannel(e).z); elementNorm.normalise(); // move the element visual position out 1mm along the normal so it isnt clipped by // tranducer itself. Assumes the the element center positions are coincident on the transdcuer outer surface elementCenter = Vector3f.add(elementCenter, (Vector3f)new Vector3f(elementNorm).scale(-1f), null); txdrElementVertsBuffer.put(elementCenter.x); txdrElementVertsBuffer.put(elementCenter.y); txdrElementVertsBuffer.put(elementCenter.z); // Calculate x and y unit vector perpendicular to the element facing direction Vector3f xvec = new Vector3f(), yvec = new Vector3f(); Vector3f upvec = new Vector3f(1.0f, 1.0f, 1.0f); // hack Vector3f.cross(elementNorm, upvec, xvec); Vector3f.cross(xvec, elementNorm, yvec); xvec.normalise(); yvec.normalise(); // For first vertex normal in the fan elementNorm.scale(-1f); txdrElementNormsBuffer.put(elementNorm.x); txdrElementNormsBuffer.put(elementNorm.y); txdrElementNormsBuffer.put(elementNorm.z); // element displayed with radius proportional to given element area float radius = (float) Math.sqrt(trans.getChannel(e).w / Math.PI) * 0.75f; for (int i = 0; i < tesselation + 1; i++) { float dx = -radius * (float) Math.cos(-(double) ((double) (i - 1) / (float) (tesselation) * 2.0 * Math.PI)); float dy = radius * (float) Math.sin(-(double) ((double) (i - 1) / (float) (tesselation) * 2.0 * Math.PI)); float vx = elementCenter.x + dx * xvec.x + dy * yvec.x; float vy = elementCenter.y + dx * xvec.y + dy * yvec.y; float vz = elementCenter.z + dx * xvec.z + dy * yvec.z; txdrElementVertsBuffer.put(vx); txdrElementVertsBuffer.put(vy); txdrElementVertsBuffer.put(vz); Vector3f vnorm = new Vector3f(vx, vy, (vz)); vnorm.scale(-1); vnorm.normalise(); // For each vert normal in the fan txdrElementNormsBuffer.put(vnorm.x); txdrElementNormsBuffer.put(vnorm.y); txdrElementNormsBuffer.put(vnorm.z); } } for (int e = 0; e < trans.getChannelCount(); e++) { Vector3f elementCenter = new Vector3f(trans.getChannel(e)); txdrRaysBuffer.put(elementCenter.x); txdrRaysBuffer.put(elementCenter.y); txdrRaysBuffer.put(elementCenter.z); // This is a hack to not draw inactive channel rays. // If inactive, loading identical start and end points for the line // so nothing gets drawn. Should do this better eventually. if (trans.getChannelActive(e) == true) { Vector3f rayTip = new Vector3f(); Vector3f center = new Vector3f(0f, 0f, 0f); rayTip = (Vector3f)Vector3f.add(elementCenter, (Vector3f)Vector3f.sub(center, elementCenter, null).scale(0.96f), null); txdrRaysBuffer.put(rayTip.x); txdrRaysBuffer.put(rayTip.y); txdrRaysBuffer.put(rayTip.z); } else { txdrRaysBuffer.put(elementCenter.x); txdrRaysBuffer.put(elementCenter.y); txdrRaysBuffer.put(elementCenter.z); } } releaseBuffers(); txdrElementVertsID = glGenBuffers(); txdrElementVertsBuffer.flip(); glBindBuffer(GL_ARRAY_BUFFER, txdrElementVertsID); glBufferData(GL_ARRAY_BUFFER, txdrElementVertsBuffer, GL_STATIC_DRAW); txdrElementNormsID = glGenBuffers(); txdrElementNormsBuffer.flip(); glBindBuffer(GL_ARRAY_BUFFER, txdrElementNormsID); glBufferData(GL_ARRAY_BUFFER, txdrElementNormsBuffer, GL_STATIC_DRAW); txdrRaysVertsID = glGenBuffers(); txdrRaysBuffer.flip(); glBindBuffer(GL_ARRAY_BUFFER, txdrRaysVertsID); glBufferData(GL_ARRAY_BUFFER, txdrRaysBuffer, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); return this; } @Override public void setTrackball(Trackball tb) { super.setTrackball(tb); // housingGrp.setTrackball(tb); // mountingRing1Grp.setTrackball(tb); // mountingRing2Grp.setTrackball(tb); defaultClinicalTransducer.setTrackball(tb); if (transducerIndex != -1) { Renderable r = transducers.get(transducerIndex).getValue(); if (r instanceof Clippable) { ((Clippable) r).setTrackball(tb); } } } @Override public void setDolly(float cameraz, float dolly) { super.setDolly(cameraz, dolly); defaultClinicalTransducer.setDolly(cameraz, dolly); if (transducerIndex != -1) { Renderable r = transducers.get(transducerIndex).getValue(); if (r instanceof Clippable) { ((Clippable) r).setDolly(cameraz, dolly); } } } public void setPosition(float x, float y, float z) { setPosition(new Vector3f(x, y, z)); } public void setPosition(Vector3f p) { if (!position.equals(p)) { setIsDirty(true); } position.set(p); transform.m03 = p.x; transform.m13 = p.y; transform.m23 = p.z; } public Vector3f getPosition() { return new Vector3f(position); } public Matrix4f getTransform() { return new Matrix4f(transform); } public void setShowRays(Boolean show) { if (showRays != show) { setIsDirty(true); } showRays = show; } public boolean getShowRays() { return showRays; } public void setClipRays(Boolean bClip) { if (clipRays != bClip) { setIsDirty(true); } clipRays = bClip; } public boolean getClipRays() { return clipRays; } public boolean getShowFocalVolume() { return this.showFocalVolume; } public void setShowFocalVolume(boolean bShow) { if (bShow != showFocalVolume) { setIsDirty(true); } this.showFocalVolume = bShow; } public boolean getShowSteeringVolume() { return this.showSteeringVolume; } public void setShowSteeringVolume(boolean bShow) { if (bShow != showSteeringVolume) { setIsDirty(true); } this.showSteeringVolume = bShow; } // public void renderclip() { // glPushAttrib(GL_ENABLE_BIT); // glEnable(GL_CULL_FACE); // glCullFace(GL_BACK); // renderPass(); //////////////////// // // Turn stencil buffer on // glClear(GL_STENCIL_BUFFER_BIT); // glEnable(GL_STENCIL_TEST); // glStencilMask(0xff); // glStencilFunc(GL_ALWAYS, 1, 0xff); // glStencilOp(GL_KEEP, GL_KEEP, GL_INCR); // glCullFace(GL_FRONT); // renderPass(); ///////////////////// // glDisable(GL_CULL_FACE); // glStencilFunc(GL_NOTEQUAL, 0, 0xff); // glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // //End cap // glDisable(GL_CLIP_PLANE0); // glDisable(GL_CLIP_PLANE1); // glDisable(GL_DEPTH_TEST); // glColor4f(0.4f, 0.4f, 0.4f, 1f); // glMatrixMode(GL_MODELVIEW); // glPushMatrix(); // glLoadIdentity(); // // Looking up the positive Z axis, Y is down, compliant with DICOM scanner sensibilities // gluLookAt(0.0f, 0.0f, -600.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f); // // camera dolly in/out // glTranslatef(0.0f, 0.0f, 400); // if (trackball != null) { // //glTranslatef(0f, 0f, 150f); // //trackball.renderOpposite(); // glBegin(GL_QUADS); // glNormal3d(0.0, 0.0, -1.0); // glVertex3d(-400, 400, 0.0); // glVertex3d(400, 400, 0.0); // glVertex3d(400, -400, 0.0); // glVertex3d(-400, -400, 0.0); // glEnd(); // glPopMatrix(); // glDisable(GL_STENCIL_TEST); // glPopAttrib(); private void renderElements() { //Draw element fans glColor3f(0.0f, 0.6f, 0.6f); shader.setDiffusetColor(0.0f, 0.6f, 0.6f, 1f); shader.setAmbientColor(0.0f, 0.1f, 0.1f, 1f); shader.setSpecularCoefficient(50f); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, txdrElementVertsID); glVertexPointer(3, GL_FLOAT, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, txdrElementNormsID); glNormalPointer(GL_FLOAT, 0, 0); shader.start(); for (int i = 0; i < trans.getChannelCount(); i++) { if (trans.getChannelActive(i) == true) { glDrawArrays(GL_TRIANGLE_FAN, i * (tesselation + 2), (tesselation + 2)); } } shader.stop(); // clean up glBindBuffer(GL_ARRAY_BUFFER, 0); } public void renderRays() { if (showRays) { glMatrixMode(GL_MODELVIEW); Main.glPushMatrix(); glTranslatef(position.x, position.y, position.z); Main.glPushAttrib(GL_ENABLE_BIT); if (clipRays) { glEnable(GL_CLIP_PLANE0); glEnable(GL_CLIP_PLANE1); } // Render element rays glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(1f, 0.3f, 0.0f, 0.5f); glDisableClientState(GL_NORMAL_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, txdrRaysVertsID); glVertexPointer(3, GL_FLOAT, 0, 0); glDrawArrays(GL_LINES, 0, trans.getChannelCount() * 2); glEnable(GL_LIGHTING); glBindBuffer(GL_ARRAY_BUFFER, 0); Main.glPopAttrib(); Main.glPopMatrix(); } } @Override public void setClipped(boolean clipped) { super.setClipped(clipped); // housingGrp.setClipped(clipped); // mountingRing1Grp.setClipped(clipped); // mountingRing2Grp.setClipped(clipped); for (int i=0; i<transducers.size(); i++) { Renderable r = transducers.get(this.transducerIndex).getValue(); if (r instanceof Clippable) { ((Clippable)r).setClipped(clipped); } } } public void render() { if (!getVisible()) return; setIsDirty(false); // if (getClipped()) { // setClipped(false); // renderClipped(); // setClipped(true); // return; glMatrixMode(GL_MODELVIEW); Main.glPushMatrix(); // glTranslatef(0, 0, 150); // glRotatef(transducerTilt, 1, 0, 0); // glTranslatef(0, 0, -150); FloatBuffer matBuf = BufferUtils.createFloatBuffer(16); transform.store(matBuf); matBuf.flip(); glMultMatrix(matBuf); // Translation is stored in the Matrix4f now, so dont need: // glTranslatef(position.x, position.y, position.z); if (getClipped()) { glEnable(GL_CLIP_PLANE0); glDisable(GL_CLIP_PLANE1); renderElements(); glDisable(GL_CLIP_PLANE0); glDisable(GL_CLIP_PLANE1); } else { renderElements(); } this.transducers.get(transducerIndex).getValue().render(); // housingGrp.render(); // mountingRing1Grp.render(); // mountingRing2Grp.render(); //TODO: remove, just debugging some registration code if (showFiducialPositions) { Main.glPushAttrib(GL_ENABLE_BIT); glDisable(GL_LIGHTING); glDisable(GL_CLIP_PLANE0); glDisable(GL_CLIP_PLANE1); glColor3f(0f, 1f, 0f); glBegin(GL_LINES); glVertex3f(-80f, -80f, 3.37f); glVertex3f(80f, -80f, 3.37f); glVertex3f(80f, -80f, 3.37f); glVertex3f(80f, 80f, 3.37f); glVertex3f(80f, 80f, 3.37f); glVertex3f(-80f, 80f, 3.37f); glVertex3f(-80f, 80f, 3.37f); glVertex3f(-80f, -80f, 3.37f); glEnd(); Main.glPopAttrib(); } // renderRays(); Main.glPopMatrix(); } public void renderFocalSpot() { glMatrixMode(GL_MODELVIEW); Main.glPushMatrix(); glTranslatef(position.x, position.y, position.z); Main.glPushAttrib(GL_ENABLE_BIT); // glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); if (showSteeringVolume) { // steering1.render(); // steering2.render(); glColor4f(0f, 1f, 0f, 0.4f); steering.setDrawStyle(GLU.GLU_FILL); steering.setNormals(GLU.GLU_SMOOTH); steering.draw(15f, 32, 16); } if (showFocalVolume) { // focalSpot1.render(); // focalSpot2.render(); glColor4f(1f, 0f, 0f, 0.6f); focalSpot.setDrawStyle(GLU.GLU_FILL); focalSpot.setNormals(GLU.GLU_SMOOTH); focalSpot.draw(1f, 32, 16); } glCullFace(GL_BACK); if (showSteeringVolume) { // steering1.render(); // steering2.render(); glColor4f(0f, 1f, 0f, 0.4f); steering.setDrawStyle(GLU.GLU_FILL); steering.setNormals(GLU.GLU_SMOOTH); steering.draw(15f, 32, 16); } if (showFocalVolume) { // focalSpot1.render(); // focalSpot2.render(); glColor4f(1f, 0f, 0f, 0.6f); focalSpot.setDrawStyle(GLU.GLU_FILL); focalSpot.setNormals(GLU.GLU_SMOOTH); focalSpot.draw(1f, 32, 16); } glDisable(GL_CULL_FACE); Main.glPopAttrib(); Main.glPopMatrix(); } // public void renderClipped(Vector4f color) { // glPushMatrix(); // glTranslatef(position.x, position.y, position.z); // renderElements(); //// housingGrp.renderClipped(new Vector4f(0.25f, 0.25f, 0.25f, 1f)); //// mountingRing1Grp.renderClipped(new Vector4f(0.05f, 0.05f, 0.05f, 1f)); //// mountingRing2Grp.renderClipped(new Vector4f(0.2f, 0.16f, 0.025f, 1f)); // glPopMatrix(); public int getElementCount() { return trans.getChannelCount(); } public Vector4f getElement(int i) { // return Matrix4f.transform(this.transducerRot, trans.getChannel(i), null); return trans.getChannel(i); } public boolean getElementActive(int i) { return trans.getChannelActive(i); } }
package org.gestern.gringotts; import java.util.Date; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.gestern.gringotts.api.Eco; import org.gestern.gringotts.api.PlayerAccount; import org.gestern.gringotts.api.TransactionResult; import org.gestern.gringotts.api.impl.GringottsEco; public class InterestModule implements Runnable { private final Eco eco = new GringottsEco(); private final double rate = 1.0 / 100.0; private final long period = 20 * 60 * 60; @SuppressWarnings("deprecation") protected void start() { long time = System.currentTimeMillis(); Date date = new Date(time); int minutes = date.getMinutes(); int seconds = date.getSeconds(); long delay = 20 * (60 - seconds) * (60 - minutes); out(delay); Bukkit.getScheduler().runTaskTimer(Gringotts.G, this, delay, period); } @Override public void run() { for (Player p : Bukkit.getServer().getOnlinePlayers()) { PlayerAccount acc = eco.player(p.getUniqueId()); if (!acc.exists()) continue; if (acc.vaultBalance() == 0.0) continue; double balance = acc.balance(); double interest = Math.floor(balance * rate); TransactionResult result = acc.add(interest); String message = ""; switch (result) { case SUCCESS: message = ChatColor.GREEN + "You earned " + interest + " interest of your " + balance + " balance at a rate of " + rate + "%, which was added to your vault."; p.sendMessage(message); case INSUFFICIENT_SPACE: message = ChatColor.RED + "You earned " + interest + " interest of your " + balance + " balance at a rate of " + rate + "%, but you don't have enough space in your vault"; p.sendMessage(message); default: break; } p.sendMessage(ChatColor.GREEN + "Remember you can get it every exact hour, when you are online!"); } } public void out(Object out) { System.out.println(out); } }
package org.jitsi.impl.neomedia; import java.io.*; import java.util.*; import javax.media.*; import javax.media.protocol.*; import org.jitsi.impl.neomedia.device.*; import org.jitsi.service.neomedia.*; import org.jitsi.service.neomedia.MediaException; import org.jitsi.util.*; /** * The call recording implementation. * Provides the capability to start and stop call recording. * * @author Dmitri Melnikov * @author Lubomir Marinov */ public class RecorderImpl implements Recorder { /** * The list of formats in which <tt>RecorderImpl</tt> instances support * recording media. */ public static final String[] SUPPORTED_FORMATS = new String[] { /* Disables formats currently not working SoundFileUtils.aif, SoundFileUtils.au, SoundFileUtils.gsm, SoundFileUtils.wav,*/ SoundFileUtils.mp3 }; /** * The <tt>AudioMixerMediaDevice</tt> which is to be or which is already * being recorded by this <tt>Recorder</tt>. */ private final AudioMixerMediaDevice device; /** * The <tt>MediaDeviceSession</tt> is used to create an output data source. */ private MediaDeviceSession deviceSession; /** * The <tt>List</tt> of <tt>Recorder.Listener</tt>s interested in * notifications from this <tt>Recorder</tt>. */ private final List<Recorder.Listener> listeners = new ArrayList<Recorder.Listener>(); /** * <tt>DataSink</tt> used to save the output data. */ private DataSink sink; /** * The indicator which determines whether this <tt>Recorder</tt> * is set to skip media from mic. */ private boolean mute = false; /** * The filename we will use to record data, supplied * when Recorder is started. */ private String filename = null; /** * Constructs the <tt>RecorderImpl</tt> with the provided session. * * @param device device that can create a session that provides the output * data source */ public RecorderImpl(AudioMixerMediaDevice device) { if (device == null) throw new NullPointerException("device"); this.device = device; } /** * Adds a new <tt>Recorder.Listener</tt> to the list of listeners interested * in notifications from this <tt>Recorder</tt>. * * @param listener the new <tt>Recorder.Listener</tt> to be added to the * list of listeners interested in notifications from this <tt>Recorder</tt> * @see Recorder#addListener(Recorder.Listener) */ public void addListener(Recorder.Listener listener) { if (listener == null) throw new NullPointerException("listener"); synchronized (listeners) { if (!listeners.contains(listener)) listeners.add(listener); } } private ContentDescriptor getContentDescriptor(String format) throws IllegalArgumentException { String type; if (SoundFileUtils.wav.equalsIgnoreCase(format)) type = FileTypeDescriptor.WAVE; else if (SoundFileUtils.mp3.equalsIgnoreCase(format)) type = FileTypeDescriptor.MPEG_AUDIO; else if (SoundFileUtils.gsm.equalsIgnoreCase(format)) type = FileTypeDescriptor.GSM; else if (SoundFileUtils.au.equalsIgnoreCase(format)) type = FileTypeDescriptor.BASIC_AUDIO; else if (SoundFileUtils.aif.equalsIgnoreCase(format)) type = FileTypeDescriptor.AIFF; else { throw new IllegalArgumentException( format + " is not a supported recording format."); } return new ContentDescriptor(type); } /** * Gets a list of the formats in which this <tt>Recorder</tt> supports * recording media. * * @return a <tt>List</tt> of the formats in which this <tt>Recorder</tt> * supports recording media * @see Recorder#getSupportedFormats() */ public List<String> getSupportedFormats() { return Arrays.asList(SUPPORTED_FORMATS); } /** * Removes a existing <tt>Recorder.Listener</tt> from the list of listeners * interested in notifications from this <tt>Recorder</tt>. * * @param listener the existing <tt>Recorder.Listener</tt> to be removed * from the list of listeners interested in notifications from this * <tt>Recorder</tt> * @see Recorder#removeListener(Recorder.Listener) */ public void removeListener(Recorder.Listener listener) { if (listener != null) { synchronized (listeners) { listeners.remove(listener); } } } /** * Starts the recording of the media associated with this <tt>Recorder</tt> * (e.g. the media being sent and received in a <tt>Call</tt>) into a file * with a specific name. * * @param format the format into which the media associated with this * <tt>Recorder</tt> is to be recorded into the specified file * @param filename the name of the file into which the media associated with * this <tt>Recorder</tt> is to be recorded * @throws IOException if anything goes wrong with the input and/or output * performed by this <tt>Recorder</tt> * @throws MediaException if anything else goes wrong while starting the * recording of media performed by this <tt>Recorder</tt> * @see Recorder#start(String, String) */ public void start(String format, String filename) throws IOException, MediaException { if (this.sink == null) { if (format == null) throw new NullPointerException("format"); if (filename == null) throw new NullPointerException("filename"); this.filename = filename; /* * A file without an extension may not only turn out to be a touch * more difficult to play but is suspected to also cause an * exception inside of JMF. */ int extensionBeginIndex = filename.lastIndexOf('.'); if (extensionBeginIndex < 0) filename += '.' + format; else if (extensionBeginIndex == filename.length() - 1) filename += format; MediaDeviceSession deviceSession = device.createSession(); try { deviceSession.setContentDescriptor( getContentDescriptor(format)); // set initial mute state, if mute was set before starting // the recorder deviceSession.setMute(mute); /* * This RecorderImpl will use deviceSession to get a hold of the * media being set to the remote peers associated with the same * AudioMixerMediaDevice i.e. this RecorderImpl needs * deviceSession to only capture and not play back. */ deviceSession.start(MediaDirection.SENDONLY); this.deviceSession = deviceSession; } finally { if (this.deviceSession == null) { throw new MediaException( "Failed to create MediaDeviceSession from" + " AudioMixerMediaDevice for the purposes of" + " recording"); } } Throwable exception = null; try { DataSource outputDataSource = deviceSession.getOutputDataSource(); DataSink sink = Manager.createDataSink( outputDataSource, new MediaLocator("file:" + filename)); sink.open(); sink.start(); this.sink = sink; } catch (NoDataSinkException ndsex) { exception = ndsex; } finally { if ((this.sink == null) || (exception != null)) { stop(); throw new MediaException( "Failed to start recording into file " + filename, exception); } } } } /** * Stops the recording of the media associated with this <tt>Recorder</tt> * (e.g. the media being sent and received in a <tt>Call</tt>) if it has * been started and prepares this <tt>Recorder</tt> for garbage collection. * * @see Recorder#stop() */ public void stop() { if (deviceSession != null) { deviceSession.close(); deviceSession = null; } if (sink != null) { sink.close(); sink = null; /* * RecorderImpl creates the sink upon start() and it does it only if * it is null so this RecorderImpl has really stopped only if it has * managed to close() the (existing) sink. Notify the registered * listeners. */ Recorder.Listener[] listeners; synchronized (this.listeners) { listeners = this.listeners.toArray( new Recorder.Listener[this.listeners.size()]); } for (Recorder.Listener listener : listeners) listener.recorderStopped(this); } } /** * Put the recorder in mute state. It won't record the local input. * This is used when the local call is muted and we don't won't to record * the local input. * * @param mute the new value of the mute property */ public void setMute(boolean mute) { this.mute = mute; if (deviceSession != null) deviceSession.setMute(mute); } /** * Returns the filename we are last started or stopped recording to, * null if not started. * * @return the filename we are last started or stopped recording to, * null if not started. */ public String getFilename() { return filename; } }
package org.mozilla.mozstumbler; import org.mozilla.mozstumbler.preferences.PreferencesScreen; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.location.LocationManager; import android.net.Uri; import android.os.Build.VERSION; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.os.StrictMode; import android.provider.Settings; import android.text.Editable; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public final class MainActivity extends Activity { private static final String LOGTAG = MainActivity.class.getName(); private static final String LEADERBOARD_URL = "https://location.services.mozilla.com/leaders"; private ScannerServiceInterface mConnectionRemote; private ServiceConnection mConnection; private ServiceBroadcastReceiver mReceiver; private int mGpsFixes; private class ServiceBroadcastReceiver extends BroadcastReceiver { private boolean mReceiverIsRegistered; public void register() { if (!mReceiverIsRegistered) { registerReceiver(this, new IntentFilter(ScannerService.MESSAGE_TOPIC)); mReceiverIsRegistered = true; } } public void unregister() { if (mReceiverIsRegistered) { unregisterReceiver(this); mReceiverIsRegistered = false; } } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (!action.equals(ScannerService.MESSAGE_TOPIC)) { Log.e(LOGTAG, "Received an unknown intent"); return; } String subject = intent.getStringExtra(Intent.EXTRA_SUBJECT); if (subject.equals("Reporter")) { updateUI(); Log.d(LOGTAG, "Received a reporter intent..."); return; } if (subject.equals("Scanner")) { mGpsFixes = intent.getIntExtra("fixes", 0); updateUI(); Log.d(LOGTAG, "Received a scanner intent..."); return; } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); enableStrictMode(); setContentView(R.layout.activity_main); Updater.checkForUpdates(this); Log.d(LOGTAG, "onCreate"); } private void checkGps() { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) { new AlertDialog.Builder(this) .setCancelable(false) .setTitle(R.string.app_name) .setMessage(R.string.gps_alert_msg) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } } @Override protected void onStart() { super.onStart(); checkGps(); mReceiver = new ServiceBroadcastReceiver(); mReceiver.register(); mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder binder) { mConnectionRemote = ScannerServiceInterface.Stub.asInterface(binder); Log.d(LOGTAG, "Service connected"); updateUI(); } public void onServiceDisconnected(ComponentName className) { mConnectionRemote = null; Log.d(LOGTAG, "Service disconnected", new Exception()); } }; Intent intent = new Intent(this, ScannerService.class); startService(intent); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); Log.d(LOGTAG, "onStart"); } @Override protected void onStop() { super.onStop(); unbindService(mConnection); mConnection = null; mConnectionRemote = null; mReceiver.unregister(); mReceiver = null; Log.d(LOGTAG, "onStop"); } protected void updateUI() { // TODO time this to make sure we're not blocking too long on mConnectionRemote // if we care, we can bundle this into one call -- or use android to remember // the state before the rotation. if (mConnectionRemote == null) { return; } Log.d(LOGTAG, "Updating UI"); boolean scanning = false; try { scanning = mConnectionRemote.isScanning(); } catch (RemoteException e) { Log.e(LOGTAG, "", e); } int locationsScanned = 0; double latitude = 0; double longitude = 0; int APs = 0; int visibleAPs = 0; long lastUploadTime = 0; long reportsSent = 0; try { locationsScanned = mConnectionRemote.getLocationCount(); latitude = mConnectionRemote.getLatitude(); longitude = mConnectionRemote.getLongitude(); APs = mConnectionRemote.getAPCount(); visibleAPs = mConnectionRemote.getVisibleAPCount(); lastUploadTime = mConnectionRemote.getLastUploadTime(); reportsSent = mConnectionRemote.getReportsSent(); } catch (RemoteException e) { Log.e(LOGTAG, "", e); } Log.d(LOGTAG, "!!!!! we are scanning?? = " + scanning); ProgressBar progress = (ProgressBar) findViewById(R.id.progressBar); if (scanning) { progress.setVisibility(View.VISIBLE); } else { progress.setVisibility(View.GONE); } String lastUploadTimeString = (lastUploadTime > 0) ? DateTimeUtils.formatTimeForLocale(lastUploadTime) : "-"; String lastLocationString = (mGpsFixes > 0 && locationsScanned > 0) ? formatLocation(latitude, longitude) : "-"; formatTextView(R.id.gps_satellites, R.string.gps_satellites, mGpsFixes); formatTextView(R.id.last_location, R.string.last_location, lastLocationString); formatTextView(R.id.visible_wifi_access_points, R.string.visible_wifi_access_points, visibleAPs); formatTextView(R.id.wifi_access_points, R.string.wifi_access_points, APs); formatTextView(R.id.locations_scanned, R.string.locations_scanned, locationsScanned); formatTextView(R.id.last_upload_time, R.string.last_upload_time, lastUploadTimeString); formatTextView(R.id.reports_sent, R.string.reports_sent, reportsSent); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_about) { startActivity(new Intent(getApplication(), AboutActivity.class)); return true; } if (item.getItemId() == R.id.action_preferences) { startActivity(new Intent(getApplication(), PreferencesScreen.class)); return true; } if (item.getItemId() == R.id.action_view_leaderboard) { Intent openLeaderboard = new Intent(Intent.ACTION_VIEW, Uri.parse(LEADERBOARD_URL)); startActivity(openLeaderboard); return true; } if (item.getItemId() == R.id.action_test_mls) { // We are starting Wi-Fi scanning because we want the the APs for our // geolocation request whose results we want to display on the map. if (mConnectionRemote != null) { try { mConnectionRemote.startScanning(); } catch (RemoteException e) { Log.e(LOGTAG, "", e); } } Intent intent = new Intent(this, MapActivity.class); startActivity(intent); return true; } if (item.getItemId() == R.id.action_exit) { if (mConnectionRemote != null) { try { mConnectionRemote.stopScanning(); } catch (RemoteException e) { Log.e(LOGTAG, "", e); } } finish(); return true; } return super.onOptionsItemSelected(item); } @TargetApi(9) private void enableStrictMode() { if (VERSION.SDK_INT < 9) { return; } StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .permitDiskReads() .permitDiskWrites() .penaltyLog().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectAll() .penaltyLog().build()); } private void formatTextView(int textViewId, int stringId, Object... args) { TextView textView = (TextView) findViewById(textViewId); String str = getResources().getString(stringId); str = String.format(str, args); textView.setText(str); } private String formatLocation(double latitude, double longitude) { final String coordinateFormatString = getResources().getString(R.string.coordinate); return String.format(coordinateFormatString, latitude, longitude); } }
package org.myrobotlab.service; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Reader; import java.io.Serializable; import java.io.StringReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.ServerSocket; //import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.atmosphere.wasync.Client; import org.atmosphere.wasync.ClientFactory; import org.atmosphere.wasync.Decoder; import org.atmosphere.wasync.Encoder; import org.atmosphere.wasync.Event; import org.atmosphere.wasync.Function; import org.atmosphere.wasync.Request; import org.atmosphere.wasync.RequestBuilder; import org.myrobotlab.framework.Message; import org.myrobotlab.framework.Platform; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceEnvironment; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.net.Connection; import org.myrobotlab.net.TCPThread2; import org.myrobotlab.service.interfaces.CommunicationInterface; import org.myrobotlab.service.interfaces.Gateway; import org.myrobotlab.service.interfaces.ServiceInterface; import org.slf4j.Logger; /** * * RemoteAdapter - Multi-node / distributed myrobotlab support. * * A RemoteAdapter allows other instances of MyRobotLab to connect. Services and * resources can be shared by 2 or more joined instances. The default * communication listener is a UDP server listening on all addresses on port * 6767. * * */ public class RemoteAdapter extends Service implements Gateway { // TODO - global address book of discovered connection public static class CommOptions implements Serializable { private static final long serialVersionUID = 1L; Platform platform; ArrayList<Gateway> gateways; public CommOptions() { } } static public class Scanner extends Thread { boolean isScanning = false; Service myService; public Scanner(Service service) { super(String.format("%s.scanner", service.getName())); this.myService = service; } @Override public void run() { // Find the server using UDP broadcast isScanning = true; while (isScanning && myService.isRunning()) { try { // Open a random port to send the package DatagramSocket dsocket = new DatagramSocket(); dsocket.setBroadcast(true); // byte[] sendData = // "DISCOVER_FUIFSERVER_REQUEST".getBytes(); Message msg = myService.createMessage("", "getConnections", null); byte[] msgBuf = org.myrobotlab.codec.CodecUtils.getBytes(msg); DatagramPacket sendPacket; // Try the 255.255.255.255 first /* * try { sendPacket = new DatagramPacket(msgBuf, msgBuf.length, * InetAddress.getByName("255.255.255.255"), 6767); * dsocket.send(sendPacket); myService.info( * ">>> Request packet sent to: 255.255.255.255 (DEFAULT)"); } catch * (Exception e) { Logging.logException(e); } */ // NEEDED ?? WE ALREADY DID BROADCAST // Broadcast the // message over all the network interfaces Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface ni = interfaces.nextElement(); // myService.info("examining interface %s %s", // ni.getName(), ni.getInetAddresses().toString()); log.info(String.format("examining interface %s %s", ni.getName(), ni.getDisplayName())); // if (ni.isLoopback() || !ni.isUp()) { if (!ni.isUp()) { log.info(String.format("skipping %s", ni.getDisplayName())); continue; // Don't want tobroadcast to the loopback // // interface } for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) { InetAddress broadcast = interfaceAddress.getBroadcast(); // short x = interfaceAddress.getNetworkPrefixLength(); log.info("" + interfaceAddress.getAddress()); if (ni.getName().equals("net4")) { log.info("net4"); } if (broadcast == null) { continue; } // Send the broadcast package! try { log.info(String.format("sending to %s %s %s", ni.getName(), broadcast.getHostAddress(), ni.getDisplayName())); if (interfaceAddress.getNetworkPrefixLength() == -1) { log.warn("jdk bug for interface %s network prefix length == -1", interfaceAddress.getAddress().getHostAddress()); String pre = interfaceAddress.getAddress().getHostAddress(); String b = pre.substring(0, pre.lastIndexOf(".")) + ".255"; log.warn("creating new broadcast address of %s", broadcast); broadcast = InetAddress.getByName(b); } sendPacket = new DatagramPacket(msgBuf, msgBuf.length, broadcast, 6767); // sendPacket = new DatagramPacket(msgBuf, // msgBuf.length, // InetAddress.getByName("192.168.0.255"), // 6767); dsocket.send(sendPacket); myService.info(">>> Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + ni.getDisplayName()); } catch (Exception e) { myService.error(e); } } } myService.info(">>> Done looping over all network interfaces. Now waiting for a reply!"); // multiple replies boolean listening = true; // wait and read replies - put them on the message queue // time out and will be done try { while (listening) { // Wait for a response byte[] recvBuf = new byte[15000]; DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); // how long we will wait for replies dsocket.setSoTimeout(2000); dsocket.receive(receivePacket); // We have a response myService.info(String.format("response from : %s", receivePacket.getAddress().getHostAddress())); // Check if the message is correct - JSON ? ObjectInputStream inBytes = new ObjectInputStream(new ByteArrayInputStream(receivePacket.getData())); Message retMsg = (Message) inBytes.readObject(); myService.info("response from instance %s", retMsg); if (!retMsg.method.equals("publishNewConnection")) { myService.error("not an publishNewConnection message"); continue; } else { List<Connection> conns = (List<Connection>) retMsg.data[0]; for (int i = 0; i < conns.size(); ++i) { myService.invoke("publishNewConnection", conns.get(i)); } } /* * String message = new String(receivePacket.getData()).trim(); if * (message.equals("DISCOVER_FUIFSERVER_RESPONSE")) { // DO * SOMETHING WITH THE SERVER'S IP (for example, store it in // * your controller) // Controller_Base * .setServerIp(receivePacket.getAddress()); log.info( * String.format( "+++++++++++++FOUND MRL INSTANCE++++++++++++ %s" * , receivePacket.getAddress())); } */ } } catch (SocketTimeoutException se) { myService.info("done listening for replies"); } finally { dsocket.close(); } } catch (Exception e) { myService.error(e); } } // while (isScanning) } } class TCPListener extends Thread { int rxCount = 0; int txCount = 0; RemoteAdapter myService = null; transient ServerSocket serverSocket = null; ObjectOutputStream out; ObjectInputStream in; int remotePort; public TCPListener(int remotePort, RemoteAdapter s) { super(String.format("%s.tcp.%d", s.getName(), remotePort)); this.remotePort = remotePort; myService = s; } public void addTCPClient(java.net.Socket clientSocket, RemoteAdapter myService) { try { String clientKey = String.format("tcp://%s:%d", clientSocket.getInetAddress().getHostAddress(), clientSocket.getPort()); URI uri = new URI(clientKey); // HELP PROTOKEY VS MRL KEY ?? TCPThread2 tcp = new TCPThread2(myService, uri, clientSocket); tcpClientList.put(uri, tcp); connections.put(uri, tcp.data); } catch (Exception e) { Logging.logError(e); } } @Override public void run() { try { serverSocket = new ServerSocket(remotePort, 10); log.info(getName() + " TCPListener listening on " + serverSocket.getLocalSocketAddress()); myService.info(String.format("listening on %s tcp", serverSocket.getLocalSocketAddress())); while (isRunning()) { // FIXME - on contact register the "environment" regardless // if a service registers !!! java.net.Socket clientSocket = serverSocket.accept(); // inbound connection FIXME - all keys constructed in // Encoder addTCPClient(clientSocket, myService); broadcastState(); } serverSocket.close(); } catch (Exception e) { logException(e); } } public void shutdown() { if ((serverSocket != null) && (!serverSocket.isClosed())) { try { serverSocket.close(); } catch (IOException e) { logException(e); } } serverSocket = null; } } class UDPListener extends Thread { DatagramSocket socket = null; RemoteAdapter myService = null; int listeningPort; boolean isRunning = false; public UDPListener(Integer listeningPort, RemoteAdapter s) { super(String.format("%s.udp.%d", s.getName(), listeningPort)); this.listeningPort = listeningPort; myService = s; } // FIXME FIXME FIXME - large amount of changes to tcp - application // logic which handles the "Messaging" should be common to both // tcp & udp & xmpp @Override public void run() { isRunning = true; try { socket = new DatagramSocket(listeningPort); log.info(String.format("%s listening on udp %s:%d", getName(), socket.getLocalAddress(), socket.getLocalPort())); byte[] b = new byte[65507]; // max udp size 65507 + 8 byte // header = 65535 ByteArrayInputStream b_in = new ByteArrayInputStream(b); DatagramPacket dgram = new DatagramPacket(b, b.length); while (isRunning) { socket.receive(dgram); // receives all datagrams // FIXME - do we need o re-create??? ObjectInputStream o_in = new ObjectInputStream(b_in); try { Message msg = (Message) o_in.readObject(); dgram.setLength(b.length); // must reset length field! b_in.reset(); // FIXME - sloppy use full method signature // FIXME Encoder.makeMethodKey(Msg msg) if ("getConnections".equals(msg.method)) { // get connections List<Connection> conn = getConnections(new URI(String.format("tcp:/%s:%d", dgram.getAddress(), dgram.getPort()))); // send them back for (int i = 0; i < conn.size(); ++i) { Message newConnMsg = createMessage("", "publishNewConnection", conn); byte[] msgBuf = org.myrobotlab.codec.CodecUtils.getBytes(newConnMsg); DatagramPacket dgp = new DatagramPacket(msgBuf, msgBuf.length, dgram.getAddress(), dgram.getPort()); socket.send(dgp); } // we will have to search for them again } else if ("publishNewConnection".equals(msg.method)) { myService.invoke("onCommOptions", msg.data[0]); } else if ("register".equals(msg.method)) { // FIXME name should be "Runtime" representing the // static // IMPORTANT - (should be in Encoder) - create the // key // for foreign service environment // Runtime.addServiceEnvironment(name, protocolKey) URI protocolKey = new URI(String.format("udp://%s:%d", socket.getInetAddress().getHostAddress(), socket.getPort())); String mrl = String.format("mrl://%s/%s", myService.getName(), protocolKey.toString()); URI mrlURI = new URI(mrl); // IMPORTANT - this is an optimization and probably // should be in the Comm interface defintion CommunicationInterface cm = myService.getComm(); cm.addRemote(mrlURI, protocolKey); // check if the URI is already defined - if not - we // will // send back the services which we want to export - // Security will filter appropriately ServiceEnvironment foreignProcess = Runtime.getEnvironment(mrlURI); ServiceInterface si = (ServiceInterface) msg.data[0]; // HMMM a vote for String vs URI here - since we // need to // catch syntax !!! si.setInstanceId(mrlURI); // if security ... msg within msg // getOutbox().add(createMessage(Runtime.getInstance().getName(), // "register", inboundMsg)); Runtime.register(si, mrlURI);// <-- not an INVOKE // no security ! :P if (foreignProcess == null) { // not defined we will send export // TODO - Security filters - default export // (include // exclude) - mapset of name ServiceEnvironment localProcess = Runtime.getLocalServicesForExport(); Iterator<String> it = localProcess.serviceDirectory.keySet().iterator(); String name; ServiceInterface toRegister; while (it.hasNext()) { name = it.next(); toRegister = localProcess.serviceDirectory.get(name); // the following will wrap a message within // a message and send it remotely // This Thread CANNOT Write on The // ObjectOutputStream directly - // IT SHOULD NEVER DO ANY METHOD WHICH CAN // BLOCK !!!! - 3 days of bug chasing when // it wrote to ObjectOutputStream and oos // blocked when the buffer was full - // causing deadlock // putting it on the inbox will move it to a // different thread Message sendService = myService.createMessage("", "register", toRegister); Message outbound = myService.createMessage(myService.getName(), "sendRemote", new Object[] { protocolKey, sendService }); myService.getInbox().add(outbound); } } } else { // ++udpRx; myService.getOutbox().add(msg); } } catch (Exception e) { error(e); } dgram.setLength(b.length); // must reset length field! b_in.reset(); // reset so next read is from start of byte[] // again } // while isRunning } catch (SocketException se) { error("UDPListener could not listen %s", se.getMessage()); Logging.logError(se); } catch (Exception e) { error("wtf error"); logException(e); } } public void shutdown() { isRunning = false; if ((socket != null) && (!socket.isClosed())) { socket.close(); } } } private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(RemoteAdapter.class); public String lastProtocolKey; private String defaultPrefix = null; private HashMap<String, String> prefixMap = new HashMap<String, String>(); // private HashSet<URI> localProtocolKeys = new HashSet<URI>(); // types of listening threads - multiple could be managed // when correct interfaces and base classes are done transient TCPListener tcpListener = null; transient UDPListener udpListener = null; private Integer udpPort; private Integer tcpPort; boolean isListening = false; boolean isScanning = false; // TODO - multiple scanners for parallel port/broadcast scanning transient Scanner scanner; transient private HashMap<URI, TCPThread2> tcpClientList = new HashMap<URI, TCPThread2>(); /** * used as a data interface to all the non-serializable network objects - it * will report stats and states */ private HashMap<URI, Connection> connections = new HashMap<URI, Connection>(); boolean listenOnStartup = false; static public ArrayList<InetAddress> getLocalAddresses() { ArrayList<InetAddress> ret = new ArrayList<InetAddress>(); try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); ret.add(inetAddress); } } } catch (Exception e) { logException(e); } return ret; } public RemoteAdapter(String n) { super(n); defaultPrefix = String.format("%s.", n); // addLocalTask(5 * 1000, "broadcastHeartbeat"); } @Override public void addConnectionListener(String name) { addListener("publishNewConnection", name, "onNewConnection"); } // FIXME - add to Gateway interfaceS public HashMap<URI, Connection> broadcastHeartbeat() { for (Map.Entry<URI, Connection> entry : connections.entrySet()) { URI uri = entry.getKey(); // Connection value = entry.getValue(); // roll through send a set of transactions off & start a // IOCompletion like // array of status ... // if timeout is reached - write the rest with timeout (those that // did not // get an asynch response if (uri.getScheme().equals("tcp")) { TCPThread2 tcp = tcpClientList.get(uri); log.info("" + tcp); // check socket connectivity // attempt to re-connect if disconnected broadcastState(); } } return connections; } @Override // TODO refactor with boolean - lower level error(problem) to put into // framework public void connect(String uri) throws URISyntaxException { Message msg = createMessage("", "register", null); sendRemote(uri, msg); } @Override public HashMap<URI, Connection> getClients() { return connections; } /** * important initial communication function related to discovery a broadcast * goes out and replies must include details of communication so that a viable * connection can be created * * @param client */ // global access keys (all gateways) - or just this gateway ??? // if it's all then this could be a function of runtime which is probably // the best @Override public List<Connection> getConnections(URI clientKey) { ArrayList<Connection> conns = new ArrayList<Connection>(); try { // FIXME - dorky - probably fix with template method // FIXME - do "global" next ArrayList<ServiceInterface> services = Runtime.getServicesFromInterface(Gateway.class); // ArrayList<Gateway> gateways = new ArrayList<Gateway>(); // if GLOBAL for (int i = 0; i < services.size(); ++i) { // Gateway // gateways.add((Gateway) services.get(i)); } // else LOCAL // add (this) services connections List<String> addr = Runtime.getLocalAddresses(); for (int i = 0; i < addr.size(); ++i) { Connection tcpConn = new Connection(); // theoretically you could advertise udp too (and others) // tcpConn.protocolKey = new // URI(String.format("mrl://%s/tcp://%s:%d", getName(), // addr.get(i), getTcpPort())); tcpConn.protocolKey = new URI(String.format("tcp://%s:%d", addr.get(i), getTcpPort())); // we dont fill in our own name // FIXME FIXME FIXME - DO THE CORRECT WAY !!! // / tcpConn.protocolKey = new URI(String.format("tcp://%s:%d", // addr.get(i), getTcpPort())); // tcpKey.prefix = suggestion // tcpKey.prefix = prefix; tcpConn.platform = Runtime.getInstance().getPlatform(); tcpConn.prefix = Runtime.getInstance().getName();// calls // getPrefix // under // hood conns.add(tcpConn); } // tcpKey.uri = } catch (Exception e) { Logging.logError(e); } return conns; } // @Override needs to be overriden - Gateway need implementation public Platform getPlatform() { return Runtime.getInstance().getPlatform(); } @Override public String getPrefix(URI protocolKey) { if (defaultPrefix != null) { return defaultPrefix; } else { return "";// important - return "" not null } } public Integer getTcpPort() { return tcpPort; } public Integer getUdpPort() { return udpPort; } public boolean isListening() { return isListening; } @Override public boolean isReady() { if (tcpListener.serverSocket != null) { return tcpListener.serverSocket.isBound(); } return false; } public boolean isScanning() { return isScanning; } public Connection onHeartbeat(Connection data) { return data; } /** * NOT USED - just left as an example of a consumer asynchronous return of * access key request * * @param keys * @return */ public Connection onNewConnection(Connection conn) { return conn; } // publishing point @Override public Connection publishNewConnection(Connection conn) { if (!connections.containsKey(conn.protocolKey)) { // uri will now become my uri connections.put(conn.protocolKey, conn); broadcastState(); } else { info("%d scanning no new connections", System.currentTimeMillis()); } return conn; } public void scan() { if (scanner != null) { stopScanning(); } scanner = new Scanner(this); scanner.start(); isScanning = true; } @Override public void sendRemote(String uri, Message msg) throws URISyntaxException { sendRemote(new URI(uri), msg); } @Override synchronized public void sendRemote(URI uri, Message msg) { String scheme = uri.getScheme(); lastProtocolKey = uri.toString(); if ("tcp".equals(scheme)) { sendRemoteTCP(uri, msg); } else if ("udp".equals(scheme)) { sendRemoteUDP(uri, msg); } else { error(String.format("%s not supported", uri.toString())); return; } } public void sendRemoteTCP(URI uri, Message msg) { TCPThread2 tcp = null; try { if (tcpClientList.containsKey(uri)) { tcp = tcpClientList.get(uri); } else { // constructor will throw if can not connect -> new Socket(host, // port) tcp = new TCPThread2(this, uri, null); tcpClientList.put(uri, tcp); connections.put(uri, tcp.data); broadcastState(); } tcp.send(msg); connections.get(uri).tx++; } catch (Exception e) { Logging.logError(e); } } public void sendRemoteUDP(URI uri, Message msg) { try { // FIXME - could use some optimization e.g. .reset() DatagramSocket s = new DatagramSocket(); ByteArrayOutputStream b_out = new ByteArrayOutputStream(); ObjectOutputStream o_out = new ObjectOutputStream(b_out); o_out.writeObject(msg); o_out.flush(); b_out.flush(); byte[] b = b_out.toByteArray(); InetAddress hostAddress = InetAddress.getByName(uri.getHost()); DatagramPacket dgram = new DatagramPacket(b, b.length, hostAddress, uri.getPort()); s.send(dgram); // dgram.se // TODO - send the damn packet??? // close the datagram to avoid resource leaks s.close(); } catch (Exception e) { Logging.logError(e); } } public String setDefaultPrefix(String prefix) { defaultPrefix = prefix; return prefix; } public void setPrefix(String source, String prefix) { prefixMap.put(source, prefix); } public void setTCPPort(Integer tcpPort) { this.tcpPort = tcpPort; } public void setUDPPort(Integer udpPort) { this.udpPort = udpPort; } public void startListening() { if (udpPort == null) { udpPort = 6767; } if (tcpPort == null) { tcpPort = 6767; } startListening(udpPort, tcpPort); isListening = true; broadcastState(); } public void startListening(int ports) { startListening(ports, ports); } public void startListening(int udpPort, int tcpPort) { startUDP(udpPort); startTCP(tcpPort); } public void startTCP(Integer port) { stopTCP(); if (port == null) { port = 6767; } tcpPort = port; tcpListener = new TCPListener(tcpPort, this); tcpListener.start(); } public void startUDP(Integer port) { stopUDP(); if (port == null) { port = 6767; } udpPort = port; udpListener = new UDPListener(udpPort, this); udpListener.start(); } public void stopListening() { stopUDP(); stopTCP(); isListening = false; broadcastState(); } public void stopScanning() { scanner.isScanning = false; isScanning = false; scanner = null; } @Override public void stopService() { stopListening(); super.stopService(); } public void stopTCP() { if (tcpListener != null) { tcpListener.interrupt(); tcpListener.shutdown(); tcpListener = null; } } public void stopUDP() { if (udpListener != null) { udpListener.interrupt(); udpListener.shutdown(); udpListener = null; } } public void startService() { super.startService(); if (listenOnStartup) { startListening(); } } public void listenOnStartup(boolean b) { listenOnStartup = b; } public void websocket(String url) throws IOException { Client client = ClientFactory.getDefault().newClient(); RequestBuilder request = client.newRequestBuilder().method(Request.METHOD.GET).uri(url).encoder(new Encoder<String, Reader>() { // Stream // the // request // body @Override public Reader encode(String s) { return new StringReader(s); } }).decoder(new Decoder<String, Reader>() { @Override public Reader decode(Event type, String s) { return new StringReader(s); } }).transport(Request.TRANSPORT.WEBSOCKET) // Try WebSocket .transport(Request.TRANSPORT.LONG_POLLING); // Fallback to Long-Polling org.atmosphere.wasync.Socket socket = client.create(); socket.on(new Function<Reader>() { @Override public void on(Reader r) { // Read the response } }).on(new Function<IOException>() { @Override public void on(IOException arg0) { // TODO Auto-generated method stub } }).open(request.build()).fire("/api/").fire("bong"); } /** * 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(RemoteAdapter.class.getCanonicalName()); meta.addDescription("allows remote communication between applets, or remote instances of myrobotlab"); meta.addCategory("connectivity", "network", "framework"); meta.addDependency("org.atmosphere.nettosphere", "2.3.0"); return meta; } public static void main(String[] args) { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.DEBUG); try { // int i = 0; // RemoteAdapter remote0 = (RemoteAdapter) // Runtime.start(String.format("remote%d", 0), "RemoteAdapter"); // Runtime.start("mac", "Runtime"); // Runtime.start("gui", "GUIService"); // Runtime.start("webgui", "WebGui"); Runtime.start("python", "Python"); // Runtime.start("mac.clock", "Clock"); // Arduino arduino = (Arduino)Runtime.start("arduino", "Arduino"); // Servo servo = (Servo) Runtime.start("servo", "Servo"); // Arduino Arduino = (Arduino) Runtime.start("arduino", "Arduino"); // Max frame length of 10240 has been exceeded. FIXME !!!! RemoteAdapter remote = (RemoteAdapter) Runtime.start("remote", "RemoteAdapter"); // remote.connect("tcp://demo.myrobotlab.org:6767"); Runtime.start("gui", "GUIService"); remote.startListening(); // remote1.startListening(); // remote1.setTCPPort(6868); // remote1.setUDPPort(6868); // remote1.startListening(); // Runtime.start(String.format("gui%d", i), "GUIService"); // Runtime.start("python", "Python"); // arduino.connect("COM9"); // remote1.startListening(6666, 6666); // remote1.startListening(); // remote0.startUDP(6767); // remote1.startListening(); // remote1.startUDP(6767); // remote1.scan(); /* * Runtime.main(new String[] { "-runtimeName", String.format("r%d", i) }); * RemoteAdapter remote = (RemoteAdapter) * Runtime.start(String.format("remote%d", i), "RemoteAdapter"); * Runtime.start(String.format("clock%d", i), "Clock"); * Runtime.start(String.format("gui%d", i), "GUIService"); * * // Security security = // * (Security)Runtime.start(String.format("security", i), // "Security"); * remote.startListening(); // security.allowExportByName("laptop", true); * // security.allowExportByName("laptop.gui", false); // * remote.connect("tcp://192.168.0.92:6767"); // * Runtime.start(String.format("joystick%d", i), "Joystick"); // * Runtime.start(String.format("python%d", i), "Python"); */ // what if null service is passed "register()" no parameters - // I'm sending a registration of nothing? // remote.broadcastState(); // remote.connect("tcp://127.0.0.1:6767"); /* * THIS WORKS Message msg = remote.createMessage("", "register", remote); * remote.sendRemote("tcp://127.0.0.1:6868", msg); */ // FIXME - sholdn't this be sendRemote ??? or at least // in an interface // remote.sendRemote(uri, msg); // xmpp1.sendMessage("xmpp 2", "robot02 02"); } catch (Exception e) { Logging.logError(e); } } }
package com.opengamma.web.timeseries; import java.net.URI; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.time.CalendricalException; import javax.time.calendar.LocalDate; import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import org.apache.commons.lang.StringUtils; import org.joda.beans.impl.flexi.FlexiBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Maps; import com.opengamma.id.IdentificationScheme; import com.opengamma.id.Identifier; import com.opengamma.id.UniqueIdentifier; import com.opengamma.master.timeseries.TimeSeriesDocument; import com.opengamma.master.timeseries.TimeSeriesLoader; import com.opengamma.master.timeseries.TimeSeriesMaster; import com.opengamma.master.timeseries.TimeSeriesSearchRequest; import com.opengamma.master.timeseries.TimeSeriesSearchResult; import com.opengamma.util.db.PagingRequest; import com.opengamma.web.WebPaging; import com.sun.jersey.api.client.ClientResponse.Status; /** * RESTful resource for all time series. * <p> * The time series resource represents the whole of a time series master. */ @Path("/timeseries") public class WebAllTimeSeriesResource extends AbstractWebTimeSeriesResource { /** Logger. */ private static final Logger s_logger = LoggerFactory.getLogger(WebAllTimeSeriesResource.class); /** * Creates the resource. * @param timeSeriesMaster the time series master, not null * @param timeSeriesLoader the timeseries loader, not null */ public WebAllTimeSeriesResource(final TimeSeriesMaster<?> timeSeriesMaster, final TimeSeriesLoader timeSeriesLoader) { super(timeSeriesMaster, timeSeriesLoader); } @GET @Produces(MediaType.TEXT_HTML) public String getHTML( @QueryParam("page") int page, @QueryParam("pageSize") int pageSize, @QueryParam("identifier") String identifier, @QueryParam("dataSource") String dataSource, @QueryParam("dataProvider") String dataProvider, @QueryParam("dataField") String dataField, @QueryParam("observationTime") String observationTime, @Context UriInfo uriInfo) { FlexiBean out = createSearchResultData(page, pageSize, identifier, dataSource, dataProvider, dataField, observationTime, uriInfo); return getFreemarker().build("timeseries/alltimeseries.ftl", out); } @GET @Produces(MediaType.APPLICATION_JSON) public String getJSON( @QueryParam("page") int page, @QueryParam("pageSize") int pageSize, @QueryParam("identifier") String identifier, @QueryParam("dataSource") String dataSource, @QueryParam("dataProvider") String dataProvider, @QueryParam("dataField") String dataField, @QueryParam("observationTime") String observationTime, @Context UriInfo uriInfo) { FlexiBean out = createSearchResultData(page, pageSize, identifier, dataSource, dataProvider, dataField, observationTime, uriInfo); return getFreemarker().build("timeseries/jsonalltimeseries.ftl", out); } @SuppressWarnings({"rawtypes", "unchecked" }) private FlexiBean createSearchResultData(int page, int pageSize, String identifier, String dataSource, String dataProvider, String dataField, String observationTime, UriInfo uriInfo) { FlexiBean out = createRootData(); TimeSeriesSearchRequest searchRequest = new TimeSeriesSearchRequest(); searchRequest.setPagingRequest(PagingRequest.of(page, pageSize)); searchRequest.setIdentifierValue(StringUtils.trimToNull(identifier)); searchRequest.setDataSource(StringUtils.trimToNull(dataSource)); searchRequest.setDataProvider(StringUtils.trimToNull(dataProvider)); searchRequest.setDataField(StringUtils.trimToNull(dataField)); searchRequest.setObservationTime(StringUtils.trimToNull(observationTime)); MultivaluedMap<String, String> query = uriInfo.getQueryParameters(); for (int i = 0; query.containsKey("idscheme." + i) && query.containsKey("idvalue." + i); i++) { Identifier id = Identifier.of(query.getFirst("idscheme." + i), query.getFirst("idvalue." + i)); searchRequest.getIdentifiers().add(id); } out.put("searchRequest", searchRequest); if (data().getUriInfo().getQueryParameters().size() > 0) { TimeSeriesSearchResult<?> searchResult = data().getTimeSeriesMaster().searchTimeSeries(searchRequest); out.put("searchResult", searchResult); out.put("paging", new WebPaging(searchResult.getPaging(), data().getUriInfo())); } return out; } @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_HTML) public Response postHTML( @FormParam("dataProvider") String dataProvider, @FormParam("dataField") String dataField, @FormParam("start") String start, @FormParam("end") String end, @FormParam("idscheme") String idScheme, @FormParam("idvalue") String idValue) { idScheme = StringUtils.trimToNull(idScheme); idValue = StringUtils.trimToNull(idValue); dataField = StringUtils.trimToNull(dataField); start = StringUtils.trimToNull(start); end = StringUtils.trimToNull(end); dataProvider = StringUtils.trimToNull(dataProvider); FlexiBean out = createRootData(); LocalDate startDate = null; boolean validStartDate = true; if (start != null) { try { startDate = LocalDate.parse(start); } catch (CalendricalException e) { out.put("err_startInvalid", true); validStartDate = false; } } LocalDate endDate = null; boolean validEndDate = true; if (end != null) { try { endDate = LocalDate.parse(end); } catch (CalendricalException e) { out.put("err_endInvalid", true); validEndDate = false; } } if (dataField == null || idValue == null || !validStartDate || !validEndDate) { //data for repopulating the form out.put("scheme", idScheme); out.put("dataField", dataField); out.put("idValue", idValue); out.put("dataProvider", dataProvider); out.put("start", start); out.put("end", end); if (dataField == null) { out.put("err_iddatafieldMissing", true); } if (idValue == null) { out.put("err_idvalueMissing", true); } String html = getFreemarker().build("timeseries/timeseries-add.ftl", out); return Response.ok(html).build(); } URI uri = addTimeSeries(dataProvider, dataField, idScheme, idValue, startDate, endDate); return Response.seeOther(uri).build(); } @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_JSON) public Response postJSON( @FormParam("dataProvider") String dataProvider, @FormParam("dataField") String dataField, @FormParam("start") String start, @FormParam("end") String end, @FormParam("idscheme") String idScheme, @FormParam("idvalue") String idValue) { idScheme = StringUtils.trimToNull(idScheme); idValue = StringUtils.trimToNull(idValue); dataField = StringUtils.trimToNull(dataField); start = StringUtils.trimToNull(start); end = StringUtils.trimToNull(end); dataProvider = StringUtils.trimToNull(dataProvider); LocalDate startDate = null; boolean validStartDate = true; if (start != null) { try { startDate = LocalDate.parse(start); validStartDate = true; } catch (CalendricalException e) { validStartDate = false; } } LocalDate endDate = null; boolean validEndDate = true; if (end != null) { try { endDate = LocalDate.parse(end); validEndDate = true; } catch (CalendricalException e) { validEndDate = false; } } if (dataField == null || idValue == null || !validStartDate || !validEndDate) { return Response.status(Status.BAD_REQUEST).build(); } URI uri = addTimeSeries(dataProvider, dataField, idScheme, idValue, startDate, endDate); return Response.created(uri).build(); } private URI addTimeSeries(String dataProvider, String dataField, String idScheme, String idValue, LocalDate startDate, LocalDate endDate) { IdentificationScheme scheme = IdentificationScheme.of(idScheme); Set<Identifier> identifiers = buildSecurityRequest(scheme, idValue); TimeSeriesLoader timeSeriesLoader = data().getTimeSeriesLoader(); Map<Identifier, UniqueIdentifier> added = Maps.newHashMap(); if (!identifiers.isEmpty()) { added = timeSeriesLoader.loadTimeSeries(identifiers, dataProvider, dataField, startDate, endDate); } URI result = null; if (!identifiers.isEmpty()) { if (identifiers.size() == 1) { Identifier requestIdentifier = identifiers.iterator().next(); UniqueIdentifier uid = added.get(requestIdentifier); if (uid != null) { result = data().getUriInfo().getAbsolutePathBuilder().path(uid.toString()).build(); } else { s_logger.warn("No timeseries added for {} ", requestIdentifier); result = uri(data()); } } else { result = uri(data(), identifiers); } } return result; } private Set<Identifier> buildSecurityRequest(final IdentificationScheme identificationScheme, final String idValue) { if (idValue == null) { return Collections.emptySet(); } final String[] identifiers = StringUtils.split(idValue, "\n"); final Set<Identifier> result = new HashSet<Identifier>(identifiers.length); for (String identifier : identifiers) { identifier = StringUtils.trimToNull(identifier); if (identifier != null) { result.add(Identifier.of(identificationScheme, identifier)); } } return result; } @Path("{timeseriesId}") public WebOneTimeSeriesResource findPortfolio(@PathParam("timeseriesId") String idStr) { data().setUriTimeSeriesId(idStr); TimeSeriesDocument<?> portfolio = data().getTimeSeriesMaster().getTimeSeries(UniqueIdentifier.parse(idStr)); data().setTimeSeries(portfolio); return new WebOneTimeSeriesResource(this); } /** * Creates the output root data. * @return the output root data, not null */ @SuppressWarnings("rawtypes") protected FlexiBean createRootData() { FlexiBean out = super.createRootData(); TimeSeriesSearchRequest<?> searchRequest = new TimeSeriesSearchRequest(); out.put("searchRequest", searchRequest); return out; } /** * Builds a URI for time series. * @param data the data, not null * @return the URI, not null */ public static URI uri(WebTimeSeriesData data) { return data.getUriInfo().getBaseUriBuilder().path(WebAllTimeSeriesResource.class).build(); } /** * Builds a URI for collection of timeseries. * @param data the data, not null * @param identifiers the identifiers to search for, may be null * @return the URI, not null */ public static URI uri(WebTimeSeriesData data, Collection<Identifier> identifiers) { UriBuilder builder = data.getUriInfo().getBaseUriBuilder().path(WebAllTimeSeriesResource.class); if (identifiers != null) { Iterator<Identifier> it = identifiers.iterator(); for (int i = 0; it.hasNext(); i++) { Identifier id = it.next(); builder.queryParam("idscheme." + i, id.getScheme().getName()); builder.queryParam("idvalue." + i, id.getValue()); } } return builder.build(); } }
package org.myrobotlab.service; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Reader; import java.io.Serializable; import java.io.StringReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.ServerSocket; //import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.atmosphere.wasync.Client; import org.atmosphere.wasync.ClientFactory; import org.atmosphere.wasync.Decoder; import org.atmosphere.wasync.Encoder; import org.atmosphere.wasync.Event; import org.atmosphere.wasync.Function; import org.atmosphere.wasync.Request; import org.atmosphere.wasync.RequestBuilder; import org.myrobotlab.framework.Message; import org.myrobotlab.framework.Platform; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceEnvironment; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.net.Connection; import org.myrobotlab.net.TCPThread2; import org.myrobotlab.service.interfaces.CommunicationInterface; import org.myrobotlab.service.interfaces.Gateway; import org.myrobotlab.service.interfaces.ServiceInterface; import org.slf4j.Logger; /** * * RemoteAdapter - Multi-node / distributed myrobotlab support. * * A RemoteAdapter allows other instances of MyRobotLab to connect. Services and * resources can be shared by 2 or more joined instances. The default * communication listener is a UDP server listening on all addresses on port * 6767. * * */ public class RemoteAdapter extends Service implements Gateway { // TODO - global address book of discovered connection public static class CommOptions implements Serializable { private static final long serialVersionUID = 1L; Platform platform; ArrayList<Gateway> gateways; public CommOptions() { } } static public class Scanner extends Thread { boolean isScanning = false; Service myService; public Scanner(Service service) { super(String.format("%s.scanner", service.getName())); this.myService = service; } @Override public void run() { // Find the server using UDP broadcast isScanning = true; while (isScanning && myService.isRunning()) { try { // Open a random port to send the package DatagramSocket dsocket = new DatagramSocket(); dsocket.setBroadcast(true); // byte[] sendData = // "DISCOVER_FUIFSERVER_REQUEST".getBytes(); Message msg = myService.createMessage("", "getConnections", null); byte[] msgBuf = org.myrobotlab.codec.CodecUtils.getBytes(msg); DatagramPacket sendPacket; // Try the 255.255.255.255 first /* * try { sendPacket = new DatagramPacket(msgBuf, msgBuf.length, * InetAddress.getByName("255.255.255.255"), 6767); * dsocket.send(sendPacket); myService.info( * ">>> Request packet sent to: 255.255.255.255 (DEFAULT)"); } catch * (Exception e) { Logging.logException(e); } */ // NEEDED ?? WE ALREADY DID BROADCAST // Broadcast the // message over all the network interfaces Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface ni = interfaces.nextElement(); // myService.info("examining interface %s %s", // ni.getName(), ni.getInetAddresses().toString()); log.info(String.format("examining interface %s %s", ni.getName(), ni.getDisplayName())); // if (ni.isLoopback() || !ni.isUp()) { if (!ni.isUp()) { log.info(String.format("skipping %s", ni.getDisplayName())); continue; // Don't want tobroadcast to the loopback // // interface } for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) { InetAddress broadcast = interfaceAddress.getBroadcast(); // short x = interfaceAddress.getNetworkPrefixLength(); log.info("" + interfaceAddress.getAddress()); if (ni.getName().equals("net4")) { log.info("net4"); } if (broadcast == null) { continue; } // Send the broadcast package! try { log.info(String.format("sending to %s %s %s", ni.getName(), broadcast.getHostAddress(), ni.getDisplayName())); if (interfaceAddress.getNetworkPrefixLength() == -1) { log.warn("jdk bug for interface %s network prefix length == -1", interfaceAddress.getAddress().getHostAddress()); String pre = interfaceAddress.getAddress().getHostAddress(); String b = pre.substring(0, pre.lastIndexOf(".")) + ".255"; log.warn("creating new broadcast address of %s", broadcast); broadcast = InetAddress.getByName(b); } sendPacket = new DatagramPacket(msgBuf, msgBuf.length, broadcast, 6767); // sendPacket = new DatagramPacket(msgBuf, // msgBuf.length, // InetAddress.getByName("192.168.0.255"), // 6767); dsocket.send(sendPacket); myService.info(">>> Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + ni.getDisplayName()); } catch (Exception e) { myService.error(e); } } } myService.info(">>> Done looping over all network interfaces. Now waiting for a reply!"); // multiple replies boolean listening = true; // wait and read replies - put them on the message queue // time out and will be done try { while (listening) { // Wait for a response byte[] recvBuf = new byte[15000]; DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); // how long we will wait for replies dsocket.setSoTimeout(2000); dsocket.receive(receivePacket); // We have a response myService.info(String.format("response from : %s", receivePacket.getAddress().getHostAddress())); // Check if the message is correct - JSON ? ObjectInputStream inBytes = new ObjectInputStream(new ByteArrayInputStream(receivePacket.getData())); Message retMsg = (Message) inBytes.readObject(); myService.info("response from instance %s", retMsg); if (!retMsg.method.equals("publishNewConnection")) { myService.error("not an publishNewConnection message"); continue; } else { List<Connection> conns = (List<Connection>) retMsg.data[0]; for (int i = 0; i < conns.size(); ++i) { myService.invoke("publishNewConnection", conns.get(i)); } } /* * String message = new String(receivePacket.getData()).trim(); if * (message.equals("DISCOVER_FUIFSERVER_RESPONSE")) { // DO * SOMETHING WITH THE SERVER'S IP (for example, store it in // * your controller) // Controller_Base * .setServerIp(receivePacket.getAddress()); log.info( * String.format( "+++++++++++++FOUND MRL INSTANCE++++++++++++ %s" * , receivePacket.getAddress())); } */ } } catch (SocketTimeoutException se) { myService.info("done listening for replies"); } finally { dsocket.close(); } } catch (Exception e) { myService.error(e); } } // while (isScanning) } } class TCPListener extends Thread { int rxCount = 0; int txCount = 0; RemoteAdapter myService = null; transient ServerSocket serverSocket = null; ObjectOutputStream out; ObjectInputStream in; int remotePort; public TCPListener(int remotePort, RemoteAdapter s) { super(String.format("%s.tcp.%d", s.getName(), remotePort)); this.remotePort = remotePort; myService = s; } public void addTCPClient(java.net.Socket clientSocket, RemoteAdapter myService) { try { String clientKey = String.format("tcp://%s:%d", clientSocket.getInetAddress().getHostAddress(), clientSocket.getPort()); URI uri = new URI(clientKey); // HELP PROTOKEY VS MRL KEY ?? TCPThread2 tcp = new TCPThread2(myService, uri, clientSocket); tcpClientList.put(uri, tcp); connections.put(uri, tcp.data); } catch (Exception e) { Logging.logError(e); } } @Override public void run() { try { serverSocket = new ServerSocket(remotePort, 10); log.info(getName() + " TCPListener listening on " + serverSocket.getLocalSocketAddress()); myService.info(String.format("listening on %s tcp", serverSocket.getLocalSocketAddress())); while (isRunning()) { // FIXME - on contact register the "environment" regardless // if a service registers !!! java.net.Socket clientSocket = serverSocket.accept(); // inbound connection FIXME - all keys constructed in // Encoder addTCPClient(clientSocket, myService); broadcastState(); } serverSocket.close(); } catch (Exception e) { logException(e); } } public void shutdown() { if ((serverSocket != null) && (!serverSocket.isClosed())) { try { serverSocket.close(); } catch (IOException e) { logException(e); } } serverSocket = null; } } class UDPListener extends Thread { DatagramSocket socket = null; RemoteAdapter myService = null; int listeningPort; boolean isRunning = false; public UDPListener(Integer listeningPort, RemoteAdapter s) { super(String.format("%s.udp.%d", s.getName(), listeningPort)); this.listeningPort = listeningPort; myService = s; } // FIXME FIXME FIXME - large amount of changes to tcp - application // logic which handles the "Messaging" should be common to both // tcp & udp & xmpp @Override public void run() { isRunning = true; try { socket = new DatagramSocket(listeningPort); log.info(String.format("%s listening on udp %s:%d", getName(), socket.getLocalAddress(), socket.getLocalPort())); byte[] b = new byte[65507]; // max udp size 65507 + 8 byte // header = 65535 ByteArrayInputStream b_in = new ByteArrayInputStream(b); DatagramPacket dgram = new DatagramPacket(b, b.length); while (isRunning) { socket.receive(dgram); // receives all datagrams // FIXME - do we need o re-create??? ObjectInputStream o_in = new ObjectInputStream(b_in); try { Message msg = (Message) o_in.readObject(); dgram.setLength(b.length); // must reset length field! b_in.reset(); // FIXME - sloppy use full method signature // FIXME Encoder.makeMethodKey(Msg msg) if ("getConnections".equals(msg.method)) { // get connections List<Connection> conn = getConnections(new URI(String.format("tcp:/%s:%d", dgram.getAddress(), dgram.getPort()))); // send them back for (int i = 0; i < conn.size(); ++i) { Message newConnMsg = createMessage("", "publishNewConnection", conn); byte[] msgBuf = org.myrobotlab.codec.CodecUtils.getBytes(newConnMsg); DatagramPacket dgp = new DatagramPacket(msgBuf, msgBuf.length, dgram.getAddress(), dgram.getPort()); socket.send(dgp); } // we will have to search for them again } else if ("publishNewConnection".equals(msg.method)) { myService.invoke("onCommOptions", msg.data[0]); } else if ("register".equals(msg.method)) { // FIXME name should be "Runtime" representing the // static // IMPORTANT - (should be in Encoder) - create the // key // for foreign service environment // Runtime.addServiceEnvironment(name, protocolKey) URI protocolKey = new URI(String.format("udp://%s:%d", socket.getInetAddress().getHostAddress(), socket.getPort())); String mrl = String.format("mrl://%s/%s", myService.getName(), protocolKey.toString()); URI mrlURI = new URI(mrl); // IMPORTANT - this is an optimization and probably // should be in the Comm interface defintion CommunicationInterface cm = myService.getComm(); cm.addRemote(mrlURI, protocolKey); // check if the URI is already defined - if not - we // will // send back the services which we want to export - // Security will filter appropriately ServiceEnvironment foreignProcess = Runtime.getEnvironment(mrlURI); ServiceInterface si = (ServiceInterface) msg.data[0]; // HMMM a vote for String vs URI here - since we // need to // catch syntax !!! si.setInstanceId(mrlURI); // if security ... msg within msg // getOutbox().add(createMessage(Runtime.getInstance().getName(), // "register", inboundMsg)); Runtime.register(si, mrlURI);// <-- not an INVOKE // no security ! :P if (foreignProcess == null) { // not defined we will send export // TODO - Security filters - default export // (include // exclude) - mapset of name ServiceEnvironment localProcess = Runtime.getLocalServicesForExport(); Iterator<String> it = localProcess.serviceDirectory.keySet().iterator(); String name; ServiceInterface toRegister; while (it.hasNext()) { name = it.next(); toRegister = localProcess.serviceDirectory.get(name); // the following will wrap a message within // a message and send it remotely // This Thread CANNOT Write on The // ObjectOutputStream directly - // IT SHOULD NEVER DO ANY METHOD WHICH CAN // BLOCK !!!! - 3 days of bug chasing when // it wrote to ObjectOutputStream and oos // blocked when the buffer was full - // causing deadlock // putting it on the inbox will move it to a // different thread Message sendService = myService.createMessage("", "register", toRegister); Message outbound = myService.createMessage(myService.getName(), "sendRemote", new Object[] { protocolKey, sendService }); myService.getInbox().add(outbound); } } } else { // ++udpRx; myService.getOutbox().add(msg); } } catch (Exception e) { error(e); } dgram.setLength(b.length); // must reset length field! b_in.reset(); // reset so next read is from start of byte[] // again } // while isRunning } catch (SocketException se) { error("UDPListener could not listen %s", se.getMessage()); Logging.logError(se); } catch (Exception e) { error("wtf error"); logException(e); } } public void shutdown() { isRunning = false; if ((socket != null) && (!socket.isClosed())) { socket.close(); } } } private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(RemoteAdapter.class); public String lastProtocolKey; private String defaultPrefix = null; private HashMap<String, String> prefixMap = new HashMap<String, String>(); // private HashSet<URI> localProtocolKeys = new HashSet<URI>(); // types of listening threads - multiple could be managed // when correct interfaces and base classes are done transient TCPListener tcpListener = null; transient UDPListener udpListener = null; private Integer udpPort; private Integer tcpPort; boolean isListening = false; boolean isScanning = false; // TODO - multiple scanners for parallel port/broadcast scanning transient Scanner scanner; transient private HashMap<URI, TCPThread2> tcpClientList = new HashMap<URI, TCPThread2>(); /** * used as a data interface to all the non-serializable network objects - it * will report stats and states */ private HashMap<URI, Connection> connections = new HashMap<URI, Connection>(); boolean listenOnStartup = false; static public ArrayList<InetAddress> getLocalAddresses() { ArrayList<InetAddress> ret = new ArrayList<InetAddress>(); try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); ret.add(inetAddress); } } } catch (Exception e) { logException(e); } return ret; } public RemoteAdapter(String n) { super(n); defaultPrefix = String.format("%s.", n); // addLocalTask(5 * 1000, "broadcastHeartbeat"); } @Override public void addConnectionListener(String name) { addListener("publishNewConnection", name, "onNewConnection"); } // FIXME - add to Gateway interfaceS public HashMap<URI, Connection> broadcastHeartbeat() { for (Map.Entry<URI, Connection> entry : connections.entrySet()) { URI uri = entry.getKey(); // Connection value = entry.getValue(); // roll through send a set of transactions off & start a // IOCompletion like // array of status ... // if timeout is reached - write the rest with timeout (those that // did not // get an asynch response if (uri.getScheme().equals("tcp")) { TCPThread2 tcp = tcpClientList.get(uri); log.info("" + tcp); // check socket connectivity // attempt to re-connect if disconnected broadcastState(); } } return connections; } @Override // TODO refactor with boolean - lower level error(problem) to put into // framework public void connect(String uri) throws URISyntaxException { Message msg = createMessage("", "register", null); sendRemote(uri, msg); } @Override public HashMap<URI, Connection> getClients() { return connections; } /** * important initial communication function related to discovery a broadcast * goes out and replies must include details of communication so that a viable * connection can be created * * @param client */ // global access keys (all gateways) - or just this gateway ??? // if it's all then this could be a function of runtime which is probably // the best @Override public List<Connection> getConnections(URI clientKey) { ArrayList<Connection> conns = new ArrayList<Connection>(); try { // FIXME - dorky - probably fix with template method // FIXME - do "global" next ArrayList<ServiceInterface> services = Runtime.getServicesFromInterface(Gateway.class); // ArrayList<Gateway> gateways = new ArrayList<Gateway>(); // if GLOBAL for (int i = 0; i < services.size(); ++i) { // Gateway // gateways.add((Gateway) services.get(i)); } // else LOCAL // add (this) services connections List<String> addr = Runtime.getLocalAddresses(); for (int i = 0; i < addr.size(); ++i) { Connection tcpConn = new Connection(); // theoretically you could advertise udp too (and others) // tcpConn.protocolKey = new // URI(String.format("mrl://%s/tcp://%s:%d", getName(), // addr.get(i), getTcpPort())); tcpConn.protocolKey = new URI(String.format("tcp://%s:%d", addr.get(i), getTcpPort())); // we dont fill in our own name // FIXME FIXME FIXME - DO THE CORRECT WAY !!! // / tcpConn.protocolKey = new URI(String.format("tcp://%s:%d", // addr.get(i), getTcpPort())); // tcpKey.prefix = suggestion // tcpKey.prefix = prefix; tcpConn.platform = Runtime.getInstance().getPlatform(); tcpConn.prefix = Runtime.getInstance().getName();// calls // getPrefix // under // hood conns.add(tcpConn); } // tcpKey.uri = } catch (Exception e) { Logging.logError(e); } return conns; } // @Override needs to be overriden - Gateway need implementation public Platform getPlatform() { return Runtime.getInstance().getPlatform(); } @Override public String getPrefix(URI protocolKey) { if (defaultPrefix != null) { return defaultPrefix; } else { return "";// important - return "" not null } } public Integer getTcpPort() { return tcpPort; } public Integer getUdpPort() { return udpPort; } public boolean isListening() { return isListening; } @Override public boolean isReady() { if (tcpListener.serverSocket != null) { return tcpListener.serverSocket.isBound(); } return false; } public boolean isScanning() { return isScanning; } public Connection onHeartbeat(Connection data) { return data; } /** * NOT USED - just left as an example of a consumer asynchronous return of * access key request * * @param keys * @return */ public Connection onNewConnection(Connection conn) { return conn; } // publishing point @Override public Connection publishNewConnection(Connection conn) { if (!connections.containsKey(conn.protocolKey)) { // uri will now become my uri connections.put(conn.protocolKey, conn); broadcastState(); } else { info("%d scanning no new connections", System.currentTimeMillis()); } return conn; } public void scan() { if (scanner != null) { stopScanning(); } scanner = new Scanner(this); scanner.start(); isScanning = true; } @Override public void sendRemote(String uri, Message msg) throws URISyntaxException { sendRemote(new URI(uri), msg); } @Override synchronized public void sendRemote(URI uri, Message msg) { String scheme = uri.getScheme(); lastProtocolKey = uri.toString(); if ("tcp".equals(scheme)) { sendRemoteTCP(uri, msg); } else if ("udp".equals(scheme)) { sendRemoteUDP(uri, msg); } else { error(String.format("%s not supported", uri.toString())); return; } } public void sendRemoteTCP(URI uri, Message msg) { TCPThread2 tcp = null; try { if (tcpClientList.containsKey(uri)) { tcp = tcpClientList.get(uri); } else { // constructor will throw if can not connect -> new Socket(host, // port) tcp = new TCPThread2(this, uri, null); tcpClientList.put(uri, tcp); connections.put(uri, tcp.data); broadcastState(); } tcp.send(msg); connections.get(uri).tx++; } catch (Exception e) { Logging.logError(e); } } public void sendRemoteUDP(URI uri, Message msg) { try { // FIXME - could use some optimization e.g. .reset() DatagramSocket s = new DatagramSocket(); ByteArrayOutputStream b_out = new ByteArrayOutputStream(); ObjectOutputStream o_out = new ObjectOutputStream(b_out); o_out.writeObject(msg); o_out.flush(); b_out.flush(); byte[] b = b_out.toByteArray(); InetAddress hostAddress = InetAddress.getByName(uri.getHost()); DatagramPacket dgram = new DatagramPacket(b, b.length, hostAddress, uri.getPort()); s.send(dgram); // dgram.se // TODO - send the damn packet??? // close the datagram to avoid resource leaks s.close(); } catch (Exception e) { Logging.logError(e); } } public String setDefaultPrefix(String prefix) { defaultPrefix = prefix; return prefix; } public void setPrefix(String source, String prefix) { prefixMap.put(source, prefix); } public void setTCPPort(Integer tcpPort) { this.tcpPort = tcpPort; } public void setUDPPort(Integer udpPort) { this.udpPort = udpPort; } public void startListening() { if (udpPort == null) { udpPort = 6767; } if (tcpPort == null) { tcpPort = 6767; } startListening(udpPort, tcpPort); isListening = true; broadcastState(); } public void startListening(int ports) { startListening(ports, ports); } public void startListening(int udpPort, int tcpPort) { startUDP(udpPort); startTCP(tcpPort); } public void startTCP(Integer port) { stopTCP(); if (port == null) { port = 6767; } tcpPort = port; tcpListener = new TCPListener(tcpPort, this); tcpListener.start(); } public void startUDP(Integer port) { stopUDP(); if (port == null) { port = 6767; } udpPort = port; udpListener = new UDPListener(udpPort, this); udpListener.start(); } public void stopListening() { stopUDP(); stopTCP(); isListening = false; broadcastState(); } public void stopScanning() { scanner.isScanning = false; isScanning = false; scanner = null; } @Override public void stopService() { stopListening(); super.stopService(); } public void stopTCP() { if (tcpListener != null) { tcpListener.interrupt(); tcpListener.shutdown(); tcpListener = null; } } public void stopUDP() { if (udpListener != null) { udpListener.interrupt(); udpListener.shutdown(); udpListener = null; } } public void startService() { super.startService(); if (listenOnStartup) { startListening(); } } public void listenOnStartup(boolean b) { listenOnStartup = b; } public void websocket(String url) throws IOException { Client client = ClientFactory.getDefault().newClient(); RequestBuilder request = client.newRequestBuilder().method(Request.METHOD.GET).uri(url).encoder(new Encoder<String, Reader>() { // Stream // the // request // body @Override public Reader encode(String s) { return new StringReader(s); } }).decoder(new Decoder<String, Reader>() { @Override public Reader decode(Event type, String s) { return new StringReader(s); } }).transport(Request.TRANSPORT.WEBSOCKET) // Try WebSocket .transport(Request.TRANSPORT.LONG_POLLING); // Fallback to Long-Polling org.atmosphere.wasync.Socket socket = client.create(); socket.on(new Function<Reader>() { @Override public void on(Reader r) { // Read the response } }).on(new Function<IOException>() { @Override public void on(IOException arg0) { // TODO Auto-generated method stub } }).open(request.build()).fire("/api/").fire("bong"); } /** * 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(RemoteAdapter.class.getCanonicalName()); meta.addDescription("allows remote communication between applets, or remote instances of myrobotlab"); meta.addCategory("connectivity", "network", "framework"); meta.addDependency("org.atmosphere.nettosphere", "2.3.0"); meta.addDependency("org.apache.commons.httpclient", "4.5.2"); return meta; } public static void main(String[] args) { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.DEBUG); try { // int i = 0; // RemoteAdapter remote0 = (RemoteAdapter) // Runtime.start(String.format("remote%d", 0), "RemoteAdapter"); // Runtime.start("mac", "Runtime"); // Runtime.start("gui", "GUIService"); // Runtime.start("webgui", "WebGui"); Runtime.start("python", "Python"); // Runtime.start("mac.clock", "Clock"); // Arduino arduino = (Arduino)Runtime.start("arduino", "Arduino"); // Servo servo = (Servo) Runtime.start("servo", "Servo"); // Arduino Arduino = (Arduino) Runtime.start("arduino", "Arduino"); // Max frame length of 10240 has been exceeded. FIXME !!!! RemoteAdapter remote = (RemoteAdapter) Runtime.start("remote", "RemoteAdapter"); // remote.connect("tcp://demo.myrobotlab.org:6767"); Runtime.start("gui", "GUIService"); remote.startListening(); // remote1.startListening(); // remote1.setTCPPort(6868); // remote1.setUDPPort(6868); // remote1.startListening(); // Runtime.start(String.format("gui%d", i), "GUIService"); // Runtime.start("python", "Python"); // arduino.connect("COM9"); // remote1.startListening(6666, 6666); // remote1.startListening(); // remote0.startUDP(6767); // remote1.startListening(); // remote1.startUDP(6767); // remote1.scan(); /* * Runtime.main(new String[] { "-runtimeName", String.format("r%d", i) }); * RemoteAdapter remote = (RemoteAdapter) * Runtime.start(String.format("remote%d", i), "RemoteAdapter"); * Runtime.start(String.format("clock%d", i), "Clock"); * Runtime.start(String.format("gui%d", i), "GUIService"); * * // Security security = // * (Security)Runtime.start(String.format("security", i), // "Security"); * remote.startListening(); // security.allowExportByName("laptop", true); * // security.allowExportByName("laptop.gui", false); // * remote.connect("tcp://192.168.0.92:6767"); // * Runtime.start(String.format("joystick%d", i), "Joystick"); // * Runtime.start(String.format("python%d", i), "Python"); */ // what if null service is passed "register()" no parameters - // I'm sending a registration of nothing? // remote.broadcastState(); // remote.connect("tcp://127.0.0.1:6767"); /* * THIS WORKS Message msg = remote.createMessage("", "register", remote); * remote.sendRemote("tcp://127.0.0.1:6868", msg); */ // FIXME - sholdn't this be sendRemote ??? or at least // in an interface // remote.sendRemote(uri, msg); // xmpp1.sendMessage("xmpp 2", "robot02 02"); } catch (Exception e) { Logging.logError(e); } } }
package org.myrobotlab.service; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Reader; import java.io.Serializable; import java.io.StringReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.ServerSocket; //import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.atmosphere.wasync.Client; import org.atmosphere.wasync.ClientFactory; import org.atmosphere.wasync.Decoder; import org.atmosphere.wasync.Encoder; import org.atmosphere.wasync.Event; import org.atmosphere.wasync.Function; import org.atmosphere.wasync.Request; import org.atmosphere.wasync.RequestBuilder; import org.myrobotlab.framework.Message; import org.myrobotlab.framework.Platform; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.ServiceEnvironment; import org.myrobotlab.framework.ServiceType; import org.myrobotlab.logging.Level; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.net.Connection; import org.myrobotlab.net.TCPThread2; import org.myrobotlab.service.interfaces.CommunicationInterface; import org.myrobotlab.service.interfaces.Gateway; import org.myrobotlab.service.interfaces.ServiceInterface; import org.slf4j.Logger; /** * * RemoteAdapter - Multi-node / distributed myrobotlab support. * * A RemoteAdapter allows other instances of MyRobotLab to connect. Services and * resources can be shared by 2 or more joined instances. The default * communication listener is a UDP server listening on all addresses on port * 6767. * * */ public class RemoteAdapter extends Service implements Gateway { // TODO - global address book of discovered connection public static class CommOptions implements Serializable { private static final long serialVersionUID = 1L; Platform platform; ArrayList<Gateway> gateways; public CommOptions() { } } static public class Scanner extends Thread { boolean isScanning = false; Service myService; public Scanner(Service service) { super(String.format("%s.scanner", service.getName())); this.myService = service; } @Override public void run() { // Find the server using UDP broadcast isScanning = true; while (isScanning && myService.isRunning()) { try { // Open a random port to send the package DatagramSocket dsocket = new DatagramSocket(); dsocket.setBroadcast(true); // byte[] sendData = // "DISCOVER_FUIFSERVER_REQUEST".getBytes(); Message msg = myService.createMessage("", "getConnections", null); byte[] msgBuf = org.myrobotlab.codec.CodecUtils.getBytes(msg); DatagramPacket sendPacket; // Try the 255.255.255.255 first /* * try { sendPacket = new DatagramPacket(msgBuf, msgBuf.length, * InetAddress.getByName("255.255.255.255"), 6767); * dsocket.send(sendPacket); myService.info( * ">>> Request packet sent to: 255.255.255.255 (DEFAULT)"); } catch * (Exception e) { Logging.logException(e); } */ // NEEDED ?? WE ALREADY DID BROADCAST // Broadcast the // message over all the network interfaces Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface ni = interfaces.nextElement(); // myService.info("examining interface %s %s", // ni.getName(), ni.getInetAddresses().toString()); log.info(String.format("examining interface %s %s", ni.getName(), ni.getDisplayName())); // if (ni.isLoopback() || !ni.isUp()) { if (!ni.isUp()) { log.info(String.format("skipping %s", ni.getDisplayName())); continue; // Don't want tobroadcast to the loopback // // interface } for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) { InetAddress broadcast = interfaceAddress.getBroadcast(); // short x = interfaceAddress.getNetworkPrefixLength(); log.info("" + interfaceAddress.getAddress()); if (ni.getName().equals("net4")) { log.info("net4"); } if (broadcast == null) { continue; } // Send the broadcast package! try { log.info(String.format("sending to %s %s %s", ni.getName(), broadcast.getHostAddress(), ni.getDisplayName())); if (interfaceAddress.getNetworkPrefixLength() == -1) { log.warn("jdk bug for interface %s network prefix length == -1", interfaceAddress.getAddress().getHostAddress()); String pre = interfaceAddress.getAddress().getHostAddress(); String b = pre.substring(0, pre.lastIndexOf(".")) + ".255"; log.warn("creating new broadcast address of %s", broadcast); broadcast = InetAddress.getByName(b); } sendPacket = new DatagramPacket(msgBuf, msgBuf.length, broadcast, 6767); // sendPacket = new DatagramPacket(msgBuf, // msgBuf.length, // InetAddress.getByName("192.168.0.255"), // 6767); dsocket.send(sendPacket); myService.info(">>> Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + ni.getDisplayName()); } catch (Exception e) { myService.error(e); } } } myService.info(">>> Done looping over all network interfaces. Now waiting for a reply!"); // multiple replies boolean listening = true; // wait and read replies - put them on the message queue // time out and will be done try { while (listening) { // Wait for a response byte[] recvBuf = new byte[15000]; DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); // how long we will wait for replies dsocket.setSoTimeout(2000); dsocket.receive(receivePacket); // We have a response myService.info(String.format("response from : %s", receivePacket.getAddress().getHostAddress())); // Check if the message is correct - JSON ? ObjectInputStream inBytes = new ObjectInputStream(new ByteArrayInputStream(receivePacket.getData())); Message retMsg = (Message) inBytes.readObject(); myService.info("response from instance %s", retMsg); if (!retMsg.method.equals("publishNewConnection")) { myService.error("not an publishNewConnection message"); continue; } else { List<Connection> conns = (List<Connection>) retMsg.data[0]; for (int i = 0; i < conns.size(); ++i) { myService.invoke("publishNewConnection", conns.get(i)); } } /* * String message = new String(receivePacket.getData()).trim(); if * (message.equals("DISCOVER_FUIFSERVER_RESPONSE")) { // DO * SOMETHING WITH THE SERVER'S IP (for example, store it in // * your controller) // Controller_Base * .setServerIp(receivePacket.getAddress()); log.info( * String.format( "+++++++++++++FOUND MRL INSTANCE++++++++++++ %s" * , receivePacket.getAddress())); } */ } } catch (SocketTimeoutException se) { myService.info("done listening for replies"); } finally { dsocket.close(); } } catch (Exception e) { myService.error(e); } } // while (isScanning) } } class TCPListener extends Thread { int rxCount = 0; int txCount = 0; RemoteAdapter myService = null; transient ServerSocket serverSocket = null; ObjectOutputStream out; ObjectInputStream in; int remotePort; public TCPListener(int remotePort, RemoteAdapter s) { super(String.format("%s.tcp.%d", s.getName(), remotePort)); this.remotePort = remotePort; myService = s; } public void addTCPClient(java.net.Socket clientSocket, RemoteAdapter myService) { try { String clientKey = String.format("tcp://%s:%d", clientSocket.getInetAddress().getHostAddress(), clientSocket.getPort()); URI uri = new URI(clientKey); // HELP PROTOKEY VS MRL KEY ?? TCPThread2 tcp = new TCPThread2(myService, uri, clientSocket); tcpClientList.put(uri, tcp); connections.put(uri, tcp.data); } catch (Exception e) { Logging.logError(e); } } @Override public void run() { try { serverSocket = new ServerSocket(remotePort, 10); log.info(getName() + " TCPListener listening on " + serverSocket.getLocalSocketAddress()); myService.info(String.format("listening on %s tcp", serverSocket.getLocalSocketAddress())); while (isRunning()) { // FIXME - on contact register the "environment" regardless // if a service registers !!! java.net.Socket clientSocket = serverSocket.accept(); // inbound connection FIXME - all keys constructed in // Encoder addTCPClient(clientSocket, myService); broadcastState(); } serverSocket.close(); } catch (Exception e) { logException(e); } } public void shutdown() { if ((serverSocket != null) && (!serverSocket.isClosed())) { try { serverSocket.close(); } catch (IOException e) { logException(e); } } serverSocket = null; } } class UDPListener extends Thread { DatagramSocket socket = null; RemoteAdapter myService = null; int listeningPort; boolean isRunning = false; public UDPListener(Integer listeningPort, RemoteAdapter s) { super(String.format("%s.udp.%d", s.getName(), listeningPort)); this.listeningPort = listeningPort; myService = s; } // FIXME FIXME FIXME - large amount of changes to tcp - application // logic which handles the "Messaging" should be common to both // tcp & udp & xmpp @Override public void run() { isRunning = true; try { socket = new DatagramSocket(listeningPort); log.info(String.format("%s listening on udp %s:%d", getName(), socket.getLocalAddress(), socket.getLocalPort())); byte[] b = new byte[65507]; // max udp size 65507 + 8 byte // header = 65535 ByteArrayInputStream b_in = new ByteArrayInputStream(b); DatagramPacket dgram = new DatagramPacket(b, b.length); while (isRunning) { socket.receive(dgram); // receives all datagrams // FIXME - do we need o re-create??? ObjectInputStream o_in = new ObjectInputStream(b_in); try { Message msg = (Message) o_in.readObject(); dgram.setLength(b.length); // must reset length field! b_in.reset(); // FIXME - sloppy use full method signature // FIXME Encoder.makeMethodKey(Msg msg) if ("getConnections".equals(msg.method)) { // get connections List<Connection> conn = getConnections(new URI(String.format("tcp:/%s:%d", dgram.getAddress(), dgram.getPort()))); // send them back for (int i = 0; i < conn.size(); ++i) { Message newConnMsg = createMessage("", "publishNewConnection", conn); byte[] msgBuf = org.myrobotlab.codec.CodecUtils.getBytes(newConnMsg); DatagramPacket dgp = new DatagramPacket(msgBuf, msgBuf.length, dgram.getAddress(), dgram.getPort()); socket.send(dgp); } // we will have to search for them again } else if ("publishNewConnection".equals(msg.method)) { myService.invoke("onCommOptions", msg.data[0]); } else if ("register".equals(msg.method)) { // FIXME name should be "Runtime" representing the // static // IMPORTANT - (should be in Encoder) - create the // key // for foreign service environment // Runtime.addServiceEnvironment(name, protocolKey) URI protocolKey = new URI(String.format("udp://%s:%d", socket.getInetAddress().getHostAddress(), socket.getPort())); String mrl = String.format("mrl://%s/%s", myService.getName(), protocolKey.toString()); URI mrlURI = new URI(mrl); // IMPORTANT - this is an optimization and probably // should be in the Comm interface defintion CommunicationInterface cm = myService.getComm(); cm.addRemote(mrlURI, protocolKey); // check if the URI is already defined - if not - we // will // send back the services which we want to export - // Security will filter appropriately ServiceEnvironment foreignProcess = Runtime.getEnvironment(mrlURI); ServiceInterface si = (ServiceInterface) msg.data[0]; // HMMM a vote for String vs URI here - since we // need to // catch syntax !!! si.setInstanceId(mrlURI); // if security ... msg within msg // getOutbox().add(createMessage(Runtime.getInstance().getName(), // "register", inboundMsg)); Runtime.register(si, mrlURI);// <-- not an INVOKE // no security ! :P if (foreignProcess == null) { // not defined we will send export // TODO - Security filters - default export // (include // exclude) - mapset of name ServiceEnvironment localProcess = Runtime.getLocalServicesForExport(); Iterator<String> it = localProcess.serviceDirectory.keySet().iterator(); String name; ServiceInterface toRegister; while (it.hasNext()) { name = it.next(); toRegister = localProcess.serviceDirectory.get(name); // the following will wrap a message within // a message and send it remotely // This Thread CANNOT Write on The // ObjectOutputStream directly - // IT SHOULD NEVER DO ANY METHOD WHICH CAN // BLOCK !!!! - 3 days of bug chasing when // it wrote to ObjectOutputStream and oos // blocked when the buffer was full - // causing deadlock // putting it on the inbox will move it to a // different thread Message sendService = myService.createMessage("", "register", toRegister); Message outbound = myService.createMessage(myService.getName(), "sendRemote", new Object[] { protocolKey, sendService }); myService.getInbox().add(outbound); } } } else { // ++udpRx; myService.getOutbox().add(msg); } } catch (Exception e) { error(e); } dgram.setLength(b.length); // must reset length field! b_in.reset(); // reset so next read is from start of byte[] // again } // while isRunning } catch (SocketException se) { error("UDPListener could not listen %s", se.getMessage()); Logging.logError(se); } catch (Exception e) { error("wtf error"); logException(e); } } public void shutdown() { isRunning = false; if ((socket != null) && (!socket.isClosed())) { socket.close(); } } } private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(RemoteAdapter.class); public String lastProtocolKey; private String defaultPrefix = null; private HashMap<String, String> prefixMap = new HashMap<String, String>(); // private HashSet<URI> localProtocolKeys = new HashSet<URI>(); // types of listening threads - multiple could be managed // when correct interfaces and base classes are done transient TCPListener tcpListener = null; transient UDPListener udpListener = null; private Integer udpPort; private Integer tcpPort; boolean isListening = false; boolean isScanning = false; // TODO - multiple scanners for parallel port/broadcast scanning transient Scanner scanner; transient private HashMap<URI, TCPThread2> tcpClientList = new HashMap<URI, TCPThread2>(); /** * used as a data interface to all the non-serializable network objects - it * will report stats and states */ private HashMap<URI, Connection> connections = new HashMap<URI, Connection>(); boolean listenOnStartup = false; static public ArrayList<InetAddress> getLocalAddresses() { ArrayList<InetAddress> ret = new ArrayList<InetAddress>(); try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); ret.add(inetAddress); } } } catch (Exception e) { logException(e); } return ret; } public RemoteAdapter(String n) { super(n); defaultPrefix = String.format("%s.", n); // addLocalTask(5 * 1000, "broadcastHeartbeat"); } @Override public void addConnectionListener(String name) { addListener("publishNewConnection", name, "onNewConnection"); } // FIXME - add to Gateway interfaceS public HashMap<URI, Connection> broadcastHeartbeat() { for (Map.Entry<URI, Connection> entry : connections.entrySet()) { URI uri = entry.getKey(); // Connection value = entry.getValue(); // roll through send a set of transactions off & start a // IOCompletion like // array of status ... // if timeout is reached - write the rest with timeout (those that // did not // get an asynch response if (uri.getScheme().equals("tcp")) { TCPThread2 tcp = tcpClientList.get(uri); log.info("" + tcp); // check socket connectivity // attempt to re-connect if disconnected broadcastState(); } } return connections; } @Override // TODO refactor with boolean - lower level error(problem) to put into // framework public void connect(String uri) throws URISyntaxException { Message msg = createMessage("", "register", null); sendRemote(uri, msg); } @Override public HashMap<URI, Connection> getClients() { return connections; } /** * important initial communication function related to discovery a broadcast * goes out and replies must include details of communication so that a viable * connection can be created * * @param client */ // global access keys (all gateways) - or just this gateway ??? // if it's all then this could be a function of runtime which is probably // the best @Override public List<Connection> getConnections(URI clientKey) { ArrayList<Connection> conns = new ArrayList<Connection>(); try { // FIXME - dorky - probably fix with template method // FIXME - do "global" next ArrayList<ServiceInterface> services = Runtime.getServicesFromInterface(Gateway.class); // ArrayList<Gateway> gateways = new ArrayList<Gateway>(); // if GLOBAL for (int i = 0; i < services.size(); ++i) { // Gateway // gateways.add((Gateway) services.get(i)); } // else LOCAL // add (this) services connections List<String> addr = Runtime.getLocalAddresses(); for (int i = 0; i < addr.size(); ++i) { Connection tcpConn = new Connection(); // theoretically you could advertise udp too (and others) // tcpConn.protocolKey = new // URI(String.format("mrl://%s/tcp://%s:%d", getName(), // addr.get(i), getTcpPort())); tcpConn.protocolKey = new URI(String.format("tcp://%s:%d", addr.get(i), getTcpPort())); // we dont fill in our own name // FIXME FIXME FIXME - DO THE CORRECT WAY !!! // / tcpConn.protocolKey = new URI(String.format("tcp://%s:%d", // addr.get(i), getTcpPort())); // tcpKey.prefix = suggestion // tcpKey.prefix = prefix; tcpConn.platform = Runtime.getInstance().getPlatform(); tcpConn.prefix = Runtime.getInstance().getName();// calls // getPrefix // under // hood conns.add(tcpConn); } // tcpKey.uri = } catch (Exception e) { Logging.logError(e); } return conns; } // @Override needs to be overriden - Gateway need implementation public Platform getPlatform() { return Runtime.getInstance().getPlatform(); } @Override public String getPrefix(URI protocolKey) { if (defaultPrefix != null) { return defaultPrefix; } else { return "";// important - return "" not null } } public Integer getTcpPort() { return tcpPort; } public Integer getUdpPort() { return udpPort; } public boolean isListening() { return isListening; } @Override public boolean isReady() { if (tcpListener.serverSocket != null) { return tcpListener.serverSocket.isBound(); } return false; } public boolean isScanning() { return isScanning; } public Connection onHeartbeat(Connection data) { return data; } /** * NOT USED - just left as an example of a consumer asynchronous return of * access key request * * @param keys * @return */ public Connection onNewConnection(Connection conn) { return conn; } // publishing point @Override public Connection publishNewConnection(Connection conn) { if (!connections.containsKey(conn.protocolKey)) { // uri will now become my uri connections.put(conn.protocolKey, conn); broadcastState(); } else { info("%d scanning no new connections", System.currentTimeMillis()); } return conn; } public void scan() { if (scanner != null) { stopScanning(); } scanner = new Scanner(this); scanner.start(); isScanning = true; } @Override public void sendRemote(String uri, Message msg) throws URISyntaxException { sendRemote(new URI(uri), msg); } @Override synchronized public void sendRemote(URI uri, Message msg) { String scheme = uri.getScheme(); lastProtocolKey = uri.toString(); if ("tcp".equals(scheme)) { sendRemoteTCP(uri, msg); } else if ("udp".equals(scheme)) { sendRemoteUDP(uri, msg); } else { error(String.format("%s not supported", uri.toString())); return; } } public void sendRemoteTCP(URI uri, Message msg) { TCPThread2 tcp = null; try { if (tcpClientList.containsKey(uri)) { tcp = tcpClientList.get(uri); } else { // constructor will throw if can not connect -> new Socket(host, // port) tcp = new TCPThread2(this, uri, null); tcpClientList.put(uri, tcp); connections.put(uri, tcp.data); broadcastState(); } tcp.send(msg); connections.get(uri).tx++; } catch (Exception e) { Logging.logError(e); } } public void sendRemoteUDP(URI uri, Message msg) { try { // FIXME - could use some optimization e.g. .reset() DatagramSocket s = new DatagramSocket(); ByteArrayOutputStream b_out = new ByteArrayOutputStream(); ObjectOutputStream o_out = new ObjectOutputStream(b_out); o_out.writeObject(msg); o_out.flush(); b_out.flush(); byte[] b = b_out.toByteArray(); InetAddress hostAddress = InetAddress.getByName(uri.getHost()); DatagramPacket dgram = new DatagramPacket(b, b.length, hostAddress, uri.getPort()); s.send(dgram); // dgram.se // TODO - send the damn packet??? // close the datagram to avoid resource leaks s.close(); } catch (Exception e) { Logging.logError(e); } } public String setDefaultPrefix(String prefix) { defaultPrefix = prefix; return prefix; } public void setPrefix(String source, String prefix) { prefixMap.put(source, prefix); } public void setTCPPort(Integer tcpPort) { this.tcpPort = tcpPort; } public void setUDPPort(Integer udpPort) { this.udpPort = udpPort; } public void startListening() { if (udpPort == null) { udpPort = 6767; } if (tcpPort == null) { tcpPort = 6767; } startListening(udpPort, tcpPort); isListening = true; broadcastState(); } public void startListening(int ports) { startListening(ports, ports); } public void startListening(int udpPort, int tcpPort) { startUDP(udpPort); startTCP(tcpPort); } public void startTCP(Integer port) { stopTCP(); if (port == null) { port = 6767; } tcpPort = port; tcpListener = new TCPListener(tcpPort, this); tcpListener.start(); } public void startUDP(Integer port) { stopUDP(); if (port == null) { port = 6767; } udpPort = port; udpListener = new UDPListener(udpPort, this); udpListener.start(); } public void stopListening() { stopUDP(); stopTCP(); isListening = false; broadcastState(); } public void stopScanning() { scanner.isScanning = false; isScanning = false; scanner = null; } @Override public void stopService() { stopListening(); super.stopService(); } public void stopTCP() { if (tcpListener != null) { tcpListener.interrupt(); tcpListener.shutdown(); tcpListener = null; } } public void stopUDP() { if (udpListener != null) { udpListener.interrupt(); udpListener.shutdown(); udpListener = null; } } public void startService() { super.startService(); if (listenOnStartup) { startListening(); } } public void listenOnStartup(boolean b) { listenOnStartup = b; } public void websocket(String url) throws IOException { Client client = ClientFactory.getDefault().newClient(); RequestBuilder request = client.newRequestBuilder().method(Request.METHOD.GET).uri(url).encoder(new Encoder<String, Reader>() { // Stream // the // request // body @Override public Reader encode(String s) { return new StringReader(s); } }).decoder(new Decoder<String, Reader>() { @Override public Reader decode(Event type, String s) { return new StringReader(s); } }).transport(Request.TRANSPORT.WEBSOCKET) // Try WebSocket .transport(Request.TRANSPORT.LONG_POLLING); // Fallback to Long-Polling org.atmosphere.wasync.Socket socket = client.create(); socket.on(new Function<Reader>() { @Override public void on(Reader r) { // Read the response } }).on(new Function<IOException>() { @Override public void on(IOException arg0) { // TODO Auto-generated method stub } }).open(request.build()).fire("/api/").fire("bong"); } /** * 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(RemoteAdapter.class.getCanonicalName()); meta.addDescription("allows remote communication between applets, or remote instances of myrobotlab"); meta.addCategory("connectivity", "network", "framework"); meta.addDependency("org.atmosphere.nettosphere", "2.3.0"); // meta.addDependency("org.apache.commons.httpclient", "4.5.2"); return meta; } public static void main(String[] args) { LoggingFactory.getInstance().configure(); LoggingFactory.getInstance().setLevel(Level.DEBUG); try { // int i = 0; // RemoteAdapter remote0 = (RemoteAdapter) // Runtime.start(String.format("remote%d", 0), "RemoteAdapter"); // Runtime.start("mac", "Runtime"); // Runtime.start("gui", "GUIService"); // Runtime.start("webgui", "WebGui"); Runtime.start("python", "Python"); // Runtime.start("mac.clock", "Clock"); // Arduino arduino = (Arduino)Runtime.start("arduino", "Arduino"); // Servo servo = (Servo) Runtime.start("servo", "Servo"); // Arduino Arduino = (Arduino) Runtime.start("arduino", "Arduino"); // Max frame length of 10240 has been exceeded. FIXME !!!! RemoteAdapter remote = (RemoteAdapter) Runtime.start("remote", "RemoteAdapter"); // remote.connect("tcp://demo.myrobotlab.org:6767"); Runtime.start("gui", "GUIService"); remote.startListening(); // remote1.startListening(); // remote1.setTCPPort(6868); // remote1.setUDPPort(6868); // remote1.startListening(); // Runtime.start(String.format("gui%d", i), "GUIService"); // Runtime.start("python", "Python"); // arduino.connect("COM9"); // remote1.startListening(6666, 6666); // remote1.startListening(); // remote0.startUDP(6767); // remote1.startListening(); // remote1.startUDP(6767); // remote1.scan(); /* * Runtime.main(new String[] { "-runtimeName", String.format("r%d", i) }); * RemoteAdapter remote = (RemoteAdapter) * Runtime.start(String.format("remote%d", i), "RemoteAdapter"); * Runtime.start(String.format("clock%d", i), "Clock"); * Runtime.start(String.format("gui%d", i), "GUIService"); * * // Security security = // * (Security)Runtime.start(String.format("security", i), // "Security"); * remote.startListening(); // security.allowExportByName("laptop", true); * // security.allowExportByName("laptop.gui", false); // * remote.connect("tcp://192.168.0.92:6767"); // * Runtime.start(String.format("joystick%d", i), "Joystick"); // * Runtime.start(String.format("python%d", i), "Python"); */ // what if null service is passed "register()" no parameters - // I'm sending a registration of nothing? // remote.broadcastState(); // remote.connect("tcp://127.0.0.1:6767"); /* * THIS WORKS Message msg = remote.createMessage("", "register", remote); * remote.sendRemote("tcp://127.0.0.1:6868", msg); */ // FIXME - sholdn't this be sendRemote ??? or at least // in an interface // remote.sendRemote(uri, msg); // xmpp1.sendMessage("xmpp 2", "robot02 02"); } catch (Exception e) { Logging.logError(e); } } }
package org.opencms.jsp.util; import org.opencms.loader.CmsImageScaler; /** * Bean containing image information for the use in JSP (for example formatters). */ public class CmsJspImageBean { /** The image URL. */ private String m_srcUrl; /** The image VFS path. */ private String m_vfsUri; /** The image's width in pixels. */ private int m_width; /** The image's height in pixels. */ private int m_height; /** The CmsImageScaler that was used to create this image. */ private CmsImageScaler m_scaler; /** * Returns the image's original height.<p> * * To get the scaled height of the image, * use {@link #getScaler()}.getHeight().<p> * * @return height in pixels */ public int getHeight() { return m_height; } /** * Returns the basic source parameters for this image.<p> * * In case the image was cropped or otherwise manipulated, * the values are created for the manipulated version.<p> * * The return form is "src='(srcUrl)' height='(h)' width='(w)'".<p> * * @return the basic source parameters for this image */ public String getImgSrc() { StringBuffer result = new StringBuffer(128); // append the image source result.append("src=\""); result.append(getSrcUrl()); result.append("\""); // append image width and height result.append(" width=\""); result.append(m_scaler.getHeight()); result.append("\""); result.append(" height=\""); result.append(m_scaler.getWidth()); result.append("\""); return result.toString(); } /** * Returns the image scaler that was used to create this image.<p> * * May be used to access image scaler properties in JSP. * * @return the image scaler that was used to create this image */ public CmsImageScaler getScaler() { return m_scaler; } /** * Returns the image URL that may be used in img or picture tags.<p> * * @return the image URL */ public String getSrcUrl() { return m_srcUrl; } /** * Returns the URI of the image in the OpenCms VFS.<p> * * @return the URI of the image in the OpenCms VFS */ public String getVfsUri() { return m_vfsUri; } /** * Returns the image's original width.<p> * * To get the scaled height of the image, * use {@link #getScaler()}.getWidth().<p> * * @return width in pixels */ public int getWidth() { return m_width; } /** * Returns <code>true</code> if the image has been scaled or otherwise processed.<p> * * @return the isScaled */ public boolean isScaled() { return !m_scaler.isOriginalScaler(); } /** * Sets the image's height.<p> * * @param height the image's height in pixels */ public void setHeight(int height) { m_height = height; } /** * Sets the image scaler that was used to create this image.<p> * * @param scaler the image scaler that was used to create this image. */ public void setScaler(CmsImageScaler scaler) { m_scaler = scaler; if (m_height <= 0) { setHeight(m_scaler.getHeight()); } if (m_width <= 0) { setWidth(m_scaler.getWidth()); } } /** * Sets the image URL.<p> * * @param srcUrl the image URL */ public void setSrcUrl(String srcUrl) { m_srcUrl = srcUrl; } /** * Sets the URI of the image in the OpenCms VFS.<p> * * @param vfsUri the URI of the image in the OpenCms VFS to set */ public void setVfsUri(String vfsUri) { m_vfsUri = vfsUri; } /** * Sets the image's width.<p> * * @param width the image's width in pixels */ public void setWidth(int width) { m_width = width; } }
package org.opencms.widgets; import org.opencms.ade.configuration.CmsADEConfigData; import org.opencms.ade.configuration.CmsResourceTypeConfig; import org.opencms.ade.galleries.shared.I_CmsGalleryProviderConstants; import org.opencms.ade.galleries.shared.I_CmsGalleryProviderConstants.GalleryMode; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.file.types.CmsResourceTypeBinary; import org.opencms.file.types.CmsResourceTypeImage; import org.opencms.file.types.CmsResourceTypePlain; import org.opencms.i18n.CmsMessages; import org.opencms.json.JSONException; import org.opencms.json.JSONObject; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.util.CmsMacroResolver; import org.opencms.util.CmsStringUtil; import org.opencms.workplace.CmsWorkplace; import org.opencms.xml.content.I_CmsXmlContentHandler.DisplayType; import org.opencms.xml.types.A_CmsXmlContentValue; import java.util.List; import java.util.Locale; import java.util.Set; import org.apache.commons.collections.Factory; import org.apache.commons.logging.Log; import com.google.common.base.Objects; /** * Provides a OpenCms VFS file selection widget, for use on a widget dialog.<p> * * @since 6.0.0 */ public class CmsVfsFileWidget extends A_CmsWidget implements I_CmsADEWidget { /** Macro resolver factory to get the default searchable types. */ protected class SearchTypesFactory implements Factory { /** The CMS context. */ private CmsObject m_cms; /** The resource. */ private CmsResource m_resource; /** * Constructor.<p> * * @param cms the CMS context * @param resource the resource */ public SearchTypesFactory(CmsObject cms, CmsResource resource) { m_cms = cms; m_resource = resource; } /** * @see org.apache.commons.collections.Factory#create() */ public Object create() { return getDefaultSearchTypes(m_cms, m_resource); } } /** Configuration parameter to set the flag to include files in popup resource tree. */ public static final String CONFIGURATION_EXCLUDEFILES = "excludefiles"; /** Configuration parameter to set the flag to show the site selector in popup resource tree. */ public static final String CONFIGURATION_HIDESITESELECTOR = "hidesiteselector"; /** Configuration parameter to set the flag to include files in popup resource tree. */ public static final String CONFIGURATION_INCLUDEFILES = "includefiles"; /** Configuration parameter to prevent the project awareness flag in the popup resource tree. */ public static final String CONFIGURATION_NOTPROJECTAWARE = "notprojectaware"; /** Configuration parameter to set the project awareness flag in the popup resource tree. */ public static final String CONFIGURATION_PROJECTAWARE = "projectaware"; /** Configuration parameter to set search types of the gallery widget. */ public static final String CONFIGURATION_SEARCHTYPES = "searchtypes"; /** Configuration parameter to set the selectable types of the gallery widget. */ public static final String CONFIGURATION_SELECTABLETYPES = "selectabletypes"; /** Configuration parameter to set the flag to show the site selector in popup resource tree. */ public static final String CONFIGURATION_SHOWSITESELECTOR = "showsiteselector"; /** Configuration parameter to set start folder. */ public static final String CONFIGURATION_STARTFOLDER = "startfolder"; /** Configuration parameter to set start site of the popup resource tree. */ public static final String CONFIGURATION_STARTSITE = "startsite"; /** The default search types macro name. */ public static final String DEFAULT_SEARCH_TYPES_MACRO = "defaultSearchTypes"; /** The logger instance for this class. */ private static final Log LOG = CmsLog.getLog(CmsVfsFileWidget.class); /** Flag to determine if files should be shown in popup window. */ private boolean m_includeFiles; /** Flag to determine project awareness, ie. if resources outside of the current project should be displayed as normal. */ private boolean m_projectAware; /** The type shown in the gallery types tab. */ private String m_searchTypes; /** The types that may be selected through the gallery widget. */ private String m_selectableTypes; /** Flag to determine if the site selector should be shown in popup window. */ private boolean m_showSiteSelector; /** The start folder. */ private String m_startFolder; /** The start site used in the popup window. */ private String m_startSite; /** * Creates a new vfs file widget.<p> */ public CmsVfsFileWidget() { // empty constructor is required for class registration this(""); } /** * Creates a new vfs file widget with the parameters to configure the popup tree window behavior.<p> * * @param showSiteSelector true if the site selector should be shown in the popup window * @param startSite the start site root for the popup window */ public CmsVfsFileWidget(boolean showSiteSelector, String startSite) { this(showSiteSelector, startSite, true); } /** * Creates a new vfs file widget with the parameters to configure the popup tree window behavior.<p> * * @param showSiteSelector true if the site selector should be shown in the popup window * @param startSite the start site root for the popup window * @param includeFiles true if files should be shown in the popup window */ public CmsVfsFileWidget(boolean showSiteSelector, String startSite, boolean includeFiles) { this(showSiteSelector, startSite, includeFiles, true); } /** * Creates a new vfs file widget with the parameters to configure the popup tree window behavior.<p> * * @param showSiteSelector true if the site selector should be shown in the popup window * @param startSite the start site root for the popup window * @param includeFiles <code>true</code> if files should be shown in the popup window * @param projectAware <code>true</code> if resources outside of the current project should be displayed as normal */ public CmsVfsFileWidget(boolean showSiteSelector, String startSite, boolean includeFiles, boolean projectAware) { m_showSiteSelector = showSiteSelector; m_startSite = startSite; m_includeFiles = includeFiles; m_projectAware = projectAware; } /** * Creates a new vfs file widget with the given configuration.<p> * * @param configuration the configuration to use */ public CmsVfsFileWidget(String configuration) { super(configuration); } /** * Returns a comma separated list of the default search type names.<p> * * @param cms the CMS context * @param resource the edited resource * * @return a comma separated list of the default search type names */ protected static String getDefaultSearchTypes(CmsObject cms, CmsResource resource) { StringBuffer result = new StringBuffer(); String referenceSitePath = cms.getSitePath(resource); CmsADEConfigData config = OpenCms.getADEManager().lookupConfiguration( cms, cms.getRequestContext().addSiteRoot(cms.getRequestContext().getUri())); Set<String> detailPageTypes = OpenCms.getADEManager().getDetailPageTypes(cms); for (CmsResourceTypeConfig typeConfig : config.getResourceTypes()) { String typeName = typeConfig.getTypeName(); if (!detailPageTypes.contains(typeName)) { continue; } if (typeConfig.checkViewable(cms, referenceSitePath)) { result.append(typeName).append(","); } } result.append(CmsResourceTypeBinary.getStaticTypeName()).append(","); result.append(CmsResourceTypeImage.getStaticTypeName()).append(","); result.append(CmsResourceTypePlain.getStaticTypeName()); return result.toString(); } /** * @see org.opencms.widgets.A_CmsWidget#getConfiguration() */ @Override public String getConfiguration() { StringBuffer result = new StringBuffer(8); // append site selector flag to configuration if (m_showSiteSelector) { result.append(CONFIGURATION_SHOWSITESELECTOR); } else { result.append(CONFIGURATION_HIDESITESELECTOR); } // append start site to configuration if (m_startSite != null) { result.append("|"); result.append(CONFIGURATION_STARTSITE); result.append("="); result.append(m_startSite); } // append flag for including files result.append("|"); if (m_includeFiles) { result.append(CONFIGURATION_INCLUDEFILES); } else { result.append(CONFIGURATION_EXCLUDEFILES); } // append flag for project awareness result.append("|"); if (m_projectAware) { result.append(CONFIGURATION_PROJECTAWARE); } else { result.append(CONFIGURATION_NOTPROJECTAWARE); } if (m_searchTypes != null) { result.append("|"); result.append(CONFIGURATION_SEARCHTYPES); result.append("="); result.append(m_searchTypes); } if (m_selectableTypes != null) { result.append("|"); result.append(CONFIGURATION_SELECTABLETYPES); result.append("="); result.append(m_selectableTypes); } return result.toString(); } /** * @see org.opencms.widgets.I_CmsADEWidget#getConfiguration(org.opencms.file.CmsObject, org.opencms.xml.types.A_CmsXmlContentValue, org.opencms.i18n.CmsMessages, org.opencms.file.CmsResource, java.util.Locale) */ public String getConfiguration( CmsObject cms, A_CmsXmlContentValue schemaType, CmsMessages messages, CmsResource resource, Locale contentLocale) { JSONObject config = getJsonConfig(cms, schemaType, messages, resource, contentLocale); return config.toString(); } /** * @see org.opencms.widgets.I_CmsADEWidget#getCssResourceLinks(org.opencms.file.CmsObject) */ public List<String> getCssResourceLinks(CmsObject cms) { return null; } /** * @see org.opencms.widgets.I_CmsADEWidget#getDefaultDisplayType() */ public DisplayType getDefaultDisplayType() { return DisplayType.wide; } /** * @see org.opencms.widgets.I_CmsWidget#getDialogIncludes(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog) */ @Override public String getDialogIncludes(CmsObject cms, I_CmsWidgetDialog widgetDialog) { StringBuffer result = new StringBuffer(16); result.append(getJSIncludeFile(CmsWorkplace.getSkinUri() + "commons/tree.js")); result.append("\n"); result.append(getJSIncludeFile(CmsWorkplace.getSkinUri() + "components/widgets/fileselector.js")); return result.toString(); } /** * @see org.opencms.widgets.I_CmsWidget#getDialogInitCall(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog) */ @Override public String getDialogInitCall(CmsObject cms, I_CmsWidgetDialog widgetDialog) { return "\tinitVfsFileSelector();\n"; } /** * @see org.opencms.widgets.I_CmsWidget#getDialogInitMethod(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog) */ @Override public String getDialogInitMethod(CmsObject cms, I_CmsWidgetDialog widgetDialog) { StringBuffer result = new StringBuffer(16); result.append("function initVfsFileSelector() {\n"); //initialize tree javascript, does parts of <code>CmsTree.initTree(CmsObject, encoding, skinuri);</code> result.append("\tinitResources(\""); result.append(OpenCms.getWorkplaceManager().getEncoding()); result.append("\", \""); result.append(CmsWorkplace.VFS_PATH_WORKPLACE); result.append("\", \""); result.append(CmsWorkplace.getSkinUri()); result.append("\", \""); result.append(OpenCms.getSystemInfo().getOpenCmsContext()); result.append("\");\n"); result.append("}\n"); return result.toString(); } /** * @see org.opencms.widgets.I_CmsWidget#getDialogWidget(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter) */ public String getDialogWidget(CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) { String id = param.getId(); StringBuffer result = new StringBuffer(128); result.append("<td class=\"xmlTd\">"); result.append("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"maxwidth\"><tr><td style=\"width: 100%;\">"); result.append("<input style=\"width: 99%;\" class=\"xmlInput"); if (param.hasError()) { result.append(" xmlInputError"); } result.append("\" value=\""); result.append(param.getStringValue(cms)); result.append("\" name=\""); result.append(id); result.append("\" id=\""); result.append(id); result.append("\"></td>"); result.append(widgetDialog.dialogHorizontalSpacer(10)); result.append("<td><table class=\"editorbuttonbackground\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>"); StringBuffer buttonJs = new StringBuffer(8); buttonJs.append("javascript:openTreeWin('EDITOR', '"); buttonJs.append(id); buttonJs.append("', document, "); buttonJs.append(m_showSiteSelector); buttonJs.append(", '"); if (m_startSite != null) { buttonJs.append(m_startSite); } else { buttonJs.append(cms.getRequestContext().getSiteRoot()); } buttonJs.append("', "); // include files buttonJs.append(m_includeFiles); // project awareness buttonJs.append(", "); buttonJs.append(m_projectAware); buttonJs.append(");return false;"); result.append(widgetDialog.button( buttonJs.toString(), null, "folder", org.opencms.workplace.Messages.GUI_DIALOG_BUTTON_SEARCH_0, widgetDialog.getButtonStyle())); result.append("</tr></table>"); result.append("</td></tr></table>"); result.append("</td>"); return result.toString(); } /** * @see org.opencms.widgets.I_CmsADEWidget#getInitCall() */ public String getInitCall() { return null; } /** * @see org.opencms.widgets.I_CmsADEWidget#getJavaScriptResourceLinks(org.opencms.file.CmsObject) */ public List<String> getJavaScriptResourceLinks(CmsObject cms) { return null; } /** * Returns the start site root shown by the widget when first displayed.<p> * * If <code>null</code> is returned, the dialog will display the current site of * the current user.<p> * * @return the start site root shown by the widget when first displayed */ public String getStartSite() { return m_startSite; } /** * @see org.opencms.widgets.I_CmsADEWidget#getWidgetName() */ public String getWidgetName() { return CmsVfsFileWidget.class.getName(); } /** * @see org.opencms.widgets.I_CmsADEWidget#isInternal() */ public boolean isInternal() { return true; } /** * Returns <code>true</code> if the site selector is shown.<p> * * The default is <code>true</code>.<p> * * @return <code>true</code> if the site selector is shown */ public boolean isShowingSiteSelector() { return m_showSiteSelector; } /** * @see org.opencms.widgets.I_CmsWidget#newInstance() */ public I_CmsWidget newInstance() { return new CmsVfsFileWidget(getConfiguration()); } /** * @see org.opencms.widgets.A_CmsWidget#setConfiguration(java.lang.String) */ @Override public void setConfiguration(String configuration) { m_showSiteSelector = true; m_includeFiles = true; m_projectAware = true; if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(configuration)) { if (configuration.contains(CONFIGURATION_HIDESITESELECTOR)) { // site selector should be hidden m_showSiteSelector = false; } int siteIndex = configuration.indexOf(CONFIGURATION_STARTSITE); if (siteIndex != -1) { // start site is given String site = configuration.substring(siteIndex + CONFIGURATION_STARTSITE.length() + 1); if (site.indexOf('|') != -1) { // cut eventual following configuration values site = site.substring(0, site.indexOf('|')); } m_startSite = site; } if (configuration.contains(CONFIGURATION_EXCLUDEFILES)) { // files should not be included m_includeFiles = false; } if (configuration.contains(CONFIGURATION_NOTPROJECTAWARE)) { // resources outside of the current project should not be disabled m_projectAware = false; } int searchTypesIndex = configuration.indexOf(CONFIGURATION_SEARCHTYPES); if (searchTypesIndex != -1) { String searchTypes = configuration.substring(searchTypesIndex + CONFIGURATION_SEARCHTYPES.length() + 1); if (searchTypes.contains("|")) { m_searchTypes = searchTypes.substring(0, searchTypes.indexOf("|")); } else { m_searchTypes = searchTypes; } } int selectableTypesIndex = configuration.indexOf(CONFIGURATION_SELECTABLETYPES); if (selectableTypesIndex != -1) { String selectableTypes = configuration.substring(selectableTypesIndex + CONFIGURATION_SELECTABLETYPES.length() + 1); if (selectableTypes.contains("|")) { m_selectableTypes = selectableTypes.substring(0, selectableTypes.indexOf("|")); } else { m_selectableTypes = selectableTypes; } } int startFolderIndex = configuration.indexOf(CONFIGURATION_STARTFOLDER); if (startFolderIndex != -1) { String startFolder = configuration.substring(startFolderIndex + CONFIGURATION_STARTFOLDER.length() + 1); if (startFolder.contains("|")) { m_startFolder = startFolder.substring(0, startFolder.indexOf("|")); } else { m_startFolder = startFolder; } } } super.setConfiguration(configuration); } /** * Gets the JSON configuration.<p> * * @param cms the current CMS context * @param schemaType the schema type * @param messages the messages * @param resource the content resource * @param contentLocale the content locale * * @return the JSON configuration object */ protected JSONObject getJsonConfig( CmsObject cms, A_CmsXmlContentValue schemaType, CmsMessages messages, CmsResource resource, Locale contentLocale) { JSONObject config = new JSONObject(); try { config.put(I_CmsGalleryProviderConstants.CONFIG_START_SITE, m_startSite); String tabConfig = null; if (m_includeFiles) { tabConfig = "selectAll"; } else { tabConfig = "folders"; } config.put(I_CmsGalleryProviderConstants.CONFIG_TAB_CONFIG, tabConfig); config.put(I_CmsGalleryProviderConstants.CONFIG_SHOW_SITE_SELECTOR, m_showSiteSelector); config.put(I_CmsGalleryProviderConstants.CONFIG_REFERENCE_PATH, cms.getSitePath(resource)); config.put(I_CmsGalleryProviderConstants.CONFIG_LOCALE, contentLocale.toString()); config.put(I_CmsGalleryProviderConstants.CONFIG_GALLERY_MODE, GalleryMode.widget.name()); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_selectableTypes)) { config.put(I_CmsGalleryProviderConstants.CONFIG_RESOURCE_TYPES, m_selectableTypes.trim()); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_searchTypes)) { CmsMacroResolver resolver = CmsMacroResolver.newInstance(); resolver.addDynamicMacro(DEFAULT_SEARCH_TYPES_MACRO, new SearchTypesFactory(cms, resource)); String searchTypes = resolver.resolveMacros(m_searchTypes.trim()); config.put(I_CmsGalleryProviderConstants.CONFIG_SEARCH_TYPES, searchTypes); } else if (CmsStringUtil.isEmptyOrWhitespaceOnly(m_selectableTypes)) { config.put(I_CmsGalleryProviderConstants.CONFIG_SEARCH_TYPES, getDefaultSearchTypes(cms, resource)); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_startFolder)) { config.put(I_CmsGalleryProviderConstants.CONFIG_START_FOLDER, m_startFolder); } String treeToken = "" + Objects.hashCode(m_startSite, cms.getRequestContext().getSiteRoot(), "" + m_selectableTypes); config.put(I_CmsGalleryProviderConstants.CONFIG_TREE_TOKEN, treeToken); } catch (JSONException e) { LOG.error(e.getLocalizedMessage(), e); } return config; } /** * Computes the tree token, which is used to decide which preloaded tree, if any, to load for the VFS/sitemap tabs.<p> * * @param cms the current CMS context * @param value the content value * @param resource the content resource * @param contentLocale the content locale * * @return the tree token */ protected String getTreeToken(CmsObject cms, A_CmsXmlContentValue value, CmsResource resource, Locale contentLocale) { return cms.getRequestContext().getSiteRoot(); } }
package org.opencms.xml; import org.opencms.configuration.CmsConfigurationManager; import org.opencms.db.CmsDriverManager; import org.opencms.db.CmsPublishedResource; import org.opencms.file.CmsFile; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.main.CmsEvent; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.I_CmsEventListener; import org.opencms.main.OpenCms; import org.opencms.util.CmsCollectionsGenericWrapper; import org.opencms.util.CmsFileUtil; import org.opencms.util.CmsUUID; import org.opencms.xml.page.CmsXmlPage; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; /** * Resolves XML entities (e.g. external DTDs) in the OpenCms VFS.<p> * * Also provides a cache for XML content schema definitions.<p> * * @since 6.0.0 */ public class CmsXmlEntityResolver implements EntityResolver, I_CmsEventListener { /** The scheme to identify a file in the OpenCms VFS. */ public static final String OPENCMS_SCHEME = "opencms: /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsXmlEntityResolver.class); /** A temporary cache for XML content definitions. */ private static Map<String, CmsXmlContentDefinition> m_cacheContentDefinitions; /** A permanent cache to avoid multiple readings of often used files from the VFS. */ private static Map<String, byte[]> m_cachePermanent; /** A temporary cache to avoid multiple readings of often used files from the VFS. */ private static Map<String, byte[]> m_cacheTemporary; /** The location of the XML page XML schema. */ private static final String XMLPAGE_OLD_DTD_LOCATION = "org/opencms/xml/page/xmlpage.dtd"; /** The (old) DTD address of the OpenCms xmlpage (used in 5.3.5). */ private static final String XMLPAGE_OLD_DTD_SYSTEM_ID_1 = "http: /** The (old) DTD address of the OpenCms xmlpage (used until 5.3.5). */ private static final String XMLPAGE_OLD_DTD_SYSTEM_ID_2 = "/system/shared/page.dtd"; /** The location of the xmlpage XSD. */ private static final String XMLPAGE_XSD_LOCATION = "org/opencms/xml/page/xmlpage.xsd"; private CmsObject m_cms; /** * Creates a new XML entity resolver based on the provided CmsObject.<p> * * If the provided CmsObject is null, then the OpenCms VFS is not * searched for XML entities, however the internal cache and * other OpenCms internal entities not in the VFS are still resolved.<p> * * @param cms the cms context to use for resolving XML files from the OpenCms VFS */ public CmsXmlEntityResolver(CmsObject cms) { initCaches(); m_cms = cms; } /** * Adds a system ID URL to to internal permanent cache.<p> * * This cache will NOT be cleared automatically.<p> * * @param systemId the system ID to add * @param content the content of the system id */ public static void cacheSystemId(String systemId, byte[] content) { initCaches(); m_cachePermanent.put(systemId, content); } /** * Checks if a given system ID URL is in the internal permanent cache.<p> * * This check is required to see if a XML content is based on a file that actually exists in the OpenCms VFS, * or if the schema has been just cached without a VFS file.<p> * * @param systemId the system id ID check * * @return <code>true</code> if the system ID is in the internal permanent cache, <code>false</code> otherwise */ public static boolean isCachedSystemId(String systemId) { if (m_cachePermanent != null) { return m_cachePermanent.containsKey(systemId); } return false; } protected static void initialize(CmsObject adminCms, byte[] typeSchemaBytes) { // create the resolver to register as event listener CmsXmlEntityResolver resolver = new CmsXmlEntityResolver(adminCms); // register this object as event listener OpenCms.addCmsEventListener(resolver, new int[] { I_CmsEventListener.EVENT_CLEAR_CACHES, I_CmsEventListener.EVENT_PUBLISH_PROJECT, I_CmsEventListener.EVENT_RESOURCE_MODIFIED, I_CmsEventListener.EVENT_RESOURCE_MOVED, I_CmsEventListener.EVENT_RESOURCE_DELETED}); // cache the base widget type XML schema definitions cacheSystemId(CmsXmlContentDefinition.XSD_INCLUDE_OPENCMS, typeSchemaBytes); } /** * Initializes the internal caches for permanent and temporary system IDs.<p> */ private static void initCaches() { if (m_cacheTemporary == null) { Map<String, byte[]> cacheTemporary = CmsCollectionsGenericWrapper.createLRUMap(1024); m_cacheTemporary = Collections.synchronizedMap(cacheTemporary); Map<String, byte[]> cachePermanent = new HashMap<String, byte[]>(32); m_cachePermanent = Collections.synchronizedMap(cachePermanent); Map<String, CmsXmlContentDefinition> cacheContentDefinitions = CmsCollectionsGenericWrapper.createLRUMap(512); m_cacheContentDefinitions = Collections.synchronizedMap(cacheContentDefinitions); } if (OpenCms.getRunLevel() > OpenCms.RUNLEVEL_1_CORE_OBJECT) { if ((OpenCms.getMemoryMonitor() != null) && !OpenCms.getMemoryMonitor().isMonitoring(CmsXmlEntityResolver.class.getName() + ".cacheTemporary")) { // reinitialize the caches after the memory monitor is set up Map<String, byte[]> cacheTemporary = CmsCollectionsGenericWrapper.createLRUMap(128); cacheTemporary.putAll(m_cacheTemporary); m_cacheTemporary = Collections.synchronizedMap(cacheTemporary); // map must be of type "LRUMap" so that memory monitor can access all information OpenCms.getMemoryMonitor().register( CmsXmlEntityResolver.class.getName() + ".cacheTemporary", cacheTemporary); Map<String, byte[]> cachePermanent = new HashMap<String, byte[]>(32); cachePermanent.putAll(m_cachePermanent); m_cachePermanent = Collections.synchronizedMap(cachePermanent); // map must be of type "HashMap" so that memory monitor can access all information OpenCms.getMemoryMonitor().register( CmsXmlEntityResolver.class.getName() + ".cachePermanent", cachePermanent); Map<String, CmsXmlContentDefinition> cacheContentDefinitions = CmsCollectionsGenericWrapper.createLRUMap(64); cacheContentDefinitions.putAll(m_cacheContentDefinitions); m_cacheContentDefinitions = Collections.synchronizedMap(cacheContentDefinitions); // map must be of type "LRUMap" so that memory monitor can access all information OpenCms.getMemoryMonitor().register( CmsXmlEntityResolver.class.getName() + ".cacheContentDefinitions", cacheContentDefinitions); } } } /** * Caches an XML content definition based on the given system id and the online / offline status * of this entity resolver instance.<p> * * @param systemId the system id to use as cache key * @param contentDefinition the content definition to cache */ public void cacheContentDefinition(String systemId, CmsXmlContentDefinition contentDefinition) { String cacheKey = getCacheKeyForCurrentProject(systemId); m_cacheContentDefinitions.put(cacheKey, contentDefinition); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_ERR_CACHED_SYSTEM_ID_1, cacheKey)); } } /** * @see org.opencms.main.I_CmsEventListener#cmsEvent(org.opencms.main.CmsEvent) */ public void cmsEvent(CmsEvent event) { CmsResource resource; switch (event.getType()) { case I_CmsEventListener.EVENT_PUBLISH_PROJECT: // only flush cache if a schema definition where published CmsUUID publishHistoryId = new CmsUUID((String)event.getData().get(I_CmsEventListener.KEY_PUBLISHID)); if (isSchemaDefinitionInPublishList(publishHistoryId)) { m_cacheTemporary.clear(); m_cacheContentDefinitions.clear(); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_ERR_FLUSHED_CACHES_0)); } } break; case I_CmsEventListener.EVENT_CLEAR_CACHES: // flush cache m_cacheTemporary.clear(); m_cacheContentDefinitions.clear(); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_ERR_FLUSHED_CACHES_0)); } break; case I_CmsEventListener.EVENT_RESOURCE_MODIFIED: Object change = event.getData().get(I_CmsEventListener.KEY_CHANGE); if ((change != null) && change.equals(new Integer(CmsDriverManager.NOTHING_CHANGED))) { // skip lock & unlock return; } resource = (CmsResource)event.getData().get(I_CmsEventListener.KEY_RESOURCE); uncacheSystemId(resource.getRootPath()); break; case I_CmsEventListener.EVENT_RESOURCE_DELETED: case I_CmsEventListener.EVENT_RESOURCE_MOVED: List<CmsResource> resources = CmsCollectionsGenericWrapper.list(event.getData().get( I_CmsEventListener.KEY_RESOURCES)); for (int i = 0; i < resources.size(); i++) { resource = resources.get(i); uncacheSystemId(resource.getRootPath()); } break; default: // no operation } } /** * Looks up the given XML content definition system id in the internal content definition cache.<p> * * @param systemId the system id of the XML content definition to look up * * @return the XML content definition found, or null if no definition is cached for the given system id */ public CmsXmlContentDefinition getCachedContentDefinition(String systemId) { String cacheKey = getCacheKeyForCurrentProject(systemId); CmsXmlContentDefinition result = m_cacheContentDefinitions.get(cacheKey); if ((result != null) && LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_CACHE_LOOKUP_SUCCEEDED_1, cacheKey)); } return result; } /** * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) */ public InputSource resolveEntity(String publicId, String systemId) { // lookup the system id caches first byte[] content; content = m_cachePermanent.get(systemId); if (content != null) { // permanent cache contains system id return new InputSource(new ByteArrayInputStream(content)); } else if (systemId.equals(CmsXmlPage.XMLPAGE_XSD_SYSTEM_ID)) { // XML page XSD reference try { InputStream stream = getClass().getClassLoader().getResourceAsStream(XMLPAGE_XSD_LOCATION); content = CmsFileUtil.readFully(stream); // cache the XML page DTD m_cachePermanent.put(systemId, content); return new InputSource(new ByteArrayInputStream(content)); } catch (Throwable t) { LOG.error(Messages.get().getBundle().key(Messages.LOG_XMLPAGE_XSD_NOT_FOUND_1, XMLPAGE_XSD_LOCATION), t); } } else if (systemId.equals(XMLPAGE_OLD_DTD_SYSTEM_ID_1) || systemId.endsWith(XMLPAGE_OLD_DTD_SYSTEM_ID_2)) { // XML page DTD reference try { InputStream stream = getClass().getClassLoader().getResourceAsStream(XMLPAGE_OLD_DTD_LOCATION); // cache the XML page DTD content = CmsFileUtil.readFully(stream); m_cachePermanent.put(systemId, content); return new InputSource(new ByteArrayInputStream(content)); } catch (Throwable t) { LOG.error( Messages.get().getBundle().key(Messages.LOG_XMLPAGE_DTD_NOT_FOUND_1, XMLPAGE_OLD_DTD_LOCATION), t); } } else if ((m_cms != null) && systemId.startsWith(OPENCMS_SCHEME)) { // opencms:// VFS reference String cacheSystemId = systemId.substring(OPENCMS_SCHEME.length() - 1); String cacheKey = getCacheKey( cacheSystemId, m_cms.getRequestContext().getCurrentProject().isOnlineProject()); // look up temporary cache content = m_cacheTemporary.get(cacheKey); if (content != null) { return new InputSource(new ByteArrayInputStream(content)); } String storedSiteRoot = m_cms.getRequestContext().getSiteRoot(); try { // content not cached, read from VFS m_cms.getRequestContext().setSiteRoot("/"); CmsFile file = m_cms.readFile(cacheSystemId, CmsResourceFilter.IGNORE_EXPIRATION); content = file.getContents(); // store content in cache m_cacheTemporary.put(cacheKey, content); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_ERR_CACHED_SYS_ID_1, cacheKey)); } return new InputSource(new ByteArrayInputStream(content)); } catch (Throwable t) { LOG.error(Messages.get().getBundle().key(Messages.LOG_ENTITY_RESOLVE_FAILED_1, systemId), t); } finally { m_cms.getRequestContext().setSiteRoot(storedSiteRoot); } } else if (systemId.substring(0, systemId.lastIndexOf("/") + 1).equalsIgnoreCase( CmsConfigurationManager.DEFAULT_DTD_PREFIX)) { // default DTD location in the org.opencms.configuration package String location = null; try { String dtdFilename = systemId.substring(systemId.lastIndexOf("/") + 1); location = CmsConfigurationManager.DEFAULT_DTD_LOCATION + dtdFilename; InputStream stream = getClass().getClassLoader().getResourceAsStream(location); content = CmsFileUtil.readFully(stream); // cache the DTD m_cachePermanent.put(systemId, content); return new InputSource(new ByteArrayInputStream(content)); } catch (Throwable t) { LOG.error(Messages.get().getBundle().key(Messages.LOG_DTD_NOT_FOUND_1, location), t); } } // use the default behaviour (i.e. resolve through external URL) return null; } /** * Returns a cache key for the given system id (filename) based on the status * of the given project flag.<p> * * @param systemId the system id (filename) to get the cache key for * @param online indicates if this key is generated for the online project * * @return the cache key for the system id */ private String getCacheKey(String systemId, boolean online) { if (online) { return "online_".concat(systemId); } return "offline_".concat(systemId); } /** * Returns a cache key for the given system id (filename) based on the status * of the internal CmsObject.<p> * * @param systemId the system id (filename) to get the cache key for * * @return the cache key for the system id */ private String getCacheKeyForCurrentProject(String systemId) { // check the project boolean project = (m_cms != null) ? m_cms.getRequestContext().getCurrentProject().isOnlineProject() : false; // remove opencms:// prefix if (systemId.startsWith(OPENCMS_SCHEME)) { systemId = systemId.substring(OPENCMS_SCHEME.length() - 1); } return getCacheKey(systemId, project); } /** * Proves if there is at least one xsd or dtd file in the list of resources to publish.<p> * * @param publishHistoryId the publish history id * * @return true, if there is at least one xsd or dtd file in the list of resources to publish, otherwise false */ private boolean isSchemaDefinitionInPublishList(CmsUUID publishHistoryId) { if (m_cms == null) { // CmsObject not available, assume there may be a schema definition in the publish history return true; } try { List<CmsPublishedResource> publishedResources = m_cms.readPublishedResources(publishHistoryId); for (CmsPublishedResource cmsPublishedResource : publishedResources) { String resourceRootPath = cmsPublishedResource.getRootPath(); String resourceRootPathLowerCase = resourceRootPath.toLowerCase(); if (resourceRootPathLowerCase.endsWith(".xsd") || resourceRootPathLowerCase.endsWith(".dtd") || m_cacheTemporary.containsKey(getCacheKey(resourceRootPath, true))) { return true; } } } catch (CmsException e) { // error reading published Resources. LOG.warn(e.getMessage(), e); } return false; } /** * Uncaches a system id (filename) from the internal offline temporary and content defintions caches.<p> * * The online resources cached for the online project are only flushed when a project is published.<p> * * @param systemId the system id (filename) to uncache */ private void uncacheSystemId(String systemId) { Object o; o = m_cacheTemporary.remove(getCacheKey(systemId, false)); if (null != o) { // if an object was removed from the temporary cache, all XML content definitions must be cleared // because this may be a nested subschema m_cacheContentDefinitions.clear(); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key( Messages.LOG_ERR_UNCACHED_SYS_ID_1, getCacheKey(systemId, false))); } } else { // check if a cached content definition has to be removed based on the system id o = m_cacheContentDefinitions.remove(getCacheKey(systemId, false)); if ((null != o) && LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key( Messages.LOG_ERR_UNCACHED_CONTENT_DEF_1, getCacheKey(systemId, false))); } } } }
package org.pentaho.di.repository; import java.util.List; import org.pentaho.di.cluster.ClusterSchema; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.Condition; import org.pentaho.di.core.ProgressMonitorListener; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleSecurityException; import org.pentaho.di.core.logging.LogChannelInterface; import org.pentaho.di.job.JobMeta; import org.pentaho.di.partition.PartitionSchema; import org.pentaho.di.shared.SharedObjects; import org.pentaho.di.trans.TransMeta; public interface Repository { /** * @return The name of the repository */ public String getName(); /** * Get the repository version. * @return The repository version as a string */ public String getVersion(); /** * @return the metadata describing this repository. */ public RepositoryMeta getRepositoryMeta(); /** * @return the currently logged on user. (also available through the repository security provider) */ public UserInfo getUserInfo(); /** * @return The security provider for this repository. */ public RepositorySecurityProvider getSecurityProvider(); /** * @return the logging channel of this repository */ public LogChannelInterface getLog(); /** * Connect to the repository. Make sure you don't connect more than once to the same repository with this repository object. * * @throws KettleSecurityException in case the supplied user or password is incorrect. * @throws KettleException in case there is a general unexpected error OR if we're already connected to the repository. */ public void connect() throws KettleException, KettleSecurityException; /** * Disconnect from the repository. */ public void disconnect(); public boolean isConnected(); /** Initialize the repository with the repository metadata and user information. * */ public void init(RepositoryMeta repositoryMeta, UserInfo userInfo); // Common methods... /** * See if a repository object exists in the repository * * @param name the name of the object * @param repositoryDirectory the directory in which it should reside * @param objectType the type of repository object * @return true if the job exists * @throws KettleException in case something goes wrong. */ public boolean exists(String name, RepositoryDirectory repositoryDirectory, RepositoryObjectType objectType) throws KettleException; public ObjectId getTransformationID(String name, RepositoryDirectory repositoryDirectory) throws KettleException; public ObjectId getJobId(String name, RepositoryDirectory repositoryDirectory) throws KettleException; public void save(RepositoryElementInterface repositoryElement, String versionComment, ProgressMonitorListener monitor) throws KettleException; // Transformations : Loading & saving objects... /** * Load a transformation with a name from a folder in the repository * * @param transname the name of the transformation to load * @param The folder to load it from * @param monitor the progress monitor to use (UI feedback) * @param setInternalVariables set to true if you want to automatically set the internal variables of the loaded transformation. (true is the default with very few exceptions!) * @param revision the revision to load. Specify null to load the last version. */ public TransMeta loadTransformation(String transname, RepositoryDirectory repdir, ProgressMonitorListener monitor, boolean setInternalVariables, String revision) throws KettleException; public SharedObjects readTransSharedObjects(TransMeta transMeta) throws KettleException; /** * Move / rename a transformation * * @param id_transformation The ObjectId of the transformation to move * @param newDirectory The RepositoryDirectory that will be the new parent of the transformation (May be null if a move is not desired) * @param newName The new name of the transformation (May be null if a rename is not desired) * @return The ObjectId of the transformation that was moved * @throws KettleException */ public ObjectId renameTransformation(ObjectId id_transformation, RepositoryDirectory newDirectory, String newName) throws KettleException; /** * Delete everything related to a transformation from the repository. * This does not included shared objects : databases, slave servers, cluster and partition schema. * * @param id_transformation the transformation id to delete * @throws KettleException */ public void deleteTransformation(ObjectId id_transformation) throws KettleException; /** * Locks this transformation for exclusive use by the current user of the repository * @param id_transformation the id of the transformation to lock * @param isSessionScoped If isSessionScoped is true then this lock will expire upon the expiration of the current session (either through an automatic or explicit Session.logout); if false, this lock does not expire until explicitly unlocked or automatically unlocked due to a implementation-specific limitation, such as a timeout. * @param message the lock message * @throws KettleException in case something goes wrong or the transformation is already locked by someone else. */ public void lockTransformation(ObjectId id_transformation, String message) throws KettleException; /** * Unlocks a transformation, allowing other people to modify it again. * @param id_transformation the id of the transformation to unlock * @throws KettleException in case something goes wrong with the database or connection */ public void unlockTransformation(ObjectId id_transformation) throws KettleException; /** * Return the lock object for this transformation. Returns null if there is no lock present. * * @param id_transformation * @return the lock object for this transformation, null if no lock is present. * @throws KettleDatabaseException */ public RepositoryLock getTransformationLock(ObjectId id_transformation) throws KettleException; // Jobs: Loading & saving objects... /** * Load a job from the repository * @param jobname the name * @param repdir the directory * @param monitor the progress monitor or null * @param revision the revision to load. Specify null to load the last version. */ public JobMeta loadJob(String jobname, RepositoryDirectory repdir, ProgressMonitorListener monitor, String revision) throws KettleException; public SharedObjects readJobMetaSharedObjects(JobMeta jobMeta) throws KettleException; /** * Move / rename a job * * @param id_job The ObjectId of the job to move * @param newDirectory The RepositoryDirectory that will be the new parent of the job (May be null if a move is not desired) * @param newName The new name of the job (May be null if a rename is not desired) * @return The ObjectId of the job that was moved * @throws KettleException */ public ObjectId renameJob(ObjectId id_job, RepositoryDirectory newDirectory, String newName) throws KettleException; public void deleteJob(ObjectId id_job) throws KettleException; /** * Locks this job for exclusive use by the current user of the repository * @param id_job the id of the job to lock * @param message the lock message * @throws KettleException in case something goes wrong or the job is already locked by someone else. */ public void lockJob(ObjectId id_job, String message) throws KettleException; /** * Unlocks a job, allowing other people to modify it again. * @param id_job the id of the transformation to unlock * @throws KettleException in case something goes wrong with the database or connection */ public void unlockJob(ObjectId id_job) throws KettleException; /** * Return the lock object for this job. Returns null if there is no lock present. * * @param id_job * @return the lock object for this job, null if no lock is present. * @throws KettleDatabaseException */ public RepositoryLock getJobLock(ObjectId id_job) throws KettleException; // Databases : loading, saving, renaming, etc. /** * Load the Database connection Metadata from the repository * @param id_database the id of the database connection to load * @param revision the revision to load. Specify null to load the last version. * @throws KettleException in case something goes wrong with database, connection, etc. */ public DatabaseMeta loadDatabaseMeta(ObjectId id_database, String revision) throws KettleException; public void deleteDatabaseMeta(String databaseName) throws KettleException; public ObjectId[] getDatabaseIDs(boolean includeDeleted) throws KettleException; public String[] getDatabaseNames(boolean includeDeleted) throws KettleException; public ObjectId renameDatabase(ObjectId id_database, String newname) throws KettleException; /** * Read all the databases defined in the repository * @return a list of all the databases defined in the repository * @throws KettleException */ public List<DatabaseMeta> readDatabases() throws KettleException; public ObjectId getDatabaseID(String name) throws KettleException; // ClusterSchema public ClusterSchema loadClusterSchema(ObjectId id_cluster_schema, List<SlaveServer> slaveServers, String versionLabel) throws KettleException; public ObjectId[] getClusterIDs(boolean includeDeleted) throws KettleException; public String[] getClusterNames(boolean includeDeleted) throws KettleException; public ObjectId getClusterID(String name) throws KettleException; public void deleteClusterSchema(ObjectId id_cluster) throws KettleException; // SlaveServer public SlaveServer loadSlaveServer(ObjectId id_slave_server, String versionLabel) throws KettleException; public ObjectId[] getSlaveIDs(boolean includeDeleted) throws KettleException; public String[] getSlaveNames(boolean includeDeleted) throws KettleException; /** * @return a list of all the slave servers in the repository. * @throws KettleException */ public List<SlaveServer> getSlaveServers() throws KettleException; public ObjectId getSlaveID(String name) throws KettleException; public void deleteSlave(ObjectId id_slave) throws KettleException; // PartitionSchema public PartitionSchema loadPartitionSchema(ObjectId id_partition_schema, String versionLabel) throws KettleException; public ObjectId[] getPartitionSchemaIDs(boolean includeDeleted) throws KettleException; // public ObjectId[] getPartitionIDs(ObjectId id_partition_schema) throws KettleException; public String[] getPartitionSchemaNames(boolean includeDeleted) throws KettleException; public ObjectId getPartitionSchemaID(String name) throws KettleException; public void deletePartitionSchema(ObjectId id_partition_schema) throws KettleException; // Directory stuff public RepositoryDirectory loadRepositoryDirectoryTree() throws KettleException; // public RepositoryDirectory loadRepositoryDirectoryTree(RepositoryDirectory root) throws KettleException; public void saveRepositoryDirectory(RepositoryDirectory dir) throws KettleException; public void deleteRepositoryDirectory(RepositoryDirectory dir) throws KettleException; /** * Move / rename a repository directory * * @param id The ObjectId of the repository directory to move * @param newParentDir The RepositoryDirectory that will be the new parent of the repository directory (May be null if a move is not desired) * @param newName The new name of the repository directory (May be null if a rename is not desired) * @return The ObjectId of the repository directory that was moved * @throws KettleException */ public ObjectId renameRepositoryDirectory(ObjectId id, RepositoryDirectory newParentDir, String newName) throws KettleException; @Deprecated public ObjectId renameRepositoryDirectory(RepositoryDirectory dir) throws KettleException; /** * Create a new directory, possibly by creating several sub-directies of / at the same time. * * @param parentDirectory the parent directory * @param directoryPath The path to the new Repository Directory, to be created. * @return The created sub-directory * @throws KettleException In case something goes wrong */ public RepositoryDirectory createRepositoryDirectory(RepositoryDirectory parentDirectory, String directoryPath) throws KettleException; public String[] getTransformationNames(ObjectId id_directory, boolean includeDeleted) throws KettleException; public List<RepositoryObject> getJobObjects(ObjectId id_directory, boolean includeDeleted) throws KettleException; public List<RepositoryObject> getTransformationObjects(ObjectId id_directory, boolean includeDeleted) throws KettleException; public String[] getJobNames(ObjectId id_directory, boolean includeDeleted) throws KettleException; public String[] getDirectoryNames(ObjectId id_directory) throws KettleException; // Logging... /** * Insert an entry in the audit trail of the repository. * This is an optional operation and depends on the capabilities of the underlying repository. * * @param The description to be put in the audit trail of the repository. */ public ObjectId insertLogEntry(String description) throws KettleException; public void insertStepDatabase(ObjectId id_transformation, ObjectId id_step, ObjectId id_database) throws KettleException; public void insertJobEntryDatabase(ObjectId id_job, ObjectId id_jobentry, ObjectId id_database) throws KettleException; // Condition /** * This method saves the object ID of the condition object (if not null) in the step attributes * @param id_step * @param code * @param condition */ public void saveConditionStepAttribute(ObjectId id_transformation, ObjectId id_step, String code, Condition condition) throws KettleException; /** * Load a condition from the repository with the Object ID stored in a step attribute. * @param id_step * @param code * @return * @throws KettleException */ public Condition loadConditionFromStepAttribute(ObjectId id_step, String code) throws KettleException; // Attributes for steps... public boolean getStepAttributeBoolean(ObjectId id_step, int nr, String code, boolean def) throws KettleException; public boolean getStepAttributeBoolean(ObjectId id_step, int nr, String code) throws KettleException; public boolean getStepAttributeBoolean(ObjectId id_step, String code) throws KettleException; public long getStepAttributeInteger(ObjectId id_step, int nr, String code) throws KettleException; public long getStepAttributeInteger(ObjectId id_step, String code) throws KettleException; public String getStepAttributeString(ObjectId id_step, int nr, String code) throws KettleException; public String getStepAttributeString(ObjectId id_step, String code) throws KettleException; public void saveStepAttribute(ObjectId id_transformation, ObjectId id_step, int nr, String code, String value) throws KettleException; public void saveStepAttribute(ObjectId id_transformation, ObjectId id_step, String code, String value) throws KettleException; public void saveStepAttribute(ObjectId id_transformation, ObjectId id_step, int nr, String code, boolean value) throws KettleException; public void saveStepAttribute(ObjectId id_transformation, ObjectId id_step, String code, boolean value) throws KettleException; public void saveStepAttribute(ObjectId id_transformation, ObjectId id_step, int nr, String code, long value) throws KettleException; public void saveStepAttribute(ObjectId id_transformation, ObjectId id_step, String code, long value) throws KettleException; public void saveStepAttribute(ObjectId id_transformation, ObjectId id_step, int nr, String code, double value) throws KettleException; public void saveStepAttribute(ObjectId id_transformation, ObjectId id_step, String code, double value) throws KettleException; public int countNrStepAttributes(ObjectId id_step, String code) throws KettleException; // Attributes for job entries... public int countNrJobEntryAttributes(ObjectId id_jobentry, String code) throws KettleException; public boolean getJobEntryAttributeBoolean(ObjectId id_jobentry, String code) throws KettleException; public boolean getJobEntryAttributeBoolean(ObjectId id_jobentry, int nr, String code) throws KettleException; public boolean getJobEntryAttributeBoolean(ObjectId id_jobentry, String code, boolean def) throws KettleException; public long getJobEntryAttributeInteger(ObjectId id_jobentry, String code) throws KettleException; public long getJobEntryAttributeInteger(ObjectId id_jobentry, int nr, String code) throws KettleException; public String getJobEntryAttributeString(ObjectId id_jobentry, String code) throws KettleException; public String getJobEntryAttributeString(ObjectId id_jobentry, int nr, String code) throws KettleException; public void saveJobEntryAttribute(ObjectId id_job, ObjectId id_jobentry, int nr, String code, String value) throws KettleException; public void saveJobEntryAttribute(ObjectId id_job, ObjectId id_jobentry, String code, String value) throws KettleException; public void saveJobEntryAttribute(ObjectId id_job, ObjectId id_jobentry, int nr, String code, boolean value) throws KettleException; public void saveJobEntryAttribute(ObjectId id_job, ObjectId id_jobentry, String code, boolean value) throws KettleException; public void saveJobEntryAttribute(ObjectId id_job, ObjectId id_jobentry, int nr, String code, long value) throws KettleException; public void saveJobEntryAttribute(ObjectId id_job, ObjectId id_jobentry, String code, long value) throws KettleException; /** * This method is introduced to avoid having to go over an integer/string/whatever in the interface and the step code. * * @param id_step * @param code * @return * @throws KettleException */ public DatabaseMeta loadDatabaseMetaFromStepAttribute(ObjectId id_step, String code, List<DatabaseMeta> databases) throws KettleException; /** * This method saves the object ID of the database object (if not null) in the step attributes * @param id_transformation * @param id_step * @param code * @param database */ public void saveDatabaseMetaStepAttribute(ObjectId id_transformation, ObjectId id_step, String code, DatabaseMeta database) throws KettleException; /** * This method is introduced to avoid having to go over an integer/string/whatever in the interface and the job entry code. * * @param id_step * @param code * @return * @throws KettleException */ public DatabaseMeta loadDatabaseMetaFromJobEntryAttribute(ObjectId id_jobentry, String nameCode, String idCode, List<DatabaseMeta> databases) throws KettleException; /** * This method saves the object ID of the database object (if not null) in the job entry attributes * @param id_job * @param id_jobentry * @param code * @param database */ public void saveDatabaseMetaJobEntryAttribute(ObjectId id_job, ObjectId id_jobentry, String nameCode, String idCode, DatabaseMeta database) throws KettleException; /** * Get the revision history of a repository element. * If the capabilities of this repositories do not include revision support, this method can return null. * * @param element the element. If the ID is specified, this will be taken. Otherwise it will be looked up. * * @return The revision history, sorted from first to last. * @throws KettleException in case something goes horribly wrong */ public List<ObjectRevision> getRevisions(RepositoryElementLocationInterface element) throws KettleException; /** * Removes he deleted flag from a repository element in the repository. * If it wasn't deleted, it remains untouched. * * @param element the repository element to restore * @throws KettleException get throws in case something goes horribly wrong. */ public void undeleteObject(RepositoryElementLocationInterface element) throws KettleException; /** * Get a hold of the version registry of this repository. * * @return the version registry. * @throws KettleException in case something goes horribly wrong. */ public RepositoryVersionRegistry getVersionRegistry() throws KettleException; }
package org.phenoscape.bridge; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.UUID; import org.obd.model.CompositionalDescription; import org.obd.model.Graph; import org.obd.model.LinkStatement; import org.obd.model.LiteralStatement; import org.obd.model.Node; import org.obd.model.Statement; import org.obd.model.CompositionalDescription.Predicate; import org.obd.model.Node.Metatype; import org.obd.model.vocabulary.TermVocabulary; import org.obo.datamodel.Link; import org.obo.datamodel.OBOClass; import org.obo.util.ReasonerUtil; import org.obo.util.TermUtil; import org.phenoscape.model.Character; import org.phenoscape.model.DataSet; import org.phenoscape.model.Phenotype; import org.phenoscape.model.Specimen; import org.phenoscape.model.State; import org.phenoscape.model.Taxon; import org.purl.obo.vocab.RelationVocabulary; /** * Bridges between phenoscape objects and a model expressed using OBO * primitives. * * OBD Instances and the relations between them generally reflect java instances * of the corresponding phenoscape model. We model cells, states and * matrixes/datasets using instances of CDAO owl classes. We go beyond the * phenoscape model and CDAO in positing an annotation link between the * phenotype and the taxon. The annotation is linked to the cell. * * TODO: reverse mapping TODO: finalize relations and classes; both from OBO_REL * and CDAO TODO: make this subclass a generic bridge framework * * @author cjm * */ public class OBDModelBridge { protected Graph graph; public static String DATASET_TYPE_ID = "cdao:CharacterStateDataMatrix"; public static String STATE_TYPE_ID = "cdao:CharacterStateDomain"; public static String CELL_TYPE_ID = "cdao:CharacterStateDatum"; public static String CHARACTER_TYPE_ID = "cdao:Character"; public static String PUBLICATION_TYPE_ID = "PHENOSCAPE:Publication"; public static String OTU_TYPE_ID = "cdao:TU"; public static String SPECIMEN_TYPE_ID = "PHENOSCAPE:Specimen"; public static String HAS_PUB_REL_ID = "PHENOSCAPE:has_publication"; public static String HAS_SPECIMEN_REL_ID = "PHENOSCAPE:has_specimen"; public static String HAS_STATE_REL_ID = "cdao:has_Datum"; public static String REFERS_TO_TAXON_REL_ID = "PHENOSCAPE:has_taxon"; public static String HAS_TU_REL_ID = "cdao:has_TU"; public static String HAS_CHARACTER_REL_ID = "cdao:has_Character"; public static String HAS_PHENOTYPE_REL_ID = "cdao:has_Phenotype"; public static String TAXON_PHENOTYPE_REL_ID = "PHENOSCAPE:exhibits"; public static String CELL_TO_STATE_REL_ID = "cdao:has_State"; public static String ANNOT_TO_CELL_REL_ID = "PHENOSCAPE:has_source"; public static String SPECIMEN_TO_COLLECTION_REL_ID = "PHENOSCAPE:belongs_to_collection"; public static String SPECIMEN_TO_CATALOG_ID_REL_ID = "PHENOSCAPE:has_catalog_id"; public static String HAS_CURATORS_REL_ID = "PHENOSCAPE:has_curators"; public static String HAS_COMMENT_REL_ID = "PHENOSCAPE:has_comment"; private static final String HAS_NUMBER_REL_ID = "PHENOSCAPE:has_number"; private static TermVocabulary vocab = new TermVocabulary(); private static RelationVocabulary relationVocabulary = new RelationVocabulary(); private Map<Character, String> characterIdMap; private Map<State, String> stateIdMap; private Map<Taxon, String> taxonIdMap; private Map<Phenotype, String> phenotypeIdMap; protected BufferedWriter problemLog; protected Set<LinkStatement> phenotypes; public Graph getGraph() { return graph; } public void setGraph(Graph graph) { this.graph = graph; } public Graph translate(DataSet ds, File dataFile) { String dsId = UUID.randomUUID().toString(); graph = new Graph(); phenotypes = new HashSet<LinkStatement>(); characterIdMap = new HashMap<Character, String>(); stateIdMap = new HashMap<State, String>(); taxonIdMap = new HashMap<Taxon, String>(); phenotypeIdMap = new HashMap<Phenotype, String>(); // Dataset metadata Node dsNode = createInstanceNode(dsId, DATASET_TYPE_ID); String curators = ds.getCurators(); Node pubNode = createInstanceNode(ds.getPublication(), PUBLICATION_TYPE_ID); LinkStatement ds2p = new LinkStatement(dsId, HAS_PUB_REL_ID, pubNode.getId()); graph.addStatement(ds2p); LiteralStatement ds2curators = new LiteralStatement(dsId, HAS_CURATORS_REL_ID, curators); graph.addStatement(ds2curators); for (Taxon t : ds.getTaxa()) { // avoid uploading taxa without names; Cartik1.0 if (t.getValidName() != null && t.getValidName().getName() != null && t.getValidName().getName().length() > 0) { Node tn = translate(t); if (tn.getId() != null) { taxonIdMap.put(t, tn.getId()); String otuId = UUID.randomUUID().toString(); Node otuNode = createInstanceNode(otuId, OTU_TYPE_ID); otuNode.setLabel(t.getValidName().getName()); // link dataset to taxa LinkStatement ds2otu = new LinkStatement(dsId, HAS_TU_REL_ID, otuNode.getId()); graph.addStatement(ds2otu); //link otu to taxon LinkStatement otu2t = new LinkStatement(otuId, REFERS_TO_TAXON_REL_ID, tn.getId()); graph.addStatement(otu2t); //link otu to specimens for(Specimen s : t.getSpecimens()){ //System.out.println(s.toString()); if(s.getCollectionCode() != null){ Node specimenNode = createInstanceNode(s.toString(), SPECIMEN_TYPE_ID); LinkStatement otu2specimen = new LinkStatement(otuId, HAS_SPECIMEN_REL_ID, specimenNode.getId()); graph.addStatement(otu2specimen); //link speciment to collection LinkStatement specimen2collection = new LinkStatement(s.toString(), SPECIMEN_TO_COLLECTION_REL_ID, s.getCollectionCode().getID()); graph.addStatement(specimen2collection); //link specimen to catalog id LinkStatement specimen2catalogId = new LinkStatement(s.toString(), SPECIMEN_TO_CATALOG_ID_REL_ID, s.getCatalogID()); graph.addStatement(specimen2catalogId); } } } } } // link dataset to characters used in that dataset for (Character character : ds.getCharacters()) { // if (character.toString().length() > 0) { int charNumber = ds.getCharacters().indexOf(character) + 1; String cid = UUID.randomUUID().toString(); Node characterNode = createInstanceNode(cid, CHARACTER_TYPE_ID); characterNode.setLabel(character.getLabel()); String charComment = character.getComment(); LiteralStatement chCommentStmt = new LiteralStatement(characterNode.getId(), HAS_COMMENT_REL_ID, charComment); characterNode.addStatement(chCommentStmt); LiteralStatement chNumberStmt = new LiteralStatement(characterNode.getId(), HAS_NUMBER_REL_ID, charNumber + ""); characterNode.addStatement(chNumberStmt); characterIdMap.put(character, cid); LinkStatement ds2c = new LinkStatement(dsId, HAS_CHARACTER_REL_ID, cid); graph.addStatement(ds2c); for (State state : character.getStates()) { String sid = UUID.randomUUID().toString(); Node stateNode = createInstanceNode(sid, STATE_TYPE_ID); stateNode.setLabel(state.getLabel()); String stateComment = state.getComment(); LiteralStatement stCommStmt = new LiteralStatement(stateNode.getId(), HAS_COMMENT_REL_ID, stateComment); stateNode.addStatement(stCommStmt); stateIdMap.put(state, sid); LinkStatement c2s = new LinkStatement(cid, HAS_STATE_REL_ID, sid); graph.addStatement(c2s); for (Phenotype p : state.getPhenotypes()) { // a minimal check: Cartik1.0 if (p.getEntity() != null && p.getQuality() != null) { CompositionalDescription cd = translate(p); if (cd.getId() != null && cd.getId().length() > 0) { phenotypeIdMap.put(p, cd.getId()); LinkStatement s2p = new LinkStatement(sid, HAS_PHENOTYPE_REL_ID, cd.getId()); graph.addStatement(s2p); } } } } } // Matrix -> annotations for (Taxon t : ds.getTaxa()) { for (Character c : ds.getCharacters()) { State state = ds.getStateForTaxon(t, c); if (state == null) { // System.err.println("no state for t:"+t+" char:"+c); continue; } for (Phenotype p : state.getPhenotypes()) { // taxon to phenotype LinkStatement annotLink = new LinkStatement(); if (phenotypeIdMap.get(p) != null && taxonIdMap.get(t) != null) { annotLink.setNodeId(taxonIdMap.get(t)); annotLink.setTargetId(phenotypeIdMap.get(p)); annotLink.setRelationId(TAXON_PHENOTYPE_REL_ID); annotLink.addSubLinkStatement("posited_by", dsId); // link description of biology back to data Node cellNode = createInstanceNode(UUID.randomUUID() .toString(), CELL_TYPE_ID); annotLink.addSubLinkStatement(CELL_TO_STATE_REL_ID, cellNode.getId()); phenotypes.add(annotLink); // cell to state LinkStatement cell2s = new LinkStatement(cellNode.getId(), CELL_TO_STATE_REL_ID, stateIdMap.get(state)); graph.addStatement(cell2s); } } } } for(Statement stmt : phenotypes){ graph.addStatement(stmt); } return graph; } public CompositionalDescription translate(Phenotype p) { OBOClass e = p.getEntity(); OBOClass q = p.getQuality(); OBOClass e2 = p.getRelatedEntity(); OBOClass u = p.getUnit(); Integer count = p.getCount(); Float m = p.getMeasurement(); CompositionalDescription cd = new CompositionalDescription( Predicate.INTERSECTION); cd.addArgument(q.getID()); // check to avoid a NullPointerException if (e.getParents() != null) { cd.addArgument(relationVocabulary.inheres_in(), translateOBOClass(e)); } if (e2 != null) cd.addArgument(relationVocabulary.towards(), translateOBOClass(e2)); if (false) { if (u == null && m != null) { // TODO : throw } if (m != null) { cd.addArgument("has_unit", u.getID()); // cd.addArgument("has_measurement",m); } } cd.setId(cd.generateId()); getGraph().addStatements(cd); return cd; } public CompositionalDescription translateOBOClass(OBOClass c) { if (TermUtil.isIntersection(c)) { CompositionalDescription cd = new CompositionalDescription( Predicate.INTERSECTION); cd.setId(c.getID()); OBOClass g = ReasonerUtil.getGenus(c); cd.addArgument(translateOBOClass(g)); Collection<Link> diffs = ReasonerUtil.getDifferentia(c); for (Link diff : diffs) { cd.addArgument(diff.getType().getID(), translateOBOClass((OBOClass) diff.getParent())); } return cd; } else { CompositionalDescription d = new CompositionalDescription( Predicate.ATOM); d.setNodeId(c.getID()); return d; } } public Node translate(Taxon taxon) { Node n = new Node(taxon.getValidName().getID()); n.setLabel(taxon.getValidName().getName()); graph.addNode(n); return n; } protected Node createInstanceNode(String id, String typeId) { Node n = new Node(id); n.setMetatype(Metatype.CLASS); n.addStatement(new LinkStatement(id, relationVocabulary.instance_of(), typeId)); graph.addNode(n); return n; } }
package org.robockets.robotswitcher; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** Used to get and initialize a SmartDashboard field for a robot number * * @author Jake Backer * @version v.1.sleepy.1.0.ocean.1450230474.7 */ public class Switcher { /** * Holds the value of the SmartDashboard field */ public int currentRobot; /** * Initializes the currentRobot field */ public Switcher() { try{ currentRobot = getRobot(); }catch(DoesNotExistException e){ System.out.println("SmartDashboard field does not exist! Run initRobotNumber()"); } } /** * Stores the value of the field in SmartDashboard in currentRobot * @return The value of currentRobot * @throws DoesNotExistException Thrown if field on SmartDashboard does not exist */ public int getRobot() throws DoesNotExistException{ currentRobot = (int) SmartDashboard.getNumber("RobotNumber"); return currentRobot; } /** * Initializes the field on SmartDashboard TEMPORARY */ public void initRobotNumber() { SmartDashboard.putNumber("RobotNumber", 0); //TEMP } }
package org.subethamail.smtp.util; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; /** * @author Jeff Schnitzer */ public class EmailUtils { /** * @return true if the string is a valid email address */ public static boolean isValidEmailAddress(String address) { // MAIL FROM: <> if (address.length() == 0) return true; boolean result = false; try { InternetAddress[] ia = InternetAddress.parse(address, true); if (ia.length == 0) result = false; else result = true; } catch (AddressException ae) { result = false; } return result; } /** * Extracts the email address within a <> after a specified offset. */ public static String extractEmailAddress(String args, int offset) { String address = args.substring(offset).trim(); if (address.indexOf('<') == 0) { address = address.substring(1, address.indexOf('>')); // spaces within the <> are also possible, Postfix apparently // trims these away: return address.trim(); } // find space (e.g. SIZE argument) int nextarg = address.indexOf(" "); if (nextarg > -1) { address = address.substring(0, nextarg).trim(); } return address; } /** * Normalize the domain-part to lowercase. If email address is missing * an '@' the email is returned as-is. */ public static String normalizeEmail(String email) { int atIndex = email.indexOf('@'); if (atIndex < 0) return email; else return email.substring(0, atIndex) + email.substring(atIndex).toLowerCase(); } }
package org.treetank.pagelayer; import org.treetank.api.IPage; import org.treetank.utils.FastByteArrayReader; import org.treetank.utils.FastByteArrayWriter; public class PageReference { private IPage mPage; private long mStart; private int mLength; private long mChecksum; public PageReference() { this(null, -1L, -1, -1L); } public PageReference(final PageReference pageReference) { this( pageReference.mPage, pageReference.mStart, pageReference.mLength, pageReference.mChecksum); } public PageReference( final IPage page, final long start, final int length, final long checksum) { mPage = page; mStart = start; mLength = length; mChecksum = checksum; } public PageReference(final FastByteArrayReader in) throws Exception { this(null, in.readVarLong(), in.readVarInt(), in.readVarLong()); } public final boolean isInstantiated() { return (mPage != null); } public final boolean isCommitted() { return (mStart != -1L); } public final boolean isDirty() { return (mPage != null || mPage.isDirty()); } public final long getChecksum() { return mChecksum; } public final void setChecksum(final long checksum) { mChecksum = checksum; } public final IPage getPage() { return mPage; } public final void setPage(final IPage page) { mPage = page; } public final int getLength() { return mLength; } public final void setLength(final int length) { mLength = length; } public final long getStart() { return mStart; } public final void setStart(final long start) { mStart = start; } public final void serialize(final FastByteArrayWriter out) throws Exception { out.writeVarLong(mStart); out.writeVarInt(mLength); out.writeVarLong(mChecksum); } @Override public final boolean equals(final Object object) { final PageReference pageReference = (PageReference) object; return ((mChecksum == pageReference.mChecksum) && (mStart == pageReference.mStart) && (mLength == pageReference.mLength)); } @Override public final String toString() { return "start=" + mStart + ", length=" + mLength + ", checksum=" + mChecksum; } }
package org.uct.cs.simplify; import javafx.geometry.BoundingBox; import javafx.geometry.Point3D; import org.apache.commons.cli.*; import org.uct.cs.simplify.ply.header.PLYHeader; import org.uct.cs.simplify.ply.reader.ImprovedPLYReader; import org.uct.cs.simplify.ply.utilities.BoundsFinder; import org.uct.cs.simplify.util.Timer; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; public class ScaleAndRecenter { public static void main(String[] args) throws ParseException { CommandLine cmd = parseArgs(args); int rescaleToSize = (cmd.hasOption("size") ? Integer.parseInt(cmd.getOptionValue("size")) : 1024); String filename = cmd.getOptionValue("filename"); String outputDirectory = cmd.getOptionValue("output"); // checking if (rescaleToSize < 2) throw new IllegalArgumentException("Rescale size must not be smaller than 2 units"); try (Timer ignored = new Timer("Processing")) { File inputFile = new File(filename); // output file stuff File outputDir = new File(new File(outputDirectory).getCanonicalPath()); if (!outputDir.exists() && !outputDir.mkdirs()) throw new IOException("Could not create output directory " + outputDir); File outputFile = new File(outputDir, inputFile.getName() + "_rescaled_" + rescaleToSize + ".ply"); // == construct & setup PLYReader // this scans the target file and works out start and end ranges PLYHeader header = new PLYHeader(inputFile); ImprovedPLYReader reader = new ImprovedPLYReader(header, inputFile); // first have to identify bounds in order to work out ranges and center BoundingBox bb = BoundsFinder.getBoundingBox(reader); Point3D center = new Point3D( (bb.getMinX() + bb.getMaxX()) / 2.0f, (bb.getMinY() + bb.getMaxY()) / 2.0f, (bb.getMinZ() + bb.getMaxZ()) / 2.0f); // mesh size is the maximum axis double meshHalfSize = Math.abs(Math.max(Math.max(bb.getMaxX() - center.getX(), bb.getMaxY() - center.getY()), bb.getMaxZ() - center.getZ())); double scale = (double) (rescaleToSize) / meshHalfSize; Point3D translate = new Point3D(-center.getX(), -center.getY(), -center.getZ()); // debug System.out.println("InputFile: " + inputFile); System.out.println("OutputFile: " + outputFile); System.out.printf("%f → %f\n", bb.getMinX(), bb.getMaxX()); System.out.printf("%f → %f\n", bb.getMinY(), bb.getMaxY()); System.out.printf("%f → %f\n", bb.getMinZ(), bb.getMaxZ()); System.out.printf("center: %f, %f, %f\n", center.getX(), center.getY(), center.getZ()); System.out.printf("rescale ratio: %f\n", scale); // now we need to // 1) navigate to vertex element // 2) for each vertex // 3) read x,y,z floats // 4) transform x,y,z // 5) rewrite // 6) skip ahead // copy first (dataoffset) bytes to destination // for n in vertex_count // read block of bytes // transform xyz // write back into block // write block to destination // write remaining bytes to destination try (RandomAccessFile rafIN = new RandomAccessFile(inputFile, "r")) { try (FileChannel fcIN = rafIN.getChannel()) { try (RandomAccessFile rafOUT = new RandomAccessFile(outputFile, "rw")) { try (FileChannel fcOUT = rafOUT.getChannel()) { // copy beginning long vertexElementBegin = reader.getElementDimension("vertex").getFirst(); long vertexElementLength = reader.getElementDimension("vertex").getSecond(); copyNBytes(fcIN, fcOUT, vertexElementBegin); int blockSize = reader.getHeader().getElement("vertex").getItemSize(); int numVertices = reader.getHeader().getElement("vertex").getCount(); ByteBuffer blockBuffer = ByteBuffer.allocate(blockSize); blockBuffer.order(ByteOrder.LITTLE_ENDIAN); for (int n = 0; n < numVertices; n++) { fcIN.read(blockBuffer); blockBuffer.flip(); fcOUT.write(blockBuffer); blockBuffer.clear(); } // copy remainder long fileRemainder = inputFile.length() - vertexElementBegin - vertexElementLength; copyNBytes(fcIN, fcOUT, fileRemainder); } } } } } catch (IOException e) { e.printStackTrace(); } } private static void copyNBytes(FileChannel input, FileChannel output, long n) throws IOException { if (n == 0) return; int bufsize = 4096; long div = n / bufsize; int rem = (int) (n % bufsize); ByteBuffer temp = ByteBuffer.allocate(bufsize); for (long i = 0; i < div; i++) { input.read(temp); temp.flip(); while (temp.hasRemaining()) output.write(temp); temp.clear(); } temp = ByteBuffer.allocate(rem); input.read(temp); temp.flip(); while (temp.hasRemaining()) output.write(temp); } private static CommandLine parseArgs(String[] args) { CommandLineParser clp = new BasicParser(); Options options = new Options(); Option o1 = new Option("f", "filename", true, "Path to PLY model to process"); o1.setRequired(true); options.addOption(o1); Option o2 = new Option("o", "output", true, "Destination directory of model"); o2.setRequired(true); options.addOption(o2); Option o3 = new Option("s", "size", true, "Scale the model to fit in a cube of this size"); o3.setType(Short.class); options.addOption(o3); try { return clp.parse(options, args); } catch (ParseException e) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("ScaleAndRecenter --filename <path> --output <path> --size <size>", options); System.exit(1); return null; } } }
package org.usfirst.frc.team6662.robot; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.DoubleSolenoid; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.PowerDistributionPanel; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.Victor; import edu.wpi.first.wpilibj.interfaces.Gyro; import edu.wpi.first.wpilibj.CameraServer; import edu.wpi.first.wpilibj.ADXRS450_Gyro; public class Robot extends IterativeRobot { RobotDrive driveTrain = new RobotDrive(0, 1, 2, 3); Joystick joystick = new Joystick(0); PowerDistributionPanel pdp = new PowerDistributionPanel(); Compressor compressor = new Compressor(0); DoubleSolenoid solenoid = new DoubleSolenoid(0, 1); Victor liftMotor = new Victor(4); Gyro gyro; @Override public void robotInit() { gyro = new ADXRS450_Gyro(); compressor.setClosedLoopControl(true); // CameraServer.getInstance().startAutomaticCapture(); } @Override public void autonomousInit() { } @Override public void autonomousPeriodic() { } @Override public void teleopInit() { gyro.calibrate(); } @Override public void testPeriodic() { } }
package org.batfish.grammar.flatjuniper; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.tree.TerminalNode; import org.batfish.grammar.flatjuniper.FlatJuniperCombinedParser; import org.batfish.grammar.flatjuniper.FlatJuniperParser.*; import org.batfish.main.BatfishException; import org.batfish.main.Warnings; import org.batfish.representation.AsPath; import org.batfish.representation.AsSet; import org.batfish.representation.Ip; import org.batfish.representation.IpProtocol; import org.batfish.representation.NamedPort; import org.batfish.representation.Prefix; import org.batfish.representation.RoutingProtocol; import org.batfish.representation.juniper.AggregateRoute; import org.batfish.representation.juniper.BgpGroup; import org.batfish.representation.juniper.CommunityList; import org.batfish.representation.juniper.CommunityListLine; import org.batfish.representation.juniper.Family; import org.batfish.representation.juniper.FirewallFilter; import org.batfish.representation.juniper.FwFrom; import org.batfish.representation.juniper.FwFromDestinationAddress; import org.batfish.representation.juniper.FwFromDestinationPort; import org.batfish.representation.juniper.FwFromProtocol; import org.batfish.representation.juniper.FwFromSourceAddress; import org.batfish.representation.juniper.FwFromSourcePort; import org.batfish.representation.juniper.FwTerm; import org.batfish.representation.juniper.FwThenAccept; import org.batfish.representation.juniper.FwThenDiscard; import org.batfish.representation.juniper.FwThenNextTerm; import org.batfish.representation.juniper.GeneratedRoute; import org.batfish.representation.juniper.Interface; import org.batfish.representation.juniper.IpBgpGroup; import org.batfish.representation.juniper.JuniperVendorConfiguration; import org.batfish.representation.juniper.NamedBgpGroup; import org.batfish.representation.juniper.OspfArea; import org.batfish.representation.juniper.PolicyStatement; import org.batfish.representation.juniper.PrefixList; import org.batfish.representation.juniper.PsFrom; import org.batfish.representation.juniper.PsFromAsPath; import org.batfish.representation.juniper.PsFromColor; import org.batfish.representation.juniper.PsFromCommunity; import org.batfish.representation.juniper.PsFromInterface; import org.batfish.representation.juniper.PsFromPrefixList; import org.batfish.representation.juniper.PsFromProtocol; import org.batfish.representation.juniper.PsFromRouteFilter; import org.batfish.representation.juniper.PsTerm; import org.batfish.representation.juniper.PsThen; import org.batfish.representation.juniper.PsThenAccept; import org.batfish.representation.juniper.PsThenCommunityAdd; import org.batfish.representation.juniper.PsThenCommunityDelete; import org.batfish.representation.juniper.PsThenCommunitySet; import org.batfish.representation.juniper.PsThenLocalPreference; import org.batfish.representation.juniper.PsThenMetric; import org.batfish.representation.juniper.PsThenNextHopIp; import org.batfish.representation.juniper.PsThenReject; import org.batfish.representation.juniper.RouteFilter; import org.batfish.representation.juniper.RouteFilterLine; import org.batfish.representation.juniper.RouteFilterLineExact; import org.batfish.representation.juniper.RouteFilterLineLengthRange; import org.batfish.representation.juniper.RouteFilterLineOrLonger; import org.batfish.representation.juniper.RouteFilterLineThrough; import org.batfish.representation.juniper.RouteFilterLineUpTo; import org.batfish.representation.juniper.RoutingInformationBase; import org.batfish.representation.juniper.RoutingInstance; import org.batfish.representation.juniper.StaticRoute; import org.batfish.representation.juniper.BgpGroup.BgpGroupType; import org.batfish.util.SubRange; public class ConfigurationBuilder extends FlatJuniperParserBaseListener { private static final AggregateRoute DUMMY_AGGREGATE_ROUTE = new AggregateRoute( Prefix.ZERO); private static final BgpGroup DUMMY_BGP_GROUP = new BgpGroup(); private static final StaticRoute DUMMY_STATIC_ROUTE = new StaticRoute( Prefix.ZERO); private static final String F_COMPLEX_POLICY = "boolean combination of policy-statements"; private static final String F_EXTENDED_COMMUNITY = "extended communities"; private static final String F_POLICY_TERM_THEN_NEXT_HOP = "policy-statement - term - then - next-hop"; public static NamedPort getNamedPort(PortContext ctx) { if (ctx.AFS() != null) { return NamedPort.AFS; } else if (ctx.BGP() != null) { return NamedPort.BGP; } else if (ctx.BIFF() != null) { return NamedPort.BIFFudp_OR_EXECtcp; } else if (ctx.BOOTPC() != null) { return NamedPort.BOOTPC; } else if (ctx.BOOTPS() != null) { return NamedPort.BOOTPS_OR_DHCP; } else if (ctx.CMD() != null) { return NamedPort.CMDtcp_OR_SYSLOGudp; } else if (ctx.CVSPSERVER() != null) { return NamedPort.CVSPSERVER; } else if (ctx.DHCP() != null) { return NamedPort.BOOTPS_OR_DHCP; } else if (ctx.DOMAIN() != null) { return NamedPort.DOMAIN; } else if (ctx.EKLOGIN() != null) { return NamedPort.EKLOGIN; } else if (ctx.EKSHELL() != null) { return NamedPort.EKSHELL; } else if (ctx.EXEC() != null) { return NamedPort.BIFFudp_OR_EXECtcp; } else if (ctx.FINGER() != null) { return NamedPort.FINGER; } else if (ctx.FTP() != null) { return NamedPort.FTP; } else if (ctx.FTP_DATA() != null) { return NamedPort.FTP_DATA; } else if (ctx.HTTP() != null) { return NamedPort.HTTP; } else if (ctx.HTTPS() != null) { return NamedPort.HTTPS; } else if (ctx.IDENT() != null) { return NamedPort.IDENT; } else if (ctx.IMAP() != null) { return NamedPort.IMAP; } else if (ctx.KERBEROS_SEC() != null) { return NamedPort.KERBEROS_SEC; } else if (ctx.KLOGIN() != null) { return NamedPort.KLOGIN; } else if (ctx.KPASSWD() != null) { return NamedPort.KPASSWD; } else if (ctx.KRB_PROP() != null) { return NamedPort.KRB_PROP; } else if (ctx.KRBUPDATE() != null) { return NamedPort.KRBUPDATE; } else if (ctx.KSHELL() != null) { return NamedPort.KSHELL; } else if (ctx.LDAP() != null) { return NamedPort.LDAP; } else if (ctx.LDP() != null) { return NamedPort.LDP; } else if (ctx.LOGIN() != null) { return NamedPort.LOGINtcp_OR_WHOudp; } else if (ctx.MOBILEIP_AGENT() != null) { return NamedPort.MOBILE_IP_AGENT; } else if (ctx.MOBILIP_MN() != null) { return NamedPort.MOBILE_IP_MN; } else if (ctx.MSDP() != null) { return NamedPort.MSDP; } else if (ctx.NETBIOS_DGM() != null) { return NamedPort.NETBIOS_DGM; } else if (ctx.NETBIOS_NS() != null) { return NamedPort.NETBIOS_NS; } else if (ctx.NETBIOS_SSN() != null) { return NamedPort.NETBIOS_SSN; } else if (ctx.NFSD() != null) { return NamedPort.NFSD; } else if (ctx.NNTP() != null) { return NamedPort.NNTP; } else if (ctx.NTALK() != null) { return NamedPort.NTALK; } else if (ctx.NTP() != null) { return NamedPort.NTP; } else if (ctx.POP3() != null) { return NamedPort.POP3; } else if (ctx.PPTP() != null) { return NamedPort.PPTP; } else if (ctx.PRINTER() != null) { return NamedPort.LDP; } else if (ctx.RADACCT() != null) { return NamedPort.RADIUS_JUNIPER; } else if (ctx.RADIUS() != null) { return NamedPort.RADIUS_JUNIPER; } else if (ctx.RIP() != null) { return NamedPort.RIP; } else if (ctx.RKINIT() != null) { return NamedPort.RKINIT; } else if (ctx.SMTP() != null) { return NamedPort.SMTP; } else if (ctx.SNMP() != null) { return NamedPort.SNMP; } else if (ctx.SNMPTRAP() != null) { return NamedPort.SNMPTRAP; } else if (ctx.SNPP() != null) { return NamedPort.SNPP; } else if (ctx.SOCKS() != null) { return NamedPort.SOCKS; } else if (ctx.SSH() != null) { return NamedPort.SSH; } else if (ctx.SUNRPC() != null) { return NamedPort.SUNRPC; } else if (ctx.SYSLOG() != null) { return NamedPort.CMDtcp_OR_SYSLOGudp; } else if (ctx.TACACS() != null) { return NamedPort.TACACS; } else if (ctx.TACACS_DS() != null) { return NamedPort.TACACS_DS; } else if (ctx.TALK() != null) { return NamedPort.TALK; } else if (ctx.TELNET() != null) { return NamedPort.TELNET; } else if (ctx.TFTP() != null) { return NamedPort.TFTP; } else if (ctx.TIMED() != null) { return NamedPort.TIMED; } else if (ctx.WHO() != null) { return NamedPort.LOGINtcp_OR_WHOudp; } else if (ctx.XDMCP() != null) { return NamedPort.XDMCP; } else { throw new BatfishException("missing port-number mapping for port: \"" + ctx.getText() + "\""); } } public static int getPortNumber(PortContext ctx) { if (ctx.DEC() != null) { int port = toInt(ctx.DEC()); return port; } else { NamedPort namedPort = getNamedPort(ctx); return namedPort.number(); } } private static long toCommunityLong(Named_communityContext ctx) { if (ctx.NO_ADVERTISE() != null) { return 0xFFFFFF02l; } else { throw new BatfishException( "missing named-community-to-long mapping for: \"" + ctx.getText() + "\""); } } private static Integer toInt(TerminalNode node) { return toInt(node.getSymbol()); } private static int toInt(Token token) { return Integer.parseInt(token.getText()); } private static IpProtocol toIpProtocol(Ip_protocolContext ctx) { if (ctx.DEC() != null) { int protocolNum = toInt(ctx.DEC()); return IpProtocol.fromNumber(protocolNum); } else if (ctx.AH() != null) { return IpProtocol.AHP; } else if (ctx.DSTOPTS() != null) { return IpProtocol.IPv6_Opts; } else if (ctx.EGP() != null) { return IpProtocol.EGP; } else if (ctx.ESP() != null) { return IpProtocol.ESP; } else if (ctx.FRAGMENT() != null) { return IpProtocol.IPv6_Frag; } else if (ctx.GRE() != null) { return IpProtocol.GRE; } else if (ctx.HOP_BY_HOP() != null) { return IpProtocol.HOPOPT; } else if (ctx.ICMP() != null) { return IpProtocol.ICMP; } else if (ctx.ICMP6() != null) { return IpProtocol.IPv6_ICMP; } else if (ctx.ICMPV6() != null) { return IpProtocol.IPv6_ICMP; } else if (ctx.IGMP() != null) { return IpProtocol.IGMP; } else if (ctx.IPIP() != null) { return IpProtocol.IPINIP; } else if (ctx.IPV6() != null) { return IpProtocol.IPv6; } else if (ctx.OSPF() != null) { return IpProtocol.OSPF; } else if (ctx.PIM() != null) { return IpProtocol.PIM; } else if (ctx.RSVP() != null) { return IpProtocol.RSVP; } else if (ctx.SCTP() != null) { return IpProtocol.SCTP; } else if (ctx.TCP() != null) { return IpProtocol.TCP; } else if (ctx.UDP() != null) { return IpProtocol.UDP; } else if (ctx.VRRP() != null) { return IpProtocol.VRRP; } else { throw new BatfishException( "missing protocol-enum mapping for protocol: \"" + ctx.getText() + "\""); } } private static RoutingProtocol toRoutingProtocol(Routing_protocolContext ctx) { if (ctx.AGGREGATE() != null) { return RoutingProtocol.AGGREGATE; } else if (ctx.BGP() != null) { return RoutingProtocol.BGP; } else if (ctx.DIRECT() != null) { return RoutingProtocol.CONNECTED; } else if (ctx.ISIS() != null) { return RoutingProtocol.ISIS; } else if (ctx.LOCAL() != null) { return RoutingProtocol.LOCAL; } else if (ctx.OSPF() != null) { return RoutingProtocol.OSPF; } else if (ctx.STATIC() != null) { return RoutingProtocol.STATIC; } else { throw new BatfishException("missing routing protocol-enum mapping"); } } private JuniperVendorConfiguration _configuration; private AggregateRoute _currentAggregateRoute; private OspfArea _currentArea; private BgpGroup _currentBgpGroup; private CommunityList _currentCommunityList; private FirewallFilter _currentFilter; private Family _currentFirewallFamily; private FwTerm _currentFwTerm; private GeneratedRoute _currentGeneratedRoute; private Interface _currentInterface; private Interface _currentMasterInterface; private Interface _currentOspfInterface; private PolicyStatement _currentPolicyStatement; private PrefixList _currentPrefixList; private PsTerm _currentPsTerm; private Set<PsThen> _currentPsThens; private RoutingInformationBase _currentRib; private RouteFilter _currentRouteFilter; private RouteFilterLine _currentRouteFilterLine; private Prefix _currentRouteFilterPrefix; private RoutingInstance _currentRoutingInstance; private StaticRoute _currentStaticRoute; private FlatJuniperCombinedParser _parser; private final Map<PsTerm, RouteFilter> _termRouteFilters; private final String _text; private final Set<String> _unimplementedFeatures; private final Warnings _w; public ConfigurationBuilder(FlatJuniperCombinedParser parser, String text, Warnings warnings, Set<String> unimplementedFeatures) { _parser = parser; _text = text; _configuration = new JuniperVendorConfiguration(unimplementedFeatures); _currentRoutingInstance = _configuration.getDefaultRoutingInstance(); _termRouteFilters = new HashMap<PsTerm, RouteFilter>(); _unimplementedFeatures = unimplementedFeatures; _w = warnings; } @Override public void enterAt_interface(At_interfaceContext ctx) { String name = ctx.id.name.getText(); String unit = null; if (ctx.id.unit != null) { unit = ctx.id.unit.getText(); } String unitFullName = name + "." + unit; Map<String, Interface> interfaces = _currentRoutingInstance .getInterfaces(); _currentOspfInterface = interfaces.get(name); if (_currentOspfInterface == null) { _currentOspfInterface = new Interface(name); interfaces.put(name, _currentOspfInterface); } if (unit != null) { Map<String, Interface> units = _currentOspfInterface.getUnits(); _currentOspfInterface = units.get(unitFullName); if (_currentOspfInterface == null) { _currentOspfInterface = new Interface(unitFullName); units.put(unitFullName, _currentOspfInterface); } } Ip currentArea = _currentArea.getAreaIp(); Ip interfaceArea = _currentOspfInterface.getOspfArea(); if (interfaceArea != null && !currentArea.equals(interfaceArea)) { throw new BatfishException("Interface assigned to multiple areas"); } _currentOspfInterface.setOspfArea(currentArea); } @Override public void enterBt_group(Bt_groupContext ctx) { String name = ctx.name.getText(); Map<String, NamedBgpGroup> namedBgpGroups = _currentRoutingInstance .getNamedBgpGroups(); NamedBgpGroup namedBgpGroup = namedBgpGroups.get(name); if (namedBgpGroup == null) { namedBgpGroup = new NamedBgpGroup(name); namedBgpGroup.setParent(_currentBgpGroup); namedBgpGroups.put(name, namedBgpGroup); } _currentBgpGroup = namedBgpGroup; } @Override public void enterBt_neighbor(Bt_neighborContext ctx) { if (ctx.IP_ADDRESS() != null) { Ip remoteAddress = new Ip(ctx.IP_ADDRESS().getText()); Map<Ip, IpBgpGroup> ipBgpGroups = _currentRoutingInstance .getIpBgpGroups(); IpBgpGroup ipBgpGroup = ipBgpGroups.get(remoteAddress); if (ipBgpGroup == null) { ipBgpGroup = new IpBgpGroup(remoteAddress); ipBgpGroup.setParent(_currentBgpGroup); ipBgpGroups.put(remoteAddress, ipBgpGroup); } _currentBgpGroup = ipBgpGroup; } else if (ctx.IPV6_ADDRESS() != null) { _currentBgpGroup = DUMMY_BGP_GROUP; } } @Override public void enterFromt_route_filter(Fromt_route_filterContext ctx) { if (ctx.IP_PREFIX() != null) { _currentRouteFilterPrefix = new Prefix(ctx.IP_PREFIX().getText()); _currentRouteFilter = _termRouteFilters.get(_currentPsTerm); if (_currentRouteFilter == null) { String rfName = _currentPolicyStatement.getName() + ":" + _currentPsTerm.getName(); _currentRouteFilter = new RouteFilter(rfName); _termRouteFilters.put(_currentPsTerm, _currentRouteFilter); _configuration.getRouteFilters().put(rfName, _currentRouteFilter); PsFromRouteFilter from = new PsFromRouteFilter(rfName); _currentPsTerm.getFroms().add(from); } } } @Override public void enterFromt_route_filter_then(Fromt_route_filter_thenContext ctx) { RouteFilterLine line = _currentRouteFilterLine; _currentPsThens = line.getThens(); } @Override public void enterFwft_term(Fwft_termContext ctx) { String name = ctx.name.getText(); Map<String, FwTerm> terms = _currentFilter.getTerms(); _currentFwTerm = terms.get(name); if (_currentFwTerm == null) { _currentFwTerm = new FwTerm(name); terms.put(name, _currentFwTerm); } } @Override public void enterFwt_family(Fwt_familyContext ctx) { if (ctx.INET() != null) { _currentFirewallFamily = Family.INET; } else if (ctx.INET6() != null) { _currentFirewallFamily = Family.INET6; } else if (ctx.MPLS() != null) { _currentFirewallFamily = Family.MPLS; } } @Override public void enterFwt_filter(Fwt_filterContext ctx) { String name = ctx.name.getText(); Map<String, FirewallFilter> filters = _configuration.getFirewallFilters(); _currentFilter = filters.get(name); if (_currentFilter == null) { _currentFilter = new FirewallFilter(name, _currentFirewallFamily); filters.put(name, _currentFilter); } } @Override public void enterIt_unit(It_unitContext ctx) { String unit = ctx.num.getText(); String unitFullName = _currentMasterInterface.getName() + "." + unit; Map<String, Interface> units = _currentMasterInterface.getUnits(); _currentInterface = units.get(unitFullName); if (_currentInterface == null) { _currentInterface = new Interface(unitFullName); units.put(unitFullName, _currentInterface); } } @Override public void enterOt_area(Ot_areaContext ctx) { Ip areaIp = new Ip(ctx.area.getText()); Map<Ip, OspfArea> areas = _currentRoutingInstance.getOspfAreas(); _currentArea = areas.get(areaIp); if (_currentArea == null) { _currentArea = new OspfArea(areaIp); areas.put(areaIp, _currentArea); } } @Override public void enterPot_community(Pot_communityContext ctx) { String name = ctx.name.getText(); Map<String, CommunityList> communityLists = _configuration .getCommunityLists(); _currentCommunityList = communityLists.get(name); if (_currentCommunityList == null) { _currentCommunityList = new CommunityList(name); communityLists.put(name, _currentCommunityList); } } @Override public void enterPot_policy_statement(Pot_policy_statementContext ctx) { String name = ctx.name.getText(); Map<String, PolicyStatement> policyStatements = _configuration .getPolicyStatements(); _currentPolicyStatement = policyStatements.get(name); if (_currentPolicyStatement == null) { _currentPolicyStatement = new PolicyStatement(name); policyStatements.put(name, _currentPolicyStatement); } _currentPsTerm = _currentPolicyStatement.getSingletonTerm(); _currentPsThens = _currentPsTerm.getThens(); } @Override public void enterPot_prefix_list(Pot_prefix_listContext ctx) { String name = ctx.name.getText(); Map<String, PrefixList> prefixLists = _configuration.getPrefixLists(); _currentPrefixList = prefixLists.get(name); if (_currentPrefixList == null) { _currentPrefixList = new PrefixList(name); prefixLists.put(name, _currentPrefixList); } } @Override public void enterPst_term(Pst_termContext ctx) { String name = ctx.name.getText(); Map<String, PsTerm> terms = _currentPolicyStatement.getTerms(); _currentPsTerm = terms.get(name); if (_currentPsTerm == null) { _currentPsTerm = new PsTerm(name); terms.put(name, _currentPsTerm); } _currentPsThens = _currentPsTerm.getThens(); } @Override public void enterRibt_aggregate(Ribt_aggregateContext ctx) { if (ctx.IP_PREFIX() != null) { Prefix prefix = new Prefix(ctx.IP_PREFIX().getText()); Map<Prefix, AggregateRoute> aggregateRoutes = _currentRib .getAggregateRoutes(); _currentAggregateRoute = aggregateRoutes.get(prefix); if (_currentAggregateRoute == null) { _currentAggregateRoute = new AggregateRoute(prefix); aggregateRoutes.put(prefix, _currentAggregateRoute); } } else { _currentAggregateRoute = DUMMY_AGGREGATE_ROUTE; } } @Override public void enterRit_named_routing_instance( Rit_named_routing_instanceContext ctx) { String name; name = ctx.name.getText(); _currentRoutingInstance = _configuration.getRoutingInstances().get(name); if (_currentRoutingInstance == null) { _currentRoutingInstance = new RoutingInstance(name); _configuration.getRoutingInstances() .put(name, _currentRoutingInstance); } } @Override public void enterRot_generate(Rot_generateContext ctx) { if (ctx.IP_PREFIX() != null) { Prefix prefix = new Prefix(ctx.IP_PREFIX().getText()); Map<Prefix, GeneratedRoute> generatedRoutes = _currentRib .getGeneratedRoutes(); _currentGeneratedRoute = generatedRoutes.get(prefix); if (_currentGeneratedRoute == null) { _currentGeneratedRoute = new GeneratedRoute(prefix); generatedRoutes.put(prefix, _currentGeneratedRoute); } } } @Override public void enterRot_rib(Rot_ribContext ctx) { String name = ctx.name.getText(); Map<String, RoutingInformationBase> ribs = _currentRoutingInstance .getRibs(); _currentRib = ribs.get(name); if (_currentRib == null) { _currentRib = new RoutingInformationBase(name); ribs.put(name, _currentRib); } } @Override public void enterRst_route(Rst_routeContext ctx) { if (ctx.IP_PREFIX() != null) { Prefix prefix = new Prefix(ctx.IP_PREFIX().getText()); Map<Prefix, StaticRoute> staticRoutes = _currentRib.getStaticRoutes(); _currentStaticRoute = staticRoutes.get(prefix); if (_currentStaticRoute == null) { _currentStaticRoute = new StaticRoute(prefix); staticRoutes.put(prefix, _currentStaticRoute); } } else if (ctx.IPV6_PREFIX() != null) { _currentStaticRoute = DUMMY_STATIC_ROUTE; } } @Override public void enterS_firewall(S_firewallContext ctx) { _currentFirewallFamily = Family.INET; } @Override public void enterS_interfaces(S_interfacesContext ctx) { if (ctx.name == null) { _currentInterface = _currentRoutingInstance.getGlobalMasterInterface(); } else { String ifaceName = ctx.name.getText(); Map<String, Interface> interfaces = _currentRoutingInstance .getInterfaces(); _currentInterface = interfaces.get(ifaceName); if (_currentInterface == null) { _currentInterface = new Interface(ifaceName); interfaces.put(ifaceName, _currentInterface); } } _currentMasterInterface = _currentInterface; } @Override public void enterS_protocols_bgp(S_protocols_bgpContext ctx) { _currentBgpGroup = _currentRoutingInstance.getMasterBgpGroup(); } @Override public void enterS_routing_options(S_routing_optionsContext ctx) { _currentRib = _currentRoutingInstance.getRibs().get( RoutingInformationBase.RIB_IPV4_UNICAST); } @Override public void exitAgt_as_path(Agt_as_pathContext ctx) { AsPath asPath = toAsPath(ctx.path); _currentAggregateRoute.setAsPath(asPath); } @Override public void exitAgt_preference(Agt_preferenceContext ctx) { int preference = toInt(ctx.preference); _currentAggregateRoute.setPreference(preference); } @Override public void exitAit_passive(Ait_passiveContext ctx) { _currentOspfInterface.setOspfPassive(true); } @Override public void exitAt_interface(At_interfaceContext ctx) { _currentOspfInterface = null; } @Override public void exitBt_description(Bt_descriptionContext ctx) { String description = ctx.s_description().description.getText(); _currentBgpGroup.setDescription(description); } @Override public void exitBt_export(Bt_exportContext ctx) { Policy_expressionContext expr = ctx.expr; if (expr.variable() != null) { String name = expr.variable().getText(); _currentBgpGroup.getExportPolicies().add(name); } else { todo(ctx, F_COMPLEX_POLICY); } } @Override public void exitBt_import(Bt_importContext ctx) { Policy_expressionContext expr = ctx.expr; if (expr.variable() != null) { String name = expr.variable().getText(); _currentBgpGroup.getImportPolicies().add(name); } else { todo(ctx, F_COMPLEX_POLICY); } } @Override public void exitBt_local_address(Bt_local_addressContext ctx) { if (ctx.IP_ADDRESS() != null) { Ip localAddress = new Ip(ctx.IP_ADDRESS().getText()); _currentBgpGroup.setLocalAddress(localAddress); } } @Override public void exitBt_local_as(Bt_local_asContext ctx) { int localAs = toInt(ctx.as); _currentBgpGroup.setLocalAs(localAs); } @Override public void exitBt_peer_as(Bt_peer_asContext ctx) { int peerAs = toInt(ctx.as); _currentBgpGroup.setPeerAs(peerAs); } @Override public void exitBt_remove_private(Bt_remove_privateContext ctx) { _currentBgpGroup.setRemovePrivate(true); } @Override public void exitBt_type(Bt_typeContext ctx) { if (ctx.INTERNAL() != null) { _currentBgpGroup.setType(BgpGroupType.INTERNAL); } else if (ctx.EXTERNAL() != null) { _currentBgpGroup.setType(BgpGroupType.EXTERNAL); } } @Override public void exitCt_members(Ct_membersContext ctx) { if (ctx.community_regex() != null) { _currentCommunityList.getLines().add( new CommunityListLine(ctx.community_regex().getText())); } else if (ctx.named_community() != null) { long communityVal = toCommunityLong(ctx.named_community()); String communityStr = org.batfish.util.Util .longToCommunity(communityVal); _currentCommunityList.getLines().add( new CommunityListLine(communityStr)); } else if (ctx.extended_community() != null) { todo(ctx, F_EXTENDED_COMMUNITY); } } @Override public void exitFromt_as_path(Fromt_as_pathContext ctx) { String name = ctx.name.getText(); PsFromAsPath fromAsPath = new PsFromAsPath(name); _currentPsTerm.getFroms().add(fromAsPath); } @Override public void exitFromt_color(Fromt_colorContext ctx) { int color = toInt(ctx.color); PsFromColor fromColor = new PsFromColor(color); _currentPsTerm.getFroms().add(fromColor); } @Override public void exitFromt_community(Fromt_communityContext ctx) { String name = ctx.name.getText(); PsFromCommunity fromCommunity = new PsFromCommunity(name); _currentPsTerm.getFroms().add(fromCommunity); } @Override public void exitFromt_interface(Fromt_interfaceContext ctx) { String name = ctx.id.name.getText(); String unit = null; if (ctx.id.unit != null) { unit = ctx.id.unit.getText(); } String unitFullName = name + "." + unit; Map<String, Interface> interfaces = _currentRoutingInstance .getInterfaces(); Interface iface = interfaces.get(name); if (iface == null) { iface = new Interface(name); interfaces.put(name, iface); } PsFrom from; if (unit != null) { Map<String, Interface> units = iface.getUnits(); iface = units.get(unitFullName); if (iface == null) { iface = new Interface(unitFullName); units.put(unitFullName, iface); } from = new PsFromInterface(unitFullName); } else { from = new PsFromInterface(name); } _currentPsTerm.getFroms().add(from); } @Override public void exitFromt_prefix_list(Fromt_prefix_listContext ctx) { String name = ctx.name.getText(); PsFrom from = new PsFromPrefixList(name); _currentPsTerm.getFroms().add(from); } @Override public void exitFromt_protocol(Fromt_protocolContext ctx) { RoutingProtocol protocol = toRoutingProtocol(ctx.protocol); PsFromProtocol fromProtocol = new PsFromProtocol(protocol); _currentPsTerm.getFroms().add(fromProtocol); } @Override public void exitFromt_route_filter(Fromt_route_filterContext ctx) { _currentRouteFilterPrefix = null; _currentRouteFilter = null; _currentRouteFilterLine = null; } @Override public void exitFromt_route_filter_then(Fromt_route_filter_thenContext ctx) { _currentPsThens = _currentPsTerm.getThens(); } @Override public void exitFwfromt_destination_address( Fwfromt_destination_addressContext ctx) { if (ctx.IP_PREFIX() != null) { Prefix prefix = new Prefix(ctx.IP_PREFIX().getText()); FwFrom from = new FwFromDestinationAddress(prefix); _currentFwTerm.getFroms().add(from); } } @Override public void exitFwfromt_destination_port(Fwfromt_destination_portContext ctx) { if (ctx.port() != null) { int port = getPortNumber(ctx.port()); SubRange subrange = new SubRange(port, port); FwFrom from = new FwFromDestinationPort(subrange); _currentFwTerm.getFroms().add(from); } else if (ctx.range() != null) { for (SubrangeContext subrangeContext : ctx.range().range_list) { int low = toInt(subrangeContext.low); int high = toInt(subrangeContext.high); SubRange subrange = new SubRange(low, high); FwFrom from = new FwFromDestinationPort(subrange); _currentFwTerm.getFroms().add(from); } } } @Override public void exitFwfromt_protocol(Fwfromt_protocolContext ctx) { IpProtocol protocol = toIpProtocol(ctx.ip_protocol()); FwFrom from = new FwFromProtocol(protocol); _currentFwTerm.getFroms().add(from); } @Override public void exitFwfromt_source_address(Fwfromt_source_addressContext ctx) { if (ctx.IP_PREFIX() != null) { Prefix prefix = new Prefix(ctx.IP_PREFIX().getText()); FwFrom from = new FwFromSourceAddress(prefix); _currentFwTerm.getFroms().add(from); } } @Override public void exitFwfromt_source_port(Fwfromt_source_portContext ctx) { if (ctx.port() != null) { int port = getPortNumber(ctx.port()); SubRange subrange = new SubRange(port, port); FwFrom from = new FwFromSourcePort(subrange); _currentFwTerm.getFroms().add(from); } else if (ctx.range() != null) { for (SubrangeContext subrangeContext : ctx.range().range_list) { int low = toInt(subrangeContext.low); int high = toInt(subrangeContext.high); SubRange subrange = new SubRange(low, high); FwFrom from = new FwFromSourcePort(subrange); _currentFwTerm.getFroms().add(from); } } } @Override public void exitFwft_term(Fwft_termContext ctx) { _currentFwTerm = null; } @Override public void exitFwt_filter(Fwt_filterContext ctx) { _currentFilter = null; } @Override public void exitFwthent_accept(Fwthent_acceptContext ctx) { _currentFwTerm.getThens().add(FwThenAccept.INSTANCE); } @Override public void exitFwthent_discard(Fwthent_discardContext ctx) { _currentFwTerm.getThens().add(FwThenDiscard.INSTANCE); } @Override public void exitFwthent_next_term(Fwthent_next_termContext ctx) { _currentFwTerm.getThens().add(FwThenNextTerm.INSTANCE); } @Override public void exitFwthent_reject(Fwthent_rejectContext ctx) { _currentFwTerm.getThens().add(FwThenDiscard.INSTANCE); } @Override public void exitGt_metric(Gt_metricContext ctx) { int metric = toInt(ctx.metric); _currentGeneratedRoute.setMetric(metric); } @Override public void exitGt_policy(Gt_policyContext ctx) { String policy = ctx.policy.getText(); _currentGeneratedRoute.getPolicies().add(policy); } @Override public void exitIfamt_address(Ifamt_addressContext ctx) { Prefix prefix = new Prefix(ctx.IP_PREFIX().getText()); _currentInterface.setPrefix(prefix); } @Override public void exitIfamt_filter(Ifamt_filterContext ctx) { FilterContext filter = ctx.filter(); String name = filter.name.getText(); DirectionContext direction = ctx.filter().direction(); if (direction.INPUT() != null) { _currentInterface.setIncomingFilter(name); } else if (direction.OUTPUT() != null) { _currentInterface.setOutgoingFilter(name); } } @Override public void exitIt_disable(It_disableContext ctx) { _currentInterface.setActive(false); } @Override public void exitIt_enable(It_enableContext ctx) { _currentInterface.setActive(true); } @Override public void exitIt_unit(It_unitContext ctx) { _currentInterface = _currentMasterInterface; } @Override public void exitOt_area(Ot_areaContext ctx) { _currentArea = null; } @Override public void exitOt_export(Ot_exportContext ctx) { String name = ctx.name.getText(); _currentRoutingInstance.getOspfExportPolicies().add(name); } @Override public void exitPlt_network(Plt_networkContext ctx) { Prefix prefix = new Prefix(ctx.network.getText()); _currentPrefixList.getPrefixes().add(prefix); } @Override public void exitPot_community(Pot_communityContext ctx) { _currentCommunityList = null; } @Override public void exitPot_policy_statement(Pot_policy_statementContext ctx) { _currentPolicyStatement = null; } public void exitPot_prefix_list(Pot_prefix_listContext ctx) { _currentPrefixList = null; } @Override public void exitPst_term_tail(Pst_term_tailContext ctx) { _currentPsTerm = null; _currentPsThens = null; } @Override public void exitRft_exact(Rft_exactContext ctx) { if (_currentRouteFilterPrefix != null) { RouteFilterLineExact fromRouteFilterExact = new RouteFilterLineExact( _currentRouteFilterPrefix); _currentRouteFilterLine = _currentRouteFilter .insertLine(fromRouteFilterExact); } } @Override public void exitRft_orlonger(Rft_orlongerContext ctx) { if (_currentRouteFilterPrefix != null) { RouteFilterLineOrLonger fromRouteFilterOrLonger = new RouteFilterLineOrLonger( _currentRouteFilterPrefix); _currentRouteFilterLine = _currentRouteFilter .insertLine(fromRouteFilterOrLonger); } } @Override public void exitRft_prefix_length_range(Rft_prefix_length_rangeContext ctx) { int minPrefixLength = toInt(ctx.low); int maxPrefixLength = toInt(ctx.high); if (_currentRouteFilterPrefix != null) { RouteFilterLineLengthRange fromRouteFilterLengthRange = new RouteFilterLineLengthRange( _currentRouteFilterPrefix, minPrefixLength, maxPrefixLength); _currentRouteFilterLine = _currentRouteFilter .insertLine(fromRouteFilterLengthRange); } } @Override public void exitRft_through(Rft_throughContext ctx) { if (_currentRouteFilterPrefix != null) { Prefix throughPrefix = new Prefix(ctx.IP_PREFIX().getText()); RouteFilterLineThrough fromRouteFilterThrough = new RouteFilterLineThrough( _currentRouteFilterPrefix, throughPrefix); _currentRouteFilterLine = _currentRouteFilter .insertLine(fromRouteFilterThrough); } } @Override public void exitRft_upto(Rft_uptoContext ctx) { int maxPrefixLength = toInt(ctx.high); if (_currentRouteFilterPrefix != null) { RouteFilterLineUpTo fromRouteFilterUpTo = new RouteFilterLineUpTo( _currentRouteFilterPrefix, maxPrefixLength); _currentRouteFilterLine = _currentRouteFilter .insertLine(fromRouteFilterUpTo); } } @Override public void exitRibt_aggregate(Ribt_aggregateContext ctx) { _currentAggregateRoute = null; } @Override public void exitRot_autonomous_system(Rot_autonomous_systemContext ctx) { int as = toInt(ctx.as); _currentRoutingInstance.setAs(as); } @Override public void exitRot_generate(Rot_generateContext ctx) { _currentGeneratedRoute = null; } @Override public void exitRot_router_id(Rot_router_idContext ctx) { Ip id = new Ip(ctx.id.getText()); _currentRoutingInstance.setRouterId(id); } @Override public void exitRot_static(Rot_staticContext ctx) { _currentStaticRoute = null; } @Override public void exitS_firewall(S_firewallContext ctx) { _currentFirewallFamily = null; } @Override public void exitS_interfaces(S_interfacesContext ctx) { _currentInterface = null; _currentMasterInterface = null; } @Override public void exitS_protocols_bgp(S_protocols_bgpContext ctx) { _currentBgpGroup = null; } @Override public void exitS_routing_options(S_routing_optionsContext ctx) { _currentRib = null; } @Override public void exitSrt_discard(Srt_discardContext ctx) { _currentStaticRoute.setDrop(true); } @Override public void exitSrt_reject(Srt_rejectContext ctx) { _currentStaticRoute.setDrop(true); } @Override public void exitSrt_tag(Srt_tagContext ctx) { int tag = toInt(ctx.tag); _currentStaticRoute.setTag(tag); } @Override public void exitSt_host_name(St_host_nameContext ctx) { String hostname = ctx.variable().getText(); _currentRoutingInstance.setHostname(hostname); } @Override public void exitTht_accept(Tht_acceptContext ctx) { _currentPsThens.add(PsThenAccept.INSTANCE); } @Override public void exitTht_community_add(Tht_community_addContext ctx) { String name = ctx.name.getText(); PsThenCommunityAdd then = new PsThenCommunityAdd(name); _currentPsThens.add(then); } @Override public void exitTht_community_delete(Tht_community_deleteContext ctx) { String name = ctx.name.getText(); PsThenCommunityDelete then = new PsThenCommunityDelete(name); _currentPsThens.add(then); } @Override public void exitTht_community_set(Tht_community_setContext ctx) { String name = ctx.name.getText(); PsThenCommunitySet then = new PsThenCommunitySet(name); _currentPsThens.add(then); } @Override public void exitTht_local_preference(Tht_local_preferenceContext ctx) { int localPreference = toInt(ctx.localpref); PsThenLocalPreference then = new PsThenLocalPreference(localPreference); _currentPsThens.add(then); } @Override public void exitTht_metric(Tht_metricContext ctx) { int metric = toInt(ctx.metric); PsThenMetric then = new PsThenMetric(metric); _currentPsThens.add(then); } @Override public void exitTht_next_hop(Tht_next_hopContext ctx) { PsThen then; if (ctx.IP_ADDRESS() != null) { Ip nextHopIp = new Ip(ctx.IP_ADDRESS().getText()); then = new PsThenNextHopIp(nextHopIp); } else { todo(ctx, F_POLICY_TERM_THEN_NEXT_HOP); return; } _currentPsThens.add(then); } @Override public void exitTht_reject(Tht_rejectContext ctx) { _currentPsThens.add(PsThenReject.INSTANCE); } public JuniperVendorConfiguration getConfiguration() { return _configuration; } private AsPath toAsPath(As_path_exprContext path) { AsPath asPath = new AsPath(); for (As_unitContext ctx : path.items) { AsSet asSet = new AsSet(); if (ctx.DEC() != null) { asSet.add(toInt(ctx.DEC())); } else { for (Token token : ctx.as_set().items) { asSet.add(toInt(token)); } } asPath.add(asSet); } return asPath; } private void todo(ParserRuleContext ctx, String feature) { _w.todo(ctx, feature, _parser, _text); _unimplementedFeatures.add("Juniper: " + feature); } }
package nl.idgis.publisher.domain; public final class MessageTypeUtils { private MessageTypeUtils() { } @SuppressWarnings({ "unchecked", "rawtypes" }) public static <T extends MessageType<?>> T valueOf(Class<T> clazz, String name) { if(Enum.class.isAssignableFrom(clazz)) { return (T)Enum.valueOf((Class<Enum>)clazz.asSubclass(Enum.class), name); } try { return clazz.getConstructor(String.class).newInstance(name); } catch(Exception e) { throw new IllegalArgumentException("provided class should be an Enum or should have a public constructor with a String parameter"); } } }
package io.github.benas.randombeans; import io.github.benas.randombeans.api.*; import io.github.benas.randombeans.randomizers.misc.EnumRandomizer; import java.lang.reflect.Field; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Stream; import static io.github.benas.randombeans.util.ReflectionUtils.*; /** * The core implementation of the {@link EnhancedRandom} abstract class. * * @author Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com) */ @SuppressWarnings({ "rawtypes", "unchecked" }) class EnhancedRandomImpl extends EnhancedRandom { private EnhancedRandomParameters parameters; private final FieldPopulator fieldPopulator; private final ArrayPopulator arrayPopulator; private final CollectionPopulator collectionPopulator; private final MapPopulator mapPopulator; private final Map<Class, EnumRandomizer> enumRandomizersByType; private final RandomizerProvider randomizerProvider; private final ObjectFactory objectFactory; private final FieldExclusionChecker fieldExclusionChecker; EnhancedRandomImpl(final Set<RandomizerRegistry> registries) { objectFactory = new ObjectFactory(); randomizerProvider = new RandomizerProvider(registries); arrayPopulator = new ArrayPopulator(this, randomizerProvider); collectionPopulator = new CollectionPopulator(this, objectFactory); mapPopulator = new MapPopulator(this, objectFactory); enumRandomizersByType = new ConcurrentHashMap<>(); fieldPopulator = new FieldPopulator(this, randomizerProvider, arrayPopulator, collectionPopulator, mapPopulator); fieldExclusionChecker = new FieldExclusionChecker(); } @Override public <T> T nextObject(final Class<T> type, final String... excludedFields) { return doPopulateBean(type, new RandomizationContext(parameters, excludedFields)); } @Override public <T> Stream<T> objects(final Class<T> type, final int streamSize, final String... excludedFields) { if (streamSize < 0) { throw new IllegalArgumentException("The stream size must be positive"); } return Stream.generate(() -> nextObject(type, excludedFields)).limit(streamSize); } <T> T doPopulateBean(final Class<T> type, final RandomizationContext context) { T result; try { Randomizer<?> randomizer = randomizerProvider.getRandomizerByType(type); if (randomizer != null) { return (T) randomizer.getRandomValue(); } // Collection types are randomized without introspection for internal fields if (!isIntrospectable(type)) { return randomize(type, context); } // If the type has been already randomized, return one cached instance to avoid recursion. if (context.hasAlreadyRandomizedType(type)) { return (T) context.getPopulatedBean(type); } // create a new instance of the target type result = objectFactory.createInstance(type); // cache instance in the population context context.addPopulatedBean(type, result); // retrieve declared and inherited fields List<Field> fields = getDeclaredFields(result); // we can not use type here, because with classpath scanning enabled the result can be a subtype fields.addAll(getInheritedFields(result.getClass())); // populate fields with random data populateFields(fields, result, context); return result; } catch (InstantiationError | Exception e) { throw new ObjectGenerationException("Unable to generate a random instance of type " + type, e); } } private <T> T randomize(final Class<T> type, final RandomizationContext context) { if (isEnumType(type)) { if (!enumRandomizersByType.containsKey(type)) { enumRandomizersByType.put(type, new EnumRandomizer(type, parameters.getSeed())); } return (T) enumRandomizersByType.get(type).getRandomValue(); } if (isArrayType(type)) { return (T) arrayPopulator.getRandomArray(type, context); } if (isCollectionType(type)) { return (T) collectionPopulator.getEmptyImplementationForCollectionInterface(type); } if (isMapType(type)) { return (T) mapPopulator.getEmptyImplementationForMapInterface(type); } return null; } private <T> void populateFields(final List<Field> fields, final T result, final RandomizationContext context) throws IllegalAccessException { for (final Field field : fields) { populateField(field, result, context); } } private <T> void populateField(final Field field, final T result, final RandomizationContext context) throws IllegalAccessException { if (!fieldExclusionChecker.shouldBeExcluded(field, context)) { if (!parameters.isOverrideDefaultInitialization() && getFieldValue(result, field) != null && !isPrimitiveFieldWithDefaultValue(result, field)) { return; } fieldPopulator.populateField(result, field, context); } } int getRandomCollectionSize() { int minCollectionSize = parameters.getCollectionSizeRange().getMin(); int maxCollectionSize = parameters.getCollectionSizeRange().getMax(); if (minCollectionSize == maxCollectionSize) { return minCollectionSize; } return nextInt((maxCollectionSize - minCollectionSize) + 1) + minCollectionSize; } public void setParameters(EnhancedRandomParameters parameters) { this.parameters = parameters; super.setSeed(parameters.getSeed()); fieldPopulator.setScanClasspathForConcreteTypes(parameters.isScanClasspathForConcreteTypes()); objectFactory.setScanClasspathForConcreteTypes(parameters.isScanClasspathForConcreteTypes()); } }
package com.google.android.apps.remixer; import android.graphics.Color; import android.media.Image; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.TypedValue; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.android.libraries.remixer.BooleanVariableBuilder; import com.google.android.libraries.remixer.Callback; import com.google.android.libraries.remixer.ItemListVariable; import com.google.android.libraries.remixer.RangeVariable; import com.google.android.libraries.remixer.Variable; import com.google.android.libraries.remixer.Remixer; import com.google.android.libraries.remixer.StringVariableBuilder; import com.google.android.libraries.remixer.Trigger; import com.google.android.libraries.remixer.annotation.BooleanVariableMethod; import com.google.android.libraries.remixer.annotation.IntegerListVariableMethod; import com.google.android.libraries.remixer.annotation.RangeVariableMethod; import com.google.android.libraries.remixer.annotation.RemixerBinder; import com.google.android.libraries.remixer.ui.gesture.Direction; import com.google.android.libraries.remixer.ui.view.RemixerFragment; /** * This activity reuses one of the values from variables in MainActivity. */ public class BoxActivity extends AppCompatActivity { // A title text whose text size is set by a variable. private TextView titleText; // An ImageView that does nothing but draw a box with its background color. private ImageView box; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_box); getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Find all UI widgets titleText = (TextView) findViewById(R.id.titleText); box = (ImageView) findViewById(R.id.box); // Initialize the remixer instance RemixerBinder.bind(this); RemixerFragment remixerFragment = RemixerFragment.newInstance(); remixerFragment.attachToGesture(this, Direction.UP, 3); } @RangeVariableMethod( key = "titleTextSize", title = "(Shared) title text size", minValue = 16, maxValue = 72, increment = 4 ) public void setTitleTextSize(Integer size) { titleText.setTextSize(TypedValue.COMPLEX_UNIT_SP, size); } @BooleanVariableMethod(key = "showBox", title = "Show box") void showBox(Boolean show) { box.setVisibility(show ? View.VISIBLE : View.GONE); } @IntegerListVariableMethod( key = "boxColor", title = "Box color", possibleValues = {Color.DKGRAY, Color.LTGRAY, Color.MAGENTA, Color.CYAN}, layoutId = R.layout.color_list_variable_widget ) void setBoxColor(Integer color) { box.setBackgroundColor(color); } }
package net.i2p.router.networkdb.kademlia; import java.util.HashSet; import java.util.List; import java.util.Set; import net.i2p.data.DataStructure; import net.i2p.data.Hash; import net.i2p.data.RouterInfo; import net.i2p.data.i2np.DatabaseLookupMessage; import net.i2p.data.i2np.DatabaseSearchReplyMessage; import net.i2p.data.i2np.DatabaseStoreMessage; import net.i2p.data.i2np.I2NPMessage; import net.i2p.router.JobImpl; import net.i2p.router.MessageSelector; import net.i2p.router.ReplyJob; import net.i2p.router.RouterContext; import net.i2p.router.TunnelInfo; import net.i2p.util.Log; /** * send a netDb lookup to a random floodfill peer - if it is found, great, * but if they reply back saying they dont know it, queue up a store of the * key to a random floodfill peer again (via FloodfillStoreJob) * */ public class FloodfillVerifyStoreJob extends JobImpl { private Log _log; private Hash _key; private Hash _target; private Hash _sentTo; private FloodfillNetworkDatabaseFacade _facade; private long _expiration; private long _sendTime; private long _published; private boolean _isRouterInfo; private MessageWrapper.WrappedMessage _wrappedMessage; private final Set<Hash> _ignore; private static final int START_DELAY = 20*1000; private static final int VERIFY_TIMEOUT = 15*1000; private static final int MAX_PEERS_TO_TRY = 5; /** * Delay a few seconds, then start the verify * @param sentTo who to give the credit or blame to, can be null */ public FloodfillVerifyStoreJob(RouterContext ctx, Hash key, long published, boolean isRouterInfo, Hash sentTo, FloodfillNetworkDatabaseFacade facade) { super(ctx); facade.verifyStarted(key); _key = key; _published = published; _isRouterInfo = isRouterInfo; _log = ctx.logManager().getLog(getClass()); _sentTo = sentTo; _facade = facade; _ignore = new HashSet(MAX_PEERS_TO_TRY); if (sentTo != null) { _ignore.add(_sentTo); } // wait some time before trying to verify the store getTiming().setStartAfter(ctx.clock().now() + START_DELAY); getContext().statManager().createRateStat("netDb.floodfillVerifyOK", "How long a floodfill verify takes when it succeeds", "NetworkDatabase", new long[] { 60*60*1000 }); getContext().statManager().createRateStat("netDb.floodfillVerifyFail", "How long a floodfill verify takes when it fails", "NetworkDatabase", new long[] { 60*60*1000 }); getContext().statManager().createRateStat("netDb.floodfillVerifyTimeout", "How long a floodfill verify takes when it times out", "NetworkDatabase", new long[] { 60*60*1000 }); } public String getName() { return "Verify netdb store"; } /** * Query a random floodfill for the leaseset or routerinfo * that we just stored to a (hopefully different) floodfill peer. * * If it fails (after a timeout period), resend the data. * If the queried data is older than what we stored, that counts as a fail. **/ public void runJob() { _target = pickTarget(); if (_target == null) { _facade.verifyFinished(_key); return; } DatabaseLookupMessage lookup = buildLookup(); if (lookup == null) { _facade.verifyFinished(_key); return; } // If we are verifying a leaseset, use the destination's own tunnels, // to avoid association by the exploratory tunnel OBEP. // Unless it is an encrypted leaseset. TunnelInfo outTunnel; if (_isRouterInfo || getContext().keyRing().get(_key) != null) outTunnel = getContext().tunnelManager().selectOutboundTunnel(); else outTunnel = getContext().tunnelManager().selectOutboundTunnel(_key); if (outTunnel == null) { if (_log.shouldLog(Log.WARN)) _log.warn("No outbound tunnels to verify a store"); _facade.verifyFinished(_key); return; } // garlic encrypt to hide contents from the OBEP RouterInfo peer = _facade.lookupRouterInfoLocally(_target); if (peer == null) { if (_log.shouldLog(Log.WARN)) _log.warn("Fail finding target RI"); _facade.verifyFinished(_key); return; } Hash fromKey; if (_isRouterInfo) fromKey = null; else fromKey = _key; _wrappedMessage = MessageWrapper.wrap(getContext(), lookup, fromKey, peer); if (_wrappedMessage == null) { if (_log.shouldLog(Log.WARN)) _log.warn("Fail Garlic encrypting"); _facade.verifyFinished(_key); return; } I2NPMessage sent = _wrappedMessage.getMessage(); if (_log.shouldLog(Log.INFO)) _log.info("Starting verify (stored " + _key + " to " + _sentTo + "), asking " + _target); _sendTime = getContext().clock().now(); _expiration = _sendTime + VERIFY_TIMEOUT; getContext().messageRegistry().registerPending(new VerifyReplySelector(), new VerifyReplyJob(getContext()), new VerifyTimeoutJob(getContext()), VERIFY_TIMEOUT); getContext().tunnelDispatcher().dispatchOutbound(sent, outTunnel.getSendTunnelId(0), _target); } /** * Pick a responsive floodfill close to the key, but not the one we sent to */ private Hash pickTarget() { Hash rkey = getContext().routingKeyGenerator().getRoutingKey(_key); FloodfillPeerSelector sel = (FloodfillPeerSelector)_facade.getPeerSelector(); List<Hash> peers = sel.selectFloodfillParticipants(rkey, 1, _ignore, _facade.getKBuckets()); if (peers.size() > 0) return peers.get(0); if (_log.shouldLog(Log.WARN)) _log.warn("No other peers to verify floodfill with, using the one we sent to"); return _sentTo; } private DatabaseLookupMessage buildLookup() { // If we are verifying a leaseset, use the destination's own tunnels, // to avoid association by the exploratory tunnel OBEP. // Unless it is an encrypted leaseset. TunnelInfo replyTunnelInfo; if (_isRouterInfo || getContext().keyRing().get(_key) != null) replyTunnelInfo = getContext().tunnelManager().selectInboundTunnel(); else replyTunnelInfo = getContext().tunnelManager().selectInboundTunnel(_key); if (replyTunnelInfo == null) { if (_log.shouldLog(Log.WARN)) _log.warn("No inbound tunnels to get a reply from!"); return null; } DatabaseLookupMessage m = new DatabaseLookupMessage(getContext(), true); m.setMessageExpiration(getContext().clock().now() + VERIFY_TIMEOUT); m.setReplyTunnel(replyTunnelInfo.getReceiveTunnelId(0)); m.setFrom(replyTunnelInfo.getPeer(0)); m.setSearchKey(_key); return m; } private class VerifyReplySelector implements MessageSelector { public boolean continueMatching() { return false; // only want one match } public long getExpiration() { return _expiration; } public boolean isMatch(I2NPMessage message) { if (message instanceof DatabaseStoreMessage) { DatabaseStoreMessage dsm = (DatabaseStoreMessage)message; return _key.equals(dsm.getKey()); } else if (message instanceof DatabaseSearchReplyMessage) { DatabaseSearchReplyMessage dsrm = (DatabaseSearchReplyMessage)message; return _key.equals(dsrm.getSearchKey()); } return false; } } private class VerifyReplyJob extends JobImpl implements ReplyJob { private I2NPMessage _message; public VerifyReplyJob(RouterContext ctx) { super(ctx); } public String getName() { return "Handle floodfill verification reply"; } public void runJob() { long delay = getContext().clock().now() - _sendTime; if (_wrappedMessage != null) _wrappedMessage.acked(); _facade.verifyFinished(_key); if (_message instanceof DatabaseStoreMessage) { // Verify it's as recent as the one we sent boolean success = false; DatabaseStoreMessage dsm = (DatabaseStoreMessage)_message; if (_isRouterInfo && dsm.getValueType() == DatabaseStoreMessage.KEY_TYPE_ROUTERINFO) success = dsm.getRouterInfo().getPublished() >= _published; else if ((!_isRouterInfo) && dsm.getValueType() == DatabaseStoreMessage.KEY_TYPE_LEASESET) success = dsm.getLeaseSet().getEarliestLeaseDate() >= _published; if (success) { // store ok, w00t! getContext().profileManager().dbLookupSuccessful(_target, delay); if (_sentTo != null) getContext().profileManager().dbStoreSuccessful(_sentTo); getContext().statManager().addRateData("netDb.floodfillVerifyOK", delay, 0); if (_log.shouldLog(Log.INFO)) _log.info("Verify success for " + _key); return; } if (_log.shouldLog(Log.WARN)) _log.warn("Verify failed (older) for " + _key); if (_log.shouldLog(Log.INFO)) _log.info("Rcvd older lease: " + dsm.getLeaseSet()); } else if (_message instanceof DatabaseSearchReplyMessage) { // assume 0 old, all new, 0 invalid, 0 dup getContext().profileManager().dbLookupReply(_target, 0, ((DatabaseSearchReplyMessage)_message).getNumReplies(), 0, 0, delay); if (_log.shouldLog(Log.WARN)) _log.warn("Verify failed (DSRM) for " + _key); } // store failed, boo, hiss! // For now, blame the sent-to peer, but not the verify peer if (_sentTo != null) getContext().profileManager().dbStoreFailed(_sentTo); getContext().statManager().addRateData("netDb.floodfillVerifyFail", delay, 0); resend(); } public void setMessage(I2NPMessage message) { _message = message; } } /** * the netDb store failed to verify, so resend it to a random floodfill peer * Fixme - since we now store closest-to-the-key, this is likely to store to the * very same ff as last time, until the stats get bad enough to switch. * Therefore, pass the failed ff through as a don't-store-to. * Let's also add the one we just tried to verify with, as they could be a pair of no-flooders. * So at least we'll try THREE ffs round-robin if things continue to fail... */ private void resend() { DataStructure ds; if (_isRouterInfo) ds = _facade.lookupRouterInfoLocally(_key); else ds = _facade.lookupLeaseSetLocally(_key); if (ds != null) { Set<Hash> toSkip = new HashSet(2); if (_sentTo != null) toSkip.add(_sentTo); if (_target != null) toSkip.add(_target); _facade.sendStore(_key, ds, null, null, FloodfillNetworkDatabaseFacade.PUBLISH_TIMEOUT, toSkip); } } private class VerifyTimeoutJob extends JobImpl { public VerifyTimeoutJob(RouterContext ctx) { super(ctx); } public String getName() { return "Floodfill verification timeout"; } public void runJob() { if (_wrappedMessage != null) _wrappedMessage.fail(); // Only blame the verify peer getContext().profileManager().dbLookupFailed(_target); //if (_sentTo != null) // getContext().profileManager().dbStoreFailed(_sentTo); getContext().statManager().addRateData("netDb.floodfillVerifyTimeout", getContext().clock().now() - _sendTime, 0); if (_log.shouldLog(Log.WARN)) _log.warn("Verify timed out for: " + _key); if (_ignore.size() < MAX_PEERS_TO_TRY) { // Don't resend, simply rerun FVSJ.this inline and // chose somebody besides _target for verification _ignore.add(_target); FloodfillVerifyStoreJob.this.runJob(); } else { _facade.verifyFinished(_key); resend(); } } } }
package net.runelite.client.plugins.agility; import com.google.common.collect.ImmutableMap; import java.util.Map; import lombok.Getter; import net.runelite.api.coords.WorldPoint; enum Courses { GNOME(86.5, 46, 9781), DRAYNOR(120.0, 79, 12338), AL_KHARID(180.0, 30, 13105, new WorldPoint(3299, 3194, 0)), PYRAMID(722.0, 300, 13356, new WorldPoint(3364, 2830, 0)), VARROCK(238.0, 125, 12853), PENGUIN(540.0, 65, 10559), BARBARIAN(139.5, 60, 10039), CANIFIS(240.0, 175, 13878), APE_ATOLL(580.0, 300, 11050), FALADOR(440, 180, 12084), WILDERNESS(571.0, 499, 11837), WEREWOLF(730.0, 380, 14234), SEERS(570.0, 435, 10806), POLLNIVNEACH(890.0, 540, 13358), RELLEKA(780.0, 475, 10553), PRIFDDINAS(1199.0, 1037, 12895), ARDOUGNE(793.0, 529, 10547); private final static Map<Integer, Courses> coursesByRegion; @Getter private final double totalXp; @Getter private final int lastObstacleXp; @Getter private final int regionId; @Getter private final WorldPoint[] courseEndWorldPoints; static { ImmutableMap.Builder<Integer, Courses> builder = new ImmutableMap.Builder<>(); for (Courses course : values()) { builder.put(course.regionId, course); } coursesByRegion = builder.build(); } Courses(double totalXp, int lastObstacleXp, int regionId, WorldPoint... courseEndWorldPoints) { this.totalXp = totalXp; this.lastObstacleXp = lastObstacleXp; this.regionId = regionId; this.courseEndWorldPoints = courseEndWorldPoints; } static Courses getCourse(int regionId) { return coursesByRegion.get(regionId); } }
package net.runelite.client.plugins.corp; import com.google.inject.Provides; import java.util.HashSet; import java.util.Set; import javax.inject.Inject; import lombok.AccessLevel; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import net.runelite.api.Actor; import net.runelite.api.ChatMessageType; import net.runelite.api.Client; import net.runelite.api.GameState; import net.runelite.api.NPC; import net.runelite.api.NpcID; import net.runelite.api.Varbits; import net.runelite.api.events.GameStateChanged; import net.runelite.api.events.HitsplatApplied; import net.runelite.api.events.InteractingChanged; import net.runelite.api.events.NpcDespawned; import net.runelite.api.events.NpcSpawned; import net.runelite.api.events.VarbitChanged; import net.runelite.client.chat.ChatColorType; import net.runelite.client.chat.ChatMessageBuilder; import net.runelite.client.chat.ChatMessageManager; import net.runelite.client.chat.QueuedMessage; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.ui.overlay.OverlayManager; @PluginDescriptor( name = "Corporeal Beast", description = "Show damage statistics and highlight dark energy cores", tags = {"bosses", "combat", "pve", "overlay"} ) @Slf4j public class CorpPlugin extends Plugin { @Getter(AccessLevel.PACKAGE) private NPC corp; @Getter(AccessLevel.PACKAGE) private NPC core; private int yourDamage; @Getter(AccessLevel.PACKAGE) private int totalDamage; @Getter(AccessLevel.PACKAGE) private final Set<Actor> players = new HashSet<>(); @Inject private Client client; @Inject private ChatMessageManager chatMessageManager; @Inject private OverlayManager overlayManager; @Inject private CorpDamageOverlay corpOverlay; @Inject private CoreOverlay coreOverlay; @Provides CorpConfig getConfig(ConfigManager configManager) { return configManager.getConfig(CorpConfig.class); } @Override protected void startUp() throws Exception { overlayManager.add(corpOverlay); overlayManager.add(coreOverlay); } @Override protected void shutDown() throws Exception { overlayManager.remove(corpOverlay); overlayManager.remove(coreOverlay); corp = core = null; yourDamage = 0; totalDamage = 0; players.clear(); } @Subscribe public void onGameStateChanged(GameStateChanged gameStateChanged) { if (gameStateChanged.getGameState() == GameState.LOADING) { players.clear(); } } @Subscribe public void onNpcSpawned(NpcSpawned npcSpawned) { NPC npc = npcSpawned.getNpc(); switch (npc.getId()) { case NpcID.CORPOREAL_BEAST: log.debug("Corporeal beast spawn: {}", npc); corp = npc; yourDamage = 0; totalDamage = 0; players.clear(); break; case NpcID.DARK_ENERGY_CORE: core = npc; break; } } @Subscribe public void onNpcDespawned(NpcDespawned npcDespawned) { NPC npc = npcDespawned.getNpc(); if (npc == corp) { log.debug("Corporeal beast despawn: {}", npc); corp = null; players.clear(); if (npc.isDead()) { // Show kill stats String message = new ChatMessageBuilder() .append(ChatColorType.NORMAL) .append("Corporeal Beast: Your damage: ") .append(ChatColorType.HIGHLIGHT) .append(Integer.toString(yourDamage)) .append(ChatColorType.NORMAL) .append(", Total damage: ") .append(ChatColorType.HIGHLIGHT) .append(Integer.toString(totalDamage)) .build(); chatMessageManager.queue(QueuedMessage.builder() .type(ChatMessageType.CONSOLE) .runeLiteFormattedMessage(message) .build()); } } else if (npc == core) { core = null; } } @Subscribe public void onHitsplatApplied(HitsplatApplied hitsplatApplied) { Actor actor = hitsplatApplied.getActor(); if (actor != corp) { return; } totalDamage += hitsplatApplied.getHitsplat().getAmount(); } @Subscribe public void onInteractingChanged(InteractingChanged interactingChanged) { Actor source = interactingChanged.getSource(); Actor target = interactingChanged.getTarget(); if (corp == null || target != corp) { return; } players.add(source); } @Subscribe public void onVarbitChanged(VarbitChanged varbitChanged) { if (corp != null) { int myDamage = client.getVar(Varbits.CORP_DAMAGE); // avoid resetting our counter when the client's is reset if (myDamage > 0) { yourDamage = myDamage; } } } }
package com.yxkang.android.sample.service; import android.Manifest; import android.app.IntentService; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.os.Build; import android.provider.MediaStore; import android.support.v4.app.ActivityCompat; import android.util.Log; import com.yxkang.android.sample.bean.MessageEvent; import org.greenrobot.eventbus.EventBus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * An {@link IntentService} subclass for handling asynchronous task requests in * a service on a separate handler thread. * <p/> */ public class MediaModifyService extends IntentService { public static final String FULL_MODE = "FullMode"; private final ArrayList<AudioInfo> audioInfos = new ArrayList<>(); private static final String TAG = MediaModifyService.class.getSimpleName(); private static final Pattern MUSIC_FILE_PATTERN = Pattern.compile("^([^;\\[]]+)(\\[[a-zA-Z0-9]+])?.(flac|ape|mp3|aac|wma|ogg|wav)$"); private static final Logger logger = LoggerFactory.getLogger(MediaModifyService.class); boolean hasWritePermission = false; public MediaModifyService() { super("MediaModifyService"); } @Override public void onCreate() { super.onCreate(); hasWritePermission = (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED); } @Override protected void onHandleIntent(Intent intent) { if (intent != null) { if (intent.getBooleanExtra(FULL_MODE, false)) { loadMediaInfoFull(); } else { loadMediaInfo(); } } } private void loadMediaInfo() { ContentResolver resolver = getContentResolver(); Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER); if (cursor != null) { while (cursor.moveToNext()) { String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)); String display_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)); String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)); Log.i(TAG, "loadMediaInfo: " + display_name + "/" + title); if ((!display_name.contains(title) || (title.contains(";") | title.contains("[") | title.contains("]")))) { String _title = parseTitle(display_name); if (!_title.equals(title)) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || hasWritePermission) { logger.debug("{}/{}", display_name, title); } else { Log.d(TAG, "loadMediaInfo: " + display_name + "/" + title); } title = _title; AudioInfo info = new AudioInfo(); info.data = data; info.title = title; info.display_name = display_name; audioInfos.add(info); } } } cursor.close(); } if (audioInfos.size() > 0) { modifyMediaInfo(); } else { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || hasWritePermission) { logger.info("no need to modify media information"); } else { Log.v(TAG, "no need to modify media information"); } } EventBus.getDefault().post(new MessageEvent(MessageEvent.MODIFY_MEDIA_COMPLETE)); } private String parseTitle(String displayName) { int end = displayName.lastIndexOf("["); if (end == -1) { end = displayName.lastIndexOf("."); } return displayName.substring(0, end).trim(); } private void modifyMediaInfo() { ContentResolver resolver = getContentResolver(); for (AudioInfo info : audioInfos) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || hasWritePermission) { logger.info("modifyMediaInfo: {}/{}", info.display_name, info.title); } else { Log.i(TAG, "modifyMediaInfo: " + info.display_name + "/" + info.title); } String where = MediaStore.Audio.Media.DATA + "=? and " + MediaStore.Audio.Media.DISPLAY_NAME + "=?"; String[] selectionArgs = new String[]{info.data, info.display_name}; ContentValues values = new ContentValues(); values.put(MediaStore.Audio.Media.TITLE, info.title); int updated = resolver.update(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values, where, selectionArgs); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || hasWritePermission) { logger.debug("modifyMediaInfo: updated = {}", updated); } else { Log.d(TAG, "modifyMediaInfo: updated = " + updated); } } audioInfos.clear(); } private void loadMediaInfoFull() { ContentResolver resolver = getContentResolver(); Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER); if (cursor != null) { while (cursor.moveToNext()) { String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)); String display_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME)); String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || hasWritePermission) { logger.info("{}/{}", display_name, title); } else { Log.i(TAG, "loadMediaInfoFull: " + display_name + "/" + title); } title = parseTitleFull(display_name); AudioInfo info = new AudioInfo(); info.data = data; info.title = title; info.display_name = display_name; audioInfos.add(info); } cursor.close(); } modifyMediaInfo(); EventBus.getDefault().post(new MessageEvent(MessageEvent.MODIFY_MEDIA_COMPLETE)); } private String parseTitleFull(String displayName) { Matcher matcher = MUSIC_FILE_PATTERN.matcher(displayName); if (matcher.matches()) { Log.i(TAG, "parseTitleFull: group0 = " + matcher.group(0)); Log.i(TAG, "parseTitleFull: group1 = " + matcher.group(1)); return matcher.group(1); } else { int end = displayName.lastIndexOf("["); if (end == -1) { end = displayName.lastIndexOf("."); } return displayName.substring(0, end).trim(); } } private static class AudioInfo { String data; String display_name; String title; } }
package com.github.basking2.sdsai.marchinesquares; public class Tile { /** * A tile of -1, 0, or 1 values. A value of -1 means the cell is below * the threshold. A value of 0 means it is at the threshold. A value of 1 * means the cell is above the threshold. */ final public byte[] tile; /** * An array of {@link IsobandContours} that is populated when {@link #isoband()} is run. * * This is one column and one row smaller than the {@link #tile} array. * That is to say, it is {@code width+1} elements shorter. * When read as a two-dimensional tile the stride (the width) is {@code width-1}. */ final public IsobandContours[] contours; /** * How wide is each row in the tile. */ final public int width; public Tile(final byte[] tile, final int width) { this.tile = tile; this.width = width; this.contours = new IsobandContours[tile.length - width - 1]; } /** * Build and attach {@link IsobandContours} for all cells. * * Note this does not define contours for the right and bottom edge as that is * left for tile joining. */ public void isoband() { final int W = width - 1; final int H = tile.length / width - 1; // Populate the contours array. for (int h = 0; h < H; h++) { for (int w = 0; w < W; w++) { this.contours[h * W + w] = new IsobandContours( tile[h * width + w], tile[h * width + w + 1], tile[h * width + width + w + 1], tile[h * width + width + w] ); } } } }
package com.cloud.cluster.agentlb; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.HostDao; import com.cloud.utils.component.Inject; @Local(value=AgentLoadBalancerPlanner.class) public class ClusterBasedAgentLoadBalancerPlanner implements AgentLoadBalancerPlanner{ private static final Logger s_logger = Logger.getLogger(AgentLoadBalancerPlanner.class); private String _name; @Inject HostDao _hostDao = null; @Override public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { _name = name; return true; } @Override public String getName() { return _name; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } @Override public List<HostVO> getHostsToRebalance(long msId, int avLoad) { List<HostVO> allHosts = _hostDao.listByManagementServer(msId); if (allHosts.size() <= avLoad) { s_logger.debug("Agent load = " + allHosts.size() + " for management server " + msId + " doesn't exceed average system agent load = " + avLoad + "; so it doesn't participate in agent rebalancing process"); return null; } List<HostVO> directHosts = _hostDao.listDirectHostsBy(msId, Status.Up); if (directHosts.isEmpty()) { s_logger.debug("No direct agents in status " + Status.Up + " exist for the management server " + msId + "; so it doesn't participate in agent rebalancing process"); return null; } Map<Long, List<HostVO>> hostToClusterMap = new HashMap<Long, List<HostVO>>(); for (HostVO directHost : directHosts) { Long clusterId = directHost.getClusterId(); List<HostVO> directHostsPerCluster = null; if (!hostToClusterMap.containsKey(clusterId)) { directHostsPerCluster = new ArrayList<HostVO>(); } else { directHostsPerCluster = hostToClusterMap.get(clusterId); } directHostsPerCluster.add(directHost); hostToClusterMap.put(clusterId, directHostsPerCluster); } hostToClusterMap = sortByClusterSize(hostToClusterMap); int hostsToGive = allHosts.size() - avLoad; int hostsLeftToGive = hostsToGive; int hostsLeft = directHosts.size(); List<HostVO> hostsToReturn = new ArrayList<HostVO>(); for (Long cluster : hostToClusterMap.keySet()) { List<HostVO> hostsInCluster = hostToClusterMap.get(cluster); hostsLeft = hostsLeft - hostsInCluster.size(); if (hostsToReturn.size() < hostsToGive) { s_logger.debug("Trying cluster id=" + cluster); if (hostsInCluster.size() > hostsLeftToGive) { if (hostsLeft >= hostsLeftToGive) { s_logger.debug("Skipping cluster id=" + cluster + " as it has more hosts that we need: " + hostsInCluster.size() + " vs " + hostsLeftToGive); continue; } else { //get all hosts that are needed from the cluster s_logger.debug("Taking " + hostsLeftToGive + " from cluster " + cluster); for (int i=0; i < hostsLeftToGive; i++) { hostsToReturn.add(hostsInCluster.get(i)); } break; } } else { s_logger.debug("Taking all " + hostsInCluster.size() + " hosts: " + hostsInCluster + " from cluster id=" + cluster); hostsToReturn.addAll(hostsInCluster); hostsLeftToGive = hostsLeftToGive - hostsInCluster.size(); } } else { break; } } return hostsToReturn; } public static LinkedHashMap<Long, List<HostVO>> sortByClusterSize(final Map<Long, List<HostVO>> hostToClusterMap) { List<Long> keys = new ArrayList<Long>(); keys.addAll(hostToClusterMap.keySet()); Collections.sort(keys, new Comparator<Long>() { @Override public int compare(Long o1, Long o2) { List<HostVO> v1 = hostToClusterMap.get(o1); List<HostVO> v2 = hostToClusterMap.get(o2); if (v1 == null) { return (v2 == null) ? 0 : 1; } if (v1.size() < v2.size()) { return 1; } else { return 0; } } }); LinkedHashMap<Long, List<HostVO>> sortedMap = new LinkedHashMap<Long, List<HostVO>>(); for (Long key : keys) { sortedMap.put(key, hostToClusterMap.get(key)); } return sortedMap; } }
package de.fau.amos.virtualledger.server.api; import de.fau.amos.virtualledger.dtos.StringApiModel; import de.fau.amos.virtualledger.server.auth.AuthenticationController; import de.fau.amos.virtualledger.server.auth.VirtualLedgerAuthenticationException; import de.fau.amos.virtualledger.server.factories.StringApiModelFactory; import de.fau.amos.virtualledger.server.model.UserCredential; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.lang.invoke.MethodHandles; /** * Endpoints for authentication / authorization */ @RestController public class AuthApiEndpoint { private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private AuthenticationController authenticationController; private StringApiModelFactory stringApiModelFactory; @Autowired public AuthApiEndpoint(AuthenticationController authenticationController, StringApiModelFactory stringApiModelFactory) { this.authenticationController = authenticationController; this.stringApiModelFactory = stringApiModelFactory; } protected AuthApiEndpoint() { } /** * Endpoint for registering a new user. Parameters must not be null or * empty, id has to be null or 0. * @param credential * @return */ @RequestMapping(method = RequestMethod.POST, value = "api/auth/register", produces = "application/json", consumes = "application/json") public ResponseEntity<?> registerEndpoint(@RequestBody UserCredential credential) { if (credential.getEmail() == null || credential.getEmail().isEmpty() || credential.getPassword() == null || credential.getPassword().isEmpty() || credential.getFirstname() == null || credential.getFirstname().isEmpty() || credential.getLastname() == null || credential.getLastname().isEmpty() || credential.getId() != 0) { return new ResponseEntity<>( "Please check your inserted values. None of the parameters must be null or empty, id has to be 0.", HttpStatus.BAD_REQUEST); } LOGGER.info("Registration for " + credential.getEmail() + " was requested."); throw new NotImplementedException(); //return this.register(credential); } /** * Does the logic operation for registering the user. Also does exception * handling. * @param credential * @return a response with status code depending on result */ private ResponseEntity<?> register(UserCredential credential) { String responseMsg; try { responseMsg = authenticationController.register(credential); } catch (VirtualLedgerAuthenticationException ex) { LOGGER.error("", ex); return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST); } StringApiModel responseObj = stringApiModelFactory.createStringApiModel(responseMsg); return new ResponseEntity<>(responseObj, HttpStatus.OK); } }
package io.spine.server.integration; import com.google.common.base.MoreObjects; import com.google.common.collect.ImmutableSet; import io.spine.core.BoundedContextId; import io.spine.core.Rejection; import io.spine.core.RejectionClass; import io.spine.core.RejectionEnvelope; import io.spine.protobuf.AnyPacker; import io.spine.server.rejection.RejectionSubscriber; import java.util.Objects; import java.util.Set; /** * A subscriber to local {@code RejectionBus}, which publishes each matching message to * a remote channel. * * <p>The messages to subscribe are those that are required by external application components * at this moment; their set is determined by the {@linkplain RequestForExternalMessages * configuration messages}, received by this instance of {@code IntegrationBus}. */ final class LocalRejectionSubscriber extends RejectionSubscriber { private final BoundedContextId boundedContextId; private final TransportFactory.PublisherHub publisherHub; private final Set<RejectionClass> rejectionClasses; LocalRejectionSubscriber(BoundedContextId boundedContextId, TransportFactory.PublisherHub publisherHub, RejectionClass rejectionClass) { super(); this.boundedContextId = boundedContextId; this.publisherHub = publisherHub; this.rejectionClasses = ImmutableSet.of(rejectionClass); } @SuppressWarnings("ReturnOfCollectionOrArrayField") // Returning an immutable impl. @Override public Set<RejectionClass> getMessageClasses() { return rejectionClasses; } @Override public Set<String> dispatch(RejectionEnvelope envelope) { final Rejection rejection = envelope.getOuterObject(); final ExternalMessage message = ExternalMessages.of(rejection, boundedContextId); final ExternalMessageClass messageClass = ExternalMessageClass.of(envelope.getMessageClass()); final TransportFactory.Publisher channel = publisherHub.get(messageClass); channel.publish(AnyPacker.pack(envelope.getId()), message); return ImmutableSet.of(channel.toString()); } @SuppressWarnings("DuplicateStringLiteralInspection") @Override public String toString() { return MoreObjects.toStringHelper(this) .add("boundedContextId", boundedContextId) .add("rejectionClasses", rejectionClasses) .toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LocalRejectionSubscriber that = (LocalRejectionSubscriber) o; return Objects.equals(boundedContextId, that.boundedContextId) && Objects.equals(rejectionClasses, that.rejectionClasses); } @Override public int hashCode() { return Objects.hash(boundedContextId, rejectionClasses); } }
package com.gdn.x.beirut.services; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.hibernate.Hibernate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.gdn.common.base.domainevent.publisher.DomainEventPublisher; import com.gdn.common.base.mapper.GdnMapper; import com.gdn.common.enums.ErrorCategory; import com.gdn.common.exception.ApplicationException; import com.gdn.x.beirut.dao.CandidateDAO; import com.gdn.x.beirut.dao.PositionDAO; import com.gdn.x.beirut.domain.event.model.CandidateNewInsert; import com.gdn.x.beirut.domain.event.model.DomainEventName; import com.gdn.x.beirut.entities.Candidate; import com.gdn.x.beirut.entities.CandidateDetail; import com.gdn.x.beirut.entities.CandidatePosition; import com.gdn.x.beirut.entities.Position; import com.gdn.x.beirut.entities.Status; import com.gdn.x.beirut.entities.StatusLog; @Service(value = "candidateService") @Transactional(readOnly = true) public class CandidateServiceImpl implements CandidateService { public static final String ID_SHOULD_NOT_BE_EMPTY = "id should not be empty"; private static final Logger LOG = LoggerFactory.getLogger(CandidateServiceImpl.class); @Autowired private CandidateDAO candidateDAO; @Autowired private PositionDAO positionDAO; @Autowired private DomainEventPublisher domainEventPublisher; @Autowired private GdnMapper gdnMapper; @Override @Transactional(readOnly = false) public Candidate applyNewPosition(String candidateId, List<String> positionIds) throws Exception { Candidate existingCandidate = getCandidate(candidateId); List<Position> positions = positionDAO.findAll(positionIds); for (Position position : positions) { existingCandidate.getCandidatePositions() .add(new CandidatePosition(existingCandidate, position, existingCandidate.getStoreId())); } return candidateDAO.save(existingCandidate); } @Override @Transactional(readOnly = false) public Candidate createNew(Candidate candidate, List<String> positionIds) throws Exception { List<Position> positions = positionDAO.findAll(positionIds); candidate.setCandidatePositions(new ArrayList<CandidatePosition>()); if (positions == null || positions.size() == 0) { throw new ApplicationException(ErrorCategory.DATA_NOT_FOUND, "position not found"); } if (positionIds == null || positionIds.size() == 0) { throw new ApplicationException(ErrorCategory.REQUIRED_PARAMETER, "position id must not empty"); } for (Position position : positions) { candidate.getCandidatePositions() .add(new CandidatePosition(candidate, position, candidate.getStoreId())); } try { List<CandidatePosition> candidatePositions = candidate.getCandidatePositions(); Candidate newCandidate = candidateDAO.save(candidate); for (Position position : positions) { CandidateNewInsert candidateNewInsert = new CandidateNewInsert(); BeanUtils.copyProperties(newCandidate, candidateNewInsert, "candidateDetail", "candidatePositions"); BeanUtils.copyProperties(position, candidateNewInsert, "candidatePositions"); candidateNewInsert.setIdCandidate(newCandidate.getId()); candidateNewInsert.setIdPosition(position.getId()); domainEventPublisher.publish(candidateNewInsert, DomainEventName.CANDIDATE_NEW_INSERT, CandidateNewInsert.class); } return newCandidate; } catch (RuntimeException e) { throw e; } } @Override @Deprecated public List<Candidate> getAllCandidates() { return candidateDAO.findAll(); } @Override public Page<Candidate> getAllCandidatesByStoreIdAndMarkForDeletePageable(String storeId, boolean markForDelete, Pageable pageable) throws Exception { return this.candidateDAO.findByStoreIdAndMarkForDelete(storeId, markForDelete, pageable); } @Override public Page<Candidate> getAllCandidatesByStoreIdPageable(String storeId, Pageable pageable) throws Exception { return this.candidateDAO.findByStoreId(storeId, pageable); } @Override @Deprecated public Page<Candidate> getAllCandidatesWithPageable(String storeId, Pageable pageable) { return candidateDAO.findByStoreId(storeId, pageable); } @Override public Candidate getCandidate(String id) throws Exception { Candidate candidate = candidateDAO.findOne(id); if (candidate == null) { throw new ApplicationException(ErrorCategory.DATA_NOT_FOUND); } else { return candidate; } } @Override public Candidate getCandidateByIdAndStoreIdEager(String id, String storeId) throws Exception { Candidate candidate = this.candidateDAO.findOne(id); if (candidate == null || candidate.equals(null)) { throw new ApplicationException(ErrorCategory.DATA_NOT_FOUND, "id and storeId not found"); } else { if (candidate.getStoreId().equals(storeId)) { Hibernate.initialize(candidate.getCandidatePositions()); return candidate; } else { throw new ApplicationException(ErrorCategory.DATA_NOT_FOUND, "id not found"); } } } @Override public Candidate getCandidateByIdAndStoreIdLazy(String id, String storeId) throws Exception { Candidate candidate = this.candidateDAO.findOne(id); if (candidate == null || candidate.equals(null)) { throw new ApplicationException(ErrorCategory.DATA_NOT_FOUND, "id not found in database"); } else { if (candidate.getStoreId().equals(storeId)) { return candidate; } else { throw new ApplicationException(ErrorCategory.DATA_NOT_FOUND, "id not found in database"); } } } public CandidateDAO getCandidateDAO() { return candidateDAO; } @Override public CandidateDetail getCandidateDetailAndStoreId(String id, String storeId) throws Exception { Candidate candidate = getCandidate(id); if (candidate.getStoreId().equals(storeId)) { Hibernate.initialize(candidate.getCandidateDetail()); return candidate.getCandidateDetail(); } else { throw new ApplicationException(ErrorCategory.DATA_NOT_FOUND, "data not found, store id"); } } @Override public CandidatePosition getCandidatePositionByStoreIdWithLogs(String idCandidate, String idPosition, String storeId) throws Exception { Candidate candidate = this.getCandidate(idCandidate); if (!candidate.getStoreId().equals(storeId)) { throw new ApplicationException(ErrorCategory.DATA_NOT_FOUND, "candidate not found by store id"); } Position position = this.positionDAO.findOne(idPosition); if (position == null || position.equals(null)) { throw new ApplicationException(ErrorCategory.DATA_NOT_FOUND, "position not found"); } if (!position.getStoreId().equals(storeId)) { throw new ApplicationException(ErrorCategory.DATA_NOT_FOUND, "position not found by store id"); } Hibernate.initialize(candidate.getCandidatePositions()); for (CandidatePosition candidatePosition : candidate.getCandidatePositions()) { if (candidatePosition.getPosition().getId().equals(position.getId())) { Hibernate.initialize(candidatePosition.getStatusLogs()); return candidatePosition; } } throw new ApplicationException(ErrorCategory.UNSPECIFIED, "didn't get equal position in candidate"); } public GdnMapper getGdnMapper() { return gdnMapper; } public PositionDAO getPositionDAO() { return positionDAO; } // Bulk Delete @Override @Transactional(readOnly = false) public void markForDelete(List<String> ids) throws Exception { System.out.println(ids.toString()); for (int i = 0; i < ids.size(); i++) { markForDelete(ids.get(i)); } } @Override public void markForDelete(String id) throws Exception { Candidate candidate = this.candidateDAO.findByIdAndMarkForDelete(id, false); if (candidate == null) { throw new ApplicationException(ErrorCategory.DATA_NOT_FOUND, "candidate not found"); } Hibernate.initialize(candidate.getCandidatePositions()); Iterator<CandidatePosition> iterator = candidate.getCandidatePositions().iterator(); while (iterator.hasNext()) { CandidatePosition candidatePositon = iterator.next(); candidatePositon.setMarkForDelete(true); Hibernate.initialize(candidatePositon.getStatusLogs()); candidatePositon.getStatusLogs().stream().forEach(statusLog -> { statusLog.setMarkForDelete(true); }); } candidate.setMarkForDelete(true); this.candidateDAO.save(candidate); } @Override public Page<Candidate> searchByCreatedDateBetweenAndStoreId(Date start, Date end, String storeId, Pageable pageable) { return candidateDAO.findByCreatedDateBetweenAndStoreId(start, end, storeId, pageable); } @Override public Page<Candidate> searchByFirstNameContainAndStoreId(String firstName, String storeId, Pageable pageable) throws Exception { return this.candidateDAO.findByFirstNameContainingAndStoreId(firstName, storeId, pageable); } @Override public Page<Candidate> searchByLastNameContainAndStoreId(String lastName, String storeId, Pageable pageable) { return candidateDAO.findByLastNameContainingAndStoreId(lastName, storeId, pageable); } @Override public Candidate searchCandidateByEmailAddressAndStoreId(String emailAddress, String storeId) { return candidateDAO.findByEmailAddressAndStoreId(emailAddress, storeId); } @Override @Deprecated public List<Candidate> searchCandidateByPhoneNumber(String phoneNumber) { return candidateDAO.findByPhoneNumber(phoneNumber); } @Override public Page<Candidate> searchCandidateByPhoneNumberContainAndStoreId(String phoneNumber, String storeId, Pageable pageable) { return candidateDAO.findByPhoneNumberContainingAndStoreId(phoneNumber, storeId, pageable); } public void setCandidateDAO(CandidateDAO candidateDAO) { this.candidateDAO = candidateDAO; } public void setGdnMapper(GdnMapper gdnMapper) { this.gdnMapper = gdnMapper; } public void setPositionDAO(PositionDAO positionDAO) { this.positionDAO = positionDAO; } @Override @Transactional(readOnly = false) public void updateCandidateDetail(String storeId, Candidate candidate) throws Exception { if (candidate.getId() != null) { Candidate existingCandidate = getCandidate(candidate.getId()); if (!existingCandidate.getStoreId().equals(storeId)) { throw new ApplicationException(ErrorCategory.DATA_NOT_FOUND, "data found but no store id match expected = " + existingCandidate.getStoreId() + " but was = " + storeId); } existingCandidate.setFirstName(candidate.getFirstName()); existingCandidate.setLastName(candidate.getLastName()); existingCandidate.setEmailAddress(candidate.getEmailAddress()); existingCandidate.setPhoneNumber(candidate.getPhoneNumber()); Hibernate.initialize(candidate.getCandidateDetail()); CandidateDetail existingDetail = existingCandidate.getCandidateDetail(); existingDetail.setContent(candidate.getCandidateDetail().getContent()); candidateDAO.save(candidate); } else { throw new ApplicationException(ErrorCategory.VALIDATION, ID_SHOULD_NOT_BE_EMPTY); } } @Override @Transactional(readOnly = false) public void updateCandidateStatus(String storeId, String idCandidate, String idPosition, Status status) throws Exception { Candidate existingCandidate = getCandidate(idCandidate); if (!existingCandidate.getStoreId().equals(storeId)) { throw new ApplicationException(ErrorCategory.DATA_NOT_FOUND, "data found but no store id match expected = " + existingCandidate.getStoreId() + " but was = " + storeId); } Position existingPosition = positionDAO.findOne(idPosition); Hibernate.initialize(existingCandidate.getCandidatePositions()); existingCandidate.getCandidatePositions().stream() .filter(candidatePosition -> candidatePosition.getPosition().equals(existingPosition)) .forEach(candidatePosition -> { candidatePosition.getStatusLogs().add(new StatusLog(candidatePosition, status)); candidatePosition.setStatus(status); // add missing setter zal }); candidateDAO.save(existingCandidate); } @Override @Transactional(readOnly = false) public void updateCandidateStatusBulk(String storeId, List<String> idCandidates, String idPosition, Status status) throws Exception { for (String id : idCandidates) { this.updateCandidateStatus(storeId, id, idPosition, status); } } }
package org.jboss.forge.addon.shell.aesh; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.aesh.cl.CommandLine; import org.jboss.aesh.cl.CommandLineParser; import org.jboss.aesh.cl.OptionBuilder; import org.jboss.aesh.cl.ParserBuilder; import org.jboss.aesh.cl.exception.OptionParserException; import org.jboss.aesh.cl.internal.ParameterInt; import org.jboss.forge.addon.convert.Converter; import org.jboss.forge.addon.convert.ConverterFactory; import org.jboss.forge.addon.shell.util.ShellUtil; import org.jboss.forge.addon.ui.UICommand; import org.jboss.forge.addon.ui.hints.InputType; import org.jboss.forge.addon.ui.input.InputComponent; import org.jboss.forge.addon.ui.input.ManyValued; import org.jboss.forge.addon.ui.input.UIInput; import org.jboss.forge.addon.ui.input.UIInputMany; import org.jboss.forge.addon.ui.input.UISelectMany; import org.jboss.forge.addon.ui.input.UISelectOne; import org.jboss.forge.addon.ui.metadata.UICommandMetadata; import org.jboss.forge.addon.ui.util.InputComponents; public class CommandLineUtil { private static final Logger logger = Logger.getLogger(CommandLineUtil.class.getName()); private ConverterFactory converterFactory; public CommandLineUtil(ConverterFactory converterFactory) { this.converterFactory = converterFactory; } public CommandLineParser generateParser(UICommand command, Map<String, InputComponent<?, Object>> inputs) { ParserBuilder builder = new ParserBuilder(); UICommandMetadata metadata = command.getMetadata(); ParameterInt parameter = new ParameterInt(ShellUtil.shellifyName(metadata.getName()), metadata.getDescription()); for (InputComponent<?, Object> input : inputs.values()) { if (!input.getName().equals("arguments")) { Object defaultValue = InputComponents.getValueFor(input); boolean isMultiple = input instanceof ManyValued; boolean hasValue = (InputComponents.getInputType(input) != InputType.CHECKBOX); try { OptionBuilder optionBuilder = new OptionBuilder(); optionBuilder.longName(input.getName()) .defaultValue(defaultValue == null ? null : defaultValue.toString()) .description(input.getLabel()) .hasMultipleValues(isMultiple) .hasValue(hasValue) .required(input.isRequired()); if (input.getShortName() != InputComponents.DEFAULT_SHORT_NAME) { optionBuilder.name(input.getShortName()); } parameter.addOption(optionBuilder.create()); } catch (OptionParserException e) { logger.log(Level.SEVERE, "Error while parsing command option", e); } } } builder.addParameter(parameter); return builder.generateParser(); } @SuppressWarnings("unchecked") // TODO Review this method public void populateUIInputs(CommandLine commandLine, Map<String, InputComponent<?, Object>> inputs) { for (InputComponent<?, Object> input : inputs.values()) { if (input.getName().equals("arguments") && input instanceof UIInputMany) { InputComponents.setValueFor(converterFactory, input, commandLine.getArguments()); } else if (input instanceof UIInputMany) { InputComponents.setValueFor(converterFactory, input, commandLine.getOptionValues(input.getName())); } else if (input instanceof UIInput) { InputComponents.setValueFor(converterFactory, input, commandLine.getOptionValue(input.getName())); } else if (input instanceof UISelectMany) { setInputChoices((UISelectMany<Object>) input, commandLine.getOptionValues(input.getName())); } else if (input instanceof UISelectOne) { setInputChoice((UISelectOne<Object>) input, commandLine.getOptionValue(input.getName())); } } } private void setInputChoice(UISelectOne<Object> input, String optionValue) { Converter<Object, String> labelConverter = input.getItemLabelConverter(); boolean found = false; for (Object choice : input.getValueChoices()) { if (labelConverter.convert(choice).equals(optionValue)) { input.setValue(choice); found = true; break; } } if (!found) logger.warning("Could not find matching value choice for input value [" + optionValue + "]"); } private void setInputChoices(UISelectMany<Object> input, List<String> optionValues) { Converter<Object, String> labelConverter = input.getItemLabelConverter(); List<Object> selected = new ArrayList<Object>(); for (String optionValue : optionValues) { boolean found = false; for (Object choice : input.getValueChoices()) { if (labelConverter.convert(choice).equals(optionValue)) { selected.add(choice); found = true; break; } } if (!found) logger.warning("Could not find matching value choice for input value [" + optionValue + "]"); } input.setValue(selected); } }
package peergos.shared; import peergos.shared.corenode.*; import peergos.shared.crypto.*; import peergos.shared.crypto.hash.*; import peergos.shared.io.ipfs.cid.*; import peergos.shared.mutable.*; import peergos.shared.social.*; import peergos.shared.storage.*; import peergos.shared.storage.auth.*; import peergos.shared.storage.controller.*; import peergos.shared.user.*; import peergos.shared.util.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.stream.*; /** This will buffer block writes, and mutable pointer updates and commit in bulk * */ public class BufferedNetworkAccess extends NetworkAccess { private final BufferedStorage blockBuffer; private final BufferedPointers pointerBuffer; private final int bufferSize; private Map<PublicKeyHash, SigningPrivateKeyAndPublicHash> writers = new HashMap<>(); private final List<WriterUpdate> writerUpdates = new ArrayList<>(); private Committer targetCommitter; private final PublicKeyHash owner; private final Supplier<Boolean> commitWatcher; private final ContentAddressedStorage blocks; private BufferedNetworkAccess(BufferedStorage blockBuffer, BufferedPointers mutableBuffer, int bufferSize, PublicKeyHash owner, Supplier<Boolean> commitWatcher, CoreNode coreNode, Account account, SocialNetwork social, ContentAddressedStorage dhtClient, BatCave batCave, MutablePointers mutable, MutableTree tree, WriteSynchronizer synchronizer, InstanceAdmin instanceAdmin, SpaceUsage spaceUsage, ServerMessager serverMessager, Hasher hasher, List<String> usernames, boolean isJavascript) { super(coreNode, account, social, blockBuffer, batCave, mutable, tree, synchronizer, instanceAdmin, spaceUsage, serverMessager, hasher, usernames, isJavascript); this.blockBuffer = blockBuffer; this.pointerBuffer = mutableBuffer; this.bufferSize = bufferSize; this.owner = owner; this.commitWatcher = commitWatcher; this.blocks = dhtClient; pointerBuffer.watchUpdates(() -> maybeCommit()); } private static class WriterUpdate { public final PublicKeyHash writer; public final CommittedWriterData prev; public final CommittedWriterData current; public WriterUpdate(PublicKeyHash writer, CommittedWriterData prev, CommittedWriterData current) { this.writer = writer; this.prev = prev; this.current = current; } } public Committer buildCommitter(Committer c) { targetCommitter = c; return (o, w, wd, e, tid) -> blockBuffer.put(owner, w.publicKeyHash, new byte[0], wd.serialize(), tid) .thenApply(newHash -> { CommittedWriterData updated = new CommittedWriterData(MaybeMultihash.of(newHash), wd); PublicKeyHash writer = w.publicKeyHash; writers.put(writer, w); if (writerUpdates.isEmpty()) writerUpdates.add(new WriterUpdate(writer, e, updated)); else { WriterUpdate last = writerUpdates.get(writerUpdates.size() - 1); if (last.writer.equals(writer)) writerUpdates.set(writerUpdates.size() - 1, new WriterUpdate(writer, last.prev, updated)); else { writerUpdates.add(new WriterUpdate(writer, e, updated)); } } return new Snapshot(writer, updated); }); } public int bufferedSize() { return blockBuffer.totalSize(); } private CompletableFuture<Boolean> maybeCommit() { if (bufferedSize() >= bufferSize) return commit(); return Futures.of(true); } private List<Cid> getRoots() { return writerUpdates.stream() .flatMap(u -> u.current.hash.toOptional().stream()) .map(c -> (Cid)c) .collect(Collectors.toList()); } private CompletableFuture<List<Snapshot>> commitPointers(TransactionId tid) { return Futures.combineAllInOrder(writerUpdates.stream() .map(u -> targetCommitter.commit(owner, writers.get(u.writer), u.current.props, u.prev, tid)) .collect(Collectors.toList())); } public synchronized CompletableFuture<Boolean> commit() { // Condense pointers and do a mini GC to remove superfluous work blockBuffer.gc(getRoots()); return blockBuffer.signBlocks(writers) .thenCompose(b -> blocks.startTransaction(owner)) .thenCompose(tid -> blockBuffer.commit(owner, tid) .thenCompose(b -> commitPointers(tid)) .thenCompose(b -> pointerBuffer.commit()) .thenCompose(x -> blocks.closeTransaction(owner, tid)) .thenApply(x -> { blockBuffer.clear(); pointerBuffer.clear(); writers.clear(); writerUpdates.clear(); return commitWatcher.get(); })); } public static BufferedNetworkAccess build(NetworkAccess base, int bufferSize, PublicKeyHash owner, Supplier<Boolean> commitWatcher, Hasher h) { BufferedStorage blockBuffer = new BufferedStorage(base.dhtClient, h); BufferedPointers mutableBuffer = new BufferedPointers(base.mutable); WriteSynchronizer synchronizer = new WriteSynchronizer(mutableBuffer, blockBuffer, h); MutableTree tree = new MutableTreeImpl(mutableBuffer, blockBuffer, h, synchronizer); return new BufferedNetworkAccess(blockBuffer, mutableBuffer, bufferSize, owner, commitWatcher, base.coreNode, base.account, base.social, base.dhtClient, base.batCave, mutableBuffer, tree, synchronizer, base.instanceAdmin, base.spaceUsage, base.serverMessager, base.hasher, base.usernames, base.isJavascript()); } }
package com.github.wreulicke.simple.product; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; @Data @Entity @Table(name = "product_stocks") public class ProductStock { @Id @Column private Long id; @Column private long count; }
package org.skyve.impl.metadata.repository; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import org.skyve.domain.Bean; import org.skyve.impl.bind.BindUtil; import org.skyve.impl.metadata.customer.CustomerImpl; import org.skyve.impl.metadata.model.document.DocumentImpl; import org.skyve.impl.metadata.module.ModuleImpl; import org.skyve.impl.metadata.view.ActionImpl; import org.skyve.impl.metadata.view.Inject; import org.skyve.impl.metadata.view.ViewImpl; import org.skyve.impl.metadata.view.ViewVisitor; import org.skyve.impl.metadata.view.container.HBox; import org.skyve.impl.metadata.view.container.Tab; import org.skyve.impl.metadata.view.container.TabPane; import org.skyve.impl.metadata.view.container.VBox; import org.skyve.impl.metadata.view.container.form.Form; import org.skyve.impl.metadata.view.container.form.FormColumn; import org.skyve.impl.metadata.view.container.form.FormItem; import org.skyve.impl.metadata.view.container.form.FormRow; import org.skyve.impl.metadata.view.event.Addable; import org.skyve.impl.metadata.view.event.Changeable; import org.skyve.impl.metadata.view.event.Editable; import org.skyve.impl.metadata.view.event.EventAction; import org.skyve.impl.metadata.view.event.EventSource; import org.skyve.impl.metadata.view.event.Focusable; import org.skyve.impl.metadata.view.event.Removable; import org.skyve.impl.metadata.view.event.RerenderEventAction; import org.skyve.impl.metadata.view.event.Selectable; import org.skyve.impl.metadata.view.event.ServerSideActionEventAction; import org.skyve.impl.metadata.view.event.SetDisabledEventAction; import org.skyve.impl.metadata.view.event.SetInvisibleEventAction; import org.skyve.impl.metadata.view.event.ToggleDisabledEventAction; import org.skyve.impl.metadata.view.event.ToggleVisibilityEventAction; import org.skyve.impl.metadata.view.model.chart.ChartBuilderMetaData; import org.skyve.impl.metadata.view.reference.ActionReference; import org.skyve.impl.metadata.view.reference.ContentReference; import org.skyve.impl.metadata.view.reference.DefaultListViewReference; import org.skyve.impl.metadata.view.reference.EditViewReference; import org.skyve.impl.metadata.view.reference.ExternalReference; import org.skyve.impl.metadata.view.reference.ImplicitActionReference; import org.skyve.impl.metadata.view.reference.QueryListViewReference; import org.skyve.impl.metadata.view.reference.ReferenceProcessor; import org.skyve.impl.metadata.view.reference.ReportReference; import org.skyve.impl.metadata.view.reference.ResourceReference; import org.skyve.impl.metadata.view.widget.Blurb; import org.skyve.impl.metadata.view.widget.Button; import org.skyve.impl.metadata.view.widget.Chart; import org.skyve.impl.metadata.view.widget.DialogButton; import org.skyve.impl.metadata.view.widget.DynamicImage; import org.skyve.impl.metadata.view.widget.Link; import org.skyve.impl.metadata.view.widget.MapDisplay; import org.skyve.impl.metadata.view.widget.Spacer; import org.skyve.impl.metadata.view.widget.StaticImage; import org.skyve.impl.metadata.view.widget.bound.Label; import org.skyve.impl.metadata.view.widget.bound.ProgressBar; import org.skyve.impl.metadata.view.widget.bound.input.CheckBox; import org.skyve.impl.metadata.view.widget.bound.input.CheckMembership; import org.skyve.impl.metadata.view.widget.bound.input.ColourPicker; import org.skyve.impl.metadata.view.widget.bound.input.Combo; import org.skyve.impl.metadata.view.widget.bound.input.Comparison; import org.skyve.impl.metadata.view.widget.bound.input.ContentImage; import org.skyve.impl.metadata.view.widget.bound.input.ContentLink; import org.skyve.impl.metadata.view.widget.bound.input.Geometry; import org.skyve.impl.metadata.view.widget.bound.input.GeometryMap; import org.skyve.impl.metadata.view.widget.bound.input.HTML; import org.skyve.impl.metadata.view.widget.bound.input.ListMembership; import org.skyve.impl.metadata.view.widget.bound.input.Lookup; import org.skyve.impl.metadata.view.widget.bound.input.LookupDescription; import org.skyve.impl.metadata.view.widget.bound.input.LookupDescriptionColumn; import org.skyve.impl.metadata.view.widget.bound.input.Password; import org.skyve.impl.metadata.view.widget.bound.input.Radio; import org.skyve.impl.metadata.view.widget.bound.input.RichText; import org.skyve.impl.metadata.view.widget.bound.input.Slider; import org.skyve.impl.metadata.view.widget.bound.input.Spinner; import org.skyve.impl.metadata.view.widget.bound.input.TextArea; import org.skyve.impl.metadata.view.widget.bound.input.TextField; import org.skyve.impl.metadata.view.widget.bound.tabular.AbstractDataWidget; import org.skyve.impl.metadata.view.widget.bound.tabular.DataGrid; import org.skyve.impl.metadata.view.widget.bound.tabular.DataGridBoundColumn; import org.skyve.impl.metadata.view.widget.bound.tabular.DataGridContainerColumn; import org.skyve.impl.metadata.view.widget.bound.tabular.DataRepeater; import org.skyve.impl.metadata.view.widget.bound.tabular.ListGrid; import org.skyve.impl.metadata.view.widget.bound.tabular.ListRepeater; import org.skyve.impl.metadata.view.widget.bound.tabular.TreeGrid; import org.skyve.metadata.FilterOperator; import org.skyve.metadata.MetaDataException; import org.skyve.metadata.model.Attribute; import org.skyve.metadata.model.Attribute.AttributeType; import org.skyve.metadata.model.Extends; import org.skyve.metadata.model.document.Document; import org.skyve.metadata.model.document.Reference; import org.skyve.metadata.model.document.Relation; import org.skyve.metadata.module.Module; import org.skyve.metadata.module.query.MetaDataQueryColumn; import org.skyve.metadata.module.query.MetaDataQueryDefinition; import org.skyve.metadata.module.query.MetaDataQueryProjectedColumn; import org.skyve.metadata.view.View.ViewParameter; import org.skyve.metadata.view.View.ViewType; import org.skyve.metadata.view.widget.bound.Bound; import org.skyve.metadata.view.widget.bound.FilterParameter; import org.skyve.metadata.view.widget.bound.Parameter; import org.skyve.persistence.DocumentQuery.AggregateFunction; import org.skyve.util.Binder; import org.skyve.util.Binder.TargetMetaData; // TODO check suggestion attributes on text fields etc class ViewValidator extends ViewVisitor { private AbstractRepository repository; private String viewIdentifier; private String uxui; // These 2 variables are used when validating the contents of a data grid / data repeater private String dataWidgetIdentifier; private String dataWidgetBinding; ViewValidator(ViewImpl view, AbstractRepository repository, CustomerImpl customer, DocumentImpl document, String uxui) { super(customer, (ModuleImpl) customer.getModule(document.getOwningModuleName()), document, view); this.repository = repository; viewIdentifier = view.getName() + " view for UX/UI " + uxui + " for document " + module.getName() + '.' + document.getName(); this.uxui = uxui; visit(); } private void validateBinding(String bindingPrefix, String binding, boolean bindingRequired, boolean compoundBindingInvalid, boolean domainValuesRequired, boolean scalarBindingOnly, String widgetIdentifier, AttributeType... assertTypes) { validateBinding(module, document, bindingPrefix, binding, bindingRequired, compoundBindingInvalid, domainValuesRequired, scalarBindingOnly, widgetIdentifier, assertTypes); } private void validateBinding(Module contextModule, Document contextDocument, String bindingPrefix, String binding, boolean bindingRequired, boolean compoundBindingInvalid, boolean domainValuesRequired, boolean scalarBindingOnly, String widgetIdentifier, AttributeType... assertTypes) { if (bindingRequired && (binding == null)) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " - binding is required."); } if (binding != null) { if (compoundBindingInvalid) { if (binding.indexOf('.') >= 0) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " - Compound binding is not allowed here"); } } String bindingToTest = binding; if (bindingPrefix != null) { bindingToTest = new StringBuilder(64).append(bindingPrefix).append('.').append(binding).toString(); } else { // conditions can be used in parameter bindings for reports etc String testConditionName = bindingToTest; if (testConditionName.startsWith("not")) { testConditionName = Character.toLowerCase(testConditionName.charAt(3)) + testConditionName.substring(4); } if (contextDocument.getConditionNames().contains(testConditionName)) { return; } } TargetMetaData target = null; try { target = BindUtil.getMetaDataForBinding(customer, contextModule, contextDocument, bindingToTest); } catch (MetaDataException e) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " has an invalid binding of " + binding, e); } if (target == null) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " - Binding points nowhere"); } Attribute attribute = target.getAttribute(); if (((assertTypes != null) && (assertTypes.length > 0)) || domainValuesRequired) { if (attribute == null) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " - Binding points to an implicit attribute or a condition that cannot have domain values defined."); } } if ((assertTypes != null) && (assertTypes.length > 0)) { AttributeType type = attribute.getAttributeType(); boolean typeMatch = false; for (AttributeType assertType : assertTypes) { if (assertType.equals(type)) { typeMatch = true; break; } } if (! typeMatch) { StringBuilder msg = new StringBuilder(128); msg.append(widgetIdentifier).append(" in ").append(viewIdentifier); msg.append(" - Binding points to an attribute of type ").append(type).append(", not one of "); for (AttributeType assertType : assertTypes) { msg.append(assertType).append(", "); } msg.setLength(msg.length() - 2); // remove last comma msg.append('.'); throw new MetaDataException(msg.toString()); } } if (domainValuesRequired) { if (attribute.getDomainType() == null) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " - Binding points to an attribute that does not have domain values defined."); } } // Can only check this if the attribute is defined. // Bindings to implicit attributes are always scalar. // NB check assert type in outer if coz we dont need to do the test if we are asserting a type if (scalarBindingOnly && ((assertTypes == null) || (assertTypes.length == 0)) && (attribute != null)) { AttributeType type = attribute.getAttributeType(); if (AttributeType.association.equals(type) || AttributeType.collection.equals(type) || AttributeType.inverseMany.equals(type) || AttributeType.inverseOne.equals(type)) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " - Binding points to an attribute that is not scalar (pointing to an association or collection or inverse)"); } } } } private void validateConditionName(String conditionName, String widgetIdentifier) { // ignore true and false when checking the condition exists if ((conditionName != null) && (! "true".equals(conditionName)) && (! "false".equals(conditionName))) { // reverse the sense of the condition if it starts with "not" String testConditionName = conditionName; if (testConditionName.startsWith("not")) { if (! Character.isUpperCase(testConditionName.charAt(3))) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + "references condition " + conditionName + " which is not correctly camel cased (eg notTrue)"); } testConditionName = Character.toLowerCase(testConditionName.charAt(3)) + testConditionName.substring(4); } // ignore implicit conditions when checking the condition exists if ((! Bean.PERSISTED_KEY.equals(testConditionName)) && (! Bean.CREATED_KEY.equals(testConditionName)) && (! Bean.CHANGED_KEY.equals(testConditionName))) { validateCondition(module, document, testConditionName, widgetIdentifier); } } } private void validateCondition(ModuleImpl currentModule, DocumentImpl currentDocument, String testConditionName, String widgetIdentifier) { if (! currentDocument.getConditionNames().contains(testConditionName)) { Extends extension = currentDocument.getExtends(); if (extension == null) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " references condition " + testConditionName + " which does not exist"); } DocumentImpl baseDocument = (DocumentImpl) currentModule.getDocument(customer, extension.getDocumentName()); ModuleImpl baseModule = (ModuleImpl) customer.getModule(baseDocument.getOwningModuleName()); validateCondition(baseModule, baseDocument, testConditionName, widgetIdentifier); } } private void validateParameterBindings(List<Parameter> parameters, String parentWidgetIdentifier) { if (parameters != null) { for (Parameter parameter : parameters) { validateBinding(null, parameter.getValueBinding(), false, false, false, false, "Parameter " + parameter.getName() + " in " + parentWidgetIdentifier); } } } private void validateFilterParameterBindings(List<FilterParameter> parameters, String parentWidgetIdentifier) { if (parameters != null) { for (FilterParameter parameter : parameters) { String name = parameter.getFilterBinding(); // TODO should validate filterBinding against child document. validateBinding(null, parameter.getValueBinding(), false, false, false, false, "Filter Parameter " + name + " in " + parentWidgetIdentifier); } } } private void validateMessageBindings(String message, String widgetIdentifier, String description) { if (message != null) { Module testModule = module; Document testDocument = document; if (dataWidgetBinding != null) { TargetMetaData target = BindUtil.getMetaDataForBinding(customer, module, document, dataWidgetBinding); Attribute targetAttribute = target.getAttribute(); // Collection and Inverse are appropriate here... if (targetAttribute instanceof Relation) { Relation relation = (Relation) targetAttribute; testDocument = module.getDocument(customer, relation.getDocumentName()); testModule = customer.getModule(testDocument.getOwningModuleName()); } } if (! BindUtil.messageBindingsAreValid(customer, testModule, testDocument, message)) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " has " + description + " containing malformed binding expressions."); } } } private void validateNoColonInParameter(List<Parameter> parameters, String widgetIdentifier) { if (parameters != null) { for (Parameter parameter : parameters) { if (parameter.getName().indexOf(':') >= 0) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " has a parameter named " + parameter.getName() + " which contains a colon (:). Use a parameter to bind a value to a named parameter in a query"); } } } } private void validateNoColonInFilterParameter(List<FilterParameter> parameters, String widgetIdentifier) { if (parameters != null) { for (FilterParameter parameter : parameters) { if (parameter.getFilterBinding().indexOf(':') >= 0) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " has a parameter with filterBinding " + parameter.getFilterBinding() + " which contains a colon (:). Use a parameter to bind a value to a named parameter in a query"); } } } } private void validateQueryOrModel(String queryName, String modelName, String widgetIdentifier) { if (queryName != null) { if (modelName != null) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " has a query and a model name."); } validateQueryName(queryName, widgetIdentifier); } else if (modelName != null) { validateListModelName(modelName, widgetIdentifier); } else { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " requires a query name or a model name."); } } private void validateQueryName(String queryName, String widgetIdentifier) { if ((queryName != null) && (module.getMetaDataQuery(queryName) == null)) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " does not reference a valid query of " + queryName); } } private void validateListModelName(String modelName, String widgetIdentifier) { if (modelName != null) { try { StringBuilder fullyQualifiedJavaCodeName = new StringBuilder(128); fullyQualifiedJavaCodeName.append(document.getOwningModuleName()).append('.').append(document.getName()); fullyQualifiedJavaCodeName.append(".models.").append(modelName); if (repository.getJavaClass(customer, fullyQualifiedJavaCodeName.toString()) == null) { throw new MetaDataException(fullyQualifiedJavaCodeName + " not found."); } } catch (Exception e) { // NB could be class cast problems throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " does not reference a valid list model of " + modelName, e); } } } private void validateMapModelName(String modelName, String widgetIdentifier) { if (modelName != null) { try { StringBuilder fullyQualifiedJavaCodeName = new StringBuilder(128); fullyQualifiedJavaCodeName.append(document.getOwningModuleName()).append('.').append(document.getName()); fullyQualifiedJavaCodeName.append(".models.").append(modelName); if (repository.getJavaClass(customer, fullyQualifiedJavaCodeName.toString()) == null) { throw new MetaDataException(fullyQualifiedJavaCodeName + " not found."); } } catch (Exception e) { // NB could be class cast problems throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " does not reference a valid map model of " + modelName, e); } } } private void validateChartModelName(String modelName, String widgetIdentifier) { if (modelName != null) { try { StringBuilder fullyQualifiedJavaCodeName = new StringBuilder(128); fullyQualifiedJavaCodeName.append(document.getOwningModuleName()).append('.').append(document.getName()); fullyQualifiedJavaCodeName.append(".models.").append(modelName); if (repository.getJavaClass(customer, fullyQualifiedJavaCodeName.toString()) == null) { throw new MetaDataException(fullyQualifiedJavaCodeName + " not found."); } } catch (Exception e) { // NB could be class cast problems throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " does not reference a valid chart model of " + modelName, e); } } } private void validateComparisonModelName(String modelName, String widgetIdentifier) { if (modelName != null) { try { StringBuilder fullyQualifiedJavaCodeName = new StringBuilder(128); fullyQualifiedJavaCodeName.append(document.getOwningModuleName()).append('.').append(document.getName()); fullyQualifiedJavaCodeName.append(".models.").append(modelName); if (repository.getJavaClass(customer, fullyQualifiedJavaCodeName.toString()) == null) { throw new MetaDataException(fullyQualifiedJavaCodeName + " not found."); } } catch (Exception e) { // NB could be class cast problems throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " does not reference a valid comparison model of " + modelName, e); } } } private void validateActionName(String actionName, String widgetIdentifier) { if ((actionName != null) && (view.getAction(actionName) == null)) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " references a non-existent action " + actionName); } } @Override public void visitButton(Button button, boolean parentVisible, boolean parentEnabled) { String actionName = button.getActionName(); String buttonIdentifier = "A button " + button.getActionName(); validateActionName(actionName, buttonIdentifier); } @Override public void visitDynamicImage(DynamicImage image, boolean parentVisible, boolean parentEnabled) { String imageIdentifier = "Dynamic Image " + image.getName(); validateConditionName(image.getInvisibleConditionName(), imageIdentifier); validateParameterBindings(image.getParameters(), imageIdentifier); } @Override public void visitCheckBox(CheckBox checkBox, boolean parentVisible, boolean parentEnabled) { String binding = checkBox.getBinding(); String checkBoxIdentifier = "CheckBox " + binding; if (dataWidgetBinding != null) { checkBoxIdentifier += " in " + dataWidgetIdentifier; } validateBinding(dataWidgetBinding, binding, true, false, false, true, checkBoxIdentifier, AttributeType.bool); validateConditionName(checkBox.getDisabledConditionName(), checkBoxIdentifier); validateConditionName(checkBox.getInvisibleConditionName(), checkBoxIdentifier); } @Override public void visitedCheckBox(CheckBox checkBox, boolean parentVisible, boolean parentEnabled) { // do nothing } @Override public void visitCheckMembership(CheckMembership membership, boolean parentVisible, boolean parentEnabled) { String membershipIdentifier = "CheckBox " + membership.getBinding(); validateBinding(null, membership.getBinding(), true, false, true, false, membershipIdentifier, AttributeType.collection); validateConditionName(membership.getDisabledConditionName(), membershipIdentifier); validateConditionName(membership.getInvisibleConditionName(), membershipIdentifier); } @Override public void visitedCheckMembership(CheckMembership membership, boolean parentVisible, boolean parentEnabled) { // do nothing } @Override public void visitColourPicker(ColourPicker colour, boolean parentVisible, boolean parentEnabled) { String binding = colour.getBinding(); String colourIdentifier = "Colour " + binding; if (dataWidgetBinding != null) { colourIdentifier += " in " + dataWidgetIdentifier; } validateBinding(dataWidgetBinding, binding, true, false, false, true, colourIdentifier, AttributeType.colour); validateConditionName(colour.getDisabledConditionName(), colourIdentifier); validateConditionName(colour.getInvisibleConditionName(), colourIdentifier); } @Override public void visitedColourPicker(ColourPicker colour, boolean parentVisible, boolean parentEnabled) { // do nothing } @Override public void visitCombo(Combo combo, boolean parentVisible, boolean parentEnabled) { String binding = combo.getBinding(); String comboIdentifier = "Combo " + binding; if (dataWidgetBinding != null) { comboIdentifier += " in " + dataWidgetIdentifier; } validateBinding(dataWidgetBinding, binding, true, false, true, false, comboIdentifier, AttributeType.enumeration, AttributeType.text, AttributeType.association, AttributeType.inverseOne, AttributeType.bool, AttributeType.integer, AttributeType.longInteger); validateConditionName(combo.getDisabledConditionName(), comboIdentifier); validateConditionName(combo.getInvisibleConditionName(), comboIdentifier); } @Override public void visitedCombo(Combo combo, boolean parentVisible, boolean parentEnabled) { // do nothing } @Override public void visitContentImage(ContentImage image, boolean parentVisible, boolean parentEnabled) { String binding = image.getBinding(); String imageIdentifier = "ContentImage " + binding; if (dataWidgetBinding != null) { imageIdentifier += " in " + dataWidgetIdentifier; } validateBinding(dataWidgetBinding, binding, true, false, false, true, imageIdentifier, AttributeType.content, AttributeType.image); validateConditionName(image.getDisabledConditionName(), imageIdentifier); validateConditionName(image.getInvisibleConditionName(), imageIdentifier); } @Override public void visitContentLink(ContentLink link, boolean parentVisible, boolean parentEnabled) { String binding = link.getBinding(); String linkIdentifier = "ContentLink " + link.getBinding(); if (dataWidgetBinding != null) { linkIdentifier += " in " + dataWidgetIdentifier; } validateBinding(dataWidgetBinding, binding, false, false, false, true, linkIdentifier, AttributeType.content, AttributeType.image); validateConditionName(link.getDisabledConditionName(), linkIdentifier); validateConditionName(link.getInvisibleConditionName(), linkIdentifier); validateParameterBindings(link.getParameters(), linkIdentifier); } @Override public void visitDataGrid(DataGrid grid, boolean parentVisible, boolean parentEnabled) { visitDataWidget(grid, "DataGrid"); validateBinding(null, grid.getSelectedIdBinding(), false, false, false, true, dataWidgetIdentifier, AttributeType.id); validateConditionName(grid.getDisabledConditionName(), dataWidgetIdentifier); validateConditionName(grid.getDisableAddConditionName(), dataWidgetIdentifier); validateConditionName(grid.getDisableEditConditionName(), dataWidgetIdentifier); validateConditionName(grid.getDisableRemoveConditionName(), dataWidgetIdentifier); validateConditionName(grid.getDisableZoomConditionName(), dataWidgetIdentifier); } @Override public void visitDataRepeater(DataRepeater repeater, boolean parentVisible, boolean parentEnabled) { visitDataWidget(repeater, "DataRepeater"); } private void visitDataWidget(AbstractDataWidget widget, String widgetDescription) { String title = widget.getTitle(); dataWidgetBinding = widget.getBinding(); StringBuilder sb = new StringBuilder(64); sb.append(widgetDescription); String widgetId = widget.getWidgetId(); if (widgetId != null) { sb.append(" with id ").append(widgetId); } if (title != null) { sb.append((sb.length() > 12) ? " and " : " with ").append("title ").append(title); } sb.append((sb.length() > 12) ? " and " : " with ").append("binding ").append(dataWidgetBinding); dataWidgetIdentifier = sb.toString(); validateBinding(null, dataWidgetBinding, true, false, false, false, dataWidgetIdentifier, AttributeType.collection, AttributeType.inverseMany); validateConditionName(widget.getInvisibleConditionName(), dataWidgetIdentifier); } @Override public void visitDataGridBoundColumn(DataGridBoundColumn column, boolean parentVisible, boolean parentEnabled) { String columnIdentifier = "Column " + column.getTitle() + " of " + dataWidgetIdentifier; validateBinding(dataWidgetBinding, column.getBinding(), false, false, false, false, columnIdentifier); } @Override public void visitedDataGridBoundColumn(DataGridBoundColumn column, boolean parentVisible, boolean parentEnabled) { // nothing to do } @Override public void visitDataGridContainerColumn(DataGridContainerColumn column, boolean parentVisible, boolean parentEnabled) { // nothing to do } @Override public void visitedDataGridContainerColumn(DataGridContainerColumn column, boolean parentVisible, boolean parentEnabled) { // nothing to do } @Override public void visitDialogButton(DialogButton button, boolean parentVisible, boolean parentEnabled) { String buttonIdentifier = "A Dialog Button" + button.getDialogName(); validateConditionName(button.getDisabledConditionName(), buttonIdentifier); validateConditionName(button.getInvisibleConditionName(), buttonIdentifier); validateParameterBindings(button.getParameters(), buttonIdentifier); } @Override public void visitForm(Form form, boolean parentVisible, boolean parentEnabled) { String formIdentifier = form.getWidgetId(); if (formIdentifier == null) { formIdentifier = "A Form"; } else { formIdentifier = "Form " + formIdentifier; } validateConditionName(form.getDisabledConditionName(), formIdentifier); validateConditionName(form.getInvisibleConditionName(), formIdentifier); validateMessageBindings(form.getBorderTitle(), formIdentifier, "borderTitle"); } @Override public void visitFormColumn(FormColumn column, boolean parentVisible, boolean parentEnabled) { // nothing to validate } @Override public void visitFormRow(FormRow row, boolean parentVisible, boolean parentEnabled) { if (row.getItems().isEmpty()) { throw new MetaDataException("A form row in " + viewIdentifier + " is empty (has not items declared)."); } } @Override public void visitFormItem(FormItem item, boolean parentVisible, boolean parentEnabled) { // TODO Implement FormItem validation } @Override public void visitGeometry(Geometry geometry, boolean parentVisible, boolean parentEnabled) { String geometryIdentifier = "Geometry " + geometry.getBinding(); validateBinding(null, geometry.getBinding(), true, false, false, true, geometryIdentifier, AttributeType.geometry); validateConditionName(geometry.getDisabledConditionName(), geometryIdentifier); validateConditionName(geometry.getInvisibleConditionName(), geometryIdentifier); } @Override public void visitedGeometry(Geometry geometry, boolean parentVisible, boolean parentEnabled) { // nothing to validate } @Override public void visitGeometryMap(GeometryMap geometry, boolean parentVisible, boolean parentEnabled) { String geometryIdentifier = "GeometryMap " + geometry.getBinding(); validateBinding(null, geometry.getBinding(), true, false, false, true, geometryIdentifier, AttributeType.geometry); validateConditionName(geometry.getDisabledConditionName(), geometryIdentifier); validateConditionName(geometry.getInvisibleConditionName(), geometryIdentifier); } @Override public void visitedGeometryMap(GeometryMap geometry, boolean parentVisible, boolean parentEnabled) { // nothing to validate } @Override public void visitMap(MapDisplay map, boolean parentVisible, boolean parentEnabled) { String geometryIdentifier = "Map with model " + map.getModelName(); validateConditionName(map.getInvisibleConditionName(), geometryIdentifier); validateMapModelName(map.getModelName(), geometryIdentifier); } @Override public void visitChart(Chart chart, boolean parentVisible, boolean parentEnabled) { String modelName = chart.getModelName(); ChartBuilderMetaData model = chart.getModel(); String chartIdentifier = "Chart" + ((model == null) ? ((modelName == null) ? " with no model" : " with model named " + modelName) : " with model label " + model.getLabel()); if (((modelName == null) && (model == null)) || ((modelName != null) && (model != null))) { throw new MetaDataException(chartIdentifier + " in " + viewIdentifier + " requires a modelName or a model but not both."); } validateConditionName(chart.getInvisibleConditionName(), chartIdentifier); if (modelName != null) { validateChartModelName(chart.getModelName(), chartIdentifier); } else { validateChartModel(model, chartIdentifier); } } private void validateChartModel(ChartBuilderMetaData model, String chartIdentifier) { Module contextModule = null; try { contextModule = customer.getModule(model.getModuleName()); } catch (Exception e) { throw new MetaDataException(chartIdentifier + " in " + viewIdentifier + " has an invalid moduleName of " + model.getModuleName(), e); } String documentName = model.getDocumentName(); String queryName = model.getQueryName(); Document contextDocument = null; if (documentName != null) { try { contextDocument = contextModule.getDocument(customer, documentName); } catch (Exception e) { throw new MetaDataException(chartIdentifier + " in " + viewIdentifier + " has an invalid documentName of " + documentName, e); } } else if (queryName != null) { MetaDataQueryDefinition query = contextModule.getMetaDataQuery(queryName); if (query == null) { throw new MetaDataException(chartIdentifier + " in " + viewIdentifier + " has an invalid queryName of " + queryName); } contextDocument = query.getDocumentModule(customer).getDocument(customer, queryName); } else { throw new MetaDataException(chartIdentifier + " in " + viewIdentifier + " needs either a documentName or queryName"); } validateBinding(contextModule, contextDocument, null, model.getCategoryBinding(), true, false, false, true, chartIdentifier + " category binding", AttributeType.bool, AttributeType.colour, AttributeType.date, AttributeType.dateTime, AttributeType.decimal2, AttributeType.decimal5, AttributeType.decimal10, AttributeType.enumeration, AttributeType.integer, AttributeType.longInteger, AttributeType.markup, AttributeType.memo, AttributeType.text, AttributeType.time, AttributeType.timestamp); String valueBinding = model.getValueBinding(); validateBinding(contextModule, contextDocument, null, valueBinding, true, false, false, true, chartIdentifier + " value binding"); AggregateFunction function = model.getValueFunction(); TargetMetaData target = BindUtil.getMetaDataForBinding(customer, contextModule, contextDocument, valueBinding); Attribute attribute = target.getAttribute(); // check for numeric value if no value function is defined if (function == null) { // we need a number here boolean invalidValueType = false; if (attribute == null) { // implicit attribute invalidValueType = true; } else { AttributeType type = attribute.getAttributeType(); invalidValueType = (! Number.class.isAssignableFrom(type.getImplementingType())); } if (invalidValueType) { throw new MetaDataException(chartIdentifier + " in " + viewIdentifier + " has an invalid value binding of " + valueBinding + " to a non-numeric or implicit attribute"); } } // check that aggregate function can be numeric, otherwise must be count else { if (! AggregateFunction.Count.equals(function)) { String invalidFunctionType = null; if (attribute == null) { // implicit attribute invalidFunctionType = "an implicit attribute"; } else { AttributeType type = attribute.getAttributeType(); if (! Number.class.isAssignableFrom(type.getImplementingType())) { invalidFunctionType = "a non-numeric type of " + type; } } if (invalidFunctionType != null) { throw new MetaDataException(chartIdentifier + " in " + viewIdentifier + " has an invalid valueFunction of " + function + " for a value binding which is to " + invalidFunctionType); } } } } @Override public void visitHBox(HBox hbox, boolean parentVisible, boolean parentEnabled) { String borderTitle = hbox.getBorderTitle(); String id = hbox.getWidgetId(); String boxIdentifier = ((id == null) ? "A HBox" : "HBox " + id) + ((borderTitle == null) ? "" : " titled " + borderTitle); validateConditionName(hbox.getInvisibleConditionName(), boxIdentifier); validateMessageBindings(hbox.getBorderTitle(), boxIdentifier, "borderTitle"); } @Override public void visitHTML(HTML html, boolean parentVisible, boolean parentEnabled) { String binding = html.getBinding(); String htmlIdentifier = "HTML " + html.getBinding(); if (dataWidgetBinding != null) { htmlIdentifier += " in " + dataWidgetIdentifier; } validateBinding(dataWidgetBinding, binding, true, false, false, true, htmlIdentifier, AttributeType.markup); validateConditionName(html.getDisabledConditionName(), htmlIdentifier); validateConditionName(html.getInvisibleConditionName(), htmlIdentifier); } @Override public void visitBlurb(Blurb blurb, boolean parentVisible, boolean parentEnabled) { String blurbIdentifier = "A Blurb"; if (dataWidgetBinding != null) { blurbIdentifier += " in " + dataWidgetIdentifier; } String markup = blurb.getMarkup(); if (markup == null) { throw new MetaDataException(blurbIdentifier + " in " + viewIdentifier + " has no markup specified."); } validateMessageBindings(blurb.getMarkup(), blurbIdentifier, "markup"); validateConditionName(blurb.getInvisibleConditionName(), blurbIdentifier); } @Override public void visitLabel(Label label, boolean parentVisible, boolean parentEnabled) { String labelIdentifier = "A Label"; if (dataWidgetBinding != null) { labelIdentifier += " in " + dataWidgetIdentifier; } validateBinding(dataWidgetBinding, label.getBinding(), false, false, false, true, labelIdentifier); validateBinding(dataWidgetBinding, label.getFor(), false, false, false, false, labelIdentifier); validateMessageBindings(label.getValue(), labelIdentifier, "a value"); validateConditionName(label.getInvisibleConditionName(), labelIdentifier); } @Override public void visitListGrid(ListGrid grid, boolean parentVisible, boolean parentEnabled) { String queryName = grid.getQueryName(); String modelName = grid.getModelName(); String listGridIdentifier = "ListGrid " + ((modelName != null) ? modelName : queryName); validateConditionName(grid.getDisabledConditionName(), listGridIdentifier); validateConditionName(grid.getInvisibleConditionName(), listGridIdentifier); validateConditionName(grid.getDisableAddConditionName(), listGridIdentifier); validateConditionName(grid.getDisableEditConditionName(), listGridIdentifier); validateConditionName(grid.getDisableZoomConditionName(), listGridIdentifier); validateConditionName(grid.getDisableRemoveConditionName(), listGridIdentifier); validateConditionName(grid.getPostRefreshConditionName(), listGridIdentifier); validateBinding(null, grid.getSelectedIdBinding(), false, false, false, true, listGridIdentifier, AttributeType.id); validateFilterParameterBindings(grid.getFilterParameters(), listGridIdentifier); validateParameterBindings(grid.getParameters(), listGridIdentifier); validateNoColonInFilterParameter(grid.getFilterParameters(), listGridIdentifier); validateNoColonInParameter(grid.getParameters(), listGridIdentifier); validateQueryOrModel(queryName, modelName, listGridIdentifier); } @Override public void visitListRepeater(ListRepeater repeater, boolean parentVisible, boolean parentEnabled) { String queryName = repeater.getQueryName(); String modelName = repeater.getModelName(); String listRepeaterIdentifier = "ListRepeater " + ((modelName != null) ? modelName : queryName); validateConditionName(repeater.getInvisibleConditionName(), listRepeaterIdentifier); validateConditionName(repeater.getPostRefreshConditionName(), listRepeaterIdentifier); validateFilterParameterBindings(repeater.getFilterParameters(), listRepeaterIdentifier); validateParameterBindings(repeater.getParameters(), listRepeaterIdentifier); validateNoColonInFilterParameter(repeater.getFilterParameters(), listRepeaterIdentifier); validateNoColonInParameter(repeater.getParameters(), listRepeaterIdentifier); validateQueryOrModel(queryName, modelName, listRepeaterIdentifier); } @Override public void visitTreeGrid(TreeGrid grid, boolean parentVisible, boolean parentEnabled) { String queryName = grid.getQueryName(); String modelName = grid.getModelName(); String treeGridIdentifier = "TreeGrid " + ((modelName != null) ? modelName : queryName); validateConditionName(grid.getDisabledConditionName(), treeGridIdentifier); validateConditionName(grid.getInvisibleConditionName(), treeGridIdentifier); validateConditionName(grid.getDisableAddConditionName(), treeGridIdentifier); validateConditionName(grid.getDisableEditConditionName(), treeGridIdentifier); validateConditionName(grid.getDisableZoomConditionName(), treeGridIdentifier); validateConditionName(grid.getDisableRemoveConditionName(), treeGridIdentifier); validateConditionName(grid.getPostRefreshConditionName(), treeGridIdentifier); validateBinding(null, grid.getSelectedIdBinding(), false, false, false, true, treeGridIdentifier, AttributeType.id); validateBinding(null, grid.getRootIdBinding(), false, false, false, true, treeGridIdentifier); validateFilterParameterBindings(grid.getFilterParameters(), treeGridIdentifier); validateParameterBindings(grid.getParameters(), treeGridIdentifier); validateNoColonInFilterParameter(grid.getFilterParameters(), treeGridIdentifier); validateNoColonInParameter(grid.getParameters(), treeGridIdentifier); validateQueryOrModel(queryName, modelName, treeGridIdentifier); } @Override public void visitListMembership(ListMembership membership, boolean parentVisible, boolean parentEnabled) { String membershipIdentifier = "ListMembership " + membership.getBinding(); validateBinding(null, membership.getBinding(), true, false, true, false, membershipIdentifier, AttributeType.collection, AttributeType.inverseMany); validateConditionName(membership.getDisabledConditionName(), membershipIdentifier); validateConditionName(membership.getInvisibleConditionName(), membershipIdentifier); } @Override public void visitedListMembership(ListMembership membership, boolean parentVisible, boolean parentEnabled) { // do nothing } @Override public void visitComparison(Comparison comparison, boolean parentVisible, boolean parentEnabled) { String comparisonIdentifier = "Comparison " + comparison.getBinding(); validateBinding(null, comparison.getBinding(), true, true, false, false, comparisonIdentifier, AttributeType.association); validateConditionName(comparison.getDisabledConditionName(), comparisonIdentifier); validateConditionName(comparison.getInvisibleConditionName(), comparisonIdentifier); validateComparisonModelName(comparison.getModelName(), comparisonIdentifier); } @Override public void visitLookup(Lookup lookup, boolean parentVisible, boolean parentEnabled) { String binding = lookup.getBinding(); String lookupIdentifier = "Lookup " + binding; if (dataWidgetBinding != null) { lookupIdentifier += " in " + dataWidgetIdentifier; } validateBinding(dataWidgetBinding, binding, true, true, false, false, lookupIdentifier, AttributeType.association); validateConditionName(lookup.getDisabledConditionName(), lookupIdentifier); validateConditionName(lookup.getInvisibleConditionName(), lookupIdentifier); validateConditionName(lookup.getDisablePickConditionName(), lookupIdentifier); validateConditionName(lookup.getDisableEditConditionName(), lookupIdentifier); validateConditionName(lookup.getDisableAddConditionName(), lookupIdentifier); validateConditionName(lookup.getDisableClearConditionName(), lookupIdentifier); validateFilterParameterBindings(lookup.getFilterParameters(), lookupIdentifier); validateParameterBindings(lookup.getParameters(), lookupIdentifier); validateNoColonInFilterParameter(lookup.getFilterParameters(), lookupIdentifier); validateNoColonInParameter(lookup.getParameters(), lookupIdentifier); validateQueryName(lookup.getQuery(), lookupIdentifier); } @Override public void visitedLookup(Lookup lookup, boolean parentVisible, boolean parentEnabled) { // do nothing } @Override public void visitLookupDescription(LookupDescription lookup, boolean parentVisible, boolean parentEnabled) { String binding = lookup.getBinding(); String descriptionBinding = lookup.getDescriptionBinding(); String lookupIdentifier = "LookupDescription " + binding; // A lookupDescription in a data grid bound to an aggregated collection // doesn't have to have a binding validateBinding(dataWidgetBinding, binding, (dataWidgetBinding == null), false, false, false, lookupIdentifier, AttributeType.association, AttributeType.inverseOne); validateBinding(dataWidgetBinding, // binding can be null if dataGridBinding is set and this // is a lookup to the elements in the collection (binding == null) ? descriptionBinding : BindUtil.createCompoundBinding(binding, descriptionBinding), true, false, false, true, lookupIdentifier); validateConditionName(lookup.getDisabledConditionName(), lookupIdentifier); validateConditionName(lookup.getInvisibleConditionName(), lookupIdentifier); validateConditionName(lookup.getDisablePickConditionName(), lookupIdentifier); validateConditionName(lookup.getDisableEditConditionName(), lookupIdentifier); validateConditionName(lookup.getDisableAddConditionName(), lookupIdentifier); validateConditionName(lookup.getDisableClearConditionName(), lookupIdentifier); validateFilterParameterBindings(lookup.getFilterParameters(), lookupIdentifier); validateParameterBindings(lookup.getParameters(), lookupIdentifier); validateNoColonInFilterParameter(lookup.getFilterParameters(), lookupIdentifier); validateNoColonInParameter(lookup.getParameters(), lookupIdentifier); validateQueryName(lookup.getQuery(), lookupIdentifier); // determine the query that will be used MetaDataQueryDefinition query = null; if (lookup.getQuery() != null) { query = module.getMetaDataQuery(lookup.getQuery()); } else { // NB Use getMetaDataForBinding() to ensure we find attributes from base documents inherited String fullBinding = binding; if (dataWidgetBinding != null) { if (binding == null) { fullBinding = dataWidgetBinding; } else { fullBinding = BindUtil.createCompoundBinding(dataWidgetBinding, binding); } } TargetMetaData target = Binder.getMetaDataForBinding(customer, module, document, fullBinding); Relation relation = (Relation) target.getAttribute(); String queryName = (relation instanceof Reference) ? ((Reference) relation).getQueryName() : null; if (queryName != null) { query = module.getMetaDataQuery(queryName); } else { query = module.getDocumentDefaultQuery(customer, relation.getDocumentName()); } } // validate drop down columns and description binding List<LookupDescriptionColumn> dropDownColumns = lookup.getDropDownColumns(); LinkedHashSet<String> testColumns = null; if (dropDownColumns != null) { testColumns = new LinkedHashSet<>(dropDownColumns.size()); for (LookupDescriptionColumn dropDownColumn : dropDownColumns) { String dropDownColumnName = dropDownColumn.getName(); if (! Bean.BIZ_KEY.equals(dropDownColumnName)) { testColumns.add(dropDownColumnName); } } } boolean foundLookupDescription = Bean.BIZ_KEY.equals(descriptionBinding); for (MetaDataQueryColumn column : query.getColumns()) { String alias = column.getName(); if (alias == null) { alias = column.getBinding(); } MetaDataQueryProjectedColumn projectedColumn = (column instanceof MetaDataQueryProjectedColumn) ? (MetaDataQueryProjectedColumn) column : null; if ((testColumns != null) && testColumns.contains(alias)) { if ((projectedColumn != null) && (! projectedColumn.isProjected())) { throw new MetaDataException(lookupIdentifier + " in " + viewIdentifier + " has a drop down column of " + alias + " which is not projected in the query."); } testColumns.remove(alias); } if ((! foundLookupDescription) && descriptionBinding.equals(alias)) { if ((projectedColumn != null) && (! projectedColumn.isProjected())) { throw new MetaDataException(lookupIdentifier + " in " + viewIdentifier + " has a description binding of " + alias + " which is not projected in the query."); } foundLookupDescription = true; } } if (! foundLookupDescription) { throw new MetaDataException(lookupIdentifier + " in " + viewIdentifier + " has a description binding of " + descriptionBinding + " which is not defined in the query."); } if ((testColumns != null) && (! testColumns.isEmpty())) { throw new MetaDataException(lookupIdentifier + " in " + viewIdentifier + " has a drop down column of " + testColumns.iterator().next() + " which is not defined in the query."); } } @Override public void visitedLookupDescription(LookupDescription lookup, boolean parentVisible, boolean parentEnabled) { // do nothing } @Override public void visitParameter(Parameter parameter, boolean parentVisible, boolean parentEnabled) { // Check that value or valueBinding is populated if ((parameter.getValue() == null) && (parameter.getValueBinding() == null)) { throw new MetaDataException("Parameter " + parameter.getName() + " requires either a value or a valueBinding."); } } @Override public void visitFilterParameter(FilterParameter parameter, boolean parentVisible, boolean parentEnabled) { // Check that value or valueBinding is populated for pertinent operators FilterOperator operator = parameter.getOperator(); if ((! FilterOperator.isNull.equals(operator)) && (! FilterOperator.notNull.equals(operator)) && (parameter.getValue() == null) && (parameter.getValueBinding() == null)) { throw new MetaDataException("Filter Parameter " + parameter.getFilterBinding() + " requires either a value or a valueBinding for operator " + parameter.getOperator()); } } @Override public void visitPassword(Password password, boolean parentVisible, boolean parentEnabled) { String binding = password.getBinding(); String passwordIdentifier = "Password " + binding; if (dataWidgetBinding != null) { passwordIdentifier += " in " + dataWidgetIdentifier; } validateBinding(dataWidgetBinding, binding, true, false, false, true, passwordIdentifier, AttributeType.text); validateConditionName(password.getDisabledConditionName(), passwordIdentifier); validateConditionName(password.getInvisibleConditionName(), passwordIdentifier); } @Override public void visitedPassword(Password password, boolean parentVisible, boolean parentEnabled) { // do nothing } @Override public void visitProgressBar(ProgressBar progressBar, boolean parentVisible, boolean parentEnabled) { String progressBarIdentifier = "ProgressBar " + progressBar.getBinding(); validateBinding(null, progressBar.getBinding(), true, false, false, true, progressBarIdentifier); validateConditionName(progressBar.getInvisibleConditionName(), progressBarIdentifier); } @Override public void visitRadio(Radio radio, boolean parentVisible, boolean parentEnabled) { String binding = radio.getBinding(); String radioIdentifier = "Radio " + binding; if (dataWidgetBinding != null) { radioIdentifier += " in " + dataWidgetIdentifier; } validateBinding(dataWidgetBinding, binding, true, false, true, false, radioIdentifier, AttributeType.enumeration, AttributeType.text, AttributeType.association, AttributeType.inverseOne, AttributeType.bool, AttributeType.integer, AttributeType.longInteger); validateConditionName(radio.getDisabledConditionName(), radioIdentifier); validateConditionName(radio.getInvisibleConditionName(), radioIdentifier); } @Override public void visitedRadio(Radio radio, boolean parentVisible, boolean parentEnabled) { // do nothing } @Override public void visitRichText(RichText richText, boolean parentVisible, boolean parentEnabled) { String binding = richText.getBinding(); String richTextIdentifier = "RichText " + binding; if (dataWidgetBinding != null) { richTextIdentifier += " in " + dataWidgetIdentifier; } validateBinding(dataWidgetBinding, binding, true, false, false, true, richTextIdentifier, AttributeType.memo, AttributeType.markup); validateConditionName(richText.getDisabledConditionName(), richTextIdentifier); validateConditionName(richText.getInvisibleConditionName(), richTextIdentifier); } @Override public void visitedRichText(RichText richText, boolean parentVisible, boolean parentEnabled) { // do nothing } @Override public void visitSlider(Slider slider, boolean parentVisible, boolean parentEnabled) { String binding = slider.getBinding(); String sliderIdentifier = "Slider " + binding; if (dataWidgetBinding != null) { sliderIdentifier += " in " + dataWidgetBinding; } validateBinding(dataWidgetBinding, binding, true, false, false, true, sliderIdentifier); validateConditionName(slider.getDisabledConditionName(), sliderIdentifier); validateConditionName(slider.getInvisibleConditionName(), sliderIdentifier); } @Override public void visitedSlider(Slider slider, boolean parentVisible, boolean parentEnabled) { // do nothing } @Override public void visitSpacer(Spacer spacer) { validateConditionName(spacer.getInvisibleConditionName(), "A Spacer"); } @Override public void visitSpinner(Spinner spinner, boolean parentVisible, boolean parentEnabled) { String binding = spinner.getBinding(); String spinnerIdentifier = "Spinner " + binding; if (dataWidgetBinding != null) { spinnerIdentifier += " in " + dataWidgetBinding; } validateBinding(dataWidgetBinding, binding, true, false, false, true, spinnerIdentifier); validateConditionName(spinner.getDisabledConditionName(), spinnerIdentifier); validateConditionName(spinner.getInvisibleConditionName(), spinnerIdentifier); } @Override public void visitedSpinner(Spinner spinner, boolean parentVisible, boolean parentEnabled) { // do nothing } @Override public void visitStaticImage(StaticImage image, boolean parentVisible, boolean parentEnabled) { String imageIdentifier = "StaticImage " + image.getRelativeFile(); validateConditionName(image.getInvisibleConditionName(), imageIdentifier); } @Override public void visitLink(Link link, boolean parentVisible, boolean parentEnabled) { final String linkIdentifier = "Link " + link.getValue(); validateConditionName(link.getInvisibleConditionName(), linkIdentifier); new ReferenceProcessor() { @SuppressWarnings("synthetic-access") private ModuleImpl validateReferenceModuleName(String referenceModuleName, String referenceDescription) { ModuleImpl result = null; if (referenceModuleName.indexOf('{') < 0) { try { result = (ModuleImpl) customer.getModule(referenceModuleName); if (result == null) { throw new MetaDataException(referenceModuleName + " DNE"); } } catch (Exception e) { throw new MetaDataException(linkIdentifier + " in " + viewIdentifier + " has " + referenceDescription + " reference with an invalid module of " + referenceModuleName, e); } } return result; } @SuppressWarnings("synthetic-access") private DocumentImpl validateReferenceDocumentName(ModuleImpl referenceModule, String referenceDocumentName, String referenceDescription) { DocumentImpl result = null; if (referenceDocumentName.indexOf('{') < 0) { try { result = (DocumentImpl) referenceModule.getDocument(customer, referenceDocumentName); if (result == null) { throw new MetaDataException(referenceDocumentName + " DNE"); } return result; } catch (Exception e) { throw new MetaDataException(linkIdentifier + " in " + viewIdentifier + " has " + referenceDescription + " reference with an invalid document of " + referenceModule.getName() + '.' + referenceDocumentName, e); } } return result; } @SuppressWarnings("synthetic-access") private TargetMetaData validateReferenceBinding(String referenceBinding, String referenceDescription) { String bindingToTest = referenceBinding; if (dataWidgetBinding != null) { if (referenceBinding == null) { bindingToTest = dataWidgetBinding; } else { bindingToTest = BindUtil.createCompoundBinding(dataWidgetBinding, referenceBinding); } } TargetMetaData result = null; // NB bindingToTest can be null when a link to an edit view for a new document instance // and the link is NOT in a grid container column if (bindingToTest != null) { try { result = BindUtil.getMetaDataForBinding(customer, module, document, bindingToTest); if (result == null) { throw new IllegalStateException("Target DNE"); } return result; } catch (MetaDataException e) { throw new MetaDataException(linkIdentifier + " in " + viewIdentifier + " has " + referenceDescription + " reference with an invalid binding of " + referenceBinding, e); } } return result; } @Override public void processResourceReference(ResourceReference reference) { // nothing to do here } @Override @SuppressWarnings("synthetic-access") public void processReportReference(ReportReference reference) { ModuleImpl reportModule = validateReferenceModuleName(reference.getModuleName(), "a report"); if (reportModule != null) { // valid module name with no '{' DocumentImpl reportDocument = validateReferenceDocumentName(reportModule, reference.getDocumentName(), "a report"); if (reportDocument != null) { // valid module name with no '{' try { if (repository.getReportFileName(customer, reportDocument, reference.getReportName()) == null) { throw new IllegalStateException("Report DNE"); } } catch (Exception e) { throw new MetaDataException(linkIdentifier + " in " + viewIdentifier + " has a report reference with an invalid report name of " + reportModule.getName() + '.' + reportDocument.getName() + '.' + reference.getReportName(), e); } } } validateParameterBindings(reference.getParameters(), linkIdentifier); } @Override @SuppressWarnings("synthetic-access") public void processQueryListViewReference(QueryListViewReference reference) { try { if (module.getMetaDataQuery(reference.getQueryName()) == null) { throw new IllegalStateException("No such query"); } } catch (Exception e) { throw new MetaDataException(linkIdentifier + " in " + viewIdentifier + " has a query list view reference with an invalid query name of " + reference.getQueryName(), e); } } @Override public void processImplicitActionReference(ImplicitActionReference reference) { // nothing to do here } @Override public void processExternalReference(ExternalReference reference) { // nothing to do here } @Override public void processEditViewReference(EditViewReference reference) { ModuleImpl viewModule = validateReferenceModuleName(reference.getModuleName(), "an edit view"); if (viewModule != null) { // valid module name with no '{' validateReferenceDocumentName(viewModule, reference.getDocumentName(), "an edit view"); } validateReferenceBinding(reference.getBinding(), "an edit view"); } @Override public void processDefaultListViewReference(DefaultListViewReference reference) { ModuleImpl viewModule = validateReferenceModuleName(reference.getModuleName(), "an edit view"); if (viewModule != null) { // valid module name with no '{' validateReferenceDocumentName(viewModule, reference.getDocumentName(), "an edit view"); } validateReferenceBinding(reference.getBinding(), "an edit view"); } @Override @SuppressWarnings("synthetic-access") public void processContentReference(ContentReference reference) { String widgetidentifier = linkIdentifier + " with a content reference"; if (dataWidgetBinding != null) { widgetidentifier += " in " + dataWidgetIdentifier; } validateBinding(dataWidgetBinding, reference.getBinding(), true, false, false, true, widgetidentifier, AttributeType.content); } @Override @SuppressWarnings("synthetic-access") public void processActionReference(ActionReference reference) { String widgetIdentifier = linkIdentifier + " with an action reference"; if (dataWidgetBinding != null) { // in a repeater or grid widgetIdentifier += " in " + dataWidgetBinding; String actionName = reference.getActionName(); try { TargetMetaData target = validateReferenceBinding(null, "an action reference"); Reference targetReference = (Reference) target.getAttribute(); if (targetReference == null) { throw new MetaDataException("Target Reference " + dataWidgetBinding + " DNE"); } ModuleImpl targetModule = (ModuleImpl) customer.getModule(target.getDocument().getOwningModuleName()); DocumentImpl targetDocument = (DocumentImpl) targetModule.getDocument(customer, targetReference.getDocumentName()); // This is a container column of an existing row in a table/grid - so get the edit view ViewImpl targetView = (ViewImpl) targetDocument.getView(uxui, customer, ViewType.edit.toString()); if (targetView.getAction(actionName) == null) { throw new MetaDataException(actionName + " DNE"); } } catch (Exception e) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " references a non-existent action " + actionName, e); } } else { validateActionName(reference.getActionName(), widgetIdentifier); } } }.process(link.getReference()); } @Override public void visitTab(Tab tab, boolean parentVisible, boolean parentEnabled) { String tabIdentifier = "Tab " + tab.getTitle(); validateConditionName(tab.getDisabledConditionName(), tabIdentifier); validateConditionName(tab.getInvisibleConditionName(), tabIdentifier); validateMessageBindings(tab.getTitle(), tabIdentifier, "title"); } @Override public void visitTabPane(TabPane tabPane, boolean parentVisible, boolean parentEnabled) { String tabPaneIdentifier = tabPane.getWidgetId(); if (tabPaneIdentifier != null) { tabPaneIdentifier = "TabPane " + tabPaneIdentifier; } else { tabPaneIdentifier = "A TabPane"; } validateConditionName(tabPane.getDisabledConditionName(), tabPaneIdentifier); validateConditionName(tabPane.getInvisibleConditionName(), tabPaneIdentifier); validateBinding(null, tabPane.getSelectedTabIndexBinding(), false, false, false, true, "The [selectedTabIndexBinding] of " + tabPaneIdentifier, AttributeType.integer, AttributeType.longInteger); } @Override public void visitTextArea(TextArea text, boolean parentVisible, boolean parentEnabled) { String binding = text.getBinding(); String textIdentifier = "TextArea " + binding; if (dataWidgetBinding != null) { textIdentifier += " in " + dataWidgetBinding; } validateBinding(dataWidgetBinding, binding, true, false, false, true, textIdentifier); validateConditionName(text.getDisabledConditionName(), textIdentifier); validateConditionName(text.getInvisibleConditionName(), textIdentifier); } @Override public void visitedTextArea(TextArea text, boolean parentVisible, boolean parentEnabled) { // do nothing } @Override public void visitTextField(TextField text, boolean parentVisible, boolean parentEnabled) { String binding = text.getBinding(); String textIdentifier = "Text " + binding; if (dataWidgetBinding != null) { textIdentifier += " in " + dataWidgetBinding; } validateBinding(dataWidgetBinding, binding, true, false, false, true, textIdentifier); validateConditionName(text.getDisabledConditionName(), textIdentifier); validateConditionName(text.getInvisibleConditionName(), textIdentifier); } @Override public void visitedTextField(TextField text, boolean parentVisible, boolean parentEnabled) { // do nothing } @Override public void visitInject(Inject inject, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitVBox(VBox vbox, boolean parentVisible, boolean parentEnabled) { String borderTitle = vbox.getBorderTitle(); String id = vbox.getWidgetId(); String boxIdentifier = ((id == null) ? "A VBox" : "VBox " + id) + ((borderTitle == null) ? "" : " titled " + borderTitle); validateConditionName(vbox.getInvisibleConditionName(), boxIdentifier); validateMessageBindings(vbox.getBorderTitle(), boxIdentifier, "borderTitle"); } @Override public void visitView() { validateMessageBindings(view.getTitle(), viewIdentifier, "a title"); List<ViewParameter> parameters = view.getParameters(); if (parameters != null) { for (ViewParameter parameter : parameters) { validateBinding(null, parameter.getBoundTo(), false, false, false, false, "Parameter " + parameter.getFromBinding() + " in " + viewIdentifier); } } validateActionName(view.getRefreshActionName(), viewIdentifier); validateConditionName(view.getRefreshConditionName(), viewIdentifier); if ((view.getHelpURL() != null) && (view.getHelpRelativeFileName() != null)) { throw new MetaDataException(viewIdentifier + " should define one of helpURL or helpRelativeFileName but not both"); } } @Override public void visitedDataGrid(DataGrid grid, boolean parentVisible, boolean parentEnabled) { dataWidgetBinding = null; dataWidgetIdentifier = null; } @Override public void visitedDataRepeater(DataRepeater repeater, boolean parentVisible, boolean parentEnabled) { dataWidgetBinding = null; dataWidgetIdentifier = null; } @Override public void visitedForm(Form form, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitedFormItem(FormItem item, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitedFormRow(FormRow row, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitedHBox(HBox hbox, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitedListGrid(ListGrid grid, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitedListRepeater(ListRepeater repeater, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitedTreeGrid(TreeGrid grid, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitedTab(Tab tab, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitedTabPane(TabPane tabPane, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitedVBox(VBox vbox, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitedView() { // nothing to do here } private void validateAction(ActionImpl action) { String actionIdentifier = "Action " + action.getName(); validateConditionName(action.getDisabledConditionName(), actionIdentifier); validateConditionName(action.getInvisibleConditionName(), actionIdentifier); validateParameterBindings(action.getParameters(), actionIdentifier); } // validate the resource name which represents the class to load for ClassActions private void validateClassAction(String resourceName) { String fullyQualifiedJavaCodeName = String.format("%s.%s.actions.%s", document.getOwningModuleName(), document.getName(), resourceName); if (repository.getJavaClass(customer, fullyQualifiedJavaCodeName) == null) { throw new MetaDataException(fullyQualifiedJavaCodeName + " not found."); } } @Override public void visitCustomAction(ActionImpl action) { validateClassAction(action.getResourceName()); validateAction(action); } @Override public void visitAddAction(ActionImpl action) { validateAction(action); } @Override public void visitBizExportAction(ActionImpl action) { validateClassAction(action.getResourceName()); validateAction(action); } @Override public void visitBizImportAction(ActionImpl action) { validateClassAction(action.getResourceName()); validateAction(action); } @Override public void visitDownloadAction(ActionImpl action) { validateClassAction(action.getResourceName()); validateAction(action); } @Override public void visitUploadAction(ActionImpl action) { validateClassAction(action.getResourceName()); validateAction(action); } @Override public void visitCancelAction(ActionImpl action) { validateAction(action); } @Override public void visitDeleteAction(ActionImpl action) { validateAction(action); } @Override public void visitEditAction(ActionImpl action) { validateAction(action); } @Override public void visitNavigateAction(ActionImpl action) { validateAction(action); } @Override public void visitNewAction(ActionImpl action) { validateAction(action); } @Override public void visitOKAction(ActionImpl action) { validateAction(action); } @Override public void visitRemoveAction(ActionImpl action) { validateAction(action); } @Override public void visitReportAction(ActionImpl action) { validateAction(action); } @Override public void visitSaveAction(ActionImpl action) { validateAction(action); } @Override public void visitZoomOutAction(ActionImpl action) { validateAction(action); } private static void validateEventHandlerSequence(List<EventAction> actions, String widgetIdentifier) { if (actions != null) { Iterator<EventAction> i = actions.iterator(); while (i.hasNext()) { EventAction action = i.next(); if (i.hasNext()) { if (action instanceof RerenderEventAction) { throw new MetaDataException("[rerender] event action in " + widgetIdentifier + " has to be the last action as it is a server-side action."); } else if (action instanceof ServerSideActionEventAction) { throw new MetaDataException("[server] event action to action " + ((ServerSideActionEventAction) action).getActionName() + " in " + widgetIdentifier + " has to be the last action as it is a server-side action."); } } } } } @Override public void visitOnChangedEventHandler(Changeable changeable, boolean parentVisible, boolean parentEnabled) { validateEventHandlerSequence(changeable.getChangedActions(), "[onChanged] event handler for widget with binding " + changeable.getBinding()); } @Override public void visitedOnChangedEventHandler(Changeable changeable, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitOnFocusEventHandler(Focusable focusable, boolean parentVisible, boolean parentEnabled) { String binding = (focusable instanceof Bound) ? ((Bound) focusable).getBinding() : "unknown"; validateEventHandlerSequence(focusable.getFocusActions(), "[onFocus] event handler for widget with binding " + binding); } @Override public void visitedOnFocusEventHandler(Focusable blurable, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitOnBlurEventHandler(Focusable focusable, boolean parentVisible, boolean parentEnabled) { String binding = (focusable instanceof Bound) ? ((Bound) focusable).getBinding() : "unknown"; validateEventHandlerSequence(focusable.getBlurActions(), "[onBlur] event handler for widget with binding " + binding); } @Override public void visitedOnBlurEventHandler(Focusable blurable, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitOnAddedEventHandler(Addable addable, boolean parentVisible, boolean parentEnabled) { String widgetIdentifier = "Unknown widget"; if (addable instanceof Bound) { widgetIdentifier = "[onAdded] event handler for widget with binding " + ((Bound) addable).getBinding(); } else if (addable instanceof ListGrid) { widgetIdentifier = "[onAdded] event handler for list grid with query " + ((ListGrid) addable).getQueryName(); } validateEventHandlerSequence(addable.getAddedActions(), widgetIdentifier); } @Override public void visitedOnAddedEventHandler(Addable addable, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitOnEditedEventHandler(Editable editable, boolean parentVisible, boolean parentEnabled) { String widgetIdentifier = "Unknown widget"; if (editable instanceof Bound) { widgetIdentifier = "[onEdited] event handler for widget with binding " + ((Bound) editable).getBinding(); } else if (editable instanceof ListGrid) { widgetIdentifier = "[onEdited] event handler for list grid with query " + ((ListGrid) editable).getQueryName(); } validateEventHandlerSequence(editable.getEditedActions(), widgetIdentifier); } @Override public void visitedOnEditedEventHandler(Editable editable, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitOnRemovedEventHandler(Removable removable, boolean parentVisible, boolean parentEnabled) { String widgetIdentifier = "Unknown widget"; if (removable instanceof Bound) { widgetIdentifier = "[onRemoved] event handler for widget with binding " + ((Bound) removable).getBinding(); } else if (removable instanceof ListGrid) { widgetIdentifier = "[onRemoved] event handler for list grid with query " + ((ListGrid) removable).getQueryName(); } validateEventHandlerSequence(removable.getRemovedActions(), widgetIdentifier); } @Override public void visitedOnRemovedEventHandler(Removable removable, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitOnSelectedEventHandler(Selectable selectable, boolean parentVisible, boolean parentEnabled) { String widgetIdentifier = "Unknown widget"; if (selectable instanceof Bound) { widgetIdentifier = "[onSelected] event handler for widget with binding " + ((Bound) selectable).getBinding(); } else if (selectable instanceof ListGrid) { widgetIdentifier = "[onSelected] event handler for list grid with query " + ((ListGrid) selectable).getQueryName(); } validateEventHandlerSequence(selectable.getSelectedActions(), widgetIdentifier); } @Override public void visitedOnSelectedEventHandler(Selectable editable, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitOnPickedEventHandler(Lookup lookup, boolean parentVisible, boolean parentEnabled) { validateEventHandlerSequence(lookup.getPickedActions(), "[onPicked] event handler for lookup with binding " + lookup.getBinding()); } @Override public void visitedOnPickedEventHandler(Lookup lookup, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitOnClearedEventHandler(Lookup lookup, boolean parentVisible, boolean parentEnabled) { validateEventHandlerSequence(lookup.getClearedActions(), "[onCleared] event handler for lookup with binding " + lookup.getBinding()); } @Override public void visitedOnClearedEventHandler(Lookup lookup, boolean parentVisible, boolean parentEnabled) { // nothing to do here } @Override public void visitRerenderEventAction(RerenderEventAction rerender, EventSource source, boolean parentVisible, boolean parentEnabled) { // no properties to check } @Override public void visitServerSideActionEventAction(ServerSideActionEventAction server, boolean parentVisible, boolean parentEnabled) { validateActionName(server.getActionName(), "[server] event action in an event handler"); } @Override public void visitSetDisabledEventAction(SetDisabledEventAction setDisabled, boolean parentVisible, boolean parentEnabled) { String widgetIdentifier = "[setDisabled] event action in an event handler"; validateBinding(null, setDisabled.getBinding(), true, false, false, false, widgetIdentifier, AttributeType.bool); String disabledConditionName = setDisabled.getDisabledConditionName(); if (disabledConditionName == null) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " requires a [disabled] or [enabled] condition name."); } validateConditionName(disabledConditionName, widgetIdentifier); } @Override public void visitToggleDisabledEventAction(ToggleDisabledEventAction toggleDisabled, boolean parentVisible, boolean parentEnabled) { String widgetIdentifier = "[toggleDisabled] event action in an event handler"; validateBinding(null, toggleDisabled.getBinding(), true, false, false, false, widgetIdentifier, AttributeType.bool); } @Override public void visitToggleVisibilityEventAction(ToggleVisibilityEventAction toggleVisibility, boolean parentVisible, boolean parentEnabled) { String widgetIdentifier = "[toggleVisibility] event action in an event handler"; validateBinding(null, toggleVisibility.getBinding(), true, false, false, false, widgetIdentifier, AttributeType.bool); } @Override public void visitSetInvisibleEventAction(SetInvisibleEventAction setInvisible, boolean parentVisible, boolean parentEnabled) { String widgetIdentifier = "[setInvisible] event action in an event handler"; validateBinding(null, setInvisible.getBinding(), true, false, false, false, widgetIdentifier, AttributeType.bool); String invisibleConditionName = setInvisible.getInvisibleConditionName(); if (invisibleConditionName == null) { throw new MetaDataException(widgetIdentifier + " in " + viewIdentifier + " requires an [invisible] or [visible] condition name."); } validateConditionName(invisibleConditionName, widgetIdentifier); } }
package com.pironet.tda; import com.pironet.tda.utils.HistogramTableModel; import com.pironet.tda.utils.PrefManager; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Stack; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.swing.JOptionPane; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreePath; /** * Parses JDK14 Thread Dumps. * Needs to be closed after use (so inner stream is closed). * * @author irockel */ public class JDK14Parser implements DumpParser { private int markSize = 16384; private int maxCheckLines = 10; private InputStream dumpFileStream = null; private MutableTreeNode nextDump = null; private BufferedReader bis = null; private Map threadStore = null; private Pattern regexPattern = null; private boolean millisTimeStamp = false; private int counter = 1; private int lineCounter = 0; private boolean patternError = false; private boolean foundClassHistograms = false; private boolean withCurrentTimeStamp = false; /** * Creates a new instance of JDK14Parser */ public JDK14Parser(InputStream dumpFileStream, Map threadStore, boolean withCurrentTimeStamp) { this.dumpFileStream = dumpFileStream; this.threadStore = threadStore; this.withCurrentTimeStamp = withCurrentTimeStamp; maxCheckLines = PrefManager.get().getMaxRows(); markSize = PrefManager.get().getStreamResetBuffer(); millisTimeStamp = PrefManager.get().getMillisTimeStamp(); if((PrefManager.get().getDateParsingRegex() != null) && !PrefManager.get().getDateParsingRegex().trim().equals("")) { try { regexPattern = Pattern.compile(PrefManager.get().getDateParsingRegex().trim()); patternError = false; } catch (PatternSyntaxException pe) { JOptionPane.showMessageDialog(null, "Error during parsing line for timestamp regular expression!\n" + "Please check regular expression in your preferences. Deactivating\n" + "parsing for the rest of the file! Error Message is " + pe.getMessage() + " \n", "Error during Parsing", JOptionPane.ERROR_MESSAGE); //System.out.println("Failed parsing! " + pe.getMessage()); //pe.printStackTrace(); patternError = true; } } } /** * returns true if at least one more dump available, already loads it * (this will be returned on next call of parseNext) */ public boolean hasMoreDumps() { nextDump = parseNext(); return(nextDump != null); } /** * @returns true, if a class histogram was found and added during parsing. */ public boolean isFoundClassHistograms() { return(foundClassHistograms); } /** * parse the next thread dump from the stream passed with the constructor. * @returns null if no more thread dumps were found. */ public MutableTreeNode parseNext() { if (nextDump != null) { MutableTreeNode tmpDump = nextDump; nextDump = null; return(tmpDump); } DefaultMutableTreeNode threadDump = null; ThreadInfo overallTDI = null; DefaultMutableTreeNode catMonitors = null; DefaultMutableTreeNode catMonitorsLocks = null; DefaultMutableTreeNode catThreads = null; DefaultMutableTreeNode catLocking = null; DefaultMutableTreeNode catSleeping = null; DefaultMutableTreeNode catWaiting = null; DefaultMutableTreeNode threadInfo = null; try { Map threads = new HashMap(); if(bis == null) { bis = new BufferedReader(new InputStreamReader(dumpFileStream)); } if(withCurrentTimeStamp) { overallTDI = new ThreadInfo("Full Thread Dump at " + new Date(System.currentTimeMillis()), null, ""); } else { overallTDI = new ThreadInfo("Full Thread Dump No. " + counter++, null, ""); } threadDump = new DefaultMutableTreeNode(overallTDI); catThreads = new DefaultMutableTreeNode(new Category("Threads", TDA.createImageIcon("Threads.gif"))); threadDump.add(catThreads); catWaiting = new DefaultMutableTreeNode(new Category("Threads waiting for Monitors", TDA.createImageIcon("ThreadsWaiting.gif"))); catSleeping = new DefaultMutableTreeNode(new Category("Threads sleeping on Monitors", TDA.createImageIcon("ThreadsSleeping.gif"))); catLocking = new DefaultMutableTreeNode(new Category("Threads locking Monitors", TDA.createImageIcon("ThreadsLocking.gif"))); // create category for monitors with disabled filtering. catMonitors = new DefaultMutableTreeNode(new Category("Monitors", TDA.createImageIcon("Monitors.gif"), false)); catMonitorsLocks = new DefaultMutableTreeNode(new Category("Monitors without locking thread", TDA.createImageIcon("Monitors-nolocks.gif"), false)); String title = null; String dumpKey = null; StringBuffer content = null; StringBuffer lContent = null; StringBuffer sContent = null; StringBuffer wContent = null; int threadCount = 0; int waiting = 0; int locking = 0; int sleeping = 0; int deadlocks = 0; boolean locked = true; boolean finished = false; MonitorMap mmap = new MonitorMap(); Stack monitorStack = new Stack(); long startTime = 0; Matcher matched = null; while(bis.ready() && !finished) { String line = bis.readLine(); lineCounter++; if(locked) { if(line.indexOf("Full thread dump") >= 0) { locked = false; if(!withCurrentTimeStamp) { overallTDI.threadName += " at line " + lineCounter; if (startTime != 0) { startTime = 0; } else if (matched != null && matched.matches()) { String parsedStartTime = matched.group(1); if (millisTimeStamp) { try { // the factor is a hack for a bug in oc4j timestamp printing (pattern timeStamp=2342342340) if (parsedStartTime.length() < 13) { startTime = Long.parseLong(parsedStartTime) * (long) Math.pow(10, 13 - parsedStartTime.length()); } else { startTime = Long.parseLong(parsedStartTime); } } catch (NumberFormatException nfe) { startTime = 0; } overallTDI.threadName += " around " + new Date(startTime); } else { overallTDI.threadName += " around " + parsedStartTime; } parsedStartTime = null; } } dumpKey = overallTDI.threadName; } else if(!patternError && (regexPattern != null)) { try { Matcher m = regexPattern.matcher(line.trim()); if(m.matches()) { matched = m; } } catch (Exception ex) { JOptionPane.showMessageDialog(null, "Error during parsing line for timestamp regular expression!\n" + "Please check regular expression in your preferences. Deactivating\n" + "parsing for the rest of the file! Error Message is " + ex.getMessage() + " \n", "Error during Parsing", JOptionPane.ERROR_MESSAGE); //System.out.println("Failed parsing! " + ex.getMessage()); //ex.printStackTrace(); patternError = true; } } } else { if(line.startsWith("\"")) { if(title != null) { threads.put(title, content.toString()); content.append("</pre></pre>"); createCategoryNode(catThreads, title, null, content); threadCount++; } if(wContent != null) { wContent.append("</b><hr>"); createCategoryNode(catWaiting, title, wContent, content); wContent = null; waiting++; } if(sContent != null) { sContent.append("</b><hr>"); createCategoryNode(catSleeping, title, sContent, content); sContent = null; sleeping++; } if(lContent != null) { lContent.append("</b><hr>"); createCategoryNode(catLocking, title, lContent, content); lContent = null; locking++; } while(!monitorStack.empty()) { mmap.parseAndAddThread((String)monitorStack.pop(), title, content.toString()); } title = line.trim(); content = new StringBuffer("<body bgcolor=\"ffffff\"><pre><font size=" + TDA.getFontSizeModifier(-1) + ">"); content.append(line); content.append("\n"); } else if (line.trim().startsWith("at ")) { content.append(line); content.append("\n"); } else if (line.trim().startsWith("java.lang.Thread.State")) { content.append(line); content.append("\n"); } else if (line.trim().startsWith("Locked ownable synchronizers:")) { content.append(line); content.append("\n"); } else if (line.trim().startsWith("- waiting on")) { String newLine = linkifyMonitor(line); content.append(newLine); if(sContent == null) { sContent = new StringBuffer("<body bgcolor=\"ffffff\"><font size=" + TDA.getFontSizeModifier(-1) + "><b>"); } sContent.append(newLine.trim()); monitorStack.push(line); sContent.append("\n"); content.append("\n"); } else if (line.trim().startsWith("- waiting to")) { String newLine = linkifyMonitor(line); content.append(newLine); if(wContent == null) { wContent = new StringBuffer("<body bgcolor=\"ffffff\"><font size=" + TDA.getFontSizeModifier(-1) + "><b>"); } wContent.append(newLine.trim()); monitorStack.push(line); wContent.append("\n"); content.append("\n"); } else if (line.trim().startsWith("- locked")) { String newLine = linkifyMonitor(line); content.append(newLine); if(lContent == null) { lContent = new StringBuffer("<body bgcolor=\"ffffff\"><font size=" + TDA.getFontSizeModifier(-1) + "><b>"); } lContent.append(newLine.trim()); monitorStack.push(line); lContent.append("\n"); content.append("\n"); } else if (line.trim().startsWith("- ")) { content.append(line); content.append("\n"); } // last thread reached? if(line.startsWith("\"Suspend Checker Thread\"") || line.startsWith("\"VM Periodic Task Thread\"")) { finished = true; bis.mark(markSize); if((deadlocks = checkForDeadlocks(threadDump)) == 0) { // no deadlocks found, set back original position. bis.reset(); } bis.mark(markSize); if(!(foundClassHistograms = checkForClassHistogram(threadDump))) { bis.reset(); } } } } // last thread if(title != null) { threads.put(title, content.toString()); content.append("</pre></pre>"); createCategoryNode(catThreads, title, null, content); threadCount++; } if(wContent != null) { wContent.append("</b><hr>"); createCategoryNode(catWaiting, title, null, wContent); wContent = null; waiting++; } if(sContent != null) { sContent.append("</b><hr>"); createCategoryNode(catSleeping, title, sContent, content); sContent = null; sleeping++; } if(lContent != null) { lContent.append("</b><hr>"); createCategoryNode(catLocking, title, null, lContent); lContent = null; locking++; } int monitorCount = mmap.size(); StringBuffer statData = new StringBuffer("<body bgcolor=\"#ffffff\"><font face=System " + "><table border=0><tr bgcolor=\"#dddddd\"><td><font face=System " + ">Overall Thread Count</td><td width=\"150\"></td><td><b><font face=System>"); statData.append(threadCount); statData.append("</b></td></tr>\n\n<tr bgcolor=\"#eeeeee\"><td><font face=System" + ">Overall Monitor Count</td><td></td><td><b><font face=System>"); statData.append(monitorCount); statData.append("</b></td></tr>\n\n<tr bgcolor=\"#dddddd\"><td><font face=System " + ">Number of threads waiting for a monitor</td><td></td><td><b><font face=System>"); statData.append(waiting); statData.append("</b></td></tr>\n\n<tr bgcolor=\"#eeeeee\"><td><font face=System " + ">Number of threads locking a monitor</td><td></td><td><b><font face=System size>"); statData.append(locking); statData.append("</b></td></tr>\n\n<tr bgcolor=\"#dddddd\"><td><font face=System " + ">Number of threads sleeping on a monitor</td><td></td><td><b><font face=System>"); statData.append(sleeping); statData.append("</b></td></tr>\n\n<tr bgcolor=\"#eeeeee\"><td><font face=System " + ">Number of deadlocks</td><td></td><td><b><font face=System>"); statData.append(deadlocks); ((Category) catThreads.getUserObject()).setName(((Category) catThreads.getUserObject()) + " (" + threadCount + " Threads overall)"); ((Category) catWaiting.getUserObject()).setName(((Category) catWaiting.getUserObject()) + " (" + waiting + " Threads waiting)"); ((Category) catSleeping.getUserObject()).setName(((Category) catSleeping.getUserObject()) + " (" + sleeping + " Threads sleeping)"); ((Category) catLocking.getUserObject()).setName(((Category) catLocking.getUserObject()) + " (" + locking + " Threads locking)"); ((Category) catMonitors.getUserObject()).setName(((Category) catMonitors.getUserObject()) + " (" + monitorCount + " Monitors)"); int monitorsWithoutLocksCount = 0; int overallThreadsWaitingWithoutLocks = 0; // dump monitors if(mmap.size() > 0) { int[] result = dumpMonitors(catMonitors, catMonitorsLocks, mmap); monitorsWithoutLocksCount = result[0]; overallThreadsWaitingWithoutLocks = result[1]; } // display nodes with stuff to display if(waiting > 0) { threadDump.add(catWaiting); } if(sleeping > 0) { threadDump.add(catSleeping); } if(locking > 0) { threadDump.add(catLocking); } if(monitorCount > 0) { threadDump.add(catMonitors); } if(monitorsWithoutLocksCount > 0) { threadDump.add(catMonitorsLocks); } statData.append("</b></td></tr>\n\n<tr bgcolor=\"#dddddd\"><td><font face=System " + ">Number of Monitors without locking threads</td><td></td><td><b><font face=System>"); statData.append(monitorsWithoutLocksCount); statData.append("</b></td></tr>"); ((Category) catMonitorsLocks.getUserObject()).setName(((Category) catMonitorsLocks.getUserObject()) + " (" + monitorsWithoutLocksCount + " Monitors)"); // add thread dump to passed dump store. if((threadCount > 0) && (dumpKey != null)) { threadStore.put(dumpKey.trim(), threads); } // check for possible hot spots concerning this thread dump // check if a lot of threads are in state "waiting" if((deadlocks == 0) && (threadCount > 0) && ((waiting / (threadCount / 100.0)) > 10.0)) { statData.append("<tr bgcolor=\"#ffffff\"<td></td></tr>"); statData.append("<tr bgcolor=\"#cccccc\"><td colspan=2><font face=System " + "><p>" + (int)(waiting / (threadCount / 100.0)) + "% of all threads are waiting for a monitor to become available again.</p><br>"); statData.append("This might indicate a congestion or even a deadlock. If a monitor doesn't have a locking thread, it might be<br>"); statData.append("hold by some external resource or system thread. You should check the <a href=\"wait://\">waiting threads</a>.<br></td></tr>"); } else if(deadlocks > 0) { statData.append("<tr bgcolor=\"#ffffff\"<td></td></tr>"); statData.append("<tr bgcolor=\"#cccccc\"><td colspan=2><font face=System " + "><p>The JVM has detected " + deadlocks + " deadlock(s) in the thread dump. You should check the <br><a href=\"dead://\">deadlocks</a> for further information.</p><br>"); } // check if a lot of threads are in state "waiting" if((threadCount > 0) && ((sleeping / (threadCount / 100.0)) > 25.0)) { statData.append("<tr bgcolor=\"#ffffff\"<td></td></tr>"); statData.append("<tr bgcolor=\"#cccccc\"><td colspan=2><font face=System" + "><p>" + (int)(sleeping / (threadCount / 100.0)) + "% of all threads are sleeping on a monitor.</p><br>"); statData.append("This might indicate they are waiting for some external resource (e.g. database) which is overloaded<br>"); statData.append("or not available or are just waiting to get to do something (idle threads).<br>"); statData.append("You should check the <a href=\"sleep://\">sleeping threads</a> with a filter excluding all idle threads.</td></tr>"); } // display an info if there are monitors without locking threads if(monitorsWithoutLocksCount > 0) { statData.append("<tr bgcolor=\"#ffffff\"<td></td></tr>"); statData.append("<tr bgcolor=\"#cccccc\"><td colspan=2><font face=System" + "><p>This thread dump contains monitors without a locking thread information.<br>"); statData.append("This means, the monitor is hold by a system thread or some external resource.</p<br>"); statData.append("You should check the monitors without locking threads for more information.<br></td></tr>"); } // check for indications for running garbage collector if((threadCount > 0) && (overallThreadsWaitingWithoutLocks / (threadCount / 100.0) > 50.0)) { statData.append("<tr bgcolor=\"#ffffff\"<td></td></tr>"); statData.append("<tr bgcolor=\"#cccccc\"><td colspan=2><font face=System " + "<p>" + (int)(overallThreadsWaitingWithoutLocks / (threadCount / 100.0)) + "% of all threads are waiting for a monitor without a application"); statData.append("thread holding it.<br> This indicates a congestion. It is very likely the garbage collector is running"); statData.append("and is blocking the monitors.</p<br>"); statData.append("You should check the monitors without locking threads for more information on the blocked threads.<br>"); statData.append("You also should analyze the garbage collector behaviour. Go to the "); statData.append("<a href=\"http: statData.append(" information on how to do this.</td></tr>"); } statData.append("</table>"); overallTDI.content = statData.toString(); return(threadCount > 0? threadDump : null); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return(null); } /** * add a monitor link for monitor navigation * @param line containing monitor */ private String linkifyMonitor(String line) { String begin = line.substring(0, line.indexOf('<')); String monitor = line.substring(line.indexOf('<'),line.indexOf('>')+1); String end = line.substring(line.indexOf('>')+1); monitor = monitor.replaceAll("<", "<a href=\"monitor://"+ monitor + "\">&lt;"); monitor = monitor.substring(0, monitor.length()-1) + "&gt;</a>"; //System.out.println("link="+ begin + monitor + end); return(begin + monitor + end); } /** * add a monitor link for monitor navigation * @param line containing monitor */ private String linkifyDeadlockInfo(String line) { String begin = line.substring(0, line.indexOf("0x")); int objectBegin = line.lastIndexOf("0x"); int monitorBegin = line.indexOf("0x"); String monitorHex = line.substring(monitorBegin, monitorBegin + 10); String monitor = line.substring(objectBegin, objectBegin + 10); String end = line.substring(line.indexOf("0x")+10); monitor = "<a href=\"monitor://<"+ monitor + ">\">" + monitorHex + "</a>"; return(begin + monitor + end); } /** * checks for the next class histogram and adds it to the tree node passed * @param threadDump which tree node to add the histogram. */ private boolean checkForClassHistogram(DefaultMutableTreeNode threadDump) throws IOException { HistogramTableModel classHistogram = parseNextClassHistogram(bis); if(classHistogram.getRowCount() > 0) { addHistogramToDump(threadDump, classHistogram); } return(classHistogram.getRowCount() > 0); } private void addHistogramToDump(DefaultMutableTreeNode threadDump, HistogramTableModel classHistogram) { DefaultMutableTreeNode catHistogram; HistogramInfo hi = new HistogramInfo("Class Histogram of Dump", classHistogram); catHistogram = new DefaultMutableTreeNode(hi); threadDump.add(catHistogram); } /** * parses the next class histogram found in the stream, uses the max check lines option to check * how many lines to parse in advance. * @param bis the stream to read. */ private HistogramTableModel parseNextClassHistogram(BufferedReader bis) throws IOException { boolean finished = false; boolean found = false; HistogramTableModel classHistogram = new HistogramTableModel(); int lineCounter = 0; while(bis.ready() && !finished) { String line = bis.readLine(); if(!found && !line.trim().equals("")) { if (line.startsWith("num #instances #bytes class name")) { found = true; } else if(lineCounter >= maxCheckLines) { finished = true; } else { lineCounter++; } } else if(found) { if(line.startsWith("Total ")) { String newLine = line.trim().replaceAll("(\\s)+", ";"); String[] elems = newLine.split(";"); classHistogram.setBytes(Long.parseLong(elems[2])); classHistogram.setInstances(Long.parseLong(elems[1])); finished = true; } else if(!line.startsWith(" String newLine = line.trim().replaceAll("(\\s)+", ";"); String[] elems = newLine.split(";"); if(elems.length == 4) { classHistogram.addEntry(elems[3].trim(),Integer.parseInt(elems[2].trim()), Integer.parseInt(elems[1].trim())); } else { classHistogram.setIncomplete(true); finished = true; } } } } return(classHistogram); } /** * check if any dead lock information is logged in the stream * @param threadDump which tree node to add the histogram. */ private int checkForDeadlocks(DefaultMutableTreeNode threadDump) throws IOException { boolean finished = false; boolean found = false; int deadlocks = 0; int lineCounter = 0; StringBuffer dContent = new StringBuffer(); Category deadlockCat = new Category("Deadlocks", TDA.createImageIcon("Deadlock.gif")); DefaultMutableTreeNode catDeadlocks = new DefaultMutableTreeNode(deadlockCat); boolean first = true; while(bis.ready() && !finished) { String line = bis.readLine(); if(!found && !line.trim().equals("")) { if (line.startsWith("Found one Java-level deadlock")) { found = true; dContent.append("<body bgcolor=\"ffffff\"><font size=" + TDA.getFontSizeModifier(-1) + "><b>"); dContent.append("Found one Java-level deadlock"); dContent.append("</b><hr></font><pre>\n"); } else if(lineCounter >= maxCheckLines) { finished = true; } else { lineCounter++; } } else if(found) { if(line.startsWith("Found one Java-level deadlock")) { if(dContent.length() > 0) { deadlocks++; createCategoryNode(catDeadlocks, "Deadlock No. " + (deadlocks), null, dContent); } dContent = new StringBuffer(); dContent.append("</pre><b><font size=" + TDA.getFontSizeModifier(-1) + ">"); dContent.append("Found one Java-level deadlock"); dContent.append("</b><hr></font><pre>\n"); first = true; } else if(line.startsWith("Found") && (line.trim().endsWith("deadlocks.") || line.trim().endsWith("deadlock."))) { finished = true; } else if(line.startsWith("=======")) { // ignore this line } else if(line.indexOf(" monitor 0x") >= 0) { dContent.append(linkifyDeadlockInfo(line)); dContent.append("\n"); } else if(line.startsWith("Java stack information for the threads listed above")) { dContent.append("</pre><br><font size=" + TDA.getFontSizeModifier(-1) + "><b>"); dContent.append("Java stack information for the threads listed above"); dContent.append("</b><hr></font><pre>"); first = true; } else if (line.trim().startsWith("- waiting on") || line.trim().startsWith("- waiting to") || line.trim().startsWith("- locked")) { dContent.append(linkifyMonitor(line)); dContent.append("\n"); } else if(line.startsWith("\"")) { dContent.append("</pre>"); if(first) { first = false; } else { dContent.append("<br>"); } dContent.append("<b><font size=" + TDA.getFontSizeModifier(-1) + "><code>"); dContent.append(line); dContent.append("</font></code></b><pre>"); } else { dContent.append(line); dContent.append("\n"); } } } if(dContent.length() > 0) { deadlocks++; createCategoryNode(catDeadlocks, "Deadlock No. " + (deadlocks), null, dContent); } if(deadlocks > 0) { threadDump.add(catDeadlocks); deadlockCat.setName("Deadlocks (" + deadlocks + (deadlocks == 1 ? " deadlock)" : " deadlocks)")); } return(deadlocks); } private int[] dumpMonitors(DefaultMutableTreeNode catMonitors, DefaultMutableTreeNode catMonitorsLocks, MonitorMap mmap) { Iterator iter = mmap.iterOfKeys(); int monitorsWithoutLocksCount = 0; int overallThreadsWaiting = 0; while(iter.hasNext()) { String monitor = (String) iter.next(); Map[] threads = mmap.getFromMonitorMap(monitor); ThreadInfo mi = new ThreadInfo(monitor, null, ""); DefaultMutableTreeNode monitorNode = new DefaultMutableTreeNode(mi); // first the locks Iterator iterLocks = threads[0].keySet().iterator(); int locks = 0; int sleeps = 0; int waits = 0; while(iterLocks.hasNext()) { String thread = (String) iterLocks.next(); if(threads[2].containsKey(thread)) { createNode(monitorNode, "locks and sleeps on monitor: " + thread, null, (String) threads[0].get(thread)); sleeps++; } else if(threads[1].containsKey(thread)) { createNode(monitorNode, "locks and waits on monitor: " + thread, null, (String) threads[0].get(thread)); sleeps++; } else { createNode(monitorNode, "locked by " + thread, null, (String) threads[0].get(thread)); } locks++; } Iterator iterWaits = threads[1].keySet().iterator(); while(iterWaits.hasNext()) { String thread = (String) iterWaits.next(); if(!threads[0].containsKey(thread)) { createNode(monitorNode, "waits on monitor: " + thread, null, (String) threads[1].get(thread)); waits++; } } StringBuffer statData = new StringBuffer ("<body bgcolor=\"ffffff\"><table border=0 bgcolor=\"#dddddd\"><tr><td><font face=System" + ">Threads locking monitor</td><td><b><font face=System>"); statData.append(locks); statData.append("</b></td></tr>\n\n<tr bgcolor=\"#eeeeee\"><td>"); statData.append("<font face=System>Threads sleeping on monitor</td><td><b><font face=System size=" + TDA.getFontSizeModifier(-1) +">"); statData.append(sleeps); statData.append("</b></td></tr>\n\n<tr><td>"); statData.append("<font face=System>Threads waiting to lock monitor</td><td><b><font face=System size=" + TDA.getFontSizeModifier(-1) + ">"); statData.append(waits); statData.append("</b></td></tr>\n\n"); if(locks == 0) { statData.append("<tr bgcolor=\"#ffffff\"<td></td></tr>"); statData.append("<tr bgcolor=\"#cccccc\"><td><font face=System " + "<p>This monitor doesn't have a thread locking it. This means a VM Thread is holding it.</p><br>"); statData.append("If you see many monitors having no locking thread, this usually means, the garbage collector is running.<br>"); statData.append("In this case you should consider analyzing the Garbage Collector output. If the dump has many monitors with no locking thread<br>"); statData.append("a click on the <a href=\"dump://\">dump node</a> will give you additional information.<br></td></tr>"); } if(waits > 5) { statData.append("<tr bgcolor=\"#ffffff\"<td></td></tr>"); statData.append("<tr bgcolor=\"#cccccc\"><td><font face=System " + "<p>A lot of threads are waiting for this monitor to become available again.</p><br>"); statData.append("This might indicate a congestion. You also should analyze other locks blocked by threads waiting<br>"); statData.append("for this monitor as there might be much more threads waiting for it.<br></td></tr>"); } statData.append("</table>"); mi.content = statData.toString(); ((Category)catMonitors.getUserObject()).addToCatTree(monitorNode); if(locks == 0) { monitorsWithoutLocksCount++; overallThreadsWaiting+=waits; ((Category)catMonitorsLocks.getUserObject()).addToCatTree(monitorNode); } } return new int[]{monitorsWithoutLocksCount, overallThreadsWaiting}; } /** * create a tree node with the provided information * @param top the parent node the new node should be added to. * @param title the title of the new node * @param info the info part of the new node * @param content the content part of the new node * @see ThreadInfo */ private void createNode(DefaultMutableTreeNode top, String title, String info, String content) { DefaultMutableTreeNode threadInfo = null; threadInfo = new DefaultMutableTreeNode(new ThreadInfo(title, info, content)); top.add(threadInfo); } /** * create a node for a category (categories are "Monitors", "Threads waiting", e.g.). A ThreadInfo * instance will be created with the passed information. * @param category the category the node should be added to. * @param title the title of the new node * @param info the info part of the new node * @param content the content part of the new node * @see ThreadInfo */ private void createCategoryNode(DefaultMutableTreeNode category, String title, StringBuffer info, StringBuffer content) { DefaultMutableTreeNode threadInfo = null; threadInfo = new DefaultMutableTreeNode(new ThreadInfo(title, info != null ? info.toString() : null, content.toString())); ((Category)category.getUserObject()).addToCatTree(threadInfo); } private String getDumpStringFromTreePath(TreePath path) { String[] elems = path.toString().split(","); if(elems.length > 1) { return(elems[1].substring(0, elems[1].lastIndexOf(']')).trim()); } else { return null; } } /** * parses a loggc file stream and reads any found class histograms and adds the to the dump store * @param loggcFileStream the stream to read * @param root the root node of the dumps. */ public void parseLoggcFile(InputStream loggcFileStream, DefaultMutableTreeNode root) { BufferedReader bis = new BufferedReader(new InputStreamReader(loggcFileStream)); Vector histograms = new Vector(); try { while(bis.ready()) { bis.mark(markSize); String nextLine = bis.readLine(); if(nextLine.startsWith("num #instances #bytes class name")) { bis.reset(); histograms.add(parseNextClassHistogram(bis)); } } // now add the found histograms to the tree. for(int i = histograms.size()-1; i >= 0; i DefaultMutableTreeNode dump = getNextDumpForHistogram(root); if(dump != null) { addHistogramToDump(dump, (HistogramTableModel) histograms.get(i)); } } } catch (IOException ex) { ex.printStackTrace(); } } /** * this counter counts backwards for adding class histograms to the thread dumpss * beginning with the last dump. */ private int dumpHistogramCounter = -1; private DefaultMutableTreeNode getNextDumpForHistogram(DefaultMutableTreeNode root) { if(dumpHistogramCounter == -1) { // -1 as index starts with 0. dumpHistogramCounter = root.getChildCount()-1; } DefaultMutableTreeNode result = null; if(dumpHistogramCounter > 0) { result = (DefaultMutableTreeNode) root.getChildAt(dumpHistogramCounter); dumpHistogramCounter } return result; } /** * set the dump histogram counter to the specified value to force to start (bottom to top) * from the specified thread dump. */ public void setDumpHistogramCounter(int value) { dumpHistogramCounter = value; } public void findLongRunningThreads(DefaultMutableTreeNode root, Map dumpStore, TreePath[] paths, int minOccurence, String regex) { diffDumps("Long running thread detection", root, dumpStore, paths, minOccurence, regex); } public void mergeDumps(DefaultMutableTreeNode root, Map dumpStore, TreePath[] dumps, int minOccurence, String regex) { diffDumps("Merge", root, dumpStore, dumps, minOccurence, regex); } private void diffDumps(String prefix, DefaultMutableTreeNode root, Map dumpStore, TreePath[] dumps, int minOccurence, String regex) { Vector keys = new Vector(dumps.length); for(int i = 0; i < dumps.length; i++) { keys.add(getDumpStringFromTreePath(dumps[i])); } String info = prefix + " between " + keys.get(0) + " and " + keys.get(keys.size()-1); DefaultMutableTreeNode catMerge = new DefaultMutableTreeNode(new Category(info, TDA.createImageIcon("DiffDumps.gif"))); root.add(catMerge); if(dumpStore.get(keys.get(0)) != null) { Iterator dumpIter = ((Map) dumpStore.get(keys.get(0))).keySet().iterator(); while(dumpIter.hasNext()) { String threadKey = ((String) dumpIter.next()).trim(); int occurence = 0; if(regex == null || regex.equals("") || threadKey.matches(regex)) { for(int i = 1; i < dumps.length; i++) { Map threads = (Map) dumpStore.get(keys.get(i)); if(threads.containsKey(threadKey)) { occurence++; } } if(occurence >= (minOccurence-1)) { StringBuffer content = new StringBuffer("<body bgcolor=\"ffffff\"><pre><font size=").append(TDA.getFontSizeModifier(-1)).append(">").append((String) keys.get(0)).append("\n\n").append((String) ((Map) dumpStore.get(keys.get(0))).get(threadKey)); for(int i = 1; i < dumps.length; i++) { if(((Map)dumpStore.get(keys.get(i))).containsKey(threadKey)) { content.append("\n\n content.append(keys.get(i)); content.append("\n\n"); content.append((String) ((Map)dumpStore.get(keys.get(i))).get(threadKey)); } } createCategoryNode(catMerge, threadKey, null, content); } } } } } /** * close this dump parser, also closes the passed dump stream */ public void close() throws IOException { if(bis != null) { bis.close(); } if(dumpFileStream != null) { dumpFileStream.close(); } } }
package brooklyn.entity.chef; import static brooklyn.util.text.StringEscapes.BashStringEscapes.wrapBash; import static com.google.common.base.Preconditions.checkNotNull; import java.io.File; import java.util.List; import java.util.Map; import com.google.common.base.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import brooklyn.entity.Entity; import brooklyn.entity.effector.EffectorTasks; import brooklyn.location.basic.SshMachineLocation; import brooklyn.util.collections.Jsonya; import brooklyn.util.collections.MutableList; import brooklyn.util.collections.MutableMap; import brooklyn.util.ssh.BashCommands; import brooklyn.util.task.system.ProcessTaskWrapper; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.gson.GsonBuilder; public class KnifeConvergeTaskFactory<RET> extends KnifeTaskFactory<RET> { private static final Logger log = LoggerFactory.getLogger(KnifeConvergeTaskFactory.class); protected Function<? super Entity,String> runList; protected Map<Object, Object> knifeAttributes = new MutableMap<Object, Object>(); protected List<String> extraBootstrapParameters = MutableList.of(); protected Boolean sudo; protected Boolean runTwice; protected String nodeName; protected Integer port; /** null means nothing specified, use user supplied or machine default; * false means use machine default (disallow user supplied); * true means use knife default (omit the argument and disallow user supplied) */ protected Boolean portOmittedToUseKnifeDefault; public KnifeConvergeTaskFactory(String taskName) { super(taskName); } @Override protected KnifeConvergeTaskFactory<RET> self() { return this; } /** construct the knife command, based on the settings on other methods * (called when instantiating the script, after all parameters sent) */ protected List<String> initialKnifeParameters() { // runs inside the task so can detect entity/machine at runtime MutableList<String> result = new MutableList<String>(); SshMachineLocation machine = EffectorTasks.findSshMachine(); result.add("bootstrap"); result.addAll(extraBootstrapParameters); result.add(wrapBash(machine.getAddress().getHostName())); Integer whichPort = knifeWhichPort(machine); if (whichPort!=null) result.add("-p "+whichPort); result.add("-x "+wrapBash(checkNotNull(machine.getUser(), "user"))); File keyfile = ChefServerTasks.extractKeyFile(machine); if (keyfile!=null) result.add("-i "+keyfile.getPath()); else result.add("-P "+checkNotNull(machine.findPassword(), "No password or private key data for "+machine)); if (sudo != Boolean.FALSE) result.add("--sudo"); if (!Strings.isNullOrEmpty(nodeName)) { result.add("--node-name"); result.add(nodeName); } result.add("-r "+wrapBash(runList.apply(entity()))); if (!knifeAttributes.isEmpty()) result.add("-j "+wrapBash(new GsonBuilder().create() .toJson(knifeAttributes))); return result; } /** whether knife should attempt to run twice; * see {@link ChefConfig#CHEF_RUN_CONVERGE_TWICE} */ public KnifeConvergeTaskFactory<RET> knifeRunTwice(boolean runTwice) { this.runTwice = runTwice; return self(); } /** whether to pass --sudo to knife; default true */ public KnifeConvergeTaskFactory<RET> knifeSudo(boolean sudo) { this.sudo = sudo; return self(); } /** what node name to pass to knife; default = null, meaning chef-client will pick the node name */ public KnifeConvergeTaskFactory<RET> knifeNodeName(String nodeName) { this.nodeName = nodeName; return self(); } /** tell knife to use an explicit port */ public KnifeConvergeTaskFactory<RET> knifePort(int port) { if (portOmittedToUseKnifeDefault!=null) { log.warn("Port "+port+" specified to "+this+" for when already explicitly told to use a default (overriding previous); see subsequent warning for more details"); } this.port = port; return self(); } /** omit the port parameter altogether (let knife use its default) */ public KnifeConvergeTaskFactory<RET> knifePortUseKnifeDefault() { if (port!=null) { log.warn("knifePortUseKnifeDefault specified to "+this+" when already told to use "+port+" explicitly (overriding previous); see subsequent warning for more details"); port = -1; } portOmittedToUseKnifeDefault = true; return self(); } /** use the default port known to brooklyn for the target machine for ssh */ public KnifeConvergeTaskFactory<RET> knifePortUseMachineSshPort() { if (port!=null) { log.warn("knifePortUseMachineSshPort specified to "+this+" when already told to use "+port+" explicitly (overriding previous); see subsequent warning for more details"); port = -1; } portOmittedToUseKnifeDefault = false; return self(); } protected Integer knifeWhichPort(SshMachineLocation machine) { if (port==null) { if (portOmittedToUseKnifeDefault==Boolean.TRUE) // user has explicitly said to use knife default, omitting port here return null; // default is to use the machine port return machine.getPort(); } if (port==-1) { // port was supplied by user, then portDefault (true or false) port = null; Integer whichPort = knifeWhichPort(machine); log.warn("knife port conflicting instructions for "+this+" at entity "+entity()+" on "+machine+"; using default ("+whichPort+")"); return whichPort; } if (portOmittedToUseKnifeDefault!=null) { // portDefault was specified (true or false), then overridden with a port log.warn("knife port conflicting instructions for "+this+" at entity "+entity()+" on "+machine+"; using supplied port "+port); } // port was supplied by user, use that return port; } /** parameters to pass to knife after the bootstrap command */ public KnifeConvergeTaskFactory<RET> knifeAddExtraBootstrapParameters(String extraBootstrapParameter1, String ...extraBootstrapParameters) { this.extraBootstrapParameters.add(extraBootstrapParameter1); for (String p: extraBootstrapParameters) this.extraBootstrapParameters.add(p); return self(); } /** function supplying the run list to be passed to knife, evaluated at the last moment */ public KnifeConvergeTaskFactory<RET> knifeRunList(Function<? super Entity, String> runList) { this.runList = runList; return self(); } public KnifeConvergeTaskFactory<RET> knifeRunList(String runList) { this.runList = Functions.constant(runList); return self(); } /** includes the given attributes in the attributes to be passed to chef; * when combining with other attributes, this uses {@link Jsonya} semantics to add * (a deep add, combining lists and maps) */ public KnifeConvergeTaskFactory<RET> knifeAddAttributes(Map<? extends Object, ? extends Object> attributes) { if (attributes!=null && !attributes.isEmpty()) { Jsonya.of(knifeAttributes).add(attributes); } return self(); } protected String buildKnifeCommand(int knifeCommandIndex) { String result = super.buildKnifeCommand(knifeCommandIndex); if (runTwice == Boolean.TRUE) result = BashCommands.alternatives(result, result); return result; } @Override public <T2> KnifeConvergeTaskFactory<T2> returning(ScriptReturnType type) { return (KnifeConvergeTaskFactory<T2>) super.<T2>returning(type); } @Override public <RET2> KnifeConvergeTaskFactory<RET2> returning(Function<ProcessTaskWrapper<?>, RET2> resultTransformation) { return (KnifeConvergeTaskFactory<RET2>) super.returning(resultTransformation); } @Override public KnifeConvergeTaskFactory<Boolean> returningIsExitCodeZero() { return (KnifeConvergeTaskFactory<Boolean>) super.returningIsExitCodeZero(); } @Override public KnifeConvergeTaskFactory<String> requiringZeroAndReturningStdout() { return (KnifeConvergeTaskFactory<String>) super.requiringZeroAndReturningStdout(); } public KnifeConvergeTaskFactory<RET> knifeAddParameters(String word1, String ...words) { super.knifeAddParameters(word1, words); return self(); } // TODO other methods from KnifeTaskFactory will return KTF class not KCTF; // should make it generic so it returns the right type... }
package com.intellij.ide.util.newProjectWizard.modes; import com.intellij.ide.util.importProject.DelegatingProgressIndicator; import com.intellij.ide.util.importProject.LibrariesDetectionStep; import com.intellij.ide.util.importProject.ModuleInsight; import com.intellij.ide.util.importProject.ModulesDetectionStep; import com.intellij.ide.util.newProjectWizard.ProjectFromSourcesBuilder; import com.intellij.ide.util.newProjectWizard.ProjectNameStep; import com.intellij.ide.util.newProjectWizard.StepSequence; import com.intellij.ide.util.projectWizard.ProjectBuilder; import com.intellij.ide.util.projectWizard.ProjectWizardStepFactory; import com.intellij.ide.util.projectWizard.WizardContext; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.roots.ui.configuration.ModulesProvider; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class CreateFromSourcesMode extends WizardMode { private ProjectFromSourcesBuilder myProjectBuilder; @NotNull public String getDisplayName(final WizardContext context) { return ProjectBundle.message("project.new.wizard.from.existent.sources.title", context.getPresentationName()); } @NotNull public String getDescription(final WizardContext context) { return ProjectBundle.message("project.new.wizard.from.existent.sources.description", context.getPresentationName()); } @Nullable protected StepSequence createSteps(final WizardContext context, final ModulesProvider modulesProvider) { final ModuleInsight moduleInsight = new ModuleInsight(new DelegatingProgressIndicator()); final ProjectFromSourcesBuilder projectBuilder = new ProjectFromSourcesBuilder(moduleInsight); myProjectBuilder = projectBuilder; final ProjectWizardStepFactory factory = ProjectWizardStepFactory.getInstance(); final StepSequence sequence = new StepSequence(); sequence.addCommonStep(new ProjectNameStep(context, sequence, this)); sequence.addCommonStep(factory.createSourcePathsStep(context, projectBuilder, null, null)); sequence.addCommonStep(new LibrariesDetectionStep(projectBuilder, moduleInsight, null, null)); sequence.addCommonStep(new ModulesDetectionStep(projectBuilder, moduleInsight, null, null)); sequence.addCommonStep(factory.createProjectJdkStep(context)); return sequence; } public boolean isAvailable(WizardContext context) { return context.getProject() == null; } public ProjectBuilder getModuleBuilder() { return myProjectBuilder; } @Nullable public JComponent getAdditionalSettings() { return null; } public void onChosen(final boolean enabled) { } public void dispose() { myProjectBuilder = null; super.dispose(); } }
/* * @author max */ package com.intellij.psi.impl.java.stubs; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiCompiledElement; import com.intellij.psi.PsiJavaCodeReferenceElement; import com.intellij.psi.PsiNameHelper; import com.intellij.psi.PsiReferenceList; import com.intellij.psi.impl.compiled.ClsReferenceListImpl; import com.intellij.psi.impl.java.stubs.impl.PsiClassReferenceListStubImpl; import com.intellij.psi.impl.java.stubs.index.JavaSuperClassNameOccurenceIndex; import com.intellij.psi.impl.source.PsiReferenceListImpl; import com.intellij.psi.impl.source.tree.java.PsiTypeParameterExtendsBoundsListImpl; import com.intellij.psi.stubs.IndexSink; import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; import com.intellij.util.ArrayUtil; import com.intellij.util.io.StringRef; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.IOException; public class JavaClassReferenceListElementType extends JavaStubElementType<PsiClassReferenceListStub, PsiReferenceList> { public JavaClassReferenceListElementType(@NotNull @NonNls String id) { super(id); } public PsiReferenceList createPsi(final PsiClassReferenceListStub stub) { if (isCompiled(stub)) { return new ClsReferenceListImpl(stub); } else { if (stub.getRole() == PsiReferenceList.Role.EXTENDS_BOUNDS_LIST) { return new PsiTypeParameterExtendsBoundsListImpl(stub, JavaStubElementTypes.EXTENDS_BOUND_LIST); } return new PsiReferenceListImpl(stub, stub.getStubType()); } } public PsiReferenceList createPsi(final ASTNode node) { if (node.getElementType() == JavaStubElementTypes.EXTENDS_BOUND_LIST) { return new PsiTypeParameterExtendsBoundsListImpl(node); } return new PsiReferenceListImpl(node); } public PsiClassReferenceListStub createStub(final PsiReferenceList psi, final StubElement parentStub) { return new PsiClassReferenceListStubImpl(roleToElementType(psi.getRole()), parentStub, getTexts(psi), psi.getRole()); } private static JavaClassReferenceListElementType roleToElementType(final PsiReferenceList.Role role) { switch (role) { case EXTENDS_BOUNDS_LIST: return JavaStubElementTypes.EXTENDS_BOUND_LIST; case EXTENDS_LIST: return JavaStubElementTypes.EXTENDS_LIST; case IMPLEMENTS_LIST: return JavaStubElementTypes.IMPLEMENTS_LIST; case THROWS_LIST: return JavaStubElementTypes.THROWS_LIST; } throw new RuntimeException("Unknown role: " + role); } private static String[] getTexts(PsiReferenceList psi) { final PsiJavaCodeReferenceElement[] refs = psi.getReferenceElements(); String[] texts = ArrayUtil.newStringArray(refs.length); for (int i = 0; i < refs.length; i++) { PsiJavaCodeReferenceElement ref = refs[i]; texts[i] = ref instanceof PsiCompiledElement ? ref.getCanonicalText() : ref.getText(); } return texts; } public void serialize(final PsiClassReferenceListStub stub, final StubOutputStream dataStream) throws IOException { dataStream.writeByte(encodeRole(stub.getRole())); final String[] names = stub.getReferencedNames(); dataStream.writeVarInt(names.length); for (String name : names) { dataStream.writeName(name); } } public PsiClassReferenceListStub deserialize(final StubInputStream dataStream, final StubElement parentStub) throws IOException { byte role = dataStream.readByte(); int len = dataStream.readVarInt(); StringRef[] names = StringRef.createArray(len); for (int i = 0; i < names.length; i++) { names[i] = dataStream.readName(); } final PsiReferenceList.Role decodedRole = decodeRole(role); return new PsiClassReferenceListStubImpl(roleToElementType(decodedRole), parentStub, names, decodedRole); } private static PsiReferenceList.Role decodeRole(int code) { switch (code) { case 0: return PsiReferenceList.Role.EXTENDS_LIST; case 1: return PsiReferenceList.Role.IMPLEMENTS_LIST; case 2: return PsiReferenceList.Role.THROWS_LIST; case 3: return PsiReferenceList.Role.EXTENDS_BOUNDS_LIST; default: throw new RuntimeException("Unknown role code: " + code); } } private static byte encodeRole(PsiReferenceList.Role role) { switch (role) { case EXTENDS_LIST: return 0; case IMPLEMENTS_LIST: return 1; case THROWS_LIST: return 2; case EXTENDS_BOUNDS_LIST: return 3; default: throw new RuntimeException("Unknown role code: " + role); } } public void indexStub(final PsiClassReferenceListStub stub, final IndexSink sink) { final PsiReferenceList.Role role = stub.getRole(); if (role == PsiReferenceList.Role.EXTENDS_LIST || role == PsiReferenceList.Role.IMPLEMENTS_LIST) { final String[] names = stub.getReferencedNames(); for (String name : names) { sink.occurrence(JavaSuperClassNameOccurenceIndex.KEY, PsiNameHelper.getShortClassName(name)); } if (role == PsiReferenceList.Role.EXTENDS_LIST) { StubElement parentStub = stub.getParentStub(); if (parentStub instanceof PsiClassStub) { PsiClassStub psiClassStub = (PsiClassStub)parentStub; if (psiClassStub.isEnum()) { sink.occurrence(JavaSuperClassNameOccurenceIndex.KEY, "Enum"); } if (psiClassStub.isAnnotationType()) { sink.occurrence(JavaSuperClassNameOccurenceIndex.KEY, "Annotation"); } } } } } }
package org.jasig.portal.services.entityproperties; import java.util.Hashtable; import org.jasig.portal.EntityIdentifier; import org.jasig.portal.services.LogService; import org.jasig.portal.services.PersonDirectory; import org.jasig.portal.utils.SoftHashMap; /** * A finder implementation to provide IPerson properties derived from the * PersonDirectory * * @author Alex Vigdor av317@columbia.edu * @version $Revision$ */ public class PersonDirPropertyFinder implements IEntityPropertyFinder { private Class person = org.jasig.portal.security.IPerson.class; private PersonDirectory pd; private SoftHashMap cache; public PersonDirPropertyFinder() { pd = PersonDirectory.instance(); cache = new SoftHashMap(120); } public String[] getPropertyNames(EntityIdentifier entityID) { String[] r = new String[0]; if (entityID.getType().equals(person)) { r = (String[])getPropertiesHash(entityID).keySet().toArray(r); } return r; } public String getProperty(EntityIdentifier entityID, String name) { String r = null; if (entityID.getType().equals(person)) { Object o = getPropertiesHash(entityID).get(name); if (o instanceof String) { r = (String)o; } else if (o instanceof List) { StringBuffer sb = new StringBuffer(); List values = (List)o; for (Iterator iter = values.iterator(); iter.hasNext();) { Object value = (Object)iter.next(); sb.append(value.toString()); if (iter.hasNext()) { sb.append(", "); } } r = sb.toString(); } } return r; } protected Hashtable getPropertiesHash(EntityIdentifier entityID) { Hashtable ht; if ((ht = (Hashtable)cache.get(entityID.getKey())) == null) { ht = new Hashtable(0); try { ht = pd.getUserDirectoryInformation(entityID.getKey()); } catch (Exception e) { LogService.log(LogService.ERROR, e); } cache.put(entityID.getKey(), ht); } return ht; } }
package pdp.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import pdp.xacml.PolicyTemplateEngine; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import java.util.Date; import java.util.HashSet; import java.util.Set; @Entity(name = "pdp_policies") public class PdpPolicy { @Id @GeneratedValue private Long id; @Column private String policyId; @Column private String policyXml; @Column private String name; @Column private String authenticatingAuthority; @Column private String userIdentifier; @Column private String userDisplayName; @Column private int revisionNbr; @Column private boolean latestRevision; @Column(name = "is_active") private boolean active; @Column private String type; @ManyToOne @JoinColumn(name = "revision_parent_id", nullable = true) //to prevent cycles @JsonIgnore private PdpPolicy parentPolicy; @OneToMany(orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "parentPolicy") private Set<PdpPolicy> revisions = new HashSet<>(); @OneToMany(orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "policy") private Set<PdpPolicyViolation> violations = new HashSet<>(); @Column(nullable = false, name = "ts") private Date created; public PdpPolicy() { } public PdpPolicy(String policyXml, String name, boolean latestRevision, String userIdentifier, String authenticatingAuthority, String userDisplayName, boolean active, String type) { this.policyXml = policyXml; this.name = name; this.latestRevision = latestRevision; this.userIdentifier = userIdentifier; this.userDisplayName = userDisplayName; this.authenticatingAuthority = authenticatingAuthority; this.active = active; this.policyId = PolicyTemplateEngine.getPolicyId(name); this.type = type; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPolicyId() { return policyId; } public void setPolicyId(String policyId) { this.policyId = policyId; } public String getPolicyXml() { return policyXml; } public void setPolicyXml(String policyXml) { this.policyXml = policyXml; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthenticatingAuthority() { return authenticatingAuthority; } public void setAuthenticatingAuthority(String authenticatingAuthority) { this.authenticatingAuthority = authenticatingAuthority; } public String getUserIdentifier() { return userIdentifier; } public void setUserIdentifier(String userIdentifier) { this.userIdentifier = userIdentifier; } public String getUserDisplayName() { return userDisplayName; } public void setUserDisplayName(String userDisplayName) { this.userDisplayName = userDisplayName; } public Set<PdpPolicy> getRevisions() { return revisions; } public void setRevisions(Set<PdpPolicy> revisions) { this.revisions = revisions; } public void addRevision(PdpPolicy revision) { revision.setParentPolicy(this); this.revisions.add(revision); } public Set<PdpPolicyViolation> getViolations() { return violations; } public void setViolations(Set<PdpPolicyViolation> violations) { this.violations = violations; } public void addPdpPolicyViolation(PdpPolicyViolation violation) { this.violations.add(violation); } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public int getRevisionNbr() { return revisionNbr; } public void setRevisionNbr(int revisionNbr) { this.revisionNbr = revisionNbr; } public boolean isLatestRevision() { return latestRevision; } public void setLatestRevision(boolean latestRevision) { this.latestRevision = latestRevision; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public PdpPolicy getParentPolicy() { return parentPolicy; } public void setParentPolicy(PdpPolicy parentPolicy) { this.parentPolicy = parentPolicy; } public String getType() { return type; } public void setType(String type) { this.type = type; } public static PdpPolicy revision(String newName, PdpPolicy parent, String newPolicyXml, String userIdentifier, String userDisplayName, boolean isActive) { parent.getRevisions().forEach(p -> p.setLatestRevision(false)); parent.setLatestRevision(false); PdpPolicy clone = new PdpPolicy(); clone.setPolicyXml(newPolicyXml); clone.setName(newName); clone.setLatestRevision(true); clone.setUserIdentifier(userIdentifier); clone.setUserDisplayName(userDisplayName); clone.setActive(isActive); clone.setRevisionNbr(parent.getRevisions().size() + 1); clone.setPolicyId(PolicyTemplateEngine.getPolicyId(newName)); clone.setType(parent.getType()); parent.addRevision(clone); return clone; } }
package com.github.msemys.esjc.node.single; import com.github.msemys.esjc.node.EndpointDiscoverer; import com.github.msemys.esjc.node.NodeEndpoints; import java.net.InetSocketAddress; import java.util.concurrent.CompletableFuture; import static com.github.msemys.esjc.util.Preconditions.checkNotNull; public class SingleEndpointDiscoverer implements EndpointDiscoverer { private final SingleNodeSettings settings; private final boolean ssl; public SingleEndpointDiscoverer(SingleNodeSettings settings, boolean ssl) { checkNotNull(settings, "settings is null"); this.settings = settings; this.ssl = ssl; } @Override public CompletableFuture<NodeEndpoints> discover(InetSocketAddress failedTcpEndpoint) { // construct new address to handle ip address changes between discovers InetSocketAddress freshAddress = new InetSocketAddress(settings.address.getHostName(), settings.address.getPort()); return CompletableFuture.completedFuture(new NodeEndpoints( ssl ? null : freshAddress, ssl ? freshAddress : null)); } }
package mx.com.geexco.test.undertow.us.handlers; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.util.Arrays; import mx.com.geexco.test.undertow.us.dao.RegistrationSource; import mx.com.geexco.test.undertow.us.dto.GCMMessage; import mx.com.geexco.test.undertow.us.dto.NotificationDTO; import mx.com.geexco.test.undertow.us.dto.ResponseDTO; import org.apache.http.Header; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicHeader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author gxc-mg */ public class NotificationHandler extends AbstractJSONProcessorHandler { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final GsonBuilder gb = new GsonBuilder(); private final HttpClientBuilder cb; RegistrationSource reg; public NotificationHandler(RegistrationSource reg, String apiKey) { this.reg = reg; Header header = new BasicHeader(HttpHeaders.AUTHORIZATION, "key=" + apiKey); cb = HttpClientBuilder.create().setDefaultHeaders(Arrays.asList(header)); } private int notifica(String registrationId, String title, String msgContent, String info) { CloseableHttpClient client = cb.build(); HttpPost post = new HttpPost("https://fcm.googleapis.com/fcm/send"); GCMMessage msg = new GCMMessage(new String[]{registrationId}); msg.addNotificationData("title", title); msg.addNotificationData("body", msgContent); msg.addNotificationData("sound", "default"); msg.addData("content-available", "1"); msg.addData("info", info); String data = gb.create().toJson(msg); log.info("Mensaje enviado:"+data); post.setEntity(new StringEntity(data, ContentType.APPLICATION_JSON)); try { CloseableHttpResponse response = client.execute(post); } catch (IOException ex) { log.error("Error sending notification: ", ex); return -1; } return 0; } @Override public String handleJSONMessage(String msg) { Gson gson = gb.create(); if (msg.isEmpty()) { return gson.toJson(new ResponseDTO(-1)); } NotificationDTO dto; try { dto = gson.fromJson(msg, NotificationDTO.class); } catch (Exception e) { log.info("Error getting DTO from '" + msg + "'"); return gson.toJson(new ResponseDTO(-2)); } String id = reg.getDevice(dto.getId()); if (id == null) { return gson.toJson(new ResponseDTO(-3)); } int res = notifica(id, dto.getTitle(), dto.getMessage(), dto.getInfo()); if (res != 0) { return gson.toJson(new ResponseDTO(-4)); } return gson.toJson(new ResponseDTO(0)); } }
package org.apache.jmeter.protocol.mqtt.client; import java.util.concurrent.atomic.AtomicInteger; import org.fusesource.hawtbuf.Buffer; import org.fusesource.hawtbuf.UTF8Buffer; import org.fusesource.mqtt.client.Listener; public class ListenerforSubscribe implements Listener { private static AtomicInteger count= new AtomicInteger(0); @Override public void onConnected() { System.out.println("Subscriber is listening"); } @Override public void onDisconnected() { System.out.println("Subscriber disabled listening"); } @Override public void onPublish(UTF8Buffer topic, Buffer body, Runnable ack) { // String message = new String(body.getData()); // System.out.println("Received: "+message); count.getAndIncrement(); System.out.println("Received " + count.get() +" messages"); ack.run(); } @Override public void onFailure(Throwable value) { System.out.println("Subscriber couldn't set up listener"); System.out.println(value); } }
package org.elasticsearch.index.translog.fs; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.index.translog.Translog; import org.elasticsearch.index.translog.TranslogException; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class BufferingFsTranslogFile implements FsTranslogFile { private final long id; private final ShardId shardId; private final RafReference raf; private final ReadWriteLock rwl = new ReentrantReadWriteLock(); private volatile int operationCounter; private long lastPosition; private volatile long lastWrittenPosition; private volatile long lastSyncPosition = 0; private byte[] buffer; private int bufferCount; public BufferingFsTranslogFile(ShardId shardId, long id, RafReference raf, int bufferSize) throws IOException { this.shardId = shardId; this.id = id; this.raf = raf; this.buffer = new byte[bufferSize]; raf.raf().setLength(0); } public long id() { return this.id; } public int estimatedNumberOfOperations() { return operationCounter; } public long translogSizeInBytes() { return lastWrittenPosition; } @Override public Translog.Location add(byte[] data, int from, int size) throws IOException { rwl.writeLock().lock(); try { operationCounter++; long position = lastPosition; if (size >= buffer.length) { flushBuffer(); // we use the channel to write, since on windows, writing to the RAF might not be reflected // when reading through the channel raf.channel().write(ByteBuffer.wrap(data, from, size)); lastWrittenPosition += size; lastPosition += size; return new Translog.Location(id, position, size); } if (size > buffer.length - bufferCount) { flushBuffer(); } System.arraycopy(data, from, buffer, bufferCount, size); bufferCount += size; lastPosition += size; return new Translog.Location(id, position, size); } finally { rwl.writeLock().unlock(); } } private void flushBuffer() throws IOException { if (bufferCount > 0) { // we use the channel to write, since on windows, writing to the RAF might not be reflected // when reading through the channel raf.channel().write(ByteBuffer.wrap(buffer, 0, bufferCount)); lastWrittenPosition += bufferCount; bufferCount = 0; } } @Override public byte[] read(Translog.Location location) throws IOException { rwl.readLock().lock(); try { if (location.translogLocation >= lastWrittenPosition) { byte[] data = new byte[location.size]; System.arraycopy(buffer, (int) (location.translogLocation - lastWrittenPosition), data, 0, location.size); return data; } } finally { rwl.readLock().unlock(); } ByteBuffer buffer = ByteBuffer.allocate(location.size); raf.channel().read(buffer, location.translogLocation); return buffer.array(); } @Override public FsChannelSnapshot snapshot() throws TranslogException { rwl.writeLock().lock(); try { flushBuffer(); if (!raf.increaseRefCount()) { return null; } return new FsChannelSnapshot(this.id, raf, lastWrittenPosition, operationCounter); } catch (IOException e) { throw new TranslogException(shardId, "failed to flush", e); } finally { rwl.writeLock().unlock(); } } @Override public boolean syncNeeded() { return lastPosition != lastSyncPosition; } @Override public void sync() { try { // check if we really need to sync here... long last = lastPosition; if (last == lastSyncPosition) { return; } lastSyncPosition = last; rwl.writeLock().lock(); try { flushBuffer(); } finally { rwl.writeLock().unlock(); } raf.channel().force(false); } catch (Exception e) { // ignore } } @Override public void close(boolean delete) { if (!delete) { rwl.writeLock().lock(); try { flushBuffer(); sync(); } catch (IOException e) { throw new TranslogException(shardId, "failed to close", e); } finally { rwl.writeLock().unlock(); } } raf.decreaseRefCount(delete); } @Override public void reuse(FsTranslogFile other) { if (!(other instanceof BufferingFsTranslogFile)) { return; } rwl.writeLock().lock(); try { flushBuffer(); this.buffer = ((BufferingFsTranslogFile) other).buffer; } catch (IOException e) { throw new TranslogException(shardId, "failed to flush", e); } finally { rwl.writeLock().unlock(); } } }
package org.sagebionetworks.web.client.widget.table; import java.util.ArrayList; import java.util.List; import org.sagebionetworks.repo.model.EntityChildrenRequest; import org.sagebionetworks.repo.model.EntityChildrenResponse; import org.sagebionetworks.repo.model.EntityHeader; import org.sagebionetworks.repo.model.EntityType; import org.sagebionetworks.repo.model.entity.Direction; import org.sagebionetworks.repo.model.entity.SortBy; import org.sagebionetworks.repo.model.entitybundle.v2.EntityBundle; import org.sagebionetworks.web.client.SynapseJavascriptClient; import org.sagebionetworks.web.client.utils.Callback; import org.sagebionetworks.web.client.utils.CallbackP; import org.sagebionetworks.web.client.widget.LoadMoreWidgetContainer; import org.sagebionetworks.web.client.widget.entity.controller.SynapseAlert; import com.google.gwt.http.client.Request; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; /** * This widget lists the tables of a given project. * * @author John * */ public class TableListWidget implements TableListWidgetView.Presenter, IsWidget { private TableListWidgetView view; private SynapseJavascriptClient jsClient; private EntityChildrenRequest query; private EntityBundle parentBundle; private CallbackP<EntityHeader> onTableClickCallback; private LoadMoreWidgetContainer loadMoreWidget; private SynapseAlert synAlert; public static final SortBy DEFAULT_SORT_BY = SortBy.CREATED_ON; public static final Direction DEFAULT_DIRECTION = Direction.DESC; boolean isInitializing = false; Request currentRequest = null; private List<String> idList = null; @Inject public TableListWidget(TableListWidgetView view, SynapseJavascriptClient jsClient, LoadMoreWidgetContainer loadMoreWidget, SynapseAlert synAlert) { this.view = view; this.jsClient = jsClient; this.loadMoreWidget = loadMoreWidget; this.synAlert = synAlert; this.view.setPresenter(this); this.view.setLoadMoreWidget(loadMoreWidget); view.setSynAlert(synAlert); loadMoreWidget.configure(new Callback() { @Override public void invoke() { loadMore(); } }); } /** * Configure this widget before use. * * @param projectOwnerId * @param canEdit * @param showAddTable */ public void configure(EntityBundle parentBundle) { if (currentRequest != null) { currentRequest.cancel(); } isInitializing = true; this.parentBundle = parentBundle; loadData(); } public void resetSynIdList() { idList = null; } public void addSynIdToList(String id) { if (idList == null) { idList = new ArrayList<>(); } idList.add(id); } public void toggleSort(SortBy sortColumn) { Direction newDirection = Direction.ASC.equals(query.getSortDirection()) ? Direction.DESC : Direction.ASC; onSort(sortColumn, newDirection); } public void onSort(SortBy sortColumn, Direction sortDirection) { resetSynIdList(); query.setSortBy(sortColumn); query.setSortDirection(sortDirection); query.setNextPageToken(null); view.clearTableWidgets(); loadMore(); } public void loadData() { resetSynIdList(); query = createQuery(parentBundle.getEntity().getId()); view.clearTableWidgets(); view.hideLoading(); query.setNextPageToken(null); loadMore(); } /** * Create a new query. * * @param parentId * @return */ public EntityChildrenRequest createQuery(String parentId) { EntityChildrenRequest newQuery = new EntityChildrenRequest(); newQuery.setSortBy(DEFAULT_SORT_BY); newQuery.setSortDirection(DEFAULT_DIRECTION); newQuery.setParentId(parentId); List<EntityType> types = new ArrayList<EntityType>(); types.add(EntityType.table); types.add(EntityType.entityview); types.add(EntityType.submissionview); newQuery.setIncludeTypes(types); return newQuery; } /** * Run a query and populate the page with the results. * * @param offset The offset used by the query. */ private void loadMore() { synAlert.clear(); if (isInitializing) { view.clearSortUI(); } else { view.setSortUI(query.getSortBy(), query.getSortDirection()); } currentRequest = jsClient.getEntityChildren(query, new AsyncCallback<EntityChildrenResponse>() { public void onSuccess(EntityChildrenResponse result) { query.setNextPageToken(result.getNextPageToken()); loadMoreWidget.setIsMore(result.getNextPageToken() != null); setResults(result.getPage()); isInitializing = false; }; @Override public void onFailure(Throwable caught) { synAlert.handleException(caught); } }); } private void setResults(List<EntityHeader> results) { view.hideLoading(); for (EntityHeader header : results) { addSynIdToList(header.getId()); view.addTableListItem(header); } for (EntityHeader header : results) { jsClient.populateEntityBundleCache(header.getId()); } } @Override public Widget asWidget() { view.setPresenter(this); return view.asWidget(); } /** * Invokes callback when a table entity is clicked in the table list. * * @param callback */ public void setTableClickedCallback(CallbackP<EntityHeader> callback) { this.onTableClickCallback = callback; } @Override public void onTableClicked(EntityHeader entityHeader) { if (onTableClickCallback != null) { view.showLoading(); view.clearTableWidgets(); onTableClickCallback.invoke(entityHeader); } } @Override public void copyIDsToClipboard() { StringBuilder clipboardValue = new StringBuilder(); for (String synId : idList) { clipboardValue.append(synId); clipboardValue.append("\n"); } view.copyToClipboard(clipboardValue.toString()); } }
package zmaster587.advancedRocketry.satellite; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.oredict.OreDictionary; import zmaster587.advancedRocketry.api.Configuration; import zmaster587.advancedRocketry.api.satellite.SatelliteBase; import zmaster587.libVulpes.util.ZUtils; public class SatelliteLaserNoDrill extends SatelliteBase { protected boolean jammed; protected IInventory boundChest; World world; private static List<ItemStack> ores; Random random; public SatelliteLaserNoDrill(IInventory boundChest) { this.boundChest = boundChest; random = new Random(System.currentTimeMillis()); //isEmpty check because <init> is called in post init to register for holo projector if(ores == null && !Configuration.standardLaserDrillOres.isEmpty()) { ores = new LinkedList<ItemStack>(); for(int i = 0; i < Configuration.standardLaserDrillOres.size(); i++) { String oreDictName = Configuration.standardLaserDrillOres.get(i); String args[] = oreDictName.split(":"); List<ItemStack> ores2 = OreDictionary.getOres(args[0]); if(ores2 != null && !ores2.isEmpty()) { int amt = 1; if(args.length > 1) { try { amt = Integer.parseInt(args[1]); } catch (NumberFormatException e) {} } ores.add(new ItemStack(ores2.get(0).getItem(), amt, ores2.get(0).getItemDamage())); } else { String splitStr[] = oreDictName.split(":"); String name = splitStr[0] + ":" + splitStr[1]; int meta = 0; int size = 1; //format: "name meta size" if(splitStr.length > 2) { try { meta = Integer.parseInt(splitStr[2]); } catch( NumberFormatException e) {} } if(splitStr.length > 3) { try { size= Integer.parseInt(splitStr[3]); } catch (NumberFormatException e) {} } ItemStack stack = null; Block block = Block.getBlockFromName(name); if(block == null) { Item item = Item.getByNameOrId(name); if(item != null) stack = new ItemStack(item, size, meta); } else stack = new ItemStack(block, size, meta); if(stack != null) ores.add(stack); } } } } public boolean isAlive() { return world != null; } public boolean isFinished() { return false; } public boolean getJammed() { return jammed; } public void setJammed(boolean newJam) { jammed = newJam; } public void deactivateLaser() { this.world = null; } /** * creates the laser and begins mining. This can * fail if the chunk cannot be force loaded * @param world world to spawn the laser into * @param x x coord * @param z z coord * @return whether creating the laser is successful */ public boolean activateLaser(World world, int x, int z) { this.world = world; return true; } public void performOperation() { ArrayList<ItemStack> items = new ArrayList<ItemStack>(); if(random.nextInt(10) == 0) { ItemStack item = ores.get(random.nextInt(ores.size())); ItemStack newStack = item.copy(); items.add(newStack); } else items.add(new ItemStack(Blocks.COBBLESTONE, 5)); //TODO: generate Items if(boundChest != null){ ItemStack stacks[] = new ItemStack[items.size()]; stacks = items.toArray(stacks); ZUtils.mergeInventory(stacks, boundChest); if(!ZUtils.isInvEmpty(stacks)) { //TODO: drop extra items this.deactivateLaser(); this.jammed = true; return; } } } @Override public String getInfo(World world) { return null; } @Override public String getName() { return "Laser"; } @Override public boolean performAction(EntityPlayer player, World world, BlockPos pos) { performOperation(); return false; } @Override public double failureChance() { return 0; } @Override public void writeToNBT(NBTTagCompound nbt) { nbt.setBoolean("jammed", jammed); } @Override public void readFromNBT(NBTTagCompound nbt) { jammed = nbt.getBoolean("jammed"); } @Override public boolean canTick() { return false; } @Override public void tickEntity() { } }
package org.mtransit.parser.ca_london_transit_bus; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.mtransit.parser.CleanUtils; import org.mtransit.parser.DefaultAgencyTools; import org.mtransit.parser.Pair; import org.mtransit.parser.SplitUtils; import org.mtransit.parser.SplitUtils.RouteTripSpec; import org.mtransit.parser.Utils; import org.mtransit.parser.gtfs.data.GCalendar; import org.mtransit.parser.gtfs.data.GCalendarDate; import org.mtransit.parser.gtfs.data.GRoute; import org.mtransit.parser.gtfs.data.GSpec; import org.mtransit.parser.gtfs.data.GStop; import org.mtransit.parser.gtfs.data.GTrip; import org.mtransit.parser.gtfs.data.GTripStop; import org.mtransit.parser.mt.data.MAgency; import org.mtransit.parser.mt.data.MRoute; import org.mtransit.parser.mt.data.MTrip; import org.mtransit.parser.mt.data.MTripStop; public class LondonTransitBusAgencyTools extends DefaultAgencyTools { public static void main(String[] args) { if (args == null || args.length == 0) { args = new String[3]; args[0] = "input/gtfs.zip"; args[1] = "../../mtransitapps/ca-london-transit-bus-android/res/raw/"; args[2] = ""; // files-prefix } new LondonTransitBusAgencyTools().start(args); } private HashSet<String> serviceIds; @Override public void start(String[] args) { System.out.printf("\nGenerating London Transit bus data..."); long start = System.currentTimeMillis(); this.serviceIds = extractUsefulServiceIds(args, this); super.start(args); System.out.printf("\nGenerating London Transit bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start)); } @Override public boolean excludeCalendar(GCalendar gCalendar) { if (this.serviceIds != null) { return excludeUselessCalendar(gCalendar, this.serviceIds); } return super.excludeCalendar(gCalendar); } @Override public boolean excludeCalendarDate(GCalendarDate gCalendarDates) { if (this.serviceIds != null) { return excludeUselessCalendarDate(gCalendarDates, this.serviceIds); } return super.excludeCalendarDate(gCalendarDates); } @Override public boolean excludeTrip(GTrip gTrip) { if (this.serviceIds != null) { return excludeUselessTrip(gTrip, this.serviceIds); } return super.excludeTrip(gTrip); } @Override public Integer getAgencyRouteType() { return MAgency.ROUTE_TYPE_BUS; } @Override public long getRouteId(GRoute gRoute) { return Long.parseLong(gRoute.getRouteShortName()); // use route short name as route ID } public String getRouteShortName(GRoute gRoute) { if (Utils.isDigitsOnly(gRoute.getRouteShortName())) { return String.valueOf(Integer.parseInt(gRoute.getRouteShortName())); // remove leading 0 } return super.getRouteShortName(gRoute); } @Override public String getRouteLongName(GRoute gRoute) { String routeLongName = gRoute.getRouteLongName(); routeLongName = routeLongName.toLowerCase(Locale.ENGLISH); return CleanUtils.cleanLabel(routeLongName); } private static final String AGENCY_COLOR_GREEN = "009F60"; // GREEN (from web site CSS) private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN; @Override public String getAgencyColor() { return AGENCY_COLOR; } @Override public String getRouteColor(GRoute gRoute) { int rsn = Integer.parseInt(gRoute.getRouteShortName()); switch (rsn) { // @formatter:off case 1: return "007393"; case 2: return "006468"; case 3: return "A78B6B"; case 4: return "91278F"; case 5: return "72BF44"; case 6: return "496E6E"; case 7: return "0071BC"; case 8: return "7670B3"; case 9: return "A47275"; case 10: return "0066B3"; case 11: return "F05B72"; case 12: return "A54686"; case 13: return "485E88"; case 14: return "3B8476"; case 15: return "00AAAD"; case 16: return "00A650"; case 17: return "ED1C24"; case 18: return "D1AC3E"; case 19: return "009BDF"; case 20: return "00839B"; case 21: return "00AEEF"; case 22: return "2E3092"; case 23: return "CD8C5D"; case 24: return "EC008C"; case 25: return "D2AB67"; case 26: return "806A50"; case 27: return "665874"; case 28: return "0086A6"; case 29: return "A55560"; case 30: return "BD1A8D"; case 31: return "008641"; case 32: return "F287B7"; case 33: return "874487"; case 34: return "0095DA"; case 35: return "FFC20E"; case 36: return "D9186B"; case 37: return "0084BC"; case 38: return "DA2128"; case 39: return "B0789A"; case 90: return "F5821F"; case 91: return "F5821F"; case 92: return "F5821F"; // @formatter:on } System.out.printf("\nUnexpected route color %s!\n", gRoute); System.exit(-1); return null; } private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2; static { HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>(); ALL_ROUTE_TRIPS2 = map2; } @Override public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) { if (ALL_ROUTE_TRIPS2.containsKey(routeId)) { return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop); } return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop); } @Override public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips(); } return super.splitTrip(mRoute, gTrip, gtfs); } @Override public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId())); } return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS); } private static final String AND = " & "; private static final String AT = " @ "; private static final String SLASH = " / "; private static final String _ = " "; private static final String UWO = "UWO"; private static final String INDUSTRIAL_SHORT = "Ind"; private static final String ADELAIDE = "Adelaide"; private static final String ALDERSBROOK = "Aldersbrook"; private static final String AIRPORT = "Airport"; private static final String ARGYLE_MALL = "Argyle Mall"; private static final String BARKER = "Barker"; private static final String BLACKACRES = "Blackacres"; private static final String BONAVENTURE = "Bonaventure"; private static final String BRIARHILL = "Briarhill"; private static final String BRIXHAM = "Brixham"; private static final String BYRON_BASELINE = "Byron Baseline"; private static final String CAPULET = "Capulet"; private static final String CHELTON = "Chelton"; private static final String COLONEL_TALBOT = "Colonel Talbot"; private static final String COMMISSIONERS = "Commissioners"; private static final String DALHOUSIE = "Dalhousie"; private static final String DARNLEY = "Darnley"; private static final String DEVERON = "Deveron"; private static final String DOWNTOWN = "Downtown"; private static final String FANSHAWE = "Fanshawe"; private static final String FANSHAWE_COLLEGE = FANSHAWE + " College"; private static final String FARRAH = "Farrah"; private static final String FIRESTONE = "Firestone"; private static final String GORE = "Gore"; private static final String GRENFELL = "Grenfell"; private static final String GRIFFITH = "Griffith"; private static final String HIGHBURY = "Highbury"; private static final String HURON = "Huron"; private static final String HYDE_PARK = "Hyde Pk"; private static final String INDUSTRIAL_PARK = INDUSTRIAL_SHORT + " Pk"; private static final String KIPPS = "Kipps"; private static final String KIPPS_LANE = KIPPS + " Ln"; private static final String MASONVILLE = "Masonville"; private static final String MASONVILLE_MALL = MASONVILLE + " Mall"; private static final String MASONVILLE_PLACE = MASONVILLE + " Pl"; private static final String MCLEAN = "Mclean"; private static final String MEADOWGATE = "Meadowgate"; private static final String NORTHRIDGE = "Northridge"; private static final String OAKVILLE = "Oakville"; private static final String OUTER = "Outer"; private static final String OXFORD = "Oxford"; private static final String PARKWOOD_HOSPITAL = "Parkwood Hosp"; private static final String PORTSMOUTH = "Portsmouth"; private static final String POWER_CTR = "Power Ctr"; private static final String PROUDFOOT = "Proudfoot"; private static final String REARDON = "Reardon"; private static final String RIVERSIDE = "Riverside"; private static final String SOVEREIGN = "Sovereign"; private static final String STONEY_CREEK = "Stoney Crk"; private static final String VICTORIA_HOSPITAL = "Victoria Hosp"; private static final String UNIV_WESTERN_ONTARIO = UWO; // "Univ Western Ontario"; private static final String WESTERN_UNIVERSITY = UWO; // "Western University"; private static final String WESTMOUNT_MALL = "Westmount Mall"; private static final String WEYMOUTH = "Weymouth"; private static final String WHARNCLIFFE = "Wharncliffe"; private static final String WHITE_OAKS_MALL = "White Oaks Mall"; private static final String WILTON_GROVE = "Wilton Grv"; private static final String WONDERLAND = "Wonderland"; private static final String AIRPORT_AND_INDUSTRIAL_AREA = AIRPORT + AND + INDUSTRIAL_SHORT; // + " area"; private static final String ALDERSBROOK_AT_BLACKACRES = ALDERSBROOK + AT + BLACKACRES; private static final String BARKER_AT_HURON = BARKER + AT + HURON; private static final String BYRON_BASELINE_AT_GRIFFITH = BYRON_BASELINE + AT + GRIFFITH; private static final String CAPULET_AT_OXFORD = CAPULET + AT + OXFORD; private static final String CHELTON_AT_REARDON = CHELTON + AT + REARDON; private static final String COMMISSIONERS_AT_DEVERON = COMMISSIONERS + AT + DEVERON; private static final String DALHOUSIE_AT_BRIXHAM = DALHOUSIE + AT + BRIXHAM; private static final String DARNLEY_AT_MEADOWGATE = DARNLEY + AT + MEADOWGATE; private static final String FANSHAWE_AT_MCLEAN = FANSHAWE + AT + MCLEAN; private static final String FARRAH_AT_PROUDFOOT = FARRAH + AT + PROUDFOOT; private static final String FIRESTONE_AT_GORE = FIRESTONE + AT + GORE; private static final String GORE_AT_FIRESTONE = GORE + AT + FIRESTONE; private static final String GRENFELL_NORTHRIDGE = GRENFELL + SLASH + NORTHRIDGE; private static final String GRIFFITH_AT_BYRON_BASELINE = GRIFFITH + AT + BYRON_BASELINE; private static final String HURON_AT_HIGHBURY = HURON + AT + HIGHBURY; private static final String HYDE_PARK_POWER_CENTRE = HYDE_PARK + _ + POWER_CTR; private static final String KIPPS_AT_ADELAIDE = KIPPS + AT + ADELAIDE; private static final String KIPPS_LANE_AT_BRIARHILL = KIPPS_LANE + AT + BRIARHILL; private static final String OAKVILLE_AT_HURON = OAKVILLE + AT + HURON; private static final String OUTER_AT_COLONEL_TALBOT = OUTER + AT + COLONEL_TALBOT; private static final String RIVERSIDE_AT_WHARNCLIFFE_ONLY = RIVERSIDE + AT + WHARNCLIFFE; // + " only"; private static final String WEYMOUTH_AT_PORTSMOUTH = WEYMOUTH + AT + PORTSMOUTH; private static final String WILTON_GROVE_INDUSTRIAL_PARK = WILTON_GROVE + _ + INDUSTRIAL_PARK; private static final String WONDERLAND_AT_OXFORD = WONDERLAND + AT + OXFORD; private static final String WONDERLAND_OXFORD = WONDERLAND + SLASH + OXFORD; private static final String WONDERLAND_POWER_CENTRE = WONDERLAND + _ + POWER_CTR; private static final int LTC_EASTBOUND = 1; private static final int LTC_NORTHBOUND = 2; private static final int LTC_SOUTHBOUND = 3; private static final int LTC_WESTBOUND = 4; @Override public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) { if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) { return; // split } if (mRoute.getId() == 1l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(COMMISSIONERS_AT_DEVERON, LTC_SOUTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(KIPPS_LANE_AT_BRIARHILL, LTC_NORTHBOUND); return; } } else if (mRoute.getId() == 2l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(BONAVENTURE, LTC_EASTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(WESTERN_UNIVERSITY, LTC_WESTBOUND); return; } } else if (mRoute.getId() == 3l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(GORE_AT_FIRESTONE, LTC_EASTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(DOWNTOWN, LTC_WESTBOUND); return; } } else if (mRoute.getId() == 4l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(WHITE_OAKS_MALL, LTC_SOUTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(FANSHAWE_COLLEGE, LTC_NORTHBOUND); return; } } else if (mRoute.getId() == 5l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(GRIFFITH_AT_BYRON_BASELINE, LTC_WESTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(DOWNTOWN, LTC_EASTBOUND); return; } } else if (mRoute.getId() == 6l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(WESTERN_UNIVERSITY, LTC_NORTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(PARKWOOD_HOSPITAL, LTC_SOUTHBOUND); return; } } else if (mRoute.getId() == 7l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(ARGYLE_MALL, LTC_EASTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(DOWNTOWN, LTC_WESTBOUND); return; } } else if (mRoute.getId() == 8l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(BYRON_BASELINE_AT_GRIFFITH, LTC_WESTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(DOWNTOWN, LTC_EASTBOUND); return; } } else if (mRoute.getId() == 9l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(ALDERSBROOK_AT_BLACKACRES, LTC_WESTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(DOWNTOWN, LTC_EASTBOUND); return; } } else if (mRoute.getId() == 10l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(MASONVILLE, LTC_NORTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(WHITE_OAKS_MALL, LTC_SOUTHBOUND); return; } } else if (mRoute.getId() == 11l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(WESTMOUNT_MALL, LTC_WESTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(DOWNTOWN, LTC_EASTBOUND); return; } } else if (mRoute.getId() == 12l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(WONDERLAND_POWER_CENTRE, LTC_SOUTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(DOWNTOWN, LTC_NORTHBOUND); return; } } else if (mRoute.getId() == 13l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(WHITE_OAKS_MALL, LTC_SOUTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(GRENFELL_NORTHRIDGE, LTC_NORTHBOUND); return; } } else if (mRoute.getId() == 14l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(BARKER_AT_HURON, LTC_NORTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(WHITE_OAKS_MALL, LTC_SOUTHBOUND); return; } } else if (mRoute.getId() == 15l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(WESTMOUNT_MALL, LTC_SOUTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(DOWNTOWN, LTC_NORTHBOUND); return; } } else if (mRoute.getId() == 16l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(DARNLEY_AT_MEADOWGATE, LTC_SOUTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(MASONVILLE_MALL, LTC_NORTHBOUND); return; } } else if (mRoute.getId() == 17l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(FIRESTONE_AT_GORE, LTC_EASTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString("BYRON_BASELINE_AT_GRIFFITH", LTC_WESTBOUND); return; } } else if (mRoute.getId() == 18l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(RIVERSIDE_AT_WHARNCLIFFE_ONLY, LTC_SOUTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(WESTERN_UNIVERSITY, LTC_NORTHBOUND); return; } } else if (mRoute.getId() == 19l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(HYDE_PARK_POWER_CENTRE, LTC_WESTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(DOWNTOWN, LTC_EASTBOUND); return; } } else if (mRoute.getId() == 20l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(FANSHAWE_COLLEGE, LTC_EASTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(CAPULET_AT_OXFORD, LTC_WESTBOUND); return; } } else if (mRoute.getId() == 21l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(OAKVILLE_AT_HURON, LTC_NORTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(DOWNTOWN, LTC_SOUTHBOUND); return; } } else if (mRoute.getId() == 22l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(ARGYLE_MALL, LTC_EASTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(DOWNTOWN, LTC_WESTBOUND); return; } } else if (mRoute.getId() == 23l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(DALHOUSIE_AT_BRIXHAM, LTC_WESTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(DOWNTOWN, LTC_EASTBOUND); return; } } else if (mRoute.getId() == 24l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(WESTMOUNT_MALL, LTC_WESTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(CHELTON_AT_REARDON, LTC_EASTBOUND); return; } } else if (mRoute.getId() == 25l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(FANSHAWE_AT_MCLEAN, LTC_NORTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(FANSHAWE_COLLEGE, LTC_SOUTHBOUND); return; } } else if (mRoute.getId() == 26l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(WHITE_OAKS_MALL, LTC_SOUTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(DOWNTOWN, LTC_NORTHBOUND); return; } } else if (mRoute.getId() == 27l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(KIPPS_AT_ADELAIDE, LTC_WESTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(FANSHAWE_COLLEGE, LTC_EASTBOUND); return; } } else if (mRoute.getId() == 28l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(OUTER_AT_COLONEL_TALBOT, LTC_SOUTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(WESTMOUNT_MALL, LTC_NORTHBOUND); return; } } else if (mRoute.getId() == 29l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(CAPULET, LTC_NORTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(WONDERLAND_OXFORD, LTC_SOUTHBOUND); return; } } else if (mRoute.getId() == 30l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(WILTON_GROVE_INDUSTRIAL_PARK, LTC_EASTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(WHITE_OAKS_MALL, LTC_WESTBOUND); return; } } else if (mRoute.getId() == 31l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(HYDE_PARK_POWER_CENTRE, LTC_WESTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(UNIV_WESTERN_ONTARIO, LTC_EASTBOUND); return; } } else if (mRoute.getId() == 32l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(HURON_AT_HIGHBURY, LTC_EASTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(WESTERN_UNIVERSITY, LTC_WESTBOUND); return; } } else if (mRoute.getId() == 33l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(FARRAH_AT_PROUDFOOT, LTC_WESTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(WESTERN_UNIVERSITY, LTC_EASTBOUND); return; } } else if (mRoute.getId() == 34l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(MASONVILLE_MALL, LTC_EASTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(WESTERN_UNIVERSITY, LTC_WESTBOUND); return; } } else if (mRoute.getId() == 35l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(WEYMOUTH_AT_PORTSMOUTH, LTC_SOUTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(ARGYLE_MALL, LTC_NORTHBOUND); return; } } else if (mRoute.getId() == 36l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(AIRPORT_AND_INDUSTRIAL_AREA, LTC_EASTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(FANSHAWE_COLLEGE, LTC_WESTBOUND); return; } } else if (mRoute.getId() == 37l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(SOVEREIGN, LTC_SOUTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(ARGYLE_MALL, LTC_NORTHBOUND); return; } } else if (mRoute.getId() == 38l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(STONEY_CREEK, LTC_NORTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(MASONVILLE_MALL, LTC_SOUTHBOUND); return; } } else if (mRoute.getId() == 39l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(HYDE_PARK_POWER_CENTRE, LTC_WESTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(MASONVILLE_MALL, LTC_EASTBOUND); return; } } else if (mRoute.getId() == 90l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(WHITE_OAKS_MALL, LTC_SOUTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(MASONVILLE_PLACE, LTC_NORTHBOUND); return; } } else if (mRoute.getId() == 91l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(FANSHAWE_COLLEGE, LTC_EASTBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(WONDERLAND_AT_OXFORD, LTC_WESTBOUND); return; } } else if (mRoute.getId() == 92l) { if (gTrip.getDirectionId() == 0) { mTrip.setHeadsignString(MASONVILLE_PLACE, LTC_NORTHBOUND); return; } else if (gTrip.getDirectionId() == 1) { mTrip.setHeadsignString(VICTORIA_HOSPITAL, LTC_SOUTHBOUND); return; } } System.out.printf("\n%s: Unexpected trip %s!\n", mRoute.getId(), gTrip); System.exit(-1); } private static final Pattern AREA = Pattern.compile("((^|\\W){1}(area)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final Pattern INDUSTRIAL = Pattern.compile("((^|\\W){1}(industrial)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String INDUSTRIAL_REPLACEMENT = "$2" + INDUSTRIAL_SHORT + "$4"; private static final Pattern ONLY = Pattern.compile("((^|\\W){1}(only)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final Pattern UNIVERSITY_OF_WESTERN_ONTARIO = Pattern.compile("((^|\\W){1}(univ western ontario|western university)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String UNIVERSITY_OF_WESTERN_ONTARIO_REPLACEMENT = "$2" + UWO + "$4"; @Override public String cleanTripHeadsign(String tripHeadsign) { tripHeadsign = AREA.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY); tripHeadsign = INDUSTRIAL.matcher(tripHeadsign).replaceAll(INDUSTRIAL_REPLACEMENT); tripHeadsign = ONLY.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY); tripHeadsign = UNIVERSITY_OF_WESTERN_ONTARIO.matcher(tripHeadsign).replaceAll(UNIVERSITY_OF_WESTERN_ONTARIO_REPLACEMENT); tripHeadsign = CleanUtils.CLEAN_AT.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); tripHeadsign = CleanUtils.CLEAN_AND.matcher(tripHeadsign).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign); tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign); tripHeadsign = CleanUtils.cleanStreetTypesFRCA(tripHeadsign); return CleanUtils.cleanLabel(tripHeadsign); } private static final Pattern BOUNDS = Pattern.compile("(eb|wb|nb|sb|fs|ns)", Pattern.CASE_INSENSITIVE); private static final Pattern ENDS_WITH_STOP_CODE = Pattern.compile("( \\- #[\\d]*$)", Pattern.CASE_INSENSITIVE); private static final Pattern HOS = Pattern.compile("((^|\\W){1}(hos)(\\W|$){1})", Pattern.CASE_INSENSITIVE); private static final String HOS_REPLACEMENT = "$2Hospital$4"; @Override public String cleanStopName(String gStopName) { if (Utils.isUppercaseOnly(gStopName, true, true)) { gStopName = gStopName.toLowerCase(Locale.ENGLISH); } gStopName = BOUNDS.matcher(gStopName).replaceAll(StringUtils.EMPTY); gStopName = ENDS_WITH_STOP_CODE.matcher(gStopName).replaceAll(StringUtils.EMPTY); gStopName = HOS.matcher(gStopName).replaceAll(HOS_REPLACEMENT); gStopName = CleanUtils.CLEAN_AND.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AND_REPLACEMENT); gStopName = CleanUtils.CLEAN_AT.matcher(gStopName).replaceAll(CleanUtils.CLEAN_AT_REPLACEMENT); gStopName = CleanUtils.removePoints(gStopName); gStopName = CleanUtils.cleanNumbers(gStopName); gStopName = CleanUtils.cleanStreetTypes(gStopName); gStopName = CleanUtils.cleanStreetTypesFRCA(gStopName); return CleanUtils.cleanLabel(gStopName); } }
package org.geogit.storage.bdbje; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Iterators.partition; import static com.sleepycat.je.OperationStatus.NOTFOUND; import static com.sleepycat.je.OperationStatus.SUCCESS; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import org.geogit.api.ObjectId; import org.geogit.api.RevObject; import org.geogit.repository.RepositoryConnectionException; import org.geogit.storage.AbstractObjectDatabase; import org.geogit.storage.BulkOpListener; import org.geogit.storage.ConfigDatabase; import org.geogit.storage.ObjectDatabase; import org.geogit.storage.ObjectReader; import org.geogit.storage.ObjectSerializingFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Stopwatch; import com.google.common.base.Throwables; import com.google.common.collect.AbstractIterator; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.UnmodifiableIterator; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.Inject; import com.ning.compress.lzf.LZFInputStream; import com.sleepycat.je.CacheMode; import com.sleepycat.je.Cursor; import com.sleepycat.je.CursorConfig; import com.sleepycat.je.Database; import com.sleepycat.je.DatabaseConfig; import com.sleepycat.je.DatabaseEntry; import com.sleepycat.je.Durability; import com.sleepycat.je.Environment; import com.sleepycat.je.LockMode; import com.sleepycat.je.OperationStatus; import com.sleepycat.je.Transaction; import com.sleepycat.je.TransactionConfig; public class JEObjectDatabase extends AbstractObjectDatabase implements ObjectDatabase { private static final Logger LOGGER = LoggerFactory.getLogger(JEObjectDatabase.class); private static final int SYNC_BYTES_LIMIT = 512 * 1024 * 1024; @Nullable private ExecutorService dbSyncService; private ExecutorService writerService; /** * The default number of objects bulk operations are partitioned into * * @see #getAll(Iterable, BulkOpListener) * @see #putAll(Iterator, BulkOpListener) * @see #deleteAll(Iterator, BulkOpListener) */ private static final Integer DEFAULT_BULK_PARTITIONING = 10 * 1000; private static final String BULK_PARTITIONING_CONFIG_KEY = "bdbje.bulkpartition"; private EnvironmentBuilder envProvider; /** * Lazily loaded, do not access it directly but through {@link #getEnvironment()} */ protected Environment env; protected Database objectDb; private ConfigDatabase configDB; @Inject public JEObjectDatabase(final ConfigDatabase configDB, final ObjectSerializingFactory serialFactory, final EnvironmentBuilder envProvider) { super(serialFactory); this.configDB = configDB; this.envProvider = envProvider; } public JEObjectDatabase(final ObjectSerializingFactory serialFactory, final Environment env, final ConfigDatabase configDb) { super(serialFactory); this.env = env; this.configDB = configDb; } /** * @return the env */ private synchronized Environment getEnvironment() { if (env == null) { env = envProvider.setRelativePath("objects").get(); } return env; } @Override public synchronized void close() { if (env == null) { LOGGER.trace("Database already closed."); return; } final File envHome = env.getHome(); LOGGER.debug("Closing object database at {}", envHome); writerService.shutdownNow(); objectDb.close(); objectDb = null; if (dbSyncService != null) { dbSyncService.shutdownNow(); } LOGGER.trace("ObjectDatabase closed. Closing environment..."); env.sync(); env.cleanLog(); env.close(); env = null; LOGGER.debug("Database {} closed.", envHome); } @Override public boolean isOpen() { return objectDb != null; } @Override public synchronized void open() { if (isOpen()) { LOGGER.trace("Environment {} already open", env.getHome()); return; } Environment environment = getEnvironment(); LOGGER.debug("Opening ObjectDatabase at {}", env.getHome()); this.objectDb = createDatabase(environment); int nWriterThreads = 1; writerService = Executors.newFixedThreadPool(nWriterThreads, new ThreadFactoryBuilder() .setNameFormat("BDBJE-" + env.getHome().getName() + "-WRITE-THREAD-%d").build()); if (!objectDb.getConfig().getTransactional()) { dbSyncService = Executors.newFixedThreadPool(nWriterThreads, new ThreadFactoryBuilder() .setNameFormat("BDBJE-" + env.getHome().getName() + "-SYNC-THREAD-%d").build()); } LOGGER.debug("Object database opened at {}. Transactional: {}", environment.getHome(), objectDb.getConfig().getTransactional()); } protected Database createDatabase(Environment environment) { DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setAllowCreate(true); boolean transactional = getEnvironment().getConfig().getTransactional(); dbConfig.setTransactional(transactional); dbConfig.setDeferredWrite(!transactional); dbConfig.setCacheMode(CacheMode.MAKE_COLD); dbConfig.setKeyPrefixing(false);// can result in a slightly smaller db size Database database = environment.openDatabase(null, "ObjectDatabase", dbConfig); return database; } @Override protected List<ObjectId> lookUpInternal(final byte[] partialId) { DatabaseEntry key; { byte[] keyData = partialId.clone(); key = new DatabaseEntry(keyData); } DatabaseEntry data = new DatabaseEntry(); data.setPartial(0, 0, true);// do not retrieve data List<ObjectId> matches; CursorConfig cursorConfig = new CursorConfig(); cursorConfig.setReadUncommitted(true); Transaction transaction = null; Cursor cursor = objectDb.openCursor(transaction, cursorConfig); try { // position cursor at the first closest key to the one looked up OperationStatus status = cursor.getSearchKeyRange(key, data, LockMode.READ_UNCOMMITTED); if (SUCCESS.equals(status)) { matches = new ArrayList<ObjectId>(2); final byte[] compKey = new byte[partialId.length]; while (SUCCESS.equals(status)) { byte[] keyData = key.getData(); System.arraycopy(keyData, 0, compKey, 0, compKey.length); if (Arrays.equals(partialId, compKey)) { matches.add(new ObjectId(keyData)); } else { break; } status = cursor.getNext(key, data, LockMode.READ_UNCOMMITTED); } } else { matches = Collections.emptyList(); } return matches; } finally { cursor.close(); } } /** * @see org.geogit.storage.ObjectDatabase#exists(org.geogit.api.ObjectId) */ @Override public boolean exists(final ObjectId id) { Preconditions.checkNotNull(id, "id"); DatabaseEntry key = new DatabaseEntry(id.getRawValue()); DatabaseEntry data = new DatabaseEntry(); // tell db not to retrieve data data.setPartial(0, 0, true); final LockMode lockMode = LockMode.READ_UNCOMMITTED; Transaction transaction = null; OperationStatus status = objectDb.get(transaction, key, data, lockMode); return SUCCESS == status; } @Override protected InputStream getRawInternal(final ObjectId id, final boolean failIfNotFound) { Preconditions.checkNotNull(id, "id"); DatabaseEntry key = new DatabaseEntry(id.getRawValue()); DatabaseEntry data = new DatabaseEntry(); final LockMode lockMode = LockMode.READ_UNCOMMITTED; Transaction transaction = null; OperationStatus operationStatus = objectDb.get(transaction, key, data, lockMode); if (NOTFOUND.equals(operationStatus)) { if (failIfNotFound) { throw new IllegalArgumentException("Object does not exist: " + id.toString()); } return null; } final byte[] cData = data.getData(); return new ByteArrayInputStream(cData); } @Override public void putAll(final Iterator<? extends RevObject> objects, final BulkOpListener listener) { checkNotNull(objects); checkNotNull(listener); if (!objects.hasNext()) { return; } final int buffSize = 8 * 1024; BulkInsert task = new BulkInsert(objects, listener, buffSize); try { Integer insertedCount = task.run(); } catch (Exception e) { throw Throwables.propagate(e); } } private class BulkInsert { private BulkOpListener listener; private int buffSize; private Iterator<? extends RevObject> objects; public BulkInsert(final Iterator<? extends RevObject> objects, final BulkOpListener listener, final int buffSize) { this.objects = objects; this.listener = listener; this.buffSize = buffSize; } public Integer run() throws Exception { int count = 0; List<Future<Void>> pendingWrites = new ArrayList<Future<Void>>(); try { InternalByteArrayOutputStream out = new InternalByteArrayOutputStream(this.buffSize); TreeMap<ObjectId, int[]> offsets = Maps.newTreeMap(ObjectId.NATURAL_ORDER); int objectsInBuffer = 0; while (true) { if (!serializeNextObject(offsets, out)) { break; } count++; objectsInBuffer++; if (out.size() >= buffSize) { Future<Void> future = insertSortedObjects(offsets, out); // future.get(); // out.reset(); // offsets.clear(); out = new InternalByteArrayOutputStream(this.buffSize); offsets = Maps.newTreeMap(ObjectId.NATURAL_ORDER); pendingWrites.add(future); if (pendingWrites.size() == 10) { waitForWrites(pendingWrites); } LOGGER.debug("Inserted {} objects with a byte buffer of {} KB", objectsInBuffer, (out.size() / 1024)); objectsInBuffer = 0; out.reset(); } } if (!offsets.isEmpty()) { Future<Void> future = insertSortedObjects(offsets, out); pendingWrites.add(future); LOGGER.debug("Inserted {} objects with a byte buffer of {} KB", objectsInBuffer, (out.size() / 1024)); } waitForWrites(pendingWrites); } catch (Exception e) { LOGGER.error("Error inserting objects: " + e.getMessage(), e); throw e; } finally { pendingWrites.clear(); pendingWrites = null; } return count; } private void waitForWrites(List<Future<Void>> pendingWrites) throws InterruptedException, ExecutionException { if (pendingWrites.isEmpty()) { return; } for (Future<Void> pendingWrite : pendingWrites) { if (!pendingWrite.isDone()) { pendingWrite.get(); } } pendingWrites.clear(); } private Future<Void> insertSortedObjects(TreeMap<ObjectId, int[]> offsets, InternalByteArrayOutputStream buffer) throws Exception { return writerService.submit(new InsertTask(offsets, buffer, listener)); } private boolean serializeNextObject(TreeMap<ObjectId, int[]> offsets, InternalByteArrayOutputStream out) { if (!objects.hasNext()) { return false; } RevObject o = objects.next(); int offset = out.size(); writeObject(o, out); int size = out.size() - offset; offsets.put(o.getId(), new int[] { offset, size }); return true; } } private AtomicInteger bytesWritten = new AtomicInteger(); private class InsertTask implements Callable<Void> { private TreeMap<ObjectId, int[]> offsets; private InternalByteArrayOutputStream buffer; private BulkOpListener listener; public InsertTask(TreeMap<ObjectId, int[]> offsets, InternalByteArrayOutputStream buffer, BulkOpListener listener) { this.offsets = offsets; this.buffer = buffer; this.listener = listener; } @Override public Void call() throws Exception { Transaction transaction = newTransaction(); final int numObjects = offsets.size(); try { final int bufferBytes = buffer.size(); DatabaseEntry key = new DatabaseEntry(new byte[ObjectId.NUM_BYTES]); final byte[] rawData = buffer.bytes(); for (Iterator<Map.Entry<ObjectId, int[]>> it = offsets.entrySet().iterator(); it .hasNext();) { Entry<ObjectId, int[]> e = it.next(); it.remove(); final ObjectId objectId = e.getKey(); int offset = e.getValue()[0]; int size = e.getValue()[1]; objectId.getRawValue(key.getData()); DatabaseEntry data = new DatabaseEntry(rawData, offset, size); OperationStatus status = objectDb.putNoOverwrite(transaction, key, data); if (OperationStatus.SUCCESS.equals(status)) { listener.inserted(objectId, size); } else if (OperationStatus.KEYEXIST.equals(status)) { listener.found(objectId, null); } } final boolean transactional = objectDb.getConfig().getTransactional(); if (transactional) { commit(transaction); LOGGER.trace("Committed {} inserts to {}", numObjects, objectDb .getEnvironment().getHome()); } else { int totalWritten; synchronized (bytesWritten) { totalWritten = bytesWritten.addAndGet(bufferBytes); } if (totalWritten >= SYNC_BYTES_LIMIT) { writerService.execute(new FlushLogTask(bytesWritten, objectDb)); } } } catch (Exception e) { abort(transaction); throw e; } finally { offsets = null; buffer = null; } return null; } } private class FlushLogTask implements Runnable { private Environment env; private volatile AtomicInteger bytesWritten; private Database objectDb; public FlushLogTask(AtomicInteger bytesWritten, Database objectDb) { this.bytesWritten = bytesWritten; this.objectDb = objectDb; this.env = objectDb.getEnvironment(); } @Override public void run() { boolean doSync = false; final int buffSize; synchronized (bytesWritten) { buffSize = bytesWritten.get(); if (buffSize >= SYNC_BYTES_LIMIT) { doSync = true; bytesWritten.set(0); } } if (doSync) { Preconditions.checkState(dbSyncService != null, "DB Sync executor service is null, but the database is non transactional."); dbSyncService.execute(new Runnable() { @Override public void run() { Stopwatch sw = new Stopwatch().start(); if (objectDb.getConfig().getDeferredWrite()) { objectDb.sync(); env.evictMemory(); env.cleanLog(); // env.sync(); } else { env.flushLog(false); } LOGGER.debug("flushed db log after {} bytes in {}", buffSize, sw.stop()); } }); } } } @Override protected boolean putInternal(final ObjectId id, final byte[] rawData) { final Transaction transaction = newTransaction(); final OperationStatus status; try { status = putInternal(id, rawData, transaction); commit(transaction); } catch (RuntimeException e) { abort(transaction); throw e; } final boolean didntExist = SUCCESS.equals(status); return didntExist; } private OperationStatus putInternal(final ObjectId id, final byte[] rawData, Transaction transaction) { OperationStatus status; final byte[] rawKey = id.getRawValue(); DatabaseEntry key = new DatabaseEntry(rawKey); DatabaseEntry data = new DatabaseEntry(rawData); status = objectDb.putNoOverwrite(transaction, key, data); return status; } @Override public boolean delete(final ObjectId id) { final byte[] rawKey = id.getRawValue(); final DatabaseEntry key = new DatabaseEntry(rawKey); final Transaction transaction = newTransaction(); final OperationStatus status; try { status = objectDb.delete(transaction, key); commit(transaction); } catch (RuntimeException e) { abort(transaction); throw e; } return SUCCESS.equals(status); } private void abort(@Nullable Transaction transaction) { if (transaction != null) { try { transaction.abort(); } catch (Exception e) { LOGGER.error("Error aborting transaction", e); } } } private void commit(@Nullable Transaction transaction) { if (transaction != null) { try { transaction.commit(); } catch (Exception e) { LOGGER.error("Error committing transaction", e); } } } @Override public long deleteAll(Iterator<ObjectId> ids, final BulkOpListener listener) { long count = 0; UnmodifiableIterator<List<ObjectId>> partition = partition(ids, getBulkPartitionSize()); final DatabaseEntry data = new DatabaseEntry(); data.setPartial(0, 0, true);// do not retrieve data while (partition.hasNext()) { List<ObjectId> nextIds = Lists.newArrayList(partition.next()); Collections.sort(nextIds); final Transaction transaction = newTransaction(); CursorConfig cconfig = new CursorConfig(); final Cursor cursor = objectDb.openCursor(transaction, cconfig); try { DatabaseEntry key = new DatabaseEntry(new byte[ObjectId.NUM_BYTES]); for (ObjectId id : nextIds) { // copy id to key object without allocating new byte[] id.getRawValue(key.getData()); OperationStatus status = cursor.getSearchKey(key, data, LockMode.DEFAULT); if (OperationStatus.SUCCESS.equals(status)) { OperationStatus delete = cursor.delete(); if (OperationStatus.SUCCESS.equals(delete)) { listener.deleted(id); count++; } else { listener.notFound(id); } } else { listener.notFound(id); } } cursor.close(); } catch (Exception e) { cursor.close(); abort(transaction); Throwables.propagate(e); } commit(transaction); } return count; } @Override public void configure() throws RepositoryConnectionException { RepositoryConnectionException.StorageType.OBJECT.configure(configDB, "bdbje", "0.1"); } @Override public void checkConfig() throws RepositoryConnectionException { RepositoryConnectionException.StorageType.OBJECT.verify(configDB, "bdbje", "0.1"); } @Override public Iterator<RevObject> getAll(final Iterable<ObjectId> ids, final BulkOpListener listener) { Preconditions.checkNotNull(ids, "ids"); return new CursorRevObjectIterator(ids.iterator(), listener); } private class CursorRevObjectIterator extends AbstractIterator<RevObject> implements Closeable { private final ObjectReader<RevObject> reader = serializationFactory.createObjectReader(); @Nullable private Transaction transaction; private Cursor cursor; private BulkOpListener listener; private UnmodifiableIterator<List<ObjectId>> unsortedIds; private Iterator<ObjectId> sortedIds; /** * Uses a transaction to open a read only cursor for it to work when called from a different * threads than the one it was created at. The transaction is aborted at {@link #close()} */ public CursorRevObjectIterator(final Iterator<ObjectId> objectIds, final BulkOpListener listener) { this.unsortedIds = Iterators.partition(objectIds, getBulkPartitionSize()); this.sortedIds = Iterators.emptyIterator(); this.listener = listener; CursorConfig cursorConfig = new CursorConfig(); cursorConfig.setReadUncommitted(true); transaction = getOrCreateTransaction(); this.cursor = objectDb.openCursor(transaction, cursorConfig); } private Transaction getOrCreateTransaction() { final boolean transactional = objectDb.getConfig().getTransactional(); if (!transactional) { return null; } TransactionConfig config = new TransactionConfig(); config.setReadUncommitted(true); Transaction t = env.beginTransaction(null, config); return t; } @Override protected RevObject computeNext() { if (!sortedIds.hasNext()) { if (unsortedIds.hasNext()) { List<ObjectId> unsorted = unsortedIds.next(); List<ObjectId> sorted = ObjectId.NATURAL_ORDER.sortedCopy(unsorted); this.sortedIds = sorted.iterator(); } else { close(); return endOfData(); } } try { byte[] keyBuff = new byte[ObjectId.NUM_BYTES]; DatabaseEntry key = new DatabaseEntry(keyBuff); RevObject found = null; while (sortedIds.hasNext() && found == null) { ObjectId id = sortedIds.next(); id.getRawValue(keyBuff); key.setData(keyBuff); DatabaseEntry data = new DatabaseEntry(); // lookup data for the next key OperationStatus status; status = cursor.getSearchKey(key, data, LockMode.READ_UNCOMMITTED); if (SUCCESS.equals(status)) { InputStream rawData; rawData = new LZFInputStream(new ByteArrayInputStream(data.getData())); found = reader.read(id, rawData); listener.found(found.getId(), data.getSize()); } else { listener.notFound(id); } } if (found == null) { return computeNext(); } return found; } catch (Exception e) { try { throw Throwables.propagate(e); } finally { close(); } } } @Override public void close() { sortedIds = null; Cursor cursor = this.cursor; this.cursor = null; if (cursor != null) { cursor.close(); } if (transaction != null) { transaction.abort(); transaction = null; } } } private int getBulkPartitionSize() { Optional<Integer> configuredSize = configDB .get(BULK_PARTITIONING_CONFIG_KEY, Integer.class); return configuredSize.or(DEFAULT_BULK_PARTITIONING).intValue(); } @Nullable private Transaction newTransaction() { final boolean transactional = objectDb.getConfig().getTransactional(); if (transactional) { TransactionConfig txConfig = new TransactionConfig(); txConfig.setReadUncommitted(true); txConfig.setDurability(Durability.COMMIT_WRITE_NO_SYNC); Transaction transaction = env.beginTransaction(null, txConfig); return transaction; } return null; } @Override protected void finalize() { if (isOpen()) { LOGGER.warn("JEObjectDatabase %s was not closed. Forcing close at finalize()", env.getHome()); close(); } } }
package com.cloudbees.plugins.deployer.casc; import com.cloudbees.plugins.deployer.DeployNowColumn; import hudson.model.View; import io.jenkins.plugins.casc.misc.ConfiguredWithCode; import io.jenkins.plugins.casc.misc.JenkinsConfiguredWithCodeRule; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import java.util.stream.StreamSupport; public class ConfigurationAsCodeTest { @Rule public JenkinsConfiguredWithCodeRule r = new JenkinsConfiguredWithCodeRule(); @Test @ConfiguredWithCode("view-configuration.yml") public void shouldBeAbleToConfigureAView() throws Exception { final View view = r.jenkins.getView("view-with-deployNowColumn"); Assert.assertNotNull(view); Assert.assertTrue( StreamSupport.stream(view.getColumns().spliterator(), false) .anyMatch( item -> item instanceof DeployNowColumn ) ); } }
package net.fender.springboot.aws.cloudsearch; import static com.amazonaws.services.cloudsearchdomain.model.QueryParser.Lucene; import static net.fender.springboot.aws.cloudsearch.CloudSearchClient.*; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.concurrent.Future; import net.fender.springboot.aws.cloudsearch.docs.AddDocument; import net.fender.springboot.aws.cloudsearch.docs.DeleteDocument; import net.fender.springboot.aws.cloudsearch.docs.Document; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.amazonaws.services.cloudsearchdomain.model.BucketInfo; import com.amazonaws.services.cloudsearchdomain.model.Hit; import com.amazonaws.services.cloudsearchdomain.model.SearchRequest; import com.amazonaws.services.cloudsearchdomain.model.SearchResult; import com.amazonaws.services.cloudsearchdomain.model.UploadDocumentsResult; import com.amazonaws.services.cloudsearchv2.model.DescribeDomainsResult; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = { TestBootstrap.class }) public class CloudSearchClientTest { private static final Logger log = LoggerFactory.getLogger(CloudSearchClientTest.class); @Autowired private CloudSearchClient cloudSearchClient; private static String uuid() { return UUID.randomUUID().toString(); } @Test public void test() throws Exception { List<Document> docs = new ArrayList<>(); DescribeDomainsResult describeDomainsResult = cloudSearchClient.describeDomain("devtest-2"); log.debug(describeDomainsResult.toString()); Random random = new Random(); Integer[] ids = new Integer[] { 1234, 2345, 3456, 4567, 5678, 6789, 7890 }; Set<Integer> intSet = new HashSet<>(1000); // create random 8 digit integers for (int i = 0; i < 1000; i++) { String string = ""; for (int j = 0; j < 8; j++) { string += random.nextInt(10); } intSet.add(Integer.valueOf(string)); } List<Integer> ints = new ArrayList<>(intSet); // create test docs for (int j = 0; j < 50_000; j++) { ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Z")); List<Integer> docInts = new ArrayList<>(); int numInts = ints.size(); for (int i = 0; i < 10 + random.nextInt(10); i++) { docInts.add(ints.get(random.nextInt(numInts))); } List<String> literals = new ArrayList<>(); int numToAdd = random.nextInt(4); for (int i = 0; i < numToAdd; i++) { literals.add(uuid()); } TestDocument testDoc = new TestDocument(). withLiteral(uuid()). withListOfIntegers(docInts). withInteger(ids[random.nextInt(ids.length)]). withListOfLiterals(literals). withDate(now); AddDocument doc = AddDocument.withRandomId().withPojo(testDoc); docs.add(doc); } log.info("upload start"); List<UploadDocumentsResult> uploadDocumentsResults = cloudSearchClient.uploadDocuments("devtest-2", docs); for (UploadDocumentsResult uploadDocumentsResult : uploadDocumentsResults) { log.info("uploadDocumentsResult: {}", uploadDocumentsResult); } SearchRequest searchRequest = new SearchRequest(). // tomorrow.toString() + "]"). // // withQuery("integer_i: 1234"). // // withSort("date asc"). // withQuery("*:*"). // withFacet(Facet.toJson("integer_i")). // // withFacet(Facet.toJson("list_of_integers_is")). // withCursor(INITIAL_CURSOR). withSize(10000L). withReturn(NO_FIELDS). withQueryParser(Lucene); log.info("search start"); List<SearchResult> searchResults = cloudSearchClient.search("devtest-2", searchRequest); log.info("search finish"); List<Document> docsToDelete = new ArrayList<>(); for (SearchResult searchResult : searchResults) { for (Entry<String, BucketInfo> facet : searchResult.getFacets().entrySet()) { log.debug("facet: {} {}", facet.getKey(), facet.getValue()); } for (Hit hit : searchResult.getHits().getHit()) { // if (random.nextBoolean()) { DeleteDocument docToDelete = new DeleteDocument(hit.getId()); docsToDelete.add(docToDelete); } } log.debug("" + docsToDelete.size()); log.info("delete start"); List<Future<UploadDocumentsResult>> deleteDocumentsResults = cloudSearchClient.uploadDocumentsAsync( "devtest-2", docsToDelete); for (Future<UploadDocumentsResult> deleteDocumentsResult : deleteDocumentsResults) { log.info("deleteDocumentsResult: {}", deleteDocumentsResult.get()); } } }
package org.jabref.logic.importer.fetcher; import java.util.Optional; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.BiblatexEntryTypes; import org.jabref.testutils.category.FetcherTests; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Answers; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; @Category(FetcherTests.class) public class IsbnViaEbookDeFetcherTest extends AbstractIsbnFetcherTest { @Before public void setUp() { bibEntry = new BibEntry(); bibEntry.setType(BiblatexEntryTypes.BOOK); bibEntry.setField("bibtexkey", "9780321356680"); bibEntry.setField("title", "Effective Java"); bibEntry.setField("publisher", "Addison Wesley"); bibEntry.setField("year", "2008"); bibEntry.setField("author", "Bloch, Joshua"); bibEntry.setField("date", "2008-05-08"); bibEntry.setField("ean", "9780321356680"); bibEntry.setField("isbn", "0321356683"); bibEntry.setField("pagetotal", "384"); bibEntry.setField("url", "http: fetcher = new IsbnViaEbookDeFetcher(mock(ImportFormatPreferences.class, Answers.RETURNS_DEEP_STUBS)); } @Test @Override public void testName() { assertEquals("ISBN (ebook.de)", fetcher.getName()); } @Test @Override public void testHelpPage() { assertEquals("ISBNtoBibTeX", fetcher.getHelpPage().getPageName()); } @Test @Override public void searchByIdSuccessfulWithShortISBN() throws FetcherException { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("0321356683"); assertEquals(Optional.of(bibEntry), fetchedEntry); } @Test @Override public void authorsAreCorrectlyFormatted() throws Exception { BibEntry bibEntry = new BibEntry(); bibEntry.setType(BiblatexEntryTypes.BOOK); bibEntry.setField("bibtexkey", "9783642434730"); bibEntry.setField("title", "Fundamentals of Business Process Management"); bibEntry.setField("publisher", "Springer"); bibEntry.setField("year", "2015"); bibEntry.setField("author", "Dumas, Marlon and Rosa, Marcello La and Mendling, Jan and Reijers, Hajo A."); bibEntry.setField("date", "2015-04-12"); bibEntry.setField("ean", "9783642434730"); bibEntry.setField("isbn", "3642434738"); bibEntry.setField("pagetotal", "428"); bibEntry.setField("url", "http: Optional<BibEntry> fetchedEntry = fetcher.performSearchById("3642434738"); assertEquals(Optional.of(bibEntry), fetchedEntry); } @Test public void searchForValidButNotFoundISBN() throws Exception { Optional<BibEntry> fetchedEntry = fetcher.performSearchById("3728128155"); assertEquals(Optional.empty(), fetchedEntry); } }
package org.tendiwa.maven.gitversioninsert; import io.takari.maven.testing.TestMavenRuntime; import io.takari.maven.testing.TestResources; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; /** * @author Georgy Vlasov (suseika@tendiwa.org) * @version $stub$ * @since 0.1 */ public final class GitVersionInsertMojoTest { public static final String PATH_TO_EXTRACTED_PROJECT = "target/extracted-test-resources/fake-maven-git"; @Rule public final TestResources resources = new TestResources( "target/extracted-test-resources/", "target/test-projects/" ); @Rule public final TestMavenRuntime maven = new TestMavenRuntime(); /** * Can replaces a token in each file with that file's last version tag name. */ @Test public void replacesToken() throws Exception { File basedir = this.resources.getBasedir("fake-maven-git"); this.maven.executeMojo( basedir, "insert-version" ); MatcherAssert.assertThat( this.fileToString( basedir.toPath().resolve( "src/main/java/org/tendiwa/fake/App.java" ) ), Matchers.containsString("@version 0.1") ); MatcherAssert.assertThat( this.fileToString( basedir.toPath().resolve( "src/test/java/org/tendiwa/fake/AppTest.java" ) ), Matchers.containsString("@version 0.2") ); } /** * Any token to replace can be set. */ @Ignore @Test public void canConfigureToken() throws Exception { File basedir = this.resources.getBasedir( GitVersionInsertMojoTest.PATH_TO_EXTRACTED_PROJECT ); this.maven.executeMojo( basedir, "insert-version", TestMavenRuntime.newParameter( "token", "App" ) ); MatcherAssert.assertThat( this.fileToString( basedir.toPath().resolve( "/src/main/java/org/tendiwa/fake/App.java" ) ), Matchers.containsString("class 0.1") ); MatcherAssert.assertThat( this.fileToString( basedir.toPath().resolve( "/src/test/java/org/tendiwa/fake/AppTest.java" ) ), Matchers.containsString("class 0.2") ); } /** * Reads a UTF-8 file into a string. * @param path Path to a file. * @return String with file's content. */ private String fileToString(Path path) throws IOException { return new String(Files.readAllBytes(path)); } }
package org.opens.tanaguru.service; import org.opens.tanaguru.entity.audit.Audit; import org.opens.tanaguru.entity.audit.AuditStatus; import org.opens.tanaguru.entity.audit.Content; import org.opens.tanaguru.entity.audit.ProcessResult; import org.opens.tanaguru.entity.reference.Test; import org.opens.tanaguru.entity.subject.Page; import org.opens.tanaguru.entity.subject.Site; import org.opens.tanaguru.entity.service.audit.AuditDataService; import org.opens.tanaguru.entity.service.subject.WebResourceDataService; import java.util.List; import org.apache.log4j.Logger; import org.opens.tanaguru.entity.audit.SSP; import org.opens.tanaguru.entity.service.audit.ProcessResultDataService; import org.opens.tanaguru.entity.service.reference.TestDataService; /** * * @author ADEX */ public class AuditServiceImpl implements AuditService { private AnalyserService analyserService; private AuditDataService auditDataService; private ConsolidatorService consolidatorService; private ContentAdapterService contentAdapterService; private ContentLoaderService contentLoaderService; private CrawlerService crawlerService; private ProcessorService processorService; private ProcessResultDataService processResultDataService; private TestDataService testDataService; private WebResourceDataService webResourceDataService; public AuditServiceImpl() { super(); } public Audit auditPage(String pageUrl, String[] testCodeList) { Page page = webResourceDataService.createPage(pageUrl); List<Test> testList = testDataService.findAllByCode(testCodeList); Audit audit = auditDataService.create(); audit.setSubject(page); audit.setTestList(testList); audit.setStatus(AuditStatus.CONTENT_LOADING); audit = audit(audit); return audit; } public Audit auditSite(String siteUrl, String[] testCodeList) { Site site = webResourceDataService.createSite(siteUrl); List<Test> testList = testDataService.findAllByCode(testCodeList); Audit audit = auditDataService.create(); audit.setSubject(site); audit.setTestList(testList); audit.setStatus(AuditStatus.CRAWLING); audit = audit(audit); return audit; } public Audit auditSite(String siteUrl, String[] pageUrlList, String[] testCodeList) { Site site = webResourceDataService.createSite(siteUrl); for (String pageUrl : pageUrlList) { site.addChild(webResourceDataService.createPage(pageUrl)); } List<Test> testList = testDataService.findAllByCode(testCodeList); Audit audit = auditDataService.create(); audit.setSubject(site); audit.setTestList(testList); audit.setStatus(AuditStatus.CONTENT_LOADING); audit = audit(audit); return audit; } public Audit audit(Audit audit) { audit = init(audit); if (audit.getSubject() instanceof Site) { audit = crawl(audit); } audit = loadContent(audit); audit = adaptContent(audit); audit = process(audit); audit = consolidate(audit); audit = analyse(audit); return audit; } public Audit init(Audit audit) { if (audit.getSubject() == null || audit.getTestList().isEmpty()) { Logger.getLogger(AuditServiceImpl.class).warn("Audit is not well initialized"); return audit; } if (audit.getStatus().equals(AuditStatus.INITIALISATION)) { audit.setStatus(AuditStatus.CRAWLING); auditDataService.saveOrUpdate(audit); } return audit; } public Audit crawl(Audit audit) { if (!audit.getStatus().equals(AuditStatus.CRAWLING)) { Logger.getLogger(AuditServiceImpl.class).warn( "Audit status is " + audit.getStatus() + " while " + AuditStatus.CRAWLING + " was required"); return audit; } if (audit.getSubject() instanceof Site) { crawlerService.crawl((Site) audit.getSubject()); } audit.setStatus(AuditStatus.CONTENT_LOADING); audit = auditDataService.saveOrUpdate(audit); return audit; } public Audit loadContent(Audit audit) { if (!audit.getStatus().equals(AuditStatus.CONTENT_LOADING)) { Logger.getLogger(AuditServiceImpl.class).warn( "Audit status is " + audit.getStatus() + " while " + AuditStatus.CONTENT_LOADING + " was required"); return audit; } audit.addAllContent(contentLoaderService.loadContent(audit.getSubject())); boolean hasContent = false; for (Content content : audit.getContentList()) { if (content instanceof SSP) { //We check that some content has been downloaded and has to //be adapted. For the moment we ignore the returned error code @TODO if (!((SSP)content).getSource().isEmpty()) { hasContent = true; break; } } } if (hasContent) { audit.setStatus(AuditStatus.CONTENT_ADAPTING); } else { Logger.getLogger(AuditServiceImpl.class).warn("Audit has no content"); audit.setStatus(AuditStatus.ERROR); } audit = auditDataService.saveOrUpdate(audit); return audit; } public Audit adaptContent(Audit audit) { if (!audit.getStatus().equals(AuditStatus.CONTENT_ADAPTING)) { Logger.getLogger(AuditServiceImpl.class).warn( "Audit status is " + audit.getStatus() + " while " + AuditStatus.CONTENT_ADAPTING + " was required"); return audit; } audit.setContentList(contentAdapterService.adaptContent((List<Content>) audit.getContentList())); boolean hasCorrectedDOM = false; for (Content content : audit.getContentList()) { if (content instanceof SSP) { if (!((SSP) content).getDOM().isEmpty()) { hasCorrectedDOM = true; break; } } } if (hasCorrectedDOM) { audit.setStatus(AuditStatus.PROCESSING); } else { Logger.getLogger(AuditServiceImpl.class).warn("Audit has no corrected DOM"); audit.setStatus(AuditStatus.ERROR); } audit = auditDataService.saveOrUpdate(audit); return audit; } public Audit process(Audit audit) { if (!audit.getStatus().equals(AuditStatus.PROCESSING)) { Logger.getLogger(AuditServiceImpl.class).warn( "Audit status is " + audit.getStatus() + " while " + AuditStatus.PROCESSING + " was required"); return audit; } audit.setGrossResultList(processorService.process((List<Content>) audit.getContentList(), (List<Test>) audit.getTestList())); if (!audit.getGrossResultList().isEmpty()) { audit.setStatus(AuditStatus.CONSOLIDATION); } else { Logger.getLogger(AuditServiceImpl.class).warn("Audit has no gross result"); audit.setStatus(AuditStatus.ERROR); } audit = auditDataService.saveOrUpdate(audit); return audit; } public Audit consolidate(Audit audit) { if (!audit.getStatus().equals(AuditStatus.CONSOLIDATION)) { Logger.getLogger(AuditServiceImpl.class).warn( "Audit status is " + audit.getStatus() + " while " + AuditStatus.CONSOLIDATION + " was required"); return audit; } // XXX Chargement explicite des resultats bruts, pour forcer le lazy loading // for (ProcessResult grossResult : audit.getGrossResultList()) { List<ProcessResult> netResultList = consolidatorService.consolidate( (List<ProcessResult>) audit.getGrossResultList(), (List<Test>) audit.getTestList()); audit.setNetResultList(netResultList); if (!audit.getNetResultList().isEmpty()) { for (ProcessResult netResult : audit.getNetResultList()) { processResultDataService.saveOrUpdate(netResult); } audit.setStatus(AuditStatus.ANALYSIS); } else { Logger.getLogger(AuditServiceImpl.class).warn("Audit has no net result"); audit.setStatus(AuditStatus.ERROR); } audit = auditDataService.saveOrUpdate(audit); return audit; } public Audit analyse(Audit audit) { if (!audit.getStatus().equals(AuditStatus.ANALYSIS)) { Logger.getLogger(AuditServiceImpl.class).warn( "Audit status is " + audit.getStatus() + " while " + AuditStatus.ANALYSIS + " was required"); return audit; } audit.setMark(analyserService.analyse((List<ProcessResult>) audit.getNetResultList())); audit.setStatus(AuditStatus.COMPLETED); audit = auditDataService.saveOrUpdate(audit); return audit; } public void setAnalyserService(AnalyserService analyserService) { this.analyserService = analyserService; } public void setAuditDataService(AuditDataService auditDataService) { this.auditDataService = auditDataService; } public void setConsolidatorService(ConsolidatorService consolidatorService) { this.consolidatorService = consolidatorService; } public void setContentAdapterService( ContentAdapterService contentAdapterService) { this.contentAdapterService = contentAdapterService; } public void setContentLoaderService( ContentLoaderService contentLoaderService) { this.contentLoaderService = contentLoaderService; } public void setCrawlerService(CrawlerService crawlerService) { this.crawlerService = crawlerService; } public void setProcessorService(ProcessorService processorService) { this.processorService = processorService; } public void setProcessResultDataService( ProcessResultDataService processResultDataService) { this.processResultDataService = processResultDataService; } public void setTestDataService(TestDataService testDataService) { this.testDataService = testDataService; } public void setWebResourceDataService( WebResourceDataService webResourceDAOService) { this.webResourceDataService = webResourceDAOService; } }
package net.fortuna.ical4j; import java.io.Console; import java.util.regex.Pattern; import java.util.regex.Matcher; public class RegexTestHarness { public static void main(String[] args){ Console console = System.console(); if (console == null) { System.err.println("No console."); System.exit(1); } while (true) { Pattern pattern = Pattern.compile(console.readLine("%nEnter your regex: ", new Object[] {})); Matcher matcher = pattern.matcher(console.readLine("Enter input string to search: ", new Object[] {})); boolean found = false; while (matcher.find()) { console.format("I found the text \"%s\" starting at " + "index %d and ending at index %d.%n", new Object[] {matcher.group(), new Integer(matcher.start()), new Integer(matcher.end())}); found = true; } if(!found){ console.format("No match found.%n", new Object[] {}); } } } }
package edu.northwestern.bioinformatics.studycalendar.domain; import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao; /** * @author Rhett Sutphin */ public class TestObject extends AbstractDomainObject { public TestObject() { } public TestObject(int id) { setId(id); } public static class MockableDao extends StudyCalendarDao<TestObject> { public Class<TestObject> domainClass() { return TestObject.class; } } }
package org.exist.xquery.xqts; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import junit.framework.Assert; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DefaultLogger; import org.apache.tools.ant.Project; import org.apache.tools.ant.ProjectHelper; import org.exist.dom.ElementImpl; import org.exist.dom.NodeListImpl; import org.exist.security.xacml.AccessContext; import org.exist.source.FileSource; import org.exist.storage.DBBroker; import org.exist.w3c.tests.TestCase; import org.exist.xmldb.XQueryService; import org.exist.xquery.CompiledXQuery; import org.exist.xquery.XPathException; import org.exist.xquery.XQuery; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.DateTimeValue; import org.exist.xquery.value.Sequence; import org.w3c.dom.Attr; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xmldb.api.DatabaseManager; import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.XMLResource; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * */ public class XQTS_case extends TestCase { protected static final String XQTS_folder = "test/external/XQTS_1_0_3/"; private static Map<String, String> sources = null; private static Map<String, String> moduleSources = null; @Override public void loadTS() throws Exception { testCollection = DatabaseManager.getCollection("xmldb:exist:///db/XQTS", "admin", ""); if (testCollection == null) { File buildFile = new File("webapp/xqts/build.xml"); Project p = new Project(); p.setUserProperty("ant.file", buildFile.getAbsolutePath()); p.setUserProperty("config.basedir", "../../"+XQTS_folder); DefaultLogger consoleLogger = new DefaultLogger(); consoleLogger.setErrorPrintStream(System.err); consoleLogger.setOutputPrintStream(System.out); consoleLogger.setMessageOutputLevel(Project.MSG_INFO); p.addBuildListener(consoleLogger); try { p.fireBuildStarted(); p.init(); ProjectHelper helper = ProjectHelper.getProjectHelper(); p.addReference("ant.projectHelper", helper); helper.parse(p, buildFile); p.executeTarget("store"); p.fireBuildFinished(null); Thread.sleep(60 * 1000); } catch (BuildException e) { p.fireBuildFinished(e); } catch (InterruptedException e) { } } testCollection = DatabaseManager.getCollection("xmldb:exist:///db/XQTS", "admin", ""); if (testCollection == null) throw new Exception("XQTS collection wasn't found"); if (sources == null) { sources = new HashMap<String, String>(); XQueryService service = (XQueryService) testCollection.getService("XQueryService", "1.0"); String query = "declare namespace catalog=\"http: "let $XQTSCatalog := xmldb:document('/db/XQTS/XQTSCatalog.xml') "+ "return $XQTSCatalog//catalog:sources//catalog:source"; ResourceSet results = service.query(query); for (int i = 0; i < results.getSize(); i++) { ElementImpl source = (ElementImpl) ((XMLResource) results.getResource(i)).getContentAsDOM(); sources.put(source.getAttribute("ID"), XQTS_folder + source.getAttribute("FileName")); } } if (moduleSources == null) { moduleSources = new HashMap<String, String>(); XQueryService service = (XQueryService) testCollection.getService("XQueryService", "1.0"); String query = "declare namespace catalog=\"http: "let $XQTSCatalog := xmldb:document('/db/XQTS/XQTSCatalog.xml') "+ "return $XQTSCatalog//catalog:sources//catalog:module"; ResourceSet results = service.query(query); for (int i = 0; i < results.getSize(); i++) { ElementImpl source = (ElementImpl) ((XMLResource) results.getResource(i)).getContentAsDOM(); moduleSources.put(source.getAttribute("ID"), "test/external/XQTS_1_0_3/"+source.getAttribute("FileName")+".xq"); } } } protected void groupCase(String testGroup, String testCase) { //ignore tests // if (testGroup.equals("FunctionCallExpr") && testCase.equals("K-FunctionCallExpr-11")) // return; // else if (testGroup.equals("SeqCollectionFunc")) { // if (testCase.equals("fn-collection-4d") // || testCase.equals("fn-collection-5d") // || testCase.equals("fn-collection-9") // || testCase.equals("fn-collection-10d")) // return; // if (testCase.equals("K2-NodeTest-11")) // return; //Added by p.b. as a quick attempt to work around current blocking code // if (testCase.equals("Constr-cont-document-3")) // return; //Added by p.b. as a quick attempt to work around current blocking code try { XQueryService service = (XQueryService) testCollection.getService( "XQueryService", "1.0"); String query = "declare namespace catalog=\"http: "let $XQTSCatalog := xmldb:document('/db/XQTS/XQTSCatalog.xml')\n"+ "let $tc := $XQTSCatalog/catalog:test-suite//catalog:test-group[@name eq \""+testGroup+"\"]/catalog:test-case[@name eq \""+testCase+"\"]\n"+ "return $tc"; ResourceSet results = service.query(query); Assert.assertFalse("", results.getSize() != 1); ElementImpl TC = (ElementImpl) ((XMLResource) results.getResource(0)).getContentAsDOM(); //collect test case information String folder = ""; String scenario = ""; String script = ""; //DateTimeValue scriptDateTime = null; NodeListImpl inputFiles = new NodeListImpl(); NodeListImpl outputFiles = new NodeListImpl(); ElementImpl contextItem = null; NodeListImpl modules = new NodeListImpl(); String expectedError = ""; String name = null; NodeList childNodes = TC.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); switch (child.getNodeType()) { case Node.ATTRIBUTE_NODE: name = ((Attr)child).getName(); if (name.equals("FilePath")) folder = ((Attr)child).getValue(); else if (name.equals("scenario")) scenario = ((Attr)child).getValue(); break; case Node.ELEMENT_NODE: name = ((ElementImpl) child).getLocalName(); if (name.equals("query")) { ElementImpl el = ((ElementImpl) child); script = el.getAttribute("name"); //scriptDateTime = new DateTimeValue(el.getAttribute("date")); } else if (name.equals("input-file")) inputFiles.add(child); else if (name.equals("output-file")) outputFiles.add(child); else if (name.equals("contextItem")) contextItem = (ElementImpl)child; else if (name.equals("module")) modules.add(child); else if (name.equals("expected-error")) expectedError = ((ElementImpl) child).getNodeValue(); break; default : ; } } DBBroker broker = null; //compile & evaluate File caseScript = new File(XQTS_folder+"Queries/XQuery/"+folder, script+".xq"); try { XQueryContext context; XQuery xquery; broker = pool.get(pool.getSecurityManager().getSystemSubject()); xquery = broker.getXQueryService(); broker.getConfiguration().setProperty( XQueryContext.PROPERTY_XQUERY_RAISE_ERROR_ON_FAILED_RETRIEVAL, true); context = xquery.newContext(AccessContext.TEST); //map modules' namespaces to location Map<String, String> moduleMap = (Map<String, String>)broker.getConfiguration().getProperty(XQueryContext.PROPERTY_STATIC_MODULE_MAP); for (int i = 0; i < modules.getLength(); i++) { ElementImpl module = (ElementImpl)modules.item(i); String id = module.getNodeValue(); moduleMap.put(module.getAttribute("namespace"), moduleSources.get(id)); } broker.getConfiguration().setProperty(XQueryContext.PROPERTY_STATIC_MODULE_MAP, moduleMap); //declare variable for (int i = 0; i < inputFiles.getLength(); i++) { ElementImpl inputFile = (ElementImpl)inputFiles.item(i); String id = inputFile.getNodeValue(); //use DocUtils //context.declareVariable( //inputFile.getAttribute("variable"), //DocUtils.getDocument(context, sources.get(id)) //in-memory nodes context.declareVariable(inputFile.getAttribute("variable"), loadVarFromURI(context, sources.get(id))); } Sequence contextSequence = null; //set context item if (contextItem != null) { String id = contextItem.getNodeValue(); contextSequence = loadVarFromURI(context, sources.get(id)); } fixBrokenTests(context, testGroup, testCase); //compile CompiledXQuery compiled = xquery.compile(context, new FileSource(caseScript, "UTF8", true)); //execute Sequence result = xquery.execute(compiled, contextSequence); //compare result with one provided by test case boolean ok = false; for (int i = 0; i < outputFiles.getLength(); i++) { ElementImpl outputFile = (ElementImpl)outputFiles.item(i); if (compareResult(script, "XQTS_1_0_3/ExpectedTestResults/"+folder, outputFile, result)) { ok = true; break; } } //collect information if result is wrong if (!ok) { StringBuilder message = new StringBuilder(); StringBuffer exp = new StringBuffer(); try { for (int i = 0; i < outputFiles.getLength(); i++) { ElementImpl outputFile = (ElementImpl)outputFiles.item(i); if (outputFile.getAttribute("compare").equalsIgnoreCase("IGNORE")) continue; File expectedResult = new File(XQTS_folder+"ExpectedTestResults/"+folder, outputFile.getNodeValue()); if (!expectedResult.canRead()) Assert.fail("can't read expected result"); //avoid to big output if (expectedResult.length() >= 1024) { exp = new StringBuffer(); exp.append("{TOO BIG}"); break; } else { exp.append("{'"); Reader reader = new BufferedReader(new FileReader(expectedResult)); char ch; while (reader.ready()) { ch = (char)reader.read(); if (ch == '\r') ch = (char)reader.read(); exp.append(String.valueOf(ch)); } exp.append("'}"); } } } catch (Exception e) { exp.append(e.getMessage()); } String res = sequenceToString(result); if (exp.length() == 0) exp.append("error "+ expectedError); StringBuilder data = new StringBuilder(); for (int i = 0; i < inputFiles.getLength(); i++) { ElementImpl inputFile = (ElementImpl)inputFiles.item(i); String id = inputFile.getNodeValue(); data.append(inputFile.getAttribute("variable")); data.append(" = \n"); data.append(readFileAsString(new File(sources.get(id)), 1024)); data.append("\n"); } message.append("\n"); message.append("expected "); message.append("[" + exp + "]"); message.append(" got "); message.append("[" + res + "]\n"); message.append("script:\n"); message.append(readFileAsString(caseScript)); message.append("\n"); message.append("data:\n"); message.append(data); Assert.fail(message.toString()); } } catch (XPathException e) { // String error = e.getMessage(); if (!expectedError.isEmpty()) ; else if (expectedError.equals("*")) ; //TODO:check e.getCode() // else if (error.indexOf(expectedError) != -1) // else { // if (error.startsWith("err:")) error = error.substring(4); // if (error.indexOf(expectedError) == -1) // Assert.fail("expected error is "+expectedError+", got "+error+" ["+e.getMessage()+"]"); } catch (Exception e) { if (e instanceof XMLDBException) { if (e.getMessage().contains("SENR0001")) { if (!expectedError.isEmpty()) return; } } e.printStackTrace(); StringBuilder message = new StringBuilder(); message.append(e.toString()); message.append("\n during script evaluation:\n"); try { message.append(readFileAsString(caseScript)); } catch (IOException e1) { message.append("ERROR - "+e1.getMessage()); } Assert.fail(message.toString()); } finally { pool.release(broker); } } catch (XMLDBException e) { Assert.fail(e.toString()); } } private void fixBrokenTests(XQueryContext context, String group, String test) { try { if (group.equals("ContextImplicitTimezoneFunc")) { TimeZone implicitTimeZone = TimeZone.getTimeZone("GMT-5:00");// getDefault(); //if( implicitTimeZone.inDaylightTime( new Date() ) ) { //implicitTimeZone.setRawOffset( implicitTimeZone.getRawOffset() + implicitTimeZone.getDSTSavings() ); context.setTimeZone(implicitTimeZone); } else if (group.equals("ContextCurrentDatetimeFunc") || group.equals("ContextCurrentDateFunc") || group.equals("ContextCurrentTimeFunc")) { DateTimeValue dt = null; if (test.equals("fn-current-time-4")) dt = new DateTimeValue("2005-12-05T13:38:03.455-05:00"); else if (test.equals("fn-current-time-6")) dt = new DateTimeValue("2005-12-05T13:38:18.059-05:00"); else if (test.equals("fn-current-time-7")) dt = new DateTimeValue("2005-12-05T13:38:18.059-05:00"); else if (test.equals("fn-current-time-10")) dt = new DateTimeValue("2005-12-05T13:38:18.09-05:00"); else if (test.startsWith("fn-current-time-")) dt = new DateTimeValue("2005-12-05T10:15:03.408-05:00"); else if (test.equals("fn-current-dateTime-6")) dt = new DateTimeValue("2005-12-05T17:10:00.312-05:00"); else if (test.equals("fn-current-datetime-7")) dt = new DateTimeValue("2005-12-05T17:10:00.312-05:00"); else if (test.equals("fn-current-dateTime-10")) dt = new DateTimeValue("2005-12-05T17:10:00.344-05:00"); else if (test.equals("fn-current-dateTime-21")) dt = new DateTimeValue("2005-12-05T17:10:00.453-05:00"); else if (test.equals("fn-current-dateTime-24")) dt = new DateTimeValue("2005-12-05T17:10:00.469-05:00"); else dt = new DateTimeValue("2005-12-05T17:10:00.203-05:00"); //if (dt != null) context.setCalendar(dt.calendar); } } catch (XPathException e) { } } }