Example usage for java.util Calendar clone

List of usage examples for java.util Calendar clone

Introduction

In this page you can find the example usage for java.util Calendar clone.

Prototype

@Override
public Object clone() 

Source Link

Document

Creates and returns a copy of this object.

Usage

From source file:org.globus.workspace.scheduler.defaults.pilot.PilotSlotManagement.java

/**
 * The pilot reports the slot has been successfully reserved and what host
 * it's ended up running on.//from w w  w.j  a v a2  s  .  c  o m
 *
 * @param slotid   uuid
 * @param hostname slot node
 * @param timestamp time of reservation
 */
public void reserved(String slotid, String hostname, Calendar timestamp) {

    if (this.schedulerAdapter == null) {
        logger.error("Severe problem, slot manager has received word " + "that the slot '" + slotid
                + "' is reserved (hostname '" + hostname + "') but the manager has "
                + "not been configured with a way to inform service " + "scheduler to proceed.");
        try {
            PilotSlot slot = this.getSlotAndAssignVM(slotid, hostname);
            // this eventually causes this.releaseSpace() to be called
            // unless there was a race
            this.cancelWorkspace(slot.vmid, SEVERE_PILOT_FAULT);
        } catch (SlotNotFoundException e) {
            logger.error(e.getMessage());
        } catch (WorkspaceDatabaseException e) {
            logger.error(e.getMessage());
        }
        return;
    }

    try {

        final PilotSlot slot = this.getSlotAndAssignVM(slotid, hostname);

        if (hostname == null) {

            logger.error("Pilot '" + slotid + "' sent reserved message "
                    + "without hostname (?). Cancelling vm #" + slot.vmid + " and running trash.");

            // this eventually causes this.releaseSpace() to be called
            // unless there was a race
            this.cancelWorkspace(slot.vmid, SEVERE_PILOT_FAULT);
            return;
        }

        if (timestamp == null) {

            logger.error("Pilot '" + slotid + "' sent reserved message "
                    + "without timestamp (?). Cancelling vm #" + slot.vmid + " and running trash.");

            // this eventually causes this.releaseSpace() to be called
            // unless there was a race
            this.cancelWorkspace(slot.vmid, SEVERE_PILOT_FAULT);
            return;
        }

        final InstanceResource resource;
        try {
            resource = this.instHome.find(slot.vmid);
        } catch (DoesNotExistException e) {
            final String msg = "workspace #" + slot.vmid + " is unknown "
                    + "to the service but the pilot tracker has receieved "
                    + "space for it to run?  pilot ID: '" + slotid + "' "
                    + "There is nothing we can do about this.";
            logger.error(e.getMessage());
            return;
        }

        final int runningTime = resource.getVM().getDeployment().getMinDuration();

        // double-checking assumptions
        if (runningTime > slot.duration - this.padding) {
            logger.error("The running time stored for workspace #" + slot.vmid
                    + " is greater than slot duration (?). " + "Implementation error, backing out.");
            this.cancelWorkspace(slot.vmid, SEVERE_PILOT_FAULT);
            return;
        }

        logger.debug("reserved: running time = " + runningTime + " (slot duration = " + slot.duration + ")");
        Calendar stop = (Calendar) timestamp.clone();
        stop.add(Calendar.SECOND, runningTime);

        Calendar slotstop = (Calendar) timestamp.clone();
        slotstop.add(Calendar.SECOND, slot.duration);

        String msg = Lager.ev(slot.vmid) + "Pilot '" + slot.uuid + "' reserved for VM " + slot.vmid
                + " @ host '" + hostname + "'.  Started at: " + localFormat.format(timestamp.getTime())
                + ".  VM " + "running time ends at: " + localFormat.format(stop.getTime()) + ".  Slot will "
                + "end itself at approximately: " + localFormat.format(slotstop.getTime());
        if (lager.eventLog) {
            logger.info(msg);
        } else {
            logger.debug(msg);
        }

        this.schedulerAdapter.slotReserved(slot.vmid, timestamp, stop, hostname);

    } catch (ManageException e) {
        if (logger.isDebugEnabled()) {
            logger.error(e.getMessage(), e);
        } else {
            logger.error(e.getMessage());
        }
    } catch (SlotNotFoundException e) {

        String msg = "Severe problem, hearing about a slot being "
                + "reserved but service has no record of it.  Slotid: " + slotid + ", hostname: " + hostname
                + " (can't qdel or " + "cancel it, we don't know the LRM handle or workspace ID)";
        logger.error(msg);
    }
}

From source file:it.govpay.core.business.Pagamento.java

/**
 * La logica prevede di cercare i pendenti per stazione nell'intervallo da >> a.
 * Se nella risposta ci sono 500+ pendenti si dimezza l'intervallo.
 * Se a forza di dimezzare l'intervallo diventa di 1 giorno ed ancora ci sono 500+ risultati, 
 * si ripete la ricerca per quel giorno sulla lista di domini. Se anche in questo caso si hanno troppi risultati, 
 * pace, non e' possibile filtrare ulteriormente. 
 * //from  w w w .  ja va2s .co  m
 * @param client
 * @param intermediario
 * @param stazione
 * @param lstDomini
 * @param perDominio
 * @param da
 * @param a
 * @return
 */
private Map<String, String> acquisisciPendenti(NodoClient client, Intermediario intermediario,
        Stazione stazione, List<Dominio> lstDomini, boolean perDominio, Calendar da, Calendar a, long soglia) {
    GpContext ctx = GpThreadLocal.get();
    Map<String, String> statiRptPendenti = new HashMap<String, String>();

    // Ciclo sui domini, ma ciclo veramente solo se perDominio == true,
    // Altrimenti ci giro una sola volta

    for (Dominio dominio : lstDomini) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        NodoChiediListaPendentiRPT richiesta = new NodoChiediListaPendentiRPT();
        richiesta.setIdentificativoIntermediarioPA(intermediario.getCodIntermediario());
        richiesta.setIdentificativoStazioneIntermediarioPA(stazione.getCodStazione());
        richiesta.setPassword(stazione.getPassword());
        richiesta.setDimensioneLista(BigInteger.valueOf(soglia));
        richiesta.setRangeA(a.getTime());
        richiesta.setRangeDa(da.getTime());

        if (perDominio) {
            richiesta.setIdentificativoDominio(dominio.getCodDominio());
            log.debug("Richiedo la lista delle RPT pendenti (Dominio " + dominio.getCodDominio() + " dal "
                    + dateFormat.format(da.getTime()) + " al " + dateFormat.format(a.getTime()) + ")");
            ctx.log("pendenti.listaPendenti", dominio.getCodDominio(), dateFormat.format(da.getTime()),
                    dateFormat.format(a.getTime()));
        } else {
            log.debug("Richiedo la lista delle RPT pendenti (Stazione " + stazione.getCodStazione() + " dal "
                    + dateFormat.format(da.getTime()) + " al " + dateFormat.format(a.getTime()) + ")");
            ctx.log("pendenti.listaPendenti", stazione.getCodStazione(), dateFormat.format(da.getTime()),
                    dateFormat.format(a.getTime()));
        }

        NodoChiediListaPendentiRPTRisposta risposta = null;
        String transactionId = null;
        try {
            transactionId = GpThreadLocal.get().openTransaction();
            GpThreadLocal.get().setupNodoClient(stazione.getCodStazione(), null,
                    Azione.nodoChiediListaPendentiRPT);
            risposta = client.nodoChiediListaPendentiRPT(richiesta, intermediario.getDenominazione());
        } catch (Exception e) {
            log.warn("Errore durante la richiesta di lista pendenti", e);
            // Esco da ciclo while e procedo con il prossimo dominio.
            if (perDominio) {
                ctx.log("pendenti.listaPendentiDominioFail", dominio.getCodDominio(), e.getMessage());
                continue;
            } else {
                ctx.log("pendenti.listaPendentiFail", stazione.getCodStazione(), e.getMessage());
                break;
            }
        } finally {
            if (transactionId != null) {
                GpThreadLocal.get().closeTransaction(transactionId);
            }
        }

        if (risposta.getFault() != null) {
            log.warn("Ricevuto errore durante la richiesta di lista pendenti: "
                    + risposta.getFault().getFaultCode() + ": " + risposta.getFault().getFaultString());

            String fc = risposta.getFault().getFaultCode() != null ? risposta.getFault().getFaultCode() : "-";
            String fs = risposta.getFault().getFaultString() != null ? risposta.getFault().getFaultString()
                    : "-";
            String fd = risposta.getFault().getDescription() != null ? risposta.getFault().getDescription()
                    : "-";
            if (perDominio) {
                ctx.log("pendenti.listaPendentiDominioKo", dominio.getCodDominio(), fc, fs, fd);
                continue;
            } else {
                ctx.log("pendenti.listaPendentiKo", stazione.getCodStazione(), fc, fs, fd);
                break;
            }
        }

        if (risposta.getListaRPTPendenti() == null
                || risposta.getListaRPTPendenti().getRptPendente().isEmpty()) {
            log.debug("Lista pendenti vuota.");
            if (perDominio) {
                ctx.log("pendenti.listaPendentiDominioVuota", dominio.getCodDominio());
                continue;
            } else {
                ctx.log("pendenti.listaPendentiVuota", stazione.getCodStazione());
                break;
            }
        }

        if (risposta.getListaRPTPendenti().getTotRestituiti() >= soglia) {

            // Vedo quanto e' ampia la finestra per capire se dimezzarla o ciclare sui domini
            int finestra = (int) TimeUnit.DAYS.convert((a.getTimeInMillis() - da.getTimeInMillis()),
                    TimeUnit.MILLISECONDS);

            if (finestra > 1) {
                ctx.log("pendenti.listaPendentiPiena", stazione.getCodStazione(),
                        dateFormat.format(da.getTime()), dateFormat.format(a.getTime()));
                finestra = finestra / 2;
                Calendar mezzo = (Calendar) a.clone();
                mezzo.add(Calendar.DATE, -finestra);
                log.debug("Lista pendenti con troppi elementi. Ricalcolo la finestra: (dal "
                        + dateFormat.format(da.getTime()) + " a " + dateFormat.format(a.getTime()) + ")");
                statiRptPendenti.putAll(acquisisciPendenti(client, intermediario, stazione, lstDomini, false,
                        da, mezzo, soglia));
                mezzo.add(Calendar.DATE, 1);
                statiRptPendenti.putAll(acquisisciPendenti(client, intermediario, stazione, lstDomini, false,
                        mezzo, a, soglia));
                return statiRptPendenti;
            } else {
                if (perDominio) {
                    ctx.log("pendenti.listaPendentiDominioDailyPiena", dominio.getCodDominio(),
                            dateFormat.format(a.getTime()));
                    log.debug(
                            "Lista pendenti con troppi elementi, ma impossibile diminuire ulteriormente la finesta. Elenco accettato.");
                } else {
                    ctx.log("pendenti.listaPendentiDailyPiena", stazione.getCodStazione(),
                            dateFormat.format(a.getTime()));
                    log.debug("Lista pendenti con troppi elementi, scalo a dominio.");
                    return acquisisciPendenti(client, intermediario, stazione, lstDomini, true, da, a, soglia);
                }
            }
        }

        // Qui ci arrivo o se ho meno di 500 risultati oppure se sono in *giornaliero per dominio*
        for (TipoRPTPendente rptPendente : risposta.getListaRPTPendenti().getRptPendente()) {
            String rptKey = rptPendente.getIdentificativoUnivocoVersamento() + "@"
                    + rptPendente.getCodiceContestoPagamento();
            statiRptPendenti.put(rptKey, rptPendente.getStato());
        }

        // Se sto ricercando per stazione, esco.
        if (!perDominio) {
            return statiRptPendenti;
        }
    }
    return statiRptPendenti;
}

