List of usage examples for java.time Instant now
public static Instant now()
From source file:org.noorganization.instalist.server.api.RecipeResourceTest.java
@Test public void testGetRecipes() throws Exception { String url = "/groups/%d/recipes"; Response notAuthorizedResponse = target(String.format(url, mGroup.getId())).request().get(); assertEquals(401, notAuthorizedResponse.getStatus()); Response wrongAuthResponse = target(String.format(url, mGroup.getId())).request() .header(HttpHeaders.AUTHORIZATION, "X-Token wrongauth").get(); assertEquals(401, wrongAuthResponse.getStatus()); Response wrongGroupResponse = target(String.format(url, mNAGroup.getId())).request() .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get(); assertEquals(401, wrongGroupResponse.getStatus()); Response okResponse1 = target(String.format(url, mGroup.getId())).request() .header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get(); assertEquals(200, okResponse1.getStatus()); RecipeInfo[] allRecipeInfo = okResponse1.readEntity(RecipeInfo[].class); assertEquals(2, allRecipeInfo.length); for (RecipeInfo current : allRecipeInfo) { if (mRecipe.getUUID().equals(UUID.fromString(current.getUUID()))) { assertEquals("recipe1", current.getName()); assertEquals(mRecipe.getUpdated(), current.getLastChanged().toInstant()); assertFalse(current.getDeleted()); } else if (mDeletedRecipe.getUUID().equals(UUID.fromString(current.getUUID()))) { assertNull(current.getName()); assertEquals(mDeletedRecipe.getUpdated(), current.getLastChanged().toInstant()); assertTrue(current.getDeleted()); } else//w w w . jav a 2s .com fail("Unexpected recipe."); } Thread.sleep(200); mManager.getTransaction().begin(); mRecipe.setUpdated(Instant.now()); mManager.getTransaction().commit(); Response okResponse2 = target(String.format(url, mGroup.getId())) .queryParam("changedsince", ISO8601Utils.format(new Date(System.currentTimeMillis() - 100), true)) .request().header(HttpHeaders.AUTHORIZATION, "X-Token " + mToken).get(); assertEquals(200, okResponse2.getStatus()); RecipeInfo[] oneRecipeInfo = okResponse2.readEntity(RecipeInfo[].class); assertEquals(1, oneRecipeInfo.length); assertEquals(mRecipe.getUUID(), UUID.fromString(oneRecipeInfo[0].getUUID())); assertEquals("recipe1", oneRecipeInfo[0].getName()); assertFalse(oneRecipeInfo[0].getDeleted()); }
From source file:keywhiz.service.resources.admin.GroupsResource.java
/** * Create Group/*from w ww.j a va 2 s . c o m*/ * * @excludeParams user * @param request the JSON client request used to formulate the Group * * @description Creates a Group with the name from a valid group request. * Used by Keywhiz CLI and the web ui. * @responseMessage 200 Successfully created Group * @responseMessage 400 Group with given name already exists */ @Timed @ExceptionMetered @POST @Consumes(APPLICATION_JSON) public Response createGroup(@Auth User user, @Valid CreateGroupRequest request) { logger.info("User '{}' creating group.", user); if (groupDAO.getGroup(request.name).isPresent()) { throw new BadRequestException("Group already exists."); } long groupId = groupDAO.createGroup(request.name, user.getName(), nullToEmpty(request.description), request.metadata); URI uri = UriBuilder.fromResource(GroupsResource.class).build(groupId); Response response = Response.created(uri).entity(groupDetailResponseFromId(groupId)).build(); if (response.getStatus() == HttpStatus.SC_CREATED) { Map<String, String> extraInfo = new HashMap<>(); if (request.description != null) { extraInfo.put("description", request.description); } if (request.metadata != null) { extraInfo.put("metadata", request.metadata.toString()); } auditLog.recordEvent( new Event(Instant.now(), EventTag.GROUP_CREATE, user.getName(), request.name, extraInfo)); } return response; }
From source file:dk.sublife.docker.integration.Container.java
/** * Wait for isUp method call is satisfied. * * @param timoutSeconds seconds before failing * @return true when service is available * @throws InterruptedException//w w w .j a va 2 s. c o m */ protected boolean waitFor(long timoutSeconds) throws Exception { final Instant start = Instant.now(); final ContainerInfo inspect = inspect(); final String name = inspect.name(); final String image = inspect.config().image(); if (LOGGER.isInfoEnabled() && !isUp) { LOGGER.info("Waiting for container is up: {}{}", image, name); } while (!isUp) { try { if (inspect().state().running()) { isUp = isUp(); if (isUp) { if (LOGGER.isInfoEnabled()) { LOGGER.info("Running post startup actions..."); } if (!postStartup()) { throw new RuntimeException("Post startup failed!"); } } } else { LOGGER.error("Container is not up: {}{}", image, name); logFromContainer(); throw new RuntimeException("Container died."); } } catch (RuntimeException e) { throw e; } catch (Exception e) { LOGGER.info(e.getMessage()); } final long seconds = Duration.between(start, Instant.now()).getSeconds(); if (seconds > timoutSeconds) { try { if (inspect().state().running()) { LOGGER.error("Container is running but not up: {}{}", image, name); logFromContainer(); } } catch (final Exception e) { LOGGER.error("Error inspecting container!", e); } throw new RuntimeException("Wait time exceeded."); } Thread.sleep(5000); } if (LOGGER.isInfoEnabled()) { LOGGER.info("container is up {}{}", image, name); } return true; }
From source file:co.runrightfast.vertx.core.eventbus.ProtobufMessageProducer.java
public <RESPONSE> void send(@NonNull final A msg, @NonNull final DeliveryOptions options, @NonNull final Handler<AsyncResult<io.vertx.core.eventbus.Message<RESPONSE>>> handler) { eventBus.send(address, msg, addRunRightFastHeaders(options), handler); this.messageSent.mark(); this.messageLastSent = Instant.now(); }
From source file:com.searchcode.app.util.Helpers.java
public String timeAgo(Instant instant) { if (instant == null) { return "not yet"; }//from w ww . j a v a 2s .c o m long seconds = Instant.now().getEpochSecond() - instant.getEpochSecond(); int minutes = Math.round(seconds / 60); int hours = Math.round(seconds / 3600); int days = Math.round(seconds / 86400); int weeks = Math.round(seconds / 604800); int months = Math.round(seconds / 2600640); int years = Math.round(seconds / 31207680); if (seconds <= 60) { if (seconds == 1) { return "one second ago"; } else { return seconds + " seconds ago"; } } else if (minutes <= 60) { if (minutes == 1) { return "one minute ago"; } else { return minutes + " minutes ago"; } } else if (hours <= 24) { if (hours == 1) { return "an hour ago"; } else { return hours + " hrs ago"; } } else if (days <= 7) { if (days == 1) { return "yesterday"; } else { return days + " days ago"; } } else if (weeks <= 4.3) { if (weeks == 1) { return "a week ago"; } else { return weeks + " weeks ago"; } } else if (months <= 12) { if (months == 1) { return "a month ago"; } else { return months + " months ago"; } } else { if (years == 1) { return "one year ago"; } else { return years + " years ago"; } } }
From source file:org.jboss.as.test.integration.web.session.SessionManagementTestCase.java
@Test public void testSessionManagementOperations() throws Exception { try (CloseableHttpClient client = HttpClients.createDefault()) { ModelNode operation = new ModelNode(); operation.get(ModelDescriptionConstants.OP).set(LIST_SESSIONS); operation.get(ModelDescriptionConstants.OP_ADDR).set(PathAddress .parseCLIStyleAddress("/deployment=management.war/subsystem=undertow").toModelNode()); ModelNode opRes = managementClient.getControllerClient().execute(operation); Assert.assertEquals(opRes.toString(), "success", opRes.get(ModelDescriptionConstants.OUTCOME).asString()); Assert.assertEquals(Collections.emptyList(), opRes.get(ModelDescriptionConstants.RESULT).asList()); long c1 = System.currentTimeMillis(); HttpGet get = new HttpGet("http://" + TestSuiteEnvironment.getServerAddress() + ":8080/management/SessionPersistenceServlet"); HttpResponse res = client.execute(get); long c2 = System.currentTimeMillis(); String sessionId = null;//from w w w . java 2 s. co m for (Header cookie : res.getHeaders("Set-Cookie")) { if (cookie.getValue().startsWith("JSESSIONID=")) { sessionId = cookie.getValue().split("=")[1].split("\\.")[0]; break; } } Assert.assertNotNull(sessionId); opRes = managementClient.getControllerClient().execute(operation); Assert.assertEquals(opRes.toString(), "success", opRes.get(ModelDescriptionConstants.OUTCOME).asString()); Assert.assertEquals(opRes.toString(), Collections.singletonList(new ModelNode(sessionId)), opRes.get(ModelDescriptionConstants.RESULT).asList()); operation.get(SESSION_ID).set(sessionId); opRes = executeOperation(operation, GET_SESSION_CREATION_TIME_MILLIS); long time1 = opRes.get(ModelDescriptionConstants.RESULT).asLong(); Assert.assertTrue(c1 <= time1); Assert.assertTrue(time1 <= c2); opRes = executeOperation(operation, GET_SESSION_CREATION_TIME); long sessionCreationTime = LocalDateTime .parse(opRes.get(ModelDescriptionConstants.RESULT).asString(), DateTimeFormatter.ISO_DATE_TIME) .toInstant(ZoneId.systemDefault().getRules().getOffset(Instant.now())).toEpochMilli(); Assert.assertEquals(time1, sessionCreationTime); opRes = executeOperation(operation, GET_SESSION_LAST_ACCESSED_TIME_MILLIS); Assert.assertEquals(time1, opRes.get(ModelDescriptionConstants.RESULT).asLong()); opRes = executeOperation(operation, GET_SESSION_LAST_ACCESSED_TIME); long aTime2 = LocalDateTime .parse(opRes.get(ModelDescriptionConstants.RESULT).asString(), DateTimeFormatter.ISO_DATE_TIME) .toInstant(ZoneId.systemDefault().getRules().getOffset(Instant.now())).toEpochMilli(); Assert.assertEquals(time1, aTime2); Assert.assertEquals(sessionCreationTime, aTime2); opRes = executeOperation(operation, LIST_SESSION_ATTRIBUTE_NAMES); List<ModelNode> resultList = opRes.get(ModelDescriptionConstants.RESULT).asList(); Assert.assertEquals(1, resultList.size()); Assert.assertEquals(opRes.toString(), "val", resultList.get(0).asString()); opRes = executeOperation(operation, LIST_SESSION_ATTRIBUTES); List<Property> properties = opRes.get(ModelDescriptionConstants.RESULT).asPropertyList(); Assert.assertEquals(opRes.toString(), 1, properties.size()); Property property = properties.get(0); Assert.assertEquals(opRes.toString(), "val", property.getName()); Assert.assertEquals(opRes.toString(), "0", property.getValue().asString()); //we want to make sure that the values will be different //so we wait 10ms Thread.sleep(10); long a1 = System.currentTimeMillis(); client.execute(get); long a2 = System.currentTimeMillis(); do { //because the last access time is updated after the request returns there is a possible race here //to get around this we execute this op in a loop and wait for the value to change //in 99% of cases this will only iterate once //because of the 10ms sleep above they should ways be different //we have a max wait time of 1s if something goes wrong opRes = executeOperation(operation, GET_SESSION_LAST_ACCESSED_TIME_MILLIS); time1 = opRes.get(ModelDescriptionConstants.RESULT).asLong(); if (time1 != sessionCreationTime) { break; } } while (System.currentTimeMillis() < a1 + 1000); Assert.assertTrue(a1 <= time1); Assert.assertTrue(time1 <= a2); opRes = executeOperation(operation, GET_SESSION_LAST_ACCESSED_TIME); long time2 = LocalDateTime .parse(opRes.get(ModelDescriptionConstants.RESULT).asString(), DateTimeFormatter.ISO_DATE_TIME) .toInstant(ZoneId.systemDefault().getRules().getOffset(Instant.now())).toEpochMilli(); Assert.assertEquals(time1, time2); operation.get(ATTRIBUTE).set("val"); opRes = executeOperation(operation, GET_SESSION_ATTRIBUTE); Assert.assertEquals("1", opRes.get(ModelDescriptionConstants.RESULT).asString()); executeOperation(operation, INVALIDATE_SESSION); opRes = executeOperation(operation, LIST_SESSIONS); Assert.assertEquals(Collections.emptyList(), opRes.get(ModelDescriptionConstants.RESULT).asList()); } }
From source file:com.torchmind.stockpile.server.service.api.ProfileService.java
/** * Fetches a display name's associated identifier directly from Mojang. * * @param name a display name.//from w w w . j a v a 2s.c o m * @return an identifier. * * @throws IOException when an error occurs while contacting Mojang. * @throws TooManyRequestsException when the rate limit is exceeded. */ @Nonnull private UUID fetchIdentifier(@Nonnull String name) throws IOException { URL identifierUrl = new URL(String.format(NAME_URL_TEMPLATE, name)); HttpURLConnection connection = (HttpURLConnection) identifierUrl.openConnection(); switch (connection.getResponseCode()) { case 204: // Dear Mojang, // 204 No Content is not the correct status code to signify no results // Thanks for your time throw new NoSuchProfileException(name); case 429: throw new TooManyRequestsException("Rate limit exceeded"); } try (InputStream inputStream = connection.getInputStream()) { JsonNode node = reader.readTree(inputStream); UUID identifier = (new MojangUUID(node.get("id").asText())).toUUID(); // fetch existing profile or create an entirely new one final Profile profile; { Profile prof = this.profileRepository.findOne(identifier); if (prof == null) { profile = new Profile(identifier); } else { profile = prof; profile.setLastSeen(Instant.now()); } } this.profileRepository.save(profile); // fetch an existing display name or create an entirely new one final String currentName = node.get("name").asText(); final DisplayName displayName = this.displayNameRepository.findOneByNameAndProfile(currentName, profile) .orElseGet(() -> new DisplayName(currentName, Instant.now(), profile)); displayName.setLastSeen(Instant.now()); this.displayNameRepository.save(displayName); profile.addName(displayName); return identifier; } }
From source file:org.mla.cbox.shibboleth.idp.authn.impl.ValidateUsernamePasswordAgainstMlaRest.java
/** {@inheritDoc} */ @Override/*from w ww .j a va 2s . c o m*/ protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext, @Nonnull final AuthenticationContext authenticationContext) { log.debug("{} Attempting to authenticate user {}", getLogPrefix(), getUsernamePasswordContext().getUsername()); try { // Construct the URL composed of the API root, members method with id value equal // to the username entered in the login form, the API key, and time stamp. StringBuilder urlBuilder = new StringBuilder().append(this.apiRoot).append("members/") .append(getUsernamePasswordContext().getUsername()).append("?").append("key=") .append(this.apiKey).append("×tamp=") .append(String.valueOf(Instant.now().getEpochSecond())); // The signature is created by prepending the GET method with a '&' separator to the // URL and then computing the SHA256 HMAC hash using the key. // StringBuilder baseStringBuilder = new StringBuilder().append("GET").append("&") .append(UriUtils.encode(urlBuilder.toString(), "UTF-8")); Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKey = new SecretKeySpec(this.apiSecret.getBytes("UTF-8"), "HmacSHA256"); sha256_HMAC.init(secretKey); String signature = Hex .encodeHexString(sha256_HMAC.doFinal(baseStringBuilder.toString().getBytes("UTF-8"))); // Append the signature to the URL. urlBuilder.append("&signature=").append(signature); log.debug("{} MLA query URL is {}", getLogPrefix(), urlBuilder.toString()); // Query the MLA API HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) { /* Set default parser as a JSON parser to make casting to class instance easier */ request.setParser(new JsonObjectParser(JSON_FACTORY)); } }); HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(urlBuilder.toString())); HttpResponse response = request.execute(); // Parse the response and create an instance of the MLAMemberObject. MLAMemberObject mlaMembership = response.parseAs(MLAMemberObject.class); List<MLAMemberObjectData> data = mlaMembership.getData(); // The data element, if present, is a list. If not present then the size of the list // is zero and this indicates that the username could not be found. if (data.size() < 1) { log.info("{} User {} is not known to MLA", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } // Parse out the id, username, password hash, and membership status. String memberId = data.get(0).getId(); String username = data.get(0).getAuthentication().getUsername(); String passwordHash = data.get(0).getAuthentication().getPassword(); String membershipStatus = data.get(0).getAuthentication().getMembership_status(); log.debug("{} MLA returned member Id {}", getLogPrefix(), memberId); log.debug("{} MLA returned username {}", getLogPrefix(), username); log.debug("{} MLA returned password hash {}", getLogPrefix(), passwordHash); log.debug("{} MLA returned membership status {}", getLogPrefix(), membershipStatus); // Non-active members cannot authenticate. if (!new String("active").equals(membershipStatus)) { log.info("{} User {} does not have active status", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } // Compute the bcrypt hash of the password using the salt sent by the MLA API. String pw_hash = BCrypt.hashpw(getUsernamePasswordContext().getPassword(), passwordHash); log.debug("{} Computed hash {}", getLogPrefix(), pw_hash); // Compare the input username with the password hash returned by the MLA API. if (!pw_hash.equals(passwordHash)) { log.info("{} Invalid password", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.INVALID_CREDENTIALS, AuthnEventIds.INVALID_CREDENTIALS); return; } // Set the username in the context directly because the user may have typed the member number // into the form rather than the username. The member number will work for authentication, // but we always want to return the username as the principal. getUsernamePasswordContext().setUsername(username); // Build the authentication result and proceed. log.info("{} Login by '{}' succeeded", getLogPrefix(), getUsernamePasswordContext().getUsername()); buildAuthenticationResult(profileRequestContext, authenticationContext); ActionSupport.buildProceedEvent(profileRequestContext); // } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | InterruptedException e) { } catch (IOException | NoSuchAlgorithmException | InvalidKeyException e) { log.warn("{} Login by {} produced exception", getLogPrefix(), getUsernamePasswordContext().getUsername(), e); handleError(profileRequestContext, authenticationContext, e, AuthnEventIds.AUTHN_EXCEPTION); } }
From source file:Creator.WidgetPanel.java
/** * Creates new form WidgetPanel/*from ww w . ja v a2s . c om*/ * * @param mf * @param cs * @param ws */ public WidgetPanel(MainFrame mf, ControlSettings cs, WidgetSettings ws) { this.mf = mf; this.cs = cs; this.widgetList = new TreeMap<>(); this.ws = ws; holderNum = Instant.now().toEpochMilli(); if (this.ws.wpl != null) { this.ws.wpl = ws.wpl; } else { this.ws.wpl = new WidgetPanelLinks(); } this.listModelWidgetsVars = new DefaultListModel(); this.listModelCodeWidgets = new DefaultListModel(); this.listModelMasterMap = new DefaultListModel(); this.stationID = -1; initComponents(); loadComboBoxPanels(); _ComboBox_Panels.setSelectedIndex(0); }
From source file:org.ng200.openolympus.controller.task.TaskViewController.java
@RequestMapping(method = RequestMethod.POST) public String submitSolution(final HttpServletRequest request, final Model model, final Locale locale, @PathVariable("task") final Task task, final Principal principal, @Valid final SolutionDto solutionDto, final BindingResult bindingResult) throws IllegalStateException, IOException, ArchiveException { Assertions.resourceExists(task);// w w w.j a v a 2 s . com this.assertSuperuserOrTaskAllowed(principal, task); final User user = this.userRepository.findByUsername(principal.getName()); this.solutionDtoValidator.validate(solutionDto, bindingResult); if (bindingResult.hasErrors()) { model.addAttribute("taskDescriptionUUID", task.getDescriptionFile()); model.addAttribute("taskDescriptionURI", MessageFormat .format(TaskViewController.TASK_DESCRIPTION_PATH_TEMPLATE, task.getDescriptionFile())); model.addAttribute("localisedDescriptionFragment", "taskDescription_" + locale.getLanguage()); model.addAttribute("task", task); return "tasks/task"; } final UUID uuid = UUID.randomUUID(); final String solutionPath = MessageFormat.format(TaskViewController.SOLUTION_PATH_TEMPLATE, StorageSpace.STORAGE_PREFIX, uuid.toString(), solutionDto.getTaskFile().getOriginalFilename().replaceAll("[^a-zA-Z0-9-\\._]", "")); final File solutionFile = new File(solutionPath); solutionFile.getParentFile().mkdirs(); solutionDto.getTaskFile().transferTo(solutionFile); Solution solution = new Solution(task, user, solutionFile.getAbsolutePath(), Date.from(Instant.now())); solution = this.solutionRepository.save(solution); this.testingService.testSolutionOnAllTests(solution); return MessageFormat.format("redirect:/solution?id={0}", Long.toString(solution.getId())); }