Example usage for java.text DateFormat getDateInstance

List of usage examples for java.text DateFormat getDateInstance

Introduction

In this page you can find the example usage for java.text DateFormat getDateInstance.

Prototype

public static final DateFormat getDateInstance(int style) 

Source Link

Document

Gets the date formatter with the given formatting style for the default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:chibi.gemmaanalysis.ExperimentMetaDataExtractorCli.java

public void generateExperimentMetaData(Collection<BioAssaySet> expressionExperiments) throws IOException {

    File file = getOutputFile(this.viewFile);

    try (Writer writer = new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(file)));) {

        String[] colNames = { "ShortName", "Taxon", "DateUpload", "IsPublic", "NumPlatform", "Platform",
                "Channel", "IsExonArray", "QtIsRatio", "QtIsNormalized", "QtScale", "NumProfiles",
                "NumFilteredProfiles", "NumSamples", "NumConditions", "NumReplicatesPerCondition",
                "PossibleOutliers", "CuratedOutlier", "IsTroubled", "PubTroubled", "PubYear", "PubJournal",
                "Batch.PC1.Var", "Batch.PC2.Var", "Batch.PC3.Var", "Batch.PC1.Pval", "Batch.PC2.Pval",
                "Batch.PC3.Pval", "NumFactors", "FactorNames", "FactorCategories", "NumFactorValues" };
        // log.info( StringUtils.join( colNames, "\t" ) + "\n" );
        writer.write(StringUtils.join(colNames, "\t") + "\n");

        int i = 0;
        Collection<String> failedEEs = new ArrayList<>();

        StopWatch timer = new StopWatch();
        timer.start();/*from   w ww  . jav  a  2s .  c o  m*/

        for (BioAssaySet bas : expressionExperiments) {
            /*
             * Skip subsets
             */
            if (bas instanceof ExpressionExperimentSubSet)
                return;

            try {

                ExpressionExperiment ee = (ExpressionExperiment) bas;
                ee = eeService.thawLite(ee);
                ExpressionExperimentValueObject vo = eeService.loadValueObject(ee.getId());
                vo.setIsPublic(!securityService.isPrivate(ee));
                log.info("Processing (" + ++i + "/" + expressionExperiments.size() + ") : " + ee);

                BibliographicReference primaryPublication = ee.getPrimaryPublication();
                Status pubStatus = primaryPublication != null ? statusService.getStatus(primaryPublication)
                        : null;
                Collection<ArrayDesign> arrayDesignsUsed = eeService.getArrayDesignsUsed(ee);

                Collection<String> arrayDesignIsExon = new ArrayList<>();
                Collection<String> arrayDesignTechTypes = new ArrayList<>();
                Collection<String> arrayDesignShortNames = new ArrayList<>();

                // for multiple platforms e.g. GSE5949
                for (ArrayDesign ad : arrayDesignsUsed) {
                    arrayDesignShortNames.add(ad.getShortName());
                    arrayDesignTechTypes.add(ad.getTechnologyType().getValue());
                    arrayDesignIsExon.add(ad.getName().toLowerCase().contains("exon") + "");
                }

                QuantitationType qt = null;
                for (QuantitationType q : ee.getQuantitationTypes()) {
                    if (q.getIsPreferred().booleanValue()) {
                        qt = q;
                        break;
                    }
                }

                int manualOutlierCount = 0;
                for (BioAssay ba : ee.getBioAssays()) {
                    if (ba.getIsOutlier().booleanValue()) {
                        manualOutlierCount++;
                    }
                }

                ExperimentalDesign experimentalDesign = edService.load(vo.getExperimentalDesign());

                // Batch PCs
                int maxcomp = 3;
                BatchEffectDetails batchEffectPC1 = null;
                BatchEffectDetails batchEffectPC2 = null;
                BatchEffectDetails batchEffectPC3 = null;
                Collection<BatchEffectDetails> batchEffects = getBatchEffect(ee, maxcomp);
                Iterator<BatchEffectDetails> batchEffectsIterator;
                if (batchEffects == null || batchEffects.size() == 0) {
                    log.warn("No batch effect info");
                } else {
                    batchEffectsIterator = batchEffects.iterator();
                    if (batchEffectsIterator.hasNext()) {
                        batchEffectPC1 = batchEffectsIterator.next();
                    }
                    if (batchEffectsIterator.hasNext()) {
                        batchEffectPC2 = batchEffectsIterator.next();
                    }
                    if (batchEffectsIterator.hasNext()) {
                        batchEffectPC3 = batchEffectsIterator.next();
                    }
                }

                // eeService.getExperimentsWithOutliers();
                StopWatch timerOutlier = new StopWatch();
                timerOutlier.start();
                // log.info( "Outlier detection service started " + timer.getTime() + "ms" );
                Collection<OutlierDetails> possibleOutliers = outlierDetectionService.identifyOutliers(ee);
                if (timerOutlier.getTime() > 10000) {
                    log.info("Automatic outlier detection took " + timerOutlier.getTime() + "ms");
                }
                // Collection<OutlierDetails> possibleOutliers = null;

                // samples per condition
                boolean removeBatchFactor = false;
                Collection<String> samplesPerConditionCount = new ArrayList<>();
                CountingMap<FactorValueVector> assayCount = ExperimentalDesignUtils.getDesignMatrix(ee,
                        removeBatchFactor);
                List<FactorValueVector> keys = assayCount.sortedKeyList(true);
                for (FactorValueVector key : keys) {
                    samplesPerConditionCount.add(Integer.toString(assayCount.get(key).intValue()));
                }

                // factor names
                Collection<ExperimentalFactor> factors = ee.getExperimentalDesign().getExperimentalFactors();
                Collection<String> factorNames = new ArrayList<>();
                Collection<String> factorCategories = new ArrayList<>();
                Collection<Integer> factorValues = new ArrayList<>();
                for (ExperimentalFactor f : factors) {
                    factorNames.add(f.getName());
                    String cat = f.getCategory() != null ? f.getCategory().getCategory() : NA;
                    factorCategories.add(cat);
                    factorValues.add(Integer.valueOf(f.getFactorValues().size()));
                }

                int filteredProfilesCount = -1;

                try {
                    FilterConfig filterConfig = new FilterConfig();
                    filterConfig.setIgnoreMinimumSampleThreshold(true);
                    filteredProfilesCount = expressionDataMatrixService.getFilteredMatrix(ee, filterConfig,
                            expressionDataMatrixService.getProcessedExpressionDataVectors(ee)).rows();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }

                String val[] = { vo.getShortName(), vo.getTaxon(),
                        DateFormat.getDateInstance(DateFormat.MEDIUM).format(vo.getDateCreated()),
                        vo != null ? Boolean.toString(vo.getIsPublic()) : NA,
                        Integer.toString(arrayDesignsUsed.size()), StringUtils.join(arrayDesignShortNames, ','),
                        StringUtils.join(arrayDesignTechTypes, ','), // arrayDesign.getTechnologyType().getValue(),
                        // ONE-COLOR, TWO-COLOR, NONE (RNA-seq
                        // GSE37646), DUAL-MODE (one or two color)
                        StringUtils.join(arrayDesignIsExon, ','), // exon GSE28383
                        qt != null ? Boolean.toString(qt.getIsRatio().booleanValue()) : NA,
                        qt != null ? Boolean.toString(qt.getIsNormalized().booleanValue()) : NA,
                        qt != null ? qt.getScale().getValue() : NA,
                        Integer.toString(vo.getProcessedExpressionVectorCount().intValue()), // NumProfiles
                        Integer.toString(filteredProfilesCount), // NumFilteredProfiles
                        Integer.toString(vo.getBioAssayCount().intValue()), // NumSamples
                        Integer.toString(assayCount.size()), // NumConditions
                        StringUtils.join(samplesPerConditionCount, ","),
                        possibleOutliers != null ? Integer.toString(possibleOutliers.size()) : NA,
                        Integer.toString(manualOutlierCount), Boolean.toString(vo.getTroubled()),
                        pubStatus != null ? Boolean.toString(pubStatus.getTroubled().booleanValue()) : NA,
                        primaryPublication != null ? DateFormat.getDateInstance(DateFormat.MEDIUM)
                                .format(primaryPublication.getPublicationDate()) : NA,
                        primaryPublication != null ? primaryPublication.getPublication() : NA,

                        batchEffectPC1 != null
                                ? Double.toString(batchEffectPC1.getComponentVarianceProportion())
                                : NA,
                        batchEffectPC2 != null
                                ? Double.toString(batchEffectPC2.getComponentVarianceProportion())
                                : NA,
                        batchEffectPC3 != null
                                ? Double.toString(batchEffectPC3.getComponentVarianceProportion())
                                : NA,

                        batchEffectPC1 != null ? Double.toString(batchEffectPC1.getPvalue()) : NA,
                        batchEffectPC2 != null ? Double.toString(batchEffectPC2.getPvalue()) : NA,
                        batchEffectPC3 != null ? Double.toString(batchEffectPC3.getPvalue()) : NA,

                        // factors
                        factors != null ? Integer.toString(factors.size()) : NA, // NumFactors
                        factorNames != null ? StringUtils.join(factorNames, ",") : NA,
                        factorCategories != null ? StringUtils.join(factorCategories, ",") : NA,
                        factorValues != null ? StringUtils.join(factorValues, ",") : NA,

                };

                // log.info( StringUtils.join( val, "\t" ) + "\n" );
                writer.write(StringUtils.join(val, "\t") + "\n");

            } catch (Exception e) {
                failedEEs.add(((ExpressionExperiment) bas).getShortName());
                StringWriter sw = new StringWriter();
                e.printStackTrace(new PrintWriter(sw));
                log.error(sw.toString());
            }
        }

        log.info("Finished processing " + expressionExperiments.size() + " datasets in " + timer.getTime()
                + " ms. ");
        log.info("Writen to " + file);
        log.info("Number of failed experiment metadata extraction(s): " + failedEEs.size() + " / "
                + expressionExperiments.size());

        if (failedEEs.size() > 0) {
            log.info("Skipped experiments:");
            log.info(StringUtils.join(failedEEs, ","));
        }
    }
}

