List of usage examples for org.apache.commons.lang StringUtils substringBefore
public static String substringBefore(String str, String separator)
Gets the substring before the first occurrence of a separator.
From source file:com.google.gdt.eclipse.designer.util.Utils.java
/** * Get absolute path to the gwt-dev-windows.jar or gwt-dev-linux.jar * // w ww. j av a 2s . co m * @param project * optional GWT {@link IProject}, if not <code>null</code>, then project-specific * gwt-user.jar may be returned; if <code>null</code>, then workspace-global one. */ public static IPath getDevLibPath(IProject project) { // try to use location of gwt-user.jar { String gwtLocation = getGWTLocation(project); // Maven if (gwtLocation.contains("/gwt/gwt-user/")) { String gwtFolder = StringUtils.substringBefore(gwtLocation, "/gwt-user/"); String versionString = StringUtils.substringAfter(gwtLocation, "/gwt/gwt-user/"); String devFolder = gwtFolder + "/gwt-dev/" + versionString; String devFileName = "gwt-dev-" + versionString + ".jar"; Path path = new Path(devFolder + "/" + devFileName); if (path.toFile().exists()) { return path; } } // gwt-dev in same folder as gwt-user.jar { IPath path = getDevLibPath(gwtLocation); if (path.toFile().exists()) { return path; } } } // use gwt-dev.jar from default GWT location { String gwtLocation = Activator.getGWTLocation(); return getDevLibPath(gwtLocation); } }
From source file:com.device.storefront.controllers.pages.CheckoutController.java
protected String processOrderCode(final String orderCode, final Model model, final HttpServletRequest request, final RedirectAttributes redirectModel) throws CMSItemNotFoundException { final OrderData orderDetails; try {//ww w .j a v a2s .c o m orderDetails = orderFacade.getOrderDetailsForCode(orderCode); } catch (final UnknownIdentifierException e) { LOG.warn( "Attempted to load an order confirmation that does not exist or is not visible. Redirect to home page."); return REDIRECT_PREFIX + ROOT; } if (orderDetails.isGuestCustomer() && !StringUtils.substringBefore(orderDetails.getUser().getUid(), "|") .equals(getSessionService().getAttribute(WebConstants.ANONYMOUS_CHECKOUT_GUID))) { return getCheckoutRedirectUrl(); } if (orderDetails.getEntries() != null && !orderDetails.getEntries().isEmpty()) { for (final OrderEntryData entry : orderDetails.getEntries()) { final String productCode = entry.getProduct().getCode(); final ProductData product = productFacade.getProductForCodeAndOptions(productCode, Arrays.asList(ProductOption.BASIC, ProductOption.PRICE, ProductOption.CATEGORIES)); entry.setProduct(product); } } model.addAttribute("orderCode", orderCode); model.addAttribute("orderData", orderDetails); model.addAttribute("allItems", orderDetails.getEntries()); model.addAttribute("deliveryAddress", orderDetails.getDeliveryAddress()); model.addAttribute("deliveryMode", orderDetails.getDeliveryMode()); model.addAttribute("paymentInfo", orderDetails.getPaymentInfo()); model.addAttribute("pageType", PageType.ORDERCONFIRMATION.name()); processEmailAddress(model, orderDetails); final String continueUrl = (String) getSessionService().getAttribute(WebConstants.CONTINUE_URL); model.addAttribute(CONTINUE_URL_KEY, (continueUrl != null && !continueUrl.isEmpty()) ? continueUrl : ROOT); final AbstractPageModel cmsPage = getContentPageForLabelOrId(CHECKOUT_ORDER_CONFIRMATION_CMS_PAGE_LABEL); storeCmsPageInModel(model, cmsPage); setUpMetaDataForContentPage(model, getContentPageForLabelOrId(CHECKOUT_ORDER_CONFIRMATION_CMS_PAGE_LABEL)); model.addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS, ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW); if (ResponsiveUtils.isResponsive()) { return getViewForPage(model); } return ControllerConstants.Views.Pages.Checkout.CheckoutConfirmationPage; }
From source file:com.amalto.core.delegator.IItemCtrlDelegator.java
public ArrayList<String> viewSearch(DataClusterPOJOPK dataClusterPOJOPK, ViewPOJOPK viewPOJOPK, IWhereItem whereItem, String orderBy, String direction, int start, int limit) throws XtentisException { try {//from ww w. j av a 2s. c o m ViewPOJO view = getViewPOJO(viewPOJOPK); whereItem = Util.fixWebConditions(whereItem, getLocalUser().getUserXML()); // Create an ItemWhere which combines the search and and view wheres ArrayList<IWhereItem> conditions = view.getWhereConditions().getList(); // fix conditions: value of condition do not generate xquery. Util.fixConditions(conditions); // Set User Property conditions. if (Util.isContainUserProperty(conditions)) { Util.updateUserPropertyCondition(conditions, getLocalUser().getUserXML()); } IWhereItem fullWhere = getFullWhereCondition(whereItem, conditions); // Add Filters from the Roles ILocalUser user = getLocalUser(); HashSet<String> roleNames = user.getRoles(); String objectType = "View"; //$NON-NLS-1$ ArrayList<IWhereItem> roleWhereConditions = new ArrayList<IWhereItem>(); for (String roleName : roleNames) { if (SecurityConfig.isSecurityPermission(roleName)) { continue; } // load Role RolePOJO role = ObjectPOJO.load(RolePOJO.class, new RolePOJOPK(roleName)); // get Specifications for the View Object RoleSpecification specification = role.getRoleSpecifications().get(objectType); if (specification != null) { if (!specification.isAdmin()) { Set<String> regexIds = specification.getInstances().keySet(); for (String regexId : regexIds) { if (viewPOJOPK.getIds()[0].matches(regexId)) { HashSet<String> parameters = specification.getInstances().get(regexId) .getParameters(); for (String marshaledWhereCondition : parameters) { if (marshaledWhereCondition == null || marshaledWhereCondition.trim().length() == 0) { continue; } WhereCondition whereCondition = RoleWhereCondition .parse(marshaledWhereCondition).toWhereCondition(); String conditionValue = whereCondition.getRightValueOrPath(); if ((conditionValue != null && conditionValue.length() > 0) || WhereCondition.EMPTY_NULL.equals(whereCondition.getOperator())) { roleWhereConditions.add(whereCondition); } } } } } } } // add collected additional conditions if (roleWhereConditions.size() > 0) { // Set User Property conditions. if (Util.isContainUserProperty(roleWhereConditions)) { Util.updateUserPropertyCondition(roleWhereConditions, getLocalUser().getUserXML()); } IWhereItem normalizedRolesConditions = normalizeConditions(roleWhereConditions); if (fullWhere == null) { fullWhere = normalizedRolesConditions; } else { WhereAnd wAnd = new WhereAnd(); wAnd.add(fullWhere); wAnd.add(normalizedRolesConditions); fullWhere = wAnd; } } // Find revision id for type String typeName = view.getSearchableBusinessElements().getList().get(0).split("/")[0]; //$NON-NLS-1$ // Try to get storage for revision Server server = ServerContext.INSTANCE.get(); String dataModelName = dataClusterPOJOPK.getUniqueId(); StorageAdmin storageAdmin = server.getStorageAdmin(); Storage storage = storageAdmin.get(dataModelName, storageAdmin.getType(dataModelName)); MetadataRepository repository = storage.getMetadataRepository(); boolean isStaging = storage.getType() == StorageType.STAGING; // Build query (from 'main' type) ComplexTypeMetadata type = repository.getComplexType(typeName); if (type == null) { throw new IllegalArgumentException( "Type '" + typeName + "' does not exist in data cluster '" + dataModelName //$NON-NLS-1$ //$NON-NLS-2$ + "'."); //$NON-NLS-1$ } UserQueryBuilder qb = UserQueryBuilder.from(type); // Select fields ArrayListHolder<String> viewableBusinessElements = view.getViewableBusinessElements(); for (String viewableBusinessElement : viewableBusinessElements.getList()) { String viewableTypeName = StringUtils.substringBefore(viewableBusinessElement, "/"); //$NON-NLS-1$ String viewablePath = StringUtils.substringAfter(viewableBusinessElement, "/"); //$NON-NLS-1$ if (viewablePath.isEmpty()) { throw new IllegalArgumentException("View element '" + viewableBusinessElement //$NON-NLS-1$ + "' is invalid: no path to element."); //$NON-NLS-1$ } ComplexTypeMetadata viewableType = repository.getComplexType(viewableTypeName); List<TypedExpression> fields = UserQueryHelper.getFields(viewableType, viewablePath); for (TypedExpression field : fields) { if (isNeedToAddExplicitly(isStaging, field)) { qb.select(field); } } } qb.select(repository.getComplexType(typeName), "../../taskId"); //$NON-NLS-1$ if (isStaging) { qb.select(repository.getComplexType(typeName), "$staging_status$"); //$NON-NLS-1$ qb.select(repository.getComplexType(typeName), "$staging_error$"); //$NON-NLS-1$ qb.select(repository.getComplexType(typeName), "$staging_source$"); //$NON-NLS-1$ } // Condition and paging qb.where(UserQueryHelper.buildCondition(qb, fullWhere, repository)); qb.start(start < 0 ? 0 : start); // UI can send negative start index qb.limit(limit); // Order by if (orderBy != null) { ComplexTypeMetadata orderByType = repository .getComplexType(StringUtils.substringBefore(orderBy, "/")); //$NON-NLS-1$ String orderByFieldName = StringUtils.substringAfter(orderBy, "/"); //$NON-NLS-1$ List<TypedExpression> fields = UserQueryHelper.getFields(orderByType, orderByFieldName); OrderBy.Direction queryDirection; if ("ascending".equals(direction) //$NON-NLS-1$ || "NUMBER:ascending".equals(direction) //$NON-NLS-1$ || "ASC".equals(direction)) { //$NON-NLS-1$ queryDirection = OrderBy.Direction.ASC; } else { queryDirection = OrderBy.Direction.DESC; } for (TypedExpression field : fields) { qb.orderBy(field, queryDirection); } } // Get records ArrayList<String> resultsAsString = new ArrayList<String>(); try { storage.begin(); StorageResults results = storage.fetch(qb.getSelect()); resultsAsString.add("<totalCount>" + results.getCount() + "</totalCount>"); //$NON-NLS-1$ //$NON-NLS-2$ DataRecordWriter writer = new ViewSearchResultsWriter(); ByteArrayOutputStream output = new ByteArrayOutputStream(); for (DataRecord result : results) { try { writer.write(result, output); } catch (IOException e) { throw new XmlServerException(e); } String document = new String(output.toByteArray(), Charset.forName("UTF-8")); //$NON-NLS-1$ resultsAsString.add(document); output.reset(); } storage.commit(); } catch (Exception e) { storage.rollback(); throw new XmlServerException(e); } return resultsAsString; } catch (XtentisException e) { throw (e); } catch (Exception e) { String err = "Unable to single search: " + ": " + e.getClass().getName() + ": " //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + e.getLocalizedMessage(); LOGGER.error(err, e); throw new XtentisException(err, e); } }
From source file:com.evolveum.midpoint.wf.impl.WfConfiguration.java
public void checkAllowedKeys(Configuration c, List<String> knownKeys, List<String> deprecatedKeys) { Set<String> knownKeysSet = new HashSet<>(knownKeys); Set<String> deprecatedKeysSet = new HashSet<>(deprecatedKeys); Iterator<String> keyIterator = c.getKeys(); while (keyIterator.hasNext()) { String keyName = keyIterator.next(); String normalizedKeyName = StringUtils.substringBefore(keyName, "."); // because of subkeys normalizedKeyName = StringUtils.substringBefore(normalizedKeyName, "["); // because of [@xmlns:c] int colon = normalizedKeyName.indexOf(':'); // because of c:generalChangeProcessorConfiguration if (colon != -1) { normalizedKeyName = normalizedKeyName.substring(colon + 1); }/*from w w w .j av a2 s.co m*/ if (deprecatedKeysSet.contains(keyName) || deprecatedKeysSet.contains(normalizedKeyName)) { throw new SystemException("Deprecated key " + keyName + " in workflow configuration. Please see https://wiki.evolveum.com/display/midPoint/Workflow+configuration."); } if (!knownKeysSet.contains(keyName) && !knownKeysSet.contains(normalizedKeyName)) { // ...we need to test both because of keys like 'midpoint.home' throw new SystemException("Unknown key " + keyName + " in workflow configuration"); } } }
From source file:com.acc.storefront.controllers.pages.CheckoutController.java
protected String processOrderCode(final String orderCode, final Model model, final HttpServletRequest request) throws CMSItemNotFoundException { final OrderData orderDetails = orderFacade.getOrderDetailsForCode(orderCode); if (orderDetails.isGuestCustomer() && !StringUtils.substringBefore(orderDetails.getUser().getUid(), "|") .equals(getSessionService().getAttribute(WebConstants.ANONYMOUS_CHECKOUT_GUID))) { return getCheckoutRedirectUrl(); }/*from w ww. ja va 2 s . c om*/ if (orderDetails.getEntries() != null && !orderDetails.getEntries().isEmpty()) { for (final OrderEntryData entry : orderDetails.getEntries()) { final String productCode = entry.getProduct().getCode(); final ProductData product = productFacade.getProductForCodeAndOptions(productCode, Arrays.asList(ProductOption.BASIC, ProductOption.PRICE, ProductOption.CATEGORIES)); entry.setProduct(product); } final BaseStoreModel baseStoreModel = baseStoreService.getCurrentBaseStore(); final OrderModel orderModel = checkoutCustomerStrategy.isAnonymousCheckout() ? customerAccountService.getOrderDetailsForGUID(orderCode, baseStoreModel) : customerAccountService.getOrderForCode((CustomerModel) userService.getCurrentUser(), orderCode, baseStoreModel); if (StringUtils.isNotEmpty(orderModel.getUCOID())) { model.addAttribute("UCOID", orderModel.getUCOID()); System.out.println("ucoid" + orderModel.getUCOID()); } } model.addAttribute("orderCode", orderCode); model.addAttribute("orderData", orderDetails); model.addAttribute("allItems", orderDetails.getEntries()); model.addAttribute("deliveryAddress", orderDetails.getDeliveryAddress()); model.addAttribute("deliveryMode", orderDetails.getDeliveryMode()); model.addAttribute("paymentInfo", orderDetails.getPaymentInfo()); model.addAttribute("pageType", PageType.ORDERCONFIRMATION.name()); final String uid = orderDetails.getPaymentInfo().getBillingAddress().getEmail(); model.addAttribute("email", uid); if (orderDetails.isGuestCustomer() && !model.containsAttribute("guestRegisterForm")) { final GuestRegisterForm guestRegisterForm = new GuestRegisterForm(); guestRegisterForm.setOrderCode(orderDetails.getGuid()); guestRegisterForm.setUid(uid); model.addAttribute(guestRegisterForm); } final AbstractPageModel cmsPage = getContentPageForLabelOrId(CHECKOUT_ORDER_CONFIRMATION_CMS_PAGE_LABEL); storeCmsPageInModel(model, cmsPage); setUpMetaDataForContentPage(model, getContentPageForLabelOrId(CHECKOUT_ORDER_CONFIRMATION_CMS_PAGE_LABEL)); model.addAttribute("metaRobots", "no-index,no-follow"); return ControllerConstants.Views.Pages.Checkout.CheckoutConfirmationPage; }
From source file:com.ctc.storefront.controllers.pages.CheckoutController.java
protected String processOrderCode(final String orderCode, final Model model, final HttpServletRequest request, final RedirectAttributes redirectModel) throws CMSItemNotFoundException { final OrderData orderDetails; try {/* www. j av a 2s.com*/ orderDetails = orderFacade.getOrderDetailsForCode(orderCode); } catch (final UnknownIdentifierException e) { LOG.warn( "Attempted to load an order confirmation that does not exist or is not visible. Redirect to home page."); return REDIRECT_PREFIX + ROOT; } if (orderDetails.isGuestCustomer() && !StringUtils.substringBefore(orderDetails.getUser().getUid(), "|") .equals(getSessionService().getAttribute(WebConstants.ANONYMOUS_CHECKOUT_GUID))) { return getCheckoutRedirectUrl(); } if (orderDetails.getEntries() != null && !orderDetails.getEntries().isEmpty()) { for (final OrderEntryData entry : orderDetails.getEntries()) { final String productCode = entry.getProduct().getCode(); final ProductData product = productFacade.getProductForCodeAndOptions(productCode, Arrays.asList(ProductOption.BASIC, ProductOption.PRICE, ProductOption.CATEGORIES)); entry.setProduct(product); } } model.addAttribute("orderCode", orderCode); model.addAttribute("orderData", orderDetails); model.addAttribute("allItems", orderDetails.getEntries()); model.addAttribute("deliveryAddress", orderDetails.getDeliveryAddress()); model.addAttribute("deliveryMode", orderDetails.getDeliveryMode()); model.addAttribute("paymentInfo", orderDetails.getPaymentInfo()); model.addAttribute("pageType", PageType.ORDERCONFIRMATION.name()); final Optional<PromotionResultData> optional = orderDetails.getAppliedOrderPromotions().stream() .filter(x -> CollectionUtils.isNotEmpty(x.getGiveAwayCouponCodes())).findFirst(); if (optional.isPresent()) { final PromotionResultData giveAwayCouponPromotion = optional.get(); final List<CouponData> giftCoupons = giveAwayCouponPromotion.getGiveAwayCouponCodes(); model.addAttribute("giftCoupon", giftCoupons.get(0)); orderDetails.getAppliedOrderPromotions() .removeIf(x -> CollectionUtils.isNotEmpty(x.getGiveAwayCouponCodes())); } processEmailAddress(model, orderDetails); final String continueUrl = (String) getSessionService().getAttribute(WebConstants.CONTINUE_URL); model.addAttribute(CONTINUE_URL_KEY, (continueUrl != null && !continueUrl.isEmpty()) ? continueUrl : ROOT); final AbstractPageModel cmsPage = getContentPageForLabelOrId(CHECKOUT_ORDER_CONFIRMATION_CMS_PAGE_LABEL); storeCmsPageInModel(model, cmsPage); setUpMetaDataForContentPage(model, getContentPageForLabelOrId(CHECKOUT_ORDER_CONFIRMATION_CMS_PAGE_LABEL)); model.addAttribute(ThirdPartyConstants.SeoRobots.META_ROBOTS, ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW); if (ResponsiveUtils.isResponsive()) { return getViewForPage(model); } return ControllerConstants.Views.Pages.Checkout.CheckoutConfirmationPage; }
From source file:com.google.gdt.eclipse.designer.core.model.widgets.CoordinatesTest.java
/** * For string like <code>"left 10px, top 20 px"</code> returns * //from www.j a v a 2s . c om * <pre> * border-left 10px; * border-top 20px; * </pre> */ private static String getSidesStyle(String stylesString, String styleName) { String styles = ""; String[] stylesParts = StringUtils.split(stylesString, ','); for (String stylePart : stylesParts) { stylePart = stylePart.trim(); styles += "\t"; if (stylePart.startsWith("top") || stylePart.startsWith("right") || stylePart.startsWith("bottom") || stylePart.startsWith("left")) { String side = StringUtils.substringBefore(stylePart, " "); String withoutSide = StringUtils.substringAfter(stylePart, " "); styles += styleName + "-" + side + ": " + withoutSide; } else { styles += styleName + ": " + stylePart; } styles += ";\n"; } styles = StringUtils.chomp(styles, "\n"); return styles; }
From source file:info.magnolia.rendering.renderer.AbstractRenderer.java
protected <T extends RenderingModel<?>> T newModel(Class<T> modelClass, final Node content, final RenderableDefinition definition, final RenderingModel<?> parentModel) throws RenderException { try {//from w w w . j a v a2s . c o m T model = Components.getComponentProvider().newInstanceWithParameterResolvers(modelClass, new ParameterResolver() { @Override public Object resolveParameter(ParameterInfo parameter) { if (parameter.getParameterType().equals(Node.class)) { return content; } if (parameter.getParameterType().isAssignableFrom(definition.getClass())) { return definition; } if (parameter.getParameterType().equals(RenderingModel.class)) { return parentModel; } return UNRESOLVED; } }); // populate the instance with values given as request parameters Map<String, String[]> params = MgnlContext.getWebContext().getRequest().getParameterMap(); // needed workaround to not break rendering when there is no index between square brackets // see https://issues.apache.org/jira/browse/BEANUTILS-419 Map<String, Object> filtered = new HashMap<String, Object>(); if (params != null) { for (Entry<String, String[]> entry : params.entrySet()) { String key = entry.getKey(); String[] value = entry.getValue(); if (StringUtils.contains(key, "[")) { key = StringUtils.substringBefore(key, "["); } filtered.put(key, value); } } BeanUtils.populate(model, filtered); return model; } catch (MgnlInstantiationException e) { throw new RenderException("Can't instantiate model: " + modelClass, e); } catch (InvocationTargetException e) { throw new RenderException("Can't create rendering model: " + ExceptionUtils.getRootCauseMessage(e), e); } catch (IllegalAccessException e) { throw new RenderException("Can't create rendering model: " + ExceptionUtils.getRootCauseMessage(e), e); } }
From source file:edu.wfu.inotado.InotadoTestBase.java
/** * Reads a XML file from directory - inotado-api/api/resources/xml * /*from ww w . ja v a 2 s . c o m*/ * @param fileName */ @SuppressWarnings("resource") protected String readXmlFromFile(String fileName) { BufferedReader br; String xmlStr = "No content available!"; // get the file location URL location = this.getClass().getProtectionDomain().getCodeSource().getLocation(); String pathCurrent = location.getFile(); String pathToXml = StringUtils.substringBefore(pathCurrent, "inotado-") + "/inotado-api/api/resources/xml/"; String file = pathToXml + fileName; try { br = new BufferedReader(new FileReader(file)); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append('\n'); line = br.readLine(); } xmlStr = sb.toString(); } catch (FileNotFoundException e) { log.error("Unalbe to read the file:" + file, e); } catch (IOException e) { log.error("Erorr occurred while reading file:" + file, e); } return xmlStr; }
From source file:com.amalto.core.history.accessor.record.DataRecordAccessor.java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override//from w w w . j a v a 2 s. c om public void create() { try { StringTokenizer tokenizer = new StringTokenizer(path, "/"); //$NON-NLS-1$ DataRecord current = dataRecord; while (tokenizer.hasMoreElements()) { String element = tokenizer.nextToken(); if (element.indexOf('@') < 0) { if (current == null) { throw new IllegalStateException(); // TODO Message } if (element.indexOf('[') > 0) { FieldMetadata field = current.getType().getField(StringUtils.substringBefore(element, "[")); //$NON-NLS-1$ if (!field.isMany()) { throw new IllegalStateException( "Expected a repeatable field for '" + element + "' in path '" + path //$NON-NLS-1$ //$NON-NLS-2$ + "'."); //$NON-NLS-1$ } int indexStart = element.indexOf('['); int indexEnd = element.indexOf(']'); if (indexStart < 0 || indexEnd < 0) { throw new RuntimeException( "Field name '" + element + "' did not match many field pattern in path '" //$NON-NLS-1$ //$NON-NLS-2$ + path + "'."); //$NON-NLS-1$ } int index = Integer.parseInt(element.substring(indexStart + 1, indexEnd)) - 1; List list = (List) current.get(field); boolean newList = list == null; if (newList) { list = new LinkedList(); } while (index >= list.size()) { if (field instanceof ContainedTypeFieldMetadata) { DataRecord record = new DataRecord((ComplexTypeMetadata) field.getType(), UnsupportedDataRecordMetadata.INSTANCE); list.add(record); } else if (field instanceof ReferenceFieldMetadata) { DataRecord record = new DataRecord( ((ReferenceFieldMetadata) field).getReferencedType(), UnsupportedDataRecordMetadata.INSTANCE); list.add(record); } else { list.add(null); } } if (newList) { current.set(field, list); } Object value = list.get(index); if (value instanceof DataRecord) { current = (DataRecord) value; } } else { FieldMetadata field = current.getType().getField(element); if (field instanceof ContainedTypeFieldMetadata) { Object value = current.get(field); if (value == null) { DataRecord record = new DataRecord( ((ContainedTypeFieldMetadata) field).getContainedType(), UnsupportedDataRecordMetadata.INSTANCE); current.set(field, record); current = record; } else { current = (DataRecord) value; } } } } } } finally { cachedExist = true; } }