Example usage for java.util GregorianCalendar getTime

List of usage examples for java.util GregorianCalendar getTime

Introduction

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

Prototype

public final Date getTime() 

Source Link

Document

Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").

Usage

From source file:org.apache.torque.generated.peer.DefaultValuesFromJavaTest.java

/**
 * Checks that if CURRENT_TIME is used as default value
 * then an object is constructed with current java time.
 *
 * @throws Exception if an error occurs.
 *//*from  w  w w.  j  a  v a  2 s  .c o  m*/
public void testCurrentTimeAsJavaDefault() throws Exception {
    if (defaultAdapter instanceof OracleAdapter || defaultAdapter instanceof MssqlAdapter
            || defaultAdapter instanceof MysqlAdapter) {
        log.error("testCurrentTimeAsJavaDefault(): " + "Oracle, MSSQL and Mysql do not support "
                + "the CURRENT_TIME function");
        return;
    }
    GregorianCalendar currentCalendarBefore = new GregorianCalendar();
    currentCalendarBefore.set(1970, 1, 1);
    JavaDefaultValues javaDefaultValues = new JavaDefaultValues();
    GregorianCalendar currentCalendarAfter = new GregorianCalendar();
    currentCalendarAfter.set(1970, 1, 1);
    assertFalse("currentTime should be >= currentCalendarBefore",
            javaDefaultValues.getCurrentTimeValue().before(currentCalendarBefore.getTime()));
    assertFalse("currentTime should be <= currentDateAfter",
            javaDefaultValues.getCurrentTimeValue().after(currentCalendarAfter.getTime()));
}

From source file:org.jfree.data.time.WeekTest.java

/**
 * A test case for bug 1498805./* w  w w  .  ja v a2  s. c  o  m*/
 */
@Test
public void testBug1498805() {
    Locale saved = Locale.getDefault();
    Locale.setDefault(Locale.UK);
    try {
        TimeZone zone = TimeZone.getTimeZone("GMT");
        GregorianCalendar gc = new GregorianCalendar(zone);
        gc.set(2005, Calendar.JANUARY, 1, 12, 0, 0);
        Week w = new Week(gc.getTime(), zone);
        assertEquals(53, w.getWeek());
        assertEquals(new Year(2004), w.getYear());
    } finally {
        Locale.setDefault(saved);
    }
}

From source file:com.handywedge.binarystore.store.azure.BinaryStoreManagerImpl.java

private BinaryInfo createReturnBinaryInfo(CloudBlockBlob blob) throws StoreException {
    BinaryInfo binary = new BinaryInfo();
    try {//from w  w  w . j a v a2  s  .c om
        if (blob.exists()) {
            long milliSeconds = Long.parseLong(PropertiesUtil.get("abs.presignedurl.expiration"));

            binary.setBucketName(blob.getContainer().getName());
            binary.setFileName(blob.getName());
            binary.setContentType(blob.getProperties().getContentType());
            binary.setSize(blob.getProperties().getLength());
            binary.setUrl(blob.getUri().toString());

            // Policy
            SharedAccessBlobPolicy itemPolicy = new SharedAccessBlobPolicy();

            GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            calendar.setTime(new Date());
            itemPolicy.setSharedAccessStartTime(calendar.getTime());

            calendar.add(Calendar.SECOND, (int) (milliSeconds / 1000));
            itemPolicy.setSharedAccessExpiryTime(calendar.getTime());

            itemPolicy.setPermissions(
                    EnumSet.of(SharedAccessBlobPermissions.LIST, SharedAccessBlobPermissions.READ));

            String sasToken = blob.generateSharedAccessSignature(itemPolicy, null);
            Thread.sleep(1500);

            String sasUri = String.format("%s?%s", blob.getUri().toString(), sasToken);
            binary.setPresignedUrl(sasUri);

            logger.debug(" ????URL: {}", binary.getUrl());
            logger.debug(" ????URL: {}", binary.getPresignedUrl());

        } else {
            binary = null;
        }
    } catch (URISyntaxException ue) {
        throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL,
                ue, blob.getName());
    } catch (NumberFormatException ne) {
        throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL,
                ne, blob.getName());
    } catch (InvalidKeyException ie) {
        throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL,
                ie, blob.getName());
    } catch (InterruptedException ite) {
        throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL,
                ite, blob.getName());
    } catch (StorageException se) {
        throw new StoreException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorClassification.CREATE_BINARY_FAIL,
                se, blob.getName());
    }

    return binary;
}

