Example usage for java.text SimpleDateFormat applyPattern

List of usage examples for java.text SimpleDateFormat applyPattern

Introduction

In this page you can find the example usage for java.text SimpleDateFormat applyPattern.

Prototype

public void applyPattern(String pattern) 

Source Link

Document

Applies the given pattern string to this date format.

Usage

From source file:org.openmrs.util.OpenmrsUtil.java

/**
 * Get the current user's datetime format Will look similar to "mm-dd-yyyy hh:mm a". Depends on
 * user's locale.//from   w  w  w .j a  va2  s. c o m
 * 
 * @return a simple date format
 * @should return a pattern with four y characters and two h characters in it
 * @should not allow the returned SimpleDateFormat to be modified
 * @since 1.9
 */
public static SimpleDateFormat getDateTimeFormat(Locale locale) {
    SimpleDateFormat dateFormat;
    SimpleDateFormat timeFormat;

    dateFormat = getDateFormat(locale);
    timeFormat = getTimeFormat(locale);

    String pattern = dateFormat.toPattern() + " " + timeFormat.toPattern();
    SimpleDateFormat sdf = new SimpleDateFormat();
    sdf.applyPattern(pattern);
    return sdf;
}

From source file:org.pentaho.di.job.entries.movefiles.JobEntryMoveFiles.java

private String getDestinationFilename(String shortsourcefilename) throws Exception {
    String shortfilename = shortsourcefilename;
    int lenstring = shortsourcefilename.length();
    int lastindexOfDot = shortfilename.lastIndexOf('.');
    if (lastindexOfDot == -1) {
        lastindexOfDot = lenstring;/* ww w.  j ava2s  . co  m*/
    }

    if (isAddDateBeforeExtension()) {
        shortfilename = shortfilename.substring(0, lastindexOfDot);
    }

    SimpleDateFormat daf = new SimpleDateFormat();
    Date now = new Date();

    if (isSpecifyFormat() && !Const.isEmpty(getDateTimeFormat())) {
        daf.applyPattern(getDateTimeFormat());
        String dt = daf.format(now);
        shortfilename += dt;
    } else {
        if (isAddDate()) {
            daf.applyPattern("yyyyMMdd");
            String d = daf.format(now);
            shortfilename += "_" + d;
        }
        if (isAddTime()) {
            daf.applyPattern("HHmmssSSS");
            String t = daf.format(now);
            shortfilename += "_" + t;
        }
    }
    if (isAddDateBeforeExtension()) {
        shortfilename += shortsourcefilename.substring(lastindexOfDot, lenstring);
    }

    return shortfilename;
}

From source file:com.panet.imeta.job.entries.movefiles.JobEntryMoveFiles.java

private String getDestinationFilename(String shortsourcefilename) throws Exception {
    String shortfilename = shortsourcefilename;
    int lenstring = shortsourcefilename.length();
    int lastindexOfDot = shortfilename.lastIndexOf('.');
    if (lastindexOfDot == -1)
        lastindexOfDot = lenstring;/*ww  w.  j  a v  a 2s.  c  o m*/

    if (isAddDateBeforeExtension())
        shortfilename = shortfilename.substring(0, lastindexOfDot);

    SimpleDateFormat daf = new SimpleDateFormat();
    Date now = new Date();

    if (isSpecifyFormat() && !Const.isEmpty(getDateTimeFormat())) {
        daf.applyPattern(getDateTimeFormat());
        String dt = daf.format(now);
        shortfilename += dt;
    } else {
        if (isAddDate()) {
            daf.applyPattern("yyyyMMdd");
            String d = daf.format(now);
            shortfilename += "_" + d;
        }
        if (isAddTime()) {
            daf.applyPattern("HHmmssSSS");
            String t = daf.format(now);
            shortfilename += "_" + t;
        }
    }
    if (isAddDateBeforeExtension())
        shortfilename += shortsourcefilename.substring(lastindexOfDot, lenstring);

    return shortfilename;
}

From source file:translator.logic.AllVendorAnnotationTranslator.java

/**
 * Convert file format from vendor Sandman
 * @param annotation_file annotation file name
 * @param edf_file edf file name//from  ww w.  ja v a2 s.co  m
 * @param mapping_file mapping file name
 * @param output_file output file name
 * @return true if the translation is successful
 */
