Java Code Examples for java.text.Format

The following are top voted examples for showing how to use java.text.Format. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: FormatSelector.java   View source code 6 votes vote down vote up
/**
 * Returns format's pattern. 
 * 
 * @return format's pattern.
 */
public String getFormat() {
    if (format != null) return format;
    String fmt = null;
    if (formatter instanceof MaskFormatter) {
        fmt = ((MaskFormatter)formatter).getMask();
    } else if (formatter instanceof InternationalFormatter) {
        Format f = ((InternationalFormatter)formatter).getFormat();
        if (f instanceof DecimalFormat) {
            fmt = ((DecimalFormat)f).toPattern();
        } else if (f instanceof SimpleDateFormat) {
            fmt = ((SimpleDateFormat)f).toPattern();
        }
    }
    return fmt;
}
 
Example 2
Project: incubator-netbeans   File: PercentRenderer.java   View source code 6 votes vote down vote up
protected String getValueString(Object value, int row, Format format) {
    if (value == null) return "-"; // NOI18N
    
    StringBuilder s = new StringBuilder();
    s.append("("); // NOI18N
    
    if (maxValue == 0) {
        s.append(NAN);
    } else {
        double number = ((Number)value).doubleValue();
        if (number == 0) {
            if (renderingDiff) s.append('+'); // NOI18N
            s.append(NUL);
        } else {
            number = number / maxValue;
            if (renderingDiff && number > 0) s.append('+'); // NOI18N
            s.append(format.format(number));
        }
    }
    
    s.append(")"); // NOI18N
    return s.toString();
}
 
Example 3
Project: Automekanik   File: ShikoPunetoret.java   View source code 6 votes vote down vote up
public void mbushPunetoret(){
    try {
        String sql = "select * from Punetoret";
        Connection conn = DriverManager.getConnection(CON_STR, "test", "test");
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        ObservableList<TabelaPunetoret> data = FXCollections.observableArrayList();
        Format format = new SimpleDateFormat("dd/MM/yyyy");
        while (rs.next()){
            String s = format.format(rs.getDate("regjistrimi"));
            data.add(new TabelaPunetoret(rs.getInt("id"), rs.getString("emri"),
                    rs.getString("mbiemri"), rs.getString("komuna"), rs.getString("pozita"),
                    s, rs.getFloat("paga")));
        }

        table.setItems(data);
        conn.close();
    }catch (Exception ex){ex.printStackTrace();}
}
 
Example 4
Project: ipack   File: LocalizedMessage.java   View source code 6 votes vote down vote up
protected String formatWithTimeZone(
        String template,
        Object[] arguments, 
        Locale locale,
        TimeZone timezone) 
{
    MessageFormat mf = new MessageFormat(" ");
    mf.setLocale(locale);
    mf.applyPattern(template);
    if (!timezone.equals(TimeZone.getDefault())) 
    {
        Format[] formats = mf.getFormats();
        for (int i = 0; i < formats.length; i++) 
        {
            if (formats[i] instanceof DateFormat) 
            {
                DateFormat temp = (DateFormat) formats[i];
                temp.setTimeZone(timezone);
                mf.setFormat(i,temp);
            }
        }
    }
    return mf.format(arguments);
}
 
Example 5
Project: plugin-scm   File: AbstractIndexBasedPluginResource.java   View source code 6 votes vote down vote up
/**
 * Find the repositories matching to the given criteria.Look into name only.
 * 
 * @param criteria
 *            the search criteria.
 * @param node
 *            the node to be tested with given parameters.
 * @return project name.
 */
@GET
@Path("{node}/{criteria}")
@Consumes(MediaType.APPLICATION_JSON)
public List<NamedBean<String>> findAllByName(@PathParam("node") final String node, @PathParam("criteria") final String criteria) {
	final Map<String, String> parameters = pvResource.getNodeParameters(node);
	final CurlRequest request = new CurlRequest(HttpMethod.GET, StringUtils.appendIfMissing(parameters.get(parameterUrl), "/"), null);
	request.setSaveResponse(true);
	newCurlProcessor(parameters).process(request);

	// Prepare the context, an ordered set of projects
	final Format format = new NormalizeFormat();
	final String formatCriteria = format.format(criteria);

	// Limit the result
	return inMemoryPagination.newPage(
			Arrays.stream(StringUtils.splitByWholeSeparator(StringUtils.defaultString(request.getResponse()), "<a href=\"")).skip(1)
					.filter(s -> format.format(s).contains(formatCriteria))
					.map(s -> StringUtils.removeEnd(s.substring(0, Math.max(0, s.indexOf('\"'))), "/"))
					.filter(((Predicate<String>) String::isEmpty).negate()).map(id -> new NamedBean<>(id, id)).collect(Collectors.toList()),
					PageRequest.of(0, 10)).getContent();
}
 