From source file:com.cachirulop.moneybox.activity.MovementDetailActivity.java

/**
 * Update the insert date field of the window with the value of the movement
 * object.// w  w w  .java  2 s.  co m
 */
private void updateInsertDate() {
    TextView txt;

    txt = (TextView) findViewById(R.id.txtDate);
    txt.setText(DateFormat.getDateInstance(DateFormat.MEDIUM).format(_movement.getInsertDate()));
}

From source file:com.examples.with.different.packagename.testcarver.DateTimeConverter.java

/**
 * Return a <code>DateFormat<code> for the Locale.
 * @param locale The Locale to create the Format with (may be null)
 * @param timeZone The Time Zone create the Format with (may be null)
 *
 * @return A Date Format.//from ww w.j  a  v  a  2  s  .  c  om
 */
protected DateFormat getFormat(Locale locale, TimeZone timeZone) {
    DateFormat format = null;
    if (locale == null) {
        format = DateFormat.getDateInstance(DateFormat.SHORT);
    } else {
        format = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    }
    if (timeZone != null) {
        format.setTimeZone(timeZone);
    }
    return format;
}

From source file:org.nuxeo.ecm.core.storage.sql.coremodel.SQLSession.java

@Override
public Document importDocument(String uuid, Document parent, String name, String typeName,
        Map<String, Serializable> properties) throws DocumentException {
    assert Model.PROXY_TYPE == CoreSession.IMPORT_PROXY_TYPE;
    boolean isProxy = typeName.equals(Model.PROXY_TYPE);
    Map<String, Serializable> props = new HashMap<String, Serializable>();
    Long pos = null; // TODO pos
    if (!isProxy) {
        // version & live document
        props.put(Model.MISC_LIFECYCLE_POLICY_PROP, properties.get(CoreSession.IMPORT_LIFECYCLE_POLICY));
        props.put(Model.MISC_LIFECYCLE_STATE_PROP, properties.get(CoreSession.IMPORT_LIFECYCLE_STATE));
        // compat with old lock import
        @SuppressWarnings("deprecation")
        String key = (String) properties.get(CoreSession.IMPORT_LOCK);
        if (key != null) {
            String[] values = key.split(":");
            if (values.length == 2) {
                String owner = values[0];
                Calendar created = new GregorianCalendar();
                try {
                    created.setTimeInMillis(
                            DateFormat.getDateInstance(DateFormat.MEDIUM).parse(values[1]).getTime());
                } catch (ParseException e) {
                    // use current date
                }//w  w  w .  j ava  2 s.c o m
                props.put(Model.LOCK_OWNER_PROP, owner);
                props.put(Model.LOCK_CREATED_PROP, created);
            }
        }

        Serializable importLockOwnerProp = properties.get(CoreSession.IMPORT_LOCK_OWNER);
        if (importLockOwnerProp != null) {
            props.put(Model.LOCK_OWNER_PROP, importLockOwnerProp);
        }
        Serializable importLockCreatedProp = properties.get(CoreSession.IMPORT_LOCK_CREATED);
        if (importLockCreatedProp != null) {
            props.put(Model.LOCK_CREATED_PROP, importLockCreatedProp);
        }

        props.put(Model.MAIN_MAJOR_VERSION_PROP, properties.get(CoreSession.IMPORT_VERSION_MAJOR));
        props.put(Model.MAIN_MINOR_VERSION_PROP, properties.get(CoreSession.IMPORT_VERSION_MINOR));
        props.put(Model.MAIN_IS_VERSION_PROP, properties.get(CoreSession.IMPORT_IS_VERSION));
    }
    Node parentNode;
    if (parent == null) {
        // version
        parentNode = null;
        props.put(Model.VERSION_VERSIONABLE_PROP,
                idFromString((String) properties.get(CoreSession.IMPORT_VERSION_VERSIONABLE_ID)));
        props.put(Model.VERSION_CREATED_PROP, properties.get(CoreSession.IMPORT_VERSION_CREATED));
        props.put(Model.VERSION_LABEL_PROP, properties.get(CoreSession.IMPORT_VERSION_LABEL));
        props.put(Model.VERSION_DESCRIPTION_PROP, properties.get(CoreSession.IMPORT_VERSION_DESCRIPTION));
        props.put(Model.VERSION_IS_LATEST_PROP, properties.get(CoreSession.IMPORT_VERSION_IS_LATEST));
        props.put(Model.VERSION_IS_LATEST_MAJOR_PROP,
                properties.get(CoreSession.IMPORT_VERSION_IS_LATEST_MAJOR));
    } else {
        parentNode = ((SQLDocument) parent).getNode();
        if (isProxy) {
            // proxy
            props.put(Model.PROXY_TARGET_PROP,
                    idFromString((String) properties.get(CoreSession.IMPORT_PROXY_TARGET_ID)));
            props.put(Model.PROXY_VERSIONABLE_PROP,
                    idFromString((String) properties.get(CoreSession.IMPORT_PROXY_VERSIONABLE_ID)));
        } else {
            // live document
            props.put(Model.MAIN_BASE_VERSION_PROP,
                    idFromString((String) properties.get(CoreSession.IMPORT_BASE_VERSION_ID)));
            props.put(Model.MAIN_CHECKED_IN_PROP, properties.get(CoreSession.IMPORT_CHECKED_IN));
        }
    }
    return importChild(uuid, parentNode, name, pos, typeName, props);
}

