org.apache.commons.collections4.map.CaseInsensitiveMap Java Examples

The following examples show how to use org.apache.commons.collections4.map.CaseInsensitiveMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ComProfileFieldDaoImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<ProfileField> getProfileFields(@VelocityCheck int companyID) throws Exception {
	if (companyID <= 0) {
		return null;
	} else {
		CaseInsensitiveMap<String, ComProfileField> comProfileFieldMap = getComProfileFieldsMap(companyID, false);
		List<ComProfileField> comProfileFieldList = new ArrayList<>(comProfileFieldMap.values());
		
		// Sort by SortingIndex or shortname
		sortComProfileList(comProfileFieldList);

		// Convert from List<ComProfileField> to List<ProfileField>
		List<ProfileField> returnList = new ArrayList<>();
		returnList.addAll(comProfileFieldList);
		
		return returnList;
	}
}
 
Example #2
Source File: UserFormExecutionServiceImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * For user form that requires error handling adds the error messages (including velocity errors) to response context.
 *
 * @param params
 * @param responseContent html content to be sent in response (could be changed inside the method).
 * @return responseContent
 * @throws Exception
 */
protected String handleEndActionErrors(UserForm userForm, CaseInsensitiveMap<String, Object> params, String responseContent) throws Exception {
	if (userForm != null && userForm.isSuccessUseUrl()) {
		// no error handling, return original content
		return responseContent;
	}
	
	if (params.get("velocity_error") != null) {
		responseContent += "<br/><br/>";
		responseContent += params.get("velocity_error");
	}
	
	if (params.get("errors") != null) {
		responseContent += "<br/>";
		ActionErrors velocityErrors = ((ActionErrors) params.get("errors"));
		@SuppressWarnings("rawtypes")
		Iterator it = velocityErrors.get();
		while (it.hasNext()) {
			responseContent += "<br/>" + it.next();
		}
	}
	
	return responseContent;
}
 
Example #3
Source File: ActionOperationSubscribeCustomerImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private final void identifyRecipientByKeyColumn(final Recipient recipient, final ActionOperationSubscribeCustomerParameters op, final CaseInsensitiveMap<String, Object> reqParams, final EmmActionOperationErrors actionOperationErrors, final HttpServletRequest request) {
	if (op.isDoubleCheck()) {
		if (op.getKeyColumn() == null) {
			logger.error(String.format("Exception: No keyColumn (%s)", request == null ? "" : request.getQueryString()));
			actionOperationErrors.addErrorCode(ErrorCode.MISSING_KEY_COLUMN);
		} else {
			final String keyVal = (String) reqParams.get(op.getKeyColumn());
			if (keyVal == null) {
				logger.error(String.format("Exception: No keyVal for '%s' (%s)", op.getKeyColumn(), request == null ? "" : request.getQueryString()));
				for (Entry<String, Object> entry : reqParams.entrySet()) {
					logger.error(entry.getKey() + ": " + entry.getValue().toString());
				}
				actionOperationErrors.addErrorCode(ErrorCode.MISSING_KEY_VALUE);
			} else {
				recipient.findByKeyColumn(op.getKeyColumn(), keyVal);
			}
		}
	}
}
 
Example #4
Source File: UserFormExecutionServiceImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private String createDirectLinkWithOptionalExtensions(String uidString, ComTrackableUserFormLink comTrackableUserFormLink) throws UIDParseException, InvalidUIDException, DeprecatedUIDVersionException, UnsupportedEncodingException {
	String linkString = comTrackableUserFormLink.getFullUrl();
	CaseInsensitiveMap<String, Object> cachedRecipientData = null;
	for (LinkProperty linkProperty : comTrackableUserFormLink.getProperties()) {
		if (linkProperty.getPropertyType() == PropertyType.LinkExtension) {
			String propertyValue = linkProperty.getPropertyValue();
			if (propertyValue != null && propertyValue.contains("##")) {
				if (cachedRecipientData == null && StringUtils.isNotBlank(uidString)) {
					final ComExtensibleUID uid = decodeUidString(uidString);
					cachedRecipientData = recipientDao.getCustomerDataFromDb(uid.getCompanyID(), uid.getCustomerID());
					cachedRecipientData.put("mailing_id", uid.getMailingID());
				}
				// Replace customer and form placeholders
				@SuppressWarnings("unchecked")
				String replacedPropertyValue = AgnUtils.replaceHashTags(propertyValue, cachedRecipientData);
				propertyValue = replacedPropertyValue;
			}
			// Extend link properly (watch out for html-anchors etc.)
			linkString = AgnUtils.addUrlParameter(linkString, linkProperty.getPropertyName(), propertyValue == null ? "" : propertyValue, "UTF-8");
		}
	}
	return linkString;
}
 
