Example usage for java.util Date toString

List of usage examples for java.util Date toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Converts this Date object to a String of the form:
 dow mon dd hh:mm:ss zzz yyyy
where:
  • dow is the day of the week ( Sun, Mon, Tue, Wed, Thu, Fri, Sat ).

    Usage

    From source file:org.chromium.latency.walt.MainActivity.java

    public String saveLogToFile() {
    
        // Save to file to later fire an Intent.ACTION_SEND
        // This allows to either send the file as email attachment
        // or upload it to Drive.
    
        // The permissions for attachments are a mess, writing world readable files
        // is frowned upon, but deliberately giving permissions as part of the intent is
        // way too cumbersome.
    
        String fname = "qstep_log.txt";
        // A reasonable world readable location,on many phones it's /storage/emulated/Documents
        // TODO: make this location configurable?
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
        File file = null;/*from  w  ww .ja  v  a2 s  . c  o m*/
        FileOutputStream outStream = null;
    
        Date now = new Date();
        logger.log("Saving log to:\n" + path.getPath() + "/" + fname);
        logger.log("On: " + now.toString());
    
        try {
            if (!path.exists()) {
                path.mkdirs();
            }
            file = new File(path, fname);
            outStream = new FileOutputStream(file);
            outStream.write(logger.getLogText().getBytes());
    
            outStream.close();
            logger.log("Log saved");
        } catch (Exception e) {
            e.printStackTrace();
            logger.log("Exception:\n" + e.getMessage());
        }
        return file.getPath();
    }
    

    From source file:org.jasig.portlet.ClassifiedsPortlet.service.AdGroomer.java

    @Override
    public void run() {
        Date now;
        Calendar nowCal = new GregorianCalendar();
        long lastCheckTime = System.currentTimeMillis();
        boolean firstCheck = true;
    
        while (bRun) {
            now = new Date();
            nowCal.setTime(now);/*from www . j  ava2  s  . c o  m*/
    
            if (nowCal.get(Calendar.HOUR_OF_DAY) == hourToCheck
                    && nowCal.get(Calendar.MINUTE) <= (minuteToCheck + 1)
                    && (firstCheck || System.currentTimeMillis() > (lastCheckTime + maxCheckIntervalMillis))) {
    
                log.info("Ad groomer to delete expired ads at " + now.toString());
                adService.deleteExpiredAds();
                lastCheckTime = System.currentTimeMillis();
                firstCheck = false;
            }
            try {
                log.debug("Ad groomer Waiting to see if we should check the time...");
                sleep(checkInterval * 1000);
            } catch (InterruptedException e) {
                break;
            }
        }
    }
    

    From source file:com.virtusa.akura.student.controller.RejoinSuspendedStudentController.java

    /**
     * Re join a student member./*  ww w  .j a  va2s .  c o m*/
     * 
     * @param request - an object of HttpServletRequest
     * @param session - a session to store selected studentId.
     * @param model - a HashMap that contains information of the Staff member
     * @param suspendStudent - an instance of SuspendStudent
     * @param result - containing list of errors and student instance to which data was bound
     * @return - name of the view which is redirected to
     * @throws AkuraAppException - The exception details that occurred when saving or updating a
     *         suspendStudent instance.
     * @throws IOException - throws when fails to update the suspended student.
     * @throws ParseException - when fails to parse a String to date.
     */
    @RequestMapping(value = ACTIVE_SUSPENDED_STUDENT_HTM, method = RequestMethod.POST)
    public final String rejoinSuspendedStudent(final HttpServletRequest request, final HttpSession session,
            final ModelMap model, @ModelAttribute(SUSPEND_STUDENT) final SuspendStudent suspendStudent,
            BindingResult result) throws AkuraAppException, IOException, ParseException {
    
        String returnResult = VIEW_GET_SUSPENDED_STUDENT_REJOIN;
    
        // String reason = request.getParameter(REASON);
        String reason = suspendStudent.getCurtailedOrExtendedReason();
        String strMessage = null;
        String message = "";
    
        // validate suspededStudent object
        rejoinSuspendedStudentValidator.validate(suspendStudent, result);
    
        String studentId = request.getParameter(SELECTED_STUDENT_ID);
        session.setAttribute(SELECTED_STUDENT_ID, studentId);
        setSuspendedStudentList(model, studentId);
    
        // if inputs are incorrect return error message
        if (result.hasErrors()) {
            strMessage = new ErrorMsgLoader().getErrorMessage(AkuraWebConstant.MANDATORY_FIELD_ERROR_CODE);
            model.addAttribute(MESSAGE, strMessage);
            return returnResult;
        }
    
        Date rejoinedDate = suspendStudent.getActivatedDate();
        String date = rejoinedDate.toString();
    
        if (!date.equals("")) {
    
            int studentIdVal = Integer.parseInt(studentId);
    
            try {
                Date convertedDate = suspendStudent.getActivatedDate();
    
                boolean joinStatus = studentService.rejoinSuspendedStudentMemberService(studentIdVal, convertedDate,
                        reason);
    
                // if process is success display success message
                if (joinStatus) {
                    this.sendConfirmationMail(studentIdVal, model, session, convertedDate, reason);
                    message = new ErrorMsgLoader().getErrorMessage(STUDENT_REJOIN_SUCCESS_MESSSAGE);
                    model.addAttribute(MODEL_ATTRIB_SUCCESS, message);
                    // add activation detail to model object
                    List<SuspendStudent> suspendedStudentDetails = studentService
                            .getSuspendedStudentByStudentId(studentIdVal);
                    model.addAttribute(MODEL_ATT_SUSPENDED_STUDENT_DETAIL_LIST, suspendedStudentDetails);
                    return VIEW_GET_SUSPENDED_STUDENT_REJOIN;
    
                }
    
            } catch (InvalidRejoinDateException e) {
    
                String messageError = new ErrorMsgLoader().getErrorMessage(ERROR_MESSAGE_STUDENT_REJOIN);
                model.addAttribute(MESSAGE, messageError);
    
            } catch (IOException e) {
    
                LOG.error(ERROR_THROWS_WHILE_UPDATING_A_STUDENT_MEMBER + e.toString());
                throw new AkuraAppException(
                        PropertyReader.getPropertyValue(AKURA_ERROR_MSG, STUDENT_REJOIN_UPDATE_SUDENT_ERROR), e);
    
            } catch (SuspendRejoinReasonValidationException e) {
                message = e.getErrorCode();
                model.addAttribute(MESSAGE, message);
    
            }
    
        }
        return returnResult;
    
    }
    

    From source file:com.knowprocess.bpm.bdd.BpmSpec.java

    /**
     * Advances process engine by the specified amount of time.
     * //from www .  j a  v a  2  s  . c om
     * @param field
     *            One of the field constants in java.util.Calendar.
     * @param amount
     *            Amount to change field by.
     * @return The updated specification.
     * @see <a
     *      href="https://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html">java.util.Calendar</a>
     */
    public BpmSpec whenProcessTimePassed(int field, int amount) {
        Calendar cal = flowableRule.getProcessEngine().getProcessEngineConfiguration().getClock()
                .getCurrentCalendar();
        cal.add(field, amount);
        Date time = cal.getTime();
        writeBddPhrase("WHEN: process time advanced to : %1$s", time.toString());
        flowableRule.setCurrentTime(time);
        return this;
    }
    

    From source file:fr.gouv.culture.vitam.eml.EmlExtract.java

    public static String extractInfoMessage(MimeMessage message, Element root, VitamArgument argument,
            ConfigLoader config) {/*from   w  w w.j a  v  a2s.  c  om*/
        File oldDir = argument.currentOutputDir;
        if (argument.currentOutputDir == null) {
            if (config.outputDir != null) {
                argument.currentOutputDir = new File(config.outputDir);
            }
        }
        Element keywords = XmlDom.factory.createElement(EMAIL_FIELDS.keywords.name);
        Element metadata = XmlDom.factory.createElement(EMAIL_FIELDS.metadata.name);
        String skey = "";
        String id = config.addRankId(root);
        Address[] from = null;
        Element sub2 = null;
        try {
            from = message.getFrom();
        } catch (MessagingException e1) {
            String[] partialResult;
            try {
                partialResult = message.getHeader("From");
                if (partialResult != null && partialResult.length > 0) {
                    sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.from.name);
                    Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                    add.setText(partialResult[0]);
                    sub2.add(add);
                }
            } catch (MessagingException e) {
            }
        }
        Address sender = null;
        try {
            sender = message.getSender();
        } catch (MessagingException e1) {
            String[] partialResult;
            try {
                partialResult = message.getHeader("Sender");
                if (partialResult != null && partialResult.length > 0) {
                    if (sub2 == null) {
                        sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.from.name);
                        Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                        add.setText(partialResult[0]);
                        sub2.add(add);
                    }
                }
            } catch (MessagingException e) {
            }
        }
        if (from != null && from.length > 0) {
            String value0 = null;
            Element sub = (sub2 != null ? sub2 : XmlDom.factory.createElement(EMAIL_FIELDS.from.name));
            if (sender != null) {
                value0 = addAddress(sub, EMAIL_FIELDS.fromUnit.name, sender, null);
            }
            for (Address address : from) {
                addAddress(sub, EMAIL_FIELDS.fromUnit.name, address, value0);
            }
            metadata.add(sub);
        } else if (sender != null) {
            Element sub = (sub2 != null ? sub2 : XmlDom.factory.createElement(EMAIL_FIELDS.from.name));
            addAddress(sub, EMAIL_FIELDS.fromUnit.name, sender, null);
            metadata.add(sub);
        } else {
            if (sub2 != null) {
                metadata.add(sub2);
            }
        }
        Address[] replyTo = null;
        try {
            replyTo = message.getReplyTo();
            if (replyTo != null && replyTo.length > 0) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.replyTo.name);
                for (Address address : replyTo) {
                    addAddress(sub, EMAIL_FIELDS.fromUnit.name, address, null);
                }
                metadata.add(sub);
            }
        } catch (MessagingException e1) {
            String[] partialResult;
            try {
                partialResult = message.getHeader("ReplyTo");
                if (partialResult != null && partialResult.length > 0) {
                    sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.replyTo.name);
                    addAddress(sub2, EMAIL_FIELDS.fromUnit.name, partialResult, null);
                    /*Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                    add.setText(partialResult[0]);
                    sub2.add(add);*/
                    metadata.add(sub2);
                }
            } catch (MessagingException e) {
            }
        }
        Address[] toRecipients = null;
        try {
            toRecipients = message.getRecipients(Message.RecipientType.TO);
            if (toRecipients != null && toRecipients.length > 0) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.toRecipients.name);
                for (Address address : toRecipients) {
                    addAddress(sub, EMAIL_FIELDS.toUnit.name, address, null);
                }
                metadata.add(sub);
            }
        } catch (MessagingException e1) {
            String[] partialResult;
            try {
                partialResult = message.getHeader("To");
                if (partialResult != null && partialResult.length > 0) {
                    sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.toRecipients.name);
                    addAddress(sub2, EMAIL_FIELDS.toUnit.name, partialResult, null);
                    /*for (String string : partialResult) {
                       Element add = XmlDom.factory.createElement(EMAIL_FIELDS.toUnit.name);
                       add.setText(string);
                       sub2.add(add);
                    }*/
                    metadata.add(sub2);
                }
            } catch (MessagingException e) {
            }
        }
        Address[] ccRecipients;
        try {
            ccRecipients = message.getRecipients(Message.RecipientType.CC);
            if (ccRecipients != null && ccRecipients.length > 0) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.ccRecipients.name);
                for (Address address : ccRecipients) {
                    addAddress(sub, EMAIL_FIELDS.ccUnit.name, address, null);
                }
                metadata.add(sub);
            }
        } catch (MessagingException e1) {
            String[] partialResult;
            try {
                partialResult = message.getHeader("Cc");
                if (partialResult != null && partialResult.length > 0) {
                    sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.ccRecipients.name);
                    addAddress(sub2, EMAIL_FIELDS.ccUnit.name, partialResult, null);
                    /*for (String string : partialResult) {
                       Element add = XmlDom.factory.createElement(EMAIL_FIELDS.ccUnit.name);
                       add.setText(string);
                       sub2.add(add);
                    }*/
                    metadata.add(sub2);
                }
            } catch (MessagingException e) {
            }
        }
        Address[] bccRecipients;
        try {
            bccRecipients = message.getRecipients(Message.RecipientType.BCC);
            if (bccRecipients != null && bccRecipients.length > 0) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.bccRecipients.name);
                for (Address address : bccRecipients) {
                    addAddress(sub, EMAIL_FIELDS.bccUnit.name, address, null);
                }
                metadata.add(sub);
            }
        } catch (MessagingException e1) {
            String[] partialResult;
            try {
                partialResult = message.getHeader("Cc");
                if (partialResult != null && partialResult.length > 0) {
                    sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.bccRecipients.name);
                    addAddress(sub2, EMAIL_FIELDS.bccUnit.name, partialResult, null);
                    /*for (String string : partialResult) {
                       Element add = XmlDom.factory.createElement(EMAIL_FIELDS.bccUnit.name);
                       add.setText(string);
                       sub2.add(add);
                    }*/
                    metadata.add(sub2);
                }
            } catch (MessagingException e) {
            }
        }
        try {
            String subject = message.getSubject();
            if (subject != null) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.subject.name);
                sub.setText(StringUtils.unescapeHTML(subject, true, false));
                metadata.add(sub);
            }
            Date sentDate = message.getSentDate();
            if (sentDate != null) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.sentDate.name);
                sub.setText(sentDate.toString());
                metadata.add(sub);
            }
            Date receivedDate = message.getReceivedDate();
            if (receivedDate != null) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.receivedDate.name);
                sub.setText(receivedDate.toString());
                metadata.add(sub);
            }
            String[] headers = message.getHeader("Received");
            if (headers != null) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.receptionTrace.name);
                MailDateFormat mailDateFormat = null;
                long maxTime = 0;
                if (receivedDate == null) {
                    mailDateFormat = new MailDateFormat();
                }
                for (String string : headers) {
                    Element sub3 = XmlDom.factory.createElement(EMAIL_FIELDS.trace.name);
                    sub3.setText(StringUtils.unescapeHTML(string, true, false));
                    sub.add(sub3);
                    if (receivedDate == null) {
                        int pos = string.lastIndexOf(';');
                        if (pos > 0) {
                            String recvdate = string.substring(pos + 2).replaceAll("\t\n\r\f", "").trim();
                            try {
                                Date date = mailDateFormat.parse(recvdate);
                                if (date.getTime() > maxTime) {
                                    maxTime = date.getTime();
                                }
                            } catch (ParseException e) {
                            }
                        }
                    }
                }
                if (receivedDate == null) {
                    Element subdate = XmlDom.factory.createElement(EMAIL_FIELDS.receivedDate.name);
                    Date date = new Date(maxTime);
                    subdate.setText(date.toString());
                    metadata.add(subdate);
                }
                metadata.add(sub);
            }
            int internalSize = message.getSize();
            if (internalSize > 0) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.emailSize.name);
                sub.setText(Integer.toString(internalSize));
                metadata.add(sub);
            }
            String encoding = message.getEncoding();
            if (encoding != null) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.encoding.name);
                sub.setText(StringUtils.unescapeHTML(encoding, true, false));
                metadata.add(sub);
            }
            String description = message.getDescription();
            if (description != null) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.description.name);
                sub.setText(StringUtils.unescapeHTML(description, true, false));
                metadata.add(sub);
            }
            String contentType = message.getContentType();
            if (contentType != null) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentType.name);
                sub.setText(StringUtils.unescapeHTML(contentType, true, false));
                metadata.add(sub);
            }
            headers = message.getHeader("Content-Transfer-Encoding");
            if (headers != null) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentTransferEncoding.name);
                StringBuilder builder = new StringBuilder();
                for (String string : headers) {
                    builder.append(StringUtils.unescapeHTML(string, true, false));
                    builder.append(' ');
                }
                sub.setText(builder.toString());
                metadata.add(sub);
            }
            String[] contentLanguage = message.getContentLanguage();
            if (contentLanguage != null) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentLanguage.name);
                StringBuilder builder = new StringBuilder();
                for (String string : contentLanguage) {
                    builder.append(StringUtils.unescapeHTML(string, true, false));
                    builder.append(' ');
                }
                sub.setText(builder.toString());
                metadata.add(sub);
            }
            String contentId = message.getContentID();
            if (contentId != null) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentId.name);
                sub.setText(StringUtils.removeChevron(StringUtils.unescapeHTML(contentId, true, false)));
                metadata.add(sub);
            }
            String disposition = message.getDisposition();
            if (disposition != null) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.disposition.name);
                sub.setText(StringUtils.removeChevron(StringUtils.unescapeHTML(disposition, true, false)));
                metadata.add(sub);
            }
            headers = message.getHeader("Keywords");
            if (headers != null) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.msgKeywords.name);
                StringBuilder builder = new StringBuilder();
                for (String string : headers) {
                    builder.append(StringUtils.unescapeHTML(string, true, false));
                    builder.append(' ');
                }
                sub.setText(builder.toString());
                metadata.add(sub);
            }
            String messageId = message.getMessageID();
            if (messageId != null) {
                messageId = StringUtils.removeChevron(StringUtils.unescapeHTML(messageId, true, false)).trim();
                if (messageId.length() > 1) {
                    Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.messageId.name);
                    sub.setText(messageId);
                    metadata.add(sub);
                }
            }
            headers = message.getHeader("In-Reply-To");
            String inreplyto = null;
            if (headers != null) {
                StringBuilder builder = new StringBuilder();
                for (String string : headers) {
                    builder.append(StringUtils.removeChevron(StringUtils.unescapeHTML(string, true, false)));
                    builder.append(' ');
                }
                inreplyto = builder.toString().trim();
                if (inreplyto.length() > 0) {
                    Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.inReplyTo.name);
                    sub.setText(inreplyto);
                    if (messageId != null && messageId.length() > 1) {
                        String old = filEmls.get(inreplyto);
                        if (old == null) {
                            old = messageId;
                        } else {
                            old += "," + messageId;
                        }
                        filEmls.put(inreplyto, old);
                    }
                    metadata.add(sub);
                }
            }
            headers = message.getHeader("References");
            if (headers != null) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.references.name);
                StringBuilder builder = new StringBuilder();
                for (String string : headers) {
                    builder.append(StringUtils.removeChevron(StringUtils.unescapeHTML(string, true, false)));
                    builder.append(' ');
                }
                String[] refs = builder.toString().trim().split(" ");
                for (String string : refs) {
                    if (string.length() > 0) {
                        Element ref = XmlDom.factory.createElement(EMAIL_FIELDS.reference.name);
                        ref.setText(string);
                        sub.add(ref);
                    }
                }
                metadata.add(sub);
            }
            Element prop = XmlDom.factory.createElement(EMAIL_FIELDS.properties.name);
            headers = message.getHeader("X-Priority");
            if (headers == null) {
                headers = message.getHeader("Priority");
                if (headers != null && headers.length > 0) {
                    prop.addAttribute(EMAIL_FIELDS.priority.name, headers[0]);
                }
            } else if (headers != null && headers.length > 0) {
                String imp = headers[0];
                try {
                    int Priority = Integer.parseInt(imp);
                    switch (Priority) {
                    case 5:
                        imp = "LOWEST";
                        break;
                    case 4:
                        imp = "LOW";
                        break;
                    case 3:
                        imp = "NORMAL";
                        break;
                    case 2:
                        imp = "HIGH";
                        break;
                    case 1:
                        imp = "HIGHEST";
                        break;
                    default:
                        imp = "LEV" + Priority;
                    }
                } catch (NumberFormatException e) {
                    // ignore since imp will be used as returned
                }
                prop.addAttribute(EMAIL_FIELDS.priority.name, imp);
            }
            headers = message.getHeader("Sensitivity");
            if (headers != null && headers.length > 0) {
                prop.addAttribute(EMAIL_FIELDS.sensitivity.name, headers[0]);
            }
            headers = message.getHeader("X-RDF");
            if (headers != null && headers.length > 0) {
                System.err.println("Found X-RDF");
                StringBuilder builder = new StringBuilder();
                for (String string : headers) {
                    builder.append(string);
                    builder.append("\n");
                }
                try {
                    byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(builder.toString());
                    String rdf = new String(decoded);
                    Document tempDocument = DocumentHelper.parseText(rdf);
                    Element xrdf = prop.addElement("x-rdf");
                    xrdf.add(tempDocument.getRootElement());
                } catch (Exception e) {
                    System.err.println("Cannot decode X-RDF: " + e.getMessage());
                }
            }
            try {
                File old = argument.currentOutputDir;
                if (config.extractFile) {
                    File newOutDir = new File(argument.currentOutputDir, id);
                    newOutDir.mkdirs();
                    argument.currentOutputDir = newOutDir;
                }
                if (argument.extractKeyword) {
                    skey = handleMessage(message, metadata, prop, id, argument, config);
                    // should have hasAttachment
                    if (prop.hasContent()) {
                        metadata.add(prop);
                    }
                    if (metadata.hasContent()) {
                        root.add(metadata);
                    }
                    ExtractInfo.exportMetadata(keywords, skey, "", config, null);
                    if (keywords.hasContent()) {
                        root.add(keywords);
                    }
                } else {
                    handleMessage(message, metadata, prop, id, argument, config);
                    // should have hasAttachment
                    if (prop.hasContent()) {
                        metadata.add(prop);
                    }
                    if (metadata.hasContent()) {
                        root.add(metadata);
                    }
                }
                argument.currentOutputDir = old;
            } catch (IOException e) {
                System.err.println(StaticValues.LBL.error_error.get() + e.toString());
            }
            try {
                message.getInputStream().close();
            } catch (IOException e) {
                System.err.println(StaticValues.LBL.error_error.get() + e.toString());
            }
            root.addAttribute(EMAIL_FIELDS.status.name, "ok");
        } catch (MessagingException e) {
            System.err.println(StaticValues.LBL.error_error.get() + e.toString());
            e.printStackTrace();
            String status = "Error during identification";
            root.addAttribute(EMAIL_FIELDS.status.name, status);
        } catch (Exception e) {
            System.err.println(StaticValues.LBL.error_error.get() + e.toString());
            e.printStackTrace();
            String status = "Error during identification";
            root.addAttribute(EMAIL_FIELDS.status.name, status);
        }
        argument.currentOutputDir = oldDir;
        return skey;
    }
    

    From source file:com.jaymullen.TrailJournal.EntryActivity.java

    private long getTimestamp(String dateString) {
    
        try {//from w  ww .  j a va2 s  . co  m
            DateFormat formatter;
            Date date;
            formatter = new SimpleDateFormat("MM/dd/yyyy");
            date = (Date) formatter.parse(dateString);
            Log.d("Time", "converted " + dateString + " to " + date.toString() + " in ms: " + date.getTime());
            return date.getTime();
        } catch (ParseException e) {
            return 0;
        }
    }
    

    From source file:it.eng.spagobi.tools.downloadFiles.service.DownloadZipAction.java

    public void service(SourceBean request, SourceBean response) throws Exception {
        logger.debug("IN");
        freezeHttpResponse();//from w ww  . ja  v a  2s  .c o  m
    
        HttpServletRequest httpRequest = getHttpRequest();
        HttpServletResponse httpResponse = getHttpResponse();
    
        // get Attribute DATE, MINUTE, DIRECTORY
        String directory = (String) request.getAttribute(DIRECTORY);
    
        String beginDate = (String) request.getAttribute(BEGIN_DATE);
        String beginTime = (String) request.getAttribute(BEGIN_TIME);
        String endDate = (String) request.getAttribute(END_DATE);
        String endTime = (String) request.getAttribute(END_TIME);
        String prefix1 = (request.getAttribute(PREFIX1) != null) ? (String) request.getAttribute(PREFIX1) + "_"
                : "";
        String prefix2 = (request.getAttribute(PREFIX2) != null) ? (String) request.getAttribute(PREFIX2) + "_"
                : "";
        //String prefix1 = (request.getAttribute(PREFIX1) != null)?(String) request.getAttribute(PREFIX1): "";
        //String prefix2 = (request.getAttribute(PREFIX2) != null)?(String) request.getAttribute(PREFIX2): "";
    
        // build begin Date         
    
        if (directory == null) {
            logger.error("search directory not specified");
            throw new SpagoBIServiceException(SERVICE_NAME, "Missing directory parameter");
        }
    
        if (beginDate == null || beginTime == null) {
            throw new SpagoBIServiceException(SERVICE_NAME, "Missing begin date parameter");
        }
    
        if (endDate == null || endTime == null) {
            throw new SpagoBIServiceException(SERVICE_NAME, "Missing end date parameter");
        }
    
        try {
    
            // remove / from days name
            beginDate = beginDate.replaceAll("/", "");
            endDate = endDate.replaceAll("/", "");
            beginTime = beginTime.replaceAll(":", "");
            endTime = endTime.replaceAll(":", "");
    
            String beginWhole = beginDate + " " + beginTime;
            String endWhole = endDate + " " + endTime;
    
            java.text.DateFormat myTimeFormat = new java.text.SimpleDateFormat(PARAMETERS_FORMAT);
    
            Date begin = myTimeFormat.parse(beginWhole);
            Date end = myTimeFormat.parse(endWhole);
    
            logger.debug("earch file from begin date " + begin.toString() + " to end date " + end.toString());
    
            directory = directory.replaceAll("\\\\", "/");
    
            File dir = new File(directory);
            if (!dir.isDirectory()) {
                logger.error("Not a valid directory specified");
                return;
            }
    
            // get all files that has to be zipped
            Vector filesToZip = searchDateFiles(dir, begin, end, prefix1 + prefix2);
            if (filesToZip.size() == 0) {
                /*throw new Exception ("Warning: Files not found with these parameters: <p><br>" +
                        " <b>Directory:</b> " + dir + "<p>" +
                        " <b>Begin date:</b> " + begin + "<p>" + 
                        " <b>End date:</b> " + end + "<p>" + 
                        " <b>Prefix:</b> " + prefix1 + prefix2 ); */
                throw new Exception("Warning: Missing files in specified interval!");
            }
    
            Date today = (new Date());
            DateFormat formatter = new SimpleDateFormat("dd-MMM-yy hh:mm:ss");
            //date = (Date)formatter.parse("11-June-07");    
            String randomName = formatter.format(today);
            randomName = randomName.replaceAll(" ", "_");
            randomName = randomName.replaceAll(":", "-");
    
            String directoryZip = System.getProperty("java.io.tmpdir");
            if (!directoryZip.endsWith(System.getProperty("file.separator"))) {
                directoryZip += System.getProperty("file.separator");
            }
            String fileZip = randomName + ".zip";
            String pathZip = directoryZip + fileZip;
            pathZip = pathZip.replaceAll("\\\\", "/");
            directoryZip = directoryZip.replaceAll("\\\\", "/");
    
            //         String directoryZip="C:/logs";
            //         String fileZip="prova.zip";
            //         String pathZip=directoryZip+"/"+fileZip;
    
            createZipFromFiles(filesToZip, pathZip, directory);
    
            //Vector<File> filesToZip = searchDateFiles(dir, beginDate, endDate)
    
            manageDownloadZipFile(httpRequest, httpResponse, directoryZip, fileZip);
    
            //manageDownloadExportFile(httpRequest, httpResponse);
        } catch (Throwable t) {
            logger.error("Error in writing the zip ", t);
            throw new SpagoBIServiceException(SERVICE_NAME, t.getMessage(), t);
            /* this manage defines a file with the error message and returns it.
            try{                     
               File file = new File("exception.txt");
               String text = t.getMessage() + " \n" + (( t.getStackTrace()!=null)?t.getStackTrace():"");
               FileUtils.writeStringToFile(file, text, "UTF-8");
               writeBackToClient(file, null, false, "exception.txt", "text/plain");                        
            }catch(Throwable t2){
               logger.error("Error in defining error file ",t2);
               throw new SpagoBIServiceException(SERVICE_NAME, "Server Error in writing the zip", t2);
            }
             */
        } finally {
            logger.debug("OUT");
        }
    }
    

    From source file:org.openmrs.module.drugorderexport.web.controller.StartTreatmentController.java

    /**
     * @see org.springframework.web.servlet.mvc.AbstractFormController#handleRequestInternal(javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse)
     *//*from w  w  w  .  ja  v a 2s.  c om*/
    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // TODO Auto-generated method stub
        Map<String, Object> map = new HashMap<String, Object>();
        List<Patient> patientsExport = new ArrayList<Patient>();
        List<Object[]> objectsList = new ArrayList<Object[]>();
    
        String checkedValueStr[] = null;
        int checkedValue = 0;
        if (request.getParameterValues("checkValue") != null) {
            checkedValueStr = request.getParameterValues("checkValue");
    
            checkedValue = Integer.parseInt(checkedValueStr[0]);
        }
        if (request.getMethod().equalsIgnoreCase("post")) {
    
            List<Integer> patientIds = new ArrayList<Integer>();
    
            Date startDate = null;
            Date endDate = null;
    
            DrugOrderService service = Context.getService(DrugOrderService.class);
    
            String startD = request.getParameter("startdate");
            String endD = request.getParameter("enddate");
    
            String gender = request.getParameter("gender"), minAge = request.getParameter("minAge"),
                    maxAge = request.getParameter("maxAge"), minBirthdate = request.getParameter("minBirthdate"),
                    maxBirthdate = request.getParameter("maxBirthdate");
    
            SimpleDateFormat df = OpenmrsUtil.getDateFormat();
    
            Date mnBirthdate = null;
            Date mxBirthdate = null;
            Date mnAge = null;
            Date mxAge = null;
    
            if (startD != null && startD.length() != 0) {
                startDate = df.parse(startD);
            }
            if (endD != null && endD.length() != 0) {
                endDate = df.parse(endD);
            }
            if (minBirthdate != null && minBirthdate.length() != 0) {
                mnBirthdate = df.parse(minBirthdate);
            }
            if (maxBirthdate != null && maxBirthdate.length() != 0) {
                mxBirthdate = df.parse(maxBirthdate);
            }
    
            if (maxAge != null && maxAge.length() != 0) {
                mxAge = service.getDateObjectFormAge(Integer.parseInt(maxAge));
            }
            if (minAge != null && minAge.length() != 0) {
                mnAge = service.getDateObjectFormAge(Integer.parseInt(minAge));
    
            }
            String arvDrugConceptIds = DrugOrderExportUtil.gpGetARVConceptIds();
    
            patientIds = service.getPatientWhoStartedOnDate(startDate, endDate, gender, mnAge, mxAge, mnBirthdate,
                    mxBirthdate);
    
            List<Integer> list = new ArrayList<Integer>();
    
            if (checkedValue == 1) {
                if (endDate == null)
                    endDate = new Date();
                patientIds = service.getActiveOnDrugsPatients(patientIds, arvDrugConceptIds, endDate);
            }
    
            for (Integer patientId : patientIds) {
                Patient patient = new Patient();
    
                patient = Context.getPatientService().getPatient(patientId);
                if (!patient.getVoided())
                    patientsExport.add(patient);
    
                Date startTreatmentDate = null;
                Date lastEncounterDate = null;
                Date lastVisitDate = null;
                String startTreatmentDateStr = "";
                String lastEncounterDateStr = "";
                String lastVisitDateStr = "";
    
                if (service.getPatientLastVisitDate(patientId) != null) {
                    lastVisitDate = service.getPatientLastVisitDate(patientId);
                    lastVisitDateStr = lastVisitDate.toString();
                }
                if (service.getWhenPatStartedXRegimen(patientId, DrugOrderExportUtil.gpGetARVDrugsIds()) != null) {
                    startTreatmentDate = service.getWhenPatientStarted(patient);
                    startTreatmentDateStr = startTreatmentDate.toString();
                }
                if (service.getPatientLastEncounterDate(patientId) != null) {
                    lastEncounterDate = service.getPatientLastEncounterDate(patientId);
                    lastEncounterDateStr = lastEncounterDate.toString();
                }
    
                objectsList.add(new Object[] { Context.getPersonService().getPerson(patientId),
                        startTreatmentDateStr, lastEncounterDateStr, lastVisitDateStr });
            }
    
            // for data exportation
            if (request.getParameter("export") != null && !request.getParameter("export").equals("")) {
    
                if (Context.getAuthenticatedUser().hasPrivilege("Export Collective Patient Data")) {
                    if (request.getParameter("export").equals("excel"))
                        DrugOrderExportUtil.exportData(request, response, patientsExport);
                    if (request.getParameter("export").equals("pdf"))
                        DrugOrderExportUtil.exportToPDF(request, response, patientsExport);
                } else
                    map.put("msg", "Required Privilege : [Export Collective Patient Data]");
    
            }
    
            map.put("objectsList", objectsList);
            map.put("collectionSize", patientsExport.size());
            map.put("checkedValueExport", checkedValue);
    
            Date now = new Date();
    
            if (startDate != null)
                map.put("startdate", df.format(startDate));
    
            if (endDate != null)
                map.put("enddate", df.format(endDate));
    
            if (gender.equals("f"))
                map.put("gender", "Female");
            else if (gender.equals(""))
                map.put("gender", "Any");
            else
                map.put("gender", "Male");
            if (mnAge != null)
                map.put("minAge", now.getYear() - mnAge.getYear());
            if (mxAge != null)
                map.put("maxAge", now.getYear() - mxAge.getYear());
            if (mnBirthdate != null)
                map.put("minBirthdate", df.format(mnBirthdate));
            if (mxBirthdate != null)
                map.put("maxBirthdate", df.format(mxBirthdate));
    
        }
        return new ModelAndView(getViewName(), map);
    }
    

    From source file:org.apache.zeppelin.submarine.job.SubmarineJob.java

    public void updateJobStateByYarn(String appName) {
        Map<String, Object> mapAppStatus = getJobStateByYarn(appName);
    
        if (mapAppStatus.size() == 0) {
            SubmarineUtils.removeAgulObjValue(intpContext, YARN_APPLICATION_ID);
            SubmarineUtils.removeAgulObjValue(intpContext, YARN_APPLICATION_STATUS);
            SubmarineUtils.removeAgulObjValue(intpContext, YARN_APPLICATION_URL);
            SubmarineUtils.removeAgulObjValue(intpContext, YARN_APP_STARTED_TIME);
            SubmarineUtils.removeAgulObjValue(intpContext, YARN_APP_LAUNCH_TIME);
            SubmarineUtils.removeAgulObjValue(intpContext, YARN_APP_FINISHED_TIME);
            SubmarineUtils.removeAgulObjValue(intpContext, YARN_APP_ELAPSED_TIME);
    
            // TODO(Xun Liu) Not wait job run ???
            SubmarineUtils.removeAgulObjValue(intpContext, JOB_STATUS);
        } else {// w  w w  .java 2  s  . c  o  m
            String state = "", finalStatus = "", appId = "";
            if (mapAppStatus.containsKey(YARN_APPLICATION_ID)) {
                appId = mapAppStatus.get(YARN_APPLICATION_ID).toString();
            }
            if (mapAppStatus.containsKey(YARN_APP_STATE_NAME)) {
                state = mapAppStatus.get(YARN_APP_STATE_NAME).toString();
                SubmarineUtils.setAgulObjValue(intpContext, YARN_APPLICATION_STATUS, state);
            }
            if (mapAppStatus.containsKey(YARN_APP_FINAL_STATUS_NAME)) {
                finalStatus = mapAppStatus.get(YARN_APP_FINAL_STATUS_NAME).toString();
                SubmarineUtils.setAgulObjValue(intpContext, YARN_APPLICATION_FINAL_STATUS, finalStatus);
            }
            SubmarineJobStatus jobStatus = convertYarnState(state, finalStatus);
            setCurrentJobState(jobStatus);
            try {
                if (mapAppStatus.containsKey(YARN_APP_STARTEDTIME_NAME)) {
                    String startedTime = mapAppStatus.get(YARN_APP_STARTEDTIME_NAME).toString();
                    long lStartedTime = Long.parseLong(startedTime);
                    if (lStartedTime > 0) {
                        Date startedDate = new Date(lStartedTime);
                        SubmarineUtils.setAgulObjValue(intpContext, YARN_APP_STARTED_TIME, startedDate.toString());
                    }
                }
                if (mapAppStatus.containsKey(YARN_APP_LAUNCHTIME_NAME)) {
                    String launchTime = mapAppStatus.get(YARN_APP_LAUNCHTIME_NAME).toString();
                    long lLaunchTime = Long.parseLong(launchTime);
                    if (lLaunchTime > 0) {
                        Date launchDate = new Date(lLaunchTime);
                        SubmarineUtils.setAgulObjValue(intpContext, YARN_APP_LAUNCH_TIME, launchDate.toString());
                    }
                }
                if (mapAppStatus.containsKey("finishedTime")) {
                    String finishedTime = mapAppStatus.get("finishedTime").toString();
                    long lFinishedTime = Long.parseLong(finishedTime);
                    if (lFinishedTime > 0) {
                        Date finishedDate = new Date(lFinishedTime);
                        SubmarineUtils.setAgulObjValue(intpContext, YARN_APP_FINISHED_TIME,
                                finishedDate.toString());
                    }
                }
                if (mapAppStatus.containsKey("elapsedTime")) {
                    String elapsedTime = mapAppStatus.get("elapsedTime").toString();
                    long lElapsedTime = Long.parseLong(elapsedTime);
                    if (lElapsedTime > 0) {
                        String finishedDate = org.apache.hadoop.util.StringUtils.formatTime(lElapsedTime);
                        SubmarineUtils.setAgulObjValue(intpContext, YARN_APP_ELAPSED_TIME, finishedDate);
                    }
                }
            } catch (NumberFormatException e) {
                LOGGER.error(e.getMessage());
            }
    
            // create YARN UI link
            StringBuffer sbUrl = new StringBuffer();
            String yarnBaseUrl = properties.getProperty(YARN_WEB_HTTP_ADDRESS, "");
            sbUrl.append(yarnBaseUrl).append("/ui2/#/yarn-app/").append(appId);
            sbUrl.append("/components?service=").append(appName);
    
            SubmarineUtils.setAgulObjValue(intpContext, YARN_APPLICATION_ID, appId);
    
            SubmarineUtils.setAgulObjValue(intpContext, YARN_APPLICATION_URL, sbUrl.toString());
        }
    }
    

    From source file:com.all.client.model.LocalFolder.java

    public final String createHashcode(String name, Date creationDate) {
        String createdHashcode = name + creationDate.toString() + new Random().nextLong();
        try {/*  www .  ja  va 2  s. c  o  m*/
            MessageDigest md = MessageDigest.getInstance("SHA1");
            md.update(createdHashcode.getBytes());
            createdHashcode = Hashcoder.toHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            log.error(e, e);
        }
        return createdHashcode;
    
    }