Java Code Examples for java.text.Format

The following examples show how to use java.text.Format. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@Test
public void testToDateWithFormatOnDate() throws Exception {
    long ts = nextTimestamp();
    initPtsdbTableValues(ts);

    String format = "yyyy-MM-dd HH:mm:ss.S";
    Format dateFormatter = DateUtil.getDateFormatter(format);
    String query = "SELECT HOST,TO_CHAR(DATE,'" + format + "') FROM PTSDB WHERE INST='x' AND HOST='y' and DATE=TO_DATE(?,'" + format + "')";
    String url = PHOENIX_JDBC_URL + ";" + PhoenixRuntime.CURRENT_SCN_ATTRIB + "=" + (ts + 5); // Run query at timestamp 5
    Properties props = new Properties(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(url, props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, dateFormatter.format(D1));
        ResultSet rs = statement.executeQuery();
        assertTrue(rs.next());
        assertEquals(dateFormatter.format(D1), rs.getString(2));
    } finally {
        conn.close();
    }
}
 
Example 2
Source Project: RAMPART   Source File: RampartProcess.java    License: GNU General Public License v3.0 6 votes vote down vote up
public RampartProcessArgs(RampartStage stage) {

            super(new Params());

            this.outputDir = new File("");
            this.samples = new ArrayList<>();
            this.threads = DEFAULT_THREADS;
            this.memoryMb = DEFAULT_MEMORY;
            this.runParallel = DEFAULT_RUN_PARALLEL;
            this.stage = stage;
            this.organism = null;

            Format formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
            String dateTime = formatter.format(new Date());
            this.jobPrefix = "rampart-" + stage.getOutputDirName() + "-" + dateTime;
        }
 
Example 3
/**
 *
 */
protected Format getFormat(Object value, TimeZone ownTimeZone)//FIXMEFORMAT optimize this with an interface
{
	Format format = null;

	if (value instanceof java.util.Date)
	{
		format = filler.getDateFormat(getDatePattern(value), ownTimeZone);
	}
	else if (value instanceof java.lang.Number)
	{
		format = filler.getNumberFormat(getNumberPattern(value));
	}
	
	return format;
}
 
Example 4
Source Project: jmeter-plugins   Source File: SynthesisReportGui.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * We use this method to get the data, since we are using
 * ObjectTableModel, so the calling getDataVector doesn't
 * work as expected.
 *
 * @param model   {@link ObjectTableModel}
 * @param formats Array of {@link Format} array can contain null formatters in this case value is added as is
 * @return the data from the model
 */
public static List<List<Object>> getAllTableData(ObjectTableModel model, Format[] formats) {
    List<List<Object>> data = new ArrayList<>();
    if (model.getRowCount() > 0) {
        for (int rw = 0; rw < model.getRowCount(); rw++) {
            int cols = model.getColumnCount();
            List<Object> column = new ArrayList<>();
            data.add(column);
            for (int idx = 0; idx < cols; idx++) {
                Object val = model.getValueAt(rw, idx);
                if (formats[idx] != null) {
                    column.add(formats[idx].format(val));
                } else {
                    column.add(val);
                }
            }
        }
    }
    return data;
}
 
Example 5
Source Project: phoenix   Source File: PArrayDataType.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String toStringLiteral(Object o, Format formatter) {
    StringBuilder buf = new StringBuilder(PArrayDataType.ARRAY_TYPE_SUFFIX + "[");
    PhoenixArray array = (PhoenixArray)o;
    PDataType baseType = PDataType.arrayBaseType(this);
    int len = array.getDimensions();
    if (len != 0)  {
        for (int i = 0; i < len; i++) {
            buf.append(baseType.toStringLiteral(array.getElement(i), null));
            buf.append(',');
        }
        buf.setLength(buf.length()-1);
    }
    buf.append(']');
    return buf.toString();
}
 
Example 6
Source Project: astor   Source File: ExtendedMessageFormat.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get a custom format from a format description.
 * 
 * @param desc String
 * @return Format
 */
private Format getFormat(String desc) {
    if (registry != null) {
        String name = desc;
        String args = null;
        int i = desc.indexOf(START_FMT);
        if (i > 0) {
            name = desc.substring(0, i).trim();
            args = desc.substring(i + 1).trim();
        }
        FormatFactory factory = registry.get(name);
        if (factory != null) {
            return factory.getFormat(name, args, getLocale());
        }
    }
    return null;
}
 