From source file:onl.netfishers.netshot.RestService.java

/**
 * Search tasks.//from  w w w  .  j av a  2s . com
 *
 * @param request the request
 * @param criteria the criteria
 * @return the list
 * @throws WebApplicationException the web application exception
 */
@POST
@Path("tasks/search")
@RolesAllowed("readonly")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Task> searchTasks(RsTaskCriteria criteria) throws WebApplicationException {

    logger.debug("REST request, search for tasks.");

    Session session = Database.getSession();
    try {
        Criteria c = session.createCriteria(Task.class);
        Task.Status status = null;
        try {
            if (!"ANY".equals(criteria.getStatus())) {
                status = Task.Status.valueOf(criteria.getStatus());
                c.add(Property.forName("status").eq(status));
            }
        } catch (Exception e) {
            logger.warn("Invalid status {}.", criteria.getStatus());
        }
        Calendar min = Calendar.getInstance();
        min.setTime(criteria.getDay());
        min.set(Calendar.HOUR_OF_DAY, 0);
        min.set(Calendar.MINUTE, 0);
        min.set(Calendar.SECOND, 0);
        min.set(Calendar.MILLISECOND, 0);
        Calendar max = (Calendar) min.clone();
        max.add(Calendar.DAY_OF_MONTH, 1);

        if (status == Task.Status.SUCCESS || status == Task.Status.FAILURE) {
            c.add(Property.forName("executionDate").between(min.getTime(), max.getTime()));
        } else if (status == Task.Status.CANCELLED) {
            c.add(Property.forName("changeDate").between(min.getTime(), max.getTime()));
        } else if (status == null) {
            c.add(Restrictions.or(Property.forName("status").eq(Task.Status.RUNNING),
                    Property.forName("status").eq(Task.Status.SCHEDULED),
                    Property.forName("executionDate").between(min.getTime(), max.getTime()),
                    Restrictions.and(Property.forName("executionDate").isNull(),
                            Property.forName("changeDate").between(min.getTime(), max.getTime()))));
        }
        c.addOrder(Property.forName("id").desc());

        @SuppressWarnings("unchecked")
        List<Task> tasks = c.list();
        return tasks;
    } catch (HibernateException e) {
        logger.error("Error while searching for tasks.", e);
        throw new NetshotBadRequestException("Unable to fetch the tasks",
                NetshotBadRequestException.NETSHOT_DATABASE_ACCESS_ERROR);
    } finally {
        session.close();
    }
}

From source file:com.homeworkreminder.Main.java

