Example usage for java.time LocalDateTime now

List of usage examples for java.time LocalDateTime now

Introduction

In this page you can find the example usage for java.time LocalDateTime now.

Prototype

public static LocalDateTime now() 

Source Link

Document

Obtains the current date-time from the system clock in the default time-zone.

Usage

From source file:org.eclipse.winery.repository.rest.resources.MainResource.java

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(value = "Imports the given CSAR (sent by simplesinglefileupload.jsp)")
@ApiResponses(value = {//from w w w  .j  a v a2s  .c o m
        @ApiResponse(code = 200, message = "success", responseHeaders = @ResponseHeader(description = "If the CSAR could be partially imported, the points where it failed are returned in the body")) })
// @formatter:off
public Response importCSAR(@FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileDetail,
        @FormDataParam("overwrite") @ApiParam(value = "true: content of CSAR overwrites existing content. false (default): existing content is kept") Boolean overwrite,
        @FormDataParam("validate") @ApiParam(value = "true: validates the hash of the manifest file with the one stored in the accountability layer") Boolean validate,
        @Context UriInfo uriInfo) {
    LocalDateTime start = LocalDateTime.now();
    // @formatter:on
    CsarImporter importer = new CsarImporter();
    CsarImportOptions options = new CsarImportOptions();
    options.setOverwrite((overwrite != null) && overwrite);
    options.setAsyncWPDParsing(false);
    options.setValidate((validate != null) && validate);
    ImportMetaInformation importMetaInformation;
    try {
        importMetaInformation = importer.readCSAR(uploadedInputStream, options);
    } catch (Exception e) {
        return Response.serverError().entity("Could not import CSAR").entity(e.getMessage()).build();
    }
    if (importMetaInformation.errors.isEmpty()) {
        if (options.isValidate()) {

            return Response.ok(importMetaInformation, MediaType.APPLICATION_JSON).build();
        } else if (Objects.nonNull(importMetaInformation.entryServiceTemplate)) {
            URI url = uriInfo.getBaseUri()
                    .resolve(RestUtils.getAbsoluteURL(importMetaInformation.entryServiceTemplate));
            LOGGER.debug("CSAR import lasted {}", Duration.between(LocalDateTime.now(), start).toString());
            return Response.created(url).build();
        } else {
            LOGGER.debug("CSAR import lasted {}", Duration.between(LocalDateTime.now(), start).toString());
            return Response.noContent().build();
        }
    } else {
        LOGGER.debug("CSAR import lasted {}", Duration.between(LocalDateTime.now(), start).toString());
        // In case there are errors, we send them as "bad request"
        return Response.status(Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON)
                .entity(importMetaInformation).build();
    }
}

From source file:org.cloud.mblog.utils.FileUtil.java

/**
 * ?/*w w  w  .  j  a va  2  s.  c  o m*/
 *
 * @param file
 * @return
 */
public static ImageData uploadSingleFile(MultipartFile file, HttpServletRequest request, Boolean haveThumb) {
    if (!file.isEmpty()) {
        LocalDateTime now = LocalDateTime.now();
        String imageRelativeFolder = getImageRelativePathByDate(now);
        String thumbRelativeFolder = getThumbRelativePathByDate(now);

        String sourceFileName = file.getOriginalFilename();
        String fileType = sourceFileName.substring(sourceFileName.lastIndexOf(".") + 1);
        String fileName = getWidFileName(fileType);
        File targetFile = new File(LOCALROOT + imageRelativeFolder + File.separator + fileName);
        try {
            file.transferTo(targetFile);
            logger.info("Upload file path: " + targetFile.getAbsolutePath());
            if (haveThumb) {
                File thumbFile = new File(LOCALROOT + thumbRelativeFolder + File.separator + fileName);
                ImageUtil.zoomImage(targetFile, thumbFile, 300);
            }
            return new ImageData(fileName, file.getSize(), imageRelativeFolder, thumbRelativeFolder);
        } catch (Exception e) {
            logger.error("error", e);
        }
    }
    return null;
}

From source file:org.jspare.jsdbc.JsdbcMockedImpl.java

@Override
public <T> QueryResult<T> queryFor(Query query) throws JsdbcException {

    try {//from w  w w.  j  av a  2s . c  o m

        Map<String, Object> m = new HashMap<>();
        this.data.entrySet().forEach(es -> {
            try {
                m.put(es.getKey(), es.getValue());
            } catch (Exception e) {
            }
        });

        QueryResult<T> result = new QueryResult<>(Status.SUCCESS, LocalDateTime.now(), "tid", m);
        return result;
    } catch (SerializationException e) {

        throw new JsdbcException(e);
    }
}

From source file:nc.noumea.mairie.appock.viewmodel.EditStockReferentAchatViewModel.java