@SuppressWarnings("unchecked")
public boolean convertSandman(String annotation_file, String edf_file, String mapping_file,
        String output_file) {

    HashMap<String, Object>[] map = readMapFile(mapping_file);
    Document doc = new DocumentImpl();
    Element root = doc.createElement("PSGAnnotation");
    Element software = doc.createElement("SoftwareVersion");
    software.appendChild(doc.createTextNode("Sandman"));
    Element epoch = doc.createElement("EpochLength");
    epoch.appendChild(doc.createTextNode((String) map[0].get("EpochLength")));
    root.appendChild(software);
    root.appendChild(epoch);
    String efile = edf_file;
    Element eventsElmt = doc.createElement("ScoredEvents");
    String[] elmtsStr = new String[3];
    String[] timeStr = readEDF(efile);
    elmtsStr[0] = "Recording Start Time";
    elmtsStr[1] = "0";
    elmtsStr[2] = timeStr[1];
    Element eventElmt = addElements(doc, elmtsStr);
    Element startTimeElmt = doc.createElement("ClockTime");
    startTimeElmt.appendChild(doc.createTextNode(timeStr[0]));
    eventElmt.appendChild(startTimeElmt);
    eventsElmt.appendChild(eventElmt);
    SimpleDateFormat df = new SimpleDateFormat("dd.mm.yyyy hh.mm.ss");
    Date clocktime = new Date();
    try {
        clocktime = df.parse(timeStr[0]);
    } catch (Exception e) {
        e.printStackTrace();
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        log(errors.toString());
    }
    df.applyPattern("dd.mm.yyyy hh:mm:ss a");
    String date = timeStr[0].split(" ")[0];
    //String date = time[0].split(" ")[0];
    //String[] timeStr = time[0].split(" ")[1].split(".");
    //clocktime = df.parse(date + " " + timeStr[0])
    boolean bTranslation = true;
    try {
        @SuppressWarnings("unused")
        File file = new File(annotation_file);
        // "input never closed" fixed by wei wang, 2014-7-11
        BufferedReader input = new BufferedReader(new FileReader(annotation_file));

        // ww add
        try {
            String line = input.readLine();
            while (!line.contains("Epoch")) {
                line = input.readLine();
            }
            while ((line = input.readLine()) != null) {
                String[] data = line.split("\t");
                String eventname = data[1];
                //Element event = doc.createElement("ScoredEvent");
                String[] elmts = new String[3];

                //scored events
                if (map[1].keySet().contains(data[1])) {

                    elmts[0] = ((ArrayList<String>) map[1].get(data[1])).get(1);
                    Date starttime = df.parse(date + " " + data[2]);
                    long time = (starttime.getTime() - clocktime.getTime()) / 1000;
                    if (time < 0) {
                        time += 24 * 60 * 60;
                    }
                    elmts[1] = Long.toString(time);
                    //startElmt.appendChild(doc.createTextNode(Long.toString(time)));
                    if (data.length > 3) {
                        //System.out.println(data[1]);
                        //durationElmt.appendChild(doc.createTextNode(data[3]));
                        elmts[2] = data[3];
                    } else {
                        elmts[2] = Integer.toString(0);
                    }
                    Element event = addElements(doc, elmts);
                    if (((ArrayList<String>) map[1].get(data[1])).size() > 2) {
                        Element notesElmt = doc.createElement("Notes");
                        notesElmt.appendChild(
                                doc.createTextNode(((ArrayList<String>) map[1].get(data[1])).get(2)));
                        event.appendChild(notesElmt);
                    }

                    if (((ArrayList<String>) map[1].get(data[1])).get(1)
                            .compareToIgnoreCase("Desaturation") != 0) {

                    }
                    eventsElmt.appendChild(event);
                } else if (!map[2].keySet().contains(data[1])) {

                    Element notesNode = doc.createElement("Notes");
                    elmts[0] = "Technician Notes";
                    //nameElmt.appendChild(doc.createTextNode("Technician Notes"));
                    Date starttime = df.parse(date + " " + data[2]);
                    long time = (starttime.getTime() - clocktime.getTime()) / 1000;
                    if (time < 0) {
                        time += 24 * 60 * 60;
                    }
                    elmts[1] = Long.toString(time);
                    //startElmt.appendChild(doc.createTextNode(Long.toString(time)));
                    if (data.length > 3) {
                        elmts[2] = data[3];
                        //durationElmt.appendChild(doc.createTextNode(data[3]));
                    } else {
                        elmts[2] = Integer.toString(0);
                    }
                    notesNode.appendChild(doc.createTextNode(eventname));

                    Element event = addElements(doc, elmts);
                    event.appendChild(notesNode);

                    String info = annotation_file + "," + eventname + "," + data[2];// + Double.toString(starttime);
                    this.log(info);
                    eventsElmt.appendChild(event);
                }
            }
            // wei wang, 2014-7-11
        } finally {
            input.close();
        }

        //sleep staging
        input = new BufferedReader(new FileReader(annotation_file));
        // wei wang:
        try {
            String line = input.readLine();
            while (!line.contains("Epoch")) {
                line = input.readLine();
            }
            while ((line = input.readLine()) != null) {
                String[] data = line.split("\t");
                String stage = "";
                if (map[2].keySet().contains(data[1])) {
                    if (data[1].compareToIgnoreCase(stage) != 0 & data.length >= 4) {
                        String[] elmts = new String[3];
                        elmts[0] = (String) map[2].get(data[1]);
                        Date starttime = df.parse(date + " " + data[2]);
                        long time = (starttime.getTime() - clocktime.getTime()) / 1000;
                        if (time < 0) {
                            time += 24 * 60 * 60;
                        }
                        elmts[1] = Long.toString(time);
                        elmts[2] = data[3];
                        Element event = addElements(doc, elmts);
                        eventsElmt.appendChild(event);
                        stage = data[1];
                    }
                }
            }
            // wei wang: fixed "input never closed", 2014-7-11
        } finally {
            input.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        bTranslation = false;
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        log(errors.toString());
    }
    root.appendChild(eventsElmt);
    doc.appendChild(root);
    saveXML(doc, output_file);
    return bTranslation;
}

From source file:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java

public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    IEngUserProfile profile;/*from ww w .  j a  va  2 s .c om*/
    JobDataMap jobDataMap;

    // documentLabel__num this is necessary because the same document can be added to one scheduled activity more than one time
    String documentInstanceName;
    String documentLabel;

    // par1=val1&par2=val2... for parameters already set in scheduled activity's configuration
    String inputParametersQueryString;

    IBIObjectDAO biobjdao;
    BIObject biobj;
    ExecutionController executionController;
    ExecutionProxy executionProxy;
    EventsManager eventManager;

    logger.debug("IN");

    try {
        profile = UserProfile.createSchedulerUserProfile();
        jobDataMap = jobExecutionContext.getMergedJobDataMap();
        biobjdao = DAOFactory.getBIObjectDAO();

        String doclabelsConcat = jobDataMap.getString("documentLabels");
        String[] docLabels = doclabelsConcat.split(",");
        Iterator itr = jobDataMap.keySet().iterator();
        while (itr.hasNext()) {
            Object key = itr.next();
            Object value = jobDataMap.get(key);
            logger.debug("jobDataMap parameter [" + key + "] is equal to [" + value + "]");
        }

        long startSchedule = System.currentTimeMillis();
        logger.debug("Scheduled activity contains [" + docLabels.length + "] documnt(s)");

        for (int ind = 0; ind < docLabels.length; ind++) {
            documentInstanceName = docLabels[ind];
            documentLabel = documentInstanceName.substring(0, documentInstanceName.lastIndexOf("__"));
            logger.debug("Processing document [" + (ind + 1) + "] with label [" + documentLabel + "] ...");

            inputParametersQueryString = jobDataMap.getString(documentInstanceName);
            logger.debug("Input parameters query string for documet [" + documentLabel + "] is equal to ["
                    + inputParametersQueryString + "]");

            // load bidocument
            biobj = biobjdao.loadBIObjectByLabel(documentLabel);

            // get the save options
            String saveOptString = jobDataMap.getString("biobject_id_" + biobj.getId() + "__" + (ind + 1));
            DispatchContext saveInfo = SchedulerUtilities.decodeDispatchContext(saveOptString);

            // create the execution controller 
            executionController = new ExecutionController();
            executionController.setBiObject(biobj);

            // fill parameters 
            executionController.refreshParameters(biobj, inputParametersQueryString);

            String iterativeParametersString = jobDataMap.getString(documentInstanceName + "_iterative");
            logger.debug("Iterative parameter configuration for documet [" + documentLabel + "] is equal to ["
                    + iterativeParametersString + "]");
            setIterativeParameters(biobj, iterativeParametersString);

            String loadAtRuntimeParametersString = jobDataMap
                    .getString(documentInstanceName + "_loadAtRuntime");
            logger.debug("Runtime parameter configuration for documet [" + documentLabel + "] is equal to ["
                    + loadAtRuntimeParametersString + "]");
            setLoadAtRuntimeParameters(biobj, loadAtRuntimeParametersString);

            String useFormulaParametersString = jobDataMap.getString(documentInstanceName + "_useFormula");
            logger.debug("Formuula based parameter configuration for documet [" + documentLabel
                    + "] is equal to [" + useFormulaParametersString + "]");
            setUseFormulaParameters(biobj, useFormulaParametersString);

            retrieveParametersValues(biobj);

            //gets the dataset data about the email address
            IDataStore emailDispatchDataStore = null;
            if (saveInfo.isUseDataSet()) {
                IDataSet dataSet = DAOFactory.getDataSetDAO()
                        .loadActiveDataSetByLabel(saveInfo.getDataSetLabel());
                dataSet.setUserProfileAttributes(UserProfileUtils.getProfileAttributes(profile));
                dataSet.loadData();
                emailDispatchDataStore = dataSet.getDataStore();
            }
            //gets the dataset data about the folder for the document save
            IDataStore folderDispatchDataSotre = null;
            if (saveInfo.isUseFolderDataSet()) {
                IDataSet dataSet = DAOFactory.getDataSetDAO()
                        .loadActiveDataSetByLabel(saveInfo.getDataSetFolderLabel());
                dataSet.setUserProfileAttributes(UserProfileUtils.getProfileAttributes(profile));
                dataSet.loadData();
                folderDispatchDataSotre = dataSet.getDataStore();
            }

            eventManager = EventsManager.getInstance();
            List roles = DAOFactory.getBIObjectDAO().getCorrectRolesForExecution(biobj.getId());

            String startExecMsg = "${scheduler.startexecsched} " + biobj.getName();
            Integer idEvent = eventManager.registerEvent("Scheduler", startExecMsg, "", roles);

            Map tempParMap = new HashMap();
            BIObjectParametersIterator objectParametersIterator = new BIObjectParametersIterator(
                    biobj.getBiObjectParameters());
            while (objectParametersIterator.hasNext()) {
                List parameters = (List) objectParametersIterator.next();
                biobj.setBiObjectParameters(parameters);

                StringBuffer toBeAppendedToName = new StringBuffer();
                StringBuffer toBeAppendedToDescription = new StringBuffer(" [");
                Iterator parametersIt = parameters.iterator();
                while (parametersIt.hasNext()) {

                    BIObjectParameter aParameter = (BIObjectParameter) parametersIt.next();

                    tempParMap.put(aParameter.getParameterUrlName(), aParameter.getParameterValuesAsString());
                    if (aParameter.isIterative()) {
                        toBeAppendedToName.append("_" + aParameter.getParameterValuesAsString());
                        toBeAppendedToDescription.append(
                                aParameter.getLabel() + ":" + aParameter.getParameterValuesAsString() + "; ");
                    }
                }
                // if there are no iterative parameters, toBeAppendedToDescription is " [" and must be cleaned
                if (toBeAppendedToDescription.length() == 2) {
                    toBeAppendedToDescription.delete(0, 2);
                } else {
                    // toBeAppendedToDescription ends with "; " and must be cleaned
                    toBeAppendedToDescription.delete(toBeAppendedToDescription.length() - 2,
                            toBeAppendedToDescription.length());
                    toBeAppendedToDescription.append("]");
                }

                // appending the current date
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat();
                sdf.applyPattern("dd:MM:yyyy");
                String dateStr = sdf.format(date);
                toBeAppendedToName.append("_" + dateStr);

                //check parameters value: if a parameter hasn't value but isn't mandatory the process 
                //must go on and so hasValidValue is set to true
                List tmpBIObjectParameters = biobj.getBiObjectParameters();
                Iterator it = tmpBIObjectParameters.iterator();
                while (it.hasNext()) {
                    boolean isMandatory = false;
                    BIObjectParameter aBIObjectParameter = (BIObjectParameter) it.next();
                    List checks = aBIObjectParameter.getParameter().getChecks();
                    if (checks != null && !checks.isEmpty()) {
                        Iterator checksIt = checks.iterator();
                        while (checksIt.hasNext()) {
                            Check check = (Check) checksIt.next();
                            if (check.getValueTypeCd().equalsIgnoreCase("MANDATORY")) {
                                isMandatory = true;
                                break;
                            }
                        }
                    }
                    if (!isMandatory && (aBIObjectParameter.getParameterValues() == null
                            || aBIObjectParameter.getParameterValues().size() == 0)) {
                        aBIObjectParameter.setParameterValues(new ArrayList());
                        aBIObjectParameter.setHasValidValues(true);
                    }
                }

                // exec the document only if all its parameter are filled
                if (executionController.directExecution()) {

                    logger.debug("Save as snapshot is eual to [" + saveInfo.isSnapshootDispatchChannelEnabled()
                            + "]");
                    logger.debug("Dispatch to a distribution list is eual to ["
                            + saveInfo.isDistributionListDispatchChannelEnabled() + "]");
                    logger.debug("Dispatch to a java class is eual to ["
                            + saveInfo.isJavaClassDispatchChannelEnabled() + "]");
                    logger.debug("Dispatch by mail-list is eual to [" + saveInfo.isMailDispatchChannelEnabled()
                            + "]");
                    logger.debug("Dispatch by folder-list is eual to ["
                            + saveInfo.isFunctionalityTreeDispatchChannelEnabled() + "]");

                    if (!saveInfo.isSnapshootDispatchChannelEnabled()
                            && !saveInfo.isDistributionListDispatchChannelEnabled()
                            && !saveInfo.isJavaClassDispatchChannelEnabled()) {
                        boolean noValidDispatchTarget = false;
                        if (saveInfo.isMailDispatchChannelEnabled()) {
                            String[] recipients = findRecipients(saveInfo, biobj, emailDispatchDataStore);
                            if (recipients != null && recipients.length > 0) {
                                noValidDispatchTarget = false;
                                logger.debug("Found at least one target of type mail");
                            } else {
                                noValidDispatchTarget = true;
                            }
                        }

                        if (saveInfo.isFunctionalityTreeDispatchChannelEnabled()) {
                            List storeInFunctionalities = findFolders(saveInfo, biobj, folderDispatchDataSotre);
                            if (storeInFunctionalities != null && !storeInFunctionalities.isEmpty()) {
                                noValidDispatchTarget = false;
                                logger.debug("Found at least one target of type folder");
                            } else {
                                noValidDispatchTarget = true;
                            }
                        }

                        if (noValidDispatchTarget) {
                            logger.debug("No valid dispatch target for document [" + (ind + 1)
                                    + "] with label [" + documentInstanceName + "] and parameters ["
                                    + toBeAppendedToDescription + "]");
                            logger.info("Document [" + (ind + 1) + "] with label [" + documentInstanceName
                                    + "] and parameters " + toBeAppendedToDescription
                                    + " not executed: no valid dispatch target");
                            continue;
                        } else if (!saveInfo.isFunctionalityTreeDispatchChannelEnabled()
                                && !saveInfo.isMailDispatchChannelEnabled()) {
                            logger.debug("There are no dispatch targets for document with label ["
                                    + documentInstanceName
                                    + "] - if not an ETL, WEKA or KPI document a dispatch target should be added");
                        } else {
                            logger.debug("There is at list one dispatch target for document with label ["
                                    + documentInstanceName + "]");
                        }
                    }

                    executionProxy = new ExecutionProxy();
                    executionProxy.setBiObject(biobj);

                    logger.info("Executing document [" + (ind + 1) + "] with label [" + documentInstanceName
                            + "] and parameters " + toBeAppendedToDescription + " ...");
                    long start = System.currentTimeMillis();
                    byte[] response = executionProxy.exec(profile, "SCHEDULATION", null);
                    if (response == null || response.length == 0) {
                        logger.debug("Document executed without any response");
                    }
                    String retCT = executionProxy.getReturnedContentType();
                    String fileextension = executionProxy.getFileExtensionFromContType(retCT);
                    long end = System.currentTimeMillis();
                    long elapsed = (end - start) / 1000;
                    logger.info("Document [" + (ind + 1) + "] with label [" + documentInstanceName
                            + "] and parameters " + toBeAppendedToDescription + " executed in [" + elapsed
                            + "]");

                    if (saveInfo.isSnapshootDispatchChannelEnabled()) {
                        saveAsSnap(saveInfo, biobj, response, toBeAppendedToName.toString(),
                                toBeAppendedToDescription.toString(), profile);
                    }

                    if (saveInfo.isFunctionalityTreeDispatchChannelEnabled()) {
                        saveAsDocument(saveInfo, biobj, jobExecutionContext, response, fileextension,
                                folderDispatchDataSotre, toBeAppendedToName.toString(),
                                toBeAppendedToDescription.toString());
                    }

                    if (saveInfo.isMailDispatchChannelEnabled()) {
                        sendMail(saveInfo, biobj, tempParMap, response, retCT, fileextension,
                                emailDispatchDataStore, toBeAppendedToName.toString(),
                                toBeAppendedToDescription.toString());
                    }
                    if (saveInfo.isDistributionListDispatchChannelEnabled()) {
                        sendToDl(saveInfo, biobj, response, retCT, fileextension, toBeAppendedToName.toString(),
                                toBeAppendedToDescription.toString());
                        if (jobExecutionContext.getNextFireTime() == null) {
                            String triggername = jobExecutionContext.getTrigger().getName();
                            List dlIds = saveInfo.getDlIds();
                            it = dlIds.iterator();
                            while (it.hasNext()) {
                                Integer dlId = (Integer) it.next();
                                DistributionList dl = DAOFactory.getDistributionListDAO()
                                        .loadDistributionListById(dlId);
                                DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl,
                                        (biobj.getId()).intValue(), triggername);
                            }
                        }
                    }

                    if (saveInfo.isJavaClassDispatchChannelEnabled()) {
                        sendToJavaClass(saveInfo, biobj, response);
                    }

                } else {
                    logger.warn("The document with label " + documentInstanceName
                            + " cannot be executed directly, " + "maybe some prameters are not filled ");
                    throw new Exception("The document with label " + documentInstanceName
                            + " cannot be executed directly, " + "maybe some prameters are not filled ");
                }
            }

            String endExecMsg = "${scheduler.endexecsched} " + biobj.getName();
            eventManager.registerEvent("Scheduler", endExecMsg, "", roles);

        }

        long endSchedule = System.currentTimeMillis();
        long elapsedSchedule = (endSchedule - startSchedule) / 1000;
        logger.info("Scheduled activity succesfully ended in [" + elapsedSchedule + "] sec.");
    } catch (Exception e) {
        logger.error("Error while executiong job ", e);
    } finally {
        logger.debug("OUT");
    }
}

