Example usage for java.text DateFormat setTimeZone

List of usage examples for java.text DateFormat setTimeZone

Introduction

In this page you can find the example usage for java.text DateFormat setTimeZone.

Prototype

public void setTimeZone(TimeZone zone) 

Source Link

Document

Sets the time zone for the calendar of this DateFormat object.

Usage

From source file:com.redhat.rhn.common.localization.LocalizationService.java

/**
 * Format the date based on the locale and convert it to a String to
 * display. Uses DateFormat.SHORT. Example: 2004-12-10 13:20:00 PST
 *
 * Also includes the timezone of the current User if there is one
 *
 * @param date Date to format./*from w  ww . j a  v  a  2 s  .  c o m*/
 * @param locale Locale to use for formatting.
 * @return String representation of given date in given locale.
 */
public String formatDate(Date date, Locale locale) {
    // Example: 2004-12-10 13:20:00 PST
    StringBuilder dbuff = new StringBuilder();
    DateFormat dateI = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    dateI.setTimeZone(determineTimeZone());
    DateFormat timeI = DateFormat.getTimeInstance(DateFormat.LONG, locale);
    timeI.setTimeZone(determineTimeZone());

    dbuff.append(dateI.format(date));
    dbuff.append(" ");
    dbuff.append(timeI.format(date));

    return getDebugVersionOfString(dbuff.toString());
}

From source file:com.devoteam.srit.xmlloader.core.report.derived.DerivedCounter.java

public JFreeChart getTimeChart() {
    double[] graphTable = this.counter.graphDataset.getGraphArray();

    double[] weightTable = null;
    if (this instanceof StatValue) {
        weightTable = ((StatValue) this).eventCounter.graphDataset.getGraphArray();
    }/* www .  j  a  v  a2  s .  c o  m*/

    TimeSeries timeSeries = new TimeSeries("", FixedMillisecond.class);

    double hits = 0;

    long offset;
    boolean absoluteDate = Config.getConfigByName("tester.properties").getBoolean("stats.CHARTS_ABSOLUTE_DATE",
            false);
    if (absoluteDate) {
        offset = reportZeroTimestamp;
    } else {
        offset = 0;
    }
    for (int i = 0; i < graphTable.length; i++) {
        long timestamp = offset + i * this.counter.graphDataset.graphParameters.graphPeriod;
        timeSeries.add(new FixedMillisecond(timestamp), graphTable[i], false);
    }

    JFreeChart chart = ChartFactory.createXYAreaChart(null, // chart title
            null, // domain axis label
            null, // range axis label
            new TimeSeriesCollection(timeSeries), // data
            PlotOrientation.VERTICAL, // orientation
            false, // include legend
            false, // tooltips
            false // urls
    );
    if (null != mean && null != std_dv) {
        chart.getXYPlot().addRangeMarker(new ValueMarker(mean));
        IntervalMarker intervalMarker = new IntervalMarker(mean - std_dv / 2, mean + std_dv / 2);
        intervalMarker.setAlpha(0.3f);
        chart.getXYPlot().addRangeMarker(intervalMarker);
    }

    chart.getXYPlot().setDomainAxis(new DateAxis());
    DateAxis axis = (DateAxis) chart.getXYPlot().getDomainAxis();
    DateFormat dateFormat;

    if (absoluteDate) {
        dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
        axis.setVerticalTickLabels(true);
    } else {
        dateFormat = new SimpleDateFormat("HH:mm:ss");
        dateFormat.setTimeZone(new SimpleTimeZone(0, "GMT"));
    }
    axis.setDateFormatOverride(dateFormat);

    chart.setBackgroundPaint(Color.WHITE);
    return chart;
}

From source file:org.nuxeo.connect.client.jsf.AppCenterViewsManager.java

public String getStudioInstallationStatus() {
    if (studioSnapshotStatus == null) {
        LocalPackage pkg = null;// ww  w  . j  a v a2s  . com
        DownloadablePackage snapshotPkg = getStudioProjectSnapshot();
        if (snapshotPkg != null) {
            try {
                PackageUpdateService pus = Framework.getLocalService(PackageUpdateService.class);
                pkg = pus.getPackage(snapshotPkg.getId());
            } catch (PackageException e) {
                log.error(e);
            }
        }
        if (pkg == null) {
            return translate(LABEL_STUDIO_UPDATE_STATUS + "noStatus");
        }
        PackageState studioPkgState = pkg.getPackageState();
        if (studioPkgState == PackageState.DOWNLOADING) {
            studioSnapshotStatus = SnapshotStatus.downloading;
        } else if (studioPkgState == PackageState.DOWNLOADED) {
            studioSnapshotStatus = SnapshotStatus.saving;
        } else if (studioPkgState == PackageState.INSTALLING) {
            studioSnapshotStatus = SnapshotStatus.installing;
        } else if (studioPkgState.isInstalled()) {
            studioSnapshotStatus = SnapshotStatus.completed;
        } else {
            studioSnapshotStatus = SnapshotStatus.error;
        }
    }

    Object[] params = new Object[0];
    if (SnapshotStatus.error.equals(studioSnapshotStatus)) {
        if (studioSnapshotUpdateError == null) {
            studioSnapshotUpdateError = "???";
        }
        params = new Object[] { studioSnapshotUpdateError };
    } else if (SnapshotStatus.downloading.equals(studioSnapshotStatus)) {
        params = new Object[] { String.valueOf(studioSnapshotDownloadProgress) };
    } else {
        FileTime update = getLastUpdateDate();
        if (update != null) {
            DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
            df.setTimeZone(TimeZone.getDefault());
            params = new Object[] { df.format(new Date(update.toMillis())) };
        }
    }

    return translate(LABEL_STUDIO_UPDATE_STATUS + studioSnapshotStatus.name(), params);
}

