List of usage examples for java.util GregorianCalendar setTime
public final void setTime(Date date)
Date
. From source file:PVGraph.java
public java.util.List<YearsData> getYearsData() { Statement stmt = null;//from ww w .j av a 2 s. c o m String query = "select * from DayData where CurrentPower != 0 order by DateTime"; Map<String, YearsData> result = new HashMap<String, YearsData>(); GregorianCalendar gc = new GregorianCalendar(); try { getDatabaseConnection(); stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String serial = rs.getString("serial"); YearsData yd = result.get(serial); if (yd == null) { yd = new YearsData(); yd.serial = serial; yd.inverter = rs.getString("inverter"); yd.startTotalPower = rs.getDouble("ETotalToday"); result.put(serial, yd); } gc.setTime(rs.getTimestamp("DateTime")); int year = gc.get(Calendar.YEAR); double totalPower = rs.getDouble("ETotalToday"); yd.powers.put(year, totalPower); yd.endTotalPower = totalPower; } } catch (SQLException e) { System.err.println("Query failed: " + e.getMessage()); } finally { try { stmt.close(); } catch (SQLException e) { // relax } } return new java.util.ArrayList<YearsData>(result.values()); }
From source file:PVGraph.java
public java.util.List<PeriodData> getYearData(int year, boolean detailed) { Statement stmt = null;/*from w w w . ja va 2s. com*/ String query = "select * from DayData where year(DateTime) = " + year + " and CurrentPower != 0 order by DateTime"; Map<String, PeriodData> result = new HashMap<String, PeriodData>(); GregorianCalendar gc = new GregorianCalendar(); try { getDatabaseConnection(); stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String serial = rs.getString("serial"); PeriodData pd = result.get(serial); if (pd == null) { pd = new PeriodData(); pd.serial = serial; pd.inverter = rs.getString("inverter"); pd.startTotalPower = rs.getDouble("ETotalToday"); result.put(serial, pd); } gc.setTime(rs.getTimestamp("DateTime")); if (detailed) pd.numPowers = gc.get(Calendar.DAY_OF_YEAR); else pd.numPowers = gc.get(Calendar.MONTH) + 1; double power = rs.getDouble("ETotalToday"); pd.powers[pd.numPowers - 1] = power; pd.endTotalPower = power; } } catch (SQLException e) { System.err.println("Query failed: " + e.getMessage()); } finally { try { stmt.close(); } catch (SQLException e) { // relax } } return new java.util.ArrayList<PeriodData>(result.values()); }
From source file:org.ramadda.util.Utils.java
/** * _more_/*from w w w .j a va 2 s . c om*/ * * @param f _more_ * * @return _more_ */ public static String normalizeTemplateUrl(String f) { StringBuilder s = new StringBuilder(); Date now = new Date(); GregorianCalendar g = new GregorianCalendar(); Date currentDate = now; TimeZone tz = TimeZone.getTimeZone("UTC"); g.setTime(currentDate); //Old macros if (f.indexOf("${now") >= 0) { f = f.replace("${now.year}", g.get(g.YEAR) + ""); f = f.replace("${now.month}", StringUtil.padZero(g.get(g.MONTH), 2)); f = f.replace("${now.day}", StringUtil.padZero(g.get(g.DAY_OF_MONTH), 2)); f = f.replace("${now.hour}", StringUtil.padZero(g.get(g.HOUR_OF_DAY), 2)); f = f.replace("${now.minute}", StringUtil.padZero(g.get(g.MINUTE), 2)); } List<String> toks = StringUtil.splitMacros(f); for (int i = 0; i < toks.size(); i++) { String t = toks.get(i); //System.err.println("T:" + t); if (i / 2.0 == (int) i / 2) { s.append(t); //System.err.println("appending"); continue; } String d = null; if (t.startsWith("z:")) { tz = TimeZone.getTimeZone(t.substring(2)); continue; } if (t.startsWith("date:")) { t = t.substring(5).trim(); Date newDate = null; if (t.equals("now")) { newDate = now; } else { newDate = DateUtil.getRelativeDate(now, t); } if (newDate != null) { currentDate = newDate; g.setTime(currentDate); } continue; } if (t.startsWith("format:")) { t = t.substring("format:".length()).trim(); SimpleDateFormat sdf = makeDateFormat(t); sdf.setTimeZone(tz); s.append(sdf.format(currentDate)); continue; } if (t.startsWith("year")) { d = g.get(g.YEAR) + ""; } else if (t.startsWith("month")) { d = StringUtil.padZero(g.get(g.MONTH), 2); } else if (t.startsWith("day")) { d = StringUtil.padZero(g.get(g.DAY_OF_MONTH), 2); } else if (t.startsWith("hour")) { d = StringUtil.padZero(g.get(g.HOUR_OF_DAY), 2); } else if (t.startsWith("minute")) { d = StringUtil.padZero(g.get(g.MINUTE), 2); } else { //Put it back d = "${" + t + "}"; // System.err.println("Unknown macro:" + t); // continue; } s.append(d); } return s.toString(); }
From source file:org.socraticgrid.docmgr.NHINQueryProcessor.java
/** * Parse metadata query result for summary return. * * @param result summary info/* w ww . j a va 2 s. c om*/ * @return */ private DocumentInfoType parseMetadata(ExtrinsicObjectType docMeta) { GregorianCalendar cal = new GregorianCalendar(); //Poplulate summary data object DocumentInfoType summaryData = new DocumentInfoType(); summaryData.setDataSource(DATA_SOURCE); String desc = "NHIN Document"; try { //So many possible nulls, this try catch seems to be the best // way to make sure we get the data. desc = docMeta.getDescription().getLocalizedString().get(0).getValue(); } catch (Exception e1) { try { desc = docMeta.getName().getLocalizedString().get(0).getValue(); } catch (Exception e2) { //do nothing } } summaryData.setDescription(desc); addNameValue(summaryData.getItemValues(), ITEM_DOCUMENT_NAME, docMeta.getName().getLocalizedString().get(0).getValue()); addNameValue(summaryData.getItemValues(), ITEM_MIME_TYPE, docMeta.getMimeType()); addNameValue(summaryData.getItemValues(), ITEM_HOME_COMMUNITY_ID, docMeta.getHome()); for (SlotType1 metaSlot : docMeta.getSlot()) { if (XDS_CREATION_TIME.equals(metaSlot.getName())) { try { cal.setTime(parseXDSDate(metaSlot.getValueList().getValue().get(0))); summaryData.setDateCreated(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal)); } catch (Exception pe) { String msg = "Error parsing: " + XDS_CREATION_TIME; log.error(msg, pe); } } if (XDS_PATIENT_INFO.equals(metaSlot.getName())) { //Find patient name for (String ptVal : metaSlot.getValueList().getValue()) { //Patient name is PID-5 if (ptVal.startsWith(XDS_PATIENT_NAME)) { summaryData.setPatient(ptVal.substring(XDS_PATIENT_NAME.length())); } } } if (XDS_DOC_SIZE.equals(metaSlot.getName())) { addNameValue(summaryData.getItemValues(), ITEM_DOCUMENT_SIZE, metaSlot.getValueList().getValue().get(0)); } if (XDS_REPOSITORY_ID.equals(metaSlot.getName())) { addNameValue(summaryData.getItemValues(), ITEM_REPOSITORY_ID, metaSlot.getValueList().getValue().get(0)); } } //end for meta slots for (ExternalIdentifierType identifier : docMeta.getExternalIdentifier()) { if (XDS_DOC_ID.equals(identifier.getName().getLocalizedString().get(0).getValue())) { summaryData.setItemId(identifier.getValue()); } } for (ClassificationType classification : docMeta.getClassification()) { if (XDS_CLASS_AUTHOR.equals(classification.getClassificationScheme())) { for (SlotType1 authorSlot : classification.getSlot()) { if (XDS_SLOT_AUTHOR.equals(authorSlot.getName())) { summaryData.setAuthor(authorSlot.getValueList().getValue().get(0)); } } for (SlotType1 authorSlot : classification.getSlot()) { if (XDS_SLOT_INSTITUTION.equals(authorSlot.getName())) { addNameValue(summaryData.getItemValues(), ITEM_INSTITUTION, authorSlot.getValueList().getValue().get(0)); } } } } return summaryData; }
From source file:org.motechproject.mobile.omp.manager.intellivr.IntellIVRBeanTest.java
private XMLGregorianCalendar toXMLGregorianCalendar(Date date) throws DatatypeConfigurationException { GregorianCalendar c = new GregorianCalendar(); c.setTime(date); return DatatypeFactory.newInstance().newXMLGregorianCalendar(c); }
From source file:org.motechproject.mobile.omp.manager.intellivr.IntellIVRBeanTest.java
private Date addToDate(Date start, int field, int amount) { GregorianCalendar cal = new GregorianCalendar(); cal.setTime(start); cal.add(field, amount);// w w w.j a v a2 s . co m return cal.getTime(); }
From source file:org.accada.epcis.repository.query.QueryOperationsBackendSQL.java
/** * {@inheritDoc}/*from w ww . j a va 2 s .c om*/ */ public Map<String, QuerySubscriptionScheduled> fetchSubscriptions(final QueryOperationsSession session) throws SQLException, ImplementationExceptionResponse { String query = "SELECT * FROM subscription"; LOG.debug("SQL: " + query); Statement stmt = session.getConnection().createStatement(); QuerySubscriptionScheduled storedSubscription; GregorianCalendar initrectime = new GregorianCalendar(); ResultSet rs = stmt.executeQuery(query); Map<String, QuerySubscriptionScheduled> subscribedMap = new HashMap<String, QuerySubscriptionScheduled>(); while (rs.next()) { try { String subscrId = rs.getString("subscriptionid"); ObjectInput in = new ObjectInputStream(rs.getBinaryStream("params")); QueryParam[] paramArray = (QueryParam[]) in.readObject(); // convert QueryParam[] to QueryParams QueryParams params = new QueryParams(); for (int i = 0; i < paramArray.length; i++) { params.getParam().add(paramArray[i]); } String dest = rs.getString("dest"); in = new ObjectInputStream(rs.getBinaryStream("sched")); Schedule sched = (Schedule) in.readObject(); initrectime.setTime(rs.getTimestamp("initialrecordingtime")); boolean exportifempty = rs.getBoolean("exportifempty"); String queryName = rs.getString("queryname"); String trigger = rs.getString("trigg"); if (trigger == null || trigger.length() == 0) { storedSubscription = new QuerySubscriptionScheduled(subscrId, params, dest, Boolean.valueOf(exportifempty), initrectime, new GregorianCalendar(), sched, queryName); } else { storedSubscription = new QuerySubscriptionTriggered(subscrId, params, dest, Boolean.valueOf(exportifempty), initrectime, new GregorianCalendar(), queryName, trigger, sched); } subscribedMap.put(subscrId, storedSubscription); } catch (SQLException e) { // sql exceptions are passed on throw e; } catch (Exception e) { // all other exceptions are caught String msg = "Unable to restore subscribed queries from the database."; LOG.error(msg, e); ImplementationException iex = new ImplementationException(); iex.setReason(msg); iex.setSeverity(ImplementationExceptionSeverity.ERROR); throw new ImplementationExceptionResponse(msg, iex, e); } } return subscribedMap; }
From source file:org.jahia.services.importexport.LegacyImportHandler.java
private boolean setPropertyField(ExtendedNodeType baseType, String localName, JCRNodeWrapper node, String propertyName, String value, Map<String, String> creationMetadata) throws RepositoryException { JCRNodeWrapper parent = node;/*from w w w. j av a2s . co m*/ String mixinType = null; if (propertyName.contains("|")) { mixinType = StringUtils.substringBefore(propertyName, "|"); propertyName = StringUtils.substringAfter(propertyName, "|"); } if (StringUtils.contains(propertyName, "/")) { String parentPath = StringUtils.substringBeforeLast(propertyName, "/"); if (parent.hasNode(parentPath)) { parent = parent.getNode(parentPath); } propertyName = StringUtils.substringAfterLast(propertyName, "/"); } parent = checkoutNode(parent); if (!StringUtils.isEmpty(mixinType) && !parent.isNodeType(mixinType)) { parent.addMixin(mixinType); } ExtendedPropertyDefinition propertyDefinition; propertyDefinition = parent.getApplicablePropertyDefinition(propertyName); if (propertyDefinition == null) { return false; } if (propertyDefinition.isProtected()) { return false; } if (StringUtils.isNotBlank(value) && !value.equals("<empty>")) { Node n = parent; if (propertyDefinition.isInternationalized()) { n = getOrCreateI18N(parent, locale, creationMetadata); } if (!n.isCheckedOut()) { session.checkout(n); } switch (propertyDefinition.getRequiredType()) { case PropertyType.DATE: GregorianCalendar cal = new GregorianCalendar(); try { DateFormat df = new SimpleDateFormat(ImportExportService.DATE_FORMAT); Date d = df.parse(value); cal.setTime(d); n.setProperty(propertyName, cal); } catch (java.text.ParseException e) { logger.error(e.getMessage(), e); } break; case PropertyType.REFERENCE: case PropertyType.WEAKREFERENCE: if (propertyDefinition.isMultiple()) { String[] strings = Patterns.TRIPPLE_DOLLAR.split(value); for (String s : strings) { createReferenceValue(s, propertyDefinition.getSelector(), n, propertyName); } } else { createReferenceValue(value, propertyDefinition.getSelector(), n, propertyName); } break; default: switch (propertyDefinition.getSelector()) { case SelectorType.RICHTEXT: { if (value.contains("=\"###")) { int count = 1; StringBuilder buf = new StringBuilder(value); while (buf.indexOf("=\"###") > -1) { int from = buf.indexOf("=\"###") + 2; int to = buf.indexOf("\"", from); String ref = buf.substring(from, to); if (ref.startsWith("###/webdav")) { ref = StringUtils.substringAfter(ref, "###/webdav"); buf.replace(from, to, "##doc-context##/{workspace}/##ref:link" + count + "##"); } else if (ref.startsWith("###file:")) { ref = StringUtils.substringAfter(ref, "###file:"); final int qmPos = ref.indexOf('?'); boolean isUuid = false; if (qmPos != -1) { if (StringUtils.substring(ref, qmPos + 1).startsWith("uuid=default:")) { ref = StringUtils.substring(ref, qmPos + 14); isUuid = true; } else ref = StringUtils.substringBefore(ref, "?"); } if (!isUuid) ref = correctFilename(ref); buf.replace(from, to, "##doc-context##/{workspace}/##ref:link" + count + "##"); } else { ref = StringUtils.substringAfterLast(ref, "/"); // we keep the URL parameters if any String params = ""; int pos = ref.indexOf('?'); if (pos == -1) { pos = ref.indexOf('#'); } if (pos != -1) { params = ref.substring(pos); ref = ref.substring(0, pos); } buf.replace(from, to, "##cms-context##/{mode}/{lang}/##ref:link" + count + "##.html" + params); } try { ref = URLDecoder.decode(ref, "UTF-8"); } catch (UnsupportedEncodingException e) { } if (!references.containsKey(ref)) { references.put(ref, new ArrayList<String>()); } references.get(ref) .add(n.getIdentifier() + "/[" + count + "]" + propertyDefinition.getName()); count++; } value = buf.toString(); } n.setProperty(propertyName, value); if (logger.isDebugEnabled()) logger.debug("Setting on node " + n.getPath() + " property " + propertyName + " with value=" + value); break; } default: { String[] vcs = propertyDefinition.getValueConstraints(); List<String> constraints = Arrays.asList(vcs); if (!propertyDefinition.isMultiple()) { if (value.startsWith("<jahia-resource")) { value = ResourceBundleMarker.parseMarkerValue(value).getResourceKey(); if (value.startsWith(propertyDefinition.getResourceBundleKey())) { value = value.substring(propertyDefinition.getResourceBundleKey().length() + 1); } } else if ("jcr:description".equals(propertyName)) { value = removeHtmlTags(value); } value = baseType != null ? mapping.getMappedPropertyValue(baseType, localName, value) : value; if (valueMatchesContraints(value, constraints)) { try { n.setProperty(propertyName, value); if (logger.isDebugEnabled()) logger.debug("Setting on node " + n.getPath() + " property " + propertyName + " with value=" + value); } catch (Exception e) { logger.error("Impossible to set property " + propertyName + " due to exception", e); } } else { logger.error( "Impossible to set property " + propertyName + " due to some constraint error"); logger.error(" - value = " + value); logger.error(" - constraints = " + constraints.toString()); } } else { String[] strings = Patterns.TRIPPLE_DOLLAR.split(value); List<Value> values = new ArrayList<Value>(); for (String string : strings) { if (string.startsWith("<jahia-resource")) { string = ResourceBundleMarker.parseMarkerValue(string).getResourceKey(); if (string.startsWith(propertyDefinition.getResourceBundleKey())) { string = string .substring(propertyDefinition.getResourceBundleKey().length() + 1); } } value = baseType != null ? mapping.getMappedPropertyValue(baseType, localName, value) : value; if (constraints.isEmpty() || constraints.contains(value)) { values.add(new ValueImpl(string, propertyDefinition.getRequiredType())); } } n.setProperty(propertyName, values.toArray(new Value[values.size()])); if (logger.isDebugEnabled()) logger.debug("Setting on node " + n.getPath() + " property " + propertyName + " with value=" + values); } break; } } } } else { return false; } return true; }
From source file:org.socraticgrid.docmgr.DocumentManagerImpl.java
/** * KMR Inbox request for cross-gateway NHIN documents. * * @param request//from w w w . j a v a2s . c o m * @return */ public org.socraticgrid.common.docmgr.GetNHINDocumentsResponseType getNHINDocuments( org.socraticgrid.common.docmgr.GetNHINDocumentsRequestType request) { GetNHINDocumentsResponseType response = new GetNHINDocumentsResponseType(); //Assign default response response.setProcessState(XDSProcessConstants.PROCESS_STATE_AVAILABLE); response.setSuccessStatus(true); //Check if there is an existing query. XDSService xdsService = new XDSService(); ProcessQueryParams query = new ProcessQueryParams(); query.setPatientId(request.getPatientId()); List<XDSProcess> processes = xdsService.getProcessesByParams(query); //If query exists and is stale, delete Iterator<XDSProcess> procIter = processes.iterator(); while (procIter.hasNext()) { XDSProcess process = procIter.next(); GregorianCalendar now = new GregorianCalendar(); GregorianCalendar staleTime = new GregorianCalendar(); staleTime.setTime(process.getStartTime()); staleTime.add(Calendar.MINUTE, XDS_QUERY_DURATION); if (now.after(staleTime)) { log.info("Removing stale process for patient: " + process.getPatientId() + ", ticket: " + process.getTicket()); xdsService.deleteProcess(process); procIter.remove(); } } //Check if there is an existing query that is still valid if (!processes.isEmpty()) { XDSProcess process = processes.get(0); response.setProcessState(XDSProcessConstants.PROCESS_STATE_IN_PROGRESS); response.setStatusMessage("Current query in progress for patient: " + process.getPatientId() + ", by user: " + process.getUserId() + ", started at: " + process.getStartTime()); } //Check action value if we don't have an existing query if (processes.isEmpty() && (request.getAction() != null) && request.getAction().equals(XDS_INBOX_ACTION)) { StartNHINQueryAndDownloadResponseType startResponse = null; try { log.debug("Starting NHIN query for patient: " + request.getPatientId()); //Start new query StartNHINQueryAndDownloadRequestType startRequest = new StartNHINQueryAndDownloadRequestType(); startRequest.setPatientUnitNumber(request.getPatientId()); startRequest.setPatientDOB(request.getPatientDOB()); startRequest.setPatientFirstName(request.getPatientFirstName()); startRequest.setPatientMiddleName(request.getPatientMiddleName()); startRequest.setPatientLastName(request.getPatientLastName()); startRequest.setUsername(request.getUserId()); startRequest.setProviderFirstName(request.getUserFirstName()); startRequest.setProviderMiddleName(request.getUserMiddleName()); startRequest.setProviderLastName(request.getUserLastName()); startRequest.setHomeCommunityId( PropertyAccessor.getProperty(REPOSITORY_PROPERTY_FILE, DEFAULT_HOME_COMMUNITY_ID)); GregorianCalendar queryDate = new GregorianCalendar(); queryDate.add(Calendar.YEAR, -5); startRequest.setQueryFromDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(queryDate)); startRequest.setCallbackURL( PropertyAccessor.getProperty(REPOSITORY_PROPERTY_FILE, XDS_PROCESS_ENDPOINT_PROP)); startResponse = startNHINQueryAndDownload(startRequest); } catch (Exception e) { log.error("Error handling getDocuments for patient: " + request.getPatientId(), e); } //Create new process record if ((startResponse != null) && !startResponse.getTicket().equals(JOB_FAILURE_ID)) { XDSProcess newProcess = new XDSProcess(); newProcess.setTicket(startResponse.getTicket()); newProcess.setPatientId(request.getPatientId()); newProcess.setUserId(request.getUserId()); newProcess.setStartTime(new Date()); newProcess.setDownloadCount(-1L); newProcess.setExistedCount(-1L); newProcess.setResultCount(-1L); xdsService.saveProcess(newProcess); response.setProcessState(XDSProcessConstants.PROCESS_STATE_IN_PROGRESS); response.setStatusMessage("Process started."); } else { response.setProcessState(XDSProcessConstants.PROCESS_STATE_AVAILABLE); response.setStatusMessage("Process start failed."); } } return response; }
From source file:org.structr.core.entity.AbstractNode.java
@Override public GregorianCalendar getLastModificationDate() { final Date creationDate = getProperty(AbstractNode.lastModifiedDate); if (creationDate != null) { final GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(creationDate); return calendar; }// w w w . j a v a 2 s.com return null; }