Example usage for java.time LocalDateTime ofInstant

List of usage examples for java.time LocalDateTime ofInstant

Introduction

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

Prototype

public static LocalDateTime ofInstant(Instant instant, ZoneId zone) 

Source Link

Document

Obtains an instance of LocalDateTime from an Instant and zone ID.

Usage

From source file:fr.pilato.elasticsearch.crawler.fs.framework.FsCrawlerUtil.java

public static LocalDateTime getCreationTime(File file) {
    LocalDateTime time;//from   w  ww  . java  2  s .c  o m
    try {
        Path path = Paths.get(file.getAbsolutePath());
        BasicFileAttributes fileattr = Files.getFileAttributeView(path, BasicFileAttributeView.class)
                .readAttributes();
        time = LocalDateTime.ofInstant(fileattr.creationTime().toInstant(), ZoneId.systemDefault());
    } catch (Exception e) {
        time = null;
    }
    return time;
}

From source file:me.rojo8399.placeholderapi.impl.utils.TypeUtils.java

@SuppressWarnings("unchecked")
public static <T> Optional<T> tryCast(Object val, final Class<T> expected) {
    if (val == null) {
        return Optional.empty();
    }/*from w w  w .j av  a 2s  . c om*/
    if (expected == null) {
        throw new IllegalArgumentException("Must provide an expected class!");
    }
    if (val instanceof BaseValue<?> && !BaseValue.class.isAssignableFrom(expected)) {
        return tryCast(((BaseValue<?>) val).get(), expected);
    }
    if (val instanceof Supplier) {
        Supplier<?> fun = (Supplier<?>) val;
        return tryCast(fun.get(), expected);
    }
    if (Text.class.isAssignableFrom(expected)) {
        if (val instanceof Text) {
            return TypeUtils.tryOptional(() -> expected.cast(val));
        } else {
            if (val instanceof ItemStack) {
                return TypeUtils.tryOptional(() -> expected.cast(TextUtils.ofItem((ItemStack) val)));
            }
            if (val instanceof Instant) {
                return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE
                        .deserialize(PlaceholderAPIPlugin.getInstance().formatter()
                                .format(LocalDateTime.ofInstant((Instant) val, ZoneId.systemDefault())))));
            }
            if (val instanceof Duration) {
                String dur = formatDuration((Duration) val);
                return TypeUtils
                        .tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(dur)));
            }
            if (val instanceof LocalDateTime) {
                return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(
                        PlaceholderAPIPlugin.getInstance().formatter().format((LocalDateTime) val))));
            }
            if (val instanceof CommandSource) {
                return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE
                        .deserialize(String.valueOf(((CommandSource) val).getName()))));
            }
            if (val.getClass().isArray()) {
                List<Text> l2 = unboxPrimitiveArray(val).stream()
                        .map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional())
                        .collect(Collectors.toList());
                return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2)));
            }
            if (val instanceof Iterable) {
                Iterable<?> l = (Iterable<?>) val;
                // should be safe cause we already checked assignability
                @SuppressWarnings("serial")
                final List<Text> l2 = new ArrayList<Object>() {
                    {
                        for (Object o : l) {
                            add(o);
                        }
                    }
                }.stream().map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional())
                        .collect(Collectors.toList());
                return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2)));
            }
            return TypeUtils.tryOptional(
                    () -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(String.valueOf(val))));
        }
    }
    if (val instanceof String) {
        if (String.class.isAssignableFrom(expected)) {
            return tryOptional(() -> expected.cast(val));
        }
        if (expected.isArray() && String.class.isAssignableFrom(expected.getComponentType())) {
            String v = (String) val;
            if (v.isEmpty()) {
                return Optional.empty();
            }
            if (!v.contains("_")) {
                return tryOptional(() -> expected.cast(new String[] { v }));
            }
            String[] x = v.split("_");
            if (x.length == 0) {
                return Optional.empty();
            }
            boolean ne = false;
            for (String s : x) {
                ne = ne || !s.isEmpty();
            }
            if (!ne) {
                return Optional.empty();
            }
            return tryOptional(() -> expected.cast(x));
        }
        if (List.class.isAssignableFrom(expected)
                && String.class.isAssignableFrom(expected.getTypeParameters()[0].getGenericDeclaration())) {
            String v = (String) val;
            if (v.isEmpty()) {
                return Optional.empty();
            }
            if (!v.contains("_")) {
                return tryOptional(() -> expected.cast(Collections.singletonList(v)));
            }
            String[] x = v.split("_");
            if (x.length == 0) {
                return Optional.empty();
            }
            boolean ne = false;
            for (String s : x) {
                ne = ne || !s.isEmpty();
            }
            if (!ne) {
                return Optional.empty();
            }
            return tryOptional(() -> expected.cast(Arrays.asList(x)));
        }
        Optional<T> opt = tryOptional(() -> convertPrimitive((String) val, expected));
        if (opt.isPresent()) {
            return opt;
        }
        opt = deserializers.entrySet().stream()
                .filter(e -> e.getKey().isSubtypeOf(expected) || e.getKey().getRawType().equals(expected))
                .map(Map.Entry::getValue).map(f -> tryOptional(() -> f.apply((String) val)))
                .flatMap(unmapOptional()).findAny().flatMap(o -> tryOptional(() -> expected.cast(o)));
        if (opt.isPresent()) {
            return opt;
        }
        try {
            // should theoretically match any string -> object conversions, such as deser

            // for now im filtering against method names as well just to avoid issues where
            // expected result is not obtained due to weird methods, might change in future
            Method method = Arrays.stream(expected.getDeclaredMethods())
                    .filter(m -> Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers()))
                    .filter(m -> Arrays.stream(m.getParameterTypes()).anyMatch(c -> c.equals(String.class)))
                    .filter(m -> m.getReturnType().equals(expected) || m.getReturnType().equals(Optional.class))
                    .filter(m -> STRING_TO_VAL_PATTERN.matcher(m.getName()).find()).findAny().get(); // error if no
            Object valout = method.invoke(null, (String) val);
            if (valout == null) {
                return Optional.empty();
            }
            if (expected.isInstance(valout)) {
                // Register a new deserializer once we confirm it works. Should prevent
                // extremely long parsing from happening multiple times.
                final MethodHandle mh = MethodHandles.publicLookup().unreflect(method);
                PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> {
                    try {
                        return expected.cast(mh.invokeExact((String) val));
                    } catch (Throwable e1) {
                        throw new RuntimeException(e1);
                    }
                });
                return tryOptional(() -> expected.cast(valout));
            }
            if (valout instanceof Optional) {
                Optional<?> valopt = (Optional<?>) valout;
                if (!valopt.isPresent()) {
                    return Optional.empty();
                }
                Object v = valopt.get();
                if (expected.isInstance(v)) {
                    // Register a new deserializer once we confirm it works. Should prevent
                    // extremely long parsing from happening multiple times.
                    final MethodHandle mh = MethodHandles.publicLookup().unreflect(method);
                    PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> {
                        try {
                            Optional<?> optx = (Optional<?>) mh.invokeExact((String) val);
                            return expected.cast(optx.get());
                        } catch (Throwable e1) {
                            throw new RuntimeException(e1);
                        }
                    });
                    return tryOptional(() -> expected.cast(v));
                } else {
                    return Optional.empty();
                }
            }
            return Optional.empty();
        } catch (Exception e) {
            // fires if no method found, if invoke throws, if something else goes wrong
            return Optional.empty();
        }
    }
    return TypeUtils.tryOptional(() -> expected.cast(val));
}

