Example usage for java.time ZoneOffset UTC

List of usage examples for java.time ZoneOffset UTC

Introduction

In this page you can find the example usage for java.time ZoneOffset UTC.

Prototype

ZoneOffset UTC

To view the source code for java.time ZoneOffset UTC.

Click Source Link

Document

The time-zone offset for UTC, with an ID of 'Z'.

Usage

From source file:com.epam.catgenome.controller.util.MultipartFileSender.java

public void serveResource() throws IOException {
    if (response == null || request == null) {
        return;/* www.  j av a  2s .  com*/
    }

    if (!Files.exists(filepath)) {
        logger.error("File doesn't exist at URI : {}", filepath.toAbsolutePath().toString());
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    Long length = Files.size(filepath);
    String fileName = filepath.getFileName().toString();
    FileTime lastModifiedObj = Files.getLastModifiedTime(filepath);

    if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    long lastModified = LocalDateTime
            .ofInstant(lastModifiedObj.toInstant(), ZoneId.of(ZoneOffset.systemDefault().getId()))
            .toEpochSecond(ZoneOffset.UTC);
    //String contentType = MimeTypeUtils.probeContentType(filepath);
    String contentType = null;

    // Validate request headers for caching ---------------------------------------------------
    if (!validateHeadersCaching(fileName, lastModified)) {
        return;
    }

    // Validate request headers for resume ----------------------------------------------------
    if (!validateHeadersResume(fileName, lastModified)) {
        return;
    }

    // Validate and process range -------------------------------------------------------------
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = processRange(length, fileName, full);
    if (ranges == null) {
        return;
    }

    // Prepare and initialize response --------------------------------------------------------

    // Get content type by file name and set content disposition.
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    } else if (!contentType.startsWith("image")) {
        // Else, expect for images, determine content disposition. If content type is supported by
        // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
        String accept = request.getHeader("Accept");
        disposition = accept != null && HttpUtils.accepts(accept, contentType) ? "inline" : "attachment";
    }
    logger.debug("Content-Type : {}", contentType);
    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Type", contentType);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    logger.debug("Content-Disposition : {}", disposition);
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", fileName);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client ------------------------------------------------

    // Prepare streams.
    try (InputStream input = new BufferedInputStream(Files.newInputStream(filepath));
            OutputStream output = response.getOutputStream()) {

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            logger.info("Return full file");
            response.setContentType(contentType);
            response.setHeader(CONTENT_RANGE_HEADER, "bytes " + full.start + "-" + full.end + "/" + full.total);
            response.setHeader("Content-Length", String.valueOf(full.length));
            Range.copy(input, output, length, full.start, full.length);

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            logger.info("Return 1 part of file : from ({}) to ({})", r.start, r.end);
            response.setContentType(contentType);
            response.setHeader(CONTENT_RANGE_HEADER, "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Copy single part range.
            Range.copy(input, output, length, r.start, r.length);

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            // Cast back to ServletOutputStream to get the easy println methods.
            ServletOutputStream sos = (ServletOutputStream) output;

            // Copy multi part range.
            for (Range r : ranges) {
                logger.info("Return multi part of file : from ({}) to ({})", r.start, r.end);
                // Add multipart boundary and header fields for every range.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY);
                sos.println("Content-Type: " + contentType);
                sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                // Copy single part range of multi part range.
                Range.copy(input, output, length, r.start, r.length);
            }

            // End with multipart boundary.
            sos.println();
            sos.println("--" + MULTIPART_BOUNDARY + "--");
        }
    }

}

From source file:com.streamsets.pipeline.stage.processor.parser.TestDataParserProcessor.java