@Command
public void demandeInventaireTousService() {
    Messagebox.show("Voulez-vous vraiment demander  tous les services de raliser un inventaire ?",
            "Suppression", new Messagebox.Button[] { Messagebox.Button.YES, Messagebox.Button.NO },
            Messagebox.QUESTION, evt -> {
                if (evt.getName().equals("onYes")) {
                    for (Service service : serviceService.findAllActif()) {
                        if (service.getStock() == null) {
                            service.setStock(new Stock());
                            service = serviceService.save(service);
                        }/*ww w  .  ja  va2 s.c o m*/

                        Stock stock = stockService.findOne(service.getStock().getId());
                        stock.setInventaireDemande(true);
                        stock.setInventaireDemandeUser(authHelper.getCurrentUser().getNomComplet());
                        stock.setDateDerniereDemandeInventaire(LocalDateTime.now());
                        stockService.save(stock);
                        mailService.sendMailDemandeInventaire(service);

                        refreshListeArticleStock();
                        rechargeOngletMonStock();
                        BindUtils.postNotifyChange(null, null, this, "*");
                        showNotificationStandard("Demande d'inventaire envoye  tous les services");
                    }
                }
            });
}

From source file:org.wallride.service.UserService.java

@CacheEvict(value = WallRideCacheConfiguration.USER_CACHE, allEntries = true)
public User updateProfile(ProfileUpdateRequest request, AuthorizedUser updatedBy) {
    User user = userRepository.findOneForUpdateById(request.getUserId());
    if (user == null) {
        throw new IllegalArgumentException("The user does not exist");
    }//from   w ww . j a  v a  2  s.c  o m

    User duplicate;
    if (!ObjectUtils.nullSafeEquals(request.getEmail(), user.getEmail())) {
        duplicate = userRepository.findOneByEmail(request.getEmail());
        if (duplicate != null) {
            throw new DuplicateEmailException(request.getEmail());
        }
    }
    if (!ObjectUtils.nullSafeEquals(request.getLoginId(), user.getLoginId())) {
        duplicate = userRepository.findOneByLoginId(request.getLoginId());
        if (duplicate != null) {
            throw new DuplicateLoginIdException(request.getLoginId());
        }
    }

    user.setEmail(request.getEmail());
    user.setLoginId(request.getLoginId());
    user.setName(request.getName());
    user.setUpdatedAt(LocalDateTime.now());
    user.setUpdatedBy(updatedBy.toString());
    return userRepository.saveAndFlush(user);
}

From source file:com.doctor.esper.reference_5_2_0.Chapter6EPLReferenceNamedWindowsAndTables.java

/**
 * Chapter 3. Processing Model//from w ww  .j  a va 2 s  .co  m
 * 3.7. Aggregation and Grouping
 * ?
 * 
 * @see http://www.espertech.com/esper/release-5.2.0/esper-reference/html_single/index.html#processingmodel_aggregation
 *      http://www.espertech.com/esper/release-5.2.0/esper-reference/html_single/index.html#config-variables
 *      http://www.espertech.com/esper/release-5.2.0/esper-reference/html_single/index.html#variable_using
 *      http://www.espertech.com/esper/release-5.2.0/esper-reference/html_single/index.html#config-engine-variables
 * 
 * @param eventBean
 * @return
 * @throws InterruptedException
 */