Example #5
Source File: ProfileImportWorker.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private void importValidationCheck() throws Exception {
	CaseInsensitiveMap<String, DbColumnType> customerDbFields = importRecipientsDao.getCustomerDbFields(importProfile.getCompanyId());
	Set<String> mappedDbColumns = new HashSet<>();
	for (ColumnMapping mapping : importProfile.getColumnMapping()) {
		if (!ColumnMapping.DO_NOT_IMPORT.equals(mapping.getDatabaseColumn())) {
			if (!customerDbFields.containsKey(mapping.getDatabaseColumn())) {
				throw new ImportException(false, "error.import.dbColumnUnknown", mapping.getDatabaseColumn());
			} else if (!mappedDbColumns.add(mapping.getDatabaseColumn())) {
				throw new ImportException(false, "error.import.dbColumnMappedMultiple", mapping.getDatabaseColumn());
			}
		}
	}

	ImportModeHandler importModeHandler = importModeHandlerFactory.getImportModeHandler(ImportMode.getFromInt(importProfile.getImportMode()).getImportModeHandlerName());
	
	importModeHandler.checkPreconditions(importProfile);
}
 
Example #6
Source File: ComRecipientDaoImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public CaseInsensitiveMap<String, CsvColInfo> readDBColumns(@VelocityCheck int companyID) {
	CaseInsensitiveMap<String, CsvColInfo> dbAllColumns = new CaseInsensitiveMap<>();

	try {
		CaseInsensitiveMap<String, DbColumnType> columnTypes = DbUtilities.getColumnDataTypes(getDataSource(), getCustomerTableName(companyID));

		for (String columnName : columnTypes.keySet()) {
			if (!columnName.equalsIgnoreCase("change_date") && !columnName.equalsIgnoreCase("creation_date") && !columnName.equalsIgnoreCase("datasource_id")) {
				DbColumnType type = columnTypes.get(columnName);
				CsvColInfo csvColInfo = new CsvColInfo();

				csvColInfo.setName(columnName);
				csvColInfo.setLength(type.getSimpleDataType() == SimpleDataType.Characters ? type.getCharacterLength() : type.getNumericPrecision());
				csvColInfo.setActive(false);
				csvColInfo.setNullable(type.isNullable());
				csvColInfo.setType(dbTypeToCsvType(type.getSimpleDataType()));

				dbAllColumns.put(columnName, csvColInfo);
			}
		}
	} catch (Exception e) {
		logger.error("readDBColumns (companyID: " + companyID + ")", e);
	}
	return dbAllColumns;
}
 
Example #7
Source File: AgnUtils.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Escapes any HTML sequence in all values in the given map.
 *
 * @param htmlMap
 * @return
 */
public static Map<String, Object> escapeHtmlInValues(Map<String, Object> htmlMap) {
	Map<String, Object> result = new CaseInsensitiveMap<>();

	if (htmlMap != null) {
		for(final Map.Entry<String, Object> entry : htmlMap.entrySet()) {
			final Object value = entry.getValue();

			if (value != null) {
				result.put(entry.getKey(), StringEscapeUtils.escapeHtml4(value.toString()));
			} else {
				result.put(entry.getKey(), null);

				if (logger.isDebugEnabled()) {
					logger.debug("value for key '" + entry.getKey() + "' is null");
				}
			}
		}
	}
	return result;
}
 