From source file:org.extensiblecatalog.ncip.v2.millennium.MillenniumLookupUserService.java

/**
 * Handles a NCIP LookupUser service by returning hard-coded data.
 * /*from w ww.  j a  va2 s.co  m*/
 * @param initData
 *            the LookupUserInitiationData
 * @param serviceManager
 *            provides access to remote services
 * @return LookupUserResponseData
 */
@Override
public LookupUserResponseData performService(LookupUserInitiationData initData,
        RemoteServiceManager serviceManager) {

    String baseUrl = "https://" + IIIClassicBaseUrl + "/patroninfo%7ES0/";

    final LookupUserResponseData responseData = new LookupUserResponseData();

    String userId = initData.getUserId().getUserIdentifierValue();

    MillenniumRemoteServiceManager millenniumSvcMgr = (MillenniumRemoteServiceManager) serviceManager;

    String strSessionId = millenniumSvcMgr.getIIISessionId(baseUrl);

    String redirectedUrl = millenniumSvcMgr.authenticate(authenticatedUserName, authenticatedUserPassword,
            baseUrl, strSessionId);

    // if the returned logIntoWebForm isn't null
    if (redirectedUrl != null) {
        // extract the iii id from the URL
        int start = redirectedUrl.indexOf("~S0/");

        // Check to see if we're not redirected to the "top"
        int end = redirectedUrl.indexOf("/top");
        if (end == -1) {
            end = redirectedUrl.indexOf("/items");
        }

        String urid = redirectedUrl.substring(start, end).replace("~S0/", "");

        authenticatedUserId = urid;
    }

    boolean getBlockOrTrap = false;
    boolean getAddress = true;
    boolean getVisibleUserID = true;
    boolean getFines = true;
    boolean getHolds = false;
    boolean getLoans = false;
    boolean getRecalls = false;
    boolean getMessages = false;

    // System.out.println("xcLookupUser authID: " + authenticatedUserId);
    // System.out.println("xcLookupUser redirUrl: " + redirectedUrl);

    // setup lookup method
    GetMethod lookupMethod = new GetMethod(redirectedUrl);
    lookupMethod.addRequestHeader("Cookie", "III_SESSION_ID=" + strSessionId);

    try {
        try {
            client.executeMethod(lookupMethod);
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String html = lookupMethod.getResponseBodyAsString();
        // log.error(html);

        /**
         * Boolean Values to Return as objects
         */

        // TODO xcLookupUser: Finish getBlockOrTrap
        // If getBlockOrTrap is true, the returned users list of blocks
        // must contain all blocks currently placed on the user represented
        // by the userId field.
        if (getBlockOrTrap) {
            // log.debug("Get Block or Trap");
            System.out.println("Todo: Get Block or Trap");
        }

        // TODO xcLookupUser: Finish getAddres (Temp Address) if possible
        // If getMessages is true, the returned users list of messages must
        // contain all messages applying the user represented by the userId

        if (getAddress) {
            // log.debug("Get Address");
            Pattern address = Pattern.compile(
                    "^<span(.*?)class=\"large\">(?s)(.*?)</form>(?s)(.*?)<p>(?s)(.*?)<br />(?s)(.*?)<p>(?s)(.*?)</span>$",
                    Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
            Matcher addressMatch = address.matcher(html);

            addressMatch.find();
            // System.out.println(addressMatch.group(5));

            String strAddress = addressMatch.group(5).replaceAll("<br />", "|").replaceAll("\\n", "")
                    .replaceAll("||", "");
            strAddress = strAddress.replace("||", "");

            // returnUser.setAddress(strAddress);
            System.out.println("Found the home address " + strAddress);
            // + " for the patron with patron ID " + patronId)
            // log.debug("Found the home address " + returnUser.getAddress()
            // + " for the patron with patron ID " + patronId);

        }

        // if true, the user's fullName must be set to the correct value for
        // the user represented by the userId field if this value is known.
        if (getVisibleUserID) {
            // log.debug("get Visible User Id");

            // If there were any results, build the full name string
            Pattern visibleId = Pattern.compile(
                    "^<span(.*?)class=\"large\">(?s)(.*?)</form>(?s)(.*?)<p>(?s)(.*?)<br />(?s)(.*?)<p>(?s)(.*?)</span>$",
                    Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);
            Matcher visibleIdMatch = visibleId.matcher(html);

            visibleIdMatch.find();
            // System.out.println(visibleIdMatch.group(4));

            // Clean up strName, removing tags
            String strName = visibleIdMatch.group(4).replace("<strong>", "").replace("</strong>", "");

            // set full name to strName, removing any unneded whitespaces
            String fullName = strName.trim();

            // Check to make sure it exists
            if (fullName.length() > 1) {

                // setFullName(fullName);
                System.out.println(fullName);

                // log.debug("Found the user's full name to be "
                // + returnUser.getFullName());
            } else {
                // log
                // .info("Could not find the name information for the patron with patron ID "
                // + patronId);
            }

        }

        // TODO xcLookupUser: Finish getFines
        // if true the user's totalFinesCurrencyCode and totalFines fields
        // must be set to the correct values for the user represented by the
        // userId field if these values are known. In addition, the list of
        // fines must contain NCIPUserFine Objects for all fines the user
        // owes.
        if (getFines) {
            // log.debug("get Fines");
            // https://jasmine.uncc.edu/patroninfo~S0/1205433/overdues
            System.out.println("Get Fines");
            // System.out.println("Auth: " + authenticatedUserId);

            html = millenniumSvcMgr.getFines(authenticatedUserId, strSessionId);

            Pattern fines = Pattern.compile(
                    "^(?s)(.*?)<table(.*?)class=\"patFunc\">(?s)(.*?)</table>(?s)(.*?)$",
                    Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);

            Matcher finesMatch = fines.matcher(html);

            if (finesMatch.matches()) {

                finesTable = finesMatch.group(3).toString();

            }

            System.out.println(finesTable);

            System.out.println("==================");

            fines = Pattern.compile("^(?s)(.*?)<tr class=\"patFuncFinesEntryTitle\">(?s)(.*?)</tr>(?s)(.*?)$",
                    Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);

            finesMatch = fines.matcher(finesTable);

            Pattern title = Pattern.compile("^(?s)(.*?)<em>(?s)(.*?)</em></td>(?s)(.*?)$",
                    Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);

            while (finesMatch.find()) {

                //for (int i=0; i < finesMatch.groupCount(); i++) {

                System.out.println(finesMatch.group(2));

                Matcher titleMatch = title.matcher(finesMatch.group(2));
                // Grab the title out of the finesMatch string
                System.out.println("=====");

                if (titleMatch.matches()) {
                    System.out.println(titleMatch.group(2));
                }

                System.out.println("=====");

                //}

            }

            System.out.println("==================");

            /*
             * <table border="1" width="100%" class="patFunc"> <tbody>
             * 
             * </tbody> </table>
             */

            // TODO Parse out fines, and add them to objects

        }

        // TODO xcLookupUser: Finish getHolds
        // If getHolds is true, the returned users list of holds must
        // contain NCIPUserRequestedItem Objects for all holds and callslips
        // the user represented by the userId field has placed.
        if (getHolds) {
            System.out.println("Todo: get holds");

            /*
             * NCIPUserRequestedItem item = new
             * NCIPUserRequestedItem(results .getDate("date_hold_placed"),
             * // The date the request // was placed null, // The date the
             * request is expected to become // available newItem); // The
             * bibliographic ID of the item the // request is for
             * 
             * // Add the item to the list of requested items
             * returnUser.addRequestedItem(item);
             */
        }
        // If getLoans is true, the returned users list of checkedOutItems
        // must contain NCIPUserLoanedItem Objects for all items the user
        // represented by the userId field has checked out.
        if (getLoans) {
            System.out.println("get Loans");

            // Setup Request URL
            String requestUrl = redirectedUrl.substring(0, redirectedUrl.lastIndexOf("/")) + "/items";

            // setup getLoans method
            GetMethod getLoansMethod = new GetMethod(requestUrl);
            getLoansMethod.addRequestHeader("Cookie", "III_SESSION_ID=" + strSessionId);

            // Grab items page
            try {
                client.executeMethod(getLoansMethod);

                String loansHtml = getLoansMethod.getResponseBodyAsString();
                // Parse out the second page

                // System.out.println(loansHtml);

                // If there were any results, build the full name string
                Pattern loans = Pattern.compile(
                        "^(?s)(.*?)<table(.*?)class=\"patFunc\">(?s)(.*?)<th(.*?)>(?s)(.*?)</th>(?s)(.*?)</tr>(?s)(.*?)</table>(?s)(.*?)$",
                        Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);

                Matcher loansMatch = loans.matcher(loansHtml);

                if (loansMatch.matches()) {
                    // System.out.println("Matches");
                    // System.out.println(loansMatch.groupCount());

                    // for (int i=0; i < loansMatch.groupCount(); i++) {
                    // Add to String Buffer
                    // System.out.println(loansMatch.group(7));
                    // }
                    String loansTable = loansMatch.group(7).toString();
                    // loansTable = loansTable.replaceAll("\n\n","");

                    Pattern loansTwo = Pattern.compile(
                            "^(.*?)<tr(.*?)class=\"patFuncEntry\">(?s)(.*?)</tr>(?s)(.*?)$",
                            Pattern.MULTILINE + Pattern.CASE_INSENSITIVE);

                    Matcher loansTwoMatch = loansTwo.matcher(loansTable);

                    // initialize variables
                    StringBuffer sb = new StringBuffer();
                    String lineMatch;
                    String strCleanup;

                    /*
                     * Pattern loansThree = Pattern.compile(
                     * "^(.*?)value=\"(.*?)\"(.*?)$",
                     * Pattern.CASE_INSENSITIVE);
                     */

                    // loop over each iteration
                    while (loansTwoMatch.find()) {

                        // Replacements to get pipe delmited output
                        lineMatch = loansTwoMatch.group(3).replaceAll("\n", "");

                        lineMatch = lineMatch.replaceAll(
                                "<td align=\"left\" class=\"patFuncMark\"><input type=\"checkbox\" name=\"renew(.*?)\" value=\"",
                                "");
                        lineMatch = lineMatch.replaceAll("\"(.*?)href=\"(.*?)&", "'|'");
                        lineMatch = lineMatch.replaceAll("</a>(.*?)Barcode\">", "'|'");
                        lineMatch = lineMatch.replaceAll("</td>(.*?)patFuncStatus\">", "'|'");
                        lineMatch = lineMatch.replaceAll("</td>(.*?)patFuncCallNo\">", "'|'");
                        lineMatch = lineMatch.replaceAll("\"> ", "'|'");
                        lineMatch = lineMatch.replaceAll(" </td>", "");

                        // Append Pipe delimited to string buffer
                        sb.append(lineMatch + "\n");

                    }
                    // Convert to string for output
                    strCleanup = sb.toString();

                    String aryTest[] = stringToArray(strCleanup, "\n");

                    // System.out.println(aryTest[1]);

                    // Loop Over Loans
                    for (int i = 0; i < aryTest.length; i++) {

                        // Split up, and turn into array / assign to object
                        String aryVal[] = aryTest[i].split("'|'");

                        /*
                         * This is all we can get, itemid, bib, title,
                         * barcode duedate and call number
                         * System.out.println("--" + i);
                         * System.out.print("| item: " + aryVal[0] +
                         * "| bib: b" + aryVal[2] + "| title " + aryVal[4] +
                         * "| barcode: " + aryVal[6] + "| due: " + aryVal[8]
                         * + "| CN: " + aryVal[10]);
                         * 
                         * System.out.println("--");
                         */

                        // set variables for loaned object
                        String strAgencyId = strConfig.getProperty("defaultAgency");/*
                                                                                    * configuration
                                                                                    * .getProperty(
                                                                                    * Constants.
                                                                                    * CONFIG_ILS_DEFAULT_AGENCY
                                                                                    * );
                                                                                    */

                        // Start Date Format
                        Date dateDue = null; // set to null
                        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.SHORT); // create
                        // formatter

                        String strDate = aryVal[8].replaceAll("DUE ", "").replace("-", "/"); // format string

                        // System.out.println(strDate); // for testing

                        // parse the date
                        try {
                            dateDue = dateFormatter.parse(strDate);
                        } catch (ParseException pe) {
                            System.out.println("LookupUser ERROR: Cannot parse \"" + strDate + "\"");
                        }

                        // add b to the value for the bib
                        String bibId = "b" + aryVal[2];

                        // Create a new item for each loaned item
                        /*
                         * NCIPUserLoanedItem item = new NCIPUserLoanedItem(
                         * dateDue, new NCIPItem(new NCIPAgency(
                         * strAgencyId), bibId));
                         */
                        // add object to returnUser
                        // returnUser.addLoanedItem(item);

                        System.out.println(
                                "Added the user's loaned item with item ID " + bibId + " Due: " + dateDue);

                    }

                } // end matches

                // Error handling
            } catch (HttpException e) {
                e.printStackTrace();
                /*
                 * throw new ILSException("HttpException thrown, exiting.",
                 * Constants.ERROR_INTERNAL_ERROR, new StrictNcipError(true,
                 * "NCIP General Processing Error",
                 * "Temporary Processing Failure", "NCIPMessage", null));
                 */
            } catch (IOException e) {
                e.printStackTrace();
                /*
                 * throw new ILSException("IOException thrown, exiting.",
                 * Constants.ERROR_INTERNAL_ERROR, new StrictNcipError(true,
                 * "NCIP General Processing Error",
                 * "Temporary Processing Failure", "NCIPMessage", null));
                 */
            }

        }

        // TODO xcLookupUser: Finish Recalls
        // If getRecalls is true, the returned users list of recalls must
        // contain XCUserRecalledItem Objects for all recalls the user
        // represented by the userId field has placed.
        if (getRecalls) {
            System.out.println("Todo: get Recalls");
        }

        // TODO xcLookupUser: Finish getMessages
        // If getMessages is true, the returned users list of messages must
        // contain all messages applying the user represented by the userId.
        if (getMessages) {
            System.out.println("Todo: get Messages");
        }

        // return returnUser;

    } catch (HttpException e) {
        e.printStackTrace();
        /*
         * throw new ILSException( "HttpException thrown, exiting.",
         * Constants.ERROR_INTERNAL_ERROR, new StrictNcipError(true,
         * "NCIP General Processing Error", "Temporary Processing Failure",
         * "NCIPMessage", null));
         */
    } catch (IOException e) {
        e.printStackTrace();
        /*
         * throw new ILSException( "IOException thrown, exiting.",
         * Constants.ERROR_INTERNAL_ERROR, new StrictNcipError(true,
         * "NCIP General Processing Error", "Temporary Processing Failure",
         * "NCIPMessage", null));
         */
    }

    user.setUserIdentifierValue(userId);
    responseData.setUserId(user);
    // Echo back the same item id that came in
    // responseData.setUserId(initData.getUserId());
    return responseData;
}

From source file:com.buzzdavidson.spork.client.OWAClient.java

/**
 * Fetch the body of the email message given a message URL.
 *
 * @param message Mime message to add body to
 * @param messageUrl URL of message (OWA WebDav)
 *//*from   w  ww  . j  a va  2  s .c  om*/
private void populateMessage(MimeMessage message, String messageUrl) {
    GetMethod get = new GetMethod(messageUrl);
    get.setRequestHeader("Translate", "F");
    try {
        logger.info("Requesting message body via url [" + messageUrl + "]");
        int status = client.executeMethod(get);
        if (logger.isDebugEnabled()) {
            logger.debug("Message request returned status code [" + status + "]");
        }
        if (status == HttpStatus.SC_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(get.getResponseBodyAsStream()));
            String contentType = OWAUtils.getSingleHeader(message, PARAM_CONTENT_TYPE);
            String contentEncoding = OWAUtils.getSingleHeader(message, PARAM_CONTENT_ENCODING);
            boolean needContentType = (contentType == null || contentType.length() < 1);

            // first set of entries are headers, followed by empty line.  skip to first empty line.
            for (String line; (line = in.readLine()) != null;) {
                if (line != null && line.trim().length() == 0) {
                    break;
                }
            }

            StringBuffer buf = new StringBuffer();
            for (String line; (line = in.readLine()) != null;) {
                buf.append(line);
                buf.append(NEWLINE);
            }

            if (needContentType || contentType.contains(CONTENT_TYPE_TEXT_PLAIN)) {
                // OWA sometimes reports XML or HTML content as "text/plain"; check for this.

                if (logger.isDebugEnabled()) {
                    logger.debug("checking content encoding");
                }
                byte[] blob = buf.toString().getBytes();
                if (logger.isDebugEnabled()) {
                    logger.debug("blob length is " + blob.length + " bytes");
                }
                if (contentEncoding.equals(BASE_64_ENCODING)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("blob is base64 encoded, decoding");
                    }
                    byte[] newblob = Base64.decodeBase64(blob);
                    if (logger.isDebugEnabled()) {
                        logger.debug("decoded blob length is " + newblob.length + " bytes");
                    }
                    String data = new String(newblob);
                    buf = new StringBuffer(data);
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("blob is encoded with [" + contentEncoding + "], not decoding");
                    }
                }
                contentType = determineContentType(buf, message);
            }

            if (wantDiagnostics) {
                buf.append(NEWLINE);
                buf.append("-------------------------------------");
                buf.append(NEWLINE);
                buf.append("SPORK Data");
                buf.append(NEWLINE);
                buf.append("content-encoding: " + contentEncoding);
                buf.append(NEWLINE);
                buf.append("content-type: " + contentType);
                if (needContentType) {
                    buf.append(" (calculated) " + contentType);
                    buf.append(" Message processed "
                            + DateFormat.getDateInstance(DateFormat.SHORT).format(new Date()));
                }
            }

            if (needContentType) {
                buf = cleanupBuffer(buf);
            }

            buf.append(NEWLINE);
            message.setText(buf.toString());
            int len = buf.length();
            message.setHeader(PARAM_CONTENT_LENGTH, Integer.valueOf(len).toString()); // close enough :)
            if (contentType != null && contentType.length() > 0) {
                message.setHeader(PARAM_CONTENT_TYPE, contentType);
            }
            message.saveChanges();
        }
    } catch (HttpException ex) {
        logger.error("Received HttpException fetching message body", ex);
    } catch (UnsupportedEncodingException ex) {
        logger.error("Received UnsupportedEncodingException fetching message body", ex);
    } catch (IOException ex) {
        logger.error("Received IOException fetching message body", ex);
    } catch (MessagingException ex) {
        logger.error("Received MessagingException fetching message body", ex);
    }
}

