001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.svl.vars; 018 019import java.util.regex.*; 020 021import org.apache.juneau.common.utils.*; 022import org.apache.juneau.svl.*; 023 024/** 025 * A transformational variable resolver that returns character count or list count (using given delimiter). 026 * 027 * <p> 028 * The format for this var is one of the following: 029 * <ul> 030 * <li><js>"$LN{arg}"</js> 031 * <li><js>"$LN{arg,delimiter}"</js> 032 * </ul> 033 * 034 * <h5 class='section'>Example:</h5> 035 * <p class='bjava'> 036 * <jc>// Create a variable resolver that resolves system properties and $SW vars.</jc> 037 * VarResolver <jv>varResolver</jv> = VarResolver.<jsm>create</jsm>().vars(LenVar.<jk>class</jk>, SystemPropertiesVar.<jk>class</jk>).build(); 038 * 039 * <jc>// Use it!</jc> 040 * System.<jsf>out</jsf>.println(<jv>varResolver</jv>.resolve(<js>"Parts = $LN{$P{os.version},.} Chars = $LN{$P{os.version}}"</js>)); 041 * </p> 042 * 043 * <p> 044 * Since this is a {@link MultipartVar}, any variables contained in the result will be recursively resolved. 045 * <br>Likewise, if the arguments contain any variables, those will be resolved before they are passed to this var. 046 * 047 * <h5 class='section'>See Also:</h5><ul> 048 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/SimpleVariableLanguageBasics">Simple Variable Language Basics</a> 049 * </ul> 050 */ 051public class LenVar extends MultipartVar { 052 053 /** The name of this variable. */ 054 public static final String NAME = "LN"; 055 056 /** 057 * Constructor. 058 */ 059 public LenVar() { 060 super(NAME); 061 } 062 063 @Override /* MultipartVar */ 064 public String resolve(VarResolverSession session, String[] args) { 065 Utils.assertArg(args.length <= 2, "Invalid number of arguments passed to $LN var. Must have 1 or 2 arguments."); 066 067 int len = 0; 068 String stringArg = args[0]; 069 if (args.length == 1) 070 len = stringArg.length(); 071 else if (args.length == 2) { 072 //delimiter is given 073 String delimiter = Pattern.quote(args[1]); 074 len = stringArg.trim().split(delimiter).length; 075 } 076 return String.valueOf(len); 077 } 078}