code
stringlengths
73
34.1k
label
stringclasses
1 value
private final CMConfigData getCMConfigData(AbstractConnectionFactoryService cfSvc, ResourceInfo refInfo) { final boolean trace = TraceComponent.isAnyTracingEnabled(); if (trace && tc.isEntryEnabled()) Tr.entry(this, tc, "getCMConfigData"); // Defaults for direct lookup int auth = J2CConstants.AUTHENTICATION_APPLICATION; int branchCoupling = ResourceRefInfo.BRANCH_COUPLING_UNSET; int commitPriority = 0; int isolation = Connection.TRANSACTION_NONE; int sharingScope; String loginConfigName = null; HashMap<String, String> loginConfigProps = null; String resRefName = null; if (refInfo != null) { if (refInfo.getAuth() == ResourceRef.AUTH_CONTAINER) auth = J2CConstants.AUTHENTICATION_CONTAINER; branchCoupling = refInfo.getBranchCoupling(); commitPriority = refInfo.getCommitPriority(); isolation = refInfo.getIsolationLevel(); loginConfigName = refInfo.getLoginConfigurationName(); loginConfigProps = toHashMap(refInfo.getLoginPropertyList()); resRefName = refInfo.getName(); sharingScope = refInfo.getSharingScope(); } else { if (properties != null) { Object enableSharingForDirectLookups = properties.get("enableSharingForDirectLookups"); sharingScope = enableSharingForDirectLookups == null || (Boolean) enableSharingForDirectLookups ? ResourceRefInfo.SHARING_SCOPE_SHAREABLE : ResourceRefInfo.SHARING_SCOPE_UNSHAREABLE; } else { sharingScope = ResourceRefInfo.SHARING_SCOPE_SHAREABLE; } } CMConfigData cmConfig = new CMConfigDataImpl(cfSvc.getJNDIName(), sharingScope, isolation, auth, cfSvc.getID(), loginConfigName, loginConfigProps, resRefName, commitPriority, branchCoupling, null // no mmProps ); if (trace && tc.isEntryEnabled()) Tr.exit(this, tc, "getCMConfigData", cmConfig); return cmConfig; }
java
@Override public ConnectionManager getConnectionManager(ResourceInfo refInfo, AbstractConnectionFactoryService svc) throws ResourceException { final boolean trace = TraceComponent.isAnyTracingEnabled(); if (trace && tc.isEntryEnabled()) Tr.entry(this, tc, "getConnectionManager", refInfo, svc); ConnectionManager cm; lock.readLock().lock(); try { if (pm == null) try { // Switch to write lock for lazy initialization lock.readLock().unlock(); lock.writeLock().lock(); if (pm == null) createPoolManager(svc); } finally { // Downgrade to read lock for rest of method lock.readLock().lock(); lock.writeLock().unlock(); } CMConfigData cmConfigData = getCMConfigData(svc, refInfo); String cfDetailsKey = cmConfigData.getCFDetailsKey(); cm = cfKeyToCM.get(cfDetailsKey); if (cm == null) { CommonXAResourceInfo xaResInfo = new EmbXAResourceInfo(cmConfigData); J2CGlobalConfigProperties gConfigProps = pm.getGConfigProps(); synchronized (this) { cm = cfKeyToCM.get(cfDetailsKey); if (cm == null) { cm = new ConnectionManager(svc, pm, gConfigProps, xaResInfo); cfKeyToCM.put(cfDetailsKey, cm); } } } } finally { lock.readLock().unlock(); } if (trace && tc.isEntryEnabled()) Tr.exit(this, tc, "getConnectionManager", cm); return cm; }
java
private final static HashMap<String, String> toHashMap(List<? extends ResourceInfo.Property> propList) { if (propList == null) return null; HashMap<String, String> propMap = new HashMap<String, String>(); for (ResourceInfo.Property prop : propList) propMap.put(prop.getName(), prop.getValue()); return propMap; }
java
@Override @FFDCIgnore(BAD_OPERATION.class) public Object narrow(Object narrowFrom, @SuppressWarnings("rawtypes") Class narrowTo) throws ClassCastException { if (narrowFrom == null) { return null; } if (narrowTo.isInstance(narrowFrom)) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "object is already an instance"); return narrowFrom; } if (!!!(narrowFrom instanceof ObjectImpl)) throw new ClassCastException(narrowTo.getName()); if (IDLEntity.class.isAssignableFrom(narrowTo)) return super.narrow(narrowFrom, narrowTo); Class<?> stubClass = loadStubClass(narrowTo); if (stubClass == null) { // The stub class could not be loaded. Fallback to the default // implementation to allow it to dynamically generate one. return super.narrow(narrowFrom, narrowTo); } Object stubObject; try { stubObject = stubClass.newInstance(); } catch (Throwable t) { // This will fail if the stub class is "invalid" (missing default // constructor, non-public default constructor, logic in the // constructor that throws, etc.). ClassCastException e = new ClassCastException(narrowTo.getName()); e.initCause(t); throw e; } // This will fail if the loaded class does not actually extend Stub. Stub stub = (Stub) stubObject; try { stub._set_delegate(((ObjectImpl) narrowFrom)._get_delegate()); } catch (org.omg.CORBA.BAD_OPERATION e) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "unable to copy delegate", e); } // This will fail if the loaded stub class does not implement the // interface. For example, narrow was called with one version of the // interface, but the context class loader loaded a stub that // implemented a different version of the interface. return narrowTo.cast(stub); }
java
private void scanClasses() throws PersistenceUnitScannerException { try { for (URL url : urlSet) { final HashSet<ClassInfoType> citSet = new HashSet<ClassInfoType>(); final String urlProtocol = url.getProtocol(); if ("file".equalsIgnoreCase(urlProtocol)) { // Protocol is "file", which either addresses a jar file or an exploded jar file final Path taPath = Paths.get(url.toURI()); if (Files.isDirectory(taPath)) { // Exploded Archive citSet.addAll(processExplodedJarFormat(taPath)); } else { // Unexploded Archive citSet.addAll(processUnexplodedFile(taPath)); } } else if (url.toString().startsWith("jar:file")) { citSet.addAll(processJarFileURL(url)); } else { // InputStream will be in jar format. citSet.addAll(processJarFormatInputStreamURL(url)); } processInnerClasses(citSet); scannedClassesMap.put(url, citSet); } } catch (Exception e) { FFDCFilter.processException(e, PersistenceUnitScanner.class.getName() + ".scanClasses", "118"); throw new PersistenceUnitScannerException(e); } }
java
private void scanEntityMappings() throws PersistenceUnitScannerException { /* * From the JPA 2.1 Specification: * * 8.2.1.6.2 Object/relational Mapping Files * An object/relational mapping XML file contains mapping information for the classes listed in it. * * A object/relational mapping XML file named orm.xml may be specified in the META-INF directory * in the root of the persistence unit or in the META-INF directory of any jar file referenced by the persistence. * xml. Alternatively, or in addition, one or more mapping files may be referenced by the * mapping-file elements of the persistence-unit element. These mapping files may be * present anywhere on the class path. * * An orm.xml mapping file or other mapping file is loaded as a resource by the persistence provider. If * a mapping file is specified, the classes and mapping information specified in the mapping file will be * used as described in Chapter 12. If multiple mapping files are specified (possibly including one or more * orm.xml files), the resulting mappings are obtained by combining the mappings from all of the files. * The result is undefined if multiple mapping files (including any orm.xml file) referenced within a single * persistence unit contain overlapping mapping information for any given class. The object/relational * mapping information contained in any mapping file referenced within the persistence unit must be disjoint * at the class-level from object/relational mapping information contained in any other such mapping * file. */ final HashSet<URL> mappingFilesLocated = new HashSet<URL>(); final HashSet<String> searchNames = new HashSet<String>(); for (PersistenceUnitInfo pui : puiList) { try { mappingFilesLocated.clear(); searchNames.clear(); searchNames.add("META-INF/orm.xml"); if (pui.getMappingFileNames() != null) { searchNames.addAll(pui.getMappingFileNames()); } for (String mappingFile : searchNames) { mappingFilesLocated.addAll(findORMResources(pui, mappingFile)); } final List<EntityMappingsDefinition> parsedOrmList = pu_ormFileParsed_map.get(pui); pu_ormFiles_map.get(pui).addAll(mappingFilesLocated); // Process discovered mapping files for (final URL mappingFileURL : mappingFilesLocated) { if (scanned_ormfile_map.containsKey(mappingFileURL)) { // Already processed this ORM File, no need to process it again. parsedOrmList.add(scanned_ormfile_map.get(mappingFileURL)); continue; } EntityMappingsDefinition emapdef = EntityMappingsFactory.parseEntityMappings(mappingFileURL); parsedOrmList.add(emapdef); scanned_ormfile_map.put(mappingFileURL, emapdef); } } catch (Exception e) { FFDCFilter.processException(e, PersistenceUnitScanner.class.getName() + ".scanEntityMappings", "460"); throw new PersistenceUnitScannerException(e); } } }
java
private List<URL> findORMResources(PersistenceUnitInfo pui, String ormFileName) throws IOException { final boolean isMetaInfoOrmXML = "META-INF/orm.xml".equals(ormFileName); final ArrayList<URL> retArr = new ArrayList<URL>(); Enumeration<URL> ormEnum = pui.getClassLoader().getResources(ormFileName); while (ormEnum.hasMoreElements()) { final URL url = ormEnum.nextElement(); final String urlExtern = url.toExternalForm(); // ParserUtils.decode(url.toExternalForm()); if (!isMetaInfoOrmXML) { // If it's not "META-INF/orm.xml", then the mapping files may be present anywhere in the classpath. retArr.add(url); continue; } // Check against persistence unit root if (urlExtern.startsWith(pui.getPersistenceUnitRootUrl().toExternalForm())) { retArr.add(url); continue; } // Check against Jar files, if any for (URL jarUrl : pui.getJarFileUrls()) { final String jarExtern = jarUrl.toExternalForm(); if (urlExtern.startsWith(jarExtern)) { retArr.add(url); continue; } } } return retArr; }
java
public boolean writeSilence(SIMPMessage m) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "writeSilence", new Object[] { m }); JsMessage jsMsg = m.getMessage(); // There may be Completed ticks after the Value, if so then // write these into the stream too long stamp = jsMsg.getGuaranteedValueValueTick(); long starts = jsMsg.getGuaranteedValueStartTick(); long ends = jsMsg.getGuaranteedValueEndTick(); if (ends < stamp) ends = stamp; TickRange tr = new TickRange( TickRange.Completed, starts, ends); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { SibTr.debug(tc, "writeSilence from: " + starts + " to " + ends + " on Stream " + streamID); } synchronized (this) { tr = oststream.writeCompletedRange(tr); long completedPrefix = oststream.getCompletedPrefix(); if (completedPrefix > oack) { oack = completedPrefix; } // Only want to send Silence if we know it has been missed // because we have sent something beyond it if (lastSent > ends) sendSilence(ends + 1, completedPrefix); // SIB0105 // Message silenced so reset the health state if (blockedStreamAlarm != null) blockedStreamAlarm.checkState(false); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "writeSilence"); setLastSent(jsMsg.getGuaranteedValueEndTick()); return true; }
java
public void writeSilence(ControlSilence m) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "writeSilence", new Object[] { m }); boolean sendMessage = false; // to use in messages sent downstream long completedPrefix; // Construct a TickRange from the Silence message long starts = m.getStartTick(); long ends = m.getEndTick(); boolean requestedOnly = m.getRequestedOnly(); TickRange tr = new TickRange(TickRange.Completed, starts, ends); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { SibTr.debug(tc, "writeSilence from: " + starts + " to " + ends + " on Stream " + streamID); } synchronized (this) { if (requestedOnly) { // Only send this Silence message if there are some ticks in // its tick range which are in Requested state in the stream if (oststream.containsRequested(tr) == false) sendMessage = false; } // Write the range of Completed ticks to the stream and // get the resultant maximal Completed range tr = oststream.writeCompletedRange(tr); if (oststream.getCompletedPrefix() > oack) { oack = oststream.getCompletedPrefix(); } completedPrefix = oststream.getCompletedPrefix(); } // end synchronized if (sendMessage) { // send silence message corresponding to tr to downstream cellule // to target cellule try { downControl.sendSilenceMessage( tr.startstamp, tr.endstamp, completedPrefix, requestedOnly, priority, reliability, streamID); } catch (SIResourceException e) { // FFDC FFDCFilter.processException( e, "com.ibm.ws.sib.processor.gd.InternalOutputStream.writeSilence", "1:788:1.83.1.1", this); SibTr.exception(tc, e); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "writeSilence", e); throw e; } setLastSent(tr.endstamp); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "writeSilence", Boolean.valueOf(sendMessage)); }
java
public void writeAckPrefix(long stamp) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "writeAckPrefix", Long.valueOf(stamp)); synchronized (this) { // SIB0105 // Update controllable health state if poss if (stamp >= lastAckExpTick) { getControlAdapter().getHealthState().updateHealth(HealthStateListener.ACK_EXPECTED_STATE, HealthState.GREEN); // Disable the checking until another ackExpected is sent lastAckExpTick = Long.MAX_VALUE; } if (stamp >= lastNackReceivedTick) { getControlAdapter() .getHealthState().updateHealth(HealthStateListener.NACK_RECEIVED_STATE, HealthState.GREEN); // Disable the checking until another ackExpected is sent lastNackReceivedTick = Long.MAX_VALUE; } // Keep track of the highest ack we have received if (stamp > ack) ack = stamp; // This will update the prefix if stamp > completedPrefix // It also combines any adjacent Completed ranges oststream.setCompletedPrefix(stamp); long newCompletedPrefix = oststream.getCompletedPrefix(); if (newCompletedPrefix > oack) { oack = newCompletedPrefix; upControl.sendAckMessage(null, null, null, newCompletedPrefix, priority, reliability, streamID, false); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "writeAckPrefix"); } }
java
public void writeSilenceForced(TickRange vtr) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "writeSilenceForced", new Object[] { vtr }); long start = vtr.startstamp; long end = vtr.endstamp; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { SibTr.debug(tc, "writeSilenceForced from: " + start + " to " + end + " on Stream " + streamID); } TickRange tr = new TickRange( TickRange.Completed, start, end); synchronized (this) { tr = oststream.writeCompletedRangeForced(tr); try { if (tr.startstamp == 0) { //we are completed up to this point so we can //simulate receiving an ack. This will enable the //src stream to remove the msg from the store if it is no longer //needed writeAckPrefix(tr.endstamp); } } catch (SIResourceException e) { FFDCFilter.processException( e, "com.ibm.ws.sib.processor.gd.InternalOutputStream.writeSilenceForced", "1:1273:1.83.1.1", this); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "writeSilenceForced"); }
java
public static final byte[] serialize(Serializable serializable) throws IOException { if (serializable == null) { return null; } ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = null; byte[] result = null; if (null != _instance ){ SerializationService ss = _instance.serializationServiceRef.getService(); if (null != ss){ objectOutputStream = ss.createObjectOutputStream(byteArrayOutputStream); } } if (null == objectOutputStream){ objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); } try { objectOutputStream.writeObject(serializable); result = byteArrayOutputStream.toByteArray(); } finally { if (byteArrayOutputStream != null) { byteArrayOutputStream.close(); } if (objectOutputStream != null) { objectOutputStream.close(); } } return result; }
java
public Object nextElement() { try { return nextElementR(); } catch (NoMoreElementsException e) { // FFDCFilter.processException(e, CLASS_NAME + ".nextElement", "109", this); throw new NoSuchElementException(); } catch (EnumeratorException e) { // FFDCFilter.processException(e, CLASS_NAME + ".nextElement", "112", this); throw new RuntimeException(e.toString()); } catch (NoSuchObjectException e) { // FFDCFilter.processException(e, CLASS_NAME + ".nextElement", "115", this); throw new IllegalStateException("Cannot access finder result outside transaction"); } catch (RemoteException e) { // FFDCFilter.processException(e, CLASS_NAME + ".nextElement", "118", this); throw new RuntimeException(e.toString()); } }
java
public boolean hasMoreElements() { try { return hasMoreElementsR(); } catch (NoMoreElementsException e) { // FFDCFilter.processException(e, CLASS_NAME + ".hasMoreElements", "131", this); return false; } catch (EnumeratorException e) { // FFDCFilter.processException(e, CLASS_NAME + ".hasMoreElements", "134", this); throw new RuntimeException(e.toString()); } catch (NoSuchObjectException e) { // FFDCFilter.processException(e, CLASS_NAME + ".hasMoreElements", "137", this); throw new IllegalStateException("Cannot access finder result outside transaction"); } catch (RemoteException e) { // FFDCFilter.processException(e, CLASS_NAME + ".hasMoreElements", "140", this); throw new RuntimeException(e.toString()); } }
java
public synchronized boolean hasMoreElementsR() throws RemoteException, EnumeratorException { if (elements != null && index < elements.length) { return true; } else if (!exhausted) { // Reset our local cache and attempt to fetch the next batch // from the server try { elements = null; index = 0; elements = fetchElements(PREFETCH_COUNT); return true; } catch (NoMoreElementsException ex) { // We've exhausted the remote result set // FFDCFilter.processException(ex, CLASS_NAME + ".hasMoreElementsR", // "172", this); return false; } } // Exhausted! return false; }
java
public synchronized Object[] nextNElements(int n) throws RemoteException, EnumeratorException { if (!hasMoreElementsR()) { throw new NoMoreElementsException(); } EJBObject[] remainder = null; final int numCached = elements.length - index; if (!exhausted && numCached < n) { // We must fetch more elements from the remote result set // to satisfy the request try { remainder = fetchElements(n - numCached); } catch (NoMoreElementsException ex) { // FFDCFilter.processException(ex, CLASS_NAME + ".nextNElements", // "220", this); } } final int numRemaining = remainder != null ? remainder.length : 0; final int totalAvail = numCached + numRemaining; final int numToReturn = Math.min(n, totalAvail); final EJBObject[] result = new EJBObject[numToReturn]; final int numFromCache = Math.min(numToReturn, numCached); System.arraycopy(elements, index, result, 0, numFromCache); index += numFromCache; if (remainder != null) { System.arraycopy(remainder, 0, result, numFromCache, numRemaining); } return result; }
java
public EJBObject[] loadEntireCollection() { EJBObject[] result = null; try { result = (EJBObject[]) allRemainingElements(); } catch (NoMoreElementsException e) { // FFDCFilter.processException(e, CLASS_NAME + ".loadEntireCollection", // "270", this); return elements; } catch (EnumeratorException e) { // FFDCFilter.processException(e, CLASS_NAME + ".loadEntireCollection", // "276", this); throw new RuntimeException(e.toString()); } catch (RemoteException e) { // FFDCFilter.processException(e, CLASS_NAME + ".loadEntireCollection", // "282", this); throw new RuntimeException(e.toString()); } elements = result; return result; }
java
public synchronized Object[] allRemainingElements() throws RemoteException, EnumeratorException { if (!hasMoreElementsR()) { throw new NoMoreElementsException(); } EJBObject[] remainder = null; if (!exhausted) { // We must fetch the remaining elements from the remote // result set try { //110799 remainder = vEnum.allRemainingElements(); } catch (NoMoreElementsException ex) { // FFDCFilter.processException(ex, CLASS_NAME + ".allRemainingElements", // "313", this); } catch (java.rmi.NoSuchObjectException exc) { // FFDCFilter.processException(exc, CLASS_NAME + ".allRemainingElements", // "319", this); throw new com.ibm.ejs.container.finder.CollectionCannotBeFurtherAccessedException("Cannot access finder result outside transaction"); } //110799 finally { exhausted = true; vEnum = null; } } // Concatenate the unenumerated elements from our local cache // and the remaining elements from the remote result set. final int numCached = elements.length - index; final int numRemaining = remainder != null ? remainder.length : 0; final EJBObject[] result = new EJBObject[numCached + numRemaining]; System.arraycopy(elements, index, result, 0, numCached); if (remainder != null) { System.arraycopy(remainder, 0, result, numCached, numRemaining); } elements = null; return result; }
java
void extractPersistenceUnits(JPAPXml pxml) { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "extractPersistenceUnits : " + pxml); // Determines the correct schema version, and uses the correct version // of JAXB generated classes to parse the persistence.xml file... and // the correct version of .xsd to validate against. F1879-16302 JaxbPersistence p = JaxbUnmarshaller.unmarshal(pxml); List<JaxbPUnit> pus = p.getPersistenceUnit(); for (JaxbPUnit pu : pus) { // Guarantee to have a puName from <persistence-unit> String puName = pu.getName(); // Set <persistence-unit> JPAApplInfo applInfo = pxml.getApplInfo(); JPAPuId puId = new JPAPuId(applInfo.getApplName(), pxml.getArchiveName(), puName); // d689596 JPAPUnitInfo puInfo = applInfo.createJPAPUnitInfo(puId, pxml, ivScopeInfo); // set XML Schema version puInfo.setPersistenceXMLSchemaVersion(p.getVersion()); // Must set the root URL first for other puInfo attribute to reference // determine the root of the persistence unit. puInfo.setPersistenceUnitRootUrl(pxml.getRootURL()); // JaxbPunit abstraction properly maps the TransactionType from // the JAXB generated class to the JPA enum value. F1879-16302 puInfo.setTransactionType(pu.getTransactionType()); // Set <persistence-unit> puInfo.setPersistenceUnitDescription(pu.getDescription()); // Set <provider> puInfo.setPersistenceProviderClassName(pu.getProvider()); // Set <jta-data-source> puInfo.setJtaDataSource(pu.getJtaDataSource()); // Set <nonjta-data-source> puInfo.setNonJtaDataSource(pu.getNonJtaDataSource()); // Set <mapping-file> puInfo.setMappingFileNames(pu.getMappingFile()); // Set <jar-file> puInfo.setJarFileUrls(pu.getJarFile(), pxml); //PK62950 // Set <class> puInfo.setManagedClassNames(pu.getClazz()); // Set <shared-cache-mode> (mapped by JaxbPUnit abstraction) // F743-8705 F1879-16302 puInfo.setSharedCacheMode(pu.getSharedCacheMode()); // Set <validataion-mode> (mapped by JaxbPUnit abstraction) // F743-8705 F1879-16302 puInfo.setValidationMode(pu.getValidationMode()); // Set <exclude-unlisted-classes> puInfo.setExcludeUnlistedClasses(pu.isExcludeUnlistedClasses()); // Set <properties> (mapped by JaxbPUnit abstraction) F1879-16302 puInfo.setProperties(pu.getProperties()); if (isTraceOn && tc.isDebugEnabled()) { String rootURLStr = pxml.getRootURL().getFile(); int earIndex = rootURLStr.indexOf(applInfo.getApplName() + ".ear"); // d507361 if (earIndex != -1) { // d507361 rootURLStr = rootURLStr.substring(earIndex // d507361 + applInfo.getApplName().length() + 5); // d507361 } // d507361 rootURLStr += PERSISTENCE_XML_RESOURCE_NAME; // d507361 Tr.debug(tc, "extractPersistenceUnits : " + applInfo.getApplName() + "|" + pxml.getArchiveName() + "|" + rootURLStr + "|" + puInfo.getPersistenceUnitName() + "|" + ivScopeInfo.getScopeType() + "|" + puInfo.dump()); } if (getPuInfo(puName) != null) // d441029 { Tr.warning(tc, "DUPLICATE_PERSISTENCE_UNIT_DEFINED_CWWJP0007W", puName, applInfo.getApplName(), pxml.getArchiveName()); // d460065 puInfo.close(); // d681393 } else { addPU(puName, puInfo); // This getFactory initiates the createEntityManagerFactory call to // the persistence provider for this pu. This process will trigger // the provider to use the jta/non-jta data source defined in the // pu as well as register transformer to the application classloader // so that when entity class is loaded, the provider can enhance // the entity class. // // However if the factory is created at this point, the resource // ref defined for the associated component has not been initialized // yet and hence the java:comp/env scheme of specifying data sources // in persistence.xml can not be processed. // // But, if the factory is NOT created at this point, the provider // will not register the transformer, and thus the class will not // be transformed when it is loaded. // // To solve this problem, the factory will be created now, and a // 'generic' datasource will be provided, but, the created factory // will never be used. When a component finally accesses a factory, // (after the component has started), a new factory will be created, // one for every java:comp/env name context. Then, each component // will have a factory created with the correct datasource. puInfo.initialize(); // d429219 d510184 } JPAIntrospection.visitJPAPUnitInfo(puName, puInfo); } if (isTraceOn && tc.isEntryEnabled()) Tr.exit(tc, "extractPersistenceUnits : # of PU defined = " + getPuCount()); }
java
void close() { synchronized (ivPuList) { for (JPAPUnitInfo puInfo : ivPuList.values()) { puInfo.close(); } ivPuList.clear(); } }
java
JPAPUnitInfo addPU(String puName, JPAPUnitInfo puInfo) { synchronized (ivPuList) { return ivPuList.put(puName, puInfo); } }
java
StringBuilder toStringBuilder(StringBuilder sbuf) { synchronized (ivPuList) { sbuf.append("\n PxmlInfo: ScopeName=").append(ivScopeInfo.getScopeName()).append("\tRootURL = ").append(ivRootURL).append("\t# PUs = ").append(ivPuList.size()).append("\t["); int index = 0; for (JPAPUnitInfo puInfo : ivPuList.values()) { puInfo.toStringBuilder(sbuf); if (++index < ivPuList.size()) { sbuf.append(", "); } } sbuf.append(']'); } return sbuf; }
java
private static void restoreInvocationSubject(SubjectCookie cookie) { try { if (cookie.token != null) { // We sync'ed the subject's identity to the thread under setInvocationSubject. // Now restore the previous identity using the token returned when we sync'ed. ThreadIdentityManager.resetChecked(cookie.token); } } catch (ThreadIdentityException e) { throw new SecurityException(e); } finally { SubjectManagerService sms = smServiceRef.getService(); if (sms != null) { sms.setInvocationSubject(cookie.subject); } } }
java
public RetryState createRetryState(RetryPolicy policy, MetricRecorder metricRecorder) { if (policy == null) { return new RetryStateNullImpl(); } else { return new RetryStateImpl(policy, metricRecorder); } }
java
public SyncBulkheadState createSyncBulkheadState(BulkheadPolicy policy, MetricRecorder metricRecorder) { if (policy == null) { return new SyncBulkheadStateNullImpl(); } else { return new SyncBulkheadStateImpl(policy, metricRecorder); } }
java
public TimeoutState createTimeoutState(ScheduledExecutorService executorService, TimeoutPolicy policy, MetricRecorder metricRecorder) { if (policy == null) { return new TimeoutStateNullImpl(); } else { return new TimeoutStateImpl(executorService, policy, metricRecorder); } }
java
public CircuitBreakerState createCircuitBreakerState(CircuitBreakerPolicy policy, MetricRecorder metricRecorder) { if (policy == null) { return new CircuitBreakerStateNullImpl(); } else { return new CircuitBreakerStateImpl(policy, metricRecorder); } }
java
public Object[] getResults(String topic) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getResults", topic); if (cachedResults != null) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getResults", cachedResults); return cachedResults; } postProcess(topic); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "getResults", "finalResults: " + Arrays.toString(finalResults)); return finalResults; }
java
protected String createPlainTextJWT() { com.google.gson.JsonObject header = createHeader(); com.google.gson.JsonObject payload = createPayload(); String plainTextTokenString = computeBaseString(header, payload); StringBuffer sb = new StringBuffer(plainTextTokenString); sb.append(".").append(""); return sb.toString(); }
java
private ConnectionData findConnectionDataToUse() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "findConnectionDataToUse"); // Look through the the connection data in this group to try and find // a connection with the lowest use count. ConnectionData connectionDataToUse = null; synchronized (connectionData) { int lowestUseCount = conversationsPerConnection; for (int i = 0; i < connectionData.size(); ++i) { final ConnectionData cd = connectionData.get(i); if (cd.getUseCount() < lowestUseCount) { lowestUseCount = cd.getUseCount(); connectionDataToUse = cd; } } // If we cannot find a suitable connection data object, see if the // idle connections pool has a connection we could use to create one. if (connectionDataToUse == null) { final IdleConnectionPool p = IdleConnectionPool.getInstance(); final OutboundConnection oc = p.remove(groupEndpointDescriptor); if (oc != null) { connectionDataToUse = new ConnectionData(this, groupEndpointDescriptor); oc.setConnectionData(connectionDataToUse); connectionDataToUse.setConnection(oc); connectionData.add(connectionDataToUse); } } // If we now have a connectionDataToUse, increment its use count NOW // so that it won't get accidentally added to the idle pool if (connectionDataToUse != null) { connectionDataToUse.incrementUseCount(); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "findConnectionDataToUse", connectionDataToUse); return connectionDataToUse; }
java
private Conversation doConnect(ConversationReceiveListener conversationReceiveListener, ConversationUsageType usageType, JFapAddressHolder jfapAddressHolder, final NetworkConnectionFactoryHolder ncfHolder) throws JFapConnectFailedException, SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "doConnect", new Object[] { conversationReceiveListener, usageType, jfapAddressHolder, ncfHolder }); Conversation retConversation; ConnectionData connectionDataToUse; synchronized (connectionMonitor) { try { connectionDataToUse = findConnectionDataToUse(); boolean isNewConnectionData = false; if (connectionDataToUse == null) { // We were either unable to find a connection at all, or we could not // find a connection with a use count lower than the maximum number of // conversations we want to share a connection. Either way, create a // new connection and add it to the group. if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "connection data does not already exist"); try { NetworkConnection vc = connectOverNetwork(jfapAddressHolder, ncfHolder); connectionDataToUse = createnewConnectionData(vc); isNewConnectionData = true; } catch (FrameworkException frameworkException) { // Something went wrong attempting to establish the outbound connection. // Link the exception that was thrown to a new SICommsException and throw // it back to the caller. FFDCFilter.processException(frameworkException, "com.ibm.ws.sib.jfapchannel.impl.octracker.ConnectionDataGroup.doConnect", JFapChannelConstants.CONNDATAGROUP_CONNECT_04, this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.exception(this, tc, frameworkException); throw new SIErrorException(nls.getFormattedMessage("CONNDATAGROUP_INTERNAL_SICJ0062", null, "CONNDATAGROUP_INTERNAL_SICJ0062"), frameworkException); } } retConversation = startNewConversation(connectionDataToUse, conversationReceiveListener, isNewConnectionData, usageType.requiresNormalHandshakeProcessing()); } finally { // Whatever happened, this connection attempt is no longer pending. // //We have to hold the connectionMonitor lock prior to obtaining the lock on 'this' as there is the potential for deadlock in the following //scenario. // //Thread 1 starts the first conversation over the connection and has to perform handshaking. //Thread 2 starts another conversation and has to wait for thread 1 to perform the handshake. This means that thread 2 has acquired the lock on 'this'. //Thread 1 tries to acquire the lock on 'this' below. //Deadlock... synchronized (this) { --connectAttemptsPending; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, connectAttemptsPending + " connection attempts still pending"); } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "doConnect", retConversation); return retConversation; }
java
private NetworkConnection connectOverNetwork(JFapAddressHolder addressHolder, NetworkConnectionFactoryHolder factoryHolder) throws JFapConnectFailedException, FrameworkException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "connectOverNetwork", new Object[] { addressHolder, factoryHolder }); NetworkConnectionFactory vcf = factoryHolder.getFactory(); NetworkConnection vc = vcf.createConnection(); Semaphore sem = new Semaphore(); ClientConnectionReadyCallback callback = new ClientConnectionReadyCallback(sem); vc.connectAsynch(addressHolder.getAddress(), callback); sem.waitOnIgnoringInterruptions(); if (!callback.connectionSucceeded()) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Connect has failed due to ", callback.getException()); String failureKey; Object[] failureInserts; if (addressHolder.getAddress() != null) { failureKey = "CONNDATAGROUP_CONNFAILED_SICJ0063"; failureInserts = addressHolder.getErrorInserts(); } else { failureKey = "CONNDATAGROUP_CONNFAILED_SICJ0080"; failureInserts = new Object[] {}; } String message = nls.getFormattedMessage(failureKey, failureInserts, failureKey); throw new JFapConnectFailedException(message, callback.getException()); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "connectOverNetwork", vc); return vc; }
java
private ConnectionData createnewConnectionData(NetworkConnection vc) throws FrameworkException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "createnewConnectionData", vc); ConnectionData connectionDataToUse; NetworkConnectionContext connLink = vc.getNetworkConnectionContext(); connectionDataToUse = new ConnectionData(this, groupEndpointDescriptor); connectionDataToUse.incrementUseCount(); // New connections start with a use count of zero and it is now in use // No need to lock as it's not in the connectionData list yet OutboundConnection oc = new OutboundConnection(connLink, vc, tracker, heartbeatInterval, heartbeatTimeout, connectionDataToUse); connectionDataToUse.setConnection(oc); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "createnewConnectionData", connectionDataToUse); return connectionDataToUse; }
java
private Conversation startNewConversation(ConnectionData connectionDataToUse, ConversationReceiveListener conversationReceiveListener, boolean isNewConnectionData, boolean handshake) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "startNewConversation", new Object[] { connectionDataToUse, conversationReceiveListener, Boolean.valueOf(isNewConnectionData), Boolean.valueOf(handshake) }); Conversation retConversation; synchronized (this) { if (isNewConnectionData) { synchronized (connectionData) { connectionData.add(connectionDataToUse); } } // Start a new conversation over the designated connection. // If this is a connection on behalf of the WMQRA then we need to disable the normal handshaking behaviour // in order to allow other non WMQRA conversations to handshake as normal. retConversation = connectionDataToUse.getConnection().startNewConversation(conversationReceiveListener, handshake); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "startNewConversation", retConversation); return retConversation; }
java
protected synchronized void connectionPending() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "connectionPending"); ++connectAttemptsPending; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, connectAttemptsPending + " connection attempts now pending"); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "connectionPending"); }
java
protected synchronized void close(OutboundConnection connection) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "close", connection); // Paranoia: Check that this connection believes that it belongs in this group. if (connection.getConnectionData().getConnectionDataGroup() != this) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "connection does not belong to this group", connection.getConnectionData().getConnectionDataGroup()); throw new SIErrorException(nls.getFormattedMessage("CONNDATAGROUP_INTERNAL_SICJ0062", null, "CONNDATAGROUP_INTERNAL_SICJ0062")); // D226223 } ConnectionData data; boolean isNowIdle = false; synchronized (connectionData) { data = connection.getConnectionData(); data.decrementUseCount(); if (data.getUseCount() == 0) { // If no one is using this connection, then remove it from our group and // add it to the idle pool. connectionData.remove(data); isNowIdle = true; } } if (isNowIdle) { IdleConnectionPool.getInstance().add(data.getConnection(), groupEndpointDescriptor); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "close"); }
java
protected boolean isEmpty() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "isEmpty"); boolean result; synchronized (this) { synchronized (connectionData) { result = connectionData.isEmpty(); } result = result && (connectAttemptsPending == 0); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "isEmpty", "" + result); return result; }
java
protected void purgeFromInvalidateImpl(OutboundConnection connection, boolean notifyPeer) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "purgeFromInvalidateImpl", new Object[] { connection, Boolean.valueOf(notifyPeer) }); purge(connection, true, notifyPeer); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "purgeFromInvalidateImpl"); }
java
protected void purgeClosedConnection(OutboundConnection connection) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "purgeClosedConnection", connection); purge(connection, false, false); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "purgeClosedConnection"); }
java
public void removeConnectionDataFromGroup(ConnectionData cd) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "removeConnectionDataFromGroup", new Object[] { cd }); boolean removed = false; synchronized (connectionData) { removed = connectionData.remove(cd); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "removeConnectionDataFromGroup", new Object[] { removed }); }
java
public static String getDateString(Date date) { SimpleDateFormat sdf = new SimpleDateFormat(sdformatMillisec); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); StringBuffer dateBuffer = new StringBuffer(sdf.format(date)); // above string is in this format // 2005-05-04T09:34:18.444-0400 // convert it to // 2005-05-04T09:34:18.444-04:00 dateBuffer.insert(dateBuffer.length() - 2, ":"); return dateBuffer.toString(); }
java
public static String[] getRDNAttributes(String dn) { String rdnstr = getRDN(dn); StringTokenizer st = new StringTokenizer(rdnstr.toLowerCase(), "+"); List<String> list = new ArrayList<String>(); while (st.hasMoreTokens()) { String rdn = st.nextToken(); int index = rdn.indexOf('='); if (index > -1) { list.add(rdn.substring(0, index)); } } return list.toArray(new String[0]); }
java
public static String getRDN(String DN) { if (DN == null || DN.trim().length() == 0) { return DN; } String RDN = null; try { LdapName name = new LdapName(DN); if (name.size() == 0) { return DN; } RDN = name.get(name.size() - 1); } catch (InvalidNameException e) { e.getMessage(); DN = DN.trim(); int pos1 = DN.indexOf(','); if (DN.charAt(pos1 - 1) == '\\') { pos1 = DN.indexOf(pos1, ','); } if (pos1 > -1) { RDN = DN.substring(0, pos1).trim(); } else { RDN = DN; } } return RDN; }
java
static public LdapURL[] getLdapURLs(Attribute attr) throws WIMException { final String METHODNAME = "getLdapURLs"; LdapURL[] ldapURLs = new LdapURL[0]; if (attr != null) { List<LdapURL> ldapURLList = new ArrayList<LdapURL>(attr.size()); try { for (NamingEnumeration<?> enu = attr.getAll(); enu.hasMoreElements();) { LdapURL ldapURL = new LdapURL((String) (enu.nextElement())); if (ldapURL.parsedOK()) { ldapURLList.add(ldapURL); } else { if (tc.isDebugEnabled()) { Tr.debug(tc, METHODNAME + " Member URL query: " + ldapURL.get_url() + " is invalid and ingored."); } } } } catch (NamingException e) { throw new WIMSystemException(WIMMessageKey.NAMING_EXCEPTION, Tr.formatMessage( tc, WIMMessageKey.NAMING_EXCEPTION, WIMMessageHelper.generateMsgParms(e.toString(true)))); } ldapURLs = ldapURLList.toArray(ldapURLs); } return ldapURLs; }
java
public static String getUniqueKey(X509Certificate cert) { // TBD - Would like to use public key instead of subject name, but // cert.getPublicKey().getEncoded() appears to return different // values for each call, using the same certificate?? StringBuffer key = new StringBuffer("subjectDN:"); key.append(cert.getSubjectX500Principal().getName()).append("issuerDN:").append(cert.getIssuerX500Principal().getName()); // TODO:: // return Base64Coder.base64Encode(getDigest(key.toString())); return null; }
java
static String getDNSubField(String varName, String DN) throws CertificateMapperException { if (varName.equals("DN")) { return DN; // return the whole DN } // Parse the DN looking for 'varName' StringTokenizer st = new StringTokenizer(DN); for (;;) { String name, value; try { name = st.nextToken(",= "); value = st.nextToken(","); if (value != null) { value = value.substring(1); } } catch (NoSuchElementException e) { e.getMessage(); break; } if (name.equals(varName)) { return value; } } throw new CertificateMapperException(WIMMessageKey.UNKNOWN_DN_FIELD, Tr.formatMessage( tc, WIMMessageKey.UNKNOWN_DN_FIELD, WIMMessageHelper.generateMsgParms(varName))); }
java
public static short getMembershipScope(String scope) { if (scope != null) { scope = scope.trim(); if (LdapConstants.LDAP_DIRECT_GROUP_MEMBERSHIP_STRING.equalsIgnoreCase(scope)) { return LdapConstants.LDAP_DIRECT_GROUP_MEMBERSHIP; } else if (LdapConstants.LDAP_NESTED_GROUP_MEMBERSHIP_STRING.equalsIgnoreCase(scope)) { return LdapConstants.LDAP_NESTED_GROUP_MEMBERSHIP; } else if (LdapConstants.LDAP_ALL_GROUP_MEMBERSHIP_STRING.equalsIgnoreCase(scope)) { return LdapConstants.LDAP_ALL_GROUP_MEMBERSHIP; } else { return LdapConstants.LDAP_DIRECT_GROUP_MEMBERSHIP; } } else { return LdapConstants.LDAP_DIRECT_GROUP_MEMBERSHIP; } }
java
public static boolean inAttributes(String attrName, Attributes attrs) { for (NamingEnumeration<String> neu = attrs.getIDs(); neu.hasMoreElements();) { String attrId = neu.nextElement(); if (attrId.equalsIgnoreCase(attrName)) { return true; } } return false; }
java
public static Attribute cloneAttribute(String newAttrName, Attribute attr) throws WIMSystemException { Attribute newAttr = new BasicAttribute(newAttrName); try { for (NamingEnumeration<?> neu = attr.getAll(); neu.hasMoreElements();) { newAttr.add(neu.nextElement()); } } catch (NamingException e) { throw new WIMSystemException(WIMMessageKey.NAMING_EXCEPTION, Tr.formatMessage(tc, WIMMessageKey.NAMING_EXCEPTION, WIMMessageHelper.generateMsgParms(e.toString(true)))); } return newAttr; }
java
public static String convertToDashedString(byte[] objectGUID) { StringBuilder displayStr = new StringBuilder(); displayStr.append(prefixZeros(objectGUID[3] & 0xFF)); displayStr.append(prefixZeros(objectGUID[2] & 0xFF)); displayStr.append(prefixZeros(objectGUID[1] & 0xFF)); displayStr.append(prefixZeros(objectGUID[0] & 0xFF)); displayStr.append("-"); displayStr.append(prefixZeros(objectGUID[5] & 0xFF)); displayStr.append(prefixZeros(objectGUID[4] & 0xFF)); displayStr.append("-"); displayStr.append(prefixZeros(objectGUID[7] & 0xFF)); displayStr.append(prefixZeros(objectGUID[6] & 0xFF)); displayStr.append("-"); displayStr.append(prefixZeros(objectGUID[8] & 0xFF)); displayStr.append(prefixZeros(objectGUID[9] & 0xFF)); displayStr.append("-"); displayStr.append(prefixZeros(objectGUID[10] & 0xFF)); displayStr.append(prefixZeros(objectGUID[11] & 0xFF)); displayStr.append(prefixZeros(objectGUID[12] & 0xFF)); displayStr.append(prefixZeros(objectGUID[13] & 0xFF)); displayStr.append(prefixZeros(objectGUID[14] & 0xFF)); displayStr.append(prefixZeros(objectGUID[15] & 0xFF)); return displayStr.toString(); }
java
public static JsonValue serializeAsJson(Object o) throws IOException { try { return findFieldsToSerialize(o).mainObject; } catch (IllegalStateException ise) { // the reflective attempt to build the object failed. throw new IOException("Unable to build JSON for Object", ise); } catch (JsonException e) { throw new IOException("Unable to build JSON for Object", e); } }
java
private static ClassAndMethod getClassForFieldName(String fieldName, Class<?> classToLookForFieldIn) { return internalGetClassForFieldName(fieldName, classToLookForFieldIn, false); }
java
private static ClassAndMethod getClassForCollectionOfFieldName(String fieldName, Class<?> classToLookForFieldIn) { return internalGetClassForFieldName(fieldName, classToLookForFieldIn, true); }
java
private static ClassAndMethod internalGetClassForFieldName(String fieldName, Class<?> classToLookForFieldIn, boolean isForArray) { Method found = null; //precalc the field name as a setter to use for each method test. String fieldNameAsASetter = new StringBuilder("set").append(fieldName.substring(0, 1).toUpperCase()).append(fieldName.substring(1)).toString(); //hunt for any matching setter in the object for (Method m : classToLookForFieldIn.getMethods()) { String methodName = m.getName(); //eligible setters must only accept a single argument. if (m.getParameterTypes().length == 1 && methodName.equals(fieldNameAsASetter)) { found = m; break; } } //at the mo, if we don't match a setter, we sysout a warning, this will likely need to become a toggle. if (found == null) { if (DataModelSerializer.IGNORE_UNKNOWN_FIELDS) { return null; } else { throw new IllegalStateException("Data Model Error: Found unexpected JSON field " + fieldName + " supposedly for in class " + classToLookForFieldIn.getName()); } } else { ClassAndMethod cm = new ClassAndMethod(); cm.m = found; if (isForArray) { //for an array we return the type of the collection, eg String for List<String> instead of List. Type t = found.getGenericParameterTypes()[0]; cm.cls = getClassForType(t); return cm; } else { cm.cls = found.getParameterTypes()[0]; return cm; } } }
java
public static void addThreadIdentityService(ThreadIdentityService tis) { if (tis != null) { threadIdentityServices.add(tis); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "A ThreadIdentityService implementation was added.", tis.getClass().getName()); } } }
java
public static void addJ2CIdentityService(J2CIdentityService j2cIdentityService) { if (j2cIdentityService != null) { j2cIdentityServices.add(j2cIdentityService); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "A J2CIdentityService implementation was added.", j2cIdentityService.getClass().getName()); } } }
java
public static void removeThreadIdentityService(ThreadIdentityService tis) { if (tis != null) { threadIdentityServices.remove(tis); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "A ThreadIdentityService implementation was removed.", tis.getClass().getName()); } } }
java
public static void removeJ2CIdentityService(J2CIdentityService j2cIdentityService) { if (j2cIdentityService != null) { j2cIdentityServices.remove(j2cIdentityService); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "A J2CIdentityService implementation was removed.", j2cIdentityService.getClass().getName()); } } }
java
public static void removeAllThreadIdentityServices() { threadIdentityServices.clear(); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "All the ThreadIdentityService implementations were removed."); } }
java
public static void removeAllJ2CIdentityServices() { j2cIdentityServices.clear(); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "All the J2CIdentityService implementations were removed."); } }
java
private static boolean checkForRecursionAndSet() { if (recursionMarker.get() == null) { recursionMarker.set(Boolean.TRUE); return false; } else { return true; // recursion detected. } }
java
public static Object runAsServer() { LinkedHashMap<ThreadIdentityService, Object> token = null; if (!checkForRecursionAndSet()) { try { for (int i = 0, size = threadIdentityServices.size(); i < size; ++i) { ThreadIdentityService tis = threadIdentityServices.get(i); if (tis.isAppThreadIdentityEnabled()) { if (token == null) { token = new LinkedHashMap<ThreadIdentityService, Object>(); } token.put(tis, tis.runAsServer()); } } } finally { resetRecursionCheck(); } } return token == null ? Collections.EMPTY_MAP : token; }
java
@SuppressWarnings({ "rawtypes" }) private static void resetCheckedInternal(Object token, Exception firstException) throws ThreadIdentityException { Exception cachedException = firstException; if (threadIdentityServices.isEmpty() == false || j2cIdentityServices.isEmpty() == false) { if (!checkForRecursionAndSet()) { try { if (token != null) { Map tokenMap = (Map) token; int size = tokenMap.size(); if (size > 0) { @SuppressWarnings("unchecked") List<Map.Entry> identityServicesToTokensMap = new ArrayList<Map.Entry>(tokenMap.entrySet()); for (int idx = size - 1; idx >= 0; idx--) { Map.Entry entry = identityServicesToTokensMap.get(idx); Object identityService = entry.getKey(); Object identityServiceToken = entry.getValue(); try { if (identityService instanceof ThreadIdentityService) { ((ThreadIdentityService) identityService).reset(identityServiceToken); } else if (identityService instanceof J2CIdentityService) { ((J2CIdentityService) identityService).reset(identityServiceToken); } } catch (Exception e) { com.ibm.ws.ffdc.FFDCFilter.processException(e, thisClass, "385"); if (cachedException == null) { cachedException = e; } } } } } } finally { resetRecursionCheck(); if (cachedException != null) { throw new ThreadIdentityException(cachedException); } } } } }
java
public static Subject getJ2CInvocationSubject() { Subject j2cSubject = null; for (J2CIdentityService j2cIdentityService : j2cIdentityServices) { if (j2cIdentityService.isJ2CThreadIdentityEnabled()) { Subject subject = j2cIdentityService.getJ2CInvocationSubject(); if (subject != null) { j2cSubject = subject; break; } } } return j2cSubject; }
java
@Override public Map<String, List<AppConfigurationEntry>> getEntries() { Map<String, List<AppConfigurationEntry>> jaasConfigurationEntries = new HashMap<String, List<AppConfigurationEntry>>(); Map<String, String> jaasConfigIDs = new HashMap<String, String>(); if (jaasLoginContextEntries != null) { createJAASClientLoginContextEntry(jaasConfigurationEntries); Iterator<JAASLoginContextEntry> lcEntries = jaasLoginContextEntries.getServices(); while (lcEntries.hasNext()) { JAASLoginContextEntry loginContextEntry = lcEntries.next(); String entryName = loginContextEntry.getEntryName(); List<JAASLoginModuleConfig> loginModules = loginContextEntry.getLoginModules(); if (JaasLoginConfigConstants.SYSTEM_DEFAULT.equalsIgnoreCase(entryName)) { ensureProxyIsNotSpecifyInSystemDefaultEntry(entryName, loginModules); } List<AppConfigurationEntry> appConfEntry = getLoginModules(loginModules); if (appConfEntry != null && !appConfEntry.isEmpty()) { if (jaasConfigIDs.containsKey(entryName)) { // if there is a duplicate name, log a warning message to indicate which id is being overwritten. String id = jaasConfigIDs.get(entryName); Tr.warning(tc, "JAAS_LOGIN_CONTEXT_ENTRY_HAS_DUPLICATE_NAME", new Object[] { entryName, id, loginContextEntry.getId() }); } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "configure jaasContextLoginEntry id: " + loginContextEntry.getId()); Tr.debug(tc, "configure jaasContextLoginEntry: " + entryName + " has " + appConfEntry.size() + " loginModule(s)"); Tr.debug(tc, "appConfEntry: " + appConfEntry); } jaasConfigurationEntries.put(entryName, appConfEntry); jaasConfigIDs.put(entryName, loginContextEntry.getId()); } } } return jaasConfigurationEntries; }
java
@Override @Trivial public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("addTransformer".equals(method.getName())) { addTransformer((ClassFileTransformer) args[0], args.length > 1 ? (Boolean) args[1] : false); return null; } if ("removeTransformer".equals(method.getName())) { return removeTransformer((ClassFileTransformer) args[0]); } if ("appendToBootstrapClassLoaderSearch".equals(method.getName())) { appendToBootstrapClassLoaderSearch((JarFile) args[0]); return null; } if ("appendToSystemClassLoaderSearch".equals(method.getName())) { appendToSystemClassLoaderSearch((JarFile) args[0]); return null; } if ("setNativeMethodPrefix".equals(method.getName())) { setNativeMethodPrefix((ClassFileTransformer) args[0], (String) args[1]); return null; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, method.getName(), args); } Object retValue = method.invoke(instrumentation, args); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { if (void.class == method.getReturnType()) { Tr.exit(tc, method.getName()); } else { Tr.exit(tc, method.getName(), retValue); } } return retValue; }
java
public static void addSubjectCustomData(Subject callSubject, Hashtable<String, Object> newCred) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "addSubjectCustomData", newCred); } AddPrivateCredentials action = new AddPrivateCredentials(callSubject, newCred); AccessController.doPrivileged(action); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "addSubjectCustomData"); } }
java
public static Hashtable<String, Object> getCustomCredentials(Subject callSubject, String cacheKey) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "getCustomCredentials", cacheKey); } if (callSubject == null || cacheKey == null) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "getCustomCredentials", " null"); } return null; } GetCustomCredentials action = new GetCustomCredentials(callSubject, cacheKey); Hashtable<String, Object> cred = (Hashtable<String, Object>) AccessController.doPrivileged(action); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "getCustomCredentials", objectId(cred)); } return cred; }
java
public static void handlePasswordValidationCallback(PasswordValidationCallback callback, Subject executionSubject, Hashtable<String, Object> addedCred, String appRealm, Invocation[] invocations) throws RemoteException, WSSecurityException { invocations[2] = Invocation.PASSWORDVALIDATIONCALLBACK; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "handlePasswordValidationCallback", new Object[] { objectId(callback), callback.getUsername() }); } Subject callSubject = callback.getSubject(); if (!executionSubject.equals(callSubject)) { Tr.warning(tc, "EXECUTION_CALLBACK_SUBJECT_MISMATCH_J2CA0673", new Object[] { "PasswordValidationCallback" }); callSubject = executionSubject; } try { // 673415 String userName = callback.getUsername(); String password = null; if (callback.getPassword() != null) { password = new String(callback.getPassword()); } if (callSubject != null) { GetRegistry action = new GetRegistry(appRealm); UserRegistry registry = AccessController.doPrivileged(action); if (checkUserPassword(userName, password, registry, appRealm, addedCred, invocations[0])) { callback.setResult(true); } else { callback.setResult(false); addedCred.clear(); // 673415 } } } catch (PrivilegedActionException pae) { // End 673415 callback.setResult(false); addedCred.clear(); Exception ex = pae.getException(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "handlePasswordValidationCallback", callback.getResult()); } if (ex instanceof WSSecurityException) { throw (WSSecurityException) ex; } else { // This means an unexpected runtime exception is wrapped in the PrivilegedActionException throw new WSSecurityException(ex); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "handlePasswordValidationCallback", callback.getResult()); } }
java
private static void addUniqueIdAndGroupsForUser(String securityName, Hashtable<String, Object> credData, String appRealm) // 675924 throws WSSecurityException, RemoteException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "addUniqueIdAndGroupsForUser", securityName); } GetRegistry action = new GetRegistry(appRealm); UserRegistry registry = null; try { registry = AccessController.doPrivileged(action); } catch (PrivilegedActionException pae) { Exception ex = pae.getException(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "addUniqueIdAndGroupsForUser"); } if (ex instanceof WSSecurityException) { throw (WSSecurityException) ex; } else { // This means an unexpected runtime exception is wrapped in the PrivilegedActionException throw new WSSecurityException(ex); } } if (registry.isValidUser(securityName)) { String uniqueId = registry.getUniqueUserId(securityName); String uidGrp = stripRealm(uniqueId, appRealm); // 669627 // 673415 List<?> groups = null; try { groups = registry.getUniqueGroupIds(uidGrp); // 673415 } catch (EntryNotFoundException ex) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "Exception is ", ex); Tr.warning(tc, "NO_GROUPS_FOR_UNIQUEID_J2CA0679", uidGrp); // 673415 } updateCustomHashtable(credData, appRealm, uniqueId, securityName, groups); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "Added uniqueId: " + uniqueId + " and uniqueGroups: " + groups); } else { String message = getNLS() .getFormattedMessage("INVALID_USER_NAME_IN_PRINCIPAL_J2CA0670", new Object[] { securityName }, "J2CA0670E: The WorkManager was unable to establish the security context for the Work instance, " + "because the resource adapter provided a caller identity " + securityName + ", which does not belong to the security " + "domain associated with the application."); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "addUniqueIdAndGroupsForUser"); } throw new WSSecurityException(message); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "addUniqueIdAndGroupsForUser"); } }
java
private static boolean checkUserPassword(String userSecurityName, String password, UserRegistry registry, String realmName, Hashtable<String, Object> addedCred, Invocation isCCInvoked) { // 675924 if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "checkUserPassword user: " + userSecurityName + ", realm: " + realmName); } if (userSecurityName == null || password == null) { Tr.error(tc, "INVALID_USERNAME_PASSWORD_INBOUND_J2CA0674", userSecurityName); // 673415 if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "checkUserPassword", new Object[] { userSecurityName, password }); } return false; // 675924 } boolean match = validateCallbackInformation(addedCred, userSecurityName, isCCInvoked); // 675924 if (!match) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "checkUserPassword", " - invalid username and password."); } return false; // 675924 } try { registry.checkPassword(userSecurityName, password); String uniqueId = registry.getUniqueUserId(userSecurityName); uniqueId = stripRealm(uniqueId, realmName); // 669627 List<String> uniqueGroups = new ArrayList<String>(); List<?> groupNames = registry.getGroupsForUser(userSecurityName); if (groupNames != null) for (Object group : groupNames) { uniqueGroups.add(registry.getUniqueGroupId((String) group)); } updateCustomHashtable(addedCred, realmName, uniqueId, userSecurityName, uniqueGroups); } catch (PasswordCheckFailedException e) { // This error is thrown when there is no entry corresponding to the username and password // in the registry. Tr.error(tc, "INVALID_USERNAME_PASSWORD_INBOUND_J2CA0674", userSecurityName); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "checkUserPassword", " - invalid username and password"); // 675924 } return false; // 675924 } catch (Exception e) { FFDCFilter.processException(e, "com.ibm.ejs.j2c.work.security.J2CSecurityHelper.checkUserPassword", "%C"); Tr.error(tc, "VALIDATION_FAILED_INBOUND_J2CA0684", userSecurityName); // 675924 if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "checkUserPassword", " - unable to validate password."); } return false; // 675924 } // End 673415 if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "checkUserPassword", " - password is valid."); } return true; }
java
public static String getCacheKey(String uniqueId, String appRealm) { StringBuilder cacheKey = new StringBuilder(); if (uniqueId == null || appRealm == null) { cacheKey.append(CACHE_KEY_PREFIX); } else { cacheKey.append(CACHE_KEY_PREFIX).append(uniqueId).append(CACHE_KEY_SEPARATOR).append(appRealm); } return cacheKey.toString(); }
java
private static boolean validateCallbackInformation(Hashtable<String, Object> credData, String securityName, Invocation isInvoked) { boolean status = true; if (isInvoked == Invocation.CALLERPRINCIPALCALLBACK) { String existingName = (String) credData.get(AttributeNameConstants.WSCREDENTIAL_SECURITYNAME); if (existingName != null && !(existingName.equals(securityName))) { status = false; Tr.error(tc, "CALLBACK_SECURITY_NAME_MISMATCH_J2CA0675", new Object[] { securityName, existingName }); } } return status; }
java
public static String objectId(Object o) { return (o == null) ? "0x0" : o.getClass().getName() + "@" + Integer.toHexString(o.hashCode()); }
java
synchronized void activate(ComponentContext componentContext) throws Exception { this.componentContext = componentContext; this.classAvailableTransformer = new ClassAvailableTransformer(this, instrumentation, includeBootstrap); this.transformer = new ProbeClassFileTransformer(this, instrumentation, includeBootstrap); this.proxyActivator = new MonitoringProxyActivator(componentContext.getBundleContext(), this, this.instrumentation); this.proxyActivator.activate(); // The class available transformer is registered as retransform incapable // to avoid having to keep track of which classes have been updated with // static initializers and serialVersionUID fields. The probe transformer // however, must run through the listener config every time a retransform // occurs to allow it to discover new probes and replace currently active // probes //RTCD 89497-Update the set with the classes for (Class<?> clazz : MonitoringUtility.loadMonitoringClasses(componentContext.getBundleContext().getBundle())) { for (int i = 0; i < clazz.getMethods().length; i++) { Annotation anno = ((clazz.getMethods()[i]).getAnnotation(ProbeSite.class)); if (anno != null) { String temp = ((ProbeSite) anno).clazz(); probeMonitorSet.add(temp); } } } //Update to the set ended. //RTC D89497 adding instrumentors moved below as the MonitoringUtility.loadMonitoringClasses //was resulting in loading classes and in turn getting called during with transform process which //might cause hang in some situations this.instrumentation.addTransformer(this.transformer, true); this.instrumentation.addTransformer(this.classAvailableTransformer); // We're active so if we have any listeners, we can run down the loaded // classes. for (Class<?> clazz : this.instrumentation.getAllLoadedClasses()) { classAvailable(clazz); } }
java
synchronized void deactivate() throws Exception { this.proxyActivator.deactivate(); this.instrumentation.removeTransformer(this.classAvailableTransformer); this.instrumentation.removeTransformer(this.transformer); this.shuttingDown = true; // Save the classes that have listeners so we can retransform Collection<Class<?>> probedClasses = processRemovedListeners(allRegisteredListeners); // Clear all data structures listenersLock.writeLock().lock(); try { listenersForMonitor.clear(); allRegisteredListeners.clear(); } finally { listenersLock.writeLock().unlock(); } activeProbesById.clear(); listenersByProbe.clear(); listenersByClass.clear(); probesByKey.clear(); probesByListener.clear(); this.proxyActivator = null; this.transformer = null; this.componentContext = null; // Retransform the probed classes without our transformers in play if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(this, tc, "deactivate: probedClasses.size() = " + probedClasses.size()); } for (Class<?> clazz : probedClasses) { instrumentation.retransformClasses(clazz); } this.instrumentation = null; }
java
@Override public boolean registerMonitor(Object monitor) { // Process the annotated object, build a configuration, and create probe // listeners that represent each call site of the monitor. if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(this, tc, "monitor = " + monitor); } long startTime = System.nanoTime(); Set<ProbeListener> listeners = buildListenersFromAnnotated(monitor); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(this, tc, "buildListenersFromAnnotated time = " + TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - startTime) + "usec"); } // Update collections of listeners startTime = System.nanoTime(); if (!addListenersForMonitor(monitor, listeners)) { return false; } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(this, tc, "addListenersForMonitorTime = " + TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - startTime) + "usec"); } // Process all of the listeners and determine which of the available // classes needs to be transformed startTime = System.nanoTime(); Collection<Class<?>> effectedClasses = processNewListeners(listeners); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(this, tc, "processNewListeners time = " + TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - startTime) + "usec"); } // Update the classes with the configured probes if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(this, tc, "effectedClasses.size() = " + effectedClasses.size()); } startTime = System.nanoTime(); this.transformer.instrumentWithProbes(effectedClasses); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(this, tc, "instrumentWithProbes time = " + TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - startTime) + "usec"); } return true; }
java
@Override public boolean unregisterMonitor(Object annotatedObject) { // Clear the listener data if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(this, tc, "unregisteringMonitor = " + annotatedObject); } Set<ProbeListener> listeners = removeListenersForMonitor(annotatedObject); if (listeners == null) { return false; } // Remove the listeners associated with the inactive monitor and // find out which classes need to be transformed to remove stale probes Collection<Class<?>> effectedClasses = processRemovedListeners(listeners); // Update the classes to remove dead probes (optional) if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(this, tc, "effectedClasses.size() = " + effectedClasses.size()); } this.transformer.instrumentWithProbes(effectedClasses); Set set = moduleInstanceToBundleMap.entrySet(); Iterator i = set.iterator(); while (i.hasNext()) { Map.Entry mapE = (Map.Entry) i.next(); if (mapE != null && mapE.getValue().equals(annotatedObject.getClass().getName())) { PmiAbstractModule s = (PmiAbstractModule) mapE.getKey(); s.unregister(); } } return true; }
java
Set<ProbeListener> removeListenersForMonitor(Object monitor) { Set<ProbeListener> listeners = null; listenersLock.writeLock().lock(); try { listeners = listenersForMonitor.remove(monitor); if (listeners == null) { listeners = Collections.emptySet(); } else { allRegisteredListeners.removeAll(listeners); } } finally { listenersLock.writeLock().unlock(); } return listeners; }
java
Collection<Class<?>> processNewListeners(Collection<ProbeListener> listeners) { Set<Class<?>> classesToTransform = new HashSet<Class<?>>(); Set<ProbeListener> matchingListeners = new HashSet<ProbeListener>(); Set<Class<?>> monitorableTemp; synchronized (this.monitorable) { monitorableTemp = new HashSet<Class<?>>(this.monitorable); } for (Class<?> clazz : monitorableTemp /* instrumentation.getAllLoadedClasses() */) { if (!isMonitorable(clazz)) { continue; } for (ProbeListener listener : listeners) { ProbeFilter filter = listener.getProbeFilter(); if (filter.matches(clazz)) { matchingListeners.add(listener); } } if (!matchingListeners.isEmpty()) { classesToTransform.add(clazz); addInterestedByClass(clazz, matchingListeners); } matchingListeners.clear(); } return classesToTransform; }
java
synchronized Collection<Class<?>> processRemovedListeners(Collection<ProbeListener> listeners) { Set<Class<?>> classesToTransform = new HashSet<Class<?>>(); for (ProbeListener listener : listeners) { Collection<ProbeImpl> listenerProbes = removeProbesByListener(listener); for (ProbeImpl probe : listenerProbes) { Class<?> clazz = probe.getSourceClass(); removeInterestedByClass(clazz, listener); if (removeListenerByProbe(probe, listener)) { classesToTransform.add(clazz); } } } return classesToTransform; }
java
public void classAvailable(Class<?> clazz) { if (!isMonitorable(clazz)) { return; } listenersLock.readLock().lock(); try { for (ProbeListener listener : allRegisteredListeners) { ProbeFilter filter = listener.getProbeFilter(); if (filter.matches(clazz)) { addInterestedByClass(clazz, Collections.singleton(listener)); } } } finally { listenersLock.readLock().unlock(); } // Update the new class with the configured probes if (!getInterestedByClass(clazz).isEmpty()) { this.transformer.instrumentWithProbes(Collections.<Class<?>> singleton(clazz)); } }
java
public synchronized ProbeImpl getProbe(Class<?> probedClass, String key) { Map<String, ProbeImpl> classProbes = probesByKey.get(probedClass); if (classProbes != null) { return classProbes.get(key); } return null; }
java
public void addActiveProbesforListener(ProbeListener listener, Collection<ProbeImpl> probes) { // Add the probes for the specified listener. This is purely additive. // Since a listener's configuration can't be updated after registration, // we're adding probes for recently initialized / modified classes. addProbesByListener(listener, probes); for (ProbeImpl probe : probes) { addListenerByProbe(probe, listener); } }
java
void addListenerByProbe(ProbeImpl probe, ProbeListener listener) { Set<ProbeListener> listeners = listenersByProbe.get(probe); if (listeners == null) { listeners = new CopyOnWriteArraySet<ProbeListener>(); listenersByProbe.putIfAbsent(probe, listeners); listeners = listenersByProbe.get(probe); } listeners.add(listener); }
java
boolean removeListenerByProbe(ProbeImpl probe, ProbeListener listener) { boolean deactivatedProbe = false; Set<ProbeListener> listeners = listenersByProbe.get(probe); if (listeners != null) { listeners.remove(listener); if (listeners.isEmpty()) { deactivateProbe(probe); deactivatedProbe = true; } } return deactivatedProbe; }
java
synchronized void deactivateProbe(ProbeImpl probe) { listenersByProbe.remove(probe); activeProbesById.remove(probe.getIdentifier()); Class<?> clazz = probe.getSourceClass(); Map<String, ProbeImpl> classProbesByKey = probesByKey.get(clazz); classProbesByKey.remove(probe.getName()); if (classProbesByKey.isEmpty()) { probesByKey.remove(clazz); } }
java
synchronized void addProbesByListener(ProbeListener listener, Collection<ProbeImpl> probes) { Set<ProbeImpl> listenerProbes = probesByListener.get(listener); if (listenerProbes == null) { listenerProbes = new HashSet<ProbeImpl>(); probesByListener.put(listener, listenerProbes); } listenerProbes.addAll(probes); }
java
synchronized Collection<ProbeImpl> removeProbesByListener(ProbeListener listener) { Set<ProbeImpl> listenerProbes = probesByListener.remove(listener); if (listenerProbes == null) { listenerProbes = Collections.emptySet(); } return listenerProbes; }
java
public boolean isExcludedClass(String className) { // We rely heavily on reflection to deliver probes if (className.startsWith("java/lang/reflect")) { return true; } // Miscellaneous sun.misc classes if (className.startsWith("sun/misc")) { return true; } // Sun VM generated accessors wreak havoc if (className.startsWith("sun/reflect")) { return true; } // IBM J9 VM internals if (className.startsWith("com/ibm/oti/")) { return true; } // Don't allow hooking into the monitoring code if (className.startsWith("com/ibm/ws/monitor/internal")) { return true; } if (className.startsWith("com/ibm/websphere/monitor")) { return true; } if (className.startsWith("com/ibm/ws/boot/delegated/monitoring")) { return true; } if ((className.startsWith("com/ibm/ws/pmi")) || (className.startsWith("com/ibm/websphere/pmi")) || (className.startsWith("com/ibm/wsspi/pmi"))) { return true; } //D89497-Excluding those classes which are not part of the Set. if ((!(probeMonitorSet.contains((className.replace("/", ".")))))) { return true; } return false; }
java
public boolean isMonitorable(Class<?> clazz) { // Faster(?) path if (notMonitorable.contains(clazz)) { return false; } else if (monitorable.contains(clazz)) { return true; } boolean isMonitorable = true; if (!instrumentation.isModifiableClass(clazz)) { isMonitorable = false; } else if (clazz.isInterface()) { isMonitorable = false; } else if (clazz.isArray()) { isMonitorable = false; } else if (Proxy.isProxyClass(clazz)) { isMonitorable = false; } else if (clazz.isPrimitive()) { isMonitorable = false; } else if (isExcludedClass(Type.getInternalName(clazz))) { isMonitorable = false; } else if (!includeBootstrap && clazz.getClassLoader() == null) { isMonitorable = false; } // Update collections if (!isMonitorable) { synchronized (notMonitorable) { notMonitorable.add(clazz); } } else { monitorable.add(clazz); } return isMonitorable; }
java
boolean checkPrefix(char[] chars, int[] cursor) { if (chars.length > cursor[0] && chars[cursor[0]] == MatchSpace.NONWILD_MARKER) return false; if (prefix == null) return true; if (cursor[1] - cursor[0] < prefix.minlen) // a conservative test, but if we can't pass it, we'll certainly fail later return false; for (int i = 0; i < prefix.items.length; i++) { Object item = prefix.items[i]; if (item == Pattern.matchOne) if (!topicSkipForward(chars, cursor)) return false; else ; // topic skip succeeded so continue else if (!matchForward(chars, (char[]) item, cursor)) return false; // else this phase succeeded so continue } // The prefix matches exactly. But, unless we are at the end of the string, // the next character MUST be a separator. return cursor[0] == cursor[1] || chars[cursor[0]] == MatchSpace.SUBTOPIC_SEPARATOR_CHAR; }
java
static boolean topicSkipForward(char[] chars, int[] cursor) { if (cursor[0] == cursor[1]) return false; while (cursor[0] < cursor[1] && chars[cursor[0]] != MatchSpace.SUBTOPIC_SEPARATOR_CHAR) cursor[0]++; return true; }
java
boolean checkSuffix(char[] chars, int[] cursor) { if (suffix == null) return true; if (cursor[1] - cursor[0] < suffix.minlen) // a conservative test, but if we can't pass it, we'll certainly fail later return false; int last = suffix.items.length - 1; for (int i = last; i >= 0; i--) { Object item = suffix.items[i]; if (item == Pattern.matchOne) if (!topicSkipBackward(chars, cursor)) return false; else ; // topic skip succeeded so continue else if (!matchBackward(chars, (char[]) item, cursor)) return false; // else this phase succeeded so continue } // The suffix matches exactly. But, the preceding character MUST be a separator. We // don't allow start-of-string because we would not have checked the suffix // at all if it were allowed to extend to the beginning (it would then be identical // to the prefix). return cursor[0] < cursor[1] && chars[cursor[1]-1] == MatchSpace.SUBTOPIC_SEPARATOR_CHAR; }
java
static boolean topicSkipBackward(char[] chars, int[] cursor) { if (cursor[0] == cursor[1]) return false; while (cursor[0] < cursor[1] && chars[cursor[1]-1] != MatchSpace.SUBTOPIC_SEPARATOR_CHAR) cursor[1]--; return true; }
java
static boolean matchBackward(char[] chars, char[] pattern, int[] cursor) { int start = cursor[1] - pattern.length; if (start < cursor[0]) // candidate is too short to possibly match return false; if (!matchForward(chars, pattern, new int[] {start, cursor[1]})) return false; // The candidate matches, so reflect that in the cursor cursor[1] = start; return true; }
java
public static Object parsePattern(String pattern) { // Unfortunately, this method shares a fair amount of logic with Topic.parsePattern // but it is hard to figure out how to factor them. char[] accum = new char[pattern.length()]; int finger = 0; List tokens = new ArrayList(); boolean trivial = true; for (int i = 0; i < pattern.length(); i++) { char c = pattern.charAt(i); if (c == '*') { finger = flush(accum, finger, tokens); tokens.add(matchOne); trivial = false; } else if (c == MatchSpace.SUBTOPIC_SEPARATOR_CHAR) { // It's a normal character unless followed by another separator // or a "." if(i == pattern.length() - 1) { accum[finger++] = c; } else { // Check to see if we have a double slash if(pattern.charAt(i+1) == MatchSpace.SUBTOPIC_SEPARATOR_CHAR) { // Double slash finger = flush(accum, finger, tokens); tokens.add(matchMany); trivial = false; // Skip the second slash i++; // If the next char is a '.', then we skip that too if(pattern.charAt(i+1) == '.') { // Skip the dot i++; // Defect 307231, handle the allowable "//./" case if( (i+1) < pattern.length() && pattern.charAt(i+1) == MatchSpace.SUBTOPIC_SEPARATOR_CHAR) { // Skip a subsequent slash i++; } } } // Check for special "/." case which we jump over. Note that topic syntax // checking will already have disallowed invalid expressions such as "a/.b" // so if a "." follows a slash then it must be the final character, or it // must be followed by a separator. else if(pattern.charAt(i+1) == '.') { // skip the slash and the dot i++; } else { accum[finger++] = c; } } } else accum[finger++] = c; } if (trivial) return new String(accum, 0, finger); flush(accum, finger, tokens); return new TopicPattern(tokens.iterator()); }
java
public static StringArrayWrapper create(String[] data, String bigDestName) throws JMSException { int size = 0; if (data != null) size = data.length; List fakedFullMsgPath = new ArrayList(size+1); if (size > 0) { for (int i = 0; i < size; i++) { // Create the appropriate List element. String destName = data[i]; String busName = null; SIDestinationAddress sida; // If this is of the form dest:bus if (destName.indexOf(BUS_SEPARATOR) != -1) { busName = destName.substring(destName.indexOf(BUS_SEPARATOR)+1); destName = destName.substring(0, destName.indexOf(BUS_SEPARATOR)); } try { sida = JmsServiceFacade.getSIDestinationAddressFactory().createSIDestinationAddress(destName,busName); fakedFullMsgPath.add(sida); } catch (Exception e) { // No FFDC code needed // This makes it the responsibility of the calling function to handle this // problem. Note that the StringArrayWrapper is used only to handle forward // and reverse routing paths, which are not supported function so this // code should never be driven in normal product operation. JMSException jmse = new JMSException(e.getMessage()); jmse.setLinkedException(e); jmse.initCause(e); }//try }//for if (bigDestName != null) { // Make sure we add the real destination on the end of the msg FRP. try { SIDestinationAddress sida = ((SIDestinationAddressFactory)JmsServiceFacade.getSIDestinationAddressFactory()).createSIDestinationAddress( bigDestName, null); fakedFullMsgPath.add(sida); } catch (Exception e) { // No FFDC code needed // This makes it the responsibility of the calling function to handle this // problem. Note that the StringArrayWrapper is used only to handle forward // and reverse routing paths, which are not supported function so this // code should never be driven in normal product operation. JMSException jmse = new JMSException(e.getMessage()); jmse.setLinkedException(e); jmse.initCause(e); }//try }//if }//if size > 0 StringArrayWrapper newSAW = new StringArrayWrapper(fakedFullMsgPath); return newSAW; }
java
public String[] getArray() { // Create a copy to return to provide isolation. String[] newArray = null; // Returning a list of the destination names excluding the // 'big' destination name. newArray = new String[fullMsgPath.size()-1]; for (int i = 0; i < newArray.length; i++) { newArray[i] = ((SIDestinationAddress)fullMsgPath.get(i)).getDestinationName(); }//for return newArray; }
java
public void createDestinationLocalization( DestinationDefinition destinationDefinition, LocalizationDefinition destinationLocalizationDefinition, Set destinationLocalizingMEs, boolean isTemporary) throws SIResourceException, SIMPDestinationAlreadyExistsException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createDestinationLocalization", new Object[] { destinationDefinition, destinationLocalizationDefinition, destinationLocalizingMEs, new Boolean(isTemporary) }); destinationManager.createDestinationLocalization(destinationDefinition, destinationLocalizationDefinition, destinationLocalizingMEs, false); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createDestinationLocalization"); }
java