Example usage for org.joda.time.format DateTimeFormatter print

List of usage examples for org.joda.time.format DateTimeFormatter print

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter print.

Prototype

public String print(ReadablePartial partial) 

Source Link

Document

Prints a ReadablePartial to a new String.

Usage

From source file:io.coala.time.Instant.java

License:Apache License

/**
 * @param offset//ww  w  .ja  v a  2  s  . c o  m
 * @param formatter
 * @return
 */
public Object prettify(final DateTime offset, final DateTimeFormatter formatter) {
    return wrapToString(() -> formatter.print(toDate(offset)));
}

From source file:io.druid.indexer.path.GranularityPathSpec.java

License:Apache License

@Override
public Job addInputPaths(HadoopDruidIndexerConfig config, Job job) throws IOException {
    final Set<Interval> intervals = Sets.newTreeSet(Comparators.intervals());
    Optional<Set<Interval>> optionalIntervals = config.getSegmentGranularIntervals();
    if (optionalIntervals.isPresent()) {
        for (Interval segmentInterval : optionalIntervals.get()) {
            for (Interval dataInterval : dataGranularity.getIterable(segmentInterval)) {
                intervals.add(dataInterval);
            }/*  www. jav a 2 s. co  m*/
        }
    }

    Path betaInput = new Path(inputPath);
    FileSystem fs = betaInput.getFileSystem(job.getConfiguration());
    Set<String> paths = Sets.newTreeSet();
    Pattern fileMatcher = Pattern.compile(filePattern);

    DateTimeFormatter customFormatter = null;
    if (pathFormat != null) {
        customFormatter = DateTimeFormat.forPattern(pathFormat);
    }

    for (Interval interval : intervals) {
        DateTime t = interval.getStart();
        String intervalPath = null;
        if (customFormatter != null) {
            intervalPath = customFormatter.print(t);
        } else {
            intervalPath = dataGranularity.toPath(t);
        }

        Path granularPath = new Path(betaInput, intervalPath);
        log.info("Checking path[%s]", granularPath);
        for (FileStatus status : FSSpideringIterator.spiderIterable(fs, granularPath)) {
            final Path filePath = status.getPath();
            if (fileMatcher.matcher(filePath.toString()).matches()) {
                paths.add(filePath.toString());
            }
        }
    }

    for (String path : paths) {
        log.info("Appending path[%s]", path);
        StaticPathSpec.addToMultipleInputs(config, job, path, inputFormat);
    }

    return job;
}

From source file:io.druid.query.expression.TimestampFormatExprMacro.java

License:Apache License

@Override
public Expr apply(final List<Expr> args) {
    if (args.size() < 1 || args.size() > 3) {
        throw new IAE("Function[%s] must have 1 to 3 arguments", name());
    }/*from   w w w .  jav  a 2s .c o  m*/

    final Expr arg = args.get(0);
    final String formatString;
    final DateTimeZone timeZone;

    if (args.size() > 1) {
        Preconditions.checkArgument(args.get(1).isLiteral(), "Function[%s] format arg must be a literal",
                name());
        formatString = (String) args.get(1).getLiteralValue();
    } else {
        formatString = null;
    }

    if (args.size() > 2) {
        timeZone = ExprUtils.toTimeZone(args.get(2));
    } else {
        timeZone = DateTimeZone.UTC;
    }

    final DateTimeFormatter formatter = formatString == null ? ISODateTimeFormat.dateTime()
            : DateTimeFormat.forPattern(formatString).withZone(timeZone);

    class TimestampFormatExpr implements Expr {
        @Nonnull
        @Override
        public ExprEval eval(final ObjectBinding bindings) {
            return ExprEval.of(formatter.print(arg.eval(bindings).asLong()));
        }

        @Override
        public void visit(final Visitor visitor) {
            arg.visit(visitor);
            visitor.visit(this);
        }
    }

    return new TimestampFormatExpr();
}

