Example usage for java.time.format DateTimeFormatter ISO_INSTANT

List of usage examples for java.time.format DateTimeFormatter ISO_INSTANT

Introduction

In this page you can find the example usage for java.time.format DateTimeFormatter ISO_INSTANT.

Prototype

DateTimeFormatter ISO_INSTANT

To view the source code for java.time.format DateTimeFormatter ISO_INSTANT.

Click Source Link

Document

The ISO instant formatter that formats or parses an instant in UTC, such as '2011-12-03T10:15:30Z'.

Usage

From source file:net.dv8tion.jda.core.entities.impl.MessageEmbedImpl.java

public JSONObject toJSONObject() {
    JSONObject obj = new JSONObject();
    if (url != null)
        obj.put("url", url);
    if (title != null)
        obj.put("title", title);
    if (description != null)
        obj.put("description", description);
    if (timestamp != null)
        obj.put("timestamp", timestamp.format(DateTimeFormatter.ISO_INSTANT));
    if (color != null)
        obj.put("color", color.getRGB() & 0xFFFFFF);
    if (thumbnail != null)
        obj.put("thumbnail", new JSONObject().put("url", thumbnail.getUrl()));
    if (siteProvider != null) {
        JSONObject siteProviderObj = new JSONObject();
        if (siteProvider.getName() != null)
            siteProviderObj.put("name", siteProvider.getName());
        if (siteProvider.getUrl() != null)
            siteProviderObj.put("url", siteProvider.getUrl());
        obj.put("provider", siteProviderObj);
    }/*from  w  w  w . j  a v  a2  s.  c o  m*/
    if (author != null) {
        JSONObject authorObj = new JSONObject();
        if (author.getName() != null)
            authorObj.put("name", author.getName());
        if (author.getUrl() != null)
            authorObj.put("url", author.getUrl());
        if (author.getIconUrl() != null)
            authorObj.put("icon_url", author.getIconUrl());
        obj.put("author", authorObj);
    }
    if (videoInfo != null)
        obj.put("video", new JSONObject().put("url", videoInfo.getUrl()));
    if (footer != null) {
        JSONObject footerObj = new JSONObject();
        if (footer.getText() != null)
            footerObj.put("text", footer.getText());
        if (footer.getIconUrl() != null)
            footerObj.put("icon_url", footer.getIconUrl());
        obj.put("footer", footerObj);
    }
    if (image != null)
        obj.put("image", new JSONObject().put("url", image.getUrl()));
    if (!fields.isEmpty()) {
        JSONArray fieldsArray = new JSONArray();
        fields.stream().forEach(field -> fieldsArray.put(new JSONObject().put("name", field.getName())
                .put("value", field.getValue()).put("inline", field.isInline())));
        obj.put("fields", fieldsArray);
    }
    return obj;
}

From source file:com.sludev.mssqlapplylog.MSSQLApplyLog.java