Example 7
/**
 * @param encodedCert
 * @return
 * @throws CertificateException
 */
public static CertData getCertData(String encodedCert) throws CertificateException {

    if (encodedCert != null) {
        byte[] bytes = Base64.decode(encodedCert);
        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) factory
                .generateCertificate(new ByteArrayInputStream(bytes));
        Format formatter = new SimpleDateFormat("dd/MM/yyyy");
        return fillCertData(cert, formatter);
    } else {
        String errorMsg = "Invalid encoded certificate: \'NULL\'";
        log.debug(errorMsg);
        throw new IllegalArgumentException(errorMsg);
    }
}
 
Example 8
Source Project: coming   Source File: Arja_0096_t.java    License: MIT License 6 votes vote down vote up
/**
 * Get a custom format from a format description.
 * 
 * @param desc String
 * @return Format
 */
private Format getFormat(String desc) {
    if (registry != null) {
        String name = desc;
        String args = null;
        int i = desc.indexOf(START_FMT);
        if (i > 0) {
            name = desc.substring(0, i).trim();
            args = desc.substring(i + 1).trim();
        }
        FormatFactory factory = (FormatFactory) registry.get(name);
        if (factory != null) {
            return factory.getFormat(name, args, getLocale());
        }
    }
    return null;
}
 
Example 9
/**
 * Adds an array of exceptions relative to the base timeline.
 *
 * @param timeline The timeline where the exceptions will be stored
 * @param exceptionString The exceptions to load
 * @param fmt The date formatter to use to parse each exceptions[i] value
 * @throws ParseException If there is any exception parsing each
 *                        exceptions[i] value.
 */
private void fillInBaseTimelineExceptions(SegmentedTimeline timeline,
                                         String[] exceptionString,
                                         Format fmt) throws ParseException {
    SegmentedTimeline baseTimeline = timeline.getBaseTimeline();
    for (int i = 0; i < exceptionString.length; i++) {
        long e;
        if (fmt instanceof NumberFormat) {
            e = ((NumberFormat) fmt).parse(exceptionString[i]).longValue();
        }
        else {
            e = timeline.getTime(((SimpleDateFormat) fmt)
                    .parse(exceptionString[i]));
        }
        timeline.addBaseTimelineException(e);

        // verify all timeline segments included in the
        // baseTimeline.segment are now exceptions
        SegmentedTimeline.Segment segment1 = baseTimeline.getSegment(e);
        for (SegmentedTimeline.Segment segment2
                = timeline.getSegment(segment1.getSegmentStart());
             segment2.getSegmentStart() <= segment1.getSegmentEnd();
             segment2.inc()) {
            if (!segment2.inExcludeSegments()) {
                assertTrue(segment2.inExceptionSegments());
            }
        }

    }
}
 
Example 10
@Test
public void test_toFormat_parseObject_StringParsePosition() throws Exception {
    DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    Format format = test.toFormat();
    ParsePosition pos = new ParsePosition(0);
    TemporalAccessor result = (TemporalAccessor) format.parseObject("ONE30XXX", pos);
    assertEquals(pos.getIndex(), 5);
    assertEquals(pos.getErrorIndex(), -1);
    assertEquals(result.isSupported(DAY_OF_MONTH), true);
    assertEquals(result.getLong(DAY_OF_MONTH), 30L);
}
 
