List of usage examples for java.util Calendar DST_OFFSET
int DST_OFFSET
To view the source code for java.util Calendar DST_OFFSET.
Click Source Link
get
and set
indicating the daylight saving offset in milliseconds. From source file:org.sakaiproject.component.app.podcasts.PodcastServiceImpl.java
/** * Returns the date set in GMT time/*from ww w .j a va 2 s. c o m*/ * * @param date * The date represented as a long value * * @return Date * The Date object set in GMT time */ public Date getGMTdate(long date) { final Calendar cal = Calendar.getInstance(timeService.getLocalTimeZone()); cal.setTimeInMillis(date); int gmtoffset = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET); return new Date(date - gmtoffset); }
From source file:org.sakaiproject.portal.charon.SkinnableCharonPortal.java
public void includeBottom(PortalRenderContext rcontext) { if (rcontext.uses(INCLUDE_BOTTOM)) { String thisUser = SessionManager.getCurrentSessionUserId(); //Get user preferences PreferencesService preferencesService = (PreferencesService) ComponentManager .get(PreferencesService.class); Preferences prefs = preferencesService.getPreferences(thisUser); boolean showServerTime = ServerConfigurationService.getBoolean("portal.show.time", true); if (showServerTime) { rcontext.put("showServerTime", "true"); Calendar now = Calendar.getInstance(); Date nowDate = new Date(now.getTimeInMillis()); //first set server date and time TimeZone serverTz = TimeZone.getDefault(); now.setTimeZone(serverTz);/*from w w w . j av a 2 s.c o m*/ rcontext.put("serverTzDisplay", serverTz.getDisplayName(serverTz.inDaylightTime(nowDate), TimeZone.SHORT)); rcontext.put("serverTzGMTOffset", String.valueOf( now.getTimeInMillis() + now.get(Calendar.ZONE_OFFSET) + now.get(Calendar.DST_OFFSET))); //provide the user's preferred timezone information if it is different //Get the Properties object that holds user's TimeZone preferences ResourceProperties tzprops = prefs.getProperties(TimeService.APPLICATION_ID); //Get the ID of the timezone using the timezone key. //Default to 'localTimeZone' (server timezone?) String preferredTzId = (String) tzprops.get(TimeService.TIMEZONE_KEY); if (preferredTzId != null && !preferredTzId.equals(serverTz.getID())) { TimeZone preferredTz = TimeZone.getTimeZone(preferredTzId); now.setTimeZone(preferredTz); rcontext.put("showPreferredTzTime", "true"); //now set up the portal information rcontext.put("preferredTzDisplay", preferredTz.getDisplayName(preferredTz.inDaylightTime(nowDate), TimeZone.SHORT)); rcontext.put("preferredTzGMTOffset", String.valueOf( now.getTimeInMillis() + now.get(Calendar.ZONE_OFFSET) + now.get(Calendar.DST_OFFSET))); } else { rcontext.put("showPreferredTzTime", "false"); } } rcontext.put("pagepopup", false); String copyright = ServerConfigurationService.getString("bottom.copyrighttext"); /** * Replace keyword in copyright message from sakai.properties * with the server's current year to auto-update of Copyright end date */ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy"); String currentServerYear = simpleDateFormat.format(new Date()); copyright = copyright.replaceAll(SERVER_COPYRIGHT_CURRENT_YEAR_KEYWORD, currentServerYear); String service = ServerConfigurationService.getString("ui.service", "Sakai"); String serviceVersion = ServerConfigurationService.getString("version.service", "?"); String sakaiVersion = ServerConfigurationService.getString("version.sakai", "?"); String server = ServerConfigurationService.getServerId(); String[] bottomNav = ServerConfigurationService.getStrings("bottomnav"); String[] poweredByUrl = ServerConfigurationService.getStrings("powered.url"); String[] poweredByImage = ServerConfigurationService.getStrings("powered.img"); String[] poweredByAltText = ServerConfigurationService.getStrings("powered.alt"); { List<Object> l = new ArrayList<Object>(); if ((bottomNav != null) && (bottomNav.length > 0)) { for (int i = 0; i < bottomNav.length; i++) { l.add(bottomNav[i]); } } rcontext.put("bottomNav", l); } boolean neoChatAvailable = ServerConfigurationService.getBoolean("portal.neochat", true) && chatHelper.checkChatPermitted(thisUser); rcontext.put("neoChat", neoChatAvailable); rcontext.put("portalChatPollInterval", ServerConfigurationService.getInt("portal.chat.pollInterval", 5000)); rcontext.put("neoAvatar", ServerConfigurationService.getBoolean("portal.neoavatar", true)); rcontext.put("neoChatVideo", ServerConfigurationService.getBoolean("portal.chat.video", true)); rcontext.put("portalVideoChatTimeout", ServerConfigurationService.getInt("portal.chat.video.timeout", 25)); if (sakaiTutorialEnabled && thisUser != null) { if (!("1".equals(prefs.getProperties().getProperty("sakaiTutorialFlag")))) { rcontext.put("tutorial", true); //now save this in the user's prefefences so we don't show it again PreferencesEdit preferences = null; SecurityAdvisor secAdv = null; try { secAdv = new SecurityAdvisor() { @Override public SecurityAdvice isAllowed(String userId, String function, String reference) { if ("prefs.add".equals(function) || "prefs.upd".equals(function)) { return SecurityAdvice.ALLOWED; } return null; } }; securityService.pushAdvisor(secAdv); try { preferences = preferencesService.edit(thisUser); } catch (IdUnusedException ex1) { try { preferences = preferencesService.add(thisUser); } catch (IdUsedException ex2) { M_log.error(ex2); } catch (PermissionException ex3) { M_log.error(ex3); } } if (preferences != null) { ResourcePropertiesEdit props = preferences.getPropertiesEdit(); props.addProperty("sakaiTutorialFlag", "1"); preferencesService.commit(preferences); } } catch (Exception e1) { M_log.error(e1); } finally { if (secAdv != null) { securityService.popAdvisor(secAdv); } } } } // rcontext.put("bottomNavSitNewWindow", // Web.escapeHtml(rb.getString("site_newwindow"))); if ((poweredByUrl != null) && (poweredByImage != null) && (poweredByAltText != null) && (poweredByUrl.length == poweredByImage.length) && (poweredByUrl.length == poweredByAltText.length)) { { List<Object> l = new ArrayList<Object>(); for (int i = 0; i < poweredByUrl.length; i++) { Map<String, Object> m = new HashMap<String, Object>(); m.put("poweredByUrl", poweredByUrl[i]); m.put("poweredByImage", poweredByImage[i]); m.put("poweredByAltText", poweredByAltText[i]); l.add(m); } rcontext.put("bottomNavPoweredBy", l); } } else { List<Object> l = new ArrayList<Object>(); Map<String, Object> m = new HashMap<String, Object>(); m.put("poweredByUrl", "http://sakaiproject.org"); m.put("poweredByImage", "/library/image/sakai_powered.gif"); m.put("poweredByAltText", "Powered by Sakai"); l.add(m); rcontext.put("bottomNavPoweredBy", l); } rcontext.put("bottomNavService", service); rcontext.put("bottomNavCopyright", copyright); rcontext.put("bottomNavServiceVersion", serviceVersion); rcontext.put("bottomNavSakaiVersion", sakaiVersion); rcontext.put("bottomNavServer", server); // SAK-25931 - Do not remove this from session here - removal is done by /direct Session s = SessionManager.getCurrentSession(); String userWarning = (String) s.getAttribute("userWarning"); rcontext.put("userWarning", new Boolean(StringUtils.isNotEmpty(userWarning))); if (ServerConfigurationService.getBoolean("pasystem.enabled", false)) { PASystem paSystem = (PASystem) ComponentManager.get(PASystem.class); rcontext.put("paSystemEnabled", true); rcontext.put("paSystem", paSystem); } } }
From source file:edu.harvard.i2b2.patientSet.ui.PatientSetJPanel.java
@SuppressWarnings("rawtypes") private void jForwardButtonActionPerformed(java.awt.event.ActionEvent evt) { System.out.println("Loading previous queries for: " + System.getProperty("user")); cellStatus = ""; //String searchStr = jSearchStringTextField.getText(); int category = jCategoryComboBox.getSelectedIndex(); int strategy = jContainComboBox.getSelectedIndex(); curCreationDate = previousQueries.get(previousQueries.size() - 1).creationTime(); //////////////////////////////////////////////// SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");//.getDateInstance(); Date date = null;//from ww w. ja va 2s . c o m try { date = df.parse(this.jStartTimeTextField.getText()); } catch (Exception e) { e.printStackTrace(); } DTOFactory dtoFactory = new DTOFactory(); TimeZone tz = Calendar.getInstance().getTimeZone(); GregorianCalendar cal = new GregorianCalendar(tz); cal.setTime(date); //cal.get(Calendar.ZONE_OFFSET); int zt_offset = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 60000; //log.info("Timezone: "+tz.getID()+" : "+zt_offset); //if (startTime() != -1) { ConstrainDateType constraindateType = new ConstrainDateType(); XMLGregorianCalendar xmlC = dtoFactory.getXMLGregorianCalendarDate(cal.get(GregorianCalendar.YEAR), cal.get(GregorianCalendar.MONTH) + 1, cal.get(GregorianCalendar.DAY_OF_MONTH)); xmlC.setTimezone(zt_offset);//0);//-5*60); xmlC.setHour(cal.get(GregorianCalendar.HOUR_OF_DAY)); xmlC.setMinute(cal.get(GregorianCalendar.MINUTE)); xmlC.setSecond(cal.get(GregorianCalendar.SECOND)); constraindateType.setValue(xmlC); //timeConstrain.setDateFrom(constraindateType); //} //////////////////////////////////////////////// String xmlStr = writePagingQueryXML("", category, strategy, false, xmlC);//curCreationDate); // System.out.println(xmlStr); String responseStr = null; if (System.getProperty("webServiceMethod").equals("SOAP")) { responseStr = QueryListNamesClient.sendQueryRequestSOAP(xmlStr); } else { responseStr = QueryListNamesClient.sendFindQueryRequestREST(xmlStr); } if (responseStr.equalsIgnoreCase("CellDown")) { cellStatus = new String("CellDown"); return; //"CellDown"; } try { JAXBUtil jaxbUtil = PatientSetJAXBUtil.getJAXBUtil(); JAXBElement jaxbElement = jaxbUtil.unMashallFromString(responseStr); ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue(); BodyType bt = messageType.getMessageBody(); MasterResponseType masterResponseType = (MasterResponseType) new JAXBUnWrapHelper().getObjectByClass( bt.getAny(), edu.harvard.i2b2.crcxmljaxb.datavo.psm.query.MasterResponseType.class); for (Condition status : masterResponseType.getStatus().getCondition()) { if (status.getType().equals("ERROR")) cellStatus = new String("CellDown"); } previousQueries = new ArrayList<QueryMasterData>(); for (QueryMasterType queryMasterType : masterResponseType.getQueryMaster()) { QueryMasterData tmpData; tmpData = new QueryMasterData(); XMLGregorianCalendar cldr = queryMasterType.getCreateDate(); tmpData.name( queryMasterType.getName() + " [" + addZero(cldr.getMonth()) + "-" + addZero(cldr.getDay()) + "-" + addZero(cldr.getYear()) + " ]" + " [" + queryMasterType.getUserId() + "]"); tmpData.creationTime(cldr);//.clone()); tmpData.creationTimeStr( addZero(cldr.getMonth()) + "-" + addZero(cldr.getDay()) + "-" + addZero(cldr.getYear()) + " " + cldr.getHour() + ":" + cldr.getMinute() + ":" + cldr.getSecond()); tmpData.tooltip("A query run by " + queryMasterType.getUserId()); // System. // getProperty // ("user")); tmpData.visualAttribute("CA"); tmpData.xmlContent(null); tmpData.id(queryMasterType.getQueryMasterId()); tmpData.userId(queryMasterType.getUserId()); // System.getProperty // ("user")); previousQueries.add(tmpData); } if (previousQueries.size() == 0) { final JPanel parent = this; java.awt.EventQueue.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(parent, "No results were found.", "Not Found", JOptionPane.INFORMATION_MESSAGE); } }); return; } loadPatientSets(); if (cellStatus.equalsIgnoreCase("")) { reset(200, false, false); } else if (cellStatus.equalsIgnoreCase("CellDown")) { final JPanel parent = this; java.awt.EventQueue.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(parent, "Trouble with connection to the remote server, " + "this is often a network error, please try again", "Network Error", JOptionPane.INFORMATION_MESSAGE); } }); } return; } catch (Exception e) { e.printStackTrace(); return; } }
From source file:edu.harvard.i2b2.previousquery.ui.PreviousQueryPanel.java
private void jBackwardButtonActionPerformed(java.awt.event.ActionEvent evt) { /*LoginHelper pms = new LoginHelper(); try {//from www . j av a 2s.c om PasswordType ptype = new PasswordType(); ptype.setIsToken(UserInfoBean.getInstance().getUserPasswordIsToken()); ptype.setTokenMsTimeout(UserInfoBean.getInstance() .getUserPasswordTimeout()); ptype.setValue(UserInfoBean.getInstance().getUserPassword()); String response = pms.getUserInfo(UserInfoBean.getInstance().getUserName(), ptype, UserInfoBean.getInstance().getSelectedProjectUrl(), UserInfoBean.getInstance().getUserDomain(), false, UserInfoBean.getInstance().getProjectId()); } catch(Exception e) { e.printStackTrace(); }*/ System.out.println("Loading previous queries for: " + System.getProperty("user")); cellStatus = ""; String searchStr = jSearchStringTextField.getText(); int category = jCategoryComboBox.getSelectedIndex(); int strategy = jContainComboBox.getSelectedIndex(); curCreationDate = previousQueries.get(0).creationTime(); //////////////////////////////////////////////// SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");//.getDateInstance(); Date date = null; try { date = df.parse(this.jStartTimeTextField.getText()); } catch (Exception e) { e.printStackTrace(); } DTOFactory dtoFactory = new DTOFactory(); TimeZone tz = Calendar.getInstance().getTimeZone(); GregorianCalendar cal = new GregorianCalendar(tz); cal.setTime(date); //cal.get(Calendar.ZONE_OFFSET); int zt_offset = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 60000; //log.info("Timezone: "+tz.getID()+" : "+zt_offset); //if (startTime() != -1) { ConstrainDateType constraindateType = new ConstrainDateType(); XMLGregorianCalendar xmlC = dtoFactory.getXMLGregorianCalendarDate(cal.get(GregorianCalendar.YEAR), cal.get(GregorianCalendar.MONTH) + 1, cal.get(GregorianCalendar.DAY_OF_MONTH)); xmlC.setTimezone(zt_offset);//0);//-5*60); xmlC.setHour(cal.get(GregorianCalendar.HOUR_OF_DAY)); xmlC.setMinute(cal.get(GregorianCalendar.MINUTE)); xmlC.setSecond(cal.get(GregorianCalendar.SECOND)); constraindateType.setValue(xmlC); //timeConstrain.setDateFrom(constraindateType); //} //////////////////////////////////////////////// String xmlStr = writePagingQueryXML("", category, strategy, true, xmlC);//curCreationDate); // System.out.println(xmlStr); String responseStr = null; if (System.getProperty("webServiceMethod").equals("SOAP")) { responseStr = QueryListNamesClient.sendQueryRequestSOAP(xmlStr); } else { responseStr = QueryListNamesClient.sendFindQueryRequestREST(xmlStr); } if (responseStr.equalsIgnoreCase("CellDown")) { cellStatus = new String("CellDown"); return; //"CellDown"; } try { JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil(); JAXBElement jaxbElement = jaxbUtil.unMashallFromString(responseStr); ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue(); BodyType bt = messageType.getMessageBody(); MasterResponseType masterResponseType = (MasterResponseType) new JAXBUnWrapHelper().getObjectByClass( bt.getAny(), edu.harvard.i2b2.crcxmljaxb.datavo.psm.query.MasterResponseType.class); for (Condition status : masterResponseType.getStatus().getCondition()) { if (status.getType().equals("ERROR")) cellStatus = new String("CellDown"); } previousQueries = new ArrayList<QueryMasterData>(); for (QueryMasterType queryMasterType : masterResponseType.getQueryMaster()) { QueryMasterData tmpData; tmpData = new QueryMasterData(); XMLGregorianCalendar cldr = queryMasterType.getCreateDate(); tmpData.name( queryMasterType.getName() + " [" + addZero(cldr.getMonth()) + "-" + addZero(cldr.getDay()) + "-" + addZero(cldr.getYear()) + " ]" + " [" + queryMasterType.getUserId() + "]"); tmpData.creationTime(cldr);//.clone()); tmpData.creationTimeStr( addZero(cldr.getMonth()) + "-" + addZero(cldr.getDay()) + "-" + addZero(cldr.getYear()) + " " + cldr.getHour() + ":" + cldr.getMinute() + ":" + cldr.getSecond()); tmpData.tooltip("A query run by " + queryMasterType.getUserId());// System. // getProperty // ("user")); tmpData.visualAttribute("CA"); tmpData.xmlContent(null); tmpData.id(queryMasterType.getQueryMasterId()); tmpData.userId(queryMasterType.getUserId()); // System.getProperty // ("user")); previousQueries.add(tmpData); } if (previousQueries.size() == 0) { final JPanel parent = this; java.awt.EventQueue.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(parent, "No results were found.", "Not Found", JOptionPane.INFORMATION_MESSAGE); } }); return; } if (cellStatus.equalsIgnoreCase("")) { reset(200, false, true); } else if (cellStatus.equalsIgnoreCase("CellDown")) { final JPanel parent = this; java.awt.EventQueue.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(parent, "Trouble with connection to the remote server, " + "this is often a network error, please try again", "Network Error", JOptionPane.INFORMATION_MESSAGE); } }); } return; } catch (Exception e) { e.printStackTrace(); return; } }
From source file:edu.harvard.i2b2.previousquery.ui.PreviousQueryPanel.java
private void jForwardButtonActionPerformed(java.awt.event.ActionEvent evt) { System.out.println("Loading previous queries for: " + System.getProperty("user")); cellStatus = ""; String searchStr = jSearchStringTextField.getText(); int category = jCategoryComboBox.getSelectedIndex(); int strategy = jContainComboBox.getSelectedIndex(); curCreationDate = previousQueries.get(previousQueries.size() - 1).creationTime(); //////////////////////////////////////////////// SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");//.getDateInstance(); Date date = null;/* w w w .j av a2 s . c o m*/ try { date = df.parse(this.jStartTimeTextField.getText()); } catch (Exception e) { e.printStackTrace(); } DTOFactory dtoFactory = new DTOFactory(); TimeZone tz = Calendar.getInstance().getTimeZone(); GregorianCalendar cal = new GregorianCalendar(tz); cal.setTime(date); //cal.get(Calendar.ZONE_OFFSET); int zt_offset = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 60000; //log.info("Timezone: "+tz.getID()+" : "+zt_offset); //if (startTime() != -1) { ConstrainDateType constraindateType = new ConstrainDateType(); XMLGregorianCalendar xmlC = dtoFactory.getXMLGregorianCalendarDate(cal.get(GregorianCalendar.YEAR), cal.get(GregorianCalendar.MONTH) + 1, cal.get(GregorianCalendar.DAY_OF_MONTH)); xmlC.setTimezone(zt_offset);//0);//-5*60); xmlC.setHour(cal.get(GregorianCalendar.HOUR_OF_DAY)); xmlC.setMinute(cal.get(GregorianCalendar.MINUTE)); xmlC.setSecond(cal.get(GregorianCalendar.SECOND)); constraindateType.setValue(xmlC); //timeConstrain.setDateFrom(constraindateType); //} //////////////////////////////////////////////// String xmlStr = writePagingQueryXML("", category, strategy, false, xmlC);//curCreationDate); // System.out.println(xmlStr); String responseStr = null; if (System.getProperty("webServiceMethod").equals("SOAP")) { responseStr = QueryListNamesClient.sendQueryRequestSOAP(xmlStr); } else { responseStr = QueryListNamesClient.sendFindQueryRequestREST(xmlStr); } if (responseStr.equalsIgnoreCase("CellDown")) { cellStatus = new String("CellDown"); return; //"CellDown"; } try { JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil(); JAXBElement jaxbElement = jaxbUtil.unMashallFromString(responseStr); ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue(); BodyType bt = messageType.getMessageBody(); MasterResponseType masterResponseType = (MasterResponseType) new JAXBUnWrapHelper().getObjectByClass( bt.getAny(), edu.harvard.i2b2.crcxmljaxb.datavo.psm.query.MasterResponseType.class); for (Condition status : masterResponseType.getStatus().getCondition()) { if (status.getType().equals("ERROR")) cellStatus = new String("CellDown"); } previousQueries = new ArrayList<QueryMasterData>(); for (QueryMasterType queryMasterType : masterResponseType.getQueryMaster()) { QueryMasterData tmpData; tmpData = new QueryMasterData(); XMLGregorianCalendar cldr = queryMasterType.getCreateDate(); tmpData.name( queryMasterType.getName() + " [" + addZero(cldr.getMonth()) + "-" + addZero(cldr.getDay()) + "-" + addZero(cldr.getYear()) + " ]" + " [" + queryMasterType.getUserId() + "]"); tmpData.creationTime(cldr);//.clone()); tmpData.creationTimeStr( addZero(cldr.getMonth()) + "-" + addZero(cldr.getDay()) + "-" + addZero(cldr.getYear()) + " " + cldr.getHour() + ":" + cldr.getMinute() + ":" + cldr.getSecond()); tmpData.tooltip("A query run by " + queryMasterType.getUserId());// System. // getProperty // ("user")); tmpData.visualAttribute("CA"); tmpData.xmlContent(null); tmpData.id(queryMasterType.getQueryMasterId()); tmpData.userId(queryMasterType.getUserId()); // System.getProperty // ("user")); previousQueries.add(tmpData); } if (previousQueries.size() == 0) { final JPanel parent = this; java.awt.EventQueue.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(parent, "No results were found.", "Not Found", JOptionPane.INFORMATION_MESSAGE); } }); return; } if (cellStatus.equalsIgnoreCase("")) { reset(200, false, false); } else if (cellStatus.equalsIgnoreCase("CellDown")) { final JPanel parent = this; java.awt.EventQueue.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(parent, "Trouble with connection to the remote server, " + "this is often a network error, please try again", "Network Error", JOptionPane.INFORMATION_MESSAGE); } }); } return; } catch (Exception e) { e.printStackTrace(); return; } }
From source file:gov.noaa.pfel.coastwatch.Projects.java
/** * Processes one CalCOFI2012 tsv file into a .nc file. * /* w w w . ja va 2 s. c o m*/ * <p>The var sequence of latitude, latitudeMinutes, latitudeLocation * will be converted to 1 latitude column (decimal degrees). * Similar with longitude. * * <p>If units are yyMM, var will be converted to yyyyMM and units="". * * <p>If units are yyMMdd, var will be converted to yyyyMMdd, then * to "seconds since 1970-01-01T00:00:00Z" (assuming Pacific time zone) * and sets attribute: time_precision=1970-01-01. * * <p>If units of variable after yyMMdd are HHmm, the date and time will * be combined into one "seconds since 1970-01-01T00:00:00Z" variable. * * <p>If variableName="timeZone", this checks to see if arriveDate value * timeZone offset is as expected. * * @param dir * @param tableName e.g., CC_TOWS * @param info with 4 strings (name, type, units, long_name) for each variable * @param towTypesDescription will be added as description=[towTypesDescrption] * when variableName=towTypeCode. * @return the table, as saved in the .nc file. */ public static Table processOneCalcofi2012(String dir, String tableName, String info[], String towTypesDescription) throws Exception { String rowName = "row"; int cutoffYear = 20; // fourDigitYear += twoDigitYear < cutoffYear? 2000 : 1900; /* make tsv into ERDDAP-style .json table //{ // "table": { // "columnNames": ["longitude", "latitude", "time", "sea_surface_temperature"], // "columnTypes": ["float", "float", "String", "float"], // "columnUnits": ["degrees_east", "degrees_north", "UTC", "degree_C"], // "rows": [ // [180.099, 0.032, "2007-10-04T12:00:00Z", 27.66], // [180.099, 0.032, null, null], // [189.971, -7.98, "2007-10-04T12:00:00Z", 29.08] // ] //} */ String inFile = dir + tableName + ".txt"; String2.log("\n* processOneCalcofi2012 " + inFile); StringArray names = new StringArray(); StringArray types = new StringArray(); StringArray units = new StringArray(); StringArray lNames = new StringArray(); Test.ensureEqual(info.length % 4, 0, "info.length=" + info.length); int nVars = info.length / 4; int n = 0; for (int v = 0; v < nVars; v++) { names.add(info[n++]); types.add(info[n++]); units.add(info[n++]); lNames.add(info[n++]); } String fromFile[] = String2.readFromFile(inFile); if (fromFile[0].length() > 0) throw new RuntimeException(fromFile[0]); String lines = String2.replaceAll(fromFile[1], "\t", ","); lines = String2.replaceAll(lines, "\n", "],\n["); lines = "{\n" + " \"table\": {\n" + " \"columnNames\": [" + names.toJsonCsvString() + "],\n" + " \"columnTypes\": [" + types.toJsonCsvString() + "],\n" + " \"columnUnits\": [" + units.toJsonCsvString() + "],\n" + " \"rows\": [\n" + "[" + lines.substring(0, lines.length() - 3) + "\n" + "]\n" + "}\n"; String2.log(lines.substring(0, Math.min(lines.length(), 1500))); Table table = new Table(); table.readJson(inFile, lines); String2.log("Before adjustments:\n" + String2.annotatedString(table.dataToString(5))); int nRows = table.nRows(); int nErrors = 0; //things where nColumns won't change for (int v = 0; v < table.nColumns(); v++) { PrimitiveArray pa = table.getColumn(v); String vName = table.getColumnName(v); Attributes atts = table.columnAttributes(v); //longNames atts.add("long_name", lNames.get(v)); //relies on original var lists //timeZone nErrors = 0; if ("timeZone".equals(vName)) { PrimitiveArray arrivePA = table.getColumn("arriveDate"); //still yyMMdd GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles")); Calendar2.clearSmallerFields(gc, Calendar2.DATE); for (int row = 0; row < nRows; row++) { String val = arrivePA.getString(row); if (val.matches("[0-9]{6}")) { int year = String2.parseInt(val.substring(0, 2)); gc.set(Calendar2.YEAR, year < cutoffYear ? 2000 : 1900); gc.set(Calendar2.MONTH, String2.parseInt(val.substring(2, 4)) - 1); //0.. gc.set(Calendar2.DATE, String2.parseInt(val.substring(4, 6))); int fileHas = pa.getInt(row); int calculated = -gc.get(Calendar.ZONE_OFFSET) / (60 * 60 * 1000) + //in hours -gc.get(Calendar.DST_OFFSET) / (60 * 60 * 1000); //in hours if (fileHas != calculated) { nErrors++; if (nErrors <= 5) String2.log("ERROR: col=" + vName + " row=" + row + " timeZone=" + fileHas + " != calculated(" + val + ")=" + calculated); } } } if (nErrors > 0) String2.pressEnterToContinue("Bob: check US daylight savings time rules. On/near these dates?\n" + "https://en.wikipedia.org/wiki/History_of_time_in_the_United_States\n" + "nErrors=" + nErrors); } } //things where nColumns may change for (int v = 0; v < table.nColumns(); v++) { PrimitiveArray pa = table.getColumn(v); String vName = table.getColumnName(v); Attributes atts = table.columnAttributes(v); String vUnits = atts.getString("units"); Attributes nextAtts = v < table.nColumns() - 1 ? table.columnAttributes(v + 1) : new Attributes(); //towTypeCode if ("towTypeCode".equals(vName)) atts.add("description", towTypesDescription); //latitude nErrors = 0; if ("latitude".equals(vName) && "latitudeMinutes".equals(table.getColumnName(v + 1)) && "latitudeLocation".equals(table.getColumnName(v + 2))) { FloatArray fa = new FloatArray(nRows, false); //float avoids, e.g., xx.33333333333333 PrimitiveArray pa1 = table.getColumn(v + 1); PrimitiveArray pa2 = table.getColumn(v + 2); for (int row = 0; row < nRows; row++) { String loc = pa2.getString(row); String combo = pa.getString(row) + " " + pa1.getString(row) + " " + loc; float f = //will be NaN if trouble (pa.getFloat(row) + (pa1.getFloat(row) / 60)) * (loc.equals("N") ? 1 : loc.equals("S") ? -1 : Float.NaN); fa.atInsert(row, f); if (combo.length() > 2 && //2 spaces (f < -90 || f > 90 || Float.isNaN(f))) { nErrors++; if (nErrors <= 5) String2.log("ERROR: col=" + vName + " row=" + row + " lat=" + combo + " -> " + f); } } table.setColumn(v, fa); table.removeColumn(v + 2); table.removeColumn(v + 1); } if (nErrors > 0) String2.pressEnterToContinue("nErrors=" + nErrors); //longitude nErrors = 0; if ("longitude".equals(vName) && "longitudeMinutes".equals(table.getColumnName(v + 1)) && "longitudeLocation".equals(table.getColumnName(v + 2))) { FloatArray fa = new FloatArray(nRows, false); //float avoids, e.g., xx.33333333333333 PrimitiveArray pa1 = table.getColumn(v + 1); PrimitiveArray pa2 = table.getColumn(v + 2); for (int row = 0; row < nRows; row++) { String loc = pa2.getString(row); String combo = pa.getString(row) + " " + pa1.getString(row) + " " + loc; float f = //will be NaN if trouble (pa.getFloat(row) + (pa1.getFloat(row) / 60)) * (loc.equals("E") ? 1 : loc.equals("W") ? -1 : Float.NaN); fa.atInsert(row, f); if (combo.length() > 2 && //2 spaces (f < -180 || f > 180 || Float.isNaN(f))) { nErrors++; if (nErrors <= 5) String2.log("ERROR: col=" + vName + " row=" + row + " lat=" + combo + " -> " + f); } } table.setColumn(v, fa); table.removeColumn(v + 2); table.removeColumn(v + 1); } if (nErrors > 0) String2.pressEnterToContinue("nErrors=" + nErrors); //yyMM add century to cruiseYYMM nErrors = 0; if ("yyMM".equals(vUnits)) { for (int row = 0; row < nRows; row++) { String val = pa.getString(row); if (val.matches("[0-9]{4}")) { int year = String2.parseInt(val.substring(0, 2)); pa.setString(row, (year < cutoffYear ? "20" : "19") + val); } else { if (val.length() != 0) { nErrors++; if (nErrors <= 5) String2.log("ERROR: col=" + vName + " row=" + row + " yyMM=" + val); } pa.setString(row, ""); //set to MV } } atts.set("units", ""); //leave it as a String identifier } if (nErrors > 0) String2.pressEnterToContinue("nErrors=" + nErrors); //yyMMdd nErrors = 0; if ("yyMMdd".equals(vUnits)) { String nextUnits = nextAtts.getString("units"); boolean nextHasMinutes = "HHmm".equals(nextUnits); if (nextHasMinutes) String2.log("combining yyMMdd and next column (HHmm)"); String nextVName = nextHasMinutes ? table.getColumnName(v + 1) : ""; DoubleArray datePA = new DoubleArray(nRows, false); PrimitiveArray minutesPA = nextHasMinutes ? table.getColumn(v + 1) : (PrimitiveArray) null; //??!! Use Zulu or local, or time_zone data (in one table only)? GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("America/Los_Angeles")); Calendar2.clearSmallerFields(gc, Calendar2.DATE); for (int row = 0; row < nRows; row++) { String val = pa.getString(row); if (val.matches("[0-9]{6}")) { int year = String2.parseInt(val.substring(0, 2)); gc.set(Calendar2.YEAR, year < cutoffYear ? 2000 : 1900); gc.set(Calendar2.MONTH, String2.parseInt(val.substring(2, 4)) - 1); //0.. gc.set(Calendar2.DATE, String2.parseInt(val.substring(4, 6))); if (nextHasMinutes) { Calendar2.clearSmallerFields(gc, Calendar2.DATE); int HHmm = minutesPA.getInt(row); if (HHmm < 0 || HHmm > 2359) { nErrors++; if (nErrors <= 5) String2.log("ERROR: col=" + nextVName + " row=" + row + " HHmm=" + minutesPA.getString(row)); } else { gc.set(Calendar2.HOUR_OF_DAY, HHmm / 100); gc.set(Calendar2.MINUTE, HHmm % 100); } } datePA.add(Calendar2.gcToEpochSeconds(gc)); } else { if (val.length() != 0) { nErrors++; if (nErrors <= 5) String2.log("ERROR: col=" + vName + " row=" + row + " yyMMdd=" + val); } datePA.add(Double.NaN); } } table.setColumn(v, datePA); atts.set("units", Calendar2.SECONDS_SINCE_1970); atts.set("time_precision", //AKA EDV.TIME_PRECISION nextHasMinutes ? "1970-01-01T00:00" : "1970-01-01"); if (nextHasMinutes) table.removeColumn(v + 1); } if (nErrors > 0) String2.pressEnterToContinue("nErrors=" + nErrors); } //save as .nc String2.log("After adjustments:\n" + String2.annotatedString(table.dataToString(5))); table.saveAsFlatNc(dir + tableName + ".nc", rowName, false); return table; }