@Override
public Integer call() throws Exception {
    Integer res = 0;/*ww  w .ja  v  a2  s .co m*/

    String backupDirStr = config.getBackupDirStr();
    String fullBackupPathStr = config.getFullBackupPathStr();
    String fullBackupDatePatternStr = config.getFullBackupDatePatternStr();
    String laterThanStr = config.getLaterThanStr();
    String fullBackupPatternStr = config.getFullBackupPatternStr();
    String logBackupPatternStr = config.getLogBackupPatternStr();
    String logBackupDatePatternStr = config.getLogBackupDatePatternStr();

    String sqlHost = config.getSqlHost();
    String sqlDb = config.getSqlDb();
    String sqlUser = config.getSqlUser();
    String sqlPass = config.getSqlPass();
    String sqlURL = config.getSqlUrl();
    String sqlProcessUser = config.getSqlProcessUser();

    boolean useLogFileLastMode = BooleanUtils.isTrue(config.getUseLogFileLastMode());
    boolean doFullRestore = BooleanUtils.isTrue(config.getDoFullRestore());
    boolean monitorLogBackupDir = BooleanUtils.isTrue(config.getMonitorLogBackupDir());

    Path backupsDir = null;
    Instant laterThan = null;

    Path fullBackupPath = null;

    // Validate the Log Backup Directory
    if (StringUtils.isBlank(backupDirStr)) {
        LOGGER.error("Invalid blank/empty backup directory");

        return 1;
    }

    try {
        backupsDir = Paths.get(backupDirStr);
    } catch (Exception ex) {
        LOGGER.error(String.format("Error parsing Backup Directory '%s'", backupDirStr), ex);

        return 1;
    }

    if (Files.notExists(backupsDir)) {
        LOGGER.error(String.format("Invalid non-existant backup directory '%s'", backupsDir));

        return 1;
    }

    if (StringUtils.isBlank(logBackupPatternStr)) {
        LOGGER.warn(String.format(
                "\"Log Backup Pattern\" cannot be empty.  Defaulting to " + "%s regex in backup directory",
                DEFAULT_LOG_FILE_PATTERN_STR));

        logBackupPatternStr = DEFAULT_LOG_FILE_PATTERN_STR;
    }

    if (StringUtils.isNoneBlank(fullBackupPathStr)) {
        fullBackupPath = Paths.get(fullBackupPathStr);
        if (Files.notExists(fullBackupPath) || Files.isRegularFile(fullBackupPath) == false) {
            LOGGER.error(String.format("Invalid Full Backup file '%s'", backupDirStr));

            return 1;
        }
    }

    if (StringUtils.isNoneBlank(fullBackupDatePatternStr) && StringUtils.isBlank(laterThanStr)
            && fullBackupPath != null) {
        // Retrieve the "Later Than" date from the full backup file name
        laterThan = FSHelper.getTimestampFromFilename(fullBackupPatternStr, fullBackupDatePatternStr, 1,
                fullBackupPath);
        if (laterThan == null) {
            LOGGER.error("'Later Than' cannot be null");

            return 1;
        }
    } else {
        // Use the "Later Than" timestamp from the command line or properties
        // file.

        try {
            laterThan = Instant.from(DateTimeFormatter.ISO_INSTANT.parse(laterThanStr));
        } catch (Exception ex) {
            LOGGER.error(String.format("Error parsing 'Later Than' time '%s'", laterThanStr), ex);
        }
    }

    try {
        Class.forName("net.sourceforge.jtds.jdbc.Driver");
    } catch (ClassNotFoundException ex) {
        LOGGER.error("Error loading SQL Server driver [ net.sourceforge.jtds.jdbc.Driver ]", ex);

        return 1;
    }

    if (StringUtils.isBlank(sqlURL)) {
        // Build the SQL URL
        sqlURL = String.format("jdbc:jtds:sqlserver://%s;DatabaseName=master", sqlHost);
    }

    Properties props = new Properties();

    props.setProperty("user", sqlUser);
    props.setProperty("password", sqlPass);

    try (Connection conn = MSSQLHelper.getConn(sqlURL, props)) {
        if (conn == null) {
            LOGGER.error("Connection to MSSQL failed.");

            return 1;
        }

        if (doFullRestore) {
            LOGGER.info(String.format("\nStarting full restore of '%s'...", fullBackupPathStr));

            StopWatch sw = new StopWatch();

            sw.start();

            String strDevice = fullBackupPathStr;

            String query = String.format("RESTORE DATABASE %s FROM DISK='%s' WITH NORECOVERY, REPLACE", sqlDb,
                    strDevice);

            Statement stmt = null;

            try {
                stmt = conn.createStatement();
            } catch (SQLException ex) {
                LOGGER.debug("Error creating statement", ex);

                return 1;
            }

            try {
                boolean sqlRes = stmt.execute(query);
            } catch (SQLException ex) {
                LOGGER.error(String.format("Error executing...\n'%s'", query), ex);

                return 1;
            }

            sw.stop();

            LOGGER.debug(String.format("Query...\n'%s'\nTook %s", query, sw.toString()));
        }
    } catch (SQLException ex) {
        LOGGER.error("SQL Exception restoring the full backup", ex);
    }

    // Filter the log files.

    // Loop multiple times to catch new logs that have been transferred
    // while we process.
    List<Path> files = null;
    do {
        try {
            files = FSHelper.listLogFiles(backupsDir, laterThan, useLogFileLastMode, logBackupPatternStr,
                    logBackupDatePatternStr, files);
        } catch (IOException ex) {
            LOGGER.error("Log Backup file filter/sort failed", ex);

            return 1;
        }

        if (files == null || files.isEmpty()) {
            LOGGER.debug("No Log Backup files found this iteration.");

            continue;
        }

        StringBuilder msg = new StringBuilder();

        for (Path file : files) {
            msg.append(String.format("file : '%s'\n", file));
        }

        LOGGER.debug(msg.toString());

        // Restore all log files
        try (Connection conn = MSSQLHelper.getConn(sqlURL, props)) {
            for (Path p : files) {
                try {
                    MSSQLHelper.restoreLog(p, sqlProcessUser, sqlDb, conn);
                } catch (SQLException ex) {
                    LOGGER.error(String.format("SQL Exception restoring the log backup '%s'", p), ex);
                }
            }
        } catch (SQLException ex) {
            LOGGER.error("SQL Exception restoring the log backup", ex);
        }
    } while (files != null && files.isEmpty() == false);

    if (monitorLogBackupDir) {
        // Watch for new log files
        List<Path> paths = new ArrayList();
        paths.add(backupsDir);

        final Watch watch;
        final String currSQLDb = sqlDb;
        final String currSQLProcUser = sqlProcessUser;
        final String currSQLURL = sqlURL;
        final String currLogBackupPatternStr = logBackupPatternStr;

        try {
            watch = Watch.from(paths);
            watch.processEvents((WatchEvent<Path> event, Path path) -> {
                int watchRes = 0;

                if (event.kind() != StandardWatchEventKinds.ENTRY_CREATE) {
                    return watchRes;
                }

                Pattern fileMatcher = Pattern.compile(currLogBackupPatternStr);

                if (fileMatcher.matcher(path.getFileName().toString()).matches()) {
                    try (Connection conn = MSSQLHelper.getConn(currSQLURL, props)) {
                        MSSQLHelper.restoreLog(path, currSQLProcUser, currSQLDb, conn);
                    } catch (SQLException ex) {
                        // There's really no recovering from a failed log backup

                        LOGGER.error("SQL Exception restoring the log backup", ex);

                        System.exit(1);
                    }
                }

                return watchRes;
            });
        } catch (IOException | FileCheckException ex) {
            LOGGER.error(String.format("Error watching backup directory...\n'%s'", backupsDir), ex);

            return 1;
        } catch (InterruptedException ex) {
            LOGGER.info(String.format("Interrupted watching backup directory...\n'%s'", backupsDir), ex);
        }
    }

    return res;
}

