Example usage for java.util GregorianCalendar setTime

List of usage examples for java.util GregorianCalendar setTime

Introduction

In this page you can find the example usage for java.util GregorianCalendar setTime.

Prototype

public final void setTime(Date date) 

Source Link

Document

Sets this Calendar's time with the given Date.

Usage

From source file:edu.umm.radonc.ca_dash.model.TxInstanceFacade.java

public TreeMap<Date, SynchronizedDescriptiveStatistics> getWeeklySummaryStatsAbs(Date startDate, Date endDate,
        Long hospitalser, String filter, boolean includeWeekends, boolean ptflag, boolean scheduledFlag) {
    Calendar cal = new GregorianCalendar();
    TreeMap<Date, SynchronizedDescriptiveStatistics> retval = new TreeMap<>();

    //SET TO BEGINNING OF WK FOR ABSOLUTE CALC
    cal.setTime(startDate);//from  w  ww  .  ja  va 2  s  .  c o m
    cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    startDate = cal.getTime();

    List<Object[]> events = getDailyCounts(startDate, endDate, hospitalser, filter, false, ptflag,
            scheduledFlag);

    DateFormat df = new SimpleDateFormat("MM/dd/yy");
    cal.setTime(startDate);
    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    int wk = cal.get(Calendar.WEEK_OF_YEAR);
    int mo = cal.get(Calendar.MONTH);
    int yr = cal.get(Calendar.YEAR);
    if (mo == Calendar.DECEMBER && wk == 1) {
        yr = yr + 1;
    } else if (mo == Calendar.JANUARY && wk == 52) {
        yr = yr - 1;
    }
    String currYrWk = yr + "-" + String.format("%02d", wk);
    //String prevYrWk = "";
    String prevYrWk = currYrWk;
    SynchronizedDescriptiveStatistics currStats = new SynchronizedDescriptiveStatistics();
    int i = 0;
    while (cal.getTime().before(endDate) && i < events.size()) {

        Object[] event = events.get(i);
        Date d = (Date) event[0];
        Long count = (Long) event[1];

        cal.setTime(d);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        wk = cal.get(Calendar.WEEK_OF_YEAR);
        mo = cal.get(Calendar.MONTH);
        yr = cal.get(Calendar.YEAR);
        if (mo == Calendar.DECEMBER && wk == 1) {
            yr = yr + 1;
        } else if (mo == Calendar.JANUARY && wk == 52) {
            yr = yr - 1;
        }
        currYrWk = yr + "-" + String.format("%02d", wk);

        if (!(prevYrWk.equals(currYrWk))) {
            GregorianCalendar lastMon = new GregorianCalendar();
            lastMon.setTime(cal.getTime());
            lastMon.add(Calendar.DATE, -7);
            retval.put(lastMon.getTime(), currStats);
            currStats = new SynchronizedDescriptiveStatistics();
        }

        prevYrWk = currYrWk;

        currStats.addValue(count);
        i++;
    }
    retval.put(cal.getTime(), currStats);

    return retval;
}

From source file:be.fedict.eidviewer.lib.file.imports.Version35CSVFile.java

