code
stringlengths
73
34.1k
label
stringclasses
1 value
public static LooseConfig convertToLooseConfig(File looseFile) throws Exception { //make sure the file exists, can be read and is an xml if (looseFile.exists() && looseFile.isFile() && looseFile.canRead() && looseFile.getName().toLowerCase().endsWith(".xml")) { LooseConfig root = new LooseConfig(LooseType.ARCHIVE); XMLStreamReader reader = null; try { LooseConfig cEntry = root; Stack<LooseConfig> stack = new Stack<LooseConfig>(); stack.push(cEntry); /* * Normally we specifically request the system default XMLInputFactory to avoid issues when * another XMLInputFactory is available on the thread context class loader. In this case it * should be safe to use XMLInputFactory.newInstance() because the commands run separately * from the rest of the code base. */ reader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(looseFile)); while (reader.hasNext() && cEntry != null) { int result = reader.next(); if (result == XMLStreamConstants.START_ELEMENT) { if ("archive".equals(reader.getLocalName())) { String targetLocation = XMLUtils.getAttribute(reader, "targetInArchive"); if (targetLocation != null) { LooseConfig pEntry = cEntry; cEntry = new LooseConfig(LooseType.ARCHIVE); cEntry.targetInArchive = targetLocation; pEntry.children.add(cEntry); //put current Loose Entry into stack stack.push(cEntry); } } else if ("dir".equals(reader.getLocalName())) { cEntry.children.add(createElement(reader, LooseType.DIR)); } else if ("file".equals(reader.getLocalName())) { cEntry.children.add(createElement(reader, LooseType.FILE)); } } else if (result == XMLStreamConstants.END_ELEMENT) { if ("archive".equals(reader.getLocalName())) { stack.pop(); //make sure stack isn't empty before we try and look at it if (!stack.empty()) { //set current entry to be the top of stack cEntry = stack.peek(); } else { cEntry = null; } } } } } catch (FileNotFoundException e) { throw e; } catch (XMLStreamException e) { throw e; } catch (FactoryConfigurationError e) { throw e; } finally { if (reader != null) { try { reader.close(); reader = null; } catch (XMLStreamException e) { Debug.printStackTrace(e); } } } return root; } return null; }
java
public static ArchiveEntryConfig createLooseArchiveEntryConfig(LooseConfig looseConfig, File looseFile, BootstrapConfig bootProps, String archiveEntryPrefix, boolean isUsr) throws IOException { File usrRoot = bootProps.getUserRoot(); int len = usrRoot.getAbsolutePath().length(); String entryPath = null; if (archiveEntryPrefix.equalsIgnoreCase(PackageProcessor.PACKAGE_ARCHIVE_PREFIX) || !isUsr) { entryPath = archiveEntryPrefix + BootstrapConstants.LOC_AREA_NAME_USR + looseFile.getAbsolutePath().substring(len); } else { entryPath = archiveEntryPrefix + looseFile.getAbsolutePath().substring(len); } entryPath = entryPath.replace("\\", "/"); entryPath = entryPath.replace("//", "/"); entryPath = entryPath.substring(0, entryPath.length() - 4); // trim the .xml File archiveFile = processArchive(looseFile.getName(), looseConfig, true, bootProps); return new FileEntryConfig(entryPath, archiveFile); }
java
public static Pattern convertToRegex(String excludeStr) { // make all "." safe decimles then convert ** to .* and /* to /.* to make it regex if (excludeStr.contains(".")) { // regex for "." is \. - but we are converting the string to a regex string so need to escape the escape slash... excludeStr = excludeStr.replace(".", "\\."); } //if we exclude a dir (eg /**/) we need to remove the closing slash so our regex is /.* if (excludeStr.endsWith("/")) { excludeStr = excludeStr.substring(0, excludeStr.length() - 1); } if (excludeStr.contains("**")) { excludeStr = excludeStr.replace("**", ".*"); } if (excludeStr.contains("/*")) { excludeStr = excludeStr.replace("/*", "/.*"); } //need to escape the file seperators correctly, as / is a regex keychar if (excludeStr.contains("/")) { excludeStr = excludeStr.replace("/", "\\/"); } //at this point we should not have any **, if we do replace with * as all * should be prefixed with a . if (excludeStr.contains("**")) { excludeStr = excludeStr.replace("**", "*"); } if (excludeStr.startsWith("*")) { excludeStr = "." + excludeStr; } if (excludeStr.contains("[")) { excludeStr = excludeStr.replace("[", "\\["); } if (excludeStr.contains("]")) { excludeStr = excludeStr.replace("]", "\\]"); } if (excludeStr.contains("-")) { excludeStr = excludeStr.replace("-", "\\-"); } return Pattern.compile(excludeStr); }
java
public synchronized CommsByteBuffer allocate() { if (tc.isEntryEnabled()) SibTr.entry(this, tc, "allocate"); // Remove a CommsByteBuffer from the pool CommsByteBuffer buff = (CommsByteBuffer) pool.remove(); // If the buffer is null then there was none available in the pool // So create a new one if (buff == null) { if (tc.isDebugEnabled()) SibTr.debug(this, tc, "No buffer available from pool - creating a new one"); buff = createNew(); } if (tc.isEntryEnabled()) SibTr.exit(this, tc, "allocate", buff); return buff; }
java
synchronized void release(CommsByteBuffer buff) { if (tc.isEntryEnabled()) SibTr.entry(this, tc, "release", buff); buff.reset(); pool.add(buff); if (tc.isEntryEnabled()) SibTr.exit(this, tc, "release"); }
java
void setMessage(MessageImpl msg) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "setMessage", msg); theMessage = msg; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "setMessage"); }
java
DataSlice encodeSinglePartMessage(Object conn) throws MessageEncodeFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "encodeSinglePartMessage"); // We must only use this method if the message does not have a payload part if (payloadPart != null) { MessageEncodeFailedException mefe = new MessageEncodeFailedException("Invalid call to encodeSinglePartMessage"); FFDCFilter.processException(mefe, "com.ibm.ws.sib.mfp.impl.JsMsgObject.encodeSinglePartMessage", "jmo530", this, new Object[] { MfpConstants.DM_MESSAGE, headerPart.jmfPart, theMessage }); throw mefe; } // The 'conn' parameter (if supplied) is passed as an Object (for no good reason except the // daft build system), but it has to be a CommsConnection instance. if (conn != null && !(conn instanceof CommsConnection)) { throw new MessageEncodeFailedException("Incorrect connection object: " + conn.getClass()); } byte[] buffer = null; // Encoding is handled by JMF. This will be a very cheap operation if JMF already has the // message in assembled form (for example if it was previously decoded from a byte buffer and // has had no major changes). try { // We need to lock the message around the call to updateDataFields() and the // actual encode of the part(s), so that noone can update any JMF message data // during that time (because they can not get the hdr2, api, or payload part). // Otherwise it is possible to get an inconsistent view of the message with some updates // included but those to the cached values 'missing'. // It is still strictly possible for the top-level schema header fields to be // updated, but this will not happen to any fields visible to an app. synchronized(theMessage) { // Ensure any cached message data is written back theMessage.updateDataFields(MfpConstants.UDF_ENCODE); // We need to check if the receiver has all the necessary schema definitions to be able // to decode this message and pre-send any that are missing. ensureReceiverHasSchemata((CommsConnection)conn); // Synchronize this section on the JMF Message, as otherwise the length could // change between allocating the array & encoding the header part into it. synchronized (getPartLockArtefact(headerPart)) { // Allocate a buffer for the Ids and the message part buffer = new byte[ IDS_LENGTH + ArrayUtil.INT_SIZE + ((JMFMessage)headerPart.jmfPart).getEncodedLength() ]; // Write the Ids to the buffer int offset = encodeIds(buffer, 0); // Write the header part to the buffer & add it to the buffer list encodePartToBuffer(headerPart, true, buffer, offset); } } } catch (MessageEncodeFailedException e1) { // This will have been thrown by encodePartToBuffer() which will // already have dumped the appropriate message part. FFDCFilter.processException(e1, "com.ibm.ws.sib.mfp.impl.JsMsgObject.encodeSinglePartMessage", "jmo500", this, new Object[] { MfpConstants.DM_MESSAGE, null, theMessage }); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "encodeSinglePartMessage failed: " + e1); throw e1; } catch (Exception e) { // This is most likely to be thrown by the getEncodedLength() call on the header // so we pass the header part to the diagnostic module. FFDCFilter.processException(e, "com.ibm.ws.sib.mfp.impl.JsMsgObject.encodeSinglePartMessage", "jmo520", this, new Object[] { MfpConstants.DM_MESSAGE, headerPart.jmfPart, theMessage }); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "encodeSinglePartMessage failed: " + e); throw new MessageEncodeFailedException(e); } // If debug trace, dump the buffer before returning if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Encoded JMF Message", debugMsg()); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { SibTr.debug(this, tc, "buffers: ", SibTr.formatBytes(buffer, 0, buffer.length)); } // Wrap the buffer in a DataSlice to return DataSlice slice = new DataSlice(buffer); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "encodeSinglePartMessage", slice); return slice; }
java
List<DataSlice> encodeFast(Object conn) throws MessageEncodeFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "encodeFast"); // The 'conn' parameter (if supplied) is passed as an Object (for no good reason except the // daft build system), but it has to be a CommsConnection instance. if (conn != null && !(conn instanceof CommsConnection)) { throw new MessageEncodeFailedException("Incorrect connection object: " + conn.getClass()); } // Initial capacity is sufficient for a 2 part message List<DataSlice> messageSlices = new ArrayList<DataSlice>(3); DataSlice slice0 = null; DataSlice slice1 = null; DataSlice slice2 = null; // Encoding is handled by JMF. This will be a very cheap operation if JMF already has the // message in assembled form (for example if it was previously decoded from a byte buffer and // has had no major changes). try { // We need to check if the receiver has all the necessary schema definitions to be able // to decode this message and pre-send any that are missing. ensureReceiverHasSchemata((CommsConnection)conn); // Write the top-level Schema Ids & their versions to the top buffer byte[] buff0 = new byte[ IDS_LENGTH + ArrayUtil.INT_SIZE]; int offset = 0; offset += encodeIds(buff0, 0); slice0 = new DataSlice(buff0, 0, buff0.length); // We need to lock the message around the call to updateDataFields() and the // actual encode of the part(s), so that noone can update any JMF message data // during that time (because they can not get the hdr2, api, or payload part). // Otherwise it is possible to get an inconsistent view of the message with some updates // included but those to the cached values 'missing'. // It is still strictly possible for the top-level schema header fields to be // updated, but this will not happen to any fields visible to an app. synchronized(theMessage) { // Next ensure any cached message data is written back before we get the // low level (JSMessageImpl) locks d364050 theMessage.updateDataFields(MfpConstants.UDF_ENCODE); // Write the second slice - this contains the header slice1 = encodeHeaderPartToSlice(headerPart); // Now we have to tell the buffer in the slice0 how long the header part is ArrayUtil.writeInt(buff0, offset, slice1.getLength()); // Now the first 2 slices are complete we can put them in the list. // Slices must be added in the correct order. messageSlices.add(slice0); messageSlices.add(slice1); // Now for the 3rd slice, which will contain the payload (if there is one) if (payloadPart != null) { slice2 = encodePayloadPartToSlice(payloadPart, (CommsConnection)conn); messageSlices.add(slice2); } } } catch (MessageEncodeFailedException e1) { // This will have been thrown by encodeXxxxxPartToSlice() which will // already have dumped the appropriate message part. FFDCFilter.processException(e1, "com.ibm.ws.sib.mfp.impl.JsMsgObject.encodeFast", "jmo560", this, new Object[] { MfpConstants.DM_MESSAGE, null, theMessage }); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "encodeFast failed: " + e1); throw e1; } catch (Exception e) { // This is most likely to be thrown by the getEncodedLength() call on the header // so we pass the header part to the diagnostic module. FFDCFilter.processException(e, "com.ibm.ws.sib.mfp.impl.JsMsgObject.encodeFast", "jmo570", this, new Object[] { MfpConstants.DM_MESSAGE, headerPart.jmfPart, theMessage }); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "encodeFast failed: " + e); throw new MessageEncodeFailedException(e); } // If debug trace, dump the message & slices before returning if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Encoded JMF Message", debugMsg()); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Message DataSlices: ", SibTr.formatSlices(messageSlices, MfpDiagnostics.getDiagnosticDataLimitInt())); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "encodeFast"); return messageSlices; }
java
private final int encodeIds(byte[] buffer, int offset) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "encodeIds"); int idOffset = offset; // Write the JMF version number and Schema id for the header ArrayUtil.writeShort(buffer, idOffset, ((JMFMessage)headerPart.jmfPart).getJMFEncodingVersion()); idOffset += ArrayUtil.SHORT_SIZE; ArrayUtil.writeLong(buffer, idOffset, headerPart.jmfPart.getEncodingSchema().getID()); idOffset += ArrayUtil.LONG_SIZE; // Write the JMF version number and Schema id for the payload, if there is one if (payloadPart != null) { ArrayUtil.writeShort(buffer, idOffset, ((JMFMessage)payloadPart.jmfPart).getJMFEncodingVersion()); idOffset += ArrayUtil.SHORT_SIZE; ArrayUtil.writeLong(buffer, idOffset, payloadPart.jmfPart.getEncodingSchema().getID()); idOffset += ArrayUtil.LONG_SIZE; } // Otherwise we just write zeros to fill up the same space else { ArrayUtil.writeShort(buffer, idOffset, (short)0); idOffset += ArrayUtil.SHORT_SIZE; ArrayUtil.writeLong(buffer, idOffset, 0L); idOffset += ArrayUtil.LONG_SIZE; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "encodeIds", Integer.valueOf(idOffset - offset)); return idOffset - offset; }
java
private final DataSlice encodeHeaderPartToSlice(JsMsgPart jsPart) throws MessageEncodeFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "encodeHeaderPartToSlice", jsPart); // We hope that it is already encoded so we can just get it from JMF..... DataSlice slice = ((JMFMessage)jsPart.jmfPart).getAssembledContent(); // ... if not, then we have to encode it now if (slice == null) { byte[] buff; // We need to ensure noone updates any vital aspects of the message part // between the calls to getEncodedLength() and toByteArray() d364050 synchronized (getPartLockArtefact(jsPart)) { buff = encodePart(jsPart); } slice = new DataSlice(buff, 0, buff.length); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "encodeHeaderPartToSlice", slice); return slice; }
java
private final DataSlice encodePayloadPartToSlice(JsMsgPart jsPart, CommsConnection conn) throws MessageEncodeFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "encodePayloadPartToSlice", new Object[]{jsPart, conn}); boolean beans = false; DataSlice slice = null; // For a payload which isn't Beans, we also hope that it is already encoded so we can // just get it from JMF. A Beans payload part always needs re-encoding as it may // be in SOAP where JMF is required, or vice versa. // Figuring it out is a bit messy: // - if this is a payload part, the message must be a JsMessage // - the ProducerType will be API for a Beans message, whether or not it is wrapped by JMS // - but we'll still have to look at the format field to see if is Beans if ( (((JsMessage)theMessage).getProducerType() != ProducerType.API) || payloadPart.getField(JsPayloadAccess.FORMAT) == null // XMS might not set the format || !(((String)payloadPart.getField(JsPayloadAccess.FORMAT)).startsWith("Bean:")) ) { slice = ((JMFMessage)jsPart.jmfPart).getAssembledContent(); } // If it is beans, leave slice == null and set a flag. else { beans = true; } // If we haven't already got some existing content, we have to encode it now. if (slice == null) { // We need to put the whole lot in a try/finally block to ensure we clear the // thread local data even if something goes wrong. try { // We need to ensure noone updates any vital aspects of the message part // during the call to encodePart() d364050 // In the case of a Beans payload, we also need to ensure no-one else // encodes the message after we unassemble it & before we encode it. synchronized (getPartLockArtefact(jsPart)) { // If we have a Beans message payload, so we need to set the // thread's partner level from the value in the CommsConnection, if present, // and unassemble the payload data to ensure that it does get re-encoded in the next step. if (beans) { // Set the thread's partner level from the value in the Connection MetaData, if present if (conn != null) MfpThreadDataImpl.setPartnerLevel(conn.getMetaData().getProtocolVersion()); try { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "unassembling Beans message"); ((JMFNativePart)jsPart.getField(JsPayloadAccess.PAYLOAD_DATA)).unassemble(); } catch (JMFException e) { // This shouldn't be possible. If we get an Exception something disastrous // must have happened so FFDC it & throw it on wrappered. // Dump the message part to give us some clue what's going on. FFDCFilter.processException(e, "com.ibm.ws.sib.mfp.impl.JsMsgObject.encodePayloadPartToSlice", "jmo620", this, new Object[] { MfpConstants.DM_MESSAGE, jsPart.jmfPart, theMessage } ); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "encodePayloadPartToSlice unassemble failed: " + e); throw new MessageEncodeFailedException(e); } } // Whatever sort of message we have, we now need to encode it. byte[] buff = encodePart(jsPart); slice = new DataSlice(buff, 0, buff.length); } // end of synchronized block } // We must ALWAYS reset the thread local partnerLevel once a payload encode // is no longer in progress, otherwise a future flatten on this thread could // encode to the wrong level. // (It doesn't matter if we didn't actually set it earlier - clearing it is harmless) finally { MfpThreadDataImpl.clearPartnerLevel(); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "encodePayloadPartToSlice", slice); return slice; }
java
JMFSchema[] getEncodingSchemas() throws MessageEncodeFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getEncodingSchemas"); JMFSchema[] result; try { JMFSchema[] result1 = ((JMFMessage)headerPart.jmfPart).getSchemata(); JMFSchema[] result2 = null; int resultSize = result1.length; if (payloadPart != null) { result2 = ((JMFMessage)payloadPart.jmfPart).getSchemata(); resultSize += result2.length; } result = new JMFSchema[resultSize]; System.arraycopy(result1, 0, result, 0, result1.length); if (payloadPart != null) { System.arraycopy(result2, 0, result, result1.length, result2.length); } } catch (JMFException e) { // Dump whatever we can of both message parts FFDCFilter.processException(e, "com.ibm.ws.sib.mfp.impl.JsMsgObject.getEncodingSchemas", "jmo700", this, new Object[] { new Object[] { MfpConstants.DM_MESSAGE, headerPart.jmfPart, theMessage }, new Object[] { MfpConstants.DM_MESSAGE, payloadPart.jmfPart, theMessage } } ); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "getEncodingSchemas failed: " + e); throw new MessageEncodeFailedException(e); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getEncodingSchemas"); return result; }
java
JsMsgObject getCopy() throws MessageCopyFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getCopy"); JsMsgObject newJmo = null; try { // We need to lock the whole of the copy with the getHdr2, getApi & getPayload // methods on the owning message, otherwise someone could reinstate the partcaches // between clearing them and creating the new parts. d352642 synchronized(theMessage) { // Ensure any cached message data is written back and cached message parts are // invalidated. theMessage.updateDataFields(MfpConstants.UDF_GET_COPY); theMessage.clearPartCaches(); // Clone this JMO and insert a copy of the underlying JMF message. It is the JMF // that handles all the "lazy" copying. newJmo = new JsMsgObject(null); newJmo.headerPart = new JsMsgPart(((JMFMessage)headerPart.jmfPart).copy()); newJmo.payloadPart = new JsMsgPart(((JMFMessage)payloadPart.jmfPart).copy()); } } catch (MessageDecodeFailedException e) { // Dump whatever we can of both message parts FFDCFilter.processException(e, "com.ibm.ws.sib.mfp.impl.JsMsgObject.getCopy", "jmo800", this, new Object[] { new Object[] { MfpConstants.DM_MESSAGE, headerPart.jmfPart, theMessage }, new Object[] { MfpConstants.DM_MESSAGE, payloadPart.jmfPart, theMessage } } ); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "copy failed: " + e); throw new MessageCopyFailedException(e); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getCopy", newJmo); return newJmo; }
java
private final void ensureReceiverHasSchemata(CommsConnection conn) throws Exception { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "ensureReceiverHasSchemata", conn); // We need to check if the receiver has all the necessary schema definitions to be able // to decode this message and pre-send any that are missing. if (conn != null) { SchemaManager.sendSchemas(conn, ((JMFMessage)headerPart.jmfPart).getSchemata()); if (payloadPart != null) { SchemaManager.sendSchemas(conn, ((JMFMessage)payloadPart.jmfPart).getSchemata()); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "ensureReceiverHasSchemata"); }
java
final String debugMsg() { StringBuffer result; result = new StringBuffer(JSFormatter.format((JMFMessage)headerPart.jmfPart)); if (payloadPart != null) { result.append(JSFormatter.formatWithoutPayloadData((JMFMessage)payloadPart.jmfPart)); } return result.toString(); }
java
final String debugId(long id) { byte[] buf = new byte[8]; ArrayUtil.writeLong(buf, 0, id); return HexUtil.toString(buf); }
java
public synchronized boolean clearIfNotInUse() { if (tc.isEntryEnabled()) Tr.entry(tc, "clearIfNotInUse",new Object[]{_recoveryId, _recoveredInUseCount}); boolean cleared = false; if (_loggedToDisk && _recoveredInUseCount == 0) { try { if (tc.isDebugEnabled()) Tr.debug(tc, "removing recoverable unit " + _recoveryId); // As it is logged to disk, we must have a _partnerLog available _partnerLog.removeRecoverableUnit(_recoveryId); _loggedToDisk = false; _recoveryId = 0; cleared = true; } catch (Exception e) { FFDCFilter.processException(e, "com.ibm.ws.Transaction.JTA.PartnerLogData.clearIfNotInUse", "218", this); if (e instanceof WriteOperationFailedException) { Tr.error(tc, "WTRN0066_LOG_WRITE_ERROR", e); } else { Tr.error(tc, "WTRN0000_ERR_INT_ERROR", new Object[]{"clearIfNotInUse", "com.ibm.ws.Transaction.JTA.PartnerLogData", e}); } // Just ignore the error and clean it up on the next server run } } if (tc.isEntryEnabled()) Tr.exit(tc, "clearIfNotInUse", cleared); return cleared; }
java
public boolean recover(ClassLoader cl, Xid[] xids, byte[] failedStoken, byte[] cruuid, int restartEpoch) { if (tc.isDebugEnabled()) Tr.debug(tc, "recover", new Object[] {this, cl, xids, failedStoken, cruuid, restartEpoch}); decrementCount(); return true; }
java
private void getFilesForFeature(File installRoot, final Set<String> absPathsForLibertyContent, final Set<String> absPathsForLibertyBundles, final Set<String> absPathsForLibertyLocalizations, final Set<String> absPathsForLibertyIcons, final ProvisioningFeatureDefinition fd, final ContentBasedLocalBundleRepository br) { Collection<FeatureResource> frs = fd.getConstituents(null); for (FeatureResource fr : frs) { switch (fr.getType()) { case FEATURE_TYPE: { // No resource for this feature break; } case BUNDLE_TYPE: case BOOT_JAR_TYPE: { // Add to the list of bundle files addJarResource(absPathsForLibertyBundles, fd, br, fr); break; } case JAR_TYPE: { // Add to the list of normal files addJarResource(absPathsForLibertyContent, fd, br, fr); break; } case FILE_TYPE: { // file uses loc as a relative path from install root. String locString = fr.getLocation(); if (locString != null) { addFileResource(installRoot, absPathsForLibertyContent, locString); } else { // a file type without a loc is bad, means misuse of the // type. throw new BuildException("No location on file type for resource " + fr.getSymbolicName() + " in feature " + fd.getFeatureName()); } break; } case UNKNOWN: { // if its not jar,bundle,feature, or file.. then something // is wrong. log("Unknown feature resource for " + fr.getSymbolicName() + " in feature " + fd.getFeatureName() + ". The type is: " + fr.getRawType(), Project.MSG_ERR); // we assume that other types will use the location field as // something useful. String locString = fr.getLocation(); if (locString != null) { addFileResource(installRoot, absPathsForLibertyContent, locString); } } } } // add in (all) the NLS files for this featuredef.. if any.. for (File nls : fd.getLocalizationFiles()) { if (nls.exists()) { absPathsForLibertyLocalizations.add(nls.getAbsolutePath()); } } for (String icon : fd.getIcons()) { File iconFile = new File(fd.getFeatureDefinitionFile().getParentFile(), "icons/" + fd.getSymbolicName() + "/" + icon); if (iconFile.exists()) { absPathsForLibertyIcons.add(iconFile.getAbsolutePath()); } else { throw new BuildException("Icon file " + iconFile.getAbsolutePath() + " doesn't exist"); } } }
java
public void addFileResource(File installRoot, final Set<String> content, String locString) { String[] locs; if (locString.contains(",")) { locs = locString.split(","); } else { locs = new String[] { locString }; } for (String loc : locs) { File test = new File(loc); if (!test.isAbsolute()) { test = new File(installRoot, loc); } loc = test.getAbsolutePath(); content.add(loc); } }
java
private void copy(OutputStream out, File in) throws IOException { FileInputStream inStream = null; try { inStream = new FileInputStream(in); byte[] buffer = new byte[4096]; int len; while ((len = inStream.read(buffer)) != -1) { out.write(buffer, 0, len); } } finally { if (inStream != null) { inStream.close(); } } }
java
public static String getDataSourceIdentifier(WSJdbcWrapper jdbcWrapper) { DSConfig config = jdbcWrapper.dsConfig.get(); return config.jndiName == null ? config.id : config.jndiName; }
java
public static String getSql(Object jdbcWrapper) { if (jdbcWrapper instanceof WSJdbcPreparedStatement) // also includes WSJdbcCallableStatement return ((WSJdbcPreparedStatement) jdbcWrapper).sql; else if (jdbcWrapper instanceof WSJdbcResultSet) return ((WSJdbcResultSet) jdbcWrapper).sql; else return null; }
java
public static void handleStaleStatement(WSJdbcWrapper jdbcWrapper) { if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) Tr.event(tc, "Encountered a Stale Statement: " + jdbcWrapper); if (jdbcWrapper instanceof WSJdbcObject) try { WSJdbcConnection connWrapper = (WSJdbcConnection) ((WSJdbcObject) jdbcWrapper).getConnectionWrapper(); WSRdbManagedConnectionImpl mc = connWrapper.managedConn; // Instead of closing the statements, mark them as // not poolable so that they are prevented from being cached again when closed. connWrapper.markStmtsAsNotPoolable(); // Clear out the cache. if (mc != null) mc.clearStatementCache(); } catch (NullPointerException nullX) { // No FFDC code needed; probably closed by another thread. if (!((WSJdbcObject) jdbcWrapper).isClosed()) throw nullX; } }
java
public static SQLException mapException(WSJdbcWrapper jdbcWrapper, SQLException sqlX) { Object mapper = null; WSJdbcConnection connWrapper = null; if (jdbcWrapper instanceof WSJdbcObject) { // Use the connection and managed connection. connWrapper = (WSJdbcConnection) ((WSJdbcObject) jdbcWrapper).getConnectionWrapper(); if (connWrapper != null) { mapper = connWrapper.isClosed() ? connWrapper.mcf : connWrapper.managedConn; } } else mapper = jdbcWrapper.mcf; return (SQLException) AdapterUtil.mapException(sqlX, connWrapper, mapper, true); }
java
@Trivial public static boolean validLocalHostName(String hostName) { InetAddress addr = findLocalHostAddress(hostName, PREFER_IPV6); return addr != null; }
java
public static ManifestInfo parseManifest(JarFile jar) throws RepositoryArchiveException, RepositoryArchiveIOException { String prov = null; // Create the WLPInformation and populate it Manifest mf = null; try { mf = jar.getManifest(); } catch (IOException e) { throw new RepositoryArchiveIOException("Unable to access manifest in sample", new File(jar.getName()), e); } finally { try { jar.close(); } catch (IOException e) { throw new RepositoryArchiveIOException("Unable to access manifest in sample", new File(jar.getName()), e); } } if (null == mf) { throw new RepositoryArchiveEntryNotFoundException("No manifest file found in sample", new File(jar.getName()), "/META-INF/MANIFEST.MF"); } String appliesTo = null; ResourceType type = null; List<String> requiresList = new ArrayList<String>(); Attributes mainattrs = mf.getMainAttributes(); // Iterate over the main attributes in the manifest and look for the ones we are interested in. for (Object at : mainattrs.keySet()) { String attribName = ((Attributes.Name) at).toString(); String attribValue = (String) mainattrs.get(at); if (APPLIES_TO.equals(attribName)) { appliesTo = attribValue; } else if (SAMPLE_TYPE.equals(attribName)) { String typeString = (String) mainattrs.get(at); if (SAMPLE_TYPE_OPENSOURCE.equals(typeString)) { type = ResourceType.OPENSOURCE; } else if (SAMPLE_TYPE_PRODUCT.equals(typeString)) { type = ResourceType.PRODUCTSAMPLE; } else { throw new IllegalArgumentException("The following jar file is not a known sample type " + jar.getName()); } } else if (REQUIRE_FEATURE.equals(attribName)) { // We need to split the required features, from a String of comma seperated // features into a List of String, where each String is a feature name. StringTokenizer featuresTokenizer = new StringTokenizer(attribValue, ","); while (featuresTokenizer.hasMoreElements()) { String nextFeature = (String) featuresTokenizer.nextElement(); requiresList.add(nextFeature); } } else if (PROVIDER.equals(attribName)) { prov = attribValue; } } if (null == prov) { throw new RepositoryArchiveInvalidEntryException("No Bundle-Vendor specified in the sample's manifest", new File(jar.getName()), "/META-INF/MANIFEST.MF"); } if (null == type) { throw new RepositoryArchiveInvalidEntryException("No Sample-Type specified in the sample's manifest", new File(jar.getName()), "/META-INF/MANIFEST.MF"); } String archiveRoot = mainattrs.getValue("Archive-Root"); archiveRoot = archiveRoot != null ? archiveRoot : ""; ManifestInfo mi = new ManifestInfo(prov, appliesTo, type, requiresList, archiveRoot, mf); return mi; }
java
void timerLoop() throws ResourceException { final String methodName = "timerLoop"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName); } checkMEs(getMEsToCheck()); if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(TRACE, methodName); } }
java
void checkMEs(JsMessagingEngine[] MEList) throws ResourceException { final String methodName = "checkMEs"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName, new Object[] { MEList }); } // Filter out any non preferred MEs. User specified target data is used to perform this filter. // If no target data is set then all the MEs are considered "preferred" for point to point and // non durable pub sub, but none of them are considered preferred for durable pub sub (which has // a preference for the durable subscription home) JsMessagingEngine[] preferredMEs = _destinationStrategy.getPreferredLocalMEs(MEList); // TODO: Can we wrapper the connect call if a try catch block, if engine is being reloaded then absorb the // exception (trace a warning) and let us kick off a timer (if one is needed). // Try to connect to the list of filtered MEs. try { connect(preferredMEs, _targetType, _targetSignificance, _target, true); SibTr.info(TRACE, "TARGETTED_CONNECTION_SUCCESSFUL_CWSIV0556", new Object[] { ((MDBMessageEndpointFactory) _messageEndpointFactory).getActivationSpecId(), _endpointConfiguration.getDestination().getDestinationName() }); } catch (Exception e) { // After attempting to create connections check to see if we should continue to check for more connections // or not. If we should then kick of a timer to try again after a user specified interval. SibTr.warning(TRACE, SibTr.Suppressor.ALL_FOR_A_WHILE, "CONNECT_FAILED_CWSIV0782", new Object[] { _endpointConfiguration.getDestination().getDestinationName(), _endpointConfiguration.getBusName(), ((MDBMessageEndpointFactory) _messageEndpointFactory).getActivationSpecId(), e }); if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) { SibTr.debug(TRACE, "Failed to obtain a connection - retry after a set interval"); } clearTimer(); // deactivate will close the connections // The connection might be successful but session might fail due to authorization error // Hence before retrying, old connection must be closed deactivate(); kickOffTimer(); } //its possible that there was no exception thrown and connection was not successfull // in that case a check is made to see if an retry attempt is needed if (_destinationStrategy.isTimerNeeded()) { clearTimer(); kickOffTimer(); } if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(TRACE, methodName); } }
java
void kickOffTimer() throws UnavailableException { final String methodName = "kickOffTimer"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName); } synchronized (_timerLock) { // Another timer is already running - no need to create a new one if (_timer != null) { return; } _timer = _bootstrapContext.createTimer(); _timer.schedule(new TimerTask() { @Override public void run() { try { synchronized (_timerLock) { _timer.cancel(); _timer = null; timerLoop(); } } catch (final ResourceException exception) { FFDCFilter.processException(exception, CLASS_NAME + "." + methodName, "1:420:1.45", this); SibTr.error(TRACE, "CONNECT_FAILED_CWSIV0783", new Object[] { _endpointConfiguration.getDestination() .getDestinationName(), _endpointConfiguration.getBusName(), this, exception }); } } }, _retryInterval); } if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(TRACE, methodName); } }
java
private void createSingleListener(final SibRaMessagingEngineConnection connection) throws ResourceException { final String methodName = "createSingleListener"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName, connection); } final SIDestinationAddress destination = _endpointConfiguration.getDestination(); if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) { SibTr.debug(TRACE, "Creating a consumer to consume from destination " + destination + " on ME " + connection.getConnection().getMeName()); } try { connection.createListener(destination, _messageEndpointFactory); SibTr.info(TRACE, "CONNECTED_CWSIV0777", new Object[] { connection.getConnection().getMeName(), _endpointConfiguration.getDestination() .getDestinationName(), _endpointConfiguration.getBusName() }); } catch (final IllegalStateException exception) { // No FFDC code needed if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) { SibTr.debug(TRACE, "Failed to create a session - blowing away the connection - rethrow the exception"); } _connections.remove(connection.getConnection().getMeUuid()); connection.close(); if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, methodName); } throw exception; } catch (final ResourceException exception) { // No FFDC code needed // Failed to create a consumer so blow away the connection and try // again if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) { SibTr.debug(TRACE, "Failed to create a session - blowing away the connection - a retry should occur"); SibTr.debug(TRACE, "Exception cause was " + exception.getCause()); } _connections.remove(connection.getConnection().getMeUuid()); connection.close(); throw exception; } if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, methodName); } }
java
private void createMultipleListeners(final SibRaMessagingEngineConnection connection) throws ResourceException { final String methodName = "createMultipleListeners"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName, connection); } try { final SICoreConnection coreConnection = connection.getConnection(); /* * Create destination listener */ final DestinationListener destinationListener = new SibRaDestinationListener( connection, _messageEndpointFactory); /* * Determine destination type */ final DestinationType destinationType = _endpointConfiguration .getDestinationType(); /* * Register destination listener */ final SIDestinationAddress[] destinations = coreConnection .addDestinationListener(_endpointConfiguration.getDestinationName(), destinationListener, destinationType, DestinationAvailability.RECEIVE); if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) { SibTr.debug(P2PTRACE, "Found " + destinations.length + " destinations that make the wildcard"); } /* * Create a listener for each destination ... */ for (int j = 0; j < destinations.length; j++) { try { if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) { SibTr.debug(P2PTRACE, "Creating a consumer for destination " + destinations[j]); } connection.createListener(destinations[j], _messageEndpointFactory); } catch (final ResourceException exception) { FFDCFilter.processException(exception, CLASS_NAME + "." + methodName, "1:877:1.45", this); SibTr.error(TRACE, "CREATE_LISTENER_FAILED_CWSIV0803", new Object[] { exception, destinations[j].getDestinationName(), connection.getConnection().getMeName(), connection.getBusName() }); } } } catch (final SIException exception) { FFDCFilter.processException(exception, CLASS_NAME + "." + methodName, "1:889:1.45", this); SibTr.error(TRACE, "ADD_DESTINATION_LISTENER_FAILED_CWSIV0804", new Object[] { exception, connection.getConnection().getMeName(), connection.getBusName() }); _connections.remove(connection.getConnection().getMeUuid()); connection.close(); } if (connection.getNumberListeners() == 0) { SibTr.warning(TRACE, "NO_LISTENERS_CREATED_CWSIV0809", new Object[] { _endpointConfiguration.getDestinationName(), connection.getConnection().getMeName(), connection.getBusName() }); } if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, methodName); } }
java
boolean checkIfRemote(SibRaMessagingEngineConnection conn) { final String methodName = "checkIfRemote"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName, new Object[] { conn }); } String meName = conn.getConnection().getMeName(); if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) { SibTr.debug(TRACE, "Connections's ME name " + meName); } boolean remote = true; JsMessagingEngine[] localMEs = SibRaEngineComponent.getActiveMessagingEngines(_endpointConfiguration.getBusName()); for (int i = 0; i < localMEs.length; i++) { JsMessagingEngine me = localMEs[i]; String localName = me.getName(); if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) { SibTr.debug(TRACE, "Checking ME name " + localName); } if (localName.equals(meName)) { if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) { SibTr.debug(TRACE, "Me name matched, the connection is local"); } remote = false; break; } } if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(TRACE, methodName, remote); } return remote; }
java
void dropNonPreferredConnections() { final String methodName = "dropNonPreferredConnections"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName); } // If we are connected to a non preferred then we will NEVER be connect to a preferred as // well, there is no mixing of connection types. if (!_connectedToPreferred) { closeConnections(); } if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(TRACE, methodName); } }
java
void dropRemoteConnections() { final String methodName = "dropRemoteConnections"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName); } if (_connectedRemotely) { closeConnections(); } if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(TRACE, methodName); } }
java
void closeConnections() { final String methodName = "closeConnections"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName); } synchronized (_connections) { Collection<SibRaMessagingEngineConnection> cons = _connections.values(); Iterator<SibRaMessagingEngineConnection> iter = cons.iterator(); while (iter.hasNext()) { SibRaMessagingEngineConnection connection = iter.next(); connection.close(); } _connections.clear(); } if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(TRACE, methodName); } }
java
@Override public synchronized void messagingEngineStopping( final JsMessagingEngine messagingEngine, final int mode) { final String methodName = "messagingEngineStopping"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName, new Object[] { messagingEngine, Integer.valueOf(mode) }); } SibTr.info(TRACE, "ME_STOPPING_CWSIV0784", new Object[] { messagingEngine.getName(), messagingEngine.getBus() }); // dropConnection (messagingEngine.getUuid().toString(), null, true); if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, methodName); } }
java
void dropConnection(SibRaMessagingEngineConnection connection, boolean isSessionError, boolean retryImmediately, boolean alreadyClosed) { String methodName = "dropConnection"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName, new Object[] { connection, Boolean.valueOf(isSessionError), Boolean.valueOf(retryImmediately), Boolean.valueOf(alreadyClosed) }); } SibRaMessagingEngineConnection connectionCheck = null; String meUuid = connection.getConnection().getMeUuid(); synchronized (_connections) { /* * Does the connection that we've been passed, still exist? */ connectionCheck = _connections.get(meUuid); /* * If the connection object that we've been passed is the same object as that retrieved from _connections, close it. */ if (connection == connectionCheck) { closeConnection(meUuid, alreadyClosed); } } // If we are reloading the engine then don't try and reconnect now. Wait until we get an engine // reloaded shoulder tap. Since we don't know if remote MEs are having an engine reloaded we will fail // the connection and deactivate the MDB. The connection is only passed in as a parameter from session // error method call. if (!isSessionError || (!SibRaEngineComponent.isMessagingEngineReloading(meUuid))) { // PM49608 The lock hierarchy is first _timerLock and then _connections // This hierarchy is necessary to avoid deadlock synchronized (_timerLock) { synchronized (_connections) { // If this was our last (or only) connection then kick off another loop to check if // we can obtain a new connection. if (_connections.size() == 0) { try { clearTimer(); if (retryImmediately) { timerLoop(); } else { kickOffTimer(); } } catch (final ResourceException resEx) { FFDCFilter.processException(resEx, CLASS_NAME + "." + methodName, "1:1434:1.45", this); SibTr.error(TRACE, "CONNECT_FAILED_CWSIV0783", new Object[] { _endpointConfiguration.getDestination() .getDestinationName(), _endpointConfiguration.getBusName(), this, resEx }); } } } } } else { // Stop any timers as no point in trying again until we have finished reloading the engine. clearTimer(); } if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, methodName); } }
java
@Override public void messagingEngineDestroyed(JsMessagingEngine messagingEngine) { final String methodName = "messagingEngineDestroyed"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName, messagingEngine); } if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, methodName); } }
java
private boolean validMagicNumber(byte[] magicNumberBuffer) { if (tc.isEntryEnabled()) Tr.entry(tc, "validMagicNumber", new java.lang.Object[] { RLSUtils.toHexString(magicNumberBuffer, RLSUtils.MAX_DISPLAY_BYTES), this }); boolean incorrectByteDetected = false; int currentByte = 0; while ((!incorrectByteDetected) && (currentByte < LogFileHeader.MAGIC_NUMBER.length)) { if (magicNumberBuffer[currentByte] != LogFileHeader.MAGIC_NUMBER[currentByte]) { incorrectByteDetected = true; } currentByte++; } if (tc.isEntryEnabled()) Tr.exit(tc, "validMagicNumber", new Boolean(!incorrectByteDetected)); return !incorrectByteDetected; }
java
public long date() { if (tc.isEntryEnabled()) Tr.entry(tc, "date", this); if (tc.isEntryEnabled()) Tr.exit(tc, "date", new Long(_date)); return _date; }
java
public long firstRecordSequenceNumber() { if (tc.isEntryEnabled()) Tr.entry(tc, "firstRecordSequenceNumber", this); if (tc.isEntryEnabled()) Tr.exit(tc, "firstRecordSequenceNumber", new Long(_firstRecordSequenceNumber)); return _firstRecordSequenceNumber; }
java
public String serviceName() { if (tc.isEntryEnabled()) Tr.entry(tc, "serviceName", this); if (tc.isEntryEnabled()) Tr.exit(tc, "serviceName", _serviceName); return _serviceName; }
java
public int serviceVersion() { if (tc.isEntryEnabled()) Tr.entry(tc, "serviceVersion", this); if (tc.isEntryEnabled()) Tr.exit(tc, "serviceVersion", new Integer(_serviceVersion)); return _serviceVersion; }
java
public String logName() { if (tc.isEntryEnabled()) Tr.entry(tc, "logName", this); if (tc.isEntryEnabled()) Tr.exit(tc, "logName", _logName); return _logName; }
java
public byte[] getServiceData() { if (tc.isEntryEnabled()) Tr.entry(tc, "getServiceData", this); if (tc.isEntryEnabled()) Tr.exit(tc, "getServiceData", RLSUtils.toHexString(_serviceData, RLSUtils.MAX_DISPLAY_BYTES)); return _serviceData; }
java
public void setServiceData(byte[] serviceData) { if (tc.isEntryEnabled()) Tr.entry(tc, "setServiceData", new java.lang.Object[] { RLSUtils.toHexString(serviceData, RLSUtils.MAX_DISPLAY_BYTES), this }); _serviceData = serviceData; if (tc.isEntryEnabled()) Tr.exit(tc, "setServiceData"); }
java
public boolean compatible() { if (tc.isEntryEnabled()) Tr.entry(tc, "compatible", this); if (tc.isEntryEnabled()) Tr.exit(tc, "compatible", new Boolean(_compatible)); return _compatible; }
java
public boolean valid() { boolean valid = true; if (tc.isEntryEnabled()) Tr.entry(tc, "valid", this); if (_status == STATUS_INVALID) valid = false; if (tc.isEntryEnabled()) Tr.exit(tc, "valid", new Boolean(valid)); return valid; }
java
public int status() { if (tc.isEntryEnabled()) Tr.entry(tc, "status", this); if (tc.isEntryEnabled()) Tr.exit(tc, "status", new Integer(_status)); return _status; }
java
public void reset() { if (tc.isEntryEnabled()) Tr.entry(tc, "reset", this); _status = STATUS_ACTIVE; _date = 0; _firstRecordSequenceNumber = 0; _serverName = null; _serviceName = null; _serviceVersion = 0; _logName = null; _variableFieldData = initVariableFieldData(); _serviceData = null; if (tc.isEntryEnabled()) Tr.exit(tc, "reset"); }
java
public void changeStatus(int newStatus) { if (tc.isEntryEnabled()) Tr.entry(tc, "changeStatus", new java.lang.Object[] { this, new Integer(newStatus) }); _status = newStatus; if (tc.isEntryEnabled()) Tr.exit(tc, "changeStatus"); }
java
public void keypointStarting(long nextRecordSequenceNumber) { if (tc.isEntryEnabled()) Tr.entry(tc, "keypointStarting", new Object[] { this, new Long(nextRecordSequenceNumber) }); GregorianCalendar currentCal = new GregorianCalendar(); Date currentDate = currentCal.getTime(); _date = currentDate.getTime(); _firstRecordSequenceNumber = nextRecordSequenceNumber; _status = STATUS_KEYPOINTING; _variableFieldData = initVariableFieldData(); // if var field data was not previously set this is the first time it will become set if (tc.isEntryEnabled()) Tr.exit(tc, "keypointStarting"); }
java
public void keypointComplete() { if (tc.isEntryEnabled()) Tr.entry(tc, "keypointComplete", this); _status = STATUS_ACTIVE; if (tc.isEntryEnabled()) Tr.exit(tc, "keypointComplete"); }
java
static String statusToString(int status) { String result = null; if (status == STATUS_INACTIVE) { result = "INACTIVE"; } else if (status == STATUS_ACTIVE) { result = "ACTIVE"; } else if (status == STATUS_KEYPOINTING) { result = "KEYPOINTING"; } else if (status == STATUS_INVALID) { result = "INVALID"; } else { result = "UNKNOWN"; } return result; }
java
public TransactionCommon registerInBatch() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "registerInBatch"); _readWriteLock.lock(); // Register as a reader synchronized(this) // lock the state against other readers { if(_currentTran == null) _currentTran = _txManager.createLocalTransaction(false); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "registerInBatch", _currentTran); return _currentTran; }
java
public void messagesAdded(int msgCount, BatchListener listener) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "messagesAdded","msgCount="+msgCount+",listener="+listener); boolean completeBatch = false; try { synchronized(this) // lock the state against other readers { _currentBatchSize += msgCount; if((listener != null) && (!_listeners.contains(listener))) { // Remember that this listener needs calling when the batch completes _listeners.add(listener); } if(_currentBatchSize >= _batchSize) // Full batch, commit all updates { completeBatch = true; // We can't do this under the synchronize as the exclusive lock // we need will deadlock with reader's trying to get this } // synchronize before these release their shared lock else if ((_currentBatchSize - msgCount) == 0) // New batch so ensure a timer is running { startTimer(); } } } finally { _readWriteLock.unlock(); // release the read lock we took in registerInBatch } // Now we hold no locks we can try to complete he batch (this takes an exclusive lock if(completeBatch) { completeBatch(false); // false = only complete a full batch } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "messagesAdded"); }
java
public void completeBatch(boolean force, BatchListener finalListener) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "completeBatch","force="+force+",finalListener="+finalListener); _readWriteLock.lockExclusive(); // Lock the batchHandler exclusively try { // If force is true we complete the batch even if it isn't full, otherwise // we only complete a full batch (it's possible someone else got in before us and completed // the old batch before we got the lock). if( (force && (_currentBatchSize > 0)) || (_currentBatchSize >= _batchSize)) { Iterator itr = _listeners.iterator(); while(itr.hasNext()) { BatchListener listener = (BatchListener) itr.next(); listener.batchPrecommit(_currentTran); } if(finalListener != null) finalListener.batchPrecommit(_currentTran); boolean committed = false; Exception exceptionOnCommit = null; try { _currentTran.commit(); // Commit the current transaction (this'll drive all the CDs) committed = true; } catch(Exception e) { FFDCFilter.processException( e, "com.ibm.ws.sib.processor.impl.store.BatchHandler.completeBatch", "1:254:1.30", this); committed = false; SibTr.exception(tc, e); exceptionOnCommit = e; } // Clear the batch details under the lock _currentBatchSize = 0; _currentTran = null; // Commit or Rollback the listeners itr = _listeners.iterator(); while(itr.hasNext()) { BatchListener listener = (BatchListener) itr.next(); if(committed) listener.batchCommitted(); else listener.batchRolledBack(); itr.remove(); } if(finalListener != null) { if(committed) finalListener.batchCommitted(); else finalListener.batchRolledBack(); } // If the commit threw an exception, pass it back now if(exceptionOnCommit != null) { //Release exclusive lock on the batch or everything grinds //to a halt _readWriteLock.unlockExclusive(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "completeBatch", exceptionOnCommit); throw new SIResourceException(exceptionOnCommit); } // Ensure any running timer is cancelled cancelTimer(); } else // Nothing transacted to do but still need to call finalListener to cleanup { if(finalListener != null) finalListener.batchCommitted(); } } finally { _readWriteLock.unlockExclusive(); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "completeBatch"); }
java
public void alarm (Object alarmContext) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "alarm", alarmContext); synchronized(this) { _alarm = null; } try { completeBatch(true); } catch(SIException e) { //No FFDC code needed SibTr.exception(this, tc, e); //can't do anything else here } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "alarm"); }
java
private void parseIDFromURL(RequestMessage request) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Looking for ID in URL"); } String url = request.getRawRequestURI(); String target = getSessionConfig().getURLRewritingMarker(); URLParser parser = new URLParser(url, target); if (-1 != parser.idMarker) { // session id marker was found, try to pull out the value int start = parser.idMarker + target.length(); if (-1 != parser.fragmentMarker) { this.id = url.substring(start, parser.fragmentMarker); } else if (-1 != parser.queryMarker) { this.id = url.substring(start, parser.queryMarker); } else { this.id = url.substring(start); } this.fromURL = true; } }
java
public static String encodeURL(String url, SessionInfo info) { // could be /path/page#fragment?query // could be /page/page;session=existing#fragment?query // where fragment and query are both optional HttpSession session = info.getSession(); if (null == session) { return url; } final String id = session.getId(); final String target = info.getSessionConfig().getURLRewritingMarker(); URLParser parser = new URLParser(url, target); StringBuilder sb = new StringBuilder(); if (-1 != parser.idMarker) { // a session exists in the URL, overlay this ID sb.append(url); int start = parser.idMarker + target.length(); if (start + 23 < url.length()) { sb.replace(start, start + 23, id); } else { // invalid length on existing session, just remove that // TODO: what if a fragment or query string was after the // invalid session data sb.setLength(parser.idMarker); sb.append(target).append(id); } } else { // add session data to the URL if (-1 != parser.fragmentMarker) { // prepend it before the uri fragment sb.append(url, 0, parser.fragmentMarker); sb.append(target).append(id); sb.append(url, parser.fragmentMarker, url.length()); } else if (-1 != parser.queryMarker) { // prepend it before the query data sb.append(url, 0, parser.queryMarker); sb.append(target).append(id); sb.append(url, parser.queryMarker, url.length()); } else { // just a uri sb.append(url).append(target).append(id); } } return sb.toString(); }
java
public static String stripURL(String url, SessionInfo info) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Removing any session id from [" + url + "]"); } String target = info.getSessionConfig().getURLRewritingMarker(); URLParser parser = new URLParser(url, target); if (-1 != parser.idMarker) { // the parser found an id marker, see if we need to include // any trailing fragment or query data StringBuilder sb = new StringBuilder(url.substring(0, parser.idMarker)); if (-1 != parser.fragmentMarker) { sb.append(url.substring(parser.fragmentMarker)); } else if (-1 != parser.queryMarker) { sb.append(url.substring(parser.queryMarker)); } return sb.toString(); } return url; }
java
private void parseIDFromCookies(RequestMessage request) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Looking for ID in cookies"); } Enumeration<String> list = request.getHeaders("Cookie"); while (list.hasMoreElements()) { String item = list.nextElement(); int index = item.indexOf(getSessionConfig().getIDName()); if (-1 != index) { index = item.indexOf('=', index); if (-1 != index) { index++; // TODO this is assuming that the full value is valid and // grabbing just the 4 digit id... if (item.length() >= (index + 4)) { this.id = item.substring(index, index + 4); this.fromCookie = true; break; } } } } }
java
public static Cookie encodeCookie(SessionInfo info) { // create a cookie using the configuration information HttpSession session = info.getSession(); SessionConfig config = info.getSessionConfig(); Cookie cookie = new Cookie( config.getIDName(), config.getSessionVersion() + session.getId()); cookie.setSecure(config.isCookieSecure()); cookie.setMaxAge(config.getCookieMaxAge()); cookie.setPath(config.getCookiePath()); cookie.setDomain(config.getCookieDomain()); return cookie; }
java
public HttpSession getSession(boolean create) { if (null != this.mySession) { if (this.mySession.isInvalid()) { this.mySession = null; } else { return this.mySession; } } this.mySession = mgr.getSession(this, create); return this.mySession; }
java
public int get_searchScope() { int searchScope = SearchControls.OBJECT_SCOPE; String scopeBuf = get_scope(); if (scopeBuf != null) { if (scopeBuf.compareToIgnoreCase("base") == 0) { searchScope = SearchControls.OBJECT_SCOPE; } else if (scopeBuf.compareToIgnoreCase("one") == 0) { searchScope = SearchControls.ONELEVEL_SCOPE; } else if (scopeBuf.compareToIgnoreCase("sub") == 0) { searchScope = SearchControls.SUBTREE_SCOPE; } } return searchScope; }
java
public PersistenceUnitTransactionType getTransactionType() { // Convert this TransactionType from the class defined in JAXB // (com.ibm.ws.jpa.pxml21.PersistenceUnitTransactionType) to JPA // (javax.persistence.spi.PersistenceUnitTransactionType). PersistenceUnitTransactionType rtnType = null; com.ibm.ws.jpa.pxml21.PersistenceUnitTransactionType jaxbType = null; jaxbType = ivPUnit.getTransactionType(); if (jaxbType == com.ibm.ws.jpa.pxml21.PersistenceUnitTransactionType.JTA) { rtnType = PersistenceUnitTransactionType.JTA; } else if (jaxbType == com.ibm.ws.jpa.pxml21.PersistenceUnitTransactionType.RESOURCE_LOCAL) { rtnType = PersistenceUnitTransactionType.RESOURCE_LOCAL; } return rtnType; }
java
public static boolean copyModuleMetaDataSlot(MetaDataEvent<ModuleMetaData> event, MetaDataSlot slot) { Container container = event.getContainer(); MetaData metaData = event.getMetaData(); try { // For now, we just need to copy from WebModuleInfo, and ClientModuleInfo // Supports EJB in WAR and ManagedBean in Client ExtendedModuleInfo moduleInfo = (ExtendedModuleInfo) container.adapt(NonPersistentCache.class).getFromCache(WebModuleInfo.class); if (moduleInfo == null) { moduleInfo = (ExtendedModuleInfo) container.adapt(NonPersistentCache.class).getFromCache(ClientModuleInfo.class); } if (moduleInfo != null) { ModuleMetaData primaryMetaData = moduleInfo.getMetaData(); if (metaData != primaryMetaData) { Object slotData = primaryMetaData.getMetaData(slot); if (slotData == null) { // The caller is required to populate slot data. throw new IllegalStateException(); } metaData.setMetaData(slot, slotData); return true; } } } catch (UnableToAdaptException e) { throw new UnsupportedOperationException(e); } return false; }
java
private static Object injectAndPostConstruct(Object injectionProvider, Class Klass, List injectedBeanStorage) { Object instance = null; if (injectionProvider != null) { try { Object managedObject = _FactoryFinderProviderFactory.INJECTION_PROVIDER_INJECT_CLASS_METHOD.invoke(injectionProvider, Klass); instance = _FactoryFinderProviderFactory.MANAGED_OBJECT_GET_OBJECT_METHOD.invoke(managedObject, null); if (instance != null) { Object creationMetaData = _FactoryFinderProviderFactory.MANAGED_OBJECT_GET_CONTEXT_DATA_METHOD.invoke (managedObject, CreationalContext.class); addBeanEntry(instance, creationMetaData, injectedBeanStorage); _FactoryFinderProviderFactory.INJECTION_PROVIDER_POST_CONSTRUCT_METHOD.invoke( injectionProvider, instance, creationMetaData); } } catch (Exception ex) { throw new FacesException(ex); } } return instance; }
java
private Collection<String> getCollectionFromSpaceSplitString(String stringValue) { //@special handling for @all, @none, @form and @this if (stringValue.equals(VAL_FORM)) { return VAL_FORM_LIST; } else if (stringValue.equals(VAL_ALL)) { return VAL_ALL_LIST; } else if (stringValue.equals(VAL_NONE)) { return VAL_NONE_LIST; } else if (stringValue.equals(VAL_THIS)) { return VAL_THIS_LIST; } // not one of the "normal" values - split it and return the Collection String[] arrValue = stringValue.split(" "); return Arrays.asList(arrValue); }
java
public static void traceSetTxCommon(int opType, String txId, String desc) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { StringBuffer sbuf = new StringBuffer(); sbuf .append(TxLifeCycle_Set_Tx_Type_Str).append(DataDelimiter) .append(TxLifeCycle_Set_Tx_Type).append(DataDelimiter) .append(opType).append(DataDelimiter) .append(txId).append(DataDelimiter) .append(desc); Tr.debug(tc, sbuf.toString()); } }
java
public static void traceCommon(int opType, String txId, String desc) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { StringBuffer sbuf = new StringBuffer(); sbuf .append(TxLifeCycle_State_Type_Str).append(DataDelimiter) .append(TxLifeCycle_State_Type).append(DataDelimiter) .append(opType).append(DataDelimiter) .append(txId).append(DataDelimiter) .append(desc); Tr.debug(tc, sbuf.toString()); } }
java
synchronized private JaspiConfig readConfigFile(final File configFile) throws PrivilegedActionException { if (tc.isEntryEnabled()) Tr.entry(tc, "readConfigFile", new Object[] { configFile }); if (configFile == null) { // TODO handle persistence // String msg = MessageFormatHelper.getFormattedMessage(msgBundle, AdminConstants.MSG_JASPI_PERSISTENT_FILE, new Object[] { PersistenceManager.JASPI_CONFIG }); // throw new RuntimeException(msg); } PrivilegedExceptionAction<JaspiConfig> unmarshalFile = new PrivilegedExceptionAction<JaspiConfig>() { @Override public JaspiConfig run() throws Exception { JaspiConfig cfg = null; JAXBContext jc = JAXBContext.newInstance(JaspiConfig.class); Object obj = jc.createUnmarshaller().unmarshal(configFile); if (obj instanceof JaspiConfig) { cfg = (JaspiConfig) obj; } return cfg; } }; JaspiConfig jaspi = AccessController.doPrivileged(unmarshalFile); if (tc.isEntryEnabled()) Tr.exit(tc, "readConfigFile", jaspi); return jaspi; }
java
synchronized private void writeConfigFile(final JaspiConfig jaspiConfig) { if (tc.isEntryEnabled()) Tr.entry(tc, "writeConfigFile", new Object[] { jaspiConfig }); if (configFile == null) { // TODO handle persistence //String msg = MessageFormatHelper.getFormattedMessage(msgBundle, AdminConstants.MSG_JASPI_PERSISTENT_FILE, new Object[] { PersistenceManager.JASPI_CONFIG }); //throw new RuntimeException(msg); } PrivilegedExceptionAction<Object> marshalFile = new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { JAXBContext jc = JAXBContext.newInstance(JaspiConfig.class); Marshaller writer = jc.createMarshaller(); writer.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); writer.marshal(jaspiConfig, configFile); return null; } }; try { AccessController.doPrivileged(marshalFile); } catch (PrivilegedActionException e) { FFDCFilter.processException(e, this.getClass().getName() + ".writeConfigFile", "290", this); throw new RuntimeException("Unable to write " + configFile, e); } if (tc.isEntryEnabled()) Tr.exit(tc, "writeConfigFile"); }
java
public ProviderAuthenticationResult authenticate(HttpServletRequest req, HttpServletResponse res, ConvergedClientConfig clientConfig) { ProviderAuthenticationResult oidcResult = null; if (!isEndpointValid(clientConfig)) { return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED); } boolean isImplicit = false; if (Constants.IMPLICIT.equals(clientConfig.getGrantType())) { isImplicit = true; } String authzCode = null; String responseState = null; Hashtable<String, String> reqParameters = new Hashtable<String, String>(); // the code cookie was set earlier by the code that receives the very first redirect back from the provider. String encodedReqParams = CookieHelper.getCookieValue(req.getCookies(), ClientConstants.WAS_OIDC_CODE); OidcClientUtil.invalidateReferrerURLCookie(req, res, ClientConstants.WAS_OIDC_CODE); if (encodedReqParams != null && !encodedReqParams.isEmpty()) { boolean validCookie = validateReqParameters(clientConfig, reqParameters, encodedReqParams); if (validCookie) { authzCode = reqParameters.get(ClientConstants.CODE); responseState = reqParameters.get(ClientConstants.STATE); } else { // error handling oidcResult = new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED); Tr.error(tc, "OIDC_CLIENT_BAD_PARAM_COOKIE", new Object[] { encodedReqParams, clientConfig.getClientId() }); // CWWKS1745E return oidcResult; } } if (responseState != null) { // if flow was implicit, we'd have a grant_type of implicit and tokens on the params. String id_token = req.getParameter(Constants.ID_TOKEN); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "id_token:" + id_token); } if (id_token != null) { reqParameters.put(Constants.ID_TOKEN, id_token); } String access_token = req.getParameter(Constants.ACCESS_TOKEN); if (access_token != null) { reqParameters.put(Constants.ACCESS_TOKEN, access_token); } if (req.getMethod().equals("POST") && req instanceof IExtendedRequest) { ((IExtendedRequest) req).setMethod("GET"); } } if (responseState == null) { oidcResult = handleRedirectToServer(req, res, clientConfig); // first time through, we go here. } else if (isImplicit) { oidcResult = handleImplicitFlowTokens(req, res, responseState, clientConfig, reqParameters); } else { // confirm the code and go get the tokens if it's good. AuthorizationCodeHandler authzCodeHandler = new AuthorizationCodeHandler(sslSupport); oidcResult = authzCodeHandler.handleAuthorizationCode(req, res, authzCode, responseState, clientConfig); } if (oidcResult.getStatus() != AuthResult.REDIRECT_TO_PROVIDER) { // restore post param. // Even the status is bad, it's OK to restore, since it will not // have any impact WebAppSecurityConfig webAppSecConfig = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig(); PostParameterHelper pph = new PostParameterHelper(webAppSecConfig); pph.restore(req, res, true); OidcClientUtil.invalidateReferrerURLCookies(req, res, OIDC_COOKIES); } return oidcResult; }
java
public String getRedirectUrlFromServerToClient(String clientId, String contextPath, String redirectToRPHostAndPort) { String redirectURL = null; if (redirectToRPHostAndPort != null && redirectToRPHostAndPort.length() > 0) { try { final String fHostPort = redirectToRPHostAndPort; @SuppressWarnings({ "unchecked", "rawtypes" }) URL url = (URL) java.security.AccessController.doPrivileged(new java.security.PrivilegedExceptionAction() { @Override public Object run() throws Exception { return new URL(fHostPort); } }); int port = url.getPort(); String path = url.getPath(); if (path == null) path = ""; if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } String entryPoint = path + contextPath + "/redirect/" + clientId; redirectURL = url.getProtocol() + "://" + url.getHost() + (port > 0 ? ":" + port : ""); redirectURL = redirectURL + (entryPoint.startsWith("/") ? "" : "/") + entryPoint; } catch (Exception e) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "the value of redirectToRPHostAndPort might not valid. Please verify that the format is <protocol>://<host>:<port> " + redirectToRPHostAndPort + "\n" + e.getMessage()); } } } return redirectURL; }
java
@FFDCIgnore({ IndexOutOfBoundsException.class }) public boolean validateReqParameters(ConvergedClientConfig clientConfig, Hashtable<String, String> reqParameters, String cookieValue) { boolean validCookie = true; String encoded = null; String cookieName = "WASOidcCode"; String requestParameters = null; try { int lastindex = cookieValue.lastIndexOf("_"); if (lastindex < 1) { if (tc.isDebugEnabled()) { Tr.debug(tc, "The cookie may have been tampered with."); if (lastindex < 0) { Tr.debug(tc, "The cookie does not contain an underscore."); } if (lastindex == 0) { Tr.debug(tc, "The cookie does not contain a value before the underscore."); } } return false; } encoded = cookieValue.substring(0, lastindex); String testCookie = OidcClientUtil.calculateOidcCodeCookieValue(encoded, clientConfig); if (!cookieValue.equals(testCookie)) { String msg = "The value for the OIDC state cookie [" + cookieName + "] failed validation."; if (tc.isDebugEnabled()) { Tr.debug(tc, msg); } validCookie = false; } } catch (IndexOutOfBoundsException e) { // anything wrong indicated the requestParameter cookie is not right or is not in right format validCookie = false; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "unexpected exception:", e); } } if (validCookie) { requestParameters = Base64Coder.toString(Base64Coder.base64DecodeString(encoded)); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "decodedRequestParameters:" + requestParameters); } JsonParser parser = new JsonParser(); JsonObject jsonObject = (JsonObject) parser.parse(requestParameters); Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet(); for (Map.Entry<String, JsonElement> entry : entries) { String key = entry.getKey(); JsonElement element = entry.getValue(); if (element.isJsonObject() || element.isJsonPrimitive()) { reqParameters.put(key, element.getAsString()); if (tc.isDebugEnabled()) { Tr.debug(tc, "parameterKey:" + key + " value:" + element.getAsString()); } } else { // this should not happen if (tc.isDebugEnabled()) { Tr.debug(tc, "unexpected json element:" + element.getClass().getName()); } validCookie = false; } } } return validCookie; }
java
public Boolean verifyState(HttpServletRequest req, HttpServletResponse res, String responseState, ConvergedClientConfig clientConfig) { if (responseState.length() < OidcUtil.STATEVALUE_LENGTH) { return false; // the state does not even match the length, the verification failed } long clockSkewMillSeconds = clientConfig.getClockSkewInSeconds() * 1000; long allowHandleTimeMillSeconds = (clientConfig.getAuthenticationTimeLimitInSeconds() * 1000) + clockSkewMillSeconds; // allow 7 minutes plust clockSkew javax.servlet.http.Cookie[] cookies = req.getCookies(); String cookieName = ClientConstants.WAS_OIDC_STATE_KEY + HashUtils.getStrHashCode(responseState); String stateKey = CookieHelper.getCookieValue(cookies, cookieName); // this could be null if used OidcClientUtil.invalidateReferrerURLCookie(req, res, cookieName); String cookieValue = HashUtils.createStateCookieValue(clientConfig, responseState); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "stateKey:'" + stateKey + "' cookieValue:'" + cookieValue + "'"); } if (cookieValue.equals(stateKey)) { long lNumber = OidcUtil.convertNormalizedTimeStampToLong(responseState); long lDate = (new Date()).getTime(); // lDate can not be earlier than lNumber by clockSkewMillSeconds // lDate can not be later than lNumber by clockSkewMllSecond + allowHandleTimeSeconds long difference = lDate - lNumber; if (difference < 0) { difference *= -1; if (difference >= clockSkewMillSeconds) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "error current: " + lDate + " ran at:" + lNumber); } } return difference < clockSkewMillSeconds; } else { if (difference >= allowHandleTimeMillSeconds) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "error current: " + lDate + " ran at:" + lNumber); } } return difference < allowHandleTimeMillSeconds; } } return false; }
java
void update(Dictionary<String, Object> props) { if (deleted) { return; } final String instancePid = (String) props.get("service.pid"); final String instanceId = (String) props.get("id"); if (instanceId == null) { Tr.error(tc, "cls.library.id.missing"); } if (libraryListenersTracker == null) { //set up a tracker for notification listeners for this library Filter listenerFilter = null; // To better support parent first nested config, also filter on libraryRef, // which will be a list of pid (or, if cardinality=0, then just a pid). try { listenerFilter = FrameworkUtil.createFilter("(&(objectClass=" + LibraryChangeListener.class.getName() + ")(|(library=" + instanceId + ")(libraryRef=*" + instancePid + "*)))"); } catch (InvalidSyntaxException e) { //auto FFDC because the syntax shouldn't be wrong! Tr.error(tc, "cls.library.id.invalid", instanceId, e.toString()); } ServiceTracker<LibraryChangeListener, LibraryChangeListener> tracker; tracker = new ServiceTracker<LibraryChangeListener, LibraryChangeListener>(this.ctx, listenerFilter, null); tracker.open(); libraryListenersTracker = tracker; } LibraryGeneration nextGen; synchronized (generationLock) { nextGen = nextGeneration; if (nextGen != null) { // there is already a new generation in the process of being updated. // since it is using stale properties we want to cancel that generation // and start a new one. nextGeneration = null; nextGen.cancel(); } nextGeneration = nextGen = new LibraryGeneration(this, instanceId, props); } nextGen.fetchFilesets(); }
java
public void mapFunction( String prefix, String fnName, final Class c, final String methodName, final Class[] args ) { //192474 start //We can get in to this method with null parameters if a JSP was compiled against the jsp-2.3 feature but running in a jsp-2.2 server. //This check is needed for the temporary JspClassInformation created in AbstractJSPExtensionServletWrapper class. if (fnName == null) { return; } //192474 end java.lang.reflect.Method method; if (System.getSecurityManager() != null){ try{ method = (java.lang.reflect.Method)AccessController.doPrivileged(new PrivilegedExceptionAction(){ public Object run() throws Exception{ return c.getDeclaredMethod(methodName, args); } }); } catch (PrivilegedActionException ex){ throw new RuntimeException( "Invalid function mapping - no such method: " + ex.getException().getMessage()); } } else { try { method = c.getDeclaredMethod(methodName, args); } catch( NoSuchMethodException e ) { throw new RuntimeException( "Invalid function mapping - no such method: " + e.getMessage()); } } this.fnmap.put( prefix + ":" + fnName, method ); }
java
void add(int event) { int b = bits.addAndGet(event); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(this, tc, "add " + event + ", polling state: " + b); }
java
boolean addAndCheckIfReady(int event) { int b = bits.addAndGet(event); boolean isReady = b == READY_WITHOUT_SIGNAL || b == READY_WITH_UNNECESSARY_SIGNAL || b == READY_WITH_SIGNAL; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(this, tc, "addAndCheckIfReady " + event + ", polling state: " + b + ", " + isReady); return isReady; }
java
public int getTransactionTimeout() throws XAException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getTransactionTimeout"); int timeout = 0; try { CommsByteBuffer request = getCommsByteBuffer(); request.putInt(getTransactionId()); CommsByteBuffer reply = jfapExchange(request, JFapChannelConstants.SEG_XA_GETTXTIMEOUT, JFapChannelConstants.PRIORITY_MEDIUM, true); try { reply.checkXACommandCompletionStatus(JFapChannelConstants.SEG_XA_GETTXTIMEOUT_R, getConversation()); timeout = reply.getInt(); } finally { if (reply != null) reply.release(); } } catch (XAException xa) { // No FFDC Code needed // Simply re-throw... throw xa; } catch (Exception e) { FFDCFilter.processException(e, CLASS_NAME + ".getTransactionTimeout", CommsConstants.SIXARESOURCEPROXY_GETTXTIMEOUT_01, this); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Caught a comms problem:", e); throw new XAException(XAException.XAER_RMFAIL); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getTransactionTimeout", ""+timeout); return timeout; }
java
private HashMap<Xid, SIXAResourceProxy> getLinkLevelXAResourceMap() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getLinkLevelXAResourceMap"); HashMap<Xid, SIXAResourceProxy> map = ((ClientLinkLevelState)getConversation().getLinkLevelAttachment()).getXidToXAResourceMap(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getLinkLevelXAResourceMap", map); return map; }
java
private String replaceCharacters(String name) { name = name.replaceAll("&gt;", ">"); name = name.replaceAll("&lt;", "<"); name = name.replaceAll("&amp;", "&"); name = name.replaceAll("<\\%", "<%"); name = name.replaceAll("%\\>", "%>"); return name; }
java
private boolean handleCaseSensitivityCheck(String path, boolean checkWEBINF) throws IOException { if (System.getSecurityManager() != null) { final String tmpPath = path; final boolean tmpCheckWEBINF = checkWEBINF; //PK81387 try { return ((Boolean) AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws IOException { return _handleCaseSensitivityCheck(tmpPath, tmpCheckWEBINF); //PK81387 added tmpCheckWEBINF param } })).booleanValue(); } catch (PrivilegedActionException pae) { throw (IOException) pae.getException(); } } else { return (_handleCaseSensitivityCheck(path, checkWEBINF)).booleanValue(); //PK81387 added checkWEBINF param } }
java
public final void nameSpace (String namespace) { if (namespace == null || namespace.equals("")) { _namespace = ""; } else { _namespace = namespace + ":"; } }
java
public final void write(Throwable e) throws IOException { indent(); newLine(); write(e.toString()); StackTraceElement[] elements = e.getStackTrace(); for (int i = 0; i < elements.length; i++) { newLine(); write(elements[i].toString()); } Throwable cause = e.getCause(); if (cause != null) { newLine(); write(cause.toString()); } outdent(); }
java
public PublicKey getPublicKeyFromJwk(String kid, String x5t, boolean useSystemPropertiesForHttpClientConnections) throws PrivilegedActionException, IOException, KeyStoreException, InterruptedException { return getPublicKeyFromJwk(kid, x5t, null, useSystemPropertiesForHttpClientConnections); }
java
@FFDCIgnore({ KeyStoreException.class }) public PublicKey getPublicKeyFromJwk(String kid, String x5t, String use, boolean useSystemPropertiesForHttpClientConnections) throws PrivilegedActionException, IOException, KeyStoreException, InterruptedException { PublicKey key = null; KeyStoreException errKeyStoreException = null; InterruptedException errInterruptedException = null; boolean isHttp = remoteHttpCall(this.jwkEndpointUrl, this.publicKeyText, this.keyLocation); try { if (isHttp) { key = this.getJwkRemote(kid, x5t, use , useSystemPropertiesForHttpClientConnections); } else { key = this.getJwkLocal(kid, x5t, publicKeyText, keyLocation, use); } } catch (KeyStoreException e) { errKeyStoreException = e; } catch (InterruptedException e) { errInterruptedException = e; } if (key == null) { if (errKeyStoreException != null) { throw errKeyStoreException; } if (errInterruptedException != null) { throw errInterruptedException; } } return key; }
java
@FFDCIgnore({ PrivilegedActionException.class }) protected InputStream getInputStream(final File f, String fileSystemSelector, String location, String classLoadingSelector ) throws IOException { // check file system first like we used to do if (f != null) { InputStream is = null; try { is = (FileInputStream) AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { if (f.exists()) { return new FileInputStream(f); } else { return null; } } }); } catch (PrivilegedActionException e1) { } if (is != null) { locationUsed = fileSystemSelector; if (tc.isDebugEnabled()) { Tr.debug(tc, "input stream obtained from file system and locationUsed set to: "+ locationUsed); } return is; } } // do the expensive classpath search // performant: we're avoiding calling getResource if entry was previously cached. URL u = Thread.currentThread().getContextClassLoader().getResource(location); locationUsed = classLoadingSelector; if (tc.isDebugEnabled()) { Tr.debug(tc, "input stream obtained from classloader and locationUsed set to: "+ locationUsed); } if (u != null) { return u.openStream(); } return null; }
java
public boolean parseJwk(String keyText, FileInputStream inputStream, JWKSet jwkset, String signatureAlgorithm) { boolean bJwk = false; if (keyText != null) { bJwk = parseKeyText(keyText, locationUsed, jwkset, signatureAlgorithm); } else if (inputStream != null) { String keyAsString = getKeyAsString(inputStream); bJwk = parseKeyText(keyAsString, locationUsed, jwkset, signatureAlgorithm); } return bJwk; }
java
@Override public CompletableFuture<T> newIncompleteFuture() { if (JAVA8) return new ManagedCompletionStage<T>(new CompletableFuture<T>(), defaultExecutor, null); else return new ManagedCompletionStage<T>(defaultExecutor); }
java
@Override @SuppressWarnings("hiding") @Trivial <T> CompletableFuture<T> newInstance(CompletableFuture<T> completableFuture, Executor managedExecutor, FutureRefExecutor futureRef) { return new ManagedCompletionStage<T>(completableFuture, managedExecutor, futureRef); }
java
public void becomeCloneOf(ManagedObject other) { final String methodName = "becomeCloneOf"; if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.entry(this, cclass, methodName, other); //!! See transactionDeleteLogRecord as to why this is necessary. //!! The dummy is used where we need to delete something in recovery that is already deleted. //!! Unfortunately a rollback of the original after an OptimisticReplace //!! during recovery will cause classCastException /* * !! DummyManagedObject dummyManagedObject = (DummyManagedObject)other; name = dummyManagedObject.name; !! */ if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.exit(this, cclass, methodName); }
java
private boolean setState(State newState) { switch (newState) { case DEPLOYED: return changeState(State.DEPLOYING, State.DEPLOYED); case DEPLOYING: //can move from either UNDEPLOYED or FAILED into DEPLOYING state return (changeState(State.UNDEPLOYED, State.DEPLOYING) || changeState(State.FAILED, State.DEPLOYING)); case UNDEPLOYING: return changeState(State.DEPLOYED, State.UNDEPLOYING); case UNDEPLOYED: return changeState(State.UNDEPLOYING, State.UNDEPLOYED); case FAILED: return changeState(State.DEPLOYING, State.FAILED); default: return false; } }
java
Event createFailedEvent(Throwable t) { synchronized (terminated) { if (terminated.get()) { return null; } if (setState(State.FAILED)) { installer.removeWabFromEligibleForCollisionResolution(this); installer.attemptRedeployOfPreviouslyCollidedContextPath(this.wabContextPath); return createEvent(State.FAILED, t, null, null); } } return null; }
java
Event createFailedEvent(String collisionContext, long[] cIds) { synchronized (terminated) { if (terminated.get()) { return null; } if (setState(State.FAILED)) return createEvent(State.FAILED, null, collisionContext, cIds); } return null; }
java
@Override @Trivial public WAB addingBundle(Bundle bundle, BundleEvent event) { //the bundle is in STARTING | ACTIVE state because of our state mask //only action work for the bundle represented by this WAB. if (bundle.getBundleId() == wabBundleId) { //sync lock inside bundle id check to avoid locking on every bundle! synchronized (terminated) { if (terminated.get()) { installer.wabLifecycleDebug("SubTracker unable to add bundle, as has been terminated.", this, bundle.getBundleId()); //if we are terminated, then the WABGroup will be handling the uninstall //and state transitions.. so it's important not to get involved here. return null; } installer.wabLifecycleDebug("SubTracker adding bundle.", this); //only deploy the wab, if the state is still deploying.. //it pretty much should be.. if (getState() == State.DEPLOYING) { installer.wabLifecycleDebug("SubTracker adding WAB to WebContainer", this); //the holder will already have the wab in its list from construction //no collision, just add to the web container - only return the WAB tracked object if successful return addToWebContainer() ? WAB.this : null; } else { return null; } } } else { return null; } }
java
public static String identityToString(Object o) { return o == null ? null : o.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(o)); }
java