From source file:org.muse.mneme.impl.AssessmentStorageSample.java

protected void fakeIt() {
    if (!fakedAlready) {
        fakedAlready = true;/*  www.  j a  va 2s  .co m*/

        Date now = new Date();

        AssessmentImpl a = newAssessment();
        a.initId("a1");
        a.setPublished(Boolean.TRUE);
        a.setContext("mercury");
        a.getCreatedBy().setUserId("admin");
        a.setTries(3);
        a.setQuestionGrouping(QuestionGrouping.question);
        a.setRandomAccess(Boolean.TRUE);
        a.setTimeLimit(1200l * 1000l);
        a.setTitle("Ann Arbor");
        a.setType(AssessmentType.test);
        // a.getAccess().setPassword("password");
        a.getCreatedBy().setUserId("admin");
        a.getCreatedBy().setDate(now);
        a.getModifiedBy().setUserId("admin");
        a.getModifiedBy().setDate(now);
        try {
            a.getDates().setOpenDate(DateFormat.getDateInstance(DateFormat.SHORT).parse("10/01/07"));
            ((AssessmentDatesImpl) a.getDates())
                    .initDueDate(DateFormat.getDateInstance(DateFormat.SHORT).parse("12/22/07"));
        } catch (ParseException e) {
        }
        a.getGrading().setAutoRelease(Boolean.FALSE);
        a.getGrading().setGradebookIntegration(Boolean.FALSE);
        a.getGrading().setAnonymous(Boolean.FALSE);
        a.getPresentation().setText("This is assessment one.");
        a.getReview().setShowCorrectAnswer(ReviewShowCorrect.yes);
        a.getReview().setShowFeedback(Boolean.TRUE);
        a.getReview().setTiming(ReviewTiming.graded);
        a.getSubmitPresentation().setText("Thanks for all the fish!");

        ManualPart p = a.getParts().addManualPart();
        p.setRandomize(Boolean.FALSE);
        p.setTitle("Part one");
        ((PartImpl) p).initId("p1");
        p.addQuestion(this.questionService.getQuestion("q1"));
        p.addQuestion(this.questionService.getQuestion("q3"));
        p.addQuestion(this.questionService.getQuestion("q4"));
        p.getPresentation().setText("This is part one.");

        p = a.getParts().addManualPart();
        p.setRandomize(Boolean.FALSE);
        p.setTitle("Part two");
        ((PartImpl) p).initId("p2");

        p.addQuestion(this.questionService.getQuestion("q5"));
        p.addQuestion(this.questionService.getQuestion("q7"));
        p.addQuestion(this.questionService.getQuestion("q8"));
        p.getPresentation().setText("This is part two.");

        a.clearChanged();
        a.clearMint();
        ((AssessmentGradingImpl) (a.getGrading())).initAutoRelease(a.getGrading().getAutoRelease());
        ((AssessmentGradingImpl) (a.getGrading()))
                .initGradebookIntegration(a.getGrading().getGradebookIntegration());
        a.initTitle(a.getTitle());
        a.initPublished(a.getPublished());
        this.assessments.put(a.getId(), a);

        //

        a = newAssessment();
        a.setType(AssessmentType.assignment);
        a.initId("a2");
        a.setPublished(Boolean.TRUE);
        a.setContext("mercury");
        a.getCreatedBy().setUserId("admin");
        a.setTries(5);
        a.setQuestionGrouping(QuestionGrouping.question);
        a.setRandomAccess(Boolean.TRUE);
        // a.setTimeLimit(1200l * 1000l);
        a.setTitle("Boston");
        // a.getAccess().setPassword("password");
        a.getCreatedBy().setUserId("admin");
        a.getCreatedBy().setDate(now);
        a.getModifiedBy().setUserId("admin");
        a.getModifiedBy().setDate(now);
        try {
            a.getDates().setOpenDate(DateFormat.getDateInstance(DateFormat.SHORT).parse("09/01/07"));
            ((AssessmentDatesImpl) a.getDates())
                    .initDueDate(DateFormat.getDateInstance(DateFormat.SHORT).parse("12/15/07"));
        } catch (ParseException e) {
        }
        a.getGrading().setAutoRelease(Boolean.TRUE);
        a.getGrading().setGradebookIntegration(Boolean.FALSE);
        a.getGrading().setAnonymous(Boolean.TRUE);
        a.getPresentation().setText("This is assessment two.");
        a.getReview().setShowCorrectAnswer(ReviewShowCorrect.yes);
        a.getReview().setShowFeedback(Boolean.TRUE);
        a.getReview().setTiming(ReviewTiming.submitted);
        a.getSubmitPresentation().setText("Have a nice day!");

        DrawPart p2 = a.getParts().addDrawPart();
        p2.addPool(this.poolService.getPool("b1"), 2);
        p2.setTitle("Part one");
        ((PartImpl) p2).initId("p3");
        p2.getPresentation().setText("This is part one.");

        a.clearChanged();
        a.clearMint();
        ((AssessmentGradingImpl) (a.getGrading())).initAutoRelease(a.getGrading().getAutoRelease());
        ((AssessmentGradingImpl) (a.getGrading()))
                .initGradebookIntegration(a.getGrading().getGradebookIntegration());
        a.initTitle(a.getTitle());
        a.initPublished(a.getPublished());
        this.assessments.put(a.getId(), a);

        //

        a = newAssessment();
        a.setType(AssessmentType.test);
        a.initId("a3");
        a.setPublished(Boolean.TRUE);
        a.setContext("mercury");
        a.getCreatedBy().setUserId("admin");
        a.setTries(5);
        a.setQuestionGrouping(QuestionGrouping.question);
        a.setRandomAccess(Boolean.TRUE);
        // a.setTimeLimit(1200l * 1000l);
        a.setTitle("Detroit");
        // a.getAccess().setPassword("password");
        a.getCreatedBy().setUserId("admin");
        a.getCreatedBy().setDate(now);
        a.getModifiedBy().setUserId("admin");
        a.getModifiedBy().setDate(now);
        a.getGrading().setAutoRelease(Boolean.TRUE);
        a.getGrading().setGradebookIntegration(Boolean.FALSE);
        a.getGrading().setAnonymous(Boolean.TRUE);
        a.getPresentation().setText("This is assessment three.");
        a.getReview().setShowCorrectAnswer(ReviewShowCorrect.yes);
        a.getReview().setShowFeedback(Boolean.TRUE);
        a.getReview().setTiming(ReviewTiming.submitted);
        a.getSubmitPresentation().setText("Have a nice day!");

        p = a.getParts().addManualPart();
        p.addQuestion(this.questionService.getQuestion("q3"));
        p.addQuestion(this.questionService.getQuestion("q4"));
        p.setTitle("Part one");
        ((PartImpl) p).initId("p4");
        p.getPresentation().setText("This is part 1.");

        a.clearChanged();
        a.clearMint();
        ((AssessmentGradingImpl) (a.getGrading())).initAutoRelease(a.getGrading().getAutoRelease());
        ((AssessmentGradingImpl) (a.getGrading()))
                .initGradebookIntegration(a.getGrading().getGradebookIntegration());
        a.initTitle(a.getTitle());
        a.initPublished(a.getPublished());
        this.assessments.put(a.getId(), a);
    }
}