From source file:io.druid.server.lookup.namespace.URIExtractionNamespaceCacheFactory.java

License:Apache License

@Override
public Callable<String> getCachePopulator(final String id, final URIExtractionNamespace extractionNamespace,
        final String lastVersion, final Map<String, String> cache) {
    final long lastCached = lastVersion == null ? JodaUtils.MIN_INSTANT : Long.parseLong(lastVersion);
    return new Callable<String>() {
        @Override//  w ww  .  j  av  a 2  s .  com
        public String call() {
            final boolean doSearch = extractionNamespace.getUriPrefix() != null;
            final URI originalUri = doSearch ? extractionNamespace.getUriPrefix()
                    : extractionNamespace.getUri();
            final SearchableVersionedDataFinder<URI> pullerRaw = pullers.get(originalUri.getScheme());
            if (pullerRaw == null) {
                throw new IAE("Unknown loader type[%s].  Known types are %s", originalUri.getScheme(),
                        pullers.keySet());
            }
            if (!(pullerRaw instanceof URIDataPuller)) {
                throw new IAE("Cannot load data from location [%s]. Data pulling from [%s] not supported",
                        originalUri, originalUri.getScheme());
            }
            final URIDataPuller puller = (URIDataPuller) pullerRaw;
            final URI uri;
            if (doSearch) {
                final Pattern versionRegex;

                if (extractionNamespace.getFileRegex() != null) {
                    versionRegex = Pattern.compile(extractionNamespace.getFileRegex());
                } else {
                    versionRegex = null;
                }
                uri = pullerRaw.getLatestVersion(extractionNamespace.getUriPrefix(), versionRegex);

                if (uri == null) {
                    throw new RuntimeException(new FileNotFoundException(
                            String.format("Could not find match for pattern `%s` in [%s] for %s", versionRegex,
                                    originalUri, extractionNamespace)));
                }
            } else {
                uri = extractionNamespace.getUri();
            }

            final String uriPath = uri.getPath();

            try {
                return RetryUtils.retry(new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        final String version = puller.getVersion(uri);
                        try {
                            long lastModified = Long.parseLong(version);
                            if (lastModified <= lastCached) {
                                final DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
                                log.debug(
                                        "URI [%s] for namespace [%s] was las modified [%s] but was last cached [%s]. Skipping ",
                                        uri.toString(), id, fmt.print(lastModified), fmt.print(lastCached));
                                return version;
                            }
                        } catch (NumberFormatException ex) {
                            log.debug(ex, "Failed to get last modified timestamp. Assuming no timestamp");
                        }
                        final ByteSource source;
                        if (CompressionUtils.isGz(uriPath)) {
                            // Simple gzip stream
                            log.debug("Loading gz");
                            source = new ByteSource() {
                                @Override
                                public InputStream openStream() throws IOException {
                                    return CompressionUtils.gzipInputStream(puller.getInputStream(uri));
                                }
                            };
                        } else {
                            source = new ByteSource() {
                                @Override
                                public InputStream openStream() throws IOException {
                                    return puller.getInputStream(uri);
                                }
                            };
                        }
                        final long lineCount = new MapPopulator<>(
                                extractionNamespace.getNamespaceParseSpec().getParser()).populate(source,
                                        cache);
                        log.info("Finished loading %d lines for namespace [%s]", lineCount, id);
                        return version;
                    }
                }, puller.shouldRetryPredicate(), DEFAULT_NUM_RETRIES);
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    };
}

From source file:io.druid.server.namespace.URIExtractionNamespaceFunctionFactory.java

License:Apache License