@Test
public void testSyslogParsing() throws Exception {
    int priority = 17;
    int facility = priority / 8;
    int severity = priority % 8;
    LocalDateTime date = LocalDateTime.now().withNano(0);
    String host = "1.2.3.4";
    String rest = "Nothing interesting happened.";

    String inputFieldPath = "input";
    String outputFieldPath = "/output";

    String syslogMsg = String.format("<%d>%s %s %s", priority,
            DateTimeFormatter.ofPattern("MMM dd HH:mm:ss").format(date), host, rest);

    DataParserConfig configs = new DataParserConfig();
    configs.dataFormat = DataFormat.SYSLOG;
    final DataParserFormatConfig dataParserFormatConfig = new DataParserFormatConfig();
    configs.dataFormatConfig = dataParserFormatConfig;
    configs.fieldPathToParse = "/" + inputFieldPath;
    configs.parsedFieldPath = outputFieldPath;

    DataParserProcessor processor = new DataParserProcessor(configs);

    final String outputLane = "out";

    ProcessorRunner runner = new ProcessorRunner.Builder(DataParserDProcessor.class, processor)
            .addOutputLane(outputLane).setOnRecordError(OnRecordError.TO_ERROR).build();
    Map<String, Field> map = new HashMap<>();
    map.put(inputFieldPath, Field.create(syslogMsg));
    Record record = RecordCreator.create();
    record.set(Field.create(map));
    List<Record> input = new ArrayList<>();
    input.add(record);//from   www .ja va  2  s.  c  o m
    try {
        runner.runInit();
        StageRunner.Output output = runner.runProcess(input);
        assertTrue(output.getRecords().containsKey(outputLane));
        final List<Record> records = output.getRecords().get(outputLane);
        assertEquals(1, records.size());
        assertTrue(records.get(0).has(outputFieldPath));
        assertEquals(Field.Type.MAP, records.get(0).get(outputFieldPath).getType());
        Map<String, Field> syslogFields = records.get(0).get(outputFieldPath).getValueAsMap();
        assertThat(syslogFields, hasKey(SyslogMessage.FIELD_SYSLOG_PRIORITY));
        assertThat(syslogFields.get(SyslogMessage.FIELD_SYSLOG_PRIORITY), fieldWithValue(priority));
        assertThat(syslogFields.get(SyslogMessage.FIELD_SYSLOG_FACILITY), fieldWithValue(facility));
        assertThat(syslogFields.get(SyslogMessage.FIELD_SYSLOG_SEVERITY), fieldWithValue(severity));
        assertThat(syslogFields.get(SyslogMessage.FIELD_HOST), fieldWithValue(host));
        assertThat(syslogFields.get(SyslogMessage.FIELD_REMAINING), fieldWithValue(rest));
        assertThat(syslogFields.get(SyslogMessage.FIELD_RAW), fieldWithValue(syslogMsg));
        assertThat(syslogFields.get(SyslogMessage.FIELD_TIMESTAMP),
                fieldWithValue(date.toInstant(ZoneOffset.UTC).toEpochMilli()));

    } finally {
        runner.runDestroy();
    }
}

From source file:com.nike.cerberus.service.AuthenticationServiceTest.java

@Test
public void test_that_getKeyId_only_validates_kms_policy_one_time_within_interval() {

    String principalArn = "principal arn";
    String region = "region";
    String iamRoleId = "iam role id";
    String kmsKeyId = "kms id";
    String cmkId = "key id";

    // ensure that validate interval is passed
    OffsetDateTime dateTime = OffsetDateTime.of(2016, 1, 1, 1, 1, 1, 1, ZoneOffset.UTC);
    OffsetDateTime now = OffsetDateTime.now();

    IamPrincipalCredentials iamPrincipalCredentials = new IamPrincipalCredentials();
    iamPrincipalCredentials.setIamPrincipalArn(principalArn);
    iamPrincipalCredentials.setRegion(region);

    AwsIamRoleRecord awsIamRoleRecord = new AwsIamRoleRecord().setAwsIamRoleArn(principalArn);
    awsIamRoleRecord.setAwsIamRoleArn(principalArn);
    awsIamRoleRecord.setId(iamRoleId);//from   ww w .j  av a 2s .  c om
    when(awsIamRoleDao.getIamRole(principalArn)).thenReturn(Optional.of(awsIamRoleRecord));

    AwsIamRoleKmsKeyRecord awsIamRoleKmsKeyRecord = new AwsIamRoleKmsKeyRecord();
    awsIamRoleKmsKeyRecord.setId(kmsKeyId);
    awsIamRoleKmsKeyRecord.setAwsKmsKeyId(cmkId);
    awsIamRoleKmsKeyRecord.setLastValidatedTs(dateTime);

    when(awsIamRoleDao.getKmsKey(iamRoleId, region)).thenReturn(Optional.of(awsIamRoleKmsKeyRecord));

    when(dateTimeSupplier.get()).thenReturn(now);

    String result = authenticationService.getKeyId(iamPrincipalCredentials);

    // verify validate is called once interval has passed
    assertEquals(cmkId, result);
    verify(kmsService, times(1)).validatePolicy(awsIamRoleKmsKeyRecord, principalArn);
}

From source file:com.example.geomesa.cassandra.CassandraQuickStart.java