Example 11
@SuppressWarnings("unchecked")
public PhoenixConnection(ConnectionQueryServices services, String url, Properties info, PMetaData metaData) throws SQLException {
    this.url = url;
    // Copy so client cannot change
    this.info = info == null ? new Properties() : new Properties(info);
    if (this.info.isEmpty()) {
        this.services = services;
    } else {
        Map<String, String> existingProps = services.getProps().asMap();
        Map<String, String> tmpAugmentedProps = Maps.newHashMapWithExpectedSize(existingProps.size() + info.size());
        tmpAugmentedProps.putAll(existingProps);
        tmpAugmentedProps.putAll((Map)this.info);
        final ReadOnlyProps augmentedProps = new ReadOnlyProps(tmpAugmentedProps);
        this.services = new DelegateConnectionQueryServices(services) {

            @Override
            public ReadOnlyProps getProps() {
                return augmentedProps;
            }
        };
    }
    this.scn = JDBCUtil.getCurrentSCN(url, this.info);
    this.tenantId = JDBCUtil.getTenantId(url, this.info);
    this.mutateBatchSize = JDBCUtil.getMutateBatchSize(url, this.info, services.getProps());
    datePattern = services.getProps().get(QueryServices.DATE_FORMAT_ATTRIB, DateUtil.DEFAULT_DATE_FORMAT);
    int maxSize = services.getProps().getInt(QueryServices.MAX_MUTATION_SIZE_ATTRIB,QueryServicesOptions.DEFAULT_MAX_MUTATION_SIZE);
    Format dateTimeFormat = DateUtil.getDateFormatter(datePattern);
    formatters[PDataType.DATE.ordinal()] = dateTimeFormat;
    formatters[PDataType.TIME.ordinal()] = dateTimeFormat;
    this.metaData = PMetaDataImpl.pruneMultiTenant(metaData);
    this.mutationState = new MutationState(maxSize, this);
    services.addConnection(this);
}
 
Example 12
Source Project: j2objc   Source File: TCKDateTimeFormatter.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_toFormat_parseObject_StringParsePosition() throws Exception {
    DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    Format format = test.toFormat();
    ParsePosition pos = new ParsePosition(0);
    TemporalAccessor result = (TemporalAccessor) format.parseObject("ONE30XXX", pos);
    assertEquals(pos.getIndex(), 5);
    assertEquals(pos.getErrorIndex(), -1);
    assertEquals(result.isSupported(DAY_OF_MONTH), true);
    assertEquals(result.getLong(DAY_OF_MONTH), 30L);
}
 
Example 13
Source Project: MergeProcessor   Source File: LogFileHandler.java    License: Apache License 2.0 5 votes vote down vote up
private static String getPattern() {
	final Date date = new Date();
	final Format fileDateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
	final String pathLogFileFolder = Configuration.getPathLogFileFolder();
	final Path logFileFolder = Paths.get(pathLogFileFolder);
	if (Files.notExists(logFileFolder)) {
		try {
			Files.createDirectories(logFileFolder);
		} catch (IOException e) {
			Logger.getLogger(LogFileHandler.class.getName()).log(Level.SEVERE, "Could not create log file folder",
					e);
		}
	}
	return pathLogFileFolder + "mp_" + fileDateFormat.format(date) + ".log";
}
 
Example 14
private static void checkSubformat(Format[] subformats, int index, Format expected) {
    Format subformat = subformats[index];
    if (subformat == expected) {
        return;
    }
    if ((subformat != null) && subformat.equals(expected)) {
        return;
    }
    throw new RuntimeException("found unexpected subformat for argument " + index + ":\n expected: " + expected + "\n   actual: " + subformat);
}
 
Example 15
Source Project: jdk8u60   Source File: TCKDateTimeFormatter.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_toFormat_parseObject_StringParsePosition_nullString() throws Exception {
    // SimpleDateFormat has this behavior
    DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    Format format = test.toFormat();
    ParsePosition pos = new ParsePosition(0);
    format.parseObject((String) null, pos);
}
 
Example 16
@Test
public void test_toFormat_parseObject_String() throws Exception {
    DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    Format format = test.toFormat();
    TemporalAccessor result = (TemporalAccessor) format.parseObject("ONE30");
    assertEquals(result.isSupported(DAY_OF_MONTH), true);
    assertEquals(result.getLong(DAY_OF_MONTH), 30L);
}
 
Example 17
Source Project: seaglass   Source File: SeaGlassTableUI.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * DOCUMENT ME!
 *
 * @param value       DOCUMENT ME!
 * @param columnClass DOCUMENT ME!
 */
