Example usage for java.time Instant getEpochSecond

List of usage examples for java.time Instant getEpochSecond

Introduction

In this page you can find the example usage for java.time Instant getEpochSecond.

Prototype

public long getEpochSecond() 

Source Link

Document

Gets the number of seconds from the Java epoch of 1970-01-01T00:00:00Z.

Usage

From source file:com.muk.services.util.GoogleOAuthService.java

private String createClaim(String scope, String privateKeyAlias, String account) {
    final Instant issued = Instant.now();
    final Instant expirePlusHour = issued.plus(50, ChronoUnit.MINUTES);

    final StringBuilder sb = new StringBuilder();

    sb.append("{\"iss\":\"").append(account).append("\",\"scope\":\"").append(scope).append("\",\"aud\":\"")
            .append(JWT_AUD).append("\",\"exp\":").append(expirePlusHour.getEpochSecond()).append(",\"iat\":")
            .append(issued.getEpochSecond()).append(",\"sub\":\"").append(JWT_SUB).append("\"}");

    /*// w ww. j a  v  a 2 s . c  o m
     * sb.append("{\"iss\":\"").append(account).append("\",\"scope\":\"").append(scope).append("\",\"aud\":\"")
     * .append(JWT_AUD).append("\",\"exp\":").append(expirePlusHour.getEpochSecond()).append(",\"iat\":")
     * .append(issued.getEpochSecond()).append("}");
     */

    String jwt = JWT_HEADER + "." + cryptoService.encodeUrlSafe(sb.toString().getBytes(StandardCharsets.UTF_8));

    try {
        jwt = jwt + "."
                + cryptoService.signature("SHA256withRSA", jwt, keystoreService.getPrivateKey(privateKeyAlias));
    } catch (final IOException ioEx) {
        LOG.error("Failed to access keystore.", ioEx);
    } catch (final GeneralSecurityException secEx) {
        LOG.error("Failed to sign jwt.", secEx);
    }

    return jwt;
}

From source file:com.searchcode.app.util.Helpers.java

