|
| 1 | +/* |
| 2 | + * Copyright © Magento, Inc. All rights reserved. |
| 3 | + * See COPYING.txt for license details. |
| 4 | + */ |
| 5 | + |
| 6 | +package com.magento.idea.magento2plugin.actions.generation.dialog.prompt; |
| 7 | + |
| 8 | +import java.lang.reflect.Field; |
| 9 | +import java.lang.reflect.Modifier; |
| 10 | +import javax.swing.text.JTextComponent; |
| 11 | +import org.jdesktop.swingx.prompt.PromptSupport; |
| 12 | +import org.jetbrains.annotations.NotNull; |
| 13 | + |
| 14 | +public final class PlaceholderInitializerUtil { |
| 15 | + |
| 16 | + private static final String PLACEHOLDER_CLIENT_PROPERTY = "promptText"; |
| 17 | + |
| 18 | + private final Class<?> type; |
| 19 | + private final Object object; |
| 20 | + |
| 21 | + /** |
| 22 | + * PlaceholderInitializerUtil constructor. |
| 23 | + * |
| 24 | + * @param object Object |
| 25 | + */ |
| 26 | + public PlaceholderInitializerUtil(final @NotNull Object object) { |
| 27 | + this.object = object; |
| 28 | + type = object.getClass(); |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Initialize placeholders for supported field types if specified promptText client property. |
| 33 | + */ |
| 34 | + public void initialize() { |
| 35 | + for (final Field field : type.getDeclaredFields()) { |
| 36 | + final JTextComponent target = getTarget(field); |
| 37 | + |
| 38 | + if (target == null) { |
| 39 | + continue; |
| 40 | + } |
| 41 | + final Object promptProperty = target.getClientProperty( |
| 42 | + PLACEHOLDER_CLIENT_PROPERTY |
| 43 | + ); |
| 44 | + |
| 45 | + if (promptProperty == null) { |
| 46 | + continue; |
| 47 | + } |
| 48 | + PromptSupport.setPrompt((String) promptProperty, target); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + private JTextComponent getTarget(final Field field) { |
| 53 | + if (Modifier.isStatic(field.getModifiers())) { |
| 54 | + return null; |
| 55 | + } |
| 56 | + final boolean isAccessible = field.canAccess(object); |
| 57 | + field.setAccessible(true); |
| 58 | + |
| 59 | + try { |
| 60 | + final Object value = field.get(object); |
| 61 | + |
| 62 | + return value instanceof JTextComponent ? (JTextComponent) value : null; |
| 63 | + } catch (IllegalAccessException exception) { |
| 64 | + return null; |
| 65 | + } finally { |
| 66 | + field.setAccessible(isAccessible); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments