com.github.jknack.handlebars.Options Java Examples

The following examples show how to use com.github.jknack.handlebars.Options. 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: Helpers.java    From bootstraped-multi-test-results-report with MIT License 6 votes vote down vote up
private Helper<Long> dateHelper() {
    return new Helper<Long>() {
        public CharSequence apply(Long arg0, Options arg1) throws IOException {
            PeriodFormatter formatter = new PeriodFormatterBuilder()
                .appendDays()
                .appendSuffix(" d : ")
                .appendHours()
                .appendSuffix(" h : ")
                .appendMinutes()
                .appendSuffix(" m : ")
                .appendSeconds()
                .appendSuffix(" s : ")
                .appendMillis()
                .appendSuffix(" ms")
                .toFormatter();
            return formatter.print(new Period((arg0 * 1) / 1000000));
        }
    };
}
 
Example #2
Source File: FormatJoinHelper.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public Object apply(Collection<?> context, Options options) {
    if (context == null || context.isEmpty()) {
        return "";
    }

    String separator = options.hash("sep", ",");
    String format = options.hash("format", null);

    Function<Object, String> formatter = format != null
            ? each -> String.format(format, each)
            : Object::toString;

    return context.stream()
            .map(formatter)
            .collect(joining(separator));
}
 
Example #3
Source File: ComponentPresentedHelper.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public Object apply(Set<String> context, Options options)
        throws IOException {
    String first = options.param(0, null);

    Validate.notNull(first, "found 'null', expected 'first'");
    if (context == null) {
        context = new HashSet<>();
    }

    Buffer buffer = options.buffer();
    if (!context.contains(first)) {
        buffer.append(options.inverse());
    } else {
        buffer.append(options.fn());
    }
    return buffer;
}
 
Example #4
Source File: BashEscapedHelper.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence apply(Object context, Options options) throws IOException {
  if (context == null) {
    return "\"\"";
  }

  final StringBuilder sb = new StringBuilder();

  sb.append('"');

  for (char c : context.toString().toCharArray()) {
    if (c == '\\' || c == '\"' || c == '`') {
      sb.append('\\');
      sb.append(c);
    } else if (c == '!') {
      sb.append("\"'!'\"");
    } else {
      sb.append(c);
    }
  }

  sb.append('"');

  return sb.toString();
}
 
Example #5
Source File: ShellQuoteHelper.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence apply(Object context, Options options) throws IOException {
  if (context == null) {
    return "''";
  }

  final StringBuilder sb = new StringBuilder();

  sb.append("'");

  for (char c : context.toString().toCharArray()) {
    if (c == '\'') {
      sb.append("'\"'\"'");
    } else if (c == '\n') {
      sb.append('\\');
      sb.append('n');
    } else {
      sb.append(c);
    }
  }

  sb.append("'");

  return sb.toString();
}
 
Example #6
Source File: EscapeNewLinesAndQuotesHelper.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence apply(Object context, Options options) throws IOException {
  if (context == null) {
    return "\"\"";
  }

  final StringBuilder sb = new StringBuilder();

  sb.append('"');

  for (char c : context.toString().toCharArray()) {
    if (c == '\n') {
      sb.append('\\');
      sb.append('n');
    } else if (c == '"') {
      sb.append('\\');
      sb.append('"');
    } else {
      sb.append(c);
    }
  }

  sb.append('"');

  return sb.toString();
}
 
Example #7
Source File: CustomHelperUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenHelperIsCreated_ThenCanRegister() throws IOException {
    Handlebars handlebars = new Handlebars(templateLoader);
    handlebars.registerHelper("isBusy", new Helper<Person>() {
        @Override
        public Object apply(Person context, Options options) throws IOException {
            String busyString = context.isBusy() ? "busy" : "available";
            return context.getName() + " - " + busyString;
        }
    });
    Template template = handlebars.compile("person");
    Person person = getPerson("Baeldung");

    String templateString = template.apply(person);

    assertThat(templateString).isEqualTo("Baeldung - busy");
}
 
Example #8
Source File: FormatTimestampHelper.java    From Baragon with Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence apply(Number context, Options options) throws IOException {
  String dateFormatString;
  try {
    dateFormatString = options.param(0, defaultFormatString);
  } catch (ClassCastException cce) {  // phorce.
    LOG.warn(String.format("Date format %s isn't subclass of String, using default: %s", options.param(0), defaultFormatString));
    dateFormatString = defaultFormatString;
  }

  final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatString);

  final Calendar cal = Calendar.getInstance();
  cal.setTimeInMillis(context.longValue());

  return simpleDateFormat.format(cal.getTime());
}
 