@Test
public void test_() throws InterruptedException {
    HttpLog httpLog = new HttpLog(1, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com",
            "userAgent", LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(1, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(1, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(1, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(1, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(1, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    TimeUnit.SECONDS.sleep(10);

    httpLog = new HttpLog(1, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(1, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(1, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(1, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(1, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(1, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
    httpLog = new HttpLog(1, UUID.randomUUID().toString(), "www.baidu.com/tieba", "www.baidu.com", "userAgent",
            LocalDateTime.now());
    esperTemplateBean.sendEvent(httpLog);
}

From source file:org.apache.metron.dataloads.nonbulk.geo.MaxmindDbEnrichmentLoader.java

protected void loadGeoLiteDatabase(CommandLine cli) throws IOException {
    // Retrieve the database file
    System.out.println("Retrieving GeoLite2 archive");

    String geo_url = GeoEnrichmentOptions.GEO_URL.get(cli, GEO_CITY_URL_DEFAULT);
    String asn_url = GeoEnrichmentOptions.ASN_URL.get(cli, ASN_URL_DEFAULT);

    String tmpDir = GeoEnrichmentOptions.TMP_DIR.get(cli, "/tmp") + "/"; // Make sure there's a file separator at the end
    int numRetries = Integer.parseInt(GeoEnrichmentOptions.RETRIES.get(cli, DEFAULT_RETRIES));
    File localGeoFile = null;//from w  w w .  j  a v a2 s. c om
    File localAsnFile = null;
    try {
        localGeoFile = downloadGeoFile(geo_url, tmpDir, numRetries);
        localAsnFile = downloadGeoFile(asn_url, tmpDir, numRetries);
    } catch (IllegalStateException ies) {
        System.err.println("Failed to download geo db file. Aborting");
        System.exit(5);
    }
    // Want to delete the tar in event of failure
    localGeoFile.deleteOnExit();
    localAsnFile.deleteOnExit();
    System.out.println("GeoIP files downloaded successfully");

    // Push the Geo file to HDFS and update Configs to ensure clients get new view
    String zookeeper = GeoEnrichmentOptions.ZK_QUORUM.get(cli);
    long millis = LocalDateTime.now().toInstant(ZoneOffset.UTC).toEpochMilli();
    String hdfsGeoLoc = GeoEnrichmentOptions.REMOTE_GEO_DIR.get(cli, "/apps/metron/geo/" + millis);
    System.out.println("Putting GeoLite City file into HDFS at: " + hdfsGeoLoc);

    // Put Geo into HDFS
    Path srcPath = new Path(localGeoFile.getAbsolutePath());
    Path dstPath = new Path(hdfsGeoLoc);
    putDbFile(srcPath, dstPath);
    pushConfig(srcPath, dstPath, GeoLiteCityDatabase.GEO_HDFS_FILE, zookeeper);

    // Push the ASN file to HDFS and update Configs to ensure clients get new view
    String hdfsAsnLoc = GeoEnrichmentOptions.REMOTE_ASN_DIR.get(cli, "/apps/metron/asn/" + millis);
    System.out.println("Putting ASN file into HDFS at: " + hdfsAsnLoc);

    // Put ASN into HDFS
    srcPath = new Path(localAsnFile.getAbsolutePath());
    dstPath = new Path(hdfsAsnLoc);
    putDbFile(srcPath, dstPath);
    pushConfig(srcPath, dstPath, GeoLiteAsnDatabase.ASN_HDFS_FILE, zookeeper);

    System.out.println("GeoLite2 file placement complete");
    System.out.println("Successfully created and updated new GeoLite information");
}

From source file:de.tum.in.socket.client.SocketClient.java

/**
 * Publishes asynchronous events for caching
 *//*from w w w. java  2 s . c  om*/
private void doBroadcastEventsForCaching(final String message) {
    LOGGER.debug("Publishing Event for caching wifi data...");

    final Dictionary<String, Object> properties = new Hashtable<>();
    properties.put("data", message);
    properties.put("timestamp", LocalDateTime.now());
    final Event event = new Event(Events.DATA_CACHE, properties);

    this.m_eventAdmin.postEvent(event);

    LOGGER.debug("Publishing Event for caching wifi data...Done");
}

From source file:org.ojbc.adapters.analyticaldatastore.personid.IndexedIdentifierGenerationStrategy.java

/**
 * This method will back up the lucene cache using the specified backup path.
 * It will create a new directory with the format yyyy_MM_dd_HH_mm_ss which will
 * contain the backed up index.  Hot backups are allowed.
 * //from  www .  j  a v  a 2  s .  co m
 */
@Override
public String backup() throws Exception {
    SnapshotDeletionPolicy snapshotter = (SnapshotDeletionPolicy) indexWriter.getConfig()
            .getIndexDeletionPolicy();

    IndexCommit commit = null;
    String backupFileDirectory = "";

    try {
        LocalDateTime today = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu_MM_dd_HH_mm_ss");
        String dateTimeStamp = today.format(dtf);

        if (!(indexBackupRoot.endsWith("/") || indexBackupRoot.endsWith("\\"))) {
            indexBackupRoot = indexBackupRoot + System.getProperty("file.separator");
        }

        backupFileDirectory = indexBackupRoot + dateTimeStamp + System.getProperty("file.separator");

        commit = snapshotter.snapshot();
        for (String fileName : commit.getFileNames()) {
            log.debug("File Name: " + fileName);

            File srcFile = new File(indexDirectoryPath + System.getProperty("file.separator") + fileName);
            File destFile = new File(backupFileDirectory + System.getProperty("file.separator") + fileName);

            FileUtils.copyFile(srcFile, destFile);

        }
    } catch (Exception e) {
        log.error("Exception", e);
    } finally {
        snapshotter.release(commit);
    }

    return backupFileDirectory;
}

From source file:org.jspare.jsdbc.JsdbcMockedImpl.java

/**
 * Result success.//from   w w w. ja  va2s.c  o m
 *
 * @return the result
 */
private Result resultSuccess() {

    return new Result(Status.SUCCESS, LocalDateTime.now(), "tid");
}