From source file:it.eng.spagobi.analiticalmodel.execution.presentation.tag.ParametersGeneratorTag.java

private void createDataInputButton(BIObjectParameter biparam, StringBuffer htmlStream, List lblBiParamDependent,
        String currTheme) {//from   w  w  w.ja v  a2 s .  c  o m
    logger.debug("IN");

    SessionContainer permSess = requestContainer.getSessionContainer().getPermanentContainer();

    String format = GeneralUtilities.getLocaleDateFormat(permSess);

    Locale currentLocale = GeneralUtilities.getCurrentLocale(this.requestContainer);

    logger.debug("DATE FORMAT:" + format);

    String datePickerFormat = GeneralUtilities.getServerDateFormat();

    Date d = new Date();
    SimpleDateFormat fVisual = new SimpleDateFormat();
    fVisual.applyPattern(format);

    SimpleDateFormat fPar = new SimpleDateFormat();
    fPar.applyPattern(datePickerFormat);

    // if it finds param value in biparam it must convert from datePickerFormat to user one!
    String paramValue = getParameterValuesAsString(biparam);
    try {

        if (paramValue != null && !paramValue.equalsIgnoreCase("")) {
            // convert from datePickerFormat
            Date temp;

            temp = fPar.parse(paramValue);
            d = temp;
        }

    } catch (ParseException e) {

        e.printStackTrace();
    }
    // Dojo DropdownDatePicker requires the value to be formatted with rfc3339 format
    String rfc3339format = "MM/dd/yyyy";
    String dateValue = StringUtils.dateToString(d, rfc3339format);
    htmlStream.append("<script type='text/javascript'>\n");
    htmlStream.append("if (!djConfig) {\n");
    htmlStream.append("   var djConfig = { extraLocale: ['" + currentLocale.getLanguage() + "'] };\n");
    htmlStream.append("}\n");
    htmlStream.append("</script>\n");

    htmlStream.append("<script type='text/javascript' src='"
            + urlBuilder.getResourceLinkByTheme(httpRequest, "/js/dojo/dojo.js", currTheme) + "'></script>"
            + "<script type='text/javascript'>" + " dojo.require('dojo.widget.DropdownDatePicker');"
            + " var isInit" + biparam.getParameterUrlName() + requestIdentity + " = true;" + " </script>\n"
            + " <input style='width:230px;' type='text' \n" + "      name='" + biparam.getParameterUrlName()
            + "' id='" + biparam.getParameterUrlName() + requestIdentity + "'\n"
            + "      dojoType='dropdowndatepicker' lang='" + currentLocale.getLanguage() + "'\n"
            + " saveFormat='" + datePickerFormat + "' displayFormat='" + format + "'\n" + " widgetId='"
            + biparam.getParameterUrlName() + requestIdentity + "DatePicker' \n"
            + "    class='portlet-form-input-field' value='" + dateValue + "' \n"
            // onValueChanged is triggered also when displaying the date picker, and we avoid this using isInit variable
            + "   onValueChanged=\"if (!isInit" + biparam.getParameterUrlName() + requestIdentity
            + ") { refresh" + requestIdentity + "('" + biparam.getParameterUrlName() + requestIdentity + "','"
            + biparam.getParameterUrlName() + requestIdentity + "');");
    if (lblBiParamDependent != null && lblBiParamDependent.size() > 0) {
        if (mustRefreshPageForCorrelation(lblBiParamDependent)) {
            htmlStream.append("setRefreshCorrelationFlag" + requestIdentity + "();");
            htmlStream.append("document.getElementById('parametersForm" + requestIdentity + "').submit();");
        }
    }
    htmlStream.append("} else {isInit" + biparam.getParameterUrlName() + requestIdentity + " = false;}\" />\n");
    logger.debug("OUT");
}