public void load(File file) throws CertificateException, FileNotFoundException, IOException {
    logger.fine("Loading Version 35X CSV File");

    String line = null;/*from www . ja v a2 s.c om*/

    certificateFactory = CertificateFactory.getInstance("X.509");
    InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "utf-8");
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    line = bufferedReader.readLine();
    if (line != null) {
        String[] tokens = line.split(";");
        for (int tokenNumber = 0; (variableCertCount < 0) && (tokenNumber < tokens.length); tokenNumber++) {
            String token = tokens[tokenNumber];
            logger.log(Level.FINEST, "token #{0} : [{1}]", new Object[] { tokenNumber, token });

            try {

                switch (tokenNumber) {
                case DOCUMENTTYPE:
                    identity = new Identity();
                    identity.documentType = DocumentType.toDocumentType(token.getBytes("utf-8"));
                    if (identity.documentType == null)
                        logger.log(Level.SEVERE, "Unknown Document Type \"{0}\"", token);
                    break;

                case FIRSTNAMES:
                    TextFormatHelper.setFirstNamesFromString(identity, token);
                    break;

                case LASTNAME:
                    identity.name = token;
                    break;

                case GENDER:
                    identity.gender = token.equals("M") ? Gender.MALE : Gender.FEMALE;
                    break;

                case BIRTHDATE: {
                    logger.fine("field BIRTHDATE");
                    DateOfBirthDataConvertor dateOfBirthConvertor = new DateOfBirthDataConvertor();
                    identity.dateOfBirth = dateOfBirthConvertor.convert(token.getBytes("utf-8"));
                }
                    break;

                case PLACEOFBIRTH:
                    identity.placeOfBirth = token;
                    break;

                case NATIONALITY:
                    identity.nationality = token;
                    break;

                case NATIONALNUMBER:
                    identity.nationalNumber = token;
                    break;

                case CARDNUMBER:
                    identity.cardNumber = token;
                    break;

                case CARDCHIPNUMBER:
                    identity.chipNumber = token;
                    break;

                case CARDVALIDFROM: {
                    GregorianCalendar validityBeginCalendar = new GregorianCalendar();
                    try {
                        validityBeginCalendar.setTime(dateFormat.parse(token));
                        identity.cardValidityDateBegin = validityBeginCalendar;
                    } catch (ParseException ex) {
                        logger.log(Level.SEVERE, "Failed to parse Card Validity Start Date \"" + token + "\"",
                                ex);
                    }
                }
                    break;

                case CARDVALIDUNTIL:
                    GregorianCalendar validityEndCalendar = new GregorianCalendar();
                    try {
                        validityEndCalendar.setTime(dateFormat.parse(token));
                        identity.cardValidityDateEnd = validityEndCalendar;
                    } catch (ParseException ex) {
                        logger.log(Level.SEVERE, "Failed to parse Card Validity End Date \"" + token + "\"",
                                ex);
                    }
                    break;

                case CARDISSUINGMUNICIPALITY:
                    identity.cardDeliveryMunicipality = token;
                    break;

                case STREETANDNUMBER:
                    address = new Address();
                    address.streetAndNumber = token;
                    break;

                case ZIP:
                    address.zip = token;
                    break;

                case MUNICIPALITY:
                    address.municipality = token;
                    break;

                case PHOTO:
                    byte[] tokenBytes = token.getBytes();
                    eidData.setPhoto(Base64.decodeBase64(tokenBytes));
                    break;

                case RRNCERTIFICATE:
                    logger.finer("Gathering RRN Certificate");
                    try {
                        rrnCert = (X509Certificate) certificateFactory.generateCertificate(
                                new ByteArrayInputStream(Base64.decodeBase64(token.getBytes())));
                    } catch (CertificateException ex) {
                        logger.log(Level.SEVERE, "Failed to RRN Certificate", ex);
                    }
                    break;

                case CERTCOUNT:
                    logger.finer("Certificate Count: [" + token + "]");
                    variableCertCount = Integer.parseInt(token);
                    break;
                }
            } catch (UnsupportedEncodingException ex) {
                logger.log(Level.SEVERE, "Unsupported Encoding for Token " + tokenNumber, ex);
            } catch (DataConvertorException ex) {
                logger.log(Level.SEVERE,
                        "Couldn't Convert Date \"" + tokens[tokenNumber] + "\" in Token " + tokenNumber, ex);
            }
        } // done looping over fixed parts..

        if (identity != null) {
            TextFormatHelper.setFirstNamesFromStrings(identity, identity.getFirstName(),
                    identity.getMiddleName());
            eidData.setIdentity(identity);
        }

        if (address != null)
            eidData.setAddress(address);

        // get variableCertCount variable certs
        for (int i = 0; i < variableCertCount; i++) {
            X509Certificate thisCertificate = null;
            int certOffset = CERTBASE + (CERTFIELDS * i);
            String certType = tokens[certOffset + CERT_NAME_OFFSET];
            String certData = tokens[certOffset + CERT_DATA_OFFSET];

            logger.finer("Gathering " + certType + " Certificate");

            try {
                thisCertificate = (X509Certificate) certificateFactory.generateCertificate(
                        new ByteArrayInputStream(Base64.decodeBase64(certData.getBytes())));
            } catch (CertificateException ex) {
                logger.log(Level.SEVERE, "Failed to Convert Signing Certificate", ex);
                thisCertificate = null;
            }

            if (thisCertificate != null) {
                if (certType.equalsIgnoreCase("Authentication"))
                    authenticationCert = thisCertificate;
                else if (certType.equalsIgnoreCase("Signature"))
                    signingCert = thisCertificate;
                else if (certType.equalsIgnoreCase("CA"))
                    citizenCert = thisCertificate;
                else if (certType.equalsIgnoreCase("Root"))
                    rootCert = thisCertificate;
            }
        }

    }

    if (rootCert != null && citizenCert != null) {
        logger.fine("Certificates were gathered");

        if (rrnCert != null) {
            logger.fine("Setting RRN Certificate Chain");
            List<X509Certificate> rrnChain = new LinkedList<X509Certificate>();
            rrnChain.add(rrnCert);
            rrnChain.add(rootCert);
            eidData.setRRNCertChain(new X509CertificateChainAndTrust(
                    TrustServiceDomains.BELGIAN_EID_NATIONAL_REGISTRY_TRUST_DOMAIN, rrnChain));
        }

        if (authenticationCert != null) {
            logger.fine("Setting Authentication Certificate Chain");
            List<X509Certificate> authChain = new LinkedList<X509Certificate>();
            authChain.add(authenticationCert);
            authChain.add(citizenCert);
            authChain.add(rootCert);
            eidData.setAuthCertChain(new X509CertificateChainAndTrust(
                    TrustServiceDomains.BELGIAN_EID_AUTH_TRUST_DOMAIN, authChain));
        }

        if (signingCert != null) {
            logger.fine("Setting Signing Certificate Chain");
            List<X509Certificate> signChain = new LinkedList<X509Certificate>();
            signChain.add(signingCert);
            signChain.add(citizenCert);
            signChain.add(rootCert);
            eidData.setSignCertChain(new X509CertificateChainAndTrust(
                    TrustServiceDomains.BELGIAN_EID_NON_REPUDIATION_TRUST_DOMAIN, signChain));
        }
    }
    inputStreamReader.close();
}