From source file:co.runrightfast.vertx.core.eventbus.ProtobufMessageProducer.java

public static DeliveryOptions addRunRightFastHeaders(final DeliveryOptions options) {
    final MultiMap headers = options.getHeaders();
    if (headers == null) {
        options.addHeader(MESSAGE_ID.header, uuid());
        options.addHeader(MESSAGE_TIMESTAMP.header, DateTimeFormatter.ISO_INSTANT.format(Instant.now()));
        return options;
    }// ww w.j  a  v  a2 s  .c  o m

    if (!headers.contains(MESSAGE_ID.header)) {
        headers.add(MESSAGE_ID.header, uuid());
    }

    if (!headers.contains(MESSAGE_TIMESTAMP.header)) {
        headers.add(MESSAGE_TIMESTAMP.header, DateTimeFormatter.ISO_INSTANT.format(Instant.now()));
    }
    return options;
}

From source file:gov.osti.search.SearchData.java

/**
 * Translate this Bean into a SOLR query parameter set.
 *
 * @return a SOLR query parameter "q" for these attributes; default to "*:*"
 * (everything) if nothing is set/*w  w w.  j  a  va 2 s .co  m*/
 */
public String toQ() {
    StringBuilder q = new StringBuilder();
    DateTimeFormatter SOLR_DATE_FORMAT = DateTimeFormatter.ISO_INSTANT;

    if (!StringUtils.isEmpty(getAllFields())) {
        if (q.length() > 0)
            q.append(" ");
        q.append("_text_:(").append(escape(getAllFields(), true)).append(")");
    }
    if (null != getAccessibility()) {
        StringBuilder codes = new StringBuilder();
        for (String code : getAccessibility()) {
            if (codes.length() > 0)
                codes.append(" OR ");
            codes.append("accessibility:").append(code);
        }
        if (codes.length() > 0) {
            if (q.length() > 0)
                q.append(" ");
            q.append("(").append(codes.toString()).append(")");
        }
    }
    // support ARRAY of SOFTWARE TYPES
    if (null != getSoftwareType()) {
        StringBuilder types = new StringBuilder();
        for (String type : getSoftwareType()) {
            if (types.length() > 0)
                types.append(" OR ");
            types.append("softwareType:").append(type);
        }
        if (types.length() > 0) {
            if (q.length() > 0)
                q.append(" ");
            q.append("(").append(types.toString()).append(")");
        }
    }
    if (null != getProgrammingLanguages()) {
        StringBuilder values = new StringBuilder();
        for (String programmingLanguage : getProgrammingLanguages()) {
            if (values.length() > 0)
                values.append(" OR ");
            values.append("programmingLanguages:\"").append(escapeToken(programmingLanguage)).append("\"");
        }
        if (values.length() > 0) {
            if (q.length() > 0)
                q.append(" ");
            q.append("(").append(values.toString()).append(")");
        }
    }
    if (!StringUtils.isEmpty(getKeywords())) {
        if (q.length() > 0)
            q.append(" ");
        q.append("keywords:(").append(escape(getKeywords(), true)).append(")");
    }
    if (null != getProjectKeywords()) {
        StringBuilder values = new StringBuilder();
        for (String projectKeyword : getProjectKeywords()) {
            if (values.length() > 0)
                values.append(" OR ");
            values.append("projectKeywords:\"").append(escapeToken(projectKeyword)).append("\"");
        }
        if (values.length() > 0) {
            if (q.length() > 0)
                q.append(" ");
            q.append("(").append(values.toString()).append(")");
        }
    }
    if (null != getLicenses()) {
        StringBuilder values = new StringBuilder();
        for (String license : getLicenses()) {
            if (values.length() > 0)
                values.append(" OR ");
            values.append("licenses:\"").append(escapeToken(license)).append("\"");
        }
        if (values.length() > 0) {
            if (q.length() > 0)
                q.append(" ");
            q.append("(").append(values.toString()).append(")");
        }
    }
    if (!StringUtils.isEmpty(getBiblioData())) {
        if (q.length() > 0)
            q.append(" ");
        q.append("_text_:(").append(escape(getBiblioData(), true)).append(")");
    }
    if (!StringUtils.isEmpty(getOrcid())) {
        if (q.length() > 0)
            q.append(" ");
        q.append("_orcids:(").append(escape(getOrcid())).append(")");
    }
    if (!StringUtils.isEmpty(getDevelopersContributors())) {
        if (q.length() > 0)
            q.append(" ");
        q.append("_names:(").append(escape(getDevelopersContributors(), true)).append(")");
    }
    if (!StringUtils.isEmpty(getIdentifiers())) {
        if (q.length() > 0)
            q.append(" ");
        q.append("_id_numbers:(").append(escape(getIdentifiers())).append(")");
    }
    if (null != getResearchOrganization()) {
        StringBuilder values = new StringBuilder();
        for (String org : getResearchOrganization()) {
            if (values.length() > 0)
                values.append(" OR ");
            values.append("researchOrganizations.organizationName:\"").append(escape(org)).append("\"");
        }
        if (values.length() > 0) {
            if (q.length() > 0)
                q.append(" ");
            q.append("(").append(values.toString()).append(")");
        }
    }
    if (null != getSponsoringOrganization()) {
        StringBuilder values = new StringBuilder();
        for (String org : getSponsoringOrganization()) {
            if (values.length() > 0)
                values.append(" OR ");
            values.append("sponsoringOrganizations.organizationName:\"").append(escape(org)).append("\"");
        }
        if (values.length() > 0) {
            if (q.length() > 0)
                q.append(" ");
            q.append("(").append(values.toString()).append(")");
        }
    }
    if (!StringUtils.isEmpty(getSoftwareTitle())) {
        if (q.length() > 0)
            q.append(" ");
        q.append("softwareTitle:(").append(escape(getSoftwareTitle(), true)).append(")");
    }
    if (null != getDateEarliest()) {
        if (q.length() > 0)
            q.append(" ");
        q.append("releaseDate:[").append(SOLR_DATE_FORMAT.format(
                getDateEarliest().toInstant().atOffset(ZoneOffset.UTC).withHour(0).withMinute(0).withSecond(0)))
                .append(" TO *]");
    }
    if (null != getDateLatest()) {
        if (q.length() > 0)
            q.append(" ");
        q.append("releaseDate:[* TO ").append(SOLR_DATE_FORMAT.format(getDateLatest().toInstant()
                .atOffset(ZoneOffset.UTC).withHour(23).withMinute(59).withSecond(59))).append("]");
    }

    return (0 == q.length()) ? "*:*" : q.toString();
}

