Example usage for java.util Date clone

List of usage examples for java.util Date clone

Introduction

In this page you can find the example usage for java.util Date clone.

Prototype

public Object clone() 

Source Link

Document

Return a copy of this object.

Usage

From source file:com.openmeap.admin.web.backing.GlobalSettingsBacking.java

@Override
public Collection<ProcessingEvent> process(ProcessingContext context, Map<Object, Object> templateVariables,
        Map<Object, Object> parameterMap) {

    List<ProcessingEvent> events = new ArrayList<ProcessingEvent>();
    GlobalSettings settings = modelManager.getGlobalSettings();

    // setup the variables required for form render
    templateVariables.put(PROCESS_TARGET_PARAM, ProcessingTargets.GLOBAL_SETTINGS);

    Boolean hasPerm = modelManager.getAuthorizer().may(Action.MODIFY, settings);
    templateVariables.put("mayModify", hasPerm);
    if (hasPerm == Boolean.FALSE) {
        events.add(new MessagesEvent(
                "The user logged in does not have permissions to change the global settings."));
    }/*from w  ww  . j a  va  2 s .c  o m*/

    if (!empty(PROCESS_TARGET_PARAM, parameterMap)) {
        // process a post to the form

        if (!empty(EXT_SVC_URL_PREFIX_PARAM, parameterMap)) {
            String svcUrl = firstValue(EXT_SVC_URL_PREFIX_PARAM, parameterMap);
            settings.setExternalServiceUrlPrefix(svcUrl);
        }

        if (!empty(MAX_FILE_UPLOAD_SIZE_PARAM, parameterMap)) {
            Integer maxFileUploadSize = Integer.valueOf(firstValue(MAX_FILE_UPLOAD_SIZE_PARAM, parameterMap));
            settings.setMaxFileUploadSize(maxFileUploadSize);
        }

        // process the storage path parameter
        if (!empty(STORAGE_PATH_PARAM, parameterMap)) {
            String path = firstValue(STORAGE_PATH_PARAM, parameterMap);
            settings.setTemporaryStoragePath(path);
        }

        // process auth salt
        if (!empty(AUTH_SALT_PARAM, parameterMap)) {
            if (empty(AUTH_SALT_VERIFY_PARAM, parameterMap)
                    || !equalsEachOther(AUTH_SALT_PARAM, AUTH_SALT_VERIFY_PARAM, parameterMap)) {
                events.add(new MessagesEvent("Authentication salt and salt verify must match"));
            } else {
                settings.setServiceManagementAuthSalt(firstValue(AUTH_SALT_PARAM, parameterMap));
            }
        }

        List<ClusterNode> toDelete = new ArrayList<ClusterNode>();

        // process the ClusterNode objects
        if (parameterMap.get(CLUSTER_NODE_URLS_PARAM) != null) {
            String[] clusterNodeUrls = (String[]) parameterMap.get(CLUSTER_NODE_URLS_PARAM);
            String[] clusterNodePaths = (String[]) parameterMap.get(CLUSTER_NODE_PATHS_PARAM);
            int end = clusterNodeUrls.length;

            // make sure there is a map in cluster nodes
            List<ClusterNode> clusterNodes = settings.getClusterNodes();
            if (clusterNodes == null) {
                clusterNodes = new Vector<ClusterNode>();
                settings.setClusterNodes(clusterNodes);
            }

            // iterate over each node configuration, updating the clusterNodes as per input
            boolean warn = false;
            for (int i = 0; i < end; i++) {

                String thisNodeUrl = clusterNodeUrls[i].trim();
                String thisNodePath = clusterNodePaths[i].trim();

                if (thisNodeUrl.length() == 0 && warn == false) {
                    warn = true;
                    events.add(new MessagesEvent(
                            "A cluster node must be specified.  The service url must be internally accessible by the administrative service, and should point to the services context.  The rest of settings changes will be applied."));
                    continue;
                }

                // remove any nodes that no longer appear
                List<String> urls = Arrays.asList(clusterNodeUrls);
                List<String> urlsToRemove = new ArrayList<String>();
                for (ClusterNode node : clusterNodes) {
                    if (!urls.contains(node.getServiceWebUrlPrefix())) {
                        urlsToRemove.add(node.getServiceWebUrlPrefix());
                    }
                }
                for (String url : urlsToRemove) {
                    ClusterNode node = settings.getClusterNode(url);
                    clusterNodes.remove(node);
                    modelManager.delete(node, events);
                }
                ClusterNode node = null;
                if ((node = settings.getClusterNode(thisNodeUrl)) != null) {
                    node.setFileSystemStoragePathPrefix(thisNodePath);
                } else {
                    ClusterNode thisNode = new ClusterNode();
                    thisNode.setServiceWebUrlPrefix(thisNodeUrl);
                    thisNode.setFileSystemStoragePathPrefix(thisNodePath);
                    settings.addClusterNode(thisNode);
                }
            }

            // remove any nodes that no longer appear
            List<String> urls = Arrays.asList(clusterNodeUrls);
            for (ClusterNode node : settings.getClusterNodes()) {
                if (!urls.contains(node.getServiceWebUrlPrefix())) {
                    toDelete.add(node);
                }
            }
        }

        try {
            modelManager.begin();
            if (toDelete != null) {
                for (ClusterNode node : toDelete) {
                    settings.removeClusterNode(node);
                    modelManager.delete(node, events);
                }
            }
            modelManager.addModify(settings, events);
            modelManager.commit(events);
            modelManager.refresh(settings, events);
            events.add(new MessagesEvent("The settings were successfully modified."));
        } catch (InvalidPropertiesException e) {
            modelManager.rollback();
            logger.info("Invalid properties submitted for an application", e);
            events.add(new MessagesEvent(e.getMessage()));
        } catch (PersistenceException e) {
            modelManager.rollback();
            logger.error("An exception occurred commiting the transaction", e);
            events.add(new MessagesEvent(e.getMessage()));
        }
        try {
            healthChecker.refreshSettings();
            List<Exception> es = healthChecker.checkNowAndWait();
            if (es.size() > 0) {
                for (Exception e : es) {
                    events.add(new MessagesEvent(e.getMessage()));
                }
            }
        } catch (InterruptedException e) {
            logger.error("Exception occurred waiting on the health check thread after updating global settings",
                    e);
            events.add(new MessagesEvent(e.getMessage()));
        }
    }

    if (settings.getExternalServiceUrlPrefix() != null) {
        templateVariables.put(EXT_SVC_URL_PREFIX_PARAM, settings.getExternalServiceUrlPrefix());
    }
    if (settings.getTemporaryStoragePath() != null) {
        templateVariables.put(STORAGE_PATH_PARAM, settings.getTemporaryStoragePath());
    }
    if (settings.getServiceManagementAuthSalt() != null) {
        templateVariables.put(AUTH_SALT_PARAM, settings.getServiceManagementAuthSalt());
        templateVariables.put(AUTH_SALT_VERIFY_PARAM, settings.getServiceManagementAuthSalt());
    }
    if (settings.getClusterNodes() != null && settings.getClusterNodes().size() > 0) {
        if (healthChecker != null) {
            for (ClusterNode node : settings.getClusterNodes()) {
                ClusterNode checkerNode = healthChecker.getSettings()
                        .getClusterNode(node.getServiceWebUrlPrefix());
                if (checkerNode != null) {
                    synchronized (checkerNode) {
                        node.setLastStatus(checkerNode.getLastStatus());
                        Date date = null;
                        node.setLastStatusCheck(
                                (Date) ((date = checkerNode.getLastStatusCheck()) != null ? date.clone()
                                        : null));
                        node.setLastStatusMessage(checkerNode.getLastStatusMessage());
                    }
                }
            }
        }
        templateVariables.put(CLUSTER_NODES_VAR, settings.getClusterNodes());
    }
    if (settings.getMaxFileUploadSize() != null) {
        templateVariables.put(MAX_FILE_UPLOAD_SIZE_PARAM, settings.getMaxFileUploadSize());
    }

    if (events.size() > 0)
        return events;
    return null;
}