From source file:org.repodriller.scm.GitRepository.java

/**
 * Get the commit with this commit id.//from www .  ja  va  2 s.c o m
 * Caveats:
 *   - If commit modifies more than maxNumberFilesInACommit, throws an exception
 *   - If one of the file diffs exceeds maxSizeOfDiff, the diffText is discarded
 *
 * @param id    The SHA1 hash that identifies a git commit.
 * @returns Commit    The corresponding Commit, or null.
 */
@Override
public Commit getCommit(String id) {
    try (Git git = openRepository()) {
        /* Using JGit, this commit will be the first entry in the log beginning at id. */
        Repository repo = git.getRepository();
        Iterable<RevCommit> jgitCommits = git.log().add(repo.resolve(id)).call();
        Iterator<RevCommit> itr = jgitCommits.iterator();

        if (!itr.hasNext())
            return null;
        RevCommit jgitCommit = itr.next();

        /* Extract metadata. */
        Developer author = new Developer(jgitCommit.getAuthorIdent().getName(),
                jgitCommit.getAuthorIdent().getEmailAddress());
        Developer committer = new Developer(jgitCommit.getCommitterIdent().getName(),
                jgitCommit.getCommitterIdent().getEmailAddress());
        TimeZone authorTimeZone = jgitCommit.getAuthorIdent().getTimeZone();
        TimeZone committerTimeZone = jgitCommit.getCommitterIdent().getTimeZone();

        String msg = collectConfig.isCollectingCommitMessages() ? jgitCommit.getFullMessage().trim() : "";
        String hash = jgitCommit.getName().toString();
        List<String> parents = Arrays.stream(jgitCommit.getParents()).map(rc -> rc.getName().toString())
                .collect(Collectors.toList());

        GregorianCalendar authorDate = new GregorianCalendar();
        authorDate.setTime(jgitCommit.getAuthorIdent().getWhen());
        authorDate.setTimeZone(jgitCommit.getAuthorIdent().getTimeZone());

        GregorianCalendar committerDate = new GregorianCalendar();
        committerDate.setTime(jgitCommit.getCommitterIdent().getWhen());
        committerDate.setTimeZone(jgitCommit.getCommitterIdent().getTimeZone());

        boolean isMerge = (jgitCommit.getParentCount() > 1);

        Set<String> branches = getBranches(git, hash);
        boolean isCommitInMainBranch = branches.contains(this.mainBranchName);

        /* Create one of our Commit's based on the jgitCommit metadata. */
        Commit commit = new Commit(hash, author, committer, authorDate, authorTimeZone, committerDate,
                committerTimeZone, msg, parents, isMerge, branches, isCommitInMainBranch);

        /* Convert each of the associated DiffEntry's to a Modification. */
        List<DiffEntry> diffsForTheCommit = diffsForTheCommit(repo, jgitCommit);
        if (diffsForTheCommit.size() > maxNumberFilesInACommit) {
            String errMsg = "Commit " + id + " touches more than " + maxNumberFilesInACommit + " files";
            log.error(errMsg);
            throw new RepoDrillerException(errMsg);
        }

        for (DiffEntry diff : diffsForTheCommit) {
            if (this.diffFiltersAccept(diff)) {
                Modification m = this.diffToModification(repo, diff);
                commit.addModification(m);
            }
        }

        return commit;
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("error detailing " + id + " in " + path, e);
    }
}