Example 6
Project: csap-core   File: HostRequests.java   View source code 6 votes vote down vote up
/**
 * du can be relatively expensive - we will cache almost always timers will
 * be reset in case of operation
 */
@RequestMapping ( "/getCpu" )
public ObjectNode getCpu (
							@RequestParam ( value = "filter" , defaultValue = "yes" , required = false ) String compressedFormat,
							HttpServletResponse response )
		throws IOException {

	logger.debug( "compressedFormat: {}", compressedFormat );

	response.setContentType( MediaType.APPLICATION_JSON_VALUE );

	ObjectNode serviceMetricsJson = osManager.getServiceMetrics( compressedFormat.equals( "yes" ) );

	Format tsFormater = new SimpleDateFormat( "HH.mm.ss" );
	// JsonNode rootNode = jacksonMapper.valueToTree(commandMap);
	((ObjectNode) serviceMetricsJson).put( "timestamp", tsFormater.format( new Date() ) );

	return serviceMetricsJson;

}
 
Example 7
Project: Automekanik   File: TeDhenat.java   View source code 6 votes vote down vote up
private void filtro(){
    try {
        String sql;
        if (!txtPuna.getText().isEmpty())
            sql = "select * from Punet where konsumatori = '" + e.getText() + "' and lower(lloji) like lower('%" + txtPuna.getText() + "%')";
        else
            sql = "select * from Punet where konsumatori = '" + e.getText() + "'";

        Connection conn = DriverManager.getConnection(CON_STR, "test", "test");
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        ObservableList<punetTbl> data = FXCollections.observableArrayList();
        Format format = new SimpleDateFormat("dd/MM/yyyy");
        String s = "";
        while (rs.next()){
            s = format.format(rs.getDate("data"));
            data.add(new punetTbl(rs.getInt("id"), rs.getString("lloji"),
                    s, rs.getFloat("qmimi"), rs.getString("pershkrimi"), rs.getString("kryer"), rs.getString("makina")));
        }
        table.setItems(data);
        conn.close();
    }catch (Exception ex){
        ex.printStackTrace();
    }
}
 
Example 8
Project: fitnotifications   File: MessageFormat.java   View source code 6 votes vote down vote up
/**
 * {@icu} Returns the first top-level format associated with the given argument name.
 * For more details, see {@link #setFormatByArgumentName(String, Format)}.
 * @param argumentName The name of the desired argument.
 * @return the Format associated with the name, or null if there isn't one.
 * @stable ICU 4.8
 */
public Format getFormatByArgumentName(String argumentName) {
    if (cachedFormatters == null) {
        return null;
    }
    int argNumber = MessagePattern.validateArgumentName(argumentName);
    if (argNumber < MessagePattern.ARG_NAME_NOT_NUMBER) {
        return null;
    }
    for (int partIndex = 0; (partIndex = nextTopLevelArgStart(partIndex)) >= 0;) {
        if (argNameMatches(partIndex + 1, argumentName, argNumber)) {
            return cachedFormatters.get(partIndex);
        }
    }
    return null;
}
 
Example 9
Project: Automekanik   File: ShikoPunetPunetoret.java   View source code 6 votes vote down vote up
public void mbush(String emri){
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String sql = "select * from Punet where punetori = '" + emri + "' order by id asc";
                Connection conn = DriverManager.getConnection(CON_STR, "test", "test");
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
                ObservableList<TabelaTeDhenatPunetore> data = FXCollections.observableArrayList();
                Format format = new SimpleDateFormat("dd/MM/yyyy");
                String s = "";
                while (rs.next()) {
                    s = format.format(rs.getDate("data"));
                    data.add(new TabelaTeDhenatPunetore(rs.getInt("id"), rs.getString("lloji"), s,
                            rs.getFloat("qmimi"), rs.getString("konsumatori"), rs.getString("pershkrimi"), rs.getString("kryer"), rs.getString("makina")));
                }

                rs.close();
                stmt.close();
                conn.close();
                table.setItems(data);
            }catch (Exception ex){ex.printStackTrace();}
        }
    });
    t.start();
}
 