From source file:software.reinvent.dependency.parser.service.ArtifactDependencyGraph.java

/**
 * Adds a model as {@link ArtifactParent}. Parses especially the managed dependencies to make sure that the
 * dependencies which are child of the parent will contain the versions.
 *
 * @param parent the model to add//from   ww w.  java2s  .com
 */
private void addParent(final Model parent) {
    final Properties properties = parent.getProperties();
    final List<Dependency> managedDependencies = parent.getDependencyManagement().getDependencies();
    setVersionToDepencies(parent, managedDependencies);
    addDependencies(managedDependencies);
    final ArtifactParent artifactParent = new ArtifactParent(parent.getGroupId(), parent.getArtifactId(),
            parent.getVersion(), LocalDateTime.ofInstant(
                    Instant.ofEpochMilli(parent.getPomFile().lastModified()), ZoneId.systemDefault()));
    if (artifactParents.contains(artifactParent)) {
        artifactParents.stream().filter(x -> x.equals(artifactParent)).findFirst().ifPresent(x -> {
            if (x.getFileDate().isBefore(artifactParent.getFileDate())) {
                artifactParents.remove(artifactParent);
            }
        });
        artifactParents.add(artifactParent);
    } else {
        artifactParents.add(artifactParent);
    }
}

From source file:retsys.client.controller.DeliveryChallanReturnController.java

