Example usage for java.util GregorianCalendar GregorianCalendar

List of usage examples for java.util GregorianCalendar GregorianCalendar

Introduction

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

Prototype

public GregorianCalendar() 

Source Link

Document

Constructs a default GregorianCalendar using the current time in the default time zone with the default Locale.Category#FORMAT FORMAT locale.

Usage

From source file:com.splicemachine.db.iapi.types.SQLDateTest.java

@Test
public void serdeKeyData() throws Exception {
    GregorianCalendar gc = new GregorianCalendar();
    SQLDate value1 = new SQLDate(new Date(97, 9, 7));
    SQLDate value2 = new SQLDate(new Date(97, 10, 7));
    SQLDate value1a = new SQLDate();
    SQLDate value2a = new SQLDate();
    PositionedByteRange range1 = new SimplePositionedMutableByteRange(value1.encodedKeyLength());
    PositionedByteRange range2 = new SimplePositionedMutableByteRange(value2.encodedKeyLength());
    value1.encodeIntoKey(range1, Order.ASCENDING);
    value2.encodeIntoKey(range2, Order.ASCENDING);
    Assert.assertTrue("Positioning is Incorrect",
            Bytes.compareTo(range1.getBytes(), 0, 9, range2.getBytes(), 0, 9) < 0);
    range1.setPosition(0);//from   w  w w. j a v a  2  s  . c  o  m
    range2.setPosition(0);
    value1a.decodeFromKey(range1);
    value2a.decodeFromKey(range2);
    Assert.assertEquals("1 incorrect", value1.getDate(gc), value1a.getDate(gc));
    Assert.assertEquals("2 incorrect", value2.getDate(gc), value2a.getDate(gc));
}

From source file:com.teamsun.framework.util.DateUtil.java

/**
 * This method returns the current date in the format: yyyy-MM-dd
 * //from   w ww .j  a va2  s .c  om
 * @return the current date
 * @throws ParseException
 */
public static Calendar getToday() throws ParseException {
    Date today = new Date();
    SimpleDateFormat df = new SimpleDateFormat(datePattern);

    // This seems like quite a hack (date -> string -> date),
    // but it works ;-)
    String todayAsString = df.format(today);
    Calendar cal = new GregorianCalendar();
    cal.setTime(convertStringToDate(todayAsString));

    return cal;
}

From source file:net.firejack.platform.core.utils.DateUtils.java

/**
 * Decrements the date by one hour//from   ww w  .  j a v a2 s . c  o  m
 * @param date - date to be decremented
 */
public static void decDateByHour(Date date) {
    Calendar cal = new GregorianCalendar();
    cal.setTime(date);
    cal.add(Calendar.HOUR, -1);
    date.setTime(cal.getTimeInMillis());
}

From source file:br.com.semanticwot.cd.controllers.SwotApplicationController.java

@RequestMapping(method = RequestMethod.POST, name = "saveApplication")
public ModelAndView save(@Valid SwotApplicationForm swotApplicationForm, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, Authentication authentication) {

    if (bindingResult.hasErrors()) {
        return form(swotApplicationForm, authentication);
    }//from   w w  w .j  a  v a 2 s .  co m

    SystemUser systemUser = (SystemUser) authentication.getPrincipal();

    SwotApplication swotApplication = null;

    try {
        swotApplication = swotApplicationDAO.findOne(systemUser);
    } catch (EmptyResultDataAccessException ex) {
    }

    if (swotApplication == null) {
        swotApplication = new SwotApplication();
    }

    swotApplication.setName(swotApplicationForm.getName());
    swotApplication.setDescription(swotApplicationForm.getDescription());

    Calendar calendar = new GregorianCalendar();
    swotApplication.setReleaseDate(calendar);
    swotApplication.setSystemUser(systemUser);

    swotApplicationDAO.update(swotApplication);

    return new ModelAndView("redirect:/#three");
}

From source file:com.fivesticks.time.activity.ActivityResolver.java

