List of usage examples for java.text DateFormat setTimeZone
public void setTimeZone(TimeZone zone)
From source file:org.dasein.cloud.azure.AzureStorageMethod.java
protected HttpRequestBase getMethod(@Nonnull String httpMethod, @Nonnull String endpoint, @Nonnull Map<String, String> queryParams, @Nullable Map<String, String> headers, boolean authorization) throws CloudException, InternalException { HttpRequestBase method;//w ww . jav a 2s .co m if (httpMethod.equals("GET")) { method = new HttpGet(endpoint); } else if (httpMethod.equals("POST")) { method = new HttpPost(endpoint); } else if (httpMethod.equals("PUT")) { method = new HttpPut(endpoint); } else if (httpMethod.equals("DELETE")) { method = new HttpDelete(endpoint); } else if (httpMethod.equals("HEAD")) { method = new HttpHead(endpoint); } else if (httpMethod.equals("OPTIONS")) { method = new HttpOptions(endpoint); } else if (httpMethod.equals("HEAD")) { method = new HttpTrace(endpoint); } else { method = new HttpGet(endpoint); } if (!authorization) { return method; } if (headers == null) { headers = new TreeMap<String, String>(); } String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z"; DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); headers.put("Date", rfc1123Format.format(new Date())); headers.put(Header_Prefix_MS + "version", VERSION); for (String key : headers.keySet()) { method.addHeader(key, headers.get(key)); } if (method.getFirstHeader("content-type") == null && !httpMethod.equals("GET")) { method.addHeader("content-type", "application/xml;charset=utf-8"); } method.addHeader("Authorization", "SharedKeyLite " + getStorageAccount() + ":" + calculatedSharedKeyLiteSignature(method, queryParams)); return method; }
From source file:com.emc.esu.api.rest.AbstractEsuRestApi.java
@SuppressWarnings("rawtypes") protected List<Version> parseVersionListLong(byte[] response) { List<Version> objs = new ArrayList<Version>(); DateFormat itimeParser = new SimpleDateFormat(ISO8601_FORMAT); itimeParser.setTimeZone(TimeZone.getTimeZone("UTC")); // Use JDOM to parse the XML SAXBuilder sb = new SAXBuilder(); try {/*from ww w . j a v a 2 s .c om*/ Document d = sb.build(new ByteArrayInputStream(response)); // The ObjectID element is part of a namespace so we need to use // the namespace to identify the elements. Namespace esuNs = Namespace.getNamespace("http://www.emc.com/cos/"); List children = d.getRootElement().getChildren("Ver", esuNs); l4j.debug("Found " + children.size() + " objects"); for (Iterator i = children.iterator(); i.hasNext();) { Object o = i.next(); if (o instanceof Element) { Element e = (Element) o; ObjectId id = new ObjectId(e.getChildText("OID", esuNs)); int versionNumber = Integer.parseInt(e.getChildText("VerNum", esuNs)); String sitime = e.getChildText("itime", esuNs); Date itime = null; try { itime = itimeParser.parse(sitime); } catch (ParseException e1) { throw new EsuException("Could not parse itime: " + sitime, e1); } objs.add(new Version(id, versionNumber, itime)); } else { l4j.debug(o + " is not an Element!"); } } } catch (JDOMException e) { throw new EsuException("Error parsing response", e); } catch (IOException e) { throw new EsuException("Error reading response", e); } return objs; }
From source file:com.bitplan.mediawiki.japi.Mediawiki.java
/** * get a current IsoTimeStamp/*from www .j a v a 2s . c o m*/ * * @return - the current timestamp */ public String getIsoTimeStamp() { TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX"); df.setTimeZone(tz); String nowAsISO = df.format(new Date()); return nowAsISO; }
From source file:kieker.tools.traceAnalysis.TraceAnalysisTool.java
/** * This method uses the (already parsed and stored) command line arguments to initialize the tool. * //from w w w. j a v a2 s . com * @param commandLine * * @return true if and only if the tool has been initialized correctly. */ private boolean initFromArgs(final CommandLine commandLine) { this.inputDirs = commandLine.getOptionValues(Constants.CMD_OPT_NAME_INPUTDIRS); this.outputDir = commandLine.getOptionValue(Constants.CMD_OPT_NAME_OUTPUTDIR); this.outputFnPrefix = this.cmdl.getOptionValue(Constants.CMD_OPT_NAME_OUTPUTFNPREFIX, ""); if (this.cmdl.hasOption(Constants.CMD_OPT_NAME_SELECTTRACES) && this.cmdl.hasOption(Constants.CMD_OPT_NAME_FILTERTRACES)) { LOG.error("Trace Id selection and filtering are mutually exclusive"); return false; } if (this.cmdl.hasOption(Constants.CMD_OPT_NAME_SELECTTRACES) || this.cmdl.hasOption(Constants.CMD_OPT_NAME_FILTERTRACES)) { // Parse list of trace Ids this.invertTraceIdFilter = this.cmdl.hasOption(Constants.CMD_OPT_NAME_FILTERTRACES); final String[] traceIdList = this.cmdl .getOptionValues(this.invertTraceIdFilter ? Constants.CMD_OPT_NAME_FILTERTRACES // NOCS (Short if operator) : Constants.CMD_OPT_NAME_SELECTTRACES); this.selectedTraces = new TreeSet<Long>(); final int numSelectedTraces = traceIdList.length; try { for (final String idStr : traceIdList) { this.selectedTraces.add(Long.valueOf(idStr)); } LOG.info(numSelectedTraces + " trace" + (numSelectedTraces > 1 ? "s" : "") + (this.invertTraceIdFilter ? " filtered" : " selected")); // NOCS } catch (final Exception e) { // NOPMD NOCS (IllegalCatchCheck) LOG.error("Failed to parse list of trace IDs: " + Arrays.toString(traceIdList), e); return false; } } this.shortLabels = commandLine.hasOption(Constants.CMD_OPT_NAME_SHORTLABELS); this.includeSelfLoops = commandLine.hasOption(Constants.CMD_OPT_NAME_INCLUDESELFLOOPS); this.ignoreInvalidTraces = commandLine.hasOption(Constants.CMD_OPT_NAME_IGNOREINVALIDTRACES); this.ignoreAssumedCalls = commandLine.hasOption(Constants.CMD_OPT_NAME_IGNORE_ASSUMED); this.repairEventBasedTraces = commandLine.hasOption(Constants.CMD_OPT_NAME_REPAIR_EVENT_BASED_TRACES); final String maxTraceDurationStr = commandLine.getOptionValue(Constants.CMD_OPT_NAME_MAXTRACEDURATION, Integer.toString(this.maxTraceDurationMillis)); try { this.maxTraceDurationMillis = Integer.parseInt(maxTraceDurationStr); } catch (final NumberFormatException exc) { LOG.error("Failed to parse int value of property " + Constants.CMD_OPT_NAME_MAXTRACEDURATION + " (must be an integer):" + maxTraceDurationStr, exc); return false; } final DateFormat dateFormat = new SimpleDateFormat(Constants.DATE_FORMAT_PATTERN, Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); try { final String ignoreRecordsBeforeTimestampString = commandLine .getOptionValue(Constants.CMD_OPT_NAME_IGNOREEXECUTIONSBEFOREDATE, null); final String ignoreRecordsAfterTimestampString = commandLine .getOptionValue(Constants.CMD_OPT_NAME_IGNOREEXECUTIONSAFTERDATE, null); if (ignoreRecordsBeforeTimestampString != null) { long ignoreExecutionsBeforeTimestampTemp; try { ignoreExecutionsBeforeTimestampTemp = Long.parseLong(ignoreRecordsBeforeTimestampString); LOG.info("Ignoring records before " + ignoreExecutionsBeforeTimestampTemp); } catch (final NumberFormatException ex) { final Date ignoreBeforeDate = dateFormat.parse(ignoreRecordsBeforeTimestampString); ignoreExecutionsBeforeTimestampTemp = ignoreBeforeDate.getTime() * (1000 * 1000); LOG.info("Ignoring records before " + dateFormat.format(ignoreBeforeDate) + " (" + ignoreExecutionsBeforeTimestampTemp + ")"); } this.ignoreExecutionsBeforeTimestamp = ignoreExecutionsBeforeTimestampTemp; } if (ignoreRecordsAfterTimestampString != null) { long ignoreExecutionsAfterTimestampTemp; try { ignoreExecutionsAfterTimestampTemp = Long.parseLong(ignoreRecordsAfterTimestampString); LOG.info("Ignoring records after " + ignoreExecutionsAfterTimestampTemp); } catch (final NumberFormatException ex) { final Date ignoreAfterDate = dateFormat.parse(ignoreRecordsAfterTimestampString); ignoreExecutionsAfterTimestampTemp = ignoreAfterDate.getTime() * (1000 * 1000); LOG.info("Ignoring records after " + dateFormat.format(ignoreAfterDate) + " (" + ignoreExecutionsAfterTimestampTemp + ")"); } this.ignoreExecutionsAfterTimestamp = ignoreExecutionsAfterTimestampTemp; } } catch (final java.text.ParseException ex) { final String errorMsg = "Error parsing date/time string. Please use the following pattern: " + DATE_FORMAT_PATTERN_CMD_USAGE_HELP; LOG.error(errorMsg, ex); return false; } return true; }
From source file:microsoft.exchange.webservices.data.ExchangeServiceBase.java
/** * Converts the universal date time string to local date time. * * @param dateString The value./*from www. j a va 2s. co m*/ * @return DateTime Returned date is always in UTC date. */ protected Date convertUniversalDateTimeStringToDate(String dateString) { String localTimeRegex = "^(.*)([+-]{1}\\d\\d:\\d\\d)$"; Pattern localTimePattern = Pattern.compile(localTimeRegex); String timeRegex = "[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2}T[0-9]{2}:[0-9]{1,2}:[0-9]{1,2}.[0-9]{1,7}"; Pattern timePattern = Pattern.compile(timeRegex); String utcPattern = "yyyy-MM-dd'T'HH:mm:ss'Z'"; String utcPattern1 = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"; String localPattern = "yyyy-MM-dd'T'HH:mm:ssz"; String localPattern1 = "yyyy-MM-dd'Z'"; String pattern = "yyyy-MM-ddz"; String localPattern2 = "yyyy-MM-dd'T'HH:mm:ss"; DateFormat utcFormatter = null; Date dt = null; String errMsg = String.format("Date String %s not in valid UTC/local format", dateString); if (dateString == null || dateString.isEmpty()) { return null; } else { if (dateString.endsWith("Z")) { // String in UTC format yyyy-MM-ddTHH:mm:ssZ utcFormatter = new SimpleDateFormat(utcPattern); utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); try { dt = utcFormatter.parse(dateString); } catch (ParseException e) { utcFormatter = new SimpleDateFormat(pattern); utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); // dateString = dateString.substring(0, 10)+"T12:00:00Z"; try { dt = utcFormatter.parse(dateString); } catch (ParseException e1) { utcFormatter = new SimpleDateFormat(localPattern1); utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); try { dt = utcFormatter.parse(dateString); } catch (ParseException ex) { utcFormatter = new SimpleDateFormat(utcPattern1); utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); } try { dt = utcFormatter.parse(dateString); } catch (ParseException e2) { throw new IllegalArgumentException(errMsg, e); } } // throw new IllegalArgumentException(errMsg,e); } } else if (dateString.endsWith("z")) { // String in UTC format yyyy-MM-ddTHH:mm:ssZ utcFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'z'"); utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); try { dt = utcFormatter.parse(dateString); } catch (ParseException e) { throw new IllegalArgumentException(e); } } else { // dateString is not ending with Z. // Check for yyyy-MM-ddTHH:mm:ss+/-HH:mm pattern Matcher localTimeMatcher = localTimePattern.matcher(dateString); if (localTimeMatcher.find()) { System.out.println("Pattern matched"); String date = localTimeMatcher.group(1); String zone = localTimeMatcher.group(2); // Add the string GMT between DateTime and TimeZone // since 'z' in yyyy-MM-dd'T'HH:mm:ssz matches // either format GMT+/-HH:mm or +/-HHmm dateString = String.format("%sGMT%s", date, zone); try { utcFormatter = new SimpleDateFormat(localPattern); utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); dt = utcFormatter.parse(dateString); } catch (ParseException e) { try { utcFormatter = new SimpleDateFormat(pattern); utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); dt = utcFormatter.parse(dateString); } catch (ParseException ex) { throw new IllegalArgumentException(ex); } } } else { // Invalid format utcFormatter = new SimpleDateFormat(localPattern2); utcFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); try { dt = utcFormatter.parse(dateString); } catch (ParseException e) { e.printStackTrace(); throw new IllegalArgumentException(errMsg); } } } return dt; } }
From source file:com.appeligo.alerts.PendingAlertThread.java
public void run() { try {/*from w w w . j a v a 2 s .c o m*/ Permissions.setCurrentUser(Permissions.SUPERUSER); while (isActive()) { PendingAlert next = null; HibernateUtil.openSession(); try { next = PendingAlert.getNextAlert(); } finally { HibernateUtil.closeSession(); } long delay = 0; if (next != null) { delay = next.getAlertTime().getTime() - System.currentTimeMillis(); log.debug("current time=" + System.currentTimeMillis() + ", next alert time=" + next.getAlertTime().getTime()); } while (((delay > 0) || (next == null)) && isActive()) { log.debug("Waiting for next pending alert. next=" + (next == null ? null : next.getId()) + ", time before next alert=" + delay); try { synchronized (this) { wait(delay); // value can only be zero (as initialized) or // a positive value (as checked in while condition). // wait(0) == wait forever } } catch (InterruptedException e) { } //need to see if there is a newer alert //(in which case, notifyAll was called), or the //alert we were waiting for was deleted delay = 0; HibernateUtil.openSession(); try { next = PendingAlert.getNextAlert(); } finally { HibernateUtil.closeSession(); } if (next != null) { delay = next.getAlertTime().getTime() - System.currentTimeMillis(); log.debug("current time=" + System.currentTimeMillis() + ", next alert time=" + next.getAlertTime().getTime()); } } if (isActive()) log.debug("Ready to fire off at least one pending alert. next=" + next.getId() + ", deleted=" + next.isDeleted()); HibernateUtil.openSession(); List<PendingAlert> pendingAlerts = PendingAlert.getExpiredAlerts(); try { if (isActive()) log.debug("checking next"); for (PendingAlert pendingAlert : pendingAlerts) { if (!isActive()) { break; } log.debug("next"); User user = null; int consecutiveExceptions = 0; Transaction transaction = HibernateUtil.currentSession().beginTransaction(); try { if (pendingAlert.isDeleted()) { log.debug("deleted"); continue; } ProgramAlert programAlert = pendingAlert.getProgramAlert(); if (programAlert == null) { // then this should be a manual pending alert pendingAlert.setDeleted(true); pendingAlert.save(); if (!pendingAlert.isManual()) { log.debug("no program alert"); continue; } } user = pendingAlert.getUser(); String programId = pendingAlert.getProgramId(); if (user == null || programId == null) { log.debug("user (" + user + ") can't be null and programId (" + programId + ") can't be null"); if (programAlert != null) { programAlert.setDeleted(true); programAlert.save(); } continue; } ScheduledProgram scheduledProgram = alertManager.getEpg() .getScheduledProgramByNetworkCallSign(pendingAlert.getUser().getLineupId(), pendingAlert.getCallSign(), pendingAlert.getProgramStartTime()); String targetId; if (programAlert == null) { targetId = scheduledProgram.getProgramId(); } else { targetId = programAlert.getProgramId(); // not a manual alert, so this is the id for the reminder itself } Program targetProgram = alertManager.getEpg().getProgram(targetId); boolean invalidProgramAlert = false; if (scheduledProgram == null) { if (log.isDebugEnabled()) log.debug("no scheduled program"); } else { if (!scheduledProgram.getProgramId().equals(programId)) { invalidProgramAlert = true; if (log.isDebugEnabled()) log.debug("Schedule must have changed...no matching programId: " + scheduledProgram.getProgramId() + " != " + programId); } else if (programAlert != null) { // Not a manual (quick) alert if (programAlert.isDisabled()) { invalidProgramAlert = true; if (log.isDebugEnabled()) log.debug("program alert disabled"); } else if (programAlert.isDeleted()) { invalidProgramAlert = true; if (log.isDebugEnabled()) log.debug("program alert was deleted"); } } } if ((scheduledProgram != null) && (!invalidProgramAlert)) { boolean scheduledAlert = false; boolean episodeAlert = false; if (programAlert == null) { scheduledAlert = true; } else { episodeAlert = true; } log.debug("firing pending alert=" + pendingAlert.getId()); Date startTime = scheduledProgram.getStartTime(); Date endTime = scheduledProgram.getEndTime(); long durationMinutes = (endTime.getTime() - startTime.getTime()) / (60 * 1000); Map<String, String> context = new HashMap<String, String>(); DateFormat format = null; DateFormat shortFormat = null; if ((startTime.getTime() - System.currentTimeMillis()) < 12 * 60 * 60 * 1000) { format = DateFormat.getTimeInstance(DateFormat.SHORT); shortFormat = DateFormat.getTimeInstance(DateFormat.SHORT); context.put("timePreposition", "at"); } else { shortFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); format = new SimpleDateFormat("EEEE, MMMM d 'at' h:mm a"); context.put("timePreposition", "on"); } format.setTimeZone(user.getTimeZone()); shortFormat.setTimeZone(user.getTimeZone()); context.put("startTime", format.format(startTime)); context.put("shortStartTime", shortFormat.format(startTime)); context.put("durationMinutes", Long.toString(durationMinutes)); context.put("programId", scheduledProgram.getProgramId()); // don't use ID from programAlert // which may be a show, but this may be an episode, or may be a team, but this a game String webPath = scheduledProgram.getWebPath(); if (webPath.charAt(0) == '/') { webPath = webPath.substring(1); } context.put("webPath", webPath); context.put("targetId", targetId); context.put("programLabel", scheduledProgram.getLabel()); if (targetId.startsWith("TE")) { context.put("whatfor", "any game featuring the " + targetProgram.getTeamName()); context.put("reducedTitle40", targetProgram.getReducedTitle40()); } else { context.put("whatfor", "the following program"); context.put("reducedTitle40", scheduledProgram.getReducedTitle40()); } if (scheduledProgram.getDescription().trim().length() > 0) { context.put("description", "Description: " + scheduledProgram.getDescription() + "<br/>"); } else { context.put("description", ""); } context.put("stationName", scheduledProgram.getNetwork().getStationName()); String greeting = user.getUsername(); context.put("username", greeting); String firstName = user.getFirstName(); if (firstName != null && firstName.trim().length() > 0) { greeting = firstName; } context.put("greeting", greeting); String targetWebPath = targetProgram.getWebPath(); if (targetWebPath.charAt(0) == '/') { targetWebPath = targetWebPath.substring(1); } context.put("showDetailsLink", "<a href=\"" + url + targetWebPath + "#reminders\">" + url + targetWebPath + "#reminders</a>"); if (episodeAlert) { context.put("deleteRemindersSentence", "Did you already see this program? If you're done with this reminder, " + "<a href=\"" + url + "reminders/deleteProgramReminders?programId=" + targetId + "\">click here to delete the reminders for this program</a>."); /* LATER, REPLACE THE LAST PARAGRAPH ABOVE WITH... <p> Did you already see this program? <a href="${url}reminders/deleteProgramReminders?programId=@programId@">Click here to delete the reminders for this program</a>\, and if you don't mind\, tell us what you think. </p> AND PUT A SIMILAR MESSAGE WITHOUT THE DELETE BUT WITH A LINK IN IF NOT EPISODEREMINDER, in "ELSE" BELOW */ } else { context.put("deleteRemindersSentence", ""); } if ((programAlert != null && programAlert.isUsingPrimaryEmail()) || user.isUsingPrimaryEmailDefault()) { Message message = new Message("program_reminder_email", context); if ((startTime.getTime() - System.currentTimeMillis()) > 4 * 60 * 60 * 1000) { message.setPriority(2); } message.setUser(user); message.setTo(user.getPrimaryEmail()); message.insert(); } if ((programAlert != null && programAlert.isUsingSMS() && user.getSmsEmail().trim().length() > 0) || user.isUsingSMSDefault()) { Message message = new Message("program_reminder_sms", context); if ((startTime.getTime() - System.currentTimeMillis()) > 4 * 60 * 60 * 1000) { message.setPriority(2); } message.setUser(user); message.setTo(user.getSmsEmail()); message.setSms(true); message.insert(); } } consecutiveExceptions = 0; } catch (MessageContextException e) { log.error( "Software bug resulted in exception with email message context or configuration", e); } catch (Throwable t) { log.error("Could not complete pending alert execution", t); transaction.rollback(); log.error("Caught throwable on pendingAlert " + pendingAlert.getId() + ", user " + ((user == null) ? null : user.getUsername()), t); consecutiveExceptions++; if (consecutiveExceptions >= maxConsecutiveExceptions) { log.fatal( "Reached max consecutive exceptions for PendingAlertThread. Exiting thread immediately."); return; } } finally { if (transaction.wasRolledBack()) { transaction = HibernateUtil.currentSession().beginTransaction(); } try { log.debug("marking pending alert=" + pendingAlert.getId() + " as fired. Should see commit message next."); pendingAlert.setFired(true); pendingAlert.save(); log.debug("committing after marking pending alert"); } catch (Throwable t) { log.error("Coult not mark pending alert", t); } finally { transaction.commit(); } } } // Now that we aren't looping on PendingAlerts, I should be able to safely // delete all of the PendingAlerts flagged as deleted without screwing up // paging (if we decide to implement paging up above) Transaction transaction = HibernateUtil.currentSession().beginTransaction(); try { log.debug("deleting marked-deleted pending alerts"); PendingAlert.deleteAllMarkedDeleted(); log.debug("deleted marked-deleted pending alerts"); log.debug("deleting marked-fired pending alerts if program has started"); PendingAlert.deleteOldFired(); log.debug("deleted marked-deleted pending alerts"); } finally { transaction.commit(); } } finally { HibernateUtil.closeSession(); } } } catch (Throwable t) { log.fatal("Caught unexpected exception, causing abort of thread!", t); } }
From source file:org.entrystore.repository.impl.ContextManagerImpl.java
private Date parseTimestamp(String timestamp) { Date date = null;/* w w w . ja v a 2s .c om*/ DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); try { date = formatter.parse(timestamp); } catch (ParseException pe) { log.error(pe.getMessage()); } return date; }
From source file:com.krawler.spring.importFunctionality.ImportUtil.java
/** * @param requestParams//from w w w. j av a2 s .co m * @param dataMap * @param columnConfig * @param column * @param customfield * @param columnHeaderMap * @param dateFormat * @param importDao * @throws JSONException * @throws DataInvalidateException * @throws ParseException */ private static void validateColumnData(HashMap<String, Object> requestParams, HashMap<String, Object> dataMap, JSONObject columnConfig, String column, JSONArray customfield, HashMap<String, Object> columnHeaderMap, String dateFormat, ImportDAO importDao, Integer colCsvIndex, HashMap<String, String> autoNoMap) throws JSONException, DataInvalidateException, ParseException { int maxLength = columnConfig.getInt("maxLength"); String csvHeader = (String) columnHeaderMap.get(column); csvHeader = (csvHeader == null ? csvHeader : csvHeader.replaceAll("\\.", " "));//remove '.' from csv Header String columnHeader = columnConfig.getString("columnName"); String data = dataMap.get(column) == null ? null : String.valueOf(dataMap.get(column)); Object vDataValue = data; if (columnConfig.has("validatetype")) { String validatetype = columnConfig.getString("validatetype"); boolean customflag = false; if (columnConfig.has("customflag")) { customflag = columnConfig.getBoolean("customflag"); } if (validatetype.equalsIgnoreCase("integer")) { try { if (!StringUtil.isNullOrEmpty(data)) { // Remove ","(comma) from number data = data.replaceAll(",", ""); } if (maxLength > 0 && data != null && data.length() > maxLength) { // Added null value check for data[Sandeep k] throw new DataInvalidateException( "Data length greater than " + maxLength + " for column " + csvHeader + "."); } vDataValue = StringUtil.isNullOrEmpty(data) ? "" : Integer.parseInt(data); } catch (DataInvalidateException dex) { throw dex; } catch (Exception ex) { throw new DataInvalidateException( "Incorrect numeric value for " + csvHeader + ", Please ensure that value type of " + csvHeader + " matches with the " + columnHeader + "."); } } else if (validatetype.equalsIgnoreCase("double")) { try { if (!StringUtil.isNullOrEmpty(data)) { // Remove ","(comma) from number data = data.replaceAll(",", ""); } if (maxLength > 0 && data != null && data.length() > maxLength) { throw new DataInvalidateException( "Data length greater than " + maxLength + " for column " + csvHeader + "."); } vDataValue = StringUtil.isNullOrEmpty(data) ? "" : Double.parseDouble(data); } catch (DataInvalidateException dex) { throw dex; } catch (Exception ex) { throw new DataInvalidateException( "Incorrect numeric value for " + csvHeader + ", Please ensure that value type of " + csvHeader + " matches with the " + columnHeader + "."); } } else if (validatetype.equalsIgnoreCase("date")) { if (!StringUtil.isNullOrEmpty(data)) { String ldf = dateFormat != null ? dateFormat : (data.length() > 10 ? df_full : df); try { if (maxLength > 0 && data == null) { throw new DataInvalidateException( "Data length greater than " + maxLength + " for column " + csvHeader + "."); } DateFormat sdf = new SimpleDateFormat(ldf); sdf.setLenient(false); sdf.setTimeZone(TimeZone.getTimeZone("GMT" + requestParams.get("tzdiff"))); vDataValue = StringUtil.isNullOrEmpty(data) ? null : sdf.parse(data); if (customflag && vDataValue != null) { vDataValue = ((Date) vDataValue).getTime(); tempFileData[colCsvIndex] = vDataValue; if (tempFileData != null) {//In case of invalid records date field is showing number(Long value) so replacing by proper format in tempFileData tempFileData[colCsvIndex.intValue()] = new Date((Long) vDataValue); } } } catch (DataInvalidateException dex) { throw dex; } catch (Exception ex) { try { vDataValue = Long.parseLong(data); if (!customflag && vDataValue != null) { vDataValue = new Date((Long) vDataValue); } if (tempFileData != null) {//In case of invalid records date field is showing number(Long value) so replacing by proper format in tempFileData tempFileData[colCsvIndex.intValue()] = customflag ? new Date((Long) vDataValue) : vDataValue; } } catch (Exception e) { throw new DataInvalidateException("Incorrect date format for " + csvHeader + ", Please specify values in " + ldf + " format."); } } } else { vDataValue = null; } } else if (validatetype.equalsIgnoreCase("time")) { if (!StringUtil.isNullOrEmpty(data)) { //@@@ need to uncomment // Pattern pattern = Pattern.compile(EmailRegEx); // if(!pattern.matcher(data).matches()){ // throw new DataInvalidateException("Incorrect time format for "+columnConfig.getString("columnName")+" use HH:MM AM or PM"); // } vDataValue = data; } else { vDataValue = null; } } else if (validatetype.equalsIgnoreCase("ref")) { if (!StringUtil.isNullOrEmpty(data)) { try { String pref = (String) requestParams.get("masterPreference"); //0:Skip Record, 1:Skip Column, 2:Add new if (columnConfig.has("refModule") && columnConfig.has("refDataColumn") && columnConfig.has("refFetchColumn") && columnConfig.has("configid")) { requestParams.put("defaultheader", columnConfig.getString("columnName")); List list = getRefData(requestParams, columnConfig.getString("refModule"), columnConfig.getString("refDataColumn"), columnConfig.getString("refFetchColumn"), columnConfig.getString("configid"), data, importDao); if (list.size() == 0) { // String configid = columnConfig.getString("configid"); // // Configid =>> 1:Owner, 2:Product, 3:Account, 4:Contact // // then we can't create new entry for such module // if(pref.equalsIgnoreCase("2") && (configid.equals("1") || configid.equals("2") || configid.equals("3") || configid.equals("4"))) { // throw new DataInvalidateException(csvHeader+" entry not found in master list for "+ columnHeader +" dropdown."); // Throw ex to skip record. // } else if (pref.equalsIgnoreCase("0")) { //Skip Record if (!ImportHandler.isMasterTable(columnConfig.getString("refModule"))) { // Cant't create entry for ref. module throw new DataInvalidateException(csvHeader + " entry not present in " + columnHeader + " list, Please create new " + columnHeader + " entry for '" + (data.replaceAll("\\.", "")) + "' as it requires some other details."); } else throw new DataInvalidateException( csvHeader + " entry not found in master list for " + columnHeader + " dropdown."); // Throw ex to skip record. } else if (pref.equalsIgnoreCase("1")) { vDataValue = null; // Put 'null' value to skip column data. } else if (pref.equalsIgnoreCase("2")) { if (!ImportHandler.isMasterTable(columnConfig.getString("refModule"))) { // Cant't create entry for ref. module throw new DataInvalidateException(csvHeader + " entry not present in " + columnHeader + " list, Please create new " + columnHeader + " entry for '" + (data.replaceAll("\\.", "")) + "' as it requires some other details."); } } } else { vDataValue = list.get(0).toString(); } } else { throw new DataInvalidateException( "Incorrect reference mapping(" + columnHeader + ") for " + csvHeader + "."); } } catch (ServiceException ex) { throw new DataInvalidateException( "Incorrect reference mapping(" + columnHeader + ") for " + csvHeader + "."); } catch (DataInvalidateException ex) { throw ex; } catch (Exception ex) { throw new DataInvalidateException( csvHeader + " entry not found in master list for " + columnHeader + " dropdown."); } } else { vDataValue = null; } } else if (!customflag && validatetype.equalsIgnoreCase("multiselect")) { if (!StringUtil.isNullOrEmpty(data)) { try { String pref = (String) requestParams.get("masterPreference"); //0:Skip Record, 1:Skip Column, 2:Add new if (columnConfig.has("refModule") && columnConfig.has("refDataColumn") && columnConfig.has("refFetchColumn") && columnConfig.has("configid")) { String[] multiData = data.toString().split(Constants.Custom_Column_Sep); String mdata = ""; Boolean isRefData = columnConfig.has("refModule") && columnConfig.has("refDataColumn") && columnConfig.has("refFetchColumn") && columnConfig.has("configid"); List list = null; for (int i = 0; isRefData && i < multiData.length; i++) { // Reference module list = getRefData(requestParams, columnConfig.getString("refModule"), columnConfig.getString("refDataColumn"), columnConfig.getString("refFetchColumn"), columnConfig.getString("configid"), multiData[i], importDao); if (list.size() == 0) { if (pref.equalsIgnoreCase("0")) { //Skip Record if (!ImportHandler.isMasterTable(columnConfig.getString("refModule"))) { // Cant't create entry for ref. module throw new DataInvalidateException(csvHeader + " entry not present in " + columnHeader + " list, Please create new " + columnHeader + " entry for '" + (multiData[i].replaceAll("\\.", "")) + "' as it requires some other details."); } else { throw new DataInvalidateException( csvHeader + " entry not found in master list for " + columnHeader + " dropdown."); // Throw ex to skip record. } } else if (pref.equalsIgnoreCase("2")) { if (!ImportHandler.isMasterTable(columnConfig.getString("refModule"))) { // Cant't create entry for ref. module throw new DataInvalidateException(csvHeader + " entry not present in " + columnHeader + " list, Please create new " + columnHeader + " entry for '" + (multiData[i].replaceAll("\\.", "")) + "' as it requires some other details."); } } } else { mdata += list.get(0).toString() + Constants.Custom_Column_Sep; } } if (mdata.length() > 0) { vDataValue = mdata.substring(0, mdata.length() - 1); } else { if (pref.equalsIgnoreCase("1")) { vDataValue = null; } else vDataValue = ""; } } else { throw new DataInvalidateException( "Incorrect reference mapping(" + columnHeader + ") for " + csvHeader + "."); } } catch (ServiceException ex) { throw new DataInvalidateException( "Incorrect reference mapping(" + columnHeader + ") for " + csvHeader + "."); } catch (DataInvalidateException ex) { throw ex; } catch (Exception ex) { throw new DataInvalidateException( csvHeader + " entry not found in master list for " + columnHeader + " dropdown."); } } else { vDataValue = null; } } else if (validatetype.equalsIgnoreCase("email")) { if (maxLength > 0 && data != null && data.length() > maxLength) { throw new DataInvalidateException( "Data length greater than " + maxLength + " for column " + csvHeader + "."); } if (!StringUtil.isNullOrEmpty(data)) { Pattern pattern = Pattern.compile(EmailRegEx); if (!pattern.matcher(data).matches()) { throw new DataInvalidateException("Invalid email address for " + csvHeader + "."); } vDataValue = data; } else { vDataValue = null; } } else if (validatetype.equalsIgnoreCase("boolean")) { if (data.equalsIgnoreCase("true") || data.equalsIgnoreCase("1") || data.equalsIgnoreCase("T")) { vDataValue = true; } else if (data.equalsIgnoreCase("false") || data.equalsIgnoreCase("0") || data.equalsIgnoreCase("F")) { vDataValue = false; } else { throw new DataInvalidateException("Incorrect boolean value for " + csvHeader + "."); } } if (vDataValue == null && columnConfig.has("isNotNull") && columnConfig.getBoolean("isNotNull")) { throw new DataInvalidateException( "Empty data found in " + csvHeader + ", Can not set empty data for " + columnHeader + "."); } else { if (customflag) { JSONObject jobj = new JSONObject(); if (columnConfig.getString("xtype").equals("4") || columnConfig.getString("xtype").equals("7")) {//Drop down & Multi Select Drop down try { if (vDataValue != null) { if (!StringUtil.isNullOrEmpty(vDataValue.toString())) { HashMap<String, Object> comborequestParams = new HashMap<String, Object>(); comborequestParams = requestParams; String pref = (String) requestParams.get("masterPreference"); //0:Skip Record, 1:Skip Column, 2:Add new KwlReturnObject result = null; if (columnConfig.getString("xtype").equals("4")) { comborequestParams.put("filtergetColumn_names", Arrays.asList("fieldid", "value")); comborequestParams.put("filter_values", Arrays.asList( columnConfig.getString("pojoHeader"), vDataValue.toString())); List lst = getCustomComboID(requestParams, vDataValue.toString(), columnConfig.getString("pojoHeader"), "id", importDao); // List lst = result.getEntityList(); if (lst.size() == 0) { if (pref.equalsIgnoreCase("0")) { //Skip Record throw new DataInvalidateException( csvHeader + " entry not found in the list for " + columnHeader + " dropdown."); // Throw ex to skip record. } else if (pref.equalsIgnoreCase("1")) { vDataValue = null; // Put 'null' value to skip column data. } } else { // FieldComboData tmpcontyp = (FieldComboData) ite.next(); vDataValue = lst.get(0).toString(); } } else if (columnConfig.getString("xtype").equals("7")) { String[] multiData = vDataValue.toString() .split(Constants.Custom_Column_Sep); String mdata = ""; for (int i = 0; i < multiData.length; i++) { // if for master multiselect data item and else for custom multiselect if (columnConfig.has("refModule") && columnConfig.has("refDataColumn") && columnConfig.has("refFetchColumn") && columnConfig.has("configid")) { List list = getRefData(requestParams, columnConfig.getString("refModule"), columnConfig.getString("refDataColumn"), columnConfig.getString("refFetchColumn"), columnConfig.getString("configid"), multiData[i], importDao); mdata += list.get(0).toString() + Constants.Custom_Column_Sep; } else { comborequestParams.put("filter_names", Arrays.asList("fieldid", "value")); comborequestParams.put("filter_values", Arrays.asList( columnConfig.getString("pojoHeader"), multiData[i])); List lst = getCustomComboID(requestParams, multiData[i], columnConfig.getString("pojoHeader"), "id", importDao); // List lst = result.getEntityList(); if (lst.size() == 0) { if (pref.equalsIgnoreCase("0")) { //Skip Record throw new DataInvalidateException( csvHeader + " entry not found in the list for " + columnHeader + " dropdown."); // Throw ex to skip record. } else if (pref.equalsIgnoreCase("1")) { vDataValue = null; // Put 'null' value to skip column data. } } else { // FieldComboData tmpcontyp = (FieldComboData) ite.next(); mdata += lst.get(0).toString() + Constants.Custom_Column_Sep; } } } if (mdata.length() > 0) { vDataValue = mdata.substring(0, mdata.length() - 1); } } } } /* else { throw new DataInvalidateException("Incorrect reference mapping("+columnHeader+") for "+csvHeader+"."); }*/ } catch (DataInvalidateException ex) { throw ex; } catch (Exception ex) { throw new DataInvalidateException(csvHeader + " entry not found in master list for " + columnHeader + " dropdown."); } } else if (columnConfig.getString("xtype").equals("8")) {//Reference Drop down try { if (vDataValue != null) { if (!StringUtil.isNullOrEmpty(vDataValue.toString())) { String pref = (String) requestParams.get("masterPreference"); //0:Skip Record, 1:Skip Column, 2:Add new if (columnConfig.has("refModule") && columnConfig.has("refDataColumn") && columnConfig.has("refFetchColumn") && columnConfig.has("configid")) { List list = getRefData(requestParams, columnConfig.getString("refModule"), columnConfig.getString("refDataColumn"), columnConfig.getString("refFetchColumn"), columnConfig.getString("configid"), vDataValue, importDao); if (list.size() == 0) { if (pref.equalsIgnoreCase("0")) { //Skip Record throw new DataInvalidateException( csvHeader + " entry not found in the list for " + columnHeader + " dropdown."); // Throw ex to skip record. } else if (pref.equalsIgnoreCase("1")) { vDataValue = null; // Put 'null' value to skip column data. } else if (pref.equalsIgnoreCase("2")) { //2:Add new if (columnConfig.getString("refModule") .equalsIgnoreCase(Constants.Crm_users_pojo)) {//For users custom column. throw new DataInvalidateException( csvHeader + " entry not found in the list for " + columnHeader + " dropdown."); // Throw ex to skip record. } } } else { vDataValue = list.get(0).toString(); } } else { throw new DataInvalidateException("Incorrect reference mapping(" + columnHeader + ") for " + csvHeader + "."); } } } /* else { throw new DataInvalidateException("Incorrect reference mapping("+columnHeader+") for "+csvHeader+"."); }*/ } catch (ServiceException ex) { throw new DataInvalidateException( "Incorrect reference mapping(" + columnHeader + ") for " + csvHeader + "."); } catch (DataInvalidateException ex) { throw ex; } catch (Exception ex) { throw new DataInvalidateException(csvHeader + " entry not found in master list for " + columnHeader + " dropdown."); } } else { if (!validatetype.equalsIgnoreCase("date") && maxLength > 0 && data != null && data.length() > maxLength) { throw new DataInvalidateException( "Data length greater than " + maxLength + " for column " + csvHeader + "."); } } createCustomColumnJSON(jobj, columnConfig, vDataValue); customfield.put(jobj); if (dataMap.containsKey(column)) { dataMap.remove(column); } } else { if (validatetype.equalsIgnoreCase("string") && maxLength > 0 && data != null && data.length() > maxLength) { throw new DataInvalidateException( "Data length greater than " + maxLength + " for column " + csvHeader + "."); } dataMap.put(column, vDataValue); } } } else { // If no validation type then check allow null property[SK] if (vDataValue == null && columnConfig.has("isNotNull") && columnConfig.getBoolean("isNotNull")) { throw new DataInvalidateException( "Empty data found in " + csvHeader + ". Can not set empty data for " + columnHeader + "."); } if (data != null && maxLength > 0 && data.length() > maxLength) { throw new DataInvalidateException( "Data length greater than " + maxLength + " for column " + csvHeader + "."); } } }
From source file:org.codehaus.mojo.webstart.JnlpMojo.java
public String getJnlpBuildVersion() { if (jnlpBuildVersion != null) { return jnlpBuildVersion; }/*from ww w . ja v a2 s.c om*/ DateFormat utcDateFormatter = new SimpleDateFormat(UTC_TIMESTAMP_PATTERN); utcDateFormatter.setTimeZone(UTC_TIME_ZONE); String timestamp = utcDateFormatter.format(new Date()); String version = getProject().getVersion(); if (version.endsWith("SNAPSHOT")) { version = version.replaceAll("SNAPSHOT", timestamp); } jnlpBuildVersion = version; return version; }
From source file:org.codehaus.mojo.webstart.JnlpMojo.java
public String getArtifactJnlpVersion(Artifact artifact) { // FIXME this should convert the version so it is jnlp safe // FIXME this isn't correctly resovling some artifacts to their // actual version numbers. This appears to happen based on the // metadata files stored in the local repository. I wasn't able // narrow down exactly what was going on, but I think it is due // to running the jnlp goal without the -U (update snapshots) // if a snapshot is built locally then its metadata is in a different // state than if it is downloaded from a remote repository. String version = artifact.getVersion(); if (version.contains("-SNAPSHOT")) { File artifactFile = artifact.getFile(); DateFormat utcDateFormatter = new SimpleDateFormat(UTC_TIMESTAMP_PATTERN); utcDateFormatter.setTimeZone(UTC_TIME_ZONE); String timestamp = utcDateFormatter.format(new Date(artifactFile.lastModified())); version = version.replaceAll("SNAPSHOT", timestamp); getLog().debug("constructing local timestamp: " + timestamp + " for SNAPSHOT: " + artifact); }/*from w w w .ja va2 s .c om*/ String suffix = jnlp.getVersionSuffix(); if (suffix != null) { version += suffix; } return version; }