List of usage examples for java.util Calendar DAY_OF_YEAR
int DAY_OF_YEAR
To view the source code for java.util Calendar DAY_OF_YEAR.
Click Source Link
get
and set
indicating the day number within the current year. From source file:com.fengduo.bee.commons.util.DateViewTools.java
public static String nextDay() { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, 1); return getFormat(SIMPLE_DATE_FORMAT_PATTERN).format(calendar.getTime()); }
From source file:es.udc.fic.test.model.CerrarMangaTest.java
@Test public void cerrarMangaTRealPenalizado() { //Creamos una sola regata con la instancia de todos los objetos en memoria Regata regata = new Regata(); regata.setNombre("Mock Regata"); regata.setDescripcion("Mock Desc"); regataDao.save(regata);// w ww .j a v a2 s. c o m Tipo tipoVLigera = new Tipo("Vela ligera", "Desc Vela ligera", true); tipoDao.save(tipoVLigera); Tipo tipoLanchas = new Tipo("Lanchas", "Desc Lanchas", true); tipoDao.save(tipoLanchas); Barco b1 = new Barco(204566, "Juan Sebastian El Cano", tipoVLigera, null, "Laser Standar"); inscripcionService.inscribir(regata, b1, "Iago Surez"); Barco b2 = new Barco(199012, "El Holandes Errante", tipoVLigera, null, "Laser Radial"); inscripcionService.inscribir(regata, b2, "Samu Paredes"); Barco b3 = new Barco(201402, "La Perla Negra", tipoVLigera, null, "Laser 4.7"); inscripcionService.inscribir(regata, b3, "Adrian Pallas"); Barco b4 = new Barco(202102, "La Pinta", tipoVLigera, null, "Laser 4.7"); inscripcionService.inscribir(regata, b4, "Pedro Cabalar"); Barco b5 = new Barco(182345, "Venus", tipoVLigera, null, "Laser Standar"); //Ponemos otro tipo para ver como funciona la clasificacion inscripcionService.inscribir(regata, b5, "Jesus Lopez"); Barco b6 = new Barco(206745, "Apolo", tipoLanchas, null, "Motora"); inscripcionService.inscribir(regata, b6, "Diego Bascoy"); Calendar dia1 = Calendar.getInstance(); dia1.add(Calendar.DAY_OF_YEAR, -18); Calendar dia2 = Calendar.getInstance(); dia2.add(Calendar.DAY_OF_YEAR, -18); dia2.add(Calendar.HOUR, 2); Calendar dia3 = Calendar.getInstance(); dia3.add(Calendar.DAY_OF_YEAR, -17); // COMPROBAMOS LAS DESCALIFICACIONES QUE NO ACARREAN EL MAX DE PUNT. Manga manga1 = new Manga(dia1, regata, null, 100); List<Posicion> posManga1 = new ArrayList<Posicion>(); //NAN -> 0 penal //ZFP -> 20% penal //SCP RDG DPI -> Penal en tiempo //Velas Ligeras // ZFP 3600s -> Tercero posManga1.add(new Posicion((long) 3000, Posicion.Penalizacion.ZFP, manga1, b1, (long) 0)); //SCP 3450s -> Segundo posManga1.add(new Posicion((long) 3300, Posicion.Penalizacion.SCP, manga1, b2, (long) 150)); //NAN 3400 -> Primero posManga1.add(new Posicion((long) 3400, Posicion.Penalizacion.NAN, manga1, b3, (long) 0)); //RDG 3750 -> Cuarto posManga1.add(new Posicion((long) 3750, Posicion.Penalizacion.RDG, manga1, b4, (long) 0)); //DPI 3860 -> Ultimo posManga1.add(new Posicion((long) 3800, Posicion.Penalizacion.DPI, manga1, b5, (long) 60)); //Lanchas //Primero -> Puntos 1 posManga1.add(new Posicion((long) 3300, Posicion.Penalizacion.ZFP, manga1, b6, (long) 0)); manga1.setPosiciones(posManga1); mangaService.cerrarYGuardarManga(manga1); regata.addManga(manga1); //Comprobamos que todas las posiciones tienen puntos mayores que 0 for (Posicion p : manga1.getPosiciones()) { assertTrue(p.getPuntos() > 0); } //Comprobamos que los puntos son correctos //Guardamos las posiciones por tipos Map<Barco, Posicion> posPorBarco = new HashMap<Barco, Posicion>(); for (Posicion p : manga1.getPosiciones()) { //Aadimos la posicionActual posPorBarco.put(p.getBarco(), p); } //Velas Ligeras // ZFP 3600s -> Tercero assertEquals(posPorBarco.get(b1).getPuntos(), 3); //SCP 3450s -> Segundo assertEquals(posPorBarco.get(b2).getPuntos(), 2); //NAN 3400 -> Primero assertEquals(posPorBarco.get(b3).getPuntos(), 1); //RDG 3750 -> Cuarto assertEquals(posPorBarco.get(b4).getPuntos(), 4); //DPI 3860 -> Ultimo assertEquals(posPorBarco.get(b5).getPuntos(), 5); //Lanchas //Primero assertEquals(posPorBarco.get(b6).getPuntos(), 1); // COMPROBAMOS LAS DESCALIFICACIONES QUE ACARREAN EL MAX DE PUNT. Manga manga2 = new Manga(dia2, regata, null, 100); List<Posicion> posManga2 = new ArrayList<Posicion>(); //DNC DNS -> No Salio // DNF RET DSQ -> No termino / Retirado / Descalificado // DNE DGM -> Descalificaciones Graves // BFD -> Bandera negra //Velas Ligeras // ZFP 3600s -> Primero (unico el llegar) posManga2.add(new Posicion((long) 3000, Posicion.Penalizacion.ZFP, manga1, b1, (long) 0)); //DNF No termino -> Ultimo -> 6 Puntos posManga2.add(new Posicion((long) 3300, Posicion.Penalizacion.DNF, manga1, b2, null)); //DNE Descalificado -> Ultimo -> 6 Puntos posManga2.add(new Posicion((long) 3400, Posicion.Penalizacion.DNE, manga1, b3, null)); //DNE Descalificado -> Ultimo -> 6 Puntos posManga2.add(new Posicion((long) 3750, Posicion.Penalizacion.DNE, manga1, b4, null)); //DGM Descalificado -> Ultimo -> 6 Puntos posManga2.add(new Posicion((long) 3800, Posicion.Penalizacion.DGM, manga1, b5, null)); //Lanchas //RET Retirado -> Puntos 2 posManga2.add(new Posicion((long) 3300, Posicion.Penalizacion.RET, manga1, b6, null)); manga2.setPosiciones(posManga2); mangaService.cerrarYGuardarManga(manga2); regata.addManga(manga2); //Comprobamos que todas las posiciones tienen puntos mayores que 0 for (Posicion p : manga2.getPosiciones()) { assertTrue(p.getPuntos() > 0); } //Comprobamos que los puntos son correctos //Guardamos las posiciones por tipos Map<Barco, Posicion> posPorBarco2 = new HashMap<Barco, Posicion>(); for (Posicion p : manga2.getPosiciones()) { //Aadimos la posicionActual posPorBarco2.put(p.getBarco(), p); } //ZFP 3600s -> Primero (unico el llegar) assertEquals(posPorBarco2.get(b1).getPuntos(), 1); //DNF No termino -> Ultimo -> 5 Puntos assertEquals(posPorBarco2.get(b2).getPuntos(), 6); //DNE Descalificado -> Ultimo -> 5 Puntos assertEquals(posPorBarco2.get(b3).getPuntos(), 6); //BFD Bandera Negra -> Ultimo -> 5 Puntos assertEquals(posPorBarco2.get(b4).getPuntos(), 6); //DGM Descalificado -> Ultimo -> 5 Puntos assertEquals(posPorBarco2.get(b5).getPuntos(), 6); //Lanchas //Primero assertEquals(posPorBarco2.get(b6).getPuntos(), 2); }
From source file:org.davidmendoza.esu.service.impl.PublicacionServiceImpl.java
@Scheduled(cron = "0 0 3 * * ?") @Override/*from w w w .ja v a 2 s. c o m*/ public void populares() { Calendar cal = Calendar.getInstance(); Date date1 = cal.getTime(); cal.add(Calendar.DAY_OF_YEAR, -1); Date date2 = cal.getTime(); List<Vista> dia1 = vistaRepository.vistas(date2, date1); date1 = date2; cal.add(Calendar.DAY_OF_YEAR, -2); date2 = cal.getTime(); List<Vista> dia2 = vistaRepository.vistas(date2, date1); Map<Long, Vista> x = new HashMap<>(); dia2.stream().forEach((vista) -> { x.put(vista.getArticulo().getId(), vista); }); Map<Integer, List<Long>> map = new TreeMap<>(); for (Vista vista : dia1) { Integer vistas; Vista y = x.get(vista.getArticulo().getId()); if (y != null) { vistas = vista.getCantidad() - y.getCantidad(); } else { vistas = vista.getCantidad(); } List<Long> ids = map.get(vistas); if (ids == null) { ids = new ArrayList<>(); map.put(vistas, ids); } ids.add(vista.getArticulo().getId()); } List<Integer> keys = new ArrayList<>(map.keySet()); log.debug("Keys: {}", keys.size()); if (!keys.isEmpty()) { popularRepository.deleteAll(); int id = 0; for (int a = keys.size() - 1; a >= 0; a--) { for (Long b : map.get(keys.get(a))) { List<Long> pubs = publicacionRepository.getByArticuloId(b); if (pubs != null && !pubs.isEmpty()) { Popular popular = new Popular(++id, publicacionRepository.getOne(pubs.get(0))); popularRepository.save(popular); } } } } }
From source file:osh.busdriver.MieleGatewayBusDriver.java
@Override public void run() { while (true) { synchronized (mieleGatewayDispatcher) { try { // wait for new data mieleGatewayDispatcher.wait(); } catch (InterruptedException e) { getGlobalLogger().logError("should not happen", e); break; }/*from w w w . j a va2 s.c om*/ long timestamp = getTimer().getUnixTime(); if (mieleGatewayDispatcher.getDeviceData().isEmpty()) { // an error has occurred for (UUID uuid : deviceProperties.keySet()) { BusDeviceStatusDetails bs = new BusDeviceStatusDetails(uuid, timestamp); bs.setState(ConnectionStatus.ERROR); getDriverRegistry().setStateOfSender(BusDeviceStatusDetails.class, bs); } } for (MieleDeviceHomeBusData dev : mieleGatewayDispatcher.getDeviceData()) { // build UUID long uuidHigh = UUIDGenerationHelper.getMieleUUIDHigherPart(dev.getUid()); long uuidLow; try { uuidLow = UUIDGenerationHelper.getHomeApplianceUUIDLowerPart((short) dev.getDeviceClass(), mieleGatewayAddr); } catch (Exception e) { getGlobalLogger().logError("should not happen: UUID generation failed", e); continue; } final UUID devUUID = new UUID(uuidHigh, uuidLow); // register UUID as command receiver to the registry if (!deviceProperties.containsKey(devUUID)) { // device already known? IEventReceiver eventReceiver = new IEventReceiver() { @Override public Object getSyncObject() { return MieleGatewayBusDriver.this; } @Override public void onQueueEventReceived(EventExchange event) throws OSHException { MieleGatewayBusDriver.this.onQueueEventReceived(event); } @Override public UUID getUUID() { return devUUID; } }; // register device try { getDriverRegistry().register(StartDeviceRequest.class, eventReceiver); getDriverRegistry().register(StopDeviceRequest.class, eventReceiver); getDriverRegistry().register(SwitchRequest.class, eventReceiver); deviceProperties.put(devUUID, new HashMap<String, String>()); } catch (OSHException e) { // nop. happens. getGlobalLogger().logError("should not happen", e); } } // check if all data is available BusDeviceStatusDetails bs = new BusDeviceStatusDetails(devUUID, timestamp); if (dev.getDeviceDetails() == null) { bs.setState(ConnectionStatus.ERROR); getDriverRegistry().setStateOfSender(BusDeviceStatusDetails.class, bs); continue; } else { bs.setState(ConnectionStatus.ATTACHED); getDriverRegistry().setStateOfSender(BusDeviceStatusDetails.class, bs); } // create program details GenericApplianceProgramDriverDetails programdetails = new GenericApplianceProgramDriverDetails( devUUID, timestamp); programdetails.setLoadProfiles(null); programdetails.setProgramName(dev.getDeviceDetails().getProgramName()); programdetails.setPhaseName(dev.getDeviceDetails().getPhaseName()); // create Miele specific details // duration MieleApplianceDriverDetails mieledetails = new MieleApplianceDriverDetails(devUUID, timestamp); if (dev.getDuration() != null) mieledetails.setExpectedProgramDuration(dev.getDuration().duration() * 60); else mieledetails.setExpectedProgramDuration(-1); // remaining time if (dev.getRemainingTime() != null) mieledetails.setProgramRemainingTime(dev.getRemainingTime().duration() * 60); else mieledetails.setProgramRemainingTime(-1); // start time if (dev.getStartTime() != null) { Calendar cal = Calendar.getInstance(); long nowInMillies = getTimer().getUnixTime() * 1000L; cal.setTimeInMillis(nowInMillies); cal.setTimeZone(getTimer().getHostTimeZone()); cal.set(Calendar.HOUR_OF_DAY, dev.getStartTime().hour()); cal.set(Calendar.MINUTE, dev.getStartTime().minute()); cal.set(Calendar.SECOND, 0); if (cal.getTimeInMillis() <= nowInMillies) cal.add(Calendar.DAY_OF_YEAR, 1); mieledetails.setStartTime(cal.getTimeInMillis() / 1000L); } else mieledetails.setStartTime(-1); // set state of the UUID try { getDriverRegistry().setStateOfSender(GenericApplianceDriverDetails.class, createApplianceDetails(devUUID, timestamp, dev)); getDriverRegistry().setStateOfSender(StartTimeDetails.class, createStartTimeDetails(devUUID, timestamp, dev)); getDriverRegistry().setStateOfSender(GenericApplianceProgramDriverDetails.class, programdetails); getDriverRegistry().setStateOfSender(MieleApplianceDriverDetails.class, mieledetails); } catch (OSHException e1) { bs.setState(ConnectionStatus.ERROR); getDriverRegistry().setStateOfSender(BusDeviceStatusDetails.class, bs); getGlobalLogger().logError(e1); } // extract additional information for invoking commands String detailsUrl = dev.getDetailsUrl(); // extract type and id from details url if (detailsUrl != null) { Map<String, String> devProps = deviceProperties.get(devUUID); try { URIBuilder uri = new URIBuilder(detailsUrl); for (NameValuePair pair : uri.getQueryParams()) { if ("type".equals(pair.getName()) || "id".equals(pair.getName())) { devProps.put(pair.getName(), pair.getValue()); } } } catch (URISyntaxException e) { // nop. shit happens. getGlobalLogger().logError("should not happen", e); } } } } } }
From source file:com.mobileman.projecth.business.impl.PatientMedicationServiceImpl.java
/** * {@inheritDoc}/*from w w w .j av a2 s . c om*/ * @see com.mobileman.projecth.business.PatientMedicationService#addConsumedMedication(java.lang.Long, java.lang.Long, java.lang.Long, double, com.mobileman.projecth.domain.util.medication.MedicationFrequency, java.util.Date, java.util.Date, java.lang.String) */ @Override public void addConsumedMedication(Long patientId, Long diseaseId, Long medicationId, double standarUnitsTaken, MedicationFrequency frequency, Date startDate, Date endDate, String comment) throws IllegalArgumentException { if (log.isDebugEnabled()) { log.debug("addConsumedMedication(" + patientId + ", " + diseaseId + ", " + medicationId + ", " + standarUnitsTaken + ", " + frequency + ", " + startDate + ", " + endDate + ") - start"); //$NON-NLS-1$ } if (patientId == null) { throw new IllegalArgumentException("patientId must not be null"); } if (diseaseId == null) { throw new IllegalArgumentException("diseaseId must not be null"); } if (medicationId == null) { throw new IllegalArgumentException("medicationId must not be null"); } if (standarUnitsTaken <= 0.0d) { throw new IllegalArgumentException("standarUnitsTaken must not be zero or negative value"); } if (frequency == null) { throw new IllegalArgumentException("frequency must not be null"); } if (endDate == null) { endDate = startDate; } Patient patient = patientDao.findById(patientId); patient.setLastUpdate(new Date()); Medication medication = medicationDao.findById(medicationId); Disease disease = diseaseDao.findById(diseaseId); Date date = startDate; Calendar calendar = new GregorianCalendar(); calendar.setTime(startDate); Date timestamp = new Date(); while (date.before(endDate) || date.equals(endDate)) { PatientMedication patientMedication = new PatientMedication(); patientMedication.setTimestamp(timestamp); patientMedication.setPatient(patient); patientMedication.setMedication(medication); patientMedication.setComment(comment); patientMedication.setConsumptionDate(date); patientMedication.setDisease(disease); patientMedication.setAmount(new BigDecimal(standarUnitsTaken)); patientMedicationDao.save(patientMedication); if (frequency.equals(MedicationFrequency.ONE_TIME)) { break; } switch (frequency) { case DAILY: calendar.add(Calendar.DAY_OF_YEAR, 1); break; case WEEKLY: calendar.add(Calendar.WEEK_OF_YEAR, 1); break; case BI_WEEKLY: calendar.add(Calendar.WEEK_OF_YEAR, 2); break; default: break; } date = calendar.getTime(); } if (log.isDebugEnabled()) { log.debug("addConsumedMedication(Long, Long, Long, double) - returns"); //$NON-NLS-1$ } }
From source file:com.fengduo.bee.commons.util.DateViewTools.java
public static String nextDayFull() { Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, 1); return getFormat(FULL_DATE_FORMAT_PATTERN).format(calendar.getTime()); }
From source file:mekhq.campaign.finances.Finances.java
public void newDay(Campaign campaign) { DecimalFormat formatter = new DecimalFormat(); CampaignOptions campaignOptions = campaign.getCampaignOptions(); GregorianCalendar calendar = campaign.getCalendar(); // check for a new year if (calendar.get(Calendar.MONTH) == 0 && calendar.get(Calendar.DAY_OF_MONTH) == 1) { // clear the ledger newFiscalYear(calendar.getTime()); }//w ww. j av a 2 s. c o m // Handle contract payments if (calendar.get(Calendar.DAY_OF_MONTH) == 1) { for (Contract contract : campaign.getActiveContracts()) { credit(contract.getMonthlyPayOut(), Transaction.C_CONTRACT, String.format(resourceMap.getString("MonthlyContractPayment.text"), contract.getName()), calendar.getTime()); campaign.addReport(String.format(resourceMap.getString("ContractPaymentCredit.text"), formatter.format(contract.getMonthlyPayOut()), contract.getName())); if (campaignOptions.getUseAtB() && campaignOptions.getUseShareSystem() && contract instanceof AtBContract) { long shares = contract.getMonthlyPayOut() * ((AtBContract) contract).getSharesPct() / 100; if (debit(shares, Transaction.C_SALARY, String.format(resourceMap.getString("ContractSharePayment.text"), contract.getName()), calendar.getTime())) { campaign.addReport(String.format(resourceMap.getString("DistributedShares.text"), formatter.format(shares))); } else { /* * This should not happen, as the shares payment is less than the contract * payment that has just been made. */ campaign.addReport(String.format(resourceMap.getString("NotImplemented.text"), "shares")); } } } } // Handle assets for (Asset asset : assets) { if (asset.getSchedule() == SCHEDULE_YEARLY && campaign.calendar.get(Calendar.DAY_OF_YEAR) == 1) { credit(asset.getIncome(), Transaction.C_MISC, "income from " + asset.getName(), campaign.getCalendar().getTime()); campaign.addReport(String.format(resourceMap.getString("AssetPayment.text"), DecimalFormat.getInstance().format(asset.getIncome()), asset.getName())); } else if (asset.getSchedule() == SCHEDULE_MONTHLY && campaign.calendar.get(Calendar.DAY_OF_MONTH) == 1) { credit(asset.getIncome(), Transaction.C_MISC, "income from " + asset.getName(), campaign.getCalendar().getTime()); campaign.addReport(String.format(resourceMap.getString("AssetPayment.text"), DecimalFormat.getInstance().format(asset.getIncome()), asset.getName())); } } // Handle peacetime operating expenses, payroll, and loan payments if (calendar.get(Calendar.DAY_OF_MONTH) == 1) { if (campaignOptions.usePeacetimeCost()) { if (!campaignOptions.showPeacetimeCost()) { if (debit(campaign.getPeacetimeCost(), Transaction.C_MAINTAIN, resourceMap.getString("PeacetimeCosts.title"), calendar.getTime())) { campaign.addReport(String.format(resourceMap.getString("PeacetimeCosts.text"), formatter.format(campaign.getPeacetimeCost()))); } else { campaign.addReport( String.format(resourceMap.getString("NotImplemented.text"), "for operating costs")); } } else { if (debit(campaign.getMonthlySpareParts(), Transaction.C_MAINTAIN, resourceMap.getString("PeacetimeCostsParts.title"), calendar.getTime())) { campaign.addReport(String.format(resourceMap.getString("PeacetimeCostsParts.text"), formatter.format(campaign.getMonthlySpareParts()))); } else { campaign.addReport( String.format(resourceMap.getString("NotImplemented.text"), "for spare parts")); } if (debit(campaign.getMonthlyAmmo(), Transaction.C_MAINTAIN, resourceMap.getString("PeacetimeCostsAmmunition.title"), calendar.getTime())) { campaign.addReport(String.format(resourceMap.getString("PeacetimeCostsAmmunition.text"), formatter.format(campaign.getMonthlySpareParts()))); } else { campaign.addReport(String.format(resourceMap.getString("NotImplemented.text"), "for training munitions")); } if (debit(campaign.getMonthlyFuel(), Transaction.C_MAINTAIN, resourceMap.getString("PeacetimeCostsFuel.title"), calendar.getTime())) { campaign.addReport(String.format(resourceMap.getString("PeacetimeCostsFuel.text"), formatter.format(campaign.getMonthlySpareParts()))); } else { campaign.addReport(String.format(resourceMap.getString("NotImplemented.text"), "for fuel")); } } } if (campaignOptions.payForSalaries()) { if (debit(campaign.getPayRoll(), Transaction.C_SALARY, resourceMap.getString("Salaries.title"), calendar.getTime())) { campaign.addReport(String.format(resourceMap.getString("Salaries.text"), formatter.format(campaign.getPayRoll()))); } else { campaign.addReport( String.format(resourceMap.getString("NotImplemented.text"), "payroll costs")); } } // Handle overhead expenses if (campaignOptions.payForOverhead()) { if (debit(campaign.getOverheadExpenses(), Transaction.C_OVERHEAD, resourceMap.getString("Overhead.title"), calendar.getTime())) { campaign.addReport(String.format(resourceMap.getString("Overhead.text"), formatter.format(campaign.getOverheadExpenses()))); } else { campaign.addReport( String.format(resourceMap.getString("NotImplemented.text"), "overhead costs")); } } } ArrayList<Loan> newLoans = new ArrayList<Loan>(); for (Loan loan : loans) { if (loan.checkLoanPayment(campaign.getCalendar())) { if (debit(loan.getPaymentAmount(), Transaction.C_LOAN_PAYMENT, String.format(resourceMap.getString("Loan.title"), loan.getDescription()), campaign.getCalendar().getTime())) { campaign.addReport(String.format(resourceMap.getString("Loan.text"), DecimalFormat.getInstance().format(loan.getPaymentAmount()), loan.getDescription())); loan.paidLoan(); } else { campaign.addReport(String.format(resourceMap.getString("Loan.insufficient"), loan.getDescription(), DecimalFormat.getInstance().format(loan.getPaymentAmount()))); loan.setOverdue(true); } } if (loan.getRemainingPayments() > 0) { newLoans.add(loan); } else { campaign.addReport(String.format(resourceMap.getString("Loan.paid"), loan.getDescription())); } } if (null != wentIntoDebt && !isInDebt()) { wentIntoDebt = null; } loans = newLoans; }
From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java
private X509V1CertificateGenerator buildX509V1CertificateGenerator(PublicKey publicKey, DigitalSigningDistinguishedName distinguishedName, long serialNumber, int validDays) { X509V1CertificateGenerator v1CertGen = new X509V1CertificateGenerator(); // Calculate Expiration Date Calendar notBeforeCal = Calendar.getInstance(); Date notBeforeDate = notBeforeCal.getTime(); Calendar notAfterCal = Calendar.getInstance(); notAfterCal.add(Calendar.DAY_OF_YEAR, validDays); Date notAfterDate = notAfterCal.getTime(); ///* ww w . j av a 2 s . c o m*/ // create the certificate - version 1 // v1CertGen.setSerialNumber(BigInteger.valueOf(serialNumber)); v1CertGen.setIssuerDN(new X509Principal(getAttributeOrder(), buildAttributes(distinguishedName))); v1CertGen.setNotBefore(notBeforeDate); v1CertGen.setNotAfter(notAfterDate); // subjects name - the same as we are self signed. v1CertGen.setSubjectDN(new X509Principal(getAttributeOrder(), buildAttributes(distinguishedName))); v1CertGen.setPublicKey(publicKey); v1CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); return v1CertGen; }
From source file:es.emergya.bbdd.dao.HistoricoGPSHome.java
/** * Dado un conjuto de flotas y una fecha de inicio y fin, devuelve los * nombres de los recursos que pertenecan a alguna de estas flotas y que * enviaron alguna posicin en el periodo. Si alguna fecha es null no se * tienen en cuenta (no se aade a la condicin) * // w w w . j av a2s.c o m * @param flotas * conjunto de flotas en las que estamos interesados. * @param initDate * fecha/hora inicial del periodo de bsqueda. * @param endDate * fecha/hora final del periodo de bsqueda. * */ @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true, rollbackFor = Throwable.class) public List<String> findRecursosInIntervalForFoltas(Set<Flota> flotas, Calendar initDate, Calendar endDate, Usuario user) { log.info("findRecursosInINtervalForFlotas"); List<String> result = new LinkedList<String>(); try { Date inicio = null; Date fin = null; if (initDate != null) { inicio = initDate.getTime(); } if (endDate != null) { fin = endDate.getTime(); } Calendar c = Calendar.getInstance(); Date inicio_day = null; if (inicio != null) { c.setTime(inicio); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); c.add(Calendar.SECOND, -1); inicio_day = c.getTime(); } Date fin_day = null; if (fin != null) { c.setTime(fin); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); c.add(Calendar.DAY_OF_YEAR, 1); fin_day = c.getTime(); } // Creamos un array con los nombres de las subflotas para usarlos en // una // condicin IN if (flotas == null || (flotas != null && flotas.size() == 0)) { return result; } Date fin_provisional = null; String[] nombreFlotas = new String[flotas.size()]; int i = 0; for (Flota f : flotas) { nombreFlotas[i++] = f.getNombre(); } // Si no hemos recibido fechas de inicio o fin significa que estamos // consultando ltimas posiciones. Utilizamos la tabla recursos para // obtener las ltimas posiciones. if (inicio == null || fin == null) { log.trace("No hay fecha de inicio o fin. Buscamos solo las ultimas posiciones."); result.addAll(calculateRecursosUltimasPosiciones(user)); } else { StringBuilder stringFlotas = new StringBuilder(""); if (nombreFlotas.length > 0) { stringFlotas.append(" subflota in ('" + nombreFlotas[0]); for (i = 1; i < nombreFlotas.length; i++) { stringFlotas.append("', '").append(nombreFlotas[i]); } stringFlotas.append("') "); } while (inicio != null && fin != null && inicio.before(fin)) { initDate.add(Calendar.DAY_OF_YEAR, 1); fin_provisional = initDate.getTime(); if (fin.before(fin_provisional)) fin_provisional = fin; result.addAll(calculateRecursos(inicio, fin_provisional, stringFlotas.toString(), result)); log.trace("De momento llevamos " + result); inicio = fin_provisional; } } if (fin != null && inicio != null) try { File directorio = new File(LogicConstants.get(DIRECTORIO_GPX, DIRECTORIO_GPX_DEFAULT)); if (!directorio.isDirectory()) { throw new IOException("La ruta pasada para los gpx no es un directorio"); } List<String> fltas = new LinkedList<String>(); for (String s : nombreFlotas) { fltas.add(s); } log.trace("Flotas: " + flotas); for (File file : directorio.listFiles()) { log.trace(file.getAbsolutePath()); try { if (file.isDirectory()) { throw new IOException(file + " no es un fichero"); } if (!file.canRead()) { throw new IOException(file + " no es legible"); } String nombreFichero = file.getName(); final String recurso = getRecursoFromFileName(nombreFichero); final String flota = getFlotaFromFileName(nombreFichero); log.debug("Encontrado " + recurso + " de " + flota); if (!result.contains(recurso)) { log.trace("Miramos el recurso " + recurso + " de " + flota + " en " + flotas); if (fltas.contains(flota)) { Date time = getTimeFromFileName(nombreFichero); // Si las fechas coinciden if (time != null) { log.trace("Hora del recurso: " + time); if (inicio_day == null || inicio_day.before(time)) { if (fin_day == null || fin_day.after(time)) { result.add(recurso); log.trace("Metemos a " + recurso); } } } } } } catch (Throwable t) { log.error("No pude leer a " + file, t); } } } catch (Throwable t) { log.error("No pudimos buscar en los gpx", t); } Collections.sort(result); } catch (Throwable t) { log.error("Error al buscar los recursos", t); } return result; }
From source file:org.auraframework.integration.test.http.AuraFrameworkServletHttpTest.java
/** * Test that AuraFrameworkServlet inspects the date header in the request and sends 304(SC_NOT_MODIFIED) if the * If-Modified-Since header indicates that resource is not stale. *//*w ww. ja va2 s. c o m*/ @Test public void testResourceCachingWithUid() throws Exception { Calendar stamp = Calendar.getInstance(); stamp.add(Calendar.DAY_OF_YEAR, 45); HttpGet get = obtainNoncedGetMethod(sampleBinaryResourcePathWithNonce, false); get.setHeader(HttpHeaders.IF_MODIFIED_SINCE, new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").format(stamp.getTime())); HttpResponse httpResponse = perform(get); int statusCode = getStatusCode(httpResponse); assertEquals("Expected server to return a 304 for unexpired cache.", HttpStatus.SC_NOT_MODIFIED, statusCode); assertNull(getResponseBody(httpResponse)); assertDefaultAntiClickjacking(httpResponse, true, false); }