From source file:com.ebay.pulsar.analytics.resources.PulsarQueryResource.java

@POST
@Path("today")
@Consumes(MediaType.APPLICATION_JSON)//from w ww.  j av  a2  s.c  om
@Produces(MediaType.APPLICATION_JSON)
public Response today(@Context HttpServletRequest request, CoreRequest req) {
    if (logger.isDebugEnabled()) {
        logger.debug("Today API called from IP: " + request.getRemoteAddr());
    }
    req.setNamespace(RequestNameSpace.today);
    req.setGranularity("fifteen_minute");

    Calendar c = Calendar.getInstance();
    long msEnd = c.getTimeInMillis();
    c.setTimeZone(TimeZone.getTimeZone("MST"));

    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);

    long msStart = c.getTimeInMillis();
    long msDiff = msEnd - msStart;

    if (msDiff < 0) {
        msStart = msStart - 86400000;
        msDiff = msDiff + 86400000;
    }

    if (msDiff < MS_15MINS) {
        // If the now time is 00:00:00 - 00:14:59 (Round to 0), let's do no
        // rounding.
        if (msDiff < 1000) {
            // If we really have the exact 00:00:00 time, let's just add 1
            // sec for end time.
            msEnd = msStart + 1000;
        } else {
            msEnd = msStart + msDiff;
        }
    } else {
        long msOffset = msDiff / MS_15MINS * MS_15MINS; // normalize to 0,
        // 15, 30, 45min of
        // each hour
        msEnd = msStart + msOffset;
    }
    Date end = new Date(msEnd);

    Date start = new Date(msStart);

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("MST"));

    req.setStartTime(dateFormat.format(start));
    req.setEndTime(dateFormat.format(end));

    boolean trace = request.getParameter("debug") == null ? false : true;
    return processRequest(req, trace);
}

From source file:org.wso2.carbon.connector.integration.test.amazonsqs.AmazonSQSAuthConnector.java

/**
 * Connect method which is generating authentication of the connector for each request.
 *
 * @param messageContext ESB messageContext.
 * @throws java.io.UnsupportedEncodingException
 * @throws IllegalStateException //from  w  w w.j a  v a  2  s .  c om
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.security.InvalidKeyException
 * @throws JSONException 
 */