From source file:org.bedework.synch.cnctrs.orgSyncV2.OrgSyncV2ConnectorInstance.java

private IcalendarType toXcal(final List<OrgSyncV2Event> osEvents, final boolean onlyPublic) {
    final IcalendarType ical = new IcalendarType();
    final VcalendarType vcal = new VcalendarType();

    ical.getVcalendar().add(vcal);/*from  w  w w  .  jav  a2 s.c om*/

    vcal.setProperties(new ArrayOfProperties());
    final List<JAXBElement<? extends BasePropertyType>> vcalProps = vcal.getProperties()
            .getBasePropertyOrTzid();

    final VersionPropType vers = new VersionPropType();
    vers.setText("2.0");
    vcalProps.add(of.createVersion(vers));

    final ProdidPropType prod = new ProdidPropType();
    prod.setText("//Bedework.org//BedeWork V3.11.1//EN");
    vcalProps.add(of.createProdid(prod));

    final ArrayOfComponents aoc = new ArrayOfComponents();
    vcal.setComponents(aoc);

    for (final OrgSyncV2Event osev : osEvents) {
        if (onlyPublic && !osev.getIsPublic()) {
            continue;
        }

        final VeventType ev = new VeventType();

        aoc.getBaseComponent().add(of.createVevent(ev));

        ev.setProperties(new ArrayOfProperties());
        final List<JAXBElement<? extends BasePropertyType>> evProps = ev.getProperties()
                .getBasePropertyOrTzid();

        final UidPropType uid = new UidPropType();
        uid.setText(config.getUidPrefix() + "-" + osev.getId());
        evProps.add(of.createUid(uid));

        final DtstampPropType dtstamp = new DtstampPropType();
        try {
            //Get todays date
            final ZonedDateTime today = ZonedDateTime.now(ZoneOffset.UTC);
            final String todayStr = today.format(DateTimeFormatter.ISO_INSTANT);

            dtstamp.setUtcDateTime(XcalUtil.getXMlUTCCal(todayStr));
            evProps.add(of.createDtstamp(dtstamp));

            final CreatedPropType created = new CreatedPropType();
            created.setUtcDateTime(XcalUtil.getXMlUTCCal(todayStr));
            evProps.add(of.createCreated(created));

            final SummaryPropType sum = new SummaryPropType();
            sum.setText(osev.getName());
            evProps.add(of.createSummary(sum));

            final DescriptionPropType desc = new DescriptionPropType();
            desc.setText(osev.getDescription());
            evProps.add(of.createDescription(desc));

            final LocationPropType l = new LocationPropType();
            l.setText(osev.getLocation());
            evProps.add(of.createLocation(l));

            if (info.getLocationKey() != null) {
                final XBedeworkLocKeyParamType par = of.createXBedeworkLocKeyParamType();

                par.setText(info.getLocationKey());
                l.setParameters(new ArrayOfParameters());
                l.getParameters().getBaseParameter().add(of.createXBedeworkLocKey(par));
            }
        } catch (final Throwable t) {
            error(t);
            continue;
        }

        if (osev.getCategory() != null) {
            final CategoriesPropType cat = new CategoriesPropType();
            cat.getText().add(osev.getCategory().getName());
            evProps.add(of.createCategories(cat));
        }

        /* The first (only) element of occurrences is the start/end of the
           event or master.
                
           If there are more occurrences these become rdates and the event is
           recurring.
         */

        if (Util.isEmpty(osev.getOccurrences())) {
            // warn?
            continue;
        }

        boolean first = true;
        for (final OrgSyncV2Occurrence occ : osev.getOccurrences()) {
            if (first) {
                final DtstartPropType dtstart = (DtstartPropType) makeDt(new DtstartPropType(),
                        occ.getStartsAt());
                evProps.add(of.createDtstart(dtstart));

                final DtendPropType dtend = (DtendPropType) makeDt(new DtendPropType(), occ.getEndsAt());
                evProps.add(of.createDtend(dtend));

                first = false;
                continue;
            }

            // Add an rdate
            // TODO - add duration if different from the master
            final RdatePropType rdate = (RdatePropType) makeDt(new RdatePropType(), occ.getStartsAt());
            evProps.add(of.createRdate(rdate));
        }
    }

    return ical;
}