@SuppressWarnings("deprecation")
private void initCalendarPage() {
    lastSelectedCalendarDate = Calendar.getInstance().getTime();
    calView = this.inflater.inflate(R.layout.calendar, main_content, false);
    if (caldroidFragment == null) {
        caldroidFragment = new CaldroidFragment();
        Bundle args = new Bundle();
        Calendar cal = Calendar.getInstance();
        args.putInt(CaldroidFragment.MONTH, cal.get(Calendar.MONTH) + 1);
        args.putInt(CaldroidFragment.YEAR, cal.get(Calendar.YEAR));
        args.putBoolean(CaldroidFragment.ENABLE_SWIPE, true);
        args.putBoolean(CaldroidFragment.SIX_WEEKS_IN_CALENDAR, true);
        caldroidFragment.setArguments(args);
    }/*from  w w  w.  j  av a2 s .co m*/
    caldroidFragment.setBackgroundResourceForDate(R.color.bg_blue, Calendar.getInstance().getTime());
    caldroidFragment.setTextColorForDate(R.color.pure_white, Calendar.getInstance().getTime());
    info_list = (ListView) calView.findViewById(R.id.info_listview);

    main_content.addView(calView);

    FragmentTransaction t = getSupportFragmentManager().beginTransaction();
    t.replace(R.id.calendar_container, caldroidFragment);
    t.commit();
    tv_calendar_notaskfordate = (TextView) findViewById(R.id.tv_calendar_notaskfordate);
    final CaldroidListener listener = new CaldroidListener() {

        @Override
        public void onSelectDate(Date date, View view) {
            initInfoListForDate(date);
            Calendar c = Calendar.getInstance();
            c.set(Calendar.YEAR, date.getYear() + 1900);
            c.set(Calendar.MONTH, date.getMonth());
            c.set(Calendar.DAY_OF_MONTH, date.getDate());
            c.set(Calendar.HOUR_OF_DAY, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
            Calendar r = Calendar.getInstance();
            r.set(Calendar.YEAR, lastSelectedCalendarDate.getYear() + 1900);
            r.set(Calendar.MONTH, lastSelectedCalendarDate.getMonth());
            r.set(Calendar.DAY_OF_MONTH, lastSelectedCalendarDate.getDate());
            r.set(Calendar.HOUR_OF_DAY, 0);
            r.set(Calendar.MINUTE, 0);
            r.set(Calendar.SECOND, 0);
            r.set(Calendar.MILLISECOND, 0);
            if (c.get(Calendar.MONTH) != currCalendarMonth.get(Calendar.MONTH)) {
                caldroidFragment.setBackgroundResourceForDate(R.drawable.border_bg, date);
                caldroidFragment.setTextColorForDate(R.color.caldroid_gray, date);
            } else {
                if (TaskMap.containsKey(c) && !TaskMap.get(c).isEmpty()) {
                    caldroidFragment.setTextColorForDate(R.color.pure_white, date);
                    caldroidFragment.setBackgroundResourceForDate(R.drawable.border_bg_green, date);
                } else {
                    caldroidFragment.setBackgroundResourceForDate(R.drawable.border_bg, date);
                    caldroidFragment.setTextColorForDate(R.color.black, date);
                }
            }
            if (r.get(Calendar.MONTH) != currCalendarMonth.get(Calendar.MONTH)) {
                caldroidFragment.setBackgroundResourceForDate(R.color.pure_white, lastSelectedCalendarDate);
                caldroidFragment.setTextColorForDate(R.color.caldroid_gray, lastSelectedCalendarDate);
            } else {
                if (TaskMap.containsKey(r) && !TaskMap.get(r).isEmpty()) {
                    caldroidFragment.setTextColorForDate(R.color.pure_white, lastSelectedCalendarDate);
                    caldroidFragment.setBackgroundResourceForDate(R.color.bg_green, lastSelectedCalendarDate);
                } else {
                    caldroidFragment.setBackgroundResourceForDate(R.color.pure_white, lastSelectedCalendarDate);
                    caldroidFragment.setTextColorForDate(R.color.black, lastSelectedCalendarDate);
                }
            }

            lastSelectedCalendarDate = new Date(date.getTime());
            caldroidFragment.setBackgroundResourceForDate(R.color.bg_blue, Calendar.getInstance().getTime());
            caldroidFragment.setTextColorForDate(R.color.pure_white, Calendar.getInstance().getTime());
            caldroidFragment.refreshView();
        }

        @Override
        public void onChangeMonth(int month, int year) {
            month--;
            currCalendarMonth.set(Calendar.MONTH, month);
            currCalendarMonth.set(Calendar.YEAR, year);
            Calendar v = Calendar.getInstance();
            v.set(Calendar.YEAR, lastSelectedCalendarDate.getYear() + 1900);
            v.set(Calendar.MONTH, lastSelectedCalendarDate.getMonth());
            v.set(Calendar.DAY_OF_MONTH, lastSelectedCalendarDate.getDate());
            v.set(Calendar.HOUR_OF_DAY, 0);
            v.set(Calendar.MINUTE, 0);
            v.set(Calendar.SECOND, 0);
            v.set(Calendar.MILLISECOND, 0);
            if (v.get(Calendar.MONTH) != month) {
                caldroidFragment.setBackgroundResourceForDate(R.color.pure_white, lastSelectedCalendarDate);
                caldroidFragment.setTextColorForDate(R.color.caldroid_gray, lastSelectedCalendarDate);
            } else {
                if (TaskMap.containsKey(v)) {
                    caldroidFragment.setTextColorForDate(R.color.pure_white, lastSelectedCalendarDate);
                    caldroidFragment.setBackgroundResourceForDate(R.color.bg_green, lastSelectedCalendarDate);
                } else {
                    caldroidFragment.setBackgroundResourceForDate(R.color.pure_white, lastSelectedCalendarDate);
                    caldroidFragment.setTextColorForDate(R.color.black, lastSelectedCalendarDate);
                }
            }
            Calendar k = Calendar.getInstance();
            k.set(Calendar.DAY_OF_MONTH, 1);
            k.set(Calendar.YEAR, year);
            k.set(Calendar.MONTH, month);
            Calendar prev = Calendar.getInstance();
            Calendar nxt = Calendar.getInstance();
            prev.set(Calendar.YEAR, k.get(Calendar.YEAR));
            nxt.set(Calendar.YEAR, k.get(Calendar.YEAR));
            prev.set(Calendar.MONTH, k.get(Calendar.MONTH) - 1);
            nxt.set(Calendar.MONTH, k.get(Calendar.MONTH) + 1);
            prev.set(Calendar.DAY_OF_MONTH, 1);
            int prev_month = prev.get(Calendar.MONTH);
            nxt.set(Calendar.DAY_OF_MONTH, 1);
            int nxt_month = nxt.get(Calendar.MONTH);
            while (k.get(Calendar.MONTH) == month) {
                caldroidFragment.setBackgroundResourceForDate(R.color.pure_white, k.getTime());
                caldroidFragment.setTextColorForDate(R.color.black, k.getTime());
                k.add(Calendar.DAY_OF_MONTH, 1);
            }
            while (prev.get(Calendar.MONTH) == prev_month) {
                caldroidFragment.setBackgroundResourceForDate(R.color.pure_white, prev.getTime());
                caldroidFragment.setTextColorForDate(R.color.caldroid_gray, prev.getTime());
                prev.add(Calendar.DAY_OF_MONTH, 1);
            }

            while (nxt.get(Calendar.MONTH) == nxt_month) {
                caldroidFragment.setBackgroundResourceForDate(R.color.pure_white, nxt.getTime());
                caldroidFragment.setTextColorForDate(R.color.caldroid_gray, nxt.getTime());
                nxt.add(Calendar.DAY_OF_MONTH, 1);
            }
            setCalendarTaskForMonth(month, year);
            Date r = new Date(year - 1900, month, 1, 0, 0, 0);
            if (initInfoListForDate(r)) {
                caldroidFragment.setTextColorForDate(R.color.pure_white, r);
                caldroidFragment.setBackgroundResourceForDate(R.drawable.border_bg_green, r);
            } else {
                caldroidFragment.setBackgroundResourceForDate(R.drawable.border_bg, r);
                caldroidFragment.setTextColorForDate(R.color.black, r);
            }
            lastSelectedCalendarDate = (Date) r.clone();
            caldroidFragment.setBackgroundResourceForDate(R.color.bg_blue, Calendar.getInstance().getTime());
            caldroidFragment.setTextColorForDate(R.color.pure_white, Calendar.getInstance().getTime());
            caldroidFragment.refreshView();
        }

        @Override
        public void onLongClickDate(Date date, View view) {
        }

        @Override
        public void onCaldroidViewCreated() {
        }

    };

    caldroidFragment.setCaldroidListener(listener);
    caldroidFragment.setBackgroundResourceForDate(R.color.bg_blue, Calendar.getInstance().getTime());
    caldroidFragment.setTextColorForDate(R.color.pure_white, Calendar.getInstance().getTime());
    setCalendarTaskForMonth(Calendar.getInstance().get(Calendar.MONTH),
            Calendar.getInstance().get(Calendar.YEAR));
}

From source file:edu.ku.brc.specify.utilapps.BuildSampleDatabase.java

/**
 * Creates a single disciplineType collection.
 * @param disciplineName the name of the Discipline to use
 * @param disciplineName the disciplineType name
 * @return the entire list of DB object to be persisted
 *///from  w  w w.  j  a  v a  2  s  .c om
@SuppressWarnings("unchecked")
public Collection createFishCollection(final Discipline discipline, final SpecifyUser user,
        final Agent userAgent, final Division division, final Journal journal, final List<Object> taxa,
        final List<Object> geos, final String colPrefix, final String colName, final boolean isVoucherCol,
        final boolean doTissues, final CollectionChoice choice) {
    createStep = 0;
    frame.setProcess(0, 15);

    frame.setDesc("Creating Collection " + colName);

    startTx();

    Pair<AutoNumberingScheme, AutoNumberingScheme> pairANS = createAutoNumberingSchemes(choice);
    AutoNumberingScheme cns = pairANS.first;
    AutoNumberingScheme accessionNS = pairANS.second;

    persist(cns);
    persist(accessionNS);

    commitTx();

    startTx();

    ////////////////////////////////
    // Create Collection
    ////////////////////////////////
    log.info("Creating a Collection");
    Collection collection = createCollection(colPrefix, colName, choice.getCatalogNumberingFmtName(), cns,
            discipline, false);
    persist(collection);

    AppContextMgr.getInstance().setClassObject(Collection.class, collection);

    division.addReference(accessionNS, "numberingSchemes");
    persist(division);

    ////////////////////////////////
    // Default user groups and test user
    ////////////////////////////////
    Map<String, SpPrincipal> groupMap = DataBuilder.createStandardGroups(session, collection);

    // add the administrator as a Collections Manager in this group
    user.addUserToSpPrincipalGroup(groupMap.get(SpecifyUserTypes.UserType.Manager.toString()));
    persist(user);

    // Tester
    String userPrefix = (isVoucherCol) ? "" : "Tis";
    createAndAddTesterToCollection(session, userPrefix + "FishTester", "fishtester@brc.ku.edu",
            userPrefix + "FishTester", "", "Fish", "", "Tester", "", discipline, division, collection, groupMap,
            "Guest");

    commitTx();

    ////////////////////////////////
    // picklists
    ////////////////////////////////
    log.info("Creating picklists");

    createPickLists(session, null);
    BldrPickList colMethods = createPickLists(session, discipline);

    frame.setProcess(++createStep);

    startTx();

    //DBTableIdMgr schema = new DBTableIdMgr(false);
    //schema.initialize(new File(XMLHelper.getConfigDirPath("specify_datamodel.xml")));
    //loadSchemaLocalization(discipline, SpLocaleContainer, schema);
    //buildDarwinCoreSchema(discipline);

    AppContextMgr.getInstance().setClassObject(SpecifyUser.class, user);

    user.addReference(userAgent, "agents");

    persist(user);

    frame.setProcess(++createStep);

    Vector<Object> dataObjects = new Vector<Object>();

    standardQueries(dataObjects, userAgent);
    persist(dataObjects);
    dataObjects.clear();

    //startTx();
    persist(dataObjects);
    //commitTx();
    dataObjects.clear();

    frame.setProcess(++createStep);

    ////////////////////////////////
    // localities
    ////////////////////////////////
    List<Locality> localities = new Vector<Locality>();

    String POINT = "Point";
    String LINE = "Line";
    String RECT = "Rectangle";

    Locality forestStream;
    Locality lake;
    Locality clintonLake;
    Locality farmpond;

    if (isVoucherCol) {
        log.info("Creating localities");
        forestStream = createLocality("Unnamed forest stream pond", (Geography) geos.get(12));
        localities.add(forestStream);
        globalLocalities.add(forestStream);
        forestStream.setLatLongType(POINT);
        forestStream.setOriginalLatLongUnit(0);
        forestStream.setLat1text("38.925467 deg N");
        forestStream.setLatitude1(new BigDecimal(38.925467));
        forestStream.setLong1text("94.984867 deg W");
        forestStream.setLongitude1(new BigDecimal(-94.984867));

        lake = createLocality("Deep, dark lake pond", (Geography) geos.get(17));
        localities.add(lake);
        globalLocalities.add(lake);
        lake.setLatLongType(RECT);
        lake.setOriginalLatLongUnit(1);
        lake.setLat1text("41.548842 deg N");
        lake.setLatitude1(new BigDecimal(41.548842));
        lake.setLong1text("93.732129 deg W");
        lake.setLongitude1(new BigDecimal(-93.732129));

        lake.setLat2text("41.642195 deg N");
        lake.setLatitude2(new BigDecimal(41.642195));
        lake.setLong2text("100.403180 deg W");
        lake.setLongitude2(new BigDecimal(-100.403180));

        Geography douglasKS = null;
        for (Object o : geos) {
            if (o instanceof Geography) {
                Geography g = (Geography) o;
                if (g.getFullName().indexOf("Douglas") == 0) {
                    douglasKS = g;
                }
            }
        }
        clintonLake = createLocality("Clinton Lake", douglasKS);
        localities.add(clintonLake);
        globalLocalities.add(clintonLake);

        farmpond = createLocality("Shoal Creek at Schermerhorn Park, S of Galena at Rt. 26",
                (Geography) geos.get(11));
        localities.add(farmpond);
        globalLocalities.add(farmpond);

        farmpond.setLatLongType(LINE);
        farmpond.setOriginalLatLongUnit(2);
        farmpond.setLat1text("41.642187 deg N");
        farmpond.setLatitude1(new BigDecimal(41.642187));
        farmpond.setLong1text("100.403163 deg W");
        farmpond.setLongitude1(new BigDecimal(-100.403163));

        farmpond.setLat2text("49.647435 deg N");
        farmpond.setLatitude2(new BigDecimal(49.647435));
        farmpond.setLong2text("-55.112163 deg W");
        farmpond.setLongitude2(new BigDecimal(-55.112163));

        persist(forestStream);
        persist(lake);
        persist(farmpond);
        persist(clintonLake);
    } else {
        forestStream = globalLocalities.get(0);
        lake = globalLocalities.get(1);
        farmpond = globalLocalities.get(2);
        localities.addAll(globalLocalities);
    }

    frame.setProcess(++createStep);

    ////////////////////////////////
    // agents and addresses
    ////////////////////////////////
    log.info("Creating agents and addresses");
    List<Agent> agents = new Vector<Agent>();
    Agent johnByrn = null;
    Agent ku = new Agent();

    if (isVoucherCol) {
        johnByrn = createAgent("mr", "John", "D", "Byrn", "jb", "jb@net.edu");
        agents.add(createAgent("mr", "David", "D", "Smith", "ds", "ds@whitehouse.gov"));
        agents.add(createAgent("mr", "Robert", "H", "Burk", "rb", "beach@net.edu"));
        agents.add(createAgent("mrs", "Margaret", "H", "Johnson", "jm", "jm@net.edu"));
        agents.add(createAgent("mr", "Kip", "C", "Spencer", "kcs", "kip@ku.edu"));
        agents.add(johnByrn);
        agents.add(createAgent("sir", "Dudley", "X", "Thompson", "dxt", ""));
        agents.add(createAgent("mr", "Joe", "A", "Campbell", "jb", ""));
        agents.add(createAgent("mr", "Joe", "A", "Tester", "jb", ""));
        agents.add(createAgent("mr", "Mitch", "A", "Smyth", "mas", "mas@ku.edu"));
        agents.add(userAgent);

        ku.initialize();
        ku.setAbbreviation("KU");
        ku.setAgentType(Agent.ORG);
        ku.setLastName("University of Kansas");
        ku.setEmail("webadmin@ku.edu");
        ku.setTimestampCreated(new Timestamp(System.currentTimeMillis()));
        ku.setDivision(AppContextMgr.getInstance().getClassObject(Division.class));

        agents.add(ku);
        agents.get(0).setOrganization(ku);
        agents.get(1).setOrganization(ku);
        agents.get(2).setOrganization(ku);
        agents.get(3).setOrganization(ku);
        agents.get(8).setOrganization(ku);

        Agent otherAgent = new Agent();
        otherAgent.initialize();
        otherAgent.setAbbreviation("O");
        otherAgent.setAgentType(Agent.OTHER);
        otherAgent.setLastName("The Other Guys");
        otherAgent.setEmail("other@other.com");
        otherAgent.setTimestampCreated(new Timestamp(System.currentTimeMillis()));
        otherAgent.setDivision(AppContextMgr.getInstance().getClassObject(Division.class));
        agents.add(otherAgent);

        List<GroupPerson> gpList = new ArrayList<GroupPerson>();
        if (true) {
            startTx();
            Agent gm1 = createAgent("mr", "John", "A", "Lyon", "jal", "jal@group.edu");
            Agent gm2 = createAgent("mr", "Dave", "D", "Jones", "ddj", "ddj@group.edu");
            persist(gm1);
            persist(gm2);
            commitTx();

            //Discipline dsp = AppContextMgr.getInstance().getClassObject(Discipline.class);

            Agent groupAgent = new Agent();
            groupAgent.initialize();
            groupAgent.setAbbreviation("GRP");
            groupAgent.setAgentType(Agent.GROUP);
            groupAgent.setLastName("The Group");
            groupAgent.setEmail("group@group.com");
            groupAgent.setTimestampCreated(new Timestamp(System.currentTimeMillis()));
            groupAgent.setDivision(AppContextMgr.getInstance().getClassObject(Division.class));

            agents.add(groupAgent);

            gpList.add(createGroupPerson(groupAgent, gm1, 0, division));
            gpList.add(createGroupPerson(groupAgent, gm2, 1, division));
        }

        globalAgents.addAll(agents);

        List<AgentVariant> agentVariants = new Vector<AgentVariant>();
        agentVariants.add(createAgentVariant(AgentVariant.VARIANT, "John Variant #1", johnByrn));
        agentVariants.add(createAgentVariant(AgentVariant.VERNACULAR, "John VERNACULAR #1", johnByrn));

        List<Address> addrs = new Vector<Address>();
        addrs.add(createAddress(agents.get(1), "1600 Pennsylvania Avenue NW", null, "Washington", "DC", "USA",
                "20500", 0));
        addrs.add(createAddress(agents.get(1), "??? Mississippi", null, "Lawrence", "KS", "USA", "66045", 1));
        addrs.add(createAddress(agents.get(2), "1 Main St", "", "Lenexa", "KS", "USA", "66071"));
        addrs.add(createAddress(agents.get(3), "13355 Inverness", "Bldg #3", "Lawrence", "KS", "USA", "66047"));
        addrs.add(createAddress(agents.get(4), "Natural History Museum", "Cromwell Rd", "London", null, "UK",
                "SW7 5BD"));
        addrs.add(createAddress(agents.get(6), "1212 Apple Street", null, "Chicago", "IL", "USA", "01010"));
        addrs.add(createAddress(agents.get(8), "11911 Oak Ln", null, "Orion", "KS", "USA", "66061"));
        addrs.add(createAddress(ku, null, null, "Lawrence", "KS", "USA", "66045"));
        addrs.add(createAddress(userAgent, "1214 East Street", null, "Grinnell", "IA", "USA", "56060"));

        persist(agents);
        persist(agentVariants);
        persist(gpList);

    } else {
        agents.addAll(globalAgents);
        johnByrn = agents.get(4);
        ku = agents.get(10);
    }

    frame.setProcess(++createStep);

    ////////////////////////////////
    // collecting events (collectors, collecting trip)
    ////////////////////////////////

    log.info("Creating collecting events, collectors and a collecting trip");
    Collector collectorMitch = createCollector(agents.get(8), 2);
    Collector collectorJim = createCollector(agents.get(1), 1);
    calendar.set(1993, 3, 19, 11, 56, 00);
    String stationFieldNumber = String.format(STATION_FIELD_FORMAT, stationFieldNumberCounter++);
    CollectingEvent ce1 = createCollectingEvent(forestStream, calendar, stationFieldNumber,
            new Collector[] { collectorMitch, collectorJim });
    ce1.setStartDateVerbatim("19 Mar 1993, 11:56 AM");
    calendar.set(1993, 3, 19, 13, 03, 00);
    ce1.setEndDate(calendar);
    ce1.setEndDateVerbatim("19 Mar 1993, 1:03 PM");
    ce1.setMethod(colMethods.getItem(1).getValue());

    AttributeDef cevAttrDef = createAttributeDef(AttributeIFace.FieldType.StringType, "ParkName", discipline,
            null);//meg added cod

    //startTx();
    persist(cevAttrDef);
    //commitTx();

    CollectingEventAttr cevAttr = createCollectingEventAttr(ce1, cevAttrDef, "Sleepy Hollow", null);

    Collector collectorMeg = createCollector(agents.get(2), 1);
    Collector collectorRod = createCollector(agents.get(3), 2);
    calendar.set(1993, 3, 20, 06, 12, 00);
    stationFieldNumber = String.format(STATION_FIELD_FORMAT, stationFieldNumberCounter++);
    CollectingEvent ce2 = createCollectingEvent(farmpond, calendar, stationFieldNumber,
            new Collector[] { collectorMeg, collectorRod });
    ce2.setStartDateVerbatim("20 Mar 1993, 6:12 AM");
    calendar.set(1993, 3, 20, 07, 31, 00);
    ce2.setEndDate(calendar);
    ce2.setEndDateVerbatim("20 Mar 1993, 7:31 AM");
    ce2.setMethod(colMethods.getItem(2).getValue());

    CollectingTrip trip = createCollectingTrip("My Collecint Trip", "Sample collecting trip",
            new CollectingEvent[] { ce1, ce2 });

    int[] mn = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    Vector<CollectingEvent> ceList = new Vector<CollectingEvent>();
    boolean oldWay = false;
    if (!oldWay) {
        int monInx = rand.nextInt(12);
        int dayInx = rand.nextInt(mn[monInx]);
        calendar.set(1990 + rand.nextInt(15), monInx + 1, dayInx + 1, rand.nextInt(24), rand.nextInt(60),
                rand.nextInt(60));
        stationFieldNumber = String.format(STATION_FIELD_FORMAT, stationFieldNumberCounter++);

        Collector collector = null;
        int coltrInx = rand.nextInt(4);
        switch (coltrInx) {
        case 0:
            collector = collectorMitch;
            break;
        case 1:
            collector = collectorJim;
            break;
        case 2:
            collector = collectorMeg;
            break;
        case 3:
            collector = collectorRod;
            break;
        default:
            collector = collectorRod;
            break;
        }
        Locality loc = globalLocalities.get(rand.nextInt(globalLocalities.size()));
        CollectingEvent ce = createCollectingEvent(loc, calendar, stationFieldNumber,
                new Collector[] { collector });
        //ce1.setStartDateVerbatim("19 Mar 1993, 11:56 AM");
        ceList.add(ce);
        dataObjects.add(ce);
    }

    dataObjects.add(trip);
    dataObjects.add(ce1);
    dataObjects.add(cevAttr);
    dataObjects.add(ce2);
    dataObjects.add(collectorMitch);
    dataObjects.add(collectorJim);
    dataObjects.add(collectorMeg);
    dataObjects.add(collectorRod);

    //startTx();
    persist(dataObjects);
    //commitTx();
    dataObjects.clear();

    ////////////////////////////////
    // permit
    ////////////////////////////////
    log.info("Creating a permit");
    Calendar issuedDate = Calendar.getInstance();
    issuedDate.set(1993, 1, 12);
    Calendar startDate = Calendar.getInstance();
    startDate.set(1993, 2, 1);
    Calendar endDate = Calendar.getInstance();
    endDate.set(1993, 5, 30);
    Permit permit = createPermit("1993-FISH-0001", "US Dept Wildlife", issuedDate, startDate, endDate, null);
    permit.setIssuedTo(ku);
    permit.setIssuedBy(agents.get(4));
    dataObjects.add(permit);

    log.info("Creating a repository agreement");
    RepositoryAgreement repoAg = new RepositoryAgreement();
    repoAg.initialize();
    repoAg.setDivision(division);
    repoAg.setRepositoryAgreementNumber("KU-1992-01");
    repoAg.setOriginator(ku);
    Calendar received = Calendar.getInstance();
    received.set(1992, 2, 10);
    repoAg.setDateReceived(received);
    Calendar repoEndDate = Calendar.getInstance();
    received.set(2010, 2, 9);
    repoAg.setEndDate(repoEndDate);
    dataObjects.add(repoAg);

    //startTx();
    persist(dataObjects);
    //commitTx();
    dataObjects.clear();

    frame.setProcess(++createStep);

    ////////////////////////////////
    // collection objects
    ////////////////////////////////
    log.info("Creating collection objects");

    List<DNASequence> dnaObjs = new Vector<DNASequence>();
    List<CollectionObject> collObjs = new Vector<CollectionObject>();
    Collection col = collection;

    Calendar[] catDates = new Calendar[oldWay ? 8 : 50];
    for (int i = 0; i < catDates.length; i++) {
        catDates[i] = Calendar.getInstance();
        catDates[i].set(catDates[i].get(Calendar.YEAR), 01, 12 + i);
    }

    String prefix = "000000";
    if (oldWay) {
        collObjs.add(createCollectionObject(prefix + "100", "RSC100", agents.get(0), col, 3, ce1, catDates[0],
                "BuildSampleDatabase"));
        collObjs.add(createCollectionObject(prefix + "101", "RSC101", agents.get(0), col, 2, ce1, catDates[1],
                "BuildSampleDatabase"));
        collObjs.add(createCollectionObject(prefix + "102", "RSC102", agents.get(1), col, 7, ce1, catDates[2],
                "BuildSampleDatabase"));
        collObjs.add(createCollectionObject(prefix + "103", "RSC103", agents.get(1), col, 12, ce1, catDates[3],
                "BuildSampleDatabase"));
        collObjs.add(createCollectionObject(prefix + "104", "RSC104", agents.get(2), col, 8, ce2, catDates[4],
                "BuildSampleDatabase"));
        collObjs.add(createCollectionObject(prefix + "105", "RSC105", agents.get(2), col, 1, ce2, catDates[5],
                "BuildSampleDatabase"));
        collObjs.add(createCollectionObject(prefix + "106", "RSC106", agents.get(2), col, 1, ce2, catDates[6],
                "BuildSampleDatabase"));
        collObjs.add(createCollectionObject(prefix + "107", "RSC107", agents.get(3), col, 1, ce2, catDates[7],
                "BuildSampleDatabase"));
    } else {
        for (int i = 0; i < catDates.length; i++) {
            Integer catNum = i + 100;
            int agentInx = rand.nextInt(agents.size());
            CollectingEvent ce = ceList.get(rand.nextInt(ceList.size()));
            collObjs.add(createCollectionObject(prefix + catNum, "RSC" + catNum, agents.get(agentInx), col,
                    rand.nextInt(12) + 1, ce, catDates[i], "BuildSampleDatabase"));
        }

        /*
                    Comp. A :   148      
                    Comp. G :   131      
                    Comp. C :   199      
                    Comp. T :   174      
                    Ambiguous :     0    
                123456789012345678901234567890123456789012345678901234567890123456789012345
                CCTGTATTTAGTATTTGGTGCCTGAGCAGGCATAGTCGGCACAGCCCTCAGCCTTCTGATCCGTGCCGAACTGAG
                CCAACCCGGTGCCCTGCTTGGCGATGATCAGATCTACAATGTTATCGTCACAGCCCACGCCTTTGTCATGATTTT
                CTTTATAGTAATACCCATCATAATTGGCGGATTCGGAAACTGACTGGTCCCCCTAATAATTGGGGCCCCAGACAT
                GGCATTTCCTCGCATGAACAATATGAGCTTCTGACTCCTACCCCCATCCTTCCTACTCCTTTTAGCCTCCTCTGG
                GGTAGAGGCCGGAGCCGGCACAGGGTGAACTGTTTACCCCCCACTGGCGGGAAACCTGGCCCATGCAGGAGCCTC
                TGTAGACCTAACCATTTTCTCCCTTCACCTGGCTGGGGTTTCGTCCATTTTGGGGGCTATTAATTTTATTACCAC
                CATTATTAACATGAAACCCCCCGCAGTATCCCAATATCAGACACCTCTATTTGTGTGATCTGTATTAATCACGGC
                CGTACTTCTCCTACTATCACTGCCAGTGCTAGCTGCAGGGATCACAATGCTCCTAACAGACCGAAATTTAAACAC
                CACCTTCTTTGACCCAGCCGGAGGAGGAGACCCCATCCTCTACCAACACCTA
                */
        char[] syms = { 'A', 'C', 'T', 'G', };

        for (int i = 0; i < catDates.length; i++) {
            int monInx = rand.nextInt(12);
            int dayInx = rand.nextInt(mn[monInx]);
            Calendar cal = Calendar.getInstance();
            cal.set(2006 + rand.nextInt(3), monInx + 1, dayInx + 1, rand.nextInt(24), rand.nextInt(60),
                    rand.nextInt(60));

            DNASequence dna = new DNASequence();
            dna.initialize();

            //dna.setSeqDate(cal); //moved to DNASequencingRun
            dna.setCollectionMemberId(collObjs.get(i).getCollectionMemberId());
            dna.setCollectionObject(collObjs.get(i));
            //dna.setGeneName("COI5'");
            int agentInx = rand.nextInt(agents.size());
            dna.setCreatedByAgent(agents.get(agentInx));
            dna.setSequencer(agents.get(agentInx));
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < ((8 * 75) + 52); j++) {
                sb.append(syms[rand.nextInt(syms.length)]);
            }
            dna.setGeneSequence(sb.toString());
            //dna.setPcrPrimerFwd("C_VF1LFt1"); //moved to DNASequencingRun (sort of)
            //dna.setPcrPrimerRev("C_VR1LRt1"); //moved to DNASequencingRun (sort of)
            //dna.setProcessIdentifier("M13R"); //moved to DNASequencingRun (sort of)
            if (rand.nextInt(3) < 2) {
                //dna.setBarCodeIdent(String.format("NOSMF%03d-%d02", rand.nextInt(1000), i)); //moved to DNASequencingRun (sort of)
                Calendar submDate = (Calendar) cal.clone();
                submDate.add(Calendar.DAY_OF_MONTH, 12);
                //dna.setSubmissionDate(submDate);
            }
            dnaObjs.add(dna);
        }
    }
    AttributeDef colObjAttrDef = createAttributeDef(AttributeIFace.FieldType.StringType, "MoonPhase",
            discipline, null);//meg added cod
    colObjAttrDef.setDiscipline(discipline);
    discipline.getAttributeDefs().add(colObjAttrDef);

    CollectionObjectAttr colObjAttr = createCollectionObjectAttr(collObjs.get(0), colObjAttrDef, "Full", null);
    dataObjects.add(colObjAttrDef);
    dataObjects.addAll(collObjs);
    dataObjects.addAll(dnaObjs);
    dataObjects.add(colObjAttr);

    //startTx();
    persist(dataObjects);
    //commitTx();
    dataObjects.clear();

    frame.setProcess(++createStep);

    ////////////////////////////////
    // determinations (determination status)
    ////////////////////////////////
    log.info("Creating determinations");

    List<Determination> determs = new Vector<Determination>();
    Calendar recent = Calendar.getInstance();
    recent.set(2006, 10, 27, 13, 44, 00);
    Calendar longAgo = Calendar.getInstance();
    longAgo.set(1976, 01, 29, 8, 12, 00);
    Calendar whileBack = Calendar.getInstance();
    whileBack.set(2002, 7, 4, 9, 33, 12);

    int baseInx = 41 - (doShallowTaxonTree ? 30 : 0);
    if (oldWay) {
        determs.add(createDetermination(collObjs.get(0), agents.get(0), (Taxon) taxa.get(baseInx + 1), true,
                recent));
        determs.add(createDetermination(collObjs.get(1), agents.get(0), (Taxon) taxa.get(baseInx + 2), true,
                recent));
        determs.add(createDetermination(collObjs.get(2), agents.get(0), (Taxon) taxa.get(baseInx + 3), true,
                recent));
        determs.add(createDetermination(collObjs.get(3), agents.get(0), (Taxon) taxa.get(baseInx + 4), true,
                recent));
        determs.add(createDetermination(collObjs.get(4), agents.get(0), (Taxon) taxa.get(baseInx + 5), true,
                recent));
        determs.add(createDetermination(collObjs.get(5), agents.get(0), (Taxon) taxa.get(baseInx + 6), true,
                recent));
        determs.add(createDetermination(collObjs.get(6), agents.get(3), (Taxon) taxa.get(baseInx + 7), true,
                recent));
        determs.add(createDetermination(collObjs.get(7), agents.get(4), (Taxon) taxa.get(baseInx + 8), true,
                recent));

        determs.add(
                createDetermination(collObjs.get(0), agents.get(0), (Taxon) taxa.get(baseInx), false, longAgo));
        determs.add(createDetermination(collObjs.get(1), agents.get(1), (Taxon) taxa.get(baseInx + 7), false,
                whileBack));
        determs.add(createDetermination(collObjs.get(2), agents.get(1), (Taxon) taxa.get(baseInx + 9), false,
                whileBack));
        determs.add(createDetermination(collObjs.get(3), agents.get(2), (Taxon) taxa.get(baseInx + 10), false,
                whileBack));
        determs.add(createDetermination(collObjs.get(4), agents.get(2), (Taxon) taxa.get(baseInx + 10), false,
                whileBack));
        determs.add(createDetermination(collObjs.get(4), agents.get(3), (Taxon) taxa.get(baseInx + 13), false,
                longAgo));
        determs.add(createDetermination(collObjs.get(4), agents.get(4), (Taxon) taxa.get(baseInx + 12), false,
                longAgo));
        determs.get(13).setRemarks("This determination is totally wrong.  What a foolish determination.");
    } else {
        for (CollectionObject co : collObjs) {
            determs.add(createDetermination(co, agents.get(0), (Taxon) taxa.get(baseInx + rand.nextInt(13)),
                    true, recent));
        }
    }

    //startTx();
    persist(determs);
    //commitTx();
    dataObjects.clear();

    frame.setProcess(++createStep);

    ////////////////////////////////
    // preparations (prep types)
    ////////////////////////////////
    log.info("Creating preparations");

    Vector<PrepType> prepTypesForSaving = loadPrepTypes(discipline.getType());
    Vector<PrepType> pt = new Vector<PrepType>();

    if (doTissues) {
        pt.clear();
        PrepType tissuePT = createPrepType(collection, "Tissue");
        for (int i = 0; i < prepTypesForSaving.size(); i++) {
            pt.add(tissuePT);
        }
        prepTypesForSaving.clear();
        prepTypesForSaving.add(tissuePT);

    } else {
        pt.addAll(prepTypesForSaving);
    }

    List<Preparation> preps = new Vector<Preparation>();
    Calendar prepDate = Calendar.getInstance();
    if (oldWay) {
        preps.add(createPreparation(pt.get(0), agents.get(0), collObjs.get(0), (Storage) locs.get(7),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(0), agents.get(0), collObjs.get(1), (Storage) locs.get(7),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(0), agents.get(1), collObjs.get(2), (Storage) locs.get(7),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(0), agents.get(1), collObjs.get(3), (Storage) locs.get(7),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(0), agents.get(2), collObjs.get(4), (Storage) locs.get(8),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(0), agents.get(2), collObjs.get(5), (Storage) locs.get(8),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(0), agents.get(3), collObjs.get(6), (Storage) locs.get(8),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(0), agents.get(3), collObjs.get(7), (Storage) locs.get(8),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(1), agents.get(1), collObjs.get(0), (Storage) locs.get(11),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(1), agents.get(1), collObjs.get(1), (Storage) locs.get(11),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(1), agents.get(1), collObjs.get(2), (Storage) locs.get(10),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(1), agents.get(2), collObjs.get(3), (Storage) locs.get(9),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(1), agents.get(3), collObjs.get(4), (Storage) locs.get(9),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(1), agents.get(0), collObjs.get(5), (Storage) locs.get(9),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(2), agents.get(1), collObjs.get(6), (Storage) locs.get(9),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(2), agents.get(1), collObjs.get(7), (Storage) locs.get(9),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(2), agents.get(1), collObjs.get(2), (Storage) locs.get(8),
                rand.nextInt(20) + 1, prepDate));

        preps.add(createPreparation(pt.get(3), agents.get(1), collObjs.get(0), (Storage) locs.get(7),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(3), agents.get(1), collObjs.get(1), (Storage) locs.get(7),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(3), agents.get(1), collObjs.get(2), (Storage) locs.get(8),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(3), agents.get(1), collObjs.get(3), (Storage) locs.get(8),
                rand.nextInt(20) + 1, prepDate));
        preps.add(createPreparation(pt.get(3), agents.get(1), collObjs.get(4), (Storage) locs.get(9),
                rand.nextInt(20) + 1, prepDate));
    } else {
        for (CollectionObject co : collObjs) {
            preps.add(createPreparation(pt.get(0), agents.get(rand.nextInt(4)), co,
                    (Storage) locs.get(rand.nextInt(6) + 7), rand.nextInt(20) + 1, prepDate));
        }
    }

    dataObjects.add(collection);
    dataObjects.addAll(prepTypesForSaving);
    dataObjects.addAll(preps);

    //startTx();
    persist(dataObjects);
    //commitTx();
    dataObjects.clear();

    frame.setProcess(++createStep);

    ////////////////////////////////
    // accessions (accession agents)
    ////////////////////////////////
    log.info("Creating accessions and accession agents");
    calendar.set(2006, 10, 27, 23, 59, 59);
    int yr = 2000 + (int) (rand.nextDouble() * 7);
    Accession acc1 = createAccession(division, "gift", "complete", yr + "-IC-001",
            DateFormat.getInstance().format(calendar.getTime()), calendar, calendar);
    acc1.setText1("Ichthyology");
    acc1.setRepositoryAgreement(repoAg);

    Agent donor = agents.get(4);
    Agent receiver = agents.get(1);
    Agent reviewer = agents.get(2);

    List<AccessionAgent> accAgents = new Vector<AccessionAgent>();

    accAgents.add(createAccessionAgent("donor", donor, acc1, null));
    accAgents.add(createAccessionAgent("receiver", receiver, acc1, null));
    accAgents.add(createAccessionAgent("reviewer", reviewer, acc1, null));

    Accession acc2 = createAccession(division, "field_work", "inprocess", yr + "-IC-002",
            DateFormat.getInstance().format(calendar.getTime()), calendar, calendar);

    Agent donor2 = agents.get(5);
    Agent receiver2 = agents.get(3);
    Agent reviewer2 = agents.get(1);

    accAgents.add(createAccessionAgent("donor", donor2, acc2, null));
    accAgents.add(createAccessionAgent("receiver", receiver2, acc2, null));
    accAgents.add(createAccessionAgent("reviewer", reviewer2, acc2, null));

    dataObjects.add(acc1);
    dataObjects.add(acc2);
    dataObjects.addAll(accAgents);

    //startTx();
    persist(dataObjects);
    //commitTx();
    dataObjects.clear();

    frame.setProcess(++createStep);

    createLoanExamples(preps, agents, dataObjects);
    frame.setProcess(++createStep);

    //startTx();
    persist(dataObjects);
    //commitTx();
    dataObjects.clear();

    /*if (false)
    {
    TaxonCitation taxonCitation = new TaxonCitation();
    taxonCitation.initialize();
    Taxon taxon11 = (Taxon)taxa.get(11);
    taxonCitation.setTaxon(taxon11);
    taxonCitation.setReferenceWork(rwList.get(0));
    rwList.get(0).addTaxonCitations(taxonCitation);
    taxon11.getTaxonCitations().add(taxonCitation);
    dataObjects.add(taxonCitation);
            
            
    LocalityCitation localityCitation = new LocalityCitation();
    localityCitation.initialize();
    localityCitation.setLocality(ce1.getLocality());
    ce1.getLocality().getLocalityCitations().add(localityCitation);
    localityCitation.setReferenceWork(rwList.get(1));
    rwList.get(1).addLocalityCitations(localityCitation);
    dataObjects.add(localityCitation);
    }*/

    ////////////////////////////////
    // Workbench
    ////////////////////////////////

    // setup a template and its mapping items
    String name = discipline.getName() + " DataSet";
    WorkbenchTemplate wbTemplate = createWorkbenchTemplate(user, name, "These are the remarks");
    WorkbenchTemplateMappingItem wbtmi0 = createWorkbenchMappingItem("CollectionObject", 1, "fieldNumber",
            "Field Number", 25, 0, 0, wbTemplate);
    WorkbenchTemplateMappingItem wbtmi1 = createWorkbenchMappingItem("CollectionObject", 1, "catalogedDate",
            "Cataloged Date", 25, 1, 1, wbTemplate);
    WorkbenchTemplateMappingItem wbtmi2 = createWorkbenchMappingItem("CollectionObject", 1, "catalogNumber",
            "Catalog Number", 25, 2, 2, wbTemplate);
    WorkbenchTemplateMappingItem wbtmi3 = createWorkbenchMappingItem("CollectionObject", 1,
            "collectionObjectYesNo1", "Yes/No", 8, 3, 3, wbTemplate);

    dataObjects.add(wbTemplate);
    dataObjects.add(wbtmi0);
    dataObjects.add(wbtmi1);
    dataObjects.add(wbtmi2);
    dataObjects.add(wbtmi3);

    // setup a workbench based on that template
    Workbench workBench = createWorkbench(user, name, "These are the remarks", "field_notebook.cvs",
            wbTemplate);
    dataObjects.add(workBench);

    // create a bunch of rows for the workbench
    for (int i = 1; i <= 14; ++i) {
        WorkbenchRow wbRow = workBench.addRow();
        WorkbenchDataItem wbdi0 = createWorkbenchDataItem(wbRow, "RS-10" + i, 0);

        // just to make the dates look a little random
        int date = (i * 547) % 31 + 1;
        String dateStr = "0" + Integer.toString(date);
        dateStr = dateStr.substring(dateStr.length() - 2);
        WorkbenchDataItem wbdi1 = createWorkbenchDataItem(wbRow, "03/" + dateStr + "/2007", 1);
        WorkbenchDataItem wbdi2 = createWorkbenchDataItem(wbRow, "CN-10" + i, 2);

        String boolValAsStr = null;
        switch (i % 3) {
        case 0: {
            boolValAsStr = "true";
            break;
        }
        case 1: {
            boolValAsStr = "false";
            break;
        }
        case 2: {
            boolValAsStr = "";
            break;
        }
        }
        boolValAsStr = "";
        WorkbenchDataItem wbdi3 = createWorkbenchDataItem(wbRow, boolValAsStr, 3);

        WorkbenchRowImage wbRowImage = null;

        File f = new File(getDefaultWorkingPath() + File.separator + "demo_files" + File.separator + "card" + i
                + (i == 2 ? ".png" : ".jpg"));
        if (f.exists()) {
            try {
                int imageIndex = wbRow.addImage(f);
                if (imageIndex > -1) {
                    wbRowImage = wbRow.getRowImage(imageIndex);
                }
            } catch (IOException e) {
                String msg = getResourceString("WB_IMG_ERR_LOAD");
                getStatusBar().setErrorMessage(msg, e);
                log.error(msg, e);
            }
        }

        dataObjects.add(wbRow);
        dataObjects.add(wbdi0);
        dataObjects.add(wbdi1);
        dataObjects.add(wbdi2);
        if (wbRowImage != null) {
            dataObjects.add(wbRowImage);
        }

        // since some of these values will be "", the data item might be null
        if (wbdi3 != null) {
            dataObjects.add(wbdi3);
        }
    }

    //        // create a workbench that uses the old, single-image capabilities
    //        Workbench         workBench2  = createWorkbench(user, name + " (pre-conversion)", "These are the remarks", "field_notebook.cvs", wbTemplate);
    //        dataObjects.add(workBench2);
    //
    //        // create a bunch of rows for the workbench
    //        for (int i = 1; i <= 14; ++i)
    //        {
    //            WorkbenchRow wbRow = workBench2.addRow();
    //            WorkbenchDataItem wbdi0 = createWorkbenchDataItem(wbRow, "RS-10" + i, 0);
    //            
    //            // just to make the dates look a little random
    //            int date = (i*547) % 31 + 1;
    //            String dateStr = "0" + Integer.toString(date);
    //            dateStr = dateStr.substring(dateStr.length()-2);
    //            WorkbenchDataItem wbdi1 = createWorkbenchDataItem(wbRow, "03/" + dateStr + "/2007", 1);
    //            WorkbenchDataItem wbdi2 = createWorkbenchDataItem(wbRow, "CN-10" + i, 2);
    //            
    //            String boolValAsStr = null;
    //            switch (i % 3)
    //            {
    //                case 0:
    //                {
    //                    boolValAsStr = "true";
    //                    break;
    //                }
    //                case 1:
    //                {
    //                    boolValAsStr = "false";
    //                    break;
    //                }
    //                case 2:
    //                {
    //                    boolValAsStr = "";
    //                    break;
    //                }
    //            }
    //            boolValAsStr = "";
    //            WorkbenchDataItem wbdi3 = createWorkbenchDataItem(wbRow, boolValAsStr, 3);
    //            
    //            WorkbenchRowImage wbRowImage = null;
    //            
    //            File f = new File("demo_files" + File.separator + "card" + i + (i == 2 ? ".png" : ".jpg"));
    //            if (f.exists())
    //            {
    //                try
    //                {
    //                    // NOTE: this is not scaling the images to the proper sizes.  Since this is just sample DB/test code, this isn't a problem.
    //                    byte[] imageData = FileUtils.readFileToByteArray(f);
    //                    wbRow.setCardImageData(imageData);
    //                    wbRow.setCardImageFullPath(f.getAbsolutePath());
    //                }
    //                catch (IOException e)
    //                {
    //                    log.error("Unable to add card image to workbench row", e);
    //                }
    //            }
    //
    //            dataObjects.add(wbRow);
    //            dataObjects.add(wbdi0);
    //            dataObjects.add(wbdi1);
    //            dataObjects.add(wbdi2);
    //            if (wbRowImage != null)
    //            {
    //                dataObjects.add(wbRowImage);
    //            }
    //            
    //            // since some of these values will be "", the data item might be null
    //            if (wbdi3 != null)
    //            {
    //                dataObjects.add(wbdi3);
    //            }
    //        }

    startTx();
    persist(dataObjects);
    commitTx();

    dataObjects.clear();

    frame.setProcess(++createStep);

    ////////////////////////////////
    // attachments (attachment metadata)
    ////////////////////////////////
    startTx();

    log.info("Creating attachments and attachment metadata");
    try {
        String attachmentFilesLoc = getDefaultWorkingPath() + File.separator + "demo_files" + File.separator;

        //                String bigEyeFilePath = attachmentFilesLoc + "bigeye.jpg";
        //                Attachment bigEye = createAttachment(bigEyeFilePath, "image/jpeg", 0);
        //                bigEye.setLoan(closedLoan);

        String[] names = { "Beach", "Smyth", "Spears", "Kumin", "Bentley" };
        String[] photos = { "beach.jpg", "rod.jpg", "rod.jpg", "meg.jpg", "andy.jpg" };
        for (Agent agent : agents) {
            for (int i = 0; i < names.length; i++) {
                if (agent.getLastName() != null && agent.getLastName().startsWith(names[i])) {
                    String photoPath = attachmentFilesLoc + photos[i];

                    File file = new File(attachmentFilesLoc + photos[i]);
                    if (!file.exists()) {
                        continue;
                    }

                    // create the attachment record
                    Attachment photoAttachment = createAttachment(photoPath, "image/jpeg",
                            Agent.getClassTableId());
                    dataObjects.add(photoAttachment);

                    // link the attachment to the agent
                    AgentAttachment agentAttach = new AgentAttachment();
                    agentAttach.initialize();
                    agentAttach.setAgent(agent);
                    agentAttach.setAttachment(photoAttachment);
                    agentAttach.setOrderIndex(0);
                    dataObjects.add(agentAttach);

                    // add some metadata to the attachment record
                    AttachmentMetadata copyrightData = new AttachmentMetadata();
                    copyrightData.initialize();
                    copyrightData.setName("Copyright");
                    copyrightData.setValue("2008");
                    photoAttachment.getMetadata().add(copyrightData);
                    copyrightData.setAttachment(photoAttachment);
                    dataObjects.add(copyrightData);

                    AttachmentMetadata defPhotoIndicator = new AttachmentMetadata();
                    defPhotoIndicator.initialize();
                    defPhotoIndicator.setName("Default Photo");
                    defPhotoIndicator.setValue("yes");
                    photoAttachment.getMetadata().add(defPhotoIndicator);
                    defPhotoIndicator.setAttachment(photoAttachment);
                    dataObjects.add(defPhotoIndicator);

                    // store the actual file into the attachment storage system
                    AttachmentUtils.getAttachmentManager().setStorageLocationIntoAttachment(photoAttachment,
                            true);
                    photoAttachment.storeFile(false); // false means do not display an error dialog
                }
            }
        }

        //                String giftPdfPath = attachmentFilesLoc + "2004-18.pdf";
        //                Attachment giftPDF = createAttachment(giftPdfPath, "application/pdf", 0);
        //                giftPDF.setLoan(closedLoan);
        //                
        //                String accessionPdfPath = attachmentFilesLoc + "Seychelles.pdf";
        //                Attachment accPDF = createAttachment(accessionPdfPath, "application/pdf", 0);
        //                // TODO: change this to setAccession()
        //                accPDF.setPermit(permit);
        //                
        //                String sharkVideoPath = attachmentFilesLoc + "shark5.mpg";
        //                Attachment sharkVideo = createAttachment(sharkVideoPath, "video/mpeg4", 0);
        //                sharkVideo.setLoan(closedLoan);
        //    
        //                Attachment sharkVideo2 = createAttachment(sharkVideoPath, "video/mpeg4", 0);
        //                sharkVideo2.setCollectingEvent(ce1);
        //    
        //                String beakerPath = attachmentFilesLoc + "beaker.jpg";
        //                Attachment beakerAsBeach = createAttachment(beakerPath, "image/jpg", 1);
        //                beakerAsBeach.setAgent(agents.get(1));
        //                
        //                dataObjects.add(bigEye);
        //                dataObjects.add(giftPDF);
        //                dataObjects.add(accPDF);
        //                dataObjects.add(sharkVideo);
        //                dataObjects.add(sharkVideo2);
        //                dataObjects.add(beakerAsBeach);
    } catch (Exception e) {
        log.error("Could not create attachments", e);
    }

    addConservatorData(agents, collObjs);

    commitTx();

    frame.setProcess(++createStep);

    if (true) {
        List<Taxon> taxa2 = session.createQuery("SELECT t FROM Taxon t WHERE t.name = 'Ammocrypta'").list();
        List<ReferenceWork> rwList = new Vector<ReferenceWork>();

        startTx();
        rwList.addAll(journal.getReferenceWorks());

        TaxonCitation taxonCitation = new TaxonCitation();
        taxonCitation.initialize();
        Taxon ammocrypta = taxa2.get(0);
        taxonCitation.setTaxon(ammocrypta);
        taxonCitation.setReferenceWork(rwList.get(0));
        rwList.get(0).addTaxonCitations(taxonCitation);
        ammocrypta.getTaxonCitations().add(taxonCitation);
        dataObjects.add(taxonCitation);
        persist(taxonCitation);

        if (isVoucherCol) {
            Locality locality = localities.get(0);
            LocalityCitation localityCitation = new LocalityCitation();
            localityCitation.initialize();
            localityCitation.setLocality(locality);
            locality.getLocalityCitations().add(localityCitation);
            localityCitation.setReferenceWork(rwList.get(1));
            rwList.get(1).addLocalityCitations(localityCitation);
            dataObjects.add(localityCitation);
            persist(localityCitation);
        }
        commitTx();
    }
    frame.setProcess(++createStep);

    //SpecifyDeleteHelper.showTableCounts("EmptyDB.txt", true);

    return collection;
}