From source file:net.chaosserver.weathernext.weather.WeatherData.java

/**
 * Constructs a WeatherData object with all of the information populated.
 * //from  w  w w .j  a v  a 2 s  . c  om
 * @param day The date this object represents
 * @param locationName The friendly name of the location
 * @param weatherState The machine readable weather state
 * @param moonPhase the machine readable lunation of the moon
 * @param weatherDescription The friendly description of the forecast
 * @param highTempurature The high temperature for the day
 * @param lowTempurature The low temperature for the day
 * @param sunrise The time the sun will rise
 * @param sunset The time the sun wills set
 * @param attributionString Attribution string for where this weather data
 *            came from
 * @param attributionUrl Attribution URL for where this weather data came
 *            from
 */
public WeatherData(Date day, String locationName, WeatherState weatherState, MoonPhase moonPhase,
        String weatherDescription, float highTempurature, float lowTempurature, Date sunrise, Date sunset,
        String attributionString, String attributionUrl) {

    this.day = day != null ? (Date) day.clone() : null;
    setLocationName(locationName);
    this.weatherState = weatherState;
    this.moonPhase = moonPhase;
    this.weatherDescription = weatherDescription;
    this.highTempurature = highTempurature;
    this.lowTempurature = lowTempurature;
    this.sunrise = sunrise != null ? (Date) sunrise.clone() : null;
    this.sunset = sunset != null ? (Date) sunset.clone() : null;
    this.attributionString = attributionString;
    this.attributionUrl = attributionUrl;

    forecast = new TreeSet<WeatherData>();
}