Example #9
Source File: EachHelper.java    From legstar-core2 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
* Iterate over a hash like object.
*
* @param context The context object.
* @param options The helper options.
* @return The string output.
* @throws IOException If something goes wrong.
*/
 private CharSequence hashContext(final Object context, final Options options)
         throws IOException {
     Set < Entry < String, Object >> propertySet = options
             .propertySet(context);
     StringBuilder buffer = new StringBuilder();
     Context parent = options.context;
     boolean first = true;
     for (Entry < String, Object > entry : propertySet) {
         Context current = Context.newBuilder(parent, entry.getValue())
                 .combine("@key", entry.getKey())
                 .combine("@first", first ? "first" : "").build();
         buffer.append(options.fn(current));
         current.destroy();
         first = false;
     }
     return buffer.toString();
 }
 
Example #10
Source File: CurrentRackIsPresentHelper.java    From Baragon with Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence apply(Collection<UpstreamInfo> upstreams, Options options) throws IOException {
  if (!currentRackId.isPresent()) {
    return options.fn();
  }

  if (upstreams == null) {
    return options.inverse();
  }

  for (UpstreamInfo upstreamInfo : upstreams) {
    if (upstreamInfo.getRackId().isPresent() && upstreamInfo.getRackId().get().toLowerCase().equals(currentRackId.get().toLowerCase())) {
      return options.fn();
    }
  }
  return options.inverse();
}
 
Example #11
Source File: PluralizeHelper.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence apply(Number context, Options options) throws IOException {
   if(context == null) {
     throw new IllegalArgumentException("a number must be provided as the first argument");
   }
   if(options.params == null || options.params.length < 2) {
      throw new IllegalArgumentException("two strings must be provided as the second and third arguments");
   }

   String singular = String.valueOf(options.params[0]);
   String plural = String.valueOf(options.params[1]);

   // 0 is plural in English
   if(context.intValue() == 1) {
      return singular;
   }
   return plural;
}
 
Example #12
Source File: FirstOfHelper.java    From Baragon with Apache License 2.0 6 votes vote down vote up
@Override
public CharSequence apply(Object context, Options options) throws IOException {
  // handle null
  if (context == null) {
    return options.param(0, fallback).toString();
  }

  // handle optional
  if (context instanceof Optional) {
    final Optional<Object> contextOptional = (Optional<Object>) context;
    return contextOptional.or(options.param(0, fallback)).toString();
  }

  // handle empty string
  if (context instanceof String) {
    final String contextString = (String) context;

    return !Strings.isNullOrEmpty(contextString) ? contextString : options.param(0, fallback).toString();
  }

  // otherwise just return context
  return context.toString();
}
 
Example #13
Source File: AllHelperTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsupportedContext_nullContext() throws Exception {

	Context ctx = Context.newContext( null );
	Handlebars handlebars = Mockito.mock( Handlebars.class );
	Template tpl = Mockito.mock(  Template.class  );
	Options opts = new Options(
			handlebars, "helper", TagType.SECTION, ctx, tpl, tpl,
			new Object[ 0 ],
			new HashMap<String,Object>( 0 ));

	AllHelper helper = new AllHelper();
	Assert.assertEquals( "", helper.apply( null, opts ));
}
 
Example #14
Source File: AllHelperTest.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnsupportedContext_unknownType() throws Exception {

	Context ctx = Context.newContext( new Object());
	Handlebars handlebars = Mockito.mock( Handlebars.class );
	Template tpl = Mockito.mock(  Template.class  );
	Options opts = new Options(
			handlebars, "helper", TagType.SECTION, ctx, tpl, tpl,
			new Object[ 0 ],
			new HashMap<String,Object>( 0 ));

	AllHelper helper = new AllHelper();
	Assert.assertEquals( "", helper.apply( null, opts ));
}
 
Example #15
Source File: IfHasNewLinesOrBackticksHelper.java    From Singularity with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public CharSequence apply(Object context, Options options) throws IOException {
  if (context.toString().contains("\n") || context.toString().contains("`")) {
    return options.fn();
  } else {
    return options.inverse();
  }
}
 