public final Map<String, String> getRequestPayload(final JSONObject signatureRequestObject)
        throws InvalidKeyException, NoSuchAlgorithmException, IllegalStateException,
        UnsupportedEncodingException, JSONException {

    final StringBuilder canonicalRequest = new StringBuilder();
    final StringBuilder stringToSign = new StringBuilder();
    final StringBuilder payloadBuilder = new StringBuilder();
    final StringBuilder payloadStrBuilder = new StringBuilder();
    final StringBuilder authHeader = new StringBuilder();
    init(signatureRequestObject);

    // Generate time-stamp which will be sent to API and to be used in Signature
    final Date date = new Date();
    final TimeZone timeZone = TimeZone.getTimeZone(AmazonSQSConstants.GMT);
    final DateFormat dateFormat = new SimpleDateFormat(AmazonSQSConstants.ISO8601_BASIC_DATE_FORMAT);
    dateFormat.setTimeZone(timeZone);
    final String amzDate = dateFormat.format(date);

    final DateFormat shortDateFormat = new SimpleDateFormat(AmazonSQSConstants.SHORT_DATE_FORMAT);
    shortDateFormat.setTimeZone(timeZone);
    final String shortDate = shortDateFormat.format(date);

    signatureRequestObject.put(AmazonSQSConstants.AMZ_DATE, amzDate);
    final Map<String, String> parameterNamesMap = getParameterNamesMap();
    final Map<String, String> parametersMap = getSortedParametersMap(signatureRequestObject, parameterNamesMap);
    canonicalRequest.append(signatureRequestObject.get(AmazonSQSConstants.HTTP_METHOD));
    canonicalRequest.append(AmazonSQSConstants.NEW_LINE);
    final String charSet = Charset.defaultCharset().toString();
    if (signatureRequestObject.has(AmazonSQSConstants.URL_QUEUE_NAME)
            && !("").equals(signatureRequestObject.get(AmazonSQSConstants.URL_QUEUE_NAME))
            && signatureRequestObject.has(AmazonSQSConstants.QUEUE_ID)
            && !("").equals(signatureRequestObject.get(AmazonSQSConstants.QUEUE_ID))) {
        // queue ID and queue name should be encoded twise to match the Signature being generated by API,
        // Note that API it looks encodes the incoming URL once before creating the signature, SInce
        // we send url encoded URLs, API signatures are twise encoded
        final String encodedQueueID = URLEncoder
                .encode(signatureRequestObject.get(AmazonSQSConstants.QUEUE_ID).toString(), charSet);
        final String encodedQueueName = URLEncoder
                .encode(signatureRequestObject.get(AmazonSQSConstants.URL_QUEUE_NAME).toString(), charSet);
        canonicalRequest.append((AmazonSQSConstants.FORWARD_SLASH + URLEncoder.encode(encodedQueueID, charSet)
                + AmazonSQSConstants.FORWARD_SLASH + URLEncoder.encode(encodedQueueName, charSet)
                + AmazonSQSConstants.FORWARD_SLASH).replaceAll(AmazonSQSConstants.REGEX_ASTERISK,
                        AmazonSQSConstants.URL_ENCODED_ASTERISK));
        // Sets the http request Uri to message context 
        signatureRequestObject.put(AmazonSQSConstants.HTTP_REQUEST_URI,
                AmazonSQSConstants.FORWARD_SLASH + encodedQueueID + AmazonSQSConstants.FORWARD_SLASH
                        + encodedQueueName + AmazonSQSConstants.FORWARD_SLASH);
    } else {
        canonicalRequest.append(AmazonSQSConstants.FORWARD_SLASH);
    }

    canonicalRequest.append(AmazonSQSConstants.NEW_LINE);

    final Set<String> keySet = parametersMap.keySet();
    for (String key : keySet) {
        payloadBuilder.append(URLEncoder.encode(key, charSet));
        payloadBuilder.append(AmazonSQSConstants.EQUAL);
        payloadBuilder.append(URLEncoder.encode(parametersMap.get(key), charSet));
        payloadBuilder.append(AmazonSQSConstants.AMPERSAND);
        payloadStrBuilder.append(AmazonSQSConstants.QUOTE);
        payloadStrBuilder.append(key);
        payloadStrBuilder.append(AmazonSQSConstants.QUOTE);
        payloadStrBuilder.append(AmazonSQSConstants.COLON);
        payloadStrBuilder.append(AmazonSQSConstants.QUOTE);
        payloadStrBuilder.append(parametersMap.get(key));
        payloadStrBuilder.append(AmazonSQSConstants.QUOTE);
        payloadStrBuilder.append(AmazonSQSConstants.COMMA);

    }
    // Adds authorization header to message context, removes additionally appended comma at the end
    if (payloadStrBuilder.length() > 0) {
        signatureRequestObject.put(AmazonSQSConstants.REQUEST_PAYLOAD,
                payloadStrBuilder.substring(0, payloadStrBuilder.length() - 1));
    }
    // Appends empty string since no URL parameters are used in POST API requests
    canonicalRequest.append("");
    canonicalRequest.append(AmazonSQSConstants.NEW_LINE);
    final Map<String, String> headersMap = getSortedHeadersMap(signatureRequestObject, parameterNamesMap);
    final StringBuilder canonicalHeaders = new StringBuilder();
    final StringBuilder signedHeader = new StringBuilder();
    final Set<String> keysSet = headersMap.keySet();
    for (String key : keysSet) {
        canonicalHeaders.append(key);
        canonicalHeaders.append(AmazonSQSConstants.COLON);
        canonicalHeaders.append(headersMap.get(key));
        canonicalHeaders.append(AmazonSQSConstants.NEW_LINE);
        signedHeader.append(key);
        signedHeader.append(AmazonSQSConstants.SEMI_COLON);
    }
    canonicalRequest.append(canonicalHeaders.toString());
    canonicalRequest.append(AmazonSQSConstants.NEW_LINE);
    // Remove unwanted semi-colon at the end of the signedHeader string
    String signedHeaders = "";
    if (signedHeader.length() > 0) {
        signedHeaders = signedHeader.substring(0, signedHeader.length() - 1);
    }
    canonicalRequest.append(signedHeaders);
    canonicalRequest.append(AmazonSQSConstants.NEW_LINE);
    // HashedPayload = HexEncode(Hash(requestPayload))
    String requestPayload = "";
    if (payloadBuilder.length() > 0) {
        /*
         * First removes the additional ampersand appended to the end of the payloadBuilder, then o
         * further modifications to preserve unreserved characters as per the API guide
         * (http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html)
         */
        requestPayload = payloadBuilder.substring(0, payloadBuilder.length() - 1).toString()
                .replace(AmazonSQSConstants.PLUS, AmazonSQSConstants.URL_ENCODED_PLUS)
                .replace(AmazonSQSConstants.URL_ENCODED_TILT, AmazonSQSConstants.TILT)
                .replace(AmazonSQSConstants.ASTERISK, AmazonSQSConstants.URL_ENCODED_ASTERISK);
    }
    canonicalRequest.append(bytesToHex(hash(requestPayload)).toLowerCase());
    stringToSign.append(AmazonSQSConstants.AWS4_HMAC_SHA_256);
    stringToSign.append(AmazonSQSConstants.NEW_LINE);
    stringToSign.append(amzDate);
    stringToSign.append(AmazonSQSConstants.NEW_LINE);
    stringToSign.append(shortDate);
    stringToSign.append(AmazonSQSConstants.FORWARD_SLASH);
    stringToSign.append(signatureRequestObject.get(AmazonSQSConstants.REGION));
    stringToSign.append(AmazonSQSConstants.FORWARD_SLASH);
    stringToSign.append(signatureRequestObject.get(AmazonSQSConstants.SERVICE));
    stringToSign.append(AmazonSQSConstants.FORWARD_SLASH);
    stringToSign.append(signatureRequestObject.get(AmazonSQSConstants.TERMINATION_STRING));
    stringToSign.append(AmazonSQSConstants.NEW_LINE);
    stringToSign.append(bytesToHex(hash(canonicalRequest.toString())).toLowerCase());
    final byte[] signingKey = getSignatureKey(signatureRequestObject,
            signatureRequestObject.get(AmazonSQSConstants.SECRET_ACCESS_KEY).toString(), shortDate,
            signatureRequestObject.get(AmazonSQSConstants.REGION).toString(),
            signatureRequestObject.get(AmazonSQSConstants.SERVICE).toString());

    // Construction of authorization header value to be in cluded in API request
    authHeader.append(AmazonSQSConstants.AWS4_HMAC_SHA_256);
    authHeader.append(AmazonSQSConstants.COMMA);
    authHeader.append(AmazonSQSConstants.CREDENTIAL);
    authHeader.append(AmazonSQSConstants.EQUAL);
    authHeader.append(signatureRequestObject.get(AmazonSQSConstants.ACCESS_KEY_ID));
    authHeader.append(AmazonSQSConstants.FORWARD_SLASH);
    authHeader.append(shortDate);
    authHeader.append(AmazonSQSConstants.FORWARD_SLASH);
    authHeader.append(signatureRequestObject.get(AmazonSQSConstants.REGION));
    authHeader.append(AmazonSQSConstants.FORWARD_SLASH);
    authHeader.append(signatureRequestObject.get(AmazonSQSConstants.SERVICE));
    authHeader.append(AmazonSQSConstants.FORWARD_SLASH);
    authHeader.append(signatureRequestObject.get(AmazonSQSConstants.TERMINATION_STRING));
    authHeader.append(AmazonSQSConstants.COMMA);
    authHeader.append(AmazonSQSConstants.SIGNED_HEADERS);
    authHeader.append(AmazonSQSConstants.EQUAL);
    authHeader.append(signedHeaders);
    authHeader.append(AmazonSQSConstants.COMMA);
    authHeader.append(AmazonSQSConstants.API_SIGNATURE);
    authHeader.append(AmazonSQSConstants.EQUAL);
    authHeader.append(bytesToHex(hmacSHA256(signingKey, stringToSign.toString())).toLowerCase());
    // Adds authorization header to message context
    signatureRequestObject.put(AmazonSQSConstants.AUTHORIZATION_HEADER, authHeader.toString());

    Map<String, String> responseMap = new HashMap<String, String>();
    responseMap.put(AmazonSQSConstants.AUTHORIZATION_HEADER, authHeader.toString());
    responseMap.put(AmazonSQSConstants.AMZ_DATE, amzDate);
    responseMap.put(AmazonSQSConstants.REQUEST_PAYLOAD, requestPayload);
    return responseMap;
}