From source file:com.googlecode.networklog.ExportDialog.java

public ExportDialog(final Context context) {
    this.context = context;
    Resources res = context.getResources();
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.exportdialog, null);

    startDateButton = (Button) view.findViewById(R.id.exportStartDateButton);
    endDateButton = (Button) view.findViewById(R.id.exportEndDateButton);
    filenameButton = (Button) view.findViewById(R.id.exportFilenameButton);

    GregorianCalendar today = new GregorianCalendar();
    startDate = new GregorianCalendar(today.get(Calendar.YEAR), today.get(Calendar.MONTH), 1).getTime();
    endDate = today.getTime();
    file = new File(
            Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + defaultFilename());

    startDateButton.setText(dateDisplayFormat.format(startDate));
    endDateButton.setText(dateDisplayFormat.format(endDate));
    filenameButton.setText(file.getAbsolutePath());

    startDateButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            datePickerMode = DatePickerMode.START_DATE;
            DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    startDate = new GregorianCalendar(year, month, day).getTime();
                    startDateButton.setText(dateDisplayFormat.format(startDate));
                    updateFilename();//from w w  w .  j  a  v a2 s. co  m
                }
            };

            Calendar cal = Calendar.getInstance();
            cal.setTime(startDate);
            DialogFragment newFragment = new DatePickerFragment(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH), listener);
            newFragment.show(NetworkLog.instance.getSupportFragmentManager(), "exportDatePicker");
        }
    });

    endDateButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            datePickerMode = DatePickerMode.END_DATE;
            DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(DatePicker view, int year, int month, int day) {
                    endDate = new GregorianCalendar(year, month, day, 23, 59, 59).getTime();
                    endDateButton.setText(dateDisplayFormat.format(endDate));
                    updateFilename();
                }
            };

            Calendar cal = Calendar.getInstance();
            cal.setTime(endDate);
            DialogFragment newFragment = new DatePickerFragment(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH), listener);
            newFragment.show(NetworkLog.instance.getSupportFragmentManager(), "exportDatePicker");
        }
    });

    filenameButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            OnHandleFileListener saveListener = new OnHandleFileListener() {
                public void handleFile(final String filePath) {
                    file = new File(filePath);
                    filenameButton.setText(filePath);
                }
            };
            new FileSelector(context, FileOperation.SAVE, saveListener, defaultFilename(),
                    new String[] { "*.*", "*.csv" }).show();
        }
    });

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(res.getString(R.string.export_title)).setView(view).setCancelable(true)
            .setPositiveButton(res.getString(R.string.export_button), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface d, int id) {
                    // see show() method for implementation -- avoids dismiss() unless validation passes
                }
            }).setNegativeButton(res.getString(R.string.cancel), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface d, int id) {
                    dialog.cancel();
                    dialog = null;
                }
            });
    dialog = builder.create();
}

From source file:net.acesinc.nifi.processors.json.BetterAttributesToJSON.java

/**
 * Builds the Map of attributes that should be included in the JSON that is
 * emitted from this process.//from   ww w.  j a v a2 s .  c o  m
 *
 * @param ff
 * @param atrListForStringValues
 * @param atrListForIntValues
 * @param atrListForDoubleValues
 * @param atrListForLongEpochToGoToDateValues
 * @return Map of values that are feed to a Jackson ObjectMapper
 * @throws java.io.IOException
 */