From source file:com.panet.imeta.job.entries.ftp.JobEntryFTP.java

/**
 * @param string the filename from the FTP server
 * /*from  w w w .j ava 2 s .  c  o m*/
 * @return the calculated target filename
 */
private String returnTargetFilename(String filename) {
    String retval = null;
    // Replace possible environment variables...
    if (filename != null)
        retval = filename;
    else
        return null;

    int lenstring = retval.length();
    int lastindexOfDot = retval.lastIndexOf(".");
    if (lastindexOfDot == -1)
        lastindexOfDot = lenstring;

    if (isAddDateBeforeExtension())
        retval = retval.substring(0, lastindexOfDot);

    SimpleDateFormat daf = new SimpleDateFormat();
    Date now = new Date();

    if (SpecifyFormat && !Const.isEmpty(date_time_format)) {
        daf.applyPattern(date_time_format);
        String dt = daf.format(now);
        retval += dt;
    } else {
        if (adddate) {
            daf.applyPattern("yyyyMMdd");
            String d = daf.format(now);
            retval += "_" + d;
        }
        if (addtime) {
            daf.applyPattern("HHmmssSSS");
            String t = daf.format(now);
            retval += "_" + t;
        }
    }

    if (isAddDateBeforeExtension())
        retval += retval.substring(lastindexOfDot, lenstring);

    // Add foldername to filename      
    retval = environmentSubstitute(targetDirectory) + Const.FILE_SEPARATOR + retval;
    return retval;
}