Example 10
Project: Equella   File: FlatterSpinnerUI.java   View source code 6 votes vote down vote up
/**
 * Returns the calendarField under the start of the selection, or -1 if
 * there is no valid calendar field under the selection (or the spinner
 * isn't editing dates.
 */
private int getCalendarField(JSpinner spinner)
{
	JComponent editor = spinner.getEditor();

	if( editor instanceof JSpinner.DateEditor )
	{
		JSpinner.DateEditor dateEditor = (JSpinner.DateEditor) editor;
		JFormattedTextField ftf = dateEditor.getTextField();
		int start = ftf.getSelectionStart();
		JFormattedTextField.AbstractFormatter formatter = ftf.getFormatter();

		if( formatter instanceof InternationalFormatter )
		{
			Format.Field[] fields = ((InternationalFormatter) formatter).getFields(start);

			for( int counter = 0; counter < fields.length; counter++ )
			{
				if( fields[counter] instanceof DateFormat.Field )
				{
					int calendarField;

					if( fields[counter] == DateFormat.Field.HOUR1 )
					{
						calendarField = Calendar.HOUR;
					}
					else
					{
						calendarField = ((DateFormat.Field) fields[counter]).getCalendarField();
					}
					if( calendarField != -1 )
					{
						return calendarField;
					}
				}
			}
		}
	}
	return -1;
}
 
Example 11
Project: lams   File: ExtendedMessageFormat.java   View source code 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 12
Project: plugin-security-fortify   File: FortifyPluginResource.java   View source code 6 votes vote down vote up
/**
 * Call a Fortify REST service to fetch items by their name.<br>
 * NOTE : process manager will be shut down.
 * 
 * @param node
 *            node to query.
 * @param url
 *            query URL.
 * @param criteria
 *            Optional name to match.
 * @return Projects matching to the given criteria.
 */
private Collection<FortifyProject> findAll(final String node, final String url, final String criteria)
		throws IOException {
	// Check the user can log-in to Fortify
	final Collection<Map<String, Object>> data = getFortifyResource(this.pvResource.getNodeParameters(node),
			url);
	final Format format = new NormalizeFormat();
	final String formatCriteria = format.format(StringUtils.trimToEmpty(criteria));

	// Filter by criteria on the project name
	final Map<Integer, FortifyProject> result = new TreeMap<>();
	data.stream().filter(item -> (format.format(item.get("name"))).contains(formatCriteria)).forEach(item -> {
		final FortifyProject entry = toProject(item);
		result.put(entry.getId(), entry);
	});
	return result.values();
}
 
Example 13
Project: plugin-bt-jira   File: CsvStatusStreamingOutput.java   View source code 6 votes vote down vote up
/**
 * Write issue data
 */
private void writeData(final JiraChangeItem change, final String key, final Writer writer, final Format df, final Format idf) throws IOException {
	// Write static data
	writer.write(change.getId().toString());
	writer.write(';');
	writer.write(key);
	writer.write(';');
	writer.write(ObjectUtils.defaultIfNull(change.getAuthor(), change.getReporter()));
	writer.write(';');
	writer.write(ObjectUtils.defaultIfNull(change.getFromStatus(), "").toString());
	writer.write(';');
	writer.write(String.valueOf(change.getToStatus()));
	writer.write(';');
	writer.write(idf.format(ObjectUtils.defaultIfNull(statusText.get(change.getFromStatus()), "")));
	writer.write(';');
	writer.write(idf.format(statusText.get(change.getToStatus())));
	writer.write(';');
	writer.write(df.format(change.getCreated()));
	writer.write(';');
	writer.write(String.valueOf(change.getCreated().getTime()));
}
 
Example 14
Project: plugin-id-ldap   File: CsvStreamingOutput.java   View source code 5 votes vote down vote up
/**
 * Write user's activities
 */
protected void writeNodeActivities(final Map<String, Activity> activities, final Writer writer, final Format df) throws IOException {
	for (final INamableBean<String> node : computations.getNodes()) {
		writer.write(';');

		// Last connection, if available
		final Activity activity = activities.get(node.getId());
		if (activity != null) {
			// There is an activity for this user and this node
			writer.write(df.format(activity.getLastConnection()));
		}
	}
}
 
