java.text.Format Java Examples

The following examples show how to use java.text.Format. 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 check out the related API usage on the sidebar.
Example #1
Source File: VariableLengthPKTest.java    From phoenix with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
@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 File: IdentityApplicationManagementUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @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 #3
Source File: PArrayDataType.java    From phoenix with 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 #4
Source File: ExtendedMessageFormat.java    From astor with 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 #5
Source File: RampartProcess.java    From RAMPART with 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 #6
Source File: SynthesisReportGui.java    From jmeter-plugins with 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 #7
Source File: JRFillTextField.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 *
 */
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 #8
Source File: Arja_0096_t.java    From coming with 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
Source File: LogFileHandler.java    From MergeProcessor with 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 #10
Source File: MessageFormatsByArgumentIndex.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
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 #11
Source File: LogAxis3D.java    From orson-charts with 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;   
}
 
Example #12
Source File: TCKDateTimeFormatter.java    From openjdk-8 with GNU General Public License v2.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 File: TestDateTimeFormatter.java    From threetenbp with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 #14
Source File: PhoenixConnection.java    From phoenix with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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 #15
Source File: TCKDateTimeFormatter.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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 #16
Source File: TCKDateTimeFormatter.java    From j2objc with 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 #17
Source File: TCKDateTimeFormatter.java    From jdk8u60 with 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 #18
Source File: SegmentedTimelineTest.java    From openstock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 #19
Source File: XDataFrameLeastSquares.java    From morpheus-core with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    this.computeIf();
    final int n = frame.rows().count();
    final int p = regressors.size() + 1;
    final int dfModel = regressors.size();
    final DataFrame<Object,Field> summary = getSummary();
    final String table = toText(100, summary);
    final int totalWidth = table.trim().split("\n")[1].length();
    final int cellWidth = (totalWidth - 4) / 4;
    final String title = "Linear Regression Results";
    final Format sciFormat = new DecimalFormat("0.###E0;-0.###E0");
    final String template = "%-" + cellWidth + "s%" + cellWidth + "s    %-" + cellWidth + "s%" + cellWidth + "s";

    final StringBuilder text = new StringBuilder();
    text.append("\n").append(lineOf('=', totalWidth));
    text.append("\n");
    text.append(lineOf(' ', (totalWidth / 2) - (title.length() / 2)));
    text.append(title);
    text.append(lineOf(' ', totalWidth - (totalWidth / 2) - (title.length() / 2) + title.length()));
    text.append("\n").append(lineOf('=', totalWidth));
    text.append("\n").append(String.format(template, "Model:", name, "R-Squared:", String.format("%.4f", getRSquared())));
    text.append("\n").append(String.format(template, "Observations:", n, "R-Squared(adjusted):", String.format("%.4f", getRSquaredAdj())));
    text.append("\n").append(String.format(template, "DF Model:", dfModel, "F-Statistic:", String.format("%.4f", getFValue())));
    text.append("\n").append(String.format(template, "DF Residuals:", n - p, "F-Statistic(Prob):", sciFormat.format(getFValueProbability())));
    text.append("\n").append(String.format(template, "Standard Error:", String.format("%.4f", getStdError()), "Runtime(millis)", runtimeMillis));
    text.append("\n").append(String.format(template, "Durbin-Watson:", String.format("%.4f", getDurbinWatsonStatistic()), "", ""));
    text.append("\n").append(lineOf('=', totalWidth));
    text.append(table);
    text.append("\n").append(lineOf('=', totalWidth));
    return text.toString();
}
 
Example #20
Source File: SeaGlassTableUI.java    From seaglass with 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 #21
Source File: TCKDateTimeFormatter.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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 #22
Source File: ScriptValuesAddedFunctions.java    From hop with 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 #23
Source File: TCKDateTimeFormatter.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@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 #24
Source File: TCKDateTimeFormatter.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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 #25
Source File: FormattedContentToken.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public FormattedContentToken( final Object original,
                              final Format format,
                              final String text ) {
  this.format = format;
  this.original = original;
  this.text = text;
}
 
Example #26
Source File: PDataType.java    From phoenix with 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 #27
Source File: TCKDateTimeFormatter.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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
Source File: MessageFormatsByArgumentIndex.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
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 #29
Source File: TableView.java    From Carbon with 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 #30
Source File: SegmentedTimelineTests.java    From astor with 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));
    }

}