List of usage examples for org.joda.time.format DateTimeFormat forPattern
public static DateTimeFormatter forPattern(String pattern)
From source file:br.eti.ranieri.opcoesweb.page.PainelOpcoes.java
License:Apache License
public PainelOpcoes(String id, List<CotacaoOpcao> opcoes, DateTime atualizacao) { this(id, opcoes, atualizacao != null ? atualizacao.toLocalDate() : null, DateTimeFormat.forPattern("'Atualizado em 'HH:mm dd/MM/yyyy").withLocale(ptBR).print(atualizacao)); }
From source file:bravox.sistema.mensagens.MensagemQtdMaiorProduzida.java
public void retornaHora(String minutos) { // DateTimeFormatter format = DateTimeFormat.forPattern("HH:mm"); LocalTime hora = LocalTime.parse(minutos, DateTimeFormat.forPattern("HH:mm")); }
From source file:broadwick.BroadwickConstants.java
License:Apache License
/** * Convert a date object to an integer (number of days from a fixed start date, here 1/1/1900). All dates in the * database are stored as integer values using this method. * @param date the date object we are converting. * @param dateFormat the format the date is in when doing the conversion. * @return the number of days from a fixed 'zero date'. */// ww w . j a va 2 s .com public static int getDate(final String date, final String dateFormat) { final DateTimeFormatter pattern = DateTimeFormat.forPattern(dateFormat); final DateTime dateTime = pattern.parseDateTime(date); return BroadwickConstants.getDate(dateTime); }
From source file:ca.farrelltonsolar.classic.DayLabelAdapter.java
License:Apache License
@Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.day_label_item, parent, false); convertView.setPadding(2, 0, 2, 0);/*from w ww . j av a 2 s . c o m*/ TextView date = (TextView) convertView.findViewById(R.id.dayLabel_date); TextView day = (TextView) convertView.findViewById(R.id.dayLabel_day); if (position == 0) { date.setText(""); day.setText(""); return convertView; } DateTime labelDate; try { labelDate = today.minusDays(getCount() - position); date.setGravity(Gravity.CENTER); String dateStamp = DateTimeFormat.forPattern("dd").print(labelDate); date.setText(dateStamp); date.setTextColor(labelColor()); day.setGravity(Gravity.CENTER); dateStamp = DateTimeFormat.forPattern("E").print(labelDate); day.setText(dateStamp); day.setTextColor(labelColor()); } catch (Exception ex) { Log.w(getClass().getName(), String.format("today.minusDays failed ex: %s", ex)); } return convertView; }
From source file:ca.farrelltonsolar.classic.DayLogCalendar.java
License:Apache License
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { theView = inflater.inflate(R.layout.day_log_calendar, container, false); Bundle args = getArguments();//w w w . ja v a 2 s . c om int monthOffset = args != null ? args.getInt(ARG_MONTH) : 0; month = DateTime.now().minusMonths(monthOffset).withTimeAtStartOfDay().withDayOfMonth(1); adapter = new CalendarAdapter(this.getActivity(), month); GridView gridview = (GridView) theView.findViewById(R.id.gridview); gridview.setAdapter(adapter); gridview.setVelocityScale(5); TextView title = (TextView) theView.findViewById(R.id.title); title.setText(month.toString("MMMM yyyy")); View linearLayout = theView.findViewById(R.id.headerlayout); DateTime days = month; for (int i = 0; i < 7; i++) { int d = ((i + 6) % 7) + 1; days = days.withDayOfWeek(d); TextView aDay = new TextView(theView.getContext()); aDay.setText(DateTimeFormat.forPattern("E").print(days)); aDay.setGravity(Gravity.CENTER); aDay.setTextColor(Color.BLACK); aDay.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1)); ((LinearLayout) linearLayout).addView(aDay); } return theView; }
From source file:ca.farrelltonsolar.classic.PVOutputService.java
License:Apache License
public static DateTime LogDate() { DateTime logDate = null;//ww w. j a v a 2 s . co m ChargeController cc = MonitorApplication.chargeControllers().getCurrentChargeController(); if (cc != null) { String fName = cc.getPVOutputLogFilename(); if (fName != null && fName.length() > 0) { try { String logDateSubstring = fName.substring(18, 28); logDate = DateTime.parse(logDateSubstring, DateTimeFormat.forPattern("yyyy-MM-dd")); } catch (Exception ex) { Log.w("PVOutputService", String.format("LogDate parse filename failed ex: %s", ex)); } } } return logDate; }
From source file:ca.farrelltonsolar.classic.PVOutputService.java
License:Apache License
private String getLogDate() { DateTime today = DateTime.now().withTimeAtStartOfDay(); return DateTimeFormat.forPattern("yyyy-MM-dd").print(today); }
From source file:ca.farrelltonsolar.classic.PVOutputUploader.java
License:Apache License
private boolean doUpload(ChargeController controller) throws InterruptedException, IOException { String uploadDateString = controller.uploadDate(); String SID = controller.getSID(); String fName = controller.getPVOutputLogFilename(); if (fName != null && fName.length() > 0 && SID != null && SID.length() > 0) { DateTime logDate = PVOutputService.LogDate(); int numberOfDays = Constants.PVOUTPUT_RECORD_LIMIT; if (uploadDateString.length() > 0) { DateTime uploadDate = DateTime.parse(uploadDateString, DateTimeFormat.forPattern("yyyy-MM-dd")); numberOfDays = Days.daysBetween(uploadDate, logDate).getDays(); }//from w ww .j a v a2s . co m numberOfDays = numberOfDays > Constants.PVOUTPUT_RECORD_LIMIT ? Constants.PVOUTPUT_RECORD_LIMIT : numberOfDays; // limit to 20 days as per pvOutput limits if (numberOfDays > 0) { Log.d(getClass().getName(), String.format("PVOutput uploading: %s for %d days on thread: %s", fName, numberOfDays, Thread.currentThread().getName())); DateTime now = DateTime.now(); String UploadDate = DateTimeFormat.forPattern("yyyy-MM-dd").print(now); Bundle logs = load(fName); float[] mData = logs.getFloatArray(String.valueOf(Constants.CLASSIC_KWHOUR_DAILY_CATEGORY)); // kWh/day boolean uploadDateRecorded = false; for (int i = 0; i < numberOfDays; i++) { logDate = logDate.minusDays(1); // latest log entry is for yesterday Socket pvOutputSocket = Connect(pvOutput); DataOutputStream outputStream = new DataOutputStream( new BufferedOutputStream(pvOutputSocket.getOutputStream())); String dateStamp = DateTimeFormat.forPattern("yyyyMMdd").print(logDate); StringBuilder feed = new StringBuilder("GET /service/r2/addoutput.jsp"); feed.append("?key="); feed.append(APIKey); feed.append("&sid="); feed.append(SID); feed.append("&d="); feed.append(dateStamp); feed.append("&g="); String wh = String.valueOf(mData[i] * 100); feed.append(wh); feed.append("\r\n"); feed.append("Host: "); feed.append(pvOutput); feed.append("\r\n"); feed.append("\r\n"); String resp = feed.toString(); outputStream.writeBytes(resp); outputStream.flush(); pvOutputSocket.close(); if (uploadDateRecorded == false) { controller.setUploadDate(UploadDate); uploadDateRecorded = true; } Thread.sleep(Constants.PVOUTPUT_RATE_LIMIT); // rate limit } return true; } } return false; }
From source file:ca.phon.csv2phon.CSVImporter.java
License:Open Source License
private void importFile(FileType fileInfo) throws IOException { // first try relative path from base // String base = importDescription.getBase(); String location = fileInfo.getLocation(); // check if location is an absolute path boolean absolute = false; if (OSInfo.isWindows()) { if (location.matches("[A-Z]:\\\\.*")) absolute = true;//from w w w . j a v a 2s. c om } else { if (location.startsWith("/")) absolute = true; } File csvFile = null; if (absolute) csvFile = new File(location); else csvFile = new File(base, location); if (!csvFile.exists()) { // throw an exception throw new FileNotFoundException("'" + csvFile.getAbsolutePath() + "' not found, check the 'base' attribute of the csvimport element."); } final InputStreamReader csvInputReader = new InputStreamReader(new FileInputStream(csvFile), fileEncoding); // read in csv file final CSVReader reader = new CSVReader(csvInputReader, fieldDelimChar, textDelimChar); // create a new transcript in the project // with the specified corpus and session name final String corpus = importDescription.getCorpus(); final String session = fileInfo.getSession(); if (!project.getCorpora().contains(corpus)) { LOGGER.info("Creating corpus '" + corpus + "'"); project.addCorpus(corpus, ""); } final SessionFactory factory = SessionFactory.newFactory(); final Session t = project.createSessionFromTemplate(corpus, session); if (t.getRecordCount() > 0) t.removeRecord(0); if (fileInfo.getDate() != null) { final DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd"); DateTime sessionDate = dateFormatter.parseDateTime(fileInfo.getDate()); t.setDate(sessionDate); } // add participants for (ParticipantType pt : importDescription.getParticipant()) { Participant newPart = CSVParticipantUtil.copyXmlParticipant(factory, pt, t.getDate()); t.addParticipant(newPart); } if (fileInfo.getMedia() != null) { t.setMediaLocation(fileInfo.getMedia()); } // set media file and date String[] colLine = reader.readNext(); // create deptier descriptions as necessary for (String columnName : colLine) { ColumnMapType colmap = getColumnMap(columnName); if (colmap != null) { String tierName = colmap.getPhontier(); if (tierName.equalsIgnoreCase("Don't import")) continue; if (!SystemTierType.isSystemTier(tierName) && !tierName.equalsIgnoreCase("Speaker:Name")) { final TierDescription tierDesc = factory.createTierDescription(tierName, colmap.isGrouped(), String.class); t.addUserTier(tierDesc); } } } int createdParticipant = 0; String[] currentRow = null; while ((currentRow = reader.readNext()) != null) { // add a new record to the transcript Record utt = factory.createRecord(); t.addRecord(utt); for (int colIdx = 0; colIdx < colLine.length; colIdx++) { String csvcol = colLine[colIdx]; String rowval = currentRow[colIdx]; ColumnMapType colmap = getColumnMap(csvcol); if (colmap == null) { // print warning and continue LOGGER.warning("No column map for csv column '" + csvcol + "'"); continue; } // convert if necessary TranscriptConverter tc = null; if (colmap.getFilter() != null && colmap.getFilter().length() > 0) { tc = TranscriptConverter.getInstanceOf(colmap.getFilter()); if (tc == null) { LOGGER.warning("Could not find transcript converter '" + colmap.getFilter() + "'"); } } String phontier = colmap.getPhontier().trim(); if (phontier.equalsIgnoreCase("Don't Import")) { continue; } // do data pre-formatting if required if (colmap.getScript() != null) { // TODO: create a new javascript context and run the given script } // handle participant tier if (phontier.equals("Speaker:Name")) { // look for the participant in the transcript Participant speaker = null; for (Participant p : t.getParticipants()) { if (p.toString().equals(rowval)) { speaker = p; break; } } // if not found in the transcript, find the // participant info in the import description // add add the participant if (speaker == null) { speaker = factory.createParticipant(); speaker.setName(rowval); speaker.setRole(ParticipantRole.PARTICIPANT); String id = "PA" + (createdParticipant > 0 ? createdParticipant : "R"); ++createdParticipant; speaker.setId(id); t.addParticipant(speaker); } utt.setSpeaker(speaker); } else { if (colmap.isGrouped() == null) colmap.setGrouped(true); // convert rowval into a list of group values List<String> rowVals = new ArrayList<String>(); if (colmap.isGrouped() && rowval.startsWith("[") && rowval.endsWith("]")) { String[] splitRow = rowval.split("\\["); for (int i = 1; i < splitRow.length; i++) { String splitVal = splitRow[i]; splitVal = splitVal.replaceAll("\\]", ""); rowVals.add(splitVal); } } else { rowVals.add(rowval); } final SystemTierType systemTier = SystemTierType.tierFromString(phontier); if (systemTier != null) { if (systemTier == SystemTierType.Orthography) { final Tier<Orthography> orthoTier = utt.getOrthography(); for (String grpVal : rowVals) { try { final Orthography ortho = Orthography.parseOrthography(grpVal); orthoTier.addGroup(ortho); } catch (ParseException e) { final Orthography ortho = new Orthography(); final UnvalidatedValue uv = new UnvalidatedValue(grpVal, e); ortho.putExtension(UnvalidatedValue.class, uv); orthoTier.addGroup(ortho); } } } else if (systemTier == SystemTierType.IPATarget || systemTier == SystemTierType.IPAActual) { final Tier<IPATranscript> ipaTier = (systemTier == SystemTierType.IPATarget ? utt.getIPATarget() : utt.getIPAActual()); for (String grpVal : rowVals) { if (tc != null) { grpVal = tc.convert(grpVal); } grpVal = grpVal.trim(); final IPATranscript ipa = (new IPATranscriptBuilder()).append(grpVal) .toIPATranscript(); ipaTier.addGroup(ipa); } } else if (systemTier == SystemTierType.Notes) { utt.getNotes().addGroup(rowval); } else if (systemTier == SystemTierType.Segment) { final MediaSegmentFormatter segmentFormatter = new MediaSegmentFormatter(); MediaSegment segment = factory.createMediaSegment(); segment.setStartValue(0.0f); segment.setEndValue(0.0f); segment.setUnitType(MediaUnit.Millisecond); try { segment = segmentFormatter.parse(rowval); } catch (ParseException e) { LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e); } utt.getSegment().addGroup(segment); } } else { Tier<String> tier = utt.getTier(phontier, String.class); if (tier == null) { tier = factory.createTier(phontier, String.class, colmap.isGrouped()); utt.putTier(tier); } for (String grpVal : rowVals) { tier.addGroup(grpVal); } } } } // end for(colIdx) // do syllabification + alignment if necessary ColumnMapType targetMapping = getPhonColumnMap(SystemTierType.IPATarget.getName()); ColumnMapType actualMapping = getPhonColumnMap(SystemTierType.IPAActual.getName()); if (targetMapping != null && actualMapping != null) { final SyllabifierLibrary library = SyllabifierLibrary.getInstance(); String targetLangName = targetMapping.getSyllabifier(); if (targetLangName == null) { targetLangName = SyllabifierLibrary.getInstance().defaultSyllabifierLanguage().toString(); } final Language targetLang = Language.parseLanguage(targetLangName); String actualLangName = targetMapping.getSyllabifier(); if (actualLangName == null) { actualLangName = SyllabifierLibrary.getInstance().defaultSyllabifierLanguage().toString(); } final Language actualLang = Language.parseLanguage(actualLangName); final PhoneAligner aligner = new PhoneAligner(); Syllabifier targetSyllabifier = library.getSyllabifierForLanguage(targetLang); Syllabifier actualSyllabifier = library.getSyllabifierForLanguage(actualLang); for (int i = 0; i < utt.numberOfGroups(); i++) { final Group grp = utt.getGroup(i); final IPATranscript targetRep = grp.getIPATarget(); if (targetSyllabifier != null) { targetSyllabifier.syllabify(targetRep.toList()); } final IPATranscript actualRep = grp.getIPAActual(); if (actualSyllabifier != null) { actualSyllabifier.syllabify(actualRep.toList()); } PhoneMap pm = aligner.calculatePhoneMap(targetRep, actualRep); grp.setPhoneAlignment(pm); } } } // end while(currentRow) reader.close(); // save transcript final UUID writeLock = project.getSessionWriteLock(t); if (writeLock != null) { project.saveSession(t, writeLock); project.releaseSessionWriteLock(t, writeLock); } }
From source file:ca.phon.phon2csv.SessionInfoColumn.java
License:Open Source License
@Override public String getData(Session t, Record utt) { String retVal = ""; if (field.equalsIgnoreCase("Name")) { retVal = t.getCorpus() + "." + t.getName(); } else if (field.equalsIgnoreCase("Corpus")) { retVal = t.getCorpus();//from w ww . ja v a 2 s. c o m } else if (field.equalsIgnoreCase("ID")) { retVal = t.getName(); } else if (field.equalsIgnoreCase("Media")) { retVal = (t.getMediaLocation() != null ? t.getMediaLocation() : ""); } else if (field.equalsIgnoreCase("Date")) { if (t.getDate() != null) { final DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd"); retVal = dateFormatter.print(t.getDate()); } } else { retVal = ""; } return retVal; }