Example usage for org.joda.time DateTimeZone forTimeZone

List of usage examples for org.joda.time DateTimeZone forTimeZone

Introduction

In this page you can find the example usage for org.joda.time DateTimeZone forTimeZone.

Prototype

public static DateTimeZone forTimeZone(TimeZone zone) 

Source Link

Document

Gets a time zone instance for a JDK TimeZone.

Usage

From source file:com.phloc.datetime.PDTFactory.java

License:Apache License

@Nonnull
public static DateTime createDateTime(@Nonnull final Date aDate, @Nonnull final TimeZone aTimeZone) {
    return new DateTime(aDate, PDTConfig.getDefaultChronology().withZone(DateTimeZone.forTimeZone(aTimeZone)));
}

From source file:com.phloc.datetime.PDTFactory.java

License:Apache License

@Nonnull
public static LocalDate createLocalDate(@Nonnull final Date aDate, final TimeZone aTimeZone) {
    return new LocalDate(aDate, getLocalChronology().withZone(DateTimeZone.forTimeZone(aTimeZone)));
}

From source file:com.phloc.datetime.PDTFactory.java

License:Apache License

@Nonnull
public static LocalTime createLocalTime(@Nonnull final Date aDate, @Nonnull final TimeZone aTimeZone) {
    return new LocalTime(aDate, getLocalChronology().withZone(DateTimeZone.forTimeZone(aTimeZone)));
}

From source file:com.prayer.App.java

License:Apache License

@Override
public void onCreate() {
    super.onCreate();
    sContext = this;

    JobManager.create(this).addJobCreator(new MyJobCreator());

    mDefaultUEH = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(mCaughtExceptionHandler);

    DateTimeZone.setDefault(DateTimeZone.forTimeZone(TimeZone.getDefault()));

    try {/*from  ww w .ja v a2 s  .  com*/
        Times.getTimes();
    } catch (Exception e) {
    }

    Utils.init(this);

    startService(new Intent(this, WidgetService.class));
    Times.setAlarms();

    PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
}

From source file:com.robwilliamson.healthyesther.fragment.dialog.AbstractDateTimePickerFragment.java

License:Open Source License

public void setDateTime(DateTime dateTime) {
    mDateTime = dateTime.withZone(DateTimeZone.forTimeZone(TimeZone.getDefault()));
}

From source file:com.robwilliamson.healthyesther.reminder.TimingManager.java

License:Open Source License

private static DateTime makeLocal(DateTime time) {
    if (time == null) {
        return null;
    }//from w w w  .  j a  va 2  s  .c om

    return time.withZone(DateTimeZone.forTimeZone(TimeZone.getDefault()));
}

From source file:com.sam.moca.applications.mload.Mload.java

License:Open Source License

/**
 * Processes a control file/*from w w w . j a v  a 2s  . c o m*/
 * @return The number of errors that occurred
 * @throws FileNotFoundException if the control file could not be located
 * @throws IOException if the control file or a data file could not be read
 * @throws MocaException if an exception occurred when executing a command
 * @throws ParseException if the control file or a data file could not be parsed
 */
