This is an automated email from the ASF dual-hosted git repository.
veithen pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ws-axiom.git
The following commit(s) were added to refs/heads/master by this push:
new 586feaadb Enforce consistent formatting in axiom-legacy-attachments
586feaadb is described below
commit 586feaadb26ab0c55c383d8d56bfd184f12ec128
Author: Andreas Veithen <[email protected]>
AuthorDate: Sat Jan 10 22:13:28 2026 +0000
Enforce consistent formatting in axiom-legacy-attachments
---
axiom-legacy-attachments/pom.xml | 11 +
.../axiom/attachments/AttachmentCacheMonitor.java | 169 ++++-----
.../apache/axiom/attachments/AttachmentSet.java | 11 +-
.../org/apache/axiom/attachments/Attachments.java | 236 +++++++-----
.../axiom/attachments/AttachmentsDelegate.java | 32 +-
.../axiom/attachments/ByteArrayDataSource.java | 7 +-
.../axiom/attachments/CachedFileDataSource.java | 31 +-
.../axiom/attachments/ConfigurableDataHandler.java | 95 +++--
.../attachments/IncomingAttachmentInputStream.java | 39 +-
.../attachments/IncomingAttachmentStreams.java | 17 +-
.../axiom/attachments/LegacyPartDataHandler.java | 2 +-
.../axiom/attachments/LegacyTempFileBlob.java | 2 +-
.../axiom/attachments/MultipartBodyAdapter.java | 55 +--
.../attachments/lifecycle/DataHandlerExt.java | 42 +--
.../attachments/lifecycle/LifecycleManager.java | 34 +-
.../attachments/lifecycle/impl/FileAccessor.java | 30 +-
.../lifecycle/impl/LifecycleEventDefinitions.java | 1 -
.../lifecycle/impl/LifecycleEventHandler.java | 22 +-
.../lifecycle/impl/LifecycleManagerImpl.java | 98 +++--
.../attachments/lifecycle/impl/VMShutdownHook.java | 49 +--
.../attachments/AttachmentCacheMonitorTest.java | 15 +-
.../apache/axiom/attachments/AttachmentsTest.java | 408 ++++++++++++---------
.../attachments/ConfigurableDataHandlerTest.java | 40 +-
.../axiom/attachments/MyLifecycleManager.java | 2 +-
.../apache/axiom/attachments/PartOnFileTest.java | 11 +-
.../attachments/PdfAttachmentStreamingTest.java | 79 ++--
.../java/org/apache/axiom/om/AbstractTestCase.java | 16 +-
27 files changed, 857 insertions(+), 697 deletions(-)
diff --git a/axiom-legacy-attachments/pom.xml b/axiom-legacy-attachments/pom.xml
index b8eb7c280..31df42b26 100644
--- a/axiom-legacy-attachments/pom.xml
+++ b/axiom-legacy-attachments/pom.xml
@@ -135,6 +135,17 @@
</instructions>
</configuration>
</plugin>
+ <plugin>
+ <groupId>com.spotify.fmt</groupId>
+ <artifactId>fmt-maven-plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
</project>
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/AttachmentCacheMonitor.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/AttachmentCacheMonitor.java
index 7d3e40f52..464f7cf06 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/AttachmentCacheMonitor.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/AttachmentCacheMonitor.java
@@ -31,31 +31,29 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
- * The CacheMonitor is responsible for deleting temporary attachment files
- * after a timeout period has expired.
- *
- * The register method is invoked when the attachment file is created.
- * The access method is invoked whenever the attachment file is accessed.
- * The checkForAgedFiles method is invoked whenever the monitor should look
for
- * files to cleanup (delete).
- *
+ * The CacheMonitor is responsible for deleting temporary attachment files
after a timeout period
+ * has expired.
+ *
+ * <p>The register method is invoked when the attachment file is created. The
access method is
+ * invoked whenever the attachment file is accessed. The checkForAgedFiles
method is invoked
+ * whenever the monitor should look for files to cleanup (delete).
*/
public final class AttachmentCacheMonitor {
- static Log log =
- LogFactory.getLog(AttachmentCacheMonitor.class.getName());
+ static Log log = LogFactory.getLog(AttachmentCacheMonitor.class.getName());
// Setting this property puts a limit on the lifetime of a cache file
// The default is "0", which is interpreted as forever
// The suggested value is 300 seconds
- private int attachmentTimeoutSeconds = 0; // Default is 0 (forever)
+ private int attachmentTimeoutSeconds = 0; // Default is 0 (forever)
private int refreshSeconds = 0;
- public static final String ATTACHMENT_TIMEOUT_PROPERTY =
"org.apache.axiom.attachments.tempfile.expiration";
+ public static final String ATTACHMENT_TIMEOUT_PROPERTY =
+ "org.apache.axiom.attachments.tempfile.expiration";
// HashMap
// Key String = Absolute file name
// Value Long = Last Access Time
- private Map<String,Long> files = new HashMap<String,Long>();
+ private Map<String, Long> files = new HashMap<String, Long>();
// Delete detection is batched
private Long priorDeleteMillis = getTime();
@@ -64,9 +62,9 @@ public final class AttachmentCacheMonitor {
private static AttachmentCacheMonitor _singleton = null;
-
/**
* Get or Create an AttachmentCacheMonitor singleton
+ *
* @return the singleton instance
*/
public static synchronized AttachmentCacheMonitor
getAttachmentCacheMonitor() {
@@ -77,8 +75,8 @@ public final class AttachmentCacheMonitor {
}
/**
- * Constructor
- * Intentionally private. Callers should use getAttachmentCacheMonitor
+ * Constructor Intentionally private. Callers should use
getAttachmentCacheMonitor
+ *
* @see getAttachmentCacheMonitor
*/
private AttachmentCacheMonitor() {
@@ -88,10 +86,14 @@ public final class AttachmentCacheMonitor {
attachmentTimeoutSeconds = Integer.valueOf(value).intValue();
} catch (Throwable t) {
// Swallow exception and use default, but log a warning message
- if (log.isDebugEnabled()) {
- log.debug("The value of " + value + " was not valid.
The default " +
- attachmentTimeoutSeconds + " will be used
instead.");
- }
+ if (log.isDebugEnabled()) {
+ log.debug(
+ "The value of "
+ + value
+ + " was not valid. The default "
+ + attachmentTimeoutSeconds
+ + " will be used instead.");
+ }
}
refreshSeconds = attachmentTimeoutSeconds / 2;
@@ -101,23 +103,21 @@ public final class AttachmentCacheMonitor {
}
if (refreshSeconds > 0) {
- timer = new Timer( true );
- timer.schedule( new CleanupFilesTask(),
- refreshSeconds * 1000,
- refreshSeconds * 1000 );
+ timer = new Timer(true);
+ timer.schedule(new CleanupFilesTask(), refreshSeconds * 1000,
refreshSeconds * 1000);
}
}
-
+
/**
* @return timeout value in seconds
*/
public synchronized int getTimeout() {
- return attachmentTimeoutSeconds;
+ return attachmentTimeoutSeconds;
}
-
+
/**
- * This method should
- * Set a new timeout value
+ * This method should Set a new timeout value
+ *
* @param timeout new timeout value in seconds
*/
public synchronized void setTimeout(int timeout) {
@@ -125,59 +125,56 @@ public final class AttachmentCacheMonitor {
if (timeout == attachmentTimeoutSeconds) {
return;
}
-
- attachmentTimeoutSeconds = timeout;
-
- // Reset the refresh
- refreshSeconds = attachmentTimeoutSeconds / 2;
-
- // Make sure to cancel the prior timer
- if (timer != null) {
+
+ attachmentTimeoutSeconds = timeout;
+
+ // Reset the refresh
+ refreshSeconds = attachmentTimeoutSeconds / 2;
+
+ // Make sure to cancel the prior timer
+ if (timer != null) {
timer.cancel(); // Remove scheduled tasks from the prior timer
timer = null;
}
-
- // Make a new timer if necessary
+
+ // Make a new timer if necessary
if (refreshSeconds > 0) {
- timer = new Timer( true );
- timer.schedule( new CleanupFilesTask(),
- refreshSeconds * 1000,
- refreshSeconds * 1000 );
+ timer = new Timer(true);
+ timer.schedule(new CleanupFilesTask(), refreshSeconds * 1000,
refreshSeconds * 1000);
}
-
- if (log.isDebugEnabled()) {
- log.debug("New timeout = " + attachmentTimeoutSeconds);
- log.debug("New refresh = " + refreshSeconds);
+
+ if (log.isDebugEnabled()) {
+ log.debug("New timeout = " + attachmentTimeoutSeconds);
+ log.debug("New refresh = " + refreshSeconds);
}
}
/**
- * Register a file name with the monitor.
- * This will allow the Monitor to remove the file after
+ * Register a file name with the monitor. This will allow the Monitor to
remove the file after
* the timeout period.
+ *
* @param fileName
*/
- public void register(String fileName) {
- if (attachmentTimeoutSeconds > 0) {
+ public void register(String fileName) {
+ if (attachmentTimeoutSeconds > 0) {
_register(fileName);
_checkForAgedFiles();
}
}
-
+
/**
* Indicates that the file was accessed.
+ *
* @param fileName
*/
public void access(String fileName) {
- if (attachmentTimeoutSeconds > 0) {
+ if (attachmentTimeoutSeconds > 0) {
_access(fileName);
_checkForAgedFiles();
}
}
-
- /**
- * Check for aged files and remove the aged ones.
- */
+
+ /** Check for aged files and remove the aged ones. */
public void checkForAgedFiles() {
if (attachmentTimeoutSeconds > 0) {
_checkForAgedFiles();
@@ -188,7 +185,7 @@ public final class AttachmentCacheMonitor {
Long currentTime = getTime();
if (log.isDebugEnabled()) {
log.debug("Register file " + fileName);
- log.debug("Time = " + currentTime);
+ log.debug("Time = " + currentTime);
}
files.put(fileName, currentTime);
}
@@ -200,15 +197,19 @@ public final class AttachmentCacheMonitor {
files.put(fileName, currentTime);
if (log.isDebugEnabled()) {
log.debug("Access file " + fileName);
- log.debug("Old Time = " + priorTime);
- log.debug("New Time = " + currentTime);
+ log.debug("Old Time = " + priorTime);
+ log.debug("New Time = " + currentTime);
}
} else {
if (log.isDebugEnabled()) {
- log.debug("The following file was already deleted and is no
longer available: " +
- fileName);
- log.debug("The value of " + ATTACHMENT_TIMEOUT_PROPERTY +
- " is " + attachmentTimeoutSeconds);
+ log.debug(
+ "The following file was already deleted and is no
longer available: "
+ + fileName);
+ log.debug(
+ "The value of "
+ + ATTACHMENT_TIMEOUT_PROPERTY
+ + " is "
+ + attachmentTimeoutSeconds);
}
}
}
@@ -216,36 +217,33 @@ public final class AttachmentCacheMonitor {
private synchronized void _checkForAgedFiles() {
Long currentTime = getTime();
// Don't keep checking the map, only trigger
- // the checking if it is plausible that
+ // the checking if it is plausible that
// files will need to be deleted.
// I chose a value of ATTACHMENTT_TIMEOUT_SECONDS/4
- if (isExpired(priorDeleteMillis,
- currentTime,
- refreshSeconds)) {
+ if (isExpired(priorDeleteMillis, currentTime, refreshSeconds)) {
Iterator<String> it = files.keySet().iterator();
while (it.hasNext()) {
String fileName = it.next();
Long lastAccess = files.get(fileName);
- if (isExpired(lastAccess,
- currentTime,
- attachmentTimeoutSeconds)) {
+ if (isExpired(lastAccess, currentTime,
attachmentTimeoutSeconds)) {
if (log.isDebugEnabled()) {
log.debug("Expired file " + fileName);
- log.debug("Old Time = " + lastAccess);
- log.debug("New Time = " + currentTime);
- log.debug("Elapsed Time (ms) = " +
- (currentTime.longValue() -
lastAccess.longValue()));
+ log.debug("Old Time = " + lastAccess);
+ log.debug("New Time = " + currentTime);
+ log.debug(
+ "Elapsed Time (ms) = "
+ + (currentTime.longValue() -
lastAccess.longValue()));
}
deleteFile(fileName);
// Use the iterator to remove this
// file from the map (this avoids
// the dreaded ConcurrentModificationException
- it.remove();
- }
+ it.remove();
+ }
}
-
+
// Reset the prior delete time
priorDeleteMillis = currentTime;
}
@@ -267,25 +265,18 @@ public final class AttachmentCacheMonitor {
return ret;
}
-
private Long getTime() {
return new Long(System.currentTimeMillis());
}
- private boolean isExpired (Long oldTimeMillis,
- Long newTimeMillis,
- int thresholdSecs) {
- long elapse = newTimeMillis.longValue() -
- oldTimeMillis.longValue();
- return (elapse > (thresholdSecs*1000));
+ private boolean isExpired(Long oldTimeMillis, Long newTimeMillis, int
thresholdSecs) {
+ long elapse = newTimeMillis.longValue() - oldTimeMillis.longValue();
+ return (elapse > (thresholdSecs * 1000));
}
-
private class CleanupFilesTask extends TimerTask {
- /**
- * Trigger a checkForAgedFiles event
- */
+ /** Trigger a checkForAgedFiles event */
@Override
public void run() {
checkForAgedFiles();
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/AttachmentSet.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/AttachmentSet.java
index 8385d8688..9c392150c 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/AttachmentSet.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/AttachmentSet.java
@@ -36,7 +36,8 @@ import org.apache.axiom.om.OMException;
* attachment parts.
*/
class AttachmentSet extends AttachmentsDelegate {
- private final Map<String,DataHandler> attachmentsMap = new
LinkedHashMap<String,DataHandler>();
+ private final Map<String, DataHandler> attachmentsMap =
+ new LinkedHashMap<String, DataHandler>();
@Override
ContentType getContentType() {
@@ -52,7 +53,7 @@ class AttachmentSet extends AttachmentsDelegate {
void addDataHandler(String contentID, DataHandler dataHandler) {
attachmentsMap.put(contentID, dataHandler);
}
-
+
@Override
void removeDataHandler(String blobContentID) {
attachmentsMap.remove(blobContentID);
@@ -84,12 +85,12 @@ class AttachmentSet extends AttachmentsDelegate {
Set<String> getContentIDs(boolean fetchAll) {
return attachmentsMap.keySet();
}
-
+
@Override
- Map<String,DataHandler> getMap() {
+ Map<String, DataHandler> getMap() {
return Collections.unmodifiableMap(attachmentsMap);
}
-
+
@Override
long getContentLength() throws IOException {
return -1;
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/Attachments.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/Attachments.java
index 1d200ca45..90a613aca 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/Attachments.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/Attachments.java
@@ -25,7 +25,6 @@ import
org.apache.axiom.attachments.lifecycle.impl.LifecycleManagerImpl;
import org.apache.axiom.blob.Blob;
import org.apache.axiom.blob.Blobs;
import org.apache.axiom.blob.MemoryBlob;
-import org.apache.axiom.blob.WritableBlob;
import org.apache.axiom.blob.WritableBlobFactory;
import org.apache.axiom.ext.activation.SizeAwareDataSource;
import org.apache.axiom.mime.ContentType;
@@ -47,7 +46,7 @@ import java.util.Map;
public class Attachments implements OMAttachmentAccessor {
private final AttachmentsDelegate delegate;
-
+
/**
* <code>applicationType</code> used to distinguish between MTOM & SWA If
the message is MTOM
* optimised type is application/xop+xml If the message is SWA, type is
??have to find out
@@ -55,7 +54,7 @@ public class Attachments implements OMAttachmentAccessor {
private String applicationType;
private LifecycleManager manager;
-
+
public LifecycleManager getLifecycleManager() {
if (manager == null) {
manager = new LifecycleManagerImpl();
@@ -77,15 +76,27 @@ public class Attachments implements OMAttachmentAccessor {
* @param attachmentRepoDir
* @throws OMException
*/
- public Attachments(LifecycleManager manager, InputStream inStream, String
contentTypeString,
- boolean fileCacheEnable, String attachmentRepoDir,
- String fileThreshold) throws OMException {
- this(manager, inStream, contentTypeString, fileCacheEnable,
attachmentRepoDir, fileThreshold, 0);
+ public Attachments(
+ LifecycleManager manager,
+ InputStream inStream,
+ String contentTypeString,
+ boolean fileCacheEnable,
+ String attachmentRepoDir,
+ String fileThreshold)
+ throws OMException {
+ this(
+ manager,
+ inStream,
+ contentTypeString,
+ fileCacheEnable,
+ attachmentRepoDir,
+ fileThreshold,
+ 0);
}
-
- /**
- * Moves the pointer to the beginning of the first MIME part. Reads
- * till first MIME boundary is found or end of stream is reached.
+
+ /**
+ * Moves the pointer to the beginning of the first MIME part. Reads till
first MIME boundary is
+ * found or end of stream is reached.
*
* @param inStream
* @param contentTypeString
@@ -95,8 +106,15 @@ public class Attachments implements OMAttachmentAccessor {
* @param contentLength
* @throws OMException
*/
- public Attachments(LifecycleManager manager, InputStream inStream, String
contentTypeString, boolean fileCacheEnable,
- String attachmentRepoDir, String fileThreshold, int contentLength)
throws OMException {
+ public Attachments(
+ LifecycleManager manager,
+ InputStream inStream,
+ String contentTypeString,
+ boolean fileCacheEnable,
+ String attachmentRepoDir,
+ String fileThreshold,
+ int contentLength)
+ throws OMException {
this.manager = manager;
final int fileStorageThreshold;
if (fileThreshold != null && (!"".equals(fileThreshold))) {
@@ -106,18 +124,23 @@ public class Attachments implements OMAttachmentAccessor {
}
WritableBlobFactory<?> attachmentBlobFactory;
if (fileCacheEnable) {
- WritableBlobFactory<?> tempFileBlobFactory = new
LegacyTempFileBlobFactory(this, attachmentRepoDir);
+ WritableBlobFactory<?> tempFileBlobFactory =
+ new LegacyTempFileBlobFactory(this, attachmentRepoDir);
if (fileStorageThreshold > 0) {
- attachmentBlobFactory = () ->
Blobs.createOverflowableBlob(fileStorageThreshold, tempFileBlobFactory);
+ attachmentBlobFactory =
+ () ->
+ Blobs.createOverflowableBlob(
+ fileStorageThreshold,
tempFileBlobFactory);
} else {
attachmentBlobFactory = tempFileBlobFactory;
}
} else {
attachmentBlobFactory = MemoryBlob.FACTORY;
}
-
- delegate = new MultipartBodyAdapter(inStream, contentTypeString,
attachmentBlobFactory,
- contentLength);
+
+ delegate =
+ new MultipartBodyAdapter(
+ inStream, contentTypeString, attachmentBlobFactory,
contentLength);
}
/**
@@ -130,15 +153,26 @@ public class Attachments implements OMAttachmentAccessor {
* @param attachmentRepoDir
* @throws OMException
*/
- public Attachments(InputStream inStream, String contentTypeString,
- boolean fileCacheEnable, String attachmentRepoDir,
- String fileThreshold) throws OMException {
- this(null, inStream, contentTypeString, fileCacheEnable,
attachmentRepoDir, fileThreshold, 0);
+ public Attachments(
+ InputStream inStream,
+ String contentTypeString,
+ boolean fileCacheEnable,
+ String attachmentRepoDir,
+ String fileThreshold)
+ throws OMException {
+ this(
+ null,
+ inStream,
+ contentTypeString,
+ fileCacheEnable,
+ attachmentRepoDir,
+ fileThreshold,
+ 0);
}
-
- /**
- * Moves the pointer to the beginning of the first MIME part. Reads
- * till first MIME boundary is found or end of stream is reached.
+
+ /**
+ * Moves the pointer to the beginning of the first MIME part. Reads till
first MIME boundary is
+ * found or end of stream is reached.
*
* @param inStream
* @param contentTypeString
@@ -148,11 +182,24 @@ public class Attachments implements OMAttachmentAccessor {
* @param contentLength
* @throws OMException
*/
- public Attachments(InputStream inStream, String contentTypeString, boolean
fileCacheEnable,
- String attachmentRepoDir, String fileThreshold, int contentLength)
throws OMException {
- this(null, inStream, contentTypeString, fileCacheEnable,
- attachmentRepoDir, fileThreshold, contentLength);
+ public Attachments(
+ InputStream inStream,
+ String contentTypeString,
+ boolean fileCacheEnable,
+ String attachmentRepoDir,
+ String fileThreshold,
+ int contentLength)
+ throws OMException {
+ this(
+ null,
+ inStream,
+ contentTypeString,
+ fileCacheEnable,
+ attachmentRepoDir,
+ fileThreshold,
+ contentLength);
}
+
/**
* Sets file cache to false.
*
@@ -160,8 +207,7 @@ public class Attachments implements OMAttachmentAccessor {
* @param contentTypeString
* @throws OMException
*/
- public Attachments(InputStream inStream, String contentTypeString)
- throws OMException {
+ public Attachments(InputStream inStream, String contentTypeString) throws
OMException {
this(null, inStream, contentTypeString, false, null, null);
}
@@ -176,19 +222,19 @@ public class Attachments implements OMAttachmentAccessor {
/**
* Identify the type of message (MTOM or SOAP with attachments)
represented by this object. Note
* that this method is only meaningful if the instance was created from a
stream.
- *
- * @return One of the {@link MTOMConstants#MTOM_TYPE}, {@link
MTOMConstants#SWA_TYPE} or
- * {@link MTOMConstants#SWA_TYPE_12} constants.
- * @throws OMException
- * if the message doesn't have one of the supported types
(i.e. is neither MTOM nor
- * SOAP with attachments) or if the instance was not created
from a stream
+ *
+ * @return One of the {@link MTOMConstants#MTOM_TYPE}, {@link
MTOMConstants#SWA_TYPE} or {@link
+ * MTOMConstants#SWA_TYPE_12} constants.
+ * @throws OMException if the message doesn't have one of the supported
types (i.e. is neither
+ * MTOM nor SOAP with attachments) or if the instance was not created
from a stream
*/
public String getAttachmentSpecType() {
if (this.applicationType == null) {
ContentType contentType = delegate.getContentType();
if (contentType == null) {
- throw new OMException("Unable to determine the attachment spec
type because the " +
- "Attachments object doesn't have a known
content type");
+ throw new OMException(
+ "Unable to determine the attachment spec type because
the "
+ + "Attachments object doesn't have a known
content type");
}
applicationType = contentType.getParameter("type");
if ((MTOMConstants.MTOM_TYPE).equalsIgnoreCase(applicationType)) {
@@ -211,12 +257,11 @@ public class Attachments implements OMAttachmentAccessor {
* stream the content of the part. In addition, the {@link DataSource}
linked to the returned
* {@link DataHandler} MAY be of type {@link SizeAwareDataSource} in which
case the caller can
* use that interface to determine the size of the MIME part.
- *
- * @param contentID
- * the raw content ID (without the surrounding angle brackets
and {@code cid:}
- * prefix) of the MIME part
- * @return the {@link DataHandler} of the MIME part referred by the
content ID or
- * <code>null</code> if the MIME part referred by the content ID
does not exist
+ *
+ * @param contentID the raw content ID (without the surrounding angle
brackets and {@code cid:}
+ * prefix) of the MIME part
+ * @return the {@link DataHandler} of the MIME part referred by the
content ID or <code>null
+ * </code> if the MIME part referred by the content ID does not exist
*/
public DataHandler getDataHandler(String contentID) {
return delegate.getDataHandler(contentID);
@@ -244,32 +289,32 @@ public class Attachments implements OMAttachmentAccessor {
}
/**
- * @deprecated Use {@link #getRootPartInputStream()} instead.
+ * @deprecated Use {@link #getRootPartInputStream()} instead.
*/
public InputStream getSOAPPartInputStream() throws OMException {
return getRootPartInputStream();
}
-
+
/**
* @deprecated Use {@link #getRootPartContentID()} instead.
*/
public String getSOAPPartContentID() {
return getRootPartContentID();
}
-
+
/**
* @deprecated Use {@link #getRootPartContentType()} instead.
*/
public String getSOAPPartContentType() {
return getRootPartContentType();
}
-
+
/**
* Get an input stream for the root part of the MIME message. The root
part is located as
* described in the documentation of the {@link #getRootPartContentID()}
method. Note that a new
* stream is returned each time this method is called, i.e. the method
does not consume the root
* part. Instead it loads the root part into memory so that it can be read
several times.
- *
+ *
* @return the input stream for the root part
*/
public InputStream getRootPartInputStream() throws OMException {
@@ -277,18 +322,16 @@ public class Attachments implements OMAttachmentAccessor {
}
/**
- * Get an input stream for the root part of the MIME message. This method
is similar to
- * {@link #getRootPartInputStream()}, but can be instructed to consume the
root part. This
- * allows streaming of the root part. If that feature is used, the root
part will not be loaded
- * into memory unless an attempt is made to access another part of the
MIME message, in which
- * case the remaining (i.e. unconsumed) content of the root part will be
buffered. If the
- * feature is not enabled, then this method behaves in the same way as
- * {@link #getRootPartInputStream()}.
- *
- * @param preserve
- * <code>true</code> if the content of the root part should be
fetched into memory so
- * that it can be read several times, <code>false</code> if the
root part should be
- * consumed
+ * Get an input stream for the root part of the MIME message. This method
is similar to {@link
+ * #getRootPartInputStream()}, but can be instructed to consume the root
part. This allows
+ * streaming of the root part. If that feature is used, the root part will
not be loaded into
+ * memory unless an attempt is made to access another part of the MIME
message, in which case
+ * the remaining (i.e. unconsumed) content of the root part will be
buffered. If the feature is
+ * not enabled, then this method behaves in the same way as {@link
#getRootPartInputStream()}.
+ *
+ * @param preserve <code>true</code> if the content of the root part
should be fetched into
+ * memory so that it can be read several times, <code>false</code> if
the root part should
+ * be consumed
* @return the input stream for the root part
*/
public InputStream getRootPartInputStream(boolean preserve) throws
OMException {
@@ -298,12 +341,13 @@ public class Attachments implements OMAttachmentAccessor {
/**
* Get the content ID of the root part of the MIME message. This content
ID is determined as
* follows:
+ *
* <ul>
- * <li>If the content type of the MIME message has a {@code start}
parameter, then the content
- * ID will be extracted from that parameter.
- * <li>Otherwise the content ID of the first MIME part of the MIME message
is returned.
+ * <li>If the content type of the MIME message has a {@code start}
parameter, then the content
+ * ID will be extracted from that parameter.
+ * <li>Otherwise the content ID of the first MIME part of the MIME
message is returned.
* </ul>
- *
+ *
* @return the content ID of the root part (without the surrounding angle
brackets)
*/
public String getRootPartContentID() {
@@ -313,10 +357,9 @@ public class Attachments implements OMAttachmentAccessor {
/**
* Get the content type of the root part of the MIME message. The root
part is located as
* described in the documentation of the {@link #getRootPartContentID()}
method.
- *
+ *
* @return the content type of the root part
- * @throws OMException
- * if the content type could not be determined
+ * @throws OMException if the content type could not be determined
*/
public String getRootPartContentType() {
return delegate.getRootPartContentType();
@@ -328,17 +371,16 @@ public class Attachments implements OMAttachmentAccessor {
* @return The stream container of type
<code>IncomingAttachmentStreams</code>
* @throws IllegalStateException if application has alreadt started using
Part's directly
*/
- public IncomingAttachmentStreams getIncomingAttachmentStreams()
- throws IllegalStateException {
+ public IncomingAttachmentStreams getIncomingAttachmentStreams() throws
IllegalStateException {
return delegate.getIncomingAttachmentStreams();
}
/**
* Get the content IDs of all MIME parts in the message. This includes the
content ID of the
* SOAP part as well as the content IDs of the attachments. Note that if
this object has been
- * created from a stream, a call to this method will force reading of all
MIME parts that
- * have not been fetched from the stream yet.
- *
+ * created from a stream, a call to this method will force reading of all
MIME parts that have
+ * not been fetched from the stream yet.
+ *
* @return an array with the content IDs in order of appearance in the
message
*/
public String[] getAllContentIDs() {
@@ -349,47 +391,45 @@ public class Attachments implements OMAttachmentAccessor {
/**
* Get the content IDs of all MIME parts in the message. This includes the
content ID of the
* SOAP part as well as the content IDs of the attachments. Note that if
this object has been
- * created from a stream, a call to this method will force reading of all
MIME parts that
- * have not been fetched from the stream yet.
- *
+ * created from a stream, a call to this method will force reading of all
MIME parts that have
+ * not been fetched from the stream yet.
+ *
* @return the set of content IDs
*/
public Set<String> getContentIDSet() {
return delegate.getContentIDs(true);
}
-
+
/**
* Get a map of all MIME parts in the message. This includes the SOAP part
as well as the
- * attachments. Note that if this object has been created from a stream, a
call to this
- * method will force reading of all MIME parts that have not been fetched
from the stream yet.
- *
- * @return A map of all MIME parts in the message, with content IDs as
keys and
- * {@link DataHandler} objects as values.
+ * attachments. Note that if this object has been created from a stream, a
call to this method
+ * will force reading of all MIME parts that have not been fetched from
the stream yet.
+ *
+ * @return A map of all MIME parts in the message, with content IDs as
keys and {@link
+ * DataHandler} objects as values.
*/
- public Map<String,DataHandler> getMap() {
+ public Map<String, DataHandler> getMap() {
return delegate.getMap();
}
/**
* Get the content IDs of the already loaded MIME parts in the message.
This includes the
- * content ID of the SOAP part as well as the content IDs of the
attachments. If this
- * object has been created from a stream, only the content IDs of the MIME
parts that
- * have already been fetched from the stream are returned. If this is not
the desired
- * behavior, {@link #getAllContentIDs()} or {@link #getContentIDSet()}
should be used
- * instead.
- *
+ * content ID of the SOAP part as well as the content IDs of the
attachments. If this object has
+ * been created from a stream, only the content IDs of the MIME parts that
have already been
+ * fetched from the stream are returned. If this is not the desired
behavior, {@link
+ * #getAllContentIDs()} or {@link #getContentIDSet()} should be used
instead.
+ *
* @return List of content IDs in order of appearance in message
*/
public List<String> getContentIDList() {
return new ArrayList<String>(delegate.getContentIDs(false));
}
-
+
/**
- * If the Attachments is backed by an InputStream, then this
- * method returns the length of the message contents
- * (Length of the entire message - Length of the Transport Headers)
- * @return length of message content or -1 if Attachments is not
- * backed by an InputStream
+ * If the Attachments is backed by an InputStream, then this method
returns the length of the
+ * message contents (Length of the entire message - Length of the
Transport Headers)
+ *
+ * @return length of message content or -1 if Attachments is not backed by
an InputStream
*/
public long getContentLength() throws IOException {
return delegate.getContentLength();
@@ -411,4 +451,4 @@ public class Attachments implements OMAttachmentAccessor {
DataHandler dh = getDataHandler(contentID);
return dh == null ? null : DataHandlerUtils.toBlob(dh);
}
-}
\ No newline at end of file
+}
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/AttachmentsDelegate.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/AttachmentsDelegate.java
index 9a7f8d2f6..ce35eebb9 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/AttachmentsDelegate.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/AttachmentsDelegate.java
@@ -32,33 +32,47 @@ import org.apache.axiom.om.OMException;
/**
* {@link Attachments} delegate. An {@link Attachments} object may actually
represent two fairly
* different things (depending on the constructor that is used):
+ *
* <ul>
- * <li>A MIME multipart message that comprises a root part and a set of
attachment parts. Axiom uses
- * deferred parsing to process the message, i.e. the parts and their content
are loaded on-demand.
- * <li>A programmatically created set of attachment parts. In that case, the
root part is not
- * included.
+ * <li>A MIME multipart message that comprises a root part and a set of
attachment parts. Axiom
+ * uses deferred parsing to process the message, i.e. the parts and
their content are loaded
+ * on-demand.
+ * <li>A programmatically created set of attachment parts. In that case, the
root part is not
+ * included.
* </ul>
+ *
* Since the behavior of the {@link Attachments} instance is fairly different
in the two cases, this
* should be considered a flaw in the API design. Unfortunately it is not
possible to fix this
* without breaking existing code. In particular, in Axis2 the {@link
Attachments} API is heavily
* used by application code. Therefore a delegation pattern is used so that
internally these two
* cases can be represented using distinct classes.
- * <p>
- * Note that this class is intentionally not public. It is for <b>internal use
only</b>. However, in
- * a later Axiom version we may want to refactor this API to make it public,
in which case
- * {@link Attachments} would simply become a legacy adapter.
+ *
+ * <p>Note that this class is intentionally not public. It is for <b>internal
use only</b>. However,
+ * in a later Axiom version we may want to refactor this API to make it
public, in which case {@link
+ * Attachments} would simply become a legacy adapter.
*/
abstract class AttachmentsDelegate {
abstract ContentType getContentType();
+
abstract DataHandler getDataHandler(String contentID);
+
abstract void addDataHandler(String contentID, DataHandler dataHandler);
+
abstract void removeDataHandler(String blobContentID);
+
abstract InputStream getRootPartInputStream(boolean preserve) throws
OMException;
+
abstract String getRootPartContentID();
+
abstract String getRootPartContentType();
+
abstract IncomingAttachmentStreams getIncomingAttachmentStreams();
+
abstract Set<String> getContentIDs(boolean fetchAll);
- abstract Map<String,DataHandler> getMap();
+
+ abstract Map<String, DataHandler> getMap();
+
abstract long getContentLength() throws IOException;
+
abstract MultipartBody getMultipartBody();
}
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/ByteArrayDataSource.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/ByteArrayDataSource.java
index 2f3b7bf19..ba7502a6b 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/ByteArrayDataSource.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/ByteArrayDataSource.java
@@ -47,10 +47,8 @@ public class ByteArrayDataSource implements
org.apache.axiom.ext.activation.Size
@Override
public String getContentType() {
- if (type == null)
- return "application/octet-stream";
- else
- return type;
+ if (type == null) return "application/octet-stream";
+ else return type;
}
@Override
@@ -74,4 +72,3 @@ public class ByteArrayDataSource implements
org.apache.axiom.ext.activation.Size
return data == null ? 0 : data.length;
}
}
-
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/CachedFileDataSource.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/CachedFileDataSource.java
index 5d37056be..288a25123 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/CachedFileDataSource.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/CachedFileDataSource.java
@@ -26,38 +26,37 @@ import org.apache.axiom.ext.activation.SizeAwareDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
public class CachedFileDataSource extends FileDataSource implements
SizeAwareDataSource {
private static final Log log =
LogFactory.getLog(CachedFileDataSource.class);
String contentType = null;
-
+
// The AttachmentCacheMonitor is used to delete expired copies of
attachment files.
- private static AttachmentCacheMonitor acm =
- AttachmentCacheMonitor.getAttachmentCacheMonitor();
-
+ private static AttachmentCacheMonitor acm =
AttachmentCacheMonitor.getAttachmentCacheMonitor();
+
// Represents the absolute pathname of cached attachment file
private String cachedFileName = null;
public CachedFileDataSource(File file) {
super(file);
if (log.isDebugEnabled()) {
- log.debug("Enter CachedFileDataSource ctor");
+ log.debug("Enter CachedFileDataSource ctor");
}
if (file != null) {
- try {
- cachedFileName = file.getCanonicalPath();
- } catch (java.io.IOException e) {
- log.error("IOException caught: " + e);
- }
+ try {
+ cachedFileName = file.getCanonicalPath();
+ } catch (java.io.IOException e) {
+ log.error("IOException caught: " + e);
+ }
}
if (cachedFileName != null) {
- if (log.isDebugEnabled()) {
- log.debug("Cached file: " + cachedFileName);
- log.debug("Registering the file with
AttachmentCacheMonitor and also marked it as being accessed");
- }
+ if (log.isDebugEnabled()) {
+ log.debug("Cached file: " + cachedFileName);
+ log.debug(
+ "Registering the file with AttachmentCacheMonitor and
also marked it as being accessed");
+ }
// Tell the monitor that the file is being accessed.
- acm.access(cachedFileName);
+ acm.access(cachedFileName);
// Register the file with the AttachmentCacheMonitor
acm.register(cachedFileName);
}
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/ConfigurableDataHandler.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/ConfigurableDataHandler.java
index aaed1969d..a77511124 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/ConfigurableDataHandler.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/ConfigurableDataHandler.java
@@ -34,13 +34,25 @@ import java.net.URL;
/**
* This Axiom DataHandler inplementation allows the user to set custom values
for the following MIME
- * body part headers. <ul> <li>content-transfer-encoding</li>
<li>content-type</li> </ul> <p>Data
- * written to the MIME part gets encoded by content-transfer-encoding
specified as above</p>
- * <p>
- * Usage is Similar to the javax.activation.DataHandler except for the setting
of the above
- * properties. </p> <p>eg: </p> <p> dataHandler = new
ConfigurableDataHandler(new
- * ByteArrayDataSource(byteArray));</p> <p>
dataHandler.setTransferEncoding("quoted-printable");</p>
- * <p> dataHandler.setContentType("image/jpg");</p>
+ * body part headers.
+ *
+ * <ul>
+ * <li>content-transfer-encoding
+ * <li>content-type
+ * </ul>
+ *
+ * <p>Data written to the MIME part gets encoded by content-transfer-encoding
specified as above
+ *
+ * <p>Usage is Similar to the javax.activation.DataHandler except for the
setting of the above
+ * properties.
+ *
+ * <p>eg:
+ *
+ * <p>dataHandler = new ConfigurableDataHandler(new
ByteArrayDataSource(byteArray));
+ *
+ * <p>dataHandler.setTransferEncoding("quoted-printable");
+ *
+ * <p>dataHandler.setContentType("image/jpg");
*
* @see jakarta.activation.DataHandler
*/
@@ -49,30 +61,37 @@ public class ConfigurableDataHandler extends DataHandler {
/**
* {@link ContentTransferEncodingPolicy} implementation that recognizes
blobs created from
- * {@link ConfigurableDataHandler} objects and returns the content
transfer encoding
- * set using {@link ConfigurableDataHandler#setTransferEncoding(String)}.
+ * {@link ConfigurableDataHandler} objects and returns the content
transfer encoding set using
+ * {@link ConfigurableDataHandler#setTransferEncoding(String)}.
*/
- public static final ContentTransferEncodingPolicy
CONTENT_TRANSFER_ENCODING_POLICY = new ContentTransferEncodingPolicy() {
- @Override
- public ContentTransferEncoding getContentTransferEncoding(Blob blob,
ContentType contentType) {
- DataHandler dataHandler = DataHandlerUtils.toDataHandler(blob);
- if (!(dataHandler instanceof ConfigurableDataHandler)) {
- return null;
- }
- String cte =
((ConfigurableDataHandler)dataHandler).getTransferEncoding();
- if (cte == null) {
- return null;
- }
- switch (cte) {
- case "8bit": return ContentTransferEncoding.EIGHT_BIT;
- case "binary": return ContentTransferEncoding.BINARY;
- case "base64": return ContentTransferEncoding.BASE64;
- default:
- log.warn(String.format("Unrecognized content transfer
encoding: %s", cte));
- return null;
- }
- }
- };
+ public static final ContentTransferEncodingPolicy
CONTENT_TRANSFER_ENCODING_POLICY =
+ new ContentTransferEncodingPolicy() {
+ @Override
+ public ContentTransferEncoding getContentTransferEncoding(
+ Blob blob, ContentType contentType) {
+ DataHandler dataHandler =
DataHandlerUtils.toDataHandler(blob);
+ if (!(dataHandler instanceof ConfigurableDataHandler)) {
+ return null;
+ }
+ String cte = ((ConfigurableDataHandler)
dataHandler).getTransferEncoding();
+ if (cte == null) {
+ return null;
+ }
+ switch (cte) {
+ case "8bit":
+ return ContentTransferEncoding.EIGHT_BIT;
+ case "binary":
+ return ContentTransferEncoding.BINARY;
+ case "base64":
+ return ContentTransferEncoding.BASE64;
+ default:
+ log.warn(
+ String.format(
+ "Unrecognized content transfer
encoding: %s", cte));
+ return null;
+ }
+ }
+ };
private String transferEncoding;
@@ -90,13 +109,13 @@ public class ConfigurableDataHandler extends DataHandler {
super(url);
}
-// public String getContentID() {
-// return contentID;
-// }
-//
-// public void setContentID(String contentID) {
-// this.contentID = contentID;
-// }
+ // public String getContentID() {
+ // return contentID;
+ // }
+ //
+ // public void setContentID(String contentID) {
+ // this.contentID = contentID;
+ // }
@Override
public String getContentType() {
@@ -105,7 +124,6 @@ public class ConfigurableDataHandler extends DataHandler {
} else {
return super.getContentType();
}
-
}
public void setContentType(String contentType) {
@@ -119,5 +137,4 @@ public class ConfigurableDataHandler extends DataHandler {
public void setTransferEncoding(String transferEncoding) {
this.transferEncoding = transferEncoding;
}
-
}
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/IncomingAttachmentInputStream.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/IncomingAttachmentInputStream.java
index f3464e0ea..3d9722929 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/IncomingAttachmentInputStream.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/IncomingAttachmentInputStream.java
@@ -25,10 +25,10 @@ import java.util.HashMap;
import java.util.Map;
public class IncomingAttachmentInputStream extends InputStream {
- private Map<String,String> _headers = null;
+ private Map<String, String> _headers = null;
+
+ private Map<String, String> _headersLowerCase = null;
- private Map<String,String> _headersLowerCase = null;
-
private InputStream _stream = null;
private IncomingAttachmentStreams parentContainer;
@@ -39,15 +39,19 @@ public class IncomingAttachmentInputStream extends
InputStream {
public static final String HEADER_CONTENT_LOCATION = "content-location";
public static final String HEADER_CONTENT_ID = "content-id";
- /** @param in */
- public IncomingAttachmentInputStream(InputStream in,
- IncomingAttachmentStreams
parentContainer) {
+ /**
+ * @param in
+ */
+ public IncomingAttachmentInputStream(
+ InputStream in, IncomingAttachmentStreams parentContainer) {
_stream = in;
this.parentContainer = parentContainer;
}
- /** @return MIME headers for this attachment. May be null if no headers
were set. */
- public Map<String,String> getHeaders() {
+ /**
+ * @return MIME headers for this attachment. May be null if no headers
were set.
+ */
+ public Map<String, String> getHeaders() {
return _headers;
}
@@ -59,8 +63,8 @@ public class IncomingAttachmentInputStream extends
InputStream {
*/
public void addHeader(String name, String value) {
if (_headers == null) {
- _headers = new HashMap<String,String>();
- _headersLowerCase = new HashMap<String,String>();
+ _headers = new HashMap<String, String>();
+ _headersLowerCase = new HashMap<String, String>();
}
_headers.put(name, value);
_headersLowerCase.put(name.toLowerCase(), value);
@@ -74,23 +78,30 @@ public class IncomingAttachmentInputStream extends
InputStream {
*/
public String getHeader(String name) {
Object header = null;
- if (_headersLowerCase == null || (header =
_headersLowerCase.get(name.toLowerCase())) == null) {
+ if (_headersLowerCase == null
+ || (header = _headersLowerCase.get(name.toLowerCase())) ==
null) {
return null;
}
return header.toString();
}
- /** @return The header with HTTPConstants.HEADER_CONTENT_ID as the key. */
+ /**
+ * @return The header with HTTPConstants.HEADER_CONTENT_ID as the key.
+ */
public String getContentId() {
return getHeader(HEADER_CONTENT_ID);
}
- /** @return The header with HTTPConstants.HEADER_CONTENT_LOCATION as the
key. */
+ /**
+ * @return The header with HTTPConstants.HEADER_CONTENT_LOCATION as the
key.
+ */
public String getContentLocation() {
return getHeader(HEADER_CONTENT_LOCATION);
}
- /** @return The header with HTTPConstants.HEADER_CONTENT_TYPE as the key.
*/
+ /**
+ * @return The header with HTTPConstants.HEADER_CONTENT_TYPE as the key.
+ */
public String getContentType() {
return getHeader(HEADER_CONTENT_TYPE);
}
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/IncomingAttachmentStreams.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/IncomingAttachmentStreams.java
index d862cb382..5449b4a6e 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/IncomingAttachmentStreams.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/IncomingAttachmentStreams.java
@@ -36,8 +36,8 @@ public final class IncomingAttachmentStreams {
private final Iterator<Part> partIterator;
/**
- * Boolean indicating weather or not the next stream can be read (next
stream cannot be read until
- * previous is consumed
+ * Boolean indicating weather or not the next stream can be read (next
stream cannot be read
+ * until previous is consumed
*/
private boolean readyToGetNextStream = true;
@@ -46,7 +46,9 @@ public final class IncomingAttachmentStreams {
partIterator = message.iterator();
}
- /** @return True if the next stream can be read, false otherwise. */
+ /**
+ * @return True if the next stream can be read, false otherwise.
+ */
public final boolean isReadyToGetNextStream() {
return readyToGetNextStream;
}
@@ -80,8 +82,9 @@ public final class IncomingAttachmentStreams {
}
if (part != null) {
- IncomingAttachmentInputStream stream = new
IncomingAttachmentInputStream(part.getInputStream(false), this);
-
+ IncomingAttachmentInputStream stream =
+ new
IncomingAttachmentInputStream(part.getInputStream(false), this);
+
for (Header header : part.getHeaders()) {
String name = header.getName();
String value = header.getValue();
@@ -92,11 +95,11 @@ public final class IncomingAttachmentStreams {
}
stream.addHeader(name, value);
}
-
+
readyToGetNextStream = false;
return stream;
} else {
return null;
}
}
-}
\ No newline at end of file
+}
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/LegacyPartDataHandler.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/LegacyPartDataHandler.java
index 99edfb3b9..8ae644965 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/LegacyPartDataHandler.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/LegacyPartDataHandler.java
@@ -36,7 +36,7 @@ final class LegacyPartDataHandler extends PartDataHandler
implements DataHandler
@Override
protected DataSource createDataSource(Blob content, String contentType) {
if (content instanceof LegacyTempFileBlob) {
- return ((LegacyTempFileBlob)content).getDataSource(contentType);
+ return ((LegacyTempFileBlob) content).getDataSource(contentType);
} else {
return null;
}
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/LegacyTempFileBlob.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/LegacyTempFileBlob.java
index 2cca20373..fece45933 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/LegacyTempFileBlob.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/LegacyTempFileBlob.java
@@ -54,7 +54,7 @@ final class LegacyTempFileBlob extends AbstractWritableBlob {
ds.setContentType(contentType);
return ds;
}
-
+
@Override
public long getSize() {
return fileAccessor.getSize();
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/MultipartBodyAdapter.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/MultipartBodyAdapter.java
index aebd5b2f1..a62c339df 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/MultipartBodyAdapter.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/MultipartBodyAdapter.java
@@ -46,7 +46,7 @@ final class MultipartBodyAdapter extends AttachmentsDelegate
implements PartCrea
private static final Log log =
LogFactory.getLog(MultipartBodyAdapter.class);
private final MultipartBody message;
- private final Map<String,DataHandler> map = new
LinkedHashMap<String,DataHandler>();
+ private final Map<String, DataHandler> map = new LinkedHashMap<String,
DataHandler>();
private final int contentLength;
private final CountingInputStream filterIS;
private final Part rootPart;
@@ -57,11 +57,18 @@ final class MultipartBodyAdapter extends
AttachmentsDelegate implements PartCrea
/** Container to hold streams for direct access */
private IncomingAttachmentStreams streams;
- MultipartBodyAdapter(InputStream inStream, String contentTypeString,
- WritableBlobFactory<?> attachmentBlobFactory, int contentLength) {
+ MultipartBodyAdapter(
+ InputStream inStream,
+ String contentTypeString,
+ WritableBlobFactory<?> attachmentBlobFactory,
+ int contentLength) {
this.contentLength = contentLength;
if (log.isDebugEnabled()) {
- log.debug("Attachments contentLength=" + contentLength + ",
contentTypeString=" + contentTypeString);
+ log.debug(
+ "Attachments contentLength="
+ + contentLength
+ + ", contentTypeString="
+ + contentTypeString);
}
// If the length is not known, install a filter so that we can
retrieve it later.
@@ -72,18 +79,20 @@ final class MultipartBodyAdapter extends
AttachmentsDelegate implements PartCrea
filterIS = null;
}
- this.message = MultipartBody.builder()
- .setInputStream(inStream)
- .setContentType(contentTypeString)
- .setAttachmentBlobFactory(attachmentBlobFactory)
- .setPartBlobFactory(new PartDataHandlerBlobFactory() {
- @Override
- protected PartDataHandler createDataHandler(Part part)
{
- return new LegacyPartDataHandler(part);
- }
- })
- .setPartCreationListener(this)
- .build();
+ this.message =
+ MultipartBody.builder()
+ .setInputStream(inStream)
+ .setContentType(contentTypeString)
+ .setAttachmentBlobFactory(attachmentBlobFactory)
+ .setPartBlobFactory(
+ new PartDataHandlerBlobFactory() {
+ @Override
+ protected PartDataHandler
createDataHandler(Part part) {
+ return new LegacyPartDataHandler(part);
+ }
+ })
+ .setPartCreationListener(this)
+ .build();
rootPart = message.getRootPart();
String rootPartContentID = rootPart.getContentID();
@@ -104,7 +113,8 @@ final class MultipartBodyAdapter extends
AttachmentsDelegate implements PartCrea
private boolean fetchNext() {
if (streams != null) {
- throw new IllegalStateException("The attachments stream can only
be accessed once; either by using the IncomingAttachmentStreams class or by
getting a collection of AttachmentPart objects. They cannot both be called
within the life time of the same service request.");
+ throw new IllegalStateException(
+ "The attachments stream can only be accessed once; either
by using the IncomingAttachmentStreams class or by getting a collection of
AttachmentPart objects. They cannot both be called within the life time of the
same service request.");
}
if (partIterator == null) {
partIterator = message.iterator();
@@ -181,18 +191,17 @@ final class MultipartBodyAdapter extends
AttachmentsDelegate implements PartCrea
IncomingAttachmentStreams getIncomingAttachmentStreams() {
if (partIterator != null) {
throw new IllegalStateException(
- "The attachments stream can only be accessed once; either
by using the IncomingAttachmentStreams class or by getting a " +
- "collection of AttachmentPart objects. They cannot
both be called within the life time of the same service request.");
+ "The attachments stream can only be accessed once; either
by using the IncomingAttachmentStreams class or by getting a "
+ + "collection of AttachmentPart objects. They
cannot both be called within the life time of the same service request.");
}
-
+
if (streams == null) {
streams = new IncomingAttachmentStreams(message);
}
-
+
return streams;
}
-
@Override
Set<String> getContentIDs(boolean fetchAll) {
if (fetchAll) {
@@ -202,7 +211,7 @@ final class MultipartBodyAdapter extends
AttachmentsDelegate implements PartCrea
}
@Override
- Map<String,DataHandler> getMap() {
+ Map<String, DataHandler> getMap() {
fetchAll();
return Collections.unmodifiableMap(map);
}
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/DataHandlerExt.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/DataHandlerExt.java
index 82972b674..d2ee25e93 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/DataHandlerExt.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/DataHandlerExt.java
@@ -30,30 +30,26 @@ public interface DataHandlerExt {
* similar to {@link DataHandler#getInputStream()} except that it can be
invoked only once. If
* the content has not been buffered yet, then the implementation may
choose to enable streaming
* of the content.
- * <p>
- * The implementation ensures that after the returned input steam is
consumed, the data handler
- * will be in the same state as after a call to {@link #purgeDataSource()}.
- *
+ *
+ * <p>The implementation ensures that after the returned input steam is
consumed, the data
+ * handler will be in the same state as after a call to {@link
#purgeDataSource()}.
+ *
* @return the stream representing the content; never <code>null</code>
- * @throws IOException
- * if an error occurs
+ * @throws IOException if an error occurs
*/
InputStream readOnce() throws IOException;
-
- /**
- * This method will give users an option to trigger a purge
- * on temporary attachment files. Temp files are created for
- * attachment data that is greater than a threshold limit.
- * On client side These temp attachment files are not deleted
- * untilthe virtual machine exits as user can choose to read
- * this dataHandler. So if user is not going to use the data
- * handlers provided on this temproray files they can choose
- * to purge the file.
- */
- public void purgeDataSource() throws IOException;
-
- /**
- * @deprecated Use {@link #readOnce()} or {@link #purgeDataSource()}
instead.
- */
- public void deleteWhenReadOnce() throws IOException;
+
+ /**
+ * This method will give users an option to trigger a purge on temporary
attachment files. Temp
+ * files are created for attachment data that is greater than a threshold
limit. On client side
+ * These temp attachment files are not deleted untilthe virtual machine
exits as user can choose
+ * to read this dataHandler. So if user is not going to use the data
handlers provided on this
+ * temproray files they can choose to purge the file.
+ */
+ public void purgeDataSource() throws IOException;
+
+ /**
+ * @deprecated Use {@link #readOnce()} or {@link #purgeDataSource()}
instead.
+ */
+ public void deleteWhenReadOnce() throws IOException;
}
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/LifecycleManager.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/LifecycleManager.java
index 73f2b02eb..49d439fe2 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/LifecycleManager.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/LifecycleManager.java
@@ -26,49 +26,53 @@ import
org.apache.axiom.attachments.lifecycle.impl.FileAccessor;
/**
* Lifecycle Manager will be used to manage the lifecycle of attachment files.
- *
- * Axiom forks attachment processing based on the size of attachment to be
processed.
- * Attachments are either processed by storing them in memory or by storing
them in
- * file system based on the size of the attachment file.
*
- * Lifecycle Manager provides and organized way of managing attachments, by
providing
- * calls to create and delete attachments.
+ * <p>Axiom forks attachment processing based on the size of attachment to be
processed. Attachments
+ * are either processed by storing them in memory or by storing them in file
system based on the
+ * size of the attachment file.
+ *
+ * <p>Lifecycle Manager provides and organized way of managing attachments, by
providing calls to
+ * create and delete attachments.
*/
public interface LifecycleManager {
/**
* Create a unique file in the designated directory
+ *
* @param attachmentDir
* @return the {@link FileAccessor} for the file created by this method
* @throws IOException
- */
+ */
public FileAccessor create(String attachmentDir) throws IOException;
-
- /**
+
+ /**
* Deletes attachment file
+ *
* @param file
* @throws IOException
*/
public void delete(File file) throws IOException;
-
+
/**
- * Mark the file for deletion on application/VM exit
+ * Mark the file for deletion on application/VM exit
+ *
* @param file
* @throws IOException
*/
public void deleteOnExit(File file) throws IOException;
-
+
/**
- * Mark attachment file for deletion when designated time interval in
seconds
- * has elapsed.
+ * Mark attachment file for deletion when designated time interval in
seconds has elapsed.
+ *
* @param interval
* @param file
* @throws IOException
*/
public void deleteOnTimeInterval(int interval, File file) throws
IOException;
-
+
/**
* This method will return the file accessor associated with this file.
+ *
* @param file
* @return the {@link FileAccessor} object for the given file
* @throws IOException
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/FileAccessor.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/FileAccessor.java
index 4ea2e4612..129ec4904 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/FileAccessor.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/FileAccessor.java
@@ -33,39 +33,38 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
- * FileAccessor wraps the attachment temp file. It is created from PartOnFile.
- * The idea behind wrapping the file is to give rumtime an ability to track
- * when the file is accessed with streams or data handler and accordingly
trigger
- * events to handle the the files lifecycle.
- *
+ * FileAccessor wraps the attachment temp file. It is created from PartOnFile.
The idea behind
+ * wrapping the file is to give rumtime an ability to track when the file is
accessed with streams
+ * or data handler and accordingly trigger events to handle the the files
lifecycle.
*/
-public class FileAccessor extends Observable{
+public class FileAccessor extends Observable {
private static final Log log = LogFactory.getLog(FileAccessor.class);
File file = null;
LifecycleManager manager;
private int accessCount = 0;
+
public FileAccessor(LifecycleManager manager, File file) {
super();
this.manager = manager;
- this.file = file;
+ this.file = file;
}
public String getFileName() {
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("getFileName()");
}
return file.getAbsolutePath();
}
public InputStream getInputStream() throws IOException {
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("getInputStream()");
}
return new FileInputStream(file);
}
- public OutputStream getOutputStream() throws FileNotFoundException{
- if(log.isDebugEnabled()){
+ public OutputStream getOutputStream() throws FileNotFoundException {
+ if (log.isDebugEnabled()) {
log.debug("getOutputStream()");
}
return new FileOutputStream(file);
@@ -74,7 +73,7 @@ public class FileAccessor extends Observable{
public long getSize() {
return file.length();
}
-
+
public File getFile() {
return file;
}
@@ -83,8 +82,7 @@ public class FileAccessor extends Observable{
this.file = file;
}
- public int getAccessCount() {
- return accessCount;
- }
-
+ public int getAccessCount() {
+ return accessCount;
+ }
}
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/LifecycleEventDefinitions.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/LifecycleEventDefinitions.java
index abd309da2..72f1aa815 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/LifecycleEventDefinitions.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/LifecycleEventDefinitions.java
@@ -17,7 +17,6 @@
* under the License.
*/
-
package org.apache.axiom.attachments.lifecycle.impl;
public class LifecycleEventDefinitions {
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/LifecycleEventHandler.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/LifecycleEventHandler.java
index 6dcef8086..db9f4bf40 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/LifecycleEventHandler.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/LifecycleEventHandler.java
@@ -22,21 +22,21 @@ package org.apache.axiom.attachments.lifecycle.impl;
import java.io.IOException;
/**
- * The attachment life cycle manager supports create and delete operations on
the FileAccessor(which holds attachment file).
- * These operations are coupled to events, the LifecycleManager needs to
execute an operation when an even
- * causes that operation to trigger. For example a delete operation should
execute when a deleteOnExit
- * or deleteOnTimeInterval event occur on FileAccessor.
- *
- * The LifecycleManager should execute operation on FileAccessor based on the
Events that trigger them.
- * EventHandler defines methods to execute LifecycleManager operation when a
event occurs.
+ * The attachment life cycle manager supports create and delete operations on
the FileAccessor(which
+ * holds attachment file). These operations are coupled to events, the
LifecycleManager needs to
+ * execute an operation when an even causes that operation to trigger. For
example a delete
+ * operation should execute when a deleteOnExit or deleteOnTimeInterval event
occur on FileAccessor.
*
+ * <p>The LifecycleManager should execute operation on FileAccessor based on
the Events that trigger
+ * them. EventHandler defines methods to execute LifecycleManager operation
when a event occurs.
*/
public interface LifecycleEventHandler {
-
+
/**
- * When a Event occurs in FileAccessor, execute the LifecycleManager
Operation
- * For example, if the delete behaviour is readOnce and if the inputstream
on attachment is read
- * and closed the first time, the delete operation in LifecycleManager
should be executed.
+ * When a Event occurs in FileAccessor, execute the LifecycleManager
Operation For example, if
+ * the delete behaviour is readOnce and if the inputstream on attachment
is read and closed the
+ * first time, the delete operation in LifecycleManager should be executed.
+ *
* @param eventId
*/
public void handleEvent(int eventId) throws IOException;
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/LifecycleManagerImpl.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/LifecycleManagerImpl.java
index 3cb3d93c9..c01198cb1 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/LifecycleManagerImpl.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/LifecycleManagerImpl.java
@@ -31,11 +31,12 @@ import org.apache.commons.logging.LogFactory;
public class LifecycleManagerImpl implements LifecycleManager {
private static final Log log =
LogFactory.getLog(LifecycleManagerImpl.class);
- //Hashtable to store file accessors.
- private static Hashtable<String,FileAccessor> table = new
Hashtable<String,FileAccessor>();
+ // Hashtable to store file accessors.
+ private static Hashtable<String, FileAccessor> table = new
Hashtable<String, FileAccessor>();
private VMShutdownHook hook = null;
+
public LifecycleManagerImpl() {
- super();
+ super();
}
/* (non-Javadoc)
@@ -43,7 +44,7 @@ public class LifecycleManagerImpl implements LifecycleManager
{
*/
@Override
public FileAccessor create(String attachmentDir) throws IOException {
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("Start Create()");
}
File file = null;
@@ -55,8 +56,8 @@ public class LifecycleManagerImpl implements LifecycleManager
{
}
}
if (!dir.isDirectory()) {
- throw new IllegalArgumentException("Given Attachment File Cache
Location "
- + dir + " should be a directory.");
+ throw new IllegalArgumentException(
+ "Given Attachment File Cache Location " + dir + " should
be a directory.");
}
// Generate unique id. The UID generator is used so that we can limit
// synchronization with the java random number generator.
@@ -65,11 +66,11 @@ public class LifecycleManagerImpl implements
LifecycleManager {
String fileString = "axiom" + id + ".att";
file = new File(dir, fileString);
FileAccessor fa = new FileAccessor(this, file);
- //add the fileAccesor to table
+ // add the fileAccesor to table
table.put(fileString, fa);
- //Default behaviour
+ // Default behaviour
deleteOnExit(file);
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("End Create()");
}
return fa;
@@ -80,37 +81,37 @@ public class LifecycleManagerImpl implements
LifecycleManager {
*/
@Override
public void delete(File file) throws IOException {
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("Start delete()");
}
- if(file!=null && file.exists()){
+ if (file != null && file.exists()) {
table.remove(file.getName());
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("invoking file.delete()");
}
- if(file.delete()){
- if(log.isDebugEnabled()){
+ if (file.delete()) {
+ if (log.isDebugEnabled()) {
log.debug("delete() successful");
}
- //If file was registered with VMShutdown hook
- //lets remove it from the list to be deleted on VMExit.
- VMShutdownHook hook =VMShutdownHook.hook();
- if(hook.isRegistered()){
+ // If file was registered with VMShutdown hook
+ // lets remove it from the list to be deleted on VMExit.
+ VMShutdownHook hook = VMShutdownHook.hook();
+ if (hook.isRegistered()) {
hook.remove(file);
}
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("File Purged and removed from Shutdown Hook
Collection");
}
- }else{
- if(log.isDebugEnabled()){
+ } else {
+ if (log.isDebugEnabled()) {
log.debug("Cannot delete file, set to delete on VM
shutdown");
}
deleteOnExit(file);
}
}
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("End delete()");
}
}
@@ -120,21 +121,21 @@ public class LifecycleManagerImpl implements
LifecycleManager {
*/
@Override
public void deleteOnExit(File file) throws IOException {
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("Start deleteOnExit()");
}
- if(hook == null){
+ if (hook == null) {
hook = RegisterVMShutdownHook();
}
- if(file!=null){
- if(log.isDebugEnabled()){
- log.debug("Invoking deleteOnExit() for file =
"+file.getAbsolutePath());
+ if (file != null) {
+ if (log.isDebugEnabled()) {
+ log.debug("Invoking deleteOnExit() for file = " +
file.getAbsolutePath());
}
hook.add(file);
table.remove(file.getName());
}
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("End deleteOnExit()");
}
}
@@ -144,65 +145,62 @@ public class LifecycleManagerImpl implements
LifecycleManager {
*/
@Override
public void deleteOnTimeInterval(int interval, File file) throws
IOException {
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("Start deleteOnTimeInterval()");
}
Thread t = new Thread(new LifecycleManagerImpl.FileDeletor(interval,
file));
t.setDaemon(true);
t.start();
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("End deleteOnTimeInterval()");
}
}
- private VMShutdownHook RegisterVMShutdownHook() throws RuntimeException{
- if(log.isDebugEnabled()){
+ private VMShutdownHook RegisterVMShutdownHook() throws RuntimeException {
+ if (log.isDebugEnabled()) {
log.debug("Start RegisterVMShutdownHook()");
}
VMShutdownHook hook = VMShutdownHook.hook();
- if(!hook.isRegistered()){
+ if (!hook.isRegistered()) {
Runtime.getRuntime().addShutdownHook(hook);
hook.setRegistered(true);
}
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("Exit RegisterVMShutdownHook()");
}
return hook;
}
- public class FileDeletor implements Runnable{
+ public class FileDeletor implements Runnable {
int interval;
File _file;
public FileDeletor(int interval, File file) {
super();
this.interval = interval;
- this._file = file;
+ this._file = file;
}
@Override
public void run() {
- try{
- Thread.sleep(interval*1000);
- if(_file.exists()){
+ try {
+ Thread.sleep(interval * 1000);
+ if (_file.exists()) {
table.remove(_file.getName());
_file.delete();
}
- }catch(InterruptedException e){
- //Log Exception
- if(log.isDebugEnabled()){
- log.warn("InterruptedException occured "+e.getMessage());
+ } catch (InterruptedException e) {
+ // Log Exception
+ if (log.isDebugEnabled()) {
+ log.warn("InterruptedException occured " + e.getMessage());
}
}
- }
+ }
}
@Override
- public FileAccessor getFileAccessor(String fileName) throws IOException
{
- return table.get(fileName);
- }
-
+ public FileAccessor getFileAccessor(String fileName) throws IOException {
+ return table.get(fileName);
+ }
}
-
-
diff --git
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/VMShutdownHook.java
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/VMShutdownHook.java
index 6a6dbc065..91a32b752 100644
---
a/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/VMShutdownHook.java
+++
b/axiom-legacy-attachments/src/main/java/org/apache/axiom/attachments/lifecycle/impl/VMShutdownHook.java
@@ -25,8 +25,9 @@ import java.util.HashSet;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+
/*
- * VMShutdown Hook will be registered with Runtime object to be invoked
+ * VMShutdown Hook will be registered with Runtime object to be invoked
* when Virutal Machine is shutdown.
* This class will be used to delete any cached attachments file that where
* added by runtime to be deleted on VM shutdown.
@@ -38,59 +39,61 @@ public class VMShutdownHook extends Thread {
private boolean isRegistered = false;
static VMShutdownHook hook() {
- if (instance == null){
- if(log.isDebugEnabled()){
+ if (instance == null) {
+ if (log.isDebugEnabled()) {
log.debug("creating VMShutdownHook");
}
- instance = new VMShutdownHook();
+ instance = new VMShutdownHook();
}
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("returning VMShutdownHook instance");
}
return instance;
}
- private VMShutdownHook(){}
- void remove(File file){
- if(file == null){
+ private VMShutdownHook() {}
+
+ void remove(File file) {
+ if (file == null) {
return;
}
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("Removing File to Shutdown Hook Collection");
}
files.remove(file);
}
+
void add(File file) {
- if(file == null){
+ if (file == null) {
return;
}
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("Adding File to Shutdown Hook Collection");
}
- files.add(file);
+ files.add(file);
}
@Override
public void run() {
- if(log.isDebugEnabled()){
+ if (log.isDebugEnabled()) {
log.debug("JVM running VM Shutdown Hook");
- }
- for (File file : files){
- if(log.isDebugEnabled()){
- log.debug("Deleting File from Shutdown Hook
Collection"+file.getAbsolutePath());
- }
+ }
+ for (File file : files) {
+ if (log.isDebugEnabled()) {
+ log.debug("Deleting File from Shutdown Hook Collection" +
file.getAbsolutePath());
+ }
file.delete();
- }
- if(log.isDebugEnabled()){
+ }
+ if (log.isDebugEnabled()) {
log.debug("JVM Done running VM Shutdown Hook");
}
}
public boolean isRegistered() {
- if(log.isDebugEnabled()){
- if(!isRegistered){
+ if (log.isDebugEnabled()) {
+ if (!isRegistered) {
log.debug("hook isRegistered= false");
- }else{
+ } else {
log.debug("hook isRegistered= true");
}
}
diff --git
a/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/AttachmentCacheMonitorTest.java
b/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/AttachmentCacheMonitorTest.java
index aa1bbd36b..374b84b59 100644
---
a/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/AttachmentCacheMonitorTest.java
+++
b/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/AttachmentCacheMonitorTest.java
@@ -24,19 +24,17 @@ import org.apache.axiom.om.AbstractTestCase;
public class AttachmentCacheMonitorTest extends AbstractTestCase {
public void testCachedFilesExpired() throws Exception {
-
+
// Set file expiration to 10 seconds
long INTERVAL = 3 * 1000; // 3 seconds for Thread to sleep
-
// Get the AttachmentCacheMonitor and force it to remove files after
// 10 seconds.
AttachmentCacheMonitor acm =
AttachmentCacheMonitor.getAttachmentCacheMonitor();
int previousTime = acm.getTimeout();
-
- try {
- acm.setTimeout(10);
+ try {
+ acm.setTimeout(10);
File aFile = File.createTempFile("fileA", ".tmp");
String aFileName = aFile.getCanonicalPath();
@@ -76,16 +74,15 @@ public class AttachmentCacheMonitorTest extends
AbstractTestCase {
// time since file C registration <= cached file expiration
assertTrue("File C should still exist", cFile.exists());
- Thread.sleep(10* INTERVAL); // Give task loop time to delete aged
files
-
+ Thread.sleep(10 * INTERVAL); // Give task loop time to delete aged
files
// All files should be gone by now
assertFalse("File A should no longer exist", aFile.exists());
assertFalse("File B should no longer exist", bFile.exists());
assertFalse("File C should no longer exist", cFile.exists());
} finally {
-
- // Reset the timeout to the previous value so that no
+
+ // Reset the timeout to the previous value so that no
// other tests are affected
acm.setTimeout(previousTime);
}
diff --git
a/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/AttachmentsTest.java
b/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/AttachmentsTest.java
index 49bde7850..79b38c138 100644
---
a/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/AttachmentsTest.java
+++
b/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/AttachmentsTest.java
@@ -73,13 +73,14 @@ public class AttachmentsTest extends AbstractTestCase {
attachmentsDir.mkdirs();
return attachmentsDir.getAbsolutePath();
}
-
+
public void testGetDataHandler() throws Exception {
InputStream inStream = MTOMSample.SAMPLE1.getInputStream();
Attachments attachments = new Attachments(inStream,
MTOMSample.SAMPLE1.getContentType());
- DataHandler dh = attachments
-
.getDataHandler("2.urn:uuid:[email protected]");
+ DataHandler dh =
+ attachments.getDataHandler(
+
"2.urn:uuid:[email protected]");
InputStream dataIs = dh.getDataSource().getInputStream();
InputStream expectedDataIs = MTOMSample.SAMPLE1.getPart(2);
@@ -112,21 +113,23 @@ public class AttachmentsTest extends AbstractTestCase {
assertEquals("1.urn:uuid:[email protected]",
contentIDs[1]);
assertEquals("2.urn:uuid:[email protected]",
contentIDs[2]);
}
-
+
public void testGetAllContentIDsWithoutStream() {
Attachments attachments = new Attachments();
// The choice of content IDs here makes sure that we test that the
attachments are returned
// in the order in which they have been added (instead of sorted by
content ID as in
// earlier Axiom versions)
- attachments.addDataHandler("[email protected]", new
DataHandler("content1", "text/plain"));
- attachments.addDataHandler("[email protected]", new
DataHandler("content2", "text/plain"));
-
+ attachments.addDataHandler(
+ "[email protected]", new DataHandler("content1",
"text/plain"));
+ attachments.addDataHandler(
+ "[email protected]", new DataHandler("content2",
"text/plain"));
+
String[] contentIDs = attachments.getAllContentIDs();
assertEquals(2, contentIDs.length);
assertEquals("[email protected]", contentIDs[0]);
assertEquals("[email protected]", contentIDs[1]);
}
-
+
public void testGetContentIDSet() {
InputStream inStream = MTOMSample.SAMPLE1.getInputStream();
Attachments attachments = new Attachments(inStream,
MTOMSample.SAMPLE1.getContentType());
@@ -136,44 +139,45 @@ public class AttachmentsTest extends AbstractTestCase {
assertTrue(idSet.contains("2.urn:uuid:[email protected]"));
assertTrue(idSet.contains("1.urn:uuid:[email protected]"));
}
-
+
public void testGetContentIDSetWithoutStream() {
Attachments attachments = new Attachments();
attachments.addDataHandler("[email protected]", new
DataHandler("content1", "text/plain"));
attachments.addDataHandler("[email protected]", new
DataHandler("content2", "text/plain"));
attachments.addDataHandler("[email protected]", new
DataHandler("content3", "text/plain"));
-
+
Set<String> idSet = attachments.getContentIDSet();
assertTrue(idSet.contains("[email protected]"));
assertTrue(idSet.contains("[email protected]"));
assertTrue(idSet.contains("[email protected]"));
}
-
+
public void testGetContentLength() throws IOException {
InputStream inStream = MTOMSample.SAMPLE1.getInputStream();
Attachments attachments = new Attachments(inStream,
MTOMSample.SAMPLE1.getContentType());
-
+
// Make sure the length is correct
long length = attachments.getContentLength();
long fileSize =
IOUtils.toByteArray(MTOMSample.SAMPLE1.getInputStream()).length;
assertEquals("Return value of getContentLength()", fileSize, length);
}
-
+
/**
* Tests that {@link Attachments#getContentLength()} returns
<code>-1</code> if the object is
* not stream backed.
- *
+ *
* @throws IOException
*/
public void testGetContentLengthWithoutStream() throws IOException {
Attachments attachments = new Attachments();
- attachments.addDataHandler(UIDGenerator.generateContentId(), new
DataHandler("test", "text/plain"));
+ attachments.addDataHandler(
+ UIDGenerator.generateContentId(), new DataHandler("test",
"text/plain"));
assertEquals(-1, attachments.getContentLength());
}
private void testGetRootPartContentID(String contentTypeStartParam, String
contentId)
throws Exception {
- MimeMessage message = new MimeMessage((Session)null);
+ MimeMessage message = new MimeMessage((Session) null);
MimeMultipart mp = new MimeMultipart("related");
MimeBodyPart rootPart = new MimeBodyPart();
rootPart.setDataHandler(new DataHandler(new TextDataSource("<root/>",
"utf-8", "xml")));
@@ -187,61 +191,67 @@ public class AttachmentsTest extends AbstractTestCase {
mp.writeTo(out);
out.close();
- Attachments attachments = new Attachments(
- blob.getInputStream(),
- new ContentType(message.getContentType())
- .toBuilder()
- .setParameter("start", contentTypeStartParam)
- .build()
- .toString());
- assertEquals("Did not obtain correct content ID", contentId,
- attachments.getRootPartContentID());
- }
-
+ Attachments attachments =
+ new Attachments(
+ blob.getInputStream(),
+ new ContentType(message.getContentType())
+ .toBuilder()
+ .setParameter("start",
contentTypeStartParam)
+ .build()
+ .toString());
+ assertEquals(
+ "Did not obtain correct content ID", contentId,
attachments.getRootPartContentID());
+ }
+
public void testGetRootPartContentIDWithoutBrackets() throws Exception {
testGetRootPartContentID("my-content-id@localhost",
"my-content-id@localhost");
}
-
+
public void testGetRootPartContentIDWithBrackets() throws Exception {
testGetRootPartContentID("<my-content-id@localhost>",
"my-content-id@localhost");
}
-
+
// Not sure when exactly somebody uses the "cid:" prefix in the start
parameter, but
// this is how the code currently works.
public void testGetRootPartContentIDWithCidPrefix() throws Exception {
testGetRootPartContentID("cid:my-content-id@localhost",
"my-content-id@localhost");
}
-
+
// Regression test for AXIOM-195
public void testGetRootPartContentIDWithCidPrefix2() throws Exception {
testGetRootPartContentID("<[email protected]>",
"[email protected]");
}
-
+
public void testGetRootPartContentIDShort() throws Exception {
testGetRootPartContentID("bbb", "bbb");
}
-
+
public void testGetRootPartContentIDShortWithBrackets() throws Exception {
testGetRootPartContentID("<b>", "b");
}
-
+
public void testGetRootPartContentIDBorderline() throws Exception {
testGetRootPartContentID("cid:", "cid:");
}
-
+
/**
* Tests that {@link Attachments#getRootPartContentType()} throws a
meaningful exception if it
* is unable to determine the content type.
*/
public void testGetRootPartContentTypeWithContentIDMismatch() {
- String contentType = "multipart/related; boundary=\"" +
MTOMSample.SAMPLE1.getBoundary() +
- "\"; type=\"text/xml\";
start=\"<[email protected]>\"";
- assertThrows(MIMEException.class, () -> {
- Attachments attachments = new
Attachments(MTOMSample.SAMPLE1.getInputStream(), contentType);
- attachments.getRootPartContentType();
- });
- }
-
+ String contentType =
+ "multipart/related; boundary=\""
+ + MTOMSample.SAMPLE1.getBoundary()
+ + "\"; type=\"text/xml\";
start=\"<[email protected]>\"";
+ assertThrows(
+ MIMEException.class,
+ () -> {
+ Attachments attachments =
+ new
Attachments(MTOMSample.SAMPLE1.getInputStream(), contentType);
+ attachments.getRootPartContentType();
+ });
+ }
+
public void testGetIncomingAttachmentStreams() throws Exception {
InputStream inStream = MTOMSample.SAMPLE1.getInputStream();
Attachments attachments = new Attachments(inStream,
MTOMSample.SAMPLE1.getContentType());
@@ -255,16 +265,17 @@ public class AttachmentsTest extends AbstractTestCase {
dataIs = ias.getNextStream();
// Make sure it was the first attachment
-
assertEquals("<1.urn:uuid:[email protected]>",
- dataIs.getContentId());
+ assertEquals(
+ "<1.urn:uuid:[email protected]>",
dataIs.getContentId());
// Consume the stream
- while (dataIs.read() != -1) ;
+ while (dataIs.read() != -1)
+ ;
// Img2 stream
dataIs = ias.getNextStream();
-
assertEquals("<2.urn:uuid:[email protected]>",
- dataIs.getContentId());
+ assertEquals(
+ "<2.urn:uuid:[email protected]>",
dataIs.getContentId());
// Test if getContentType() works..
assertEquals("image/jpeg", dataIs.getContentType());
@@ -273,7 +284,7 @@ public class AttachmentsTest extends AbstractTestCase {
dataIs.addHeader("new-header", "test-value");
assertEquals("test-value", dataIs.getHeader("new-header"));
}
-
+
public void testGetIncomingAttachmentStreams2() throws Exception {
MTOMSample sample = MTOMSample.SAMPLE1;
@@ -287,7 +298,8 @@ public class AttachmentsTest extends AbstractTestCase {
// directly, and then get to the streams. If this sequence throws an
// error, something is wrong with the stream handling code.
InputStream is = attachments.getRootPartInputStream();
- while (is.read() != -1) ;
+ while (is.read() != -1)
+ ;
// Get the inputstream container
IncomingAttachmentStreams ias =
attachments.getIncomingAttachmentStreams();
@@ -302,22 +314,23 @@ public class AttachmentsTest extends AbstractTestCase {
// Confirm that no more streams are left
assertNull(ias.getNextStream());
-
+
// After all is done, we should *still* be able to access and
// re-consume the SOAP part stream, as it should be cached.. can we?
is = attachments.getRootPartInputStream();
- while (is.read() != -1) ;
+ while (is.read() != -1)
+ ;
}
-
+
public void testSimultaneousStreamAccess1() throws Exception {
InputStream inStream = MTOMSample.SAMPLE1.getInputStream();
Attachments attachments = new Attachments(inStream,
MTOMSample.SAMPLE1.getContentType());
-
+
attachments.getDataHandler("2.urn:uuid:[email protected]");
-
+
// This should throw an error
assertThrows(IllegalStateException.class,
attachments::getIncomingAttachmentStreams);
-
+
inStream.close();
}
@@ -325,28 +338,34 @@ public class AttachmentsTest extends AbstractTestCase {
// Try the other way around.
InputStream inStream = MTOMSample.SAMPLE1.getInputStream();
Attachments attachments = new Attachments(inStream,
MTOMSample.SAMPLE1.getContentType());
-
+
attachments.getIncomingAttachmentStreams();
-
+
// These should NOT throw error even though they are using part based
access
String contentType = attachments.getRootPartContentType();
- assertTrue(contentType.indexOf("application/xop+xml;") >=0);
- assertTrue(contentType.indexOf("charset=UTF-8;") >=0);
- assertTrue(contentType.indexOf("type=\"application/soap+xml\";") >=0);
-
+ assertTrue(contentType.indexOf("application/xop+xml;") >= 0);
+ assertTrue(contentType.indexOf("charset=UTF-8;") >= 0);
+ assertTrue(contentType.indexOf("type=\"application/soap+xml\";") >= 0);
+
attachments.getRootPartInputStream();
-
+
// These should throw an error
- assertThrows(IllegalStateException.class, () ->
-
attachments.getDataHandler("2.urn:uuid:[email protected]"));
-
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ attachments.getDataHandler(
+
"2.urn:uuid:[email protected]"));
+
// Additionally, we also need to ensure mutual exclusion if someone
// tries to access part data directly
-
+
assertThrows(IllegalStateException.class,
attachments::getAllContentIDs);
-
- assertThrows(IllegalStateException.class, () ->
-
attachments.getDataHandler("2.urn:uuid:[email protected]"));
+
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ attachments.getDataHandler(
+
"2.urn:uuid:[email protected]"));
}
public void testRemoveDataHandlerAfterParsing() {
@@ -355,10 +374,10 @@ public class AttachmentsTest extends AbstractTestCase {
Set<String> list = attachments.getContentIDSet();
assertEquals(3, list.size());
-
+
assertTrue(list.contains("1.urn:uuid:[email protected]"));
assertTrue(list.contains("2.urn:uuid:[email protected]"));
-
+
attachments.removeDataHandler("1.urn:uuid:[email protected]");
List<String> list2 = attachments.getContentIDList();
@@ -383,7 +402,7 @@ public class AttachmentsTest extends AbstractTestCase {
assertFalse(idSet.contains("1.urn:uuid:[email protected]"));
assertTrue(idSet.contains("2.urn:uuid:[email protected]"));
}
-
+
/**
* Tests that {@link Attachments#removeDataHandler(String)} returns
silently if the message
* doesn't contain a MIME part with the specified content ID.
@@ -409,9 +428,9 @@ public class AttachmentsTest extends AbstractTestCase {
private void testReadBase64EncodedAttachment(boolean useFile) throws
Exception {
// Note: We are only interested in the MimeMultipart, but we need to
create a
// MimeMessage to be able to calculate the correct content type
- MimeMessage message = new MimeMessage((Session)null);
+ MimeMessage message = new MimeMessage((Session) null);
MimeMultipart mp = new MimeMultipart("related");
-
+
// Prepare the "SOAP" part
MimeBodyPart bp1 = new MimeBodyPart();
// Obviously this is not SOAP, but this is irrelevant for this test
@@ -419,23 +438,24 @@ public class AttachmentsTest extends AbstractTestCase {
bp1.addHeader("Content-Transfer-Encoding", "binary");
bp1.addHeader("Content-ID", "[email protected]");
mp.addBodyPart(bp1);
-
+
// Prepare the attachment
MimeBodyPart bp2 = new MimeBodyPart();
byte[] content = new byte[8192];
new Random().nextBytes(content);
- bp2.setDataHandler(new DataHandler(new ByteArrayDataSource(content,
"application/octet-stream")));
+ bp2.setDataHandler(
+ new DataHandler(new ByteArrayDataSource(content,
"application/octet-stream")));
bp2.addHeader("Content-Transfer-Encoding", "base64");
bp2.addHeader("Content-ID", "[email protected]");
mp.addBodyPart(bp2);
-
+
message.setContent(mp);
// Compute the correct content type
message.saveChanges();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mp.writeTo(baos);
String contentType = message.getContentType();
-
+
InputStream in = new ByteArrayInputStream(baos.toByteArray());
Attachments attachments;
if (useFile) {
@@ -458,114 +478,134 @@ public class AttachmentsTest extends AbstractTestCase {
/**
* Tests that {@link Attachments} can successfully read an attachment with
zero length. This is
- * a regression test for
- * <a href="https://issues.apache.org/jira/browse/AXIOM-383">AXIOM-383</a>.
- *
+ * a regression test for <a
+ * href="https://issues.apache.org/jira/browse/AXIOM-383">AXIOM-383</a>.
+ *
* @throws Exception
*/
public void testZeroLengthAttachment() throws Exception {
InputStream in = getTestResource("mtom/zero-length-attachment.bin");
try {
- Attachments attachments = new Attachments(in,
- "multipart/related; " +
-
"boundary=MIMEBoundaryurn_uuid_0549F3F826EC3041861188639371825; " +
- "type=\"application/xop+xml\"; " +
-
"start=\"0.urn:uuid:[email protected]\"; " +
- "start-info=\"application/soap+xml\";
action=\"urn:test\"");
- DataHandler dh =
attachments.getDataHandler("1.urn:uuid:[email protected]");
+ Attachments attachments =
+ new Attachments(
+ in,
+ "multipart/related; "
+ +
"boundary=MIMEBoundaryurn_uuid_0549F3F826EC3041861188639371825; "
+ + "type=\"application/xop+xml\"; "
+ +
"start=\"0.urn:uuid:[email protected]\"; "
+ + "start-info=\"application/soap+xml\";
action=\"urn:test\"");
+ DataHandler dh =
+ attachments.getDataHandler(
+
"1.urn:uuid:[email protected]");
InputStream content = dh.getInputStream();
assertEquals(-1, content.read());
} finally {
in.close();
}
}
-
+
public void testPurgeDataSource() throws Exception {
InputStream in = getTestResource("mtom/msg-soap-wls81.txt");
MyLifecycleManager manager = new MyLifecycleManager();
- Attachments attachments = new Attachments(manager, in,
-
"multipart/related;type=\"text/xml\";boundary=\"----=_Part_0_3437046.1188904239130\";start=__WLS__1188904239161__SOAP__",
- true, getAttachmentsDir(), "1024");
-
+ Attachments attachments =
+ new Attachments(
+ manager,
+ in,
+
"multipart/related;type=\"text/xml\";boundary=\"----=_Part_0_3437046.1188904239130\";start=__WLS__1188904239161__SOAP__",
+ true,
+ getAttachmentsDir(),
+ "1024");
+
// Read the attachment once to make sure it is buffered
DataHandler dh =
attachments.getDataHandler("__WLS__1188904239162__SOAP__");
assertTrue(dh instanceof DataHandlerExt);
InputStream content = dh.getInputStream();
IOUtils.copy(content, NullOutputStream.NULL_OUTPUT_STREAM);
content.close();
-
+
assertEquals(1, manager.getFileCount());
- ((DataHandlerExt)dh).purgeDataSource();
+ ((DataHandlerExt) dh).purgeDataSource();
assertEquals(0, manager.getFileCount());
-
+
in.close();
}
-
+
/**
* Tests that after consuming the input stream returned by {@link
DataHandlerExt#readOnce()} for
* an attachment that has been buffered on disk, the temporary file for
that attachment is
* deleted.
- *
+ *
* @throws Exception
*/
public void testReadOnceOnBufferedPart() throws Exception {
InputStream in = getTestResource("mtom/msg-soap-wls81.txt");
MyLifecycleManager manager = new MyLifecycleManager();
- Attachments attachments = new Attachments(manager, in,
-
"multipart/related;type=\"text/xml\";boundary=\"----=_Part_0_3437046.1188904239130\";start=__WLS__1188904239161__SOAP__",
- true, getAttachmentsDir(), "1024");
-
+ Attachments attachments =
+ new Attachments(
+ manager,
+ in,
+
"multipart/related;type=\"text/xml\";boundary=\"----=_Part_0_3437046.1188904239130\";start=__WLS__1188904239161__SOAP__",
+ true,
+ getAttachmentsDir(),
+ "1024");
+
// Read the attachment once to make sure it is buffered
DataHandler dh =
attachments.getDataHandler("__WLS__1188904239162__SOAP__");
InputStream content = dh.getInputStream();
IOUtils.copy(content, NullOutputStream.NULL_OUTPUT_STREAM);
content.close();
-
+
assertEquals(1, manager.getFileCount());
// Now consume the content of the attachment
- content = ((DataHandlerExt)dh).readOnce();
+ content = ((DataHandlerExt) dh).readOnce();
IOUtils.copy(content, NullOutputStream.NULL_OUTPUT_STREAM);
content.close();
-
+
// The temporary file should have been deleted
assertEquals(0, manager.getFileCount());
-
+
in.close();
}
-
+
/**
* Tests that attachments are correctly buffered on file if the threshold
is very low. This is a
* regression test for <a
href="https://issues.apache.org/jira/browse/AXIOM-61">AXIOM-61</a>.
- *
+ *
* @throws Exception
*/
public void testFileBufferingWithLowThreshold() throws Exception {
InputStream in = getTestResource("mtom/msg-soap-wls81.txt");
- Attachments attachments = new Attachments(in,
-
"multipart/related;type=\"text/xml\";boundary=\"----=_Part_0_3437046.1188904239130\";start=__WLS__1188904239161__SOAP__",
- true, getAttachmentsDir(), "1");
-
+ Attachments attachments =
+ new Attachments(
+ in,
+
"multipart/related;type=\"text/xml\";boundary=\"----=_Part_0_3437046.1188904239130\";start=__WLS__1188904239161__SOAP__",
+ true,
+ getAttachmentsDir(),
+ "1");
+
DataHandler dh =
attachments.getDataHandler("__WLS__1188904239162__SOAP__");
- BufferedReader reader = new BufferedReader(new
InputStreamReader(dh.getInputStream(), StandardCharsets.UTF_8));
+ BufferedReader reader =
+ new BufferedReader(
+ new InputStreamReader(dh.getInputStream(),
StandardCharsets.UTF_8));
assertEquals("%PDF-1.3", reader.readLine());
reader.close();
-
+
in.close();
}
/**
* Tests that a call to {@link DataHandlerExt#readOnce()} on a {@link
DataHandler} returned by
* the {@link Attachments} object streams the content of the MIME part.
- *
+ *
* @throws Exception
*/
public void testDataHandlerStreaming() throws Exception {
// Note: We are only interested in the MimeMultipart, but we need to
create a
// MimeMessage to be able to calculate the correct content type
- MimeMessage message = new MimeMessage((Session)null);
+ MimeMessage message = new MimeMessage((Session) null);
final MimeMultipart mp = new MimeMultipart("related");
-
+
// Prepare the "SOAP" part
MimeBodyPart bp1 = new MimeBodyPart();
// Obviously this is not SOAP, but this is irrelevant for this test
@@ -573,42 +613,45 @@ public class AttachmentsTest extends AbstractTestCase {
bp1.addHeader("Content-Transfer-Encoding", "binary");
bp1.addHeader("Content-ID", "[email protected]");
mp.addBodyPart(bp1);
-
+
// Create an attachment that is larger than the maximum heap
- Blob blob = new
RandomBlob((int)Math.min(Runtime.getRuntime().maxMemory(), Integer.MAX_VALUE));
+ Blob blob =
+ new RandomBlob((int)
Math.min(Runtime.getRuntime().maxMemory(), Integer.MAX_VALUE));
MimeBodyPart bp2 = new MimeBodyPart();
bp2.setDataHandler(DataHandlerUtils.toDataHandler(blob));
bp2.addHeader("Content-Transfer-Encoding", "binary");
bp2.addHeader("Content-ID", "[email protected]");
mp.addBodyPart(bp2);
-
+
message.setContent(mp);
// Compute the correct content type
message.saveChanges();
-
+
// We use a pipe (with a producer running in a separate thread)
because obviously we can't
// store the multipart in memory.
PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = new PipedInputStream(pipeOut);
-
- Thread producerThread = new Thread(() -> {
- try {
- try {
- mp.writeTo(pipeOut);
- } finally {
- pipeOut.close();
- }
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- });
+
+ Thread producerThread =
+ new Thread(
+ () -> {
+ try {
+ try {
+ mp.writeTo(pipeOut);
+ } finally {
+ pipeOut.close();
+ }
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ }
+ });
producerThread.start();
-
+
try {
// We configure Attachments to buffer MIME parts in memory. If the
part content is not
// streamed, then this will result in an OOM error.
Attachments attachments = new Attachments(pipeIn,
message.getContentType());
- DataHandlerExt dh =
(DataHandlerExt)attachments.getDataHandler("[email protected]");
+ DataHandlerExt dh = (DataHandlerExt)
attachments.getDataHandler("[email protected]");
IOTestUtils.compareStreams(blob.getInputStream(), dh.readOnce());
} finally {
pipeIn.close();
@@ -619,14 +662,14 @@ public class AttachmentsTest extends AbstractTestCase {
Locale locale = Locale.getDefault();
Locale.setDefault(new Locale("tr", "TR"));
try {
- MimeMessage message = new MimeMessage((Session)null);
+ MimeMessage message = new MimeMessage((Session) null);
MimeMultipart mp = new MimeMultipart("related");
-
+
MimeBodyPart bp1 = new MimeBodyPart();
bp1.setDataHandler(new DataHandler(new TextDataSource("<root/>",
"utf-8", "xml")));
bp1.addHeader("Content-Transfer-Encoding", "binary");
mp.addBodyPart(bp1);
-
+
MimeBodyPart bp2 = new MimeBodyPart();
byte[] content = new byte[8192];
new Random().nextBytes(content);
@@ -634,13 +677,13 @@ public class AttachmentsTest extends AbstractTestCase {
bp2.addHeader("Content-Transfer-Encoding", "binary");
bp2.addHeader(contentIDHeaderName, "[email protected]");
mp.addBodyPart(bp2);
-
+
message.setContent(mp);
message.saveChanges();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
mp.writeTo(baos);
String contentType = message.getContentType();
-
+
InputStream in = new ByteArrayInputStream(baos.toByteArray());
Attachments attachments = new Attachments(in, contentType);
assertNotNull(attachments.getDataHandler("[email protected]"));
@@ -657,8 +700,9 @@ public class AttachmentsTest extends AbstractTestCase {
public void testTurkishLocale2() throws Exception {
testTurkishLocale("content-id");
}
-
- private void testGetAttachmentSpecType(MIMESample resource, String
expectedResult) throws Exception {
+
+ private void testGetAttachmentSpecType(MIMESample resource, String
expectedResult)
+ throws Exception {
InputStream in = resource.getInputStream();
try {
Attachments attachments = new Attachments(in,
resource.getContentType());
@@ -667,15 +711,15 @@ public class AttachmentsTest extends AbstractTestCase {
in.close();
}
}
-
+
public void testGetAttachmentSpecTypeMTOM() throws Exception {
testGetAttachmentSpecType(MTOMSample.SAMPLE1, MTOMConstants.MTOM_TYPE);
}
-
+
public void testGetAttachmentSpecTypeSWA() throws Exception {
testGetAttachmentSpecType(SwASample.SAMPLE1, MTOMConstants.SWA_TYPE);
}
-
+
public void testGetAttachmentSpecTypeWithoutStream() {
assertThrows(OMException.class, () -> new
Attachments().getAttachmentSpecType());
}
@@ -685,45 +729,63 @@ public class AttachmentsTest extends AbstractTestCase {
try {
Attachments attachments;
if (useFiles) {
- attachments = new Attachments(in,
MTOMSample.SAMPLE1.getContentType(),
- true, getAttachmentsDir(), "4096");
+ attachments =
+ new Attachments(
+ in,
+ MTOMSample.SAMPLE1.getContentType(),
+ true,
+ getAttachmentsDir(),
+ "4096");
} else {
attachments = new Attachments(in,
MTOMSample.SAMPLE1.getContentType());
}
- DataHandler dh = attachments
-
.getDataHandler("2.urn:uuid:[email protected]");
+ DataHandler dh =
+ attachments.getDataHandler(
+
"2.urn:uuid:[email protected]");
DataSource ds = dh.getDataSource();
assertTrue(ds instanceof SizeAwareDataSource);
- assertEquals(13887, ((SizeAwareDataSource)ds).getSize());
+ assertEquals(13887, ((SizeAwareDataSource) ds).getSize());
} finally {
in.close();
}
}
-
+
public void testGetSizeOnDataSourceOnMemory() throws Exception {
testGetSizeOnDataSource(false);
}
-
+
public void testGetSizeOnDataSourceOnFile() throws Exception {
testGetSizeOnDataSource(true);
}
-
+
public void testIOExceptionInPartHeaders() throws Exception {
InputStream in = MTOMSample.SAMPLE1.getInputStream();
try {
- Attachments attachments = new Attachments(new
ExceptionInputStream(in, 1050), MTOMSample.SAMPLE1.getContentType());
+ Attachments attachments =
+ new Attachments(
+ new ExceptionInputStream(in, 1050),
+ MTOMSample.SAMPLE1.getContentType());
// TODO: decide what exception should be thrown exactly here
- assertThrows(MIMEException.class, () ->
attachments.getDataHandler("1.urn:uuid:[email protected]"));
+ assertThrows(
+ MIMEException.class,
+ () ->
+ attachments.getDataHandler(
+
"1.urn:uuid:[email protected]"));
} finally {
in.close();
}
}
-
+
public void testIOExceptionInPartContent() throws Exception {
InputStream in = MTOMSample.SAMPLE1.getInputStream();
try {
- Attachments attachments = new Attachments(new
ExceptionInputStream(in, 1500), MTOMSample.SAMPLE1.getContentType());
- DataHandler dh =
attachments.getDataHandler("1.urn:uuid:[email protected]");
+ Attachments attachments =
+ new Attachments(
+ new ExceptionInputStream(in, 1500),
+ MTOMSample.SAMPLE1.getContentType());
+ DataHandler dh =
+ attachments.getDataHandler(
+
"1.urn:uuid:[email protected]");
// TODO: decide what exception should be thrown exactly here
assertThrows(MIMEException.class, dh::getInputStream);
} finally {
@@ -735,45 +797,45 @@ public class AttachmentsTest extends AbstractTestCase {
* Regression test for <a
href="https://issues.apache.org/jira/browse/AXIOM-467">AXIOM-467</a>.
*/
public void testQuotedPrintable() throws Exception {
- Attachments attachments = new Attachments(
- MTOMSample.QUOTED_PRINTABLE.getInputStream(),
- MTOMSample.QUOTED_PRINTABLE.getContentType());
+ Attachments attachments =
+ new Attachments(
+ MTOMSample.QUOTED_PRINTABLE.getInputStream(),
+ MTOMSample.QUOTED_PRINTABLE.getContentType());
DataHandler dh =
attachments.getDataHandler("SDESS_COREP_00000_KO_SNG.xml");
- IOTestUtils.compareStreams(
- MTOMSample.QUOTED_PRINTABLE.getPart(1),
- dh.getInputStream());
+ IOTestUtils.compareStreams(MTOMSample.QUOTED_PRINTABLE.getPart(1),
dh.getInputStream());
}
/**
- * Tests access to a root part that doesn't have a content ID. In this
case, the
- * {@link Attachments} API generates a fake content ID.
- *
+ * Tests access to a root part that doesn't have a content ID. In this
case, the {@link
+ * Attachments} API generates a fake content ID.
+ *
* @throws Exception
*/
public void testFakeRootPartContentID() throws Exception {
- MimeMessage message = new MimeMessage((Session)null);
+ MimeMessage message = new MimeMessage((Session) null);
MimeMultipart mp = new MimeMultipart("related");
- DataHandler expectedRootPart = new DataHandler(new
TextDataSource("<root/>", "utf-8", "xml"));
+ DataHandler expectedRootPart =
+ new DataHandler(new TextDataSource("<root/>", "utf-8", "xml"));
MimeBodyPart bp1 = new MimeBodyPart();
bp1.setDataHandler(expectedRootPart);
bp1.addHeader("Content-Transfer-Encoding", "binary");
mp.addBodyPart(bp1);
-
+
MimeBodyPart bp2 = new MimeBodyPart();
bp2.setDataHandler(new DataHandler(new TextDataSource("Test", "utf-8",
"plain")));
bp2.addHeader("Content-Transfer-Encoding", "binary");
mp.addBodyPart(bp2);
-
+
message.setContent(mp);
message.saveChanges();
-
+
MemoryBlob blob = Blobs.createMemoryBlob();
OutputStream out = blob.getOutputStream();
mp.writeTo(out);
out.close();
String contentType = message.getContentType();
-
+
Attachments attachments = new Attachments(blob.getInputStream(),
contentType);
String rootPartContentID = attachments.getRootPartContentID();
assertThat(rootPartContentID).isNotNull();
diff --git
a/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/ConfigurableDataHandlerTest.java
b/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/ConfigurableDataHandlerTest.java
index e525885ea..726c2c8ec 100644
---
a/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/ConfigurableDataHandlerTest.java
+++
b/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/ConfigurableDataHandlerTest.java
@@ -29,31 +29,39 @@ import org.junit.Test;
public class ConfigurableDataHandlerTest {
@Test
public void testContentTransferEncoding() {
- ConfigurableDataHandler dh = new ConfigurableDataHandler(new byte[10],
- "application/octet-stream");
+ ConfigurableDataHandler dh =
+ new ConfigurableDataHandler(new byte[10],
"application/octet-stream");
dh.setTransferEncoding("base64");
- assertThat(ConfigurableDataHandler.CONTENT_TRANSFER_ENCODING_POLICY
- .getContentTransferEncoding(DataHandlerUtils.toBlob(dh),
- new ContentType(MediaType.APPLICATION_OCTET_STREAM)))
-
.isSameInstanceAs(ContentTransferEncoding.BASE64);
+ assertThat(
+
ConfigurableDataHandler.CONTENT_TRANSFER_ENCODING_POLICY
+ .getContentTransferEncoding(
+ DataHandlerUtils.toBlob(dh),
+ new
ContentType(MediaType.APPLICATION_OCTET_STREAM)))
+ .isSameInstanceAs(ContentTransferEncoding.BASE64);
}
@Test
public void testContentTransferEncodingNotSet() {
- ConfigurableDataHandler dh = new ConfigurableDataHandler(new byte[10],
- "application/octet-stream");
- assertThat(ConfigurableDataHandler.CONTENT_TRANSFER_ENCODING_POLICY
- .getContentTransferEncoding(DataHandlerUtils.toBlob(dh),
- new
ContentType(MediaType.APPLICATION_OCTET_STREAM))).isNull();
+ ConfigurableDataHandler dh =
+ new ConfigurableDataHandler(new byte[10],
"application/octet-stream");
+ assertThat(
+
ConfigurableDataHandler.CONTENT_TRANSFER_ENCODING_POLICY
+ .getContentTransferEncoding(
+ DataHandlerUtils.toBlob(dh),
+ new
ContentType(MediaType.APPLICATION_OCTET_STREAM)))
+ .isNull();
}
@Test
public void testContentTransferEncodingNotRecognized() {
- ConfigurableDataHandler dh = new ConfigurableDataHandler(new byte[10],
- "application/octet-stream");
+ ConfigurableDataHandler dh =
+ new ConfigurableDataHandler(new byte[10],
"application/octet-stream");
dh.setTransferEncoding("foobar");
- assertThat(ConfigurableDataHandler.CONTENT_TRANSFER_ENCODING_POLICY
- .getContentTransferEncoding(DataHandlerUtils.toBlob(dh),
- new
ContentType(MediaType.APPLICATION_OCTET_STREAM))).isNull();
+ assertThat(
+
ConfigurableDataHandler.CONTENT_TRANSFER_ENCODING_POLICY
+ .getContentTransferEncoding(
+ DataHandlerUtils.toBlob(dh),
+ new
ContentType(MediaType.APPLICATION_OCTET_STREAM)))
+ .isNull();
}
}
diff --git
a/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/MyLifecycleManager.java
b/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/MyLifecycleManager.java
index d452e554b..4246ebfb0 100644
---
a/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/MyLifecycleManager.java
+++
b/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/MyLifecycleManager.java
@@ -41,7 +41,7 @@ public class MyLifecycleManager extends LifecycleManagerImpl {
super.delete(file);
files.remove(file);
}
-
+
public int getFileCount() {
return files.size();
}
diff --git
a/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/PartOnFileTest.java
b/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/PartOnFileTest.java
index 180927519..93fdfa720 100644
---
a/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/PartOnFileTest.java
+++
b/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/PartOnFileTest.java
@@ -32,7 +32,6 @@ import java.io.InputStream;
import junit.framework.TestCase;
/** Test the PartOnFile class */
-
public class PartOnFileTest extends TestCase {
public PartOnFileTest(String testName) {
@@ -55,11 +54,13 @@ public class PartOnFileTest extends TestCase {
InputStream inStream = MTOMSample.SAMPLE1.getInputStream();
Attachments attachments =
- new Attachments(inStream, MTOMSample.SAMPLE1.getContentType(),
true, temp.getPath(), "1");
+ new Attachments(
+ inStream, MTOMSample.SAMPLE1.getContentType(), true,
temp.getPath(), "1");
+
+ DataHandler dh =
+ attachments.getDataHandler(
+
"1.urn:uuid:[email protected]");
- DataHandler dh = attachments
-
.getDataHandler("1.urn:uuid:[email protected]");
-
assertNotNull(dh);
DataSource ds = dh.getDataSource();
diff --git
a/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/PdfAttachmentStreamingTest.java
b/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/PdfAttachmentStreamingTest.java
index a30dd0dd5..dac52c3df 100644
---
a/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/PdfAttachmentStreamingTest.java
+++
b/axiom-legacy-attachments/src/test/java/org/apache/axiom/attachments/PdfAttachmentStreamingTest.java
@@ -18,7 +18,6 @@
*/
package org.apache.axiom.attachments;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -30,51 +29,49 @@ import org.apache.axiom.om.AbstractTestCase;
public class PdfAttachmentStreamingTest extends AbstractTestCase {
- String contentType =
"multipart/related;type=\"text/xml\";boundary=\"----=_Part_0_3437046.1188904239130\";start=__WLS__1188904239161__SOAP__";
- String inputFile = "mtom/msg-soap-wls81.txt";
-
- public PdfAttachmentStreamingTest(String name) {
- super(name);
- }
-
- public void testStreamingAttachments() throws Exception {
- InputStream inStream = getTestResource(inputFile);
- // creating attachments using that stream
- Attachments attachments = new Attachments(inStream,
contentType);
+ String contentType =
+
"multipart/related;type=\"text/xml\";boundary=\"----=_Part_0_3437046.1188904239130\";start=__WLS__1188904239161__SOAP__";
+ String inputFile = "mtom/msg-soap-wls81.txt";
+
+ public PdfAttachmentStreamingTest(String name) {
+ super(name);
+ }
+
+ public void testStreamingAttachments() throws Exception {
+ InputStream inStream = getTestResource(inputFile);
+ // creating attachments using that stream
+ Attachments attachments = new Attachments(inStream, contentType);
- // getting attachments as streams
- IncomingAttachmentStreams attachStreams =
attachments.getIncomingAttachmentStreams();
-
+ // getting attachments as streams
+ IncomingAttachmentStreams attachStreams =
attachments.getIncomingAttachmentStreams();
- // getting first attachments after the soap part
- IncomingAttachmentInputStream firstAttach =
attachStreams.getNextStream();
-
- // coping contents of the attachment to byte array
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- copy(firstAttach, output);
+ // getting first attachments after the soap part
+ IncomingAttachmentInputStream firstAttach =
attachStreams.getNextStream();
- // reading the message again, getting second attachment using
datahandlers
- inStream = getTestResource(inputFile);
- attachments = new Attachments(inStream, contentType);
- DataHandler h =
attachments.getDataHandler(attachments.getAllContentIDs()[1]);
+ // coping contents of the attachment to byte array
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ copy(firstAttach, output);
- ByteArrayOutputStream input = new ByteArrayOutputStream();
- copy(h.getInputStream(), input);
+ // reading the message again, getting second attachment using
datahandlers
+ inStream = getTestResource(inputFile);
+ attachments = new Attachments(inStream, contentType);
+ DataHandler h =
attachments.getDataHandler(attachments.getAllContentIDs()[1]);
- assertEquals(input.toString("UTF-8"), output.toString("UTF-8"));
- }
-
+ ByteArrayOutputStream input = new ByteArrayOutputStream();
+ copy(h.getInputStream(), input);
+ assertEquals(input.toString("UTF-8"), output.toString("UTF-8"));
+ }
- public static void copy(InputStream in, OutputStream out) throws
IOException {
- byte[] buf = new byte[4096];
- while(true) {
- int len = in.read(buf);
- if (len != -1) {
- out.write(buf, 0, len);
- } else {
- break;
- }
- }
- }
+ public static void copy(InputStream in, OutputStream out) throws
IOException {
+ byte[] buf = new byte[4096];
+ while (true) {
+ int len = in.read(buf);
+ if (len != -1) {
+ out.write(buf, 0, len);
+ } else {
+ break;
+ }
+ }
+ }
}
diff --git
a/axiom-legacy-attachments/src/test/java/org/apache/axiom/om/AbstractTestCase.java
b/axiom-legacy-attachments/src/test/java/org/apache/axiom/om/AbstractTestCase.java
index 0e9cf3132..0f4781daf 100644
---
a/axiom-legacy-attachments/src/test/java/org/apache/axiom/om/AbstractTestCase.java
+++
b/axiom-legacy-attachments/src/test/java/org/apache/axiom/om/AbstractTestCase.java
@@ -32,8 +32,10 @@ public abstract class AbstractTestCase extends TestCase {
public AbstractTestCase() {
this(null);
}
-
- /** @param testName */
+
+ /**
+ * @param testName
+ */
public AbstractTestCase(String testName) {
super(testName);
}
@@ -53,9 +55,11 @@ public abstract class AbstractTestCase extends TestCase {
}
return in;
}
-
- public static OMElement getTestResourceAsElement(OMMetaFactory
omMetaFactory, String relativePath) {
- return
OMXMLBuilderFactory.createOMBuilder(omMetaFactory.getOMFactory(),
getTestResource(relativePath)).getDocumentElement();
+
+ public static OMElement getTestResourceAsElement(
+ OMMetaFactory omMetaFactory, String relativePath) {
+ return OMXMLBuilderFactory.createOMBuilder(
+ omMetaFactory.getOMFactory(),
getTestResource(relativePath))
+ .getDocumentElement();
}
}
-