Example usage for java.util GregorianCalendar setTime

List of usage examples for java.util GregorianCalendar setTime

Introduction

In this page you can find the example usage for java.util GregorianCalendar setTime.

Prototype

public final void setTime(Date date) 

Source Link

Document

Sets this Calendar's time with the given Date.

Usage

From source file:org.agnitas.util.AgnUtils.java

/**
 * Checks if date is in future./*from ww  w .  j a  va  2s.c o m*/
 *
 * @param aDate Checked date.
 */
public static boolean isDateInFuture(Date aDate) {
    boolean result = false;
    GregorianCalendar aktCal = new GregorianCalendar();
    GregorianCalendar tmpCal = new GregorianCalendar();

    tmpCal.setTime(aDate);
    aktCal.add(GregorianCalendar.MINUTE, 5); // look five minutes in future ;-)
    if (aktCal.before(tmpCal)) {
        result = true;
    }

    return result;
}

From source file:org.apache.taverna.scufl2.translator.t2flow.T2FlowParser.java

private Calendar parseDate(String dateStr) {
    // Based briefly on patterns used by 
    // com.thoughtworks.xstream.converters.basic.DateConverter

    List<String> patterns = new ArrayList<>();
    patterns.add("yyyy-MM-dd HH:mm:ss.S z");
    patterns.add("yyyy-MM-dd HH:mm:ss z");
    patterns.add("yyyy-MM-dd HH:mm:ssz");
    patterns.add("yyyy-MM-dd HH:mm:ss.S 'UTC'");
    patterns.add("yyyy-MM-dd HH:mm:ss 'UTC'");
    Date date;/*w ww.j  av a 2s .c  o  m*/
    for (String pattern : patterns)
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat(pattern, ENGLISH);
            date = dateFormat.parse(dateStr);
            GregorianCalendar cal = new GregorianCalendar(getTimeZone("UTC"), ENGLISH);
            cal.setTime(date);
            return cal;
        } catch (ParseException e) {
            continue;
        }
    throw new IllegalArgumentException("Can't parse date: " + dateStr);
}

From source file:org.sakaiproject.sdata.tool.JCRHandler.java

/**
 * Perform a mime multipart upload into the JCR repository based on a location specified
 * by the rp parameter. The parts of the multipart upload are relative to the current
 * request path//  w  w  w  .j  a  v a 2  s.c  om
 *
 * @param request
 *          the request object of the current request.
 * @param response
 *          the response object of the current request
 * @param rp
 *          the resource definition for the current request
 * @throws ServletException
 * @throws IOException
 */