From source file:org.repodriller.scm.GitRepository.java

private GregorianCalendar convertToDate(RevCommit revCommit) {
    GregorianCalendar date = new GregorianCalendar();
    date.setTimeZone(revCommit.getAuthorIdent().getTimeZone());
    date.setTime(revCommit.getAuthorIdent().getWhen());

    return date;/*from   w w  w. j a  v  a  2s  .co m*/
}

From source file:be.fedict.trust.client.XKMS2Client.java

private XMLGregorianCalendar getXmlGregorianCalendar(Date date) {
    try {//from  w  ww  .  j a  v  a2 s  .com
        DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();

        GregorianCalendar gregorianCalendar = new GregorianCalendar();
        gregorianCalendar.setTime(date);
        XMLGregorianCalendar currentXmlGregorianCalendar = datatypeFactory
                .newXMLGregorianCalendar(gregorianCalendar);
        return currentXmlGregorianCalendar;

    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException("datatype config error");
    }
}

From source file:gov.va.ds4p.ds4pmobileportal.pep.XACMLPolicyEnforcement.java

private XMLGregorianCalendar convertDateToXMLGregorianCalendar(Date dt) {
    XMLGregorianCalendar xcal = null;
    try {/* w  w w  .j  av a 2 s . co m*/
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(dt);
        xcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return xcal;
}

From source file:be.fedict.eid.applet.service.signer.facets.XAdESSignatureFacet.java

public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    LOG.debug("preSign");

    // QualifyingProperties
    QualifyingPropertiesType qualifyingProperties = this.xadesObjectFactory.createQualifyingPropertiesType();
    qualifyingProperties.setTarget("#" + signatureId);

    // SignedProperties
    SignedPropertiesType signedProperties = this.xadesObjectFactory.createSignedPropertiesType();
    String signedPropertiesId;// w ww.  ja  va 2s.  c  om
    if (null != this.idSignedProperties) {
        signedPropertiesId = this.idSignedProperties;
    } else {
        signedPropertiesId = signatureId + "-xades";
    }
    signedProperties.setId(signedPropertiesId);
    qualifyingProperties.setSignedProperties(signedProperties);

    // SignedSignatureProperties
    SignedSignaturePropertiesType signedSignatureProperties = this.xadesObjectFactory
            .createSignedSignaturePropertiesType();
    signedProperties.setSignedSignatureProperties(signedSignatureProperties);

    // SigningTime
    GregorianCalendar signingTime = new GregorianCalendar(TimeZone.getTimeZone("Z"));
    Date currentClockValue = this.clock.getTime();
    signingTime.setTime(currentClockValue);
    XMLGregorianCalendar xmlGregorianCalendar = this.datatypeFactory.newXMLGregorianCalendar(signingTime);
    xmlGregorianCalendar.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
    signedSignatureProperties.setSigningTime(xmlGregorianCalendar);

    // SigningCertificate
    if (null == signingCertificateChain || signingCertificateChain.isEmpty()) {
        throw new RuntimeException("no signing certificate chain available");
    }
    X509Certificate signingCertificate = signingCertificateChain.get(0);
    CertIDType signingCertificateId = getCertID(signingCertificate, this.xadesObjectFactory,
            this.xmldsigObjectFactory, this.digestAlgorithm, this.issuerNameNoReverseOrder);
    CertIDListType signingCertificates = this.xadesObjectFactory.createCertIDListType();
    signingCertificates.getCert().add(signingCertificateId);
    signedSignatureProperties.setSigningCertificate(signingCertificates);

    // ClaimedRole
    if (null != this.role && false == this.role.isEmpty()) {
        SignerRoleType signerRole = this.xadesObjectFactory.createSignerRoleType();
        signedSignatureProperties.setSignerRole(signerRole);
        ClaimedRolesListType claimedRolesList = this.xadesObjectFactory.createClaimedRolesListType();
        signerRole.setClaimedRoles(claimedRolesList);
        AnyType claimedRole = this.xadesObjectFactory.createAnyType();
        claimedRole.getContent().add(this.role);
        claimedRolesList.getClaimedRole().add(claimedRole);
    }

    // XAdES-EPES
    if (null != this.signaturePolicyService) {
        SignaturePolicyIdentifierType signaturePolicyIdentifier = this.xadesObjectFactory
                .createSignaturePolicyIdentifierType();
        signedSignatureProperties.setSignaturePolicyIdentifier(signaturePolicyIdentifier);

        SignaturePolicyIdType signaturePolicyId = this.xadesObjectFactory.createSignaturePolicyIdType();
        signaturePolicyIdentifier.setSignaturePolicyId(signaturePolicyId);

        ObjectIdentifierType objectIdentifier = this.xadesObjectFactory.createObjectIdentifierType();
        signaturePolicyId.setSigPolicyId(objectIdentifier);
        IdentifierType identifier = this.xadesObjectFactory.createIdentifierType();
        objectIdentifier.setIdentifier(identifier);
        identifier.setValue(this.signaturePolicyService.getSignaturePolicyIdentifier());
        objectIdentifier.setDescription(this.signaturePolicyService.getSignaturePolicyDescription());

        byte[] signaturePolicyDocumentData = this.signaturePolicyService.getSignaturePolicyDocument();
        DigestAlgAndValueType sigPolicyHash = getDigestAlgAndValue(signaturePolicyDocumentData,
                this.xadesObjectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
        signaturePolicyId.setSigPolicyHash(sigPolicyHash);

        String signaturePolicyDownloadUrl = this.signaturePolicyService.getSignaturePolicyDownloadUrl();
        if (null != signaturePolicyDownloadUrl) {
            SigPolicyQualifiersListType sigPolicyQualifiers = this.xadesObjectFactory
                    .createSigPolicyQualifiersListType();
            signaturePolicyId.setSigPolicyQualifiers(sigPolicyQualifiers);

            AnyType sigPolicyQualifier = this.xadesObjectFactory.createAnyType();
            sigPolicyQualifiers.getSigPolicyQualifier().add(sigPolicyQualifier);

            JAXBElement<String> spUriElement = this.xadesObjectFactory.createSPURI(signaturePolicyDownloadUrl);
            sigPolicyQualifier.getContent().add(spUriElement);
        }
    } else if (this.signaturePolicyImplied) {
        SignaturePolicyIdentifierType signaturePolicyIdentifier = this.xadesObjectFactory
                .createSignaturePolicyIdentifierType();
        signedSignatureProperties.setSignaturePolicyIdentifier(signaturePolicyIdentifier);

        signaturePolicyIdentifier.setSignaturePolicyImplied("");
    }

    // DataObjectFormat
    if (false == this.dataObjectFormatMimeTypes.isEmpty()) {
        SignedDataObjectPropertiesType signedDataObjectProperties = this.xadesObjectFactory
                .createSignedDataObjectPropertiesType();
        signedProperties.setSignedDataObjectProperties(signedDataObjectProperties);

        List<DataObjectFormatType> dataObjectFormats = signedDataObjectProperties.getDataObjectFormat();
        for (Map.Entry<String, String> dataObjectFormatMimeType : this.dataObjectFormatMimeTypes.entrySet()) {
            DataObjectFormatType dataObjectFormat = this.xadesObjectFactory.createDataObjectFormatType();
            dataObjectFormat.setObjectReference("#" + dataObjectFormatMimeType.getKey());
            dataObjectFormat.setMimeType(dataObjectFormatMimeType.getValue());
            dataObjectFormats.add(dataObjectFormat);
        }
    }

    // marshall XAdES QualifyingProperties
    Node qualifyingPropertiesNode = marshallQualifyingProperties(document, this.xadesObjectFactory,
            qualifyingProperties);

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(qualifyingPropertiesNode));
    XMLObject xadesObject = signatureFactory.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);

    // add XAdES ds:Reference
    DigestMethod digestMethod = signatureFactory.newDigestMethod(digestAlgorithm.getXmlAlgoId(), null);
    List<Transform> transforms = new LinkedList<Transform>();
    Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);
    Reference reference = signatureFactory.newReference("#" + signedPropertiesId, digestMethod, transforms,
            XADES_TYPE, null);
    references.add(reference);
}

