List of usage examples for java.util Date from
public static Date from(Instant instant)
From source file:org.noorganization.instalist.server.api.UnitResource.java
/** * Get a list of units./* w ww . j a va 2s . c o m*/ * @param _groupId The id of the group containing the requested units. * @param _changedSince Requests only the elements that changed since the given date. ISO * 8601 time e.g. 2016-01-19T11:54:07+01:00 */ @GET @TokenSecured @Produces({ "application/json" }) public Response getUnits(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince) throws Exception { Instant changedSince = null; try { if (_changedSince != null) changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant(); } catch (ParseException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE); } EntityManager manager = DatabaseHelper.getInstance().getManager(); DeviceGroup group = manager.find(DeviceGroup.class, _groupId); List<Unit> resultUnits; List<DeletedObject> resultDeletedUnits; if (changedSince == null) { resultUnits = new ArrayList<Unit>(group.getUnits()); TypedQuery<DeletedObject> deletedUnitsQuery = manager.createQuery( "select do from " + "DeletedObject do where do.group = :group and do.type = :type", DeletedObject.class); deletedUnitsQuery.setParameter("group", group); deletedUnitsQuery.setParameter("type", DeletedObject.Type.UNIT); resultDeletedUnits = deletedUnitsQuery.getResultList(); } else { TypedQuery<Unit> unitsQuery = manager.createQuery( "select u from Unit u where " + "u.group = :group and u.updated > :updated", Unit.class); unitsQuery.setParameter("group", group); unitsQuery.setParameter("updated", changedSince); resultUnits = unitsQuery.getResultList(); TypedQuery<DeletedObject> deletedUnitsQuery = manager.createQuery("select do from " + "DeletedObject do where do.group = :group and do.type = :type and " + "do.updated > :updated", DeletedObject.class); deletedUnitsQuery.setParameter("group", group); deletedUnitsQuery.setParameter("type", DeletedObject.Type.UNIT); deletedUnitsQuery.setParameter("updated", changedSince); resultDeletedUnits = deletedUnitsQuery.getResultList(); } manager.close(); List<UnitInfo> rtn = new ArrayList<UnitInfo>(resultUnits.size() + resultDeletedUnits.size()); for (Unit current : resultUnits) { UnitInfo info = new UnitInfo().withDeleted(false); info.setName(current.getName()); info.setUUID(current.getUUID()); info.setLastChanged(Date.from(current.getUpdated())); rtn.add(info); } for (DeletedObject current : resultDeletedUnits) { UnitInfo info = new UnitInfo().withDeleted(true); info.setUUID(current.getUUID()); info.setLastChanged(Date.from(current.getUpdated())); rtn.add(info); } return ResponseFactory.generateOK(rtn); }
From source file:org.noorganization.instalist.server.api.RecipeResource.java
/** * Get a list of recipes./*from w w w . j a v a 2 s. c om*/ * @param _groupId The id of the group containing the recipes. * @param _changedSince Limits the request to elements that changed since the given date. ISO * 8601 time e.g. 2016-01-19T11:54:07+0100. Optional. */ @GET @TokenSecured @Produces({ "application/json" }) public Response getRecipes(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince) throws Exception { Instant changedSince = null; try { if (_changedSince != null) changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant(); } catch (ParseException _e) { return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE); } EntityManager manager = DatabaseHelper.getInstance().getManager(); List<Recipe> recipes; List<DeletedObject> deletedRecipes; DeviceGroup group = manager.find(DeviceGroup.class, _groupId); if (changedSince != null) { TypedQuery<Recipe> recipeQuery = manager.createQuery( "select r from Recipe r where " + "r.group = :group and r.updated > :updated", Recipe.class); recipeQuery.setParameter("group", group); recipeQuery.setParameter("updated", changedSince); recipes = recipeQuery.getResultList(); TypedQuery<DeletedObject> deletedRecipesQuery = manager.createQuery( "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and " + "do.type = :type", DeletedObject.class); deletedRecipesQuery.setParameter("group", group); deletedRecipesQuery.setParameter("updated", changedSince); deletedRecipesQuery.setParameter("type", DeletedObject.Type.RECIPE); deletedRecipes = deletedRecipesQuery.getResultList(); } else { recipes = new ArrayList<Recipe>(group.getRecipes()); TypedQuery<DeletedObject> deletedRecipesQuery = manager.createQuery( "select do " + "from DeletedObject do where do.group = :group and do.type = :type", DeletedObject.class); deletedRecipesQuery.setParameter("group", group); deletedRecipesQuery.setParameter("type", DeletedObject.Type.RECIPE); deletedRecipes = deletedRecipesQuery.getResultList(); } manager.close(); ArrayList<RecipeInfo> rtn = new ArrayList<RecipeInfo>(recipes.size() + deletedRecipes.size()); for (Recipe current : recipes) { RecipeInfo toAdd = new RecipeInfo().withDeleted(false); toAdd.setUUID(current.getUUID()); toAdd.setName(current.getName()); toAdd.setLastChanged(Date.from(current.getUpdated())); rtn.add(toAdd); } for (DeletedObject current : deletedRecipes) { RecipeInfo toAdd = new RecipeInfo().withDeleted(true); toAdd.setUUID(current.getUUID()); toAdd.setLastChanged(Date.from(current.getUpdated())); rtn.add(toAdd); } return ResponseFactory.generateOK(rtn); }
From source file:org.apache.james.jmap.methods.integration.cucumber.GetMessagesMethodStepdefs.java
private void appendMessage(String mailbox, ContentType contentType, String subject, String content, Optional<Map<String, String>> headers) throws Exception { ZonedDateTime dateTime = ZonedDateTime.parse("2014-10-30T14:12:00Z"); mainStepdefs.jmapServer.serverProbe().appendMessage(userStepdefs.lastConnectedUser, new MailboxPath(MailboxConstants.USER_NAMESPACE, userStepdefs.lastConnectedUser, mailbox), new ByteArrayInputStream(message(contentType, subject, content, headers).getBytes(Charsets.UTF_8)), Date.from(dateTime.toInstant()), false, new Flags()); }
From source file:com.bdb.weather.display.day.DayWindPane.java
@Override protected void loadDataSeries(List<HistoricalRecord> list) { super.loadDataSeries(list); speedSeries.clear();// w w w.j a v a 2 s. c om gustSeries.clear(); int n = 0; for (HistoricalRecord r : list) { Wind w = r.getAvgWind(); if (w != null) { Minute period = new Minute(Date.from(r.getTime().atZone(ZoneId.systemDefault()).toInstant())); WindSeriesDataItem item = new WindSeriesDataItem(period, w.getSpeed().get(), w.getDirection().get()); speedSeries.add(item); w = r.getWindGust(); if (w != null && w.getSpeed().get() > 0.0) { period = new Minute(TimeUtils.localDateTimeToDate(r.getTime())); gustSeries.add(period, w.getSpeed().get()); } } n++; } dataset.removeAllSeries(); dataset.addSeries(speedSeries); if (!gustSeries.isEmpty()) dataset.addSeries(gustSeries); }
From source file:com.vmware.photon.controller.api.client.resource.ClusterApiTest.java
@Test public void testResize() throws IOException { Task responseTask = new Task(); responseTask.setId("12345"); responseTask.setState("QUEUED"); responseTask.setQueuedTime(Date.from(Instant.now())); ObjectMapper mapper = new ObjectMapper(); String serializedTask = mapper.writeValueAsString(responseTask); setupMocks(serializedTask, HttpStatus.SC_CREATED); ClusterApi clusterApi = new ClusterApi(restClient); Task task = clusterApi.resize("dummy-cluster-id", 100); assertEquals(task, responseTask);/*from w w w . j a va2 s . c om*/ }
From source file:Index.RegisterUserServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w.j av a 2 s .c om * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String errorMessage; if (request.getParameter("user") != null && request.getParameter("password") != null && request.getParameter("email") != null && request.getParameter("passwordConfirmation") != null && request.getParameter("name") != null && request.getParameter("address") != null && request.getParameter("lastName") != null && request.getParameter("dateBorn") != null) { String user = request.getParameter("user"); String password = request.getParameter("password"); String passwordConfirmation = request.getParameter("passwordConfirmation"); String email = request.getParameter("email"); String name = request.getParameter("name"); String address = request.getParameter("address"); String lastName = request.getParameter("lastName"); String dateBorn = request.getParameter("dateBorn"); if (user.equalsIgnoreCase("") || password.equalsIgnoreCase("") || passwordConfirmation.equalsIgnoreCase("") || email.equalsIgnoreCase("") || name.equalsIgnoreCase("")) { errorMessage = "Ingrese todos los datos."; request.setAttribute("error", errorMessage); request.setAttribute("funcionalidad", "Registro"); request.getRequestDispatcher("/Login.jsp").forward(request, response); } else { if (password.equals(passwordConfirmation)) { QuickOrderWebService webService = new QuickOrderWebService(); ControllerInterface port = webService.getQuickOrderWebServicePort(); webservice.Cliente listCli = port.infoCliente(user); if (listCli != null && listCli.getApellido() != null) { errorMessage = "Ya existe un usuario con ese nickname"; request.setAttribute("error", errorMessage); request.setAttribute("funcionalidad", "Registro"); request.getRequestDispatcher("/Login.jsp").forward(request, response); } else { webservice.Cliente usr = new webservice.Cliente(); usr.setNickname(user); usr.setNombre(name); usr.setEmail(email); usr.setDireccion(address); usr.setImagen(user + ".jpg"); usr.setApellido(lastName); //PORCEDIMIENTO PARA ENCRIPTAR LA CLAVE INGRESADA CUANDO INICIA SESIN UN USUARIO. String encriptMD5 = DigestUtils.md5Hex(password); password = "md5:" + encriptMD5; usr.setPassword(password); Date dt; try { dt = new Date(dateBorn); } catch (Exception ex) { dt = Date.from(Instant.now()); } GregorianCalendar c = new GregorianCalendar(); c.setTime(dt); XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); usr.setFechaNac(date2); String result = port.registrarCliente(usr); if (result.equals("")) { request.setAttribute("error", null); request.setAttribute("funcionalidad", "Imagen"); request.getSession().setAttribute("userName", user); } else { request.setAttribute("error", "Surgio un error al registrar el cliente"); request.setAttribute("funcionalidad", "Registro"); } request.getRequestDispatcher("/Login.jsp").forward(request, response); } } else { errorMessage = "Las contraseas no cohinciden"; request.setAttribute("error", errorMessage); request.setAttribute("funcionalidad", "Registro"); request.getRequestDispatcher("/Login.jsp").forward(request, response); } } } else { errorMessage = "Error al realizar el registro."; request.setAttribute("error", errorMessage); request.setAttribute("funcionalidad", "Registro"); request.getRequestDispatcher("/Login.jsp").forward(request, response); } } catch (Exception ex) { out.print("Error en proceso de registro: " + ex.getMessage()); } finally { out.close(); } }
From source file:com.vmware.photon.controller.api.client.resource.ClusterRestApiTest.java
@Test public void testResize() throws IOException { Task responseTask = new Task(); responseTask.setId("12345"); responseTask.setState("QUEUED"); responseTask.setQueuedTime(Date.from(Instant.now())); ObjectMapper mapper = new ObjectMapper(); String serializedTask = mapper.writeValueAsString(responseTask); setupMocks(serializedTask, HttpStatus.SC_CREATED); ClusterApi clusterApi = new ClusterRestApi(restClient); Task task = clusterApi.resize("dummy-cluster-id", 100); assertEquals(task, responseTask);/*from w ww . ja va 2 s. c o m*/ }
From source file:org.nuxeo.ecm.blob.azure.TestAzureBinaryManager.java
@Test public void testSigning() throws IOException, URISyntaxException, StorageException, InvalidKeyException { CloudBlobContainer container = binaryManager.container; Binary binary = binaryManager.getBinary(Blobs.createBlob(CONTENT)); assertNotNull(binary);//from w w w . j a v a 2s . co m CloudBlockBlob blockBlobReference = container.getBlockBlobReference(CONTENT_MD5); SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy(); policy.setPermissionsFromString("r"); // rscd content-dispositoon // rsct content-type Instant endDateTime = LocalDateTime.now().plusHours(1).atZone(ZoneId.systemDefault()).toInstant(); policy.setSharedAccessExpiryTime(Date.from(endDateTime)); SharedAccessBlobHeaders headers = new SharedAccessBlobHeaders(); headers.setContentDisposition("attachment; filename=\"blabla.txt\""); headers.setContentType("text/plain"); String something = blockBlobReference.generateSharedAccessSignature(policy, headers, null); System.out.println(something); CloudBlockBlob blob = new CloudBlockBlob(blockBlobReference.getUri(), new StorageCredentialsSharedAccessSignature(something)); System.out.println(blob.getQualifiedUri()); }
From source file:org.noorganization.instalist.server.api.EntryResource.java
/** * Get a list of listEntries.// w ww . j a va 2 s . c o m * @param _groupId The id of the group containing various list-entries. * @param _changedSince Limits the result to elements that changed since the given date. ISO * 8601 time e.g. 2016-01-19T11:54:07+0100 */ @GET @TokenSecured @Produces({ "application/json" }) public Response getEntries(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince) throws Exception { List<ListEntry> foundEntries; List<DeletedObject> foundDeleted; EntityManager manager = DatabaseHelper.getInstance().getManager(); DeviceGroup group = manager.find(DeviceGroup.class, _groupId); if (_changedSince != null) { Instant changedSince; try { changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant(); } catch (ParseException _e) { manager.close(); return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE); } TypedQuery<ListEntry> foundEntriesQuery = manager.createQuery( "select le from " + "ListEntry le where le.group = :group and le.updated > :updated", ListEntry.class); foundEntriesQuery.setParameter("group", group); foundEntriesQuery.setParameter("updated", changedSince); foundEntries = foundEntriesQuery.getResultList(); TypedQuery<DeletedObject> foundDeletedEntriesQuery = manager.createQuery( "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and " + "do.type = :type", DeletedObject.class); foundDeletedEntriesQuery.setParameter("group", group); foundDeletedEntriesQuery.setParameter("updated", changedSince); foundDeletedEntriesQuery.setParameter("type", DeletedObject.Type.LISTENTRY); foundDeleted = foundDeletedEntriesQuery.getResultList(); } else { foundEntries = new ArrayList<ListEntry>(group.getListEntries()); TypedQuery<DeletedObject> deletedEntriesQuery = manager.createQuery( "select do from " + "DeletedObject do where do.group = :group and do.type = :type", DeletedObject.class); deletedEntriesQuery.setParameter("group", group); deletedEntriesQuery.setParameter("type", DeletedObject.Type.LISTENTRY); foundDeleted = deletedEntriesQuery.getResultList(); } manager.close(); ArrayList<EntryInfo> rtn = new ArrayList<EntryInfo>(foundEntries.size() + foundDeleted.size()); for (ListEntry current : foundEntries) { EntryInfo toAdd = new EntryInfo().withDeleted(false); toAdd.setUUID(current.getUUID()); toAdd.setProductUUID(current.getProduct().getUUID()); toAdd.setListUUID(current.getList().getUUID()); toAdd.setAmount(current.getAmount()); toAdd.setPriority(current.getPriority()); toAdd.setStruck(current.getStruck()); toAdd.setLastChanged(Date.from(current.getUpdated())); rtn.add(toAdd); } for (DeletedObject current : foundDeleted) { EntryInfo toAdd = new EntryInfo(); toAdd.setUUID(current.getUUID()); toAdd.setLastChanged(Date.from(current.getUpdated())); toAdd.setDeleted(true); rtn.add(toAdd); } return ResponseFactory.generateOK(rtn); }
From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java
/** * Given a certificate signing request, produce a signed certificate. * * @param caKey//from ww w . j ava 2s . co m * @param caCert * @param r * @param makeAuthority * @return */ public static X509Certificate fulfillCertRequest(PrivateKey caKey, X509Certificate caCert, PKCS10CertificationRequest r, boolean makeAuthority) { X509v3CertificateBuilder b = new JcaX509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()), // the order of O,OU,CN returned is very important BigInteger.probablePrime(128, new SecureRandom()), Date.from(Instant.now().minusSeconds(1)), Date.from(LocalDateTime.now().plusYears(3).toInstant(ZoneOffset.UTC)), r.getSubject(), getPublicKeyFromInfo(r.getSubjectPublicKeyInfo())); try { b.addExtension(Extension.basicConstraints, true, new BasicConstraints(makeAuthority)); } catch (CertIOException ex) { Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex); } try { ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider("BC").build(caKey); X509CertificateHolder build = b.build(signer); return new JcaX509CertificateConverter().setProvider("BC").getCertificate(build); } catch (OperatorCreationException | CertificateException ex) { Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex); return null; } }