List of usage examples for java.lang.reflect Type equals
public boolean equals(Object obj)
From source file:com.liferay.tool.datamanipulator.handler.BaseHandler.java
private Object[] _getArgs(String[] argNames, Class<?>[] argClazzs, RequestContext requestContext, Map<String, Object> entrySpecifiedArgs) throws Exception { long companyId = requestContext.getCompanyId(); long groupId = requestContext.getGroupId(); long userId = requestContext.getUserId(); Date now = new Date(); ServiceContext serviceContext = HandlerUtil.getServiceContext(groupId, userId); Map<String, Calendar> dateMap = new HashMap<String, Calendar>(entryDateFields.size()); for (String entryDateField : entryDateFields) { String dateVarName = entryDateField + "Date"; String dateKeyName = entryDateField + "-date"; Date serviceContextDate = (Date) BeanUtil.getPropertySilently(serviceContext, dateVarName); Calendar dateVarValue;//from w ww . j a v a 2 s . c om if (requestContext.contains(dateKeyName + "-from") && requestContext.contains(dateKeyName + "-to")) { dateVarValue = requestContext.getBetweenCalendar(dateKeyName); } else if (Validator.isNotNull(serviceContextDate)) { dateVarValue = Calendar.getInstance(); dateVarValue.setTime(serviceContextDate); } else { dateVarValue = Calendar.getInstance(); dateVarValue.setTime(now); } dateMap.put(dateVarName, dateVarValue); } StringBuilder sb = new StringBuilder(); sb.append(_entryName); sb.append(requestContext.getString("entryCount")); sb.append(" ${fieldName} "); if (requestContext.contains("editCount")) { sb.append("Edited "); sb.append(requestContext.getString("editCount")); sb.append(" times "); } sb.append(requestContext.getRandomString()); String entryTemplate = sb.toString(); User user = UserLocalServiceUtil.fetchUser(userId); List<Object> argValues = new ArrayList<Object>(argNames.length); for (int i = 0; i < argNames.length; i++) { String argName = argNames[i]; Class<?> argClazz = argClazzs[i]; if (entrySpecifiedArgs.containsKey(argName)) { argValues.add(entrySpecifiedArgs.get(argName)); } else if (argName.equals(Field.COMPANY_ID)) { argValues.add(companyId); } else if (argName.matches(".*Date.*")) { int x = argName.indexOf("Date") + 4; String dateKey = argName.substring(0, x); Calendar calendar = dateMap.get(dateKey); String calendarFieldName = argName.substring(x).toUpperCase(); if (calendarFieldName.equals("DAY")) { calendarFieldName = "DATE"; } int calendarFieldValue = (Integer) GetterUtil.getFieldValue(Calendar.class.getName(), calendarFieldName); argValues.add(calendar.get(calendarFieldValue)); } else if (entryStringFields.contains(argName)) { Map<String, String> context = new HashMap<String, String>(1); context.put("fieldName", argName); String content = StringUtil.getStringFieldValue(argName, context, entryTemplate); argValues.add(content); } else if (entryMapFields.contains(argName)) { argName = argName.substring(0, (argName.length() - 3)); Map<String, String> context = new HashMap<String, String>(1); context.put("fieldName", argName); String content = StringUtil.getStringFieldValue(argName, context, entryTemplate); argValues.add(StringUtil.getLocalizationMap(content)); } else if (argName.equals("friendlyURL")) { Map<String, String> context = new HashMap<String, String>(1); context.put("fieldName", "name"); String friendlyURL = StringUtil.getStringFieldValue(argName, context, entryTemplate); friendlyURL = StringPool.SLASH + FriendlyURLNormalizerUtil.normalize(friendlyURL); argValues.add(friendlyURL); } else if (argName.equals(Field.GROUP_ID)) { argValues.add(groupId); } else if (argName.equals(getParentClassPKName())) { argValues.add(Long.valueOf(_getParentClassPK(requestContext))); } else if (argName.equals("locale")) { argValues.add(LocaleUtil.getDefault()); } else if (argName.equals("serviceContext")) { argValues.add(serviceContext); } else if (argName.equals(Field.USER_ID)) { argValues.add(userId); } else if (argName.equals(Field.USER_NAME)) { argValues.add(user.getFullName()); } else if (requestContext.contains(argName)) { argValues.add(requestContext.get(argName)); } else { Object argValue = null; try { Object object = argClazz.newInstance(); if (object instanceof String) { argValue = StringPool.BLANK; } } catch (InstantiationException e) { Type type = argClazz; if (type.equals(Boolean.TYPE)) { argValue = false; } else if (type.equals(Integer.TYPE)) { argValue = (int) 0; } else if (type.equals(List.class)) { argValue = new ArrayList<Object>(0); } else if (type.equals(Long.TYPE)) { argValue = (long) 0; } } argValues.add(argValue); } } return (Object[]) argValues.toArray(new Object[argValues.size()]); }
From source file:org.wrml.runtime.format.ParserModelGraph.java
private Object convertRawIntegerValue(final Integer rawValue) { final DimensionsBuilder dimensionsBuilder = _DimensionsBuilderStack.peek(); final URI modelSchemaUri = dimensionsBuilder.getSchemaUri(); if (modelSchemaUri == null) { return rawValue; }/* ww w. ja va2s . c o m*/ final String slotName = _SlotNameStack.peek(); final Context context = getContext(); final SchemaLoader schemaLoader = context.getSchemaLoader(); final Prototype prototype = schemaLoader.getPrototype(modelSchemaUri); final ProtoSlot protoSlot = prototype.getProtoSlot(slotName); final Type slotType = protoSlot.getHeapValueType(); if (slotType.equals(Integer.class) || (slotType.equals(int.class) && rawValue != null)) { return rawValue; } final ScopeType scopeType = _ScopeStack.peek(); switch (scopeType) { case Model: { if (slotType.equals(Long.class) || (slotType.equals(long.class) && rawValue != null)) { return new Long(rawValue); } if (slotType.equals(Double.class) || (slotType.equals(double.class) && rawValue != null)) { return new Double(rawValue); } break; } case List: { if (protoSlot.getValueType() == ValueType.List) { final Type listElementType = ((PropertyProtoSlot) protoSlot).getListElementType(); if (listElementType.equals(Long.class) || (listElementType.equals(long.class) && rawValue != null)) { return new Long(rawValue); } if (listElementType.equals(Double.class) || (listElementType.equals(double.class) && rawValue != null)) { return new Double(rawValue); } } break; } } // End of switch final ModelGraphException e = new ModelGraphException( "Unable to transform schema (" + modelSchemaUri + ") slot named \"" + slotName + "\" raw String value \"" + rawValue + "\" to type " + slotType + ".", this); ParserModelGraph.LOG.error(e.getMessage(), e); throw e; }
From source file:richtercloud.reflection.form.builder.fieldhandler.MappingFieldHandler.java
/** * Figures out candidates which the longest common prefix in the * {@code fieldParameterizedType} chain of (nested) generic types ignoring * specifications of {@link AnyType}. Then determines the candidates with * the smallest number of {@link AnyType} specifications in the chain. If * there're multiple with the same number of {@link AnyType} chooses the * first it finds which might lead to random choices. * * @param fieldParameterizedType the chain of generic types (remember to * retrieve this information with {@link Field#getGenericType() } instead of * {@link Field#getType() } from fields) * @return the choice result as described above or {@code null} if no * candidate exists/* w ww. jav a 2 s . com*/ */ protected Type retrieveClassMappingBestMatch(ParameterizedType fieldParameterizedType) { //check in a row (walking a tree doesn't make sense because it's //agnostic of the position of the type SortedMap<Integer, List<ParameterizedType>> candidates = new TreeMap<>(); //TreeMap is a SortedMap for (Type mappingType : classMapping.keySet()) { if (!(mappingType instanceof ParameterizedType)) { continue; } ParameterizedType mappingParameterizedType = (ParameterizedType) mappingType; if (!mappingParameterizedType.getRawType().equals(fieldParameterizedType.getRawType())) { continue; } Type[] parameterizedTypeArguments = mappingParameterizedType.getActualTypeArguments(); Type[] fieldParameterizedTypeArguments = fieldParameterizedType.getActualTypeArguments(); for (int i = 0; i < Math.min(parameterizedTypeArguments.length, fieldParameterizedTypeArguments.length); i++) { if (fieldParameterizedTypeArguments[i].equals(AnyType.class)) { throw new IllegalArgumentException(String.format( "type %s must only be used to declare placeholders in class mapping, not in classes (was used in field type %s", AnyType.class, fieldParameterizedType)); } // only compare raw type to raw type in the chain Type fieldParameterizedTypeArgument = fieldParameterizedTypeArguments[i]; if (fieldParameterizedTypeArgument instanceof ParameterizedType) { fieldParameterizedTypeArgument = ((ParameterizedType) fieldParameterizedTypeArgument) .getRawType(); } Type parameterizedTypeArgument = parameterizedTypeArguments[i]; if (parameterizedTypeArgument instanceof ParameterizedType) { parameterizedTypeArgument = ((ParameterizedType) parameterizedTypeArgument).getRawType(); } //record AnyType matches as well boolean anyTypeMatch = AnyType.class.equals(parameterizedTypeArgument); //work around sucky debugger if (!parameterizedTypeArgument.equals(fieldParameterizedTypeArgument) && !anyTypeMatch) { break; } int matchCount = i + 1; List<ParameterizedType> candidateList = candidates.get(matchCount); if (candidateList == null) { candidateList = new LinkedList<>(); candidates.put(matchCount, candidateList); } candidateList.add(mappingParameterizedType); } } if (candidates.isEmpty()) { return null; //avoid NoSuchElementException } List<ParameterizedType> higestCandidatesList = candidates.get(candidates.lastKey()); int lowestAnyCount = Integer.MAX_VALUE; ParameterizedType lowestAnyCountCandidate = null; for (ParameterizedType highestCandidateCandidate : higestCandidatesList) { int highestCandidateCandidateAnyCount = retrieveAnyCountRecursively(highestCandidateCandidate); if (highestCandidateCandidateAnyCount < lowestAnyCount) { lowestAnyCount = highestCandidateCandidateAnyCount; lowestAnyCountCandidate = highestCandidateCandidate; } } return lowestAnyCountCandidate; }
From source file:au.com.addstar.cellblock.configuration.AutoConfig.java
public boolean save() { try {//from w w w . j av a2s . co m onPreSave(); YamlConfiguration config = new YamlConfiguration(); Map<String, String> comments = new HashMap<>(); // Add all the category comments comments.putAll(mCategoryComments); // Add all the values for (Field field : getClass().getDeclaredFields()) { ConfigField configField = field.getAnnotation(ConfigField.class); if (configField == null) continue; String optionName = configField.name(); if (optionName.isEmpty()) optionName = field.getName(); field.setAccessible(true); String path = (configField.category().isEmpty() ? "" : configField.category() + ".") + optionName; //$NON-NLS-2$ // Ensure the secion exists if (!configField.category().isEmpty() && !config.contains(configField.category())) config.createSection(configField.category()); if (field.getType().isArray()) { // Integer if (field.getType().getComponentType().equals(Integer.TYPE)) config.set(path, Arrays.asList((Integer[]) field.get(this))); // Float else if (field.getType().getComponentType().equals(Float.TYPE)) config.set(path, Arrays.asList((Float[]) field.get(this))); // Double else if (field.getType().getComponentType().equals(Double.TYPE)) config.set(path, Arrays.asList((Double[]) field.get(this))); // Long else if (field.getType().getComponentType().equals(Long.TYPE)) config.set(path, Arrays.asList((Long[]) field.get(this))); // Short else if (field.getType().getComponentType().equals(Short.TYPE)) config.set(path, Arrays.asList((Short[]) field.get(this))); // Boolean else if (field.getType().getComponentType().equals(Boolean.TYPE)) config.set(path, Arrays.asList((Boolean[]) field.get(this))); // String else if (field.getType().getComponentType().equals(String.class)) config.set(path, Arrays.asList((String[]) field.get(this))); else throw new IllegalArgumentException( "Cannot use type " + field.getType().getSimpleName() + " for AutoConfiguration"); //$NON-NLS-2$ } else if (List.class.isAssignableFrom(field.getType())) { if (field.getGenericType() == null) throw new IllegalArgumentException( "Cannot use type List without specifying generic type for AutoConfiguration"); Type type = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; if (type.equals(Integer.class) || type.equals(Float.class) || type.equals(Double.class) || type.equals(Long.class) || type.equals(Short.class) || type.equals(Boolean.class) || type.equals(String.class)) { config.set(path, field.get(this)); } else throw new IllegalArgumentException("Cannot use type " + field.getType().getSimpleName() + "<" + type.toString() + "> for AutoConfiguration"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (Set.class.isAssignableFrom(field.getType())) { if (field.getGenericType() == null) throw new IllegalArgumentException( "Cannot use type Set without specifying generic type for AutoConfiguration"); Type type = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0]; if (type.equals(Integer.class) || type.equals(Float.class) || type.equals(Double.class) || type.equals(Long.class) || type.equals(Short.class) || type.equals(Boolean.class) || type.equals(String.class)) { config.set(path, new ArrayList<Object>((Set<?>) field.get(this))); } else throw new IllegalArgumentException("Cannot use type " + field.getType().getSimpleName() + "<" + type.toString() + "> for AutoConfiguration"); //$NON-NLS-1$ //$NON-NLS-2$ } else { // Integer if (field.getType().equals(Integer.TYPE)) config.set(path, field.get(this)); // Float else if (field.getType().equals(Float.TYPE)) config.set(path, field.get(this)); // Double else if (field.getType().equals(Double.TYPE)) config.set(path, field.get(this)); // Long else if (field.getType().equals(Long.TYPE)) config.set(path, field.get(this)); // Short else if (field.getType().equals(Short.TYPE)) config.set(path, field.get(this)); // Boolean else if (field.getType().equals(Boolean.TYPE)) config.set(path, field.get(this)); // ItemStack else if (field.getType().equals(ItemStack.class)) config.set(path, field.get(this)); // String else if (field.getType().equals(String.class)) config.set(path, field.get(this)); else throw new IllegalArgumentException( "Cannot use type " + field.getType().getSimpleName() + " for AutoConfiguration"); //$NON-NLS-2$ } // Record the comment if (!configField.comment().isEmpty()) comments.put(path, configField.comment()); } String output = config.saveToString(); // Apply comments String category = ""; List<String> lines = new ArrayList<>(Arrays.asList(output.split("\n"))); for (int l = 0; l < lines.size(); l++) { String line = lines.get(l); if (line.startsWith("#")) continue; if (line.trim().startsWith("-")) continue; if (!line.contains(":")) continue; String path; line = line.substring(0, line.indexOf(":")); if (line.startsWith(" ")) path = category + "." + line.substring(2).trim(); else { category = line.trim(); path = line.trim(); } if (comments.containsKey(path)) { String indent = ""; for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == ' ') indent += " "; else break; } // Add in the comment lines String[] commentLines = comments.get(path).split("\n"); lines.add(l++, ""); for (int i = 0; i < commentLines.length; i++) { commentLines[i] = indent + "# " + commentLines[i]; lines.add(l++, commentLines[i]); } } } output = ""; for (String line : lines) output += line + "\n"; FileWriter writer = new FileWriter(mFile); writer.write(output); writer.close(); return true; } catch (IllegalArgumentException | IOException | IllegalAccessException e) { e.printStackTrace(); } return false; }
From source file:org.wrml.runtime.format.ParserModelGraph.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private Object convertRawStringValue(final String rawValue) { final DimensionsBuilder dimensionsBuilder = _DimensionsBuilderStack.peek(); final URI schemaUri = dimensionsBuilder.getSchemaUri(); if (schemaUri == null) { return rawValue; }//from w w w . j a v a2 s .co m final ScopeType scopeType = _ScopeStack.peek(); final String slotName = _SlotNameStack.peek(); // Check if the slotName is heapId if (slotName.equals(Model.SLOT_NAME_HEAP_ID) && scopeType.equals(ScopeType.Model)) { LOG.debug("Current slot is a Heap Id {}", rawValue); final UUID heapId = UUID.fromString(rawValue); if (_ShortcutModels.containsKey(heapId)) { // Need to stuff this into the current model location.... return _ShortcutModels.get(heapId); } else { // Assumes scope type is Model LOG.debug("Creating new model with schema {} with heapId {}", new Object[] { schemaUri, heapId }); // Pull the created reference from the model stack and put into the map final Model parentModel = _ModelStack.peek(); _ShortcutModels.put(heapId, parentModel); // Return null if we're in the first occurrence return null; } } final Context context = getContext(); final SchemaLoader schemaLoader = context.getSchemaLoader(); final SyntaxLoader syntaxLoader = context.getSyntaxLoader(); final Prototype prototype = schemaLoader.getPrototype(schemaUri); // TODO fix this for HEAP ID's { final ProtoSlot protoSlot = prototype.getProtoSlot(slotName); final Type slotType = protoSlot.getHeapValueType(); if (slotType.equals(String.class)) { return rawValue; } switch (scopeType) { case Model: { if (TypeUtils.isAssignable(slotType, Enum.class)) { return Enum.valueOf((Class<Enum>) slotType, rawValue); } else if (slotType instanceof Class<?>) { final SyntaxHandler<?> syntaxHandler = syntaxLoader.getSyntaxHandler((Class<?>) slotType); if (syntaxHandler != null) { return syntaxHandler.parseSyntacticText(rawValue); } } break; } case List: { if (protoSlot.getValueType() == ValueType.List) { final Type listElementType = ((PropertyProtoSlot) protoSlot).getListElementType(); if (String.class.equals(listElementType)) { return rawValue; } else if (TypeUtils.isAssignable(listElementType, Enum.class)) { return Enum.valueOf((Class<Enum>) listElementType, rawValue); } else if (listElementType instanceof Class<?>) { final SyntaxHandler<?> syntaxHandler = syntaxLoader .getSyntaxHandler((Class<?>) listElementType); if (syntaxHandler != null) { return syntaxHandler.parseSyntacticText(rawValue); } } } break; } } // End of switch final ModelGraphException e = new ModelGraphException( "Unable to transform schema (" + schemaUri + ") slot named \"" + slotName + "\" raw String value \"" + rawValue + "\" to type " + slotType + ".", this); ParserModelGraph.LOG.error(e.getMessage(), e); throw e; }
From source file:com.uphyca.idobata.transform.JSONConverter.java
@Override public Object convert(TypedInput body, Type type) throws ConversionException, IOException { String src;//from w w w. j a va 2 s. c o m InputStream in = null; try { in = body.in(); src = drain(in); } finally { if (in != null) { in.close(); } } try { JSONObject json = new JSONObject(src); if (type.equals(Seed.class)) { Seed seed = new SeedBean(); drain(json, seed); return seed; } if (type.equals(Room[].class)) { return asRoomList(getJSONArray(json, "rooms")); } if (type.equals(Room.class)) { Room room = new RoomBean(); drain(getJSONObject(json, "room"), room); return room; } if (type.equals(Message[].class)) { return asMessageList(getJSONArray(json, "messages")); } if (type.equals(Message.class)) { Message message = new MessageBean(); drain(getJSONObject(json, "message"), message); return message; } if (type.equals(User[].class)) { return asUserList((getJSONArray(json, "users"))); } if (type.equals(User.class)) { User user = new UserBean(); drain(getJSONObject(json, "user"), user); return user; } if (type.equals(Bot[].class)) { return asBotList((getJSONArray(json, "bots"))); } if (type.equals(Bot.class)) { Bot bot = new BotBean(); drain(getJSONObject(json, "bot"), bot); return bot; } if (type.equals(MemberStatusChangedEvent.class)) { return asMemberStatusChangedEvent(json); } if (type.equals(MessageCreatedEvent.class)) { return asMessageCreatedEvent(getJSONObject(json, "message")); } if (type.equals(RoomTouchedEvent.class)) { return asRoomTouchedEvent(json); } } catch (JSONException e) { throw new ConversionException(e); } throw new IllegalArgumentException(); }
From source file:com.iCo6.iConomy.java
public void onEnable() { final long startTime = System.nanoTime(); final long endTime; try {//from www . j ava2s . c o m // Localize locale to prevent issues. Locale.setDefault(Locale.US); // Server & Terminal Support Server = getServer(); if (getServer().getServerName().equalsIgnoreCase("craftbukkit")) { TerminalSupport = ((CraftServer) getServer()).getReader().getTerminal().isAnsiSupported(); } // Get general plugin information info = getDescription(); // Plugin directory setup directory = getDataFolder(); if (!directory.exists()) directory.mkdir(); // Extract Files Common.extract("Config.yml", "Template.yml"); // Setup Configuration Constants.load(new File(directory, "Config.yml")); // Setup Template Template = new Template(directory.getPath(), "Template.yml"); // Upgrade Template to 6.0.9b LinkedHashMap<String, String> nodes = new LinkedHashMap<String, String>(); nodes.put("top.opening", "<green>-----[ <white>Wealthiest Accounts <green>]-----"); nodes.put("top.item", "<gray>+i. <green>+name <gray>- <white>+amount"); try { Template.update(nodes); } catch (IOException ex) { System.out.println(ex.getMessage()); } // Check Drivers if needed Type type = Database.getType(Constants.Nodes.DatabaseType.toString()); if (!(type.equals(Type.InventoryDB) || type.equals(Type.MiniDB))) { Drivers driver = null; switch (type) { case H2DB: driver = Constants.Drivers.H2; break; case MySQL: driver = Constants.Drivers.MySQL; break; case SQLite: driver = Constants.Drivers.SQLite; break; case Postgre: driver = Constants.Drivers.Postgre; break; } if (driver != null) if (!(new File("lib", driver.getFilename()).exists())) { System.out.println("[iConomy] Downloading " + driver.getFilename() + "..."); wget.fetch(driver.getUrl(), driver.getFilename()); System.out.println("[iConomy] Finished Downloading."); } } // Setup Commands Commands.add("/money +name", new Money(this)); Commands.setPermission("money", "iConomy.holdings"); Commands.setPermission("money+", "iConomy.holdings.others"); Commands.setHelp("money", new String[] { "", "Check your balance." }); Commands.setHelp("money+", new String[] { " [name]", "Check others balance." }); Commands.add("/money -h|?|help +command", new Help(this)); Commands.setPermission("help", "iConomy.help"); Commands.setHelp("help", new String[] { " (command)", "For Help & Information." }); Commands.add("/money -t|top", new Top(this)); Commands.setPermission("top", "iConomy.top"); Commands.setHelp("top", new String[] { "", "View top economical accounts." }); Commands.add("/money -p|pay +name +amount:empty", new Payment(this)); Commands.setPermission("pay", "iConomy.payment"); Commands.setHelp("pay", new String[] { " [name] [amount]", "Send money to others." }); Commands.add("/money -c|create +name", new Create(this)); Commands.setPermission("create", "iConomy.accounts.create"); Commands.setHelp("create", new String[] { " [name]", "Create an account." }); Commands.add("/money -r|remove +name", new Remove(this)); Commands.setPermission("remove", "iConomy.accounts.remove"); Commands.setHelp("remove", new String[] { " [name]", "Remove an account." }); Commands.add("/money -g|give +name +amount:empty", new Give(this)); Commands.setPermission("give", "iConomy.accounts.give"); Commands.setHelp("give", new String[] { " [name] [amount]", "Give money." }); Commands.add("/money -t|take +name +amount:empty", new Take(this)); Commands.setPermission("take", "iConomy.accounts.take"); Commands.setHelp("take", new String[] { " [name] [amount]", "Take money." }); Commands.add("/money -s|set +name +amount:empty", new Set(this)); Commands.setPermission("set", "iConomy.accounts.set"); Commands.setHelp("set", new String[] { " [name] [amount]", "Set account balance." }); Commands.add("/money -u|status +name +status:empty", new Status(this)); Commands.setPermission("status", "iConomy.accounts.status"); Commands.setPermission("status+", "iConomy.accounts.status.set"); Commands.setHelp("status", new String[] { " [name] (status)", "Check/Set account status." }); Commands.add("/money -x|purge", new Purge(this)); Commands.setPermission("purge", "iConomy.accounts.purge"); Commands.setHelp("purge", new String[] { "", "Purge all accounts with initial holdings." }); Commands.add("/money -e|empty", new Empty(this)); Commands.setPermission("empty", "iConomy.accounts.empty"); Commands.setHelp("empty", new String[] { "", "Empty database of accounts." }); // Setup Database. try { Database = new Database(Constants.Nodes.DatabaseType.toString(), Constants.Nodes.DatabaseUrl.toString(), Constants.Nodes.DatabaseUsername.toString(), Constants.Nodes.DatabasePassword.toString()); // Check to see if it's a binary database, if so, check the database existance // If it doesn't exist, Create one. if (Database.isSQL()) { if (!Database.tableExists(Constants.Nodes.DatabaseTable.toString())) { String SQL = Common.resourceToString( "SQL/Core/Create-Table-" + Database.getType().toString().toLowerCase() + ".sql"); SQL = String.format(SQL, Constants.Nodes.DatabaseTable.getValue()); try { QueryRunner run = new QueryRunner(); Connection c = iConomy.Database.getConnection(); try { run.update(c, SQL); } catch (SQLException ex) { System.out.println("[iConomy] Error creating database: " + ex); } finally { DbUtils.close(c); } } catch (SQLException ex) { System.out.println("[iConomy] Database Error: " + ex); } } } else { this.onConversion(); } } catch (MissingDriver ex) { System.out.println(ex.getMessage()); } getServer().getPluginManager().registerEvents(new players(), this); } finally { endTime = System.nanoTime(); } // Setup Interest if (Constants.Nodes.Interest.getBoolean()) { Thrun.init(new Runnable() { public void run() { long time = Constants.Nodes.InterestTime.getLong() * 1000L; Interest = new Timer(); Interest.scheduleAtFixedRate(new Interest(getDataFolder().getPath()), time, time); } }); } if (Constants.Nodes.Purging.getBoolean()) { Thrun.init(new Runnable() { public void run() { Queried.purgeDatabase(); System.out.println("[" + info.getName() + " - " + Constants.Nodes.CodeName.toString() + "] Purged accounts with default balance."); } }); } final long duration = endTime - startTime; // Finish System.out.println("[" + info.getName() + " - " + Constants.Nodes.CodeName.toString() + "] Enabled (" + Common.readableProfile(duration) + ")"); }
From source file:au.com.addstar.cellblock.configuration.AutoConfig.java
@SuppressWarnings("unchecked") public boolean load() { FileConfiguration yml = new YamlConfiguration(); try {// w w w.ja v a2 s. c o m if (mFile.getParentFile().exists() || mFile.getParentFile().mkdirs()) {// Make sure the file exists if (mFile.exists() || mFile.createNewFile()) { // Parse the config yml.load(mFile); for (Field field : getClass().getDeclaredFields()) { ConfigField configField = field.getAnnotation(ConfigField.class); if (configField == null) continue; String optionName = configField.name(); if (optionName.isEmpty()) optionName = field.getName(); field.setAccessible(true); String path = (configField.category().isEmpty() ? "" : configField.category() + ".") //$NON-NLS-2$ + optionName; if (!yml.contains(path)) { if (field.get(this) == null) throw new InvalidConfigurationException( path + " is required to be set! Info:\n" + configField.comment()); } else { // Parse the value if (field.getType().isArray()) { // Integer if (field.getType().getComponentType().equals(Integer.TYPE)) field.set(this, yml.getIntegerList(path).toArray(new Integer[0])); // Float else if (field.getType().getComponentType().equals(Float.TYPE)) field.set(this, yml.getFloatList(path).toArray(new Float[0])); // Double else if (field.getType().getComponentType().equals(Double.TYPE)) field.set(this, yml.getDoubleList(path).toArray(new Double[0])); // Long else if (field.getType().getComponentType().equals(Long.TYPE)) field.set(this, yml.getLongList(path).toArray(new Long[0])); // Short else if (field.getType().getComponentType().equals(Short.TYPE)) field.set(this, yml.getShortList(path).toArray(new Short[0])); // Boolean else if (field.getType().getComponentType().equals(Boolean.TYPE)) field.set(this, yml.getBooleanList(path).toArray(new Boolean[0])); // String else if (field.getType().getComponentType().equals(String.class)) { field.set(this, yml.getStringList(path).toArray(new String[0])); } else throw new IllegalArgumentException("Cannot use type " + field.getType().getSimpleName() + " for AutoConfiguration"); //$NON-NLS-1$ } else if (List.class.isAssignableFrom(field.getType())) { if (field.getGenericType() == null) throw new IllegalArgumentException( "Cannot use type List without specifying generic type for AutoConfiguration"); Type type = ((ParameterizedType) field.getGenericType()) .getActualTypeArguments()[0]; if (type.equals(Integer.class)) field.set(this, newList((Class<? extends List<Integer>>) field.getType(), yml.getIntegerList(path))); else if (type.equals(Float.class)) field.set(this, newList((Class<? extends List<Float>>) field.getType(), yml.getFloatList(path))); else if (type.equals(Double.class)) field.set(this, newList((Class<? extends List<Double>>) field.getType(), yml.getDoubleList(path))); else if (type.equals(Long.class)) field.set(this, newList((Class<? extends List<Long>>) field.getType(), yml.getLongList(path))); else if (type.equals(Short.class)) field.set(this, newList((Class<? extends List<Short>>) field.getType(), yml.getShortList(path))); else if (type.equals(Boolean.class)) field.set(this, newList((Class<? extends List<Boolean>>) field.getType(), yml.getBooleanList(path))); else if (type.equals(String.class)) field.set(this, newList((Class<? extends List<String>>) field.getType(), yml.getStringList(path))); else throw new IllegalArgumentException( "Cannot use type " + field.getType().getSimpleName() + "<" //$NON-NLS-2$ + type.toString() + "> for AutoConfiguration"); } else if (Set.class.isAssignableFrom(field.getType())) { if (field.getGenericType() == null) throw new IllegalArgumentException( "Cannot use type set without specifying generic type for AytoConfiguration"); Type type = ((ParameterizedType) field.getGenericType()) .getActualTypeArguments()[0]; if (type.equals(Integer.class)) field.set(this, newSet((Class<? extends Set<Integer>>) field.getType(), yml.getIntegerList(path))); else if (type.equals(Float.class)) field.set(this, newSet((Class<? extends Set<Float>>) field.getType(), yml.getFloatList(path))); else if (type.equals(Double.class)) field.set(this, newSet((Class<? extends Set<Double>>) field.getType(), yml.getDoubleList(path))); else if (type.equals(Long.class)) field.set(this, newSet((Class<? extends Set<Long>>) field.getType(), yml.getLongList(path))); else if (type.equals(Short.class)) field.set(this, newSet((Class<? extends Set<Short>>) field.getType(), yml.getShortList(path))); else if (type.equals(Boolean.class)) field.set(this, newSet((Class<? extends Set<Boolean>>) field.getType(), yml.getBooleanList(path))); else if (type.equals(String.class)) field.set(this, newSet((Class<? extends Set<String>>) field.getType(), yml.getStringList(path))); else throw new IllegalArgumentException( "Cannot use type " + field.getType().getSimpleName() + "<" //$NON-NLS-2$ + type.toString() + "> for AutoConfiguration"); } else { // Integer if (field.getType().equals(Integer.TYPE)) field.setInt(this, yml.getInt(path)); // Float else if (field.getType().equals(Float.TYPE)) field.setFloat(this, (float) yml.getDouble(path)); // Double else if (field.getType().equals(Double.TYPE)) field.setDouble(this, yml.getDouble(path)); // Long else if (field.getType().equals(Long.TYPE)) field.setLong(this, yml.getLong(path)); // Short else if (field.getType().equals(Short.TYPE)) field.setShort(this, (short) yml.getInt(path)); // Boolean else if (field.getType().equals(Boolean.TYPE)) field.setBoolean(this, yml.getBoolean(path)); // ItemStack else if (field.getType().equals(ItemStack.class)) field.set(this, yml.getItemStack(path)); // String else if (field.getType().equals(String.class)) field.set(this, yml.getString(path)); else throw new IllegalArgumentException("Cannot use type " + field.getType().getSimpleName() + " for AutoConfiguration"); //$NON-NLS-1$ } } } onPostLoad(); } else { Bukkit.getLogger().log(Level.INFO, "Unable to create file: " + mFile.toString()); } } else { Bukkit.getLogger().log(Level.INFO, "Unable to create file: " + mFile.getParentFile().toString()); } return true; } catch (IOException | InvalidConfigurationException | IllegalAccessException | IllegalArgumentException e) { e.printStackTrace(); return false; } }
From source file:pl.bristleback.server.bristle.conf.resolver.action.ActionResolver.java
private boolean isDefaultRemoteAction(Class clazz, Method action) { if (!DefaultAction.class.isAssignableFrom(clazz)) { // this action class does not have default action return false; }//from w w w. j a v a 2 s . c om Method defaultMethod = DefaultAction.class.getMethods()[0]; if (!defaultMethod.getName().equals(action.getName())) { return false; } Class[] defaultParameterTypes = defaultMethod.getParameterTypes(); if (defaultParameterTypes.length != action.getParameterTypes().length) { return false; } int parametersLength = defaultParameterTypes.length; for (int i = 0; i < parametersLength - 1; i++) { Class defaultParameterType = defaultParameterTypes[i]; if (!defaultParameterType.isAssignableFrom(action.getParameterTypes()[i])) { return false; } } Type requiredLastParameterType = action.getGenericParameterTypes()[parametersLength - 1]; Type actualLastParameterType = null; for (int i = 0; i < clazz.getInterfaces().length; i++) { Class interfaceOfClass = clazz.getInterfaces()[i]; if (DefaultAction.class.equals(interfaceOfClass)) { Type genericInterface = clazz.getGenericInterfaces()[i]; if (genericInterface instanceof ParameterizedType) { actualLastParameterType = ((ParameterizedType) (genericInterface)).getActualTypeArguments()[1]; } else { actualLastParameterType = Object.class; } } } return requiredLastParameterType.equals(actualLastParameterType); }
From source file:org.xwiki.component.embed.EmbeddableComponentManager.java
@Override @SuppressWarnings("unchecked") public <T> Map<String, T> getInstanceMap(Type role) throws ComponentLookupException { Map<String, T> objects = new HashMap<String, T>(); for (Map.Entry<RoleHint<?>, ComponentEntry<?>> entry : this.componentEntries.entrySet()) { RoleHint<?> roleHint = entry.getKey(); if (role.equals(roleHint.getRoleType())) { try { objects.put(roleHint.getHint(), getComponentInstance((ComponentEntry<T>) entry.getValue())); } catch (Exception e) { throw new ComponentLookupException("Failed to lookup component [" + roleHint + "]", e); }//w ww . j av a 2 s . co m } } // Add parent's list of components if (getParent() != null) { // If the hint already exists in the children Component Manager then don't add the one from the parent. for (Map.Entry<String, T> entry : getParent().<T>getInstanceMap(role).entrySet()) { if (!objects.containsKey(entry.getKey())) { objects.put(entry.getKey(), entry.getValue()); } } } return objects; }