From source file:org.awknet.commons.model.business.UserBOImpl.java

/**
 * Verify if a retrieve code still valid. The default time validation is 2
 * days.// w ww  .  j  av  a  2  s .  co m
 * 
 * @param requestDate
 * @return true for if is valid.
 */
public boolean isValidRequest(Date requestDate, final String retrieveCode) throws RetrieveCodeException {

    RetrievePasswordLog rpLog = daoFactory.getRetrievePasswordLogDao().findRetrieveCode(retrieveCode);
    if (rpLog == null)
        throw new RetrieveCodeException(RetrieveCodeExceptionType.RETRIEVE_CODE);

    if (rpLog.getUpdated())
        throw new RetrieveCodeException(RetrieveCodeExceptionType.RETRIEVE_CODE);

    LOG.debug("[VALID REQUEST] found something!");
    // int
    // days=SystemMessageAcessor.getPropertyAsInteger("request.activation.form.valid.until.days");

    int days = RetrievePasswordLog.DEFAULT_TIME_RETRIEVE_CODE;

    GregorianCalendar currentDate = new GregorianCalendar();
    GregorianCalendar dateGenerateLink = new GregorianCalendar();
    dateGenerateLink.setTime(requestDate);
    dateGenerateLink.add(Calendar.DAY_OF_YEAR, days);

    if (currentDate.before(dateGenerateLink)) {
        return true;
        // try {
        // FIXME must set true here?
        // rpLog.setUpdated(true);
        // daoFactory.beginTransaction();
        // daoFactory.getRetrievePasswordLogDao().update(rpLog);
        // daoFactory.commit();
        // return true;
        // } catch (ConstraintViolationException e) {
        // // FIXME adjust message
        // LOG.error("[VALID REQUEST] code not updated in DB.", e);
        // return false;
        // } catch (Exception e) {
        // LOG.error("[VALID REQUEST] generic error in DB.", e);
        // return false;
        // }
    }

    return false;
}