Example #8
Source File: ComRecipientDaoImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private void validateCriteriaEquals(List<CriteriaEquals> criteriaEquals, CaseInsensitiveMap<String, ProfileField> customerDBProfileStructure) {
	for (CriteriaEquals criteriaEqualsElement : criteriaEquals) {
		if (!customerDBProfileStructure.containsKey(criteriaEqualsElement.getProfilefield())) {
			throw new IllegalArgumentException("The profile field " + criteriaEqualsElement.getProfilefield() + " does not exist");
		}
	
		ProfileField profileField = customerDBProfileStructure.get(criteriaEqualsElement.getProfilefield());
	
		if ("DATE".equalsIgnoreCase(profileField.getDataType()) && criteriaEqualsElement.getDateformat() == null) {
			throw new IllegalArgumentException("The \"dateformat\" is missing for a date field: " + criteriaEqualsElement.getProfilefield());
		}
	
		if (!"DATE".equalsIgnoreCase(profileField.getDataType()) && criteriaEqualsElement.getDateformat() != null) {
			throw new IllegalArgumentException("The \"dateformat\" is specified for a non-date field: " + criteriaEqualsElement.getProfilefield());
		}
	}
}
 
Example #9
Source File: EmmProfileFieldResolverImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Reads data of all profile fields of given company and extracts essential
 * data.
 * 
 * @param companyId company ID
 * @param dao       DAO accessing profile field data
 * 
 * @return map of profile field short names to essential data
 * 
 * @throws Exception on errors reading or extracting profile field data
 */
private static Map<String, ColumnNameAndType> readProfileFields(int companyId, ComProfileFieldDao dao)
		throws Exception {
	Map<String, ColumnNameAndType> map = new HashMap<>();

	CaseInsensitiveMap<String, ComProfileField> rawMap = dao.getComProfileFieldsMap(companyId, false);
	SimpleDataType simpleType;
	ColumnNameAndType cnat;
	for (ComProfileField field : rawMap.values()) {
		simpleType = DbColumnType.getSimpleDataType(field.getDataType());
		cnat = new ColumnNameAndType(field.getColumn(), DbTypeMapper.mapDbType(simpleType));

		map.put(field.getShortname().toLowerCase(), cnat);
	}

	return map;
}
 
Example #10
Source File: UserFormExecutionServiceImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private final UserFormExecutionResult doExecuteForm(final UserForm userForm, final EmmActionOperationErrors actionOperationErrors, final CaseInsensitiveMap<String, Object> params, final HttpServletRequest request) throws Exception {
	String responseContent = userForm.evaluateForm(applicationContext, params, actionOperationErrors);
	String responseMimeType = determineSuccessResponseMimeType(userForm, params);

	final String uidString = (String) params.get("agnUID");
	responseContent = addRedirectLinks(responseContent, uidString, userForm);
	
	if (params.get("_error") == null) {
		evaluateFormEndAction(request, userForm, params, actionOperationErrors);
		responseContent = handleEndActionErrors(userForm, params, responseContent);
	} else {
		responseMimeType = userForm.getErrorMimetype();
	}

	return new UserFormExecutionResult(responseContent, responseMimeType);
}
 
Example #11
Source File: RecipientServiceImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
@Transactional
@Validate("deleteSubscriber")
public void deleteSubscriber(RecipientModel model, List<UserAction> userActions) {
	final int companyId = model.getCompanyId();
	final int recipientId = model.getCustomerId();
	CaseInsensitiveMap<String, Object> customerData = recipientDao.getCustomerDataFromDb(companyId, recipientId, DEFAULT_COLUMNS);

	if (customerData.isEmpty()) {
		throw new IllegalStateException("Attempt to delete not existing recipient #"
				+ recipientId + " (company #" + companyId + ")");
	}

	recipientDao.deleteRecipients(companyId, Collections.singletonList(recipientId));

	userActions.add(new UserAction("delete recipient", RecipientUtils.getRecipientDescription(customerData)));
}
 