public Date resolve() {

    Calendar c = new GregorianCalendar();
    c.setTime(date);/*from   w w  w .j  av  a2 s .c om*/

    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);

    parseActivityString();

    Calendar c2 = new GregorianCalendar(year, month, day, this.getResolvedHours(), this.getResolvedMinutes());
    Date ret = new Date();
    ret.setTime(c2.getTimeInMillis());

    return ret;
}

From source file:com.rogers.ute.creditservice.util.CreditServiceUtils.java

public static XMLGregorianCalendar asXMLGregorianCalendar(Date date) {
    try {/*from  w w w  .ja  v  a  2  s .co  m*/
        GregorianCalendar instance = new GregorianCalendar();
        instance.setTime(date);
        return DatatypeFactory.newInstance().newXMLGregorianCalendar(instance);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.seedstack.monitoring.batch.internal.rest.jobinstance.JobInstanceResource.java

/**
 * Retrieves the list of job instances by job name.
 *
 * @param jobName  the job name//from ww  w  .j  a va2 s.  c om
 * @param startJob the start job
 * @param pageSize the page size
 * @return the response
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response listJobInstancesForJobs(@PathParam("jobName") String jobName,
        @DefaultValue("0") @QueryParam("startJob") int startJob,
        @DefaultValue("20") @QueryParam("pageSize") int pageSize) {

    try {

        Collection<JobInstance> result = jobService.listJobInstances(jobName, startJob, pageSize);
        Collection<JobInstanceRepresentation> jobInstancesRepresentations = new ArrayList<JobInstanceRepresentation>();
        for (JobInstance jobInstance : result) {
            Collection<JobExecutionInfo> executionRepresentations = new ArrayList<JobExecutionInfo>();

            Collection<JobExecution> jobExecutionsForJobInstance = jobService
                    .getJobExecutionsForJobInstance(jobName, jobInstance.getId());

            for (JobExecution jobExecution : jobExecutionsForJobInstance) {
                executionRepresentations
                        .add(new JobExecutionInfo(jobExecution, new GregorianCalendar().getTimeZone()));
                jobInstancesRepresentations.add(new JobInstanceRepresentation(jobInstance.getJobName(),
                        jobInstance.getId(), jobExecution.getJobParameters(), executionRepresentations));
            }

        }
        return Response.ok(jobInstancesRepresentations).build();
    } catch (NoSuchJobException e) {
        String error = "There is no such job (" + jobName + ")";
        return Response.status(Response.Status.BAD_REQUEST).entity(error).type(MediaType.TEXT_PLAIN).build();
    }

}

From source file:edu.stanford.muse.email.WebPageThumbnail.java

/** create a dataset and emit top level pages */
public static void fetchWebPageThumbnails(String rootDir, String prefix, List<Document> allDocs,
        boolean archivedPages, int limit) throws IOException, JSONException {
    List<LinkInfo> links = EmailUtils.getLinksForDocs(allDocs);

    // compute map of url -> doc
    Map<String, List<Document>> fmap = new LinkedHashMap<String, List<Document>>();
    for (LinkInfo li : links) {
        List<Document> lis = fmap.get(li);
        if (lis == null) {
            lis = new ArrayList<Document>();
            fmap.put(li.link, lis);//from  w ww . j a  v a 2s. c o m
        }
        lis.add(li.doc);
    }

    List<Blob> allDatas = new ArrayList<Blob>();
    BlobStore data_store = new BlobStore(rootDir + File.separator + "blobs");

    int successes = 0;
    outer: for (String url : fmap.keySet()) {
        List<Document> lis = fmap.get(url);
        for (Document doc : lis) {
            if (doc instanceof DatedDocument) {
                String targetURL = url;
                DatedDocument dd = ((DatedDocument) doc);
                if (archivedPages) {
                    Calendar c = new GregorianCalendar();
                    c.setTime(((DatedDocument) doc).date);
                    String archiveDate = c.get(Calendar.YEAR) + String.format("%02d", c.get(Calendar.MONTH))
                            + String.format("%02d", c.get(Calendar.DATE)) + "120000";
                    // color dates
                    targetURL = "http://web.archive.org/" + archiveDate + "/" + url;
                }

                try {
                    // the name is just the URL, so that different URLs have a different Data
                    String sanitizedURL = Util.sanitizeFolderName(targetURL); // targetURL is not really a folder name, but all we want is to convert the '/' to __
                    WebPageThumbnail wpt = new WebPageThumbnail(sanitizedURL + ".png", dd); /// 10K as a dummy ??
                    boolean targetURLIsHTML = !(Util.is_image_filename(targetURL)
                            || Util.is_office_document(targetURL) || Util.is_pdf_filename(targetURL));

                    if (!data_store.contains(wpt)) {
                        // download the html page first
                        HttpClient client = new HttpClient();
                        String tmpFile = File.createTempFile("webtn.", ".tmp").getAbsolutePath();
                        GetMethod get = new GetMethod(targetURL);
                        int statusCode = client.executeMethod(get);
                        if (statusCode == 200) {
                            // execute method and handle any error responses.
                            InputStream in = get.getResponseBodyAsStream();
                            // Process the data from the input stream.
                            Util.copy_stream_to_file(in, tmpFile);
                            get.releaseConnection();

                            if (targetURLIsHTML) {
                                // use jtidy to convert it to xhtml
                                String tmpXHTMLFile = File.createTempFile("webtn.", ".xhtml").getAbsolutePath();
                                Tidy tidy = new Tidy(); // obtain a new Tidy instance
                                tidy.setXHTML(true); // set desired config options using tidy setters
                                InputStream is = new FileInputStream(tmpFile);
                                OutputStream os = new FileOutputStream(tmpXHTMLFile);
                                tidy.parse(is, os); // run tidy, providing an input and output stream
                                try {
                                    is.close();
                                } catch (Exception e) {
                                }
                                try {
                                    os.close();
                                } catch (Exception e) {
                                }

                                // use xhtmlrenderer to convert it to a png
                                File pngFile = File.createTempFile("webtn.", ".png");
                                BufferedImage buff = null;
                                String xhtmlURL = new File(tmpXHTMLFile).toURI().toString();
                                buff = Graphics2DRenderer.renderToImage(xhtmlURL, 640, 480);
                                ImageIO.write(buff, "png", pngFile);
                                data_store.add(wpt, new FileInputStream(pngFile));
                            } else {
                                data_store.add(wpt, new FileInputStream(tmpFile));
                                if (Util.is_pdf_filename(targetURL))
                                    data_store.generate_thumbnail(wpt);
                            }
                            successes++;
                            if (successes == limit)
                                break outer;
                        } else
                            log.info("Unable to GET targetURL " + targetURL + " status code = " + statusCode);
                    }

                    allDatas.add(wpt);
                } catch (Exception e) {
                    log.warn(Util.stackTrace(e));
                } catch (Error e) {
                    log.warn(Util.stackTrace(e));
                }
            }

            if (!archivedPages)
                break; // only need to show one page if we're not showing archives
        }
    }
    BlobSet bs = new BlobSet(rootDir, allDatas, data_store);
    bs.generate_top_level_page(prefix);
}

From source file:at.alladin.rmbt.statisticServer.UsageJSONResource.java

@Get("json")
public String request(final String entity) {
    JSONObject result = new JSONObject();
    int month = -1;
    int year = -1;
    try {//from www  .  j  ava  2  s. c  om
        //parameters
        final Form getParameters = getRequest().getResourceRef().getQueryAsForm();
        try {

            if (getParameters.getNames().contains("month")) {
                month = Integer.parseInt(getParameters.getFirstValue("month"));
                if (month > 11 || month < 0) {
                    throw new NumberFormatException();
                }
            }
            if (getParameters.getNames().contains("year")) {
                year = Integer.parseInt(getParameters.getFirstValue("year"));
                if (year < 0) {
                    throw new NumberFormatException();
                }
            }
        } catch (NumberFormatException e) {
            return "invalid parameters";
        }

        Calendar now = new GregorianCalendar();
        Calendar monthBegin = new GregorianCalendar((year > 0) ? year : now.get(Calendar.YEAR),
                (month >= 0) ? month : now.get(Calendar.MONTH), 1);
        Calendar monthEnd = new GregorianCalendar((year > 0) ? year : now.get(Calendar.YEAR),
                (month >= 0) ? month : now.get(Calendar.MONTH),
                monthBegin.getActualMaximum(Calendar.DAY_OF_MONTH));
        //if now -> do not use the last day
        if (month == now.get(Calendar.MONTH) && year == now.get(Calendar.YEAR)) {
            monthEnd = now;
            monthEnd.add(Calendar.DATE, -1);
        }

        JSONObject platforms = getPlatforms(new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject usage = getClassicUsage(new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject versionsIOS = getVersions("iOS", new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject versionsAndroid = getVersions("Android", new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject versionsApplet = getVersions("Applet", new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject networkGroupNames = getNetworkGroupName(new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        JSONObject networkGroupTypes = getNetworkGroupType(new Timestamp(monthBegin.getTimeInMillis()),
                new Timestamp(monthEnd.getTimeInMillis()));
        result.put("platforms", platforms);
        result.put("usage", usage);
        result.put("versions_ios", versionsIOS);
        result.put("versions_android", versionsAndroid);
        result.put("versions_applet", versionsApplet);
        result.put("network_group_names", networkGroupNames);
        result.put("network_group_types", networkGroupTypes);
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return result.toString();
}

From source file:me.ryandowling.allmightybot.commands.QuoteCommand.java

@Override
public boolean run(AllmightyBot bot, MessageEvent event) {
    if (super.run(bot, event)) {
        switch (this.quoteType) {
        case NEW:
            List<String> arguments = Utils.getCommandsArguments(1, event.getMessage(), true);

            if (arguments.size() != 1) {
                return false;
            }//from   ww w.  j  a va2s. c  om

            quotes.add(new Quote(arguments.get(0)));

            event.getChannel().send().message(bot.getLangValue("newQuoteAdded"));
            break;
        case SAY:
            List<String> arguments1 = Utils.getCommandsArguments(event.getMessage(), true);

            if (arguments1.size() == 0) {
                if (quotes.size() == 0) {
                    return false;
                }

                Random random = new Random();
                Quote randomQuote = quotes.get(random.nextInt(quotes.size()));

                Calendar cal = new GregorianCalendar();
                cal.setTime(randomQuote.getDate());

                event.getChannel().send()
                        .message(Utils.replaceVariablesInString(bot.getLangValue("sayQuote"),
                                randomQuote.getQuote(), bot.getSettings().getCastersName(),
                                cal.get(Calendar.YEAR) + ""));
            } else if (arguments1.size() == 1) {
                List<ChatLog> logs = bot.getUsersChatLog(arguments1.get(0));

                if (logs == null || logs.size() == 0) {
                    return false;
                }

                Random random = new Random();
                ChatLog randomQuote;
                int tries = 0;

                do {
                    tries++;
                    randomQuote = logs.get(random.nextInt(logs.size()));
                } while (tries <= 100 && randomQuote.getMessage().startsWith("!"));

                if (randomQuote.getMessage().startsWith("!")) {
                    return false;
                }

                Calendar cal = new GregorianCalendar();
                cal.setTime(randomQuote.getTime());

                event.getChannel().send().message(Utils.replaceVariablesInString(bot.getLangValue("sayQuote"),
                        randomQuote.getMessage(), randomQuote.getUser(),
                        Utils.getPrintableMonth(cal.get(Calendar.MONTH)) + " " + cal.get(Calendar.YEAR)));
            }
            break;
        }
        return true;
    }

    return false;
}