protected Map<String, Object> buildAttributesMapAndBringInFlowAttrs(FlowFile ff, String atrListForStringValues,
        String atrListForIntValues, String atrListForDoubleValues, String atrListForLongEpochToGoToDateValues)
        throws IOException {
    Map<String, Object> atsToWrite = new HashMap<>();

    //handle all the string values
    //If list of attributes specified get only those attributes. Otherwise write them all
    if (StringUtils.isNotBlank(atrListForStringValues)) {
        String[] ats = StringUtils.split(atrListForStringValues, AT_LIST_SEPARATOR);
        if (ats != null) {
            for (String str : ats) {
                String cleanStr = str.trim();
                String val = ff.getAttribute(cleanStr);
                if (val != null) {
                    atsToWrite.put(cleanStr, val);
                } else {
                    atsToWrite.put(cleanStr, "");
                }
            }
        }

    } else {
        atsToWrite.putAll(ff.getAttributes());
    }
    //handle all int values
    if (StringUtils.isNotBlank(atrListForIntValues)) {
        String[] ats = StringUtils.split(atrListForIntValues, AT_LIST_SEPARATOR);
        if (ats != null) {
            for (String str : ats) {
                String cleanStr = str.trim();
                String val = ff.getAttribute(cleanStr);
                if (val != null) {
                    atsToWrite.put(cleanStr, Integer.parseInt(val));
                } else {
                    atsToWrite.put(cleanStr, null);
                }
            }
        }
    }
    //handle all double values
    if (StringUtils.isNotBlank(atrListForDoubleValues)) {
        String[] ats = StringUtils.split(atrListForDoubleValues, AT_LIST_SEPARATOR);
        if (ats != null) {
            for (String str : ats) {
                String cleanStr = str.trim();
                String val = ff.getAttribute(cleanStr);
                if (val != null) {
                    atsToWrite.put(cleanStr, Double.parseDouble(val));
                } else {
                    atsToWrite.put(cleanStr, null);
                }
            }
        }
    }
    //handle all date values
    if (StringUtils.isNotBlank(atrListForLongEpochToGoToDateValues)) {
        String[] ats = StringUtils.split(atrListForLongEpochToGoToDateValues, AT_LIST_SEPARATOR);
        if (ats != null) {
            for (String str : ats) {
                String cleanStr = str.trim();
                String val = ff.getAttribute(cleanStr);
                if (val != null) {
                    long epochTime = Long.parseLong(val);
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeZone(TimeZone.getTimeZone(MONGO_TIME_ZONE));
                    gcal.setTimeInMillis(epochTime);
                    SimpleDateFormat sdf = new SimpleDateFormat(MONGO_DATE_TEMPLATE);
                    String mongoDate = sdf.format(gcal.getTime());
                    //to Date
                    Map<String, String> isoDate = new HashMap<>();
                    isoDate.put("$date", mongoDate);
                    atsToWrite.put(cleanStr, isoDate);
                } else {
                    atsToWrite.put(cleanStr, null);
                }
            }
        }
    }

    return atsToWrite;
}

From source file:airport.dispatcher.infrastructure.AirportRunawaysImpl.java

private void setTaimer(int runawayId) {
    if (LOG.isInfoEnabled()) {
        LOG.info("create task");
    }//from  ww w .j  a  va 2  s . co  m

    JobDataMap dataMap = new JobDataMap();
    dataMap.put(PARAMETER_RUNAWAY_ID, runawayId);
    dataMap.put(PARAMETER_RUNAWAY_DAO, runawayDao);

    GregorianCalendar calendar = new GregorianCalendar();
    calendar.add(GregorianCalendar.SECOND, DELAY_TIMER_LEBIRATE);

    JobDetail jobDetail = newJob(JobLebirateRunaway.class)
            .withIdentity(SCHEDULLER_JOBDET_NAME + schedduler_name_count, SCHEDULLER_GROUP_NAME)
            .setJobData(dataMap).build();

    Trigger trigger = newTrigger()
            .withIdentity(SCHEDULLER_TRIGGER_NAME + schedduler_name_count, SCHEDULLER_GROUP_NAME)
            .startAt(calendar.getTime()).withSchedule(SimpleScheduleBuilder.simpleSchedule()).build();

    if (schedduler_name_count == Integer.MAX_VALUE) {
        schedduler_name_count = 0;
    } else {
        schedduler_name_count++;
    }

    try {
        scheduler.scheduleJob(jobDetail, trigger);

        scheduler.start();
    } catch (SchedulerException ex) {
        if (LOG.isInfoEnabled()) {
            LOG.info("error start taimer", ex);
        }
    }
}