private void doMumtipartUpload(HttpServletRequest request, HttpServletResponse response, ResourceDefinition rp)
        throws ServletException, IOException {
    try {
        try {
            Node n = jcrNodeFactory.createFolder(rp.getRepositoryPath());
            if (n == null) {
                response.reset();
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Unable to uplaod to location " + rp.getRepositoryPath());
                return;
            }
        } catch (Exception ex) {
            sendError(request, response, ex);
            snoopRequest(request);
            LOG.error("Failed  TO service Request ", ex);
            return;
        }

        // Check that we have a file upload request

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();
        List<String> errors = new ArrayList<String>();

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(request);
        Map<String, Object> responseMap = new HashMap<String, Object>();
        Map<String, Object> uploads = new HashMap<String, Object>();
        Map<String, List<String>> values = new HashMap<String, List<String>>();
        int uploadNumber = 0;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            LOG.debug("Got Upload through Uploads");
            String name = item.getName();
            String fieldName = item.getFieldName();
            LOG.info("    Name is " + name + " field Name " + fieldName);
            for (String headerName : item.getHeaderNames()) {
                LOG.info("Header " + headerName + " is " + item.getHeader(headerName));
            }
            InputStream stream = item.openStream();
            if (!item.isFormField()) {
                try {
                    if (name != null && name.trim().length() > 0) {

                        List<String> realNames = values.get(REAL_UPLOAD_NAME);
                        String finalName = name;
                        if (realNames != null && realNames.size() > uploadNumber) {
                            finalName = realNames.get(uploadNumber);
                        }

                        String path = rp.convertToAbsoluteRepositoryPath(finalName);
                        // pooled uploads never overwrite.
                        List<String> pooled = values.get(POOLED);
                        if (pooled != null && pooled.size() > 0 && "1".equals(pooled.get(0))) {
                            path = rp.convertToAbsoluteRepositoryPath(PathUtils.getPoolPrefix(finalName));
                            int i = 0;
                            String basePath = path;
                            try {
                                while (true) {
                                    Node n = jcrNodeFactory.getNode(path);
                                    if (n == null) {
                                        break;
                                    }
                                    int lastStop = basePath.lastIndexOf('.');
                                    path = basePath.substring(0, lastStop) + "_" + i
                                            + basePath.substring(lastStop);
                                    i++;
                                }
                            } catch (JCRNodeFactoryServiceException ex) {
                                // the path does not exist which is good.
                            }
                        }

                        String mimeType = ContentTypes.getContentType(finalName, item.getContentType());
                        Node target = jcrNodeFactory.createFile(path, mimeType);
                        GregorianCalendar lastModified = new GregorianCalendar();
                        lastModified.setTime(new Date());
                        long size = saveStream(target, stream, mimeType, "UTF-8", lastModified);
                        Map<String, Object> uploadMap = new HashMap<String, Object>();
                        if (size > Integer.MAX_VALUE) {
                            uploadMap.put("contentLength", String.valueOf(size));
                        } else {
                            uploadMap.put("contentLength", (int) size);
                        }
                        uploadMap.put("name", finalName);
                        uploadMap.put("url", rp.convertToExternalPath(path));
                        uploadMap.put("mimeType", mimeType);
                        uploadMap.put("lastModified", lastModified.getTime());
                        uploadMap.put("status", "ok");

                        uploads.put(fieldName, uploadMap);
                    }
                } catch (Exception ex) {
                    LOG.error("Failed to Upload Content", ex);
                    Map<String, Object> uploadMap = new HashMap<String, Object>();
                    uploadMap.put("mimeType", "text/plain");
                    uploadMap.put("encoding", "UTF-8");
                    uploadMap.put("contentLength", -1);
                    uploadMap.put("lastModified", 0);
                    uploadMap.put("status", "Failed");
                    uploadMap.put("cause", ex.getMessage());
                    List<String> stackTrace = new ArrayList<String>();
                    for (StackTraceElement ste : ex.getStackTrace()) {
                        stackTrace.add(ste.toString());
                    }
                    uploadMap.put("stacktrace", stackTrace);
                    uploads.put(fieldName, uploadMap);
                    uploadMap = null;

                }

            } else {
                String value = Streams.asString(stream);
                List<String> valueList = values.get(name);
                if (valueList == null) {
                    valueList = new ArrayList<String>();
                    values.put(name, valueList);

                }
                valueList.add(value);
            }
        }

        responseMap.put("success", true);
        responseMap.put("errors", errors.toArray(new String[1]));
        responseMap.put("uploads", uploads);
        sendMap(request, response, responseMap);
        LOG.info("Response Complete Saved to " + rp.getRepositoryPath());
    } catch (Throwable ex) {
        LOG.error("Failed  TO service Request ", ex);
        sendError(request, response, ex);
        return;
    }
}

From source file:org.talend.components.marketo.runtime.client.MarketoSOAPClient.java