From source file:com.panet.imeta.job.entries.movefiles.JobEntryMoveFiles.java

private boolean MoveFile(String shortfilename, FileObject sourcefilename, FileObject destinationfilename,
        FileObject movetofolderfolder, LogWriter log, Job parentJob, Result result) {

    FileObject destinationfile = null;
    boolean retval = false;
    try {// w  w  w.j  ava 2 s  . c o m
        if (!destinationfilename.exists()) {
            if (!simulate)
                sourcefilename.moveTo(destinationfilename);
            if (log.isDetailed())
                log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.FileMoved",
                        sourcefilename.getName().toString(), destinationfilename.getName().toString()));

            // add filename to result filename
            if (add_result_filesname && !iffileexists.equals("fail") && !iffileexists.equals("do_nothing"))
                addFileToResultFilenames(destinationfilename.toString(), log, result, parentJob);

            updateSuccess();

        } else {
            if (log.isDetailed())
                log.logDetailed(toString(),
                        Messages.getString("JobMoveFiles.Log.FileExists", destinationfilename.toString()));
            if (iffileexists.equals("overwrite_file")) {
                if (!simulate)
                    sourcefilename.moveTo(destinationfilename);
                if (log.isDetailed())
                    log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.FileOverwrite",
                            destinationfilename.getName().toString()));

                // add filename to result filename
                if (add_result_filesname && !iffileexists.equals("fail") && !iffileexists.equals("do_nothing"))
                    addFileToResultFilenames(destinationfilename.toString(), log, result, parentJob);

                updateSuccess();

            } else if (iffileexists.equals("unique_name")) {
                String short_filename = shortfilename;

                // return destination short filename
                try {
                    short_filename = getMoveDestinationFilename(short_filename, "ddMMyyyy_HHmmssSSS");
                } catch (Exception e) {
                    log.logError(toString(), Messages.getString(
                            Messages.getString("JobMoveFiles.Error.GettingFilename", short_filename)));
                    return retval;
                }

                String movetofilenamefull = destinationfilename.getParent().toString() + Const.FILE_SEPARATOR
                        + short_filename;
                destinationfile = KettleVFS.getFileObject(movetofilenamefull);

                if (!simulate)
                    sourcefilename.moveTo(destinationfile);
                if (log.isDetailed())
                    log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.FileMoved",
                            sourcefilename.getName().toString(), destinationfile.getName().toString()));

                // add filename to result filename
                if (add_result_filesname && !iffileexists.equals("fail") && !iffileexists.equals("do_nothing"))
                    addFileToResultFilenames(destinationfile.toString(), log, result, parentJob);

                updateSuccess();
            } else if (iffileexists.equals("delete_file")) {
                if (!simulate)
                    destinationfilename.delete();
                if (log.isDetailed())
                    log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.FileDeleted",
                            destinationfilename.getName().toString()));
            } else if (iffileexists.equals("move_file")) {
                String short_filename = shortfilename;
                // return destination short filename
                try {
                    short_filename = getMoveDestinationFilename(short_filename, null);
                } catch (Exception e) {
                    log.logError(toString(), Messages.getString(
                            Messages.getString("JobMoveFiles.Error.GettingFilename", short_filename)));
                    return retval;
                }

                String movetofilenamefull = movetofolderfolder.toString() + Const.FILE_SEPARATOR
                        + short_filename;
                destinationfile = KettleVFS.getFileObject(movetofilenamefull);
                if (!destinationfile.exists()) {
                    if (!simulate)
                        sourcefilename.moveTo(destinationfile);
                    if (log.isDetailed())
                        log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.FileMoved",
                                sourcefilename.getName().toString(), destinationfile.getName().toString()));

                    // add filename to result filename
                    if (add_result_filesname && !iffileexists.equals("fail")
                            && !iffileexists.equals("do_nothing"))
                        addFileToResultFilenames(destinationfile.toString(), log, result, parentJob);

                } else {
                    if (ifmovedfileexists.equals("overwrite_file")) {
                        if (!simulate)
                            sourcefilename.moveTo(destinationfile);
                        if (log.isDetailed())
                            log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.FileOverwrite",
                                    destinationfile.getName().toString()));

                        // add filename to result filename
                        if (add_result_filesname && !iffileexists.equals("fail")
                                && !iffileexists.equals("do_nothing"))
                            addFileToResultFilenames(destinationfile.toString(), log, result, parentJob);

                        updateSuccess();
                    } else if (ifmovedfileexists.equals("unique_name")) {
                        SimpleDateFormat daf = new SimpleDateFormat();
                        Date now = new Date();
                        daf.applyPattern("ddMMyyyy_HHmmssSSS");
                        String dt = daf.format(now);
                        short_filename += "_" + dt;

                        String destinationfilenamefull = movetofolderfolder.toString() + Const.FILE_SEPARATOR
                                + short_filename;
                        destinationfile = KettleVFS.getFileObject(destinationfilenamefull);

                        if (!simulate)
                            sourcefilename.moveTo(destinationfile);
                        if (log.isDetailed())
                            log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.FileMoved",
                                    destinationfile.getName().toString()));

                        // add filename to result filename
                        if (add_result_filesname && !iffileexists.equals("fail")
                                && !iffileexists.equals("do_nothing"))
                            addFileToResultFilenames(destinationfile.toString(), log, result, parentJob);

                        updateSuccess();
                    } else if (ifmovedfileexists.equals("fail")) {
                        // Update Errors
                        updateErrors();
                    }
                }

            } else if (iffileexists.equals("fail")) {
                // Update Errors
                updateErrors();
            }

        }
    } catch (Exception e) {
        log.logError(toString(), Messages.getString("JobMoveFiles.Error.Exception.MoveProcessError",
                sourcefilename.toString(), destinationfilename.toString(), e.getMessage()));
    } finally {
        if (destinationfile != null) {
            try {
                destinationfile.close();
            } catch (IOException ex) {
            }
            ;
        }
    }
    return retval;
}