From source file:dk.dbc.rawrepo.oai.OAIWorker.java

/**
 * http://www.openarchives.org/OAI/openarchivesprotocol.html#Identify
 *
 * @param oaipmh response object//from  ww w. ja v  a2 s. co  m
 */
public void identify(OAIPMH oaipmh) {
    setRequest(oaipmh, VerbType.IDENTIFY);

    Timestamp timestamp = EPOCH;
    try (PreparedStatement stmt = connection.prepareStatement("SELECT MIN(changed) FROM oairecords");
            ResultSet resultSet = stmt.executeQuery()) {
        if (resultSet.next()) {
            timestamp = resultSet.getTimestamp(1);
        }
    } catch (SQLException ex) {
        log.error("Exception: " + ex.getMessage());
        log.debug("Exception:", ex);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, "Internal Error");
    }

    String ts = DateTimeFormatter.ISO_INSTANT.format(timestamp.toInstant());

    IdentifyType identify = OBJECT_FACTORY.createIdentifyType();
    identify.setRepositoryName(config.getRepositoryName());
    identify.setBaseURL(config.getBaseUrl());
    identify.setProtocolVersion("2.0");
    identify.setEarliestDatestamp(ts);
    identify.setDeletedRecord(DeletedRecordType.TRANSIENT);
    identify.setGranularity(GranularityType.YYYY_MM_DD_THH_MM_SS_Z);
    oaipmh.setIdentify(identify);
}