@Override
public MarketoRecordResult getLeadChanges(TMarketoInputProperties parameters, String offset) {
    Schema schema = parameters.schemaInput.schema.getValue();
    Map<String, String> mappings = parameters.mappingInput.getNameMappingsForMarketo();
    int bSize = parameters.batchSize.getValue() > 100 ? 100 : parameters.batchSize.getValue();
    String sOldest = parameters.oldestCreateDate.getValue();
    String sLatest = parameters.latestCreateDate.getValue();
    LOG.debug("LeadChanges - from {} to {}.", sOldest, sLatest);
    ////from  ww  w  .  j  a  v  a 2 s  .  com
    // Create Request
    //
    ParamsGetLeadChanges request = new ParamsGetLeadChanges();
    LastUpdateAtSelector leadSelector = new LastUpdateAtSelector();
    try {
        Date oldest = MarketoUtils.parseDateString(sOldest);
        Date latest = MarketoUtils.parseDateString(sLatest);
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(latest);
        DatatypeFactory factory = newInstance();
        JAXBElement<XMLGregorianCalendar> until = objectFactory
                .createLastUpdateAtSelectorLatestUpdatedAt(factory.newXMLGregorianCalendar(gc));
        GregorianCalendar since = new GregorianCalendar();
        since.setTime(oldest);
        leadSelector.setOldestUpdatedAt(factory.newXMLGregorianCalendar(since));
        leadSelector.setLatestUpdatedAt(until);
        request.setLeadSelector(leadSelector);

        JAXBElement<XMLGregorianCalendar> oldestCreateAtValue = objectFactory
                .createStreamPositionOldestCreatedAt(factory.newXMLGregorianCalendar(since));

        StreamPosition sp = new StreamPosition();
        sp.setOldestCreatedAt(oldestCreateAtValue);
        if (offset != null && !offset.isEmpty()) {
            sp.setOffset(objectFactory.createStreamPositionOffset(offset));
        }
        request.setStartPosition(sp);

    } catch (ParseException | DatatypeConfigurationException e) {
        LOG.error("Error for LastUpdateAtSelector : {}.", e.getMessage());
        throw new ComponentException(e);
    }

    // attributes
    ArrayOfString attributes = new ArrayOfString();
    for (String s : mappings.values()) {
        attributes.getStringItems().add(s);
    }
    // Activity filter
    ActivityTypeFilter filter = new ActivityTypeFilter();

    if (parameters.setIncludeTypes.getValue()) {
        ArrayOfActivityType includes = new ArrayOfActivityType();
        for (String a : parameters.includeTypes.type.getValue()) {
            includes.getActivityTypes().add(fromValue(a));
        }
        filter.setIncludeTypes(includes);
    }
    if (parameters.setExcludeTypes.getValue()) {
        ArrayOfActivityType excludes = new ArrayOfActivityType();
        for (String a : parameters.excludeTypes.type.getValue()) {
            excludes.getActivityTypes().add(fromValue(a));
        }
        filter.setExcludeTypes(excludes);
    }

    JAXBElement<ActivityTypeFilter> typeFilter = objectFactory
            .createParamsGetLeadActivityActivityFilter(filter);
    request.setActivityFilter(typeFilter);
    // batch size
    JAXBElement<Integer> batchSize = objectFactory.createParamsGetMultipleLeadsBatchSize(bSize);
    request.setBatchSize(batchSize);
    //
    //
    // Request execution
    //
    SuccessGetLeadChanges result = null;

    MarketoRecordResult mkto = new MarketoRecordResult();
    try {
        result = getPort().getLeadChanges(request, header);
        mkto.setSuccess(true);
    } catch (Exception e) {
        LOG.error("getLeadChanges error: {}.", e.getMessage());
        mkto.setSuccess(false);
        mkto.setRecordCount(0);
        mkto.setRemainCount(0);
        mkto.setErrors(Collections.singletonList(new MarketoError(SOAP, e.getMessage())));
        return mkto;
    }

    if (result == null || result.getResult().getReturnCount() == 0) {
        LOG.debug(MESSAGE_REQUEST_RETURNED_0_MATCHING_LEADS);
        mkto.setErrors(Collections.singletonList(new MarketoError(SOAP, MESSAGE_NO_LEADS_FOUND)));
        return mkto;
    }

    String streamPos = result.getResult().getNewStartPosition().getOffset().getValue();
    int recordCount = result.getResult().getReturnCount();
    int remainCount = result.getResult().getRemainingCount();

    // Process results
    List<IndexedRecord> results = convertLeadChangeRecords(
            result.getResult().getLeadChangeRecordList().getValue().getLeadChangeRecords(), schema, mappings);

    mkto.setRecordCount(recordCount);
    mkto.setRemainCount(remainCount);
    mkto.setStreamPosition(streamPos);
    mkto.setRecords(results);

    return mkto;
}

From source file:org.apache.ambari.controller.Clusters.java