static FeatureCollection createNewFeatures(SimpleFeatureType simpleFeatureType, int numNewFeatures) {
    DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();

    String id;//from   w  w w .j a va 2  s .c om
    Object[] NO_VALUES = {};
    String[] PEOPLE_NAMES = { "Addams", "Bierce", "Clemens" };
    Long SECONDS_PER_YEAR = 365L * 24L * 60L * 60L;
    Random random = new Random(5771);
    ZonedDateTime MIN_DATE = ZonedDateTime.of(2014, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
    Double MIN_X = -78.0;
    Double MIN_Y = -39.0;
    Double DX = 2.0;
    Double DY = 2.0;

    for (int i = 0; i < numNewFeatures; i++) {
        // create the new (unique) identifier and empty feature shell
        id = "Observation." + Integer.toString(i);
        SimpleFeature simpleFeature = SimpleFeatureBuilder.build(simpleFeatureType, NO_VALUES, id);

        // be sure to tell GeoTools explicitly that you want to use the ID you provided
        simpleFeature.getUserData().put(Hints.USE_PROVIDED_FID, java.lang.Boolean.TRUE);

        // populate the new feature's attributes

        // string value
        simpleFeature.setAttribute("Who", PEOPLE_NAMES[i % PEOPLE_NAMES.length]);

        // long value
        simpleFeature.setAttribute("What", i);

        // location:  construct a random point within a 2-degree-per-side square
        double x = MIN_X + random.nextDouble() * DX;
        double y = MIN_Y + random.nextDouble() * DY;
        Geometry geometry = WKTUtils.read("POINT(" + x + " " + y + ")");

        // date-time:  construct a random instant within a year
        simpleFeature.setAttribute("Where", geometry);
        ZonedDateTime dateTime = MIN_DATE.plusSeconds((int) Math.round(random.nextDouble() * SECONDS_PER_YEAR));
        simpleFeature.setAttribute("When", Date.from(dateTime.toInstant()));

        // another string value
        // "Why"; left empty, showing that not all attributes need values

        // accumulate this new feature in the collection
        featureCollection.add(simpleFeature);
    }

    return featureCollection;
}

From source file:com.ethlo.geodata.util.ResourceUtil.java

private static LocalDateTime formatDate(long timestamp) {
    return LocalDateTime.ofEpochSecond(timestamp / 1_000, 0, ZoneOffset.UTC);
}

From source file:net.bis5.slack.command.gcal.SlashCommandApi.java

private EventDateTime toDateTime(LocalDate date, LocalTime time) {
    if (time != null) {
        DateTime dateTime = new DateTime(
                Date.from(LocalDateTime.of(date, time).toInstant(ZoneOffset.ofHours(+9))));
        return new EventDateTime().setDateTime(dateTime);
    } else {/*from   ww w . j  a  v  a 2 s .  c  om*/
        DateTime dateTime = new DateTime(true,
                Date.from(date.atStartOfDay().toInstant(ZoneOffset.UTC)).getTime(), 9);
        return new EventDateTime().setDate(dateTime);
    }
}

From source file:dhbw.clippinggorilla.external.twitter.TwitterUtils.java

private static Article fillArticle(Status status) {
    Article article = new Article();
    article.setTitle(status.getUser().getName());
    article.setDescription(status.getText());
    article.setBody(status.getText());/*from w  w  w.java 2s .  c  o m*/
    article.setSource(SourceUtils.TWITTER);
    for (MediaEntity mediaEntity : status.getMediaEntities()) {
        if (!mediaEntity.getType().equals("video")) {
            article.setUrlToImage(mediaEntity.getMediaURL());
            break;
        }
    }
    if (article.getUrlToImage().isEmpty()) {
        article.setUrlToImage(status.getUser().getBiggerProfileImageURL());
    }
    article.setUrl("https://twitter.com/" + status.getUser().getScreenName() + "/status/" + status.getId());
    article.setId(status.getId() + "");
    article.setAuthor("@" + status.getUser().getScreenName());
    Date date = status.getCreatedAt();
    Instant instant = Instant.ofEpochMilli(date.getTime());
    LocalDateTime createdAt = LocalDateTime.ofInstant(instant, ZoneOffset.UTC);
    article.setPublishedAt(createdAt.toString());
    return article;
}

From source file:com.algodefu.yeti.data.Pass.java

private void calculateEquityChartImg() throws IOException {
    int i = 0;/*from  w  w  w  .  j  ava2  s  .c o m*/
    double sum = 0;
    TimeSeries equity = new TimeSeries("Equity");

    // save values in temp array first, then use System.arraycopy to copy non empty values to this.equityArray
    double[][] tempEquityArr = new double[this.getTrades().length][4];

    for (Trade trade : this.getTrades()) {
        if (trade.getCloseDateTime() != null) {
            sum += trade.getProfit();
            equity.add(new Millisecond(Date.from(trade.getCloseDateTime().toInstant(ZoneOffset.UTC))), sum);
            tempEquityArr[i][0] = (double) trade.getCloseDateTime().toInstant(ZoneOffset.UTC).toEpochMilli();
            tempEquityArr[i][1] = sum;
            tempEquityArr[i][2] = trade.getTradeID();
            tempEquityArr[i][3] = trade.getProfit();
            i++;
        }
    }
    this.equityArray = new double[i][4];
    System.arraycopy(tempEquityArr, 0, this.equityArray, 0, i);

    TimeSeriesCollection dataset = new TimeSeriesCollection(equity);
    JFreeChart chart = ChartFactory.createTimeSeriesChart("", "", "", dataset, false, false, false);
    chart.getXYPlot().getDomainAxis().setTickLabelsVisible(false);
    chart.setBorderVisible(true);
    chart.getXYPlot().setRangeAxisLocation(AxisLocation.TOP_OR_RIGHT);
    chart.getXYPlot().getRenderer().setSeriesPaint(0, Color.blue);
    chart.getXYPlot().setBackgroundPaint(Color.white);
    chart.getXYPlot().setRangeGridlinePaint(Color.gray);
    chart.getXYPlot().setDomainGridlinePaint(Color.gray);
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        ChartUtilities.writeChartAsPNG(baos, chart, 320, 180);
        baos.flush();
        this.equityChartByteArray = baos.toByteArray();
    } catch (IOException e) {
        throw e;
    }

}