From source file:org.hardisonbrewing.s3j.FileSyncer.java

private long getLastModified(ListEntry listEntry) {

    XMLGregorianCalendar xmlGregorianCalendar = listEntry.getLastModified();
    GregorianCalendar gregorianCalendar = xmlGregorianCalendar.toGregorianCalendar();
    Date date = gregorianCalendar.getTime();
    return date.getTime();
}

From source file:fr.esrf.icat.manager.core.part.SameEntitiesMenuContribution.java

private String makeFieldFilter(final List<WrappedEntityBean> selection, final String fieldName) {
    final List<Object> values = new LinkedList<>();
    for (WrappedEntityBean bean : selection) {
        try {// w w  w.j a v a  2  s .  c o m
            final Object v = bean.get(fieldName);
            if (null != v) {
                values.add(v);
            }
        } catch (Exception e) {
            String simpleName = null;
            try {
                simpleName = bean.getEntityName();
                LOG.error("Error getting field {} from {}", fieldName, simpleName, e);
            } catch (IllegalArgumentException e1) {
                LOG.error("Error getting field {} from {}: {}", fieldName, simpleName,
                        "ERROR getting name: " + e1.getMessage(), e);
            }
        }
    }
    if (values.size() == 0) {
        return null;
    }
    StringBuilder b = new StringBuilder();
    boolean first = true;
    for (Object v : values) {
        if (first) {
            first = false;
        } else {
            b.append(" OR ");
        }
        if (v instanceof String) {
            b.append("(");
            b.append(fieldName);
            b.append("=");
            b.append("'");
            b.append(v);
            b.append("'");
            b.append(")");
        } else if (v instanceof Boolean) {
            b.append("(");
            b.append(fieldName);
            b.append("=");
            b.append(v.toString().toUpperCase());
            b.append(")");
        } else if (v instanceof XMLGregorianCalendar) {
            final GregorianCalendar calendar = ((XMLGregorianCalendar) v).toGregorianCalendar();
            QUERY_DATE_FORMAT.setTimeZone(calendar.getTimeZone());
            b.append("(");
            b.append(fieldName);
            b.append(">");
            b.append("{ts ");
            b.append(QUERY_DATE_FORMAT.format(calendar.getTime()));
            b.append("}");
            b.append(" AND ");
            b.append(fieldName);
            b.append("<");
            b.append("{ts ");
            calendar.roll(Calendar.SECOND, true);
            b.append(QUERY_DATE_FORMAT.format(calendar.getTime()));
            b.append("}");
            b.append(")");
        } else {
            b.append("(");
            b.append(fieldName);
            b.append("=");
            b.append(v);
            b.append(")");
        }
    }
    return b.toString();
}

From source file:org.apache.tuscany.sca.binding.rest.provider.RESTBindingInvoker.java