From source file:dk.dbc.rawrepo.oai.OAIIdentifierCollection.java

/**
 * Fetch identifiers from database/*from  w  w  w. j a v  a 2 s. c  o  m*/
 *
 * json argument is object with: null null null null null     {@literal
 * f: fromTimestamp*
 * u: untilTimestamp*
 * m: metadataPrefix
 * o: fromOffset (how many records with fromTimestamp has been seen)*
 * s: set*
 * }
 *
 * @param json  as described
 * @param limit how many records to fetch
 * @return json as described or null if no more records
 */
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
public ObjectNode fetch(ObjectNode json, int limit) {
    log.debug("limit = " + limit);
    StringBuilder sb = new StringBuilder();
    String set = json.path("s").asText(null);
    String from = json.path("f").asText(null);
    String until = json.path("u").asText(null);
    String metadataPrefix = json.path("m").asText("");
    int offset = json.path("o").asInt(0);
    sb.append("SELECT pid, changed, deleted FROM oairecords JOIN oairecordsets USING (pid) WHERE");
    if (set != null) {
        sb.append(" setSpec = ?");
    } else if (allowedSets.isEmpty()) {
        return null;
    } else {
        sb.append(" setSpec IN ('");
        sb.append(allowedSets.stream().sorted().collect(Collectors.joining("', '")));
        sb.append("')");
    }
    sb.append(" AND ? in (SELECT prefix FROM oaiformats)");

    if (from != null) {
        sb.append(" AND");
        if (from.contains(".")) {
            sb.append(
                    " DATE_TRUNC('milliseconds', changed) >= DATE_TRUNC('milliseconds', ?::timestamp AT TIME ZONE 'UTC')");
        } else if (from.contains("T")) {
            sb.append(
                    " DATE_TRUNC('second', changed) >= DATE_TRUNC('second', ?::timestamp AT TIME ZONE 'UTC')");
        } else {
            sb.append(" DATE_TRUNC('day', changed) >= DATE_TRUNC('day', ?::timestamp AT TIME ZONE 'UTC')");
        }
    }
    if (until != null) {
        sb.append(" AND");
        if (until.contains(".")) {
            sb.append(
                    " DATE_TRUNC('milliseconds', changed) <= DATE_TRUNC('milliseconds', ?::timestamp AT TIME ZONE 'UTC')");
        } else if (until.contains("T")) {
            sb.append(
                    " DATE_TRUNC('second', changed) <= DATE_TRUNC('second', ?::timestamp AT TIME ZONE 'UTC')");
        } else {
            sb.append(" DATE_TRUNC('day', changed) <= DATE_TRUNC('day', ?::timestamp AT TIME ZONE 'UTC')");
        }
    }
    sb.append(" GROUP BY pid");
    if (set != null) {
        sb.append(", gone");
    }
    sb.append(" ORDER BY changed, pid OFFSET ? LIMIT ?");
    String query = sb.toString();
    log.debug("query = " + query);

    sb = new StringBuilder();
    sb.append("SELECT setSpec FROM oairecordsets WHERE pid = ? AND setSpec IN ('")
            .append(allowedSets.stream().sorted().collect(Collectors.joining("', '")))
            .append("') AND NOT gone ORDER BY setSpec");
    String setQuery = sb.toString();

    Timestamp last = null;
    int row = 0;
    try (PreparedStatement stmt = connection.prepareStatement(query);
            PreparedStatement sets = connection.prepareStatement(setQuery)) {
        int i = 1;
        if (set != null) {
            stmt.setString(i++, set);
        }
        stmt.setString(i++, metadataPrefix);
        if (from != null) {
            stmt.setString(i++, from);
        }
        if (until != null) {
            stmt.setString(i++, until);
        }
        stmt.setInt(i++, offset);
        stmt.setInt(i++, limit + 1);
        try (ResultSet resultSet = stmt.executeQuery()) {
            while (resultSet.next()) {
                row++;
                String pid = resultSet.getString(1);
                Timestamp changed = resultSet.getTimestamp(2);
                Boolean deleted = resultSet.getBoolean(3);
                if (row <= limit) {
                    OAIIdentifier oaiRecord = new OAIIdentifier(pid, changed, deleted);
                    sets.setString(1, pid);
                    try (ResultSet setsResult = sets.executeQuery()) {
                        while (setsResult.next()) {
                            oaiRecord.add(setsResult.getString(1));
                        }
                    }
                    if (oaiRecord.isEmpty() && !oaiRecord.isDeleted()) {
                        oaiRecord = new OAIIdentifier(pid, changed, true);
                    }
                    add(oaiRecord);
                    if (changed.equals(last)) {
                        offset++;
                    } else {
                        last = changed;
                        offset = 1;
                    }
                } else {
                    ObjectNode obj = OBJECT_MAPPER.createObjectNode();
                    String continueFrom = changed.toInstant().atZone(ZoneId.systemDefault())
                            .format(DateTimeFormatter.ISO_INSTANT);
                    obj.put("f", continueFrom);
                    if (changed.equals(last)) {
                        obj.put("o", offset);
                    }
                    if (until != null) {
                        obj.put("u", until);
                    }
                    if (set != null) {
                        obj.put("s", set);
                    }
                    if (metadataPrefix != null) {
                        obj.put("m", metadataPrefix);
                    }
                    log.debug("continueFrom = " + obj);
                    return obj;
                }
            }
        }
    } catch (SQLException ex) {
        log.error("Exception: " + ex.getMessage());
        log.debug("Exception:", ex);
        throw new ServerErrorException(Response.Status.INTERNAL_SERVER_ERROR, "Internal Error");
    }
    return null;
}

