private <T> ValueExtractor provideExtractorForValue(Class<T> clazz, int target, List<String> chainOfProperties) { Class<?> propertyClass = clazz; List<ValueExtractor> chainedExtractors = Lists.newArrayList(); for (String property : chainOfProperties) { Class<?> finalPropertyClass = propertyClass; Optional<Method> matchingMethod = Stream.of(property, "get" + WordUtils.capitalize(property), "is" + WordUtils.capitalize(property)) .map(token -> MethodUtils.getMatchingMethod(finalPropertyClass, token)) .findFirst(); Method method = matchingMethod.orElseThrow( () -> new InvalidQueryException( String.format("Cannot find appropriate method for property [%s] on class [%s]", property, finalPropertyClass))); ReflectionExtractor extractor = new ReflectionExtractor(method.getName()); chainedExtractors.add(extractor); propertyClass = method.getDeclaringClass(); } return new ChainedExtractor(chainedExtractors.toArray(new ValueExtractor[chainedExtractors.size()])); }
@Override public void initGui() { super.initGui(); if (searchGui != null) { inventorySlots.getSlot(editingSlot).putStack(searchGui.getSearchStack()); NetworkHandler.sendToServer(new PacketSetLogisticsFilterStack(logistics, searchGui.getSearchStack(), editingSlot)); searchGui = null; } if (fluidSearchGui != null && fluidSearchGui.getFilter() != null) { FluidStack filter = new FluidStack(fluidSearchGui.getFilter(), 1000); logistics.setFilter(editingSlot, filter); NetworkHandler.sendToServer(new PacketSetLogisticsFluidFilterStack(logistics, filter, editingSlot)); fluidSearchGui = null; } String invisibleText = I18n.format("gui.logistic_frame.invisible"); addWidget(invisible = new GuiCheckBox(9, guiLeft + xSize - 15 - fontRenderer.getStringWidth(invisibleText), guiTop + 7, 0xFF404040, invisibleText)); invisible.setTooltip(Arrays.asList(WordUtils.wrap(I18n.format("gui.logistic_frame.invisible.tooltip"), 40).split(System.getProperty("line.separator")))); addWidget(new WidgetLabel(guiLeft + 8, guiTop + 18, I18n.format(String.format("gui.%s.filters", SemiBlockManager.getKeyForSemiBlock(logistics))))); addWidget(new WidgetLabel(guiLeft + 8, guiTop + 90, I18n.format("gui.logistic_frame.liquid"))); for (int i = 0; i < 9; i++) { addWidget(new WidgetFluidStack(i, guiLeft + i * 18 + 8, guiTop + 101, logistics.getTankFilter(i))); } addInfoTab(I18n.format("gui.tab.info." + SemiBlockManager.getKeyForSemiBlock(logistics))); }
@Override public void addTooltip(int mouseX, int mouseY, List<String> curTip, boolean shiftPressed) { super.addTooltip(mouseX, mouseY, curTip, shiftPressed); for (IGuiWidget widget : widgets) { if (widget.getBounds().contains(mouseX, mouseY)) { widget.addTooltip(mouseX, mouseY, curTip, shiftPressed); } } boolean isInBounds = false; for (Rectangle rect : tooltipRectangles) { if (rect.contains(mouseX, mouseY)) { isInBounds = true; } } if (!isInBounds) { curTip.add(I18n.format("gui.amadron.amadronWidget.selling", getStringForObject(offer.getOutput()))); curTip.add(I18n.format("gui.amadron.amadronWidget.buying", getStringForObject(offer.getInput()))); curTip.add(I18n.format("gui.amadron.amadronWidget.vendor", offer.getVendor())); curTip.add(I18n.format("gui.amadron.amadronWidget.inBasket", shoppingAmount)); if (offer.getStock() >= 0) curTip.add(I18n.format("gui.amadron.amadronWidget.stock", offer.getStock())); if (offer.getVendor().equals(PneumaticCraftRepressurized.proxy.getPlayer().getName())) { curTip.addAll(Arrays.asList(WordUtils.wrap(I18n.format("gui.amadron.amadronWidget.sneakRightClickToRemove"), 40).split(System.getProperty("line.separator")))); } } }
/** * allows items to add custom lines of information to the mouseover description */ @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack remote, World world, List<String> curInfo, ITooltipFlag moreInfo) { super.addInformation(remote, world, curInfo, moreInfo); curInfo.add(I18n.format("gui.remote.tooltip.sneakRightClickToEdit")); NBTTagCompound tag = remote.getTagCompound(); if (tag != null && tag.hasKey("securityX")) { int x = tag.getInteger("securityX"); int y = tag.getInteger("securityY"); int z = tag.getInteger("securityZ"); int dimensionId = tag.getInteger("securityDimension"); Collections.addAll(curInfo, WordUtils.wrap(I18n.format("gui.remote.tooltip.boundToSecurityStation", dimensionId, x, y, z), 40).split(System.getProperty("line.separator"))); } else { Collections.addAll(curInfo, WordUtils.wrap(I18n.format("gui.remote.tooltip.rightClickToBind"), 40).split(System.getProperty("line.separator"))); } }
@Override public void renderExtraInfo() { if (getExtraStringInfo() != null) { GL11.glPushMatrix(); GL11.glScaled(0.5, 0.5, 0.5); FontRenderer fr = Minecraft.getMinecraft().fontRenderer; String[] splittedInfo = WordUtils.wrap(getExtraStringInfo(), 40).split(System.getProperty("line.separator")); for (int i = 0; i < splittedInfo.length; i++) { int stringLength = fr.getStringWidth(splittedInfo[i]); int startX = getWidth() / 2 - stringLength / 4; int startY = getHeight() / 2 - (fr.FONT_HEIGHT + 1) * (splittedInfo.length - 1) / 4 + (fr.FONT_HEIGHT + 1) * i / 2 - fr.FONT_HEIGHT / 4; Gui.drawRect(startX * 2 - 1, startY * 2 - 1, startX * 2 + stringLength + 1, startY * 2 + fr.FONT_HEIGHT + 1, 0xFFFFFFFF); fr.drawString(splittedInfo[i], startX * 2, startY * 2, 0xFF000000); } GL11.glPopMatrix(); GL11.glColor4d(1, 1, 1, 1); } }
@Override protected String getSingleItemDescription(String expression) { String exp = expression; if (expression.contains("#")) { exp = expression.substring(0, expression.indexOf("#")); } else if (expression.contains("L")) { exp = exp.replace("L", ""); } if (StringUtils.isNumeric(exp)) { int dayOfWeekNum = Integer.parseInt(exp); boolean isZeroBasedDayOfWeek = (options == null || options.isZeroBasedDayOfWeek()); boolean isInvalidDayOfWeekForSetting = (options != null && !options.isZeroBasedDayOfWeek() && dayOfWeekNum <= 1); if (isInvalidDayOfWeekForSetting || (isZeroBasedDayOfWeek && dayOfWeekNum == 0)) { return DateAndTimeUtils.getDayOfWeekName(7); } else if (options != null && !options.isZeroBasedDayOfWeek()) { dayOfWeekNum -= 1; } return DateAndTimeUtils.getDayOfWeekName(dayOfWeekNum); } else { DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("EEE").withLocale(Locale.ENGLISH); return dateTimeFormatter.parseDateTime(WordUtils.capitalizeFully(exp)).dayOfWeek().getAsText(I18nMessages.getCurrentLocale()); } }
public void register(String eventName, ScriptEventHandler handler) { Class<? extends Event> eventClass = null; for (String eventPackage : eventPackages) { try { eventClass = Class.forName(eventPackage + "." + WordUtils.capitalize(eventName) + "Event").asSubclass(Event.class); break; } catch (ClassNotFoundException e) { } } if (eventClass == null) { throw new RuntimeException("Event class not found: " + eventName); } entries.add(new EventHandlerEntry(eventClass, handler)); }
public static void setupAbilitiesMenu(Player player, boolean temporary) { String title = temporary ? "Temporary" : "Permanent"; Inventory inventory = Bukkit.createInventory(player, Convert.getInventorySize(plugin.getAbilityManager().getAbilities().size()), ChatColor.BOLD + title + " God Tokens"); for(Ability ability : plugin.getAbilityManager().getAbilities()) { List<String> description = new ArrayList<>(ability.getDescription()); // Adding price depending whetver ability is permanent or temporary if(temporary) { description.add(ChatColor.GRAY + "Duration: " + ChatColor.RED + "15 minutes"); } int price = temporary ? ability.getTemporaryPrice() : ability.getPermanentPrice(); String line = ChatColor.GRAY + "Price: " + ChatColor.RED + price + " GT"; description.add(line); description.add(ChatColor.GRAY + "Supported items:"); for(ItemType item : ability.getItems()) { description.add(ChatColor.RED + "- " + WordUtils.capitalize(item.toString().replaceAll("_", "").toLowerCase())); } inventory.addItem(ItemStackGenerator.createItem(ability.getIcon(), 0, 0, ChatColor.RED + ability.getName(), description, true)); } player.openInventory(inventory); }
public static void setup(Player player) { Inventory inv = Bukkit.createInventory(player, Convert.getInventorySize(plugin.getChallengesFile().getChallengesAmount()), ChatColor.BOLD + "Challenges"); String status = ChatColor.GREEN + " [COMPLETED]"; int level = plugin.getPlayerManager().getRank(player); int prestige = plugin.getPlayerManager().getPrestige(player); for(int i = 1; i <= plugin.getChallengesFile().getChallengesAmount(); i++) { if(level + 1 == i) status = ChatColor.YELLOW + " [CURRENT]"; else if(i > level) status = ChatColor.RED + " [LOCKED]"; inv.addItem(ItemStackGenerator.createItem(plugin.getChallengesFile().getTypeMaterial(i), 0, 0, ChatColor.GOLD + "" + i + Convert.getOrdinalFor(i) + " challenge" + status, Arrays.asList(ChatColor.GRAY + "Type: " + ChatColor.RED + WordUtils.capitalize(plugin.getChallengesFile().getType(i)), ChatColor.GRAY + "Cost: " + Convert.toPrice(plugin.getChallengesFile().getPrice(i) * (prestige + 1), true)), true)); } player.openInventory(inv); }
public void annotate(final MethodStep methodStep, final Method m) { // resources are not annotated at all, because the resource itself will contain a method // that will get into the public API. It is a method with GET annotation and empty path. if (!TypeHelper.isResource(methodStep.getReturnType())) { final String description = restOperation != null && restOperation.getDescription() != null ? restOperation.getDescription() : WordUtils.capitalize(StringHelper.splitCamelCase(m.getName())); getMethod().annotate(ApiOperation.class) // .param("value", StringHelper.firstSentence(description)) .param("notes", description) ; if (restOperation != null && restOperation.getExternalDocUrl() != null) { getMethod().annotate(ExternalDocs.class) .param("value", "Reference Guide") .param("url", restOperation.getExternalDocUrl()) ; } } }
/** * A utility method to wrap multiple lines of text, while respecting the original * newlines. * * @param input the String of text to wrap * @param width the width in characters into which to wrap the text. Less than 1 is treated as 1 * @return the original string with newlines added, and starting spaces trimmed * so that the resulting lines fit inside a column of with characters. */ public static String wrapParagraph(final String input, final int width) { if (input == null || input.isEmpty()) { return input; } final StringBuilder out = new StringBuilder(); try (final BufferedReader bufReader = new BufferedReader(new StringReader(input))) { out.append(bufReader.lines() .map(line -> WordUtils.wrap(line, width)) .collect(Collectors.joining("\n"))); } catch (IOException e) { throw new RuntimeException("Unreachable Statement.\nHow did the Buffered reader throw when it was " + "wrapping a StringReader?", e); } //if the last character of the input is a newline, we need to add another newline to conserve that. if (input.charAt(input.length() - 1) == '\n') { out.append('\n'); } return out.toString(); }
private static String buildName( String displayName ) { String[] temp = displayName.split( " " ); StringBuilder newName = new StringBuilder(); for ( int i = 0; i < temp.length; i++ ) { String old = temp[i]; if ( old.contains( "(" ) ) { old = old.replaceAll( "\\(", "" ); old = old.replaceAll( "\\)", "" ); } String part = WordUtils.capitalize( old.replaceAll( "'", "" ) ); newName.append( part ); } return newName.toString(); }
public String printCommandHelp(CommandInfo description) { StringBuilder sb = new StringBuilder(); sb.append(String.format("Usage: %s%s\n", Style.bold(Constants.command()), Style.bold(description.usage()))); if (!description.aliases().isEmpty()) { sb.append(String.format("%s: %s\n", com.atomist.rug.cli.utils.StringUtils.puralize("Alias", "Aliases", description.aliases()), Style.bold( StringUtils.collectionToDelimitedString(description.aliases(), ", ")))); } sb.append(String.format("%s.\n", description.description())); printOptions(description.globalOptions(), sb, Style.bold("Options")); printOptions(description.options(), sb, Style.bold("Command Options")); sb.append("\n"); sb.append(WordUtils.wrap(description.detail(), WRAP)); sb.append(WordUtils.wrap(HELP_FOOTER, WRAP)); return sb.toString(); }
public String printHelp(CommandInfoRegistry commandRegistry, GestureRegistry gestureRegistry, Options options) { StringBuilder sb = new StringBuilder(); sb.append(String.format("Usage: %s\n", Style.bold(Constants.command() + "[OPTION]... [COMMAND]..."))); sb.append("Work with Rugs like editors or generators.\n"); printOptions(options, sb, Style.bold("Options")); printCommands(sb, commandRegistry); printGestures(sb, gestureRegistry); sb.append("\n"); sb.append(String.format("Run '%sCOMMAND --help' for more detailed information on COMMAND.", Constants.command())); if (Constants.isShell()) { sb.append(WordUtils.wrap(SHELL_HELP_FOOTER, WRAP)); } sb.append(WordUtils.wrap(HELP_FOOTER, WRAP)); return sb.toString(); }
/** * This is a generic method that copies the simple attribute values from an * argument jsonObject to an argument generic object. * * @param jsonObject The jsonObject from where the attributes are to be copied. * @param destObject The object where the attributes should be copied into. * @throws Exception Throws a Exception when the operation are unsuccessful. */ public static <T> void convertJSONObjectToDirectoryObject(JSONObject jsonObject, T destObject) throws Exception { // Get the list of all the field names. Field[] fieldList = destObject.getClass().getDeclaredFields(); // For all the declared field. for (int i = 0; i < fieldList.length; i++) { // If the field is of type String, that is // if it is a simple attribute. if (fieldList[i].getType().equals(String.class)) { // Invoke the corresponding set method of the destObject using // the argument taken from the jsonObject. destObject .getClass() .getMethod(String.format("set%s", WordUtils.capitalize(fieldList[i].getName())), String.class) .invoke(destObject, jsonObject.optString(fieldList[i].getName())); } } }
private List<String> createDeserSetters(Class<? extends Storable> storableClass, String typeName) { List<String> deserSetters = new LinkedList<>(); Set<String> methodNames = new HashSet<>(); for (Method method : storableClass.getDeclaredMethods()) { methodNames.add(method.getName()); } for (Field field : storableClass.getDeclaredFields()) { String name = field.getName(); String capitalizedName = WordUtils.capitalize(name); //make sure there's a setter if (methodNames.contains("set" + capitalizedName)) { deserSetters.add(String.format("%s.set%2$s(extended.get%2s());", WordUtils.uncapitalize(typeName), capitalizedName)); } } return deserSetters; }
@Override public String exec(CommandRequest request, InodeHandle inode) { _failed = false; IMDBVFSDataNFO imdbData = new IMDBVFSDataNFO((DirectoryHandle)inode); IMDBInfo imdbInfo = imdbData.getIMDBInfoFromCache(); if (imdbInfo != null) { if (imdbInfo.getMovieFound()) { StringBuilder sb = new StringBuilder(); sb.append("#########################################").append(")\n"); sb.append("# Title # - ").append(imdbInfo.getTitle()).append("\n"); sb.append("# Year # - ").append(imdbInfo.getYear()).append("\n"); sb.append("# Genre # - ").append(imdbInfo.getGenre()).append("\n"); sb.append("# Rating # - "); sb.append(imdbInfo.getRating() != null ? imdbInfo.getRating()/10+"."+imdbInfo.getRating()%10+"/10" : "-").append("\n"); sb.append("# Votes # - ").append(imdbInfo.getVotes()).append("\n"); sb.append("# Director # - ").append(imdbInfo.getDirector()).append("\n"); sb.append("# Screens # - ").append(imdbInfo.getScreens()).append("\n"); sb.append("# URL # - ").append(imdbInfo.getURL()).append("\n"); sb.append("# Plot #\n").append(WordUtils.wrap(imdbInfo.getPlot(), 70)); return sb.toString(); } } return "#########################################\nNO IMDB INFO FOUND FOR: " + inode.getPath(); }
@Override public String exec(CommandRequest request, InodeHandle inode) { _failed = false; TvMazeVFSData tvmazeData = new TvMazeVFSData((DirectoryHandle)inode); TvMazeInfo tvmazeInfo = tvmazeData.getTvMazeInfoFromCache(); if (tvmazeInfo != null) { StringBuilder sb = new StringBuilder(); sb.append("#########################################").append(")\n"); sb.append("# Title # - ").append(tvmazeInfo.getName()).append("\n"); sb.append("# Genre # - ").append(StringUtils.join(tvmazeInfo.getGenres().toString(), ", ")).append("\n"); sb.append("# URL # - ").append(tvmazeInfo.getURL()).append("\n"); sb.append("# Plot #\n").append(WordUtils.wrap(tvmazeInfo.getSummary(), 70)); return sb.toString(); } return "#########################################\nNO TvMaze INFO FOUND FOR: " + inode.getPath(); }
@Override public void render(TileEntitySignalBase te, double x, double y, double z, float partialTicks, int destroyStage, float alpha) { String message = te.getMessage(); if(message.equals("")) return; GlStateManager.pushMatrix(); GlStateManager.translate((float)x + 0.5F, (float)y + 1.0, (float)z + 0.5F); GlStateManager.rotate(180 + Minecraft.getMinecraft().getRenderManager().playerViewY, 0.0F, -1.0F, 0.0F); GlStateManager.rotate(Minecraft.getMinecraft().getRenderManager().playerViewX, -1.0F, 0.0F,0.0F); double scale = 1/32D; GlStateManager.scale(scale, -scale, scale); String[] splitted = WordUtils.wrap(message, 40).split("\r\n"); FontRenderer f = Minecraft.getMinecraft().fontRenderer; for(int i = 0; i < splitted.length; i++){ String line = splitted[i]; f.drawString(line, -f.getStringWidth(line) / 2, (i - splitted.length + 1) * (f.FONT_HEIGHT + 1), 0xFFFFFFFF); } GlStateManager.popMatrix(); }
/** * Defines common functionality for a "create entity" service. * * @param formParams * POST request body parameters * @param defaultPropertyValues * default values for the entity properties * @return response with XML representation of the created entity */ protected Response create(final MultivaluedMap<String, String> formParams, final Map<String, String> defaultPropertyValues) { final Netlicensing netlicensing = objectFactory.createNetlicensing(); netlicensing.setItems(objectFactory.createNetlicensingItems()); final Item item = objectFactory.createItem(); item.setType(WordUtils.capitalize(serviceId)); netlicensing.getItems().getItem().add(item); final Map<String, String> propertyValues = new HashMap<String, String>(defaultPropertyValues); for (final String paramKey : formParams.keySet()) { propertyValues.put(paramKey, formParams.getFirst(paramKey)); } final List<Property> properties = netlicensing.getItems().getItem().get(0).getProperty(); for (final String propertyName : propertyValues.keySet()) { final Property property = SchemaFunction.propertyByName(properties, propertyName); if (!properties.contains(property)) { properties.add(property); } property.setValue(propertyValues.get(propertyName)); } return Response.ok(netlicensing).build(); }
private static void printUsage() { System.out.println(WordUtils.wrap("The Jaccard Index measures the similarity between vertex" + " neighborhoods and is computed as the number of shared neighbors divided by the number of" + " distinct neighbors. Scores range from 0.0 (no shared neighbors) to 1.0 (all neighbors are" + " shared).", 80)); System.out.println(); System.out.println(WordUtils.wrap("This algorithm returns 4-tuples containing two vertex IDs, the" + " number of shared neighbors, and the number of distinct neighbors.", 80)); System.out.println(); System.out.println("usage: JaccardIndex --input <csv | rmat [options]> --output <print | hash | csv [options]>"); System.out.println(); System.out.println("options:"); System.out.println(" --input csv --type <integer | string> --input_filename FILENAME [--input_line_delimiter LINE_DELIMITER] [--input_field_delimiter FIELD_DELIMITER]"); System.out.println(" --input rmat [--scale SCALE] [--edge_factor EDGE_FACTOR]"); System.out.println(); System.out.println(" --output print"); System.out.println(" --output hash"); System.out.println(" --output csv --output_filename FILENAME [--output_line_delimiter LINE_DELIMITER] [--output_field_delimiter FIELD_DELIMITER]"); }
private static void printUsage() { System.out.println(WordUtils.wrap("Lists all triangles in a graph.", 80)); System.out.println(); System.out.println(WordUtils.wrap("This algorithm returns tuples containing the vertex IDs for each triangle and" + " for directed graphs a bitmask indicating the presence of the six potential connecting edges.", 80)); System.out.println(); System.out.println("usage: TriangleListing --directed <true | false> --input <csv | rmat [options]> --output <print | hash | csv [options]>"); System.out.println(); System.out.println("options:"); System.out.println(" --input csv --type <integer | string> --input_filename FILENAME [--input_line_delimiter LINE_DELIMITER] [--input_field_delimiter FIELD_DELIMITER]"); System.out.println(" --input rmat [--scale SCALE] [--edge_factor EDGE_FACTOR]"); System.out.println(); System.out.println(" --output print"); System.out.println(" --output hash"); System.out.println(" --output csv --output_filename FILENAME [--output_line_delimiter LINE_DELIMITER] [--output_field_delimiter FIELD_DELIMITER]"); }
private static void printUsage() { System.out.println(WordUtils.wrap("The local clustering coefficient measures the connectedness of each" + " vertex's neighborhood and the global clustering coefficient measures the connectedness of the graph." + " Scores range from 0.0 (no edges between neighbors or vertices) to 1.0 (neighborhood or graph" + " is a clique).", 80)); System.out.println(); System.out.println(WordUtils.wrap("This algorithm returns tuples containing the vertex ID, the degree of" + " the vertex, and the number of edges between vertex neighbors.", 80)); System.out.println(); System.out.println("usage: ClusteringCoefficient --directed <true | false> --input <csv | rmat [options]> --output <print | hash | csv [options]>"); System.out.println(); System.out.println("options:"); System.out.println(" --input csv --type <integer | string> --input_filename FILENAME [--input_line_delimiter LINE_DELIMITER] [--input_field_delimiter FIELD_DELIMITER]"); System.out.println(" --input rmat [--scale SCALE] [--edge_factor EDGE_FACTOR]"); System.out.println(); System.out.println(" --output print"); System.out.println(" --output hash"); System.out.println(" --output csv --output_filename FILENAME [--output_line_delimiter LINE_DELIMITER] [--output_field_delimiter FIELD_DELIMITER]"); }
private static String getUsage(String message) { return new StrBuilder() .appendNewLine() .appendln("A Graph500 generator using the Recursive Matrix (RMat) graph generator.") .appendNewLine() .appendln(WordUtils.wrap("The graph matrix contains 2^scale vertices although not every vertex will" + " be represented in an edge. The number of edges is edge_factor * 2^scale edges" + " although some edges may be duplicates.", 80)) .appendNewLine() .appendln("Note: this does not yet implement permutation of vertex labels or edges.") .appendNewLine() .appendln("usage: Graph500 --directed <true | false> --simplify <true | false> --output <print | hash | csv [options]>") .appendNewLine() .appendln("options:") .appendln(" --output print") .appendln(" --output hash") .appendln(" --output csv --output_filename FILENAME [--output_line_delimiter LINE_DELIMITER] [--output_field_delimiter FIELD_DELIMITER]") .appendNewLine() .appendln("Usage error: " + message) .toString(); }
public static void changeCTT(String[] args) { StringBuilder sb = new StringBuilder(); int i = 1; while (i <= args.length - 1) { if (i == 1) { sb.append(WordUtils.capitalize(args[i])); } else { sb.append(args[i]); } sb.append("+"); i++; } Defaults.cttText = sb.toString(); Bot.extra.setProperty("ctt", sb.toString()); Save.properties(); }
/** * Set a field of an object with a value, also if the field is of primitive type. * * Apart from this, it mimics behavior from java.reflection.Field.set(Object, Object). */ public static void setFieldFromObject(Object object, Field field, Object value) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { if (!field.getType().isPrimitive()) { field.set(object, value); return; } Class<?> primitiveClass = value.getClass(); if (!primitiveClass.isPrimitive()) { primitiveClass = ClassUtils.wrapperToPrimitive(primitiveClass); if (primitiveClass == null) { throw new IllegalArgumentException(field + " is a primitive field but the value is neither primitive nor wrapper."); } } String assignerName = "set" + WordUtils.capitalize(primitiveClass.getSimpleName()); Method assigner = Field.class.getMethod(assignerName, new Class<?>[] {Object.class, primitiveClass}); assigner.invoke(field, new Object[] {object, value}); }
public static <T extends Date> Renderer<T> fromDatePattern(final IDatePattern datePattern) { Renderer<T> renderer = fromFormat(new SerializableFunction<Locale, DateFormat>() { private static final long serialVersionUID = 1L; @Override public DateFormat apply(Locale locale) { return new SimpleDateFormat(Localizer.get().getString(datePattern.getJavaPatternKey(), null, null, locale, null, (IModel<String>) null), locale); } }); if (datePattern.capitalize()) { renderer = renderer.compose(new SerializableFunction<String, String>() { private static final long serialVersionUID = 1L; @Override public String apply(String input) { return WordUtils.capitalize(input); } }); } return renderer; }
private void addContextGetMethods(String contextName, ComponentData data, JavaClassSource source) { source.addMethod() .setName(String.format("get%1$sEntity", getTypeName(data))) .setReturnType(contextName + "Entity") .setPublic() .setBody(String.format("return getGroup(%1$sMatcher.%2$s()).getSingleEntity();" , WordUtils.capitalize(contextName), getTypeName(data))); if (!isUnique(data)) { source.addMethod() .setName(String.format("get%1$s", getTypeName(data))) .setReturnType(getTypeName(data)) .setPublic() .setBody(String.format("return get%1$sEntity().get%1$s();" , getTypeName(data))); } }
private JavaClassSource generateIndicesLookup(String contextName, List<ComponentData> dataList) { String pkgDestiny = targetPackageConfig.getTargetPackage(); JavaClassSource codeGen = Roaster.parse(JavaClassSource.class, String.format("public class %1$s {}", WordUtils.capitalize(contextName) + DEFAULT_COMPONENT_LOOKUP_TAG)); if (dataList.size() > 0 && !pkgDestiny.endsWith(dataList.get(0).getSubDir()) ) { // pkgDestiny += "." + dataList.get(0).getSubDir(); } codeGen.setPackage(pkgDestiny); addIndices(dataList, codeGen); addComponentNames(dataList, codeGen); addComponentTypes(dataList, codeGen); System.out.println(codeGen); return codeGen; }
private void addMatcherMethods(String contextName, ComponentData data, JavaClassSource codeGenerated) { String body = "if (_matcher%2$s == null) {" + " Matcher matcher = (Matcher)Matcher.AllOf(%1$s.%2$s);" + " matcher.componentNames = %1$s.componentNames();" + " _matcher%2$s = matcher;" + "}" + "return _matcher%2$s;"; codeGenerated.addMethod() .setName(getTypeName(data)) .setReturnType("Matcher") .setPublic() .setStatic(true) .setBody(String.format(body, WordUtils.capitalize(contextName) + DEFAULT_COMPONENT_LOOKUP_TAG, getTypeName(data))); }
@Test public void wordUtilsDemo() { System.out.println("单词处理功能"); String str1 = "wOrD"; String str2 = "ghj\nui\tpo"; System.out.println(WordUtils.capitalize(str1)); // 首字母大写 System.out.println(WordUtils.capitalizeFully(str1)); // 首字母大写其它字母小写 char[] ctrg = { '.' }; System.out.println(WordUtils.capitalizeFully("i aM.fine", ctrg)); // 在规则地方转换 System.out.println(WordUtils.initials(str1)); // 获取首字母 System.out.println(WordUtils.initials("Ben John Lee", null)); // 取每个单词的首字母 char[] ctr = { ' ', '.' }; System.out.println(WordUtils.initials("Ben J.Lee", ctr)); // 按指定规则获取首字母 System.out.println(WordUtils.swapCase(str1)); // 大小写逆转 System.out.println(WordUtils.wrap(str2, 1)); // 解析\n和\t等字符 }
@Override protected void updateItem(ExternalRef item, boolean empty) { super.updateItem(item, empty); this.value = empty ? Optional.empty() : Optional.of(item); this.layout.setVisible(!empty); try { txtRefType.setText(empty ? "" : item.getReferenceType().getReferenceTypeUri().toString()); txtLocator.setText(empty ? "" : item.getReferenceLocator()); if (!empty){ chcCategory.setValue(WordUtils.capitalize(item.getReferenceCategory().getTag())); } } catch (InvalidSPDXAnalysisException e) { throw new RuntimeException(e); } setGraphic(layout); }
static String modify(String toModify, String modifier) { switch (modifier) { case ModifierTypes.LOWER: return toModify.toLowerCase(); case ModifierTypes.UPPER: return toModify.toUpperCase(); case ModifierTypes.FIRST_CAP: return StrUtils.capitalizeFully(toModify); case ModifierTypes.WORD_CAP: return WordUtils.capitalizeFully(toModify); case ModifierTypes.FIRST_CAP_SOFT: return StringUtils.capitalize(toModify); case ModifierTypes.WORD_CAP_SOFT: return WordUtils.capitalize(toModify); default: return toModify; } }
private void saveFeature(AnnotationFeature aFeature) { // Set properties of link features since these are currently not configurable in the UI if (!PRIMITIVE_TYPES.contains(aFeature.getType()) && !aFeature.isVirtualFeature()) { aFeature.setMode(MultiValueMode.ARRAY); aFeature.setLinkMode(LinkMode.WITH_ROLE); aFeature.setLinkTypeRoleFeatureName("role"); aFeature.setLinkTypeTargetFeatureName("target"); aFeature.setLinkTypeName(aFeature.getLayer().getName() + WordUtils.capitalize(aFeature.getName()) + "Link"); } // If the feature is not a string feature or a link-with-role feature, force the tagset // to null. if (!(CAS.TYPE_NAME_STRING.equals(aFeature.getType()) || !PRIMITIVE_TYPES.contains(aFeature .getType()))) { aFeature.setTagset(null); } applicationEventPublisherHolder.get() .publishEvent(new LayerConfigurationChangedEvent(this, aFeature.getProject())); annotationService.createFeature(aFeature); featureDetailForm.setVisible(false); }
/** * This is a generic method that copies the simple attribute values from an * argument jsonObject to an argument generic object. * * @param jsonObject * The jsonObject from where the attributes are to be copied. * @param destObject * The object where the attributes should be copied into. * @throws Exception * Throws a Exception when the operation are unsuccessful. */ public static <T> void convertJSONObjectToDirectoryObject(JSONObject jsonObject, T destObject) throws Exception { // Get the list of all the field names. Field[] fieldList = destObject.getClass().getDeclaredFields(); // For all the declared field. for (int i = 0; i < fieldList.length; i++) { // If the field is of type String, that is // if it is a simple attribute. if (fieldList[i].getType().equals(String.class)) { // Invoke the corresponding set method of the destObject using // the argument taken from the jsonObject. destObject .getClass() .getMethod(String.format("set%s", WordUtils.capitalize(fieldList[i].getName())), new Class[] { String.class }) .invoke(destObject, new Object[] { jsonObject.optString(fieldList[i].getName()) }); } } }
private String classificationLine(List<Taxon> classification, int index, Options options) { if(index == classification.size()-1) { return String.format("<ol><li><h1 class=\"c-summary__heading\">%s</h1></li><ol>", taxonNameAndAuthor(classification.get(index), options)); } else { if(classification.get(index).getTaxonRank() == null) { return String.format("<ol><li>%s%s</li></ol>", taxonLink(classification.get(index), options), classificationLine(classification, index+1, options)); } else { return String.format("<ol><li>%s: %s%s</li></ol>", WordUtils.capitalize(classification.get(index).getTaxonRank().toString().toLowerCase()), taxonLink(classification.get(index), options), classificationLine(classification, index+1, options)); } } }