From source file:graficos.GraficoGantt.java

private void agregarTareasConcretas(Suceso suceso, Date fecha_com, int unidad_tiempo) {
    Vector<Actividad> vec = suceso.getActividadesSalientes();
    for (Iterator<Actividad> it = vec.iterator(); it.hasNext();) {
        Actividad a = it.next();//from  ww w .jav a2  s .  com
        if (!a.esFicticia()) {
            Date fecha_fin = getFechaIncremento(fecha_com, unidad_tiempo,
                    a.getParametrosNormales().getTiempo());
            Task tarea;
            if (a.esCritica()) {
                tarea = new Task("(" + a.getIdentificador().toString() + ") " + a.getDescripcion(),
                        new SimpleTimePeriod((Date) fecha_com.clone(), fecha_fin));
                serie_tareas_c.add(tarea);
            } else {
                tarea = new Task("(" + a.getIdentificador().toString() + ") " + a.getDescripcion(),
                        new SimpleTimePeriod((Date) fecha_com.clone(), fecha_fin));
                serie_tareas_nc.add(tarea);
            }
            agregarTareasConcretas(a.getSucesoFin(), fecha_fin, unidad_tiempo);
        } else
            agregarTareasConcretas(a.getSucesoFin(), fecha_com, unidad_tiempo);
    }
}

From source file:org.seedstack.samples.ddd.domain.model.handling.HandlingEvent.java

/**
 * @param trackingId       cargo//  w w  w .jav  a 2 s .co  m
 * @param completionTime   completion time, the reported time that the event actually happened (e.g. the receive
 *                         took place).
 * @param registrationTime registration time, the time the message is received
 * @param type             type of event
 * @param location         where the event took place
 */
public HandlingEvent(final TrackingId trackingId, final Date completionTime, final Date registrationTime,
        final Type type, final UnLocode location) {
    Validate.notNull(trackingId, "Cargo is required");
    Validate.notNull(completionTime, "Completion time is required");
    Validate.notNull(registrationTime, "Registration time is required");
    Validate.notNull(type, "Handling event type is required");
    Validate.notNull(location, "Location is required");

    if (type.requiresVoyage()) {
        throw new IllegalArgumentException("Voyage is required for event type " + type);
    }

    this.completionTime = (Date) completionTime.clone();
    this.registrationTime = (Date) registrationTime.clone();
    this.type = type;
    this.location = location;
    this.trackingId = trackingId;
    this.voyage = null;
}

From source file:fi.mjpphotographs.bbqtemp.main.JsonHandler.java