public int processCtl() throws FileNotFoundException, IOException, MocaException, ParseException {
    // Format is for turning duration into a formatted string
    DateTimeFormatter dateFormat = DateTimeFormat.forPattern("HH:mm:ss.SSS")
            .withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT")));

    BufferedReader inputFile = null;
    StringBuilder buffer;
    String line;
    int totalErrors = 0;

    // Read the control file
    ctlFileLines = readControlFile(ctlFile);

    File[] files = datawd.listFiles(new WildcardFilenameFilter(dataFile));

    if (files == null || files.length == 0) {

        // We have to check the fallback directory as well, since this
        // could have been invoked programmatically.
        files = virtualwd.listFiles(new WildcardFilenameFilter(dataFile));

        if (files == null || files.length == 0) {
            // Lastly we try the file as an absolute value.
            String expandedName = MocaUtils.expandEnvironmentVariables(MocaUtils.currentContext(), dataFile);
            File file = new File(expandedName);
            if (!file.exists() || !file.isAbsolute()) {
                errStream.append("Data file ");
                errStream.append(dataFile);
                errStream.append(" could not be found for control file ");
                errStream.append(ctlFile);
                errStream.append("!\n");

                //                    throw new FileNotFoundException("Could not locate file " + expandedName);
                return 0;
            }
            files = new File[] { file };
        }
    }

    List<File> sortedFiles = new ArrayList<File>(Arrays.asList(files));

    // Now sort the list by Names
    Collections.sort(sortedFiles, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });

    String ctlFileLinesRestore = ctlFileLines;

    for (File dataFile : sortedFiles) {
        ctlFileLines = ctlFileLinesRestore;
        try {
            inputFile = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile), "UTF-8"));

            String fileName;

            if (dataFile.isAbsolute()) {
                fileName = dataFile.getAbsolutePath();
            } else {
                fileName = dataFile.getParentFile().getName() + File.separator + dataFile.getName();
            }

            buffer = new StringBuilder();
            buffer.append("Processing ");
            buffer.append(fileName);
            buffer.append("... ");
            if (linesPerCommit > 0) {
                buffer.append("(commit window ");
                buffer.append(linesPerCommit);
                buffer.append(" lines)");
            }
            buffer.append('\n');
            outStream.append(buffer);
            outStream.append('\n');

            int columnCount = 0;
            int lineNum = 0;
            int curLineNum = 0;
            if (hasHeader) {
                line = inputFile.readLine();
                if (line == null || line.isEmpty()) {
                    throw new ParseException("Unable to read header line", 0);
                }

                curLineNum++;

                String[] fields = separateFields(line, fieldDelim);
                columnCount = fields.length;

                buffer = new StringBuilder();

                boolean inAt = false;
                int startPos = 0;

                // This replaces headers with the generic @VAR#@
                for (int pos = 0; pos < ctlFileLines.length(); pos++) {
                    char c = ctlFileLines.charAt(pos);
                    if (inAt) {
                        if (c == '@') {
                            String varName = ctlFileLines.substring(startPos, pos + 1);
                            boolean found = false;

                            // Handle updating
                            if (varName.equalsIgnoreCase("@mode_updating@")) {
                                varName = (upgrading ? "Y" : "N");
                                found = true;
                            }
                            // Handle column names
                            else {
                                for (int i = 0; i < fields.length; i++) {
                                    //                                        String fieldName = "@" + fields[i] + "@";
                                    String fieldName = "@" + fields[i].trim() + "@";
                                    if (varName.equalsIgnoreCase(fieldName)) {
                                        varName = varBaseName + (i + 1) + "@";
                                        found = true;
                                        break;
                                    }
                                }
                            }

                            // Handle not found encapsulated by single quotes
                            if (!found && startPos > 0 && ctlFileLines.charAt(startPos - 1) == '\''
                                    && pos < ctlFileLines.length() && ctlFileLines.charAt(pos + 1) == '\'') {
                                varName = "";
                            }

                            buffer.append(varName);
                            inAt = false;
                        } else if (!Character.isLetterOrDigit(c) && c != '_') {
                            inAt = false;
                            buffer.append(ctlFileLines.substring(startPos, pos + 1));
                        }
                    } else {
                        if (c == '@') {
                            startPos = pos;
                            inAt = true;
                        } else {
                            buffer.append(c);
                        }
                    }
                }

                ctlFileLines = buffer.toString();
            }

            int recordNum = 0;
            int blankCount = 0;
            int rollbackNum = 0;
            int errCount = 0;
            int pendingCommitNum = 0;
            long startTime = System.currentTimeMillis();

            while ((line = inputFile.readLine()) != null) {
                curLineNum++;
                lineNum = curLineNum;

                // Skip empty lines
                if (line.isEmpty())
                    continue;

                recordNum++;

                // Skip empty records
                if (line.matches("\\" + fieldDelim + "*")) {
                    if (!silent) {
                        buffer = new StringBuilder();
                        buffer.append("Ignoring record ");
                        buffer.append(recordNum);
                        buffer.append(", line number: ");
                        buffer.append(lineNum);
                        buffer.append(" in the data file [");
                        buffer.append(fileName);
                        buffer.append("] since all columns are blank");
                        outStream.append(buffer);
                        outStream.append('\n');
                    }
                    blankCount++;
                    continue;
                }

                // Append extra lines from unmatched double-quotes if needed
                StringBuilder lineBuffer = new StringBuilder(line);

                int numQuotes = 0;
                for (char c : line.toCharArray()) {
                    if (c == '"')
                        numQuotes++;
                }

                while (numQuotes % 2 != 0) {
                    line = inputFile.readLine();
                    if (line == null)
                        break;

                    for (char c : line.toCharArray()) {
                        if (c == '"')
                            numQuotes++;
                    }

                    lineBuffer.append('\n');
                    lineBuffer.append(line);
                    curLineNum++;
                }

                line = lineBuffer.toString();

                pendingCommitNum++;
                String[] fields;
                try {
                    fields = separateFields(line, fieldDelim);
                } catch (ParseException e) {
                    // Rethrow after adding more information
                    throw new ParseException(
                            e.getMessage() + " on line " + lineNum + " while parsing " + dataFile.getName(),
                            e.getErrorOffset());
                }

                // Check for an invalid amount of columns
                if (columnCount != 0 && fields.length != columnCount) {
                    int rollbackCount = pendingCommitNum - 1;
                    errCount++;
                    rollbackNum += rollbackCount;
                    pendingCommitNum = 0;

                    connection.executeCommand("rollback");
                    displayError("Error: wrong number of columns when parsing", recordNum, rollbackCount,
                            lineNum, curLineNum, fileName);
                } else {
                    try {
                        subDataAndExec(fields, errCount);
                    } catch (MocaException e) {
                        int rollbackCount = pendingCommitNum - 1;
                        errCount++;
                        rollbackNum += rollbackCount;
                        pendingCommitNum = 0;

                        connection.executeCommand("rollback");

                        if (!silent && (maxErrors == 0 || errCount < maxErrors)) {
                            displayError("Error " + e.getErrorCode() + " when executing on", recordNum,
                                    rollbackCount, lineNum, curLineNum, fileName);
                        }
                    }

                    if (recordNum % 100000 == 0) {
                        Date elapsed = new Date(System.currentTimeMillis() - startTime);
                        outStream.append(String.valueOf(recordNum));
                        outStream.append(" record(s) processed; elapsed: ");
                        outStream.append(dateFormat.print(elapsed.getTime()));
                        outStream.append('\n');
                    }
                }

                /*
                 * Commit pending, if linesPerCommit is set greater than
                 * zero and the number of pending commits is greater than
                 * or equal to it. Note that it is possible to miss this
                 * code if the number of lines in a file are less than
                 * linesPerCommit or on a fatal error so we call this later
                 * outside the loop as well
                 */
                if (linesPerCommit > 0 && pendingCommitNum >= linesPerCommit) {
                    pendingCommitNum = 0;
                    connection.executeCommand("commit");
                }
            } // while !eof

            if (pendingCommitNum > 0) {
                connection.executeCommand("commit");
            }

            //Build up the result
            buffer = new StringBuilder();

            if (errCount > 0) {
                buffer.append("     ");
                buffer.append(recordNum);
                buffer.append(" record(s) processed\n");
            }
            buffer.append("     ");
            buffer.append(recordNum - errCount - rollbackNum - blankCount);
            buffer.append(" record(s) successfully loaded\n");
            if (rollbackNum > 0) {
                buffer.append("     ");
                buffer.append(rollbackNum);
                buffer.append(" record(s) successfully loaded, but rolled back\n");
            }
            if (errCount > 0) {
                buffer.append("     ");
                buffer.append(errCount);
                buffer.append(" record(s) errored\n");
            }
            if (blankCount > 0) {
                buffer.append("     ");
                buffer.append(blankCount);
                buffer.append(" blank record(s) ignored\n");
            }
            Date elapsed = new Date(System.currentTimeMillis() - startTime);
            buffer.append("       Elapsed Time: ");
            buffer.append(dateFormat.print(elapsed.getTime()));
            buffer.append('\n');
            outStream.append(buffer);
            outStream.append('\n');

            // Keep a counter of the total number of errored records.
            totalErrors += errCount;
        } finally {
            if (inputFile != null)
                inputFile.close();
        }
    }

    return totalErrors;
}