From source file:net.siveo.virtualization.vmware.Main.java

public void getVAppPerformance() throws VMwareException {
    // ===================================================================================
    // Connection to the  VirtualCenter
    // ===================================================================================
    String hostName = "10.251.5.14";
    VMware.create(hostName, 443, "SIVEO\\Administrateur", "Clmdp@09", false, -1L);

    // ===================================================================================
    // Get all ResourcePool from the VC
    // ===================================================================================
    ArrayList<TreeNode> listOfTreenodes = new ArrayList<TreeNode>();

    //InventoryManager inventoryManager=InventoryManager.getInstance();
    //listOfTreenodes=inventoryManager.getTreeNodeByType("ResourcePool", hostName);

    VirtualAppManager virtualAppManager = VirtualAppManager.getInstance();

    listOfTreenodes.addAll(virtualAppManager.getAllVApp(hostName));

    // ===================================================================================
    // Create the "Performance Engine"
    // --------------------------------------------------------------
    PerformanceManager performanceManager = PerformanceManager.getInstance();
    Performance performance = performanceManager.create(hostName);

    // ===================================================================================
    // Build the StartTime and the EndTime
    // ===================================================================================
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss:SSSS");
    Calendar curTime = performance.getCurrentDateTime();

    Calendar startTime = (Calendar) curTime.clone();
    startTime.set(Calendar.HOUR_OF_DAY, 23);
    startTime.set(Calendar.MINUTE, 00);
    startTime.set(Calendar.SECOND, 00);
    startTime.set(Calendar.MILLISECOND, 00);
    startTime.set(Calendar.HOUR_OF_DAY, startTime.get(Calendar.HOUR_OF_DAY) - 1);

    Calendar endTime = (Calendar) curTime.clone();
    endTime.set(Calendar.HOUR_OF_DAY, 22);
    endTime.set(Calendar.MINUTE, 59);
    endTime.set(Calendar.SECOND, 59);
    endTime.set(Calendar.MILLISECOND, 00);
    endTime.set(Calendar.HOUR_OF_DAY, endTime.get(Calendar.HOUR_OF_DAY) - 1);

    startTime.roll(Calendar.DATE, -2);
    endTime.roll(Calendar.DATE, -1);

    System.out.println("StartTime: " + dateFormat.format(startTime.getTime()));
    System.out.println("EndTime: " + dateFormat.format(endTime.getTime()));

    // #########################################################

    // ===================================================================================
    // ResourcePool Performance Counters Collect
    // ===================================================================================

    // --------------------------------------------------------------
    // Build the PerfMetrics from the Host Performance Counters
    // --------------------------------------------------------------
    PerfMetricId[] arrayOfPerfMetricId = null;

    /*/*from  w  w  w . j  av  a 2  s  .  co m*/
    HashMap<Integer,PerfCounterInfo> mapPerf=performance.getMapOfPerfCounterInfoByIdByVC().get(hostName);
            
    System.out.println("Nb PerfCounterInfo: "+mapPerf.size());
            
    PerfMetricId perfMetricId=null;
            
    ArrayList<PerfMetricId> listOfPerfMetricIds=new ArrayList<PerfMetricId>();
            
    for (Map.Entry<Integer,PerfCounterInfo> entry:mapPerf.entrySet())
    {
       perfMetricId=new PerfMetricId();
       perfMetricId.setCounterId(entry.getKey());
       perfMetricId.setInstance("*");
       listOfPerfMetricIds.add(perfMetricId);
    }
            
    System.out.println("Nb PerfMetric: "+listOfPerfMetricIds.size());
            
            
    if (!listOfPerfMetricIds.isEmpty())
    {
       arrayOfPerfMetricId=(listOfPerfMetricIds.toArray(new PerfMetricId[listOfPerfMetricIds.size()]));   
    }
    */

    // --------------------------------------------------------------
    // Build the PerfMetrics from the Host Performance Counters
    // --------------------------------------------------------------
    HashMap<String, String> mapOfInstanceByCounterName = new HashMap<String, String>();

    mapOfInstanceByCounterName.put("cpu.cpuentitlement.latest", "");
    mapOfInstanceByCounterName.put("cpu.usagemhz.average", "");
    mapOfInstanceByCounterName.put("mem.consumed.average", "");
    mapOfInstanceByCounterName.put("mem.mementitlement.latest", "");
    mapOfInstanceByCounterName.put("mem.overhead.average", "");
    mapOfInstanceByCounterName.put("mem.vmmemctl.average", "");

    //PerfMetricId[] arrayOfPerfMetricId=performance.getPerfMetric(this.getResourcePoolPerformanceCounters());
    arrayOfPerfMetricId = performance.getPerfMetric(mapOfInstanceByCounterName);

    // --------------------------------------------------------------
    // Build the PerfQuerySpecs from the Host PerfMetrics
    // --------------------------------------------------------------
    int refreshRate = 300;
    PerfQuerySpec[] arrayOfPerfQuerySpecs = performance.getQueryPerfSpec(listOfTreenodes, arrayOfPerfMetricId,
            null, null, refreshRate);
    //PerfQuerySpec[]  arrayOfPerfQuerySpecs=performance.getQueryPerfSpec(listOfTreenodes, arrayOfPerfMetricId, startTime, endTime, refreshRate);

    // --------------------------------------------------------------
    // Retrieve the Performance Counter Values
    // --------------------------------------------------------------
    ArrayList<PerfMetric> listOfPerfMetrics = null;
    ArrayList<PerfResult> listOfPerfResults = null;
    listOfPerfResults = performance.getPerf(arrayOfPerfQuerySpecs);
    System.out.println("listOfPerfResults: " + listOfPerfResults.size());

    if (!listOfPerfResults.isEmpty()) {
        System.out.println("\n\n\n########## PerfResult ##########");

        for (PerfResult perfResult : listOfPerfResults) {
            System.out.println("- Sampling Interval: " + perfResult.getSamplingRate());
            System.out.println("- Sampling Period: " + perfResult.getSamplingPeriod());
            System.out.println("- Entity: " + perfResult.getEntity().getName() + " / "
                    + perfResult.getEntity().getMor().get_value() + " / "
                    + perfResult.getEntity().getMor().getType());

            listOfPerfMetrics = perfResult.getListOfPerfMetrics();
            if (!listOfPerfMetrics.isEmpty()) {
                System.out.println("- Metrics:");

                for (PerfMetric perfMetric : listOfPerfMetrics) {
                    System.out.println(
                            " - Counter: " + perfMetric.getCounterName() + " / " + perfMetric.getInstance());
                    System.out.println(" - Values: " + perfMetric.getValues());
                }

            }

            System.out.println("");

        }
    }

    // ===================================================================================
    // Destroy the VC connection
    // ===================================================================================
    VMware.delete(hostName);

}

