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:be.fedict.eid.pkira.portal.util.TypeMapper.java

public XMLGregorianCalendar map(Date date) {
    if (date == null)
        return null;

    GregorianCalendar calendar = new GregorianCalendar();
    calendar.setTime(date);
    calendar.setTimeZone(TimeZone.getTimeZone("GMT"));

    return getDatatypeFactory().newXMLGregorianCalendar(calendar);
}

From source file:de.arago.rike.task.action.EvaluateTask.java

@Override
public void execute(IDataWrapper data) throws Exception {

    if (data.getRequestAttribute("id") != null) {

        Task task = TaskHelper.getTask(data.getRequestAttribute("id"));

        String user = SecurityHelper.getUserEmail(data.getUser());

        if (task.getStatusEnum() == Task.Status.UNKNOWN || task.getStatusEnum() == Task.Status.OPEN) {
            task.setMilestone(//w ww. j a  v  a  2s  .  c o m
                    new DataHelperRike<Milestone>(Milestone.class).find(data.getRequestAttribute("milestone")));
            task.setArtifact(
                    new DataHelperRike<Artifact>(Artifact.class).find(data.getRequestAttribute("artifact")));

            task.setDescription(data.getRequestAttribute("description"));

            try {
                task.setSizeEstimated(Integer.valueOf(data.getRequestAttribute("size_estimated"), 10));
            } catch (Exception ignored) {
            }

            try {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                task.setDueDate(format.parse(data.getRequestAttribute("due_date")));
            } catch (Exception ignored) {
            }

            task.setTitle(data.getRequestAttribute("title"));
            task.setUrl(data.getRequestAttribute("url"));
            int priority = Integer.parseInt(GlobalConfig.get(PRIORITY_NORMAL));

            try {
                priority = Integer.valueOf(data.getRequestAttribute("priority"), 10);
            } catch (Exception ignored) {
            }

            task.setPriority(priority);
            task.setRated(new Date());
            task.setRatedBy(user);
            task.setStatus(Task.Status.OPEN);
            if (GlobalConfig.get(WORKFLOW_TYPE).equalsIgnoreCase("arago Technologies") && priority == 1) {
                GregorianCalendar c = new GregorianCalendar();
                c.setTime(task.getRated());
                c.add(Calendar.DAY_OF_MONTH, Integer.parseInt(GlobalConfig.get(WORKFLOW_DAYS_TOP_PRIO_TASK)));
                task.setDueDate(c.getTime());
            }

            TaskHelper.save(task);

            StatisticHelper.update();

            data.setSessionAttribute("task", task);

            HashMap<String, Object> notificationParam = new HashMap<String, Object>();

            notificationParam.put("id", data.getRequestAttribute("id"));
            data.setEvent("TaskUpdateNotification", notificationParam);

            data.removeSessionAttribute("targetView");

            ActivityLogHelper.log(
                    " rated Task #" + task.getId() + " <a href=\"/web/guest/rike/-/show/task/" + task.getId()
                            + "\">" + StringEscapeUtils.escapeHtml(task.getTitle()) + "</a> ",
                    task.getStatus(), SecurityHelper.getUserEmail(data.getUser()), data, task.toMap());
        }
    }
}

From source file:jenkins.plugins.coverity.DefectFiltersTest.java

@Test
public void defectCutOffDates() throws FormException, java.text.ParseException, DatatypeConfigurationException {
    String cutOffDate = null;//  w w  w.j  a v  a  2s .co m
    DefectFilters filters = new DefectFilters(null, null, null, null, null, null, cutOffDate);

    assertNull(filters.getCutOffDate());
    assertNull(filters.getXMLCutOffDate());

    cutOffDate = "unparsable-date-format";
    filters = new DefectFilters(null, null, null, null, null, null, cutOffDate);

    assertNull(filters.getCutOffDate());
    assertNull(filters.getXMLCutOffDate());

    cutOffDate = "2010-01-31";
    filters = new DefectFilters(null, null, null, null, null, null, cutOffDate);

    assertEquals(cutOffDate, filters.getCutOffDate());

    GregorianCalendar calender = new GregorianCalendar();
    calender.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(cutOffDate));
    XMLGregorianCalendar expectedXmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(calender);
    assertEquals(expectedXmlDate, filters.getXMLCutOffDate());
}