Example #16
Source File: PASystemImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private Handlebars loadHandleBars(final I18n i18n) {
    Handlebars handlebars = new Handlebars()
            .with(cache);

    handlebars.registerHelper("t", new Helper<Object>() {
        @Override
        public CharSequence apply(final Object context, final Options options) {
            String key = options.param(0);
            return i18n.t(key);
        }
    });

    return handlebars;
}
 
Example #17
Source File: IfNullHelper.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public Object apply(Object context, Options options) throws IOException {
    Buffer buffer = options.buffer();

    if (context == null) {
        buffer.append(options.fn());
    } else {
        buffer.append(options.inverse());
    }
    return buffer;
}
 
Example #18
Source File: IsKeyHelper.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Override
public CharSequence apply( String context, Options options )
throws IOException {

	CharSequence result = StringUtils.EMPTY;
	Object model = options.context.model();
	if( model instanceof VariableContextBean ) {
		String name = ((VariableContextBean) model).getName();
		if( Objects.equals( name, context ))
			result = ((VariableContextBean) model).getValue();
	}

	return result;
}
 
Example #19
Source File: EqHelper.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public Object apply(Object context, Options options)
        throws IOException {
    String first = options.param(0, null);

    Validate.notNull(first, "found 'null', expected 'first'");

    Buffer buffer = options.buffer();
    if (!first.equals(context.toString())) {
        buffer.append(options.inverse());
    } else {
        buffer.append(options.fn());
    }
    return buffer;
}
 
Example #20
Source File: AllHelper.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Same as above, but with type-safe arguments.
 *
 * @param instances the instances to which this helper is applied.
 * @param options   the options of this helper invocation.
 * @return a string result.
 * @throws IOException if a template cannot be loaded.
 */
private String safeApply( Collection<InstanceContextBean> instances, Options options, String componentPath )
throws IOException {

	// Parse the filter.
	String installerName = (String) options.hash.get( "installer" );
	final InstanceFilter filter = InstanceFilter.createFilter( componentPath, installerName );

	// Apply the filter.
	final Collection<InstanceContextBean> selectedInstances = filter.apply( instances );

	// Apply the content template of the helper to each selected instance.
	final StringBuilder buffer = new StringBuilder();
	final Context parent = options.context;
	int index = 0;
	final int last = selectedInstances.size() - 1;

	for( final InstanceContextBean instance : selectedInstances ) {
		final Context current = Context.newBuilder( parent, instance )
				.combine( "@index", index )
				.combine( "@first", index == 0 ? "first" : "" )
				.combine( "@last", index == last ? "last" : "" )
				.combine( "@odd", index % 2 == 0 ? "" : "odd" )
				.combine( "@even", index % 2 == 0 ? "even" : "" )
				.build();

		index++;
		buffer.append( options.fn( current ));
	}

	return buffer.toString();
}
 
Example #21
Source File: NeqHelper.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
public Object apply(Object context, Options options)
        throws IOException {
    String first = options.param(0, null);

    Validate.notNull(first, "found 'null', expected 'first'");

    Buffer buffer = options.buffer();
    if (first.equals(context)) {
        buffer.append(options.inverse());
    } else {
        buffer.append(options.fn());
    }
    return buffer;
}
 
Example #22
Source File: IfHelper.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
protected Object decision(Boolean context, Options options) throws IOException {
    if (context == null) {
        context = false;
    }

    Buffer buffer = options.buffer();
    if (context) {
        buffer.append(options.inverse());
    } else {
        buffer.append(options.fn());
    }
    return buffer;
}
 
Example #23
Source File: IfPresentHelper.java    From Singularity with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public CharSequence apply(Object context, Options options) throws IOException {
  if (context instanceof Optional) {
    context = ((Optional<Object>) context).orElse(null);
  }

  if (context != null) {
    return options.fn(context);
  } else {
    return options.inverse();
  }
}
 