From source file:net.jmhertlein.mcanalytics.api.auth.SSLUtil.java

/**
 * Given a certificate signing request, produce a signed certificate.
 *
 * @param caKey//from w  w w.j a v a  2s.  c o m
 * @param caCert
 * @param r
 * @param makeAuthority
 * @return
 */
public static X509Certificate fulfillCertRequest(PrivateKey caKey, X509Certificate caCert,
        PKCS10CertificationRequest r, boolean makeAuthority) {
    X509v3CertificateBuilder b = new JcaX509v3CertificateBuilder(new X500Name(caCert.getSubjectDN().getName()), // the order of O,OU,CN returned is very important
            BigInteger.probablePrime(128, new SecureRandom()), Date.from(Instant.now().minusSeconds(1)),
            Date.from(LocalDateTime.now().plusYears(3).toInstant(ZoneOffset.UTC)), r.getSubject(),
            getPublicKeyFromInfo(r.getSubjectPublicKeyInfo()));

    try {
        b.addExtension(Extension.basicConstraints, true, new BasicConstraints(makeAuthority));
    } catch (CertIOException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider("BC").build(caKey);
        X509CertificateHolder build = b.build(signer);
        return new JcaX509CertificateConverter().setProvider("BC").getCertificate(build);
    } catch (OperatorCreationException | CertificateException ex) {
        Logger.getLogger(SSLUtil.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:org.silverpeas.core.date.Period.java

/**
 * Creates a new period of time between the two non null specified datetime. The period starts at
 * the specified inclusive datetime and it ends at the specified other exclusive datetime. For
 * example, a period between 2016-12-17T13:30:00Z and 2016-12-17T14:30:00Z means the period is
 * spanning one hour the December 12./*w  w  w.j  a  v a  2s . c o  m*/
 * @param startDateTime the start datetime of the period. It defines the inclusive date
 * time at which the period starts.
 * @param endDateTime the end datetime of the period. It defines the exclusive datetime
 * at which the period ends. The end datetime must be after the start datetime.
 * @return the period of time between the two specified datetimes.
 */
public static Period between(OffsetDateTime startDateTime, OffsetDateTime endDateTime) {
    checkPeriod(startDateTime, endDateTime);
    Period period = new Period();
    period.startDateTime = startDateTime == OffsetDateTime.MIN ? OffsetDateTime.MIN
            : startDateTime.withOffsetSameInstant(ZoneOffset.UTC);
    period.endDateTime = endDateTime == OffsetDateTime.MAX ? OffsetDateTime.MAX
            : endDateTime.withOffsetSameInstant(ZoneOffset.UTC);
    period.inDays = false;
    return period;
}