List of usage examples for java.text ParseException getMessage
public String getMessage()
From source file:org.egov.egf.web.actions.payment.PaymentAction.java
@ValidationErrorPage(value = "form") @SkipValidation/* w ww . j av a 2 s .c o m*/ @Action(value = "/payment/payment-create") public String create() { try { final String vdate = parameters.get("voucherdate")[0]; final Date paymentVoucherDate = DateUtils.parseDate(vdate, "dd/MM/yyyy"); final String voucherDate = formatter1.format(paymentVoucherDate); String cutOffDate1 = null; validateBillVoucherDate(billList, paymentVoucherDate); paymentActionHelper.setbillRegisterFunction(billregister, cFunctionobj); if (LOGGER.isDebugEnabled()) LOGGER.debug("Starting createPayment..."); populateWorkflowBean(); if (parameters.get("department") != null) billregister.getEgBillregistermis().setEgDepartment(departmentService .getDepartmentById(Long.valueOf(parameters.get("department")[0].toString()))); if (parameters.get("function") != null) billregister.getEgBillregistermis().setFunction( functionService.findOne(Long.valueOf(parameters.get("function")[0].toString()))); paymentheader = paymentService.createPayment(parameters, billList, billregister, workflowBean); miscBillList = paymentActionHelper.getPaymentBills(paymentheader); // sendForApproval();// this should not be called here as it is // public method which is called from jsp submit if (!cutOffDate.isEmpty() && cutOffDate != null) try { date = sdf1.parse(cutOffDate); cutOffDate1 = formatter1.format(date); } catch (final ParseException e) { // } if (cutOffDate1 != null && voucherDate.compareTo(cutOffDate1) <= 0 && FinancialConstants.CREATEANDAPPROVE.equalsIgnoreCase(workflowBean.getWorkFlowAction())) addActionMessage(getMessage("payment.transaction.success", new String[] { paymentheader.getVoucherheader().getVoucherNumber() })); else { addActionMessage(getMessage("payment.transaction.success", new String[] { paymentheader.getVoucherheader().getVoucherNumber() })); if (FinancialConstants.BUTTONFORWARD.equalsIgnoreCase(workflowBean.getWorkFlowAction())) addActionMessage(getMessage("payment.voucher.approved", new String[] { paymentService .getEmployeeNameForPositionId(paymentheader.getState().getOwnerPosition()) })); } } catch (final ValidationException e) { final List<ValidationError> errors = new ArrayList<ValidationError>(); errors.add(new ValidationError("exception", e.getErrors().get(0).getMessage())); loadbankBranch(billregister.getEgBillregistermis().getFund()); throw new ValidationException(errors); } catch (final ApplicationRuntimeException e) { LOGGER.error(e.getMessage()); loadbankBranch(billregister.getEgBillregistermis().getFund()); final List<ValidationError> errors = new ArrayList<ValidationError>(); errors.add(new ValidationError("exception", e.getMessage())); throw new ValidationException(errors); } catch (final Exception e) { final List<ValidationError> errors = new ArrayList<ValidationError>(); loadbankBranch(billregister.getEgBillregistermis().getFund()); errors.add(new ValidationError("exception", e.getMessage())); throw new ValidationException(errors); } if (LOGGER.isDebugEnabled()) LOGGER.debug("Completed createPayment."); setMode("view"); return VIEW; }
From source file:davmail.exchange.ExchangeSession.java
/** * Get freebusy info for attendee between start and end date. * * @param attendee attendee email//ww w .j av a 2 s . c o m * @param startDateValue start date * @param endDateValue end date * @return FreeBusy info * @throws IOException on error */ public FreeBusy getFreebusy(String attendee, String startDateValue, String endDateValue) throws IOException { // replace ical encoded attendee name attendee = replaceIcal4Principal(attendee); // then check that email address is valid to avoid InvalidSmtpAddress error if (attendee == null || attendee.indexOf('@') < 0 || attendee.charAt(attendee.length() - 1) == '@') { return null; } if (attendee.startsWith("mailto:") || attendee.startsWith("MAILTO:")) { attendee = attendee.substring("mailto:".length()); } SimpleDateFormat exchangeZuluDateFormat = getExchangeZuluDateFormat(); SimpleDateFormat icalDateFormat = getZuluDateFormat(); Date startDate; Date endDate; try { if (startDateValue.length() == 8) { startDate = parseDate(startDateValue); } else { startDate = icalDateFormat.parse(startDateValue); } if (endDateValue.length() == 8) { endDate = parseDate(endDateValue); } else { endDate = icalDateFormat.parse(endDateValue); } } catch (ParseException e) { throw new DavMailException("EXCEPTION_INVALID_DATES", e.getMessage()); } FreeBusy freeBusy = null; String fbdata = getFreeBusyData(attendee, exchangeZuluDateFormat.format(startDate), exchangeZuluDateFormat.format(endDate), FREE_BUSY_INTERVAL); if (fbdata != null) { freeBusy = new FreeBusy(icalDateFormat, startDate, fbdata); } if (freeBusy != null && freeBusy.knownAttendee) { return freeBusy; } else { return null; } }
From source file:org.eclipse.smarthome.binding.sonos.handler.ZonePlayerHandler.java
public void setAlarm(boolean alarmSwitch) { List<SonosAlarm> sonosAlarms = getCurrentAlarmList(); // find the nearest alarm - take the current time from the Sonos system, // not the system where we are running SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); fmt.setTimeZone(TimeZone.getTimeZone("GMT")); String currentLocalTime = getTime(); Date currentDateTime = null;// w w w.j ava2 s .c o m try { currentDateTime = fmt.parse(currentLocalTime); } catch (ParseException e) { logger.error("An exception occurred while formatting a date"); e.printStackTrace(); } if (currentDateTime != null) { Calendar currentDateTimeCalendar = Calendar.getInstance(); currentDateTimeCalendar.setTimeZone(TimeZone.getTimeZone("GMT")); currentDateTimeCalendar.setTime(currentDateTime); currentDateTimeCalendar.add(Calendar.DAY_OF_YEAR, 10); long shortestDuration = currentDateTimeCalendar.getTimeInMillis() - currentDateTime.getTime(); SonosAlarm firstAlarm = null; for (SonosAlarm anAlarm : sonosAlarms) { SimpleDateFormat durationFormat = new SimpleDateFormat("HH:mm:ss"); durationFormat.setTimeZone(TimeZone.getTimeZone("GMT")); Date durationDate; try { durationDate = durationFormat.parse(anAlarm.getDuration()); } catch (ParseException e) { logger.error("An exception occurred while parsing a date : '{}'", e.getMessage()); continue; } long duration = durationDate.getTime(); if (duration < shortestDuration && anAlarm.getRoomUUID().equals(getUDN())) { shortestDuration = duration; firstAlarm = anAlarm; } } // Set the Alarm if (firstAlarm != null) { if (alarmSwitch) { firstAlarm.setEnabled(true); } else { firstAlarm.setEnabled(false); } updateAlarm(firstAlarm); } } }
From source file:com.att.pirates.controller.ProjectController.java
public static List<ProjectDetailsStatusViewModel> getProjectDetailsStatus(String prismId, String uuid) { List<ProjectDetailsStatusViewModel> detailStatus = new ArrayList<ProjectDetailsStatusViewModel>(); try {// ww w . j a va 2 s. c om // logger.error("getProjectDetailsStatus, before calling getProjectAppOwners(prismId)"); List<ProjectAppOwnerModel> results = getProjectAppOwners(prismId); // logger.error("getProjectDetailsStatus, after calling getProjectAppOwners(prismId)"); if (!results.isEmpty()) { ArrayList<String> list = new ArrayList<String>(); for (ProjectAppOwnerModel p : results) { list.add(p.getApplicationName()); } // convert the List into a Set Set<String> set = new HashSet<String>(list); // create a new List from the Set // now, they are unique ArrayList<String> distinctApps = new ArrayList<String>(set); Collections.sort(distinctApps); for (String app : distinctApps) { int impactTypeId = DataService.getImpactTypeIdByPrismIdAndApplicationName(prismId, app); boolean validateThreshold = !(impactTypeId == 4); ProjectDetailsStatusViewModel aRow = new ProjectDetailsStatusViewModel(); List<ProjectAppOwnerModel> thisAppRows = getAppOwnerModelObjectsByAppName(results, app); if (!thisAppRows.isEmpty()) { aRow.setApplicationId(thisAppRows.get(0).getApplicationId()); aRow.setApplication(app); aRow.setImpactType(impactTypeId); // 1. BR List<ProjectAppOwnerModel> allBRs = getProjectAppOwnerModelObjectByArtifactName(thisAppRows, PiratesConstants.BR); if (!allBRs.isEmpty()) { aRow.setBR(allBRs.get(0).getPercentageComplete()); aRow.setBRheaderDueDate(allBRs.get(0).getDueDate()); aRow.setBRDuedate(allBRs.get(0).getDateCreated()); aRow.setUpdatedByUUID(allBRs.get(0).getUpdatedByUUID()); // get history records List<AppProjectArtifactOwnersHistory> history = getStatusHistoryListByApplicationOwner( allBRs.get(0)); if (!history.isEmpty()) { for (AppProjectArtifactOwnersHistory h : history) { // for percentage aRow.setBR(aRow.getBR() + "," + h.getPercentageComplete()); aRow.setBRDuedate(aRow.getBRDuedate() + "," + h.getDateLogged()); aRow.setUpdatedByUUID(aRow.getUpdatedByUUID() + "," + h.getUpdatedByUUID()); } } // after processing each history record aRow.setBRStr(getRowDueDatePercentageString(aRow.getBR(), aRow.getBRDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getBRheaderDueDate(), false, validateThreshold)); } // end processing isEmpty() else { aRow.setBR("0%"); aRow.setBRDuedate("NA"); aRow.setUpdatedByUUID("NA"); aRow.setBRheaderDueDate("NA"); aRow.setBRStr(getRowDueDatePercentageString(aRow.getBR(), aRow.getBRDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getBRheaderDueDate(), false, validateThreshold)); } // end of BR // 2. SR List<ProjectAppOwnerModel> allSRs = getProjectAppOwnerModelObjectByArtifactName(thisAppRows, PiratesConstants.SR); if (!allSRs.isEmpty()) { aRow.setSR(allSRs.get(0).getPercentageComplete()); aRow.setSRheaderDueDate(allSRs.get(0).getDueDate()); aRow.setSRDuedate(allSRs.get(0).getDateCreated()); aRow.setUpdatedByUUID(allSRs.get(0).getUpdatedByUUID()); // get history records List<AppProjectArtifactOwnersHistory> history = getStatusHistoryListByApplicationOwner( allSRs.get(0)); if (!history.isEmpty()) { for (AppProjectArtifactOwnersHistory h : history) { // for percentage aRow.setSR(aRow.getSR() + "," + h.getPercentageComplete()); aRow.setSRDuedate(aRow.getSRDuedate() + "," + h.getDateLogged()); aRow.setUpdatedByUUID(aRow.getUpdatedByUUID() + "," + h.getUpdatedByUUID()); } } // after processing each history record aRow.setSRStr(getRowDueDatePercentageString(aRow.getSR(), aRow.getSRDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getSRheaderDueDate(), true, validateThreshold)); } // end processing isEmpty() else { aRow.setSR("0%"); aRow.setSRDuedate("NA"); aRow.setUpdatedByUUID("NA"); aRow.setSRheaderDueDate("NA"); aRow.setSRStr(getRowDueDatePercentageString(aRow.getSR(), aRow.getSRDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getSRheaderDueDate(), true, validateThreshold)); } // end of SR // 3. HLD List<ProjectAppOwnerModel> allHLDs = getProjectAppOwnerModelObjectByArtifactName( thisAppRows, PiratesConstants.HLD); if (!allHLDs.isEmpty()) { aRow.setHLD(allHLDs.get(0).getPercentageComplete()); aRow.setHLDheaderDueDate(allHLDs.get(0).getDueDate()); aRow.setHLDDuedate(allHLDs.get(0).getDateCreated()); aRow.setUpdatedByUUID(allHLDs.get(0).getUpdatedByUUID()); // get history records List<AppProjectArtifactOwnersHistory> history = getStatusHistoryListByApplicationOwner( allHLDs.get(0)); if (!history.isEmpty()) { for (AppProjectArtifactOwnersHistory h : history) { // for percentage aRow.setHLD(aRow.getHLD() + "," + h.getPercentageComplete()); aRow.setHLDDuedate(aRow.getHLDDuedate() + "," + h.getDateLogged()); aRow.setUpdatedByUUID(aRow.getUpdatedByUUID() + "," + h.getUpdatedByUUID()); } } // after processing each history record aRow.setHLDStr(getRowDueDatePercentageString(aRow.getHLD(), aRow.getHLDDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getHLDheaderDueDate(), true, validateThreshold)); } // end processing isEmpty() else { aRow.setHLD("0%"); aRow.setHLDDuedate("NA"); aRow.setUpdatedByUUID("NA"); aRow.setHLDheaderDueDate("NA"); aRow.setHLDStr(getRowDueDatePercentageString(aRow.getHLD(), aRow.getHLDDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getHLDheaderDueDate(), true, validateThreshold)); } // end of HLD // 4. AID List<ProjectAppOwnerModel> allAIDs = getProjectAppOwnerModelObjectByArtifactName( thisAppRows, PiratesConstants.AID); if (!allAIDs.isEmpty()) { aRow.setAID(allAIDs.get(0).getPercentageComplete()); aRow.setAIDheaderDueDate(allAIDs.get(0).getDueDate()); aRow.setAIDDuedate(allAIDs.get(0).getDateCreated()); aRow.setUpdatedByUUID(allAIDs.get(0).getUpdatedByUUID()); // get history records List<AppProjectArtifactOwnersHistory> history = getStatusHistoryListByApplicationOwner( allAIDs.get(0)); if (!history.isEmpty()) { for (AppProjectArtifactOwnersHistory h : history) { // for percentage aRow.setAID(aRow.getAID() + "," + h.getPercentageComplete()); aRow.setAIDDuedate(aRow.getAIDDuedate() + "," + h.getDateLogged()); aRow.setUpdatedByUUID(aRow.getUpdatedByUUID() + "," + h.getUpdatedByUUID()); } } // after processing each history record aRow.setAIDStr(getRowDueDatePercentageString(aRow.getAID(), aRow.getAIDDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getAIDheaderDueDate(), true, validateThreshold)); } // end processing isEmpty() else { aRow.setAID("0%"); aRow.setAIDDuedate("NA"); aRow.setUpdatedByUUID("NA"); aRow.setAIDheaderDueDate("NA"); aRow.setAIDStr(getRowDueDatePercentageString(aRow.getAID(), aRow.getAIDDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getAIDheaderDueDate(), true, validateThreshold)); } // end of AID // 5. AD List<ProjectAppOwnerModel> allADs = getProjectAppOwnerModelObjectByArtifactName(thisAppRows, PiratesConstants.DES); if (!allADs.isEmpty()) { aRow.setDES(allADs.get(0).getPercentageComplete()); aRow.setDESheaderDueDate(allADs.get(0).getDueDate()); aRow.setDESDuedate(allADs.get(0).getDateCreated()); aRow.setUpdatedByUUID(allADs.get(0).getUpdatedByUUID()); // get history records List<AppProjectArtifactOwnersHistory> history = getStatusHistoryListByApplicationOwner( allADs.get(0)); if (!history.isEmpty()) { for (AppProjectArtifactOwnersHistory h : history) { // for percentage aRow.setDES(aRow.getDES() + "," + h.getPercentageComplete()); aRow.setDESDuedate(aRow.getDESDuedate() + "," + h.getDateLogged()); aRow.setUpdatedByUUID(aRow.getUpdatedByUUID() + "," + h.getUpdatedByUUID()); } } // after processing each history record aRow.setDESStr(getRowDueDatePercentageString(aRow.getDES(), aRow.getDESDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getDESheaderDueDate(), true, validateThreshold)); } // end processing isEmpty() else { aRow.setDES("0%"); aRow.setDESDuedate("NA"); aRow.setUpdatedByUUID("NA"); aRow.setDESheaderDueDate("NA"); aRow.setDESStr(getRowDueDatePercentageString(aRow.getDES(), aRow.getDESDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getDESheaderDueDate(), true, validateThreshold)); } // end of DES // 6. DEV List<ProjectAppOwnerModel> allDEVs = getProjectAppOwnerModelObjectByArtifactName( thisAppRows, PiratesConstants.DEV); if (!allDEVs.isEmpty()) { aRow.setDEV(allDEVs.get(0).getPercentageComplete()); aRow.setDEVheaderDueDate(allDEVs.get(0).getDueDate()); aRow.setDEVDuedate(allDEVs.get(0).getDateCreated()); aRow.setUpdatedByUUID(allDEVs.get(0).getUpdatedByUUID()); // get history records List<AppProjectArtifactOwnersHistory> history = getStatusHistoryListByApplicationOwner( allDEVs.get(0)); if (!history.isEmpty()) { for (AppProjectArtifactOwnersHistory h : history) { // for percentage aRow.setDEV(aRow.getDEV() + "," + h.getPercentageComplete()); aRow.setDEVDuedate(aRow.getDEVDuedate() + "," + h.getDateLogged()); aRow.setUpdatedByUUID(aRow.getUpdatedByUUID() + "," + h.getUpdatedByUUID()); } } // after processing each history record aRow.setDEVStr(getRowDueDatePercentageString(aRow.getDEV(), aRow.getDEVDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getDEVheaderDueDate(), true, validateThreshold)); } // end processing isEmpty() else { aRow.setDEV("0%"); aRow.setDEVDuedate("NA"); aRow.setUpdatedByUUID("NA"); aRow.setDEVheaderDueDate("NA"); aRow.setDEVStr(getRowDueDatePercentageString(aRow.getDEV(), aRow.getDEVDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getDEVheaderDueDate(), true, validateThreshold)); } // end of DEV // 7. IST List<ProjectAppOwnerModel> allISTs = getProjectAppOwnerModelObjectByArtifactName( thisAppRows, PiratesConstants.IST); if (!allISTs.isEmpty()) { aRow.setIST(allISTs.get(0).getPercentageComplete()); aRow.setISTheaderDueDate(allISTs.get(0).getDueDate()); aRow.setISTDuedate(allISTs.get(0).getDateCreated()); aRow.setUpdatedByUUID(allISTs.get(0).getUpdatedByUUID()); // get history records List<AppProjectArtifactOwnersHistory> history = getStatusHistoryListByApplicationOwner( allISTs.get(0)); if (!history.isEmpty()) { for (AppProjectArtifactOwnersHistory h : history) { // for percentage aRow.setIST(aRow.getIST() + "," + h.getPercentageComplete()); aRow.setISTDuedate(aRow.getISTDuedate() + "," + h.getDateLogged()); aRow.setUpdatedByUUID(aRow.getUpdatedByUUID() + "," + h.getUpdatedByUUID()); } } // after processing each history record aRow.setISTStr(getRowDueDatePercentageString(aRow.getIST(), aRow.getISTDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getISTheaderDueDate(), true, validateThreshold)); } // end processing isEmpty() else { aRow.setIST("0%"); aRow.setISTDuedate("NA"); aRow.setUpdatedByUUID("NA"); aRow.setISTheaderDueDate("NA"); aRow.setISTStr(getRowDueDatePercentageString(aRow.getIST(), aRow.getISTDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getISTheaderDueDate(), true, validateThreshold)); } // end of IST // 8. ISTExec List<ProjectAppOwnerModel> allISTExecs = getProjectAppOwnerModelObjectByArtifactName( thisAppRows, PiratesConstants.ISTExec); if (!allISTExecs.isEmpty() && impactTypeId != 4) { aRow.setISTExec(allISTExecs.get(0).getPercentageComplete()); aRow.setISTExecheaderDueDate(allISTExecs.get(0).getDueDate()); aRow.setISTExecDuedate(allISTExecs.get(0).getDateCreated()); aRow.setUpdatedByUUID(allISTExecs.get(0).getUpdatedByUUID()); // get history records List<AppProjectArtifactOwnersHistory> history = getStatusHistoryListByApplicationOwner( allISTExecs.get(0)); if (!history.isEmpty()) { for (AppProjectArtifactOwnersHistory h : history) { // for percentage aRow.setISTExec(aRow.getISTExec() + "," + h.getPercentageComplete()); aRow.setISTExecDuedate(aRow.getISTExecDuedate() + "," + h.getDateLogged()); aRow.setUpdatedByUUID(aRow.getUpdatedByUUID() + "," + h.getUpdatedByUUID()); } } // after processing each history record aRow.setISTExecStr(getRowDueDatePercentageString(aRow.getISTExec(), aRow.getISTExecDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getISTExecheaderDueDate(), true, validateThreshold)); } // end processing isEmpty() else { aRow.setISTExec("0%"); aRow.setISTExecDuedate("NA"); aRow.setUpdatedByUUID("NA"); aRow.setISTExecheaderDueDate("NA"); aRow.setISTExecStr(getRowDueDatePercentageString(aRow.getISTExec(), aRow.getISTExecDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getISTExecheaderDueDate(), true, validateThreshold)); } // end of ISTExec // 9. CloseOut List<ProjectAppOwnerModel> allCloseout = getProjectAppOwnerModelObjectByArtifactName( thisAppRows, PiratesConstants.CLOSEOUT); if (!allCloseout.isEmpty()) { aRow.setCloseOut(allCloseout.get(0).getPercentageComplete()); aRow.setCloseOutheaderDueDate(allCloseout.get(0).getDueDate()); aRow.setCloseOutDuedate(allCloseout.get(0).getDateCreated()); aRow.setUpdatedByUUID(allCloseout.get(0).getUpdatedByUUID()); // get history records List<AppProjectArtifactOwnersHistory> history = getStatusHistoryListByApplicationOwner( allCloseout.get(0)); if (!history.isEmpty()) { for (AppProjectArtifactOwnersHistory h : history) { // for percentage aRow.setCloseOut(aRow.getCloseOut() + "," + h.getPercentageComplete()); aRow.setCloseOutDuedate(aRow.getCloseOutDuedate() + "," + h.getDateLogged()); aRow.setUpdatedByUUID(aRow.getUpdatedByUUID() + "," + h.getUpdatedByUUID()); } } // after processing each history record aRow.setCloseOutStr(getRowDueDatePercentageString(aRow.getCloseOut(), aRow.getCloseOutDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getCloseOutheaderDueDate(), true, validateThreshold)); } // end processing isEmpty() else { aRow.setCloseOut("0%"); aRow.setCloseOutDuedate("NA"); aRow.setUpdatedByUUID("NA"); aRow.setCloseOutheaderDueDate("NA"); aRow.setCloseOutStr(getRowDueDatePercentageString(aRow.getCloseOut(), aRow.getCloseOutDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getCloseOutheaderDueDate(), true, validateThreshold)); } // end of CloseOut // 10. Agile List<ProjectAppOwnerModel> allAgile = getProjectAppOwnerModelObjectByArtifactName( thisAppRows, PiratesConstants.AGILE); if (!allAgile.isEmpty()) { aRow.setAgile(allAgile.get(0).getPercentageComplete()); aRow.setAgileheaderDueDate(allAgile.get(0).getDueDate()); aRow.setAgileDuedate(allAgile.get(0).getDateCreated()); aRow.setUpdatedByUUID(allAgile.get(0).getUpdatedByUUID()); // get history records List<AppProjectArtifactOwnersHistory> history = getStatusHistoryListByApplicationOwner( allAgile.get(0)); if (!history.isEmpty()) { for (AppProjectArtifactOwnersHistory h : history) { // for percentage aRow.setAgile(aRow.getAgile() + "," + h.getPercentageComplete()); aRow.setAgileDuedate(aRow.getAgileDuedate() + "," + h.getDateLogged()); aRow.setUpdatedByUUID(aRow.getUpdatedByUUID() + "," + h.getUpdatedByUUID()); } } // after processing each history record aRow.setAgileStr(getRowDueDatePercentageString(aRow.getAgile(), aRow.getAgileDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getAgileheaderDueDate(), true, validateThreshold)); } // end processing isEmpty() else { aRow.setAgile("0%"); aRow.setAgileDuedate("NA"); aRow.setUpdatedByUUID("NA"); aRow.setAgileheaderDueDate("NA"); aRow.setAgileStr(getRowDueDatePercentageString(aRow.getAgile(), aRow.getAgileDuedate(), aRow.getUpdatedByUUID(), uuid, aRow.getAgileheaderDueDate(), true, validateThreshold)); } // end of Agile aRow.setPrismId(prismId); detailStatus.add(aRow); } // end thisAppRow.ANY() check } // end distinct appName loop } } catch (Exception ex) { logger.error(msgHeader + "Error occurred getProjectDetailsStatuc... " + ex.getMessage()); } // new code SimpleDateFormat yFormat = new SimpleDateFormat("MM/dd/yyyy"); List<Date> tmpDates = new ArrayList<Date>(); Date BR = null; Date SR = null; Date HLD = null; Date AID = null; Date AD = null; Date DEV = null; Date IST = null; Date ISTExec = null; Date CloseOut = null; Date Agile = null; // Process BR for (ProjectDetailsStatusViewModel i : detailStatus) { if (!("NA".equalsIgnoreCase(i.getBRheaderDueDate()))) { try { Date t = yFormat.parse(i.getBRheaderDueDate()); tmpDates.add(t); } catch (ParseException pe) { logger.error("can't parse date from value " + i.getBRheaderDueDate() + ", so skipping .. exception: " + pe.getMessage()); } } } if (tmpDates.size() > 0) { // sort all BRduedates, pick the earliest one as the final one Collections.sort(tmpDates, new Comparator<Date>() { @Override public int compare(Date o1, Date o2) { return o1.compareTo(o2); } }); BR = tmpDates.get(0); } tmpDates.clear(); // Process SR for (ProjectDetailsStatusViewModel i : detailStatus) { if (!("NA".equalsIgnoreCase(i.getSRheaderDueDate()))) { try { Date t = yFormat.parse(i.getSRheaderDueDate()); tmpDates.add(t); } catch (ParseException pe) { logger.error("can't parse date from value " + i.getSRheaderDueDate() + ", so skipping .. exception: " + pe.getMessage()); } } } if (tmpDates.size() > 0) { // sort all BRduedates, pick the earliest one as the final one Collections.sort(tmpDates, new Comparator<Date>() { @Override public int compare(Date o1, Date o2) { return o1.compareTo(o2); } }); SR = tmpDates.get(0); } tmpDates.clear(); // Process HLD for (ProjectDetailsStatusViewModel i : detailStatus) { if (!("NA".equalsIgnoreCase(i.getHLDheaderDueDate()))) { try { Date t = yFormat.parse(i.getHLDheaderDueDate()); tmpDates.add(t); } catch (ParseException pe) { logger.error("can't parse date from value " + i.getHLDheaderDueDate() + ", so skipping .. exception: " + pe.getMessage()); } } } if (tmpDates.size() > 0) { // sort all BRduedates, pick the earliest one as the final one Collections.sort(tmpDates, new Comparator<Date>() { @Override public int compare(Date o1, Date o2) { return o1.compareTo(o2); } }); HLD = tmpDates.get(0); } tmpDates.clear(); // Process AID for (ProjectDetailsStatusViewModel i : detailStatus) { if (!("NA".equalsIgnoreCase(i.getAIDheaderDueDate()))) { try { Date t = yFormat.parse(i.getAIDheaderDueDate()); tmpDates.add(t); } catch (ParseException pe) { logger.error("can't parse date from value " + i.getAIDheaderDueDate() + ", so skipping .. exception: " + pe.getMessage()); } } } if (tmpDates.size() > 0) { // sort all BRduedates, pick the earliest one as the final one Collections.sort(tmpDates, new Comparator<Date>() { @Override public int compare(Date o1, Date o2) { return o1.compareTo(o2); } }); AID = tmpDates.get(0); } tmpDates.clear(); // Process AD for (ProjectDetailsStatusViewModel i : detailStatus) { if (!("NA".equalsIgnoreCase(i.getDESheaderDueDate()))) { try { Date t = yFormat.parse(i.getDESheaderDueDate()); tmpDates.add(t); } catch (ParseException pe) { logger.error("can't parse date from value " + i.getDESheaderDueDate() + ", so skipping .. exception: " + pe.getMessage()); } } } if (tmpDates.size() > 0) { // sort all BRduedates, pick the earliest one as the final one Collections.sort(tmpDates, new Comparator<Date>() { @Override public int compare(Date o1, Date o2) { return o1.compareTo(o2); } }); AD = tmpDates.get(0); } tmpDates.clear(); // Process DEV for (ProjectDetailsStatusViewModel i : detailStatus) { if (!("NA".equalsIgnoreCase(i.getDEVheaderDueDate()))) { try { Date t = yFormat.parse(i.getDEVheaderDueDate()); tmpDates.add(t); } catch (ParseException pe) { logger.error("can't parse date from value " + i.getDEVheaderDueDate() + ", so skipping .. exception: " + pe.getMessage()); } } } if (tmpDates.size() > 0) { // sort all BRduedates, pick the earliest one as the final one Collections.sort(tmpDates, new Comparator<Date>() { @Override public int compare(Date o1, Date o2) { return o1.compareTo(o2); } }); DEV = tmpDates.get(0); } tmpDates.clear(); // Process IST for (ProjectDetailsStatusViewModel i : detailStatus) { if (!("NA".equalsIgnoreCase(i.getISTheaderDueDate()))) { try { Date t = yFormat.parse(i.getISTheaderDueDate()); tmpDates.add(t); } catch (ParseException pe) { logger.error("can't parse date from value " + i.getISTheaderDueDate() + ", so skipping .. exception: " + pe.getMessage()); } } } if (tmpDates.size() > 0) { // sort all BRduedates, pick the earliest one as the final one Collections.sort(tmpDates, new Comparator<Date>() { @Override public int compare(Date o1, Date o2) { return o1.compareTo(o2); } }); IST = tmpDates.get(0); } tmpDates.clear(); // Process ISTExec for (ProjectDetailsStatusViewModel i : detailStatus) { if (!("NA".equalsIgnoreCase(i.getISTExecheaderDueDate()))) { try { Date t = yFormat.parse(i.getISTExecheaderDueDate()); tmpDates.add(t); } catch (ParseException pe) { logger.error("can't parse date from value " + i.getISTExecheaderDueDate() + ", so skipping .. exception: " + pe.getMessage()); } } } if (tmpDates.size() > 0) { // sort all BRduedates, pick the earliest one as the final one Collections.sort(tmpDates, new Comparator<Date>() { @Override public int compare(Date o1, Date o2) { return o1.compareTo(o2); } }); ISTExec = tmpDates.get(0); } tmpDates.clear(); // Process Closeout for (ProjectDetailsStatusViewModel i : detailStatus) { if (!("NA".equalsIgnoreCase(i.getCloseOutheaderDueDate()))) { try { Date t = yFormat.parse(i.getCloseOutheaderDueDate()); tmpDates.add(t); } catch (ParseException pe) { logger.error("can't parse date from value " + i.getCloseOutheaderDueDate() + ", so skipping .. exception: " + pe.getMessage()); } } } if (tmpDates.size() > 0) { // sort all BRduedates, pick the earliest one as the final one Collections.sort(tmpDates, new Comparator<Date>() { @Override public int compare(Date o1, Date o2) { return o1.compareTo(o2); } }); CloseOut = tmpDates.get(0); } tmpDates.clear(); // Process Agile for (ProjectDetailsStatusViewModel i : detailStatus) { if (!("NA".equalsIgnoreCase(i.getAgileheaderDueDate()))) { try { Date t = yFormat.parse(i.getAgileheaderDueDate()); tmpDates.add(t); } catch (ParseException pe) { logger.error("can't parse date from value " + i.getAgileheaderDueDate() + ", so skipping .. exception: " + pe.getMessage()); } } } if (tmpDates.size() > 0) { // sort all BRduedates, pick the earliest one as the final one Collections.sort(tmpDates, new Comparator<Date>() { @Override public int compare(Date o1, Date o2) { return o1.compareTo(o2); } }); Agile = tmpDates.get(0); } tmpDates.clear(); // TODO if (BR != null) { try { for (ProjectDetailsStatusViewModel i : detailStatus) { i.setBRheaderDueDate(yFormat.format(BR)); } } catch (Exception pe) { logger.error("Can not convert BR from Date " + BR.toString() + ", pe: " + pe.getMessage() + ". Skipping.."); } } if (SR != null) { try { for (ProjectDetailsStatusViewModel i : detailStatus) { i.setSRheaderDueDate(yFormat.format(SR)); } } catch (Exception pe) { logger.error("Can not convert SR from Date " + SR.toString() + ", pe: " + pe.getMessage() + ". Skipping.."); } } if (HLD != null) { try { for (ProjectDetailsStatusViewModel i : detailStatus) { i.setHLDheaderDueDate(yFormat.format(HLD)); } } catch (Exception pe) { logger.error("Can not convert HLD from Date " + HLD.toString() + ", pe: " + pe.getMessage() + ". Skipping.."); } } if (AID != null) { try { for (ProjectDetailsStatusViewModel i : detailStatus) { i.setAIDheaderDueDate(yFormat.format(AID)); } } catch (Exception pe) { logger.error("Can not convert AID from Date " + AID.toString() + ", pe: " + pe.getMessage() + ". Skipping.."); } } if (AD != null) { try { for (ProjectDetailsStatusViewModel i : detailStatus) { i.setDESheaderDueDate(yFormat.format(AD)); } } catch (Exception pe) { logger.error("Can not convert AD from Date " + AD.toString() + ", pe: " + pe.getMessage() + ". Skipping.."); } } if (DEV != null) { try { for (ProjectDetailsStatusViewModel i : detailStatus) { i.setDEVheaderDueDate(yFormat.format(DEV)); } } catch (Exception pe) { logger.error("Can not convert DEV from Date " + DEV.toString() + ", pe: " + pe.getMessage() + ". Skipping.."); } } if (IST != null) { try { for (ProjectDetailsStatusViewModel i : detailStatus) { i.setISTheaderDueDate(yFormat.format(IST)); } } catch (Exception pe) { logger.error("Can not convert IST from Date " + IST.toString() + ", pe: " + pe.getMessage() + ". Skipping.."); } } if (ISTExec != null) { try { for (ProjectDetailsStatusViewModel i : detailStatus) { i.setISTExecheaderDueDate(yFormat.format(ISTExec)); } } catch (Exception pe) { logger.error("Can not convert ISTExec from Date " + ISTExec.toString() + ", pe: " + pe.getMessage() + ". Skipping.."); } } if (CloseOut != null) { try { for (ProjectDetailsStatusViewModel i : detailStatus) { i.setCloseOutheaderDueDate(yFormat.format(CloseOut)); } } catch (Exception pe) { logger.error("Can not convert CloseOut from Date " + CloseOut.toString() + ", pe: " + pe.getMessage() + ". Skipping.."); } } if (Agile != null) { try { for (ProjectDetailsStatusViewModel i : detailStatus) { i.setAgileheaderDueDate(yFormat.format(Agile)); } } catch (Exception pe) { logger.error("Can not convert Agile from Date " + Agile.toString() + ", pe: " + pe.getMessage() + ". Skipping.."); } } return detailStatus; }
From source file:org.eclipse.smarthome.binding.sonos.internal.handler.ZonePlayerHandler.java
public void setAlarm(boolean alarmSwitch) { List<SonosAlarm> sonosAlarms = getCurrentAlarmList(); // find the nearest alarm - take the current time from the Sonos system, // not the system where we are running SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); fmt.setTimeZone(TimeZone.getTimeZone("GMT")); String currentLocalTime = getTime(); Date currentDateTime = null;// w w w.j a va2 s . c o m try { currentDateTime = fmt.parse(currentLocalTime); } catch (ParseException e) { logger.debug("An exception occurred while formatting a date", e); } if (currentDateTime != null) { Calendar currentDateTimeCalendar = Calendar.getInstance(); currentDateTimeCalendar.setTimeZone(TimeZone.getTimeZone("GMT")); currentDateTimeCalendar.setTime(currentDateTime); currentDateTimeCalendar.add(Calendar.DAY_OF_YEAR, 10); long shortestDuration = currentDateTimeCalendar.getTimeInMillis() - currentDateTime.getTime(); SonosAlarm firstAlarm = null; for (SonosAlarm anAlarm : sonosAlarms) { SimpleDateFormat durationFormat = new SimpleDateFormat("HH:mm:ss"); durationFormat.setTimeZone(TimeZone.getTimeZone("GMT")); Date durationDate; try { durationDate = durationFormat.parse(anAlarm.getDuration()); } catch (ParseException e) { logger.debug("An exception occurred while parsing a date : '{}'", e.getMessage()); continue; } long duration = durationDate.getTime(); if (duration < shortestDuration && anAlarm.getRoomUUID().equals(getUDN())) { shortestDuration = duration; firstAlarm = anAlarm; } } // Set the Alarm if (firstAlarm != null) { if (alarmSwitch) { firstAlarm.setEnabled(true); } else { firstAlarm.setEnabled(false); } updateAlarm(firstAlarm); } } }
From source file:net.alexjf.tmm.fragments.ImmedTransactionEditorFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_immedtransaction_editor, container, false); descriptionText = (EditText) v.findViewById(R.id.description_text); categoryButton = (SelectorButton) v.findViewById(R.id.category_button); executionDateButton = (Button) v.findViewById(R.id.executionDate_button); executionTimeButton = (Button) v.findViewById(R.id.executionTime_button); valueSignToggle = (SignToggleButton) v.findViewById(R.id.value_sign); valueText = (EditText) v.findViewById(R.id.value_text); currencyTextView = (TextView) v.findViewById(R.id.currency_label); transferCheck = (CheckBox) v.findViewById(R.id.transfer_check); transferPanel = (LinearLayout) v.findViewById(R.id.transfer_panel); transferMoneyNodeLabel = (TextView) v.findViewById(R.id.transfer_moneynode_label); transferMoneyNodeButton = (SelectorButton) v.findViewById(R.id.transfer_moneynode_button); transferConversionPanel = (LinearLayout) v.findViewById(R.id.transfer_conversion_panel); transferConversionAmountText = (EditText) v.findViewById(R.id.transfer_conversion_amount_value); transferConversionCurrencyLabel = (TextView) v.findViewById(R.id.transfer_conversion_amount_currency); addButton = (Button) v.findViewById(R.id.add_button); valueText.setRawInputType(InputType.TYPE_CLASS_NUMBER); FragmentManager fm = getFragmentManager(); timePicker = (TimePickerFragment) fm.findFragmentByTag(TAG_TIMEPICKER); datePicker = (DatePickerFragment) fm.findFragmentByTag(TAG_DATEPICKER); if (timePicker == null) { timePicker = new TimePickerFragment(); }/*from w ww .j a va2s .c o m*/ if (datePicker == null) { datePicker = new DatePickerFragment(); } timePicker.setListener(this); datePicker.setListener(this); categoryButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent intent = new Intent(view.getContext(), CategoryListActivity.class); intent.putExtra(CategoryListActivity.KEY_INTENTION, CategoryListActivity.INTENTION_SELECT); startActivityForResult(intent, REQCODE_CATEGORYCHOOSE); } }); executionDateButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { try { datePicker.setDate(dateFormat.parse(executionDateButton.getText().toString())); } catch (ParseException e) { } datePicker.show(getFragmentManager(), TAG_DATEPICKER); } }); executionTimeButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { try { timePicker.setTime(timeFormat.parse(executionTimeButton.getText().toString())); } catch (ParseException e) { } timePicker.show(getFragmentManager(), TAG_TIMEPICKER); } }); valueSignToggle.setOnChangeListener(new SignToggleButton.SignToggleButtonListener() { @Override public void onChange(boolean isPositive) { if (isPositive) { transferMoneyNodeLabel.setText(getResources().getString(R.string.transfer_moneynode_from)); } else { transferMoneyNodeLabel.setText(getResources().getString(R.string.transfer_moneynode_to)); } } }); transferCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton view, boolean checked) { if (checked) { transferPanel.setVisibility(View.VISIBLE); } else { transferPanel.setVisibility(View.GONE); } } ; }); transferMoneyNodeButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent intent = new Intent(view.getContext(), MoneyNodeListActivity.class); intent.putExtra(MoneyNodeListActivity.KEY_INTENTION, MoneyNodeListActivity.INTENTION_SELECT); ArrayList<MoneyNode> excludedMoneyNodes = new ArrayList<MoneyNode>(); excludedMoneyNodes.add(currentMoneyNode); intent.putParcelableArrayListExtra(MoneyNodeListActivity.KEY_EXCLUDE, excludedMoneyNodes); startActivityForResult(intent, REQCODE_MONEYNODECHOOSE); } }); addButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { if (!validateInputFields()) { return; } String description = descriptionText.getText().toString().trim(); boolean isTransfer = transferCheck.isChecked(); Date executionDate; Date executionTime; Date executionDateTime; try { executionDate = dateFormat.parse(executionDateButton.getText().toString()); executionTime = timeFormat.parse(executionTimeButton.getText().toString()); } catch (ParseException e) { executionTime = executionDate = new Date(); } executionDateTime = Utils.combineDateTime(executionDate, executionTime); Money value; try { Calculable calc = new ExpressionBuilder(valueText.getText().toString()).build(); value = Money.of(currentMoneyNode.getCurrency(), calc.calculate(), RoundingMode.HALF_EVEN); } catch (Exception e) { Log.e("TMM", "Error calculating value expression: " + e.getMessage(), e); value = Money.zero(currentMoneyNode.getCurrency()); } if (valueSignToggle.isNegative()) { value = value.negated(); } Money currencyConversionValue = null; // If an amount was entered for conversion to other currency, set // value of transfer transaction to this amount if (isTransfer && !TextUtils.isEmpty(transferConversionAmountText.getText())) { try { Calculable calc = new ExpressionBuilder(transferConversionAmountText.getText().toString()) .build(); currencyConversionValue = Money.of(selectedTransferMoneyNode.getCurrency(), calc.calculate(), RoundingMode.HALF_EVEN); currencyConversionValue = currencyConversionValue.abs(); } catch (Exception e) { Log.e("TMM", "Error calculating conversion amount expression: " + e.getMessage(), e); currencyConversionValue = Money.zero(selectedTransferMoneyNode.getCurrency()); } if (!valueSignToggle.isNegative()) { currencyConversionValue = currencyConversionValue.negated(); } } // If we are creating a new transaction if (transaction == null) { ImmediateTransaction newTransaction = new ImmediateTransaction(currentMoneyNode, value, description, selectedCategory, executionDateTime); // If this new transaction is a transfer if (isTransfer && selectedTransferMoneyNode != null) { ImmediateTransaction otherTransaction = new ImmediateTransaction(newTransaction, selectedTransferMoneyNode); // If a value was specified for the conversion to other currency, // use that value instead of the negation of current one if (currencyConversionValue != null) { otherTransaction.setValue(currencyConversionValue); } newTransaction.setTransferTransaction(otherTransaction); otherTransaction.setTransferTransaction(newTransaction); } listener.onImmediateTransactionCreated(newTransaction); } // If we are updating an existing transaction else { ImmedTransactionEditOldInfo oldInfo = new ImmedTransactionEditOldInfo(transaction); transaction.setDescription(description); transaction.setCategory(selectedCategory); transaction.setExecutionDate(executionDateTime); transaction.setValue(value); if (isTransfer && selectedTransferMoneyNode != null) { ImmediateTransaction otherTransaction = null; // If edited transaction wasn't part of a transfer and // now is, create transfer transaction if (transaction.getTransferTransaction() == null) { otherTransaction = new ImmediateTransaction(transaction, selectedTransferMoneyNode); transaction.setTransferTransaction(otherTransaction); otherTransaction.setTransferTransaction(transaction); } // If edited transaction was already part of a // transfer, update transfer transaction else { otherTransaction = transaction.getTransferTransaction(); otherTransaction.setMoneyNode(selectedTransferMoneyNode); otherTransaction.setDescription(description); otherTransaction.setCategory(selectedCategory); otherTransaction.setExecutionDate(executionDateTime); otherTransaction.setValue(value.negated()); } // If a value was specified for the conversion to other currency, // use that value instead of the negation of current one if (currencyConversionValue != null) { otherTransaction.setValue(currencyConversionValue); } } // If edited transaction no longer is a transfer but // was a transfer before, we need to remove the opposite // transaction. else if (transaction.getTransferTransaction() != null) { transaction.setTransferTransaction(null); } listener.onImmediateTransactionEdited(transaction, oldInfo); } } }); this.savedInstanceState = savedInstanceState; return v; }
From source file:edu.hawaii.soest.kilonalu.ctd.CTDSource.java
/** * A method that executes the streaming of data from the source to the RBNB * server after all configuration of settings, connections to hosts, and * thread initiatizing occurs. This method contains the detailed code for * streaming the data and interpreting the stream. */// www . ja v a 2 s . c o m protected boolean execute() { logger.debug("CTDSource.execute() called."); // do not execute the stream if there is no connection if (!isConnected()) return false; boolean failed = false; // test the connection type if (this.connectionType.equals("serial")) { // create a serial connection to the local serial port this.channel = getSerialConnection(); } else if (this.connectionType.equals("socket")) { // otherwise create a TCP or UDP socket connection to the remote host this.channel = getSocketConnection(); } else { logger.info("There was an error establishing either a serial or " + "socket connection to the instrument. Please be sure " + "the connection type is set to either 'serial' or 'socket'."); return false; } // while data are being sent, read them into the buffer try { // create four byte placeholders used to evaluate up to a four-byte // window. The FIFO layout looks like: // ------------------------- // in ---> | One | Two |Three|Four | ---> out // ------------------------- byte byteOne = 0x00, // set initial placeholder values byteTwo = 0x00, byteThree = 0x00, byteFour = 0x00; // Create a buffer that will store the sample bytes as they are read ByteBuffer sampleBuffer = ByteBuffer.allocate(getBufferSize()); // Declare sample variables to be used in the response parsing byte[] sampleArray; // create a byte buffer to store bytes from the TCP stream ByteBuffer buffer = ByteBuffer.allocateDirect(getBufferSize()); // add a channel of data that will be pushed to the server. // Each sample will be sent to the Data Turbine as an rbnb frame. ChannelMap rbnbChannelMap = new ChannelMap(); // while there are bytes to read from the channel ... while (this.channel.read(buffer) != -1 || buffer.position() > 0) { // prepare the buffer for reading buffer.flip(); // while there are unread bytes in the ByteBuffer while (buffer.hasRemaining()) { byteOne = buffer.get(); logger.debug("b1: " + new String(Hex.encodeHex((new byte[] { byteOne }))) + "\t" + "b2: " + new String(Hex.encodeHex((new byte[] { byteTwo }))) + "\t" + "b3: " + new String(Hex.encodeHex((new byte[] { byteThree }))) + "\t" + "b4: " + new String(Hex.encodeHex((new byte[] { byteFour }))) + "\t" + "sample pos: " + sampleBuffer.position() + "\t" + "sample rem: " + sampleBuffer.remaining() + "\t" + "sample cnt: " + sampleByteCount + "\t" + "buffer pos: " + buffer.position() + "\t" + "buffer rem: " + buffer.remaining() + "\t" + "state: " + this.state); // Use a State Machine to process the byte stream. // Start building an rbnb frame for the entire sample, first by // inserting a timestamp into the channelMap. This time is merely // the time of insert into the data turbine, not the time of // observations of the measurements. That time should be parsed out // of the sample in the Sink client code switch (this.state) { case 0: // wake up the instrument // check for instrument metadata fields if (this.enableSendCommands && !this.hasMetadata) { // wake the instrument with an initial '\r\n' command this.command = this.commandSuffix; this.sentCommand = queryInstrument(this.command); this.sentCommand = queryInstrument(this.command); streamingThread.sleep(2000); this.state = 1; break; } else { this.state = 11; break; } case 1: // stop the sampling // be sure the instrument woke (look for S> prompt) //if (byteOne == 0x3E && byteTwo == 0x53 ) { // // sampleByteCount = 0; // sampleBuffer.clear(); // // // send the stop sampling command this.command = this.commandPrefix + this.stopSamplingCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); sampleBuffer.clear(); sampleByteCount = 0; this.state = 2; break; //} else { // // handle instrument hardware response // sampleByteCount++; // add the last byte found to the count // // // add the last byte found to the sample buffer // if ( sampleBuffer.remaining() > 0 ) { // sampleBuffer.put(byteOne); // // } else { // sampleBuffer.compact(); // sampleBuffer.put(byteOne); // // } // // break; // continue reading bytes // //} case 2: // based on outputType, get metadata from the instrument // the response should end in <Executed/> if (byteOne == 0x3E && byteTwo == 0x2F && byteThree == 0x64 && byteFour == 0x65) { sampleBuffer.clear(); sampleByteCount = 0; this.samplingIsStopped = true; // for newer firmware CTDs, use xml-based query commands if (getOutputType().equals("xml")) { // create the CTD parser instance used to parse CTD output this.ctdParser = new CTDParser(); this.state = 3; break; // otherwise, use text-based query commands } else if (getOutputType().equals("text")) { this.state = 12; // process DS and DCal commands break; } else { logger.info("The CTD output type is not recognized. " + "Please set the output type to either " + "'xml' or 'text'."); failed = true; this.state = 0; // close the serial or socket channel if (this.channel != null && this.channel.isOpen()) { try { this.channel.close(); } catch (IOException cioe) { logger.debug("An error occurred trying to close the byte channel. " + " The error message was: " + cioe.getMessage()); return !failed; } } // disconnect from the RBNB if (isConnected()) { disconnect(); } return !failed; } } else { // handle instrument hardware response sampleByteCount++; // add the last byte found to the count // add the last byte found to the sample buffer if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); sampleBuffer.put(byteOne); } break; // continue reading bytes } case 3: // get the instrument status metadata if (!this.ctdParser.getHasStatusMetadata()) { this.command = this.commandPrefix + this.getStatusCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); streamingThread.sleep(5000); this.state = 4; break; } else { // get the configuration metadata this.command = this.commandPrefix + this.getConfigurationCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); streamingThread.sleep(5000); this.state = 5; break; } case 4: // handle instrument status response // command response ends with <Executed/> (so find: ed/>) if (byteOne == 0x3E && byteTwo == 0x2F && byteThree == 0x64 && byteFour == 0x65) { // handle instrument status response sampleByteCount++; // add the last byte found to the count // add the last byte found to the sample buffer if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); sampleBuffer.put(byteOne); } // extract the sampleByteCount length from the sampleBuffer sampleArray = new byte[sampleByteCount]; sampleBuffer.flip(); sampleBuffer.get(sampleArray); this.responseString = new String(sampleArray, "US-ASCII"); // set the CTD metadata int executedIndex = this.responseString.indexOf("<Executed/>"); this.responseString = this.responseString.substring(0, executedIndex - 1); this.ctdParser.setMetadata(this.responseString); // reset variables for the next sample sampleBuffer.clear(); sampleByteCount = 0; // then get the instrument configuration metadata if (!this.ctdParser.getHasConfigurationMetadata()) { this.command = this.commandPrefix + this.getConfigurationCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); streamingThread.sleep(5000); this.state = 5; break; } else { // get the calibration metadata this.command = this.commandPrefix + this.getCalibrationCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); streamingThread.sleep(5000); this.state = 6; break; } } else { break; // continue reading bytes } case 5: // handle the instrument configuration metadata // command response ends with <Executed/> (so find: ed/>) if (byteOne == 0x3E && byteTwo == 0x2F && byteThree == 0x64 && byteFour == 0x65) { // handle instrument configration response sampleByteCount++; // add the last byte found to the count // add the last byte found to the sample buffer if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); sampleBuffer.put(byteOne); } // extract the sampleByteCount length from the sampleBuffer sampleArray = new byte[sampleByteCount]; sampleBuffer.flip(); sampleBuffer.get(sampleArray); this.responseString = new String(sampleArray, "US-ASCII"); // set the CTD metadata int executedIndex = this.responseString.indexOf("<Executed/>"); this.responseString = this.responseString.substring(0, executedIndex - 1); this.ctdParser.setMetadata(this.responseString); // reset variables for the next sample sampleBuffer.clear(); sampleByteCount = 0; // then get the instrument calibration metadata if (!this.ctdParser.getHasCalibrationMetadata()) { this.command = this.commandPrefix + this.getCalibrationCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); streamingThread.sleep(5000); this.state = 6; break; } else { this.command = this.commandPrefix + this.getEventsCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); streamingThread.sleep(5000); this.state = 7; break; } } else { break; // continue reading bytes } case 6: // handle the instrument calibration metadata // command response ends with <Executed/> (so find: ed/>) if (byteOne == 0x3E && byteTwo == 0x2F && byteThree == 0x64 && byteFour == 0x65) { // handle instrument calibration response sampleByteCount++; // add the last byte found to the count // add the last byte found to the sample buffer if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); sampleBuffer.put(byteOne); } // extract the sampleByteCount length from the sampleBuffer sampleArray = new byte[sampleByteCount]; sampleBuffer.flip(); sampleBuffer.get(sampleArray); this.responseString = new String(sampleArray, "US-ASCII"); // set the CTD metadata int executedIndex = this.responseString.indexOf("<Executed/>"); this.responseString = this.responseString.substring(0, executedIndex - 1); this.ctdParser.setMetadata(this.responseString); // reset variables for the next sample sampleBuffer.clear(); sampleByteCount = 0; // then get the instrument event metadata if (!this.ctdParser.getHasEventMetadata()) { this.command = this.commandPrefix + this.getEventsCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); streamingThread.sleep(5000); this.state = 7; break; } else { this.command = this.commandPrefix + this.getHardwareCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); streamingThread.sleep(5000); this.state = 8; break; } } else { break; // continue reading bytes } case 7: // handle instrument event metadata // command response ends with <Executed/> (so find: ed/>) if (byteOne == 0x3E && byteTwo == 0x2F && byteThree == 0x64 && byteFour == 0x65) { // handle instrument events response sampleByteCount++; // add the last byte found to the count // add the last byte found to the sample buffer if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); sampleBuffer.put(byteOne); } // extract the sampleByteCount length from the sampleBuffer sampleArray = new byte[sampleByteCount]; sampleBuffer.flip(); sampleBuffer.get(sampleArray); this.responseString = new String(sampleArray, "US-ASCII"); // set the CTD metadata int executedIndex = this.responseString.indexOf("<Executed/>"); this.responseString = this.responseString.substring(0, executedIndex - 1); this.ctdParser.setMetadata(this.responseString); // reset variables for the next sample sampleBuffer.clear(); sampleByteCount = 0; // then get the instrument hardware metadata if (!this.ctdParser.getHasHardwareMetadata()) { this.command = this.commandPrefix + this.getHardwareCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); streamingThread.sleep(5000); this.state = 8; break; } else { this.state = 9; break; } } else { break; // continue reading bytes } case 8: // handle the instrument hardware response // command response ends with <Executed/> (so find: ed/>) if (byteOne == 0x3E && byteTwo == 0x2F && byteThree == 0x64 && byteFour == 0x65) { // handle instrument hardware response sampleByteCount++; // add the last byte found to the count // add the last byte found to the sample buffer if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); sampleBuffer.put(byteOne); } // extract the sampleByteCount length from the sampleBuffer sampleArray = new byte[sampleByteCount]; sampleBuffer.flip(); sampleBuffer.get(sampleArray); this.responseString = new String(sampleArray, "US-ASCII"); // set the CTD metadata int executedIndex = this.responseString.indexOf("<Executed/>"); this.responseString = this.responseString.substring(0, executedIndex - 1); this.ctdParser.setMetadata(this.responseString); // reset variables for the next sample sampleBuffer.clear(); sampleByteCount = 0; // sync the clock if it is not synced if (!this.clockIsSynced) { this.state = 9; break; } else { this.state = 10; break; } } else { break; // continue reading bytes } case 9: // set the instrument clock // is sampling stopped? if (!this.samplingIsStopped) { // wake the instrument with an initial '\r\n' command this.command = this.commandSuffix; this.sentCommand = queryInstrument(this.command); streamingThread.sleep(2000); // then stop the sampling this.command = this.commandPrefix + this.stopSamplingCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); this.samplingIsStopped = true; } // now set the clock if (this.sentCommand) { this.clockSyncDate = new Date(); DATE_FORMAT.setTimeZone(TZ); String dateAsString = DATE_FORMAT.format(this.clockSyncDate); this.command = this.commandPrefix + this.setDateTimeCommand + dateAsString + this.commandSuffix; this.sentCommand = queryInstrument(command); streamingThread.sleep(5000); this.clockIsSynced = true; logger.info("The instrument clock has bee synced at " + this.clockSyncDate.toString()); this.state = 10; break; } else { break; // try the clock sync again due to failure } case 10: // restart the instrument sampling if (this.samplingIsStopped) { this.hasMetadata = true; this.command = this.commandPrefix + this.startSamplingCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); streamingThread.sleep(5000); if (this.sentCommand) { this.state = 11; break; } else { break; // try starting the sampling again due to failure } } else { break; } case 11: // read bytes to the next EOL characters // sample line is terminated by \r\n // note bytes are in reverse order in the FIFO window if (byteOne == 0x0A && byteTwo == 0x0D) { sampleByteCount++; // add the last byte found to the count // add the last byte found to the sample buffer if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); sampleBuffer.put(byteOne); } // extract just the length of the sample bytes out of the // sample buffer, and place it in the channel map as a // byte array. Then, send it to the data turbine. sampleArray = new byte[sampleByteCount]; sampleBuffer.flip(); sampleBuffer.get(sampleArray); this.responseString = new String(sampleArray, "US-ASCII"); // test if the sample is not just an instrument message if (this.responseString.matches("^# [0-9].*\r\n") || this.responseString.matches("^# [0-9].*\r\n") || this.responseString.matches("^ [0-9].*\r\n")) { // add the data observations string to the CTDParser object // and populate the CTDParser data fields //this.ctdParser.setData(this.responseString); //this.ctdParser.parse(); // build the channel map with all of the data and metadata channels: int channelIndex = rbnbChannelMap.Add(getRBNBChannelName()); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutTimeAuto("server"); // add the ASCII sample data field rbnbChannelMap.PutDataAsString(channelIndex, this.responseString); // add other metadata and data fields to the map if metadata was collected if (this.hasMetadata && this.ctdParser != null) { // add the samplingMode field data channelIndex = rbnbChannelMap.Add("samplingMode"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getSamplingMode()); // String // add the temperatureSerialNumber field data channelIndex = rbnbChannelMap.Add("temperatureSerialNumber"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getTemperatureSerialNumber()); // String // add the conductivitySerialNumber field data channelIndex = rbnbChannelMap.Add("conductivitySerialNumber"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getConductivitySerialNumber()); // String // add the mainBatteryVoltage field data channelIndex = rbnbChannelMap.Add("mainBatteryVoltage"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getMainBatteryVoltage() }); // double // add the lithiumBatteryVoltage field data channelIndex = rbnbChannelMap.Add("lithiumBatteryVoltage"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getLithiumBatteryVoltage() }); // double // add the operatingCurrent field data channelIndex = rbnbChannelMap.Add("operatingCurrent"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getOperatingCurrent() }); // double // add the pumpCurrent field data channelIndex = rbnbChannelMap.Add("pumpCurrent"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getPumpCurrent() }); // double // add the channels01ExternalCurrent field data channelIndex = rbnbChannelMap.Add("channels01ExternalCurrent"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getChannels01ExternalCurrent() }); // double // add the channels23ExternalCurrent field data channelIndex = rbnbChannelMap.Add("channels23ExternalCurrent"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getChannels23ExternalCurrent() }); // double // add the loggingStatus field data channelIndex = rbnbChannelMap.Add("loggingStatus"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getLoggingStatus()); // String // add the numberOfScansToAverage field data channelIndex = rbnbChannelMap.Add("numberOfScansToAverage"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { this.ctdParser.getNumberOfScansToAverage() }); // int // add the numberOfSamples field data channelIndex = rbnbChannelMap.Add("numberOfSamples"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { this.ctdParser.getNumberOfSamples() }); // int // add the numberOfAvailableSamples field data channelIndex = rbnbChannelMap.Add("numberOfAvailableSamples"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { this.ctdParser.getNumberOfAvailableSamples() }); // int // add the sampleInterval field data channelIndex = rbnbChannelMap.Add("sampleInterval"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { this.ctdParser.getSampleInterval() }); // int // add the measurementsPerSample field data channelIndex = rbnbChannelMap.Add("measurementsPerSample"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { this.ctdParser.getMeasurementsPerSample() }); // int // add the transmitRealtime field data channelIndex = rbnbChannelMap.Add("transmitRealtime"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getTransmitRealtime()); // String // add the numberOfCasts field data channelIndex = rbnbChannelMap.Add("numberOfCasts"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { this.ctdParser.getNumberOfCasts() }); // int // add the minimumConductivityFrequency field data channelIndex = rbnbChannelMap.Add("minimumConductivityFrequency"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { this.ctdParser.getMinimumConductivityFrequency() }); // int // add the pumpDelay field data channelIndex = rbnbChannelMap.Add("pumpDelay"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { this.ctdParser.getPumpDelay() }); // int // add the automaticLogging field data channelIndex = rbnbChannelMap.Add("automaticLogging"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getAutomaticLogging()); // String // add the ignoreMagneticSwitch field data channelIndex = rbnbChannelMap.Add("ignoreMagneticSwitch"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getIgnoreMagneticSwitch()); // String // add the batteryType field data channelIndex = rbnbChannelMap.Add("batteryType"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getBatteryType()); // String // add the batteryCutoff field data channelIndex = rbnbChannelMap.Add("batteryCutoff"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getBatteryCutoff()); // String // add the pressureSensorType field data channelIndex = rbnbChannelMap.Add("pressureSensorType"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getPressureSensorType()); // String // add the pressureSensorRange field data channelIndex = rbnbChannelMap.Add("pressureSensorRange"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getPressureSensorRange()); // String // add the sbe38TemperatureSensor field data channelIndex = rbnbChannelMap.Add("sbe38TemperatureSensor"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getSbe38TemperatureSensor()); // String // add the gasTensionDevice field data channelIndex = rbnbChannelMap.Add("gasTensionDevice"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getGasTensionDevice()); // String // add the externalVoltageChannelZero field data channelIndex = rbnbChannelMap.Add("externalVoltageChannelZero"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getExternalVoltageChannelZero()); // String // add the externalVoltageChannelOne field data channelIndex = rbnbChannelMap.Add("externalVoltageChannelOne"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getExternalVoltageChannelOne()); // String // add the externalVoltageChannelTwo field data channelIndex = rbnbChannelMap.Add("externalVoltageChannelTwo"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getExternalVoltageChannelTwo()); // String // add the externalVoltageChannelThree field data channelIndex = rbnbChannelMap.Add("externalVoltageChannelThree"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getExternalVoltageChannelThree()); // String // add the echoCommands field data channelIndex = rbnbChannelMap.Add("echoCommands"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getEchoCommands()); // String // add the outputFormat field data channelIndex = rbnbChannelMap.Add("outputFormat"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getOutputFormat()); // String // add the temperatureCalibrationDate field data channelIndex = rbnbChannelMap.Add("temperatureCalibrationDate"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getTemperatureCalibrationDate()); // String // add the temperatureCoefficientTA0 field data channelIndex = rbnbChannelMap.Add("temperatureCoefficientTA0"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getTemperatureCoefficientTA0() }); // double // add the temperatureCoefficientTA1 field data channelIndex = rbnbChannelMap.Add("temperatureCoefficientTA1"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getTemperatureCoefficientTA1() }); // double // add the temperatureCoefficientTA2 field data channelIndex = rbnbChannelMap.Add("temperatureCoefficientTA2"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getTemperatureCoefficientTA2() }); // double // add the temperatureCoefficientTA3 field data channelIndex = rbnbChannelMap.Add("temperatureCoefficientTA3"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getTemperatureCoefficientTA3() }); // double // add the temperatureOffsetCoefficient field data channelIndex = rbnbChannelMap.Add("temperatureOffsetCoefficient"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getTemperatureOffsetCoefficient() }); // double // add the conductivityCalibrationDate field data channelIndex = rbnbChannelMap.Add("conductivityCalibrationDate"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getConductivityCalibrationDate()); // String // add the conductivityCoefficientG field data channelIndex = rbnbChannelMap.Add("conductivityCoefficientG"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getConductivityCoefficientG() }); // double // add the conductivityCoefficientH field data channelIndex = rbnbChannelMap.Add("conductivityCoefficientH"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getConductivityCoefficientH() }); // double // add the conductivityCoefficientI field data channelIndex = rbnbChannelMap.Add("conductivityCoefficientI"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getConductivityCoefficientI() }); // double // add the conductivityCoefficientJ field data channelIndex = rbnbChannelMap.Add("conductivityCoefficientJ"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getConductivityCoefficientJ() }); // double // add the conductivityCoefficientCF0 field data channelIndex = rbnbChannelMap.Add("conductivityCoefficientCF0"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getConductivityCoefficientCF0() }); // double // add the conductivityCoefficientCPCOR field data channelIndex = rbnbChannelMap.Add("conductivityCoefficientCPCOR"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getConductivityCoefficientCPCOR() }); // double // add the conductivityCoefficientCTCOR field data channelIndex = rbnbChannelMap.Add("conductivityCoefficientCTCOR"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getConductivityCoefficientCTCOR() }); // double // add the conductivityCoefficientCSLOPE field data channelIndex = rbnbChannelMap.Add("conductivityCoefficientCSLOPE"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getConductivityCoefficientCSLOPE() }); // double // add the pressureSerialNumber field data channelIndex = rbnbChannelMap.Add("pressureSerialNumber"); rbnbChannelMap.PutMime(channelIndex, "text/plain"); rbnbChannelMap.PutDataAsString(channelIndex, this.ctdParser.getPressureSerialNumber()); // String // add the pressureCoefficientPA0 field data channelIndex = rbnbChannelMap.Add("pressureCoefficientPA0"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getPressureCoefficientPA0() }); // double // add the pressureCoefficientPA1 field data channelIndex = rbnbChannelMap.Add("pressureCoefficientPA1"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getPressureCoefficientPA1() }); // double // add the pressureCoefficientPA2 field data channelIndex = rbnbChannelMap.Add("pressureCoefficientPA2"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getPressureCoefficientPA2() }); // double // add the pressureCoefficientPTCA0 field data channelIndex = rbnbChannelMap.Add("pressureCoefficientPTCA0"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getPressureCoefficientPTCA0() }); // double // add the pressureCoefficientPTCA1 field data channelIndex = rbnbChannelMap.Add("pressureCoefficientPTCA1"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getPressureCoefficientPTCA1() }); // double // add the pressureCoefficientPTCA2 field data channelIndex = rbnbChannelMap.Add("pressureCoefficientPTCA2"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getPressureCoefficientPTCA2() }); // double // add the pressureCoefficientPTCB0 field data channelIndex = rbnbChannelMap.Add("pressureCoefficientPTCB0"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getPressureCoefficientPTCB0() }); // double // add the pressureCoefficientPTCB1 field data channelIndex = rbnbChannelMap.Add("pressureCoefficientPTCB1"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getPressureCoefficientPTCB1() }); // double // add the pressureCoefficientPTCB2 field data channelIndex = rbnbChannelMap.Add("pressureCoefficientPTCB2"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getPressureCoefficientPTCB2() }); // double // add the pressureCoefficientPTEMPA0 field data channelIndex = rbnbChannelMap.Add("pressureCoefficientPTEMPA0"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getPressureCoefficientPTEMPA0() }); // double // add the pressureCoefficientPTEMPA1 field data channelIndex = rbnbChannelMap.Add("pressureCoefficientPTEMPA1"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getPressureCoefficientPTEMPA1() }); // double // add the pressureCoefficientPTEMPA2 field data channelIndex = rbnbChannelMap.Add("pressureCoefficientPTEMPA2"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getPressureCoefficientPTEMPA2() }); // double // add the pressureOffsetCoefficient field data channelIndex = rbnbChannelMap.Add("pressureOffsetCoefficient"); rbnbChannelMap.PutMime(channelIndex, "application/octet-stream"); rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { this.ctdParser.getPressureOffsetCoefficient() }); // double } // send the sample to the data turbine getSource().Flush(rbnbChannelMap); logger.info("Sent sample to the DataTurbine: " + this.responseString); // reset variables for the next sample sampleBuffer.clear(); sampleByteCount = 0; channelIndex = 0; rbnbChannelMap.Clear(); logger.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap."); // check if the clock needs syncing (daily) if (this.enableSendCommands) { // get the current datetime Calendar currentCalendar = Calendar.getInstance(); currentCalendar.setTime(new Date()); Calendar lastSyncedCalendar = Calendar.getInstance(); lastSyncedCalendar.setTime(this.clockSyncDate); // round the dates to the day currentCalendar.clear(Calendar.MILLISECOND); currentCalendar.clear(Calendar.SECOND); currentCalendar.clear(Calendar.MINUTE); currentCalendar.clear(Calendar.HOUR); lastSyncedCalendar.clear(Calendar.MILLISECOND); lastSyncedCalendar.clear(Calendar.SECOND); lastSyncedCalendar.clear(Calendar.MINUTE); lastSyncedCalendar.clear(Calendar.HOUR); // sync the clock daily if (currentCalendar.before(lastSyncedCalendar)) { this.state = 8; } } // otherwise stay in state = 11 break; // the sample looks more like an instrument message, don't flush } else { logger.info("This string does not look like a sample, " + "and was not sent to the DataTurbine."); logger.info("Skipping sample: " + this.responseString); // reset variables for the next sample sampleBuffer.clear(); sampleByteCount = 0; //rbnbChannelMap.Clear(); logger.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap."); this.state = 11; break; } } else { // not 0x0A0D // still in the middle of the sample, keep adding bytes sampleByteCount++; // add each byte found if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); logger.debug("Compacting sampleBuffer ..."); sampleBuffer.put(byteOne); } break; } // end if for 0x0A0D EOL case 12: // alternatively use legacy DS and DCal commands if (this.enableSendCommands) { // start by getting the DS status output this.command = this.commandPrefix + this.displayStatusCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); streamingThread.sleep(5000); this.state = 13; break; } else { this.state = 0; break; } case 13: // handle the DS command response // command should end with the S> prompt if (byteOne == 0x7E && byteTwo == 0x53) { // handle instrument status response sampleByteCount++; // add the last byte found to the count // add the last byte found to the sample buffer if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); sampleBuffer.put(byteOne); } // extract the sampleByteCount length from the sampleBuffer sampleArray = new byte[sampleByteCount - 2]; //subtract "S>" sampleBuffer.flip(); sampleBuffer.get(sampleArray); this.responseString = new String(sampleArray, "US-ASCII"); // reset variables for the next sample sampleBuffer.clear(); sampleByteCount = 0; // then get the instrument calibration metadata this.command = this.commandPrefix + this.displayCalibrationCommand + this.commandSuffix; this.sentCommand = queryInstrument(command); streamingThread.sleep(5000); this.state = 14; break; } else { break; // continue reading bytes } case 14: // handle the DCal command response // command should end with the S> prompt if (byteOne == 0x7E && byteTwo == 0x53) { // handle instrument status response sampleByteCount++; // add the last byte found to the count // add the last byte found to the sample buffer if (sampleBuffer.remaining() > 0) { sampleBuffer.put(byteOne); } else { sampleBuffer.compact(); sampleBuffer.put(byteOne); } // extract the sampleByteCount length from the sampleBuffer sampleArray = new byte[sampleByteCount - 2]; // subtract "S>" sampleBuffer.flip(); sampleBuffer.get(sampleArray); // append the DCal output to the DS output this.responseString = this.responseString.concat(new String(sampleArray, "US-ASCII")); // and add the data delimiter expected in the CTDParser this.responseString = this.responseString.concat("*END*\r\n\r\n"); // build the CTDParser object with legacy DS and DCal metadata this.ctdParser = new CTDParser(this.responseString); // reset variables for the next sample sampleBuffer.clear(); sampleByteCount = 0; this.state = 9; // set the clock and start sampling break; } else { break; // continue reading bytes } } // end switch statement // shift the bytes in the FIFO window byteFour = byteThree; byteThree = byteTwo; byteTwo = byteOne; } //end while (more unread bytes) // prepare the buffer to read in more bytes from the stream buffer.compact(); } // end while (more channel bytes to read) this.channel.close(); } catch (IOException e) { // handle exceptions // In the event of an i/o exception, log the exception, and allow execute() // to return false, which will prompt a retry. failed = true; this.state = 0; // close the serial or socket channel if (this.channel != null && this.channel.isOpen()) { try { this.channel.close(); } catch (IOException cioe) { logger.debug("An error occurred trying to close the byte channel. " + " The error message was: " + cioe.getMessage()); } } // disconnect from the RBNB if (isConnected()) { disconnect(); } e.printStackTrace(); return !failed; } catch (InterruptedException intde) { // in the event that the streamingThread is interrupted failed = true; this.state = 0; // close the serial or socket channel if (this.channel != null && this.channel.isOpen()) { try { this.channel.close(); } catch (IOException cioe) { logger.debug("An error occurred trying to close the byte channel. " + " The error message was: " + cioe.getMessage()); } } // disconnect from the RBNB if (isConnected()) { disconnect(); } intde.printStackTrace(); return !failed; } catch (SAPIException sapie) { // In the event of an RBNB communication exception, log the exception, // and allow execute() to return false, which will prompt a retry. //this.channel.close(); failed = true; this.state = 0; // close the serial or socket channel if (this.channel != null && this.channel.isOpen()) { try { this.channel.close(); } catch (IOException cioe) { logger.debug("An error occurred trying to close the byte channel. " + " The error message was: " + cioe.getMessage()); } } // disconnect from the RBNB if (isConnected()) { disconnect(); } sapie.printStackTrace(); return !failed; } catch (ParseException pe) { failed = true; this.state = 0; // close the serial or socket channel if (this.channel != null && this.channel.isOpen()) { try { this.channel.close(); } catch (IOException cioe) { logger.debug("An error occurred trying to close the byte channel. " + " The error message was: " + cioe.getMessage()); } } // disconnect from the RBNB if (isConnected()) { disconnect(); } logger.info("There was an error parsing the metadata response. " + "The error message was: " + pe.getMessage()); return !failed; } finally { this.state = 0; // close the serial or socket channel if (this.channel != null && this.channel.isOpen()) { try { this.channel.close(); } catch (IOException cioe) { logger.debug("An error occurred trying to close the byte channel. " + " The error message was: " + cioe.getMessage()); } } } return !failed; }
From source file:au.org.theark.core.dao.DataExtractionDao.java
/** * /*from ww w . j a v a 2 s . c o m*/ * Simple export to CSV as Biocollection Data * */ public File createBiocollectionCSV(Search search, DataExtractionVO devo, List<CustomFieldDisplay> cfds, FieldCategory fieldCategory) { final String tempDir = System.getProperty("java.io.tmpdir"); String filename = new String("BIOCOLLECTION.csv"); final java.io.File file = new File(tempDir, filename); if (filename == null || filename.isEmpty()) { filename = "exportBiocollectioncsv.csv"; } HashMap<String, ExtractionVO> hashOfBiocollectionsWithData = devo.getBiocollectionData(); HashMap<String, ExtractionVO> hashOfBiocollectionCustomData = devo.getBiocollectionCustomData(); Set<String> bioCollectionUids = new HashSet<String>(); bioCollectionUids.addAll(hashOfBiocollectionsWithData.keySet()); bioCollectionUids.addAll(hashOfBiocollectionCustomData.keySet()); OutputStream outputStream; try { outputStream = new FileOutputStream(file); CsvWriter csv = new CsvWriter(outputStream); // Header csv.write("SUBJECTID"); csv.write("BIOCOLLECTIONUID"); for (BiocollectionFieldSearch bcfs : search.getBiocollectionFieldsToReturn()) { csv.write(bcfs.getBiocollectionField().getPublicFieldName()); } for (CustomFieldDisplay cfd : cfds) { csv.write(cfd.getCustomField().getName()); } csv.endLine(); for (String biocollectionUID : bioCollectionUids) { ExtractionVO hash = hashOfBiocollectionsWithData.get(biocollectionUID); csv.write(hash.getSubjectUid()); csv.write(biocollectionUID); for (BiocollectionFieldSearch bcfs : search.getBiocollectionFieldsToReturn()) { if (hash != null) { HashMap<String, String> keyValues = hash.getKeyValues(); //csv.write(keyValues.get(bcfs.getBiocollectionField().getPublicFieldName())); String valueResult = keyValues.get(bcfs.getBiocollectionField().getPublicFieldName()); if (bcfs.getBiocollectionField().getFieldType().getName() .equalsIgnoreCase(Constants.FIELD_TYPE_DATE) && valueResult != null) { try { DateFormat dateFormat = new SimpleDateFormat( au.org.theark.core.Constants.DD_MM_YYYY); String[] dateFormats = { au.org.theark.core.Constants.DD_MM_YYYY, au.org.theark.core.Constants.yyyy_MM_dd_hh_mm_ss_S }; Date date = DateUtils.parseDate(valueResult, dateFormats); csv.write(dateFormat.format(date)); } catch (ParseException e) { csv.write(valueResult); } } else { csv.write(valueResult); } } } /* * for(CustomFieldDisplay cfd : cfds) { HashMap<String, String> keyValues = * hashOfBiocollectionCustomData.get(biocollectionUID).getKeyValues(); String valueResult = keyValues.get(cfd.getCustomField().getName()); * if (cfd.getCustomField().getFieldType().getName().equalsIgnoreCase(Constants.FIELD_TYPE_DATE) && valueResult != null) { DateFormat * dateFormat = new SimpleDateFormat(au.org.theark.core.Constants.DD_MM_YYYY); dateFormat.setLenient(false); try { String date = * dateFormat.format(dateFormat.parse(valueResult)); csv.write(date); } catch (ParseException e) { csv.write(valueResult); } * csv.write(valueResult); } else { csv.write(valueResult); } } csv.endLine(); */ ExtractionVO evo = hashOfBiocollectionCustomData.get(biocollectionUID); if (evo != null) { HashMap<String, String> keyValues = evo.getKeyValues(); for (CustomFieldDisplay cfd : cfds) { String valueResult = keyValues.get(cfd.getCustomField().getName()); if (cfd.getCustomField().getFieldType().getName() .equalsIgnoreCase(Constants.FIELD_TYPE_DATE) && valueResult != null) { try { DateFormat dateFormat = new SimpleDateFormat( au.org.theark.core.Constants.DD_MM_YYYY); String[] dateFormats = { au.org.theark.core.Constants.DD_MM_YYYY, au.org.theark.core.Constants.yyyy_MM_dd_hh_mm_ss_S }; Date date = DateUtils.parseDate(valueResult, dateFormats); csv.write(dateFormat.format(date)); } catch (ParseException e) { csv.write(valueResult); } } else { csv.write(valueResult); } } } else { // Write out a line with no values (no data existed for subject in question for (CustomFieldDisplay cfd : cfds) { csv.write(""); } } csv.endLine(); } csv.close(); } catch (FileNotFoundException e) { log.error(e.getMessage()); } return file; }
From source file:com.att.pirates.controller.ProjectController.java
@RequestMapping(value = "/pid/{prismId}/getProjectNotesJson", method = RequestMethod.GET) public @ResponseBody String getCompanies(@PathVariable("prismId") String prismId, HttpServletRequest request) { // logger.error(msgHeader + " getCompanies prismId: " + prismId); JQueryDataTableParamModel param = DataTablesParamUtility.getParam(request); String sEcho = param.sEcho;// ww w . ja va 2 s . c o m int iTotalRecords; // total number of records (unfiltered) int iTotalDisplayRecords; //value will be set when code filters companies by keyword List<Company> allNotes = GlobalDataController.GetCompanies(prismId); iTotalRecords = allNotes.size(); List<Company> companies = new LinkedList<Company>(); for (Company c : allNotes) { if (c.getName().toLowerCase().contains(param.sSearch.toLowerCase()) || c.getAddress().toLowerCase().contains(param.sSearch.toLowerCase()) || c.getTown().toLowerCase().contains(param.sSearch.toLowerCase()) || c.getDateCreated().toLowerCase().contains(param.sSearch.toLowerCase())) { companies.add(c); // add company that matches given search criterion } } iTotalDisplayRecords = companies.size();// number of companies that match search criterion should be returned final int sortColumnIndex = param.iSortColumnIndex; final int sortDirection = param.sSortDirection.equals("asc") ? -1 : 1; Collections.sort(companies, new Comparator<Company>() { @Override public int compare(Company c1, Company c2) { switch (sortColumnIndex) { case 0: return 0; // sort by id is not allowed case 1: return c1.getName().compareTo(c2.getName()) * sortDirection; case 2: return c1.getAddress().compareTo(c2.getAddress()) * sortDirection; case 3: return c1.getTown().compareTo(c2.getTown()) * sortDirection; case 4: SimpleDateFormat yFormat = new SimpleDateFormat("MM/dd/yyyy"); try { Date c1d = yFormat.parse(c1.getDateCreated()); Date c2d = yFormat.parse(c2.getDateCreated()); return c1d.compareTo(c2d) * sortDirection; } catch (ParseException ex) { logger.error(ex.getMessage()); } } return 0; } }); if (companies.size() < param.iDisplayStart + param.iDisplayLength) { companies = companies.subList(param.iDisplayStart, companies.size()); } else { companies = companies.subList(param.iDisplayStart, param.iDisplayStart + param.iDisplayLength); } try { JsonObject jsonResponse = new JsonObject(); jsonResponse.addProperty("sEcho", sEcho); jsonResponse.addProperty("iTotalRecords", iTotalRecords); jsonResponse.addProperty("iTotalDisplayRecords", iTotalDisplayRecords); Gson gson = new Gson(); jsonResponse.add("aaData", gson.toJsonTree(companies)); String tmp = jsonResponse.toString(); // logger.error(msgHeader + ".. json string: " + tmp); return jsonResponse.toString(); } catch (JsonIOException e) { logger.error(msgHeader + e.getMessage()); } return null; }