/**
 * This method is used for averaging temperature data arrays
 * (List<Temperature>). Mainly used for chart drawing purposes. This is
 * thread safe implementation (creates new/clone objects for output list)
 *
 * @param groupSize How many samples is taken for average.
 * @param temperatures List of Temperature objects.
 * @return Returns new array of Temperature objects which has been averaged.
 * The first occurence of logDatetime of current group is used for time.
 *//*from w ww  .ja va2 s  . c  om*/
private List<Temperature> averageData(int groupSize, List<Temperature> temperatures) {
    List<Temperature> returnArray = new ArrayList();
    int j = 0;
    float sum = 0;

    Date firstDate = null;
    for (int i = 0; i < temperatures.size(); i++) {
        if (j == 0) {
            firstDate = temperatures.get(i).getLogDatatime();
        }
        if (j < groupSize) {
            sum += temperatures.get(i).getMjTemperature();
            j++;
        }

        if (j == groupSize) {
            Temperature tmpTemperature = new Temperature();
            tmpTemperature.setMjTemperature((sum / groupSize));
            tmpTemperature.setLogDatatime((Date) firstDate.clone());
            returnArray.add(tmpTemperature);
            j = 0;
            sum = 0;
        }
    }
    if (sum > 0) {
        Temperature tmpTemperature = new Temperature();
        tmpTemperature.setMjTemperature((sum / j));
        tmpTemperature.setLogDatatime(firstDate);
        returnArray.add(tmpTemperature);
    }

    return returnArray;
}

From source file:tools.descartes.wcf.management.timeSeries.TimeSeries.java