From source file:com.thinkbiganalytics.policy.standardization.DateTimeStandardizer.java

License:Apache License

/**
 * Returns a time formatter for the specified timezone
 *
 * @param format   the current formatter
 * @param timezone the timezone string// w w  w .ja va 2s . c o  m
 * @return a time formatter for the specified timezone
 */
protected DateTimeFormatter formatterForTimezone(DateTimeFormatter format, String timezone) {

    if (StringUtils.isEmpty(timezone)) {
        return format;
    }
    if ("UTC".equals(timezone)) {
        return format.withZoneUTC();
    }
    return format.withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone(timezone)));

}

From source file:com.thoughtworks.xstream.core.util.ISO8601JodaTimeConverter.java

License:Open Source License

@Override
public Object fromString(final String str) {
    for (final DateTimeFormatter formatter : formattersUTC) {
        try {//w  w  w . j  a  v a 2  s  .  co  m
            final DateTime dt = formatter.parseDateTime(str);
            final Calendar calendar = dt.toGregorianCalendar();
            calendar.setTimeZone(TimeZone.getDefault());
            return calendar;
        } catch (final IllegalArgumentException e) {
            // try with next formatter
        }
    }
    final DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(TimeZone.getDefault());
    for (final DateTimeFormatter element : formattersNoUTC) {
        try {
            final DateTimeFormatter formatter = element.withZone(dateTimeZone);
            final DateTime dt = formatter.parseDateTime(str);
            final Calendar calendar = dt.toGregorianCalendar();
            calendar.setTimeZone(TimeZone.getDefault());
            return calendar;
        } catch (final IllegalArgumentException e) {
            // try with next formatter
        }
    }
    final ConversionException exception = new ConversionException("Cannot parse date");
    exception.add("date", str);
    throw exception;
}

From source file:com.twitter.elephanttwin.util.DateUtil.java

License:Apache License

/**
 * Returns DateTimeFormatter with specified timezone.
 *///  ww  w .j av  a2  s . c  o m
public static DateTimeFormatter getFormatter(String format, TimeZone timeZone) {
    return DateTimeFormat.forPattern(format).withZone(DateTimeZone.forTimeZone(timeZone));
}