@Override
public Callable<String> getCachePopulator(final URIExtractionNamespace extractionNamespace,
        final String lastVersion, final Map<String, String> cache) {
    final long lastCached = lastVersion == null ? JodaUtils.MIN_INSTANT : Long.parseLong(lastVersion);
    return new Callable<String>() {
        @Override/* w w  w . j a v a2s .  c o  m*/
        public String call() {
            final URI originalUri = extractionNamespace.getUri();
            final SearchableVersionedDataFinder<URI> pullerRaw = pullers.get(originalUri.getScheme());
            if (pullerRaw == null) {
                throw new IAE("Unknown loader type[%s].  Known types are %s", originalUri.getScheme(),
                        pullers.keySet());
            }
            if (!(pullerRaw instanceof URIDataPuller)) {
                throw new IAE("Cannot load data from location [%s]. Data pulling from [%s] not supported",
                        originalUri.toString(), originalUri.getScheme());
            }
            final URIDataPuller puller = (URIDataPuller) pullerRaw;
            final String versionRegex = extractionNamespace.getVersionRegex();
            final URI uri = pullerRaw.getLatestVersion(originalUri,
                    versionRegex == null ? null : Pattern.compile(versionRegex));
            if (uri == null) {
                throw new RuntimeException(new FileNotFoundException(
                        String.format("Could not find match for pattern `%s` in [%s] for %s", versionRegex,
                                originalUri, extractionNamespace)));
            }
            final String uriPath = uri.getPath();

            try {
                return RetryUtils.retry(new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        final String version = puller.getVersion(uri);
                        try {
                            long lastModified = Long.parseLong(version);
                            if (lastModified <= lastCached) {
                                final DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
                                log.debug(
                                        "URI [%s] for namespace [%s] was las modified [%s] but was last cached [%s]. Skipping ",
                                        uri.toString(), extractionNamespace.getNamespace(),
                                        fmt.print(lastModified), fmt.print(lastCached));
                                return version;
                            }
                        } catch (NumberFormatException ex) {
                            log.debug(ex, "Failed to get last modified timestamp. Assuming no timestamp");
                        }
                        final ByteSource source;
                        if (CompressionUtils.isGz(uriPath)) {
                            // Simple gzip stream
                            log.debug("Loading gz");
                            source = new ByteSource() {
                                @Override
                                public InputStream openStream() throws IOException {
                                    return CompressionUtils.gzipInputStream(puller.getInputStream(uri));
                                }
                            };
                        } else {
                            source = new ByteSource() {
                                @Override
                                public InputStream openStream() throws IOException {
                                    return puller.getInputStream(uri);
                                }
                            };
                        }
                        final long lineCount = new MapPopulator<>(
                                extractionNamespace.getNamespaceParseSpec().getParser()).populate(source,
                                        cache);
                        log.info("Finished loading %d lines for namespace [%s]", lineCount,
                                extractionNamespace.getNamespace());
                        return version;
                    }
                }, puller.shouldRetryPredicate(), DEFAULT_NUM_RETRIES);
            } catch (Exception e) {
                throw Throwables.propagate(e);
            }
        }
    };
}

From source file:io.hops.hopsworks.api.zeppelin.socket.NotebookServer.java

License:Apache License

private void moveFolderToTrash(Session conn, HashSet<String> userAndRoles, Notebook notebook,
        Message fromMessage) throws SchedulerException, IOException {
    String folderId = (String) fromMessage.get("id");
    if (folderId == null) {
        return;/*w ww  . j a va  2  s  . c  o  m*/
    }

    Folder folder = notebook.getFolder(folderId);
    if (folder != null && !folder.isTrash()) {
        String trashFolderId = Folder.TRASH_FOLDER_ID + "/" + folderId;
        if (notebook.hasFolder(trashFolderId)) {
            DateTime currentDate = new DateTime();
            DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
            trashFolderId += Folder.TRASH_FOLDER_CONFLICT_INFIX + formatter.print(currentDate);
        }

        fromMessage.put("name", trashFolderId);
        renameFolder(conn, userAndRoles, notebook, fromMessage, "move");
    }
}

From source file:io.hops.hopsworks.api.zeppelin.socket.NotebookServerImpl.java