Example 15
Project: jdk8u-jdk   File: TCKDateTimeFormatter.java   View source code 5 votes vote down vote up
@Test
public void test_toFormat_parseObject_StringParsePosition_invalidPosition_tooBig() throws Exception {
    // SimpleDateFormat has this behavior
    DateTimeFormatter dtf = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    ParsePosition pos = new ParsePosition(6);
    Format test = dtf.toFormat();
    assertNull(test.parseObject("ONE30", pos));
    assertTrue(pos.getErrorIndex() >= 0);
}
 
Example 16
Project: data-binding-validator   File: AbstractCalendarValidator.java   View source code 5 votes vote down vote up
/**
 * <p>Format a value with the specified <code>DateFormat</code>.</p>
 *
 * @param value The value to be formatted.
 * @param formatter The Format to use.
 * @return The formatted value.
 */
@Override
protected String format(Object value, Format formatter) {
    if (value == null) {
        return null;
    } else if (value instanceof Calendar) {
        value = ((Calendar)value).getTime();
    }
    return formatter.format(value);
}
 
Example 17
Project: Automekanik   File: DritarjaKryesore.java   View source code 5 votes vote down vote up
public void filtroFinancat(TextField puna) {
    try {
        String sql;
        if (!puna.getText().isEmpty())
            sql = "select * from Punet where lower(lloji) like lower('%" + puna.getText() + "%') or lower(konsumatori) like lower('%" + puna.getText() + "%'" +
                    ") order by data desc";
        else
            sql = "select * from Punet order by data desc";
        Connection conn = DriverManager.getConnection(CON_STR, "test", "test");
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        ObservableList<TabelaPunet> data = FXCollections.observableArrayList();
        Format format = new SimpleDateFormat("dd/MM/yyyy");
        while (rs.next()) {
            String d = format.format(rs.getDate("data"));
            data.add(new TabelaPunet(rs.getInt("id"), rs.getString("lloji").toUpperCase(), d,
                    rs.getFloat("qmimi"), rs.getString("konsumatori").toUpperCase(),
                    rs.getString("pershkrimi"), rs.getString("kryer"), rs.getString("makina").toUpperCase()));
        }
        tblPunet.getItems().clear();
        tblPunet.setItems(data);
        stmt.close();
        rs.close();
        conn.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 18
Project: incubator-netbeans   File: NumberRenderer.java   View source code 5 votes vote down vote up
protected String getValueString(Object value, int row, Format format) {
    if (value == null) return "-"; // NOI18N
    String s = super.getValueString(value, row, format);
    s = outputFormat == null ? s : formatImpl(outputFormat, s);
    if (renderingDiff && value instanceof Number)
        if (((Number)value).doubleValue() >= 0) s = '+' + s; // NOI18N
    return s;
}
 
Example 19
Project: incubator-netbeans   File: Formatters.java   View source code 5 votes vote down vote up
/**
 * Returns Format instance for formatting numbers according to current Locale.
 * 
 * @return Format instance for formatting numbers according to current Locale
 */
public static Format numberFormat() {
    if (NUMBER_FORMAT == null) {
        NUMBER_FORMAT = NumberFormat.getNumberInstance();
        NUMBER_FORMAT.setGroupingUsed(true);
    }
    return NUMBER_FORMAT;
}
 
Example 20
Project: openjdk-jdk10   File: TCKDateTimeFormatter.java   View source code 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 21
Project: BizareChat   File: DialogModel.java   View source code 5 votes vote down vote up
public String getLastMessageTime() {
    SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm");
    Format formatter = new SimpleDateFormat("dd/MM/yy");
    Date dt = new Date(lastMessageDateSent * 1000);

    String now = formatter.format(new Date());
    String messageDate = formatter.format(dt);
    if (now.equals(messageDate)) {
        return localDateFormat.format(dt).toString();
    } else if (lastMessageDateSent == 0) {
        return "";
    } else {
        return messageDate;
    }
}
 
Example 22
Project: incubator-netbeans   File: NbProcessDescriptor.java   View source code 5 votes vote down vote up
/** Executes the process with arguments, processName and envp formatted by the provided
* format. Also the envp properties are passed to the executed process,
* and a working directory may be supplied. Optionally the environment variables of the NetBeans JVM may
* be appended to (replaced when there is overlap) instead of specifying
* all of the environment variables from scratch. This requires the NetBeans core
* to translate environment variables to system properties prefixed
* by <samp>Env-</samp> in order to work correctly.
*
* @param format format to be applied to arguments, process and envp supplied by user. It can be <code>null</code> if no formatting should be done.
* @param envp list of properties to be applied to the process, or <code>null</code> to leave unspecified
* @param appendEnv if true and <code>envp</code> is not <code>null</code>, append or replace JVM's environment
* @param cwd the working directory to use, or <code>null</code> if this should not be specified
* @return handle to executed process.
* @exception IOException if the start of the process fails, or if setting the working directory is not supported
* @since 1.15
*/
public Process exec (Format format, String[] envp, boolean appendEnv, File cwd) throws IOException {
    String stringArgs = format == null ? arguments : format.format (arguments);
    String[] args = parseArguments (stringArgs);
    String[] call = null;
    
    envp = substituteEnv(format, envp);
   
    // copy the call string
    call = new String[args.length + 1];
    call[0] = format == null ? processName : format.format(processName);
    System.arraycopy (args, 0, call, 1, args.length); 

    logArgs(call);
    
    ProcessBuilder pb = new ProcessBuilder(call);
    
    if (envp != null) {
        Map<String,String> e = pb.environment();
        if (!appendEnv) e.clear();
        for (int i = 0; i < envp.length; i++) {
            String nameval = envp[i];
            int idx = nameval.indexOf ('='); // NOI18N
            // [PENDING] add localized annotation...
            if (idx == -1) throw new IOException ("No equal sign in name=value: " + nameval); // NOI18N
            e.put (nameval.substring (0, idx), nameval.substring (idx + 1));
        }
    }

    if (cwd != null) pb.directory(cwd);
    return pb.start();
}
 
Example 23
Project: plugin-bt-jira   File: AbstractCsvOutput.java   View source code 5 votes vote down vote up
@Override
public void write(final OutputStream output) throws IOException {
	final Writer writer = new BufferedWriter(new OutputStreamWriter(output, "cp1252"));
	final FastDateFormat df = FastDateFormat.getInstance("yyyy/MM/dd HH:mm:ss");
	final Format idf = new NormalizeFormat();

	// Write headers
	writeHeaders(writer);

	// Write data
	writeData(writer, df, idf);
	writer.flush();
}
 
Example 24
Project: openjdk-jdk10   File: MessageFormatsByArgumentIndex.java   View source code 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 25
Project: jdk8u-jdk   File: TCKDateTimeFormatter.java   View source code 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 26
Project: jdk8u-jdk   File: TCKDateTimeFormatter.java   View source code 5 votes vote down vote up
@Test(expectedExceptions=ParseException.class)
public void test_toFormat_parseObject_String_parseErrorLongText() throws Exception {
    DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    Format format = test.toFormat();
    try {
        format.parseObject("ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789");
    } catch (DateTimeParseException ex) {
        assertEquals(ex.getMessage().contains("ONEXXX6789012345678901234567890123456789012345678901234567890123..."), true);
        assertEquals(ex.getParsedString(), "ONEXXX67890123456789012345678901234567890123456789012345678901234567890123456789");
        assertEquals(ex.getErrorIndex(), 3);
        throw ex;
    }
}
 
Example 27
Project: music_player   File: MainActivity.java   View source code 5 votes vote down vote up
private String praseLyric(String lyric) {
    Log.v("歌词", "歌词" + lyric);
    try {
        String[] split = lyric.split("\n");
        if (split[split.length - 2].substring(9, 10).equals("]")) {
            //歌曲时间格式标准[04:28.46]
            return lyric;
        } else if (split[split.length - 2].substring(10, 11).equals("]")) {
            //歌曲时间格式不标准[04:28.660][04:28.660]
            lyric = "";
            Format f = new DecimalFormat("00");
            for (int i = 0; i < split.length; i++) {
                if (!split[i].substring(1, 2).equals("0")) {
                    //有作者标签
                } else {
                    //无作者标签
                    if(split[i].lastIndexOf("]")!=9) {
                        int allIndex = split[i].indexOf("]");
                        while (allIndex != -1) {
                            split[i] = split[i].substring(0, allIndex - 3) + String.valueOf(f.format(Integer.valueOf(split[i].substring(allIndex - 3, allIndex)) / 50 * 3)) + split[i].substring(allIndex);
                            Log.v("歌词解析", "歌词" + split[i]);
                            allIndex = split[i].indexOf("]", allIndex + 1);
                        }
                    }
                    lyric = lyric + split[i] + "\n";
                }
            }
            Log.v("歌词解析", "歌词结果" + lyric);
            return lyric;
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return lyric;
}
 
Example 28
Project: jdk8u-jdk   File: TCKDateTimeFormatter.java   View source code 5 votes vote down vote up
@Test
public void test_toFormat_format() throws Exception {
    DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    Format format = test.toFormat();
    String result = format.format(LocalDate.of(2008, 6, 30));
    assertEquals(result, "ONE30");
}
 
Example 29
Project: streamsx.jmxclients   File: StreamsInstanceTracker.java   View source code 5 votes vote down vote up
private String convertTime(Long time) {
    if (time != null) {
        Date date = new Date(time);
        Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
        return format.format(date);
    } else {
        return "null";
    }
}
 
Example 30
Project: react-native-google-fit   File: CalorieHistory.java   View source code 5 votes vote down vote up
private void processDataSet(DataSet dataSet, WritableArray map) {
    Log.i(TAG, "Data returned for Data type: " + dataSet.getDataType().getName());
    DateFormat dateFormat = DateFormat.getDateInstance();
    DateFormat timeFormat = DateFormat.getTimeInstance();
    Format formatter = new SimpleDateFormat("EEE");
    WritableMap stepMap = Arguments.createMap();
    
    
    for (DataPoint dp : dataSet.getDataPoints()) {
        Log.i(TAG, "Data point:");
        Log.i(TAG, "\tType: " + dp.getDataType().getName());
        Log.i(TAG, "\tStart: " + dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
        Log.i(TAG, "\tEnd: " + dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS)) + " " + timeFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS)));
        
        String day = formatter.format(new Date(dp.getStartTime(TimeUnit.MILLISECONDS)));
        Log.i(TAG, "Day: " + day);
        
        for(Field field : dp.getDataType().getFields()) {
            Log.i("History", "\tField: " + field.getName() +
                  " Value: " + dp.getValue(field));
            
            stepMap.putString("day", day);
            stepMap.putDouble("startDate", dp.getStartTime(TimeUnit.MILLISECONDS));
            stepMap.putDouble("endDate", dp.getEndTime(TimeUnit.MILLISECONDS));
            float basal = 0;
            try {
                basal = getBasalAVG(dp.getEndTime(TimeUnit.MILLISECONDS));
            } catch (Exception e) {
                e.printStackTrace();
            }
            stepMap.putDouble("calorie", dp.getValue(field).asFloat() - basal);
            map.pushMap(stepMap);
        }
    }
}
 
Example 31
Project: openjdk-jdk10   File: TCKDateTimeFormatter.java   View source code 5 votes vote down vote up
@Test
public void test_toFormat_format() throws Exception {
    DateTimeFormatter test = fmt.withLocale(Locale.ENGLISH).withDecimalStyle(DecimalStyle.STANDARD);
    Format format = test.toFormat();
    String result = format.format(LocalDate.of(2008, 6, 30));
    assertEquals(result, "ONE30");
}
 
Example 32
Project: plugin-bt-jira   File: CsvWithCustomFieldsStreamingOutput.java   View source code 5 votes vote down vote up
/**
 * Custom non fixed fields
 */
private void writeCustomData(final IssueSla issue, final Writer writer, final Format df) throws IOException {

	// Write components data
	writeComponentsData(issue, writer);

	// Write custom fields data
	writeCustomFieldsData(issue, writer, df);
}
 
Example 33
Project: BIMplatform   File: ColladaSerializer.java   View source code 5 votes vote down vote up
private List<String> intBufferToStringList(ByteBuffer buffer, Format formatter) {
	List<Integer> list = new ArrayList<Integer>();
	while (buffer.hasRemaining())
		list.add(new Integer(buffer.getInt()));
	// Get the data as a list of String objects.
	return listToStringList(list, formatter);
}
 
Example 34
Project: BIMplatform   File: ColladaSerializer.java   View source code 5 votes vote down vote up
private List<String> listToStringList(List<?> list, Format formatter) {
	// Prepare to store floating-points as a list of strings.
	List<String> stringScalars = new ArrayList<String>();
	// For each scalar in the buffer, turn it into a string, adding it to the overall list.
	for (Object scalar : list) {
		String scalarAsString = formatter.format(scalar);
		stringScalars.add(scalarAsString);
	}
	return stringScalars;
}
 
Example 35
Project: open-rmbt   File: ImageExport.java   View source code 5 votes vote down vote up
/**
 * Formats a number to 2 significant digits
 * @param number the number
 * @return the formatted number
 */
protected String formatNumber(double number, String lang) {
	final Locale locale = new Locale(lang);
	final Format format = new SignificantFormat(2, locale);
	
	final StringBuffer buf = format.format(number, new StringBuffer(), new FieldPosition(0));
	return buf.toString();
}
 
Example 36
Project: oscm   File: PriceConverter.java   View source code 5 votes vote down vote up
@Override
protected Format getFormat(String pattern, Locale locale) {
    DecimalFormat format = (DecimalFormat) super.getFormat(pattern,
            locale);
    format.setMaximumIntegerDigits(NUMBER_OF_INTEGER_PLACES);
    format.setMaximumFractionDigits(NUMBER_OF_DECIMAL_PLACES);
    // avoid lost precision due to parsing to double:
    format.setParseBigDecimal(true);
    return format;
}
 
Example 37
Project: fitnotifications   File: DecimalFormat.java   View source code 5 votes vote down vote up
AttributedCharacterIterator formatToCharacterIterator(Object obj, Unit unit) {
    if (!(obj instanceof Number))
        throw new IllegalArgumentException();
    Number number = (Number) obj;
    StringBuffer text = new StringBuffer();
    unit.writePrefix(text);
    attributes.clear();
    if (obj instanceof BigInteger) {
        format((BigInteger) number, text, new FieldPosition(0), true);
    } else if (obj instanceof java.math.BigDecimal) {
        format((java.math.BigDecimal) number, text, new FieldPosition(0)
                      , true);
    } else if (obj instanceof Double) {
        format(number.doubleValue(), text, new FieldPosition(0), true);
    } else if (obj instanceof Integer || obj instanceof Long) {
        format(number.longValue(), text, new FieldPosition(0), true);
    } else {
        throw new IllegalArgumentException();
    }
    unit.writeSuffix(text);
    AttributedString as = new AttributedString(text.toString());

    // add NumberFormat field attributes to the AttributedString
    for (int i = 0; i < attributes.size(); i++) {
        FieldPosition pos = attributes.get(i);
        Format.Field attribute = pos.getFieldAttribute();
        as.addAttribute(attribute, attribute, pos.getBeginIndex(), pos.getEndIndex());
    }

    // return the CharacterIterator from AttributedString
    return as.getIterator();
}
 
Example 38
Project: openjdk-jdk10   File: TCKDateTimeFormatter.java   View source code 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 39
Project: fitnotifications   File: MessageFormat.java   View source code 5 votes vote down vote up
/**
 * {@inheritDoc}
 * @stable ICU 3.0
 */
@Override
public Object clone() {
    MessageFormat other = (MessageFormat) super.clone();

    if (customFormatArgStarts != null) {
        other.customFormatArgStarts = new HashSet<Integer>();
        for (Integer key : customFormatArgStarts) {
            other.customFormatArgStarts.add(key);
        }
    } else {
        other.customFormatArgStarts = null;
    }

    if (cachedFormatters != null) {
        other.cachedFormatters = new HashMap<Integer, Format>();
        Iterator<Map.Entry<Integer, Format>> it = cachedFormatters.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry<Integer, Format> entry = it.next();
            other.cachedFormatters.put(entry.getKey(), entry.getValue());
        }
    } else {
        other.cachedFormatters = null;
    }

    other.msgPattern = msgPattern == null ? null : (MessagePattern)msgPattern.clone();
    other.stockDateFormatter =
            stockDateFormatter == null ? null : (DateFormat) stockDateFormatter.clone();
    other.stockNumberFormatter =
            stockNumberFormatter == null ? null : (NumberFormat) stockNumberFormatter.clone();

    other.pluralProvider = null;
    other.ordinalProvider = null;
    return other;
}
 
Example 40
Project: jdk8u-jdk   File: TCKDateTimeFormatter.java   View source code 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);
}