public List<Node> getClusterNodes(String clusterName, String roleName, String alive) throws Exception {

    List<Node> list = new ArrayList<Node>();
    Map<String, Node> nodeMap = nodes.getNodes();
    ClusterDefinition c = operational_clusters.get(clusterName).getClusterDefinition(-1);
    if (c.getNodes() == null || c.getNodes().equals("")
            || getClusterByName(clusterName).getClusterState().getState().equalsIgnoreCase("ATTIC")) {
        String msg = "No nodes are reserved for the cluster. Typically"
                + " cluster in ATTIC state does not have any nodes reserved";
        throw new WebApplicationException((new ExceptionResponse(msg, Response.Status.NO_CONTENT)).get());
    }/*from w  w w.  j av  a2s .  com*/
    List<String> hosts = getHostnamesFromRangeExpressions(c.getNodes());
    for (String host : hosts) {
        if (!nodeMap.containsKey(host)) {
            String msg = "Node [" + host + "] is expected to be registered w/ controller but not "
                    + "locatable";
            throw new WebApplicationException(
                    (new ExceptionResponse(msg, Response.Status.INTERNAL_SERVER_ERROR)).get());
        }
        Node n = nodeMap.get(host);
        if (roleName != null && !roleName.equals("")) {
            if (n.getNodeState().getNodeRoleNames("") == null) {
                continue;
            }
            if (!n.getNodeState().getNodeRoleNames("").contains(roleName)) {
                continue;
            }
        }

        // Heart beat is set to epoch during node initialization.
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(new Date());
        XMLGregorianCalendar curTime = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
        if (alive.equals("")
                || (alive.equalsIgnoreCase("true") && Nodes.getTimeDiffInMillis(curTime,
                        n.getNodeState().getLastHeartbeatTime()) < Nodes.NODE_NOT_RESPONDING_DURATION)
                || (alive.equals("false") && Nodes.getTimeDiffInMillis(curTime,
                        n.getNodeState().getLastHeartbeatTime()) >= Nodes.NODE_NOT_RESPONDING_DURATION)) {
            list.add(nodeMap.get(host));
        }
    }
    return list;
}

From source file:org.talend.components.marketo.runtime.client.MarketoSOAPClient.java

/**
 * In getMultipleLeadsJSON you have to add includeAttributes base fields like Email. Otherwise, they return null from
 * API. WTF ?!? It's like that.../*from  w ww . j  a v  a 2s . c  om*/
 */