From source file:edu.stanford.muse.index.EmailDocument.java

public String getSignature() {
    StringBuilder sb = new StringBuilder();
    StringBuilder timeSB = new StringBuilder();
    Formatter formatter = new Formatter(timeSB);
    if (this.date != null) {
        GregorianCalendar cc = new GregorianCalendar();
        cc.setTime(this.date);
        formatter.format("%02d:%02d",
                new Object[] { Integer.valueOf(cc.get(11)), Integer.valueOf(cc.get(12)) });
        sb.append("Date: " + cc.get(5) + " " + CalendarUtil.getDisplayMonth(cc) + " " + cc.get(1) + " " + timeSB
                + "\n");
    }//ww w  . ja  v a  2  s . c  om

    formatter.close();
    sb.append("From: " + this.getFromString() + "\n");
    sb.append("To: " + this.getToString() + "\n");
    String cc1 = this.getCcString();
    if (!Util.nullOrEmpty(cc1)) {
        sb.append("Cc: " + cc1 + "\n");
    }

    String bcc = this.getBccString();
    if (!Util.nullOrEmpty(bcc)) {
        sb.append("Bcc: " + bcc + "\n");
    }

    if (this.description == null) {
        this.description = "<None>";
    }

    sb.append("Subject: " + this.description + "\n");
    sb.append("\n");
    return sb.toString();
}

From source file:org.exoplatform.wiki.service.impl.WikiRestServiceImpl.java

private void fillAttachment(Attachment attachment, ObjectFactory objectFactory, URI baseUri,
        AttachmentImpl pageAttachment, String xwikiRelativeUrl, String xwikiAbsoluteUrl) throws Exception {
    PageImpl page = pageAttachment.getParentPage();

    attachment.setId(String.format("%s@%s", page.getName(), pageAttachment.getName()));
    attachment.setName(pageAttachment.getName());
    attachment.setSize((int) pageAttachment.getWeightInBytes());
    attachment.setVersion("current");
    attachment.setPageId(page.getName());
    attachment.setPageVersion("current");
    attachment.setMimeType(pageAttachment.getContentResource().getMimeType());
    attachment.setAuthor(pageAttachment.getCreator());

    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(pageAttachment.getCreated());
    attachment.setDate(calendar);/*  w  w  w.j  a  v  a2  s.c  om*/

    attachment.setXwikiRelativeUrl(xwikiRelativeUrl);
    attachment.setXwikiAbsoluteUrl(xwikiAbsoluteUrl);

    String pageUri = UriBuilder.fromUri(baseUri).path("/wiki/{wikiName}/spaces/{spaceName}/pages/{pageName}")
            .build(page.getWiki().getType(), page.getWiki().getOwner(), page.getName()).toString();
    Link pageLink = objectFactory.createLink();
    pageLink.setHref(pageUri);
    pageLink.setRel(Relations.PAGE);
    attachment.getLinks().add(pageLink);
}