Example #24
Source File: AllHelper.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Selects instances according to a selection path.
 * <p>For example:</p>
 * <pre>
 * {{#all children path="/VM/Apache" installer="script"}}
 *   {{path}}
 * {{/all}}
 * </pre>
 */
@Override
public CharSequence apply( final Object computedContext, final Options options ) throws IOException {

	// Get parameters
	Object context = options.context.model();
	String componentPath = null;
	if( computedContext instanceof String )
		componentPath = (String) computedContext;

	if( Utils.isEmptyOrWhitespaces( componentPath ))
		componentPath = InstanceFilter.JOKER;

	// Process them
	CharSequence result = StringUtils.EMPTY;
	if (context instanceof ApplicationContextBean) {
		// Implicit: all instances of the application.
		result = safeApply(((ApplicationContextBean) context).getInstances(), options, componentPath );

	} else if (context instanceof InstanceContextBean) {
		// Implicit: all descendants of the instance.
		result = safeApply( descendantInstances((InstanceContextBean) context), options, componentPath );

	} else {
		this.logger.warning( "An unexpected context was received: " + (context == null ? null : context.getClass()));
	}

	return result;
}
 
Example #25
Source File: IfContainedInHelperSource.java    From Baragon with Apache License 2.0 5 votes vote down vote up
public static CharSequence ifContainedIn(Collection<String> haystack, String needle, Options options) throws IOException {
  if (Objects.isNull(haystack)) {
    return options.inverse();
  }

  for (String element : haystack) {
    if (element.contains(needle)) {
      return options.fn();
    }
  }

  return options.inverse();
}
 
Example #26
Source File: IfEqualHelperSource.java    From Baragon with Apache License 2.0 5 votes vote down vote up
public static CharSequence ifEqual(String v1, String v2, Options options) throws IOException {
  if (v1 == null ? v2 == null : v1.equals(v2)) {
    return options.fn();
  } else {
    return options.inverse();
  }
}
 
Example #27
Source File: IfEqualHelperSource.java    From Baragon with Apache License 2.0 5 votes vote down vote up
public static CharSequence ifOptionalEqual(Optional<String> v1, Optional<String> v2, Options options) throws IOException {
  if (v1.equals(v2)) {
    return options.fn();
  } else {
    return options.inverse();
  }
}
 
Example #28
Source File: ToNginxVarHelper.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@Override
public CharSequence apply(String input, Options options) throws UnknownHostException {
  if (!Strings.isNullOrEmpty(input)) {
    return input.toLowerCase().replaceAll("-", "_");
  } else {
    return input;
  }
}
 
Example #29
Source File: PreferSameRackWeightingHelper.java    From Baragon with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param upstreams
 * @param currentUpstream
 * @param options
 * @return wrapper for calling the operation method that computes the balanced weighting
 */
public CharSequence preferSameRackWeighting(Collection<UpstreamInfo> upstreams, UpstreamInfo currentUpstream, Options options) {
  final RackMethodsHelper rackHelper = new RackMethodsHelper();
  final List<String> allRacks = rackHelper.generateAllRacks(upstreams);
  if (allRacks.size() == 0) {
    return "";
  }
  final BigDecimal totalPendingLoad = rackHelper.getTotalPendingLoad(allRacks);
  final BigDecimal capacity = rackHelper.calculateCapacity(allRacks);
  final BigDecimal multiplier = rackHelper.calculateMultiplier(allRacks);
  return preferSameRackWeightingOperation(upstreams, currentUpstream, allRacks, capacity, multiplier, totalPendingLoad, null);
}
 
Example #30
Source File: Helpers.java    From bootstraped-multi-test-results-report with MIT License 5 votes vote down vote up
private Helper<List<StepRow>> doTableHelperForStep() {
    return new Helper<List<StepRow>>() {
        @Override
        public CharSequence apply(List<StepRow> rows, Options arg1) throws IOException {
            String tableContent = "<table  class='table table-condensed table-hover'>";
            int indexRow = 0;
            for (StepRow row : rows) {
                indexRow++;
                if (indexRow == 1) {
                    tableContent += "<thead><tr>";
                } else if (indexRow == 2) {
                    tableContent += "<tbody><tr>";
                } else {
                    tableContent += "<tr>";
                }
                for (String cell : row.getCells()) {
                    if (indexRow == 1) {
                        tableContent += "<th>" + cell + "</th>";
                    } else {
                        tableContent += "<td>" + cell + "</td>";
                    }
                }
                if (indexRow == 1) {
                    tableContent += "</tr></thead>";
                } else {
                    tableContent += "</tr>";
                }
            }
            tableContent += "</tbody></table>";
            return tableContent;
        }
    };
}