code
stringlengths 73
34.1k
| label
stringclasses 1
value |
|---|---|
public static final String getThreadId() {
String id = threadids.get();
if (null == id) {
// Pad the tid out to 8 characters
id = getThreadId(Thread.currentThread());
threadids.set(id);
}
return id;
}
|
java
|
public static final String padHexString(int num, int width) {
final String zeroPad = "0000000000000000";
String str = Integer.toHexString(num);
final int length = str.length();
if (length >= width)
return str;
StringBuilder buffer = new StringBuilder(zeroPad.substring(0, width));
buffer.replace(width - length, width, str);
return buffer.toString();
}
|
java
|
public static final String throwableToString(Throwable t) {
final StringWriter s = new StringWriter();
final PrintWriter p = new PrintWriter(s);
if (t == null) {
p.println("none");
} else {
printStackTrace(p, t);
}
return DataFormatHelper.escape(s.toString());
}
|
java
|
private static final boolean printFieldStackTrace(PrintWriter p, Throwable t, String className, String fieldName) {
for (Class<?> c = t.getClass(); c != Object.class; c = c.getSuperclass()) {
if (c.getName().equals(className)) {
try {
Object value = c.getField(fieldName).get(t);
if (value instanceof Throwable && value != t.getCause()) {
p.append(fieldName).append(": ");
printStackTrace(p, (Throwable) value);
}
return true;
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
}
}
return false;
}
|
java
|
private String createErrorMsg(JspLineId jspLineId, int errorLineNr) {
StringBuffer compilerOutput = new StringBuffer();
if (jspLineId.getSourceLineCount() <= 1) {
Object[] objArray = new Object[] { new Integer(jspLineId.getStartSourceLineNum()), jspLineId.getFilePath()};
if (jspLineId.getFilePath().equals(jspLineId.getParentFile())) {
compilerOutput.append(separatorString+JspCoreException.getMsg("jsp.error.single.line.number", objArray)); // Defect 211450
}
else {
compilerOutput.append(separatorString+JspCoreException.getMsg("jsp.error.single.line.number.included.file", objArray)); // Defect 211450
}
}
else {
// compute exact JSP line number
int actualLineNum=jspLineId.getStartSourceLineNum()+(errorLineNr-jspLineId.getStartGeneratedLineNum());
if (actualLineNum>=jspLineId.getStartSourceLineNum() && actualLineNum <=(jspLineId.getStartSourceLineNum() + jspLineId.getSourceLineCount() - 1)) {
Object[] objArray = new Object[] { new Integer(actualLineNum), jspLineId.getFilePath()};
if (jspLineId.getFilePath().equals(jspLineId.getParentFile())) {
compilerOutput.append(separatorString+JspCoreException.getMsg("jsp.error.single.line.number", objArray)); // Defect 211450
}
else {
compilerOutput.append(separatorString+JspCoreException.getMsg("jsp.error.single.line.number.included.file", objArray)); // Defect 211450
}
}
else {
Object[] objArray = new Object[] {
new Integer(jspLineId.getStartSourceLineNum()),
new Integer((jspLineId.getStartSourceLineNum()) + jspLineId.getSourceLineCount() - 1),
jspLineId.getFilePath()};
if (jspLineId.getFilePath().equals(jspLineId.getParentFile())) {
compilerOutput.append(separatorString+ // Defect 211450
JspCoreException.getMsg(
"jsp.error.multiple.line.number", objArray));
}
else {
compilerOutput.append(separatorString+ // Defect 211450
JspCoreException.getMsg(
"jsp.error.multiple.line.number.included.file",objArray));
}
}
}
compilerOutput.append(separatorString+JspCoreException.getMsg("jsp.error.corresponding.servlet",new Object[] { jspLineId.getParentFile()})); // Defect 211450
//152470 starts
if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable(Level.FINER)) {
logger.logp(Level.FINER, CLASS_NAME, "createErrorMsg", "The value of the JSP attribute jdkSourceLevel is ["+ jdkSourceLevel +"]");
}
//152470 ends
return compilerOutput.toString();
}
|
java
|
@SuppressWarnings("unchecked")
public static <T> T getInstanceInitParameter(ExternalContext context, String name,
String deprecatedName, T defaultValue)
{
String param = getStringInitParameter(context, name, deprecatedName);
if (param == null)
{
return defaultValue;
}
else
{
try
{
return (T) ClassUtils.classForName(param).newInstance();
}
catch (Exception e)
{
throw new FacesException("Error Initializing Object[" + param + "]", e);
}
}
}
|
java
|
public static String escapeLDAPFilterTerm(String term) {
if (term == null)
return null;
Matcher m = FILTER_CHARS_TO_ESCAPE.matcher(term);
StringBuffer sb = new StringBuffer(term.length());
while (m.find()) {
final String replacement = escapeFilterChar(m.group().charAt(0));
m.appendReplacement(sb, Matcher.quoteReplacement(replacement));
}
m.appendTail(sb);
return sb.toString();
}
|
java
|
private static Method getBindingMethod(UIComponent parent)
{
Class[] clazzes = parent.getClass().getInterfaces();
for (int i = 0; i < clazzes.length; i++)
{
Class clazz = clazzes[i];
if(clazz.getName().indexOf("BindingAware")!=-1)
{
try
{
return parent.getClass().getMethod("handleBindings",new Class[]{});
}
catch (NoSuchMethodException e)
{
// return
}
}
}
return null;
}
|
java
|
public void setObjectClasses(List<String> objectClasses) {
int size = objectClasses.size();
iObjectClasses = new ArrayList<String>(objectClasses.size());
for (int i = 0; i < size; i++) {
String objectClass = objectClasses.get(i).toLowerCase();
if (!iObjectClasses.contains(objectClass)) {
iObjectClasses.add(objectClass);
}
}
}
|
java
|
public void setObjectClassesForCreate(List<String> objectClasses) {
if (iRDNObjectClass != null && iRDNObjectClass.length > 1) {
iObjectClassAttrs = new Attribute[iRDNObjectClass.length];
for (int i = 0; i < iRDNObjectClass.length; i++) {
iObjectClassAttrs[i] = new BasicAttribute(LdapConstants.LDAP_ATTR_OBJECTCLASS, iRDNObjectClass[i][0]);
// Remove the object class for create
objectClasses.remove(iRDNObjectClass[i][0]);
}
// Add rest auxliary object classes.
for (int i = 0; i < iObjectClassAttrs.length; i++) {
for (int j = 0; j < objectClasses.size(); j++) {
iObjectClassAttrs[i].add(objectClasses.get(j));
}
}
} else {
iObjectClassAttrs = new Attribute[1];
iObjectClassAttrs[0] = new BasicAttribute(LdapConstants.LDAP_ATTR_OBJECTCLASS);
if (objectClasses.size() > 0) {
for (int i = 0; i < objectClasses.size(); i++) {
iObjectClassAttrs[0].add(objectClasses.get(i));
}
} else {
// If create object class is not define, use object classes
for (int i = 0; i < iObjectClasses.size(); i++) {
iObjectClassAttrs[0].add(iObjectClasses.get(i));
}
}
}
}
|
java
|
public void setRDNAttributes(List<Map<String, Object>> rdnAttrList) throws MissingInitPropertyException {
int size = rdnAttrList.size();
// if size = 0, No RDN attributes defined. Same as RDN properties.
if (size > 0) {
iRDNAttrs = new String[size][];
iRDNObjectClass = new String[size][];
if (size == 1) {
Map<String, Object> rdnAttr = rdnAttrList.get(0);
String[] rdns = LdapHelper.getRDNs((String) rdnAttr.get(ConfigConstants.CONFIG_PROP_NAME));
iRDNAttrs[0] = rdns;
} else {
int i = 0;
for (Map<String, Object> rdnAttr : rdnAttrList) {
String name = (String) rdnAttr.get(ConfigConstants.CONFIG_PROP_NAME);
String[] rdns = LdapHelper.getRDNs(name);
iRDNAttrs[i] = rdns;
String[] objCls = (String[]) rdnAttr.get(ConfigConstants.CONFIG_PROP_OBJECTCLASS);
if (objCls == null) {
throw new MissingInitPropertyException(WIMMessageKey.MISSING_INI_PROPERTY, Tr.formatMessage(
tc,
WIMMessageKey.MISSING_INI_PROPERTY,
WIMMessageHelper.generateMsgParms(ConfigConstants.CONFIG_PROP_OBJECTCLASS)));
} else {
iRDNObjectClass[i] = objCls;
}
i++;
}
}
}
}
|
java
|
public Attribute getObjectClassAttribute(String dn) {
if (iObjectClassAttrs.length == 1 || dn == null) {
return iObjectClassAttrs[0];
} else {
String[] rdns = LdapHelper.getRDNAttributes(dn);
for (int i = 0; i < iRDNAttrs.length; i++) {
String[] attrs = iRDNAttrs[i];
for (int j = 0; j < attrs.length; j++) {
for (int k = 0; k < attrs.length; k++) {
if (attrs[j].equals(rdns[k])) {
return iObjectClassAttrs[i];
}
}
}
}
}
return null;
}
|
java
|
public SimpleEntry next()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
{
SibTr.entry(tc, "next", this);
SibTr.exit(tc, "next", this.next);
}
return this.next;
}
|
java
|
public void remove()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "remove", this);
if(previous != null)
previous.next = next;
else
list.first = next;
if(next != null)
next.previous = previous;
else
list.last = previous;
previous = null;
next = null;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "remove", list.printList());
}
|
java
|
void rank(MetatypeOcd ocd, List<String> rankedSuffixes) {
List<String> childAliasSuffixes = new LinkedList<String>();
for (String suffix : rankedSuffixes)
if (!childAliasSuffixes.contains(suffix)) {
MetatypeOcd collision = unavailableSuffixes.put(suffix, ocd);
if (collision == null)
childAliasSuffixes.add(suffix);
else {
List<String> suffixesForCollisionOCD = rankings.get(collision);
if (suffixesForCollisionOCD != null)
suffixesForCollisionOCD.remove(suffix);
}
}
rankings.put(ocd, childAliasSuffixes);
}
|
java
|
void reserve(String suffix, MetatypeOcd ocd) {
MetatypeOcd previous = unavailableSuffixes.put(suffix, ocd);
if (previous != null)
throw new IllegalArgumentException("aliasSuffix: " + suffix);
}
|
java
|
private CapabilityMatchingResult matchCapability(Collection<? extends ProvisioningFeatureDefinition> features) {
String capabilityString = esaResource.getProvisionCapability();
if (capabilityString == null) {
CapabilityMatchingResult result = new CapabilityMatchingResult();
result.capabilitySatisfied = true;
result.features = Collections.emptyList();
return result;
}
CapabilityMatchingResult result = new CapabilityMatchingResult();
result.capabilitySatisfied = true;
result.features = new ArrayList<>();
List<FeatureCapabilityInfo> capabilityMaps = createCapabilityMaps(features);
for (Filter filter : createFilterList()) {
boolean matched = false;
for (FeatureCapabilityInfo capabilityInfo : capabilityMaps) {
if (filter.matches(capabilityInfo.capabilities)) {
matched = true;
result.features.add(capabilityInfo.feature);
break;
}
}
// If any of the filters in the provision capability header don't match, we're not satisfied
if (!matched) {
result.capabilitySatisfied = false;
}
}
return result;
}
|
java
|
public String getAssetURL(String id) {
String url = getRepositoryUrl() + "/assets/" + id + "?";
if (getUserId() != null) {
url += "userId=" + getUserId();
}
if (getUserId() != null && getPassword() != null) {
url += "&password=" + getPassword();
}
if (getApiKey() != null) {
url += "&apiKey=" + getApiKey();
}
return url;
}
|
java
|
public String getTaskUsage(ExeAction task) {
StringBuilder taskUsage = new StringBuilder(NL);
// print a empty line
taskUsage.append(getHelpPart("global.usage"));
taskUsage.append(NL);
taskUsage.append('\t');
taskUsage.append(COMMAND);
taskUsage.append(' ');
taskUsage.append(task);
taskUsage.append(" [");
taskUsage.append(getHelpPart("global.options.lower"));
taskUsage.append("]");
List<String> options = task.getCommandOptions();
for (String option : options) {
if (option.charAt(0) != '-') {
taskUsage.append(' ');
taskUsage.append(option);
}
}
taskUsage.append(NL);
taskUsage.append(NL);
taskUsage.append(getHelpPart("global.description"));
taskUsage.append(NL);
taskUsage.append(getDescription(task));
taskUsage.append(NL);
if (options.size() > 0) {
taskUsage.append(NL);
taskUsage.append(getHelpPart("global.options"));
for (String option : task.getCommandOptions()) {
taskUsage.append(NL);
String optionKey;
try {
optionKey = getHelpPart(task + ".option-key." + option);
} catch (MissingResourceException e) {
// This happens because we don't have a message for the key for the
// license arguments but these are not translated and don't need any
// arguments after them so can just use the option
optionKey = " " + option;
}
taskUsage.append(optionKey);
taskUsage.append(NL);
taskUsage.append(getHelpPart(task + ".option-desc." + option));
taskUsage.append(NL);
}
}
taskUsage.append(NL);
return taskUsage.toString();
}
|
java
|
private int getQueueIndex(Object[] queue, java.util.concurrent.atomic.AtomicInteger counter, boolean increment) {
// fast path for single element array
if (queue.length == 1) {
return 0;
} else if (increment) {
// get the next long value from counter
int i = counter.incrementAndGet();
// rollover logic to make sure we stay within
// the bounds of an integer. Not important that
// this logic is highly accurate, ballpark is okay.
if (i > MAX_COUNTER) {
if (counter.compareAndSet(i, 0)) {
System.out.println("BoundedBuffer: reset counter to 0");
}
}
return i % queue.length;
} else {
return counter.get() % queue.length;
}
}
|
java
|
public void put(Object x) throws InterruptedException {
if (x == null) {
throw new IllegalArgumentException();
}
// D186845 if (Thread.interrupted())
// D186845 throw new InterruptedException();
// D312598 - begin
boolean ret = false;
while (true) {
synchronized (lock) {
if (numberOfUsedSlots.get() < buffer.length) {
insert(x);
numberOfUsedSlots.getAndIncrement();
ret = true;
}
}
if (ret) {
notifyGet_();
return;
}
int spinctr = SPINS_PUT_;
while (numberOfUsedSlots.get() >= buffer.length) {
// busy wait
if (spinctr > 0) {
if (YIELD_PUT_)
Thread.yield();
spinctr--;
} else {
// block on lock
waitPut_(WAIT_SHORT_SLICE_);
}
}
}
// D312598 - end
}
|
java
|
@Override
public void setTarget(String target) {
if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) {
SibTr.debug(this, TRACE, "setTarget", target);
}
_target = target;
}
|
java
|
@Override
public void setTargetType(String targetType) {
if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) {
SibTr.debug(this, TRACE, "setTargetType", targetType);
}
_targetType = targetType;
}
|
java
|
@Override
public void setMaxSequentialMessageFailure(final String maxSequentialMessageFailure)
{
_maxSequentialMessageFailure = (maxSequentialMessageFailure == null ? null : Integer.valueOf(maxSequentialMessageFailure));
}
|
java
|
@Override
public void setAutoStopSequentialMessageFailure(final String autoStopSequentialMessageFailure)
{
_autoStopSequentialMessageFailure = (autoStopSequentialMessageFailure == null ? null : Integer.valueOf(autoStopSequentialMessageFailure));
}
|
java
|
public static UOWScopeCallback createUserTransactionCallback() {
if (tc.isEntryEnabled())
Tr.entry(tc, "createUserTransactionCallback");
if (userTranCallback == null) {
userTranCallback = new LTCUOWCallback(UOW_TYPE_TRANSACTION);
}
if (tc.isEntryEnabled())
Tr.exit(tc, "createUserTransactionCallback", userTranCallback);
return userTranCallback;
}
|
java
|
public static X509Name getInstance(
ASN1TaggedObject obj,
boolean explicit)
{
return getInstance(ASN1Sequence.getInstance(obj, explicit));
}
|
java
|
public Vector getOIDs()
{
Vector v = new Vector();
for (int i = 0; i != ordering.size(); i++)
{
v.addElement(ordering.elementAt(i));
}
return v;
}
|
java
|
public Vector getValues()
{
Vector v = new Vector();
for (int i = 0; i != values.size(); i++)
{
v.addElement(values.elementAt(i));
}
return v;
}
|
java
|
public static ConfigID fromProperty(String property) {
//TODO Perhaps there is a clever regex that could handle this
String[] parents = property.split("//");
ConfigID id = null;
for (String parentString : parents) {
id = constructId(id, parentString);
}
return id;
}
|
java
|
@Override
public Conversation connect(InetSocketAddress remoteHost,
ConversationReceiveListener arl,
String chainName)
throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "connect", new Object[] { remoteHost, arl, chainName });
if (initialisationFailed)
{
String nlsMsg = nls.getFormattedMessage("EXCP_CONN_FAIL_NO_CF_SICJ0007", null, null);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(this, tc, "connection failed because comms failed to initialise");
throw new SIResourceException(nlsMsg);
}
Conversation conversation = tracker.connect(remoteHost, arl, chainName, Conversation.CLIENT);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(this, tc, "connect", conversation);
return conversation;
}
|
java
|
public static void initialise() throws SIErrorException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "initialise");
initialisationFailed = true;
Framework framework = Framework.getInstance();
if (framework != null)
{
tracker = new OutboundConnectionTracker(framework);
initialisationFailed = false;
}
else
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "initialisation failed");
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "initialise");
}
|
java
|
private void destroy() {
final boolean bTrace = TraceComponent.isAnyTracingEnabled();
if (bTrace && tc.isEventEnabled()) {
Tr.event(tc, "Session being destroyed; " + this);
}
// List<HttpSessionListener> list = this.myConfig.getSessionListeners();
// if (null != list) {
// HttpSessionEvent event = new HttpSessionEvent(this);
// for (HttpSessionListener listener : list) {
// if (bTrace && tc.isDebugEnabled()) {
// Tr.debug(tc, "Notifying listener of destroy; " + listener);
// }
// listener.sessionDestroyed(event);
// }
// }
for (String key : this.attributes.keySet()) {
Object value = this.attributes.get(key);
HttpSessionBindingEvent event = new HttpSessionBindingEvent(this, key);
if (value instanceof HttpSessionBindingListener) {
if (bTrace && tc.isDebugEnabled()) {
Tr.debug(tc, "Notifying attribute of removal: " + value);
}
((HttpSessionBindingListener) value).valueUnbound(event);
}
}
this.attributes.clear();
this.myContext = null;
}
|
java
|
private void cleanup() {
final String methodName = "cleanup(): ";
try {
final Bundle b = bundle.getAndSet(null);
if (b != null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, methodName + "Uninstalling bundle location: " + b.getLocation() + ", bundle id: " + b.getBundleId());
}
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
try {
b.uninstall();
return null;
} catch (BundleException ignored) {
return null;
}
}
});
} else {
b.uninstall();
}
}
} catch (BundleException ignored) {
} catch (IllegalStateException ignored) {
}
}
|
java
|
int decrementRefCount() {
final String methodName = "decrementRefCount(): ";
final int count = refCount.decrementAndGet();
if (count < 0) {
// more destroys than creates
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, methodName + " refCount < 0 - too many calls to destroy/cleaup", new Throwable("stack trace"));
}
}
if (count == 0) {
cleanup();
}
return count;
}
|
java
|
private static PersistenceContext newPersistenceContext(final String fJndiName, final String fUnitName, final int fCtxType,
final List<Property> fCtxProperties) {
return new PersistenceContext() {
@Override
public Class<? extends Annotation> annotationType() {
return PersistenceContext.class;
}
@Override
public String name() {
return fJndiName;
}
@Override
public PersistenceProperty[] properties() {
//TODO not ideal doing this conversion processing here
PersistenceProperty[] props = new PersistenceProperty[fCtxProperties.size()];
int i = 0;
for (Property property : fCtxProperties) {
final String name = property.getName();
final String value = property.getValue();
PersistenceProperty prop = new PersistenceProperty() {
@Override
public Class<? extends Annotation> annotationType() {
return PersistenceProperty.class;
}
@Override
public String name() {
return name;
}
@Override
public String value() {
return value;
}
};
props[i++] = prop;
}
return props;
}
@Override
public PersistenceContextType type() {
if (fCtxType == PersistenceContextRef.TYPE_TRANSACTION) {
return PersistenceContextType.TRANSACTION;
} else {
return PersistenceContextType.EXTENDED;
}
}
@Override
public String unitName() {
return fUnitName;
}
@Override
public String toString() {
return "JPA.PersistenceContext(name=" + fJndiName +
", unitName=" + fUnitName + ")";
}
};
}
|
java
|
private void processConnectionInfo(CommsByteBuffer buffer, Conversation conversation)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "processConnectionInfo",
new Object[]{buffer, conversation});
ClientConversationState convState = (ClientConversationState) conversation.getAttachment();
short connectionObjectId = buffer.getShort(); // BIT16 ConnectionObjectID
String meName = buffer.getString(); // STR MEName
// Set the connection object ID in the conversation state
convState.setConnectionObjectID(connectionObjectId);
// Create the connection proxy and save it away in the conversation state
final ConnectionProxy connectionProxy;
// The type of connection proxy we create is dependent on FAP version. Fap version 5 supports
// a connection which MSSIXAResourceProvider. This is done so that PEV (introduced in line with
// FAP 5) can perform remote recovery of resources.
if (conversation.getHandshakeProperties().getFapLevel() >= JFapChannelConstants.FAP_VERSION_5)
{
connectionProxy = new MSSIXAResourceProvidingConnectionProxy(conversation);
}
else
{
connectionProxy = new ConnectionProxy(conversation);
}
convState.setSICoreConnection(connectionProxy);
// Set in the ME name
connectionProxy.setMeName(meName);
// Now get the unique Id if there was one, and set it in the connection proxy
short idLength = buffer.getShort();
if (idLength != 0)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Got unique id of length:", idLength);
byte[] uniqueId = buffer.get(idLength);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.bytes(tc, uniqueId);
connectionProxy.setInitialUniqueId(uniqueId);
}
else
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "No unique Id was returned");
}
// Get the ME Uuid
String meUuid = buffer.getString();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "ME Uuid: ", meUuid);
connectionProxy.setMeUuid(meUuid);
// Get the resolved User Id
String resolvedUserId = buffer.getString();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Resolved UserId: ", resolvedUserId);
connectionProxy.setResolvedUserId(resolvedUserId);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "processConnectionInfo");
}
|
java
|
private void processSchema(CommsByteBuffer buffer, Conversation conversation)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "processSchema",
new Object[]
{
buffer,
conversation
});
ClientConversationState convState = (ClientConversationState) conversation.getAttachment();
byte[] mfpDataAsBytes = buffer.getRemaining();
// Get hold of the CommsConnection associated with this conversation
CommsConnection cc = convState.getCommsConnection();
// Get hold of MFP Singleton and pass it the schema
try
{
// Get hold of product version
final HandshakeProperties handshakeGroup = conversation.getHandshakeProperties();
final int productVersion = handshakeGroup.getMajorVersion();
// Get hold of MFP and inform it of the schema
CompHandshake ch = (CompHandshake) CompHandshakeFactory.getInstance();
ch.compData(cc,productVersion,mfpDataAsBytes);
}
catch (Exception e1)
{
FFDCFilter.processException(e1, CLASS_NAME + ".processSchema",
CommsConstants.PROXYRECEIVELISTENER_PROCESSSCHEMA_01, this);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "MFP unable to create CompHandshake Singleton", e1);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "processSchema");
}
|
java
|
private void processSyncMessageChunk(CommsByteBuffer buffer, Conversation conversation,
boolean connectionMessage)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "processSyncMessageChunk",
new Object[]{buffer, conversation, connectionMessage});
// First get the ConnectionProxy for this conversation
ClientConversationState convState = (ClientConversationState) conversation.getAttachment();
ConnectionProxy connProxy = (ConnectionProxy) convState.getSICoreConnection();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Found connection: ", connProxy);
// Now read the connection object Id
buffer.getShort(); // BIT16 ConnectionObjId
if (connectionMessage)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Adding message part directly to connection");
connProxy.addMessagePart(buffer);
}
else
{
short consumerSessionId = buffer.getShort(); // BIT16 ConsumerSessionId
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Consumer Session Id:", ""+consumerSessionId);
// Now simply pass the message buffer off to the consumer
ConsumerSessionProxy consumer = connProxy.getConsumerSessionProxy(consumerSessionId);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Found consumer:", consumer);
consumer.addMessagePart(buffer);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "processSyncMessageChunk");
}
|
java
|
public BeanO getBean(ContainerTx tx, BeanId id)
{
return id.getActivationStrategy().atGet(tx, id);
}
|
java
|
public void commitBean(ContainerTx tx, BeanO bean)
{
bean.getActivationStrategy().atCommit(tx, bean);
}
|
java
|
public void unitOfWorkEnd(ContainerAS as, BeanO bean)
{
bean.getActivationStrategy().atUnitOfWorkEnd(as, bean);
}
|
java
|
public void rollbackBean(ContainerTx tx, BeanO bean)
{
bean.getActivationStrategy().atRollback(tx, bean);
}
|
java
|
public final void enlistBean(ContainerTx tx, BeanO bean)
{
bean.getActivationStrategy().atEnlist(tx, bean);
}
|
java
|
public void terminate()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "terminate");
statefulBeanReaper.cancel(); //d601399
// Force a reaper sweep
statefulBeanReaper.finalSweep(passivator);
beanCache.terminate();
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "terminate");
}
|
java
|
public void uninstallBean(J2EEName homeName)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "uninstallBean " + homeName);
BeanO cacheMember;
J2EEName cacheHomeName;
Iterator<?> statefulBeans; // d103404.1
int numEnumerated = 0, numRemoved = 0, numTimedout = 0; // d103404.2
// Enumerate through the bean cache, removing all instances
// associated with the specified home.
Enumeration<?> enumerate = beanCache.enumerateElements();
while (enumerate.hasMoreElements())
{
cacheMember = (BeanO) ((CacheElement)
enumerate.nextElement()).getObject();
BeanId cacheMemberBeanId = cacheMember.getId();
cacheHomeName = cacheMemberBeanId.getJ2EEName();
numEnumerated++;
// If the cache has homeObj as it's home, remove it.
// If the bean has been removed since it was found (above),
// then the call to atUninstall() will just no-op.
// Note that the enumeration can handle elements being removed
// from the cache while enumerating. d103404.2
if (cacheHomeName.equals(homeName))
{
HomeInternal home = cacheMember.getHome();
// On z/OS, the application might be stopping in a single SR
// only. We can't tell, so assume the SFSB needs to remain
// available for the application running in another SR, and
// passivate the SFSB rather than uninstalling it. LIDB2775-23.4
BeanMetaData bmd = cacheMemberBeanId.getBeanMetaData();
if (EJSPlatformHelper.isZOS() && bmd.isPassivationCapable()) {
try {
home.getActivationStrategy().atPassivate(cacheMemberBeanId);
} catch (Exception ex) {
Tr.warning(tc, "UNABLE_TO_PASSIVATE_EJB_CNTR0005W",
new Object[] { cacheMemberBeanId, this, ex });
}
} else {
home.getActivationStrategy().atUninstall(cacheMemberBeanId,
cacheMember);
}
numRemoved++;
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { // d103404.1 d103404.2
Tr.debug(tc, beanCache.getName() + ": Uninstalled " + numRemoved +
" bean instances (total = " + numEnumerated + ")");
}
// Also, uninstall all passivated Stateful Session beans for the
// specified home, regardless of whether they have timed out or not.
// All of the beans for this home in the StatefulBeanReaper should
// be in the passivated state (i.e. state written to a file), as the
// above loop should have cleared all active ones from the EJB Cache.
// Calling atUninstall on them will delete the file and remove them
// from the reaper. d103404.1
statefulBeans = statefulBeanReaper.getPassivatedStatefulBeanIds(homeName);
while (statefulBeans.hasNext())
{
// Call atUninstall just like for those in the cache... atUninstall
// will handle them not being in the cache and remove the file.
// Note that atTimeout cannot be used, as the beans (though passivated)
// may not be timed out, and atTimeout would skip them. d129562
BeanId beanId = (BeanId) statefulBeans.next();
// LIDB2775-23.4 Begins
if (EJSPlatformHelper.isZOS())
{
statefulBeanReaper.remove(beanId);
} else
// LIDB2775-23.4 Ends
{
beanId.getActivationStrategy().atUninstall(beanId, null);
}
numTimedout++;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { // d103404.2
Tr.debug(tc, "Passivated Beans: Uninstalled " + numTimedout +
" bean instances");
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "uninstallBean");
}
|
java
|
synchronized long calculateNextExpiration()
{
boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "calculateNextExpiration: " + this);
ivLastExpiration = ivExpiration; // 598265
if (ivParsedScheduleExpression != null) {
// F7437591.codRev - getNextTimeout returns -1 for "no more timeouts",
// but this class uses ivExpiration=0.
ivExpiration = Math.max(0, ivParsedScheduleExpression.getNextTimeout(ivExpiration));
}
else {
if (ivInterval > 0) {
ivExpiration += ivInterval; // 597753
}
else {
ivExpiration = 0;
}
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "calculateNextExpiration: " + ivExpiration); // 597753
return ivExpiration;
}
|
java
|
public static void removeTimersByJ2EEName(J2EEName j2eeName)
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "removeTimersByJ2EEName: " + j2eeName);
Collection<TimerNpImpl> timersToRemove = null;
// Although this seems inefficient, removing all of the timers for an
// application or module that is stopping is done in two steps to avoid
// obtaining locks on both the active timers map and any individual
// timer concurrently. Many methods on a timer will also need to obtain
// the lock on the active timers map as well, so the two step approach
// avoids the possibility of deadlock. RTC107334
synchronized (svActiveTimers)
{
if (svActiveTimers.size() > 0)
{
String appToRemove = j2eeName.getApplication();
String modToRemove = j2eeName.getModule();
for (TimerNpImpl timer : svActiveTimers.values())
{
J2EEName timerJ2EEName = timer.ivBeanId.j2eeName;
if (appToRemove.equals(timerJ2EEName.getApplication()) &&
(modToRemove == null || modToRemove.equals(timerJ2EEName.getModule())))
{
// save the timer to be removed outside the active timers map lock
if (timersToRemove == null)
{
timersToRemove = new ArrayList<TimerNpImpl>();
}
timersToRemove.add(timer);
}
}
}
}
if (timersToRemove != null)
{
for (TimerNpImpl timer : timersToRemove)
{
timer.remove(true); // permanently remove the timer; cannot be rolled back
}
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "removeTimersByJ2EEName: removed " + (timersToRemove != null ? timersToRemove.size() : 0));
}
|
java
|
public void statisticCreated (SPIStatistic s)
{
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE))
logger.logp(Level.FINE, CLASS_NAME,"statisticCreated","Servlet statistic created with id="+s.getId());
if (s.getId() == LOADED_SERVLETS)
{
sgLoadedServlets = (SPICountStatistic)s;
}
else
if (s.getId() == NUM_RELOADS)
{
sgNumReloads = (SPICountStatistic)s;
}
}
|
java
|
public EJBModuleMetaDataImpl createEJBModuleMetaDataImpl(EJBApplicationMetaData ejbAMD, // F743-4950
ModuleInitData mid,
SfFailoverCache statefulFailoverCache,
EJSContainer container) {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "createEJBModuleMetaDataImpl");
EJBJar ejbJar = mid.ivEJBJar;
EJBModuleMetaDataImpl mmd = mid.createModuleMetaData(ejbAMD);
mmd.ivInitData = mid;
mmd.ivMetadataComplete = mid.ivMetadataComplete;
mmd.ivJ2EEName = mid.ivJ2EEName;
mmd.ivName = mid.ivName;
mmd.ivAppName = mid.ivAppName;
mmd.ivLogicalName = mid.ivLogicalName;
mmd.ivApplicationExceptionMap = createApplicationExceptionMap(ejbJar);
mmd.ivModuleVersion = ejbJar == null ? BeanMetaData.J2EE_EJB_VERSION_3_0 : ejbJar.getVersionID();
// Determine if the SetRollbackOnly behavior should be as it was in 2.x
// modules (where SetRollbackOnly would need to be invoked within the
// actual EJB instance), or use the 3.x behavior (where
// SetRollbackOnly can be invoke within and ejb instance that is itself
// invoked from within the ejb instance that began the transaction).
// For EJB 3.x applications, the LimitSetRollbackOnlyBehaviorToInstanceFor property
// is usd to indicate that the 2.x behavior should be used.
// Likewise, 2.x applications can use the ExtendSetRollbackOnlyBehaviorBeyondInstanceFor
// property to get the 3.x behavior.
// d461917.1
if (mmd.ivModuleVersion >= BeanMetaData.J2EE_EJB_VERSION_3_0) {
if ((LimitSetRollbackOnlyBehaviorToInstanceFor == null) ||
(!LimitSetRollbackOnlyBehaviorToInstanceFor.contains(mmd.ivAppName))) {
mmd.ivUseExtendedSetRollbackOnlyBehavior = true;
}
} else { // not a 3.0 module
if ((ExtendSetRollbackOnlyBehaviorBeyondInstanceFor != null) &&
(ExtendSetRollbackOnlyBehaviorBeyondInstanceFor.contains("*") ||
ExtendSetRollbackOnlyBehaviorBeyondInstanceFor.contains(mmd.ivAppName))) {
mmd.ivUseExtendedSetRollbackOnlyBehavior = true;
}
}
// Get the failover instance ID and SFSB Failover value to use for this module if
// a SfFailoverCache object was created.
if (statefulFailoverCache != null) {
mmd.ivSfsbFailover = getSFSBFailover(mmd, container);
mmd.ivFailoverInstanceId = getFailoverInstanceId(mmd, statefulFailoverCache);
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "createEJBModuleMetaDataImpl: " + mmd);
return mmd;
}
|
java
|
public void processDeferredBMD(BeanMetaData bmd) throws EJBConfigurationException, ContainerException {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "processDeferredBMD: " + bmd.j2eeName);
// F743-506 - Process automatic timers. This always needs to be
// done regardless of deferred EJB initialization.
if (bmd.ivInitData.ivTimerMethods == null) {
processAutomaticTimerMetaData(bmd);
}
// d659020 - Clear references that aren't needed for deferred init.
bmd.ivInitData.unload();
bmd.wccm.unload();
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "processDeferredBMD");
}
|
java
|
private void initializeLifecycleInterceptorMethodMD(Method[] ejbMethods,
List<ContainerTransaction> transactionList,
List<ActivitySessionMethod> activitySessionList,
BeanMetaData bmd) throws EJBConfigurationException {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "initializeLifecycleInterceptorMethodMD", (Object[]) ejbMethods);
final int numMethods = LifecycleInterceptorWrapper.NUM_METHODS;
String[] methodNames = new String[numMethods];
Class<?>[][] methodParamTypes = new Class<?>[numMethods][];
String[] methodSignatures = new String[numMethods];
TransactionAttribute[] transactionAttrs = new TransactionAttribute[numMethods];
ActivitySessionAttribute[] activitySessionAttrs = new ActivitySessionAttribute[numMethods];
for (int i = 0; i < numMethods; i++) {
if (ejbMethods[i] == null) {
methodNames[i] = LifecycleInterceptorWrapper.METHOD_NAMES[i];
methodParamTypes[i] = LifecycleInterceptorWrapper.METHOD_PARAM_TYPES[i];
methodSignatures[i] = LifecycleInterceptorWrapper.METHOD_SIGNATURES[i];
// The spec states that in order to specify a transaction attribute
// for lifecycle interceptor methods, the method must be declared
// on the bean class. Afterwards, it states that if a transaction
// attribute is not specified, then it must be REQUIRED. This
// implies that if the bean class specifies a class-level
// transaction attribute of NOT_SUPPORT but does not specify a
// lifecycle interceptor method, we still use REQUIRED for the
// other lifecycle interceptors.
//
// By specifying the default transaction attribute here, we avoid
// NPE in getAnnotationCMTransactions by using null ejbMethods[i].
transactionAttrs[i] = bmd.type == InternalConstants.TYPE_STATEFUL_SESSION ? TransactionAttribute.TX_NOT_SUPPORTED : TransactionAttribute.TX_REQUIRED;
} else {
methodNames[i] = ejbMethods[i].getName();
methodParamTypes[i] = ejbMethods[i].getParameterTypes();
methodSignatures[i] = MethodAttribUtils.methodSignatureOnly(ejbMethods[i]);
}
}
initializeBeanMethodTransactionAttributes(false,
false,
MethodInterface.LIFECYCLE_INTERCEPTOR,
ejbMethods,
null,
null,
transactionList,
activitySessionList,
methodNames,
methodParamTypes,
methodSignatures,
transactionAttrs,
activitySessionAttrs,
bmd);
EJBMethodInfoImpl[] methodInfos = new EJBMethodInfoImpl[numMethods];
int slotSize = bmd.container.getEJBRuntime().getMetaDataSlotSize(MethodMetaData.class);
for (int i = 0; i < numMethods; i++) {
String methodSig = ejbMethods[i] == null ? methodNames[i] + MethodAttribUtils.METHOD_ARGLIST_SEP
+ methodSignatures[i] : MethodAttribUtils.methodSignature(ejbMethods[i]);
String jdiMethodSig = ejbMethods[i] == null ? LifecycleInterceptorWrapper.METHOD_JDI_SIGNATURES[i] : MethodAttribUtils.jdiMethodSignature(ejbMethods[i]);
EJBMethodInfoImpl methodInfo = bmd.createEJBMethodInfoImpl(slotSize);
methodInfo.initializeInstanceData(methodSig, methodNames[i], bmd, MethodInterface.LIFECYCLE_INTERCEPTOR, transactionAttrs[i], false);
methodInfo.setMethodDescriptor(jdiMethodSig);
methodInfo.setActivitySessionAttribute(activitySessionAttrs[i]);
methodInfos[i] = methodInfo;
}
bmd.lifecycleInterceptorMethodInfos = methodInfos;
bmd.lifecycleInterceptorMethodNames = methodNames;
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "initializeLifecycleInterceptorMethodMD");
}
|
java
|
@SuppressWarnings("deprecation")
protected Throwable getNestedException(Throwable t) {
Throwable root = t;
for (;;) {
if (root instanceof RemoteException) {
RemoteException re = (RemoteException) root;
if (re.detail == null)
break;
root = re.detail;
} else if (root instanceof NamingException) {
NamingException ne = (NamingException) root;
if (ne.getRootCause() == null)
break;
root = ne.getRootCause();
} else if (root instanceof com.ibm.ws.exception.WsNestedException) { //d121522
com.ibm.ws.exception.WsNestedException ne = (com.ibm.ws.exception.WsNestedException) root;
if (ne.getCause() == null)
break;
root = ne.getCause();
} else {
break;
}
}
return root;
}
|
java
|
private void processSingletonConcurrencyManagementType(BeanMetaData bmd) throws EJBConfigurationException {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled()) {
Tr.entry(tc, "processSingletonConcurrencyManagementType");
}
// Initialize DD Concurrency Management type to null and change to
// non null value if it is specified in the DD for the module.
ConcurrencyManagementType ddType = null;
// F743-7027 start
Session sessionBean = (Session) bmd.wccm.enterpriseBean;
if (sessionBean != null) {
int type = sessionBean.getConcurrencyManagementTypeValue();
if (type == Session.CONCURRENCY_MANAGEMENT_TYPE_CONTAINER) {
ddType = ConcurrencyManagementType.CONTAINER;
} else if (type == Session.CONCURRENCY_MANAGEMENT_TYPE_BEAN) {
ddType = ConcurrencyManagementType.BEAN;
}
} // F743-7027 end
// Initialize annotation Concurrency Management type to null and change to
// non null value only if metadata complete is false and annotation is used
// for this Singleton session bean.
ConcurrencyManagementType annotationType = null;
if (bmd.metadataComplete == false) {
// Metadata complete is false, so do we have annotation value?
// Note, EJB spec says annotation can not be inherited from superclass.
Class<?> ejbClass = bmd.enterpriseBeanClass;
ConcurrencyManagement annotation = ejbClass.getAnnotation(javax.ejb.ConcurrencyManagement.class);
if (annotation != null) {
// We have an annotation on EJB class, so validate that it is a valid value.
annotationType = annotation.value();
if (annotationType != ConcurrencyManagementType.CONTAINER && annotationType != ConcurrencyManagementType.BEAN) {
// CNTR0193E: The value, {0}, that is specified for the concurrency management type of
// the {1} enterprise bean class must be either BEAN or CONTAINER.
Tr.error(tc, "SINGLETON_INVALID_CONCURRENCY_MANAGEMENT_CNTR0193E", new Object[] { annotationType, bmd.enterpriseBeanClassName });
throw new EJBConfigurationException("CNTR0193E: The value, " + annotationType
+ ", that is specified for the concurrency management type of the "
+ bmd.enterpriseBeanClassName + " enterprise bean class must be either BEAN or CONTAINER.");
}
}
}
// Assign concurrency management type for this Singleton seesion bean.
// Note, in "4.8.4.3 Specification of a Concurrency Management Type" of EJB 3.1 specification,
// it says "The application assembler is not permitted to use the deployment
// descriptor to override a bean's concurrency management type regardless of whether
// it has been explicitly specified or defaulted by the Bean Provider." However,
// we have no way to know whether DD is from application assembler vs Bean Provider,
// so we have to assume it came from Bean Provider. The team decided that if both
// annotation and DD is used, then the value must match. If they do not match,
// throw an exception.
// Was a value provided via DD?
if (ddType == null) {
// DD did not provide a value, so use annotation value if one was provided.
// Otherwise, use default value required by EJB 3.1 spec.
if (annotationType != null) {
// No DD, but we have annotation. So use the annotation.
bmd.ivSingletonUsesBeanManagedConcurrency = (annotationType == ConcurrencyManagementType.BEAN);
} else {
// Neither DD nor annotation, so default to Container Concurrency Management type.
bmd.ivSingletonUsesBeanManagedConcurrency = false;
}
} else {
// DD did provide a concurrency management type. Verify it matches annotation type
// if both annotation and DD provided a value.
if (annotationType != null && ddType != annotationType) {
// CNTR0194E: The value {0} that is specified in the ejb-jar.xml file for concurrency management type is
// not the same as the @ConcurrencyManagement annotation value {1} on the {2} enterprise bean class.
Tr.error(tc, "SINGLETON_XML_OVERRIDE_CONCURRENCY_MANAGEMENT_CNTR0194E", new Object[] { ddType, annotationType, bmd.enterpriseBeanClassName });
throw new EJBConfigurationException("CNTR0194E: The value " + ddType
+ " that is specified in the ejb-jar.xml file for concurrency management type is not the same "
+ " as the @ConcurrencyManagement annotation value " + annotationType + " on the "
+ bmd.enterpriseBeanClassName + " enterprise bean class.");
}
// Use DD value since either annotation not used or DD matches the annotation type.
bmd.ivSingletonUsesBeanManagedConcurrency = (ddType == ConcurrencyManagementType.BEAN);
}
if (isTraceOn && tc.isEntryEnabled()) {
Tr.exit(tc, "processSingletonConcurrencyManagementType returning "
+ bmd.ivSingletonUsesBeanManagedConcurrency + " for j2ee name = " + bmd.j2eeName);
}
}
|
java
|
private void initializeManagedObjectFactoryOrConstructor(BeanMetaData bmd) throws EJBConfigurationException {
if (bmd.isManagedBean()) {
bmd.ivEnterpriseBeanFactory = getManagedBeanManagedObjectFactory(bmd, bmd.enterpriseBeanClass);
// If the managed object factroy and the managed object instances will perform all injection
// and interceptor processing, then save that indication and reset all of the methodinfos so
// that AroundInvoke is not handled by the EJB Container. Injection, PostConstruct, and
// PreDestroy will also be skipped.
if (bmd.ivEnterpriseBeanFactory != null && bmd.ivEnterpriseBeanFactory.managesInjectionAndInterceptors()) {
bmd.managedObjectManagesInjectionAndInterceptors = true;
if (bmd.ivInterceptorMetaData != null && bmd.localMethodInfos != null) {
for (EJBMethodInfoImpl mbMethod : bmd.localMethodInfos) {
mbMethod.setAroundInterceptorProxies(null);
}
}
}
} else {
bmd.ivEnterpriseBeanFactory = getEJBManagedObjectFactory(bmd, bmd.enterpriseBeanClass);
}
if (bmd.ivEnterpriseBeanFactory == null) {
try {
bmd.ivEnterpriseBeanClassConstructor = bmd.enterpriseBeanClass.getConstructor((Class<?>[]) null);
} catch (NoSuchMethodException e) {
Tr.error(tc, "JIT_NO_DEFAULT_CTOR_CNTR5007E",
new Object[] { bmd.enterpriseBeanClassName, bmd.enterpriseBeanName });
throw new EJBConfigurationException("CNTR5007E: The " + bmd.enterpriseBeanClassName + " bean class for the " + bmd.enterpriseBeanName +
" bean does not have a public constructor that does not take parameters.");
}
}
// Removed else clause that calls bmd.ivEnterpriseBeanFactory.getConstructor() because this method
// is called before cdiMMD.setWebBeansContext(webBeansContext) in LibertySingletonServer. If we call
// getConstructor before setting the webBeansContext, we default to a constructor that may not be correct.
// eg. returning no-arg constructor when multi-arg constructor injection should be invoked.
}
|
java
|
private void initializeEntityConstructor(BeanMetaData bmd) throws EJBConfigurationException {
try {
bmd.ivEnterpriseBeanClassConstructor = bmd.enterpriseBeanClass.getConstructor((Class<?>[]) null);
} catch (NoSuchMethodException e) {
Tr.error(tc, "JIT_NO_DEFAULT_CTOR_CNTR5007E",
new Object[] { bmd.enterpriseBeanClassName, bmd.enterpriseBeanName });
throw new EJBConfigurationException("CNTR5007E: The " + bmd.enterpriseBeanClassName + " bean class for the " + bmd.enterpriseBeanName +
" bean does not have a public constructor that does not take parameters.");
}
}
|
java
|
protected <T> ManagedObjectFactory<T> getManagedBeanManagedObjectFactory(BeanMetaData bmd, Class<T> klass) throws EJBConfigurationException {
ManagedObjectFactory<T> factory = null;
ManagedObjectService managedObjectService = getManagedObjectService();
if (managedObjectService != null) {
try {
factory = managedObjectService.createManagedObjectFactory(bmd._moduleMetaData, klass, true);
//TODO the isManaged method could be moved to the ManagedObjectService and then wouldn't need to create the factory
if (!factory.isManaged()) {
factory = null;
}
} catch (ManagedObjectException e) {
throw new EJBConfigurationException(e);
}
}
return factory;
}
|
java
|
protected <T> ManagedObjectFactory<T> getInterceptorManagedObjectFactory(BeanMetaData bmd, Class<T> klass) throws EJBConfigurationException {
ManagedObjectFactory<T> factory = null;
ManagedObjectService managedObjectService = getManagedObjectService();
if (managedObjectService != null) {
try {
factory = managedObjectService.createInterceptorManagedObjectFactory(bmd._moduleMetaData, klass);
//TODO the isManaged method could be moved to the ManagedObjectService and then wouldn't need to create the factory
if (!factory.isManaged()) {
factory = null;
}
} catch (ManagedObjectException e) {
throw new EJBConfigurationException(e);
}
}
return factory;
}
|
java
|
protected <T> ManagedObjectFactory<T> getEJBManagedObjectFactory(BeanMetaData bmd, Class<T> klass) throws EJBConfigurationException {
ManagedObjectFactory<T> factory = null;
ManagedObjectService managedObjectService = getManagedObjectService();
if (managedObjectService != null) {
try {
factory = managedObjectService.createEJBManagedObjectFactory(bmd._moduleMetaData, klass, bmd.j2eeName.getComponent());
//TODO the isManaged method could be moved to the ManagedObjectService and then wouldn't need to create the factory
if (!factory.isManaged()) {
factory = null;
}
} catch (ManagedObjectException e) {
throw new EJBConfigurationException(e);
}
}
return factory;
}
|
java
|
private ClassLoader getWrapperProxyClassLoader(BeanMetaData bmd, Class<?> intf) // F58064
throws EJBConfigurationException {
// Wrapper proxies are intended to support application restart scenarios.
// In order to allow GC of the target EJB class loader when the
// application stops, the wrapper proxy class must not be defined by the
// target EJB class loader. Instead, we directly define the class on the
// class loader of the interface.
ClassLoader loader = intf.getClassLoader();
// Classes defined by the boot class loader (i.e., java.lang.Runnable)
// have a null class loader.
if (loader != null) {
try {
loader.loadClass(BusinessLocalWrapperProxy.class.getName());
return loader;
} catch (ClassNotFoundException ex) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "unable to load EJSLocalWrapperProxy for " + intf.getName() + " from " + loader);
}
}
// The class loader of the interface did not have visibility to our
// com.ibm.ejs.container classes, which is required. Attempt to use the
// server class loader instead.
loader = bmd.container.getEJBRuntime().getServerClassLoader();
try {
if (loader.loadClass(intf.getName()) == intf) {
return loader;
}
} catch (ClassNotFoundException ex) {
// Nothing.
}
// The server class loader did not have visibility to the interface
// class. The interface was probably loaded by a non-runtime bundle that
// didn't import com.ibm.ejs.container. Just use the application class
// loader even though this will prevent it from being garbage collected,
// and it will do the wrong thing for package-private methods in
// no-interface view.
return bmd.classLoader; // d727494
}
|
java
|
private Constructor<?> getWrapperProxyConstructor(BeanMetaData bmd,
String proxyClassName,
Class<?> interfaceClass,
Method[] methods) // F58064
throws EJBConfigurationException, ClassNotFoundException {
ClassLoader proxyClassLoader = getWrapperProxyClassLoader(bmd, interfaceClass);
Class<?>[] interfaces = new Class<?>[] { interfaceClass };
Class<?> proxyClass = JITDeploy.generateEJBWrapperProxy(proxyClassLoader, proxyClassName, interfaces, methods,
bmd.container.getEJBRuntime().getClassDefiner()); // F70650
try {
return proxyClass.getConstructor(WrapperProxyState.class);
} catch (NoSuchMethodException ex) {
throw new IllegalStateException(ex);
}
}
|
java
|
private static boolean hasEmptyThrowsClause(Method method) {
for (Class<?> klass : method.getExceptionTypes()) {
// Per CTS, callback methods can declare unchecked exceptions on the
// throws clause.
if (!RuntimeException.class.isAssignableFrom(klass) &&
!Error.class.isAssignableFrom(klass)) {
return false;
}
}
return true;
}
|
java
|
private void dealWithUnsatisifedXMLTimers(Map<String, List<com.ibm.ws.javaee.dd.ejb.Timer>> timers1ParmByMethodName,
Map<String, List<com.ibm.ws.javaee.dd.ejb.Timer>> timers0ParmByMethodName,
BeanMetaData bmd) throws EJBConfigurationException {
String oneMethodInError = null;
String last1ParmError = dealWithUnsatisfiedXMLTimers(timers1ParmByMethodName, bmd);
String last0ParmError = dealWithUnsatisfiedXMLTimers(timers0ParmByMethodName, bmd);
//We log all the methods-in-error, but we only explicitly callout one of them in the exception, and it doesn't matter which one we pick.
if (last1ParmError != null) {
oneMethodInError = last1ParmError;
} else {
if (last0ParmError != null) {
oneMethodInError = last0ParmError;
}
}
if (oneMethodInError != null) {
throw new EJBConfigurationException("CNTR0210: The " + bmd.j2eeName.getComponent()
+ " enterprise bean in the " + bmd.j2eeName.getModule()
+ " module has an automatic timer configured in the deployment descriptor for the " + oneMethodInError
+ " method, but no timeout callback method with that name was found.");
}
}
|
java
|
private boolean hasTimeoutCallbackParameters(MethodMap.MethodInfo methodInfo) {
int numParams = methodInfo.getNumParameters();
return numParams == 0 ||
(numParams == 1 && methodInfo.getParameterType(0) == Timer.class);
}
|
java
|
private void addTimerToCorrectMap(Map<String, List<com.ibm.ws.javaee.dd.ejb.Timer>> timers1ParmByMethodName,
Map<String, List<com.ibm.ws.javaee.dd.ejb.Timer>> timers0ParmByMethodName,
Map<String, List<com.ibm.ws.javaee.dd.ejb.Timer>> timersUnspecifiedParmByMethodName,
int parmCount,
String methodName,
com.ibm.ws.javaee.dd.ejb.Timer timer) {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
Map<String, List<com.ibm.ws.javaee.dd.ejb.Timer>> mapToUse = null;
if (parmCount == 0) {
mapToUse = timers0ParmByMethodName;
} else if (parmCount == 1) {
mapToUse = timers1ParmByMethodName;
} else {
mapToUse = timersUnspecifiedParmByMethodName;
}
List<com.ibm.ws.javaee.dd.ejb.Timer> timerList = mapToUse.get(methodName);
if (timerList == null) {
timerList = new ArrayList<com.ibm.ws.javaee.dd.ejb.Timer>();
mapToUse.put(methodName, timerList);
}
if (isTraceOn && tc.isDebugEnabled()) {
Tr.debug(tc, "found XML timer for method " + methodName);
}
timerList.add(timer);
}
|
java
|
private EJBMethodInfoImpl findMethodInEJBMethodInfoArray(EJBMethodInfoImpl[] methodInfos, final Method targetMethod) {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled()) {
Tr.entry(tc, "findMethodInEJBMethodInfoArray for method \"" + targetMethod.toString() + "\"");
}
for (EJBMethodInfoImpl info : methodInfos) {
if (targetMethod.equals(info.getMethod())) {
if (isTraceOn && tc.isEntryEnabled()) {
Tr.exit(tc, "findMethodInEJBMethodInfoArray found EJBMethodInfoImpl for method \"" + targetMethod.toString() + "\"");
}
return info;
}
}
if (isTraceOn && tc.isEntryEnabled()) {
Tr.exit(tc, "findMethodInEJBMethodInfoArray did not find EJBMethodInfoImpl for method \"" + targetMethod.toString() + "\"");
}
return null;
}
|
java
|
protected void processReferenceContext(BeanMetaData bmd) throws InjectionException, EJBConfigurationException {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "ensureReferenceDataIsProcessed");
// At this point, regardless of whether we are in a pure or hybrid flow,
// we should have a populated ReferenceContext.
//
// Now we attempt to process it. If we are in a pure flow, processing
// will actually occur. If we are in a hybrid flow, processing will
// occur if it has not been done yet (via the webcontainer, or via
// some other bean component). If it has already been done, this
// call will no-op...but thats a black box to us here, and we don't
// know are care if processing actually runs now, or if it already
// ran earlier in time.
ReferenceContext refContext = bmd.ivReferenceContext;
refContext.process();
// Persist output data structures into BMD
bmd._javaNameSpaceContext = refContext.getJavaCompContext(); // F743-17630CodRv
bmd.setJavaNameSpace(refContext.getComponentNameSpace());
bmd._resourceRefList = refContext.getResolvedResourceRefs();
bmd.ivJavaColonCompEnvMap = refContext.getJavaColonCompEnvMap();
bmd.envProps = refContext.getEJBContext10Properties(); // F743-17630CodRv
// F743-21481
// Stick InjectionTargets that are visible to bean class into BMD
bmd.ivBeanInjectionTargets = getInjectionTargets(bmd, bmd.enterpriseBeanClass);
// F743-21481
// Stick the InjectionTargets that are visible to each interceptor
// class into the InterceptorMetaData
InterceptorMetaData imd = bmd.ivInterceptorMetaData;
if (imd != null) {
Class<?>[] interceptorClasses = imd.ivInterceptorClasses;
if (interceptorClasses != null && interceptorClasses.length > 0) {
InjectionTarget[][] interceptorInjectionTargets = new InjectionTarget[interceptorClasses.length][0];
for (int i = 0; i < interceptorClasses.length; i++) {
// The InjectionTarget[] associated with the interceptor class is
// empty (ie, 0 length array) if there are no visible
// InjectionTargets. Its added to the interceptorInjectionTargets
// array anyway because this array needs to have the same length
// as the IMD.ivInterceptorClasses array...ie, each 'row' in this
// array corresponds directly to a class in that array, and if the
// two arrays get out-of-sync, then we have a problem.
Class<?> oneInterceptorClass = interceptorClasses[i];
InjectionTarget[] targets = getInjectionTargets(bmd, oneInterceptorClass);
interceptorInjectionTargets[i] = targets;
}
imd.ivInterceptorInjectionTargets = interceptorInjectionTargets;
}
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "Interceptor metadata after adding any InjectionTargets:\n" + imd);
}
if (!EJSPlatformHelper.isZOSCRA()) {
// Verify that a MDB or stateless session bean instance or the
// interceptor instances of MDB and SLSB are not the target of a
// extended persistent context injection since extended persistent
// unit is only allowed for the SFSB and it's interceptor instances.
findAndProcessExtendedPC(bmd); //465813
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "ensureReferenceDataIsProcessed");
}
|
java
|
private void removeTemporaryMethodData(BeanMetaData bmd) {
bmd.methodsExposedOnLocalHomeInterface = null;
bmd.methodsExposedOnLocalInterface = null;
bmd.methodsExposedOnRemoteHomeInterface = null;
bmd.methodsExposedOnRemoteInterface = null;
bmd.allPublicMethodsOnBean = null;
bmd.methodsToMethodInfos = null;
}
|
java
|
public SIBusMessage next()
throws SISessionUnavailableException, SISessionDroppedException,
SIResourceException, SIConnectionLostException,
SIErrorException
{
if (TraceComponent.isAnyTracingEnabled() && CoreSPIBrowserSession.tc.isEntryEnabled())
SibTr.entry(CoreSPIBrowserSession.tc, "next", this);
JsMessage msg = null;
synchronized(this)
{
//Check that the session is not closed, if it is throw an exception
checkNotClosed();
//if the browse cursor is null - it was pub sub - this
//session will never return any messages
if (_browseCursor != null)
{
try
{
//Get the next item from the browseCursor and cast it
//to a SIMPMessage
msg = _browseCursor.next();
}
catch (SISessionDroppedException e)
{
// MessageStoreException shouldn't occur so FFDC.
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.BrowserSessionImpl.next",
"1:265:1.78.1.7",
this);
close();
SibTr.exception(tc, e);
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0002",
new Object[] {
"com.ibm.ws.sib.processor.impl.BrowserSessionImpl",
"1:274:1.78.1.7",
e });
if (TraceComponent.isAnyTracingEnabled() && CoreSPIBrowserSession.tc.isEntryEnabled())
SibTr.exit(CoreSPIBrowserSession.tc, "next", e);
throw e;
}
catch (SIResourceException e)
{
// MessageStoreException shouldn't occur so FFDC.
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.BrowserSessionImpl.next",
"1:287:1.78.1.7",
this);
SibTr.exception(tc, e);
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0002",
new Object[] {
"com.ibm.ws.sib.processor.impl.BrowserSessionImpl",
"1:294:1.78.1.7",
e });
if (TraceComponent.isAnyTracingEnabled() && CoreSPIBrowserSession.tc.isEntryEnabled())
SibTr.exit(CoreSPIBrowserSession.tc, "next", e);
throw e;
}
}//end if
}//end sync
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(CoreSPIBrowserSession.tc, "next", msg);
return msg;
}
|
java
|
public void close()
{
if (TraceComponent.isAnyTracingEnabled() && CoreSPIBrowserSession.tc.isEntryEnabled())
SibTr.entry(CoreSPIBrowserSession.tc, "close", this);
synchronized (this)
{
if (!_closed)
//if we're closed already, don't bother doing anything.
{
//dereference from the parent connection
_conn.removeBrowserSession(this);
_close();
}
}
if (TraceComponent.isAnyTracingEnabled() && CoreSPIBrowserSession.tc.isEntryEnabled())
SibTr.exit(CoreSPIBrowserSession.tc, "close");
}
|
java
|
void checkNotClosed() throws SISessionUnavailableException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "checkNotClosed");
synchronized (this)
{
if (_closed)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "checkNotClosed", "Object closed");
throw new SISessionUnavailableException(
nls.getFormattedMessage("OBJECT_CLOSED_ERROR_CWSIP0081",
new Object[] { _dest.getName(),
_dest.getMessageProcessor().getMessagingEngineName() },
null));
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "checkNotClosed");
}
|
java
|
public DestinationHandler getNamedDestination()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
{
SibTr.entry(tc, "getNamedDestination");
SibTr.exit(tc, "getNamedDestination", _dest);
}
return _dest;
}
|
java
|
public String getUserAgent(FacesContext facesContext)
{
if (userAgent == null)
{
synchronized (this)
{
if (userAgent == null)
{
Map<String, String[]> requestHeaders =
facesContext.getExternalContext().getRequestHeaderValuesMap();
if (requestHeaders != null &&
requestHeaders.containsKey("User-Agent"))
{
String[] userAgents = requestHeaders.get("User-Agent");
userAgent = userAgents.length > 0 ? userAgents[0] : null;
}
}
}
}
return userAgent;
}
|
java
|
public static BigInteger decode(String s) {
byte[] bytes = Base64.decodeBase64(s);
BigInteger bi = new BigInteger(1, bytes);
return bi;
}
|
java
|
public static synchronized void initialise()
{
// Only initialise if it has not already been created
if (_instance == null)
{
// Check what environment we are running in. If we are in server mode we must use the
// server diagnostic module.
//Liberty COMMS TODO:
//For now not enabling server side diagnostics as can not load SERVER_DIAG_MODULE_CLASS in a clean manner
// without having dependency of COMMs server ( at least more than 4/5 classes are needed) which defeat
// the purpose of COMMS client independence w.r.to COMMS server
//Has to rework on load SERVER_DIAG_MODULE_CLASS without too many dependencies of COMMS server.
/*
if (RuntimeInfo.isServer())
{
if (tc.isDebugEnabled()) SibTr.debug(tc, "We are in Server mode");
try
{
Class clazz = Class.forName(CommsConstants.SERVER_DIAG_MODULE_CLASS);
Method getInstanceMethod = clazz.getMethod("getInstance", new Class[0]);
_instance = (CommsDiagnosticModule) getInstanceMethod.invoke(null, (Object[]) null);
}
catch (Exception e)
{
FFDCFilter.processException(e, CLASS_NAME + ".initialise",
CommsConstants.COMMSDIAGMODULE_INITIALIZE_01,
CommsConstants.SERVER_DIAG_MODULE_CLASS);
if (tc.isDebugEnabled()) SibTr.debug(tc, "Unable to load the Comms Server Diagnostic Module", e);
// In this case, fall out of here with a null _instance and default to the client
// one. At least in that case we get _some_ diagnostics...
// This is the point where I mention that that shouldn't ever happen :-).
}
}
*/
// In all other cases use the client diagnostic module. Note we can instantiate this
// directly as we are located in the same build component
if (_instance == null)
{
if (tc.isDebugEnabled()) SibTr.debug(tc, "We are NOT in Server mode");
_instance = ClientCommsDiagnosticModule.getInstance();
}
// Now register the packages
_instance.register(packageList);
}
}
|
java
|
public void ffdcDumpDefault(Throwable t, IncidentStream is, Object callerThis, Object[] objs, String sourceId)
{
if (tc.isEntryEnabled()) SibTr.entry(this, tc, "ffdcDumpDefault",
new Object[]{t, is, callerThis, objs, sourceId});
// Dump the SIB information
super.ffdcDumpDefault(t, is, callerThis, objs, sourceId);
is.writeLine("\n= ============= SIB Communications Diagnostic Information =============", "");
is.writeLine("Current Diagnostic Module: ", _instance);
dumpJFapClientStatus(is);
dumpJFapServerStatus(is);
if (tc.isEntryEnabled()) SibTr.exit(this, tc, "ffdcDumpDefault");
}
|
java
|
boolean setObserver(Observer observer) { // F16043
boolean success;
Observer oldObserver;
synchronized (this) {
oldObserver = ivObserver;
success = oldObserver != null || !isDone();
ivObserver = success ? observer : null;
}
if (oldObserver != null) {
oldObserver.update(null, observer);
}
return success;
}
|
java
|
private void cleanup() { // d623593
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "cleanup");
synchronized (ivRemoteAsyncResultReaper) {
if (ivAddedToReaper) { // d690014
// d690014.3 - The call to remove will remove the result from the
// reaper and then call unexportObject itself.
this.ivRemoteAsyncResultReaper.remove(this);
} else {
unexportObject();
}
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "cleanup");
}
|
java
|
RemoteAsyncResult exportObject() throws RemoteException {
ivObjectID = ivRemoteRuntime.activateAsyncResult((Servant) createTie());
return ivRemoteRuntime.getAsyncResultReference(ivObjectID);
}
|
java
|
protected void unexportObject() { // d623593
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "unexportObject: " + this);
if (ivObjectID != null) {
// Either the allowed timeout occurred or a method was called and we
// know that the client no longer needs this server resource.
try {
ivRemoteRuntime.deactivateAsyncResult(ivObjectID);
} catch (Throwable e) {
// We failed to unexport the object. This should never happen, but
// it's not fatal.
if (isTraceOn && tc.isDebugEnabled())
Tr.debug(tc, "unexportObject exception", e);
FFDCFilter.processException(e, CLASS_NAME + ".unexportObject", "237", this);
}
this.ivObjectID = null;
}
}
|
java
|
public BeanId find(EJSHome home, Serializable pkey, boolean isHome)
{
int hashValue = BeanId.computeHashValue(home.j2eeName, pkey, isHome);
BeanId[] buckets = this.ivBuckets;
BeanId element = buckets[(hashValue & 0x7FFFFFFF) % buckets.length];
if (element == null || !element.equals(home, pkey, isHome))
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
++ivCacheFinds;
Tr.debug(tc, "BeanId not found in BeanId Cache : " +
ivCacheHits + " / " + ivCacheFinds);
}
element = new BeanId(home, pkey, isHome);
}
else
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
{
++ivCacheFinds;
++ivCacheHits;
Tr.debug(tc, "BeanId found in BeanId Cache : " +
ivCacheHits + " / " + ivCacheFinds);
}
}
return element;
}
|
java
|
protected boolean needsToBeRefreshed(DefaultFacelet facelet)
{
// if set to 0, constantly reload-- nocache
if (_refreshPeriod == NO_CACHE_DELAY)
{
return true;
}
// if set to -1, never reload
if (_refreshPeriod == INFINITE_DELAY)
{
return false;
}
long target = facelet.getCreateTime() + _refreshPeriod;
if (System.currentTimeMillis() > target)
{
// Should check for file modification
URLConnection conn = null;
try
{
conn = facelet.getSource().openConnection();
long lastModified = ResourceLoaderUtils.getResourceLastModified(conn);
return lastModified == 0 || lastModified > target;
}
catch (IOException e)
{
throw new FaceletException("Error Checking Last Modified for " + facelet.getAlias(), e);
}
finally
{
// finally close input stream when finished, if fails just continue.
if (conn != null)
{
try
{
InputStream is = conn.getInputStream();
if (is != null)
{
is.close();
}
}
catch (IOException e)
{
// Ignore
}
}
}
}
return false;
}
|
java
|
int getState() {
if (tc.isEntryEnabled())
tc.entry(this,cclass, "getState");
int state;
if (!prefixDone) {
// Somewhere in the prefix or at beginning and there is no prefix
Pattern.Clause prefix = pattern.getPrefix();
if (prefix == null || next >= prefix.items.length) {
// There is no prefix or we're at the end of it
Pattern.Clause suffix = pattern.getSuffix();
// Answer depends on the suffix
state = suffix == null ? FINAL_MANY : suffix == prefix ? FINAL_EXACT
: SWITCH_TO_SUFFIX;
}
else
// We're somewhere in the body of the prefix
state = prefix.items[next] == Pattern.matchOne ? SKIP_ONE_PREFIX : PREFIX_CHARS;
}
else {
// We're in the suffix
Pattern.Clause suffix = pattern.getSuffix();
state = (next < 0) ? FINAL_MANY
: suffix.items[next] == Pattern.matchOne ? SKIP_ONE_SUFFIX : SUFFIX_CHARS;
}
if (tc.isEntryEnabled())
tc.exit(this,cclass, "getState", new Integer(state));
return state;
}
|
java
|
void advance() {
if (tc.isEntryEnabled())
tc.entry(this,cclass, "advance");
if (!prefixDone) {
Pattern.Clause prefix = pattern.getPrefix();
if (prefix == null || next >= prefix.items.length) {
Pattern.Clause suffix = pattern.getSuffix();
if (suffix != null && suffix != prefix) {
// SWITCH_TO_SUFFIX
prefixDone = true;
next = suffix.items.length-1;
}
// else in one of the FINAL_ states, so do nothing
}
else
// somewhere in the body of the prefix, so advance by incrementing
next++;
}
else
// somewhere in the suffix, so advance by decrementing
next--;
if (tc.isEntryEnabled())
tc.exit(this,cclass, "advance");
}
|
java
|
char[] getChars() {
if (tc.isEntryEnabled())
tc.entry(this,cclass, "getChars");
char[] ans;
if (prefixDone)
ans = (char[]) pattern.getSuffix().items[next--];
else
ans = (char[]) pattern.getPrefix().items[next++];
if (tc.isEntryEnabled())
tc.exit(this,cclass, "getChars", new String(ans));
return ans;
}
|
java
|
public boolean matchMidClauses(char[] chars, int start, int length)
{
return pattern.matchMiddle(chars, start, start+length);
}
|
java
|
public String extractPropertyFromURI(String propName, String uri) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "extractPropertyFromURI", new Object[]{propName, uri});
String result = null;
// only something to do if uri is non-null & non-empty u
if (uri != null) {
uri = uri.trim();
if (!uri.equals("")) {
String[] parts = splitOnNonEscapedChar(uri, '?', 2);
// parts[1] (if present) is the NVPs, so only something to do if present & non-empty
if (parts.length >= 2) {
String nvps = parts[1].trim();
if (!nvps.equals("")) {
// break the nvps string into an array of name=value strings
// Use a regular expression to split on an '&' only if it isn't preceeded by a '\'.
String[] nvpArray = splitOnNonEscapedChar(nvps, '&', -1);
// Search the array for the named property
String propNameE = propName+"=";
for (int i = 0; i < nvpArray.length; i++) {
String nvp = nvpArray[i];
if (nvp.startsWith(propNameE)) {
// everything after the = is the value
result = nvp.substring(propNameE.length());
break; // exit the loop
}
}
}
}
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "extractPropertyFromURI", result);
return result;
}
|
java
|
private String[] splitOnNonEscapedChar(String inputStr, char splitChar, int expectedPartCount) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "splitOnNonEscapedChar", new Object[]{inputStr, splitChar, expectedPartCount});
String[] parts = null;
List<String> partsList = null;
// Index variable along the length of the string
int startPoint = 0;
int tokenStart = 0;
int splitCharIndex = 0;
// Used to keep track of how many parts we have found
int partCount = 0;
// Implement manual splitting here.
// Loop through searching for unescaped splitter characters until we reach the end of the string
// or the requested number of pieces.
while ((splitCharIndex != -1) && (partCount != (expectedPartCount-1))) {
splitCharIndex = inputStr.indexOf(splitChar, startPoint);
// We only have work to do here if a splitter char was found and it was not escaped.
if ((splitCharIndex != -1) && !charIsEscaped(inputStr, splitCharIndex)) {
// Found a non-escaped splitter character
// Set the first part of the string.
String nextPart = inputStr.substring(tokenStart, splitCharIndex);
// If we have not yet initialized the storage then do so now.
if (expectedPartCount >= 2) {
if (parts == null) parts = new String[expectedPartCount];
parts[partCount] = nextPart;
}
else {
// Variable storage mechanism.
if (partsList == null) partsList = new ArrayList<String>(5);
partsList.add(nextPart);
}
// Indicate that we have found a new part.
partCount++;
// Move up the start point appropriately
startPoint = splitCharIndex+1;
tokenStart = startPoint;
}
else {
// If the splitter is escaped then we need to look further
// down the string for the next one.
startPoint = splitCharIndex+1;
// implicit 'continue' on the while loop.
}
}
// Get the last part of the token string here. Either we haven't found another splitter,
// or we just need to pick up the last chunk (regardless of whether it contains further
// splitters).
String nextPart = inputStr.substring(tokenStart, inputStr.length());
if (expectedPartCount >= 2) {
if (parts == null) {
// If we haven't found any splitters then just pass back the string itself.
parts = new String[1];
}
// Either there weren't any splitter characters, or we found one at some point but
// have subsequently run out of further ones to process - in any case we need to put
// in the last part of the string.
parts[partCount] = nextPart;
}
else {
// Variable storage final step here.
if (partsList == null) {
// No parts found - special optimized path here.
parts = new String[1];
parts[0] = nextPart;
}
else {
partsList.add(nextPart);
// Conver the list back into a string[]
parts = partsList.toArray(new String[] {});
}
}
// Do a quick check to see whether we were unable to make up the requested number of elements in
// the array (in which case it is too big and needs resizing). This should hopefully be a minority
// case.
if ((parts[parts.length-1] == null)) {
// There are one or more empty spaces at the end of the array.
// Find the last element that doesn't have real data in it and trim the array appropriately.
// In observations the last element can be empty string, so the partCount isn't any good to us here.
int lastValidEntry = 0;
while ((parts[lastValidEntry] != null) && (!"".equals(parts[lastValidEntry]))) {
lastValidEntry++;
}
String[] tempParts = new String[lastValidEntry];
System.arraycopy(parts, 0, tempParts, 0, lastValidEntry);
parts = tempParts;
}
// Slightly unconventional way of ensuring that the content of the array is properly traced rather than just
// the array object code (tr.exit will call toString on each of the parts of the array)
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "splitOnNonEscapedChar", parts);
return parts;
}
|
java
|
private String unescape(String input, char c) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "unescape", new Object[]{input, c});
String result = input;
// if there are no instances of c in the String we can just return the original
if (input.indexOf(c) != -1) {
int startValue = 0;
StringBuffer temp = new StringBuffer(input);
String cStr = new String(new char[] { c });
while ((startValue = temp.indexOf(cStr, startValue)) != -1) {
if (startValue > 0 && temp.charAt(startValue - 1) == '\\') {
// remove the preceding slash to leave the escaped character
temp.deleteCharAt(startValue - 1);
}
else {
startValue++;
}
}
result = temp.toString();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "unescape", result);
return result;
}
|
java
|
private String unescapeBackslash(String input) throws JMSException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "unescapeBackslash", input);
String result = input;
// If there are no backslashes then don't bother creating the buffer etc.
if (input.indexOf("\\") != -1) {
int startValue = 0;
StringBuffer tmp = new StringBuffer(input);
while ((startValue = tmp.indexOf("\\", startValue)) != -1) {
// check that the next character is also a \
if (startValue + 1 < tmp.length() && tmp.charAt(startValue + 1) == '\\') {
// remove the first slash
tmp.deleteCharAt(startValue);
// increment startValue so that the next indexOf begins after the second slash
startValue++;
}
else {
// we've found a single \, so throw an exception
throw (JMSException) JmsErrorUtils.newThrowable(
JMSException.class,
"BAD_ESCAPE_CHAR_CWSIA0387",
new Object[] { input },
tc);
}
}
result = tmp.toString();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "unescapeBackslash", result);
return result;
}
|
java
|
private String[] validateNVP(String namePart, String valuePart, String uri, JmsDestination dest) throws JMSException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "validateNVP", new Object[]{namePart, valuePart, uri, dest});
// de-escape any escaped &s in the value (we define names, so no & there)
if (valuePart.indexOf('&') != -1) {
valuePart = valuePart.replaceAll("\\\\&", "&");
}
// The only valid escape sequence that should be left is "\\" which
// transforms to a single '\'
valuePart = unescapeBackslash(valuePart);
// Performing mapping from MA88 names to Jetstream names.
// If the name part is any of the following MA88 properties, we leave it because
// there is no direct Jetstream equivalent for the property:
// 'CCSID', 'encoding', 'brokerDurSubQueue', 'brokerCCDurSubQueue', 'multicast'.
// In this event, the unknown property will be silently ignored, and NOT throw an exception.
if (namePart.equalsIgnoreCase(MA88_EXPIRY)) {
namePart = JmsInternalConstants.TIME_TO_LIVE;
}
if (namePart.equalsIgnoreCase(MA88_PERSISTENCE)) {
namePart = JmsInternalConstants.DELIVERY_MODE;
// map between the MA88 Integer values and the Jetstream String values
if (valuePart.equals("1")) {
valuePart = ApiJmsConstants.DELIVERY_MODE_NONPERSISTENT;
}
else if (valuePart.equals("2")) {
valuePart = ApiJmsConstants.DELIVERY_MODE_PERSISTENT;
}
else {
valuePart = ApiJmsConstants.DELIVERY_MODE_APP;
}
}
// create a new String[] and populate it with the newly validated element, then return.
String[] result = new String[] { namePart, valuePart };
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "validateNVP", result);
return result;
}
|
java
|
private void configureDestinationFromMap(JmsDestination dest, Map<String,String> props, String uri) throws JMSException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "configureDestinationFromMap", new Object[]{dest, props, uri});
// Iterate over the map, retrieving the name and value parts of the NVP.
Iterator<Map.Entry<String,String>> iter = props.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String,String> nextProp = iter.next();
String namePart = nextProp.getKey();
String valuePart = nextProp.getValue();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "name " + namePart + ", value " + valuePart);
// Here we want to try and get the class for the value part or a property name.
// If this returns null, we can silently ignore the property because we know
// that it in not a valid property to set on a Destination object.
// We also use a boolean flag so that we don't then try to process this property again below.
boolean propertyIsSettable = true;
Class cl = MsgDestEncodingUtilsImpl.getPropertyType(namePart);
if (cl == null) {
propertyIsSettable = false;
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Ignoring invalid property " + namePart);
}
// Now we know they're legal, we can process the name and value pairs
// Determine the type of the value using a dynamic lookup on the name.
// This uses the utility methods in MsgDestEncodingUtilsImpl.
// We only want to perform this step if an exception was not throw in the code block above.
if (propertyIsSettable) {
try {
// Convert the property to the right type of object
Object valueObject = MsgDestEncodingUtilsImpl.convertPropertyToType(namePart, valuePart);
if (namePart.equals(TOPIC_NAME)) {
// special case topicName, as it may be null, and the reflection stuff can't cope
if (dest instanceof JmsTopicImpl) {
((JmsTopicImpl) dest).setTopicName((String) valueObject);
}
else {
// generate an internal error
throw (JMSException) JmsErrorUtils.newThrowable(
JMSException.class,
"INTERNAL_ERROR_CWSIA0386",
null,
tc);
}
}
else {
// call setDestinationProperty(JmsDestination dest, String propName, String propVal)
MsgDestEncodingUtilsImpl.setDestinationProperty(dest, namePart, valueObject);
}
}
catch (NumberFormatException nfe) {
// No FFDC code needed
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.exception(tc, nfe);
// d238447 FFDC review.
// Updated during d272111. NFEs can be generated by supplying badly formed URIs from
// user code, so don't FFDC.
throw (JMSException) JmsErrorUtils.newThrowable(
JMSException.class,
"INVALID_URI_ELEMENT_CWSIA0384",
new Object[] { namePart, valuePart, uri },
nfe, null, null, // nulls = no ffdc
tc);
}
catch (JMSException jmse) {
// No FFDC code needed
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.exception(tc, jmse);
throw (JMSException) JmsErrorUtils.newThrowable(
JMSException.class,
"INVALID_URI_ELEMENT_CWSIA0384",
new Object[] { namePart, valuePart, uri },
tc);
}
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "configureDestinationFromMap");
}
|
java
|
public Destination createDestinationFromURI(String uri, int qmProcessing) throws JMSException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "createDestinationFromURI", new Object[]{uri, qmProcessing});
Destination result = null;
if (uri != null) {
result = processURI(uri, qmProcessing, null);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "createDestinationFromURI", result);
return result;
}
|
java
|
private static boolean charIsEscaped(String str, int index) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "charIsEscaped", new Object[]{str, index});
// precondition, null str or out of range index returns false.
if (str == null || index < 0 || index >= str.length()) return false;
// A character is escaped if it is preceded by an odd number of '\'s.
int nEscape = 0;
int i = index-1;
while(i>=0 && str.charAt(i) == '\\') {
nEscape++;
i--;
}
boolean result = nEscape % 2 == 1 ;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "charIsEscaped", result);
return result;
}
|
java
|
public static PrivateKey readPrivateKey(String pemResName) throws Exception {
InputStream contentIS = TokenUtils.class.getResourceAsStream(pemResName);
byte[] tmp = new byte[4096];
int length = contentIS.read(tmp);
PrivateKey privateKey = decodePrivateKey(new String(tmp, 0, length));
return privateKey;
}
|
java
|
public static PublicKey readPublicKey(String pemResName) throws Exception {
InputStream contentIS = TokenUtils.class.getResourceAsStream(pemResName);
byte[] tmp = new byte[4096];
int length = contentIS.read(tmp);
PublicKey publicKey = decodePublicKey(new String(tmp, 0, length));
return publicKey;
}
|
java
|
public static KeyPair generateKeyPair(int keySize) throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(keySize);
KeyPair keyPair = keyPairGenerator.genKeyPair();
return keyPair;
}
|
java
|
public static PrivateKey decodePrivateKey(String pemEncoded) throws Exception {
pemEncoded = removeBeginEnd(pemEncoded);
byte[] pkcs8EncodedBytes = Base64.getDecoder().decode(pemEncoded);
// extract the private key
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PrivateKey privKey = kf.generatePrivate(keySpec);
return privKey;
}
|
java
|
public static PublicKey decodePublicKey(String pemEncoded) throws Exception {
pemEncoded = removeBeginEnd(pemEncoded);
byte[] encodedBytes = Base64.getDecoder().decode(pemEncoded);
X509EncodedKeySpec spec = new X509EncodedKeySpec(encodedBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
|
java
|
public void registerDeferredService(BundleContext bundleContext, Class<?> providedService, Dictionary dict) {
Object obj = serviceReg.get();
if (obj instanceof ServiceRegistration<?>) {
// already registered - nothing to do here
return;
}
if (obj instanceof CountDownLatch) {
// another thread is in the process of (de)registering - wait for it to finish
try {
((CountDownLatch) obj).await();
if (serviceReg.get() instanceof ServiceRegistration<?>) {
// Another thread has successfully registered to return out (so we don't go
// into recursive loop).
return;
}
} catch (InterruptedException swallowed) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Count down interrrupted", swallowed);
}
}
} else {
// This is probably the first thread to register.
// Claim the right to register by setting a latch for other threads to wait on.
CountDownLatch latch = new CountDownLatch(1);
if (serviceReg.compareAndSet(null, latch)) {
// This thread won the right to register the service
try {
serviceReg.set(bundleContext.registerService(providedService.getName(), this, dict));
// successfully registered - nothing more to do
return;
} finally {
// if the serviceReg was not updated for any reason, we need to set it back to null
serviceReg.compareAndSet(latch, null);
// in any case we need to allow any blocked threads to proceed
latch.countDown();
}
}
}
// If we get to here we have not successfully registered
// nor seen another thread successfully register, so just recurse.
registerDeferredService(bundleContext, providedService, dict);
}
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.