From source file:org.wso2.carbon.connector.amazons3.auth.AmazonS3AuthConnector.java

/**
 * Connect method which is generating authentication of the connector for each request.
 *
 * @param messageContext ESB messageContext.
 *//*  w  w w  . j a  v  a  2  s  .c o  m*/
public final void connect(final MessageContext messageContext) {
    final StringBuilder canonicalRequest = new StringBuilder();
    final StringBuilder stringToSign = new StringBuilder();
    final StringBuilder authHeader = new StringBuilder();
    final Map<String, String> parametersMap = getParametersMap(messageContext);
    final Locale defaultLocale = Locale.getDefault();

    final Date date = new Date();
    final TimeZone timeZone = TimeZone.getTimeZone(AmazonS3Constants.TIME_ZONE);
    final SimpleDateFormat dateFormat = new SimpleDateFormat(AmazonS3Constants.CURR_DATE_FORMAT, defaultLocale);
    dateFormat.setTimeZone(timeZone);
    final String currentDate = dateFormat.format(date);

    final DateFormat shortDateFormat = new SimpleDateFormat(AmazonS3Constants.SHORT_DATE_FORMAT);
    shortDateFormat.setTimeZone(timeZone);
    final String shortDate = shortDateFormat.format(date);
    try {
        final String dateTrimmed = currentDate.trim();
        final Map<String, String> amzHeadersMap = new HashMap<>();
        final Map<String, String> queryParamsMap = new HashMap<>();
        final StringBuilder canonicalHeaders = new StringBuilder();
        final StringBuilder canonicalQueryString = new StringBuilder();
        final StringBuilder signedHeader = new StringBuilder();

        canonicalRequest.append(parametersMap.get(AmazonS3Constants.METHOD_TYPE))
                .append(AmazonS3Constants.NEW_LINE);
        // Setting the canonicalized resource.
        if (StringUtils.isNotEmpty(parametersMap.get(AmazonS3Constants.BUCKET_NAME))) {
            canonicalRequest.append(AmazonS3Constants.FORWARD_SLASH)
                    .append(parametersMap.get(AmazonS3Constants.BUCKET_NAME));
        }
        String urlRemainder = (String) messageContext.getProperty(AmazonS3Constants.URI_REMAINDER);
        if (urlRemainder != null && !urlRemainder.isEmpty()) {
            canonicalRequest.append(urlRemainder.replaceAll("%2F", "/"));
        }

        // Setting canonicalQueryString
        final Map<String, String> queryParametersMap = getQueryParamKeysMap();
        for (Map.Entry<String, String> entry : queryParametersMap.entrySet()) {
            String key = entry.getKey();
            String tempParam = parametersMap.get(key);
            if (!tempParam.isEmpty()) {
                queryParamsMap.put(queryParametersMap.get(key),
                        tempParam.replaceAll(AmazonS3Constants.REGEX, AmazonS3Constants.EMPTY_STR));
            }
        }

        String queryString = (String) messageContext.getProperty(AmazonS3Constants.QUERY_STRING);
        final SortedSet<String> queryKeys = new TreeSet<>(queryParamsMap.keySet());

        for (String key : queryKeys) {
            if (key.equals(AmazonS3Constants.QUERY_STRING)) {
                canonicalQueryString.append(URLEncoder.encode(queryString, AmazonS3Constants.UTF_8))
                        .append(AmazonS3Constants.EQUAL).append(AmazonS3Constants.EMPTY_STR)
                        .append(AmazonS3Constants.AMP);
            } else {
                String queryValue = queryParamsMap.get(key);
                canonicalQueryString.append(URLEncoder.encode(key, AmazonS3Constants.UTF_8))
                        .append(AmazonS3Constants.EQUAL)
                        .append(URLEncoder.encode(queryValue, AmazonS3Constants.UTF_8))
                        .append(AmazonS3Constants.AMP);
            }

        }

        //Remove additionally added ampersand at the end from canonicalQueryString and append to canonicalRequest.
        if (canonicalQueryString.length() > 0) {
            canonicalRequest.append(AmazonS3Constants.NEW_LINE);
            canonicalRequest.append(canonicalQueryString.substring(0, canonicalQueryString.length() - 1));
        } else {
            canonicalRequest.append(AmazonS3Constants.NEW_LINE);
        }

        if (Boolean.parseBoolean(parametersMap.get(AmazonS3Constants.IS_XAMZ_DATE))) {
            canonicalRequest.append(AmazonS3Constants.NEW_LINE);
            amzHeadersMap.put(AmazonS3Constants.HD_XAMZ_DATE, dateTrimmed);
            messageContext.setProperty(AmazonS3Constants.IS_XAMZ_DATE_VAL, dateTrimmed);
        } else {
            canonicalRequest.append(dateTrimmed).append(AmazonS3Constants.NEW_LINE);
        }

        final Map<String, String> amzHeaderKeysMap = getHeaderKeysMap();
        for (Map.Entry<String, String> entry : amzHeaderKeysMap.entrySet()) {
            String key = entry.getKey();
            String tempParam = parametersMap.get(key);
            if (!tempParam.isEmpty()) {
                amzHeadersMap.put(amzHeaderKeysMap.get(key), tempParam);
            }
        }

        final SortedSet<String> keys = new TreeSet<>(amzHeadersMap.keySet());
        for (String key : keys) {
            String headerValues = amzHeadersMap.get(key);
            canonicalHeaders.append(key.toLowerCase(defaultLocale)).append(AmazonS3Constants.COLON)
                    .append(headerValues).append(AmazonS3Constants.NEW_LINE);
            signedHeader.append(key.toLowerCase(defaultLocale));
            signedHeader.append(AmazonS3Constants.SEMI_COLON);
        }
        canonicalRequest.append(canonicalHeaders).append(AmazonS3Constants.NEW_LINE);

        // Remove unwanted semi-colon at the end of the signedHeader string
        String signedHeaders = "";
        if (signedHeader.length() > 0) {
            signedHeaders = signedHeader.substring(0, signedHeader.length() - 1);
        }
        canonicalRequest.append(signedHeaders).append(AmazonS3Constants.NEW_LINE);
        canonicalRequest.append(AmazonS3Constants.UNSIGNED_PAYLOAD);

        // Create stringToSign
        stringToSign.append(AmazonS3Constants.AWS4_HMAC_SHA_256);
        stringToSign.append(AmazonS3Constants.NEW_LINE);
        stringToSign.append(dateTrimmed);
        stringToSign.append(AmazonS3Constants.NEW_LINE);

        stringToSign.append(shortDate);
        stringToSign.append(AmazonS3Constants.FORWARD_SLASH);
        stringToSign.append(messageContext.getProperty(AmazonS3Constants.REGION));
        stringToSign.append(AmazonS3Constants.FORWARD_SLASH);
        stringToSign.append(messageContext.getProperty(AmazonS3Constants.SERVICE));
        stringToSign.append(AmazonS3Constants.FORWARD_SLASH);
        stringToSign.append(messageContext.getProperty(AmazonS3Constants.TERMINATION_STRING));

        stringToSign.append(AmazonS3Constants.NEW_LINE);
        stringToSign.append(bytesToHex(hash(messageContext, canonicalRequest.toString())).toLowerCase());

        if ((messageContext.getProperty(AmazonS3Constants.SECRET_ACCESS_KEY) != null)
                && (messageContext.getProperty(AmazonS3Constants.REGION) != null)
                && (messageContext.getProperty(AmazonS3Constants.SERVICE) != null) && (shortDate) != null) {
            final byte[] signingKey = getSignatureKey(messageContext,
                    messageContext.getProperty(AmazonS3Constants.SECRET_ACCESS_KEY).toString(), shortDate,
                    messageContext.getProperty(AmazonS3Constants.REGION).toString(),
                    messageContext.getProperty(AmazonS3Constants.SERVICE).toString());

            // Construction of authorization header value to be included in API request
            authHeader.append(AmazonS3Constants.AWS4_HMAC_SHA_256);
            authHeader.append(" ");
            authHeader.append(AmazonS3Constants.CREDENTIAL);
            authHeader.append(AmazonS3Constants.EQUAL);
            authHeader.append(messageContext.getProperty(AmazonS3Constants.ACCESS_KEY_ID));
            authHeader.append(AmazonS3Constants.FORWARD_SLASH);
            authHeader.append(shortDate);
            authHeader.append(AmazonS3Constants.FORWARD_SLASH);
            authHeader.append(messageContext.getProperty(AmazonS3Constants.REGION));
            authHeader.append(AmazonS3Constants.FORWARD_SLASH);
            authHeader.append(messageContext.getProperty(AmazonS3Constants.SERVICE));
            authHeader.append(AmazonS3Constants.FORWARD_SLASH);
            authHeader.append(messageContext.getProperty(AmazonS3Constants.TERMINATION_STRING));
            authHeader.append(AmazonS3Constants.COMMA);
            authHeader.append(AmazonS3Constants.SIGNED_HEADERS);
            authHeader.append(AmazonS3Constants.EQUAL);
            authHeader.append(signedHeaders);
            authHeader.append(AmazonS3Constants.COMMA);
            authHeader.append(AmazonS3Constants.API_SIGNATURE);
            authHeader.append(AmazonS3Constants.EQUAL);
            authHeader.append(bytesToHex(hmacSHA256(signingKey, stringToSign.toString())).toLowerCase());

            // Adds authorization header to message context
            messageContext.setProperty(AmazonS3Constants.AUTH_CODE, authHeader.toString());
        } else {
            if (log.isDebugEnabled()) {
                log.debug("secretAccessKey or region or service or shortDate may be null"
                        + "Hence couldn't generate signingKey");
            }
            handleException(AmazonS3Constants.CONNECTOR_ERROR + " secretAccessKey or region or service or "
                    + "shortDate may be null" + "Hence couldn't generate signingKey.", messageContext);
        }
    } catch (InvalidKeyException exc) {
        storeErrorResponseStatus(messageContext, exc, AmazonS3Constants.INVALID_KEY_ERROR_CODE);
        handleException(AmazonS3Constants.INVALID_KEY_ERROR, exc, messageContext);
    } catch (NoSuchAlgorithmException exc) {
        storeErrorResponseStatus(messageContext, exc, AmazonS3Constants.NO_SUCH_ALGORITHM_ERROR_CODE);
        handleException(AmazonS3Constants.NO_SUCH_ALGORITHM_ERROR, exc, messageContext);
    } catch (IllegalStateException exc) {
        storeErrorResponseStatus(messageContext, exc, AmazonS3Constants.ILLEGAL_STATE_ERROR_CODE);
        handleException(AmazonS3Constants.CONNECTOR_ERROR, exc, messageContext);
    } catch (UnsupportedEncodingException exc) {
        storeErrorResponseStatus(messageContext, exc, AmazonS3Constants.UNSUPPORTED_ENCORDING_ERROR_CODE);
        handleException(AmazonS3Constants.CONNECTOR_ERROR, exc, messageContext);
    }
}

