Example usage for org.joda.time.format DateTimeFormatter print

List of usage examples for org.joda.time.format DateTimeFormatter print

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter print.

Prototype

public String print(ReadablePartial partial) 

Source Link

Document

Prints a ReadablePartial to a new String.

Usage

From source file:com.quinsoft.zeidon.vml.VmlOperation.java

License:Open Source License

protected int UfFormatDateTime(StringBuilder sbDayOfWeek, String szDate, String strFormat) {
    //TODO: This is slow.  Do we need to improve it?
    DateTime date = JoeUtils.parseStandardDateString(szDate);
    String javaFormat = JoeUtils.convertZeidonDateFormatToJavaFormat(strFormat);
    DateTimeFormatter formatter = DateTimeFormat.forPattern(javaFormat);
    sbDayOfWeek.append(formatter.print(date));
    return 0;/* w  w  w . ja va  2  s . c om*/
}

From source file:com.rappsantiago.weighttracker.util.DisplayUtil.java

License:Apache License

public static String getReadableDate(long dateInMillis) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM dd, yyyy");
    return formatter.print(dateInMillis);
}

From source file:com.rappsantiago.weighttracker.util.DisplayUtil.java

License:Apache License

public static String getReadableDateNoYear(long dateInMillis) {
    DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM dd");
    return formatter.print(dateInMillis);
}

From source file:com.reveldigital.api.util.DateTypeFormatter.java

License:Apache License

public JsonElement serialize(Date date, Type type, JsonSerializationContext context) {
    final DateTimeFormatter primary = formats[0];
    String formatted;//from  ww  w  .j  a v  a2s.com
    synchronized (primary) {
        formatted = primary.print(new DateTime(date));
    }
    return new JsonPrimitive(formatted);
}

From source file:com.rhythm.swagr.SwagrDAO.java

License:Apache License

private String utcToString(long dt) {
    DateTime jodadt = new DateTime(dt * 1000);
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
    return fmt.print(jodadt);
}

From source file:com.rusticisoftware.tincan.internal.StatementBase.java

License:Apache License

@Override
public ObjectNode toJSONNode(TCAPIVersion version) {
    ObjectNode node = Mapper.getInstance().createObjectNode();
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime().withZoneUTC();

    node.put("actor", this.getActor().toJSONNode(version));
    node.put("verb", this.getVerb().toJSONNode(version));
    node.put("object", this.getObject().toJSONNode(version));

    if (this.result != null) {
        node.put("result", this.getResult().toJSONNode(version));
    }/*from   ww  w. java 2  s .  c o m*/
    if (this.context != null) {
        node.put("context", this.getContext().toJSONNode(version));
    }
    if (this.timestamp != null) {
        node.put("timestamp", fmt.print(this.getTimestamp()));
    }

    //Include 1.0.x specific fields if asking for 1.0.x version
    if (version.ordinal() <= TCAPIVersion.V100.ordinal()) {
        if (this.getAttachments() != null && this.getAttachments().size() > 0) {
            ArrayNode attachmentsNode = Mapper.getInstance().createArrayNode();
            for (Attachment attachment : this.getAttachments()) {
                attachmentsNode.add(attachment.toJSONNode(version));
            }
            node.put("attachments", attachmentsNode);
        }
    }

    return node;
}

From source file:com.rusticisoftware.tincan.Statement.java

License:Apache License

@Override
public ObjectNode toJSONNode(TCAPIVersion version) {
    ObjectNode node = super.toJSONNode(version);
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime().withZoneUTC();

    if (this.id != null) {
        node.put("id", this.getId().toString());
    }/*  ww w . ja  v a  2 s .co m*/
    if (this.stored != null) {
        node.put("stored", fmt.print(this.getStored()));
    }
    if (this.authority != null) {
        node.put("authority", this.getAuthority().toJSONNode(version));
    }

    //Include 0.95 specific fields if asking for 0.95 version
    if (TCAPIVersion.V095.equals(version)) {
        if (this.getVoided() != null) {
            node.put("voided", this.getVoided());
        }
    }

    //Include 1.0.x specific fields if asking for 1.0.x version
    if (version.ordinal() <= TCAPIVersion.V100.ordinal()) {
        if (this.getVersion() != null) {
            node.put("version", this.getVersion().toString());
        }
    }

    return node;
}

From source file:com.rusticisoftware.tincan.v095.StatementsQuery.java

License:Apache License

public HashMap<String, String> toParameterMap() throws IOException {
    HashMap<String, String> params = new HashMap<String, String>();
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime().withZoneUTC();

    if (this.getVerbID() != null) {
        params.put("verb", this.getVerbID().toString());
    }//  ww w.  j  a v a  2  s. c o  m
    if (this.getObject() != null) {
        params.put("object", this.getObject().toJSON(version));
    }
    if (this.getRegistration() != null) {
        params.put("registration", this.getRegistration().toString());
    }
    if (this.getContext() != null) {
        params.put("context", this.getContext().toString());
    }
    if (this.getActor() != null) {
        params.put("actor", this.getActor().toJSON(version));
    }
    if (this.getSince() != null) {
        params.put("since", fmt.print(this.getSince()));
    }
    if (this.getUntil() != null) {
        params.put("until", fmt.print(this.getUntil()));
    }
    if (this.getLimit() != null) {
        params.put("limit", this.getLimit().toString());
    }
    if (this.getAuthoritative() != null) {
        params.put("authoritative", this.getAuthoritative().toString());
    }
    if (this.getSparse() != null) {
        params.put("sparse", this.getSparse().toString());
    }
    if (this.getInstructor() != null) {
        params.put("instructor", this.getInstructor().toJSON(version));
    }
    if (this.getAscending() != null) {
        params.put("ascending", this.getAscending().toString());
    }

    return params;
}

From source file:com.rusticisoftware.tincan.v10x.StatementsQuery.java

License:Apache License

public HashMap<String, String> toParameterMap() throws IOException {
    HashMap<String, String> params = new HashMap<String, String>();
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime().withZoneUTC();

    if (this.getAgent() != null) {
        params.put("agent", this.getAgent().toJSON(version));
    }/*from w ww  . j  av  a  2 s .c  o  m*/
    if (this.getVerbID() != null) {
        params.put("verb", this.getVerbID().toString());
    }
    if (this.getActivityID() != null) {
        params.put("activity", this.getActivityID().toString());
    }
    if (this.getRegistration() != null) {
        params.put("registration", this.getRegistration().toString());
    }
    if (this.getRelatedActivities() != null) {
        params.put("related_activities", this.getRelatedActivities().toString());
    }
    if (this.getRelatedAgents() != null) {
        params.put("related_agents", this.getRelatedAgents().toString());
    }
    if (this.getSince() != null) {
        params.put("since", fmt.print(this.getSince()));
    }
    if (this.getUntil() != null) {
        params.put("until", fmt.print(this.getUntil()));
    }
    if (this.getLimit() != null) {
        params.put("limit", this.getLimit().toString());
    }
    if (this.getFormat() != null) {
        params.put("format", this.getFormat().toString().toLowerCase());
    }
    if (this.getAscending() != null) {
        params.put("ascending", this.getAscending().toString());
    }

    if (this.getAttachments() != null) {
        params.put("attachments", this.getAttachments().toString());
    }

    return params;
}

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

License:Open Source License

/**
 * Processes a control file/*from   w  w w .  jav 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;
}