License:Open Source License

public void moveFolderToTrash(Session conn, HashSet<String> userAndRoles, Notebook notebook,
        Message fromMessage, Users user) throws SchedulerException, IOException {
    String folderId = (String) fromMessage.get("id");
    if (folderId == null) {
        return;/*w w w  . j a va 2  s .c o  m*/
    }

    Folder folder = notebook.getFolder(folderId);
    if (folder != null && !folder.isTrash()) {
        String trashFolderId = Folder.TRASH_FOLDER_ID + "/" + folderId;
        if (notebook.hasFolder(trashFolderId)) {
            DateTime currentDate = new DateTime();
            DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
            trashFolderId += Folder.TRASH_FOLDER_CONFLICT_INFIX + formatter.print(currentDate);
        }

        fromMessage.put("name", trashFolderId);
        renameFolder(conn, userAndRoles, notebook, fromMessage, "move", user);

        logTrashActivity(ActivityFacade.TRASH_NOTEBOOK + "notebook folder " + folderId + "/", user);
    }
}

From source file:io.jawg.osmcontributor.ui.adapters.CommentAdapter.java

License:Open Source License

@Override
public View getView(final int position, View view, final ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final Comment comment = comments.get(position);
    final ViewHolder holder;

    if (view != null) {
        holder = (ViewHolder) view.getTag();
    } else {/*from w  w w  .j  a va2s .com*/
        view = inflater.inflate(R.layout.single_comment_layout, parent, false);
        holder = new ViewHolder(view);
        view.setTag(holder);
    }

    holder.getCommentContentTextView().setText(comment.getText());
    holder.getActionTextView().setText(comment.getAction());

    DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/yy");
    String date = comment.getCreatedDate() == null ? "" : fmt.print(comment.getCreatedDate());

    if (comment.getUpdated()) {
        date = context.getResources().getString(R.string.synchronizing);
    }

    holder.getDateTextView().setText(date);
    return view;
}

From source file:io.jawg.osmcontributor.ui.fragments.MapFragment.java

License:Open Source License

public void showNeedToRefreshData(LocalDateTime lastUpate) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
    new AlertDialog.Builder(getActivity()).setTitle(R.string.load_poi_data_outdated_refresh_title)
            .setMessage(getString(R.string.load_poi_data_outdated_refresh_content, formatter.print(lastUpate)))
            .setPositiveButton(R.string.load_poi_data_outdated_refresh_btn,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            presenter.refreshAreaConfirmed();
                            dialog.dismiss();
                        }// ww w  . j  a  v a  2  s. com
                    })
            .setNegativeButton(R.string.load_poi_data_outdated_refresh_cancel,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    })
            .show();
}

From source file:io.prestosql.operator.scalar.DateTimeFunctions.java

License:Apache License

@ScalarFunction("to_iso8601")
@SqlType("varchar(35)")
// YYYY-MM-DDTHH:MM:SS.mmm+HH:MM is a standard notation, and it requires 29 characters.
// However extended notation with format (Y)+-MM-DDTHH:MM:SS.mmm+HH:MM is also acceptable and as
// the maximum year represented by 64bits timestamp is ~584944387 it may require up to 35 characters.
public static Slice toISO8601FromTimestamp(ConnectorSession session,
        @SqlType(StandardTypes.TIMESTAMP) long timestamp) {
    if (session.isLegacyTimestamp()) {
        DateTimeFormatter formatter = ISODateTimeFormat.dateTime()
                .withChronology(getChronology(session.getTimeZoneKey()));
        return utf8Slice(formatter.print(timestamp));
    } else {//from   ww  w  .j  a  v  a2s. c om
        DateTimeFormatter formatter = ISODateTimeFormat.dateHourMinuteSecondMillis()
                .withChronology(UTC_CHRONOLOGY);
        return utf8Slice(formatter.print(timestamp));
    }
}