/**
 * Initializes the controller class./*w w w.java2 s .c  om*/
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    dc_date.setValue(LocalDate.now());

    material_name.setCellValueFactory(new PropertyValueFactory<DCItem, String>("name"));
    brand_name.setCellValueFactory(new PropertyValueFactory<DCItem, String>("brand"));
    model_code.setCellValueFactory(new PropertyValueFactory<DCItem, String>("model"));
    units.setCellValueFactory(new PropertyValueFactory<DCItem, String>("model"));
    quantity.setCellValueFactory(new PropertyValueFactory<DCItem, Integer>("quantity"));
    amount.setCellValueFactory(new PropertyValueFactory<DCItem, Integer>("amount"));

    dcDetail.getColumns().setAll(material_name, brand_name, model_code, quantity, amount);
    // TODO

    AutoCompletionBinding<Item> bindForTxt_name = TextFields.bindAutoCompletion(txt_name,
            new Callback<AutoCompletionBinding.ISuggestionRequest, Collection<Item>>() {

                @Override
                public Collection<Item> call(AutoCompletionBinding.ISuggestionRequest param) {
                    List<Item> list = null;
                    try {
                        LovHandler lovHandler = new LovHandler("items", "name");
                        String response = lovHandler.getSuggestions(param.getUserText());
                        list = (List<Item>) new JsonHelper().convertJsonStringToObject(response,
                                new TypeReference<List<Item>>() {
                                });
                    } catch (IOException ex) {
                        Logger.getLogger(ProjectController.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    return list;
                }
            }, new StringConverter<Item>() {

                @Override
                public String toString(Item object) {
                    System.out.println("here..." + object);
                    return object.getName() + " (ID:" + object.getId() + ")";
                }

                @Override
                public Item fromString(String string) {
                    throw new UnsupportedOperationException();
                }
            });
    //event handler for setting other item fields with values from selected Item object
    //fires after autocompletion
    bindForTxt_name.setOnAutoCompleted(new EventHandler<AutoCompletionBinding.AutoCompletionEvent<Item>>() {

        @Override
        public void handle(AutoCompletionBinding.AutoCompletionEvent<Item> event) {
            Item item = event.getCompletion();
            //fill other item related fields
            txt_name.setUserData(item.getId());
            txt_brand.setText(item.getBrand());
            txt_model.setText(null); // item doesn't have this field. add??
            txt_rate.setText(String.valueOf(item.getRate()));
        }
    });

    AutoCompletionBinding<DeliveryChallan> bindForProject = TextFields.bindAutoCompletion(project,
            new Callback<AutoCompletionBinding.ISuggestionRequest, Collection<DeliveryChallan>>() {

                @Override
                public Collection<DeliveryChallan> call(AutoCompletionBinding.ISuggestionRequest param) {
                    List<DeliveryChallan> list = null;
                    try {
                        LovHandler lovHandler = new LovHandler("deliverychallans", "name");
                        String response = lovHandler.getSuggestions(param.getUserText());
                        list = (List<DeliveryChallan>) new JsonHelper().convertJsonStringToObject(response,
                                new TypeReference<List<DeliveryChallan>>() {
                                });
                    } catch (IOException ex) {
                        Logger.getLogger(ProjectController.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    return list;
                }
            }, new StringConverter<DeliveryChallan>() {

                @Override
                public String toString(DeliveryChallan object) {
                    System.out.println("here..." + object);

                    String strDate = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(LocalDateTime
                            .ofInstant(object.getChallanDate().toInstant(), ZoneId.systemDefault()));
                    return "Project:" + object.getProject().getName() + " DC Date:" + strDate + " DC No.:"
                            + object.getId();
                }

                @Override
                public DeliveryChallan fromString(String string) {
                    throw new UnsupportedOperationException();
                }
            });

    bindForProject
            .setOnAutoCompleted(new EventHandler<AutoCompletionBinding.AutoCompletionEvent<DeliveryChallan>>() {

                @Override
                public void handle(AutoCompletionBinding.AutoCompletionEvent<DeliveryChallan> event) {
                    DeliveryChallan dc = event.getCompletion();
                    dc_no.setText(dc.getId().toString());
                    dc_date.setValue(LocalDateTime
                            .ofInstant(dc.getChallanDate().toInstant(), ZoneId.systemDefault()).toLocalDate());
                    dc_no.setText(dc.getId().toString());
                    project.setText(dc.getProject().getName() + " (ID:" + dc.getProject().getId() + ")");
                    deliverymode.setText(dc.getDeliveryMode());
                    concernperson.setText(dc.getConcernPerson());

                    ObservableList<DCItem> items = FXCollections.observableArrayList();
                    Iterator detailsIt = dc.getDeliveryChallanDetail().iterator();
                    while (detailsIt.hasNext()) {
                        DeliveryChallanDetail detail = (DeliveryChallanDetail) detailsIt.next();
                        Item item = detail.getItem();
                        int id = item.getId();
                        String site = item.getSite();
                        String name = item.getName();
                        String brand = item.getBrand();
                        String model = null;
                        int rate = item.getRate().intValue();
                        int quantity = detail.getQuantity();
                        int amount = detail.getAmount();
                        String units = detail.getUnits();

                        items.add(new DCItem(id, name + " (ID:" + id + ")", brand, model, rate, quantity, units,
                                amount));
                    }
                    dcDetail.setItems(items);

                    populateAuditValues(dc);

                }
            });

    txt_qty.focusedProperty().addListener(new ChangeListener<Boolean>() {
        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (!newValue) {
                calcAmount();
            }
        }
    });
}

From source file:software.reinvent.dependency.parser.service.ArtifactDependencyGraph.java

/**
 * Adds a non parent {@link Model} as {@link Artifact}.
 *
 * @param model the model to parse// ww w .  j a  v a  2s.  c o m
 */
private void addArtifact(final Model model) {
    final Properties properties = model.getProperties();
    final List<Dependency> dependencies = model.getDependencies();
    setVersionToDepencies(model, dependencies);
    final Set<ArtifactDependency> artifactDependencies = addDependencies(dependencies);

    final String groupId = model.getGroupId() == null ? model.getParent().getGroupId() : model.getGroupId();

    final ArtifactParent artifactParent = model.getParent() == null ? null
            : new ArtifactParent(model.getParent());
    Artifact artifact = new Artifact(
            groupId, model.getArtifactId(), model.getVersion(), model.getPackaging(), LocalDateTime
                    .ofInstant(Instant.ofEpochMilli(model.getPomFile().lastModified()), ZoneId.systemDefault()),
            artifactParent);
    if (artifacts.contains(artifact)) {
        artifacts.stream().filter(x -> x.equals(artifact)).findFirst().ifPresent(x -> {
            if (x.getFileDate().isBefore(artifact.getFileDate())) {
                artifacts.remove(artifact);
            } else {
                x.getDependencies().addAll(artifactDependencies);
            }
        });
        artifact.getDependencies().addAll(artifactDependencies);
        artifacts.add(artifact);
    } else {
        artifact.getDependencies().addAll(artifactDependencies);
        artifacts.add(artifact);
    }
}

From source file:com.thinkbiganalytics.nifi.v2.ingest.GetTableData.java

private static LocalDateTime toDateTime(Date date) {
    return date == null ? LocalDateTime.MIN
            : LocalDateTime.ofInstant(date.toInstant(), ZoneOffset.UTC.normalized());
}

From source file:retsys.client.controller.PurchaseOrderConfirmController.java

/**
 * Initializes the controller class./* ww  w .  ja  v a2  s  .c  om*/
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    po_date.setValue(LocalDate.now());

    loc_of_material.setCellValueFactory(new PropertyValueFactory<POItem, String>("location"));
    material_name.setCellValueFactory(new PropertyValueFactory<POItem, String>("name"));
    brand_name.setCellValueFactory(new PropertyValueFactory<POItem, String>("brand"));
    model_code.setCellValueFactory(new PropertyValueFactory<POItem, String>("model"));
    quantity.setCellValueFactory(new PropertyValueFactory<POItem, Integer>("quantity"));
    confirm.setCellValueFactory(new PropertyValueFactory<POItem, Boolean>("confirm"));
    confirm.setCellFactory(CheckBoxTableCell.forTableColumn(confirm));
    billNo.setCellValueFactory(new PropertyValueFactory<POItem, String>("billNo"));
    billNo.setCellFactory(TextFieldTableCell.forTableColumn());
    supervisor.setCellValueFactory(new PropertyValueFactory<POItem, String>("supervisor"));
    supervisor.setCellFactory(TextFieldTableCell.forTableColumn());
    receivedDate.setCellValueFactory(new PropertyValueFactory<POItem, LocalDate>("receivedDate"));
    receivedDate.setCellFactory(new Callback<TableColumn<POItem, LocalDate>, TableCell<POItem, LocalDate>>() {

        @Override
        public TableCell<POItem, LocalDate> call(TableColumn<POItem, LocalDate> param) {
            TableCell<POItem, LocalDate> cell = new TableCell<POItem, LocalDate>() {

                @Override
                protected void updateItem(LocalDate item, boolean empty) {
                    super.updateItem(item, empty); //To change body of generated methods, choose Tools | Templates.
                    if (empty || item == null) {
                        setText(null);
                        setGraphic(null);
                    } else {
                        setText(formatter.format(item));
                    }
                }

                @Override
                public void startEdit() {
                    super.startEdit();
                    System.out.println("start edit");
                    DatePicker dateControl = null;
                    if (this.getItem() != null) {
                        dateControl = new DatePicker(this.getItem());
                    } else {
                        dateControl = new DatePicker();
                    }

                    dateControl.valueProperty().addListener(new ChangeListener<LocalDate>() {

                        @Override
                        public void changed(ObservableValue<? extends LocalDate> observable, LocalDate oldValue,
                                LocalDate newValue) {
                            if (newValue == null) {
                                cancelEdit();
                            } else {
                                commitEdit(newValue);
                            }
                        }
                    });
                    this.setGraphic(dateControl);
                }

                @Override
                public void cancelEdit() {
                    super.cancelEdit();
                    System.out.println("cancel edit");
                    setGraphic(null);
                    if (this.getItem() != null) {
                        setText(formatter.format(this.getItem()));
                    } else {
                        setText(null);
                    }
                }

                @Override
                public void commitEdit(LocalDate newValue) {
                    super.commitEdit(newValue);
                    System.out.println("commit edit");
                    setGraphic(null);
                    setText(formatter.format(newValue));
                }
            };

            return cell;
        }
    });

    poDetail.getColumns().setAll(loc_of_material, material_name, brand_name, model_code, quantity, confirm,
            receivedDate, billNo, supervisor);
    AutoCompletionBinding<PurchaseOrder> bindForTxt_name = TextFields.bindAutoCompletion(project,
            new Callback<AutoCompletionBinding.ISuggestionRequest, Collection<PurchaseOrder>>() {

                @Override
                public Collection<PurchaseOrder> call(AutoCompletionBinding.ISuggestionRequest param) {
                    List<PurchaseOrder> list = null;
                    try {
                        LovHandler lovHandler = new LovHandler("purchaseorders", "name");
                        String response = lovHandler.getSuggestions(param.getUserText());
                        list = (List<PurchaseOrder>) new JsonHelper().convertJsonStringToObject(response,
                                new TypeReference<List<PurchaseOrder>>() {
                                });
                    } catch (IOException ex) {
                        Logger.getLogger(ProjectController.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    return list;
                }
            }, new StringConverter<PurchaseOrder>() {

                @Override
                public String toString(PurchaseOrder object) {
                    System.out.println("here..." + object);

                    String strDate = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).format(
                            LocalDateTime.ofInstant(object.getDate().toInstant(), ZoneId.systemDefault()));
                    return "Project:" + object.getProject().getName() + " PO Date:" + strDate + " PO No.:"
                            + object.getId();
                }

                @Override
                public PurchaseOrder fromString(String string) {
                    throw new UnsupportedOperationException();
                }
            });

    bindForTxt_name
            .setOnAutoCompleted(new EventHandler<AutoCompletionBinding.AutoCompletionEvent<PurchaseOrder>>() {

                @Override
                public void handle(AutoCompletionBinding.AutoCompletionEvent<PurchaseOrder> event) {
                    populateData(event.getCompletion());
                }
            });

    AutoCompletionBinding<Vendor> bindForVendor = TextFields.bindAutoCompletion(vendor,
            new Callback<AutoCompletionBinding.ISuggestionRequest, Collection<Vendor>>() {

                @Override
                public Collection<Vendor> call(AutoCompletionBinding.ISuggestionRequest param) {
                    List<Vendor> list = null;
                    try {
                        LovHandler lovHandler = new LovHandler("vendors", "name");
                        String response = lovHandler.getSuggestions(param.getUserText());
                        list = (List<Vendor>) new JsonHelper().convertJsonStringToObject(response,
                                new TypeReference<List<Vendor>>() {
                                });
                    } catch (IOException ex) {
                        Logger.getLogger(ProjectController.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    return list;
                }
            }, new StringConverter<Vendor>() {

                @Override
                public String toString(Vendor object) {
                    return object.getName() + " (ID:" + object.getId() + ")";
                }

                @Override
                public Vendor fromString(String string) {
                    throw new UnsupportedOperationException();
                }
            });
}

From source file:software.coolstuff.springframework.owncloud.service.impl.rest.OwncloudRestResourceServiceImpl.java

private OwncloudRestResourceExtension createOwncloudResourceFrom(DavResource davResource,
        OwncloudResourceConversionProperties conversionProperties) {
    log.debug("Create OwncloudResource based on DavResource {}", davResource.getHref());
    MediaType mediaType = MediaType.valueOf(davResource.getContentType());
    URI rootPath = conversionProperties.getRootPath();
    URI href = rootPath.resolve(davResource.getHref());
    String name = davResource.getName();
    if (davResource.isDirectory() && href.equals(rootPath)) {
        name = SLASH;/* w w  w. j av a 2 s . com*/
    }
    LocalDateTime lastModifiedAt = LocalDateTime.ofInstant(davResource.getModified().toInstant(),
            ZoneId.systemDefault());
    href = rootPath.relativize(href);
    href = URI.create(SLASH).resolve(href).normalize(); // prepend "/" to the href
    OwncloudRestResourceExtension owncloudResource = OwncloudRestResourceImpl.builder().href(href).name(name)
            .lastModifiedAt(lastModifiedAt).mediaType(mediaType)
            .eTag(StringUtils.strip(davResource.getEtag(), QUOTE)).build();
    if (davResource.isDirectory()) {
        return owncloudResource;
    }
    return OwncloudRestFileResourceImpl.fileBuilder().owncloudResource(owncloudResource)
            .contentLength(davResource.getContentLength()).build();
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceServiceImpl.java

private OwncloudLocalResourceExtension createOwncloudResourceOf(Path path) {
    Path rootPath = getRootLocationOfAuthenticatedUser();
    Path relativePath = rootPath.toAbsolutePath().relativize(path.toAbsolutePath());
    URI href = URI.create(UriComponentsBuilder.fromPath("/").path(relativePath.toString()).toUriString());
    String name = path.getFileName().toString();
    MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
    if (Files.isDirectory(path)) {
        href = URI.create(UriComponentsBuilder.fromUri(href).path("/").toUriString());
        mediaType = OwncloudUtils.getDirectoryMediaType();
    } else {//from ww  w .  j a  v  a 2  s  .c  o m
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentType = fileNameMap.getContentTypeFor(path.getFileName().toString());
        if (StringUtils.isNotBlank(contentType)) {
            mediaType = MediaType.valueOf(contentType);
        }
    }
    try {
        LocalDateTime lastModifiedAt = LocalDateTime.ofInstant(Files.getLastModifiedTime(path).toInstant(),
                ZoneId.systemDefault());
        Optional<String> checksum = checksumService.getChecksum(path);
        if (Files.isSameFile(rootPath, path)) {
            name = "/";
            checksum = Optional.empty();
        }
        OwncloudLocalResourceExtension resource = OwncloudLocalResourceImpl.builder().href(href).name(name)
                .eTag(checksum.orElse(null)).mediaType(mediaType).lastModifiedAt(lastModifiedAt).build();
        if (Files.isDirectory(path)) {
            return resource;
        }

        return OwncloudLocalFileResourceImpl.fileBuilder().owncloudResource(resource)
                .contentLength(Files.size(path)).build();
    } catch (NoSuchFileException e) {
        throw new OwncloudResourceNotFoundException(href, getUsername());
    } catch (IOException e) {
        val logMessage = String.format("Cannot create OwncloudResource from Path %s", path);
        log.error(logMessage, e);
        throw new OwncloudLocalResourceException(logMessage, e);
    }
}

From source file:com.bdb.weather.display.summary.HighLowMedianTempPanel.java

@Override
public void chartMouseClicked(ChartMouseEventFX event) {
    ChartEntity entity = event.getEntity();
    //// www  .  ja  v  a 2 s.  c  o m
    // Was a point on the plot selected?
    //
    if (entity instanceof XYItemEntity) {
        XYItemEntity itemEntity = (XYItemEntity) entity;
        XYDataset dataset = itemEntity.getDataset();
        Number x = dataset.getXValue(itemEntity.getSeriesIndex(), itemEntity.getItem());

        //ZoneId id = ZoneId.of(ZoneId.systemDefault().getId());
        //ZoneOffset offset = ZoneOffset.of(ZoneId.systemDefault().getId());
        LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochSecond(x.longValue() / 1000),
                ZoneId.systemDefault());

        boolean doubleClick = event.getTrigger().getClickCount() == 2;
        if (doubleClick)
            supporter.launchView(viewLauncher, time.toLocalDate());
    }
}