Example #12
Source File: ComProfileFieldDaoImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
public CaseInsensitiveMap<String, ComProfileField> getComProfileFieldsMap(@VelocityCheck int companyID, int adminID, final boolean noNotNullConstraintCheck) throws Exception {
     if (companyID <= 0) {
         return null;
     } else {
CaseInsensitiveMap<String, ComProfileField> comProfileFieldMap = getComProfileFieldsMap(companyID, noNotNullConstraintCheck);
CaseInsensitiveMap<String, ComProfileField> returnMap = new CaseInsensitiveMap<>();
for (ComProfileField comProfileField : comProfileFieldMap.values()) {
	List<ComProfileFieldPermission> profileFieldPermissionList = select(logger, SELECT_PROFILEFIELDPERMISSION, new ComProfileFieldPermission_RowMapper(), companyID, comProfileField.getColumn(), adminID);
         	if (profileFieldPermissionList != null && profileFieldPermissionList.size() > 1) {
 				throw new RuntimeException("Invalid number of permission entries found in getProfileFields: " + profileFieldPermissionList.size());
 			} else if (profileFieldPermissionList != null && profileFieldPermissionList.size() == 1) {
 				comProfileField.setAdminID(adminID);
 				comProfileField.setModeEdit(profileFieldPermissionList.get(0).getModeEdit());
 				returnMap.put(comProfileField.getColumn(), comProfileField);
 			} else {
 				returnMap.put(comProfileField.getColumn(), comProfileField);
 			}
}
return returnMap;
     }
 }
 
Example #13
Source File: RecipientUtils.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
public static Map<String, String> sortDuplicateAnalysisFields(CaseInsensitiveMap<String, ProfileField> columnMap) {
final LinkedHashMap<String, String> fieldsMap = new LinkedHashMap<>();

// we need predefined order for default columns: gender, firstname, lastname.
fieldsMap.put(COLUMN_GENDER, columnMap.get(COLUMN_GENDER).getShortname());
fieldsMap.put(COLUMN_FIRSTNAME, columnMap.get(COLUMN_FIRSTNAME).getShortname());
fieldsMap.put(COLUMN_LASTNAME, columnMap.get(COLUMN_LASTNAME).getShortname());
fieldsMap.put(COLUMN_TIMESTAMP, columnMap.get(COLUMN_TIMESTAMP).getShortname());
fieldsMap.put(COLUMN_CUSTOMER_ID, columnMap.get(COLUMN_CUSTOMER_ID).getShortname());

columnMap.remove(COLUMN_GENDER);
columnMap.remove(COLUMN_FIRSTNAME);
columnMap.remove(COLUMN_LASTNAME);
columnMap.remove(COLUMN_TIMESTAMP);
columnMap.remove(COLUMN_CUSTOMER_ID);

columnMap.forEach((key, value) -> fieldsMap.put(key, value.getShortname()));

MapUtils.reorderLinkedHashMap(fieldsMap, RecipientUtils.getFieldOrderComparator(true));

return fieldsMap;
  }
 
Example #14
Source File: Request.java    From JDA with Apache License 2.0 6 votes vote down vote up
public Request(
        RestActionImpl<T> restAction, Consumer<? super T> onSuccess, Consumer<? super Throwable> onFailure,
        BooleanSupplier checks, boolean shouldQueue, RequestBody body, Object rawBody, long deadline, boolean priority,
        Route.CompiledRoute route, CaseInsensitiveMap<String, String> headers)
{
    this.deadline = deadline;
    this.priority = priority;
    this.restAction = restAction;
    this.onSuccess = onSuccess;
    if (onFailure instanceof ContextException.ContextConsumer)
        this.onFailure = onFailure;
    else if (RestActionImpl.isPassContext())
        this.onFailure = ContextException.here(onFailure);
    else
        this.onFailure = onFailure;
    this.checks = checks;
    this.shouldQueue = shouldQueue;
    this.body = body;
    this.rawBody = rawBody;
    this.route = route;
    this.headers = headers;

    this.api = (JDAImpl) restAction.getJDA();
    this.localReason = ThreadLocalReason.getCurrent();
}
 