private void configureValue(Object value, Class columnClass) {
    if (columnClass == Object.class || columnClass == null) {
        setHorizontalAlignment(JLabel.LEADING);
    } else if (columnClass == Float.class || columnClass == Double.class) {
        if (numberFormat == null) {
            numberFormat = NumberFormat.getInstance();
        }

        setHorizontalAlignment(JLabel.TRAILING);
        setText((value == null) ? "" : ((NumberFormat) numberFormat).format(value));
    } else if (columnClass == Number.class) {
        setHorizontalAlignment(JLabel.TRAILING);
        // Super will have set value.
    } else if (columnClass == Icon.class || columnClass == ImageIcon.class) {
        setHorizontalAlignment(JLabel.CENTER);
        setIcon((value instanceof Icon) ? (Icon) value : null);
        setText("");
    } else if (columnClass == Date.class) {
        if (dateFormat == null) {
            dateFormat = DateFormat.getDateInstance();
        }

        setHorizontalAlignment(JLabel.LEADING);
        setText((value == null) ? "" : ((Format) dateFormat).format(value));
    } else {
        configureValue(value, columnClass.getSuperclass());
    }
}
 
Example 18
@Test
public void test_toFormat_parseObject_StringParsePosition_parseError() throws Exception {
    DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    Format format = test.toFormat();
    ParsePosition pos = new ParsePosition(0);
    TemporalAccessor result = (TemporalAccessor) format.parseObject("ONEXXX", pos);
    assertEquals(pos.getIndex(), 0);  // TODO: is this right?
    assertEquals(pos.getErrorIndex(), 3);
    assertEquals(result, null);
}
 
Example 19
Source Project: hop   Source File: ScriptValuesAddedFunctions.java    License: Apache License 2.0 5 votes vote down vote up
public static Object getFiscalDate( Context actualContext, Scriptable actualObject, Object[] ArgList,
                                    Function FunctionContext ) {

  if ( ArgList.length == 2 ) {
    try {
      if ( isNull( ArgList ) ) {
        return null;
      } else if ( isUndefined( ArgList ) ) {
        return Context.getUndefinedValue();
      }
      Date dIn = (Date) Context.jsToJava( ArgList[ 0 ], Date.class );
      Calendar startDate = Calendar.getInstance();
      Calendar fisStartDate = Calendar.getInstance();
      Calendar fisOffsetDate = Calendar.getInstance();
      startDate.setTime( dIn );
      Format dfFormatter = new SimpleDateFormat( "dd.MM.yyyy" );
      String strOffsetDate = Context.toString( ArgList[ 1 ] ) + String.valueOf( startDate.get( Calendar.YEAR ) );
      Date dOffset = (Date) dfFormatter.parseObject( strOffsetDate );
      fisOffsetDate.setTime( dOffset );

      String strFisStartDate = "01.01." + String.valueOf( startDate.get( Calendar.YEAR ) + 1 );
      fisStartDate.setTime( (Date) dfFormatter.parseObject( strFisStartDate ) );
      int iDaysToAdd = (int) ( ( startDate.getTimeInMillis() - fisOffsetDate.getTimeInMillis() ) / 86400000 );
      fisStartDate.add( Calendar.DATE, iDaysToAdd );
      return fisStartDate.getTime();
    } catch ( Exception e ) {
      throw Context.reportRuntimeError( e.toString() );
    }
  } else {
    throw Context.reportRuntimeError( "The function call getFiscalDate requires 2 arguments." );
  }

}
 
Example 20
@Test
public void test_toFormat_parseObject_StringParsePosition_parseError() throws Exception {
    DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    Format format = test.toFormat();
    ParsePosition pos = new ParsePosition(0);
    TemporalAccessor result = (TemporalAccessor) format.parseObject("ONEXXX", pos);
    assertEquals(pos.getIndex(), 0);  // TODO: is this right?
    assertEquals(pos.getErrorIndex(), 3);
    assertEquals(result, null);
}
 
Example 21
public FormattedContentToken( final Object original,
                              final Format format,
                              final String text ) {
  this.format = format;
  this.original = original;
  this.text = text;
}
 
Example 22
Source Project: phoenix   Source File: PDataType.java    License: Apache License 2.0 5 votes vote down vote up
public String toStringLiteral(Object o, Format formatter) {
    if (o == null) {
        return String.valueOf(o);
    }
    if (formatter != null) {
        return formatter.format(o);
    }
    return o.toString();
}
 