@Override
public MarketoRecordResult getMultipleLeads(TMarketoInputProperties parameters, String offset) {
    LOG.debug("MarketoSOAPClient.getMultipleLeadsJSON with {}", parameters.leadSelectorSOAP.getValue());
    Schema schema = parameters.schemaInput.schema.getValue();
    Map<String, String> mappings = parameters.mappingInput.getNameMappingsForMarketo();
    int bSize = parameters.batchSize.getValue();
    //
    // Create Request
    //
    ParamsGetMultipleLeads request = new ParamsGetMultipleLeads();
    // LeadSelect
    //
    // Request Using LeadKey Selector
    //
    if (parameters.leadSelectorSOAP.getValue().equals(LeadKeySelector)) {
        LOG.info("LeadKeySelector - Key type:  {} with value : {}.",
                parameters.leadKeyTypeSOAP.getValue().toString(), parameters.leadKeyValues.getValue());
        LeadKeySelector keySelector = new LeadKeySelector();
        keySelector.setKeyType(valueOf(parameters.leadKeyTypeSOAP.getValue().toString()));
        ArrayOfString aos = new ArrayOfString();
        String[] keys = parameters.leadKeyValues.getValue().split("(,|;|\\s)");
        for (String s : keys) {
            LOG.debug("Adding leadKeyValue : {}.", s);
            aos.getStringItems().add(s);
        }
        keySelector.setKeyValues(aos);
        request.setLeadSelector(keySelector);
    } else
    //
    // Request Using LastUpdateAtSelector
    //

    if (parameters.leadSelectorSOAP.getValue().equals(LastUpdateAtSelector)) {
        LOG.debug("LastUpdateAtSelector - since {} to  {}.", parameters.oldestUpdateDate.getValue(),
                parameters.latestUpdateDate.getValue());
        LastUpdateAtSelector leadSelector = new LastUpdateAtSelector();
        try {
            DatatypeFactory factory = newInstance();
            Date oldest = MarketoUtils.parseDateString(parameters.oldestUpdateDate.getValue());
            Date latest = MarketoUtils.parseDateString(parameters.latestUpdateDate.getValue());
            GregorianCalendar gc = new GregorianCalendar();
            gc.setTime(latest);
            JAXBElement<XMLGregorianCalendar> until = objectFactory
                    .createLastUpdateAtSelectorLatestUpdatedAt(factory.newXMLGregorianCalendar(gc));
            GregorianCalendar since = new GregorianCalendar();
            since.setTime(oldest);
            leadSelector.setOldestUpdatedAt(factory.newXMLGregorianCalendar(since));
            leadSelector.setLatestUpdatedAt(until);
            request.setLeadSelector(leadSelector);
        } catch (ParseException | DatatypeConfigurationException e) {
            LOG.error("Error for LastUpdateAtSelector : {}.", e.getMessage());
            throw new ComponentException(e);
        }
    } else
    //
    // Request Using StaticList Selector
    //
    if (parameters.leadSelectorSOAP.getValue().equals(StaticListSelector)) {
        LOG.info("StaticListSelector - List type : {} with value : {}.", parameters.listParam.getValue(),
                parameters.listParamListName.getValue());

        StaticListSelector staticListSelector = new StaticListSelector();
        if (parameters.listParam.getValue().equals(STATIC_LIST_NAME)) {
            JAXBElement<String> listName = objectFactory
                    .createStaticListSelectorStaticListName(parameters.listParamListName.getValue());
            staticListSelector.setStaticListName(listName);

        } else {
            // you can find listId by examining the URL : https://app-abq.marketo.com/#ST29912B2
            // #ST29912B2 :
            // #ST -> Static list identifier
            // 29912 -> our list FIELD_ID !
            // B2 -> tab in the UI
            JAXBElement<Integer> listId = objectFactory
                    .createStaticListSelectorStaticListId(parameters.listParamListId.getValue()); //
            staticListSelector.setStaticListId(listId);
        }
        request.setLeadSelector(staticListSelector);
    } else {
        // Duh !
        LOG.error("Unknown LeadSelector : {}.", parameters.leadSelectorSOAP.getValue());
        throw new ComponentException(new Exception(
                "Incorrect parameter value for LeadSelector : " + parameters.leadSelectorSOAP.getValue()));
    }
    // attributes
    // curiously we have to put some basic fields like Email in attributes if we have them feed...
    ArrayOfString attributes = new ArrayOfString();
    for (String s : mappings.values()) {
        attributes.getStringItems().add(s);
    }
    attributes.getStringItems().add("Company");
    request.setIncludeAttributes(attributes);
    // batchSize : another curious behavior... Don't seem to work properly with leadKeySelector...
    // nevertheless, the server automatically adjust batch size according request.
    JAXBElement<Integer> batchSize = new ObjectFactory().createParamsGetMultipleLeadsBatchSize(bSize);
    request.setBatchSize(batchSize);
    // stream position
    if (offset != null && !offset.isEmpty()) {
        request.setStreamPosition(new ObjectFactory().createParamsGetMultipleLeadsStreamPosition(offset));
    }
    //
    //
    // Request execution
    //
    SuccessGetMultipleLeads result = null;
    MarketoRecordResult mkto = new MarketoRecordResult();
    try {
        result = getPort().getMultipleLeads(request, header);
    } catch (Exception e) {
        LOG.error("Lead not found : {}.", e.getMessage());
        mkto.setSuccess(false);
        mkto.setErrors(Collections.singletonList(new MarketoError(SOAP, e.getMessage())));
        return mkto;
    }

    if (result == null || result.getResult().getReturnCount() == 0) {
        LOG.debug(MESSAGE_REQUEST_RETURNED_0_MATCHING_LEADS);
        mkto.setSuccess(true);
        mkto.setErrors(Collections.singletonList(new MarketoError(SOAP, MESSAGE_NO_LEADS_FOUND)));
        mkto.setRecordCount(0);
        mkto.setRemainCount(0);
        return mkto;
    } else {

        String streamPos = result.getResult().getNewStreamPosition();
        int recordCount = result.getResult().getReturnCount();
        int remainCount = result.getResult().getRemainingCount();

        // Process results
        List<IndexedRecord> results = convertLeadRecords(
                result.getResult().getLeadRecordList().getValue().getLeadRecords(), schema, mappings);

        return new MarketoRecordResult(true, streamPos, recordCount, remainCount, results);
    }
}

From source file:org.mifos.accounts.loan.struts.action.LoanAccountAction.java