From source file:com.att.aro.datacollector.ioscollector.utilities.AppSigningHelper.java

private boolean isProvProfileExpired() throws IOSAppException {
    DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT;
    Instant dateTime = Instant.from(formatter.parse(provProfile.getExpiration()));
    return dateTime.compareTo(Instant.now()) < 0;
}

From source file:dk.dbc.rawrepo.oai.OAIIdentifierCollectionIT.java

private void loadRecordsFrom(String... jsons) throws SQLException, IOException {
    Connection connection = pg.getConnection();
    connection.prepareStatement("SET TIMEZONE TO 'UTC'").execute();
    try (PreparedStatement rec = connection
            .prepareStatement("INSERT INTO oairecords (pid, changed, deleted) VALUES(?, ?::timestamp, ?)");
            PreparedStatement recSet = connection
                    .prepareStatement("INSERT INTO oairecordsets (pid, setSpec) VALUES(?, ?)")) {

        for (String json : jsons) {
            InputStream is = getClass().getClassLoader().getResourceAsStream(json);
            if (is == null) {
                throw new RuntimeException("Cannot find: " + json);
            }//from   w w  w .  j  a  v a 2s.c om
            ObjectMapper objectMapper = new ObjectMapper();
            List<ObjectNode> array = objectMapper.readValue(is, List.class);
            for (Object object : array) {
                Map<String, Object> obj = (Map<String, Object>) object;
                rec.setString(1, (String) obj.get("pid"));
                rec.setString(2, (String) obj.getOrDefault("changed",
                        DateTimeFormatter.ISO_INSTANT.format(Instant.now().atZone(ZoneId.systemDefault()))));
                rec.setBoolean(3, (boolean) obj.getOrDefault("deleted", false));
                rec.executeUpdate();
                recSet.setString(1, (String) obj.get("pid"));
                List<Object> sets = (List<Object>) obj.get("sets");

                for (Object set : sets) {
                    recSet.setString(2, (String) set);
                    recSet.executeUpdate();
                }
            }
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}

From source file:org.sakaiproject.rubrics.logic.impl.RubricsServiceImpl.java

/**
 * call the rubrics-service to save the binding between assignment and rubric
 * @param params A hashmap with all the rbcs params comming from the component. The tool should generate it.
 * @param tool the tool id, something like "sakai.assignment"
 * @param id the id of the element to//from   ww  w  .  jav a  2 s .  c o m
 */

public void saveRubricAssociation(String tool, String id, HashMap<String, String> params) {

    String associationHref = null;
    String created = "";
    String owner = "";
    Map<String, Boolean> oldParams = new HashMap<>();

    try {
        Optional<Resource<ToolItemRubricAssociation>> associationResource = getRubricAssociationResource(tool,
                id);
        if (associationResource.isPresent()) {
            associationHref = associationResource.get().getLink(Link.REL_SELF).getHref();
            ToolItemRubricAssociation association = associationResource.get().getContent();
            created = association.getMetadata().getCreated().toString();
            owner = association.getMetadata().getOwner();
            oldParams = association.getParameters();
        }

        //we will create a new one or update if the parameter rbcs-associate is true
        String nowTime = DateTimeFormatter.ISO_INSTANT.format(Instant.now());
        if (params.get("rbcs-associate").equals("1")) {

            if (associationHref == null) { // create a new one.
                String input = "{\"toolId\" : \"" + tool + "\",\"itemId\" : \"" + id + "\",\"rubricId\" : "
                        + params.get("rbcs-rubricslist") + ",\"metadata\" : {\"created\" : \"" + nowTime
                        + "\",\"modified\" : \"" + nowTime + "\",\"owner\" : \""
                        + userDirectoryService.getCurrentUser().getId() + "\"},\"parameters\" : {"
                        + setConfigurationParameters(params, oldParams) + "}}";
                log.debug("New association " + input);
                String query = serverConfigurationService.getServerUrl() + RBCS_SERVICE_URL_PREFIX
                        + "rubric-associations/";
                String resultPost = postRubricResource(query, input, tool);
                log.debug("resultPost: " + resultPost);
            } else {
                String input = "{\"toolId\" : \"" + tool + "\",\"itemId\" : \"" + id + "\",\"rubricId\" : "
                        + params.get("rbcs-rubricslist") + ",\"metadata\" : {\"created\" : \"" + created
                        + "\",\"modified\" : \"" + nowTime + "\",\"owner\" : \"" + owner
                        + "\"},\"parameters\" : {" + setConfigurationParameters(params, oldParams) + "}}";
                log.debug("Existing association update" + input);
                String resultPut = putRubricResource(associationHref, input, tool);
                //update the actual one.
                log.debug("resultPUT: " + resultPut);
            }
        } else {
            // We delete the association
            if (associationHref != null) {
                deleteRubricAssociation(associationHref, tool);
            }
        }

    } catch (Exception e) {
        //TODO If we have an error here, maybe we should return say something to the user
    }
}