From source file:org.pentaho.di.job.entries.pgpdecryptfiles.JobEntryPGPDecryptFiles.java

private boolean DecryptFile(String shortfilename, FileObject sourcefilename, String passPharse,
        FileObject destinationfilename, FileObject movetofolderfolder, Job parentJob, Result result) {

    FileObject destinationfile = null;
    boolean retval = false;
    try {//ww  w  . j a  va  2s  .  c o m
        if (!destinationfilename.exists()) {
            gpg.decryptFile(sourcefilename, passPharse, destinationfilename);

            if (isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileDecrypted",
                        sourcefilename.getName().toString(), destinationfilename.getName().toString()));
            }

            // add filename to result filename
            if (add_result_filesname && !iffileexists.equals("fail") && !iffileexists.equals("do_nothing")) {
                addFileToResultFilenames(destinationfilename.toString(), result, parentJob);
            }

            updateSuccess();

        } else {
            if (isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileExists",
                        destinationfilename.toString()));
            }
            if (iffileexists.equals("overwrite_file")) {
                gpg.decryptFile(sourcefilename, passPharse, destinationfilename);

                if (isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileOverwrite",
                            destinationfilename.getName().toString()));
                }

                // add filename to result filename
                if (add_result_filesname && !iffileexists.equals("fail")
                        && !iffileexists.equals("do_nothing")) {
                    addFileToResultFilenames(destinationfilename.toString(), result, parentJob);
                }

                updateSuccess();

            } else if (iffileexists.equals("unique_name")) {
                String short_filename = shortfilename;

                // return destination short filename
                try {
                    short_filename = getMoveDestinationFilename(short_filename, "ddMMyyyy_HHmmssSSS");
                } catch (Exception e) {
                    logError(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Error.GettingFilename",
                            short_filename), e);
                    return retval;
                }

                String movetofilenamefull = destinationfilename.getParent().toString() + Const.FILE_SEPARATOR
                        + short_filename;
                destinationfile = KettleVFS.getFileObject(movetofilenamefull);

                gpg.decryptFile(sourcefilename, passPharse, destinationfile);

                if (isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileDecrypted",
                            sourcefilename.getName().toString(), destinationfile.getName().toString()));
                }

                // add filename to result filename
                if (add_result_filesname && !iffileexists.equals("fail")
                        && !iffileexists.equals("do_nothing")) {
                    addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                }

                updateSuccess();
            } else if (iffileexists.equals("delete_file")) {
                destinationfilename.delete();
                if (isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileDeleted",
                            destinationfilename.getName().toString()));
                }
            } else if (iffileexists.equals("move_file")) {
                String short_filename = shortfilename;
                // return destination short filename
                try {
                    short_filename = getMoveDestinationFilename(short_filename, null);
                } catch (Exception e) {
                    logError(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Error.GettingFilename",
                            short_filename), e);
                    return retval;
                }

                String movetofilenamefull = movetofolderfolder.toString() + Const.FILE_SEPARATOR
                        + short_filename;
                destinationfile = KettleVFS.getFileObject(movetofilenamefull);
                if (!destinationfile.exists()) {
                    sourcefilename.moveTo(destinationfile);
                    if (isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileDecrypted",
                                sourcefilename.getName().toString(), destinationfile.getName().toString()));
                    }

                    // add filename to result filename
                    if (add_result_filesname && !iffileexists.equals("fail")
                            && !iffileexists.equals("do_nothing")) {
                        addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                    }

                } else {
                    if (ifmovedfileexists.equals("overwrite_file")) {
                        sourcefilename.moveTo(destinationfile);
                        if (isDetailed()) {
                            logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileOverwrite",
                                    destinationfile.getName().toString()));
                        }

                        // add filename to result filename
                        if (add_result_filesname && !iffileexists.equals("fail")
                                && !iffileexists.equals("do_nothing")) {
                            addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                        }

                        updateSuccess();
                    } else if (ifmovedfileexists.equals("unique_name")) {
                        SimpleDateFormat daf = new SimpleDateFormat();
                        Date now = new Date();
                        daf.applyPattern("ddMMyyyy_HHmmssSSS");
                        String dt = daf.format(now);
                        short_filename += "_" + dt;

                        String destinationfilenamefull = movetofolderfolder.toString() + Const.FILE_SEPARATOR
                                + short_filename;
                        destinationfile = KettleVFS.getFileObject(destinationfilenamefull);

                        sourcefilename.moveTo(destinationfile);
                        if (isDetailed()) {
                            logDetailed(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Log.FileDecrypted",
                                    destinationfile.getName().toString()));
                        }

                        // add filename to result filename
                        if (add_result_filesname && !iffileexists.equals("fail")
                                && !iffileexists.equals("do_nothing")) {
                            addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                        }

                        updateSuccess();
                    } else if (ifmovedfileexists.equals("fail")) {
                        // Update Errors
                        updateErrors();
                    }
                }

            } else if (iffileexists.equals("fail")) {
                // Update Errors
                updateErrors();
            }

        }
    } catch (Exception e) {
        updateErrors();
        logError(BaseMessages.getString(PKG, "JobPGPDecryptFiles.Error.Exception.MoveProcessError",
                sourcefilename.toString(), destinationfilename.toString(), e.getMessage()));
    } finally {
        if (destinationfile != null) {
            try {
                destinationfile.close();
            } catch (IOException ex) { /* Ignore */
            }
        }
    }
    return retval;
}