/**
 * Resolve repayment start date according to given disbursement date
 * <p/>/*from   w  w  w. jav  a  2 s .com*/
 * The resulting date equates to the disbursement date plus MIN_DAYS_BETWEEN_DISBURSAL_AND_FIRST_REPAYMENT_DAY: e.g.
 * If disbursement date is 18 June 2008, and MIN_DAYS_BETWEEN_DISBURSAL_AND_FIRST_REPAYMENT_DAY is 1 then the
 * repayment start date would be 19 June 2008
 *
 * @return Date repaymentStartDate
 * @throws PersistenceException
 */
private Date resolveRepaymentStartDate(final Date disbursementDate) {
    int minDaysInterval = configurationPersistence
            .getConfigurationValueInteger(MIN_DAYS_BETWEEN_DISBURSAL_AND_FIRST_REPAYMENT_DAY);

    final GregorianCalendar repaymentStartDate = new GregorianCalendar();
    repaymentStartDate.setTime(disbursementDate);
    repaymentStartDate.add(Calendar.DAY_OF_WEEK, minDaysInterval);
    return repaymentStartDate.getTime();
}

From source file:org.sakaiproject.sdata.tool.JCRHandler.java

@Override
public void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {// www  .  j a va  2 s .  co  m
        snoopRequest(request);

        ResourceDefinition rp = resourceDefinitionFactory.getSpec(request);
        String mimeType = ContentTypes.getContentType(rp.getRepositoryPath(), request.getContentType());
        String charEncoding = null;
        if (mimeType.startsWith("text")) {
            charEncoding = request.getCharacterEncoding();
        }
        Node n = jcrNodeFactory.getNode(rp.getRepositoryPath());
        boolean created = false;
        if (n == null) {
            n = jcrNodeFactory.createFile(rp.getRepositoryPath(), mimeType);
            created = true;
            if (n == null) {
                throw new RuntimeException(
                        "Failed to create node at " + rp.getRepositoryPath() + " type " + JCRConstants.NT_FILE);
            }
        } else {
            NodeType nt = n.getPrimaryNodeType();
            if (!JCRConstants.NT_FILE.equals(nt.getName())) {
                response.reset();
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Content Can only be put to a file, resource type is " + nt.getName());
                return;
            }
        }

        GregorianCalendar gc = new GregorianCalendar();
        long lastMod = request.getDateHeader(LAST_MODIFIED);
        if (lastMod > 0) {
            gc.setTimeInMillis(lastMod);
        } else {
            gc.setTime(new Date());
        }

        InputStream in = request.getInputStream();
        saveStream(n, in, mimeType, charEncoding, gc);

        in.close();
        if (created) {
            response.setStatus(HttpServletResponse.SC_CREATED);
        } else {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    } catch (UnauthorizedException ape) {
        // catch any Unauthorized exceptions and send a 401
        response.reset();
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ape.getMessage());
    } catch (PermissionDeniedException pde) {
        // catch any permission denied exceptions, and send a 403
        response.reset();
        response.sendError(HttpServletResponse.SC_FORBIDDEN, pde.getMessage());
    } catch (SDataException e) {
        sendError(request, response, e);
        LOG.error("Failed  To service Request " + e.getMessage());
    } catch (Exception e) {
        sendError(request, response, e);
        snoopRequest(request);
        LOG.error("Failed  TO service Request ", e);
    }
}

From source file:org.socraticgrid.displayalert.DisplayAlertDataUtil.java

/**
 * Retrieve detail data.//from  w w w.ja  va2s .c  o m
 *
 * @param request
 * @return
 */