Example 23
@Test
public void test_toFormat_parseObject_StringParsePosition_invalidPosition_tooSmall() throws Exception {
    // SimpleDateFormat throws StringIndexOutOfBoundException
    DateTimeFormatter dtf = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    ParsePosition pos = new ParsePosition(-1);
    Format test = dtf.toFormat();
    assertNull(test.parseObject("ONE30", pos));
    assertTrue(pos.getErrorIndex() >= 0);
}
 
Example 24
Source Project: Carbon   Source File: TableView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void bindView(TextView view, Integer value, Format format) {
    if (format != null) {
        view.setText(format.format(value));
    } else {
        view.setText(value);
    }
}
 
Example 25
Source Project: astor   Source File: SegmentedTimelineTests.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests methods related to adding exceptions.
 *
 * @param timeline the timeline to verify
 * @param exceptionString array of Strings that represent the exceptions
 * @param fmt Format object that can parse the exceptionString strings
 *
 * @throws ParseException if there is a parsing error.
 */
public void verifyExceptionSegments(SegmentedTimeline timeline,
                                    String[] exceptionString,
                                    Format fmt)
    throws ParseException {

    // fill in the exceptions
    long[] exception = verifyFillInExceptions(timeline, exceptionString,
            fmt);

    int m = exception.length;

    // verify list of exceptions
    assertEquals(exception.length, timeline.getExceptionSegments().size());
    SegmentedTimeline.Segment lastSegment = timeline.getSegment(
            exception[m - 1]);
    for (int i = 0; i < m; i++) {
        SegmentedTimeline.Segment segment = timeline.getSegment(
                exception[i]);
        assertTrue(segment.inExceptionSegments());
        // include current exception and last one
        assertEquals(m - i, timeline.getExceptionSegmentCount(
                segment.getSegmentStart(), lastSegment.getSegmentEnd()));
        // exclude current exception and last one
        assertEquals(Math.max(0, m - i - 2),
                timeline.getExceptionSegmentCount(exception[i] + 1,
                exception[m - 1] - 1));
    }

}
 
Example 26
private static void checkSubformat(Format[] subformats, int index, Format expected) {
    Format subformat = subformats[index];
    if (subformat == expected) {
        return;
    }
    if ((subformat != null) && subformat.equals(expected)) {
        return;
    }
    throw new RuntimeException("found unexpected subformat for argument " + index + ":\n expected: " + expected + "\n   actual: " + subformat);
}
 
Example 27
@Test
public void test_toFormat_parseObject_StringParsePosition_invalidPosition_tooSmall() throws Exception {
    // SimpleDateFormat throws StringIndexOutOfBoundException
    DateTimeFormatter dtf = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    ParsePosition pos = new ParsePosition(-1);
    Format test = dtf.toFormat();
    assertNull(test.parseObject("ONE30", pos));
    assertTrue(pos.getErrorIndex() >= 0);
}
 
Example 28
@Test(expectedExceptions=NullPointerException.class)
public void test_toFormat_parseObject_StringParsePosition_nullParsePosition() throws Exception {
    // SimpleDateFormat has this behavior
    DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    Format format = test.toFormat();
    format.parseObject("ONE30", (ParsePosition) null);
}
 
Example 29
@Test(expectedExceptions=NullPointerException.class)
public void test_toFormat_parseObject_StringParsePosition_nullParsePosition() throws Exception {
    // SimpleDateFormat has this behavior
    DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    Format format = test.toFormat();
    format.parseObject("ONE30", (ParsePosition) null);
}
 
Example 30
Source Project: orson-charts   Source File: LogAxis3D.java    License: GNU General Public License v3.0 5 votes vote down vote up
private AttributedString createTickLabelAttributedString(double logy, 
        Format exponentFormatter) {
    String baseStr = this.baseSymbol;
    if (baseStr == null) {
        baseStr = this.baseFormatter.format(this.base);
    }
    String exponentStr = exponentFormatter.format(logy);
    AttributedString as = new AttributedString(baseStr + exponentStr);
    as.addAttributes(getTickLabelFont().getAttributes(), 0, (baseStr 
            + exponentStr).length());
    as.addAttribute(TextAttribute.SUPERSCRIPT, 
            TextAttribute.SUPERSCRIPT_SUPER, baseStr.length(), 
            baseStr.length() + exponentStr.length());
    return as;   
}