Example #15
Source File: RedirectServlet.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private final void executeLinkAction(final int actionID, final int deviceID, final int companyID, final int customerID, final int mailingID, final DeviceClass deviceClass, final HttpServletRequest request) throws Exception {
	if (actionID != 0) {
		// "_request" is the original unmodified request which might be needed (and used) somewhere else ...
		final Map<String, String> tmpRequestParams = AgnUtils.getReqParameters(request);
		tmpRequestParams.put("mobileDevice", String.valueOf(deviceClass == DeviceClass.MOBILE ? deviceID : 0)); // for mobile detection
		
		final EmmActionOperationErrors actionOperationErrors = new EmmActionOperationErrors();
		
		final CaseInsensitiveMap<String, Object> params = new CaseInsensitiveMap<>();
		params.put("requestParameters", tmpRequestParams);
		params.put("_request", request);
		params.put("customerID", customerID);
		params.put("mailingID", mailingID);
		params.put("actionErrors", actionOperationErrors);
		getEmmActionService().executeActions(actionID, companyID, params, actionOperationErrors);
	}
	
}
 
Example #16
Source File: LocationCache.java    From azure-cosmosdb-java with MIT License 6 votes vote down vote up
private UnmodifiableMap<String, URL> getEndpointByLocation(Iterable<DatabaseAccountLocation> locations,
                                                              Utils.ValueHolder<UnmodifiableList<String>> orderedLocations) {
    Map<String, URL> endpointsByLocation = new CaseInsensitiveMap<>();
    List<String> parsedLocations = new ArrayList<>();

    for (DatabaseAccountLocation location: locations) {
        if (!Strings.isNullOrEmpty(location.getName())) {
            try {
                URL endpoint = new URL(location.getEndpoint().toLowerCase());
                endpointsByLocation.put(location.getName().toLowerCase(), endpoint);
                parsedLocations.add(location.getName());

            } catch (Exception e) {
                logger.warn("GetAvailableEndpointsByLocation() - skipping add for location = [{}] as it is location name is either empty or endpoint is malformed [{}]",
                        location.getName(),
                        location.getEndpoint());
            }
        }
    }

    orderedLocations.v = new UnmodifiableList(parsedLocations);
    return (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(endpointsByLocation);
}
 
Example #17
Source File: ComProfileFieldDaoImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
public List<ComProfileField> getComProfileFields(@VelocityCheck int companyID, int adminID, boolean customSorting, final boolean noNotNullConstraintCheck) throws Exception {
	if (companyID <= 0) {
		return null;
	} else {
		CaseInsensitiveMap<String, ComProfileField> comProfileFieldMap = getComProfileFieldsMap(companyID, adminID, noNotNullConstraintCheck);
		List<ComProfileField> comProfileFieldList = new ArrayList<>(comProfileFieldMap.values());

		// Sort by SortingIndex or shortname
           if (customSorting) {
		    sortCustomComProfileList(comProfileFieldList);
           }
           // Sort by shortname (or by column if shortname is empty)
           else {
               sortComProfileList(comProfileFieldList);
           }

		return comProfileFieldList;
	}
}
 
Example #18
Source File: RecipientAction.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Gets the list of recipient fields
 *
 * @param companyId
 *            current company ID
 * @return recipient fields in a form of map: column -> column-shortname
 * @throws Exception
 *             if the exception happens in columnInfoService class
 */
protected Map<String, String> getRecipientFieldsNames(int companyId, int adminId) throws Exception {
	final CaseInsensitiveMap<String, ProfileField> columnInfoMap = columnInfoService.getColumnInfoMap(companyId, adminId);
	final LinkedHashMap<String, String> fieldsMap = new LinkedHashMap<>();
	
	// we need predefined order for default columns: gender, firstname, lastname.
	fieldsMap.put(COLUMN_GENDER, columnInfoMap.get(COLUMN_GENDER).getShortname());
	fieldsMap.put(COLUMN_FIRSTNAME, columnInfoMap.get(COLUMN_FIRSTNAME).getShortname());
	fieldsMap.put(COLUMN_LASTNAME, columnInfoMap.get(COLUMN_LASTNAME).getShortname());
	
	columnInfoMap.remove(COLUMN_GENDER);
	columnInfoMap.remove(COLUMN_FIRSTNAME);
	columnInfoMap.remove(COLUMN_LASTNAME);

	columnInfoMap.forEach((key, value) -> fieldsMap.put(key, value.getShortname()));
	
	MapUtils.reorderLinkedHashMap(fieldsMap, RecipientUtils.getFieldOrderComparator());

	return fieldsMap;
}
 
Example #19
Source File: ComRecipientDaoImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Load structure of Customer-Table for the given Company-ID in member
 * variable "companyID". Load profile data into map. Has to be done before
 * working with customer-data in class instance
 *
 * @return true on success
 */
protected CaseInsensitiveMap<String, ProfileField> loadCustDBProfileStructure(@VelocityCheck int companyID) throws Exception {
	CaseInsensitiveMap<String, ProfileField> custDBStructure = new CaseInsensitiveMap<>();
	for (ProfileField fieldDescription : columnInfoService.getColumnInfos(companyID)) {
		custDBStructure.put(fieldDescription.getColumn(), fieldDescription);
	}
	return custDBStructure;
}
 
Example #20
Source File: ComRecipientDaoImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Find Subscriber by providing a column-name and a value and an customer object. Fills the customer_id of this customer object if found. Only exact matches possible.
 *
 * @return customerID or 0 if no matching record found
 * @param keyColumn
 *			Column-Name
 * @param value
 *			Value to search for in col
 */
@Override
public int findByKeyColumn(Recipient customer, String keyColumn, String value) {
	try {
		CaseInsensitiveMap<String, ProfileField> customerDBProfileStructure = loadCustDBProfileStructure(customer.getCompanyID());
		String keyColumnType = customerDBProfileStructure.get(keyColumn).getDataType();
		if (keyColumnType != null) {
			List<Map<String, Object>> custList;
			if (keyColumnType.toUpperCase().startsWith("VARCHAR") || keyColumnType.equalsIgnoreCase("CHAR")) {
				if ("email".equalsIgnoreCase(keyColumn)) {
					value = AgnUtils.normalizeEmail(value);
					if (!AgnUtils.isEmailValid(value)) {
						throw new Exception("Invalid search value for email key column");
					} else {
						custList = select(logger, "SELECT customer_id FROM " + getCustomerTableName(customer.getCompanyID()) + " cust WHERE email = ? AND " + ComCompanyDaoImpl.STANDARD_FIELD_BOUNCELOAD + " = 0", value == null ? null : value.toLowerCase());
					}
				} else {
					custList = select(logger, "SELECT customer_id FROM " + getCustomerTableName(customer.getCompanyID()) + " cust WHERE LOWER(cust." + SafeString.getSafeDbColumnName(keyColumn) + ") = ? AND " + ComCompanyDaoImpl.STANDARD_FIELD_BOUNCELOAD + " = 0", value == null ? null : value.toLowerCase());
				}
			} else {
				if (AgnUtils.isNumber(value)) {
					int intValue = Integer.parseInt(value);
					custList = select(logger, "SELECT customer_id FROM " + getCustomerTableName(customer.getCompanyID()) + " cust WHERE cust." + SafeString.getSafeDbColumnName(keyColumn) + " = ? AND " + ComCompanyDaoImpl.STANDARD_FIELD_BOUNCELOAD + " = 0", intValue);
				} else {
					throw new Exception("Invalid search value for numeric key column");
				}
			}

			// cannot use queryForInt, because of possible existing duplicates
			if (custList != null && custList.size() > 0) {
				customer.setCustomerID(((Number) custList.get(0).get("customer_id")).intValue());
			} else {
				customer.setCustomerID(0);
			}
		}
	} catch (Exception e) {
		customer.setCustomerID(0);
	}
	return customer.getCustomerID();
}
 
Example #21
Source File: CsvImportExportDescription.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public void prepareColumnMapping(ComReferenceTable table, CaseInsensitiveMap<String, DbColumnType> structure, File importFile) throws Exception {
	List<String> csvColumns;
	try (CsvReader readerForAnalyse = new CsvReader(getImportInputStream(importFile), getEncoding(), getDelimiter(), getStringQuote())) {
		readerForAnalyse.setAlwaysTrim(true);
		csvColumns = readerForAnalyse.readNextCsvLine();
	} catch (Exception e) {
		throw new ImportError(ImportErrorKey.cannotReadImportFile);
	}
	
	if (csvColumns == null) {
		throw new ImportError(ImportErrorKey.emptyImportFile);
	}
		
	String duplicateCsvColumn = CsvReader.checkForDuplicateCsvHeader(csvColumns, autoMapping);
	if (duplicateCsvColumn != null) {
		throw new ImportError(ImportErrorKey.csvContainsInvalidColumn, duplicateCsvColumn);
	}

	String keyColumn = table.getKeyColumn().toLowerCase();

	if (autoMapping || CollectionUtils.isEmpty(columnMapping)) {
		List<ColumnMapping> mappings = new ArrayList<>();

		for (String csvColumn : csvColumns) {
			if (structure.containsKey(csvColumn)) {
				mappings.add(createMapping(csvColumn, csvColumn.toLowerCase(), csvColumn.equalsIgnoreCase(keyColumn)));
			} else {
				throw exceptionCsvInvalidColumn(csvColumn);
			}
		}

		columnMapping = mappings;
	}

	validateColumnMapping(table.isVoucher(), structure, keyColumn, csvColumns);
}
 
Example #22
Source File: RestActionImpl.java    From JDA with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public CompletableFuture<T> submit(boolean shouldQueue)
{
    Route.CompiledRoute route = finalizeRoute();
    Checks.notNull(route, "Route");
    RequestBody data = finalizeData();
    CaseInsensitiveMap<String, String> headers = finalizeHeaders();
    BooleanSupplier finisher = getFinisher();
    return new RestFuture<>(this, shouldQueue, finisher, data, rawData, getDeadline(), priority, route, headers);
}
 
Example #23
Source File: ComProfileFieldDaoImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public CaseInsensitiveMap<String, ProfileField> getProfileFieldsMap(@VelocityCheck int companyID, int adminID, final boolean noNotNullConstraintCheck) throws Exception {
	if (companyID == 0) {
		return null;
	} else {
		CaseInsensitiveMap<String, ComProfileField> comProfileFieldMap = getComProfileFieldsMap(companyID, adminID, noNotNullConstraintCheck);
		CaseInsensitiveMap<String, ProfileField> returnMap = new CaseInsensitiveMap<>();

		for (Entry<String, ComProfileField> entry : comProfileFieldMap.entrySet()) {
			returnMap.put(entry.getKey(), entry.getValue());
		}
		return returnMap;
	}
}
 
Example #24
Source File: LocationCache.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
public DatabaseAccountLocationsInfo(List<String> preferredLocations,
                                    URL defaultEndpoint) {
    this.preferredLocations = new UnmodifiableList<>(preferredLocations.stream().map(loc -> loc.toLowerCase()).collect(Collectors.toList()));
    this.availableWriteEndpointByLocation = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(new CaseInsensitiveMap<>());
    this.availableReadEndpointByLocation = (UnmodifiableMap) UnmodifiableMap.unmodifiableMap(new CaseInsensitiveMap<>());
    this.availableReadLocations = new UnmodifiableList<>(Collections.emptyList());
    this.availableWriteLocations = new UnmodifiableList<>(Collections.emptyList());
    this.readEndpoints = new UnmodifiableList<>(Collections.singletonList(defaultEndpoint));
    this.writeEndpoints = new UnmodifiableList<>(Collections.singletonList(defaultEndpoint));
}
 
Example #25
Source File: ComProfileFieldDaoImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public CaseInsensitiveMap<String, ProfileField> getProfileFieldsMap(@VelocityCheck int companyID) throws Exception {
	if (companyID <= 0) {
		return null;
	} else {
		CaseInsensitiveMap<String, ComProfileField> comProfileFieldMap = getComProfileFieldsMap(companyID);
		CaseInsensitiveMap<String, ProfileField> returnMap = new CaseInsensitiveMap<>();

		for (Entry<String, ComProfileField> entry : comProfileFieldMap.entrySet()) {
			returnMap.put(entry.getKey(), entry.getValue());
		}
		
		return returnMap;
	}
}
 
Example #26
Source File: UserFormExecutionServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public final UserFormExecutionResult executeForm(final int companyID, final String formName, final HttpServletRequest request, CaseInsensitiveMap<String, Object> params, final boolean useSession) throws Exception {
	populateRequestParametersAsVelocityParameters(request, params);

	int deviceID = deviceService.getDeviceId(request.getHeader("User-Agent"));
	DeviceClass deviceClass = deviceService.getDeviceClassForStatistics(deviceID);
	if (deviceID == ComDeviceService.DEVICE_BLACKLISTED_NO_SERVICE) {
		throw new BlacklistedDeviceException();
	}

	final int mobileID = deviceClass == DeviceClass.MOBILE ? deviceID : -1;
	if (mobileID > 0) {
		populateMobileDeviceParametersAsVelocityParameters(mobileID, params, request);
	}

	final int clientID = clientService.getClientId(request.getHeader("User-Agent"));
	final UserForm userForm = loadUserForm(formName, companyID);

	final ComExtensibleUID uid = processUID(request, params, useSession);
	
	logFormAccess(userForm, uid, request.getRemoteAddr(), deviceID, deviceClass, clientID);
	
	final EmmActionOperationErrors actionOperationErrors = populateEmmActionErrorsAsVelocityParameters(params);
	populateFormPropertiesAsVelocityParameters(userForm, params);

	return doExecuteForm(userForm, actionOperationErrors, params, request);
}
 
Example #27
Source File: RecipientForm.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public void clearRecipientData() {
	recipientID = 0;
    gender = 2;
    mailtype = 1;
	title = "";
    firstname = "";
    lastname = "";
    email = "";
    column = new CaseInsensitiveMap<>();
    mailing = new HashMap<>();
}
 
Example #28
Source File: ComProfileFieldDaoImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<ComProfileField> getComProfileFields(int companyID) throws Exception {
	if (companyID <= 0) {
		return null;
	} else {
		CaseInsensitiveMap<String, ComProfileField> comProfileFieldMap = getComProfileFieldsMap(companyID);
		List<ComProfileField> comProfileFieldList = new ArrayList<>(comProfileFieldMap.values());
		
		// Sort by SortingIndex or shortname
		sortComProfileList(comProfileFieldList);
		
		return comProfileFieldList;
	}
}
 
Example #29
Source File: CaseInsensitiveMapUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenCommonsCaseInsensitiveMap_whenSameEntryAdded_thenValueUpdated(){
    Map<String, Integer> commonsHashMap = new CaseInsensitiveMap<>();
    commonsHashMap.put("abc", 1);
    commonsHashMap.put("ABC", 2);

    assertEquals(2, commonsHashMap.get("aBc").intValue());
    assertEquals(2, commonsHashMap.get("ABc").intValue());
}
 
Example #30
Source File: UserFormExecutionServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private final String determineSuccessResponseMimeType(final UserForm userForm, final CaseInsensitiveMap<String, Object> params) {
	final String formMimeType = (String)params.get(FORM_MIMETYPE_PARAM_NAME);

	
	return StringUtils.isNotBlank(formMimeType)
			? formMimeType
			: userForm.getSuccessMimetype();
}