Entry encode(final T o, final String parentDN) throws LDAPPersistException { // Get the attributes that should be included in the entry. final LinkedHashMap<String, Attribute> attrMap = new LinkedHashMap<String, Attribute>(); attrMap.put("objectClass", objectClassAttribute); for (final Map.Entry<String, FieldInfo> e : fieldMap.entrySet()) { final FieldInfo i = e.getValue(); if (!i.includeInAdd()) { continue; } final Attribute a = i.encode(o, false); if (a != null) { attrMap.put(e.getKey(), a); } } for (final Map.Entry<String, GetterInfo> e : getterMap.entrySet()) { final GetterInfo i = e.getValue(); if (!i.includeInAdd()) { continue; } final Attribute a = i.encode(o); if (a != null) { attrMap.put(e.getKey(), a); } } final String dn = constructDN(o, parentDN, attrMap); final Entry entry = new Entry(dn, attrMap.values()); if (postEncodeMethod != null) { try { postEncodeMethod.invoke(o, entry); } catch (Throwable t) { debugException(t); if (t instanceof InvocationTargetException) { t = ((InvocationTargetException) t).getTargetException(); } throw new LDAPPersistException( ERR_OBJECT_HANDLER_ERROR_INVOKING_POST_ENCODE_METHOD.get( postEncodeMethod.getName(), type.getName(), getExceptionMessage(t)), t); } } setDNAndEntryFields(o, entry); if (superclassHandler != null) { final Entry e = superclassHandler.encode(o, parentDN); for (final Attribute a : e.getAttributes()) { entry.addAttribute(a); } } return entry; }
@Nullable public InstanceFactory findInstanceFactory(@Nonnull Type mockedType) { InstanceFactory instanceFactory = mockedTypesAndInstances.get(mockedType); if (instanceFactory != null) { return instanceFactory; } Class<?> mockedClass = getClassType(mockedType); //noinspection ReuseOfLocalVariable instanceFactory = mockedTypesAndInstances.get(mockedClass); if (instanceFactory != null) { return instanceFactory; } boolean abstractType = mockedClass.isInterface() || isAbstract(mockedClass.getModifiers()); for (Entry<Type, InstanceFactory> entry : mockedTypesAndInstances.entrySet()) { Type registeredMockedType = entry.getKey(); Class<?> registeredMockedClass = getClassType(registeredMockedType); if (abstractType) { registeredMockedClass = getMockedClassOrInterfaceType(registeredMockedClass); } if (mockedClass.isAssignableFrom(registeredMockedClass)) { instanceFactory = entry.getValue(); break; } } return instanceFactory; }
private static void checkGarbageCollectionNotificationInfoContent( GarbageCollectionNotificationInfo notif) throws Exception { System.out.println("GC notification for " + notif.getGcName()); System.out.print("Action: " + notif.getGcAction()); System.out.println(" Cause: " + notif.getGcCause()); GcInfo info = notif.getGcInfo(); System.out.print("GC Info #" + info.getId()); System.out.print(" start:" + info.getStartTime()); System.out.print(" end:" + info.getEndTime()); System.out.println(" (" + info.getDuration() + "ms)"); Map<String, MemoryUsage> usage = info.getMemoryUsageBeforeGc(); List<String> pnames = new ArrayList<String>(); for (Map.Entry entry : usage.entrySet()) { String poolname = (String) entry.getKey(); pnames.add(poolname); MemoryUsage busage = (MemoryUsage) entry.getValue(); MemoryUsage ausage = (MemoryUsage) info.getMemoryUsageAfterGc().get(poolname); if (ausage == null) { throw new RuntimeException("After Gc Memory does not exist" + " for " + poolname); } System.out.println("Usage for pool " + poolname); System.out.println(" Before GC: " + busage); System.out.println(" After GC: " + ausage); } // check if memory usage for all memory pools are returned List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans(); for (MemoryPoolMXBean p : pools) { if (!pnames.contains(p.getName())) { throw new RuntimeException( "GcInfo does not contain " + "memory usage for pool " + p.getName()); } } }
private void putMap(String name, Map m) { _put(OBJECT, name); final int sizePos = _buf.getPosition(); _buf.writeInt(0); for (Map.Entry entry : (Set<Map.Entry>) m.entrySet()) _putObjectField(entry.getKey().toString(), entry.getValue()); _buf.write(EOO); _buf.writeInt(sizePos, _buf.getPosition() - sizePos); }
public void addEnvToIntent(Intent intent) { Map<String, String> envMap = System.getenv(); Set<Map.Entry<String, String>> envSet = envMap.entrySet(); Iterator<Map.Entry<String, String>> envIter = envSet.iterator(); int c = 0; while (envIter.hasNext()) { Map.Entry<String, String> entry = envIter.next(); intent.putExtra("env" + c, entry.getKey() + "=" + entry.getValue()); c++; } }
/** * Adds the channel-bundles of this <tt>Conference</tt> as * <tt>ColibriConferenceIQ.ChannelBundle</tt> instances in <tt>iq</tt>. * * @param iq the <tt>ColibriConferenceIQ</tt> in which to describe. */ void describeChannelBundles(ColibriConferenceIQ iq) { synchronized (transportManagers) { for (Map.Entry<String, IceUdpTransportManager> entry : transportManagers.entrySet()) { ColibriConferenceIQ.ChannelBundle responseBundleIQ = new ColibriConferenceIQ.ChannelBundle(entry.getKey()); entry.getValue().describe(responseBundleIQ); iq.addChannelBundle(responseBundleIQ); } } }
/** * Quickie init test of the static initializer and print out of asynch response mappings * * @param args none */ public static void main(String[] args) { SimpleLogger.info("Initialized"); for (Map.Entry<Byte, Method> entry : keyToMethod.entrySet()) { Method am = keyToAsynchMethod.get(entry.getKey()); SimpleLogger.info("\t", entry.getValue().getName(), " --> ", am.getName()); } StringBuilder b = new StringBuilder("Mappings"); for (Map.Entry<Byte, Method> entry : keyToMethod.entrySet()) { b.append("\n\t[") .append(entry.getKey()) .append("]") .append(" --") .append(entry.getValue().getName()) .append("-- ") .append("[") .append(methodToKey.get(entry.getValue())) .append("]"); } SimpleLogger.info(b); }
public Query setColumnMappings(Map<String, String> mappings) { this.caseSensitiveColumnMappings = new HashMap<>(); this.columnMappings = new HashMap<>(); for (Map.Entry<String, String> entry : mappings.entrySet()) { this.caseSensitiveColumnMappings.put(entry.getKey(), entry.getValue()); this.columnMappings.put(entry.getKey().toLowerCase(), entry.getValue().toLowerCase()); } return this; }
/** {@inheritDoc} */ @Override public void onDiscoveryDataReceived(UUID nodeId, UUID rmtNodeId, Serializable data) { Map<String, Serializable> discData = (Map<String, Serializable>) data; if (discData != null) { for (Map.Entry<String, Serializable> e : discData.entrySet()) { PluginProvider provider = plugins.get(e.getKey()); if (provider != null) provider.receiveDiscoveryData(nodeId, e.getValue()); else U.warn(log, "Received discovery data for unknown plugin: " + e.getKey()); } } }
/** * Returns the map of attributes names and values for attributes which value is neither null or * the default value. These attributes are considered having a non default value and must be * written out. * * @return map of attributes indexed by name that must be persisted */ private Map<String, String> attributesToWrite() { Map<String, String> attributesToWrite = new HashMap<String, String>(); Map<String, String> localAttr = new HashMap<String, String>(attributes); for (Map.Entry<String, String> a : localAttr.entrySet()) { ConfigModel.AttributeLeaf am = model.attributes.get(a.getKey()); String dv = am.getDefaultValue(); if (dv == null || !dv.equals(a.getValue())) { attributesToWrite.put(a.getKey(), a.getValue()); } } return attributesToWrite; }
private Map<Object, Object> convertMap( Class<?> mapClass, Type targetKeyType, Type targetValueType, Map<?, ?> sourceObject, Action<? super SourceObjectMapping> mapping) { Map<Object, Object> convertedElements = collectionMapper.createEmptyMap(mapClass); for (Map.Entry<?, ?> entry : sourceObject.entrySet()) { convertedElements.put( convert(targetKeyType, entry.getKey(), mapping), convert(targetValueType, entry.getValue(), mapping)); } return convertedElements; }
/** {@inheritDoc} */ @Nullable @Override public Serializable collectDiscoveryData(UUID nodeId) { HashMap<String, Serializable> discData = null; for (Map.Entry<String, PluginProvider> e : plugins.entrySet()) { Serializable data = e.getValue().provideDiscoveryData(nodeId); if (data != null) { if (discData == null) discData = new HashMap<>(); discData.put(e.getKey(), data); } } return discData; }
private PreparedStatement buildPreparedStatement(boolean allowArrayParameters) { // array parameter handling parsedQuery = ArrayParameters.updateQueryAndParametersIndexes( parsedQuery, paramNameToIdxMap, parameters, allowArrayParameters); // prepare statement creation if (preparedStatement == null) { try { if (columnNames != null && columnNames.length > 0) { preparedStatement = connection.getJdbcConnection().prepareStatement(parsedQuery, columnNames); } else if (returnGeneratedKeys) { preparedStatement = connection .getJdbcConnection() .prepareStatement(parsedQuery, Statement.RETURN_GENERATED_KEYS); } else { preparedStatement = connection.getJdbcConnection().prepareStatement(parsedQuery); } } catch (SQLException ex) { throw new Sql2oException( String.format("Error preparing statement - %s", ex.getMessage()), ex); } connection.registerStatement(preparedStatement); } // parameters assignation to query for (Map.Entry<String, ParameterSetter> parameter : parameters.entrySet()) { for (int paramIdx : paramNameToIdxMap.get(parameter.getKey())) { try { parameter.getValue().setParameter(paramIdx, preparedStatement); } catch (SQLException e) { throw new RuntimeException( String.format("Error adding parameter '%s' - %s", parameter.getKey(), e.getMessage()), e); } } } // the parameters need to be cleared, so in case of batch, only new parameters will be added parameters.clear(); return preparedStatement; }
private static Dictionary<String, Object> getDictionary( Map<String, Type> types, Map<String, Object> values) throws Exception { Hashtable<String, Object> ht = new Hashtable<String, Object>(); for (Map.Entry<String, Object> e : values.entrySet()) { String key = e.getKey(); Object value = e.getValue(); Type type; if (types != null && (type = types.get(key)) != null) { if (type.scalar != null) { value = convert(value, type.scalar); } else if (type.vectorOf != null) { Collection<Object> coll = (Collection<Object>) value; Vector vector = new Vector(); for (Object o : coll) { vector.add(convert(o, type.vectorOf)); } value = vector; } else if (type.arrayOf != null) { if (value instanceof String && type.arrayOf.equals("byte")) { value = Base64.decodeBase64((String) value); } else { Collection<Object> coll = (Collection<Object>) value; Object array = Array.newInstance(getClass(type.arrayOf), coll.size()); int n = 0; for (Object o : coll) { Array.set(array, n++, convert(o, type.arrayOf)); } value = array; } } else { throw new IllegalArgumentException( "Key " + key + " has type but neither scalar, vectorOf, nor arrayOf is set"); } } ht.put(key, value); } return ht; }
/** Enter a set of generated class files. */ private List<ClassSymbol> enterClassFiles(Map<String, JavaFileObject> classFiles) { ClassReader reader = ClassReader.instance(context); Names names = Names.instance(context); List<ClassSymbol> list = List.nil(); for (Map.Entry<String, JavaFileObject> entry : classFiles.entrySet()) { Name name = names.fromString(entry.getKey()); JavaFileObject file = entry.getValue(); if (file.getKind() != JavaFileObject.Kind.CLASS) throw new AssertionError(file); ClassSymbol cs; if (isPkgInfo(file, JavaFileObject.Kind.CLASS)) { Name packageName = Convert.packagePart(name); PackageSymbol p = reader.enterPackage(packageName); if (p.package_info == null) p.package_info = reader.enterClass(Convert.shortName(name), p); cs = p.package_info; if (cs.classfile == null) cs.classfile = file; } else cs = reader.enterClass(name, file); list = list.prepend(cs); } return list.reverse(); }
public static String generateProxy(Class interfaceClass) throws Exception { StringBuilder b = new StringBuilder(); b.append("#include <jni.h>\n"); b.append("#ifdef _WIN32\n"); b.append("#define PROXY_EXPORT __declspec(dllexport)\n"); b.append("#else\n"); b.append("#define PROXY_EXPORT\n"); b.append("#endif\n"); b.append( "#define FIND_GLOBAL_CLASS(name) (*env)->NewGlobalRef(env, (*env)->FindClass(env, name))\n"); List<ProxiedMethod> methods = new ArrayList<ProxiedMethod>(); int iClassName = 0, iMethodName = 0; Map<Class, String> classVarNames = new HashMap<Class, String>(); for (Method m : interfaceClass.getDeclaredMethods()) { try { ProxiedMethod pm = getProxiedMethod(m); String classVarName = classVarNames.get(pm.owner); if (classVarName == null) classVarNames.put(pm.owner, classVarName = "gClass" + (++iClassName)); pm.classVarName = classVarName; pm.methodVarName = "gMethod" + (++iMethodName); methods.add(pm); } catch (Throwable th) { // th.printStackTrace(); } } b.append("jboolean inited = JNI_FALSE;\n"); String instanceVarName = "gProxiedInstance"; b.append("JNIEnv* env = NULL;\n"); b.append("JavaVM* jvm = NULL;\n"); b.append("jobject ").append(instanceVarName).append(" = NULL;\n"); for (String n : classVarNames.values()) b.append("jclass ").append(n).append(" = NULL;\n"); for (ProxiedMethod pm : methods) b.append("jmethodID ").append(pm.methodVarName).append(" = NULL;\n"); String jniInit = "jni_init"; b.append("void ").append(jniInit).append("(JNIEnv* env) {\n"); b.append("\tif (inited) return; else inited = JNI_TRUE;\n"); for (Map.Entry<Class, String> e : classVarNames.entrySet()) { String n = e.getValue(); Class c = e.getKey(); b.append("\t") .append(n) .append(" = ") .append("FIND_GLOBAL_CLASS(\"") .append(name(c)) .append("\");\n"); } for (ProxiedMethod pm : methods) { int mods = pm.method.getModifiers(); b.append("\t") .append(pm.methodVarName) .append(" = ") .append("(*env)->") .append(Modifier.isStatic(mods) ? "GetStaticMethodID" : "GetMethodID") .append("(env, ") .append(pm.classVarName) .append(", \"") .append(pm.name) .append("\", \"") .append(pm.jni_signature) .append("\");\n"); } b.append("}\n"); for (ProxiedMethod pm : methods) { b.append("PROXY_EXPORT ").append(pm.c_signature).append(" {\n"); int mods = pm.method.getModifiers(); b.append("\t").append(jniInit).append("();\n"); b.append("\t"); if (pm.method.getReturnType() != null && !pm.method.getReturnType().equals(void.class)) b.append("return "); StringBuilder r = new StringBuilder(); boolean stat = Modifier.isStatic(mods); r.append("(*env)->") .append("Call" + (stat ? "Static" : "") + pm.retCapitalized + "Method") .append("(env, "); if (stat) r.append(pm.classVarName); else r.append(instanceVarName); for (String argValue : pm.argValues) { r.append(", \n\t\t"); r.append(argValue); } // TODO... r.append("\n\t)"); b.append(c_signature(pm.method.getReturnType(), r.toString())[2]); b.append(";\n"); b.append("}\n"); } return b.toString(); }
private void discoverAndRunProcs( Context context, Set<TypeElement> annotationsPresent, List<ClassSymbol> topLevelClasses, List<PackageSymbol> packageInfoFiles) { Map<String, TypeElement> unmatchedAnnotations = new HashMap<String, TypeElement>(annotationsPresent.size()); for (TypeElement a : annotationsPresent) { unmatchedAnnotations.put(a.getQualifiedName().toString(), a); } // Give "*" processors a chance to match if (unmatchedAnnotations.size() == 0) unmatchedAnnotations.put("", null); DiscoveredProcessors.ProcessorStateIterator psi = discoveredProcs.iterator(); // TODO: Create proper argument values; need past round // information to fill in this constructor. Note that the 1 // st round of processing could be the last round if there // were parse errors on the initial source files; however, we // are not doing processing in that case. Set<Element> rootElements = new LinkedHashSet<Element>(); rootElements.addAll(topLevelClasses); rootElements.addAll(packageInfoFiles); rootElements = Collections.unmodifiableSet(rootElements); RoundEnvironment renv = new JavacRoundEnvironment(false, false, rootElements, JavacProcessingEnvironment.this); while (unmatchedAnnotations.size() > 0 && psi.hasNext()) { ProcessorState ps = psi.next(); Set<String> matchedNames = new HashSet<String>(); Set<TypeElement> typeElements = new LinkedHashSet<TypeElement>(); for (Map.Entry<String, TypeElement> entry : unmatchedAnnotations.entrySet()) { String unmatchedAnnotationName = entry.getKey(); if (ps.annotationSupported(unmatchedAnnotationName)) { matchedNames.add(unmatchedAnnotationName); TypeElement te = entry.getValue(); if (te != null) typeElements.add(te); } } if (matchedNames.size() > 0 || ps.contributed) { boolean processingResult = callProcessor(ps.processor, typeElements, renv); ps.contributed = true; ps.removeSupportedOptions(unmatchedProcessorOptions); if (printProcessorInfo || verbose) { log.printNoteLines( "x.print.processor.info", ps.processor.getClass().getName(), matchedNames.toString(), processingResult); } if (processingResult) { unmatchedAnnotations.keySet().removeAll(matchedNames); } } } unmatchedAnnotations.remove(""); if (lint && unmatchedAnnotations.size() > 0) { // Remove annotations processed by javac unmatchedAnnotations.keySet().removeAll(platformAnnotations); if (unmatchedAnnotations.size() > 0) { log = Log.instance(context); log.warning("proc.annotations.without.processors", unmatchedAnnotations.keySet()); } } // Run contributing processors that haven't run yet psi.runContributingProcs(renv); // Debugging if (options.isSet("displayFilerState")) filer.displayState(); }
List<Modification> getModifications( final T o, final boolean deleteNullValues, final String... attributes) throws LDAPPersistException { final ReadOnlyEntry originalEntry; if (entryField != null) { originalEntry = getEntry(o); } else { originalEntry = null; } if (originalEntry != null) { try { final T decodedOrig = decode(originalEntry); final Entry reEncodedOriginal = encode(decodedOrig, originalEntry.getParentDNString()); final Entry newEntry = encode(o, originalEntry.getParentDNString()); final List<Modification> mods = Entry.diff(reEncodedOriginal, newEntry, true, false, attributes); if (!deleteNullValues) { final Iterator<Modification> iterator = mods.iterator(); while (iterator.hasNext()) { final Modification m = iterator.next(); if (m.getRawValues().length == 0) { iterator.remove(); } } } HashSet<String> stripAttrs = null; for (final FieldInfo i : fieldMap.values()) { if (!i.includeInModify()) { if (stripAttrs == null) { stripAttrs = new HashSet<String>(10); } stripAttrs.add(toLowerCase(i.getAttributeName())); } } for (final GetterInfo i : getterMap.values()) { if (!i.includeInModify()) { if (stripAttrs == null) { stripAttrs = new HashSet<String>(10); } stripAttrs.add(toLowerCase(i.getAttributeName())); } } if (stripAttrs != null) { final Iterator<Modification> iterator = mods.iterator(); while (iterator.hasNext()) { final Modification m = iterator.next(); if (stripAttrs.contains(toLowerCase(m.getAttributeName()))) { iterator.remove(); } } } return mods; } catch (final Exception e) { debugException(e); } finally { setDNAndEntryFields(o, originalEntry); } } final HashSet<String> attrSet; if ((attributes == null) || (attributes.length == 0)) { attrSet = null; } else { attrSet = new HashSet<String>(attributes.length); for (final String s : attributes) { attrSet.add(toLowerCase(s)); } } final ArrayList<Modification> mods = new ArrayList<Modification>(5); for (final Map.Entry<String, FieldInfo> e : fieldMap.entrySet()) { final String attrName = toLowerCase(e.getKey()); if ((attrSet != null) && (!attrSet.contains(attrName))) { continue; } final FieldInfo i = e.getValue(); if (!i.includeInModify()) { continue; } final Attribute a = i.encode(o, false); if (a == null) { if (!deleteNullValues) { continue; } if ((originalEntry != null) && (!originalEntry.hasAttribute(attrName))) { continue; } mods.add(new Modification(ModificationType.REPLACE, i.getAttributeName())); continue; } if (originalEntry != null) { final Attribute originalAttr = originalEntry.getAttribute(attrName); if ((originalAttr != null) && originalAttr.equals(a)) { continue; } } mods.add(new Modification(ModificationType.REPLACE, i.getAttributeName(), a.getRawValues())); } for (final Map.Entry<String, GetterInfo> e : getterMap.entrySet()) { final String attrName = toLowerCase(e.getKey()); if ((attrSet != null) && (!attrSet.contains(attrName))) { continue; } final GetterInfo i = e.getValue(); if (!i.includeInModify()) { continue; } final Attribute a = i.encode(o); if (a == null) { if (!deleteNullValues) { continue; } if ((originalEntry != null) && (!originalEntry.hasAttribute(attrName))) { continue; } mods.add(new Modification(ModificationType.REPLACE, i.getAttributeName())); continue; } if (originalEntry != null) { final Attribute originalAttr = originalEntry.getAttribute(attrName); if ((originalAttr != null) && originalAttr.equals(a)) { continue; } } mods.add(new Modification(ModificationType.REPLACE, i.getAttributeName(), a.getRawValues())); } if (superclassHandler != null) { final List<Modification> superMods = superclassHandler.getModifications(o, deleteNullValues, attributes); final ArrayList<Modification> modsToAdd = new ArrayList<Modification>(superMods.size()); for (final Modification sm : superMods) { boolean add = true; for (final Modification m : mods) { if (m.getAttributeName().equalsIgnoreCase(sm.getAttributeName())) { add = false; break; } } if (add) { modsToAdd.add(sm); } } mods.addAll(modsToAdd); } return Collections.unmodifiableList(mods); }
public void buildTypeGraph() { Map<String, JarFile> openJarFiles = new HashMap<String, JarFile>(); Map<String, File> openClassFiles = new HashMap<String, File>(); // use global cache to load resource in/out of the same jar as the classes Set<String> resourceCacheSet = new HashSet<>(); try { for (String path : pathsToScan) { File f = null; try { f = new File(path); if (!f.exists() || f.isDirectory() || (!f.getName().endsWith("jar") && !f.getName().endsWith("class"))) { continue; } if (GENERATED_CLASSES_JAR.equals(f.getName())) { continue; } if (f.getName().endsWith("class")) { typeGraph.addNode(f); openClassFiles.put(path, f); } else { JarFile jar = new JarFile(path); openJarFiles.put(path, jar); java.util.Enumeration<JarEntry> entriesEnum = jar.entries(); while (entriesEnum.hasMoreElements()) { final java.util.jar.JarEntry jarEntry = entriesEnum.nextElement(); String entryName = jarEntry.getName(); if (jarEntry.isDirectory()) { continue; } if (entryName.endsWith("-javadoc.xml")) { try { processJavadocXml(jar.getInputStream(jarEntry)); // break; } catch (Exception ex) { LOG.warn("Cannot process javadoc {} : ", entryName, ex); } } else if (entryName.endsWith(".class")) { TypeGraph.TypeGraphVertex newNode = typeGraph.addNode(jarEntry, jar); // check if any visited resources belong to this type for (Iterator<String> iter = resourceCacheSet.iterator(); iter.hasNext(); ) { String entry = iter.next(); if (entry.startsWith(entryName.substring(0, entryName.length() - 6))) { newNode.setHasResource(true); iter.remove(); } } } else { String className = entryName; boolean foundClass = false; // check if this resource belongs to any visited type while (className.contains("/")) { className = className.substring(0, className.lastIndexOf('/')); TypeGraph.TypeGraphVertex tgv = typeGraph.getNode(className.replace('/', '.')); if (tgv != null) { tgv.setHasResource(true); foundClass = true; break; } } if (!foundClass) { resourceCacheSet.add(entryName); } } } } } catch (IOException ex) { LOG.warn("Cannot process file {}", f, ex); } } typeGraph.trim(); typeGraph.updatePortTypeInfoInTypeGraph(openJarFiles, openClassFiles); } finally { for (Entry<String, JarFile> entry : openJarFiles.entrySet()) { try { entry.getValue().close(); } catch (IOException e) { DTThrowable.wrapIfChecked(e); } } } }