From source file:edu.ku.brc.specify.config.DateConverter.java

/**
 *
 *//*from   ww  w  .  j  a  v a  2 s  . c o  m*/
public DateConverter() {
    String currentFormat = "MM/DD/YYYY";//AppPreferences.getRemote().get("ui.formatting.scrdateformat", null);
    if (currentFormat.startsWith("MM") || currentFormat.startsWith("mm")) {
        preferMonthDay = true;
    } else if (currentFormat.startsWith("DD") || currentFormat.startsWith("dd")) {
        preferMonthDay = false;
    } else {
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT); //for default locale; SHORT -> completely numeric
        Calendar result = new GregorianCalendar();
        result.set(2000, 3, 1);
        String dtstr = df.format(result.getTime());
        int moIdx = dtstr.indexOf("4");
        int dayIdx = dtstr.indexOf("1");
        preferMonthDay = moIdx < dayIdx;
    }

    //System.out.println(df.)
    //preferMonthDay = /*loc == Locale.CANADA || */loc == Locale.US;            
}

From source file:org.openehealth.pors.core.PorsCoreBean.java

/**
 * @see IPorsCore#assembleLoggingEntryDTO(History)
 *///  w  w  w  .  j  ava2 s  . c o  m
public LoggingEntryDTO assembleLoggingEntryDTO(History loggingEntry) {
    LoggingEntryDTO loggingEntryDto = new LoggingEntryDTO();
    loggingEntryDto.setPorsUserId(loggingEntry.getUserId());
    loggingEntryDto.setUserName(loggingEntry.getUserName());
    loggingEntryDto.setLogTime(loggingEntry.getLogTime());
    loggingEntryDto
            .setLogDateString(DateFormat.getDateInstance(DateFormat.MEDIUM).format(loggingEntry.getLogTime()));

    DateFormat dfmt = new SimpleDateFormat("HH:mm:ss:SS");

    loggingEntryDto.setLogTimeString(dfmt.format(loggingEntry.getLogTime()));
    loggingEntryDto.setDomain(loggingEntry.getDomain());
    loggingEntryDto.setAction(loggingEntry.getAction());
    loggingEntryDto.setLogEntryId(loggingEntry.getLogId());

    return loggingEntryDto;
}