public String timeAgo(Instant instant) {
    if (instant == null) {
        return "not yet";
    }//from www.  j  ava2s  . co 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:hspc.submissionsprogram.AppDisplay.java

private void updateCList(boolean forced) {
    Instant now = Instant.now();
    boolean query = false;
    if (!forced)/*w w  w  . j  av a  2  s . c o m*/
        query = true;
    if (forced) {
        if ((now.getEpochSecond() - old.getEpochSecond()) > 10) {
            query = true;
            old = now;
        }
    }
    if (query) {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            Class.forName(JDBC_DRIVER);

            conn = DriverManager.getConnection(Main.Configuration.get("jdbc_mysql_address"),
                    Main.Configuration.get("mysql_user"), Main.Configuration.get("mysql_pass"));

            String sql = "SELECT * FROM clarifications WHERE response IS NOT NULL";
            stmt = conn.prepareStatement(sql);

            ResultSet rs = stmt.executeQuery();

            ArrayList<String> clarifications = new ArrayList<>();
            clarificationDatas.clear();
            StringBuilder builder = new StringBuilder();
            while (rs.next()) {
                builder.setLength(0);
                builder.append(rs.getInt("id")).append(".  ").append(rs.getString("problem")).append(" - ")
                        .append(rs.getString("text"));
                clarifications.add(builder.toString());
                clarificationDatas.add(new ClarificationData(rs.getInt("id"), rs.getString("problem"),
                        rs.getString("text"), rs.getString("response")));

                int rsId = Integer.parseInt(rs.getString("id"));
                if (rsId > lastId) {
                    lastId = rsId;
                    displayClarification(rs);
                }
            }
            int selected = cList.getSelectedIndex();
            String[] listOfItems = new String[clarifications.size()];
            for (int i = 0; i < clarifications.size(); i++) {
                listOfItems[i] = clarifications.get(i);
            }
            cList.setListData(listOfItems);
            cList.setSelectedIndex(selected);

            stmt.close();
            conn.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (Exception ex2) {
                ex2.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (Exception ex2) {
                ex2.printStackTrace();
            }
        }
    }
}

From source file:com.joyent.manta.client.MantaClient.java

/**
 * <p>Generates a URL that allows for the download of the resource specified
 * in the path without any additional authentication.</p>
 *
 * <p>This could be useful for when you want to generate links that expire
 * after N seconds to give to external users for temporary download
 * access.</p>/*from  www .  j av a 2 s  .c  o m*/
 *
 * @param path The fully qualified path of the object. i.e. /user/stor/foo/bar/baz
 * @param method the String GET or the string HEAD. This is the HTTP verb
 *               that will be used when requesting this resource
 * @param expires time when resource expires and become unavailable
 * @return a signed URL that allows for downloading a resource
 * @throws IOException thrown if there is a problem generating the URL
 */
public URI getAsSignedURI(final String path, final String method, final Instant expires) throws IOException {
    Validate.notNull(expires, "Expires setting must not be null");

    return getAsSignedURI(path, method, expires.getEpochSecond());
}

From source file:org.cloudfoundry.identity.uaa.util.TokenValidation.java

public TokenValidation checkExpiry(Instant asOf) {
    if (!decoded || !claims.containsKey(EXP)) {
        addError("Token does not bear an EXP claim.");
        return this;
    }/*  w w  w  .  j a v a 2s .co m*/

    Object expClaim = claims.get(EXP);
    long expiry;
    try {
        expiry = (int) expClaim;
        if (asOf.getEpochSecond() > expiry) {
            addError("Token expired at " + expiry);
        }
    } catch (ClassCastException ex) {
        addError("Token bears an invalid or unparseable EXP claim.", ex);
    }
    return this;
}

From source file:org.eclipse.packagedrone.utils.rpm.build.RpmBuilder.java

private <T> void addFile(final String targetName, final T sourcePath, final Consumer<FileEntry> customizer,
        final int mode, final Instant fileModificationInstant, final RecorderFunction<T> func)
        throws IOException {
    final PathName pathName = PathName.parse(targetName);

    final long mtime = fileModificationInstant.getEpochSecond();
    final int inode = this.currentInode++;

    final short smode = (short) (mode | CpioConstants.C_ISREG);

    final Result result = func.record(this.recorder, "./" + pathName.toString(), sourcePath,
            cpioCustomizer(mtime, inode, smode));

    Consumer<FileEntry> c = this::initEntry;
    c = c.andThen(entry -> {/*from   w  ww.j  a v  a2  s.  c  om*/
        entry.setModificationTime((int) mtime);
        entry.setInode(inode);
        entry.setMode(smode);
    });

    if (customizer != null) {
        c = c.andThen(customizer);
    }

    addResult(pathName, result, c);
}

From source file:org.eclipse.packagedrone.utils.rpm.build.RpmBuilder.java

private void addDirectory(final String targetName, final int mode, final Instant modInstant,
        final Consumer<FileEntry> customizer) throws IOException {
    final PathName pathName = PathName.parse(targetName);

    final long mtime = modInstant.getEpochSecond();
    final int inode = this.currentInode++;

    final short smode = (short) (mode | CpioConstants.C_ISDIR);

    final Result result = this.recorder.addDirectory("./" + pathName.toString(),
            cpioCustomizer(mtime, inode, smode));

    Consumer<FileEntry> c = this::initEntry;
    c = c.andThen(entry -> {/*w ww.j a  v  a2 s . com*/
        entry.setModificationTime((int) mtime);
        entry.setInode(inode);
        entry.setMode(smode);
        entry.setSize(0);
        entry.setTargetSize(4096);
    });

    if (customizer != null) {
        c = c.andThen(customizer);
    }

    addResult(pathName, result, c);
}

From source file:org.eclipse.packagedrone.utils.rpm.build.RpmBuilder.java

private void addSymbolicLink(final String targetName, final String linkTo, final int mode,
        final Instant modInstant, final Consumer<FileEntry> customizer) throws IOException {
    final PathName pathName = PathName.parse(targetName);

    final long mtime = modInstant.getEpochSecond();
    final int inode = this.currentInode++;

    final short smode = (short) (mode | CpioConstants.C_ISLNK);

    final Result result = this.recorder.addSymbolicLink("./" + pathName.toString(), linkTo,
            cpioCustomizer(mtime, inode, smode));

    Consumer<FileEntry> c = this::initEntry;
    c = c.andThen(entry -> {/*from www  .  j av a 2s .  co m*/
        entry.setModificationTime((int) mtime);
        entry.setInode(inode);
        entry.setMode(smode);
        entry.setSize(result.getSize());
        entry.setTargetSize(result.getSize());
        entry.setLinkTo(linkTo);
    });

    if (customizer != null) {
        c = c.andThen(customizer);
    }

    addResult(pathName, result, c);
}

From source file:org.hyperledger.fabric.sdk.helper.SDKUtil.java

/**
 * Create a new {@link Timestamp} instance based on the current time
 * @return timestamp/* www.j  a va2  s  . c  o m*/
 */
public static Timestamp generateTimestamp() {
    Instant time = Instant.now();
    Timestamp timestamp = Timestamp.newBuilder().setSeconds(time.getEpochSecond()).setNanos(time.getNano())
            .build();
    return timestamp;
}

From source file:org.hyperledger.fabric.sdk.helper.Utils.java

/**
 * Create a new {@link Timestamp} instance based on the current time
 *
 * @return timestamp// ww  w .j  a v  a 2  s.  c  o m
 */
public static Timestamp generateTimestamp() {
    Instant time = Instant.now();
    return Timestamp.newBuilder().setSeconds(time.getEpochSecond()).setNanos(time.getNano()).build();
}