/**
 * /*from www . j ava  2s. co m*/
 * @param startTime:    The timestamp (absolute time in [ms]) 
 *                   of the first arrival rate value added to the time series is equal 
 *                   to the start time of the time series
 * @param deltaTime:   The constant time difference between two time series values is the Delta Time
 * @param deltaTimeUnit: This parameter defines the time unit of the DeltaTime parameter
 * @param frequency:   The Frequency is the number of time series points that add up either 
 *                   to the next bigger time unit and/or to the estimated length of 
 *                   seasonal patterns in focus. The value should not be too small 
 *                   (still able to approximate the shape of the seasonal pattern) 
 *                   and not to high (to limit the computational effort of 
 *                   complex forecast strategies)
 * @param maxPeriods   The amount of Frequency time series points form a period. 
 *                   This parameter defines the maximum number of periods that 
 *                   fit into the time series. As in a `fifo queue the oldest values fall 
 *                   off when more recent values are added. The value of this setting should 
 *                   be at least 3 to enable reliable pattern detection by complex forecast 
 *                   strategies and multiplied the by Frequency value not be higher than 
 *                   200 if the computational effort of more complex forecast strategies 
 *                   should stay below one minute. 
 * @param skippedValues: The number of time series points that have fallen 
 *                   of the time series due to capacity constraints by max_periods
 */
public TimeSeries(final Date startTime, final long deltaTime, final TimeUnit deltaTimeUnit, final int frequency,
        final int maxPeriods, long skippedValues) {
    this.startTime = startTime;
    this.deltaTime = deltaTime;
    this.deltaTimeUnit = deltaTimeUnit;
    this.frequency = frequency;
    this.maxPeriods = maxPeriods;
    this.capacity = frequency * maxPeriods;
    this.skippedValues = skippedValues;
    this.oneStepMillis = TimeUnit.MILLISECONDS.convert(this.deltaTime, this.deltaTimeUnit);

    this.points = new CircularFifoBuffer(this.capacity);

    this.nextTime = (Date) startTime.clone();
    this.setNextTime();
}

From source file:nl.mpi.lamus.workspace.model.implementation.LamusWorkspace.java

public LamusWorkspace(int workspaceID, String userID, int topNodeID, URI topNodeArchiveURI,
        URL topNodeArchiveURL, Date startDate, Date endDate, Date sessionStartDate, Date sessionEndDate,
        long usedStorageSpace, long maxStorageSpace, WorkspaceStatus status, String message, String crawlerID) {
    this.workspaceID = workspaceID;
    this.userID = userID;
    this.topNodeID = topNodeID;
    this.topNodeArchiveURI = topNodeArchiveURI;
    this.topNodeArchiveURL = topNodeArchiveURL;
    if (startDate != null) {
        this.startDate = (Date) startDate.clone();
    }/*from   w ww .  j a  v a2  s .c  o m*/
    if (endDate != null) {
        this.endDate = (Date) endDate.clone();
    }
    if (sessionStartDate != null) {
        this.sessionStartDate = (Date) sessionStartDate.clone();
    }
    if (sessionEndDate != null) {
        this.sessionEndDate = (Date) sessionEndDate.clone();
    }
    this.usedStorageSpace = usedStorageSpace;
    this.maxStorageSpace = maxStorageSpace;
    this.status = status;
    this.message = message;
    this.crawlerID = crawlerID;
}

From source file:com.flexive.extractor.FxSummaryInformation.java

public FxSummaryInformation(String author, String applicationName, long charCount, String comments,
        Date createdAt, Date editTime, String keywords, String lastModifiedBy, Date lastPrintedAt, String title,
        Date lastModifiedAt, int pageCount, String revNumber, int wordCount, boolean encrypted,
        String additionalText) {//from  w  w  w  .j  a  v  a2 s. c  o m
    this.author = author;
    this.applicationName = applicationName == null ? "" : applicationName;
    this.charCount = charCount;
    this.comments = comments == null ? "" : comments;
    if (createdAt != null)
        this.createdAt = (Date) createdAt.clone();
    else
        this.createdAt = new Date();
    if (editTime != null)
        this.editTime = (Date) editTime.clone();
    else
        this.editTime = new Date();
    this.keywords = keywords == null ? "" : keywords;
    this.lastModifiedBy = lastModifiedBy;
    if (lastPrintedAt != null)
        this.lastPrintedAt = (Date) lastPrintedAt.clone();
    else
        this.lastPrintedAt = new Date();
    this.title = title == null ? "" : title;
    if (lastModifiedAt != null)
        this.lastModifiedAt = (Date) lastModifiedAt.clone();
    else
        this.lastModifiedAt = new Date();
    this.pageCount = pageCount;
    this.revNumber = revNumber == null ? "" : revNumber;
    this.wordCount = wordCount;
    this.encrypted = encrypted;
    this.additionalText = additionalText == null ? "" : additionalText;
}

From source file:fr.cph.stock.entities.Portfolio.java

/**
 * Set last company ypdate date//from  w  w  w  .  jav a 2s.  co  m
 *
 * @param lastCompanyUpdate the date
 */
public final void setLastCompanyUpdate(final Date lastCompanyUpdate) {
    if (lastCompanyUpdate != null) {
        this.lastCompanyUpdate = (Date) lastCompanyUpdate.clone();
    }
}

From source file:org.seedstack.samples.ddd.domain.model.handling.HandlingEvent.java

/**
 * @param trackingId       cargo//from  w  w w .j  a  v a  2s  .  co m
 * @param completionTime   completion time, the reported time that the event actually happened (e.g. the receive
 *                         took place).
 * @param registrationTime registration time, the time the message is received
 * @param type             type of event
 * @param location         where the event took place
 * @param voyage           the voyage
 */
public HandlingEvent(final TrackingId trackingId, final Date completionTime, final Date registrationTime,
        final Type type, final UnLocode location, final VoyageNumber voyage) {
    Validate.notNull(trackingId, "Cargo is required");
    Validate.notNull(completionTime, "Completion time is required");
    Validate.notNull(registrationTime, "Registration time is required");
    Validate.notNull(type, "Handling event type is required");
    Validate.notNull(location, "Location is required");
    Validate.notNull(voyage, "Voyage is required");

    if (type.prohibitsVoyage()) {
        throw new IllegalArgumentException("Voyage is not allowed with event type " + type);
    }

    this.voyage = voyage;
    this.completionTime = (Date) completionTime.clone();
    this.registrationTime = (Date) registrationTime.clone();
    this.type = type;
    this.location = location;
    this.trackingId = trackingId;
}