From source file:org.etudes.mneme.impl.AssessmentStorageSample.java

protected void fakeIt() {
    if (!fakedAlready) {
        fakedAlready = true;//from   w w w. j  av a 2s. co m

        Date now = new Date();

        AssessmentImpl a = newAssessment();
        a.initId("a1");
        a.setPublished(Boolean.TRUE);
        a.setContext("mercury");
        a.getCreatedBy().setUserId("admin");
        a.setTries(3);
        a.setQuestionGrouping(QuestionGrouping.question);
        a.setRandomAccess(Boolean.TRUE);
        a.setTimeLimit(1200l * 1000l);
        a.setTitle("Ann Arbor");
        a.setType(AssessmentType.test);
        // a.getAccess().setPassword("password");
        a.getCreatedBy().setUserId("admin");
        a.getCreatedBy().setDate(now);
        a.getModifiedBy().setUserId("admin");
        a.getModifiedBy().setDate(now);
        try {
            a.getDates().setOpenDate(DateFormat.getDateInstance(DateFormat.SHORT).parse("10/01/07"));
            ((AssessmentDatesImpl) a.getDates())
                    .initDueDate(DateFormat.getDateInstance(DateFormat.SHORT).parse("12/22/07"));
        } catch (ParseException e) {
        }
        a.getGrading().setAutoRelease(Boolean.FALSE);
        a.getGrading().setGradebookIntegration(Boolean.FALSE);
        a.getGrading().setAnonymous(Boolean.FALSE);
        a.getPresentation().setText("This is assessment one.");
        a.getReview().setShowCorrectAnswer(ReviewShowCorrect.yes);
        a.getReview().setShowFeedback(Boolean.TRUE);
        a.getReview().setShowSummary(Boolean.FALSE);
        a.getReview().setTiming(ReviewTiming.graded);
        a.setMinScoreSet(Boolean.FALSE);
        a.getSubmitPresentation().setText("Thanks for all the fish!");

        Part p = a.getParts().addPart();
        p.setRandomize(Boolean.FALSE);
        p.setTitle("Part one");
        ((PartImpl) p).initId("p1");
        p.addPickDetail(this.questionService.getQuestion("q1"));
        p.addPickDetail(this.questionService.getQuestion("q3"));
        p.addPickDetail(this.questionService.getQuestion("q4"));
        p.getPresentation().setText("This is part one.");

        p = a.getParts().addPart();
        p.setRandomize(Boolean.FALSE);
        p.setTitle("Part two");
        ((PartImpl) p).initId("p2");

        p.addPickDetail(this.questionService.getQuestion("q5"));
        p.addPickDetail(this.questionService.getQuestion("q7"));
        p.addPickDetail(this.questionService.getQuestion("q8"));
        p.getPresentation().setText("This is part two.");

        a.clearChanged();
        a.clearMint();
        ((AssessmentGradingImpl) (a.getGrading())).initAutoRelease(a.getGrading().getAutoRelease());
        ((AssessmentGradingImpl) (a.getGrading()))
                .initGradebookIntegration(a.getGrading().getGradebookIntegration());
        a.initTitle(a.getTitle());
        a.initPublished(a.getPublished());
        this.assessments.put(a.getId(), a);

        //

        a = newAssessment();
        a.setType(AssessmentType.assignment);
        a.initId("a2");
        a.setPublished(Boolean.TRUE);
        a.setContext("mercury");
        a.getCreatedBy().setUserId("admin");
        a.setTries(5);
        a.setQuestionGrouping(QuestionGrouping.question);
        a.setRandomAccess(Boolean.TRUE);
        // a.setTimeLimit(1200l * 1000l);
        a.setTitle("Boston");
        // a.getAccess().setPassword("password");
        a.getCreatedBy().setUserId("admin");
        a.getCreatedBy().setDate(now);
        a.getModifiedBy().setUserId("admin");
        a.getModifiedBy().setDate(now);
        try {
            a.getDates().setOpenDate(DateFormat.getDateInstance(DateFormat.SHORT).parse("09/01/07"));
            ((AssessmentDatesImpl) a.getDates())
                    .initDueDate(DateFormat.getDateInstance(DateFormat.SHORT).parse("12/15/07"));
        } catch (ParseException e) {
        }
        a.getGrading().setAutoRelease(Boolean.TRUE);
        a.getGrading().setGradebookIntegration(Boolean.FALSE);
        a.getGrading().setAnonymous(Boolean.TRUE);
        a.getPresentation().setText("This is assessment two.");
        a.getReview().setShowCorrectAnswer(ReviewShowCorrect.yes);
        a.getReview().setShowFeedback(Boolean.TRUE);
        a.getReview().setShowSummary(Boolean.FALSE);
        a.getReview().setTiming(ReviewTiming.submitted);
        a.setMinScoreSet(Boolean.FALSE);
        a.getSubmitPresentation().setText("Have a nice day!");

        Part p2 = a.getParts().addPart();
        p2.addDrawDetail(this.poolService.getPool("b1"), 2);
        p2.setTitle("Part one");
        ((PartImpl) p2).initId("p3");
        p2.getPresentation().setText("This is part one.");

        a.clearChanged();
        a.clearMint();
        ((AssessmentGradingImpl) (a.getGrading())).initAutoRelease(a.getGrading().getAutoRelease());
        ((AssessmentGradingImpl) (a.getGrading()))
                .initGradebookIntegration(a.getGrading().getGradebookIntegration());
        a.initTitle(a.getTitle());
        a.initPublished(a.getPublished());
        this.assessments.put(a.getId(), a);

        //

        a = newAssessment();
        a.setType(AssessmentType.test);
        a.initId("a3");
        a.setPublished(Boolean.TRUE);
        a.setContext("mercury");
        a.getCreatedBy().setUserId("admin");
        a.setTries(5);
        a.setQuestionGrouping(QuestionGrouping.question);
        a.setRandomAccess(Boolean.TRUE);
        // a.setTimeLimit(1200l * 1000l);
        a.setTitle("Detroit");
        // a.getAccess().setPassword("password");
        a.getCreatedBy().setUserId("admin");
        a.getCreatedBy().setDate(now);
        a.getModifiedBy().setUserId("admin");
        a.getModifiedBy().setDate(now);
        a.getGrading().setAutoRelease(Boolean.TRUE);
        a.getGrading().setGradebookIntegration(Boolean.FALSE);
        a.getGrading().setAnonymous(Boolean.TRUE);
        a.getPresentation().setText("This is assessment three.");
        a.getReview().setShowCorrectAnswer(ReviewShowCorrect.yes);
        a.getReview().setShowFeedback(Boolean.TRUE);
        a.getReview().setShowSummary(Boolean.FALSE);
        a.getReview().setTiming(ReviewTiming.submitted);
        a.setMinScoreSet(Boolean.FALSE);
        a.getSubmitPresentation().setText("Have a nice day!");

        p = a.getParts().addPart();
        p.addPickDetail(this.questionService.getQuestion("q3"));
        p.addPickDetail(this.questionService.getQuestion("q4"));
        p.setTitle("Part one");
        ((PartImpl) p).initId("p4");
        p.getPresentation().setText("This is part 1.");

        a.clearChanged();
        a.clearMint();
        ((AssessmentGradingImpl) (a.getGrading())).initAutoRelease(a.getGrading().getAutoRelease());
        ((AssessmentGradingImpl) (a.getGrading()))
                .initGradebookIntegration(a.getGrading().getGradebookIntegration());
        a.initTitle(a.getTitle());
        a.initPublished(a.getPublished());
        this.assessments.put(a.getId(), a);
    }
}