From source file:net.sf.jasperreports.functions.standard.DateTimeFunctions.java

/**
 * This methods tries to convert a generic object into a java.util.Date instance.
 * Supported types are for now String, Long values (time millis) and Date subtypes
 * like for example java.sql.Date./*from w w w .j  a v  a 2 s  . c  o  m*/
 */
private Date convertDateObject(Object dateObject) {
    if (dateObject == null) {
        if (log.isDebugEnabled()) {
            log.debug("The date object can not be null.");
        }
        return null;
    } else if (dateObject instanceof String) {
        // Try to convert using the different style for pattern.
        // We use MEDIUM as the first one because it is the DEFAULT
        int formatTypes[] = new int[] { DateFormat.MEDIUM, DateFormat.SHORT, DateFormat.LONG, DateFormat.FULL };
        for (int formatType : formatTypes) {
            try {
                DateFormat df = DateFormat.getDateInstance(formatType, getReportLocale());
                df.setTimeZone(getReportTimeZone());
                return df.parse((String) dateObject);
            } catch (ParseException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Unable to parse the string as Date using the standard SimpleDateFormat.");
                }
            }
        }
        return null;
    } else if (dateObject instanceof Long) {
        Calendar cal = Calendar.getInstance(getReportTimeZone(), getReportLocale());
        cal.setTimeInMillis((Long) dateObject);
        return cal.getTime();
    } else if (dateObject instanceof Date) {
        return (Date) dateObject;
    }
    if (log.isDebugEnabled()) {
        log.debug("The specified object is not among the allowed types for Date conversion.");
    }
    return null;
}