public Message invoke(Message msg) {

    Object entity = null;/*from w  w w. j  a v  a  2  s .c  o m*/
    Object[] args = msg.getBody();

    URI uri = URI.create(endpointReference.getDeployedURI());
    UriBuilder uriBuilder = UriBuilder.fromUri(uri);

    Method method = ((JavaOperation) operation).getJavaMethod();

    if (method.isAnnotationPresent(Path.class)) {
        // Only for resource method
        uriBuilder.path(method);
    }

    if (!JAXRSHelper.isResourceMethod(method)) {
        // This is RPC over GET
        uriBuilder.replaceQueryParam("method", method.getName());
    }

    Map<String, Object> pathParams = new HashMap<String, Object>();
    Map<String, Object> matrixParams = new HashMap<String, Object>();
    Map<String, Object> queryParams = new HashMap<String, Object>();
    Map<String, Object> headerParams = new HashMap<String, Object>();
    Map<String, Object> formParams = new HashMap<String, Object>();
    Map<String, Object> cookieParams = new HashMap<String, Object>();

    for (int i = 0; i < method.getParameterTypes().length; i++) {
        boolean isEntity = true;
        Annotation[] annotations = method.getParameterAnnotations()[i];
        PathParam pathParam = getAnnotation(annotations, PathParam.class);
        if (pathParam != null) {
            isEntity = false;
            pathParams.put(pathParam.value(), args[i]);
        }
        MatrixParam matrixParam = getAnnotation(annotations, MatrixParam.class);
        if (matrixParam != null) {
            isEntity = false;
            matrixParams.put(matrixParam.value(), args[i]);
        }
        QueryParam queryParam = getAnnotation(annotations, QueryParam.class);
        if (queryParam != null) {
            isEntity = false;
            queryParams.put(queryParam.value(), args[i]);
        }
        HeaderParam headerParam = getAnnotation(annotations, HeaderParam.class);
        if (headerParam != null) {
            isEntity = false;
            headerParams.put(headerParam.value(), args[i]);
        }
        FormParam formParam = getAnnotation(annotations, FormParam.class);
        if (formParam != null) {
            isEntity = false;
            formParams.put(formParam.value(), args[i]);
        }
        CookieParam cookieParam = getAnnotation(annotations, CookieParam.class);
        if (cookieParam != null) {
            isEntity = false;
            cookieParams.put(cookieParam.value(), args[i]);
        }
        isEntity = (getAnnotation(annotations, Context.class) == null);
        if (isEntity) {
            entity = args[i];
        }
    }

    for (Map.Entry<String, Object> p : queryParams.entrySet()) {
        uriBuilder.replaceQueryParam(p.getKey(), p.getValue());
    }
    for (Map.Entry<String, Object> p : matrixParams.entrySet()) {
        uriBuilder.replaceMatrixParam(p.getKey(), p.getValue());
    }

    uri = uriBuilder.buildFromMap(pathParams);
    Resource resource = restClient.resource(uri);

    for (Map.Entry<String, Object> p : headerParams.entrySet()) {
        resource.header(p.getKey(), String.valueOf(p.getValue()));
    }

    for (Map.Entry<String, Object> p : cookieParams.entrySet()) {
        Cookie cookie = new Cookie(p.getKey(), String.valueOf(p.getValue()));
        resource.cookie(cookie);
    }

    resource.contentType(getContentType());
    resource.accept(getAccepts());

    //handles declarative headers configured on the composite
    for (HTTPHeader header : binding.getHttpHeaders()) {
        //treat special headers that need to be calculated
        if (header.getName().equalsIgnoreCase("Expires")) {
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(new Date());

            calendar.add(Calendar.HOUR, Integer.parseInt(header.getValue()));

            resource.header("Expires", HTTPCacheContext.RFC822DateFormat.format(calendar.getTime()));
        } else {
            //default behaviour to pass the header value to HTTP response
            resource.header(header.getName(), header.getValue());
        }
    }

    Object result = resource.invoke(httpMethod, responseType, entity);
    msg.setBody(result);
    return msg;
}

From source file:org.apache.torque.generated.peer.DateTest.java

/**
 * Checks that a select is possible when milliseconds are used.
 * in databases where this is supported.
 *
 * @throws TorqueException if a problem occurs.
 *///from  w w  w. j a  v  a2  s .  c  o m
public void testSelectWithMillisecondsOnTimestampExactMatch() throws TorqueException {
    cleanDateTimeTimestampTable();

    // insert new DateTest object to db
    DateTimeTimestampType dateTimeTimestamp = new DateTimeTimestampType();
    dateTimeTimestamp.setDateValue(new Date());
    dateTimeTimestamp.setTimeValue(new Date());
    GregorianCalendar calendar = new GregorianCalendar(2010, 1, 23);
    calendar.set(GregorianCalendar.MILLISECOND, 123);
    dateTimeTimestamp.setTimestampValue(calendar.getTime());
    dateTimeTimestamp.save();

    // execute matching select
    Criteria criteria = new Criteria();
    calendar = new GregorianCalendar(2010, 1, 23);
    calendar.set(GregorianCalendar.MILLISECOND, 123);
    criteria.where(DateTimeTimestampTypePeer.TIMESTAMP_VALUE, calendar.getTime());
    List<DateTimeTimestampType> result = DateTimeTimestampTypePeer.doSelect(criteria);

    // verify
    assertEquals(1, result.size());
    assertEquals(dateTimeTimestamp, result.get(0));
}