public GetComponentDetailDataResponseType getComponentDetailDataForUser(String source,
        GetComponentDetailDataForUserRequestType request) {
    GetComponentDetailDataResponseType response = new GetComponentDetailDataResponseType();

    log.debug("Retrieving " + source + " detail for ticket for user: " + request.getUserId());

    try {
        //Query based on ticket ticket id
        AlertService service = new AlertService();
        TicketQueryParams query = new TicketQueryParams();
        query.setTicketUniqueId(request.getItemId());
        List<AlertTicket> tickets = service.ticketQuery(query);

        if ((tickets == null) || (tickets.isEmpty())) {
            log.debug("Cound not find " + source + " ticket: " + request.getItemId());
            throw new Exception(ERR_MSG_ITEM_NOT_FOUND);
        }

        //Poplulate detail data object
        GregorianCalendar cal = new GregorianCalendar();
        AlertTicket ticket = tickets.get(0);
        DetailData detailData = new DetailData();
        detailData.setAuthor(ticket.getAlertOriginator());
        detailData.setFrom(ticket.getAlertOriginator());
        detailData.setData(sanitizePayload(request.getUserId(), ticket.getPayload(), ticket));
        detailData.setDataSource(source);
        cal.setTime(ticket.getAlertTimestamp());
        detailData.setDateCreated(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));
        detailData.setDescription(ticket.getDescription());
        detailData.setItemId(ticket.getTicketUniqueId());
        detailData.setPatient(ticket.getPatientName());

        //Object specific name/value pairs
        addNameValue(detailData.getItemValues(), ITEM_PRIORITY, ticket.getPriority());
        addNameValue(detailData.getItemValues(), ITEM_PATIENT_UNIT_NUMBER, ticket.getPatientUnitNumber());
        addNameValue(detailData.getItemValues(), ITEM_PATIENT_SEX, ticket.getPatientSex());
        //          addNameValue(detailData.getItemValues(), ITEM_PATIENT_FMPSSN, ticket.getPatientFMPSSN());

        //Go through action history and add to name/value
        //  Also, check if ticket is new for this user
        //  Also, hold onto last action performed by user or system user
        //  Also, hold onto last action
        int i = 1;
        boolean isNewAlert = true;
        AlertAction lastAction = null;
        AlertAction lastUserAction = null;
        for (AlertAction action : ticket.getActionHistory()) {
            addNameValue(detailData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_NAME,
                    action.getActionName());
            cal.setTime(action.getActionTimestamp());
            addNameValue(detailData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_TIME,
                    DatatypeFactory.newInstance().newXMLGregorianCalendar(cal).toString());
            addNameValue(detailData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_USER_ID,
                    action.getUserId());
            addNameValue(detailData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_USER_NAME,
                    action.getUserName());
            addNameValue(detailData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_USER_PROVIDER,
                    action.getUserProvider().toString());
            addNameValue(detailData.getItemValues(), ITEM_UPDATE_REC_PREFIX + i + ITEM_UPDATE_REC_MESSAGE,
                    action.getMessage());
            i++;

            //Check if ticket is new for this user
            if (SYSTEM_USER_ID.equals(action.getUserId())
                    || ((request.getUserId() != null) && request.getUserId().equals(action.getUserId()))) {

                if (ActionConstants.ACTION_READ.equals(action.getActionName())) {
                    isNewAlert = false;
                }

                lastUserAction = action;
            }

            //Set last action
            lastAction = action;
        }

        //Set appropriate status value
        String status = "";
        if (isNewAlert) {
            //The ticket may be new to this user, but if it is closed and no further
            //  action can be done, then set the status to the last action
            if (AlertUtil.isTickedClosed(ticket)) {
                status = lastAction.getActionName();
            } else {
                status = ALERT_STATUS_NEW;
            }
        } else if (lastUserAction != null) {
            status = lastUserAction.getActionName();
        } else if (lastAction != null) {
            status = lastAction.getActionName();
        }
        addNameValue(detailData.getItemValues(), ITEM_STATUS, status);

        response.setDetailObject(detailData);
    } catch (Exception e) {
        log.error("Error retriving detail for alert ticket: " + request.getItemId(), e);

        ServiceError serviceError = new ServiceError();
        serviceError.setCode(ERR_CODE);
        serviceError.setText(e.getMessage());
        response.getErrorList().add(serviceError);
    }

    return response;
}

From source file:it.cg.main.process.mapping.easyway.MapperProductAssetToPASS.java

/**
 * Return a TypeData for PASS from a passed Date
 * @param Date data/*from  w w  w.  j ava  2s .  c  o m*/
 * @return TypeData from input
 */
public TypeData dataToTypeData(Date data) {

    TypeData dataOpenTypeData = new TypeData();
    GregorianCalendar c = new GregorianCalendar();
    XMLGregorianCalendar dataOpen = null;
    try {
        c.setTime(data);
        dataOpen = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
    } catch (NullPointerException ex) {
        logger.error("Date passed is null : " + data + " ");
    } catch (DatatypeConfigurationException ex) {
        logger.error("Error conversion for data : " + data + " ");
    }
    dataOpenTypeData.setData(dataOpen);

    return dataOpenTypeData;

}