From source file:bkampfbot.state.Opponent.java

public final void checkNewDay() {
    GregorianCalendar today = new GregorianCalendar();
    today.setTime(Config.getDate());
    today.set(GregorianCalendar.HOUR, 0);
    today.set(GregorianCalendar.MINUTE, 0);

    if (date.before(today)) {
        date = new GregorianCalendar();

        // Set all counters to zero
        setNew();//from   w  w w .j  ava 2 s . c  om
    }
}

From source file:org.getobjects.ofs.OFSResourceFileRenderer.java

/**
 * Stream the given OFSResourceFile object to the response.
 *//*w w  w. j  av  a 2s  .  c  o m*/
public Exception renderObjectInContext(Object _object, final WOContext _ctx) {
    if (_object == null)
        return new GoInternalErrorException("got no object to render");

    /* retrieve basic info */

    final OFSResourceFile doc = (OFSResourceFile) _object;

    final String mimeType = doc.defaultDeliveryMimeType();

    /* start response */

    final WOResponse r = _ctx.response();
    r.setStatus(WOMessage.HTTP_STATUS_OK);
    r.setHeaderForKey(mimeType, "content-type");

    /* setup caching headers */

    final Date now = new Date();
    final GregorianCalendar cal = new GregorianCalendar();

    cal.setTime(doc.lastModified());
    r.setHeaderForKey(WOMessage.httpFormatDate(cal), "last-modified");

    cal.setTime(now);
    r.setHeaderForKey(WOMessage.httpFormatDate(cal), "date");

    // TBD: document
    if (mimeType.startsWith("image/"))
        cal.add(Calendar.HOUR, 1);
    else if (mimeType.startsWith("text/css"))
        cal.add(Calendar.MINUTE, 10);
    else
        cal.add(Calendar.SECOND, 5);
    r.setHeaderForKey(WOMessage.httpFormatDate(cal), "expires");

    /* transfer content */

    r.setHeaderForKey("" + doc.size(), "content-length");

    /* remember that no headers can be set after streaming got activated */
    // TODO: this should be ensured by WOResponse
    if (!r.enableStreaming())
        log.warn("could not enable streaming for doc: " + doc);

    final InputStream is = doc.openStream();
    if (is == null)
        return new GoInternalErrorException("could not open resource stream");

    r.resetLastException();
    try {
        byte[] buffer = new byte[0xFFFF];
        for (int len; (len = is.read(buffer)) != -1;)
            r.appendContentData(buffer, len);
    } catch (IOException e) {
        return new GoInternalErrorException("failed to read from resource stream");
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
            log.warn("could not close input stream");
        }
    }

    return r.lastException(); /* WOResponse might have caught an issue */
}

From source file:org.motechproject.mobile.omp.manager.intellivr.ConvertSerializedIVRSessionsBean.java

private Date addToDate(Date start, int field, int amount) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(start);
    cal.add(field, amount);/*from  w  w w . jav  a2  s .c  om*/
    return cal.getTime();
}

From source file:au.csiro.notify.util.NotificationAssembler.java

public XMLNotificationType createXMLNotificationType(Notification notification) {
    logger.trace("createXMLNotificationType({})", notification);
    XMLNotificationType xmlNotification = new XMLNotificationType();

    xmlNotification.setSource(notification.getSource());
    xmlNotification.setSubject(notification.getSubject());
    xmlNotification.setMessage(notification.getMessage());
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(notification.getStartDate());
    xmlNotification.setStartDate(dtf.newXMLGregorianCalendar(gc));
    gc.setTime(notification.getExpiryDate());
    xmlNotification.setExpiryDate(dtf.newXMLGregorianCalendar(gc));
    XMLTypeOfNotificationType type;/*from w  ww . java2  s  .  c  o  m*/
    switch (notification.getNotificationType()) {
    case ACTION_REQUIRED:
        type = XMLTypeOfNotificationType.ACTION_REQUIRED;
        break;
    case INFORMATION:
    default:
        type = XMLTypeOfNotificationType.INFORMATION;
        break;
    }
    xmlNotification.setNotificationType(type);

    xmlNotification.setRecipients(new XMLRecipients());
    if (notification.getRecipients() != null) {
        for (String recipient : notification.getRecipients()) {
            XMLRecipientType xrt = new XMLRecipientType();
            xrt.setType(XMLTypeOfRecipientType.USERNAME);
            xrt.setValue(recipient);
            xmlNotification.getRecipients().getRecipient().add(xrt);
        }
    }
    logger.trace("createXMLNotificationType result {}", xmlNotification);
    return xmlNotification;
}