From source file:net.siveo.virtualization.vmware.Main.java

public void getDatacenterPerf() throws VMwareException {
    // =========================================================================================
    // Cration de la connexion au VirtualCenter
    // =========================================================================================
    //String hostName="192.168.101.79";
    //VMware.create(hostName,443,"svc-siveo","S1v30d6m3",false,-1L,1000L);

    //String hostName="vsphere-4-1";
    //VMware.create(hostName,443,"Administrateur","Gd@jJ2009$",false,-1L);

    String hostName = "10.251.5.14";
    VMware.create(hostName, 443, "SIVEO\\Administrateur", "Clmdp@09", false, -1L);

    //String hostName="192.168.101.179";
    //VMware.create(hostName,443,"svc-siveodev","KzT$g#h4",false,-1L);

    // =========================================================================================
    // /*from  ww  w  .  j a va 2 s . c  om*/
    // =========================================================================================
    WSManager wsManager = WSManager.getInstance();
    WS ws = wsManager.getWS(hostName);

    Calendar curTime = null;
    try {
        curTime = ws.getVIMService().getService().currentTime(ws.getVIMService().getServiceInstance());
    } catch (RuntimeFault e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (RemoteException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    DatacenterManager datacenterManager = DatacenterManager.getInstance();
    ArrayList<Datacenter> listOfDatacenter = datacenterManager.getAllDatacenter(hostName);
    ArrayList<TreeNode> listOfTreeNodes = new ArrayList<TreeNode>();

    if (listOfDatacenter != null && !listOfDatacenter.isEmpty()) {
        for (Datacenter datacenter : listOfDatacenter) {
            listOfTreeNodes.add((TreeNode) datacenter);
        }
    }

    Calendar startTime = (Calendar) curTime.clone();
    //startTime.roll(Calendar.DATE, -1);

    PerformanceManager performanceManager = PerformanceManager.getInstance();
    performanceManager.init(hostName);

    performanceManager.getPerfDC(listOfTreeNodes, startTime, null, 300);

    // =========================================================================================
    // Destruction de la connexion au VirtualCenter
    // =========================================================================================
    VMware.delete(hostName);

}

From source file:net.siveo.virtualization.vmware.Main.java

public void getDatastorePerf() throws VMwareException {
    // =========================================================================================
    // Cration de la connexion au VirtualCenter
    // =========================================================================================
    //String hostName="192.168.101.79";
    //VMware.create(hostName,443,"svc-siveo","S1v30d6m3",false,-1L,1000L);

    //String hostName="vsphere-4-1";
    //VMware.create(hostName,443,"Administrateur","Gd@jJ2009$",false,-1L);

    String hostName = "10.251.5.14";
    VMware.create(hostName, 443, "SIVEO\\Administrateur", "Clmdp@09", false, -1L);

    //String hostName="192.168.101.179";
    //VMware.create(hostName,443,"svc-siveodev","KzT$g#h4",false,-1L);

    WSManager wsManager = WSManager.getInstance();
    WS ws = wsManager.getWS(hostName);/* w w  w. j  ava  2 s. c o m*/

    // =========================================================================================
    // Initialize Variables
    // =========================================================================================
    // Initialize the Performance Engine
    PerformanceManager performanceManager = PerformanceManager.getInstance();
    performanceManager.init(hostName);

    DataStoreManager dataStoreManager = DataStoreManager.getInstance();
    //Datastore datastore=dataStoreManager.getDatastoreByName("VCE-AMP-2", hostName);
    Datastore datastore = dataStoreManager.getDatastoreByName("SIVEO_ADMIN", hostName);
    System.out.println("DataStore: " + datastore.getMor().get_value());

    // Get the Performance Counters
    PerfMetricId[] arrayOfPerfMetricIds = null;
    PerfQuerySpec[] arrayOfPerfQuerySpecs = null;
    DataStoreManager dsManager = DataStoreManager.getInstance();

    HashMap<Integer, PerfCounterInfo> mapOfPerfCounterInfoByID = performanceManager
            .getMapOfPerfCounterInfoByIdByVC().get(hostName);

    // =========================================================================================
    // Get Datastore Performance Counters
    // =========================================================================================
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss:SSSS");
    Calendar curTime = null;

    try {
        curTime = ws.getVIMService().getService().currentTime(ws.getVIMService().getServiceInstance());
    } catch (RuntimeFault e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (RemoteException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //System.out.println("curTime: "+curTime);
    //System.out.println("curTime: "+curTime.getTime());
    //System.out.println("curTime timeZone: "+curTime.getTimeZone());
    //System.out.println("curTime timeZone: "+curTime.getTimeZone().getDisplayName());
    //System.out.println("curTime timeZone id: "+curTime.getTimeZone().getID());
    //System.out.println("curTime lenient: "+curTime.isLenient());

    Calendar startTime = (Calendar) curTime.clone();
    //startTime.set(Calendar.HOUR_OF_DAY, startTime.get(Calendar.HOUR_OF_DAY)-1);

    startTime.set(Calendar.HOUR_OF_DAY, 23);
    startTime.set(Calendar.MINUTE, 30);
    startTime.set(Calendar.SECOND, 00);
    startTime.set(Calendar.MILLISECOND, 00);
    startTime.set(Calendar.HOUR_OF_DAY, startTime.get(Calendar.HOUR_OF_DAY) - 1);

    Calendar endTime = (Calendar) curTime.clone();
    endTime.set(Calendar.HOUR_OF_DAY, 23);
    endTime.set(Calendar.MINUTE, 59);
    endTime.set(Calendar.SECOND, 59);
    endTime.set(Calendar.MILLISECOND, 00);
    endTime.set(Calendar.HOUR_OF_DAY, endTime.get(Calendar.HOUR_OF_DAY) - 1);

    startTime.roll(Calendar.DATE, -2);
    endTime.roll(Calendar.DATE, -1);

    //System.out.println("Ecart entre dbut et fin: "+(endTime.getTime().getTime()-startTime.getTime().getTime()));

    for (String counterName : this.getDatastorePerformanceCountersName()) {
        System.out.println("Counter: " + counterName);
    }

    arrayOfPerfMetricIds = performanceManager
            .getPerfMetricFromCounterNames(this.getDatastorePerformanceCountersName(), false, hostName);
    arrayOfPerfQuerySpecs = performanceManager.getDSQueryPerfSpec(dsManager.getAllDatastore(hostName),
            arrayOfPerfMetricIds, startTime, endTime);

    PerfCounterInfo perfCounterInfo = null;

    for (PerfMetricId perfMetricId : arrayOfPerfMetricIds) {
        if (mapOfPerfCounterInfoByID.containsKey(perfMetricId.getCounterId())) {
            perfCounterInfo = mapOfPerfCounterInfoByID.get(perfMetricId.getCounterId());
            System.out.println("Metric: " + perfMetricId.getCounterId() + "/"
                    + perfCounterInfo.getGroupInfo().getKey() + "." + perfCounterInfo.getNameInfo().getKey()
                    + "." + perfCounterInfo.getRollupType().name());
        }
    }

    System.out.println("StartTime: " + dateFormat.format(startTime.getTime()));
    System.out.println("EndTime: " + dateFormat.format(endTime.getTime()));

    performanceManager.getPerfDS(hostName, arrayOfPerfQuerySpecs);

    // =========================================================================================
    // Destruction de la connexion au VirtualCenter
    // =========================================================================================
    VMware.delete(hostName);

}

From source file:net.siveo.virtualization.vmware.Main.java

public void getDatacenterPerf_() throws VMwareException {
    // =========================================================================================
    // Cration de la connexion au VirtualCenter
    // =========================================================================================
    //String hostName="192.168.101.79";
    //VMware.create(hostName,443,"svc-siveo","S1v30d6m3",false,-1L,1000L);

    //String hostName="vsphere-4-1";
    //VMware.create(hostName,443,"Administrateur","Gd@jJ2009$",false,-1L);

    String hostName = "10.251.5.14";
    VMware.create(hostName, 443, "SIVEO\\Administrateur", "Clmdp@09", false, -1L);

    //String hostName="192.168.101.179";
    //VMware.create(hostName,443,"svc-siveodev","KzT$g#h4",false,-1L);

    WSManager wsManager = WSManager.getInstance();
    WS ws = wsManager.getWS(hostName);//from   www.ja  v  a 2  s  .  c  o  m

    // =========================================================================================
    // Construction des dates de Dpart de Fin pour la collecte des statistiques
    // =========================================================================================
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss:SSSS");
    Calendar curTime = null;

    try {
        curTime = ws.getVIMService().getService().currentTime(ws.getVIMService().getServiceInstance());
    } catch (RuntimeFault e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (RemoteException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //System.out.println("curTime: "+curTime);
    //System.out.println("curTime: "+curTime.getTime());
    //System.out.println("curTime timeZone: "+curTime.getTimeZone());
    //System.out.println("curTime timeZone: "+curTime.getTimeZone().getDisplayName());
    //System.out.println("curTime timeZone id: "+curTime.getTimeZone().getID());
    //System.out.println("curTime lenient: "+curTime.isLenient());

    Calendar startTime = (Calendar) curTime.clone();
    //startTime.set(Calendar.HOUR_OF_DAY, startTime.get(Calendar.HOUR_OF_DAY)-1);

    startTime.set(Calendar.HOUR_OF_DAY, 23);
    startTime.set(Calendar.MINUTE, 30);
    startTime.set(Calendar.SECOND, 00);
    startTime.set(Calendar.MILLISECOND, 00);
    startTime.set(Calendar.HOUR_OF_DAY, startTime.get(Calendar.HOUR_OF_DAY) - 1);

    Calendar endTime = (Calendar) curTime.clone();
    endTime.set(Calendar.HOUR_OF_DAY, 23);
    endTime.set(Calendar.MINUTE, 59);
    endTime.set(Calendar.SECOND, 59);
    endTime.set(Calendar.MILLISECOND, 00);
    endTime.set(Calendar.HOUR_OF_DAY, endTime.get(Calendar.HOUR_OF_DAY) - 1);

    startTime.roll(Calendar.DATE, -2);
    endTime.roll(Calendar.DATE, -1);

    System.out.println("StartTime: " + dateFormat.format(startTime.getTime()));
    System.out.println("EndTime: " + dateFormat.format(endTime.getTime()));

    // =========================================================================================
    // 
    // =========================================================================================
    ArrayList<TreeNode> listOfTreeNodes = new ArrayList<TreeNode>();

    DatacenterManager datacenterManager = DatacenterManager.getInstance();
    Datacenter datacenter = datacenterManager.getDatacenterByName("RISC_POC", hostName);
    listOfTreeNodes.add(datacenter);

    System.out.println("Datacenter: " + datacenter.getMor().get_value());

    // Initialize the Performance Engine
    PerformanceManager performanceManager = PerformanceManager.getInstance();
    performanceManager.init(hostName);

    // =========================================================================================
    // 
    // =========================================================================================
    //PerfMetricId[] arrOfPerfMetricIds=null;
    //arrOfPerfMetricIds=performanceManager.getAvailablePerfCounter(datacenter, null, null, 300);

    // Get the Performance Counters
    PerfMetricId[] arrayOfPerfMetricIds = null;
    PerfQuerySpec[] arrayOfPerfQuerySpecs = null;

    HashMap<Integer, PerfCounterInfo> mapOfPerfCounterInfoByID = performanceManager
            .getMapOfPerfCounterInfoByIdByVC().get(hostName);

    arrayOfPerfMetricIds = performanceManager
            .getPerfMetricFromCounterNames(this.getDatacenterPerformanceCounters(), false, hostName);
    arrayOfPerfQuerySpecs = performanceManager.getQueryPerfSpec(listOfTreeNodes, arrayOfPerfMetricIds,
            startTime, endTime, 300);

    /*
    PerfCounterInfo perfCounterInfo=null;
    for (PerfMetricId perfMetricId:arrayOfPerfMetricIds)
    {
       if (mapOfPerfCounterInfoByID.containsKey(perfMetricId.getCounterId()))
       {
    perfCounterInfo=mapOfPerfCounterInfoByID.get(perfMetricId.getCounterId());
    System.out.println("Metric: "+perfMetricId.getCounterId()+"/"+perfCounterInfo.getGroupInfo().getKey()+"."+perfCounterInfo.getNameInfo().getKey()+"."+perfCounterInfo.getRollupType().name());
       }
    }
    */

    performanceManager.getPerf(hostName, arrayOfPerfQuerySpecs);

    // =========================================================================================
    // Destruction de la connexion au VirtualCenter
    // =========================================================================================
    VMware.delete(hostName);

}

From source file:net.siveo.virtualization.vmware.Main.java

public void getClusterPerf() throws VMwareException {
    // =========================================================================================
    // Cration de la connexion au VirtualCenter
    // =========================================================================================
    //String hostName="192.168.101.79";
    //VMware.create(hostName,443,"svc-siveo","S1v30d6m3",false,-1L,1000L);

    //String hostName="vsphere-4-1";
    //VMware.create(hostName,443,"Administrateur","Gd@jJ2009$",false,-1L);

    String hostName = "10.251.5.14";
    VMware.create(hostName, 443, "SIVEO\\Administrateur", "Clmdp@09", false, -1L);

    //String hostName="192.168.101.179";
    //VMware.create(hostName,443,"svc-siveodev","KzT$g#h4",false,-1L);

    WSManager wsManager = WSManager.getInstance();
    WS ws = wsManager.getWS(hostName);//from  ww  w. j av  a 2  s . com

    // =========================================================================================
    // Construction des dates de Dpart de Fin pour la collecte des statistiques
    // =========================================================================================
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss:SSSS");
    Calendar curTime = null;

    try {
        curTime = ws.getVIMService().getService().currentTime(ws.getVIMService().getServiceInstance());
    } catch (RuntimeFault e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (RemoteException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    //System.out.println("curTime: "+curTime);
    //System.out.println("curTime: "+curTime.getTime());
    //System.out.println("curTime timeZone: "+curTime.getTimeZone());
    //System.out.println("curTime timeZone: "+curTime.getTimeZone().getDisplayName());
    //System.out.println("curTime timeZone id: "+curTime.getTimeZone().getID());
    //System.out.println("curTime lenient: "+curTime.isLenient());

    Calendar startTime = (Calendar) curTime.clone();
    //startTime.set(Calendar.HOUR_OF_DAY, startTime.get(Calendar.HOUR_OF_DAY)-1);

    startTime.set(Calendar.HOUR_OF_DAY, 23);
    startTime.set(Calendar.MINUTE, 30);
    startTime.set(Calendar.SECOND, 00);
    startTime.set(Calendar.MILLISECOND, 00);
    startTime.set(Calendar.HOUR_OF_DAY, startTime.get(Calendar.HOUR_OF_DAY) - 1);

    Calendar endTime = (Calendar) curTime.clone();
    endTime.set(Calendar.HOUR_OF_DAY, 23);
    endTime.set(Calendar.MINUTE, 59);
    endTime.set(Calendar.SECOND, 59);
    endTime.set(Calendar.MILLISECOND, 00);
    endTime.set(Calendar.HOUR_OF_DAY, endTime.get(Calendar.HOUR_OF_DAY) - 1);

    startTime.roll(Calendar.DATE, -2);
    endTime.roll(Calendar.DATE, -1);

    System.out.println("StartTime: " + dateFormat.format(startTime.getTime()));
    System.out.println("EndTime: " + dateFormat.format(endTime.getTime()));

    // =========================================================================================
    // 
    // =========================================================================================
    ArrayList<TreeNode> listOfTreeNodes = new ArrayList<TreeNode>();

    ResourceManager resourceManager = ResourceManager.getInstance();
    ClusterComputeResource cluster = resourceManager.getClusterComputeResourceByName("SIVEO", hostName);
    listOfTreeNodes.add(cluster);

    System.out.println("Cluster: " + cluster.getMor().get_value());

    // Initialize the Performance Engine
    PerformanceManager performanceManager = PerformanceManager.getInstance();
    performanceManager.init(hostName);

    // =========================================================================================
    // 
    // =========================================================================================
    //PerfMetricId[] arrOfPerfMetricIds=null;
    //arrOfPerfMetricIds=performanceManager.getAvailablePerfCounter(datacenter, null, null, 300);
    performanceManager.getAvailablePerfCounter(cluster, null, null, 300);

    // Get the Performance Counters
    PerfMetricId[] arrayOfPerfMetricIds = null;
    PerfQuerySpec[] arrayOfPerfQuerySpecs = null;

    HashMap<Integer, PerfCounterInfo> mapOfPerfCounterInfoByID = performanceManager
            .getMapOfPerfCounterInfoByIdByVC().get(hostName);

    arrayOfPerfMetricIds = performanceManager
            .getPerfMetricFromCounterNames(this.getClusterPerformanceCounters(), true, hostName);
    arrayOfPerfQuerySpecs = performanceManager.getQueryPerfSpec(listOfTreeNodes, arrayOfPerfMetricIds,
            startTime, endTime, 300);

    /*
    PerfCounterInfo perfCounterInfo=null;
    for (PerfMetricId perfMetricId:arrayOfPerfMetricIds)
    {
       if (mapOfPerfCounterInfoByID.containsKey(perfMetricId.getCounterId()))
       {
    perfCounterInfo=mapOfPerfCounterInfoByID.get(perfMetricId.getCounterId());
    System.out.println("Metric: "+perfMetricId.getCounterId()+"/"+perfCounterInfo.getGroupInfo().getKey()+"."+perfCounterInfo.getNameInfo().getKey()+"."+perfCounterInfo.getRollupType().name());
       }
    }
    */

    performanceManager.getPerf(hostName, arrayOfPerfQuerySpecs);

    // =========================================================================================
    // Destruction de la connexion au VirtualCenter
    // =========================================================================================
    VMware.delete(hostName);

}