private void intializeMetadataPages() {
   metadataWizardPages =
       new MetadataWizardPageGroup(
           getMetadataWizardPageFactory(),
           getLocations(),
           CONSTANTS.runWizardType(),
           CONSTANTS.runWizardBatchType());
 }
    ProteomicsRunWizardCommand(final Collection<TreeItem> locations) {
      super(locations);
      final ArrayList<WizardPage> pages = Lists.newArrayListWithCapacity(8);
      intializeMetadataPages();
      pages.add(sourcePage);
      pages.addAll(metadataWizardPages.asList());

      final ServiceSelectionComponent<QueueGridService> thermoSelectionComponent =
          serviceSelectionComponentSupplier.get();
      thermoSelectionComponent.setServicesType("rawExtract");
      thermoServicesSelectionPage =
          new ServiceWizardPageImpl<QueueGridService>(thermoSelectionComponent);

      final ServiceSelectionComponent<QueueGridService> proteomicsConvertSelectionComponent =
          serviceSelectionComponentSupplier.get();
      proteomicsConvertSelectionComponent.setServicesType("proteomicsConvert");
      proteomicsConvertServicesSelectionPage =
          new ServiceWizardPageImpl<QueueGridService>(proteomicsConvertSelectionComponent);

      pages.add(thermoServicesSelectionPage);
      pages.add(proteomicsConvertServicesSelectionPage);
      pages.add(uploadWizardPage);
      final WizardOptions options = new WizardOptions();
      options.setTitle(CONSTANTS.runWizardTitle());
      setupSourceTypeListeners();
      updateSourceType();
      setWidget(
          WizardFactoryImpl.getInstance()
              .getWizard(
                  pages,
                  options,
                  new WizardCompletionHandler() {
                    public void onCompletion(final Window wizard) {
                      uploadComponent.startUpload();
                    }
                  }));
    }
    private void init(final ListGridRecord sampleRecord, final boolean add) {
      final Form form = new Form(nameItem, mudpitItem, categoryItem);
      form.setWrapItemTitles(false);
      nameItem.setValue(sampleRecord.getAttributeAsString("Name"));
      nameItem.addChangedHandler(
          new ChangedHandler() {
            public void onChanged(final ChangedEvent event) {
              checkOk();
            }
          });
      mudpitItem.setValue(sampleRecord.getAttributeAsBoolean("Mudpit"));
      categoryItem.setValue(sampleRecord.getAttributeAsString("Category"));

      final Label label = new Label(CONSTANTS.scaffoldWizardSampleSearchLabel());
      label.setWidth100();
      label.setHeight(12);

      final TreeOptions treeOptions = new TreeOptions();
      treeOptions.setInitialItems(
          locationFactory.getTropixObjectSourceRootItems(TropixObjectTreeItemExpanders.get(types)));
      treeOptions.setShowPredicate(getShowItemPredicate());
      treeOptions.setSelectionPredicate(LocationPredicates.getTropixObjectNotFolderPredicate());
      treeOptions.setSelectionType(SelectionType.MULTIPlE);
      @SuppressWarnings("unchecked")
      final Collection<TreeItem> selectedItems =
          (Collection<TreeItem>) sampleRecord.getAttributeAsObject("Selection");
      treeOptions.setExpandIds(Locations.getAncestorIds(selectedItems));
      treeOptions.setSelectedItems(selectedItems);
      final TreeComponent tree = treeComponentFactory.get(treeOptions);
      tree.addMultiSelectionListener(this);
      final TreeGrid treeGrid = tree.get();
      treeGrid.setTooltip("Hold the control key to select multiple items.");
      final VLayout layout = new VLayout();
      layout.addMember(form);
      layout.addMember(label);
      layout.addMember(treeGrid);
      layout.setSize("500px", "500px");
      okButton =
          SmartUtils.getButton(
              add ? "Add" : "Update",
              null,
              new Command() {
                public void execute() {
                  sampleRecord.setAttribute("Name", (String) nameItem.getValue());
                  sampleRecord.setAttribute("Category", (String) categoryItem.getValue());
                  sampleRecord.setAttribute("Mudpit", (Boolean) mudpitItem.getValue());
                  sampleRecord.setAttribute("Selection", selection);
                  if (add) {
                    dataSource.addData(sampleRecord);
                    records.add(sampleRecord);
                  }
                  listGrid.markForRedraw();
                  get().markForDestroy();
                  checkValid();
                }
              });
      final Button cancelButton = SmartUtils.getCancelButton(this);
      final Layout opsLayout = new CanvasWithOpsLayout<VLayout>(layout, okButton, cancelButton);
      final Window window =
          PopOutWindowBuilder.titled((add ? "Add" : "Update") + " Sample")
              .withContents(opsLayout)
              .autoSized()
              .get();
      setWidget(window);
      checkOk();
      get().draw();
    }
  protected void print(Printer out, List<EventInterface> events) throws IOException {
    out.printHeader(
        /*  0 */ MESSAGES.colName(),
        /*  1 */ MESSAGES.colSection(),
        /*  2 */ MESSAGES.colType(),
        /*  3 */ MESSAGES.colTitle(),
        /*  4 */ MESSAGES.colNote(),
        /*  5 */ MESSAGES.colDayOfWeek(),
        /*  6 */ MESSAGES.colFirstDate(),
        /*  7 */ MESSAGES.colLastDate(),
        /*  8 */ MESSAGES.colPublishedStartTime(),
        /*  9 */ MESSAGES.colPublishedEndTime(),
        /* 10 */ MESSAGES.colAllocatedStartTime(),
        /* 11 */ MESSAGES.colAllocatedEndTime(),
        /* 12 */ MESSAGES.colSetupTimeShort(),
        /* 13 */ MESSAGES.colTeardownTimeShort(),
        /* 14 */ MESSAGES.colLocation(),
        /* 15 */ MESSAGES.colCapacity(),
        /* 16 */ MESSAGES.colEnrollment(),
        /* 17 */ MESSAGES.colLimit(),
        /* 18 */ MESSAGES.colSponsorOrInstructor(),
        /* 19 */ MESSAGES.colEmail(),
        /* 20 */ MESSAGES.colMainContact(),
        /* 21 */ MESSAGES.colEmail(),
        /* 22 */ MESSAGES.colApproval(),
        /* 23 */ MESSAGES.colLastChange());

    Formats.Format<Date> df = Formats.getDateFormat(Formats.Pattern.DATE_EVENT);

    for (EventInterface event : events) {
      for (MultiMeetingInterface multi :
          EventInterface.getMultiMeetings(event.getMeetings(), false)) {
        MeetingInterface meeting = multi.getMeetings().first();
        out.printLine(
            getName(event),
            getSection(event),
            event.hasInstruction()
                ? event.getInstruction()
                : event.getType().getAbbreviation(CONSTANTS),
            getTitle(event),
            event.hasEventNote() ? event.getEventNote("\n").replace("<br>", "\n") : "",
            multi.getDays(CONSTANTS.shortDays(), CONSTANTS.shortDays(), CONSTANTS.daily()),
            multi.getFirstMeetingDate() == null ? "" : df.format(multi.getFirstMeetingDate()),
            multi.getLastMeetingDate() == null
                ? ""
                : multi.getNrMeetings() == 1 ? null : df.format(multi.getLastMeetingDate()),
            meeting.isArrangeHours() ? "" : meeting.getStartTime(CONSTANTS, true),
            meeting.isArrangeHours() ? "" : meeting.getEndTime(CONSTANTS, true),
            meeting.isArrangeHours() ? "" : meeting.getStartTime(CONSTANTS, false),
            meeting.isArrangeHours() ? "" : meeting.getEndTime(CONSTANTS, false),
            meeting.isArrangeHours() ? "" : String.valueOf(meeting.getStartOffset()),
            meeting.isArrangeHours() ? "" : String.valueOf(-meeting.getEndOffset()),
            meeting.getLocationName(),
            meeting.hasLocation() && meeting.getLocation().hasSize()
                ? meeting.getLocation().getSize().toString()
                : null,
            event.hasEnrollment() ? event.getEnrollment().toString() : null,
            event.hasMaxCapacity() ? event.getMaxCapacity().toString() : null,
            event.hasInstructors()
                ? event.getInstructorNames("\n", MESSAGES)
                : event.hasSponsor() ? event.getSponsor().getName() : null,
            event.hasInstructors()
                ? event.getInstructorEmails("\n")
                : event.hasSponsor() ? event.getSponsor().getEmail() : null,
            event.hasContact() ? event.getContact().getName(MESSAGES) : null,
            event.hasContact() ? event.getContact().getEmail() : null,
            event.getType() == EventType.Unavailabile
                ? ""
                : multi.getApprovalStatus() == ApprovalStatus.Approved
                    ? df.format(multi.getApprovalDate())
                    : multi.getApprovalStatus() == ApprovalStatus.Cancelled
                        ? MESSAGES.approvalCancelled()
                        : multi.getApprovalStatus() == ApprovalStatus.Rejected
                            ? MESSAGES.approvalRejected()
                            : multi.getApprovalStatus() == ApprovalStatus.Deleted
                                ? MESSAGES.approvalDeleted()
                                : multi.isPast()
                                    ? MESSAGES.approvalNotApprovedPast()
                                    : event.getExpirationDate() != null
                                        ? MESSAGES.approvalExpire(
                                            df.format(event.getExpirationDate()))
                                        : MESSAGES.approvalNotApproved(),
            event.getLastNote() != null
                ? df.format(event.getLastNote().getDate())
                    + " "
                    + event.getLastNote().getType().getName()
                : null);
      }
      out.flush();
    }
    out.close();
  }
  public static GwtRpcResponseList<ClassAssignmentInterface.Enrollment> convert(
      Collection<StudentClassEnrollment> enrollments,
      Map<Long, List<Meeting>> conflicts,
      boolean canShowExtId,
      boolean canRegister,
      boolean canUseAssistant) {
    GwtRpcResponseList<ClassAssignmentInterface.Enrollment> converted =
        new GwtRpcResponseList<ClassAssignmentInterface.Enrollment>();
    Map<String, String> approvedBy2name = new Hashtable<String, String>();
    Hashtable<Long, ClassAssignmentInterface.Enrollment> student2enrollment =
        new Hashtable<Long, ClassAssignmentInterface.Enrollment>();
    for (StudentClassEnrollment enrollment : enrollments) {
      ClassAssignmentInterface.Enrollment enrl =
          student2enrollment.get(enrollment.getStudent().getUniqueId());
      if (enrl == null) {
        ClassAssignmentInterface.Student st = new ClassAssignmentInterface.Student();
        st.setId(enrollment.getStudent().getUniqueId());
        st.setExternalId(enrollment.getStudent().getExternalUniqueId());
        st.setCanShowExternalId(canShowExtId);
        st.setCanRegister(canRegister);
        st.setCanUseAssistant(canUseAssistant);
        st.setName(
            enrollment
                .getStudent()
                .getName(ApplicationProperty.OnlineSchedulingStudentNameFormat.value()));
        for (AcademicAreaClassification ac :
            enrollment.getStudent().getAcademicAreaClassifications()) {
          st.addArea(ac.getAcademicArea().getAcademicAreaAbbreviation());
          st.addClassification(ac.getAcademicClassification().getCode());
        }
        for (PosMajor m : enrollment.getStudent().getPosMajors()) {
          st.addMajor(m.getCode());
        }
        for (StudentGroup g : enrollment.getStudent().getGroups()) {
          st.addGroup(g.getGroupAbbreviation());
        }
        for (StudentAccomodation a : enrollment.getStudent().getAccomodations()) {
          st.addAccommodation(a.getAbbreviation());
        }
        enrl = new ClassAssignmentInterface.Enrollment();
        enrl.setStudent(st);
        enrl.setEnrolledDate(enrollment.getTimestamp());
        CourseAssignment c = new CourseAssignment();
        c.setCourseId(enrollment.getCourseOffering().getUniqueId());
        c.setSubject(enrollment.getCourseOffering().getSubjectAreaAbbv());
        c.setCourseNbr(enrollment.getCourseOffering().getCourseNbr());
        enrl.setCourse(c);
        student2enrollment.put(enrollment.getStudent().getUniqueId(), enrl);
        if (enrollment.getCourseRequest() != null) {
          enrl.setPriority(1 + enrollment.getCourseRequest().getCourseDemand().getPriority());
          if (enrollment.getCourseRequest().getCourseDemand().getCourseRequests().size() > 1) {
            CourseRequest first = null;
            for (CourseRequest r :
                enrollment.getCourseRequest().getCourseDemand().getCourseRequests()) {
              if (first == null || r.getOrder().compareTo(first.getOrder()) < 0) first = r;
            }
            if (!first.equals(enrollment.getCourseRequest()))
              enrl.setAlternative(first.getCourseOffering().getCourseName());
          }
          if (enrollment.getCourseRequest().getCourseDemand().isAlternative()) {
            CourseDemand first = enrollment.getCourseRequest().getCourseDemand();
            demands:
            for (CourseDemand cd : enrollment.getStudent().getCourseDemands()) {
              if (!cd.isAlternative()
                  && cd.getPriority().compareTo(first.getPriority()) < 0
                  && !cd.getCourseRequests().isEmpty()) {
                for (CourseRequest cr : cd.getCourseRequests())
                  if (cr.getClassEnrollments().isEmpty()) continue demands;
                first = cd;
              }
            }
            CourseRequest alt = null;
            for (CourseRequest r : first.getCourseRequests()) {
              if (alt == null || r.getOrder().compareTo(alt.getOrder()) < 0) alt = r;
            }
            enrl.setAlternative(alt.getCourseOffering().getCourseName());
          }
          enrl.setRequestedDate(enrollment.getCourseRequest().getCourseDemand().getTimestamp());
          enrl.setApprovedDate(enrollment.getApprovedDate());
          if (enrollment.getApprovedBy() != null) {
            String name = approvedBy2name.get(enrollment.getApprovedBy());
            if (name == null) {
              TimetableManager mgr =
                  (TimetableManager)
                      EventDAO.getInstance()
                          .getSession()
                          .createQuery("from TimetableManager where externalUniqueId = :externalId")
                          .setString("externalId", enrollment.getApprovedBy())
                          .setMaxResults(1)
                          .uniqueResult();
              if (mgr != null) {
                name = mgr.getName();
              } else {
                DepartmentalInstructor instr =
                    (DepartmentalInstructor)
                        EventDAO.getInstance()
                            .getSession()
                            .createQuery(
                                "from DepartmentalInstructor where externalUniqueId = :externalId and department.session.uniqueId = :sessionId")
                            .setString("externalId", enrollment.getApprovedBy())
                            .setLong(
                                "sessionId", enrollment.getStudent().getSession().getUniqueId())
                            .setMaxResults(1)
                            .uniqueResult();
                if (instr != null) name = instr.nameLastNameFirst();
              }
              if (name != null) approvedBy2name.put(enrollment.getApprovedBy(), name);
            }
            enrl.setApprovedBy(name == null ? enrollment.getApprovedBy() : name);
          }
        } else {
          enrl.setPriority(-1);
        }

        List<Meeting> conf =
            (conflicts == null ? null : conflicts.get(enrollment.getStudent().getUniqueId()));
        if (conf != null) {
          Map<Event, TreeSet<Meeting>> events = new HashMap<Event, TreeSet<Meeting>>();
          for (Meeting m : conf) {
            TreeSet<Meeting> ms = events.get(m.getEvent());
            if (ms == null) {
              ms = new TreeSet<Meeting>();
              events.put(m.getEvent(), ms);
            }
            ms.add(m);
          }
          for (Event confEvent : new TreeSet<Event>(events.keySet())) {
            Conflict conflict = new Conflict();
            conflict.setName(confEvent.getEventName());
            conflict.setType(confEvent.getEventTypeAbbv());
            String lastDate = null, lastTime = null, lastRoom = null;
            for (MultiMeeting mm : Event.getMultiMeetings(events.get(confEvent))) {
              String date =
                  getDateFormat().format(mm.getMeetings().first().getMeetingDate())
                      + (mm.getMeetings().size() == 1
                          ? ""
                          : " - "
                              + getDateFormat().format(mm.getMeetings().last().getMeetingDate()));
              if (lastDate == null) {
                conflict.setDate(date);
              } else if (lastDate.equals(date)) {
                conflict.setDate(conflict.getDate() + "<br>");
              } else {
                conflict.setDate(conflict.getDate() + "<br>" + date);
              }
              lastDate = date;

              String time =
                  mm.getDays(CONSTANTS.days(), CONSTANTS.shortDays())
                      + " "
                      + (mm.getMeetings().first().isAllDay()
                          ? "All Day"
                          : mm.getMeetings().first().startTime()
                              + " - "
                              + mm.getMeetings().first().stopTime());
              if (lastTime == null) {
                conflict.setTime(time);
              } else if (lastTime.equals(time)) {
                conflict.setTime(conflict.getTime() + "<br>");
              } else {
                conflict.setTime(conflict.getTime() + "<br>" + time);
              }
              lastTime = time;

              String room =
                  (mm.getMeetings().first().getLocation() == null
                      ? ""
                      : mm.getMeetings().first().getLocation().getLabel());
              if (lastRoom == null) {
                conflict.setRoom(room);
              } else if (lastRoom.equals(room)) {
                conflict.setRoom(conflict.getRoom() + "<br>");
              } else {
                conflict.setRoom(conflict.getRoom() + "<br>" + room);
              }
              lastRoom = room;
            }
            enrl.addConflict(conflict);
          }
        }

        converted.add(enrl);
      }
      ClassAssignmentInterface.ClassAssignment c = enrl.getCourse().addClassAssignment();
      c.setClassId(enrollment.getClazz().getUniqueId());
      c.setSection(enrollment.getClazz().getClassSuffix(enrollment.getCourseOffering()));
      if (c.getSection() == null) c.setSection(enrollment.getClazz().getSectionNumberString());
      c.setClassNumber(enrollment.getClazz().getSectionNumberString());
      c.setSubpart(enrollment.getClazz().getSchedulingSubpart().getItypeDesc());
    }
    return converted;
  }
  private class ProteomicsRunWizardCommand extends WizardCommand {
    private MetadataWizardPageGroup metadataWizardPages;

    private final ServiceWizardPageImpl<QueueGridService> thermoServicesSelectionPage;
    private final ServiceWizardPageImpl<QueueGridService> proteomicsConvertServicesSelectionPage;

    private final UploadComponentOptions uploadOpts =
        new UploadComponentOptions(
            true,
            new AsyncCallbackImpl<List<FileSource>>() {
              @Override
              public void handleSuccess() {
                try {
                  final PeakListWorkflowBuilder builder = new PeakListWorkflowBuilder(CONSTANTS);
                  builder.setFileSources(getResult());
                  builder.setCommonMetadataProvider(
                      metadataWizardPages.getEnabledWizardPage().getMetadataCanvasSupplier());
                  builder.setSourcePage(sourcePage);
                  builder.setThermoServicesSelectionPage(thermoServicesSelectionPage);
                  builder.setProteomicsConvertServicesSelectionPage(
                      proteomicsConvertServicesSelectionPage);
                  JobSubmitService.Util.getInstance()
                      .submit(builder.build(), new AsyncCallbackImpl<Void>());
                } finally {
                  destroy();
                }
              }
            });

    private final DynamicUploadComponent uploadComponent = uploadComponentFactory.get(uploadOpts);
    private UploadWizardPageImpl uploadWizardPage =
        new UploadWizardPageImpl(
            uploadComponent,
            CONSTANTS.runWizardSourceTitle(),
            CONSTANTS.runWizardSourceDescription());
    private final ProteomicsRunSourceTypeWizardPageImpl sourcePage =
        new ProteomicsRunSourceTypeWizardPageImpl(false);

    private void intializeMetadataPages() {
      metadataWizardPages =
          new MetadataWizardPageGroup(
              getMetadataWizardPageFactory(),
              getLocations(),
              CONSTANTS.runWizardType(),
              CONSTANTS.runWizardBatchType());
    }

    private final Listener<Object> sourceTypeListener =
        new Listener<Object>() {
          public void onEvent(final Object event) {
            updateSourceType();
          }
        };

    private void updateSourceType() {
      final ProteomicsRunSource type = sourcePage.getProteomicsRunSourceProperty().get();
      final boolean batch = sourcePage.getBatchProperty().get();
      metadataWizardPages.setBatch(batch);

      if (type == ProteomicsRunSource.THERMO) {
        uploadOpts.setTypes("*.raw;*.RAW");
        uploadOpts.setTypesDescription("Thermo Finnigan RAW");
        uploadOpts.setExtension(StockFileExtensionEnum.THERMO_RAW.getExtension());
      } else if (type == ProteomicsRunSource.MZXML) {
        uploadOpts.setTypes("*.mzXML;*.mzxml;*.MZXML;*.MzXML");
        uploadOpts.setTypesDescription("MzXML");
        uploadOpts.setExtension(null);
      } else if (type == ProteomicsRunSource.MGF) {
        uploadOpts.setTypes("*.mgf;*.MGF;*.msm;*.MSM");
        uploadOpts.setTypesDescription("Mascot Generic Format");
        uploadOpts.setExtension(null);
      }
      uploadOpts.setAllowMultiple(batch);
      uploadComponent.update(uploadOpts);

      thermoServicesSelectionPage.setEnabled(type == ProteomicsRunSource.THERMO);
      proteomicsConvertServicesSelectionPage.setEnabled(type == ProteomicsRunSource.MGF);
    }

    private void setupSourceTypeListeners() {
      sourcePage.getBatchProperty().addListener(sourceTypeListener);
      sourcePage.getProteomicsRunSourceProperty().addListener(sourceTypeListener);
    }

    ProteomicsRunWizardCommand(final Collection<TreeItem> locations) {
      super(locations);
      final ArrayList<WizardPage> pages = Lists.newArrayListWithCapacity(8);
      intializeMetadataPages();
      pages.add(sourcePage);
      pages.addAll(metadataWizardPages.asList());

      final ServiceSelectionComponent<QueueGridService> thermoSelectionComponent =
          serviceSelectionComponentSupplier.get();
      thermoSelectionComponent.setServicesType("rawExtract");
      thermoServicesSelectionPage =
          new ServiceWizardPageImpl<QueueGridService>(thermoSelectionComponent);

      final ServiceSelectionComponent<QueueGridService> proteomicsConvertSelectionComponent =
          serviceSelectionComponentSupplier.get();
      proteomicsConvertSelectionComponent.setServicesType("proteomicsConvert");
      proteomicsConvertServicesSelectionPage =
          new ServiceWizardPageImpl<QueueGridService>(proteomicsConvertSelectionComponent);

      pages.add(thermoServicesSelectionPage);
      pages.add(proteomicsConvertServicesSelectionPage);
      pages.add(uploadWizardPage);
      final WizardOptions options = new WizardOptions();
      options.setTitle(CONSTANTS.runWizardTitle());
      setupSourceTypeListeners();
      updateSourceType();
      setWidget(
          WizardFactoryImpl.getInstance()
              .getWizard(
                  pages,
                  options,
                  new WizardCompletionHandler() {
                    public void onCompletion(final Window wizard) {
                      uploadComponent.startUpload();
                    }
                  }));
    }
  }