From source file:org.oscarehr.PMmodule.web.ManageConsent.java

public boolean displayAsSelectedExpiry(int months) {
    if (previousConsentToView == null)
        return (months == -1);
    else {//from ww w.  ja va2  s .c o m
        if (previousConsentToView.getExpiry() == null)
            return (months == -1);
        else {
            GregorianCalendar cal1 = new GregorianCalendar();
            cal1.setTime(previousConsentToView.getCreatedDate());
            cal1.add(Calendar.MONTH, months);

            return (DateUtils.isSameDay(cal1.getTime(), previousConsentToView.getExpiry()));
        }
    }
}

From source file:org.webcat.grader.graphs.StackedAreaChart.java

@Override
protected JFreeChart generateChart(WCChartTheme chartTheme) {
    JFreeChart chart = ChartFactory.createStackedXYAreaChart(null, xAxisLabel(), yAxisLabel(), tableXYDataset(),
            orientation(), true, false, false);

    XYPlot plot = chart.getXYPlot();/*from  w w  w .  jav  a2s.  c  om*/

    long diff = (long) tableXYDataset().getXValue(0, tableXYDataset().getItemCount() - 1)
            - (long) tableXYDataset().getXValue(0, 0);

    GregorianCalendar calDiff = new GregorianCalendar();
    calDiff.setTime(new NSTimestamp(diff));

    // Set the time axis
    PeriodAxis axis = new PeriodAxis(null); // ( "Date" );
    PeriodAxisLabelInfo labelinfo[] = new PeriodAxisLabelInfo[2];

    if (calDiff.get(Calendar.DAY_OF_YEAR) > 1) {
        axis.setTimeZone(TimeZone.getTimeZone(user().timeZoneName()));
        axis.setAutoRangeTimePeriodClass(org.jfree.data.time.Day.class);
        axis.setMajorTickTimePeriodClass(org.jfree.data.time.Week.class);

        labelinfo[0] = new PeriodAxisLabelInfo(org.jfree.data.time.Day.class, new SimpleDateFormat("d"),
                PeriodAxisLabelInfo.DEFAULT_INSETS, chartTheme.smallFont(), chartTheme.textColor(), true,
                PeriodAxisLabelInfo.DEFAULT_DIVIDER_STROKE, PeriodAxisLabelInfo.DEFAULT_DIVIDER_PAINT);

        labelinfo[1] = new PeriodAxisLabelInfo(org.jfree.data.time.Month.class, new SimpleDateFormat("MMM"),
                PeriodAxisLabelInfo.DEFAULT_INSETS, chartTheme.smallFont(), chartTheme.textColor(), true,
                PeriodAxisLabelInfo.DEFAULT_DIVIDER_STROKE, PeriodAxisLabelInfo.DEFAULT_DIVIDER_PAINT);
    } else {
        axis.setAutoRangeTimePeriodClass(org.jfree.data.time.Hour.class);

        labelinfo[0] = new PeriodAxisLabelInfo(org.jfree.data.time.Day.class, new SimpleDateFormat("ha"),
                PeriodAxisLabelInfo.DEFAULT_INSETS, chartTheme.smallFont(), chartTheme.textColor(), true,
                PeriodAxisLabelInfo.DEFAULT_DIVIDER_STROKE, PeriodAxisLabelInfo.DEFAULT_DIVIDER_PAINT);

        labelinfo[1] = new PeriodAxisLabelInfo(org.jfree.data.time.Month.class, new SimpleDateFormat("MMM-d"),
                PeriodAxisLabelInfo.DEFAULT_INSETS, chartTheme.smallFont(), chartTheme.textColor(), true,
                PeriodAxisLabelInfo.DEFAULT_DIVIDER_STROKE, PeriodAxisLabelInfo.DEFAULT_DIVIDER_PAINT);
    }

    axis.setLabelInfo(labelinfo);
    plot.setDomainAxis(axis);

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    NumberTickUnit tickUnit = new NumberTickUnit(5);
    rangeAxis.setTickUnit(tickUnit);

    XYAreaRenderer2 renderer = (XYAreaRenderer2) plot.getRenderer();
    renderer.setOutline(true);
    renderer.setAutoPopulateSeriesOutlinePaint(true);

    plot.setDomainMinorGridlinesVisible(false);
    plot.setRangeMinorGridlinesVisible(false);

    if (markValue != null) {
        plot.setDomainCrosshairVisible(true);
        plot.setDomainCrosshairValue(markValue.doubleValue());
        plot.setDomainCrosshairPaint(Color.red);
        plot.setDomainCrosshairStroke(MARKER_STROKE);
    }

    chart.getLegend().setBorder(0, 0, 0, 0);

    return chart;
}