From source file:org.apache.archiva.web.api.DefaultFileUploadService.java

protected void saveFile(String repositoryId, FileMetadata fileMetadata, boolean generatePom, String groupId,
        String artifactId, String version, String packaging) throws ArchivaRestServiceException {
    try {/*from   w w w.  ja  va 2  s.c om*/

        ManagedRepository repoConfig = managedRepositoryAdmin.getManagedRepository(repositoryId);

        ArtifactReference artifactReference = new ArtifactReference();
        artifactReference.setArtifactId(artifactId);
        artifactReference.setGroupId(groupId);
        artifactReference.setVersion(version);
        artifactReference.setClassifier(fileMetadata.getClassifier());
        artifactReference.setType(
                StringUtils.isEmpty(fileMetadata.getPackaging()) ? packaging : fileMetadata.getPackaging());

        ManagedRepositoryContent repository = repositoryFactory.getManagedRepositoryContent(repositoryId);

        String artifactPath = repository.toPath(artifactReference);

        int lastIndex = artifactPath.lastIndexOf('/');

        String path = artifactPath.substring(0, lastIndex);
        File targetPath = new File(repoConfig.getLocation(), path);

        log.debug("artifactPath: {} found targetPath: {}", artifactPath, targetPath);

        Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
        int newBuildNumber = -1;
        String timestamp = null;

        File versionMetadataFile = new File(targetPath, MetadataTools.MAVEN_METADATA);
        ArchivaRepositoryMetadata versionMetadata = getMetadata(versionMetadataFile);

        if (VersionUtil.isSnapshot(version)) {
            TimeZone timezone = TimeZone.getTimeZone("UTC");
            DateFormat fmt = new SimpleDateFormat("yyyyMMdd.HHmmss");
            fmt.setTimeZone(timezone);
            timestamp = fmt.format(lastUpdatedTimestamp);
            if (versionMetadata.getSnapshotVersion() != null) {
                newBuildNumber = versionMetadata.getSnapshotVersion().getBuildNumber() + 1;
            } else {
                newBuildNumber = 1;
            }
        }

        if (!targetPath.exists()) {
            targetPath.mkdirs();
        }

        String filename = artifactPath.substring(lastIndex + 1);
        if (VersionUtil.isSnapshot(version)) {
            filename = filename.replaceAll(VersionUtil.SNAPSHOT, timestamp + "-" + newBuildNumber);
        }

        boolean fixChecksums = !(archivaAdministration.getKnownContentConsumers()
                .contains("create-missing-checksums"));

        try {
            File targetFile = new File(targetPath, filename);
            if (targetFile.exists() && !VersionUtil.isSnapshot(version) && repoConfig.isBlockRedeployments()) {
                throw new ArchivaRestServiceException("Overwriting released artifacts in repository '"
                        + repoConfig.getId() + "' is not allowed.", Response.Status.BAD_REQUEST.getStatusCode(),
                        null);
            } else {
                copyFile(new File(fileMetadata.getServerFileName()), targetPath, filename, fixChecksums);
                triggerAuditEvent(repository.getId(), path + "/" + filename, AuditEvent.UPLOAD_FILE);
                queueRepositoryTask(repository.getId(), targetFile);
            }
        } catch (IOException ie) {
            log.error("IOException copying file: {}", ie.getMessage(), ie);
            throw new ArchivaRestServiceException(
                    "Overwriting released artifacts in repository '" + repoConfig.getId() + "' is not allowed.",
                    Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), ie);
        }

        if (generatePom) {
            String pomFilename = filename;
            if (StringUtils.isNotEmpty(fileMetadata.getClassifier())) {
                pomFilename = StringUtils.remove(pomFilename, "-" + fileMetadata.getClassifier());
            }
            pomFilename = FilenameUtils.removeExtension(pomFilename) + ".pom";

            try {
                File generatedPomFile = createPom(targetPath, pomFilename, fileMetadata, groupId, artifactId,
                        version, packaging);
                triggerAuditEvent(repoConfig.getId(), path + "/" + pomFilename, AuditEvent.UPLOAD_FILE);
                if (fixChecksums) {
                    fixChecksums(generatedPomFile);
                }
                queueRepositoryTask(repoConfig.getId(), generatedPomFile);
            } catch (IOException ie) {
                throw new ArchivaRestServiceException(
                        "Error encountered while writing pom file: " + ie.getMessage(),
                        Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), ie);
            }
        }

        // explicitly update only if metadata-updater consumer is not enabled!
        if (!archivaAdministration.getKnownContentConsumers().contains("metadata-updater")) {
            updateProjectMetadata(targetPath.getAbsolutePath(), lastUpdatedTimestamp, timestamp, newBuildNumber,
                    fixChecksums, fileMetadata, groupId, artifactId, version, packaging);

            if (VersionUtil.isSnapshot(version)) {
                updateVersionMetadata(versionMetadata, versionMetadataFile, lastUpdatedTimestamp, timestamp,
                        newBuildNumber, fixChecksums, fileMetadata, groupId, artifactId, version, packaging);
            }
        }
    } catch (RepositoryNotFoundException re) {
        throw new ArchivaRestServiceException("Target repository cannot be found: " + re.getMessage(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), re);
    } catch (RepositoryException rep) {
        throw new ArchivaRestServiceException("Repository exception: " + rep.getMessage(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), rep);
    } catch (RepositoryAdminException e) {
        throw new ArchivaRestServiceException("RepositoryAdmin exception: " + e.getMessage(),
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e);
    }
}

From source file:com.rogchen.common.xml.UtilDateTime.java

/**
 * Returns an initialized DateFormat object.
 *
 * @param dateFormat optional format string
 * @param tz/*from  w ww  . j a  v a  2s.  c  om*/
 * @param locale can be null if dateFormat is not null
 * @return DateFormat object
 */
public static DateFormat toDateFormat(String dateFormat, TimeZone tz, Locale locale) {
    DateFormat df = null;
    if (dateFormat == null) {
        df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    } else {
        df = new SimpleDateFormat(dateFormat);
    }
    df.setTimeZone(tz);
    return df;
}

From source file:com.rogchen.common.xml.UtilDateTime.java

/**
 * Returns an initialized DateFormat object.
 *
 * @param timeFormat optional format string
 * @param tz/*from www . j  a va  2s.c  om*/
 * @param locale can be null if timeFormat is not null
 * @return DateFormat object
 */
public static DateFormat toTimeFormat(String timeFormat, TimeZone tz, Locale locale) {
    DateFormat df = null;
    if (timeFormat == null) {
        df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
    } else {
        df = new SimpleDateFormat(timeFormat);
    }
    df.setTimeZone(tz);
    return df;
}