List of usage examples for java.text DateFormat setLenient
public void setLenient(boolean lenient)
From source file:org.sakaiproject.calendar.impl.GenericCalendarImporter.java
public List doImport(String importType, InputStream importStream, Map columnMapping, String[] customFieldPropertyNames) throws ImportException { final List rowList = new ArrayList(); final Reader scheduleImport; try {/*ww w . jav a2 s . c o m*/ scheduleImport = (Reader) ((Class) readerMap.get(importType)).newInstance(); // Set the timeservice in the reader. scheduleImport.setTimeService(getTimeService()); } catch (InstantiationException e1) { String msg = (String) rb.getFormattedMessage("err_import", new Object[] { importType }); throw new ImportException(msg); } catch (IllegalAccessException e1) { String msg = (String) rb.getFormattedMessage("err_import", new Object[] { importType }); throw new ImportException(msg); } if (scheduleImport == null) { throw new ImportException(rb.getString("err_import_unknown")); } // If no column mapping has been specified, use the default. if (columnMapping != null) { scheduleImport.setColumnHeaderToAtributeMapping(columnMapping); } columnMap = scheduleImport.getDefaultColumnMap(); // Read in the file. scheduleImport.importStreamFromDelimitedFile(importStream, new Reader.ReaderImportRowHandler() { String frequencyColumn = columnMap.get(FREQUENCY_DEFAULT_COLUMN_HEADER); String startTimeColumn = columnMap.get(START_TIME_DEFAULT_COLUMN_HEADER); String endTimeColumn = columnMap.get(END_TIME_DEFAULT_COLUMN_HEADER); String durationTimeColumn = columnMap.get(DURATION_DEFAULT_COLUMN_HEADER); String dateColumn = columnMap.get(DATE_DEFAULT_COLUMN_HEADER); String endsColumn = columnMap.get(ENDS_DEFAULT_COLUMN_HEADER); String intervalColumn = columnMap.get(INTERVAL_DEFAULT_COLUMN_HEADER); String repeatColumn = columnMap.get(REPEAT_DEFAULT_COLUMN_HEADER); // This is the callback that is called for each row. public void handleRow(Iterator columnIterator) throws ImportException { final Map eventProperties = new HashMap(); // Add all the properties to the map while (columnIterator.hasNext()) { Reader.ReaderImportCell column = (Reader.ReaderImportCell) columnIterator.next(); String value = column.getCellValue().trim(); Object mapCellValue = null; // First handle any empy columns. if (value.length() == 0) { mapCellValue = null; } else { if (frequencyColumn != null && frequencyColumn.equals(column.getColumnHeader())) { mapCellValue = column.getCellValue(); } else if (endTimeColumn != null && endTimeColumn.equals(column.getColumnHeader()) || (startTimeColumn != null && startTimeColumn.equals(column.getColumnHeader()))) { boolean success = false; try { mapCellValue = timeFormatter().parse(value); success = true; } catch (ParseException e) { // Try another format } if (!success) { try { mapCellValue = timeFormatterWithSeconds().parse(value); success = true; } catch (ParseException e) { // Try another format } } if (!success) { try { mapCellValue = time24HourFormatter().parse(value); success = true; } catch (ParseException e) { // Try another format } } if (!success) { try { mapCellValue = time24HourFormatterWithSeconds().parse(value); success = true; } catch (ParseException e) { // Give up, we've run out of possible formats. String msg = (String) rb.getFormattedMessage("err_time", new Object[] { Integer.valueOf(column.getLineNumber()), column.getColumnHeader() }); throw new ImportException(msg); } } } else if (durationTimeColumn != null && durationTimeColumn.equals(column.getColumnHeader())) { String timeFormatErrorString = (String) rb.getFormattedMessage("err_time", new Object[] { Integer.valueOf(column.getLineNumber()), column.getColumnHeader() }); String parts[] = value.split(":"); if (parts.length == 1) { // Convert to minutes to get into one property field. try { mapCellValue = Integer.valueOf(Integer.parseInt(parts[0])); } catch (NumberFormatException ex) { throw new ImportException(timeFormatErrorString); } } else if (parts.length == 2) { // Convert to hours:minutes to get into one property field. try { mapCellValue = Integer .valueOf(Integer.parseInt(parts[0]) * 60 + Integer.parseInt(parts[1])); } catch (NumberFormatException ex) { throw new ImportException(timeFormatErrorString); } } else { // Not a legal format of mm or hh:mm throw new ImportException(timeFormatErrorString); } } else if (dateColumn != null && dateColumn.equals(column.getColumnHeader()) || (endsColumn != null && endsColumn.equals(column.getColumnHeader()))) { DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, rb.getLocale()); df.setLenient(false); try { mapCellValue = df.parse(value); } catch (ParseException e) { String msg = (String) rb.getFormattedMessage("err_date", new Object[] { Integer.valueOf(column.getLineNumber()), column.getColumnHeader() }); throw new ImportException(msg); } } else if (intervalColumn != null && intervalColumn.equals(column.getColumnHeader()) || repeatColumn != null && repeatColumn.equals(column.getColumnHeader())) { try { mapCellValue = Integer.valueOf(column.getCellValue()); } catch (NumberFormatException ex) { String msg = (String) rb.getFormattedMessage("err_interval", new Object[] { Integer.valueOf(column.getLineNumber()), column.getColumnHeader() }); throw new ImportException(msg); } } else if (ITEM_TYPE_PROPERTY_NAME.equals(column.getColumnHeader())) { String cellValue = column.getCellValue(); if (cellValue != null) { if (cellValue.equals("event.activity")) { mapCellValue = "Activity"; } else if (cellValue.equals("event.exam")) { mapCellValue = "Exam"; } else if (cellValue.equals("event.meeting")) { mapCellValue = "Meeting"; } else if (cellValue.equals("event.academic.calendar")) { mapCellValue = "Academic Calendar"; } else if (cellValue.equals("event.cancellation")) { mapCellValue = "Cancellation"; } else if (cellValue.equals("event.discussion")) { mapCellValue = "Class section - Discussion"; } else if (cellValue.equals("event.lab")) { mapCellValue = "Class section - Lab"; } else if (cellValue.equals("event.lecture")) { mapCellValue = "Class section - Lecture"; } else if (cellValue.equals("event.smallgroup")) { mapCellValue = "Class section - Small Group"; } else if (cellValue.equals("event.class")) { mapCellValue = "Class session"; } else if (cellValue.equals("event.computer")) { mapCellValue = "Computer Session"; } else if (cellValue.equals("event.deadline")) { mapCellValue = "Deadline"; } else if (cellValue.equals("event.conference")) { mapCellValue = "Multidisciplinary Conference"; } else if (cellValue.equals("event.quiz")) { mapCellValue = "Quiz"; } else if (cellValue.equals("event.special")) { mapCellValue = "Special event"; } else if (cellValue.equals("event.assignment")) { mapCellValue = "Web Assignment"; } else { mapCellValue = cellValue; } } } else { // Just a string... mapCellValue = column.getCellValue(); } } // Store in the map for later reference. eventProperties.put(column.getColumnHeader(), mapCellValue); } // Add the map of properties for this row to the list of rows. rowList.add(eventProperties); } }); return getPrototypeEvents(scheduleImport.filterEvents(rowList, customFieldPropertyNames), customFieldPropertyNames); }
From source file:com.eleybourn.bookcatalogue.utils.Utils.java
/** * Attempt to parse a date string based on a range of possible formats; allow * for caller to specify if the parsing should be strict or lenient. * /*from w ww. java 2 s.c o m*/ * @param s String to parse * @param lenient True if parsing should be lenient * * @return Resulting date if parsed, otherwise null */ private static Date parseDate(String s, boolean lenient) { Date d; for (SimpleDateFormat sdf : mParseDateFormats) { try { sdf.setLenient(lenient); d = sdf.parse(s); return d; } catch (Exception e) { // Ignore } } // All SDFs failed, try locale-specific... try { java.text.DateFormat df = java.text.DateFormat.getDateInstance(java.text.DateFormat.SHORT); df.setLenient(lenient); d = df.parse(s); return d; } catch (Exception e) { // Ignore } return null; }
From source file:com.cloud.api.dispatch.ParamProcessWorker.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private void setFieldValue(final Field field, final BaseCmd cmdObj, final Object paramObj, final Parameter annotation) throws IllegalArgumentException, ParseException { try {/* www . ja v a 2 s . c om*/ field.setAccessible(true); final CommandType fieldType = annotation.type(); switch (fieldType) { case BOOLEAN: field.set(cmdObj, Boolean.valueOf(paramObj.toString())); break; case DATE: // This piece of code is for maintaining backward compatibility // and support both the date formats(Bug 9724) if (cmdObj instanceof ListEventsCmd || cmdObj instanceof DeleteEventsCmd || cmdObj instanceof ArchiveEventsCmd || cmdObj instanceof ArchiveAlertsCmd || cmdObj instanceof DeleteAlertsCmd || cmdObj instanceof GetUsageRecordsCmd) { final boolean isObjInNewDateFormat = isObjInNewDateFormat(paramObj.toString()); if (isObjInNewDateFormat) { final DateFormat newFormat = newInputFormat; synchronized (newFormat) { field.set(cmdObj, newFormat.parse(paramObj.toString())); } } else { final DateFormat format = inputFormat; synchronized (format) { Date date = format.parse(paramObj.toString()); if (field.getName().equals("startDate")) { date = messageDate(date, 0, 0, 0); } else if (field.getName().equals("endDate")) { date = messageDate(date, 23, 59, 59); } field.set(cmdObj, date); } } } else { final DateFormat format = inputFormat; synchronized (format) { format.setLenient(false); field.set(cmdObj, format.parse(paramObj.toString())); } } break; case FLOAT: // Assuming that the parameters have been checked for required before now, // we ignore blank or null values and defer to the command to set a default // value for optional parameters ... if (paramObj != null && isNotBlank(paramObj.toString())) { field.set(cmdObj, Float.valueOf(paramObj.toString())); } break; case DOUBLE: // Assuming that the parameters have been checked for required before now, // we ignore blank or null values and defer to the command to set a default // value for optional parameters ... if (paramObj != null && isNotBlank(paramObj.toString())) { field.set(cmdObj, Double.valueOf(paramObj.toString())); } break; case INTEGER: // Assuming that the parameters have been checked for required before now, // we ignore blank or null values and defer to the command to set a default // value for optional parameters ... if (paramObj != null && isNotBlank(paramObj.toString())) { field.set(cmdObj, Integer.valueOf(paramObj.toString())); } break; case LIST: final List listParam = new ArrayList(); final StringTokenizer st = new StringTokenizer(paramObj.toString(), ","); while (st.hasMoreTokens()) { final String token = st.nextToken(); final CommandType listType = annotation.collectionType(); switch (listType) { case INTEGER: listParam.add(Integer.valueOf(token)); break; case UUID: if (token.isEmpty()) break; final Long internalId = translateUuidToInternalId(token, annotation); listParam.add(internalId); break; case LONG: { listParam.add(Long.valueOf(token)); } break; case SHORT: listParam.add(Short.valueOf(token)); break; case STRING: listParam.add(token); break; } } field.set(cmdObj, listParam); break; case UUID: final Long internalId = translateUuidToInternalId(paramObj.toString(), annotation); field.set(cmdObj, internalId); break; case LONG: field.set(cmdObj, Long.valueOf(paramObj.toString())); break; case SHORT: field.set(cmdObj, Short.valueOf(paramObj.toString())); break; case STRING: if ((paramObj != null)) { if (paramObj.toString().length() > annotation.length()) { s_logger.error("Value greater than max allowed length " + annotation.length() + " for param: " + field.getName()); throw new InvalidParameterValueException("Value greater than max allowed length " + annotation.length() + " for param: " + field.getName()); } else { field.set(cmdObj, paramObj.toString()); } } break; case TZDATE: field.set(cmdObj, DateUtil.parseTZDateString(paramObj.toString())); break; case MAP: default: field.set(cmdObj, paramObj); break; } } catch (final IllegalAccessException ex) { s_logger.error("Error initializing command " + cmdObj.getCommandName() + ", field " + field.getName() + " is not accessible."); throw new CloudRuntimeException("Internal error initializing parameters for command " + cmdObj.getCommandName() + " [field " + field.getName() + " is not accessible]"); } }
From source file:com.krawler.spring.importFunctionality.ImportUtil.java
/** * @param requestParams// w w w . ja va 2 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.kuali.kfs.module.cam.batch.service.impl.AssetDepreciationServiceImpl.java
private Date convertToDate(String date) throws ParseException { DateFormat dateFormat = new SimpleDateFormat(CamsConstants.DateFormats.MONTH_DAY_YEAR); dateFormat.setLenient(false); return dateFormat.parse(date); }
From source file:org.kuali.kfs.fp.batch.service.impl.ProcurementCardCreateDocumentServiceImpl.java
/** * Retrieve date formatter used to format batch running timestamp in report. System parameter has precedence over system default String. * * @return/* w w w .j ava 2 s.c om*/ */ protected DateFormat getDateFormat(String namespaceCode, String componentCode, String parameterName, String defaultValue) { DateFormat dateFormat = new SimpleDateFormat(defaultValue); if (getParameterService().parameterExists(namespaceCode, componentCode, parameterName)) { String formatParmVal = getParameterService().getParameterValueAsString(namespaceCode, componentCode, parameterName, defaultValue); if (StringUtils.isNotBlank(formatParmVal)) { try { dateFormat = new SimpleDateFormat(formatParmVal); } catch (IllegalArgumentException e) { LOG.error( "Parameter PCARD_BATCH_SUMMARY_RUNNING_TIMESTAMP_FORMAT used by ProcurementCardCreateDocumentsStep does not set up properly. Use system default timestamp format instead for generating report."); dateFormat = new SimpleDateFormat(defaultValue); } } } dateFormat.setLenient(false); return dateFormat; }
From source file:org.andromda.timetracker.web.timecardsearch.SearchTimecardsFormImpl.java
/** * Default constructor//w w w. j a va 2 s.c o m */ public SearchTimecardsFormImpl() { final DateFormat timecardSummariesStartDateDateFormatter = new SimpleDateFormat("MM/dd/yyyy"); timecardSummariesStartDateDateFormatter.setLenient(true); this.dateTimeFormatters.put("timecardSummaries.startDate", timecardSummariesStartDateDateFormatter); final DateFormat startDateMinimumDateFormatter = new SimpleDateFormat("MM/dd/yyyy"); startDateMinimumDateFormatter.setLenient(true); this.dateTimeFormatters.put("startDateMinimum", startDateMinimumDateFormatter); final DateFormat startDateMaximumDateFormatter = new SimpleDateFormat("MM/dd/yyyy"); startDateMaximumDateFormatter.setLenient(true); this.dateTimeFormatters.put("startDateMaximum", startDateMaximumDateFormatter); // - setup the default Date.toString() formatter final DateFormat dateFormatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy"); dateFormatter.setLenient(true); this.dateTimeFormatters.put(null, dateFormatter); }
From source file:org.andromda.timetracker.web.timecardsearch.SearchTimecardsSearchFormImpl.java
/** * Default constructor// w ww .jav a 2 s . com */ public SearchTimecardsSearchFormImpl() { final DateFormat timecardSummariesStartDateDateFormatter = new SimpleDateFormat("MM/dd/yyyy"); timecardSummariesStartDateDateFormatter.setLenient(true); this.dateTimeFormatters.put("timecardSummaries.startDate", timecardSummariesStartDateDateFormatter); final DateFormat startDateMinimumDateFormatter = new SimpleDateFormat("MM/dd/yyyy"); startDateMinimumDateFormatter.setLenient(true); this.dateTimeFormatters.put("startDateMinimum", startDateMinimumDateFormatter); final DateFormat startDateMaximumDateFormatter = new SimpleDateFormat("MM/dd/yyyy"); startDateMaximumDateFormatter.setLenient(true); this.dateTimeFormatters.put("startDateMaximum", startDateMaximumDateFormatter); // - setup the default Date.toString() formatter final DateFormat dateFormatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy"); dateFormatter.setLenient(true); this.dateTimeFormatters.put(null, dateFormatter); }
From source file:org.aksw.mex.log4mex.MEXSerializer.java
/** * serializes the mex file//from www .jav a 2s .co m * @param filename * @param URIbase * @param mex * @param format * @throws Exception */ private void writeJena(String filename, String URIbase, MyMEX mex, MEXConstant.EnumRDFFormats format) throws Exception { Model model = ModelFactory.createDefaultModel(); try { setHeaders(model, URIbase); //common resources Resource provAgent = model.createResource(PROVO.NS + PROVO.ClasseTypes.AGENT); Resource provOrganization = model.createResource(PROVO.NS + PROVO.ClasseTypes.ORGANIZATION); //MEX-CORE Resource mexcore_APC = model.createResource(MEXCORE_10.NS + MEXCORE_10.ClasseTypes.APPLICATION_CONTEXT); Resource mexcore_EXP_HEADER = model.createResource(MEXCORE_10.NS + MEXCORE_10.ClasseTypes.EXPERIMENT); Resource mexcore_EXP_CONF = model .createResource(MEXCORE_10.NS + MEXCORE_10.ClasseTypes.EXPERIMENT_CONFIGURATION); Resource mexcore_MODEL = model.createResource(MEXCORE_10.NS + MEXCORE_10.ClasseTypes.MODEL); Resource mexcore_HARDWARE = model .createResource(MEXCORE_10.NS + MEXCORE_10.ClasseTypes.HARDWARE_CONFIGURATION); Resource mexcore_DATASET = model.createResource(MEXCORE_10.NS + MEXCORE_10.ClasseTypes.DATASET); Resource mexcore_FEATURE = model.createResource(MEXCORE_10.NS + MEXCORE_10.ClasseTypes.FEATURE); Resource mexcore_FEATURE_COLLECTION = model .createResource(MEXCORE_10.NS + MEXCORE_10.ClasseTypes.FEATURE_COLLECTION); Resource mexcore_EXAMPLE = model.createResource(MEXCORE_10.NS + MEXCORE_10.ClasseTypes.EXAMPLE); Resource mexcore_EXAMPLE_COLLECTION = model .createResource(MEXCORE_10.NS + MEXCORE_10.ClasseTypes.EXAMPLE_COLLECTION); //MEX-ALGO Resource mexalgo_ALGO = model.createResource(MEXALGO_10.NS + MEXALGO_10.ClasseTypes.ALGORITHM); Resource mexalgo_HYPER_PARAM = model .createResource(MEXALGO_10.NS + MEXALGO_10.ClasseTypes.HYPER_PARAMETER); Resource mexalgo_HYPER_PARAM_COLLECTION = model .createResource(MEXALGO_10.NS + MEXALGO_10.ClasseTypes.HYPER_PARAMETER_COLLECTION); Resource mexalgo_TOOL_PARAM = model .createResource(MEXALGO_10.NS + MEXALGO_10.ClasseTypes.TOOL_PARAMETER); Resource mexalgo_TOOL_PARAM_COLLECTION = model .createResource(MEXALGO_10.NS + MEXALGO_10.ClasseTypes.TOOL_PARAMETER_COLLECTION); //MEX-PERF Resource mexperf_EXAMPLE_PERFORMANCE_COLLECTION = model .createResource(MEXPERF_10.NS + MEXPERF_10.ClasseTypes.EXAMPLE_PERFORMANCE_COLLECTION); Resource mexperf_EXAMPLE_PERFORMANCE_MEASURE = model .createResource(MEXPERF_10.NS + MEXPERF_10.ClasseTypes.EXAMPLE_PERFORMANCE_MEASURE); Resource mexperf_USER_DEFINED_PERFORMANCE_COLLECTION = model .createResource(MEXPERF_10.NS + MEXPERF_10.ClasseTypes.USER_DEFINED_MEASURE_COLLECTION); Resource mexperf_USER_DEFINED_PERFORMANCE_MEASURE = model .createResource(MEXPERF_10.NS + MEXPERF_10.ClasseTypes.USER_DEFINED_MEASURE); //mex-core Resource _application = null; Resource _context; Resource _version; Resource _organization; Resource _expHeader = null; //gets if (mex.getApplicationContext() != null) { _application = model.createResource(mex.getApplicationContext().getIndividualName()) .addProperty(RDFS.label, "Basic Experiment Infomation").addProperty(RDF.type, mexcore_APC) .addProperty(DCTerms.dateCopyrighted, new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z") .format(mex.getApplicationContext().get_fileDate())); if (mex.getApplicationContext().get_givenName() != null) { _application.addProperty(FOAF.givenName, mex.getApplicationContext().get_givenName()); } if (mex.getApplicationContext().get_mbox() != null) { _application.addProperty(FOAF.mbox, mex.getApplicationContext().get_mbox()); } if (mex.getApplicationContext().get_homepage() != null) { _application.addProperty(DOAP.homepage, mex.getApplicationContext().get_givenName()); } if (mex.getApplicationContext().get_description() != null) { _application.addProperty(DOAP.description, mex.getApplicationContext().get_mbox()); } if (mex.getApplicationContext().get_category() != null) { _application.addProperty(DOAP.category, mex.getApplicationContext().get_givenName()); } if (mex.getApplicationContext().get_location() != null) { _application.addProperty(DOAP.location, mex.getApplicationContext().get_mbox()); } if (mex.getApplicationContext().get_trustyURI() != null) { _application.addProperty(MEXCORE_10.trustyURI, mex.getApplicationContext().get_trustyURI()); } if (mex.getApplicationContext().get_organization() != null) { //Resource mexcore_ORG = model.createResource(MEXCORE_10.NS + mex.getApplicationContext().get_organization()); _organization = model.createResource(URIbase + "org_" + mex.getUserHash()) .addProperty(RDF.type, provOrganization) .addProperty(FOAF.givenName, mex.getApplicationContext().get_organization()); _application.addProperty(PROVO.actedOnBehalfOf, _organization); } if (mex.getApplicationContext().getContext() != null && mex.getApplicationContext().getContext() .get_context() != MEXEnum.EnumContexts.NOT_INFORMED) { Resource mexcore_CON = model.createResource( MEXCORE_10.NS + mex.getApplicationContext().getContext().get_context().toString()); _context = model.createResource(mex.getApplicationContext().getContext().getIndividualName()) .addProperty(RDF.type, mexcore_CON) .addProperty(RDFS.label, mex.getApplicationContext().getContext().getLabel()) .addProperty(PROVO.wasAttributedTo, _application); } _version = model.createResource(URIbase + "version").addProperty(DCTerms.hasVersion, this.getVersion()); } //EXPERIMENT if (mex.getExperiment() != null) { _expHeader = model.createResource(mex.getExperiment().getIndividualName()) .addProperty(RDF.type, mexcore_EXP_HEADER) .addProperty(MEXCORE_10.experimentHash, mex.getUserHash()); if (StringUtils.isNotEmpty(mex.getExperiment().getId()) && StringUtils.isNotBlank(mex.getExperiment().getId())) { _expHeader.addProperty(DCTerms.identifier, mex.getExperiment().getId()); _expHeader.addProperty(RDFS.label, "Experiment: " + mex.getExperiment().getId()); } if (StringUtils.isNotEmpty(mex.getExperiment().getTitle()) && StringUtils.isNotBlank(mex.getExperiment().getTitle())) { _expHeader.addProperty(DCTerms.title, mex.getExperiment().getTitle()); } if (mex.getExperiment().getDate() != null) { DateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); try { df.setLenient(false); df.parse(mex.getExperiment().getDate().toString()); _expHeader.addProperty(DCTerms.date, new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z") .format(mex.getExperiment().getDate())); } catch (ParseException e) { } } if (StringUtils.isNotEmpty(mex.getExperiment().getAttributeSelectionDescription()) && StringUtils.isNotBlank(mex.getExperiment().getAttributeSelectionDescription())) { _expHeader.addProperty(MEXCORE_10.attributeSelectionDescription, mex.getExperiment().getAttributeSelectionDescription()); } if (StringUtils.isNotEmpty(mex.getExperiment().getDataNormalizedDescription()) && StringUtils.isNotBlank(mex.getExperiment().getDataNormalizedDescription())) { _expHeader.addProperty(MEXCORE_10.dataNormalizedDescription, mex.getExperiment().getDataNormalizedDescription()); } if (StringUtils.isNotEmpty(mex.getExperiment().getNoiseRemovedDescription()) && StringUtils.isNotBlank(mex.getExperiment().getNoiseRemovedDescription())) { _expHeader.addProperty(MEXCORE_10.noiseRemovedDescription, mex.getExperiment().getNoiseRemovedDescription()); } if (StringUtils.isNotEmpty(mex.getExperiment().getOutliersRemovedDescription()) && StringUtils.isNotBlank(mex.getExperiment().getOutliersRemovedDescription())) { _expHeader.addProperty(MEXCORE_10.outliersRemovedDescription, mex.getExperiment().getOutliersRemovedDescription()); } if (StringUtils.isNotEmpty(mex.getExperiment().getDescription()) && StringUtils.isNotBlank(mex.getExperiment().getDescription())) { _expHeader.addProperty(DCTerms.description, mex.getExperiment().getDescription()); } if (mex.getApplicationContext() != null) { _expHeader.addProperty(PROVO.wasAttributedTo, _application); } } //EXPERIMENT CONFIGURATIONS if (mex.getExperimentConfigurations() != null) { int auxExpConf = 0; for (Iterator<ExperimentConfigurationVO> i = mex.getExperimentConfigurations().iterator(); i .hasNext();) { ExperimentConfigurationVO item = i.next(); Resource _expConfiguration = model.createResource(item.getIndividualName()) .addProperty(RDF.type, mexcore_EXP_CONF).addProperty(PROVO.wasStartedBy, _expHeader) .addProperty(RDFS.label, item.getLabel()); if (StringUtils.isNotEmpty(item.getId()) && StringUtils.isNotBlank(item.getId())) { _expConfiguration.addProperty(DCTerms.identifier, item.getId()); } if (StringUtils.isNotEmpty(item.getDescription()) && StringUtils.isNotBlank(item.getDescription())) { _expConfiguration.addProperty(DCTerms.description, item.getDescription()); } //MODEL if (item.Model() != null && item.Model().hasValue()) { String auxIN = objectCreatedBefore(item.Model(), auxExpConf, mex.getExperimentConfigurations()); Resource _model; if (StringUtils.isEmpty(auxIN)) { _model = model.createResource(item.Model().getIndividualName()).addProperty(RDF.type, mexcore_MODEL); if (StringUtils.isNotBlank(item.Model().getId()) && StringUtils.isNotEmpty(item.Model().getId())) { _model.addProperty(DCTerms.identifier, item.Model().getId()); } if (StringUtils.isNotBlank(item.Model().getDescription()) && StringUtils.isNotEmpty(item.Model().getDescription())) { _model.addProperty(DCTerms.description, item.Model().getDescription()); } if (item.Model().getDate() != null) { _model.addProperty(DCTerms.date, item.Model().getDate().toString()); } } else { _model = model.getResource(auxIN); } _expConfiguration.addProperty(PROVO.used, _model); } //TOOL Resource _imp = null; if (item.Tool() != null && item.Tool().hasValue()) { if (StringUtils.isNotBlank(item.Tool().getName()) && StringUtils.isNotEmpty(item.Tool().getName())) { String auxIN = objectCreatedBefore(item.Tool(), auxExpConf, mex.getExperimentConfigurations()); Resource _tool; if (StringUtils.isEmpty(auxIN)) { _tool = model.createResource(MEXALGO_10.NS + item.Tool().getName()); _imp = model.createResource(item.Tool().getIndividualName()) .addProperty(RDFS.label, setLabelSplitingTerms(item.Tool().getName())) .addProperty(RDF.type, _tool); } else { _imp = model.getResource(auxIN); } _expConfiguration.addProperty(PROVO.used, _imp); } //TOOL PARAMETER if (item.getToolParameters() != null && item.getToolParameters().size() > 0) { //COLLECTION Resource _toolcollection = model .createResource(URIbase + "exp_cf_" + (auxExpConf + 1) + "_" + mex.getUserHash() + "_tool_param_collection") .addProperty(RDF.type, mexalgo_TOOL_PARAM_COLLECTION) .addProperty(RDFS.label, "Tool Parameter Collection"); _expConfiguration.addProperty(PROVO.used, _toolcollection); //TOOL PARAMETER //int auxtoolp = 0; for (Iterator<ToolParameterVO> iparam = item.getToolParameters().iterator(); iparam .hasNext();) { ToolParameterVO toolParam = iparam.next(); String auxIN = objectCreatedBefore(toolParam, auxExpConf, mex.getExperimentConfigurations()); Resource _toolParam; if (StringUtils.isEmpty(auxIN)) { _toolParam = model.createResource(toolParam.getIndividualName()) .addProperty(RDF.type, mexalgo_TOOL_PARAM) .addProperty(RDFS.label, toolParam.getLabel()) .addProperty(PROVO.value, toolParam.getValue()) .addProperty(DCTerms.identifier, toolParam.getId()); } else { _toolParam = model.getResource(auxIN); } _imp.addProperty(MEXALGO_10.hasToolParameter, _toolParam); _toolcollection.addProperty(PROVO.hadMember, _toolParam); //auxtoolp++; } } } //SAMPLING METHOD if (item.SamplingMethod() != null && item.SamplingMethod().hasValue()) { String auxIN = objectCreatedBefore(item.SamplingMethod(), auxExpConf, mex.getExperimentConfigurations()); Resource _sampling; if (StringUtils.isEmpty(auxIN)) { Resource mexcore_SAMPLING_METHOD = model .createResource(MEXCORE_10.NS + item.SamplingMethod().getClassName()); _sampling = model.createResource(item.SamplingMethod().getIndividualName()) .addProperty(RDFS.label, item.SamplingMethod().getLabel()) .addProperty(RDF.type, mexcore_SAMPLING_METHOD); if (item.SamplingMethod().getFolds() != null && StringUtils.isNotBlank(item.SamplingMethod().getFolds().toString()) && StringUtils.isNotEmpty(item.SamplingMethod().getFolds().toString())) { _sampling.addProperty(MEXCORE_10.folds, item.SamplingMethod().getFolds().toString()); } if (item.SamplingMethod().getSequential() != null && StringUtils.isNotBlank(item.SamplingMethod().getSequential().toString()) && StringUtils.isNotEmpty(item.SamplingMethod().getSequential().toString())) { _sampling.addProperty(MEXCORE_10.sequential, item.SamplingMethod().getSequential().toString()); } if (item.SamplingMethod().getTrainSize() != null && StringUtils.isNotBlank(item.SamplingMethod().getTrainSize().toString()) && StringUtils.isNotEmpty(item.SamplingMethod().getTrainSize().toString())) { _sampling.addProperty(MEXCORE_10.trainSize, item.SamplingMethod().getTrainSize().toString()); } if (item.SamplingMethod().getTestSize() != null && StringUtils.isNotBlank(item.SamplingMethod().getTestSize().toString()) && StringUtils.isNotEmpty(item.SamplingMethod().getTestSize().toString())) { _sampling.addProperty(MEXCORE_10.testSize, item.SamplingMethod().getTestSize().toString()); } } else { _sampling = model.getResource(auxIN); } _expConfiguration.addProperty(PROVO.used, _sampling); } //HARDWARE CONFIGURATION if (item.HardwareConfiguration() != null && item.HardwareConfiguration().hasValue()) { String auxIN = objectCreatedBefore(item.HardwareConfiguration(), auxExpConf, mex.getExperimentConfigurations()); Resource _hardware; if (StringUtils.isEmpty(auxIN)) { _hardware = model.createResource(item.HardwareConfiguration().getIndividualName()) .addProperty(RDF.type, mexcore_HARDWARE); if (StringUtils.isNotBlank(item.HardwareConfiguration().getOs()) && StringUtils.isNotEmpty(item.HardwareConfiguration().getOs())) { _hardware.addProperty(DOAP.os, item.HardwareConfiguration().getOs()); } if (StringUtils.isNotBlank(item.HardwareConfiguration().getCache()) && StringUtils.isNotEmpty(item.HardwareConfiguration().getCache())) { _hardware.addProperty(MEXCORE_10.cache, item.HardwareConfiguration().getCache()); } if (StringUtils.isNotBlank(item.HardwareConfiguration().getCPU()) && StringUtils.isNotEmpty(item.HardwareConfiguration().getCPU())) { _hardware.addProperty(MEXCORE_10.cpu, item.HardwareConfiguration().getCPU()); } if (StringUtils.isNotBlank(item.HardwareConfiguration().getMemory()) && StringUtils.isNotEmpty(item.HardwareConfiguration().getMemory())) { _hardware.addProperty(MEXCORE_10.memory, item.HardwareConfiguration().getMemory()); } if (StringUtils.isNotBlank(item.HardwareConfiguration().getHD()) && StringUtils.isNotEmpty(item.HardwareConfiguration().getHD())) { _hardware.addProperty(MEXCORE_10.hd, item.HardwareConfiguration().getHD()); } if (StringUtils.isNotBlank(item.HardwareConfiguration().getVideo()) && StringUtils.isNotEmpty(item.HardwareConfiguration().getVideo())) { _hardware.addProperty(MEXCORE_10.video, item.HardwareConfiguration().getVideo()); } _hardware.addProperty(RDFS.label, item.HardwareConfiguration().getLabel()); } else { _hardware = model.getResource(auxIN); } _expConfiguration.addProperty(PROVO.used, _hardware); } //DATASET if (item.DataSet() != null && item.DataSet().hasValue()) { String auxIN = objectCreatedBefore(item.DataSet(), auxExpConf, mex.getExperimentConfigurations()); Resource _dataset; if (StringUtils.isEmpty(auxIN)) { _dataset = model.createResource(item.DataSet().getIndividualName()) .addProperty(RDFS.label, "Dataset " + item.DataSet().getLabel()) .addProperty(RDF.type, mexcore_DATASET); if (StringUtils.isNotBlank(item.DataSet().getName()) && StringUtils.isNotEmpty(item.DataSet().getName())) { _dataset.addProperty(DCTerms.title, item.DataSet().getName()); } if (StringUtils.isNotBlank(item.DataSet().getDescription()) && StringUtils.isNotEmpty(item.DataSet().getDescription())) { _dataset.addProperty(DCTerms.description, item.DataSet().getDescription()); } if (StringUtils.isNotBlank(item.DataSet().getURI()) && StringUtils.isNotEmpty(item.DataSet().getURI())) { _dataset.addProperty(DCAT.landingPage, item.DataSet().getURI()); } } else { _dataset = model.getResource(auxIN); } _expConfiguration.addProperty(PROVO.used, _dataset); } //FEATURE COLLECTION if (item.getFeatures() != null && item.getFeatures().size() > 0) { Resource _featurecollection = model .createResource( URIbase + "fea_col" + "_cf_" + (auxExpConf + 1) + "_" + mex.getUserHash()) .addProperty(RDF.type, mexcore_FEATURE_COLLECTION) .addProperty(RDFS.label, "Feature Collection"); _expConfiguration.addProperty(PROVO.used, _featurecollection); //FEATURE int auxf = 1; for (Iterator<FeatureVO> ifeature = item.getFeatures().iterator(); ifeature.hasNext();) { FeatureVO f = ifeature.next(); if (f != null) { Resource _feature = model.createResource(f.getIndividualName()) .addProperty(RDF.type, mexcore_FEATURE); if (StringUtils.isNotBlank(f.getId()) && StringUtils.isNotEmpty(f.getId())) { _feature.addProperty(DCTerms.identifier, f.getId()); } if (StringUtils.isNotBlank(f.getName()) && StringUtils.isNotEmpty(f.getName())) { _feature.addProperty(RDFS.label, f.getName()); } //_expConfiguration.addProperty(PROVO.used, _feature); auxf++; _featurecollection.addProperty(PROVO.hadMember, _feature); } } } //EXECUTIONS (e) if (item.getExecutions() != null && item.getExecutions().size() > 0) { int auxexecutions = 1; for (Iterator<Execution> iexec = item.getExecutions().iterator(); iexec.hasNext();) { Execution e = iexec.next(); Resource _exec = null; if (e != null) { _exec = model.createResource(e.getIndividualName()); //EXECUTION Resource mexcore_EXEC = null; if (e instanceof ExecutionIndividualVO) { mexcore_EXEC = model.createResource( MEXCORE_10.NS + MEXCORE_10.ClasseTypes.EXECUTION_SINGLE); _exec.addProperty(RDF.type, mexcore_EXEC); _exec.addProperty(RDFS.label, "Single Execution: " + e.getId()); } else if (e instanceof ExecutionSetVO) { mexcore_EXEC = model.createResource( MEXCORE_10.NS + MEXCORE_10.ClasseTypes.EXECUTION_OVERALL); _exec.addProperty(RDF.type, mexcore_EXEC); _exec.addProperty(RDFS.label, "Overall Execution: " + e.getId()); } else { throw new Exception("Execution type unknown!"); } _exec.addProperty(PROVO.id, e.getId()); if (e.getErrorMessage() != null) { _exec.addProperty(MEXCORE_10.executionErrorMessage, e.getErrorMessage().toString()); } if (e.getStartedAtTime() != null) { _exec.addProperty(PROVO.startedAtTime, e.getStartedAtTime().toString()); } if (e.getEndedAtTime() != null) { _exec.addProperty(PROVO.endedAtTime, e.getEndedAtTime().toString()); } if (e.getTargetClass() != null && StringUtils.isNotEmpty(e.getTargetClass()) && StringUtils.isNotBlank(e.getTargetClass())) { _exec.addProperty(MEXCORE_10.targetClass, e.getTargetClass()); } if (e instanceof ExecutionSetVO) { ExecutionSetVO temp = (ExecutionSetVO) e; if (temp.getStartsAtPosition() != null) { _exec.addProperty(MEXCORE_10.startsAtPosition, temp.getStartsAtPosition()); } if (temp.getEndsAtPosition() != null) { _exec.addProperty(MEXCORE_10.endsAtPosition, temp.getEndsAtPosition()); } _exec.addProperty(MEXCORE_10.group, model.createTypedLiteral("true", XSDDatatype.XSDboolean)); } else { _exec.addProperty(MEXCORE_10.group, model.createTypedLiteral("false", XSDDatatype.XSDboolean)); } //PERFORMANCE MEASURE -> super class, there is no need to create it /* Resource _execPerformance = model.createResource(URIbase + "performanceMeasures_" + auxe + "_conf_" + auxExpConf + "_" + this.userHash) //.addProperty(RDF.type, provActivity) .addProperty(RDF.type, mexperf_PERFORMANCE_MEASURE) .addProperty(RDFS.label, "The performance measures generated by an execution") .addProperty(PROVO.wasInformedBy, _exec); */ //PHASE if (e.getPhase() != null) { //is there a similar resource in the list? String auxIN = objectCreatedBefore(e.getPhase(), auxExpConf, mex.getExperimentConfigurations()); Resource _phase; if (StringUtils.isEmpty(auxIN)) { Resource mexcore_PHASE = model .createResource(MEXCORE_10.NS + e.getPhase().getName()); if (StringUtils.isNotBlank(e.getPhase().getName().toString()) && StringUtils.isNotEmpty(e.getPhase().getName().toString())) { //creating resource _phase = model.createResource(e.getPhase().getIndividualName()) .addProperty(RDFS.label, e.getPhase().getLabel()) .addProperty(RDF.type, mexcore_PHASE); _exec.addProperty(PROVO.used, _phase); } } else { _phase = model.getResource(auxIN); _exec.addProperty(PROVO.used, _phase); } } //} //esse aqui sai??? //EXAMPLE COLLECTION if (e.getExamples() != null && e.getExamples().size() > 0) { Resource _examplecollection = model .createResource(URIbase + "exa_col_" + "_cf_" + (auxExpConf + 1) + "_exe_" + String.valueOf(auxexecutions) + "_" + mex.getUserHash()) .addProperty(RDF.type, mexcore_EXAMPLE_COLLECTION) .addProperty(RDFS.label, "Example Collection"); _exec.addProperty(PROVO.used, _examplecollection); //EXAMPLE Integer auxex = 1; for (Iterator<ExampleVO> iexample = e.getExamples().iterator(); iexample .hasNext();) { ExampleVO example = iexample.next(); if (example != null) { Resource _ex = model.createResource(example.getIndividualName()) .addProperty(RDFS.label, "Dataset Example " + example.getId()) .addProperty(RDF.type, mexcore_EXAMPLE) .addProperty(DCTerms.identifier, example.getId()) .addProperty(PROVO.value, example.getValue()); if (example.getDatasetColumn() != 0) { _ex.addProperty(MEXCORE_10.datasetColumn, String.valueOf(example.getDatasetColumn())); } if (example.getDatasetRow() != 0) { _ex.addProperty(MEXCORE_10.datasetRow, String.valueOf(example.getDatasetRow())); } if (StringUtils.isNotEmpty(example.getExampleType())) { _ex.addProperty(MEXCORE_10.exampleType, String.valueOf(example.getExampleType())); } //_exec.addProperty(PROVO.used, _ex); _examplecollection.addProperty(PROVO.hadMember, _ex); auxex++; } } } //ALGORITHM if (e.getAlgorithm() != null) { Resource _alg = model.createResource(e.getAlgorithm().getIndividualName()) .addProperty(RDF.type, mexalgo_ALGO); if (StringUtils.isNotBlank(e.getAlgorithm().getClassName()) && StringUtils.isNotEmpty(e.getAlgorithm().getClassName())) { Resource _algClass = model .createResource(MEXALGO_10.NS + e.getAlgorithm().getClassName()); _algClass.addProperty(RDFS.label, setLabelSplitingTerms(e.getAlgorithm().getClassName())); _alg.addProperty(MEXALGO_10.hasAlgorithmClass, _algClass); _alg.addProperty(RDFS.label, setLabelSplitingTerms(e.getAlgorithm().getClassName())); } else { //label if (StringUtils.isNotBlank(e.getAlgorithm().getLabel()) && StringUtils.isNotEmpty(e.getAlgorithm().getLabel())) { _alg.addProperty(RDFS.label, e.getAlgorithm().getLabel()); } } _exec.addProperty(PROVO.used, _alg); //id if (StringUtils.isNotBlank(e.getAlgorithm().getIdentifier()) && StringUtils.isNotEmpty(e.getAlgorithm().getIdentifier())) { _alg.addProperty(DCTerms.identifier, e.getAlgorithm().getIdentifier()); } //uri if (e.getAlgorithm().getURI() != null && StringUtils.isNotBlank(e.getAlgorithm().getURI().toURL().toString()) && StringUtils .isNotEmpty(e.getAlgorithm().getURI().toURL().toString())) { _alg.addProperty(DCAT.landingPage, e.getAlgorithm().getURI().toURL().toString()); } //acronym if (StringUtils.isNotBlank(e.getAlgorithm().getAcronym()) && StringUtils.isNotEmpty(e.getAlgorithm().getAcronym())) { _alg.addProperty(MEXALGO_10.acronym, e.getAlgorithm().getAcronym()); } _exec.addProperty(PROVO.used, _alg); //HYPER PARAMETER if (e.getAlgorithm().getParameters() != null && e.getAlgorithm().getParameters().size() > 0) { //COLLECTION Resource _hypercollection = model .createResource(URIbase + "hyperp_col" + "cf" + (auxExpConf + 1) + "_" + mex.getUserHash()) .addProperty(RDF.type, mexalgo_HYPER_PARAM_COLLECTION) .addProperty(RDFS.label, "HyperParameter Collection"); _exec.addProperty(PROVO.used, _hypercollection); for (Iterator<HyperParameterVO> iparam = e.getAlgorithm().getParameters() .iterator(); iparam.hasNext();) { HyperParameterVO algoParam = iparam.next(); if (algoParam != null) { Resource _algoParam = null; _algoParam = model.createResource(algoParam.getIndividualName()) .addProperty(RDF.type, mexalgo_HYPER_PARAM) .addProperty(RDFS.label, algoParam.getLabel()) .addProperty(PROVO.value, algoParam.getValue()) .addProperty(DCTerms.identifier, algoParam.getIdentifier()); _alg.addProperty(MEXALGO_10.hasHyperParameter, _algoParam); _hypercollection.addProperty(PROVO.hadMember, _algoParam); } } } } //PERFORMANCES if (e.getPerformances() != null && e.getPerformances().size() > 0) { //Integer auxmea = 1; //COMMON MEASURES for (Iterator<Measure> imea = e.getPerformances().iterator(); imea.hasNext();) { Measure mea = imea.next(); if (mea != null) { Resource mexperf_klass = null, mexperf_cla = null, mexperf_reg = null, mexperf_clu = null, mexperf_sta = null, mexperf_custom = null, mexperf_example = null; Resource mexperf_ins = null, mexperf_cla_ins = null, mexperf_reg_ins = null, mexperf_clu_ins = null, mexperf_sta_ins = null, mexperf_custom_ins = null, mexperf_example_ins = null; if (mea instanceof ClassificationMeasureVO) { if (mexperf_cla == null) { mexperf_cla_ins = model.createResource(mea.getIndividualName()); mexperf_cla = model.createResource(MEXPERF_10.NS + MEXPERF_10.ClasseTypes.CLASSIFICATION_MEASURE); } mexperf_klass = mexperf_cla; mexperf_ins = mexperf_cla_ins; } else if (mea instanceof RegressionMeasureVO) { if (mexperf_reg == null) { mexperf_reg_ins = model.createResource(mea.getIndividualName()); mexperf_reg = model.createResource(MEXPERF_10.NS + MEXPERF_10.ClasseTypes.REGRESSION_MEASURE); } mexperf_klass = mexperf_reg; mexperf_ins = mexperf_reg_ins; } else if (mea instanceof ClusteringMeasureVO) { if (mexperf_clu == null) { mexperf_clu_ins = model.createResource(mea.getIndividualName()); mexperf_clu = model.createResource(MEXPERF_10.NS + MEXPERF_10.ClasseTypes.CLUSTERING_MEASURE); } mexperf_klass = mexperf_clu; mexperf_ins = mexperf_clu_ins; } else if (mea instanceof StatisticalMeasureVO) { if (mexperf_sta == null) { mexperf_sta_ins = model.createResource(mea.getIndividualName()); mexperf_sta = model.createResource(MEXPERF_10.NS + MEXPERF_10.ClasseTypes.STATISTICAL_MEASURE); } mexperf_klass = mexperf_sta; mexperf_ins = mexperf_sta_ins; } mexperf_ins.addProperty(RDF.type, mexperf_klass); mexperf_ins.addProperty(RDFS.label, mea.getLabel()); mexperf_ins.addProperty( model.createProperty(MEXPERF_10.NS + mea.getName()), model.createTypedLiteral(mea.getValue())); mexperf_ins.addProperty(PROVO.wasGeneratedBy, _exec); _exec.addProperty(PROVO.generated, mexperf_ins); } } //OTHER MEASURES - EXAMPLE PERFORMANCE MEASURE List<Measure> examplePerformanceList = e .getPerformances(ExamplePerformanceMeasureVO.class); if (examplePerformanceList != null && examplePerformanceList.size() > 0) { Resource _examplePerformanceCollection = model .createResource(URIbase + "exa_perf_col" + "_cf_" + (auxExpConf + 1) + "_" + mex.getUserHash()) .addProperty(RDF.type, mexperf_EXAMPLE_PERFORMANCE_COLLECTION) .addProperty(RDFS.label, "Dataset Example Performance") .addProperty(PROVO.wasGeneratedBy, _exec); _exec.addProperty(PROVO.generated, _examplePerformanceCollection); int auxep = 1; for (Iterator<Measure> iexpm = examplePerformanceList.iterator(); iexpm .hasNext();) { ExamplePerformanceMeasureVO epm = (ExamplePerformanceMeasureVO) iexpm .next(); if (epm != null) { Resource _examplePerf = model .createResource(epm.getIndividualName()) .addProperty(RDF.type, mexperf_EXAMPLE_PERFORMANCE_MEASURE); if (StringUtils.isNotBlank(epm.getId()) && StringUtils.isNotEmpty(epm.getId())) { _examplePerf.addProperty(DCTerms.identifier, epm.getId()); } if (StringUtils.isNotBlank(epm.getPredictedValue()) && StringUtils.isNotEmpty(epm.getPredictedValue())) { _examplePerf.addProperty(MEXPERF_10.predictedValue, epm.getPredictedValue()); } if (StringUtils.isNotBlank(epm.getRealValue()) && StringUtils.isNotEmpty(epm.getRealValue())) { _examplePerf.addProperty(MEXPERF_10.realValue, epm.getRealValue()); } auxep++; _examplePerformanceCollection.addProperty(PROVO.hadMember, _examplePerf); } } } //OTHER MEASURES - USER DEFINED MEASURE List<Measure> UserDefinedList = e.getPerformances(UserDefinedMeasureVO.class); if (UserDefinedList != null && UserDefinedList.size() > 0) { Resource _userDefinedCollection = model .createResource(URIbase + "userdef_perf_col" + "_cf_" + (auxExpConf + 1) + "_" + mex.getUserHash()) .addProperty(RDF.type, mexperf_USER_DEFINED_PERFORMANCE_COLLECTION) .addProperty(PROVO.wasGeneratedBy, _exec); _exec.addProperty(PROVO.generated, _userDefinedCollection); int auxudf = 1; for (Iterator<Measure> iexpm = UserDefinedList.iterator(); iexpm .hasNext();) { UserDefinedMeasureVO udm = (UserDefinedMeasureVO) iexpm.next(); if (udm != null) { Resource _userdefPerf = model .createResource(udm.getIndividualName()) .addProperty(RDF.type, mexperf_USER_DEFINED_PERFORMANCE_MEASURE) .addProperty(RDFS.label, "User Defined Measure"); if (StringUtils.isNotBlank(udm.getId()) && StringUtils.isNotEmpty(udm.getId())) { _userdefPerf.addProperty(DCTerms.identifier, udm.getId()); } if (StringUtils.isNotBlank(udm.getValue().toString()) && StringUtils.isNotEmpty(udm.getValue().toString())) { _userdefPerf.addProperty(PROVO.value, udm.getValue().toString()); } if (StringUtils.isNotBlank(udm.getDescription()) && StringUtils.isNotEmpty(udm.getDescription())) { _userdefPerf.addProperty(DCTerms.description, udm.getDescription()); } if (StringUtils.isNotBlank(udm.getFormula()) && StringUtils.isNotEmpty(udm.getFormula())) { _userdefPerf.addProperty(MEXPERF_10.formula, udm.getFormula()); } auxudf++; _userDefinedCollection.addProperty(PROVO.hadMember, _userdefPerf); } } } //PERFORMANCES - FOR } //PERFORMANCES - NOT NULL } // EXECUTION - NOT NULL auxexecutions++; _exec.addProperty(PROVO.wasInformedBy, _expConfiguration); } // EXECUTIONS - FOR } //EXECUTIONS - NOT NULL auxExpConf++; } //EXPERIMENT CONFIGURATION - FOR } //EXPERIMENT CONFIGURATION - NOT NULL FileWriter out; out = new FileWriter(filename + "." + format.toString().toLowerCase().replace("/", "").replace(".", "").replace("-", "")); model.write(out, format.toString()); out.close(); } catch (Exception e) { LOGGER.error(e.toString()); throw (e); } }
From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java
private Object doConvertToDate(Map<String, Object> context, Object value, Class toType) { Date result = null;/*from w ww. ja v a 2s .c o m*/ if (value instanceof String && value != null && ((String) value).length() > 0) { String sa = (String) value; Locale locale = getLocale(context); DateFormat df = null; if (java.sql.Time.class == toType) { df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale); } else if (java.sql.Timestamp.class == toType) { Date check = null; SimpleDateFormat dtfmt = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, locale); SimpleDateFormat fullfmt = new SimpleDateFormat(dtfmt.toPattern() + MILLISECOND_FORMAT, locale); SimpleDateFormat dfmt = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale); SimpleDateFormat[] fmts = { fullfmt, dtfmt, dfmt }; for (SimpleDateFormat fmt : fmts) { try { check = fmt.parse(sa); df = fmt; if (check != null) { break; } } catch (ParseException ignore) { } } } else if (java.util.Date.class == toType) { Date check = null; DateFormat[] dfs = getDateFormats(locale); for (DateFormat df1 : dfs) { try { check = df1.parse(sa); df = df1; if (check != null) { break; } } catch (ParseException ignore) { } } } //final fallback for dates without time if (df == null) { df = DateFormat.getDateInstance(DateFormat.SHORT, locale); } try { df.setLenient(false); // let's use strict parsing (XW-341) result = df.parse(sa); if (!(Date.class == toType)) { try { Constructor constructor = toType.getConstructor(new Class[] { long.class }); return constructor.newInstance(new Object[] { Long.valueOf(result.getTime()) }); } catch (Exception e) { throw new XWorkException( "Couldn't create class " + toType + " using default (long) constructor", e); } } } catch (ParseException e) { throw new XWorkException("Could not parse date", e); } } else if (Date.class.isAssignableFrom(value.getClass())) { result = (Date) value; } return result; }