From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java

/**
 *
 * Generates and saves info.xml// www . j  a  v  a 2  s  .c  o  m
 *
 * @param path
 * @param mets
 */
public static void saveInfoFile(String path, MetsContext metsContext, String md5, String fileMd5Name,
        File metsFile) throws MetsExportException {
    File infoFile = new File(path + File.separator + metsContext.getPackageID() + File.separator + "info_"
            + metsContext.getPackageID() + ".xml");
    GregorianCalendar c = new GregorianCalendar();
    c.setTime(new Date());
    XMLGregorianCalendar date2;
    try {
        date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    } catch (DatatypeConfigurationException e1) {
        throw new MetsExportException("Error while generating info.xml file", false, e1);
    }
    Info infoJaxb = new Info();
    infoJaxb.setCreated(date2);
    infoJaxb.setMainmets("./" + metsFile.getName());
    Checksum checkSum = new Checksum();
    checkSum.setChecksum(md5);
    checkSum.setType("MD5");
    addModsIdentifiersRecursive(metsContext.getRootElement(), infoJaxb);
    checkSum.setValue(fileMd5Name);
    infoJaxb.setChecksum(checkSum);
    Validation validation = new Validation();
    validation.setValue("W3C-XML");
    validation.setVersion(Float.valueOf("0.0"));
    infoJaxb.setValidation(validation);
    infoJaxb.setCreator(metsContext.getCreatorOrganization());
    infoJaxb.setPackageid(metsContext.getPackageID());
    if (Const.PERIODICAL_TITLE.equalsIgnoreCase(metsContext.getRootElement().getElementType())) {
        infoJaxb.setMetadataversion((float) 1.5);
    } else {
        infoJaxb.setMetadataversion((float) 1.1);
    }
    Itemlist itemList = new Itemlist();
    infoJaxb.setItemlist(itemList);
    itemList.setItemtotal(BigInteger.valueOf(metsContext.getFileList().size()));
    List<FileMD5Info> fileList = metsContext.getFileList();
    long size = 0;
    for (FileMD5Info fileName : fileList) {
        itemList.getItem()
                .add(fileName.getFileName().replaceAll(Matcher.quoteReplacement(File.separator), "/"));
        size += fileName.getSize();
    }
    int infoTotalSize = (int) (size / 1024);
    infoJaxb.setSize(infoTotalSize);
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Info.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        // SchemaFactory factory =
        // SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        // factory.setResourceResolver(MetsLSResolver.getInstance());
        // Schema schema = factory.newSchema(new
        // StreamSource(Info.class.getResourceAsStream("info.xsd")));
        // marshaller.setSchema(schema);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
        marshaller.marshal(infoJaxb, infoFile);
    } catch (Exception ex) {
        throw new MetsExportException("Error while generating info.xml", false, ex);
    }

    List<String> validationErrors;
    try {
        validationErrors = MetsUtils.validateAgainstXSD(infoFile, Info.class.getResourceAsStream("info.xsd"));
    } catch (Exception e) {
        throw new MetsExportException("Error while validating info.xml", false, e);
    }

    if (validationErrors.size() > 0) {
        MetsExportException metsException = new MetsExportException(
                "Invalid info file:" + infoFile.getAbsolutePath(), false, null);
        metsException.getExceptions().get(0).setValidationErrors(validationErrors);
        for (String error : validationErrors) {
            LOG.fine(error);
        }
        throw metsException;
    }
}