From source file:org.pentaho.di.job.entries.movefiles.JobEntryMoveFiles.java

private boolean MoveFile(String shortfilename, FileObject sourcefilename, FileObject destinationfilename,
        FileObject movetofolderfolder, Job parentJob, Result result) {

    FileObject destinationfile = null;
    boolean retval = false;
    try {// www. j  a v a  2s.com
        if (!destinationfilename.exists()) {
            if (!simulate) {
                sourcefilename.moveTo(destinationfilename);
            }
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileMoved",
                        sourcefilename.getName().toString(), destinationfilename.getName().toString()));
            }

            // add filename to result filename
            if (add_result_filesname && !iffileexists.equals("fail") && !iffileexists.equals("do_nothing")) {
                addFileToResultFilenames(destinationfilename.toString(), result, parentJob);
            }

            updateSuccess();
            retval = true;

        } else {
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileExists",
                        destinationfilename.toString()));
            }
            if (iffileexists.equals("overwrite_file")) {
                if (!simulate) {
                    sourcefilename.moveTo(destinationfilename);
                }
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileOverwrite",
                            destinationfilename.getName().toString()));
                }

                // add filename to result filename
                if (add_result_filesname && !iffileexists.equals("fail")
                        && !iffileexists.equals("do_nothing")) {
                    addFileToResultFilenames(destinationfilename.toString(), result, parentJob);
                }

                updateSuccess();
                retval = true;

            } else if (iffileexists.equals("unique_name")) {
                String short_filename = shortfilename;

                // return destination short filename
                try {
                    short_filename = getMoveDestinationFilename(short_filename, "ddMMyyyy_HHmmssSSS");
                } catch (Exception e) {
                    logError(BaseMessages.getString(PKG,
                            BaseMessages.getString(PKG, "JobMoveFiles.Error.GettingFilename", short_filename)),
                            e);
                    return retval;
                }

                String movetofilenamefull = destinationfilename.getParent().toString() + Const.FILE_SEPARATOR
                        + short_filename;
                destinationfile = KettleVFS.getFileObject(movetofilenamefull, this);

                if (!simulate) {
                    sourcefilename.moveTo(destinationfile);
                }
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileMoved",
                            sourcefilename.getName().toString(), destinationfile.getName().toString()));
                }

                // add filename to result filename
                if (add_result_filesname && !iffileexists.equals("fail")
                        && !iffileexists.equals("do_nothing")) {
                    addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                }

                updateSuccess();
                retval = true;
            } else if (iffileexists.equals("delete_file")) {
                if (!simulate) {
                    destinationfilename.delete();
                }
                if (log.isDetailed()) {
                    logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileDeleted",
                            destinationfilename.getName().toString()));
                }
            } else if (iffileexists.equals("move_file")) {
                String short_filename = shortfilename;
                // return destination short filename
                try {
                    short_filename = getMoveDestinationFilename(short_filename, null);
                } catch (Exception e) {
                    logError(BaseMessages.getString(PKG,
                            BaseMessages.getString(PKG, "JobMoveFiles.Error.GettingFilename", short_filename)),
                            e);
                    return retval;
                }

                String movetofilenamefull = movetofolderfolder.toString() + Const.FILE_SEPARATOR
                        + short_filename;
                destinationfile = KettleVFS.getFileObject(movetofilenamefull, this);
                if (!destinationfile.exists()) {
                    if (!simulate) {
                        sourcefilename.moveTo(destinationfile);
                    }
                    if (log.isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileMoved",
                                sourcefilename.getName().toString(), destinationfile.getName().toString()));
                    }

                    // add filename to result filename
                    if (add_result_filesname && !iffileexists.equals("fail")
                            && !iffileexists.equals("do_nothing")) {
                        addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                    }

                } else {
                    if (ifmovedfileexists.equals("overwrite_file")) {
                        if (!simulate) {
                            sourcefilename.moveTo(destinationfile);
                        }
                        if (log.isDetailed()) {
                            logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileOverwrite",
                                    destinationfile.getName().toString()));
                        }

                        // add filename to result filename
                        if (add_result_filesname && !iffileexists.equals("fail")
                                && !iffileexists.equals("do_nothing")) {
                            addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                        }

                        updateSuccess();
                        retval = true;
                    } else if (ifmovedfileexists.equals("unique_name")) {
                        SimpleDateFormat daf = new SimpleDateFormat();
                        Date now = new Date();
                        daf.applyPattern("ddMMyyyy_HHmmssSSS");
                        String dt = daf.format(now);
                        short_filename += "_" + dt;

                        String destinationfilenamefull = movetofolderfolder.toString() + Const.FILE_SEPARATOR
                                + short_filename;
                        destinationfile = KettleVFS.getFileObject(destinationfilenamefull, this);

                        if (!simulate) {
                            sourcefilename.moveTo(destinationfile);
                        }
                        if (log.isDetailed()) {
                            logDetailed(BaseMessages.getString(PKG, "JobMoveFiles.Log.FileMoved",
                                    destinationfile.getName().toString()));
                        }

                        // add filename to result filename
                        if (add_result_filesname && !iffileexists.equals("fail")
                                && !iffileexists.equals("do_nothing")) {
                            addFileToResultFilenames(destinationfile.toString(), result, parentJob);
                        }

                        updateSuccess();
                        retval = true;
                    } else if (ifmovedfileexists.equals("fail")) {
                        // Update Errors
                        updateErrors();
                    }
                }

            } else if (iffileexists.equals("fail")) {
                // Update Errors
                updateErrors();
            }
        }
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobMoveFiles.Error.Exception.MoveProcessError",
                sourcefilename.toString(), destinationfilename.toString(), e.getMessage()));
        updateErrors();
    } finally {
        if (destinationfile != null) {
            try {
                destinationfile.close();
            } catch (IOException ex) { /* Ignore */
            }
        }
    }
    return retval;
}